common.go 63 KB

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