If you need to expose services to the internet then you need to put in place more than just a simple firewall. A reverse proxy such as HAproxy, can help by sitting between the internet and the actual services you want to expose. Where the services use HTTPS the reverse proxy can act as the actual server to terminate the TLS connection to then inspect and act on the requests.

All the while the services are only used by internal users, an in-house TLS certificate can be used, but the moment you want to make services available to others a publicly signed certificate will be needed which always used to come at a cost. LetsEncrypt provide 90 day certificates for free, and with some additional scripting the renewal can fully automated to work with HAproxy.

I originally installed HAproxy as part of a mail & calendar upgrade. Mail connections using IMAPS and SMTPS could be checked and forwarded to the mail server, and calendar and contact sync using CalDAV & CardDAV over HTTPS could also be checked and forwarded to a Nextcloud instance. Since I use an in-house Certificate Authority I didn't have to worry about buying TLS certificates for anything.

Anyone attempting to poke around would be rejected by HAproxy and then fail2ban would block the IP from connecting again. Within a day of configuring that, the number of connection attempts dropped significantly.

I now want to allow a small group of volunteer leaders from a local Beaver Scout colony to connect to a Nextcloud instance I'm hosting for them, and using an in-house TLS certificate on devices I don't control would make it much more awkward for them.

HAproxy schematic

Back in 2015 the Lets Encrypt project went live with it's mission to provide free domain-validated TLS certificates to help secure the world wide web and make HTTPS the default. Using their certificates and certbot to automate the renewal is ideal for this.

Note: I've used the example.com domain in all examples here to make it easier to spot where you'll need to substitute your own details.

Certbot

Certbot is a program provided by LetsEncrypt to make requesting, issuing and renewing TLS certificates as easy as possible. It handles the complete process automatically from a command line. To prove you really are who you claim to be you need to make sure that Certbot is contactable over the internet on the fully-qualified domain name you want a certificate for.

This also limits it's use for purely internal TLS certificates so I don't see me getting rid of my in-house CA any time soon - especially as that lets me also add additional teeth on the watchdogs, and maybe implement user certificates too.

Certbot Installation

Certbot can be downloaded from the Electronic Freedom Foundation Certbot project and is available for most webservers and operating systems. It's also in most Linux distributions repositories too so on my Ubuntu servers installation is quite simple:

sudo apt install certbot

On Ubuntu 20.04 this installs certbot 0.40.0 and creates a systemd certbot.service to run certbot when needed and a certbot.timer to trigger the service twice a day by default.

It's also worth creating a test certbot installation somewhere and using some test host names such as test1.certbot.example.com and run against the testing LetsEncrypt backend during initial setup as LetsEncrypt put usage limits on their main service.

Certbot Configuration

On Ubuntu Linux the Certbot configuration is held in /etc/letsencrypt which should contain a cli.ini file for configuration defaults. We want to add two lines to this to save a bit of typing later

# Accept ToS, set email
agree-tos = true
email = This email address is being protected from spambots. You need JavaScript enabled to view it.

This saves you having to acknowledge you've read the Certbot Terms of Service every time (read 'em once and agree - you can't use the service otherwise) and also sets the email address where you want reminders and notifications sent to.

Certbot also maintains a directory structure to manage keys, certificates, the hooks for renewal scripts and it's own state, but helpfully doesn't create them during installation. So the next task is to this by launching certbot with a made-up configuration. You need to be root to run this

root@host:/etc/letsencrypt# certbot certonly -d bogus.example.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log

How would you like to authenticate with the ACME CA?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Spin up a temporary webserver (standalone)
2: Place files in webroot directory (webroot)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): c
Could not choose appropriate plugin: authenticator could not be determined or is not installed
authenticator could not be determined or is not installed

Type c to cancel certbot and the required directories will be created.

Certbot is now ready to run and start requesting certificates, but we still need to set up the renewal script and enable it to be contacted by the LetsEncrypt certificate issuing servers.

Certbot Renewal Hook

Early versions of Certbot would renew certificates but didn't provide an easy way to trigger any other actions once it had done so which lead to some very complicated solutions to work out what it had done and react according. It now proves a mechanism where it will run all scripts in three directories - pre, deploy and post - whenever it renews a certificate and more importantly it passes the domain name and path to the key and certificates as parameters to the script.

If the following script is placed in /etc/letsencrypt/renewal-hooks/deploy/haproxy.sh it will concatenate full certificate chain and the private key into a single file into the directory we have configured HAproxy to check.

#!/bin/bash
# Certbot renewal hook to package the certificate for use with HAproxy
# Copyright Authors of the Bostoncube.com
# v1.0 - no warranty, use at your own risk. Treat as CC BY-NC-SA untill I choose a proper licence on it.

echo "Starting Certbot deploy hook haproxycert.sh"
echo ""
echo "RENEWED_LINEAGE=$RENEWED_LINEAGE"
echo "RENEWED_DOMAINS=$RENEWED_DOMAINS"
echo ""

HAPROXY_CERTDIR=/etc/ssl/haproxy

# Verify certificate chain and private key exists
if [[ -f $RENEWED_LINEAGE/fullchain.pem ]] ; then
  echo "Chain: $RENEWED_LINEAGE/fullchain.pem"
else
  echo "Error: Chain $RENEWED_LINEAGE/fullchain.pem not found"
  exit 1
fi

if [[ -f $RENEWED_LINEAGE/privkey.pem ]] ; then
  echo "Key: $RENEWED_LINEAGE/privkey.pem"
else
  echo "Error: Key $RENEWED_LINEAGE/privkey.pem not found"
  exit 1
fi

# If we get a list of domains, just use the first one
DOMAINLIST=($RENEWED_DOMAINS)
DOMAIN=${DOMAINLIST[0]}
echo "Combined file: $HAPROXY_CERTDIR/$DOMAIN.pem"

cat $RENEWED_LINEAGE/fullchain.pem $RENEWED_LINEAGE/privkey.pem > $HAPROXY_CERTDIR/$DOMAIN.pem

systemctl reload haproxy

Serious Note: This will get run as root. If you want to use it or be inspired from it make sure for yourself that it's good and it's at your own risk. I'm still a few weeks away from this running for real. If it goes awry don't blame me...

Request New Certificate via Certbot

To request a new certificate is simply a case of calling certbot with the the appropriate parameters, and I put this into a script - certbot-new.sh - to make it easier while working out the haproxy.sh renewal-hook script. The parameters change slightly with different versions so using man certbot will give you the list for the version installed. In my case:

  • certonly means to just requests a new certificate and not to attempt to install it - we'll do that with the script
  • --standalone means it handles the challenge itself rather than using another web server
  • --preferred-challenges http specifies we want to use the http challenge
  • --http-01-port specifies the port to listen on for the http challenge. We will configure HAproxy to use this port
  • -d $CERT is the hostname we want the certificate for, which we pick up from the parameters given to this script
  • --deploy_hook is explicitly calls our config script as it doesn't call the hooks for the first time a certificate is requested for some reason
  • --test-cert specifies to use the non-trusted test system to issue certs, otherwise me may run into problem with usage limits during testing
  • --break-my-certs during testing to replace any valid certs with test versions.

 

#!/bin/bash
# Request a new LetsEncrypt TLS certificate
# Explicitly call the deploy hook to reformat for HAproxy
# Copyright Authors of the Bostoncube.com
# v1.0 - no warranty, use at your own risk. Treat as CC BY-NC-SA untill I choose a proper licence on it.


DEPLOYHOOK=/etc/letsencrypt/renewal-hooks/deploy/haproxycert.sh


if [[ $1 == "" ]] ; then 
echo "Please specifiy domain name e.g. certbot-new.sh host1.geeklab.example.com"
  exit 1
else
  CERT=$1
fi

# Testing mode
echo "Calling Certbot in TEST mode"
certbot certonly --standalone --preferred-challenges http --http-01-port 10080 -d $CERT --deploy-hook $DEPLOYHOOK --test-cert --break-my-certs

# Live mode
#echo "Calling Certbot in LIVE mode"
#certbot certonly --standalone --preferred-challenges http --http-01-port 10080 -d $CERT --deploy-hook $DEPLOYHOOK


echo ""
echo "Complete"
echo ""

To use just copy to /etc/letsencrypt/certbot-new.sh, set permissions to 754 root:root and run it with the fully-qualified host name you want the certificate for. The above script is in test mode, and I suggest using a test FQDN too. To run in live mode and get a genuine certificate comment out the echo and certbot lines under # Testing mode an remove the comments for the echo and certbot lines under # Live mode.

The scripts should now be runnable although it will timeout waiting for a response since we're not yet connected to the internet.

HAproxy config

The last step is to configure HAproxy to connect to Certbot to allow it to receive the challenge and issue the certificate.

The first step is to allow access to HAproxy from the internet on the standard HTTP port 80/tcp. Depending on your router this is typically a case of of configuring NAT forwarding, maybe with an associated firewall rule.

You will of course also need to configure your router for HTTPS as well, which is port 443/tcp (unless you're doing something clever and using a custom port) although I'm assuming you already have that part sorted, along with appropriate configuration of HAproxy for the site you want to connect to.

In HAproxy we want to forward all request for the http challenge to the the HAproxy itself as localhost on the port we specified for http-01-port.  Add the following two sections to /etc/haproxy/haproxy.cfg

frontend HTTP  bind *:80  mode http
  option forwardfor
...
acl path_letsencrypt path_beg /.well-known/acme-challenge/ use_backend http-letsencrypt if path_letsencrypt
...
[other lines]

This defines a frontend called HTTP that listens on the standard HTTP port 80/tcp and sends any HTTP requests for the certbot http challenge to the certbot backend http-letsencrypt where certbot will be listening during the renewal process. Make sure the acl path and use_backend lines are before any other similar lines you might have configured for HTTP that refer to hosts you want a certificate for as we do not want this going to the actual host.

backend http-letsencrypt
  # Use local certbot
  server local_certbot 127.0.0.1: 10080

The http-letsencrypt backend sends all requests to the HAproxy host itself on the loopback address, which is where we're running certbot, on the port we specified for the http-01-port in the certbot certificate request. 

Certbot will only run for about 10 seconds or so, the so any attempts to connect to a host on the acme-challenge URL will get a 503 Service Unavailable error and I have fail2ban configured to ban that host for good measure.

You could also define an acl on the host header and modify the use_backend to include this as well to be even more selective about which hosts you'd forward the http challenge to certbot for.

Testing

With all the config in place and with the request script set to test mode, and of course making sure you have a public DNS A or CNAME record for the certificate you want to request pointing at your public IP. Preferably on a short TTL.

As mentioned above, it's worth using a test hostname such as cb1.test.example.com at first. The test certificate won't be trusted by browsers, but you can request lots of certificates to prove the process.

If you're using the request script simply call it with the hostname you desire

./certbot-new.sh cb1.test.example.com

Within a minute you should have a certificate file in /etc/ssl/haproxy/cb1.test.example.com.pem and if you cat the file you should see three lots of ----- begin certificate ----- / ----- end certificate ---- lines and a ----- begin rsa private key ----- / ----- end rsa private key ----- pair of lines with blocks of alpha-numeric text between them. If you really want to be sure you can use openssl to decode and validate the file.

If you try to connect to your site you should get dire warnings from your browser that the world is about to end for connecting to a site it deems untrustworthy, assuming you've configured a backend HTTPS service to connect to.

Live Use

Once you're happy the process works using the test service, make sure have public DNS A or CNAME records for your real hostnames pointing to the public IP of your proxy and issue the request using the live service. If you're using the request script above comment out the two lines after # Testing Mode and uncomment the two lines after # Live Mode and save the file, then request your certificate as before

./certbot-new.sh mysite.example.com

Once HAproxy has reloaded, you should be able to connect to the site and the browser security info should now show that you have a TLS connection verified by LetsEncrypt - assuming you've correctly configured the backend HTTPS service for what you want to connect to. Have a look at the Internal Proxy with HTTPS Termination chapter of  Nextcloud 26 Initial Configuration for setting up HAproxy to handle this.

At the time of publishing I've had this configured for just over a month so it'll be a while longer before it goes through with a live renewal. I have the date in my diary.