common.go 58 KB

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