common.go 62 KB

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