Tuesday, January 12, 2016

Code Snippet: Fetch certificate information from a live endpoint in Go

I generally try to post snippets on my blog that I don't find on a Google search. This is like one of those snippets.

This sample code fetches the time to expiry for a certificate that's currently deployed at a live endpoint. 

Code:-

package main

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

func main() {
 // Parse cmdline arguments using flag package
 server := flag.String("server", "abhijeetr.com", "Server to ping")
 port := flag.Uint("port", 443, "Port that has TLS")
 flag.Parse()

 conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", *server, *port), &tls.Config{})
 if err != nil {
  panic("failed to connect: " + err.Error())
 }

 // Get the ConnectionState struct as that's the one which gives us x509.Certificate struct
 connectionState := conn.ConnectionState()

 fmt.Printf("Time to expiry for the certificate: %v\n", connectionState.PeerCertificates[0].NotAfter.Sub(time.Now()))
 conn.Close()
}

Usage:-

% ./ssl_certs -h
Usage of ./ssl_certs:
  -port uint
     Port that has TLS (default 443)
  -server string
     Server to ping (default "abhijeetr.com")
% ./ssl_certs
Time to expiry for the certificate: 1843h21m3.857177591s

No comments:

Post a Comment