Search code examples
opensslcertificatessl

How to Check Subject Alternative Names for a SSL/TLS Certificate?


Is there a way to programmatically check the Subject Alternative Names of a SAN SSL cert?

Using, for instance, the following command I can get many info but not all the SANs:

openssl s_client -connect www.website.example:443

Solution

  • To get the Subject Alternative Names (SAN) for a certificate, use the following command:

    openssl s_client -connect website.example:443 </dev/null 2>/dev/null \
    | openssl x509 -noout -text | grep DNS:
    

    First, this command connects to the site we want (website.example, port 443 for SSL):

    openssl s_client -connect website.example:443

    Then pipe (|) that into this command:

    openssl x509 -noout -text

    This takes the certificate file and outputs all its juicy details. The -noout flag keeps it from outputting the (base64-encoded) certificate file itself, which we don't need. The -text flag tells it to output the certificate details in text form.

    Normally there's a whole lot of output (signature, issuer, extensions, etc) that we don't care about, so then we pipe that into a simple grep:

    grep DNS:

    Since the SAN entries begin with DNS: this simply returns only the lines that contain that, stripping out all the other info and leaving us with the desired information.

    You may note that the command does not cleanly exit; openssl s_client actually acts as a client and leaves the connection open, waiting for input. If you want it to immediately exit (e.g. to parse the output in a shell script) simply pipe echo into it:

    echo | openssl s_client -connect website.example:443 \
    | openssl x509 -noout -text | grep DNS:
    

    How do I get the SAN directly from a file?

    For this, you don't need the openssl s_client command. Just add -in MyCertificate.crt on the openssl x509 command and once again pipe through grep, e.g.:

    openssl x509 -noout -text -in MyCertificate.crt | grep DNS: