common.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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. package tls
  5. import (
  6. "bytes"
  7. "container/list"
  8. "context"
  9. "crypto"
  10. "crypto/ecdsa"
  11. "crypto/ed25519"
  12. "crypto/elliptic"
  13. "crypto/rand"
  14. "crypto/rsa"
  15. "crypto/sha512"
  16. "crypto/x509"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. const (
  26. VersionTLS10 = 0x0301
  27. VersionTLS11 = 0x0302
  28. VersionTLS12 = 0x0303
  29. VersionTLS13 = 0x0304
  30. // Deprecated: SSLv3 is cryptographically broken, and is no longer
  31. // supported by this package. See golang.org/issue/32716.
  32. VersionSSL30 = 0x0300
  33. )
  34. const (
  35. maxPlaintext = 16384 // maximum plaintext payload length
  36. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  37. maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
  38. recordHeaderLen = 5 // record header length
  39. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  40. maxUselessRecords = 16 // maximum number of consecutive non-advancing records
  41. )
  42. // TLS record types.
  43. type recordType uint8
  44. const (
  45. recordTypeChangeCipherSpec recordType = 20
  46. recordTypeAlert recordType = 21
  47. recordTypeHandshake recordType = 22
  48. recordTypeApplicationData recordType = 23
  49. )
  50. // TLS handshake message types.
  51. const (
  52. typeHelloRequest uint8 = 0
  53. typeClientHello uint8 = 1
  54. typeServerHello uint8 = 2
  55. typeNewSessionTicket uint8 = 4
  56. typeEndOfEarlyData uint8 = 5
  57. typeEncryptedExtensions uint8 = 8
  58. typeCertificate uint8 = 11
  59. typeServerKeyExchange uint8 = 12
  60. typeCertificateRequest uint8 = 13
  61. typeServerHelloDone uint8 = 14
  62. typeCertificateVerify uint8 = 15
  63. typeClientKeyExchange uint8 = 16
  64. typeFinished uint8 = 20
  65. typeCertificateStatus uint8 = 22
  66. typeKeyUpdate uint8 = 24
  67. typeNextProtocol uint8 = 67 // Not IANA assigned
  68. typeMessageHash uint8 = 254 // synthetic message
  69. )
  70. // TLS compression types.
  71. const (
  72. compressionNone uint8 = 0
  73. )
  74. // TLS extension numbers
  75. const (
  76. extensionServerName uint16 = 0
  77. extensionStatusRequest uint16 = 5
  78. extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
  79. extensionSupportedPoints uint16 = 11
  80. extensionSignatureAlgorithms uint16 = 13
  81. extensionALPN uint16 = 16
  82. extensionSCT uint16 = 18
  83. extensionSessionTicket uint16 = 35
  84. extensionPreSharedKey uint16 = 41
  85. extensionEarlyData uint16 = 42
  86. extensionSupportedVersions uint16 = 43
  87. extensionCookie uint16 = 44
  88. extensionPSKModes uint16 = 45
  89. extensionCertificateAuthorities uint16 = 47
  90. extensionSignatureAlgorithmsCert uint16 = 50
  91. extensionKeyShare uint16 = 51
  92. extensionRenegotiationInfo uint16 = 0xff01
  93. )
  94. // TLS signaling cipher suite values
  95. const (
  96. scsvRenegotiation uint16 = 0x00ff
  97. )
  98. // CurveID is the type of a TLS identifier for an elliptic curve. See
  99. // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
  100. //
  101. // In TLS 1.3, this type is called NamedGroup, but at this time this library
  102. // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
  103. type CurveID uint16
  104. const (
  105. CurveP256 CurveID = 23
  106. CurveP384 CurveID = 24
  107. CurveP521 CurveID = 25
  108. X25519 CurveID = 29
  109. )
  110. // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
  111. type keyShare struct {
  112. group CurveID
  113. data []byte
  114. }
  115. // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
  116. const (
  117. pskModePlain uint8 = 0
  118. pskModeDHE uint8 = 1
  119. )
  120. // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
  121. // session. See RFC 8446, Section 4.2.11.
  122. type pskIdentity struct {
  123. label []byte
  124. obfuscatedTicketAge uint32
  125. }
  126. // TLS Elliptic Curve Point Formats
  127. // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  128. const (
  129. pointFormatUncompressed uint8 = 0
  130. )
  131. // TLS CertificateStatusType (RFC 3546)
  132. const (
  133. statusTypeOCSP uint8 = 1
  134. )
  135. // Certificate types (for certificateRequestMsg)
  136. const (
  137. certTypeRSASign = 1
  138. certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
  139. )
  140. // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
  141. // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
  142. const (
  143. signaturePKCS1v15 uint8 = iota + 225
  144. signatureRSAPSS
  145. signatureECDSA
  146. signatureEd25519
  147. )
  148. // directSigning is a standard Hash value that signals that no pre-hashing
  149. // should be performed, and that the input should be signed directly. It is the
  150. // hash function associated with the Ed25519 signature scheme.
  151. var directSigning crypto.Hash = 0
  152. // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
  153. // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
  154. // CertificateRequest. The two fields are merged to match with TLS 1.3.
  155. // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
  156. var defaultSupportedSignatureAlgorithms = []SignatureScheme{
  157. PSSWithSHA256,
  158. ECDSAWithP256AndSHA256,
  159. Ed25519,
  160. PSSWithSHA384,
  161. PSSWithSHA512,
  162. PKCS1WithSHA256,
  163. PKCS1WithSHA384,
  164. PKCS1WithSHA512,
  165. ECDSAWithP384AndSHA384,
  166. ECDSAWithP521AndSHA512,
  167. PKCS1WithSHA1,
  168. ECDSAWithSHA1,
  169. }
  170. // helloRetryRequestRandom is set as the Random value of a ServerHello
  171. // to signal that the message is actually a HelloRetryRequest.
  172. var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
  173. 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
  174. 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
  175. 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
  176. 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
  177. }
  178. const (
  179. // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
  180. // random as a downgrade protection if the server would be capable of
  181. // negotiating a higher version. See RFC 8446, Section 4.1.3.
  182. downgradeCanaryTLS12 = "DOWNGRD\x01"
  183. downgradeCanaryTLS11 = "DOWNGRD\x00"
  184. )
  185. // testingOnlyForceDowngradeCanary is set in tests to force the server side to
  186. // include downgrade canaries even if it's using its highers supported version.
  187. var testingOnlyForceDowngradeCanary bool
  188. // ConnectionState records basic TLS details about the connection.
  189. type ConnectionState struct {
  190. // Version is the TLS version used by the connection (e.g. VersionTLS12).
  191. Version uint16
  192. // HandshakeComplete is true if the handshake has concluded.
  193. HandshakeComplete bool
  194. // DidResume is true if this connection was successfully resumed from a
  195. // previous session with a session ticket or similar mechanism.
  196. DidResume bool
  197. // CipherSuite is the cipher suite negotiated for the connection (e.g.
  198. // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
  199. CipherSuite uint16
  200. // NegotiatedProtocol is the application protocol negotiated with ALPN.
  201. NegotiatedProtocol string
  202. // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
  203. //
  204. // Deprecated: this value is always true.
  205. NegotiatedProtocolIsMutual bool
  206. // ServerName is the value of the Server Name Indication extension sent by
  207. // the client. It's available both on the server and on the client side.
  208. ServerName string
  209. // PeerCertificates are the parsed certificates sent by the peer, in the
  210. // order in which they were sent. The first element is the leaf certificate
  211. // that the connection is verified against.
  212. //
  213. // On the client side, it can't be empty. On the server side, it can be
  214. // empty if Config.ClientAuth is not RequireAnyClientCert or
  215. // RequireAndVerifyClientCert.
  216. PeerCertificates []*x509.Certificate
  217. // VerifiedChains is a list of one or more chains where the first element is
  218. // PeerCertificates[0] and the last element is from Config.RootCAs (on the
  219. // client side) or Config.ClientCAs (on the server side).
  220. //
  221. // On the client side, it's set if Config.InsecureSkipVerify is false. On
  222. // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
  223. // (and the peer provided a certificate) or RequireAndVerifyClientCert.
  224. VerifiedChains [][]*x509.Certificate
  225. // SignedCertificateTimestamps is a list of SCTs provided by the peer
  226. // through the TLS handshake for the leaf certificate, if any.
  227. SignedCertificateTimestamps [][]byte
  228. // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
  229. // response provided by the peer for the leaf certificate, if any.
  230. OCSPResponse []byte
  231. // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
  232. // Section 3). This value will be nil for TLS 1.3 connections and for all
  233. // resumed connections.
  234. //
  235. // Deprecated: there are conditions in which this value might not be unique
  236. // to a connection. See the Security Considerations sections of RFC 5705 and
  237. // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
  238. TLSUnique []byte
  239. // ekm is a closure exposed via ExportKeyingMaterial.
  240. ekm func(label string, context []byte, length int) ([]byte, error)
  241. }
  242. // ExportKeyingMaterial returns length bytes of exported key material in a new
  243. // slice as defined in RFC 5705. If context is nil, it is not used as part of
  244. // the seed. If the connection was set to allow renegotiation via
  245. // Config.Renegotiation, this function will return an error.
  246. func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
  247. return cs.ekm(label, context, length)
  248. }
  249. // ClientAuthType declares the policy the server will follow for
  250. // TLS Client Authentication.
  251. type ClientAuthType int
  252. const (
  253. // NoClientCert indicates that no client certificate should be requested
  254. // during the handshake, and if any certificates are sent they will not
  255. // be verified.
  256. NoClientCert ClientAuthType = iota
  257. // RequestClientCert indicates that a client certificate should be requested
  258. // during the handshake, but does not require that the client send any
  259. // certificates.
  260. RequestClientCert
  261. // RequireAnyClientCert indicates that a client certificate should be requested
  262. // during the handshake, and that at least one certificate is required to be
  263. // sent by the client, but that certificate is not required to be valid.
  264. RequireAnyClientCert
  265. // VerifyClientCertIfGiven indicates that a client certificate should be requested
  266. // during the handshake, but does not require that the client sends a
  267. // certificate. If the client does send a certificate it is required to be
  268. // valid.
  269. VerifyClientCertIfGiven
  270. // RequireAndVerifyClientCert indicates that a client certificate should be requested
  271. // during the handshake, and that at least one valid certificate is required
  272. // to be sent by the client.
  273. RequireAndVerifyClientCert
  274. )
  275. // requiresClientCert reports whether the ClientAuthType requires a client
  276. // certificate to be provided.
  277. func requiresClientCert(c ClientAuthType) bool {
  278. switch c {
  279. case RequireAnyClientCert, RequireAndVerifyClientCert:
  280. return true
  281. default:
  282. return false
  283. }
  284. }
  285. // ClientSessionState contains the state needed by clients to resume TLS
  286. // sessions.
  287. type ClientSessionState struct {
  288. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  289. vers uint16 // TLS version negotiated for the session
  290. cipherSuite uint16 // Ciphersuite negotiated for the session
  291. masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
  292. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  293. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  294. receivedAt time.Time // When the session ticket was received from the server
  295. ocspResponse []byte // Stapled OCSP response presented by the server
  296. scts [][]byte // SCTs presented by the server
  297. // TLS 1.3 fields.
  298. nonce []byte // Ticket nonce sent by the server, to derive PSK
  299. useBy time.Time // Expiration of the ticket lifetime as set by the server
  300. ageAdd uint32 // Random obfuscation factor for sending the ticket age
  301. }
  302. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  303. // by a client to resume a TLS session with a given server. ClientSessionCache
  304. // implementations should expect to be called concurrently from different
  305. // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
  306. // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
  307. // are supported via this interface.
  308. type ClientSessionCache interface {
  309. // Get searches for a ClientSessionState associated with the given key.
  310. // On return, ok is true if one was found.
  311. Get(sessionKey string) (session *ClientSessionState, ok bool)
  312. // Put adds the ClientSessionState to the cache with the given key. It might
  313. // get called multiple times in a connection if a TLS 1.3 server provides
  314. // more than one session ticket. If called with a nil *ClientSessionState,
  315. // it should remove the cache entry.
  316. Put(sessionKey string, cs *ClientSessionState)
  317. }
  318. //go:generate stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go
  319. // SignatureScheme identifies a signature algorithm supported by TLS. See
  320. // RFC 8446, Section 4.2.3.
  321. type SignatureScheme uint16
  322. const (
  323. // RSASSA-PKCS1-v1_5 algorithms.
  324. PKCS1WithSHA256 SignatureScheme = 0x0401
  325. PKCS1WithSHA384 SignatureScheme = 0x0501
  326. PKCS1WithSHA512 SignatureScheme = 0x0601
  327. // RSASSA-PSS algorithms with public key OID rsaEncryption.
  328. PSSWithSHA256 SignatureScheme = 0x0804
  329. PSSWithSHA384 SignatureScheme = 0x0805
  330. PSSWithSHA512 SignatureScheme = 0x0806
  331. // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
  332. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  333. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  334. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  335. // EdDSA algorithms.
  336. Ed25519 SignatureScheme = 0x0807
  337. // Legacy signature and hash algorithms for TLS 1.2.
  338. PKCS1WithSHA1 SignatureScheme = 0x0201
  339. ECDSAWithSHA1 SignatureScheme = 0x0203
  340. )
  341. // ClientHelloInfo contains information from a ClientHello message in order to
  342. // guide application logic in the GetCertificate and GetConfigForClient callbacks.
  343. type ClientHelloInfo struct {
  344. // CipherSuites lists the CipherSuites supported by the client (e.g.
  345. // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
  346. CipherSuites []uint16
  347. // ServerName indicates the name of the server requested by the client
  348. // in order to support virtual hosting. ServerName is only set if the
  349. // client is using SNI (see RFC 4366, Section 3.1).
  350. ServerName string
  351. // SupportedCurves lists the elliptic curves supported by the client.
  352. // SupportedCurves is set only if the Supported Elliptic Curves
  353. // Extension is being used (see RFC 4492, Section 5.1.1).
  354. SupportedCurves []CurveID
  355. // SupportedPoints lists the point formats supported by the client.
  356. // SupportedPoints is set only if the Supported Point Formats Extension
  357. // is being used (see RFC 4492, Section 5.1.2).
  358. SupportedPoints []uint8
  359. // SignatureSchemes lists the signature and hash schemes that the client
  360. // is willing to verify. SignatureSchemes is set only if the Signature
  361. // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
  362. SignatureSchemes []SignatureScheme
  363. // SupportedProtos lists the application protocols supported by the client.
  364. // SupportedProtos is set only if the Application-Layer Protocol
  365. // Negotiation Extension is being used (see RFC 7301, Section 3.1).
  366. //
  367. // Servers can select a protocol by setting Config.NextProtos in a
  368. // GetConfigForClient return value.
  369. SupportedProtos []string
  370. // SupportedVersions lists the TLS versions supported by the client.
  371. // For TLS versions less than 1.3, this is extrapolated from the max
  372. // version advertised by the client, so values other than the greatest
  373. // might be rejected if used.
  374. SupportedVersions []uint16
  375. // Conn is the underlying net.Conn for the connection. Do not read
  376. // from, or write to, this connection; that will cause the TLS
  377. // connection to fail.
  378. Conn net.Conn
  379. // config is embedded by the GetCertificate or GetConfigForClient caller,
  380. // for use with SupportsCertificate.
  381. config *Config
  382. // ctx is the context of the handshake that is in progress.
  383. ctx context.Context
  384. }
  385. // Context returns the context of the handshake that is in progress.
  386. // This context is a child of the context passed to HandshakeContext,
  387. // if any, and is canceled when the handshake concludes.
  388. func (c *ClientHelloInfo) Context() context.Context {
  389. return c.ctx
  390. }
  391. // CertificateRequestInfo contains information from a server's
  392. // CertificateRequest message, which is used to demand a certificate and proof
  393. // of control from a client.
  394. type CertificateRequestInfo struct {
  395. // AcceptableCAs contains zero or more, DER-encoded, X.501
  396. // Distinguished Names. These are the names of root or intermediate CAs
  397. // that the server wishes the returned certificate to be signed by. An
  398. // empty slice indicates that the server has no preference.
  399. AcceptableCAs [][]byte
  400. // SignatureSchemes lists the signature schemes that the server is
  401. // willing to verify.
  402. SignatureSchemes []SignatureScheme
  403. // Version is the TLS version that was negotiated for this connection.
  404. Version uint16
  405. // ctx is the context of the handshake that is in progress.
  406. ctx context.Context
  407. }
  408. // Context returns the context of the handshake that is in progress.
  409. // This context is a child of the context passed to HandshakeContext,
  410. // if any, and is canceled when the handshake concludes.
  411. func (c *CertificateRequestInfo) Context() context.Context {
  412. return c.ctx
  413. }
  414. // RenegotiationSupport enumerates the different levels of support for TLS
  415. // renegotiation. TLS renegotiation is the act of performing subsequent
  416. // handshakes on a connection after the first. This significantly complicates
  417. // the state machine and has been the source of numerous, subtle security
  418. // issues. Initiating a renegotiation is not supported, but support for
  419. // accepting renegotiation requests may be enabled.
  420. //
  421. // Even when enabled, the server may not change its identity between handshakes
  422. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  423. // handshake and application data flow is not permitted so renegotiation can
  424. // only be used with protocols that synchronise with the renegotiation, such as
  425. // HTTPS.
  426. //
  427. // Renegotiation is not defined in TLS 1.3.
  428. type RenegotiationSupport int
  429. const (
  430. // RenegotiateNever disables renegotiation.
  431. RenegotiateNever RenegotiationSupport = iota
  432. // RenegotiateOnceAsClient allows a remote server to request
  433. // renegotiation once per connection.
  434. RenegotiateOnceAsClient
  435. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  436. // request renegotiation.
  437. RenegotiateFreelyAsClient
  438. )
  439. // A Config structure is used to configure a TLS client or server.
  440. // After one has been passed to a TLS function it must not be
  441. // modified. A Config may be reused; the tls package will also not
  442. // modify it.
  443. type Config struct {
  444. // Rand provides the source of entropy for nonces and RSA blinding.
  445. // If Rand is nil, TLS uses the cryptographic random reader in package
  446. // crypto/rand.
  447. // The Reader must be safe for use by multiple goroutines.
  448. Rand io.Reader
  449. // Time returns the current time as the number of seconds since the epoch.
  450. // If Time is nil, TLS uses time.Now.
  451. Time func() time.Time
  452. // Certificates contains one or more certificate chains to present to the
  453. // other side of the connection. The first certificate compatible with the
  454. // peer's requirements is selected automatically.
  455. //
  456. // Server configurations must set one of Certificates, GetCertificate or
  457. // GetConfigForClient. Clients doing client-authentication may set either
  458. // Certificates or GetClientCertificate.
  459. //
  460. // Note: if there are multiple Certificates, and they don't have the
  461. // optional field Leaf set, certificate selection will incur a significant
  462. // per-handshake performance cost.
  463. Certificates []Certificate
  464. // NameToCertificate maps from a certificate name to an element of
  465. // Certificates. Note that a certificate name can be of the form
  466. // '*.example.com' and so doesn't have to be a domain name as such.
  467. //
  468. // Deprecated: NameToCertificate only allows associating a single
  469. // certificate with a given name. Leave this field nil to let the library
  470. // select the first compatible chain from Certificates.
  471. NameToCertificate map[string]*Certificate
  472. // GetCertificate returns a Certificate based on the given
  473. // ClientHelloInfo. It will only be called if the client supplies SNI
  474. // information or if Certificates is empty.
  475. //
  476. // If GetCertificate is nil or returns nil, then the certificate is
  477. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  478. // best element of Certificates will be used.
  479. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  480. // GetClientCertificate, if not nil, is called when a server requests a
  481. // certificate from a client. If set, the contents of Certificates will
  482. // be ignored.
  483. //
  484. // If GetClientCertificate returns an error, the handshake will be
  485. // aborted and that error will be returned. Otherwise
  486. // GetClientCertificate must return a non-nil Certificate. If
  487. // Certificate.Certificate is empty then no certificate will be sent to
  488. // the server. If this is unacceptable to the server then it may abort
  489. // the handshake.
  490. //
  491. // GetClientCertificate may be called multiple times for the same
  492. // connection if renegotiation occurs or if TLS 1.3 is in use.
  493. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  494. // GetConfigForClient, if not nil, is called after a ClientHello is
  495. // received from a client. It may return a non-nil Config in order to
  496. // change the Config that will be used to handle this connection. If
  497. // the returned Config is nil, the original Config will be used. The
  498. // Config returned by this callback may not be subsequently modified.
  499. //
  500. // If GetConfigForClient is nil, the Config passed to Server() will be
  501. // used for all connections.
  502. //
  503. // If SessionTicketKey was explicitly set on the returned Config, or if
  504. // SetSessionTicketKeys was called on the returned Config, those keys will
  505. // be used. Otherwise, the original Config keys will be used (and possibly
  506. // rotated if they are automatically managed).
  507. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  508. // VerifyPeerCertificate, if not nil, is called after normal
  509. // certificate verification by either a TLS client or server. It
  510. // receives the raw ASN.1 certificates provided by the peer and also
  511. // any verified chains that normal processing found. If it returns a
  512. // non-nil error, the handshake is aborted and that error results.
  513. //
  514. // If normal verification fails then the handshake will abort before
  515. // considering this callback. If normal verification is disabled by
  516. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  517. // RequestClientCert or RequireAnyClientCert, then this callback will
  518. // be considered but the verifiedChains argument will always be nil.
  519. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  520. // VerifyConnection, if not nil, is called after normal certificate
  521. // verification and after VerifyPeerCertificate by either a TLS client
  522. // or server. If it returns a non-nil error, the handshake is aborted
  523. // and that error results.
  524. //
  525. // If normal verification fails then the handshake will abort before
  526. // considering this callback. This callback will run for all connections
  527. // regardless of InsecureSkipVerify or ClientAuth settings.
  528. VerifyConnection func(ConnectionState) error
  529. // RootCAs defines the set of root certificate authorities
  530. // that clients use when verifying server certificates.
  531. // If RootCAs is nil, TLS uses the host's root CA set.
  532. RootCAs *x509.CertPool
  533. // NextProtos is a list of supported application level protocols, in
  534. // order of preference. If both peers support ALPN, the selected
  535. // protocol will be one from this list, and the connection will fail
  536. // if there is no mutually supported protocol. If NextProtos is empty
  537. // or the peer doesn't support ALPN, the connection will succeed and
  538. // ConnectionState.NegotiatedProtocol will be empty.
  539. NextProtos []string
  540. // ServerName is used to verify the hostname on the returned
  541. // certificates unless InsecureSkipVerify is given. It is also included
  542. // in the client's handshake to support virtual hosting unless it is
  543. // an IP address.
  544. ServerName string
  545. // ClientAuth determines the server's policy for
  546. // TLS Client Authentication. The default is NoClientCert.
  547. ClientAuth ClientAuthType
  548. // ClientCAs defines the set of root certificate authorities
  549. // that servers use if required to verify a client certificate
  550. // by the policy in ClientAuth.
  551. ClientCAs *x509.CertPool
  552. // InsecureSkipVerify controls whether a client verifies the server's
  553. // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
  554. // accepts any certificate presented by the server and any host name in that
  555. // certificate. In this mode, TLS is susceptible to machine-in-the-middle
  556. // attacks unless custom verification is used. This should be used only for
  557. // testing or in combination with VerifyConnection or VerifyPeerCertificate.
  558. InsecureSkipVerify bool
  559. // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
  560. // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
  561. //
  562. // If CipherSuites is nil, a safe default list is used. The default cipher
  563. // suites might change over time.
  564. CipherSuites []uint16
  565. // PreferServerCipherSuites is a legacy field and has no effect.
  566. //
  567. // It used to control whether the server would follow the client's or the
  568. // server's preference. Servers now select the best mutually supported
  569. // cipher suite based on logic that takes into account inferred client
  570. // hardware, server hardware, and security.
  571. //
  572. // Deprecated: PreferServerCipherSuites is ignored.
  573. PreferServerCipherSuites bool
  574. // SessionTicketsDisabled may be set to true to disable session ticket and
  575. // PSK (resumption) support. Note that on clients, session ticket support is
  576. // also disabled if ClientSessionCache is nil.
  577. SessionTicketsDisabled bool
  578. // SessionTicketKey is used by TLS servers to provide session resumption.
  579. // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
  580. // with random data before the first server handshake.
  581. //
  582. // Deprecated: if this field is left at zero, session ticket keys will be
  583. // automatically rotated every day and dropped after seven days. For
  584. // customizing the rotation schedule or synchronizing servers that are
  585. // terminating connections for the same host, use SetSessionTicketKeys.
  586. SessionTicketKey [32]byte
  587. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  588. // session resumption. It is only used by clients.
  589. ClientSessionCache ClientSessionCache
  590. // MinVersion contains the minimum TLS version that is acceptable.
  591. //
  592. // By default, TLS 1.2 is currently used as the minimum when acting as a
  593. // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum
  594. // supported by this package, both as a client and as a server.
  595. //
  596. // The client-side default can temporarily be reverted to TLS 1.0 by
  597. // including the value "x509sha1=1" in the GODEBUG environment variable.
  598. // Note that this option will be removed in Go 1.19 (but it will still be
  599. // possible to set this field to VersionTLS10 explicitly).
  600. MinVersion uint16
  601. // MaxVersion contains the maximum TLS version that is acceptable.
  602. //
  603. // By default, the maximum version supported by this package is used,
  604. // which is currently TLS 1.3.
  605. MaxVersion uint16
  606. // CurvePreferences contains the elliptic curves that will be used in
  607. // an ECDHE handshake, in preference order. If empty, the default will
  608. // be used. The client will use the first preference as the type for
  609. // its key share in TLS 1.3. This may change in the future.
  610. CurvePreferences []CurveID
  611. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  612. // When true, the largest possible TLS record size is always used. When
  613. // false, the size of TLS records may be adjusted in an attempt to
  614. // improve latency.
  615. DynamicRecordSizingDisabled bool
  616. // Renegotiation controls what types of renegotiation are supported.
  617. // The default, none, is correct for the vast majority of applications.
  618. Renegotiation RenegotiationSupport
  619. // KeyLogWriter optionally specifies a destination for TLS master secrets
  620. // in NSS key log format that can be used to allow external programs
  621. // such as Wireshark to decrypt TLS connections.
  622. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  623. // Use of KeyLogWriter compromises security and should only be
  624. // used for debugging.
  625. KeyLogWriter io.Writer
  626. SessionIDGenerator func(clientHello []byte, sessionID []byte) error
  627. // mutex protects sessionTicketKeys and autoSessionTicketKeys.
  628. mutex sync.RWMutex
  629. // sessionTicketKeys contains zero or more ticket keys. If set, it means the
  630. // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
  631. // first key is used for new tickets and any subsequent keys can be used to
  632. // decrypt old tickets. The slice contents are not protected by the mutex
  633. // and are immutable.
  634. sessionTicketKeys []ticketKey
  635. // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
  636. // auto-rotation logic. See Config.ticketKeys.
  637. autoSessionTicketKeys []ticketKey
  638. }
  639. const (
  640. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  641. // an encrypted session ticket in order to identify the key used to encrypt it.
  642. ticketKeyNameLen = 16
  643. // ticketKeyLifetime is how long a ticket key remains valid and can be used to
  644. // resume a client connection.
  645. ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
  646. // ticketKeyRotation is how often the server should rotate the session ticket key
  647. // that is used for new tickets.
  648. ticketKeyRotation = 24 * time.Hour
  649. )
  650. // ticketKey is the internal representation of a session ticket key.
  651. type ticketKey struct {
  652. // keyName is an opaque byte string that serves to identify the session
  653. // ticket key. It's exposed as plaintext in every session ticket.
  654. keyName [ticketKeyNameLen]byte
  655. aesKey [16]byte
  656. hmacKey [16]byte
  657. // created is the time at which this ticket key was created. See Config.ticketKeys.
  658. created time.Time
  659. }
  660. // ticketKeyFromBytes converts from the external representation of a session
  661. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  662. // bytes and this function expands that into sufficient name and key material.
  663. func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  664. hashed := sha512.Sum512(b[:])
  665. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  666. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  667. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  668. key.created = c.time()
  669. return key
  670. }
  671. // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
  672. // ticket, and the lifetime we set for tickets we send.
  673. const maxSessionTicketLifetime = 7 * 24 * time.Hour
  674. // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
  675. // being used concurrently by a TLS client or server.
  676. func (c *Config) Clone() *Config {
  677. if c == nil {
  678. return nil
  679. }
  680. c.mutex.RLock()
  681. defer c.mutex.RUnlock()
  682. return &Config{
  683. Rand: c.Rand,
  684. Time: c.Time,
  685. Certificates: c.Certificates,
  686. NameToCertificate: c.NameToCertificate,
  687. GetCertificate: c.GetCertificate,
  688. GetClientCertificate: c.GetClientCertificate,
  689. GetConfigForClient: c.GetConfigForClient,
  690. VerifyPeerCertificate: c.VerifyPeerCertificate,
  691. VerifyConnection: c.VerifyConnection,
  692. RootCAs: c.RootCAs,
  693. NextProtos: c.NextProtos,
  694. ServerName: c.ServerName,
  695. ClientAuth: c.ClientAuth,
  696. ClientCAs: c.ClientCAs,
  697. InsecureSkipVerify: c.InsecureSkipVerify,
  698. CipherSuites: c.CipherSuites,
  699. PreferServerCipherSuites: c.PreferServerCipherSuites,
  700. SessionTicketsDisabled: c.SessionTicketsDisabled,
  701. SessionTicketKey: c.SessionTicketKey,
  702. ClientSessionCache: c.ClientSessionCache,
  703. MinVersion: c.MinVersion,
  704. MaxVersion: c.MaxVersion,
  705. CurvePreferences: c.CurvePreferences,
  706. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  707. Renegotiation: c.Renegotiation,
  708. KeyLogWriter: c.KeyLogWriter,
  709. sessionTicketKeys: c.sessionTicketKeys,
  710. autoSessionTicketKeys: c.autoSessionTicketKeys,
  711. }
  712. }
  713. // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
  714. // randomized for backwards compatibility but is not in use.
  715. var deprecatedSessionTicketKey = []byte("DEPRECATED")
  716. // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
  717. // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
  718. func (c *Config) initLegacySessionTicketKeyRLocked() {
  719. // Don't write if SessionTicketKey is already defined as our deprecated string,
  720. // or if it is defined by the user but sessionTicketKeys is already set.
  721. if c.SessionTicketKey != [32]byte{} &&
  722. (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
  723. return
  724. }
  725. // We need to write some data, so get an exclusive lock and re-check any conditions.
  726. c.mutex.RUnlock()
  727. defer c.mutex.RLock()
  728. c.mutex.Lock()
  729. defer c.mutex.Unlock()
  730. if c.SessionTicketKey == [32]byte{} {
  731. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  732. panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
  733. }
  734. // Write the deprecated prefix at the beginning so we know we created
  735. // it. This key with the DEPRECATED prefix isn't used as an actual
  736. // session ticket key, and is only randomized in case the application
  737. // reuses it for some reason.
  738. copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
  739. } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
  740. c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
  741. }
  742. }
  743. // ticketKeys returns the ticketKeys for this connection.
  744. // If configForClient has explicitly set keys, those will
  745. // be returned. Otherwise, the keys on c will be used and
  746. // may be rotated if auto-managed.
  747. // During rotation, any expired session ticket keys are deleted from
  748. // c.sessionTicketKeys. If the session ticket key that is currently
  749. // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
  750. // is not fresh, then a new session ticket key will be
  751. // created and prepended to c.sessionTicketKeys.
  752. func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
  753. // If the ConfigForClient callback returned a Config with explicitly set
  754. // keys, use those, otherwise just use the original Config.
  755. if configForClient != nil {
  756. configForClient.mutex.RLock()
  757. if configForClient.SessionTicketsDisabled {
  758. return nil
  759. }
  760. configForClient.initLegacySessionTicketKeyRLocked()
  761. if len(configForClient.sessionTicketKeys) != 0 {
  762. ret := configForClient.sessionTicketKeys
  763. configForClient.mutex.RUnlock()
  764. return ret
  765. }
  766. configForClient.mutex.RUnlock()
  767. }
  768. c.mutex.RLock()
  769. defer c.mutex.RUnlock()
  770. if c.SessionTicketsDisabled {
  771. return nil
  772. }
  773. c.initLegacySessionTicketKeyRLocked()
  774. if len(c.sessionTicketKeys) != 0 {
  775. return c.sessionTicketKeys
  776. }
  777. // Fast path for the common case where the key is fresh enough.
  778. if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
  779. return c.autoSessionTicketKeys
  780. }
  781. // autoSessionTicketKeys are managed by auto-rotation.
  782. c.mutex.RUnlock()
  783. defer c.mutex.RLock()
  784. c.mutex.Lock()
  785. defer c.mutex.Unlock()
  786. // Re-check the condition in case it changed since obtaining the new lock.
  787. if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
  788. var newKey [32]byte
  789. if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
  790. panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
  791. }
  792. valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
  793. valid = append(valid, c.ticketKeyFromBytes(newKey))
  794. for _, k := range c.autoSessionTicketKeys {
  795. // While rotating the current key, also remove any expired ones.
  796. if c.time().Sub(k.created) < ticketKeyLifetime {
  797. valid = append(valid, k)
  798. }
  799. }
  800. c.autoSessionTicketKeys = valid
  801. }
  802. return c.autoSessionTicketKeys
  803. }
  804. // SetSessionTicketKeys updates the session ticket keys for a server.
  805. //
  806. // The first key will be used when creating new tickets, while all keys can be
  807. // used for decrypting tickets. It is safe to call this function while the
  808. // server is running in order to rotate the session ticket keys. The function
  809. // will panic if keys is empty.
  810. //
  811. // Calling this function will turn off automatic session ticket key rotation.
  812. //
  813. // If multiple servers are terminating connections for the same host they should
  814. // all have the same session ticket keys. If the session ticket keys leaks,
  815. // previously recorded and future TLS connections using those keys might be
  816. // compromised.
  817. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  818. if len(keys) == 0 {
  819. panic("tls: keys must have at least one key")
  820. }
  821. newKeys := make([]ticketKey, len(keys))
  822. for i, bytes := range keys {
  823. newKeys[i] = c.ticketKeyFromBytes(bytes)
  824. }
  825. c.mutex.Lock()
  826. c.sessionTicketKeys = newKeys
  827. c.mutex.Unlock()
  828. }
  829. func (c *Config) rand() io.Reader {
  830. r := c.Rand
  831. if r == nil {
  832. return rand.Reader
  833. }
  834. return r
  835. }
  836. func (c *Config) time() time.Time {
  837. t := c.Time
  838. if t == nil {
  839. t = time.Now
  840. }
  841. return t()
  842. }
  843. func (c *Config) cipherSuites() []uint16 {
  844. if needFIPS() {
  845. return fipsCipherSuites(c)
  846. }
  847. if c.CipherSuites != nil {
  848. return c.CipherSuites
  849. }
  850. return defaultCipherSuites
  851. }
  852. var supportedVersions = []uint16{
  853. VersionTLS13,
  854. VersionTLS12,
  855. VersionTLS11,
  856. VersionTLS10,
  857. }
  858. // roleClient and roleServer are meant to call supportedVersions and parents
  859. // with more readability at the callsite.
  860. const (
  861. roleClient = true
  862. roleServer = false
  863. )
  864. func (c *Config) supportedVersions(isClient bool) []uint16 {
  865. versions := make([]uint16, 0, len(supportedVersions))
  866. for _, v := range supportedVersions {
  867. if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
  868. continue
  869. }
  870. if (c == nil || c.MinVersion == 0) &&
  871. isClient && v < VersionTLS12 {
  872. continue
  873. }
  874. if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  875. continue
  876. }
  877. if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  878. continue
  879. }
  880. versions = append(versions, v)
  881. }
  882. return versions
  883. }
  884. func (c *Config) maxSupportedVersion(isClient bool) uint16 {
  885. supportedVersions := c.supportedVersions(isClient)
  886. if len(supportedVersions) == 0 {
  887. return 0
  888. }
  889. return supportedVersions[0]
  890. }
  891. // supportedVersionsFromMax returns a list of supported versions derived from a
  892. // legacy maximum version value. Note that only versions supported by this
  893. // library are returned. Any newer peer will use supportedVersions anyway.
  894. func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  895. versions := make([]uint16, 0, len(supportedVersions))
  896. for _, v := range supportedVersions {
  897. if v > maxVersion {
  898. continue
  899. }
  900. versions = append(versions, v)
  901. }
  902. return versions
  903. }
  904. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  905. func (c *Config) curvePreferences() []CurveID {
  906. if needFIPS() {
  907. return fipsCurvePreferences(c)
  908. }
  909. if c == nil || len(c.CurvePreferences) == 0 {
  910. return defaultCurvePreferences
  911. }
  912. return c.CurvePreferences
  913. }
  914. func (c *Config) supportsCurve(curve CurveID) bool {
  915. for _, cc := range c.curvePreferences() {
  916. if cc == curve {
  917. return true
  918. }
  919. }
  920. return false
  921. }
  922. // mutualVersion returns the protocol version to use given the advertised
  923. // versions of the peer. Priority is given to the peer preference order.
  924. func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
  925. supportedVersions := c.supportedVersions(isClient)
  926. for _, peerVersion := range peerVersions {
  927. for _, v := range supportedVersions {
  928. if v == peerVersion {
  929. return v, true
  930. }
  931. }
  932. }
  933. return 0, false
  934. }
  935. var errNoCertificates = errors.New("tls: no certificates configured")
  936. // getCertificate returns the best certificate for the given ClientHelloInfo,
  937. // defaulting to the first element of c.Certificates.
  938. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  939. if c.GetCertificate != nil &&
  940. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  941. cert, err := c.GetCertificate(clientHello)
  942. if cert != nil || err != nil {
  943. return cert, err
  944. }
  945. }
  946. if len(c.Certificates) == 0 {
  947. return nil, errNoCertificates
  948. }
  949. if len(c.Certificates) == 1 {
  950. // There's only one choice, so no point doing any work.
  951. return &c.Certificates[0], nil
  952. }
  953. if c.NameToCertificate != nil {
  954. name := strings.ToLower(clientHello.ServerName)
  955. if cert, ok := c.NameToCertificate[name]; ok {
  956. return cert, nil
  957. }
  958. if len(name) > 0 {
  959. labels := strings.Split(name, ".")
  960. labels[0] = "*"
  961. wildcardName := strings.Join(labels, ".")
  962. if cert, ok := c.NameToCertificate[wildcardName]; ok {
  963. return cert, nil
  964. }
  965. }
  966. }
  967. for _, cert := range c.Certificates {
  968. if err := clientHello.SupportsCertificate(&cert); err == nil {
  969. return &cert, nil
  970. }
  971. }
  972. // If nothing matches, return the first certificate.
  973. return &c.Certificates[0], nil
  974. }
  975. // SupportsCertificate returns nil if the provided certificate is supported by
  976. // the client that sent the ClientHello. Otherwise, it returns an error
  977. // describing the reason for the incompatibility.
  978. //
  979. // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
  980. // callback, this method will take into account the associated Config. Note that
  981. // if GetConfigForClient returns a different Config, the change can't be
  982. // accounted for by this method.
  983. //
  984. // This function will call x509.ParseCertificate unless c.Leaf is set, which can
  985. // incur a significant performance cost.
  986. func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
  987. // Note we don't currently support certificate_authorities nor
  988. // signature_algorithms_cert, and don't check the algorithms of the
  989. // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
  990. // Section 4.4.2.2).
  991. config := chi.config
  992. if config == nil {
  993. config = &Config{}
  994. }
  995. vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
  996. if !ok {
  997. return errors.New("no mutually supported protocol versions")
  998. }
  999. // If the client specified the name they are trying to connect to, the
  1000. // certificate needs to be valid for it.
  1001. if chi.ServerName != "" {
  1002. x509Cert, err := c.leaf()
  1003. if err != nil {
  1004. return fmt.Errorf("failed to parse certificate: %w", err)
  1005. }
  1006. if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
  1007. return fmt.Errorf("certificate is not valid for requested server name: %w", err)
  1008. }
  1009. }
  1010. // supportsRSAFallback returns nil if the certificate and connection support
  1011. // the static RSA key exchange, and unsupported otherwise. The logic for
  1012. // supporting static RSA is completely disjoint from the logic for
  1013. // supporting signed key exchanges, so we just check it as a fallback.
  1014. supportsRSAFallback := func(unsupported error) error {
  1015. // TLS 1.3 dropped support for the static RSA key exchange.
  1016. if vers == VersionTLS13 {
  1017. return unsupported
  1018. }
  1019. // The static RSA key exchange works by decrypting a challenge with the
  1020. // RSA private key, not by signing, so check the PrivateKey implements
  1021. // crypto.Decrypter, like *rsa.PrivateKey does.
  1022. if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
  1023. if _, ok := priv.Public().(*rsa.PublicKey); !ok {
  1024. return unsupported
  1025. }
  1026. } else {
  1027. return unsupported
  1028. }
  1029. // Finally, there needs to be a mutual cipher suite that uses the static
  1030. // RSA key exchange instead of ECDHE.
  1031. rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1032. if c.flags&suiteECDHE != 0 {
  1033. return false
  1034. }
  1035. if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1036. return false
  1037. }
  1038. return true
  1039. })
  1040. if rsaCipherSuite == nil {
  1041. return unsupported
  1042. }
  1043. return nil
  1044. }
  1045. // If the client sent the signature_algorithms extension, ensure it supports
  1046. // schemes we can use with this certificate and TLS version.
  1047. if len(chi.SignatureSchemes) > 0 {
  1048. if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
  1049. return supportsRSAFallback(err)
  1050. }
  1051. }
  1052. // In TLS 1.3 we are done because supported_groups is only relevant to the
  1053. // ECDHE computation, point format negotiation is removed, cipher suites are
  1054. // only relevant to the AEAD choice, and static RSA does not exist.
  1055. if vers == VersionTLS13 {
  1056. return nil
  1057. }
  1058. // The only signed key exchange we support is ECDHE.
  1059. if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
  1060. return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
  1061. }
  1062. var ecdsaCipherSuite bool
  1063. if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1064. switch pub := priv.Public().(type) {
  1065. case *ecdsa.PublicKey:
  1066. var curve CurveID
  1067. switch pub.Curve {
  1068. case elliptic.P256():
  1069. curve = CurveP256
  1070. case elliptic.P384():
  1071. curve = CurveP384
  1072. case elliptic.P521():
  1073. curve = CurveP521
  1074. default:
  1075. return supportsRSAFallback(unsupportedCertificateError(c))
  1076. }
  1077. var curveOk bool
  1078. for _, c := range chi.SupportedCurves {
  1079. if c == curve && config.supportsCurve(c) {
  1080. curveOk = true
  1081. break
  1082. }
  1083. }
  1084. if !curveOk {
  1085. return errors.New("client doesn't support certificate curve")
  1086. }
  1087. ecdsaCipherSuite = true
  1088. case ed25519.PublicKey:
  1089. if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1090. return errors.New("connection doesn't support Ed25519")
  1091. }
  1092. ecdsaCipherSuite = true
  1093. case *rsa.PublicKey:
  1094. default:
  1095. return supportsRSAFallback(unsupportedCertificateError(c))
  1096. }
  1097. } else {
  1098. return supportsRSAFallback(unsupportedCertificateError(c))
  1099. }
  1100. // Make sure that there is a mutually supported cipher suite that works with
  1101. // this certificate. Cipher suite selection will then apply the logic in
  1102. // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1103. cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1104. if c.flags&suiteECDHE == 0 {
  1105. return false
  1106. }
  1107. if c.flags&suiteECSign != 0 {
  1108. if !ecdsaCipherSuite {
  1109. return false
  1110. }
  1111. } else {
  1112. if ecdsaCipherSuite {
  1113. return false
  1114. }
  1115. }
  1116. if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1117. return false
  1118. }
  1119. return true
  1120. })
  1121. if cipherSuite == nil {
  1122. return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1123. }
  1124. return nil
  1125. }
  1126. // SupportsCertificate returns nil if the provided certificate is supported by
  1127. // the server that sent the CertificateRequest. Otherwise, it returns an error
  1128. // describing the reason for the incompatibility.
  1129. func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
  1130. if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
  1131. return err
  1132. }
  1133. if len(cri.AcceptableCAs) == 0 {
  1134. return nil
  1135. }
  1136. for j, cert := range c.Certificate {
  1137. x509Cert := c.Leaf
  1138. // Parse the certificate if this isn't the leaf node, or if
  1139. // chain.Leaf was nil.
  1140. if j != 0 || x509Cert == nil {
  1141. var err error
  1142. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  1143. return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
  1144. }
  1145. }
  1146. for _, ca := range cri.AcceptableCAs {
  1147. if bytes.Equal(x509Cert.RawIssuer, ca) {
  1148. return nil
  1149. }
  1150. }
  1151. }
  1152. return errors.New("chain is not signed by an acceptable CA")
  1153. }
  1154. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1155. // from the CommonName and SubjectAlternateName fields of each of the leaf
  1156. // certificates.
  1157. //
  1158. // Deprecated: NameToCertificate only allows associating a single certificate
  1159. // with a given name. Leave that field nil to let the library select the first
  1160. // compatible chain from Certificates.
  1161. func (c *Config) BuildNameToCertificate() {
  1162. c.NameToCertificate = make(map[string]*Certificate)
  1163. for i := range c.Certificates {
  1164. cert := &c.Certificates[i]
  1165. x509Cert, err := cert.leaf()
  1166. if err != nil {
  1167. continue
  1168. }
  1169. // If SANs are *not* present, some clients will consider the certificate
  1170. // valid for the name in the Common Name.
  1171. if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
  1172. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1173. }
  1174. for _, san := range x509Cert.DNSNames {
  1175. c.NameToCertificate[san] = cert
  1176. }
  1177. }
  1178. }
  1179. const (
  1180. keyLogLabelTLS12 = "CLIENT_RANDOM"
  1181. keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1182. keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1183. keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
  1184. keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
  1185. )
  1186. func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1187. if c.KeyLogWriter == nil {
  1188. return nil
  1189. }
  1190. logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
  1191. writerMutex.Lock()
  1192. _, err := c.KeyLogWriter.Write(logLine)
  1193. writerMutex.Unlock()
  1194. return err
  1195. }
  1196. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1197. // and is only for debugging, so a global mutex saves space.
  1198. var writerMutex sync.Mutex
  1199. // A Certificate is a chain of one or more certificates, leaf first.
  1200. type Certificate struct {
  1201. Certificate [][]byte
  1202. // PrivateKey contains the private key corresponding to the public key in
  1203. // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
  1204. // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
  1205. // an RSA PublicKey.
  1206. PrivateKey crypto.PrivateKey
  1207. // SupportedSignatureAlgorithms is an optional list restricting what
  1208. // signature algorithms the PrivateKey can be used for.
  1209. SupportedSignatureAlgorithms []SignatureScheme
  1210. // OCSPStaple contains an optional OCSP response which will be served
  1211. // to clients that request it.
  1212. OCSPStaple []byte
  1213. // SignedCertificateTimestamps contains an optional list of Signed
  1214. // Certificate Timestamps which will be served to clients that request it.
  1215. SignedCertificateTimestamps [][]byte
  1216. // Leaf is the parsed form of the leaf certificate, which may be initialized
  1217. // using x509.ParseCertificate to reduce per-handshake processing. If nil,
  1218. // the leaf certificate will be parsed as needed.
  1219. Leaf *x509.Certificate
  1220. }
  1221. // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1222. // the corresponding c.Certificate[0].
  1223. func (c *Certificate) leaf() (*x509.Certificate, error) {
  1224. if c.Leaf != nil {
  1225. return c.Leaf, nil
  1226. }
  1227. return x509.ParseCertificate(c.Certificate[0])
  1228. }
  1229. type handshakeMessage interface {
  1230. marshal() []byte
  1231. unmarshal([]byte) bool
  1232. }
  1233. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1234. // caching strategy.
  1235. type lruSessionCache struct {
  1236. sync.Mutex
  1237. m map[string]*list.Element
  1238. q *list.List
  1239. capacity int
  1240. }
  1241. type lruSessionCacheEntry struct {
  1242. sessionKey string
  1243. state *ClientSessionState
  1244. }
  1245. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  1246. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1247. // is used instead.
  1248. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1249. const defaultSessionCacheCapacity = 64
  1250. if capacity < 1 {
  1251. capacity = defaultSessionCacheCapacity
  1252. }
  1253. return &lruSessionCache{
  1254. m: make(map[string]*list.Element),
  1255. q: list.New(),
  1256. capacity: capacity,
  1257. }
  1258. }
  1259. // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1260. // corresponding to sessionKey is removed from the cache instead.
  1261. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1262. c.Lock()
  1263. defer c.Unlock()
  1264. if elem, ok := c.m[sessionKey]; ok {
  1265. if cs == nil {
  1266. c.q.Remove(elem)
  1267. delete(c.m, sessionKey)
  1268. } else {
  1269. entry := elem.Value.(*lruSessionCacheEntry)
  1270. entry.state = cs
  1271. c.q.MoveToFront(elem)
  1272. }
  1273. return
  1274. }
  1275. if c.q.Len() < c.capacity {
  1276. entry := &lruSessionCacheEntry{sessionKey, cs}
  1277. c.m[sessionKey] = c.q.PushFront(entry)
  1278. return
  1279. }
  1280. elem := c.q.Back()
  1281. entry := elem.Value.(*lruSessionCacheEntry)
  1282. delete(c.m, entry.sessionKey)
  1283. entry.sessionKey = sessionKey
  1284. entry.state = cs
  1285. c.q.MoveToFront(elem)
  1286. c.m[sessionKey] = elem
  1287. }
  1288. // Get returns the ClientSessionState value associated with a given key. It
  1289. // returns (nil, false) if no value is found.
  1290. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1291. c.Lock()
  1292. defer c.Unlock()
  1293. if elem, ok := c.m[sessionKey]; ok {
  1294. c.q.MoveToFront(elem)
  1295. return elem.Value.(*lruSessionCacheEntry).state, true
  1296. }
  1297. return nil, false
  1298. }
  1299. var emptyConfig Config
  1300. func defaultConfig() *Config {
  1301. return &emptyConfig
  1302. }
  1303. func unexpectedMessageError(wanted, got any) error {
  1304. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1305. }
  1306. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1307. for _, s := range supportedSignatureAlgorithms {
  1308. if s == sigAlg {
  1309. return true
  1310. }
  1311. }
  1312. return false
  1313. }