Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, March 28, 2022

Check Certificate in GoLang

 


The following code checks a fully qualified domain name (aka FQDN), and returns a boolean indicating if the FQDN has a valid certificate. We have several steps in this.

First we check if the FQDN is an IP address. A valid certificate must be issued for a host name, and not for an IP, and hence we reject IP addresses.

Next we connect to the FQDN on port 443. To get a valid SSL certification the connection must be successful.

Now that we have an established TLS connection, we check it properties:

  • The host name in the certificate must match the FQDN
  • The SSL certificate is not expired

Once all the previous steps are done, we can set the SSL certificate as a valid one.




package certificateupdater

import (
"crypto/tls"
"fmt"
"regexp"
"time"
)

var ipRegex = regexp.MustCompile(`(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}`)

func IsIpAddress(name string) bool {
return ipRegex.MatchString(name)
}

func IsValidCertificate(fqdn string) bool {
if IsIpAddress(fqdn) {
return false
}

hostAndPort := fmt.Sprintf("%v:443", fqdn)
conn, err := tls.Dial("tcp", hostAndPort, nil)
if err != nil {
return false
}
defer func() {
closeErr := conn.Close()
if closeErr != nil {
panic(closeErr)
}
}()

err = conn.VerifyHostname(fqdn)
if err != nil {
return false
}
expiry := conn.ConnectionState().PeerCertificates[0].NotAfter
if expiry.Before(time.Now()) {
return false
}

return true
}


No comments:

Post a Comment