How to check if a website SSL certificate is valid with Bash

How to check if a website SSL certificate is valid with Bash

In this article, we will explain how to create a Bash script that, given an input domain, verifies the validity of its SSL certificate.

Online security is a fundamental priority, and an essential part of this aspect is represented by SSL (Secure Socket Layer) certificates. An SSL certificate encrypts the connection between the server and the browser, ensuring that transmitted data is protected from unauthorized access. In this article, we will explain how to create a Bash script that, given an input domain, verifies the validity of its SSL certificate.

Before we begin, let's make sure we have some essential tools installed on our system, such as OpenSSL, an open-source tool for implementing SSL/TLS protocols.


sudo apt-get install openssl    # For Debian/Ubuntu-based systems

Let's create a Bash script named check_ssl.sh using a text editor like nano or vim.


nano check_ssl.sh

Inside the script, insert the following code:


#!/bin/bash

# Check if a domain is provided as an argument
if [ $# -eq 0 ]; then
    echo "Usage: $0 "
    exit 1
fi

domain=$1

# Run the OpenSSL command to get certificate information
cert_info=$(openssl s_client -connect ${domain}:443 -servername ${domain} -showcerts /dev/null | openssl x509 -text)

# Check the expiration date of the certificate
expiration_date=$(echo "${cert_info}" | grep "After" | awk -F' : ' '{print $2}')

# Convert the expiration date to a timestamp on Linux systems
expiration_timestamp=$(date -d "${expiration_date}" +%s 2>/dev/null)

# If the conversion fails, try another syntax on BSD systems (like MacOS)
if [ -z "${expiration_timestamp}" ]; then
    expiration_timestamp=$(date -jf "%b %e %T %Y %Z" "${expiration_date}" +%s 2>/dev/null)
fi

# Get the current date and time in timestamp format
current_timestamp=$(date +%s)

# Check if the certificate has expired
if [ ${current_timestamp} -gt ${expiration_timestamp} ]; then
    echo "The SSL certificate for the domain ${domain} has expired."
else
    echo "The SSL certificate for the domain ${domain} is valid until ${expiration_date}."
fi

Save and close the file. Make the script executable with the following command:


chmod +x check_ssl.sh

Now, we can use the script by providing a domain as an argument. For example:


./check_ssl.sh example.com

The script will initiate an SSL connection to the specified domain and check the certificate's expiration date. It will return a message indicating whether the certificate is valid or has expired.

This script can be useful for monitoring the validity of SSL certificates on different domains and automating the verification process. Ensure to use this script ethically and comply with privacy and data security regulations.