github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/crypto/tls/tls.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package tls partially implements TLS 1.2, as specified in RFC 5246, 6 // and TLS 1.3, as specified in RFC 8446. 7 package tls 8 9 // BUG(agl): The crypto/tls package only implements some countermeasures 10 // against Lucky13 attacks on CBC-mode encryption, and only on SHA1 11 // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and 12 // https://www.imperialviolet.org/2013/02/04/luckythirteen.html. 13 14 import ( 15 "bytes" 16 "crypto" 17 "crypto/ecdsa" 18 "crypto/ed25519" 19 "crypto/rsa" 20 "crypto/x509" 21 "encoding/pem" 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "net" 26 "strings" 27 "time" 28 ) 29 30 // Server returns a new TLS server side connection 31 // using conn as the underlying transport. 32 // The configuration config must be non-nil and must include 33 // at least one certificate or else set GetCertificate. 34 func Server(conn net.Conn, config *Config) *Conn { 35 return &Conn{conn: conn, config: config} 36 } 37 38 // Client returns a new TLS client side connection 39 // using conn as the underlying transport. 40 // The config cannot be nil: users must set either ServerName or 41 // InsecureSkipVerify in the config. 42 func Client(conn net.Conn, config *Config) *Conn { 43 return &Conn{conn: conn, config: config, isClient: true} 44 } 45 46 // A listener implements a network listener (net.Listener) for TLS connections. 47 type listener struct { 48 net.Listener 49 config *Config 50 } 51 52 // Accept waits for and returns the next incoming TLS connection. 53 // The returned connection is of type *Conn. 54 func (l *listener) Accept() (net.Conn, error) { 55 c, err := l.Listener.Accept() 56 if err != nil { 57 return nil, err 58 } 59 return Server(c, l.config), nil 60 } 61 62 // NewListener creates a Listener which accepts connections from an inner 63 // Listener and wraps each connection with Server. 64 // The configuration config must be non-nil and must include 65 // at least one certificate or else set GetCertificate. 66 func NewListener(inner net.Listener, config *Config) net.Listener { 67 l := new(listener) 68 l.Listener = inner 69 l.config = config 70 return l 71 } 72 73 // Listen creates a TLS listener accepting connections on the 74 // given network address using net.Listen. 75 // The configuration config must be non-nil and must include 76 // at least one certificate or else set GetCertificate. 77 func Listen(network, laddr string, config *Config) (net.Listener, error) { 78 if config == nil || len(config.Certificates) == 0 && 79 config.GetCertificate == nil && config.GetConfigForClient == nil { 80 return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config") 81 } 82 l, err := net.Listen(network, laddr) 83 if err != nil { 84 return nil, err 85 } 86 return NewListener(l, config), nil 87 } 88 89 type timeoutError struct{} 90 91 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } 92 func (timeoutError) Timeout() bool { return true } 93 func (timeoutError) Temporary() bool { return true } 94 95 // DialWithDialer connects to the given network address using dialer.Dial and 96 // then initiates a TLS handshake, returning the resulting TLS connection. Any 97 // timeout or deadline given in the dialer apply to connection and TLS 98 // handshake as a whole. 99 // 100 // DialWithDialer interprets a nil configuration as equivalent to the zero 101 // configuration; see the documentation of Config for the defaults. 102 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { 103 // We want the Timeout and Deadline values from dialer to cover the 104 // whole process: TCP connection and TLS handshake. This means that we 105 // also need to start our own timers now. 106 timeout := dialer.Timeout 107 108 if !dialer.Deadline.IsZero() { 109 deadlineTimeout := time.Until(dialer.Deadline) 110 if timeout == 0 || deadlineTimeout < timeout { 111 timeout = deadlineTimeout 112 } 113 } 114 115 var errChannel chan error 116 117 if timeout != 0 { 118 errChannel = make(chan error, 2) 119 time.AfterFunc(timeout, func() { 120 errChannel <- timeoutError{} 121 }) 122 } 123 124 rawConn, err := dialer.Dial(network, addr) 125 if err != nil { 126 return nil, err 127 } 128 129 colonPos := strings.LastIndex(addr, ":") 130 if colonPos == -1 { 131 colonPos = len(addr) 132 } 133 hostname := addr[:colonPos] 134 135 if config == nil { 136 config = defaultConfig() 137 } 138 // If no ServerName is set, infer the ServerName 139 // from the hostname we're connecting to. 140 if config.ServerName == "" { 141 // Make a copy to avoid polluting argument or default. 142 c := config.Clone() 143 c.ServerName = hostname 144 config = c 145 } 146 147 conn := Client(rawConn, config) 148 149 if timeout == 0 { 150 err = conn.Handshake() 151 } else { 152 go func() { 153 errChannel <- conn.Handshake() 154 }() 155 156 err = <-errChannel 157 } 158 159 if err != nil { 160 rawConn.Close() 161 return nil, err 162 } 163 164 return conn, nil 165 } 166 167 // Dial connects to the given network address using net.Dial 168 // and then initiates a TLS handshake, returning the resulting 169 // TLS connection. 170 // Dial interprets a nil configuration as equivalent to 171 // the zero configuration; see the documentation of Config 172 // for the defaults. 173 func Dial(network, addr string, config *Config) (*Conn, error) { 174 return DialWithDialer(new(net.Dialer), network, addr, config) 175 } 176 177 // LoadX509KeyPair reads and parses a public/private key pair from a pair 178 // of files. The files must contain PEM encoded data. The certificate file 179 // may contain intermediate certificates following the leaf certificate to 180 // form a certificate chain. On successful return, Certificate.Leaf will 181 // be nil because the parsed form of the certificate is not retained. 182 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) { 183 certPEMBlock, err := ioutil.ReadFile(certFile) 184 if err != nil { 185 return Certificate{}, err 186 } 187 keyPEMBlock, err := ioutil.ReadFile(keyFile) 188 if err != nil { 189 return Certificate{}, err 190 } 191 return X509KeyPair(certPEMBlock, keyPEMBlock) 192 } 193 194 // X509KeyPair parses a public/private key pair from a pair of 195 // PEM encoded data. On successful return, Certificate.Leaf will be nil because 196 // the parsed form of the certificate is not retained. 197 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { 198 fail := func(err error) (Certificate, error) { return Certificate{}, err } 199 200 var cert Certificate 201 var skippedBlockTypes []string 202 for { 203 var certDERBlock *pem.Block 204 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) 205 if certDERBlock == nil { 206 break 207 } 208 if certDERBlock.Type == "CERTIFICATE" { 209 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) 210 } else { 211 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type) 212 } 213 } 214 215 if len(cert.Certificate) == 0 { 216 if len(skippedBlockTypes) == 0 { 217 return fail(errors.New("tls: failed to find any PEM data in certificate input")) 218 } 219 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") { 220 return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched")) 221 } 222 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) 223 } 224 225 skippedBlockTypes = skippedBlockTypes[:0] 226 var keyDERBlock *pem.Block 227 for { 228 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) 229 if keyDERBlock == nil { 230 if len(skippedBlockTypes) == 0 { 231 return fail(errors.New("tls: failed to find any PEM data in key input")) 232 } 233 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { 234 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key")) 235 } 236 return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) 237 } 238 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { 239 break 240 } 241 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) 242 } 243 244 // We don't need to parse the public key for TLS, but we so do anyway 245 // to check that it looks sane and matches the private key. 246 x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) 247 if err != nil { 248 return fail(err) 249 } 250 251 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) 252 if err != nil { 253 return fail(err) 254 } 255 256 switch pub := x509Cert.PublicKey.(type) { 257 case *rsa.PublicKey: 258 priv, ok := cert.PrivateKey.(*rsa.PrivateKey) 259 if !ok { 260 return fail(errors.New("tls: private key type does not match public key type")) 261 } 262 if pub.N.Cmp(priv.N) != 0 { 263 return fail(errors.New("tls: private key does not match public key")) 264 } 265 case *ecdsa.PublicKey: 266 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) 267 if !ok { 268 return fail(errors.New("tls: private key type does not match public key type")) 269 } 270 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { 271 return fail(errors.New("tls: private key does not match public key")) 272 } 273 case ed25519.PublicKey: 274 priv, ok := cert.PrivateKey.(ed25519.PrivateKey) 275 if !ok { 276 return fail(errors.New("tls: private key type does not match public key type")) 277 } 278 if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) { 279 return fail(errors.New("tls: private key does not match public key")) 280 } 281 default: 282 return fail(errors.New("tls: unknown public key algorithm")) 283 } 284 285 return cert, nil 286 } 287 288 // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates 289 // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. 290 // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. 291 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { 292 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { 293 return key, nil 294 } 295 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { 296 switch key := key.(type) { 297 case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey: 298 return key, nil 299 default: 300 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping") 301 } 302 } 303 if key, err := x509.ParseECPrivateKey(der); err == nil { 304 return key, nil 305 } 306 307 return nil, errors.New("tls: failed to parse private key") 308 }