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