/
cert.go
88 lines (76 loc) 路 1.97 KB
/
cert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package cert
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"os"
"time"
)
const (
certTemplate string = `Certificate #%d:
Subject: %s
Issuer: %s
NotBefore: %s
NotAfter: %s
`
)
var (
loc = time.Local
out io.Writer = os.Stdout // modified during testing
)
// Print all certificates for the given target URL
func Print(targetURL string) error {
certs, err := FetchCertificates(targetURL)
if err != nil {
return err
}
for i, cert := range certs {
if _, err = fmt.Fprintf(out, certTemplate, i, cert.Subject.CommonName, cert.Issuer.CommonName, cert.NotBefore.In(loc).String(), cert.NotAfter.In(loc).String()); err != nil {
return err
}
}
return nil
}
// FetchCertificates fetch the certificate chain from te target URL
func FetchCertificates(targetURL string) ([]*x509.Certificate, error) {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{
// #nosec G402 we are checking the cert, hence we allow insecure ones
InsecureSkipVerify: true,
}
// #nosec G107
resp, err := http.Get(targetURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.TLS != nil {
return resp.TLS.PeerCertificates, err
}
return nil, fmt.Errorf("could not find any certificates")
}
// IsToExport check whether the current index is to be exported
func IsToExport(certIndexes []int, i int) bool {
if len(certIndexes) == 0 {
return true
}
for _, a := range certIndexes {
if a == i {
return true
}
}
return false
}
// PrintAdd print an add statement
func PrintAdd(i int, cert *x509.Certificate) {
_, _ = fmt.Fprintf(out, " + Adding certificate #%d: %s\n", i, cert.Subject.CommonName)
}
// PrintSkip print an skip statement
func PrintSkip(i int, cert *x509.Certificate) {
PrintSkipDetailed(i, cert, "")
}
// PrintSkipDetailed print an skip statement
func PrintSkipDetailed(i int, cert *x509.Certificate, detail string) {
_, _ = fmt.Fprintf(out, " - Skipping certificate #%d: %s %s\n", i, cert.Subject.CommonName, detail)
}