Brent Austin | ba3052e | 2015-04-21 16:08:23 -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 tls |
| 6 | |
| 7 | import ( |
| 8 | "container/list" |
| 9 | "crypto" |
| 10 | "crypto/rand" |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 11 | "crypto/sha512" |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 12 | "crypto/x509" |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 13 | "errors" |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 14 | "fmt" |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 15 | "internal/cpu" |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 16 | "io" |
| 17 | "math/big" |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 18 | "net" |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 19 | "os" |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 20 | "strings" |
| 21 | "sync" |
| 22 | "time" |
| 23 | ) |
| 24 | |
| 25 | const ( |
| 26 | VersionSSL30 = 0x0300 |
| 27 | VersionTLS10 = 0x0301 |
| 28 | VersionTLS11 = 0x0302 |
| 29 | VersionTLS12 = 0x0303 |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 30 | VersionTLS13 = 0x0304 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 31 | ) |
| 32 | |
| 33 | const ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 34 | maxPlaintext = 16384 // maximum plaintext payload length |
| 35 | maxCiphertext = 16384 + 2048 // maximum ciphertext payload length |
| 36 | maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3 |
| 37 | recordHeaderLen = 5 // record header length |
| 38 | maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) |
| 39 | maxUselessRecords = 16 // maximum number of consecutive non-advancing records |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 40 | ) |
| 41 | |
| 42 | // TLS record types. |
| 43 | type recordType uint8 |
| 44 | |
| 45 | const ( |
| 46 | recordTypeChangeCipherSpec recordType = 20 |
| 47 | recordTypeAlert recordType = 21 |
| 48 | recordTypeHandshake recordType = 22 |
| 49 | recordTypeApplicationData recordType = 23 |
| 50 | ) |
| 51 | |
| 52 | // TLS handshake message types. |
| 53 | const ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 54 | typeHelloRequest uint8 = 0 |
| 55 | typeClientHello uint8 = 1 |
| 56 | typeServerHello uint8 = 2 |
| 57 | typeNewSessionTicket uint8 = 4 |
| 58 | typeEndOfEarlyData uint8 = 5 |
| 59 | typeEncryptedExtensions uint8 = 8 |
| 60 | typeCertificate uint8 = 11 |
| 61 | typeServerKeyExchange uint8 = 12 |
| 62 | typeCertificateRequest uint8 = 13 |
| 63 | typeServerHelloDone uint8 = 14 |
| 64 | typeCertificateVerify uint8 = 15 |
| 65 | typeClientKeyExchange uint8 = 16 |
| 66 | typeFinished uint8 = 20 |
| 67 | typeCertificateStatus uint8 = 22 |
| 68 | typeKeyUpdate uint8 = 24 |
| 69 | typeNextProtocol uint8 = 67 // Not IANA assigned |
| 70 | typeMessageHash uint8 = 254 // synthetic message |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 71 | ) |
| 72 | |
| 73 | // TLS compression types. |
| 74 | const ( |
| 75 | compressionNone uint8 = 0 |
| 76 | ) |
| 77 | |
| 78 | // TLS extension numbers |
| 79 | const ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 80 | extensionServerName uint16 = 0 |
| 81 | extensionStatusRequest uint16 = 5 |
| 82 | extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7 |
| 83 | extensionSupportedPoints uint16 = 11 |
| 84 | extensionSignatureAlgorithms uint16 = 13 |
| 85 | extensionALPN uint16 = 16 |
| 86 | extensionSCT uint16 = 18 |
| 87 | extensionSessionTicket uint16 = 35 |
| 88 | extensionPreSharedKey uint16 = 41 |
| 89 | extensionEarlyData uint16 = 42 |
| 90 | extensionSupportedVersions uint16 = 43 |
| 91 | extensionCookie uint16 = 44 |
| 92 | extensionPSKModes uint16 = 45 |
| 93 | extensionCertificateAuthorities uint16 = 47 |
| 94 | extensionSignatureAlgorithmsCert uint16 = 50 |
| 95 | extensionKeyShare uint16 = 51 |
| 96 | extensionNextProtoNeg uint16 = 13172 // not IANA assigned |
| 97 | extensionRenegotiationInfo uint16 = 0xff01 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 98 | ) |
| 99 | |
| 100 | // TLS signaling cipher suite values |
| 101 | const ( |
| 102 | scsvRenegotiation uint16 = 0x00ff |
| 103 | ) |
| 104 | |
| 105 | // CurveID is the type of a TLS identifier for an elliptic curve. See |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 106 | // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. |
| 107 | // |
| 108 | // In TLS 1.3, this type is called NamedGroup, but at this time this library |
| 109 | // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 110 | type CurveID uint16 |
| 111 | |
| 112 | const ( |
| 113 | CurveP256 CurveID = 23 |
| 114 | CurveP384 CurveID = 24 |
| 115 | CurveP521 CurveID = 25 |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 116 | X25519 CurveID = 29 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 117 | ) |
| 118 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 119 | // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8. |
| 120 | type keyShare struct { |
| 121 | group CurveID |
| 122 | data []byte |
| 123 | } |
| 124 | |
| 125 | // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9. |
| 126 | const ( |
| 127 | pskModePlain uint8 = 0 |
| 128 | pskModeDHE uint8 = 1 |
| 129 | ) |
| 130 | |
| 131 | // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved |
| 132 | // session. See RFC 8446, Section 4.2.11. |
| 133 | type pskIdentity struct { |
| 134 | label []byte |
| 135 | obfuscatedTicketAge uint32 |
| 136 | } |
| 137 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 138 | // TLS Elliptic Curve Point Formats |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 139 | // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 140 | const ( |
| 141 | pointFormatUncompressed uint8 = 0 |
| 142 | ) |
| 143 | |
| 144 | // TLS CertificateStatusType (RFC 3546) |
| 145 | const ( |
| 146 | statusTypeOCSP uint8 = 1 |
| 147 | ) |
| 148 | |
| 149 | // Certificate types (for certificateRequestMsg) |
| 150 | const ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 151 | certTypeRSASign = 1 |
| 152 | certTypeECDSASign = 64 // RFC 4492, Section 5.5 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 153 | ) |
| 154 | |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 155 | // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 156 | // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 157 | const ( |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 158 | signaturePKCS1v15 uint8 = iota + 16 |
| 159 | signatureECDSA |
| 160 | signatureRSAPSS |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 161 | ) |
| 162 | |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 163 | // supportedSignatureAlgorithms contains the signature and hash algorithms that |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 164 | // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+ |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 165 | // CertificateRequest. The two fields are merged to match with TLS 1.3. |
| 166 | // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc. |
| 167 | var supportedSignatureAlgorithms = []SignatureScheme{ |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 168 | PSSWithSHA256, |
| 169 | PSSWithSHA384, |
| 170 | PSSWithSHA512, |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 171 | PKCS1WithSHA256, |
| 172 | ECDSAWithP256AndSHA256, |
| 173 | PKCS1WithSHA384, |
| 174 | ECDSAWithP384AndSHA384, |
| 175 | PKCS1WithSHA512, |
| 176 | ECDSAWithP521AndSHA512, |
| 177 | PKCS1WithSHA1, |
| 178 | ECDSAWithSHA1, |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 179 | } |
| 180 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 181 | // RSA-PSS is disabled in TLS 1.2 for Go 1.12. See Issue 30055. |
| 182 | var supportedSignatureAlgorithmsTLS12 = supportedSignatureAlgorithms[3:] |
| 183 | |
| 184 | // helloRetryRequestRandom is set as the Random value of a ServerHello |
| 185 | // to signal that the message is actually a HelloRetryRequest. |
| 186 | var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3. |
| 187 | 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, |
| 188 | 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, |
| 189 | 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, |
| 190 | 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C, |
| 191 | } |
| 192 | |
| 193 | const ( |
| 194 | // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server |
| 195 | // random as a downgrade protection if the server would be capable of |
| 196 | // negotiating a higher version. See RFC 8446, Section 4.1.3. |
| 197 | downgradeCanaryTLS12 = "DOWNGRD\x01" |
| 198 | downgradeCanaryTLS11 = "DOWNGRD\x00" |
| 199 | ) |
| 200 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 201 | // ConnectionState records basic TLS details about the connection. |
| 202 | type ConnectionState struct { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 203 | Version uint16 // TLS version used by the connection (e.g. VersionTLS12) |
| 204 | HandshakeComplete bool // TLS handshake is complete |
| 205 | DidResume bool // connection resumes a previous TLS connection |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 206 | CipherSuite uint16 // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...) |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 207 | NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos) |
| 208 | NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only) |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 209 | ServerName string // server name requested by client, if any (server side only) |
| 210 | PeerCertificates []*x509.Certificate // certificate chain presented by remote peer |
| 211 | VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 212 | SignedCertificateTimestamps [][]byte // SCTs from the peer, if any |
| 213 | OCSPResponse []byte // stapled OCSP response from peer, if any |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 214 | |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 215 | // ekm is a closure exposed via ExportKeyingMaterial. |
| 216 | ekm func(label string, context []byte, length int) ([]byte, error) |
| 217 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 218 | // TLSUnique contains the "tls-unique" channel binding value (see RFC |
| 219 | // 5929, section 3). For resumed sessions this value will be nil |
| 220 | // because resumption does not include enough context (see |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 221 | // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will |
| 222 | // change in future versions of Go once the TLS master-secret fix has |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 223 | // been standardized and implemented. It is not defined in TLS 1.3. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 224 | TLSUnique []byte |
| 225 | } |
| 226 | |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 227 | // ExportKeyingMaterial returns length bytes of exported key material in a new |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 228 | // slice as defined in RFC 5705. If context is nil, it is not used as part of |
| 229 | // the seed. If the connection was set to allow renegotiation via |
| 230 | // Config.Renegotiation, this function will return an error. |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 231 | func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) { |
| 232 | return cs.ekm(label, context, length) |
| 233 | } |
| 234 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 235 | // ClientAuthType declares the policy the server will follow for |
| 236 | // TLS Client Authentication. |
| 237 | type ClientAuthType int |
| 238 | |
| 239 | const ( |
| 240 | NoClientCert ClientAuthType = iota |
| 241 | RequestClientCert |
| 242 | RequireAnyClientCert |
| 243 | VerifyClientCertIfGiven |
| 244 | RequireAndVerifyClientCert |
| 245 | ) |
| 246 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 247 | // requiresClientCert reports whether the ClientAuthType requires a client |
| 248 | // certificate to be provided. |
| 249 | func requiresClientCert(c ClientAuthType) bool { |
| 250 | switch c { |
| 251 | case RequireAnyClientCert, RequireAndVerifyClientCert: |
| 252 | return true |
| 253 | default: |
| 254 | return false |
| 255 | } |
| 256 | } |
| 257 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 258 | // ClientSessionState contains the state needed by clients to resume TLS |
| 259 | // sessions. |
| 260 | type ClientSessionState struct { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 261 | sessionTicket []uint8 // Encrypted ticket used for session resumption with server |
| 262 | vers uint16 // SSL/TLS version negotiated for the session |
| 263 | cipherSuite uint16 // Ciphersuite negotiated for the session |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 264 | masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 265 | serverCertificates []*x509.Certificate // Certificate chain presented by the server |
| 266 | verifiedChains [][]*x509.Certificate // Certificate chains we built for verification |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 267 | receivedAt time.Time // When the session ticket was received from the server |
| 268 | |
| 269 | // TLS 1.3 fields. |
| 270 | nonce []byte // Ticket nonce sent by the server, to derive PSK |
| 271 | useBy time.Time // Expiration of the ticket lifetime as set by the server |
| 272 | ageAdd uint32 // Random obfuscation factor for sending the ticket age |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 273 | } |
| 274 | |
| 275 | // ClientSessionCache is a cache of ClientSessionState objects that can be used |
| 276 | // by a client to resume a TLS session with a given server. ClientSessionCache |
| 277 | // implementations should expect to be called concurrently from different |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 278 | // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not |
| 279 | // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which |
| 280 | // are supported via this interface. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 281 | type ClientSessionCache interface { |
| 282 | // Get searches for a ClientSessionState associated with the given key. |
| 283 | // On return, ok is true if one was found. |
| 284 | Get(sessionKey string) (session *ClientSessionState, ok bool) |
| 285 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 286 | // Put adds the ClientSessionState to the cache with the given key. It might |
| 287 | // get called multiple times in a connection if a TLS 1.3 server provides |
| 288 | // more than one session ticket. If called with a nil *ClientSessionState, |
| 289 | // it should remove the cache entry. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 290 | Put(sessionKey string, cs *ClientSessionState) |
| 291 | } |
| 292 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 293 | // SignatureScheme identifies a signature algorithm supported by TLS. See |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 294 | // RFC 8446, Section 4.2.3. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 295 | type SignatureScheme uint16 |
| 296 | |
| 297 | const ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 298 | // RSASSA-PKCS1-v1_5 algorithms. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 299 | PKCS1WithSHA256 SignatureScheme = 0x0401 |
| 300 | PKCS1WithSHA384 SignatureScheme = 0x0501 |
| 301 | PKCS1WithSHA512 SignatureScheme = 0x0601 |
| 302 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 303 | // RSASSA-PSS algorithms with public key OID rsaEncryption. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 304 | PSSWithSHA256 SignatureScheme = 0x0804 |
| 305 | PSSWithSHA384 SignatureScheme = 0x0805 |
| 306 | PSSWithSHA512 SignatureScheme = 0x0806 |
| 307 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 308 | // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 309 | ECDSAWithP256AndSHA256 SignatureScheme = 0x0403 |
| 310 | ECDSAWithP384AndSHA384 SignatureScheme = 0x0503 |
| 311 | ECDSAWithP521AndSHA512 SignatureScheme = 0x0603 |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 312 | |
| 313 | // Legacy signature and hash algorithms for TLS 1.2. |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 314 | PKCS1WithSHA1 SignatureScheme = 0x0201 |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 315 | ECDSAWithSHA1 SignatureScheme = 0x0203 |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 316 | ) |
| 317 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 318 | // ClientHelloInfo contains information from a ClientHello message in order to |
| 319 | // guide certificate selection in the GetCertificate callback. |
| 320 | type ClientHelloInfo struct { |
| 321 | // CipherSuites lists the CipherSuites supported by the client (e.g. |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 322 | // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 323 | CipherSuites []uint16 |
| 324 | |
| 325 | // ServerName indicates the name of the server requested by the client |
| 326 | // in order to support virtual hosting. ServerName is only set if the |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 327 | // client is using SNI (see RFC 4366, Section 3.1). |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 328 | ServerName string |
| 329 | |
| 330 | // SupportedCurves lists the elliptic curves supported by the client. |
| 331 | // SupportedCurves is set only if the Supported Elliptic Curves |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 332 | // Extension is being used (see RFC 4492, Section 5.1.1). |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 333 | SupportedCurves []CurveID |
| 334 | |
| 335 | // SupportedPoints lists the point formats supported by the client. |
| 336 | // SupportedPoints is set only if the Supported Point Formats Extension |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 337 | // is being used (see RFC 4492, Section 5.1.2). |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 338 | SupportedPoints []uint8 |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 339 | |
| 340 | // SignatureSchemes lists the signature and hash schemes that the client |
| 341 | // is willing to verify. SignatureSchemes is set only if the Signature |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 342 | // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 343 | SignatureSchemes []SignatureScheme |
| 344 | |
| 345 | // SupportedProtos lists the application protocols supported by the client. |
| 346 | // SupportedProtos is set only if the Application-Layer Protocol |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 347 | // Negotiation Extension is being used (see RFC 7301, Section 3.1). |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 348 | // |
| 349 | // Servers can select a protocol by setting Config.NextProtos in a |
| 350 | // GetConfigForClient return value. |
| 351 | SupportedProtos []string |
| 352 | |
| 353 | // SupportedVersions lists the TLS versions supported by the client. |
| 354 | // For TLS versions less than 1.3, this is extrapolated from the max |
| 355 | // version advertised by the client, so values other than the greatest |
| 356 | // might be rejected if used. |
| 357 | SupportedVersions []uint16 |
| 358 | |
| 359 | // Conn is the underlying net.Conn for the connection. Do not read |
| 360 | // from, or write to, this connection; that will cause the TLS |
| 361 | // connection to fail. |
| 362 | Conn net.Conn |
| 363 | } |
| 364 | |
| 365 | // CertificateRequestInfo contains information from a server's |
| 366 | // CertificateRequest message, which is used to demand a certificate and proof |
| 367 | // of control from a client. |
| 368 | type CertificateRequestInfo struct { |
| 369 | // AcceptableCAs contains zero or more, DER-encoded, X.501 |
| 370 | // Distinguished Names. These are the names of root or intermediate CAs |
| 371 | // that the server wishes the returned certificate to be signed by. An |
| 372 | // empty slice indicates that the server has no preference. |
| 373 | AcceptableCAs [][]byte |
| 374 | |
| 375 | // SignatureSchemes lists the signature schemes that the server is |
| 376 | // willing to verify. |
| 377 | SignatureSchemes []SignatureScheme |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 378 | } |
| 379 | |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 380 | // RenegotiationSupport enumerates the different levels of support for TLS |
| 381 | // renegotiation. TLS renegotiation is the act of performing subsequent |
| 382 | // handshakes on a connection after the first. This significantly complicates |
| 383 | // the state machine and has been the source of numerous, subtle security |
| 384 | // issues. Initiating a renegotiation is not supported, but support for |
| 385 | // accepting renegotiation requests may be enabled. |
| 386 | // |
| 387 | // Even when enabled, the server may not change its identity between handshakes |
| 388 | // (i.e. the leaf certificate must be the same). Additionally, concurrent |
| 389 | // handshake and application data flow is not permitted so renegotiation can |
| 390 | // only be used with protocols that synchronise with the renegotiation, such as |
| 391 | // HTTPS. |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 392 | // |
| 393 | // Renegotiation is not defined in TLS 1.3. |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 394 | type RenegotiationSupport int |
| 395 | |
| 396 | const ( |
| 397 | // RenegotiateNever disables renegotiation. |
| 398 | RenegotiateNever RenegotiationSupport = iota |
| 399 | |
| 400 | // RenegotiateOnceAsClient allows a remote server to request |
| 401 | // renegotiation once per connection. |
| 402 | RenegotiateOnceAsClient |
| 403 | |
| 404 | // RenegotiateFreelyAsClient allows a remote server to repeatedly |
| 405 | // request renegotiation. |
| 406 | RenegotiateFreelyAsClient |
| 407 | ) |
| 408 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 409 | // A Config structure is used to configure a TLS client or server. |
| 410 | // After one has been passed to a TLS function it must not be |
| 411 | // modified. A Config may be reused; the tls package will also not |
| 412 | // modify it. |
| 413 | type Config struct { |
| 414 | // Rand provides the source of entropy for nonces and RSA blinding. |
| 415 | // If Rand is nil, TLS uses the cryptographic random reader in package |
| 416 | // crypto/rand. |
| 417 | // The Reader must be safe for use by multiple goroutines. |
| 418 | Rand io.Reader |
| 419 | |
| 420 | // Time returns the current time as the number of seconds since the epoch. |
| 421 | // If Time is nil, TLS uses time.Now. |
| 422 | Time func() time.Time |
| 423 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 424 | // Certificates contains one or more certificate chains to present to |
| 425 | // the other side of the connection. Server configurations must include |
| 426 | // at least one certificate or else set GetCertificate. Clients doing |
| 427 | // client-authentication may set either Certificates or |
| 428 | // GetClientCertificate. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 429 | Certificates []Certificate |
| 430 | |
| 431 | // NameToCertificate maps from a certificate name to an element of |
| 432 | // Certificates. Note that a certificate name can be of the form |
| 433 | // '*.example.com' and so doesn't have to be a domain name as such. |
| 434 | // See Config.BuildNameToCertificate |
| 435 | // The nil value causes the first element of Certificates to be used |
| 436 | // for all connections. |
| 437 | NameToCertificate map[string]*Certificate |
| 438 | |
| 439 | // GetCertificate returns a Certificate based on the given |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 440 | // ClientHelloInfo. It will only be called if the client supplies SNI |
| 441 | // information or if Certificates is empty. |
| 442 | // |
| 443 | // If GetCertificate is nil or returns nil, then the certificate is |
| 444 | // retrieved from NameToCertificate. If NameToCertificate is nil, the |
| 445 | // first element of Certificates will be used. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 446 | GetCertificate func(*ClientHelloInfo) (*Certificate, error) |
| 447 | |
| 448 | // GetClientCertificate, if not nil, is called when a server requests a |
| 449 | // certificate from a client. If set, the contents of Certificates will |
| 450 | // be ignored. |
| 451 | // |
| 452 | // If GetClientCertificate returns an error, the handshake will be |
| 453 | // aborted and that error will be returned. Otherwise |
| 454 | // GetClientCertificate must return a non-nil Certificate. If |
| 455 | // Certificate.Certificate is empty then no certificate will be sent to |
| 456 | // the server. If this is unacceptable to the server then it may abort |
| 457 | // the handshake. |
| 458 | // |
| 459 | // GetClientCertificate may be called multiple times for the same |
| 460 | // connection if renegotiation occurs or if TLS 1.3 is in use. |
| 461 | GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) |
| 462 | |
| 463 | // GetConfigForClient, if not nil, is called after a ClientHello is |
| 464 | // received from a client. It may return a non-nil Config in order to |
| 465 | // change the Config that will be used to handle this connection. If |
| 466 | // the returned Config is nil, the original Config will be used. The |
| 467 | // Config returned by this callback may not be subsequently modified. |
| 468 | // |
| 469 | // If GetConfigForClient is nil, the Config passed to Server() will be |
| 470 | // used for all connections. |
| 471 | // |
| 472 | // Uniquely for the fields in the returned Config, session ticket keys |
| 473 | // will be duplicated from the original Config if not set. |
| 474 | // Specifically, if SetSessionTicketKeys was called on the original |
| 475 | // config but not on the returned config then the ticket keys from the |
| 476 | // original config will be copied into the new config before use. |
| 477 | // Otherwise, if SessionTicketKey was set in the original config but |
| 478 | // not in the returned config then it will be copied into the returned |
| 479 | // config before use. If neither of those cases applies then the key |
| 480 | // material from the returned config will be used for session tickets. |
| 481 | GetConfigForClient func(*ClientHelloInfo) (*Config, error) |
| 482 | |
| 483 | // VerifyPeerCertificate, if not nil, is called after normal |
| 484 | // certificate verification by either a TLS client or server. It |
| 485 | // receives the raw ASN.1 certificates provided by the peer and also |
| 486 | // any verified chains that normal processing found. If it returns a |
| 487 | // non-nil error, the handshake is aborted and that error results. |
| 488 | // |
| 489 | // If normal verification fails then the handshake will abort before |
| 490 | // considering this callback. If normal verification is disabled by |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 491 | // setting InsecureSkipVerify, or (for a server) when ClientAuth is |
| 492 | // RequestClientCert or RequireAnyClientCert, then this callback will |
| 493 | // be considered but the verifiedChains argument will always be nil. |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 494 | VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 495 | |
| 496 | // RootCAs defines the set of root certificate authorities |
| 497 | // that clients use when verifying server certificates. |
| 498 | // If RootCAs is nil, TLS uses the host's root CA set. |
| 499 | RootCAs *x509.CertPool |
| 500 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 501 | // NextProtos is a list of supported application level protocols, in |
| 502 | // order of preference. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 503 | NextProtos []string |
| 504 | |
| 505 | // ServerName is used to verify the hostname on the returned |
| 506 | // certificates unless InsecureSkipVerify is given. It is also included |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 507 | // in the client's handshake to support virtual hosting unless it is |
| 508 | // an IP address. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 509 | ServerName string |
| 510 | |
| 511 | // ClientAuth determines the server's policy for |
| 512 | // TLS Client Authentication. The default is NoClientCert. |
| 513 | ClientAuth ClientAuthType |
| 514 | |
| 515 | // ClientCAs defines the set of root certificate authorities |
| 516 | // that servers use if required to verify a client certificate |
| 517 | // by the policy in ClientAuth. |
| 518 | ClientCAs *x509.CertPool |
| 519 | |
| 520 | // InsecureSkipVerify controls whether a client verifies the |
| 521 | // server's certificate chain and host name. |
| 522 | // If InsecureSkipVerify is true, TLS accepts any certificate |
| 523 | // presented by the server and any host name in that certificate. |
| 524 | // In this mode, TLS is susceptible to man-in-the-middle attacks. |
| 525 | // This should be used only for testing. |
| 526 | InsecureSkipVerify bool |
| 527 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 528 | // CipherSuites is a list of supported cipher suites for TLS versions up to |
| 529 | // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites |
| 530 | // is used, with a preference order based on hardware performance. The |
| 531 | // default cipher suites might change over Go versions. Note that TLS 1.3 |
| 532 | // ciphersuites are not configurable. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 533 | CipherSuites []uint16 |
| 534 | |
| 535 | // PreferServerCipherSuites controls whether the server selects the |
| 536 | // client's most preferred ciphersuite, or the server's most preferred |
| 537 | // ciphersuite. If true then the server's preference, as expressed in |
| 538 | // the order of elements in CipherSuites, is used. |
| 539 | PreferServerCipherSuites bool |
| 540 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 541 | // SessionTicketsDisabled may be set to true to disable session ticket and |
| 542 | // PSK (resumption) support. Note that on clients, session ticket support is |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 543 | // also disabled if ClientSessionCache is nil. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 544 | SessionTicketsDisabled bool |
| 545 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 546 | // SessionTicketKey is used by TLS servers to provide session resumption. |
| 547 | // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled |
| 548 | // with random data before the first server handshake. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 549 | // |
| 550 | // If multiple servers are terminating connections for the same host |
| 551 | // they should all have the same SessionTicketKey. If the |
| 552 | // SessionTicketKey leaks, previously recorded and future TLS |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 553 | // connections using that key might be compromised. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 554 | SessionTicketKey [32]byte |
| 555 | |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 556 | // ClientSessionCache is a cache of ClientSessionState entries for TLS |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 557 | // session resumption. It is only used by clients. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 558 | ClientSessionCache ClientSessionCache |
| 559 | |
| 560 | // MinVersion contains the minimum SSL/TLS version that is acceptable. |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 561 | // If zero, then TLS 1.0 is taken as the minimum. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 562 | MinVersion uint16 |
| 563 | |
| 564 | // MaxVersion contains the maximum SSL/TLS version that is acceptable. |
| 565 | // If zero, then the maximum version supported by this package is used, |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 566 | // which is currently TLS 1.3. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 567 | MaxVersion uint16 |
| 568 | |
| 569 | // CurvePreferences contains the elliptic curves that will be used in |
| 570 | // an ECDHE handshake, in preference order. If empty, the default will |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 571 | // be used. The client will use the first preference as the type for |
| 572 | // its key share in TLS 1.3. This may change in the future. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 573 | CurvePreferences []CurveID |
| 574 | |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 575 | // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. |
| 576 | // When true, the largest possible TLS record size is always used. When |
| 577 | // false, the size of TLS records may be adjusted in an attempt to |
| 578 | // improve latency. |
| 579 | DynamicRecordSizingDisabled bool |
| 580 | |
| 581 | // Renegotiation controls what types of renegotiation are supported. |
| 582 | // The default, none, is correct for the vast majority of applications. |
| 583 | Renegotiation RenegotiationSupport |
| 584 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 585 | // KeyLogWriter optionally specifies a destination for TLS master secrets |
| 586 | // in NSS key log format that can be used to allow external programs |
| 587 | // such as Wireshark to decrypt TLS connections. |
| 588 | // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. |
| 589 | // Use of KeyLogWriter compromises security and should only be |
| 590 | // used for debugging. |
| 591 | KeyLogWriter io.Writer |
| 592 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 593 | serverInitOnce sync.Once // guards calling (*Config).serverInit |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 594 | |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 595 | // mutex protects sessionTicketKeys. |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 596 | mutex sync.RWMutex |
| 597 | // sessionTicketKeys contains zero or more ticket keys. If the length |
| 598 | // is zero, SessionTicketsDisabled must be true. The first key is used |
| 599 | // for new tickets and any subsequent keys can be used to decrypt old |
| 600 | // tickets. |
| 601 | sessionTicketKeys []ticketKey |
| 602 | } |
| 603 | |
| 604 | // ticketKeyNameLen is the number of bytes of identifier that is prepended to |
| 605 | // an encrypted session ticket in order to identify the key used to encrypt it. |
| 606 | const ticketKeyNameLen = 16 |
| 607 | |
| 608 | // ticketKey is the internal representation of a session ticket key. |
| 609 | type ticketKey struct { |
| 610 | // keyName is an opaque byte string that serves to identify the session |
| 611 | // ticket key. It's exposed as plaintext in every session ticket. |
| 612 | keyName [ticketKeyNameLen]byte |
| 613 | aesKey [16]byte |
| 614 | hmacKey [16]byte |
| 615 | } |
| 616 | |
| 617 | // ticketKeyFromBytes converts from the external representation of a session |
| 618 | // ticket key to a ticketKey. Externally, session ticket keys are 32 random |
| 619 | // bytes and this function expands that into sufficient name and key material. |
| 620 | func ticketKeyFromBytes(b [32]byte) (key ticketKey) { |
| 621 | hashed := sha512.Sum512(b[:]) |
| 622 | copy(key.keyName[:], hashed[:ticketKeyNameLen]) |
| 623 | copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) |
| 624 | copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) |
| 625 | return key |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 626 | } |
| 627 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 628 | // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session |
| 629 | // ticket, and the lifetime we set for tickets we send. |
| 630 | const maxSessionTicketLifetime = 7 * 24 * time.Hour |
| 631 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 632 | // Clone returns a shallow clone of c. It is safe to clone a Config that is |
| 633 | // being used concurrently by a TLS client or server. |
| 634 | func (c *Config) Clone() *Config { |
| 635 | // Running serverInit ensures that it's safe to read |
| 636 | // SessionTicketsDisabled. |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 637 | c.serverInitOnce.Do(func() { c.serverInit(nil) }) |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 638 | |
| 639 | var sessionTicketKeys []ticketKey |
| 640 | c.mutex.RLock() |
| 641 | sessionTicketKeys = c.sessionTicketKeys |
| 642 | c.mutex.RUnlock() |
| 643 | |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 644 | return &Config{ |
| 645 | Rand: c.Rand, |
| 646 | Time: c.Time, |
| 647 | Certificates: c.Certificates, |
| 648 | NameToCertificate: c.NameToCertificate, |
| 649 | GetCertificate: c.GetCertificate, |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 650 | GetClientCertificate: c.GetClientCertificate, |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 651 | GetConfigForClient: c.GetConfigForClient, |
| 652 | VerifyPeerCertificate: c.VerifyPeerCertificate, |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 653 | RootCAs: c.RootCAs, |
| 654 | NextProtos: c.NextProtos, |
| 655 | ServerName: c.ServerName, |
| 656 | ClientAuth: c.ClientAuth, |
| 657 | ClientCAs: c.ClientCAs, |
| 658 | InsecureSkipVerify: c.InsecureSkipVerify, |
| 659 | CipherSuites: c.CipherSuites, |
| 660 | PreferServerCipherSuites: c.PreferServerCipherSuites, |
| 661 | SessionTicketsDisabled: c.SessionTicketsDisabled, |
| 662 | SessionTicketKey: c.SessionTicketKey, |
| 663 | ClientSessionCache: c.ClientSessionCache, |
| 664 | MinVersion: c.MinVersion, |
| 665 | MaxVersion: c.MaxVersion, |
| 666 | CurvePreferences: c.CurvePreferences, |
| 667 | DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, |
| 668 | Renegotiation: c.Renegotiation, |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 669 | KeyLogWriter: c.KeyLogWriter, |
| 670 | sessionTicketKeys: sessionTicketKeys, |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 671 | } |
| 672 | } |
| 673 | |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 674 | // serverInit is run under c.serverInitOnce to do initialization of c. If c was |
| 675 | // returned by a GetConfigForClient callback then the argument should be the |
| 676 | // Config that was passed to Server, otherwise it should be nil. |
| 677 | func (c *Config) serverInit(originalConfig *Config) { |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 678 | if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 { |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 679 | return |
| 680 | } |
| 681 | |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 682 | alreadySet := false |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 683 | for _, b := range c.SessionTicketKey { |
| 684 | if b != 0 { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 685 | alreadySet = true |
| 686 | break |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | if !alreadySet { |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 691 | if originalConfig != nil { |
| 692 | copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:]) |
| 693 | } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 694 | c.SessionTicketsDisabled = true |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 695 | return |
| 696 | } |
| 697 | } |
| 698 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 699 | if originalConfig != nil { |
| 700 | originalConfig.mutex.RLock() |
| 701 | c.sessionTicketKeys = originalConfig.sessionTicketKeys |
| 702 | originalConfig.mutex.RUnlock() |
| 703 | } else { |
| 704 | c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)} |
| 705 | } |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 706 | } |
| 707 | |
| 708 | func (c *Config) ticketKeys() []ticketKey { |
| 709 | c.mutex.RLock() |
| 710 | // c.sessionTicketKeys is constant once created. SetSessionTicketKeys |
| 711 | // will only update it by replacing it with a new value. |
| 712 | ret := c.sessionTicketKeys |
| 713 | c.mutex.RUnlock() |
| 714 | return ret |
| 715 | } |
| 716 | |
| 717 | // SetSessionTicketKeys updates the session ticket keys for a server. The first |
| 718 | // key will be used when creating new tickets, while all keys can be used for |
| 719 | // decrypting tickets. It is safe to call this function while the server is |
| 720 | // running in order to rotate the session ticket keys. The function will panic |
| 721 | // if keys is empty. |
| 722 | func (c *Config) SetSessionTicketKeys(keys [][32]byte) { |
| 723 | if len(keys) == 0 { |
| 724 | panic("tls: keys must have at least one key") |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 725 | } |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 726 | |
| 727 | newKeys := make([]ticketKey, len(keys)) |
| 728 | for i, bytes := range keys { |
| 729 | newKeys[i] = ticketKeyFromBytes(bytes) |
| 730 | } |
| 731 | |
| 732 | c.mutex.Lock() |
| 733 | c.sessionTicketKeys = newKeys |
| 734 | c.mutex.Unlock() |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 735 | } |
| 736 | |
| 737 | func (c *Config) rand() io.Reader { |
| 738 | r := c.Rand |
| 739 | if r == nil { |
| 740 | return rand.Reader |
| 741 | } |
| 742 | return r |
| 743 | } |
| 744 | |
| 745 | func (c *Config) time() time.Time { |
| 746 | t := c.Time |
| 747 | if t == nil { |
| 748 | t = time.Now |
| 749 | } |
| 750 | return t() |
| 751 | } |
| 752 | |
| 753 | func (c *Config) cipherSuites() []uint16 { |
| 754 | s := c.CipherSuites |
| 755 | if s == nil { |
| 756 | s = defaultCipherSuites() |
| 757 | } |
| 758 | return s |
| 759 | } |
| 760 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 761 | var supportedVersions = []uint16{ |
| 762 | VersionTLS13, |
| 763 | VersionTLS12, |
| 764 | VersionTLS11, |
| 765 | VersionTLS10, |
| 766 | VersionSSL30, |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 767 | } |
| 768 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 769 | func (c *Config) supportedVersions(isClient bool) []uint16 { |
| 770 | versions := make([]uint16, 0, len(supportedVersions)) |
| 771 | for _, v := range supportedVersions { |
| 772 | if c != nil && c.MinVersion != 0 && v < c.MinVersion { |
| 773 | continue |
| 774 | } |
| 775 | if c != nil && c.MaxVersion != 0 && v > c.MaxVersion { |
| 776 | continue |
| 777 | } |
| 778 | // TLS 1.0 is the minimum version supported as a client. |
| 779 | if isClient && v < VersionTLS10 { |
| 780 | continue |
| 781 | } |
| 782 | // TLS 1.3 is opt-in in Go 1.12. |
| 783 | if v == VersionTLS13 && !isTLS13Supported() { |
| 784 | continue |
| 785 | } |
| 786 | versions = append(versions, v) |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 787 | } |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 788 | return versions |
| 789 | } |
| 790 | |
| 791 | // tls13Support caches the result for isTLS13Supported. |
| 792 | var tls13Support struct { |
| 793 | sync.Once |
| 794 | cached bool |
| 795 | } |
| 796 | |
| 797 | // isTLS13Supported returns whether the program opted into TLS 1.3 via |
| 798 | // GODEBUG=tls13=1. It's cached after the first execution. |
| 799 | func isTLS13Supported() bool { |
| 800 | tls13Support.Do(func() { |
| 801 | tls13Support.cached = goDebugString("tls13") == "1" |
| 802 | }) |
| 803 | return tls13Support.cached |
| 804 | } |
| 805 | |
| 806 | // goDebugString returns the value of the named GODEBUG key. |
| 807 | // GODEBUG is of the form "key=val,key2=val2". |
| 808 | func goDebugString(key string) string { |
| 809 | s := os.Getenv("GODEBUG") |
| 810 | for i := 0; i < len(s)-len(key)-1; i++ { |
| 811 | if i > 0 && s[i-1] != ',' { |
| 812 | continue |
| 813 | } |
| 814 | afterKey := s[i+len(key):] |
| 815 | if afterKey[0] != '=' || s[i:i+len(key)] != key { |
| 816 | continue |
| 817 | } |
| 818 | val := afterKey[1:] |
| 819 | for i, b := range val { |
| 820 | if b == ',' { |
| 821 | return val[:i] |
| 822 | } |
| 823 | } |
| 824 | return val |
| 825 | } |
| 826 | return "" |
| 827 | } |
| 828 | |
| 829 | func (c *Config) maxSupportedVersion(isClient bool) uint16 { |
| 830 | supportedVersions := c.supportedVersions(isClient) |
| 831 | if len(supportedVersions) == 0 { |
| 832 | return 0 |
| 833 | } |
| 834 | return supportedVersions[0] |
| 835 | } |
| 836 | |
| 837 | // supportedVersionsFromMax returns a list of supported versions derived from a |
| 838 | // legacy maximum version value. Note that only versions supported by this |
| 839 | // library are returned. Any newer peer will use supportedVersions anyway. |
| 840 | func supportedVersionsFromMax(maxVersion uint16) []uint16 { |
| 841 | versions := make([]uint16, 0, len(supportedVersions)) |
| 842 | for _, v := range supportedVersions { |
| 843 | if v > maxVersion { |
| 844 | continue |
| 845 | } |
| 846 | versions = append(versions, v) |
| 847 | } |
| 848 | return versions |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 849 | } |
| 850 | |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 851 | var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521} |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 852 | |
| 853 | func (c *Config) curvePreferences() []CurveID { |
| 854 | if c == nil || len(c.CurvePreferences) == 0 { |
| 855 | return defaultCurvePreferences |
| 856 | } |
| 857 | return c.CurvePreferences |
| 858 | } |
| 859 | |
| 860 | // mutualVersion returns the protocol version to use given the advertised |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 861 | // versions of the peer. Priority is given to the peer preference order. |
| 862 | func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) { |
| 863 | supportedVersions := c.supportedVersions(isClient) |
| 864 | for _, peerVersion := range peerVersions { |
| 865 | for _, v := range supportedVersions { |
| 866 | if v == peerVersion { |
| 867 | return v, true |
| 868 | } |
| 869 | } |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 870 | } |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 871 | return 0, false |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 872 | } |
| 873 | |
| 874 | // getCertificate returns the best certificate for the given ClientHelloInfo, |
| 875 | // defaulting to the first element of c.Certificates. |
| 876 | func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 877 | if c.GetCertificate != nil && |
| 878 | (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 879 | cert, err := c.GetCertificate(clientHello) |
| 880 | if cert != nil || err != nil { |
| 881 | return cert, err |
| 882 | } |
| 883 | } |
| 884 | |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 885 | if len(c.Certificates) == 0 { |
Dan Willemsen | 38f2dba | 2016-07-08 14:54:35 -0700 | [diff] [blame] | 886 | return nil, errors.New("tls: no certificates configured") |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 887 | } |
| 888 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 889 | if len(c.Certificates) == 1 || c.NameToCertificate == nil { |
| 890 | // There's only one choice, so no point doing any work. |
| 891 | return &c.Certificates[0], nil |
| 892 | } |
| 893 | |
| 894 | name := strings.ToLower(clientHello.ServerName) |
| 895 | for len(name) > 0 && name[len(name)-1] == '.' { |
| 896 | name = name[:len(name)-1] |
| 897 | } |
| 898 | |
| 899 | if cert, ok := c.NameToCertificate[name]; ok { |
| 900 | return cert, nil |
| 901 | } |
| 902 | |
| 903 | // try replacing labels in the name with wildcards until we get a |
| 904 | // match. |
| 905 | labels := strings.Split(name, ".") |
| 906 | for i := range labels { |
| 907 | labels[i] = "*" |
| 908 | candidate := strings.Join(labels, ".") |
| 909 | if cert, ok := c.NameToCertificate[candidate]; ok { |
| 910 | return cert, nil |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | // If nothing matches, return the first certificate. |
| 915 | return &c.Certificates[0], nil |
| 916 | } |
| 917 | |
| 918 | // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate |
| 919 | // from the CommonName and SubjectAlternateName fields of each of the leaf |
| 920 | // certificates. |
| 921 | func (c *Config) BuildNameToCertificate() { |
| 922 | c.NameToCertificate = make(map[string]*Certificate) |
| 923 | for i := range c.Certificates { |
| 924 | cert := &c.Certificates[i] |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 925 | x509Cert := cert.Leaf |
| 926 | if x509Cert == nil { |
| 927 | var err error |
| 928 | x509Cert, err = x509.ParseCertificate(cert.Certificate[0]) |
| 929 | if err != nil { |
| 930 | continue |
| 931 | } |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 932 | } |
| 933 | if len(x509Cert.Subject.CommonName) > 0 { |
| 934 | c.NameToCertificate[x509Cert.Subject.CommonName] = cert |
| 935 | } |
| 936 | for _, san := range x509Cert.DNSNames { |
| 937 | c.NameToCertificate[san] = cert |
| 938 | } |
| 939 | } |
| 940 | } |
| 941 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 942 | const ( |
| 943 | keyLogLabelTLS12 = "CLIENT_RANDOM" |
| 944 | keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" |
| 945 | keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET" |
| 946 | keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0" |
| 947 | keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0" |
| 948 | ) |
| 949 | |
| 950 | func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error { |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 951 | if c.KeyLogWriter == nil { |
| 952 | return nil |
| 953 | } |
| 954 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 955 | logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret)) |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 956 | |
| 957 | writerMutex.Lock() |
| 958 | _, err := c.KeyLogWriter.Write(logLine) |
| 959 | writerMutex.Unlock() |
| 960 | |
| 961 | return err |
| 962 | } |
| 963 | |
| 964 | // writerMutex protects all KeyLogWriters globally. It is rarely enabled, |
| 965 | // and is only for debugging, so a global mutex saves space. |
| 966 | var writerMutex sync.Mutex |
| 967 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 968 | // A Certificate is a chain of one or more certificates, leaf first. |
| 969 | type Certificate struct { |
| 970 | Certificate [][]byte |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 971 | // PrivateKey contains the private key corresponding to the public key in |
| 972 | // Leaf. This must implement crypto.Signer with an RSA or ECDSA PublicKey. |
| 973 | // For a server up to TLS 1.2, it can also implement crypto.Decrypter with |
| 974 | // an RSA PublicKey. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 975 | PrivateKey crypto.PrivateKey |
| 976 | // OCSPStaple contains an optional OCSP response which will be served |
| 977 | // to clients that request it. |
| 978 | OCSPStaple []byte |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 979 | // SignedCertificateTimestamps contains an optional list of Signed |
| 980 | // Certificate Timestamps which will be served to clients that request it. |
| 981 | SignedCertificateTimestamps [][]byte |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 982 | // Leaf is the parsed form of the leaf certificate, which may be |
| 983 | // initialized using x509.ParseCertificate to reduce per-handshake |
| 984 | // processing for TLS clients doing client authentication. If nil, the |
| 985 | // leaf certificate will be parsed as needed. |
| 986 | Leaf *x509.Certificate |
| 987 | } |
| 988 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 989 | type handshakeMessage interface { |
| 990 | marshal() []byte |
| 991 | unmarshal([]byte) bool |
| 992 | } |
| 993 | |
| 994 | // lruSessionCache is a ClientSessionCache implementation that uses an LRU |
| 995 | // caching strategy. |
| 996 | type lruSessionCache struct { |
| 997 | sync.Mutex |
| 998 | |
| 999 | m map[string]*list.Element |
| 1000 | q *list.List |
| 1001 | capacity int |
| 1002 | } |
| 1003 | |
| 1004 | type lruSessionCacheEntry struct { |
| 1005 | sessionKey string |
| 1006 | state *ClientSessionState |
| 1007 | } |
| 1008 | |
| 1009 | // NewLRUClientSessionCache returns a ClientSessionCache with the given |
| 1010 | // capacity that uses an LRU strategy. If capacity is < 1, a default capacity |
| 1011 | // is used instead. |
| 1012 | func NewLRUClientSessionCache(capacity int) ClientSessionCache { |
| 1013 | const defaultSessionCacheCapacity = 64 |
| 1014 | |
| 1015 | if capacity < 1 { |
| 1016 | capacity = defaultSessionCacheCapacity |
| 1017 | } |
| 1018 | return &lruSessionCache{ |
| 1019 | m: make(map[string]*list.Element), |
| 1020 | q: list.New(), |
| 1021 | capacity: capacity, |
| 1022 | } |
| 1023 | } |
| 1024 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1025 | // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry |
| 1026 | // corresponding to sessionKey is removed from the cache instead. |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 1027 | func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { |
| 1028 | c.Lock() |
| 1029 | defer c.Unlock() |
| 1030 | |
| 1031 | if elem, ok := c.m[sessionKey]; ok { |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1032 | if cs == nil { |
| 1033 | c.q.Remove(elem) |
| 1034 | delete(c.m, sessionKey) |
| 1035 | } else { |
| 1036 | entry := elem.Value.(*lruSessionCacheEntry) |
| 1037 | entry.state = cs |
| 1038 | c.q.MoveToFront(elem) |
| 1039 | } |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 1040 | return |
| 1041 | } |
| 1042 | |
| 1043 | if c.q.Len() < c.capacity { |
| 1044 | entry := &lruSessionCacheEntry{sessionKey, cs} |
| 1045 | c.m[sessionKey] = c.q.PushFront(entry) |
| 1046 | return |
| 1047 | } |
| 1048 | |
| 1049 | elem := c.q.Back() |
| 1050 | entry := elem.Value.(*lruSessionCacheEntry) |
| 1051 | delete(c.m, entry.sessionKey) |
| 1052 | entry.sessionKey = sessionKey |
| 1053 | entry.state = cs |
| 1054 | c.q.MoveToFront(elem) |
| 1055 | c.m[sessionKey] = elem |
| 1056 | } |
| 1057 | |
| 1058 | // Get returns the ClientSessionState value associated with a given key. It |
| 1059 | // returns (nil, false) if no value is found. |
| 1060 | func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { |
| 1061 | c.Lock() |
| 1062 | defer c.Unlock() |
| 1063 | |
| 1064 | if elem, ok := c.m[sessionKey]; ok { |
| 1065 | c.q.MoveToFront(elem) |
| 1066 | return elem.Value.(*lruSessionCacheEntry).state, true |
| 1067 | } |
| 1068 | return nil, false |
| 1069 | } |
| 1070 | |
| 1071 | // TODO(jsing): Make these available to both crypto/x509 and crypto/tls. |
| 1072 | type dsaSignature struct { |
| 1073 | R, S *big.Int |
| 1074 | } |
| 1075 | |
| 1076 | type ecdsaSignature dsaSignature |
| 1077 | |
| 1078 | var emptyConfig Config |
| 1079 | |
| 1080 | func defaultConfig() *Config { |
| 1081 | return &emptyConfig |
| 1082 | } |
| 1083 | |
| 1084 | var ( |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1085 | once sync.Once |
| 1086 | varDefaultCipherSuites []uint16 |
| 1087 | varDefaultCipherSuitesTLS13 []uint16 |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 1088 | ) |
| 1089 | |
| 1090 | func defaultCipherSuites() []uint16 { |
| 1091 | once.Do(initDefaultCipherSuites) |
| 1092 | return varDefaultCipherSuites |
| 1093 | } |
| 1094 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1095 | func defaultCipherSuitesTLS13() []uint16 { |
| 1096 | once.Do(initDefaultCipherSuites) |
| 1097 | return varDefaultCipherSuitesTLS13 |
| 1098 | } |
| 1099 | |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 1100 | func initDefaultCipherSuites() { |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1101 | var topCipherSuites []uint16 |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 1102 | |
| 1103 | // Check the cpu flags for each platform that has optimized GCM implementations. |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1104 | // Worst case, these variables will just all be false. |
| 1105 | var ( |
| 1106 | hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ |
| 1107 | hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL |
| 1108 | // Keep in sync with crypto/aes/cipher_s390x.go. |
| 1109 | hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 1110 | |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1111 | hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X |
| 1112 | ) |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 1113 | |
| 1114 | if hasGCMAsm { |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1115 | // If AES-GCM hardware is provided then prioritise AES-GCM |
| 1116 | // cipher suites. |
| 1117 | topCipherSuites = []uint16{ |
| 1118 | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1119 | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1120 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, |
| 1121 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, |
| 1122 | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, |
| 1123 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, |
| 1124 | } |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1125 | varDefaultCipherSuitesTLS13 = []uint16{ |
| 1126 | TLS_AES_128_GCM_SHA256, |
| 1127 | TLS_CHACHA20_POLY1305_SHA256, |
| 1128 | TLS_AES_256_GCM_SHA384, |
| 1129 | } |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1130 | } else { |
| 1131 | // Without AES-GCM hardware, we put the ChaCha20-Poly1305 |
| 1132 | // cipher suites first. |
| 1133 | topCipherSuites = []uint16{ |
| 1134 | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, |
| 1135 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, |
| 1136 | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1137 | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1138 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, |
| 1139 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, |
| 1140 | } |
Colin Cross | d9c6b80 | 2019-03-19 21:10:31 -0700 | [diff] [blame^] | 1141 | varDefaultCipherSuitesTLS13 = []uint16{ |
| 1142 | TLS_CHACHA20_POLY1305_SHA256, |
| 1143 | TLS_AES_128_GCM_SHA256, |
| 1144 | TLS_AES_256_GCM_SHA384, |
| 1145 | } |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1146 | } |
| 1147 | |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 1148 | varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites)) |
Dan Willemsen | d279748 | 2017-07-26 13:13:13 -0700 | [diff] [blame] | 1149 | varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...) |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1150 | |
| 1151 | NextCipherSuite: |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 1152 | for _, suite := range cipherSuites { |
| 1153 | if suite.flags&suiteDefaultOff != 0 { |
| 1154 | continue |
| 1155 | } |
Dan Willemsen | ebae302 | 2017-01-13 23:01:08 -0800 | [diff] [blame] | 1156 | for _, existing := range varDefaultCipherSuites { |
| 1157 | if existing == suite.id { |
| 1158 | continue NextCipherSuite |
| 1159 | } |
| 1160 | } |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 1161 | varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) |
Brent Austin | ba3052e | 2015-04-21 16:08:23 -0700 | [diff] [blame] | 1162 | } |
| 1163 | } |
| 1164 | |
| 1165 | func unexpectedMessageError(wanted, got interface{}) error { |
| 1166 | return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) |
| 1167 | } |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 1168 | |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 1169 | func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool { |
| 1170 | for _, s := range supportedSignatureAlgorithms { |
| 1171 | if s == sigAlg { |
Dan Willemsen | 09eb3b1 | 2015-09-16 14:34:17 -0700 | [diff] [blame] | 1172 | return true |
| 1173 | } |
| 1174 | } |
| 1175 | return false |
| 1176 | } |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 1177 | |
| 1178 | // signatureFromSignatureScheme maps a signature algorithm to the underlying |
| 1179 | // signature method (without hash function). |
| 1180 | func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 { |
| 1181 | switch signatureAlgorithm { |
| 1182 | case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512: |
Dan Willemsen | c741332 | 2018-08-27 23:21:26 -0700 | [diff] [blame] | 1183 | return signaturePKCS1v15 |
| 1184 | case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512: |
| 1185 | return signatureRSAPSS |
Dan Willemsen | a322328 | 2018-02-27 19:41:43 -0800 | [diff] [blame] | 1186 | case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512: |
| 1187 | return signatureECDSA |
| 1188 | default: |
| 1189 | return 0 |
| 1190 | } |
| 1191 | } |