Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 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 main |
| 6 | |
| 7 | import ( |
| 8 | "container/list" |
| 9 | "crypto" |
| 10 | "crypto/rand" |
| 11 | "crypto/x509" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "math/big" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "time" |
| 18 | ) |
| 19 | |
| 20 | const ( |
| 21 | VersionSSL30 = 0x0300 |
| 22 | VersionTLS10 = 0x0301 |
| 23 | VersionTLS11 = 0x0302 |
| 24 | VersionTLS12 = 0x0303 |
| 25 | ) |
| 26 | |
| 27 | const ( |
| 28 | maxPlaintext = 16384 // maximum plaintext payload length |
| 29 | maxCiphertext = 16384 + 2048 // maximum ciphertext payload length |
| 30 | recordHeaderLen = 5 // record header length |
| 31 | maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) |
| 32 | |
| 33 | minVersion = VersionSSL30 |
| 34 | maxVersion = VersionTLS12 |
| 35 | ) |
| 36 | |
| 37 | // TLS record types. |
| 38 | type recordType uint8 |
| 39 | |
| 40 | const ( |
| 41 | recordTypeChangeCipherSpec recordType = 20 |
| 42 | recordTypeAlert recordType = 21 |
| 43 | recordTypeHandshake recordType = 22 |
| 44 | recordTypeApplicationData recordType = 23 |
| 45 | ) |
| 46 | |
| 47 | // TLS handshake message types. |
| 48 | const ( |
| 49 | typeClientHello uint8 = 1 |
| 50 | typeServerHello uint8 = 2 |
| 51 | typeNewSessionTicket uint8 = 4 |
| 52 | typeCertificate uint8 = 11 |
| 53 | typeServerKeyExchange uint8 = 12 |
| 54 | typeCertificateRequest uint8 = 13 |
| 55 | typeServerHelloDone uint8 = 14 |
| 56 | typeCertificateVerify uint8 = 15 |
| 57 | typeClientKeyExchange uint8 = 16 |
| 58 | typeFinished uint8 = 20 |
| 59 | typeCertificateStatus uint8 = 22 |
| 60 | typeNextProtocol uint8 = 67 // Not IANA assigned |
| 61 | ) |
| 62 | |
| 63 | // TLS compression types. |
| 64 | const ( |
| 65 | compressionNone uint8 = 0 |
| 66 | ) |
| 67 | |
| 68 | // TLS extension numbers |
| 69 | const ( |
| 70 | extensionServerName uint16 = 0 |
| 71 | extensionStatusRequest uint16 = 5 |
| 72 | extensionSupportedCurves uint16 = 10 |
| 73 | extensionSupportedPoints uint16 = 11 |
| 74 | extensionSignatureAlgorithms uint16 = 13 |
| 75 | extensionSessionTicket uint16 = 35 |
| 76 | extensionNextProtoNeg uint16 = 13172 // not IANA assigned |
| 77 | extensionRenegotiationInfo uint16 = 0xff01 |
| 78 | ) |
| 79 | |
| 80 | // TLS signaling cipher suite values |
| 81 | const ( |
| 82 | scsvRenegotiation uint16 = 0x00ff |
| 83 | ) |
| 84 | |
| 85 | // CurveID is the type of a TLS identifier for an elliptic curve. See |
| 86 | // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 |
| 87 | type CurveID uint16 |
| 88 | |
| 89 | const ( |
| 90 | CurveP256 CurveID = 23 |
| 91 | CurveP384 CurveID = 24 |
| 92 | CurveP521 CurveID = 25 |
| 93 | ) |
| 94 | |
| 95 | // TLS Elliptic Curve Point Formats |
| 96 | // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 |
| 97 | const ( |
| 98 | pointFormatUncompressed uint8 = 0 |
| 99 | ) |
| 100 | |
| 101 | // TLS CertificateStatusType (RFC 3546) |
| 102 | const ( |
| 103 | statusTypeOCSP uint8 = 1 |
| 104 | ) |
| 105 | |
| 106 | // Certificate types (for certificateRequestMsg) |
| 107 | const ( |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 108 | CertTypeRSASign = 1 // A certificate containing an RSA key |
| 109 | CertTypeDSSSign = 2 // A certificate containing a DSA key |
| 110 | CertTypeRSAFixedDH = 3 // A certificate containing a static DH key |
| 111 | CertTypeDSSFixedDH = 4 // A certificate containing a static DH key |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 112 | |
| 113 | // See RFC4492 sections 3 and 5.5. |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 114 | CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. |
| 115 | CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. |
| 116 | CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA. |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 117 | |
| 118 | // Rest of these are reserved by the TLS spec |
| 119 | ) |
| 120 | |
| 121 | // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1) |
| 122 | const ( |
| 123 | hashSHA1 uint8 = 2 |
| 124 | hashSHA256 uint8 = 4 |
| 125 | ) |
| 126 | |
| 127 | // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1) |
| 128 | const ( |
| 129 | signatureRSA uint8 = 1 |
| 130 | signatureECDSA uint8 = 3 |
| 131 | ) |
| 132 | |
| 133 | // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See |
| 134 | // RFC 5246, section A.4.1. |
| 135 | type signatureAndHash struct { |
| 136 | hash, signature uint8 |
| 137 | } |
| 138 | |
| 139 | // supportedSKXSignatureAlgorithms contains the signature and hash algorithms |
| 140 | // that the code advertises as supported in a TLS 1.2 ClientHello. |
| 141 | var supportedSKXSignatureAlgorithms = []signatureAndHash{ |
| 142 | {hashSHA256, signatureRSA}, |
| 143 | {hashSHA256, signatureECDSA}, |
| 144 | {hashSHA1, signatureRSA}, |
| 145 | {hashSHA1, signatureECDSA}, |
| 146 | } |
| 147 | |
| 148 | // supportedClientCertSignatureAlgorithms contains the signature and hash |
| 149 | // algorithms that the code advertises as supported in a TLS 1.2 |
| 150 | // CertificateRequest. |
| 151 | var supportedClientCertSignatureAlgorithms = []signatureAndHash{ |
| 152 | {hashSHA256, signatureRSA}, |
| 153 | {hashSHA256, signatureECDSA}, |
| 154 | } |
| 155 | |
| 156 | // ConnectionState records basic TLS details about the connection. |
| 157 | type ConnectionState struct { |
| 158 | Version uint16 // TLS version used by the connection (e.g. VersionTLS12) |
| 159 | HandshakeComplete bool // TLS handshake is complete |
| 160 | DidResume bool // connection resumes a previous TLS connection |
| 161 | CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) |
| 162 | NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) |
| 163 | NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server |
| 164 | ServerName string // server name requested by client, if any (server side only) |
| 165 | PeerCertificates []*x509.Certificate // certificate chain presented by remote peer |
| 166 | VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates |
| 167 | } |
| 168 | |
| 169 | // ClientAuthType declares the policy the server will follow for |
| 170 | // TLS Client Authentication. |
| 171 | type ClientAuthType int |
| 172 | |
| 173 | const ( |
| 174 | NoClientCert ClientAuthType = iota |
| 175 | RequestClientCert |
| 176 | RequireAnyClientCert |
| 177 | VerifyClientCertIfGiven |
| 178 | RequireAndVerifyClientCert |
| 179 | ) |
| 180 | |
| 181 | // ClientSessionState contains the state needed by clients to resume TLS |
| 182 | // sessions. |
| 183 | type ClientSessionState struct { |
| 184 | sessionTicket []uint8 // Encrypted ticket used for session resumption with server |
| 185 | vers uint16 // SSL/TLS version negotiated for the session |
| 186 | cipherSuite uint16 // Ciphersuite negotiated for the session |
| 187 | masterSecret []byte // MasterSecret generated by client on a full handshake |
| 188 | serverCertificates []*x509.Certificate // Certificate chain presented by the server |
| 189 | } |
| 190 | |
| 191 | // ClientSessionCache is a cache of ClientSessionState objects that can be used |
| 192 | // by a client to resume a TLS session with a given server. ClientSessionCache |
| 193 | // implementations should expect to be called concurrently from different |
| 194 | // goroutines. |
| 195 | type ClientSessionCache interface { |
| 196 | // Get searches for a ClientSessionState associated with the given key. |
| 197 | // On return, ok is true if one was found. |
| 198 | Get(sessionKey string) (session *ClientSessionState, ok bool) |
| 199 | |
| 200 | // Put adds the ClientSessionState to the cache with the given key. |
| 201 | Put(sessionKey string, cs *ClientSessionState) |
| 202 | } |
| 203 | |
| 204 | // A Config structure is used to configure a TLS client or server. |
| 205 | // After one has been passed to a TLS function it must not be |
| 206 | // modified. A Config may be reused; the tls package will also not |
| 207 | // modify it. |
| 208 | type Config struct { |
| 209 | // Rand provides the source of entropy for nonces and RSA blinding. |
| 210 | // If Rand is nil, TLS uses the cryptographic random reader in package |
| 211 | // crypto/rand. |
| 212 | // The Reader must be safe for use by multiple goroutines. |
| 213 | Rand io.Reader |
| 214 | |
| 215 | // Time returns the current time as the number of seconds since the epoch. |
| 216 | // If Time is nil, TLS uses time.Now. |
| 217 | Time func() time.Time |
| 218 | |
| 219 | // Certificates contains one or more certificate chains |
| 220 | // to present to the other side of the connection. |
| 221 | // Server configurations must include at least one certificate. |
| 222 | Certificates []Certificate |
| 223 | |
| 224 | // NameToCertificate maps from a certificate name to an element of |
| 225 | // Certificates. Note that a certificate name can be of the form |
| 226 | // '*.example.com' and so doesn't have to be a domain name as such. |
| 227 | // See Config.BuildNameToCertificate |
| 228 | // The nil value causes the first element of Certificates to be used |
| 229 | // for all connections. |
| 230 | NameToCertificate map[string]*Certificate |
| 231 | |
| 232 | // RootCAs defines the set of root certificate authorities |
| 233 | // that clients use when verifying server certificates. |
| 234 | // If RootCAs is nil, TLS uses the host's root CA set. |
| 235 | RootCAs *x509.CertPool |
| 236 | |
| 237 | // NextProtos is a list of supported, application level protocols. |
| 238 | NextProtos []string |
| 239 | |
| 240 | // ServerName is used to verify the hostname on the returned |
| 241 | // certificates unless InsecureSkipVerify is given. It is also included |
| 242 | // in the client's handshake to support virtual hosting. |
| 243 | ServerName string |
| 244 | |
| 245 | // ClientAuth determines the server's policy for |
| 246 | // TLS Client Authentication. The default is NoClientCert. |
| 247 | ClientAuth ClientAuthType |
| 248 | |
| 249 | // ClientCAs defines the set of root certificate authorities |
| 250 | // that servers use if required to verify a client certificate |
| 251 | // by the policy in ClientAuth. |
| 252 | ClientCAs *x509.CertPool |
| 253 | |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 254 | // ClientCertificateTypes defines the set of allowed client certificate |
| 255 | // types. The default is CertTypeRSASign and CertTypeECDSASign. |
| 256 | ClientCertificateTypes []byte |
| 257 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 258 | // InsecureSkipVerify controls whether a client verifies the |
| 259 | // server's certificate chain and host name. |
| 260 | // If InsecureSkipVerify is true, TLS accepts any certificate |
| 261 | // presented by the server and any host name in that certificate. |
| 262 | // In this mode, TLS is susceptible to man-in-the-middle attacks. |
| 263 | // This should be used only for testing. |
| 264 | InsecureSkipVerify bool |
| 265 | |
| 266 | // CipherSuites is a list of supported cipher suites. If CipherSuites |
| 267 | // is nil, TLS uses a list of suites supported by the implementation. |
| 268 | CipherSuites []uint16 |
| 269 | |
| 270 | // PreferServerCipherSuites controls whether the server selects the |
| 271 | // client's most preferred ciphersuite, or the server's most preferred |
| 272 | // ciphersuite. If true then the server's preference, as expressed in |
| 273 | // the order of elements in CipherSuites, is used. |
| 274 | PreferServerCipherSuites bool |
| 275 | |
| 276 | // SessionTicketsDisabled may be set to true to disable session ticket |
| 277 | // (resumption) support. |
| 278 | SessionTicketsDisabled bool |
| 279 | |
| 280 | // SessionTicketKey is used by TLS servers to provide session |
| 281 | // resumption. See RFC 5077. If zero, it will be filled with |
| 282 | // random data before the first server handshake. |
| 283 | // |
| 284 | // If multiple servers are terminating connections for the same host |
| 285 | // they should all have the same SessionTicketKey. If the |
| 286 | // SessionTicketKey leaks, previously recorded and future TLS |
| 287 | // connections using that key are compromised. |
| 288 | SessionTicketKey [32]byte |
| 289 | |
| 290 | // SessionCache is a cache of ClientSessionState entries for TLS session |
| 291 | // resumption. |
| 292 | ClientSessionCache ClientSessionCache |
| 293 | |
| 294 | // MinVersion contains the minimum SSL/TLS version that is acceptable. |
| 295 | // If zero, then SSLv3 is taken as the minimum. |
| 296 | MinVersion uint16 |
| 297 | |
| 298 | // MaxVersion contains the maximum SSL/TLS version that is acceptable. |
| 299 | // If zero, then the maximum version supported by this package is used, |
| 300 | // which is currently TLS 1.2. |
| 301 | MaxVersion uint16 |
| 302 | |
| 303 | // CurvePreferences contains the elliptic curves that will be used in |
| 304 | // an ECDHE handshake, in preference order. If empty, the default will |
| 305 | // be used. |
| 306 | CurvePreferences []CurveID |
| 307 | |
| 308 | // Bugs specifies optional misbehaviour to be used for testing other |
| 309 | // implementations. |
| 310 | Bugs ProtocolBugs |
| 311 | |
| 312 | serverInitOnce sync.Once // guards calling (*Config).serverInit |
| 313 | } |
| 314 | |
| 315 | type BadValue int |
| 316 | |
| 317 | const ( |
| 318 | BadValueNone BadValue = iota |
| 319 | BadValueNegative |
| 320 | BadValueZero |
| 321 | BadValueLimit |
| 322 | BadValueLarge |
| 323 | NumBadValues |
| 324 | ) |
| 325 | |
| 326 | type ProtocolBugs struct { |
| 327 | // InvalidSKXSignature specifies that the signature in a |
| 328 | // ServerKeyExchange message should be invalid. |
| 329 | InvalidSKXSignature bool |
| 330 | |
| 331 | // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message |
| 332 | // to be wrong. |
| 333 | InvalidSKXCurve bool |
| 334 | |
| 335 | // BadECDSAR controls ways in which the 'r' value of an ECDSA signature |
| 336 | // can be invalid. |
| 337 | BadECDSAR BadValue |
| 338 | BadECDSAS BadValue |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 339 | |
| 340 | // MaxPadding causes CBC records to have the maximum possible padding. |
| 341 | MaxPadding bool |
| 342 | // PaddingFirstByteBad causes the first byte of the padding to be |
| 343 | // incorrect. |
| 344 | PaddingFirstByteBad bool |
| 345 | // PaddingFirstByteBadIf255 causes the first byte of padding to be |
| 346 | // incorrect if there's a maximum amount of padding (i.e. 255 bytes). |
| 347 | PaddingFirstByteBadIf255 bool |
Adam Langley | ac61fa3 | 2014-06-23 12:03:11 -0700 | [diff] [blame] | 348 | |
| 349 | // FailIfNotFallbackSCSV causes a server handshake to fail if the |
| 350 | // client doesn't send the fallback SCSV value. |
| 351 | FailIfNotFallbackSCSV bool |
David Benjamin | 35a7a44 | 2014-07-05 00:23:20 -0400 | [diff] [blame] | 352 | |
| 353 | // DuplicateExtension causes an extra empty extension of bogus type to |
| 354 | // be emitted in either the ClientHello or the ServerHello. |
| 355 | DuplicateExtension bool |
David Benjamin | 1c375dd | 2014-07-12 00:48:23 -0400 | [diff] [blame] | 356 | |
| 357 | // UnauthenticatedECDH causes the server to pretend ECDHE_RSA |
| 358 | // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No |
| 359 | // Certificate message is sent and no signature is added to |
| 360 | // ServerKeyExchange. |
| 361 | UnauthenticatedECDH bool |
David Benjamin | 9c651c9 | 2014-07-12 13:27:45 -0400 | [diff] [blame] | 362 | |
| 363 | // SkipServerKeyExchange causes the server to skip sending |
| 364 | // ServerKeyExchange messages. |
| 365 | SkipServerKeyExchange bool |
David Benjamin | a0e5223 | 2014-07-19 17:39:58 -0400 | [diff] [blame] | 366 | |
| 367 | // SkipChangeCipherSpec causes the implementation to skip |
| 368 | // sending the ChangeCipherSpec message (and adjusting cipher |
| 369 | // state accordingly for the Finished message). |
| 370 | SkipChangeCipherSpec bool |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 371 | |
| 372 | // EarlyChangeCipherSpec causes the client to send an early |
| 373 | // ChangeCipherSpec message before the ClientKeyExchange. A value of |
| 374 | // zero disables this behavior. One and two configure variants for 0.9.8 |
| 375 | // and 1.0.1 modes, respectively. |
| 376 | EarlyChangeCipherSpec int |
David Benjamin | d23f412 | 2014-07-23 15:09:48 -0400 | [diff] [blame] | 377 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 378 | // FragmentAcrossChangeCipherSpec causes the implementation to fragment |
| 379 | // the Finished (or NextProto) message around the ChangeCipherSpec |
| 380 | // messages. |
| 381 | FragmentAcrossChangeCipherSpec bool |
| 382 | |
David Benjamin | d23f412 | 2014-07-23 15:09:48 -0400 | [diff] [blame] | 383 | // SkipNewSessionTicket causes the server to skip sending the |
| 384 | // NewSessionTicket message despite promising to in ServerHello. |
| 385 | SkipNewSessionTicket bool |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 386 | |
| 387 | // SendV2ClientHello causes the client to send a V2ClientHello |
| 388 | // instead of a normal ClientHello. |
| 389 | SendV2ClientHello bool |
David Benjamin | bef270a | 2014-08-02 04:22:02 -0400 | [diff] [blame] | 390 | |
| 391 | // SendFallbackSCSV causes the client to include |
| 392 | // TLS_FALLBACK_SCSV in the ClientHello. |
| 393 | SendFallbackSCSV bool |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 394 | |
| 395 | // MaxHandshakeRecordLength, if non-zero, is the maximum size of a |
| 396 | // handshake record. Handshake messages will be split at the record |
| 397 | // layer. |
| 398 | MaxHandshakeRecordLength int |
David Benjamin | a8e3e0e | 2014-08-06 22:11:10 -0400 | [diff] [blame^] | 399 | |
| 400 | // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a |
| 401 | // ClientKeyExchange with the specified version rather than the |
| 402 | // client_version when performing the RSA key exchange. |
| 403 | RsaClientKeyExchangeVersion uint16 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 404 | } |
| 405 | |
| 406 | func (c *Config) serverInit() { |
| 407 | if c.SessionTicketsDisabled { |
| 408 | return |
| 409 | } |
| 410 | |
| 411 | // If the key has already been set then we have nothing to do. |
| 412 | for _, b := range c.SessionTicketKey { |
| 413 | if b != 0 { |
| 414 | return |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { |
| 419 | c.SessionTicketsDisabled = true |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | func (c *Config) rand() io.Reader { |
| 424 | r := c.Rand |
| 425 | if r == nil { |
| 426 | return rand.Reader |
| 427 | } |
| 428 | return r |
| 429 | } |
| 430 | |
| 431 | func (c *Config) time() time.Time { |
| 432 | t := c.Time |
| 433 | if t == nil { |
| 434 | t = time.Now |
| 435 | } |
| 436 | return t() |
| 437 | } |
| 438 | |
| 439 | func (c *Config) cipherSuites() []uint16 { |
| 440 | s := c.CipherSuites |
| 441 | if s == nil { |
| 442 | s = defaultCipherSuites() |
| 443 | } |
| 444 | return s |
| 445 | } |
| 446 | |
| 447 | func (c *Config) minVersion() uint16 { |
| 448 | if c == nil || c.MinVersion == 0 { |
| 449 | return minVersion |
| 450 | } |
| 451 | return c.MinVersion |
| 452 | } |
| 453 | |
| 454 | func (c *Config) maxVersion() uint16 { |
| 455 | if c == nil || c.MaxVersion == 0 { |
| 456 | return maxVersion |
| 457 | } |
| 458 | return c.MaxVersion |
| 459 | } |
| 460 | |
| 461 | var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521} |
| 462 | |
| 463 | func (c *Config) curvePreferences() []CurveID { |
| 464 | if c == nil || len(c.CurvePreferences) == 0 { |
| 465 | return defaultCurvePreferences |
| 466 | } |
| 467 | return c.CurvePreferences |
| 468 | } |
| 469 | |
| 470 | // mutualVersion returns the protocol version to use given the advertised |
| 471 | // version of the peer. |
| 472 | func (c *Config) mutualVersion(vers uint16) (uint16, bool) { |
| 473 | minVersion := c.minVersion() |
| 474 | maxVersion := c.maxVersion() |
| 475 | |
| 476 | if vers < minVersion { |
| 477 | return 0, false |
| 478 | } |
| 479 | if vers > maxVersion { |
| 480 | vers = maxVersion |
| 481 | } |
| 482 | return vers, true |
| 483 | } |
| 484 | |
| 485 | // getCertificateForName returns the best certificate for the given name, |
| 486 | // defaulting to the first element of c.Certificates if there are no good |
| 487 | // options. |
| 488 | func (c *Config) getCertificateForName(name string) *Certificate { |
| 489 | if len(c.Certificates) == 1 || c.NameToCertificate == nil { |
| 490 | // There's only one choice, so no point doing any work. |
| 491 | return &c.Certificates[0] |
| 492 | } |
| 493 | |
| 494 | name = strings.ToLower(name) |
| 495 | for len(name) > 0 && name[len(name)-1] == '.' { |
| 496 | name = name[:len(name)-1] |
| 497 | } |
| 498 | |
| 499 | if cert, ok := c.NameToCertificate[name]; ok { |
| 500 | return cert |
| 501 | } |
| 502 | |
| 503 | // try replacing labels in the name with wildcards until we get a |
| 504 | // match. |
| 505 | labels := strings.Split(name, ".") |
| 506 | for i := range labels { |
| 507 | labels[i] = "*" |
| 508 | candidate := strings.Join(labels, ".") |
| 509 | if cert, ok := c.NameToCertificate[candidate]; ok { |
| 510 | return cert |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | // If nothing matches, return the first certificate. |
| 515 | return &c.Certificates[0] |
| 516 | } |
| 517 | |
| 518 | // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate |
| 519 | // from the CommonName and SubjectAlternateName fields of each of the leaf |
| 520 | // certificates. |
| 521 | func (c *Config) BuildNameToCertificate() { |
| 522 | c.NameToCertificate = make(map[string]*Certificate) |
| 523 | for i := range c.Certificates { |
| 524 | cert := &c.Certificates[i] |
| 525 | x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) |
| 526 | if err != nil { |
| 527 | continue |
| 528 | } |
| 529 | if len(x509Cert.Subject.CommonName) > 0 { |
| 530 | c.NameToCertificate[x509Cert.Subject.CommonName] = cert |
| 531 | } |
| 532 | for _, san := range x509Cert.DNSNames { |
| 533 | c.NameToCertificate[san] = cert |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | // A Certificate is a chain of one or more certificates, leaf first. |
| 539 | type Certificate struct { |
| 540 | Certificate [][]byte |
| 541 | PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey |
| 542 | // OCSPStaple contains an optional OCSP response which will be served |
| 543 | // to clients that request it. |
| 544 | OCSPStaple []byte |
| 545 | // Leaf is the parsed form of the leaf certificate, which may be |
| 546 | // initialized using x509.ParseCertificate to reduce per-handshake |
| 547 | // processing for TLS clients doing client authentication. If nil, the |
| 548 | // leaf certificate will be parsed as needed. |
| 549 | Leaf *x509.Certificate |
| 550 | } |
| 551 | |
| 552 | // A TLS record. |
| 553 | type record struct { |
| 554 | contentType recordType |
| 555 | major, minor uint8 |
| 556 | payload []byte |
| 557 | } |
| 558 | |
| 559 | type handshakeMessage interface { |
| 560 | marshal() []byte |
| 561 | unmarshal([]byte) bool |
| 562 | } |
| 563 | |
| 564 | // lruSessionCache is a ClientSessionCache implementation that uses an LRU |
| 565 | // caching strategy. |
| 566 | type lruSessionCache struct { |
| 567 | sync.Mutex |
| 568 | |
| 569 | m map[string]*list.Element |
| 570 | q *list.List |
| 571 | capacity int |
| 572 | } |
| 573 | |
| 574 | type lruSessionCacheEntry struct { |
| 575 | sessionKey string |
| 576 | state *ClientSessionState |
| 577 | } |
| 578 | |
| 579 | // NewLRUClientSessionCache returns a ClientSessionCache with the given |
| 580 | // capacity that uses an LRU strategy. If capacity is < 1, a default capacity |
| 581 | // is used instead. |
| 582 | func NewLRUClientSessionCache(capacity int) ClientSessionCache { |
| 583 | const defaultSessionCacheCapacity = 64 |
| 584 | |
| 585 | if capacity < 1 { |
| 586 | capacity = defaultSessionCacheCapacity |
| 587 | } |
| 588 | return &lruSessionCache{ |
| 589 | m: make(map[string]*list.Element), |
| 590 | q: list.New(), |
| 591 | capacity: capacity, |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | // Put adds the provided (sessionKey, cs) pair to the cache. |
| 596 | func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { |
| 597 | c.Lock() |
| 598 | defer c.Unlock() |
| 599 | |
| 600 | if elem, ok := c.m[sessionKey]; ok { |
| 601 | entry := elem.Value.(*lruSessionCacheEntry) |
| 602 | entry.state = cs |
| 603 | c.q.MoveToFront(elem) |
| 604 | return |
| 605 | } |
| 606 | |
| 607 | if c.q.Len() < c.capacity { |
| 608 | entry := &lruSessionCacheEntry{sessionKey, cs} |
| 609 | c.m[sessionKey] = c.q.PushFront(entry) |
| 610 | return |
| 611 | } |
| 612 | |
| 613 | elem := c.q.Back() |
| 614 | entry := elem.Value.(*lruSessionCacheEntry) |
| 615 | delete(c.m, entry.sessionKey) |
| 616 | entry.sessionKey = sessionKey |
| 617 | entry.state = cs |
| 618 | c.q.MoveToFront(elem) |
| 619 | c.m[sessionKey] = elem |
| 620 | } |
| 621 | |
| 622 | // Get returns the ClientSessionState value associated with a given key. It |
| 623 | // returns (nil, false) if no value is found. |
| 624 | func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { |
| 625 | c.Lock() |
| 626 | defer c.Unlock() |
| 627 | |
| 628 | if elem, ok := c.m[sessionKey]; ok { |
| 629 | c.q.MoveToFront(elem) |
| 630 | return elem.Value.(*lruSessionCacheEntry).state, true |
| 631 | } |
| 632 | return nil, false |
| 633 | } |
| 634 | |
| 635 | // TODO(jsing): Make these available to both crypto/x509 and crypto/tls. |
| 636 | type dsaSignature struct { |
| 637 | R, S *big.Int |
| 638 | } |
| 639 | |
| 640 | type ecdsaSignature dsaSignature |
| 641 | |
| 642 | var emptyConfig Config |
| 643 | |
| 644 | func defaultConfig() *Config { |
| 645 | return &emptyConfig |
| 646 | } |
| 647 | |
| 648 | var ( |
| 649 | once sync.Once |
| 650 | varDefaultCipherSuites []uint16 |
| 651 | ) |
| 652 | |
| 653 | func defaultCipherSuites() []uint16 { |
| 654 | once.Do(initDefaultCipherSuites) |
| 655 | return varDefaultCipherSuites |
| 656 | } |
| 657 | |
| 658 | func initDefaultCipherSuites() { |
| 659 | varDefaultCipherSuites = make([]uint16, len(cipherSuites)) |
| 660 | for i, suite := range cipherSuites { |
| 661 | varDefaultCipherSuites[i] = suite.id |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | func unexpectedMessageError(wanted, got interface{}) error { |
| 666 | return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) |
| 667 | } |