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" |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 10 | "crypto/ecdsa" |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 11 | "crypto/rand" |
| 12 | "crypto/x509" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "math/big" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "time" |
| 19 | ) |
| 20 | |
| 21 | const ( |
| 22 | VersionSSL30 = 0x0300 |
| 23 | VersionTLS10 = 0x0301 |
| 24 | VersionTLS11 = 0x0302 |
| 25 | VersionTLS12 = 0x0303 |
| 26 | ) |
| 27 | |
| 28 | const ( |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 29 | maxPlaintext = 16384 // maximum plaintext payload length |
| 30 | maxCiphertext = 16384 + 2048 // maximum ciphertext payload length |
| 31 | tlsRecordHeaderLen = 5 // record header length |
| 32 | dtlsRecordHeaderLen = 13 |
| 33 | maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 34 | |
| 35 | minVersion = VersionSSL30 |
| 36 | maxVersion = VersionTLS12 |
| 37 | ) |
| 38 | |
| 39 | // TLS record types. |
| 40 | type recordType uint8 |
| 41 | |
| 42 | const ( |
| 43 | recordTypeChangeCipherSpec recordType = 20 |
| 44 | recordTypeAlert recordType = 21 |
| 45 | recordTypeHandshake recordType = 22 |
| 46 | recordTypeApplicationData recordType = 23 |
| 47 | ) |
| 48 | |
| 49 | // TLS handshake message types. |
| 50 | const ( |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 51 | typeHelloRequest uint8 = 0 |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 52 | typeClientHello uint8 = 1 |
| 53 | typeServerHello uint8 = 2 |
| 54 | typeHelloVerifyRequest uint8 = 3 |
| 55 | typeNewSessionTicket uint8 = 4 |
| 56 | typeCertificate uint8 = 11 |
| 57 | typeServerKeyExchange uint8 = 12 |
| 58 | typeCertificateRequest uint8 = 13 |
| 59 | typeServerHelloDone uint8 = 14 |
| 60 | typeCertificateVerify uint8 = 15 |
| 61 | typeClientKeyExchange uint8 = 16 |
| 62 | typeFinished uint8 = 20 |
| 63 | typeCertificateStatus uint8 = 22 |
| 64 | typeNextProtocol uint8 = 67 // Not IANA assigned |
| 65 | typeEncryptedExtensions uint8 = 203 // Not IANA assigned |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 66 | ) |
| 67 | |
| 68 | // TLS compression types. |
| 69 | const ( |
| 70 | compressionNone uint8 = 0 |
| 71 | ) |
| 72 | |
| 73 | // TLS extension numbers |
| 74 | const ( |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 75 | extensionServerName uint16 = 0 |
| 76 | extensionStatusRequest uint16 = 5 |
| 77 | extensionSupportedCurves uint16 = 10 |
| 78 | extensionSupportedPoints uint16 = 11 |
| 79 | extensionSignatureAlgorithms uint16 = 13 |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 80 | extensionUseSRTP uint16 = 14 |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 81 | extensionALPN uint16 = 16 |
| 82 | extensionExtendedMasterSecret uint16 = 23 |
| 83 | extensionSessionTicket uint16 = 35 |
| 84 | extensionNextProtoNeg uint16 = 13172 // not IANA assigned |
| 85 | extensionRenegotiationInfo uint16 = 0xff01 |
| 86 | extensionChannelID uint16 = 30032 // not IANA assigned |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 87 | ) |
| 88 | |
| 89 | // TLS signaling cipher suite values |
| 90 | const ( |
| 91 | scsvRenegotiation uint16 = 0x00ff |
| 92 | ) |
| 93 | |
| 94 | // CurveID is the type of a TLS identifier for an elliptic curve. See |
| 95 | // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 |
| 96 | type CurveID uint16 |
| 97 | |
| 98 | const ( |
| 99 | CurveP256 CurveID = 23 |
| 100 | CurveP384 CurveID = 24 |
| 101 | CurveP521 CurveID = 25 |
| 102 | ) |
| 103 | |
| 104 | // TLS Elliptic Curve Point Formats |
| 105 | // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 |
| 106 | const ( |
| 107 | pointFormatUncompressed uint8 = 0 |
| 108 | ) |
| 109 | |
| 110 | // TLS CertificateStatusType (RFC 3546) |
| 111 | const ( |
| 112 | statusTypeOCSP uint8 = 1 |
| 113 | ) |
| 114 | |
| 115 | // Certificate types (for certificateRequestMsg) |
| 116 | const ( |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 117 | CertTypeRSASign = 1 // A certificate containing an RSA key |
| 118 | CertTypeDSSSign = 2 // A certificate containing a DSA key |
| 119 | CertTypeRSAFixedDH = 3 // A certificate containing a static DH key |
| 120 | CertTypeDSSFixedDH = 4 // A certificate containing a static DH key |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 121 | |
| 122 | // See RFC4492 sections 3 and 5.5. |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 123 | CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. |
| 124 | CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. |
| 125 | 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] | 126 | |
| 127 | // Rest of these are reserved by the TLS spec |
| 128 | ) |
| 129 | |
| 130 | // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1) |
| 131 | const ( |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 132 | hashMD5 uint8 = 1 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 133 | hashSHA1 uint8 = 2 |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 134 | hashSHA224 uint8 = 3 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 135 | hashSHA256 uint8 = 4 |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 136 | hashSHA384 uint8 = 5 |
| 137 | hashSHA512 uint8 = 6 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 138 | ) |
| 139 | |
| 140 | // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1) |
| 141 | const ( |
| 142 | signatureRSA uint8 = 1 |
| 143 | signatureECDSA uint8 = 3 |
| 144 | ) |
| 145 | |
| 146 | // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See |
| 147 | // RFC 5246, section A.4.1. |
| 148 | type signatureAndHash struct { |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 149 | signature, hash uint8 |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 150 | } |
| 151 | |
| 152 | // supportedSKXSignatureAlgorithms contains the signature and hash algorithms |
| 153 | // that the code advertises as supported in a TLS 1.2 ClientHello. |
| 154 | var supportedSKXSignatureAlgorithms = []signatureAndHash{ |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 155 | {signatureRSA, hashSHA256}, |
| 156 | {signatureECDSA, hashSHA256}, |
| 157 | {signatureRSA, hashSHA1}, |
| 158 | {signatureECDSA, hashSHA1}, |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 159 | } |
| 160 | |
| 161 | // supportedClientCertSignatureAlgorithms contains the signature and hash |
| 162 | // algorithms that the code advertises as supported in a TLS 1.2 |
| 163 | // CertificateRequest. |
| 164 | var supportedClientCertSignatureAlgorithms = []signatureAndHash{ |
David Benjamin | e098ec2 | 2014-08-27 23:13:20 -0400 | [diff] [blame] | 165 | {signatureRSA, hashSHA256}, |
| 166 | {signatureECDSA, hashSHA256}, |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 167 | } |
| 168 | |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 169 | // SRTP protection profiles (See RFC 5764, section 4.1.2) |
| 170 | const ( |
| 171 | SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001 |
| 172 | SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002 |
| 173 | ) |
| 174 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 175 | // ConnectionState records basic TLS details about the connection. |
| 176 | type ConnectionState struct { |
| 177 | Version uint16 // TLS version used by the connection (e.g. VersionTLS12) |
| 178 | HandshakeComplete bool // TLS handshake is complete |
| 179 | DidResume bool // connection resumes a previous TLS connection |
| 180 | CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) |
| 181 | NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) |
| 182 | NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 183 | NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 184 | ServerName string // server name requested by client, if any (server side only) |
| 185 | PeerCertificates []*x509.Certificate // certificate chain presented by remote peer |
| 186 | VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 187 | ChannelID *ecdsa.PublicKey // the channel ID for this connection |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 188 | SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 189 | } |
| 190 | |
| 191 | // ClientAuthType declares the policy the server will follow for |
| 192 | // TLS Client Authentication. |
| 193 | type ClientAuthType int |
| 194 | |
| 195 | const ( |
| 196 | NoClientCert ClientAuthType = iota |
| 197 | RequestClientCert |
| 198 | RequireAnyClientCert |
| 199 | VerifyClientCertIfGiven |
| 200 | RequireAndVerifyClientCert |
| 201 | ) |
| 202 | |
| 203 | // ClientSessionState contains the state needed by clients to resume TLS |
| 204 | // sessions. |
| 205 | type ClientSessionState struct { |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 206 | sessionTicket []uint8 // Encrypted ticket used for session resumption with server |
| 207 | vers uint16 // SSL/TLS version negotiated for the session |
| 208 | cipherSuite uint16 // Ciphersuite negotiated for the session |
| 209 | masterSecret []byte // MasterSecret generated by client on a full handshake |
| 210 | handshakeHash []byte // Handshake hash for Channel ID purposes. |
| 211 | serverCertificates []*x509.Certificate // Certificate chain presented by the server |
| 212 | extendedMasterSecret bool // Whether an extended master secret was used to generate the session |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 213 | } |
| 214 | |
| 215 | // ClientSessionCache is a cache of ClientSessionState objects that can be used |
| 216 | // by a client to resume a TLS session with a given server. ClientSessionCache |
| 217 | // implementations should expect to be called concurrently from different |
| 218 | // goroutines. |
| 219 | type ClientSessionCache interface { |
| 220 | // Get searches for a ClientSessionState associated with the given key. |
| 221 | // On return, ok is true if one was found. |
| 222 | Get(sessionKey string) (session *ClientSessionState, ok bool) |
| 223 | |
| 224 | // Put adds the ClientSessionState to the cache with the given key. |
| 225 | Put(sessionKey string, cs *ClientSessionState) |
| 226 | } |
| 227 | |
| 228 | // A Config structure is used to configure a TLS client or server. |
| 229 | // After one has been passed to a TLS function it must not be |
| 230 | // modified. A Config may be reused; the tls package will also not |
| 231 | // modify it. |
| 232 | type Config struct { |
| 233 | // Rand provides the source of entropy for nonces and RSA blinding. |
| 234 | // If Rand is nil, TLS uses the cryptographic random reader in package |
| 235 | // crypto/rand. |
| 236 | // The Reader must be safe for use by multiple goroutines. |
| 237 | Rand io.Reader |
| 238 | |
| 239 | // Time returns the current time as the number of seconds since the epoch. |
| 240 | // If Time is nil, TLS uses time.Now. |
| 241 | Time func() time.Time |
| 242 | |
| 243 | // Certificates contains one or more certificate chains |
| 244 | // to present to the other side of the connection. |
| 245 | // Server configurations must include at least one certificate. |
| 246 | Certificates []Certificate |
| 247 | |
| 248 | // NameToCertificate maps from a certificate name to an element of |
| 249 | // Certificates. Note that a certificate name can be of the form |
| 250 | // '*.example.com' and so doesn't have to be a domain name as such. |
| 251 | // See Config.BuildNameToCertificate |
| 252 | // The nil value causes the first element of Certificates to be used |
| 253 | // for all connections. |
| 254 | NameToCertificate map[string]*Certificate |
| 255 | |
| 256 | // RootCAs defines the set of root certificate authorities |
| 257 | // that clients use when verifying server certificates. |
| 258 | // If RootCAs is nil, TLS uses the host's root CA set. |
| 259 | RootCAs *x509.CertPool |
| 260 | |
| 261 | // NextProtos is a list of supported, application level protocols. |
| 262 | NextProtos []string |
| 263 | |
| 264 | // ServerName is used to verify the hostname on the returned |
| 265 | // certificates unless InsecureSkipVerify is given. It is also included |
| 266 | // in the client's handshake to support virtual hosting. |
| 267 | ServerName string |
| 268 | |
| 269 | // ClientAuth determines the server's policy for |
| 270 | // TLS Client Authentication. The default is NoClientCert. |
| 271 | ClientAuth ClientAuthType |
| 272 | |
| 273 | // ClientCAs defines the set of root certificate authorities |
| 274 | // that servers use if required to verify a client certificate |
| 275 | // by the policy in ClientAuth. |
| 276 | ClientCAs *x509.CertPool |
| 277 | |
David Benjamin | 7b03051 | 2014-07-08 17:30:11 -0400 | [diff] [blame] | 278 | // ClientCertificateTypes defines the set of allowed client certificate |
| 279 | // types. The default is CertTypeRSASign and CertTypeECDSASign. |
| 280 | ClientCertificateTypes []byte |
| 281 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 282 | // InsecureSkipVerify controls whether a client verifies the |
| 283 | // server's certificate chain and host name. |
| 284 | // If InsecureSkipVerify is true, TLS accepts any certificate |
| 285 | // presented by the server and any host name in that certificate. |
| 286 | // In this mode, TLS is susceptible to man-in-the-middle attacks. |
| 287 | // This should be used only for testing. |
| 288 | InsecureSkipVerify bool |
| 289 | |
| 290 | // CipherSuites is a list of supported cipher suites. If CipherSuites |
| 291 | // is nil, TLS uses a list of suites supported by the implementation. |
| 292 | CipherSuites []uint16 |
| 293 | |
| 294 | // PreferServerCipherSuites controls whether the server selects the |
| 295 | // client's most preferred ciphersuite, or the server's most preferred |
| 296 | // ciphersuite. If true then the server's preference, as expressed in |
| 297 | // the order of elements in CipherSuites, is used. |
| 298 | PreferServerCipherSuites bool |
| 299 | |
| 300 | // SessionTicketsDisabled may be set to true to disable session ticket |
| 301 | // (resumption) support. |
| 302 | SessionTicketsDisabled bool |
| 303 | |
| 304 | // SessionTicketKey is used by TLS servers to provide session |
| 305 | // resumption. See RFC 5077. If zero, it will be filled with |
| 306 | // random data before the first server handshake. |
| 307 | // |
| 308 | // If multiple servers are terminating connections for the same host |
| 309 | // they should all have the same SessionTicketKey. If the |
| 310 | // SessionTicketKey leaks, previously recorded and future TLS |
| 311 | // connections using that key are compromised. |
| 312 | SessionTicketKey [32]byte |
| 313 | |
| 314 | // SessionCache is a cache of ClientSessionState entries for TLS session |
| 315 | // resumption. |
| 316 | ClientSessionCache ClientSessionCache |
| 317 | |
| 318 | // MinVersion contains the minimum SSL/TLS version that is acceptable. |
| 319 | // If zero, then SSLv3 is taken as the minimum. |
| 320 | MinVersion uint16 |
| 321 | |
| 322 | // MaxVersion contains the maximum SSL/TLS version that is acceptable. |
| 323 | // If zero, then the maximum version supported by this package is used, |
| 324 | // which is currently TLS 1.2. |
| 325 | MaxVersion uint16 |
| 326 | |
| 327 | // CurvePreferences contains the elliptic curves that will be used in |
| 328 | // an ECDHE handshake, in preference order. If empty, the default will |
| 329 | // be used. |
| 330 | CurvePreferences []CurveID |
| 331 | |
David Benjamin | d30a990 | 2014-08-24 01:44:23 -0400 | [diff] [blame] | 332 | // ChannelID contains the ECDSA key for the client to use as |
| 333 | // its TLS Channel ID. |
| 334 | ChannelID *ecdsa.PrivateKey |
| 335 | |
| 336 | // RequestChannelID controls whether the server requests a TLS |
| 337 | // Channel ID. If negotiated, the client's public key is |
| 338 | // returned in the ConnectionState. |
| 339 | RequestChannelID bool |
| 340 | |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 341 | // PreSharedKey, if not nil, is the pre-shared key to use with |
| 342 | // the PSK cipher suites. |
| 343 | PreSharedKey []byte |
| 344 | |
| 345 | // PreSharedKeyIdentity, if not empty, is the identity to use |
| 346 | // with the PSK cipher suites. |
| 347 | PreSharedKeyIdentity string |
| 348 | |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 349 | // SRTPProtectionProfiles, if not nil, is the list of SRTP |
| 350 | // protection profiles to offer in DTLS-SRTP. |
| 351 | SRTPProtectionProfiles []uint16 |
| 352 | |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 353 | // SignatureAndHashes, if not nil, overrides the default set of |
| 354 | // supported signature and hash algorithms to advertise in |
| 355 | // CertificateRequest. |
| 356 | SignatureAndHashes []signatureAndHash |
| 357 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 358 | // Bugs specifies optional misbehaviour to be used for testing other |
| 359 | // implementations. |
| 360 | Bugs ProtocolBugs |
| 361 | |
| 362 | serverInitOnce sync.Once // guards calling (*Config).serverInit |
| 363 | } |
| 364 | |
| 365 | type BadValue int |
| 366 | |
| 367 | const ( |
| 368 | BadValueNone BadValue = iota |
| 369 | BadValueNegative |
| 370 | BadValueZero |
| 371 | BadValueLimit |
| 372 | BadValueLarge |
| 373 | NumBadValues |
| 374 | ) |
| 375 | |
| 376 | type ProtocolBugs struct { |
| 377 | // InvalidSKXSignature specifies that the signature in a |
| 378 | // ServerKeyExchange message should be invalid. |
| 379 | InvalidSKXSignature bool |
| 380 | |
| 381 | // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message |
| 382 | // to be wrong. |
| 383 | InvalidSKXCurve bool |
| 384 | |
| 385 | // BadECDSAR controls ways in which the 'r' value of an ECDSA signature |
| 386 | // can be invalid. |
| 387 | BadECDSAR BadValue |
| 388 | BadECDSAS BadValue |
Adam Langley | 80842bd | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 389 | |
| 390 | // MaxPadding causes CBC records to have the maximum possible padding. |
| 391 | MaxPadding bool |
| 392 | // PaddingFirstByteBad causes the first byte of the padding to be |
| 393 | // incorrect. |
| 394 | PaddingFirstByteBad bool |
| 395 | // PaddingFirstByteBadIf255 causes the first byte of padding to be |
| 396 | // incorrect if there's a maximum amount of padding (i.e. 255 bytes). |
| 397 | PaddingFirstByteBadIf255 bool |
Adam Langley | ac61fa3 | 2014-06-23 12:03:11 -0700 | [diff] [blame] | 398 | |
| 399 | // FailIfNotFallbackSCSV causes a server handshake to fail if the |
| 400 | // client doesn't send the fallback SCSV value. |
| 401 | FailIfNotFallbackSCSV bool |
David Benjamin | 35a7a44 | 2014-07-05 00:23:20 -0400 | [diff] [blame] | 402 | |
| 403 | // DuplicateExtension causes an extra empty extension of bogus type to |
| 404 | // be emitted in either the ClientHello or the ServerHello. |
| 405 | DuplicateExtension bool |
David Benjamin | 1c375dd | 2014-07-12 00:48:23 -0400 | [diff] [blame] | 406 | |
| 407 | // UnauthenticatedECDH causes the server to pretend ECDHE_RSA |
| 408 | // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No |
| 409 | // Certificate message is sent and no signature is added to |
| 410 | // ServerKeyExchange. |
| 411 | UnauthenticatedECDH bool |
David Benjamin | 9c651c9 | 2014-07-12 13:27:45 -0400 | [diff] [blame] | 412 | |
| 413 | // SkipServerKeyExchange causes the server to skip sending |
| 414 | // ServerKeyExchange messages. |
| 415 | SkipServerKeyExchange bool |
David Benjamin | a0e5223 | 2014-07-19 17:39:58 -0400 | [diff] [blame] | 416 | |
| 417 | // SkipChangeCipherSpec causes the implementation to skip |
| 418 | // sending the ChangeCipherSpec message (and adjusting cipher |
| 419 | // state accordingly for the Finished message). |
| 420 | SkipChangeCipherSpec bool |
David Benjamin | f3ec83d | 2014-07-21 22:42:34 -0400 | [diff] [blame] | 421 | |
| 422 | // EarlyChangeCipherSpec causes the client to send an early |
| 423 | // ChangeCipherSpec message before the ClientKeyExchange. A value of |
| 424 | // zero disables this behavior. One and two configure variants for 0.9.8 |
| 425 | // and 1.0.1 modes, respectively. |
| 426 | EarlyChangeCipherSpec int |
David Benjamin | d23f412 | 2014-07-23 15:09:48 -0400 | [diff] [blame] | 427 | |
David Benjamin | 86271ee | 2014-07-21 16:14:03 -0400 | [diff] [blame] | 428 | // FragmentAcrossChangeCipherSpec causes the implementation to fragment |
| 429 | // the Finished (or NextProto) message around the ChangeCipherSpec |
| 430 | // messages. |
| 431 | FragmentAcrossChangeCipherSpec bool |
| 432 | |
David Benjamin | d23f412 | 2014-07-23 15:09:48 -0400 | [diff] [blame] | 433 | // SkipNewSessionTicket causes the server to skip sending the |
| 434 | // NewSessionTicket message despite promising to in ServerHello. |
| 435 | SkipNewSessionTicket bool |
David Benjamin | d86c767 | 2014-08-02 04:07:12 -0400 | [diff] [blame] | 436 | |
| 437 | // SendV2ClientHello causes the client to send a V2ClientHello |
| 438 | // instead of a normal ClientHello. |
| 439 | SendV2ClientHello bool |
David Benjamin | bef270a | 2014-08-02 04:22:02 -0400 | [diff] [blame] | 440 | |
| 441 | // SendFallbackSCSV causes the client to include |
| 442 | // TLS_FALLBACK_SCSV in the ClientHello. |
| 443 | SendFallbackSCSV bool |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 444 | |
| 445 | // MaxHandshakeRecordLength, if non-zero, is the maximum size of a |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 446 | // handshake record. Handshake messages will be split into multiple |
| 447 | // records at the specified size, except that the client_version will |
| 448 | // never be fragmented. |
David Benjamin | 43ec06f | 2014-08-05 02:28:57 -0400 | [diff] [blame] | 449 | MaxHandshakeRecordLength int |
David Benjamin | a8e3e0e | 2014-08-06 22:11:10 -0400 | [diff] [blame] | 450 | |
David Benjamin | 9821454 | 2014-08-07 18:02:39 -0400 | [diff] [blame] | 451 | // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to |
| 452 | // the first 6 bytes of the ClientHello. |
| 453 | FragmentClientVersion bool |
| 454 | |
Alex Chernyakhovsky | 4cd8c43 | 2014-11-01 19:39:08 -0400 | [diff] [blame] | 455 | // FragmentAlert will cause all alerts to be fragmented across |
| 456 | // two records. |
| 457 | FragmentAlert bool |
| 458 | |
| 459 | // SendSpuriousAlert will cause an spurious, unwanted alert to be sent. |
| 460 | SendSpuriousAlert bool |
| 461 | |
David Benjamin | a8e3e0e | 2014-08-06 22:11:10 -0400 | [diff] [blame] | 462 | // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a |
| 463 | // ClientKeyExchange with the specified version rather than the |
| 464 | // client_version when performing the RSA key exchange. |
| 465 | RsaClientKeyExchangeVersion uint16 |
David Benjamin | bed9aae | 2014-08-07 19:13:38 -0400 | [diff] [blame] | 466 | |
| 467 | // RenewTicketOnResume causes the server to renew the session ticket and |
| 468 | // send a NewSessionTicket message during an abbreviated handshake. |
| 469 | RenewTicketOnResume bool |
David Benjamin | 98e882e | 2014-08-08 13:24:34 -0400 | [diff] [blame] | 470 | |
| 471 | // SendClientVersion, if non-zero, causes the client to send a different |
| 472 | // TLS version in the ClientHello than the maximum supported version. |
| 473 | SendClientVersion uint16 |
David Benjamin | 83c0bc9 | 2014-08-04 01:23:53 -0400 | [diff] [blame] | 474 | |
| 475 | // SkipHelloVerifyRequest causes a DTLS server to skip the |
| 476 | // HelloVerifyRequest message. |
| 477 | SkipHelloVerifyRequest bool |
David Benjamin | e58c4f5 | 2014-08-24 03:47:07 -0400 | [diff] [blame] | 478 | |
| 479 | // ExpectFalseStart causes the server to, on full handshakes, |
| 480 | // expect the peer to False Start; the server Finished message |
| 481 | // isn't sent until we receive an application data record |
| 482 | // from the peer. |
| 483 | ExpectFalseStart bool |
David Benjamin | 5c24a1d | 2014-08-31 00:59:27 -0400 | [diff] [blame] | 484 | |
| 485 | // SSL3RSAKeyExchange causes the client to always send an RSA |
| 486 | // ClientKeyExchange message without the two-byte length |
| 487 | // prefix, as if it were SSL3. |
| 488 | SSL3RSAKeyExchange bool |
David Benjamin | 39ebf53 | 2014-08-31 02:23:49 -0400 | [diff] [blame] | 489 | |
| 490 | // SkipCipherVersionCheck causes the server to negotiate |
| 491 | // TLS 1.2 ciphers in earlier versions of TLS. |
| 492 | SkipCipherVersionCheck bool |
David Benjamin | e78bfde | 2014-09-06 12:45:15 -0400 | [diff] [blame] | 493 | |
| 494 | // ExpectServerName, if not empty, is the hostname the client |
| 495 | // must specify in the server_name extension. |
| 496 | ExpectServerName string |
David Benjamin | fc7b086 | 2014-09-06 13:21:53 -0400 | [diff] [blame] | 497 | |
| 498 | // SwapNPNAndALPN switches the relative order between NPN and |
| 499 | // ALPN on the server. This is to test that server preference |
| 500 | // of ALPN works regardless of their relative order. |
| 501 | SwapNPNAndALPN bool |
David Benjamin | 01fe820 | 2014-09-24 15:21:44 -0400 | [diff] [blame] | 502 | |
| 503 | // AllowSessionVersionMismatch causes the server to resume sessions |
| 504 | // regardless of the version associated with the session. |
| 505 | AllowSessionVersionMismatch bool |
Adam Langley | 3831173 | 2014-10-16 19:04:35 -0700 | [diff] [blame] | 506 | |
| 507 | // CorruptTicket causes a client to corrupt a session ticket before |
| 508 | // sending it in a resume handshake. |
| 509 | CorruptTicket bool |
| 510 | |
| 511 | // OversizedSessionId causes the session id that is sent with a ticket |
| 512 | // resumption attempt to be too large (33 bytes). |
| 513 | OversizedSessionId bool |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 514 | |
| 515 | // RequireExtendedMasterSecret, if true, requires that the peer support |
| 516 | // the extended master secret option. |
| 517 | RequireExtendedMasterSecret bool |
| 518 | |
David Benjamin | ca6554b | 2014-11-08 12:31:52 -0500 | [diff] [blame] | 519 | // NoExtendedMasterSecret causes the client and server to behave as if |
Adam Langley | 7571292 | 2014-10-10 16:23:43 -0700 | [diff] [blame] | 520 | // they didn't support an extended master secret. |
| 521 | NoExtendedMasterSecret bool |
Adam Langley | 2ae77d2 | 2014-10-28 17:29:33 -0700 | [diff] [blame] | 522 | |
| 523 | // EmptyRenegotiationInfo causes the renegotiation extension to be |
| 524 | // empty in a renegotiation handshake. |
| 525 | EmptyRenegotiationInfo bool |
| 526 | |
| 527 | // BadRenegotiationInfo causes the renegotiation extension value in a |
| 528 | // renegotiation handshake to be incorrect. |
| 529 | BadRenegotiationInfo bool |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 530 | |
David Benjamin | ca6554b | 2014-11-08 12:31:52 -0500 | [diff] [blame] | 531 | // NoRenegotiationInfo causes the client to behave as if it |
| 532 | // didn't support the renegotiation info extension. |
| 533 | NoRenegotiationInfo bool |
| 534 | |
David Benjamin | 5e961c1 | 2014-11-07 01:48:35 -0500 | [diff] [blame] | 535 | // SequenceNumberIncrement, if non-zero, causes outgoing sequence |
| 536 | // numbers in DTLS to increment by that value rather by 1. This is to |
| 537 | // stress the replay bitmap window by simulating extreme packet loss and |
| 538 | // retransmit at the record layer. |
| 539 | SequenceNumberIncrement uint64 |
David Benjamin | 9114fae | 2014-11-08 11:41:14 -0500 | [diff] [blame] | 540 | |
| 541 | // RSAServerKeyExchange, if true, causes the server to send a |
| 542 | // ServerKeyExchange message in the plain RSA key exchange. |
| 543 | RSAServerKeyExchange bool |
David Benjamin | ca6c826 | 2014-11-15 19:06:08 -0500 | [diff] [blame] | 544 | |
| 545 | // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the |
| 546 | // client offers when negotiating SRTP. MKI support is still missing so |
| 547 | // the peer must still send none. |
| 548 | SRTPMasterKeyIdentifer string |
| 549 | |
| 550 | // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the |
| 551 | // server sends in the ServerHello instead of the negotiated one. |
| 552 | SendSRTPProtectionProfile uint16 |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 553 | |
| 554 | // NoSignatureAndHashes, if true, causes the client to omit the |
| 555 | // signature and hashes extension. |
| 556 | // |
| 557 | // For a server, it will cause an empty list to be sent in the |
| 558 | // CertificateRequest message. None the less, the configured set will |
| 559 | // still be enforced. |
| 560 | NoSignatureAndHashes bool |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 561 | } |
| 562 | |
| 563 | func (c *Config) serverInit() { |
| 564 | if c.SessionTicketsDisabled { |
| 565 | return |
| 566 | } |
| 567 | |
| 568 | // If the key has already been set then we have nothing to do. |
| 569 | for _, b := range c.SessionTicketKey { |
| 570 | if b != 0 { |
| 571 | return |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { |
| 576 | c.SessionTicketsDisabled = true |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | func (c *Config) rand() io.Reader { |
| 581 | r := c.Rand |
| 582 | if r == nil { |
| 583 | return rand.Reader |
| 584 | } |
| 585 | return r |
| 586 | } |
| 587 | |
| 588 | func (c *Config) time() time.Time { |
| 589 | t := c.Time |
| 590 | if t == nil { |
| 591 | t = time.Now |
| 592 | } |
| 593 | return t() |
| 594 | } |
| 595 | |
| 596 | func (c *Config) cipherSuites() []uint16 { |
| 597 | s := c.CipherSuites |
| 598 | if s == nil { |
| 599 | s = defaultCipherSuites() |
| 600 | } |
| 601 | return s |
| 602 | } |
| 603 | |
| 604 | func (c *Config) minVersion() uint16 { |
| 605 | if c == nil || c.MinVersion == 0 { |
| 606 | return minVersion |
| 607 | } |
| 608 | return c.MinVersion |
| 609 | } |
| 610 | |
| 611 | func (c *Config) maxVersion() uint16 { |
| 612 | if c == nil || c.MaxVersion == 0 { |
| 613 | return maxVersion |
| 614 | } |
| 615 | return c.MaxVersion |
| 616 | } |
| 617 | |
| 618 | var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521} |
| 619 | |
| 620 | func (c *Config) curvePreferences() []CurveID { |
| 621 | if c == nil || len(c.CurvePreferences) == 0 { |
| 622 | return defaultCurvePreferences |
| 623 | } |
| 624 | return c.CurvePreferences |
| 625 | } |
| 626 | |
| 627 | // mutualVersion returns the protocol version to use given the advertised |
| 628 | // version of the peer. |
| 629 | func (c *Config) mutualVersion(vers uint16) (uint16, bool) { |
| 630 | minVersion := c.minVersion() |
| 631 | maxVersion := c.maxVersion() |
| 632 | |
| 633 | if vers < minVersion { |
| 634 | return 0, false |
| 635 | } |
| 636 | if vers > maxVersion { |
| 637 | vers = maxVersion |
| 638 | } |
| 639 | return vers, true |
| 640 | } |
| 641 | |
| 642 | // getCertificateForName returns the best certificate for the given name, |
| 643 | // defaulting to the first element of c.Certificates if there are no good |
| 644 | // options. |
| 645 | func (c *Config) getCertificateForName(name string) *Certificate { |
| 646 | if len(c.Certificates) == 1 || c.NameToCertificate == nil { |
| 647 | // There's only one choice, so no point doing any work. |
| 648 | return &c.Certificates[0] |
| 649 | } |
| 650 | |
| 651 | name = strings.ToLower(name) |
| 652 | for len(name) > 0 && name[len(name)-1] == '.' { |
| 653 | name = name[:len(name)-1] |
| 654 | } |
| 655 | |
| 656 | if cert, ok := c.NameToCertificate[name]; ok { |
| 657 | return cert |
| 658 | } |
| 659 | |
| 660 | // try replacing labels in the name with wildcards until we get a |
| 661 | // match. |
| 662 | labels := strings.Split(name, ".") |
| 663 | for i := range labels { |
| 664 | labels[i] = "*" |
| 665 | candidate := strings.Join(labels, ".") |
| 666 | if cert, ok := c.NameToCertificate[candidate]; ok { |
| 667 | return cert |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // If nothing matches, return the first certificate. |
| 672 | return &c.Certificates[0] |
| 673 | } |
| 674 | |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 675 | func (c *Config) signatureAndHashesForServer() []signatureAndHash { |
| 676 | if c != nil && c.SignatureAndHashes != nil { |
| 677 | return c.SignatureAndHashes |
| 678 | } |
| 679 | return supportedClientCertSignatureAlgorithms |
| 680 | } |
| 681 | |
| 682 | func (c *Config) signatureAndHashesForClient() []signatureAndHash { |
| 683 | if c != nil && c.SignatureAndHashes != nil { |
| 684 | return c.SignatureAndHashes |
| 685 | } |
| 686 | return supportedSKXSignatureAlgorithms |
| 687 | } |
| 688 | |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 689 | // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate |
| 690 | // from the CommonName and SubjectAlternateName fields of each of the leaf |
| 691 | // certificates. |
| 692 | func (c *Config) BuildNameToCertificate() { |
| 693 | c.NameToCertificate = make(map[string]*Certificate) |
| 694 | for i := range c.Certificates { |
| 695 | cert := &c.Certificates[i] |
| 696 | x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) |
| 697 | if err != nil { |
| 698 | continue |
| 699 | } |
| 700 | if len(x509Cert.Subject.CommonName) > 0 { |
| 701 | c.NameToCertificate[x509Cert.Subject.CommonName] = cert |
| 702 | } |
| 703 | for _, san := range x509Cert.DNSNames { |
| 704 | c.NameToCertificate[san] = cert |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | // A Certificate is a chain of one or more certificates, leaf first. |
| 710 | type Certificate struct { |
| 711 | Certificate [][]byte |
| 712 | PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey |
| 713 | // OCSPStaple contains an optional OCSP response which will be served |
| 714 | // to clients that request it. |
| 715 | OCSPStaple []byte |
| 716 | // Leaf is the parsed form of the leaf certificate, which may be |
| 717 | // initialized using x509.ParseCertificate to reduce per-handshake |
| 718 | // processing for TLS clients doing client authentication. If nil, the |
| 719 | // leaf certificate will be parsed as needed. |
| 720 | Leaf *x509.Certificate |
| 721 | } |
| 722 | |
| 723 | // A TLS record. |
| 724 | type record struct { |
| 725 | contentType recordType |
| 726 | major, minor uint8 |
| 727 | payload []byte |
| 728 | } |
| 729 | |
| 730 | type handshakeMessage interface { |
| 731 | marshal() []byte |
| 732 | unmarshal([]byte) bool |
| 733 | } |
| 734 | |
| 735 | // lruSessionCache is a ClientSessionCache implementation that uses an LRU |
| 736 | // caching strategy. |
| 737 | type lruSessionCache struct { |
| 738 | sync.Mutex |
| 739 | |
| 740 | m map[string]*list.Element |
| 741 | q *list.List |
| 742 | capacity int |
| 743 | } |
| 744 | |
| 745 | type lruSessionCacheEntry struct { |
| 746 | sessionKey string |
| 747 | state *ClientSessionState |
| 748 | } |
| 749 | |
| 750 | // NewLRUClientSessionCache returns a ClientSessionCache with the given |
| 751 | // capacity that uses an LRU strategy. If capacity is < 1, a default capacity |
| 752 | // is used instead. |
| 753 | func NewLRUClientSessionCache(capacity int) ClientSessionCache { |
| 754 | const defaultSessionCacheCapacity = 64 |
| 755 | |
| 756 | if capacity < 1 { |
| 757 | capacity = defaultSessionCacheCapacity |
| 758 | } |
| 759 | return &lruSessionCache{ |
| 760 | m: make(map[string]*list.Element), |
| 761 | q: list.New(), |
| 762 | capacity: capacity, |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | // Put adds the provided (sessionKey, cs) pair to the cache. |
| 767 | func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { |
| 768 | c.Lock() |
| 769 | defer c.Unlock() |
| 770 | |
| 771 | if elem, ok := c.m[sessionKey]; ok { |
| 772 | entry := elem.Value.(*lruSessionCacheEntry) |
| 773 | entry.state = cs |
| 774 | c.q.MoveToFront(elem) |
| 775 | return |
| 776 | } |
| 777 | |
| 778 | if c.q.Len() < c.capacity { |
| 779 | entry := &lruSessionCacheEntry{sessionKey, cs} |
| 780 | c.m[sessionKey] = c.q.PushFront(entry) |
| 781 | return |
| 782 | } |
| 783 | |
| 784 | elem := c.q.Back() |
| 785 | entry := elem.Value.(*lruSessionCacheEntry) |
| 786 | delete(c.m, entry.sessionKey) |
| 787 | entry.sessionKey = sessionKey |
| 788 | entry.state = cs |
| 789 | c.q.MoveToFront(elem) |
| 790 | c.m[sessionKey] = elem |
| 791 | } |
| 792 | |
| 793 | // Get returns the ClientSessionState value associated with a given key. It |
| 794 | // returns (nil, false) if no value is found. |
| 795 | func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { |
| 796 | c.Lock() |
| 797 | defer c.Unlock() |
| 798 | |
| 799 | if elem, ok := c.m[sessionKey]; ok { |
| 800 | c.q.MoveToFront(elem) |
| 801 | return elem.Value.(*lruSessionCacheEntry).state, true |
| 802 | } |
| 803 | return nil, false |
| 804 | } |
| 805 | |
| 806 | // TODO(jsing): Make these available to both crypto/x509 and crypto/tls. |
| 807 | type dsaSignature struct { |
| 808 | R, S *big.Int |
| 809 | } |
| 810 | |
| 811 | type ecdsaSignature dsaSignature |
| 812 | |
| 813 | var emptyConfig Config |
| 814 | |
| 815 | func defaultConfig() *Config { |
| 816 | return &emptyConfig |
| 817 | } |
| 818 | |
| 819 | var ( |
| 820 | once sync.Once |
| 821 | varDefaultCipherSuites []uint16 |
| 822 | ) |
| 823 | |
| 824 | func defaultCipherSuites() []uint16 { |
| 825 | once.Do(initDefaultCipherSuites) |
| 826 | return varDefaultCipherSuites |
| 827 | } |
| 828 | |
| 829 | func initDefaultCipherSuites() { |
David Benjamin | 48cae08 | 2014-10-27 01:06:24 -0400 | [diff] [blame] | 830 | for _, suite := range cipherSuites { |
| 831 | if suite.flags&suitePSK == 0 { |
| 832 | varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) |
| 833 | } |
Adam Langley | 95c29f3 | 2014-06-20 12:00:00 -0700 | [diff] [blame] | 834 | } |
| 835 | } |
| 836 | |
| 837 | func unexpectedMessageError(wanted, got interface{}) error { |
| 838 | return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) |
| 839 | } |
David Benjamin | 000800a | 2014-11-14 01:43:59 -0500 | [diff] [blame^] | 840 | |
| 841 | func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool { |
| 842 | for _, s := range sigHashes { |
| 843 | if s == sigHash { |
| 844 | return true |
| 845 | } |
| 846 | } |
| 847 | return false |
| 848 | } |