common.go 60 KB

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