ssl-certs-checker/utils.go

91 lines
1.6 KiB
Go
Raw Normal View History

2020-02-22 15:39:16 +00:00
package main
import (
"crypto/tls"
"crypto/x509"
2020-03-15 14:07:50 +00:00
"fmt"
2020-02-22 15:39:16 +00:00
"net"
"os"
"strconv"
"strings"
"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
)
func getPeerCertificates(h string, port int) ([]*x509.Certificate, error) {
conn, err := tls.DialWithDialer(
&net.Dialer{
Timeout: dialerTimeout,
},
protocol,
h+":"+strconv.Itoa(port),
&tls.Config{
ServerName: h,
})
if err != nil {
return nil, err
}
defer conn.Close()
if err := conn.Handshake(); err != nil {
return nil, err
}
return conn.ConnectionState().PeerCertificates, nil
}
2020-03-15 14:07:50 +00:00
func getCells(t table.Writer, host string, port int) {
certs, err := getPeerCertificates(host, port)
2020-02-22 15:39:16 +00:00
if err != nil {
2020-03-15 14:07:50 +00:00
fmt.Printf("err: %s\n", err)
2020-02-22 15:39:16 +00:00
return // skip if target host invalid
}
for _, c := range certs {
if c.IsCA {
continue
}
2020-03-15 14:07:50 +00:00
t.AppendRows([]table.Row{{
host + ":" + strconv.Itoa(port),
(*c).Subject.CommonName,
strings.Join((*c).DNSNames, "\n"),
(*c).NotBefore,
(*c).NotAfter,
(*c).Issuer.CommonName,
}})
2020-02-22 15:39:16 +00:00
}
}
func prettyPrintCertsInfo(h string) {
targets := strings.Split(h, ",")
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{
"Host",
"Common Name",
2020-03-04 02:32:34 +00:00
"DNS Names",
2020-02-22 15:39:16 +00:00
"Not Before",
"Not After",
"Issuer",
})
for _, target := range targets {
2020-03-15 14:07:50 +00:00
p := defaultPort
ts := strings.Split(target, ":")
if len(ts) == 2 {
tp, err := strconv.Atoi(ts[1])
if err != nil {
fmt.Printf("err: invalid port [%s], assume target port is 443\n", target)
} else {
p = tp
}
}
getCells(t, ts[0], p)
2020-02-22 15:39:16 +00:00
}
t.Style().Format.Header = text.FormatDefault
t.Render()
}