| 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 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 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 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 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 |
} |