common.go 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "bytes"
  7. "container/list"
  8. "context"
  9. "crypto"
  10. "crypto/ecdsa"
  11. "crypto/ed25519"
  12. "crypto/elliptic"
  13. "crypto/rand"
  14. "crypto/rsa"
  15. "crypto/sha512"
  16. "crypto/x509"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. const (
  26. VersionTLS10 = 0x0301
  27. VersionTLS11 = 0x0302
  28. VersionTLS12 = 0x0303
  29. VersionTLS13 = 0x0304
  30. // Deprecated: SSLv3 is cryptographically broken, and is no longer
  31. // supported by this package. See golang.org/issue/32716.
  32. VersionSSL30 = 0x0300
  33. )
  34. // VersionName returns the name for the provided TLS version number
  35. // (e.g. "TLS 1.3"), or a fallback representation of the value if the
  36. // version is not implemented by this package.
  37. func VersionName(version uint16) string {
  38. switch version {
  39. case VersionSSL30:
  40. return "SSLv3"
  41. case VersionTLS10:
  42. return "TLS 1.0"
  43. case VersionTLS11:
  44. return "TLS 1.1"
  45. case VersionTLS12:
  46. return "TLS 1.2"
  47. case VersionTLS13:
  48. return "TLS 1.3"
  49. default:
  50. return fmt.Sprintf("0x%04X", version)
  51. }
  52. }
  53. const (
  54. maxPlaintext = 16384 // maximum plaintext payload length
  55. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  56. maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
  57. recordHeaderLen = 5 // record header length
  58. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  59. maxUselessRecords = 32 // maximum number of consecutive non-advancing records
  60. )
  61. // TLS record types.
  62. type recordType uint8
  63. const (
  64. recordTypeChangeCipherSpec recordType = 20
  65. recordTypeAlert recordType = 21
  66. recordTypeHandshake recordType = 22
  67. recordTypeApplicationData recordType = 23
  68. )
  69. // TLS handshake message types.
  70. const (
  71. typeHelloRequest uint8 = 0
  72. typeClientHello uint8 = 1
  73. typeServerHello uint8 = 2
  74. typeNewSessionTicket uint8 = 4
  75. typeEndOfEarlyData uint8 = 5
  76. typeEncryptedExtensions uint8 = 8
  77. typeCertificate uint8 = 11
  78. typeServerKeyExchange uint8 = 12
  79. typeCertificateRequest uint8 = 13
  80. typeServerHelloDone uint8 = 14
  81. typeCertificateVerify uint8 = 15
  82. typeClientKeyExchange uint8 = 16
  83. typeFinished uint8 = 20
  84. typeCertificateStatus uint8 = 22
  85. typeKeyUpdate uint8 = 24
  86. typeNextProtocol uint8 = 67 // Not IANA assigned
  87. typeMessageHash uint8 = 254 // synthetic message
  88. )
  89. // TLS compression types.
  90. const (
  91. compressionNone uint8 = 0
  92. )
  93. // TLS extension numbers
  94. const (
  95. extensionServerName uint16 = 0
  96. extensionStatusRequest uint16 = 5
  97. extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
  98. extensionSupportedPoints uint16 = 11
  99. extensionSignatureAlgorithms uint16 = 13
  100. extensionALPN uint16 = 16
  101. extensionStatusRequestV2 uint16 = 17
  102. extensionSCT uint16 = 18
  103. extensionExtendedMasterSecret uint16 = 23
  104. extensionDelegatedCredentials uint16 = 34
  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. )
  117. // TLS signaling cipher suite values
  118. const (
  119. scsvRenegotiation uint16 = 0x00ff
  120. )
  121. // CurveID is the type of a TLS identifier for an elliptic curve. See
  122. // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
  123. //
  124. // In TLS 1.3, this type is called NamedGroup, but at this time this library
  125. // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
  126. type CurveID uint16
  127. const (
  128. CurveP256 CurveID = 23
  129. CurveP384 CurveID = 24
  130. CurveP521 CurveID = 25
  131. X25519 CurveID = 29
  132. )
  133. // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
  134. type keyShare struct {
  135. group CurveID
  136. data []byte
  137. }
  138. // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
  139. const (
  140. pskModePlain uint8 = 0
  141. pskModeDHE uint8 = 1
  142. )
  143. // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
  144. // session. See RFC 8446, Section 4.2.11.
  145. type pskIdentity struct {
  146. label []byte
  147. obfuscatedTicketAge uint32
  148. }
  149. // TLS Elliptic Curve Point Formats
  150. // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  151. const (
  152. pointFormatUncompressed uint8 = 0
  153. )
  154. // TLS CertificateStatusType (RFC 3546)
  155. const (
  156. statusTypeOCSP uint8 = 1
  157. statusV2TypeOCSP uint8 = 2
  158. )
  159. // Certificate types (for certificateRequestMsg)
  160. const (
  161. certTypeRSASign = 1
  162. certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
  163. )
  164. // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
  165. // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
  166. const (
  167. signaturePKCS1v15 uint8 = iota + 225
  168. signatureRSAPSS
  169. signatureECDSA
  170. signatureEd25519
  171. signatureEdDilithium3
  172. )
  173. // directSigning is a standard Hash value that signals that no pre-hashing
  174. // should be performed, and that the input should be signed directly. It is the
  175. // hash function associated with the Ed25519 signature scheme.
  176. var directSigning crypto.Hash = 0
  177. // defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that
  178. // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
  179. // CertificateRequest. The two fields are merged to match with TLS 1.3.
  180. // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
  181. var defaultSupportedSignatureAlgorithms = []SignatureScheme{
  182. PSSWithSHA256,
  183. ECDSAWithP256AndSHA256,
  184. Ed25519,
  185. PSSWithSHA384,
  186. PSSWithSHA512,
  187. PKCS1WithSHA256,
  188. PKCS1WithSHA384,
  189. PKCS1WithSHA512,
  190. ECDSAWithP384AndSHA384,
  191. ECDSAWithP521AndSHA512,
  192. PKCS1WithSHA1,
  193. ECDSAWithSHA1,
  194. }
  195. // helloRetryRequestRandom is set as the Random value of a ServerHello
  196. // to signal that the message is actually a HelloRetryRequest.
  197. var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
  198. 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
  199. 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
  200. 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
  201. 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
  202. }
  203. const (
  204. // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
  205. // random as a downgrade protection if the server would be capable of
  206. // negotiating a higher version. See RFC 8446, Section 4.1.3.
  207. downgradeCanaryTLS12 = "DOWNGRD\x01"
  208. downgradeCanaryTLS11 = "DOWNGRD\x00"
  209. )
  210. // testingOnlyForceDowngradeCanary is set in tests to force the server side to
  211. // include downgrade canaries even if it's using its highers supported version.
  212. var testingOnlyForceDowngradeCanary bool
  213. // [Psiphon]
  214. type ConnectionMetrics struct {
  215. // ClientSentTicket is true if the client has sent a TLS 1.2 session ticket
  216. // or a TLS 1.3 PSK in the ClientHello successfully.
  217. ClientSentTicket bool
  218. }
  219. // ConnectionState records basic TLS details about the connection.
  220. type ConnectionState struct {
  221. // Version is the TLS version used by the connection (e.g. VersionTLS12).
  222. Version uint16
  223. // HandshakeComplete is true if the handshake has concluded.
  224. HandshakeComplete bool
  225. // DidResume is true if this connection was successfully resumed from a
  226. // previous session with a session ticket or similar mechanism.
  227. DidResume bool
  228. // CipherSuite is the cipher suite negotiated for the connection (e.g.
  229. // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
  230. CipherSuite uint16
  231. // NegotiatedProtocol is the application protocol negotiated with ALPN.
  232. NegotiatedProtocol string
  233. // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
  234. //
  235. // Deprecated: this value is always true.
  236. NegotiatedProtocolIsMutual bool
  237. // PeerApplicationSettings is the Application-Layer Protocol Settings (ALPS)
  238. // provided by peer.
  239. PeerApplicationSettings []byte // [uTLS]
  240. // ServerName is the value of the Server Name Indication extension sent by
  241. // the client. It's available both on the server and on the client side.
  242. ServerName string
  243. // PeerCertificates are the parsed certificates sent by the peer, in the
  244. // order in which they were sent. The first element is the leaf certificate
  245. // that the connection is verified against.
  246. //
  247. // On the client side, it can't be empty. On the server side, it can be
  248. // empty if Config.ClientAuth is not RequireAnyClientCert or
  249. // RequireAndVerifyClientCert.
  250. //
  251. // PeerCertificates and its contents should not be modified.
  252. PeerCertificates []*x509.Certificate
  253. // VerifiedChains is a list of one or more chains where the first element is
  254. // PeerCertificates[0] and the last element is from Config.RootCAs (on the
  255. // client side) or Config.ClientCAs (on the server side).
  256. //
  257. // On the client side, it's set if Config.InsecureSkipVerify is false. On
  258. // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
  259. // (and the peer provided a certificate) or RequireAndVerifyClientCert.
  260. //
  261. // VerifiedChains and its contents should not be modified.
  262. VerifiedChains [][]*x509.Certificate
  263. // SignedCertificateTimestamps is a list of SCTs provided by the peer
  264. // through the TLS handshake for the leaf certificate, if any.
  265. SignedCertificateTimestamps [][]byte
  266. // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
  267. // response provided by the peer for the leaf certificate, if any.
  268. OCSPResponse []byte
  269. // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
  270. // Section 3). This value will be nil for TLS 1.3 connections and for
  271. // resumed connections that don't support Extended Master Secret (RFC 7627).
  272. TLSUnique []byte
  273. // ekm is a closure exposed via ExportKeyingMaterial.
  274. ekm func(label string, context []byte, length int) ([]byte, error)
  275. // ECHRetryConfigs contains the ECH retry configurations sent by the server in
  276. // EncryptedExtensions message. It is only populated if the server sent the
  277. // ech extension in EncryptedExtensions message.
  278. ECHRetryConfigs []ECHConfig // [uTLS]
  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 -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. // InsecureServerNameToVerify is used to verify the hostname on the returned
  616. // certificates. It is intended to use with spoofed ServerName.
  617. // If InsecureServerNameToVerify is "*", crypto/tls will do normal
  618. // certificate validation but ignore certifacate's DNSName.
  619. //
  620. // This field is ignored when InsecureSkipVerify is true.
  621. InsecureServerNameToVerify string // [uTLS]
  622. // PreferSkipResumptionOnNilExtension controls the behavior when session resumption is enabled but the corresponding session extensions are nil.
  623. //
  624. // To successfully use session resumption, ensure that the following requirements are met:
  625. // - SessionTicketsDisabled is set to false
  626. // - ClientSessionCache is non-nil
  627. // - For TLS 1.2, SessionTicketExtension is non-nil
  628. // - For TLS 1.3, PreSharedKeyExtension is non-nil
  629. //
  630. // 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.
  631. //
  632. // By default, utls throws an exception in such scenarios. Set this to true to skip the resumption and suppress the exception.
  633. PreferSkipResumptionOnNilExtension bool // [uTLS]
  634. // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
  635. // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
  636. //
  637. // If CipherSuites is nil, a safe default list is used. The default cipher
  638. // suites might change over time. In Go 1.22 RSA key exchange based cipher
  639. // suites were removed from the default list, but can be re-added with the
  640. // GODEBUG setting tlsrsakex=1.
  641. CipherSuites []uint16
  642. // PreferServerCipherSuites is a legacy field and has no effect.
  643. //
  644. // It used to control whether the server would follow the client's or the
  645. // server's preference. Servers now select the best mutually supported
  646. // cipher suite based on logic that takes into account inferred client
  647. // hardware, server hardware, and security.
  648. //
  649. // Deprecated: PreferServerCipherSuites is ignored.
  650. PreferServerCipherSuites bool
  651. // SessionTicketsDisabled may be set to true to disable session ticket and
  652. // PSK (resumption) support. Note that on clients, session ticket support is
  653. // also disabled if ClientSessionCache is nil.
  654. SessionTicketsDisabled bool
  655. // SessionTicketKey is used by TLS servers to provide session resumption.
  656. // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
  657. // with random data before the first server handshake.
  658. //
  659. // Deprecated: if this field is left at zero, session ticket keys will be
  660. // automatically rotated every day and dropped after seven days. For
  661. // customizing the rotation schedule or synchronizing servers that are
  662. // terminating connections for the same host, use SetSessionTicketKeys.
  663. SessionTicketKey [32]byte
  664. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  665. // session resumption. It is only used by clients.
  666. ClientSessionCache ClientSessionCache
  667. // UnwrapSession is called on the server to turn a ticket/identity
  668. // previously produced by [WrapSession] into a usable session.
  669. //
  670. // UnwrapSession will usually either decrypt a session state in the ticket
  671. // (for example with [Config.EncryptTicket]), or use the ticket as a handle
  672. // to recover a previously stored state. It must use [ParseSessionState] to
  673. // deserialize the session state.
  674. //
  675. // If UnwrapSession returns an error, the connection is terminated. If it
  676. // returns (nil, nil), the session is ignored. crypto/tls may still choose
  677. // not to resume the returned session.
  678. UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
  679. // WrapSession is called on the server to produce a session ticket/identity.
  680. //
  681. // WrapSession must serialize the session state with [SessionState.Bytes].
  682. // It may then encrypt the serialized state (for example with
  683. // [Config.DecryptTicket]) and use it as the ticket, or store the state and
  684. // return a handle for it.
  685. //
  686. // If WrapSession returns an error, the connection is terminated.
  687. //
  688. // Warning: the return value will be exposed on the wire and to clients in
  689. // plaintext. The application is in charge of encrypting and authenticating
  690. // it (and rotating keys) or returning high-entropy identifiers. Failing to
  691. // do so correctly can compromise current, previous, and future connections
  692. // depending on the protocol version.
  693. WrapSession func(ConnectionState, *SessionState) ([]byte, error)
  694. // MinVersion contains the minimum TLS version that is acceptable.
  695. //
  696. // By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the
  697. // minimum supported by this package.
  698. //
  699. // The server-side default can be reverted to TLS 1.0 by including the value
  700. // "tls10server=1" in the GODEBUG environment variable.
  701. MinVersion uint16
  702. // MaxVersion contains the maximum TLS version that is acceptable.
  703. //
  704. // By default, the maximum version supported by this package is used,
  705. // which is currently TLS 1.3.
  706. MaxVersion uint16
  707. // CurvePreferences contains the elliptic curves that will be used in
  708. // an ECDHE handshake, in preference order. If empty, the default will
  709. // be used. The client will use the first preference as the type for
  710. // its key share in TLS 1.3. This may change in the future.
  711. CurvePreferences []CurveID
  712. // PQSignatureSchemesEnabled controls whether additional post-quantum
  713. // signature schemes are supported for peer certificates. For available
  714. // signature schemes, see tls_cf.go.
  715. PQSignatureSchemesEnabled bool // [UTLS] ported from cloudflare/go
  716. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  717. // When true, the largest possible TLS record size is always used. When
  718. // false, the size of TLS records may be adjusted in an attempt to
  719. // improve latency.
  720. DynamicRecordSizingDisabled bool
  721. // Renegotiation controls what types of renegotiation are supported.
  722. // The default, none, is correct for the vast majority of applications.
  723. Renegotiation RenegotiationSupport
  724. // KeyLogWriter optionally specifies a destination for TLS master secrets
  725. // in NSS key log format that can be used to allow external programs
  726. // such as Wireshark to decrypt TLS connections.
  727. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  728. // Use of KeyLogWriter compromises security and should only be
  729. // used for debugging.
  730. KeyLogWriter io.Writer
  731. // mutex protects sessionTicketKeys and autoSessionTicketKeys.
  732. mutex sync.RWMutex
  733. // sessionTicketKeys contains zero or more ticket keys. If set, it means
  734. // the keys were set with SessionTicketKey or SetSessionTicketKeys. The
  735. // first key is used for new tickets and any subsequent keys can be used to
  736. // decrypt old tickets. The slice contents are not protected by the mutex
  737. // and are immutable.
  738. sessionTicketKeys []ticketKey
  739. // autoSessionTicketKeys is like sessionTicketKeys but is owned by the
  740. // auto-rotation logic. See Config.ticketKeys.
  741. autoSessionTicketKeys []ticketKey
  742. // ECHConfigs contains the ECH configurations to be used by the ECH
  743. // extension if any.
  744. // It could either be distributed by the server in EncryptedExtensions
  745. // message or out-of-band.
  746. //
  747. // If ECHConfigs is nil and an ECH extension is present, GREASEd ECH
  748. // extension will be sent.
  749. //
  750. // If GREASE ECH extension is present, this field will be ignored.
  751. ECHConfigs []ECHConfig // [uTLS]
  752. }
  753. const (
  754. // ticketKeyLifetime is how long a ticket key remains valid and can be used to
  755. // resume a client connection.
  756. ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
  757. // ticketKeyRotation is how often the server should rotate the session ticket key
  758. // that is used for new tickets.
  759. ticketKeyRotation = 24 * time.Hour
  760. )
  761. // ticketKey is the internal representation of a session ticket key.
  762. type ticketKey struct {
  763. aesKey [16]byte
  764. hmacKey [16]byte
  765. // created is the time at which this ticket key was created. See Config.ticketKeys.
  766. created time.Time
  767. }
  768. // ticketKeyFromBytes converts from the external representation of a session
  769. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  770. // bytes and this function expands that into sufficient name and key material.
  771. func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  772. hashed := sha512.Sum512(b[:])
  773. // The first 16 bytes of the hash used to be exposed on the wire as a ticket
  774. // prefix. They MUST NOT be used as a secret. In the future, it would make
  775. // sense to use a proper KDF here, like HKDF with a fixed salt.
  776. const legacyTicketKeyNameLen = 16
  777. copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:])
  778. copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):])
  779. key.created = c.time()
  780. return key
  781. }
  782. // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
  783. // ticket, and the lifetime we set for all tickets we send.
  784. const maxSessionTicketLifetime = 7 * 24 * time.Hour
  785. // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a [Config] that is
  786. // being used concurrently by a TLS client or server.
  787. func (c *Config) Clone() *Config {
  788. if c == nil {
  789. return nil
  790. }
  791. c.mutex.RLock()
  792. defer c.mutex.RUnlock()
  793. return &Config{
  794. Rand: c.Rand,
  795. Time: c.Time,
  796. Certificates: c.Certificates,
  797. NameToCertificate: c.NameToCertificate,
  798. GetCertificate: c.GetCertificate,
  799. GetClientCertificate: c.GetClientCertificate,
  800. GetConfigForClient: c.GetConfigForClient,
  801. VerifyPeerCertificate: c.VerifyPeerCertificate,
  802. VerifyConnection: c.VerifyConnection,
  803. RootCAs: c.RootCAs,
  804. NextProtos: c.NextProtos,
  805. ApplicationSettings: c.ApplicationSettings,
  806. ServerName: c.ServerName,
  807. ClientAuth: c.ClientAuth,
  808. ClientCAs: c.ClientCAs,
  809. InsecureSkipVerify: c.InsecureSkipVerify,
  810. InsecureSkipTimeVerify: c.InsecureSkipTimeVerify,
  811. InsecureServerNameToVerify: c.InsecureServerNameToVerify,
  812. OmitEmptyPsk: c.OmitEmptyPsk,
  813. CipherSuites: c.CipherSuites,
  814. PreferServerCipherSuites: c.PreferServerCipherSuites,
  815. SessionTicketsDisabled: c.SessionTicketsDisabled,
  816. SessionTicketKey: c.SessionTicketKey,
  817. ClientSessionCache: c.ClientSessionCache,
  818. UnwrapSession: c.UnwrapSession,
  819. WrapSession: c.WrapSession,
  820. MinVersion: c.MinVersion,
  821. MaxVersion: c.MaxVersion,
  822. CurvePreferences: c.CurvePreferences,
  823. PQSignatureSchemesEnabled: c.PQSignatureSchemesEnabled, // [UTLS]
  824. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  825. Renegotiation: c.Renegotiation,
  826. KeyLogWriter: c.KeyLogWriter,
  827. sessionTicketKeys: c.sessionTicketKeys,
  828. autoSessionTicketKeys: c.autoSessionTicketKeys,
  829. PreferSkipResumptionOnNilExtension: c.PreferSkipResumptionOnNilExtension, // [UTLS]
  830. ECHConfigs: c.ECHConfigs, // [uTLS]
  831. }
  832. }
  833. // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
  834. // randomized for backwards compatibility but is not in use.
  835. var deprecatedSessionTicketKey = []byte("DEPRECATED")
  836. // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
  837. // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
  838. func (c *Config) initLegacySessionTicketKeyRLocked() {
  839. // Don't write if SessionTicketKey is already defined as our deprecated string,
  840. // or if it is defined by the user but sessionTicketKeys is already set.
  841. if c.SessionTicketKey != [32]byte{} &&
  842. (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
  843. return
  844. }
  845. // We need to write some data, so get an exclusive lock and re-check any conditions.
  846. c.mutex.RUnlock()
  847. defer c.mutex.RLock()
  848. c.mutex.Lock()
  849. defer c.mutex.Unlock()
  850. if c.SessionTicketKey == [32]byte{} {
  851. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  852. panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
  853. }
  854. // Write the deprecated prefix at the beginning so we know we created
  855. // it. This key with the DEPRECATED prefix isn't used as an actual
  856. // session ticket key, and is only randomized in case the application
  857. // reuses it for some reason.
  858. copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
  859. } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
  860. c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
  861. }
  862. }
  863. // ticketKeys returns the ticketKeys for this connection.
  864. // If configForClient has explicitly set keys, those will
  865. // be returned. Otherwise, the keys on c will be used and
  866. // may be rotated if auto-managed.
  867. // During rotation, any expired session ticket keys are deleted from
  868. // c.sessionTicketKeys. If the session ticket key that is currently
  869. // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
  870. // is not fresh, then a new session ticket key will be
  871. // created and prepended to c.sessionTicketKeys.
  872. func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
  873. // If the ConfigForClient callback returned a Config with explicitly set
  874. // keys, use those, otherwise just use the original Config.
  875. if configForClient != nil {
  876. configForClient.mutex.RLock()
  877. if configForClient.SessionTicketsDisabled {
  878. return nil
  879. }
  880. configForClient.initLegacySessionTicketKeyRLocked()
  881. if len(configForClient.sessionTicketKeys) != 0 {
  882. ret := configForClient.sessionTicketKeys
  883. configForClient.mutex.RUnlock()
  884. return ret
  885. }
  886. configForClient.mutex.RUnlock()
  887. }
  888. c.mutex.RLock()
  889. defer c.mutex.RUnlock()
  890. if c.SessionTicketsDisabled {
  891. return nil
  892. }
  893. c.initLegacySessionTicketKeyRLocked()
  894. if len(c.sessionTicketKeys) != 0 {
  895. return c.sessionTicketKeys
  896. }
  897. // Fast path for the common case where the key is fresh enough.
  898. if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
  899. return c.autoSessionTicketKeys
  900. }
  901. // autoSessionTicketKeys are managed by auto-rotation.
  902. c.mutex.RUnlock()
  903. defer c.mutex.RLock()
  904. c.mutex.Lock()
  905. defer c.mutex.Unlock()
  906. // Re-check the condition in case it changed since obtaining the new lock.
  907. if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
  908. var newKey [32]byte
  909. if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
  910. panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
  911. }
  912. valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
  913. valid = append(valid, c.ticketKeyFromBytes(newKey))
  914. for _, k := range c.autoSessionTicketKeys {
  915. // While rotating the current key, also remove any expired ones.
  916. if c.time().Sub(k.created) < ticketKeyLifetime {
  917. valid = append(valid, k)
  918. }
  919. }
  920. c.autoSessionTicketKeys = valid
  921. }
  922. return c.autoSessionTicketKeys
  923. }
  924. // SetSessionTicketKeys updates the session ticket keys for a server.
  925. //
  926. // The first key will be used when creating new tickets, while all keys can be
  927. // used for decrypting tickets. It is safe to call this function while the
  928. // server is running in order to rotate the session ticket keys. The function
  929. // will panic if keys is empty.
  930. //
  931. // Calling this function will turn off automatic session ticket key rotation.
  932. //
  933. // If multiple servers are terminating connections for the same host they should
  934. // all have the same session ticket keys. If the session ticket keys leaks,
  935. // previously recorded and future TLS connections using those keys might be
  936. // compromised.
  937. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  938. if len(keys) == 0 {
  939. panic("tls: keys must have at least one key")
  940. }
  941. newKeys := make([]ticketKey, len(keys))
  942. for i, bytes := range keys {
  943. newKeys[i] = c.ticketKeyFromBytes(bytes)
  944. }
  945. c.mutex.Lock()
  946. c.sessionTicketKeys = newKeys
  947. c.mutex.Unlock()
  948. }
  949. func (c *Config) rand() io.Reader {
  950. r := c.Rand
  951. if r == nil {
  952. return rand.Reader
  953. }
  954. return r
  955. }
  956. func (c *Config) time() time.Time {
  957. t := c.Time
  958. if t == nil {
  959. t = time.Now
  960. }
  961. return t()
  962. }
  963. // var tlsrsakex = godebug.New("tlsrsakex") // [UTLS] unsupported
  964. func (c *Config) cipherSuites() []uint16 {
  965. if needFIPS() {
  966. return fipsCipherSuites(c)
  967. }
  968. if c.CipherSuites != nil {
  969. return c.CipherSuites
  970. }
  971. // [uTLS SECTION BEGIN]
  972. // Disable unsupported godebug package
  973. // if tlsrsakex.Value() == "1" {
  974. // return defaultCipherSuitesWithRSAKex
  975. // }
  976. // [uTLS SECTION END]
  977. return defaultCipherSuites
  978. }
  979. var supportedVersions = []uint16{
  980. VersionTLS13,
  981. VersionTLS12,
  982. VersionTLS11,
  983. VersionTLS10,
  984. }
  985. // roleClient and roleServer are meant to call supportedVersions and parents
  986. // with more readability at the callsite.
  987. const roleClient = true
  988. const roleServer = false
  989. // var tls10server = godebug.New("tls10server") // [UTLS] unsupported
  990. func (c *Config) supportedVersions(isClient bool) []uint16 {
  991. versions := make([]uint16, 0, len(supportedVersions))
  992. for _, v := range supportedVersions {
  993. if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) {
  994. continue
  995. }
  996. if (c == nil || c.MinVersion == 0) && v < VersionTLS12 {
  997. // [uTLS SECTION BEGIN]
  998. // Disable unsupported godebug package
  999. // if isClient || tls10server.Value() != "1" {
  1000. // continue
  1001. // }
  1002. if isClient {
  1003. continue
  1004. }
  1005. // [uTLS SECTION END]
  1006. }
  1007. if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  1008. continue
  1009. }
  1010. if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  1011. continue
  1012. }
  1013. versions = append(versions, v)
  1014. }
  1015. return versions
  1016. }
  1017. func (c *Config) maxSupportedVersion(isClient bool) uint16 {
  1018. supportedVersions := c.supportedVersions(isClient)
  1019. if len(supportedVersions) == 0 {
  1020. return 0
  1021. }
  1022. return supportedVersions[0]
  1023. }
  1024. // supportedVersionsFromMax returns a list of supported versions derived from a
  1025. // legacy maximum version value. Note that only versions supported by this
  1026. // library are returned. Any newer peer will use supportedVersions anyway.
  1027. func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  1028. versions := make([]uint16, 0, len(supportedVersions))
  1029. for _, v := range supportedVersions {
  1030. if v > maxVersion {
  1031. continue
  1032. }
  1033. versions = append(versions, v)
  1034. }
  1035. return versions
  1036. }
  1037. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  1038. func (c *Config) curvePreferences() []CurveID {
  1039. if needFIPS() {
  1040. return fipsCurvePreferences(c)
  1041. }
  1042. if c == nil || len(c.CurvePreferences) == 0 {
  1043. return defaultCurvePreferences
  1044. }
  1045. return c.CurvePreferences
  1046. }
  1047. func (c *Config) supportsCurve(curve CurveID) bool {
  1048. for _, cc := range c.curvePreferences() {
  1049. if cc == curve {
  1050. return true
  1051. }
  1052. }
  1053. return false
  1054. }
  1055. // mutualVersion returns the protocol version to use given the advertised
  1056. // versions of the peer. Priority is given to the peer preference order.
  1057. func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
  1058. supportedVersions := c.supportedVersions(isClient)
  1059. for _, peerVersion := range peerVersions {
  1060. for _, v := range supportedVersions {
  1061. if v == peerVersion {
  1062. return v, true
  1063. }
  1064. }
  1065. }
  1066. return 0, false
  1067. }
  1068. var errNoCertificates = errors.New("tls: no certificates configured")
  1069. // getCertificate returns the best certificate for the given ClientHelloInfo,
  1070. // defaulting to the first element of c.Certificates.
  1071. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  1072. if c.GetCertificate != nil &&
  1073. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  1074. cert, err := c.GetCertificate(clientHello)
  1075. if cert != nil || err != nil {
  1076. return cert, err
  1077. }
  1078. }
  1079. if len(c.Certificates) == 0 {
  1080. return nil, errNoCertificates
  1081. }
  1082. if len(c.Certificates) == 1 {
  1083. // There's only one choice, so no point doing any work.
  1084. return &c.Certificates[0], nil
  1085. }
  1086. if c.NameToCertificate != nil {
  1087. name := strings.ToLower(clientHello.ServerName)
  1088. if cert, ok := c.NameToCertificate[name]; ok {
  1089. return cert, nil
  1090. }
  1091. if len(name) > 0 {
  1092. labels := strings.Split(name, ".")
  1093. labels[0] = "*"
  1094. wildcardName := strings.Join(labels, ".")
  1095. if cert, ok := c.NameToCertificate[wildcardName]; ok {
  1096. return cert, nil
  1097. }
  1098. }
  1099. }
  1100. for _, cert := range c.Certificates {
  1101. if err := clientHello.SupportsCertificate(&cert); err == nil {
  1102. return &cert, nil
  1103. }
  1104. }
  1105. // If nothing matches, return the first certificate.
  1106. return &c.Certificates[0], nil
  1107. }
  1108. // SupportsCertificate returns nil if the provided certificate is supported by
  1109. // the client that sent the ClientHello. Otherwise, it returns an error
  1110. // describing the reason for the incompatibility.
  1111. //
  1112. // If this [ClientHelloInfo] was passed to a GetConfigForClient or GetCertificate
  1113. // callback, this method will take into account the associated [Config]. Note that
  1114. // if GetConfigForClient returns a different [Config], the change can't be
  1115. // accounted for by this method.
  1116. //
  1117. // This function will call x509.ParseCertificate unless c.Leaf is set, which can
  1118. // incur a significant performance cost.
  1119. func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
  1120. // Note we don't currently support certificate_authorities nor
  1121. // signature_algorithms_cert, and don't check the algorithms of the
  1122. // signatures on the chain (which anyway are a SHOULD, see RFC 8446,
  1123. // Section 4.4.2.2).
  1124. config := chi.config
  1125. if config == nil {
  1126. config = &Config{}
  1127. }
  1128. vers, ok := config.mutualVersion(roleServer, chi.SupportedVersions)
  1129. if !ok {
  1130. return errors.New("no mutually supported protocol versions")
  1131. }
  1132. // If the client specified the name they are trying to connect to, the
  1133. // certificate needs to be valid for it.
  1134. if chi.ServerName != "" {
  1135. x509Cert, err := c.leaf()
  1136. if err != nil {
  1137. return fmt.Errorf("failed to parse certificate: %w", err)
  1138. }
  1139. if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
  1140. return fmt.Errorf("certificate is not valid for requested server name: %w", err)
  1141. }
  1142. }
  1143. // supportsRSAFallback returns nil if the certificate and connection support
  1144. // the static RSA key exchange, and unsupported otherwise. The logic for
  1145. // supporting static RSA is completely disjoint from the logic for
  1146. // supporting signed key exchanges, so we just check it as a fallback.
  1147. supportsRSAFallback := func(unsupported error) error {
  1148. // TLS 1.3 dropped support for the static RSA key exchange.
  1149. if vers == VersionTLS13 {
  1150. return unsupported
  1151. }
  1152. // The static RSA key exchange works by decrypting a challenge with the
  1153. // RSA private key, not by signing, so check the PrivateKey implements
  1154. // crypto.Decrypter, like *rsa.PrivateKey does.
  1155. if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
  1156. if _, ok := priv.Public().(*rsa.PublicKey); !ok {
  1157. return unsupported
  1158. }
  1159. } else {
  1160. return unsupported
  1161. }
  1162. // Finally, there needs to be a mutual cipher suite that uses the static
  1163. // RSA key exchange instead of ECDHE.
  1164. rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1165. if c.flags&suiteECDHE != 0 {
  1166. return false
  1167. }
  1168. if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1169. return false
  1170. }
  1171. return true
  1172. })
  1173. if rsaCipherSuite == nil {
  1174. return unsupported
  1175. }
  1176. return nil
  1177. }
  1178. // If the client sent the signature_algorithms extension, ensure it supports
  1179. // schemes we can use with this certificate and TLS version.
  1180. if len(chi.SignatureSchemes) > 0 {
  1181. if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
  1182. return supportsRSAFallback(err)
  1183. }
  1184. }
  1185. // In TLS 1.3 we are done because supported_groups is only relevant to the
  1186. // ECDHE computation, point format negotiation is removed, cipher suites are
  1187. // only relevant to the AEAD choice, and static RSA does not exist.
  1188. if vers == VersionTLS13 {
  1189. return nil
  1190. }
  1191. // The only signed key exchange we support is ECDHE.
  1192. if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
  1193. return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
  1194. }
  1195. var ecdsaCipherSuite bool
  1196. if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1197. switch pub := priv.Public().(type) {
  1198. case *ecdsa.PublicKey:
  1199. var curve CurveID
  1200. switch pub.Curve {
  1201. case elliptic.P256():
  1202. curve = CurveP256
  1203. case elliptic.P384():
  1204. curve = CurveP384
  1205. case elliptic.P521():
  1206. curve = CurveP521
  1207. default:
  1208. return supportsRSAFallback(unsupportedCertificateError(c))
  1209. }
  1210. var curveOk bool
  1211. for _, c := range chi.SupportedCurves {
  1212. if c == curve && config.supportsCurve(c) {
  1213. curveOk = true
  1214. break
  1215. }
  1216. }
  1217. if !curveOk {
  1218. return errors.New("client doesn't support certificate curve")
  1219. }
  1220. ecdsaCipherSuite = true
  1221. case ed25519.PublicKey:
  1222. if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1223. return errors.New("connection doesn't support Ed25519")
  1224. }
  1225. ecdsaCipherSuite = true
  1226. case *rsa.PublicKey:
  1227. default:
  1228. return supportsRSAFallback(unsupportedCertificateError(c))
  1229. }
  1230. } else {
  1231. return supportsRSAFallback(unsupportedCertificateError(c))
  1232. }
  1233. // Make sure that there is a mutually supported cipher suite that works with
  1234. // this certificate. Cipher suite selection will then apply the logic in
  1235. // reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1236. cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
  1237. if c.flags&suiteECDHE == 0 {
  1238. return false
  1239. }
  1240. if c.flags&suiteECSign != 0 {
  1241. if !ecdsaCipherSuite {
  1242. return false
  1243. }
  1244. } else {
  1245. if ecdsaCipherSuite {
  1246. return false
  1247. }
  1248. }
  1249. if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1250. return false
  1251. }
  1252. return true
  1253. })
  1254. if cipherSuite == nil {
  1255. return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1256. }
  1257. return nil
  1258. }
  1259. // SupportsCertificate returns nil if the provided certificate is supported by
  1260. // the server that sent the CertificateRequest. Otherwise, it returns an error
  1261. // describing the reason for the incompatibility.
  1262. func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
  1263. if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
  1264. return err
  1265. }
  1266. if len(cri.AcceptableCAs) == 0 {
  1267. return nil
  1268. }
  1269. for j, cert := range c.Certificate {
  1270. x509Cert := c.Leaf
  1271. // Parse the certificate if this isn't the leaf node, or if
  1272. // chain.Leaf was nil.
  1273. if j != 0 || x509Cert == nil {
  1274. var err error
  1275. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  1276. return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
  1277. }
  1278. }
  1279. for _, ca := range cri.AcceptableCAs {
  1280. if bytes.Equal(x509Cert.RawIssuer, ca) {
  1281. return nil
  1282. }
  1283. }
  1284. }
  1285. return errors.New("chain is not signed by an acceptable CA")
  1286. }
  1287. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1288. // from the CommonName and SubjectAlternateName fields of each of the leaf
  1289. // certificates.
  1290. //
  1291. // Deprecated: NameToCertificate only allows associating a single certificate
  1292. // with a given name. Leave that field nil to let the library select the first
  1293. // compatible chain from Certificates.
  1294. func (c *Config) BuildNameToCertificate() {
  1295. c.NameToCertificate = make(map[string]*Certificate)
  1296. for i := range c.Certificates {
  1297. cert := &c.Certificates[i]
  1298. x509Cert, err := cert.leaf()
  1299. if err != nil {
  1300. continue
  1301. }
  1302. // If SANs are *not* present, some clients will consider the certificate
  1303. // valid for the name in the Common Name.
  1304. if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
  1305. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1306. }
  1307. for _, san := range x509Cert.DNSNames {
  1308. c.NameToCertificate[san] = cert
  1309. }
  1310. }
  1311. }
  1312. const (
  1313. keyLogLabelTLS12 = "CLIENT_RANDOM"
  1314. keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1315. keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1316. keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
  1317. keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
  1318. )
  1319. func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1320. if c.KeyLogWriter == nil {
  1321. return nil
  1322. }
  1323. logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret)
  1324. writerMutex.Lock()
  1325. _, err := c.KeyLogWriter.Write(logLine)
  1326. writerMutex.Unlock()
  1327. return err
  1328. }
  1329. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1330. // and is only for debugging, so a global mutex saves space.
  1331. var writerMutex sync.Mutex
  1332. // A Certificate is a chain of one or more certificates, leaf first.
  1333. type Certificate struct {
  1334. Certificate [][]byte
  1335. // PrivateKey contains the private key corresponding to the public key in
  1336. // Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
  1337. // For a server up to TLS 1.2, it can also implement crypto.Decrypter with
  1338. // an RSA PublicKey.
  1339. PrivateKey crypto.PrivateKey
  1340. // SupportedSignatureAlgorithms is an optional list restricting what
  1341. // signature algorithms the PrivateKey can be used for.
  1342. SupportedSignatureAlgorithms []SignatureScheme
  1343. // OCSPStaple contains an optional OCSP response which will be served
  1344. // to clients that request it.
  1345. OCSPStaple []byte
  1346. // SignedCertificateTimestamps contains an optional list of Signed
  1347. // Certificate Timestamps which will be served to clients that request it.
  1348. SignedCertificateTimestamps [][]byte
  1349. // Leaf is the parsed form of the leaf certificate, which may be initialized
  1350. // using x509.ParseCertificate to reduce per-handshake processing. If nil,
  1351. // the leaf certificate will be parsed as needed.
  1352. Leaf *x509.Certificate
  1353. }
  1354. // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1355. // the corresponding c.Certificate[0].
  1356. func (c *Certificate) leaf() (*x509.Certificate, error) {
  1357. if c.Leaf != nil {
  1358. return c.Leaf, nil
  1359. }
  1360. return x509.ParseCertificate(c.Certificate[0])
  1361. }
  1362. type handshakeMessage interface {
  1363. marshal() ([]byte, error)
  1364. unmarshal([]byte) bool
  1365. }
  1366. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1367. // caching strategy.
  1368. type lruSessionCache struct {
  1369. sync.Mutex
  1370. m map[string]*list.Element
  1371. q *list.List
  1372. capacity int
  1373. }
  1374. type lruSessionCacheEntry struct {
  1375. sessionKey string
  1376. state *ClientSessionState
  1377. }
  1378. // NewLRUClientSessionCache returns a [ClientSessionCache] with the given
  1379. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1380. // is used instead.
  1381. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1382. const defaultSessionCacheCapacity = 64
  1383. if capacity < 1 {
  1384. capacity = defaultSessionCacheCapacity
  1385. }
  1386. return &lruSessionCache{
  1387. m: make(map[string]*list.Element),
  1388. q: list.New(),
  1389. capacity: capacity,
  1390. }
  1391. }
  1392. // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1393. // corresponding to sessionKey is removed from the cache instead.
  1394. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1395. c.Lock()
  1396. defer c.Unlock()
  1397. if elem, ok := c.m[sessionKey]; ok {
  1398. if cs == nil {
  1399. c.q.Remove(elem)
  1400. delete(c.m, sessionKey)
  1401. } else {
  1402. entry := elem.Value.(*lruSessionCacheEntry)
  1403. entry.state = cs
  1404. c.q.MoveToFront(elem)
  1405. }
  1406. return
  1407. }
  1408. if c.q.Len() < c.capacity {
  1409. entry := &lruSessionCacheEntry{sessionKey, cs}
  1410. c.m[sessionKey] = c.q.PushFront(entry)
  1411. return
  1412. }
  1413. elem := c.q.Back()
  1414. entry := elem.Value.(*lruSessionCacheEntry)
  1415. delete(c.m, entry.sessionKey)
  1416. entry.sessionKey = sessionKey
  1417. entry.state = cs
  1418. c.q.MoveToFront(elem)
  1419. c.m[sessionKey] = elem
  1420. }
  1421. // Get returns the [ClientSessionState] value associated with a given key. It
  1422. // returns (nil, false) if no value is found.
  1423. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1424. c.Lock()
  1425. defer c.Unlock()
  1426. if elem, ok := c.m[sessionKey]; ok {
  1427. c.q.MoveToFront(elem)
  1428. return elem.Value.(*lruSessionCacheEntry).state, true
  1429. }
  1430. return nil, false
  1431. }
  1432. var emptyConfig Config
  1433. func defaultConfig() *Config {
  1434. return &emptyConfig
  1435. }
  1436. func unexpectedMessageError(wanted, got any) error {
  1437. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1438. }
  1439. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1440. for _, s := range supportedSignatureAlgorithms {
  1441. if s == sigAlg {
  1442. return true
  1443. }
  1444. }
  1445. return false
  1446. }
  1447. // CertificateVerificationError is returned when certificate verification fails during the handshake.
  1448. type CertificateVerificationError struct {
  1449. // UnverifiedCertificates and its contents should not be modified.
  1450. UnverifiedCertificates []*x509.Certificate
  1451. Err error
  1452. }
  1453. func (e *CertificateVerificationError) Error() string {
  1454. return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err)
  1455. }
  1456. func (e *CertificateVerificationError) Unwrap() error {
  1457. return e.Err
  1458. }