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