Free SSL Encryption using Certbot and LetsEncrypt

Lets be honest folks. If SSL encryption is available free of charge and was easy to implement, wouldn't it be foolish not to use it?

Here are some snippets to get you started using letsencrypt on your Ubuntu 16 LTS machine running Apache2.

1. Remove Letsencrypt (If previously installed)######
sudo apt-get purge --auto-remove letsencrypt
1. Install Certbot######
sudo apt-get update
sudo apt-get install software-properties-common -y
sudo add-apt-repository ppa:certbot/certbot -y
sudo apt-get update
sudo apt-get install python-certbot-apache -y
2. Next configure Apache to use SSL######
sudo a2enmod ssl
sudo a2ensite default-ssl
sudo systemctl restart apache2
3. Add the http virtualhost so letsencrypt can validate the certificate files######
sudo vi /etc/apahce2/sites-available/examplesite.com.conf

Add the following lines.

<VirtualHost *:80>
    ServerName examplesite.com
    ServerAlias www.examplesite.com
    DocumentRoot /var/www/html
</VirtualHost>
4. Enable the site and reload apache######
sudo a2ensite examplesite.com.conf
sudo service apache2 reload
5. Generate a SSL certificate for your http site using certbot######

The following snippet will upgrade the non https virtualhost file to ssl automatically.

sudo certbot --apache \
    -n --agree-tos \
    --redirect \
    --keep-until-expiring \
    -m "you@example.com" \
    -d "examplesite.com" \
    --webroot-path /var/www/html/ \
    --renew-hook "/home/ubuntu/certbot_renewal_email.sh you@example.com examplesite.com"
Create the email send hook script#######
vi /home/ubuntu/certbot_renewal_email.sh

Add the following snippet

#!/bin/bash

EMAIL=${1:-"example@example.org"}
DOMAIN=${2:-"Domain Not Specified"}

mail -s "Certbot Certificate Renewal" -t $EMAIL <<< $DOMAIN

You will need to have mail installed on the server. Add the following snippet to a file, and give it execute permissions, then run the script with sudo to install mail

#!/bin/bash

MAILNAME=${1:-"example.com"}

vagrant_build_log=/home/ubuntu/vm_build.log

##########################
# Ensure Root privileges #
##########################
if [ "$(whoami)" != "root" ]; then
  echo "!- You will need to run this with root, or sudo. -!"
  exit 1
fi
apt-get update
debconf-set-selections <<< "postfix postfix/mailname string $MAILNAME"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
apt-get install -y mailutils
Setup a cron job to refresh the certificates on a regular basis######
sudo crontab -e

Append the following line to the crontab

30 2 * * 1 /usr/bin/certbot renew --logs-dir /var/log/letsencrypt/
Thats it! Your site is now SSL encrypted! Now, quick, go encrypt the rest of your sites

 

Certificate Removal

If you ever need to remove a certificate, for example, if you no longer manage a particular domain see my post about removing a certificate below.

remove a LetsEncrypt certificate