Let's Encrypt setup

2023-01-23

Manually create, update and destroy SSL certificates with Let's Encrypt.

Create certificates

You'll first need a web server. We'll do a server-agnostic setup, so you should be able to port the following instructions to your server of choice. We'll use lighttpd as an example.

First install the certbot package, a python CLI distributed by the Electronic Frontier Foundation. certbot is able to automatically renew the certificates obtained from Let's Encrypt once it's correctly setup.

The trick is that certbot needs access to the domain over http in order to create the https certificate on it. Make sure your setup resembles :

export SERVER_URL=YOUR_SERVER_URL_HERE

cat > /etc/lighttpd/lighttpd.conf << EOF
server.username = "http"
server.groupname = "http"
server.document-root = "/srv/http"
index-file.names = ( "index.html" )
include "mime-types.conf"
server.modules = (
    "mod_access",
    "mod_accesslog",
    "mod_alias"
)
include "letsencrypt.conf"
EOF

cat > /etc/lighttpd/letsencrypt.conf << EOF
server.modules += ( "mod_openssl" )
alias.url = (
    "/.well-known/acme-challenge/" => "/var/lib/letsencrypt/"
)
$SERVER["socket"] == ":443" {
    ssl.engine = "enable"
    ssl.pemfile = "/etc/letsencrypt/live/$SERVER_URL/fullchain.pem"
    ssl.privkey = "/etc/letsencrypt/live/$SERVER_URL/privkey.pem"
    #server.name = "$SERVER_URL"  # Domain Name OR Virtual Host Name
    server.errorlog = "/var/log/lighttpd/${SERVER_URL}_error.log"
    accesslog.filename = "/var/log/lighttpd/${SERVER_URL}_access.log"
}
EOF

# Optional CORS configuration that you may `include`.
cat > /etc/lighttpd/cors.conf << EOF
setenv.add-response-header = (
    "Access-Control-Allow-Origin" => "*",
    "Access-Control-Allow-Methods" => "HEAD, GET, OPTIONS, POST",
    "Access-Control-Expose-Headers" => "Content-Range, Date, Etag, Cache-Control, Last-Modified",
    "Access-Control-Allow-Headers" => "Content-Type, Origin, Accept, Range, Cache-Control",
    "Access-Control-Max-Age" => "600",
    "Timing-Allow-Origin" => "*"
)
EOF

Restart lighttpd. Then request a certificate :

certbot certonly --agree-tos --domain $SERVER_URL --webroot /var/lib/letsencrypt -m YOUR@EMAIL.COM

Renew certificates

If your system ships with systemd, certbot should provide a certbot.timer unit to automatically renew certificates. If you don't, you can add a cron job for it :

cat > /etc/periodic/daily/letsencrypt << EOF
#!/bin/sh

certbot renew
EOF

Make the latter file executable. Check that cron will use it (works on alpine linux).

Get rid of a certificate

There are two theoretical situations where one would want to get rid of one's certificate :

In the first situation, one should revoke the certificate, with :

certbot revoke --cert-path /etc/letsencrypt/archive/${YOUR_DOMAIN}/cert1.pem

In the second situation, one should simply delete the certificate :

certbot delete

The latter command is interactive.

List certificates

certbot certificates