forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
65 lines (60 loc) · 1.87 KB
/
remote.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
package certificate
import (
"crypto/tls"
"crypto/x509"
"strings"
"github.com/pkg/errors"
"github.com/smallstep/cli/crypto/x509util"
)
var urlPrefixes = []string{"https://", "tcp://", "tls://"}
// getPeerCertificates creates a connection to a remote server and returns the
// list of server certificates.
//
// If the address does not contain a port then default to port 443.
//
// Params
// *addr*: e.g. smallstep.com
// *roots*: a file, a directory, or a comma-separated list of files.
// *insecure*: do not verify that the server's certificate has been signed by
// a trusted root
func getPeerCertificates(addr, roots string, insecure bool) ([]*x509.Certificate, error) {
var (
err error
rootCAs *x509.CertPool
)
if roots != "" {
rootCAs, err = x509util.ReadCertPool(roots)
if err != nil {
return nil, errors.Wrapf(err, "failure to load root certificate pool from input path '%s'", roots)
}
}
if !strings.Contains(addr, ":") {
addr += ":443"
}
tlsConfig := &tls.Config{RootCAs: rootCAs}
if insecure {
tlsConfig.InsecureSkipVerify = true
}
conn, err := tls.Dial("tcp", addr, tlsConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to connect")
}
conn.Close()
return conn.ConnectionState().PeerCertificates, nil
}
// trimURLPrefix returns the url split into prefix and suffix and a bool which
// tells if the input string had a recognizable URL prefix.
//
// Examples:
// trimURLPrefix("https://smallstep.com") -> "https://", "smallstep.com", true
// trimURLPrefix("./certs/root_ca.crt") -> "", "", false
// trimURLPrefix("hTtPs://sMaLlStEp.cOm") -> "hTtPs://", "sMaLlStEp.cOm", true
func trimURLPrefix(url string) (string, string, bool) {
tmp := strings.ToLower(url)
for _, prefix := range urlPrefixes {
if strings.HasPrefix(tmp, prefix) {
return url[:len(prefix)], url[len(prefix):], true
}
}
return "", "", false
}