Debian Codegraph @

command/certificate/remote.go

raw symbols SCIP
1 package certificate
2
3 import (
4 "crypto/tls"
5 "crypto/x509"
6 "net"
7 "net/url"
8 "strings"
9
10 "github.com/pkg/errors"
11 "github.com/smallstep/cli/crypto/x509util"
12 )
13
14 var urlPrefixes = []string{"https://", "tcp://", "tls://"}
15
16 // getPeerCertificates creates a connection to a remote server and returns the
17 // list of server certificates.
18 //
19 // If the address does not contain a port then default to port 443.
20 //
21 // Params
22 // *addr*: can be a host (e.g. smallstep.com) or an IP (e.g. 127.0.0.1)
23 // *serverName*: use a specific Server Name Indication (e.g. smallstep.com)
24 // *roots*: a file, a directory, or a comma-separated list of files.
25 // *insecure*: do not verify that the server's certificate has been signed by
26 // a trusted root
27 func getPeerCertificates(addr, serverName, roots string, insecure bool) ([]*x509.Certificate, error) {
28 var (
29 err error
30 rootCAs *x509.CertPool
31 )
32 if roots != "" {
33 rootCAs, err = x509util.ReadCertPool(roots)
34 if err != nil {
35 return nil, errors.Wrapf(err, "failure to load root certificate pool from input path '%s'", roots)
36 }
37 }
38 if _, _, err := net.SplitHostPort(addr); err != nil {
39 addr = net.JoinHostPort(addr, "443")
40 }
41 tlsConfig := &tls.Config{RootCAs: rootCAs}
42 if insecure {
43 tlsConfig.InsecureSkipVerify = true
44 }
45 if serverName != "" {
46 tlsConfig.ServerName = serverName
47 }
48 conn, err := tls.Dial("tcp", addr, tlsConfig)
49 if err != nil {
50 return nil, errors.Wrapf(err, "failed to connect")
51 }
52 conn.Close()
53 return conn.ConnectionState().PeerCertificates, nil
54 }
55
56 // trimURL returns the host[:port] if the input is a URL, otherwise returns an
57 // empty string (and 'isURL:false').
58 //
59 // Examples:
60 // trimURL("https://smallstep.com/onbaording") -> "smallstep.com", true, nil
61 // trimURL("https://ca.smallSTEP.com:8080") -> "ca.smallSTEP.com:8080", true, nil
62 // trimURL("./certs/root_ca.crt") -> "", false, nil
63 // trimURL("hTtPs://sMaLlStEp.cOm") -> "sMaLlStEp.cOm", true, nil
64 // trimURL("hTtPs://sMaLlStEp.cOm hello") -> "", false, err{"invalid url"}
65 func trimURL(ref string) (string, bool, error) {
66 tmp := strings.ToLower(ref)
67 for _, prefix := range urlPrefixes {
68 if strings.HasPrefix(tmp, prefix) {
69 u, err := url.Parse(ref)
70 if err != nil {
71 return "", false, errors.Wrapf(err, "error parsing URL '%s'", ref)
72 }
73 return u.Host, true, nil
74 }
75 }
76 return "", false, nil
77 }