Ubuntu: Creating a self-signed certificate using OpenSSL on Ubuntu

There are numerous articles I’ve written  where a certificate is a prerequisite for deploying a piece of infrastructure.

Here are the quick steps for installing a simple self-signed certificate on an Ubuntu server.  If you instead need to create a certificate with SAN (Subject Alternative Name) support, read my article here.

Some of you will want a full explanation of the steps required, others will only want to run the script I’m putting on github.

Shortcut: Use this script

$ wget https://raw.githubusercontent.com/fabianlee/blogcode/master/haproxy/selfsigned.sh
$ chmod 755 selfsigned.sh
$ ./selfsigned.sh

You now have a self-signed cert in ‘/etc/pki/tls/certs’ directory with a CN matching the fully qualified hostname.  If you want an explanation of what this script does, continue reading below.

Longer Explanation

First we create the destination directory and make sure we have the ssl packages.

# mkdir -p /etc/pki/tls/certs
# chmod 755 /etc/pki/tls/certs
# apt-get install libssl1.0.0 -y

Then we create the self-signed cert good for 10 years with a CN matching the fully qualified name of the host:

# cd /etc/pki/tls/certs
# export FQDN=`hostname -f`
# openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
-keyout $FQDN.key -out $FQDN.crt \
-subj "/C=US/ST=CA/L=SFO/O=myorg/CN=$FQDN"

This puts two files into the directory: $FQDN.crt (public cert) and $FQDN.key (private key).

You can validate the certificate using:

$ openssl x509 -in $FQDN.crt -text -noout

There are applications that require this public/private pair in a slightly different format.  For example, haproxy wants a .pem file which is just a concatenation of these files which can be constructed like:

# cat $FQDN.crt $FQDN.key > $FQDN.pem

And Windows application servers like IIS will want a binary .pfx file:

# openssl pkcs12 -export -out $FQDN.pfx \
-inkey $FQDN.key -in $FQDN.pem

 

REFERENCES

https://www.sslshopper.com/article-most-common-openssl-commands.html

NOTES

openssl pkcs12 -export -out $FQDN.pfx -inkey $FQDN.key -in $FQDN.crt -certfile intermediate.pem (for singled out cert and pem trust chain)

openSSL pkcs8 -in certificatename.pem -topk8 -nocrypt -out certificatename.pk8 (convert PEM to PKCS8)

Show certs for site

echo QUIT | openssl s_client -connect <host>:443 -showcerts

openssl s_client -connect <host>:443 < /dev/null 2>&1 | openssl x509 -text -in /dev/stdin (pull cert using host address)