common.go 54 KB

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