common.go 55 KB

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