common.go 53 KB

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