Relentless Coding

A Developer’s Blog

Create Self-Signed TLS Cert With Wildcard

Let’s create a self-signed certificate that contains a wildcard Subject Alternative Name (SAN).

$ openssl req -x509 \
    -subj "/C=NL/L=Utrecht/O=Relentless Coding/CN=*.example.com" \
    -addext "subjectAltName = DNS:example.com, DNS:*.example.com" \
    -newkey rsa:2048 \
    -noenc \
    -keyout key.pem \
    -out cert.pem

-addext allows us to add X509 extensions to the certificate from the command line. In older versions of openssl(1) you needed to use a configuration file (--config openssl.cnf) to achieve the same thing. (See x509v3_config(5) for more information about X509 extensions.)

Note we can add multiple DNS names to the SAN field by separating them with commas. This is different from the way this information is provided in the configuration file.

Also note that -noenc replaced the -nodes flag in openssl version 3. They both indicate that the private key is not to be encrypted with a passphrase.

Copy key.pem and cert.pem to where the server reads TLS certs and restart it.

Add entry to /etc/hosts:

127.0.0.1	example.com sub.example.com

Use with curl:

$ curl --cacert cert.pem https://sub.example.com

Notice we use --cacert <cert>. This way, the server can still present a self-signed certificate, and we still get the benefit from all certificate checks curl does, such as domain checking. (The -k, --insecure flag disables all those checks, so it will accept any certificate, including a certificate for other.com when connecting to example.com, which is not always what we want.)