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