github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-15/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 qtls partially implements TLS 1.2, as specified in RFC 5246, 6 // and TLS 1.3, as specified in RFC 8446. 7 package qtls 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 "context" 17 "crypto" 18 "crypto/ecdsa" 19 "crypto/ed25519" 20 "crypto/rsa" 21 "crypto/x509" 22 "encoding/pem" 23 "errors" 24 "fmt" 25 "io/ioutil" 26 "net" 27 "strings" 28 "time" 29 ) 30 31 // Server returns a new TLS server side connection 32 // using conn as the underlying transport. 33 // The configuration config must be non-nil and must include 34 // at least one certificate or else set GetCertificate. 35 func Server(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { 36 c := &Conn{ 37 conn: conn, 38 config: fromConfig(config), 39 extraConfig: extraConfig, 40 } 41 c.handshakeFn = c.serverHandshake 42 return c 43 } 44 45 // Client returns a new TLS client side connection 46 // using conn as the underlying transport. 47 // The config cannot be nil: users must set either ServerName or 48 // InsecureSkipVerify in the config. 49 func Client(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { 50 c := &Conn{ 51 conn: conn, 52 config: fromConfig(config), 53 extraConfig: extraConfig, 54 isClient: true, 55 } 56 c.handshakeFn = c.clientHandshake 57 return c 58 } 59 60 // A listener implements a network listener (net.Listener) for TLS connections. 61 type listener struct { 62 net.Listener 63 config *Config 64 extraConfig *ExtraConfig 65 } 66 67 // Accept waits for and returns the next incoming TLS connection. 68 // The returned connection is of type *Conn. 69 func (l *listener) Accept() (net.Conn, error) { 70 c, err := l.Listener.Accept() 71 if err != nil { 72 return nil, err 73 } 74 return Server(c, l.config, l.extraConfig), nil 75 } 76 77 // NewListener creates a Listener which accepts connections from an inner 78 // Listener and wraps each connection with Server. 79 // The configuration config must be non-nil and must include 80 // at least one certificate or else set GetCertificate. 81 func NewListener(inner net.Listener, config *Config, extraConfig *ExtraConfig) net.Listener { 82 l := new(listener) 83 l.Listener = inner 84 l.config = config 85 l.extraConfig = extraConfig 86 return l 87 } 88 89 // Listen creates a TLS listener accepting connections on the 90 // given network address using net.Listen. 91 // The configuration config must be non-nil and must include 92 // at least one certificate or else set GetCertificate. 93 func Listen(network, laddr string, config *Config, extraConfig *ExtraConfig) (net.Listener, error) { 94 if config == nil || len(config.Certificates) == 0 && 95 config.GetCertificate == nil && config.GetConfigForClient == nil { 96 return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config") 97 } 98 l, err := net.Listen(network, laddr) 99 if err != nil { 100 return nil, err 101 } 102 return NewListener(l, config, extraConfig), nil 103 } 104 105 type timeoutError struct{} 106 107 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } 108 func (timeoutError) Timeout() bool { return true } 109 func (timeoutError) Temporary() bool { return true } 110 111 // DialWithDialer connects to the given network address using dialer.Dial and 112 // then initiates a TLS handshake, returning the resulting TLS connection. Any 113 // timeout or deadline given in the dialer apply to connection and TLS 114 // handshake as a whole. 115 // 116 // DialWithDialer interprets a nil configuration as equivalent to the zero 117 // configuration; see the documentation of Config for the defaults. 118 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { 119 return dial(context.Background(), dialer, network, addr, config, extraConfig) 120 } 121 122 func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { 123 // We want the Timeout and Deadline values from dialer to cover the 124 // whole process: TCP connection and TLS handshake. This means that we 125 // also need to start our own timers now. 126 timeout := netDialer.Timeout 127 128 if !netDialer.Deadline.IsZero() { 129 deadlineTimeout := time.Until(netDialer.Deadline) 130 if timeout == 0 || deadlineTimeout < timeout { 131 timeout = deadlineTimeout 132 } 133 } 134 135 // hsErrCh is non-nil if we might not wait for Handshake to complete. 136 var hsErrCh chan error 137 if timeout != 0 || ctx.Done() != nil { 138 hsErrCh = make(chan error, 2) 139 } 140 if timeout != 0 { 141 timer := time.AfterFunc(timeout, func() { 142 hsErrCh <- timeoutError{} 143 }) 144 defer timer.Stop() 145 } 146 147 rawConn, err := netDialer.DialContext(ctx, network, addr) 148 if err != nil { 149 return nil, err 150 } 151 152 colonPos := strings.LastIndex(addr, ":") 153 if colonPos == -1 { 154 colonPos = len(addr) 155 } 156 hostname := addr[:colonPos] 157 158 if config == nil { 159 config = defaultConfig() 160 } 161 // If no ServerName is set, infer the ServerName 162 // from the hostname we're connecting to. 163 if config.ServerName == "" { 164 // Make a copy to avoid polluting argument or default. 165 c := config.Clone() 166 c.ServerName = hostname 167 config = c 168 } 169 170 conn := Client(rawConn, config, extraConfig) 171 172 if hsErrCh == nil { 173 err = conn.Handshake() 174 } else { 175 go func() { 176 hsErrCh <- conn.Handshake() 177 }() 178 179 select { 180 case <-ctx.Done(): 181 err = ctx.Err() 182 case err = <-hsErrCh: 183 if err != nil { 184 // If the error was due to the context 185 // closing, prefer the context's error, rather 186 // than some random network teardown error. 187 if e := ctx.Err(); e != nil { 188 err = e 189 } 190 } 191 } 192 } 193 194 if err != nil { 195 rawConn.Close() 196 return nil, err 197 } 198 199 return conn, nil 200 } 201 202 // Dial connects to the given network address using net.Dial 203 // and then initiates a TLS handshake, returning the resulting 204 // TLS connection. 205 // Dial interprets a nil configuration as equivalent to 206 // the zero configuration; see the documentation of Config 207 // for the defaults. 208 func Dial(network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { 209 return DialWithDialer(new(net.Dialer), network, addr, config, extraConfig) 210 } 211 212 // Dialer dials TLS connections given a configuration and a Dialer for the 213 // underlying connection. 214 type Dialer struct { 215 // NetDialer is the optional dialer to use for the TLS connections' 216 // underlying TCP connections. 217 // A nil NetDialer is equivalent to the net.Dialer zero value. 218 NetDialer *net.Dialer 219 220 // Config is the TLS configuration to use for new connections. 221 // A nil configuration is equivalent to the zero 222 // configuration; see the documentation of Config for the 223 // defaults. 224 Config *Config 225 226 ExtraConfig *ExtraConfig 227 } 228 229 // Dial connects to the given network address and initiates a TLS 230 // handshake, returning the resulting TLS connection. 231 // 232 // The returned Conn, if any, will always be of type *Conn. 233 func (d *Dialer) Dial(network, addr string) (net.Conn, error) { 234 return d.DialContext(context.Background(), network, addr) 235 } 236 237 func (d *Dialer) netDialer() *net.Dialer { 238 if d.NetDialer != nil { 239 return d.NetDialer 240 } 241 return new(net.Dialer) 242 } 243 244 // DialContext connects to the given network address and initiates a TLS 245 // handshake, returning the resulting TLS connection. 246 // 247 // The provided Context must be non-nil. If the context expires before 248 // the connection is complete, an error is returned. Once successfully 249 // connected, any expiration of the context will not affect the 250 // connection. 251 // 252 // The returned Conn, if any, will always be of type *Conn. 253 func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { 254 c, err := dial(ctx, d.netDialer(), network, addr, d.Config, d.ExtraConfig) 255 if err != nil { 256 // Don't return c (a typed nil) in an interface. 257 return nil, err 258 } 259 return c, nil 260 } 261 262 // LoadX509KeyPair reads and parses a public/private key pair from a pair 263 // of files. The files must contain PEM encoded data. The certificate file 264 // may contain intermediate certificates following the leaf certificate to 265 // form a certificate chain. On successful return, Certificate.Leaf will 266 // be nil because the parsed form of the certificate is not retained. 267 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) { 268 certPEMBlock, err := ioutil.ReadFile(certFile) 269 if err != nil { 270 return Certificate{}, err 271 } 272 keyPEMBlock, err := ioutil.ReadFile(keyFile) 273 if err != nil { 274 return Certificate{}, err 275 } 276 return X509KeyPair(certPEMBlock, keyPEMBlock) 277 } 278 279 // X509KeyPair parses a public/private key pair from a pair of 280 // PEM encoded data. On successful return, Certificate.Leaf will be nil because 281 // the parsed form of the certificate is not retained. 282 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { 283 fail := func(err error) (Certificate, error) { return Certificate{}, err } 284 285 var cert Certificate 286 var skippedBlockTypes []string 287 for { 288 var certDERBlock *pem.Block 289 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) 290 if certDERBlock == nil { 291 break 292 } 293 if certDERBlock.Type == "CERTIFICATE" { 294 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) 295 } else { 296 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type) 297 } 298 } 299 300 if len(cert.Certificate) == 0 { 301 if len(skippedBlockTypes) == 0 { 302 return fail(errors.New("tls: failed to find any PEM data in certificate input")) 303 } 304 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") { 305 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")) 306 } 307 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) 308 } 309 310 skippedBlockTypes = skippedBlockTypes[:0] 311 var keyDERBlock *pem.Block 312 for { 313 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) 314 if keyDERBlock == nil { 315 if len(skippedBlockTypes) == 0 { 316 return fail(errors.New("tls: failed to find any PEM data in key input")) 317 } 318 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { 319 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key")) 320 } 321 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)) 322 } 323 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { 324 break 325 } 326 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) 327 } 328 329 // We don't need to parse the public key for TLS, but we so do anyway 330 // to check that it looks sane and matches the private key. 331 x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) 332 if err != nil { 333 return fail(err) 334 } 335 336 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) 337 if err != nil { 338 return fail(err) 339 } 340 341 switch pub := x509Cert.PublicKey.(type) { 342 case *rsa.PublicKey: 343 priv, ok := cert.PrivateKey.(*rsa.PrivateKey) 344 if !ok { 345 return fail(errors.New("tls: private key type does not match public key type")) 346 } 347 if pub.N.Cmp(priv.N) != 0 { 348 return fail(errors.New("tls: private key does not match public key")) 349 } 350 case *ecdsa.PublicKey: 351 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) 352 if !ok { 353 return fail(errors.New("tls: private key type does not match public key type")) 354 } 355 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { 356 return fail(errors.New("tls: private key does not match public key")) 357 } 358 case ed25519.PublicKey: 359 priv, ok := cert.PrivateKey.(ed25519.PrivateKey) 360 if !ok { 361 return fail(errors.New("tls: private key type does not match public key type")) 362 } 363 if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) { 364 return fail(errors.New("tls: private key does not match public key")) 365 } 366 default: 367 return fail(errors.New("tls: unknown public key algorithm")) 368 } 369 370 return cert, nil 371 } 372 373 // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates 374 // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys. 375 // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. 376 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { 377 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { 378 return key, nil 379 } 380 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { 381 switch key := key.(type) { 382 case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey: 383 return key, nil 384 default: 385 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping") 386 } 387 } 388 if key, err := x509.ParseECPrivateKey(der); err == nil { 389 return key, nil 390 } 391 392 return nil, errors.New("tls: failed to parse private key") 393 }