Introduction
In web development, security is essential. SSL certificates guarantee the confidentiality and integrity of the data exchanged between a client and a server. You need to keep them valid at all times; that way you assure your customers that their communication with you is secure and private.
In this short guide, we’ll build a program that tells us when our certificates are about to expire, so we can monitor them.
Our function
We’ll create a function called CheckSSLExpiry that takes the URL of the website serving our certificate. The function returns the certificate’s expiration date and any error it ran into.
It will look like this:
func CheckSSLExpiry(website string) (time.Time, error)
We’ll use this function later to monitor the site.
Establishing the connection
To get the site’s certificate, we need to open a connection to the server. We’ll use the tls.Dial function from the crypto/tls package to do that.
conn, err := tls.Dial("tcp", address, nil)
As you can see, this function takes three arguments:
-
network -
tcp/udp. In our case we’re using the HTTP protocol, so the value we’ll use is tcp. -
address - This value has to be in the
"host:port"format.- If the port isn’t specified, use the default HTTPS port (443). When connecting to
https://www.cibera.mx, the value will bewww.cibera.mx:443. - If the port is specified in the URL, use that port. If we want to connect to
https://www.example.com:1234, the format has to bewww.example.com:1234.
- If the port isn’t specified, use the default HTTPS port (443). When connecting to
-
This value is of type tls.Config. A nil value means we want the default configuration. If you want to add your own certificates to the validation process, or you need more control over the connection, you’ll have to pass your own configuration.
Converting the URL to an address
At this point we have everything we need to open the connection except the address value.
To turn the URL into the format address expects, we pass it through url.Parse. This function gives us access to methods with more detailed information about the URL.
We’ll write another function to keep our code modular.
func parseAddress(website string) (string, error) {
u, err := url.Parse(website)
if err != nil {
return "", err
}
port := u.Port()
scheme := u.Scheme
if scheme != "https" {
return "", errors.New("site must use the https scheme")
}
if port == "" {
port = "443"
}
address := net.JoinHostPort(u.Hostname(), port)
return address, nil
}
With this, we have everything we need to open the connection.
address, _ := parseAddress(url)
conn, err := tls.Dial("tcp", address, nil)
We’ll deal with error handling in the finished function.
Expiration Date
Once the connection is open, we’ll loop through the certificate chain. We’re looking for the certificate that belongs to our site, that is, the one issued by Let’s Encrypt or another certificate provider. When we find it, we’ll read its date.
To find it, we check that its hostname matches the URL’s hostname.
for _, cert := range conn.ConnectionState().PeerCertificates {
if err := cert.VerifyHostname(u.Hostname()); err == nil {
return cert.NotAfter, nil
}
}
The NotAfter property holds the expiration date.
Our finished function
Here is our function in its final form. We handle every error and make sure to defer closing the connection.
func CheckSSLExpiry(website string) (time.Time, error) {
expiry := time.Time{}
address, err := parseAddress(website)
if err != nil {
return expiry, err
}
conn, err := tls.Dial("tcp", address, nil)
if err != nil {
return expiry, errors.New("could not establish a connection")
}
defer conn.Close()
for _, cert := range conn.ConnectionState().PeerCertificates {
if err := cert.VerifyHostname(u.Hostname()); err == nil {
return cert.NotAfter, nil
}
}
return expiry, errors.New("certificate not found")
}
How to use the function for monitoring
To monitor our site, we’ll simply check whether the expiration date is less than a week away. If it’s about to expire, we’ll print a message to the console. This is where you can do whatever you want: send an email, a text message, or notify any integration you have (for example, Slack or Microsoft Teams).
package main
import (
"time"
"log"
)
func main() {
expires, err := CheckSSLExpiry("https://www.cibera.mx")
if err != nil {
log.Fatal(err)
}
duration := time.Until(expires)
if duration < time.Hour * 24 * 7 {
log.Printf("the ssl certificate expires in %s", duration)
}
}
Here are a few ideas for extending the program:
- On Linux, use a cron job to run the program every day at 8 a.m.
- Send notifications through Slack, Microsoft Teams, Telegram, email, etc. with a message saying the certificate is about to expire.
- Keep a file with the list of all your sites. The program could read this file and send notifications for each site. That way you wouldn’t need to change the program every time you want to monitor a new site.
Conclusion
Online, security is essential, and monitoring your SSL certificates is a basic part of it. These certificates don’t just secure encrypted connections; they also protect data and help your SEO. With threats constantly changing, steady monitoring prevents breaches and protects your reputation. Stay proactive so you catch and fix problems in time, and keep your website secure and reliable.
If you’d rather not maintain your own program, Monitoro, our open-source monitoring platform, watches your SSL certificates and warns you before they expire.
