common.go 53 KB

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