common.go 59 KB

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