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