common.go 57 KB

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