forked from pete911/certinfo
/
location.go
73 lines (58 loc) · 1.91 KB
/
location.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
package cert
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"os"
"time"
)
const tlsDialTimeout = 5 * time.Second
type CertificateLocation struct {
TLSVersion uint16 // only applicable for network certificates
Path string
Certificates Certificates
VerifiedChains []Certificates // only applicable for network certificates
}
func LoadCertificatesFromNetwork(addr string, tlsSkipVerify bool) (CertificateLocation, error) {
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: tlsDialTimeout}, "tcp", addr, &tls.Config{InsecureSkipVerify: tlsSkipVerify})
if err != nil {
return CertificateLocation{}, fmt.Errorf("tcp connection failed: %w", err)
}
connectionState := conn.ConnectionState()
x509Certificates := connectionState.PeerCertificates
var verifiedChains []Certificates
for _, chain := range connectionState.VerifiedChains {
verifiedChains = append(verifiedChains, FromX509Certificates(chain))
}
return CertificateLocation{
TLSVersion: conn.ConnectionState().Version,
Path: addr,
Certificates: FromX509Certificates(x509Certificates),
VerifiedChains: verifiedChains,
}, nil
}
func LoadCertificatesFromFile(fileName string) (CertificateLocation, error) {
b, err := ioutil.ReadFile(fileName)
if err != nil {
return CertificateLocation{}, fmt.Errorf("skipping %s file: %w", fileName, err)
}
return LoadCertificate(fileName, b)
}
func LoadCertificateFromStdin() (CertificateLocation, error) {
content, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return CertificateLocation{}, fmt.Errorf("reading stdin: %w", err)
}
return LoadCertificate("stdin", content)
}
func LoadCertificate(fileName string, data []byte) (CertificateLocation, error) {
certificates, err := FromBytes(data)
if err != nil {
return CertificateLocation{}, fmt.Errorf("file %s: %w", fileName, err)
}
return CertificateLocation{
Path: fileName,
Certificates: certificates,
}, nil
}