common.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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. "container/list"
  7. "crypto"
  8. "crypto/rand"
  9. "crypto/sha512"
  10. "crypto/x509"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "math/big"
  15. "net"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  20. "github.com/Psiphon-Labs/tls-tris/cipherhw"
  21. )
  22. const (
  23. VersionSSL30 = 0x0300
  24. VersionTLS10 = 0x0301
  25. VersionTLS11 = 0x0302
  26. VersionTLS12 = 0x0303
  27. VersionTLS13 = 0x0304
  28. )
  29. const (
  30. maxPlaintext = 16384 // maximum plaintext payload length
  31. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  32. recordHeaderLen = 5 // record header length
  33. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  34. maxWarnAlertCount = 5 // maximum number of consecutive warning alerts
  35. minVersion = VersionTLS12
  36. maxVersion = VersionTLS13
  37. )
  38. // TLS record types.
  39. type recordType uint8
  40. const (
  41. recordTypeChangeCipherSpec recordType = 20
  42. recordTypeAlert recordType = 21
  43. recordTypeHandshake recordType = 22
  44. recordTypeApplicationData recordType = 23
  45. )
  46. // TLS handshake message types.
  47. const (
  48. typeHelloRequest uint8 = 0
  49. typeClientHello uint8 = 1
  50. typeServerHello uint8 = 2
  51. typeNewSessionTicket uint8 = 4
  52. typeEndOfEarlyData uint8 = 5
  53. typeEncryptedExtensions uint8 = 8
  54. typeCertificate uint8 = 11
  55. typeServerKeyExchange uint8 = 12
  56. typeCertificateRequest uint8 = 13
  57. typeServerHelloDone uint8 = 14
  58. typeCertificateVerify uint8 = 15
  59. typeClientKeyExchange uint8 = 16
  60. typeFinished uint8 = 20
  61. typeCertificateStatus uint8 = 22
  62. typeNextProtocol uint8 = 67 // Not IANA assigned
  63. )
  64. // TLS compression types.
  65. const (
  66. compressionNone uint8 = 0
  67. )
  68. // TLS extension numbers
  69. const (
  70. extensionServerName uint16 = 0
  71. extensionStatusRequest uint16 = 5
  72. extensionSupportedCurves uint16 = 10 // Supported Groups in 1.3 nomenclature
  73. extensionSupportedPoints uint16 = 11
  74. extensionSignatureAlgorithms uint16 = 13
  75. extensionALPN uint16 = 16
  76. extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
  77. extensionEMS uint16 = 23
  78. extensionSessionTicket uint16 = 35
  79. extensionPreSharedKey uint16 = 41
  80. extensionEarlyData uint16 = 42
  81. extensionSupportedVersions uint16 = 43
  82. extensionPSKKeyExchangeModes uint16 = 45
  83. extensionCAs uint16 = 47
  84. extensionSignatureAlgorithmsCert uint16 = 50
  85. extensionKeyShare uint16 = 51
  86. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  87. extensionRenegotiationInfo uint16 = 0xff01
  88. extensionDelegatedCredential uint16 = 0xff02 // TODO(any) Get IANA assignment
  89. )
  90. // TLS signaling cipher suite values
  91. const (
  92. scsvRenegotiation uint16 = 0x00ff
  93. )
  94. // PSK Key Exchange Modes
  95. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.7
  96. const (
  97. pskDHEKeyExchange uint8 = 1
  98. )
  99. // CurveID is the type of a TLS identifier for an elliptic curve. See
  100. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  101. //
  102. // TLS 1.3 refers to these as Groups, but this library implements only
  103. // curve-based ones anyway. See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.4.
  104. type CurveID uint16
  105. const (
  106. CurveP256 CurveID = 23
  107. CurveP384 CurveID = 24
  108. CurveP521 CurveID = 25
  109. X25519 CurveID = 29
  110. )
  111. // TLS 1.3 Key Share
  112. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
  113. type keyShare struct {
  114. group CurveID
  115. data []byte
  116. }
  117. // TLS 1.3 PSK Identity and Binder, as sent by the client
  118. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.6
  119. type psk struct {
  120. identity []byte
  121. obfTicketAge uint32
  122. binder []byte
  123. }
  124. // TLS Elliptic Curve Point Formats
  125. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  126. const (
  127. pointFormatUncompressed uint8 = 0
  128. )
  129. // TLS CertificateStatusType (RFC 3546)
  130. const (
  131. statusTypeOCSP uint8 = 1
  132. )
  133. // Certificate types (for certificateRequestMsg)
  134. const (
  135. certTypeRSASign = 1 // A certificate containing an RSA key
  136. certTypeDSSSign = 2 // A certificate containing a DSA key
  137. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  138. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  139. // See RFC 4492 sections 3 and 5.5.
  140. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  141. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  142. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  143. // Rest of these are reserved by the TLS spec
  144. )
  145. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  146. const (
  147. signaturePKCS1v15 uint8 = iota + 1
  148. signatureECDSA
  149. signatureRSAPSS
  150. )
  151. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  152. // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
  153. // CertificateRequest. The two fields are merged to match with TLS 1.3.
  154. // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
  155. var supportedSignatureAlgorithms = []SignatureScheme{
  156. PKCS1WithSHA256,
  157. ECDSAWithP256AndSHA256,
  158. PKCS1WithSHA384,
  159. ECDSAWithP384AndSHA384,
  160. PKCS1WithSHA512,
  161. ECDSAWithP521AndSHA512,
  162. PKCS1WithSHA1,
  163. ECDSAWithSHA1,
  164. }
  165. // supportedSignatureAlgorithms13 lists the advertised signature algorithms
  166. // allowed for digital signatures. It includes TLS 1.2 + PSS.
  167. var supportedSignatureAlgorithms13 = []SignatureScheme{
  168. PSSWithSHA256,
  169. PKCS1WithSHA256,
  170. ECDSAWithP256AndSHA256,
  171. PSSWithSHA384,
  172. PKCS1WithSHA384,
  173. ECDSAWithP384AndSHA384,
  174. PSSWithSHA512,
  175. PKCS1WithSHA512,
  176. ECDSAWithP521AndSHA512,
  177. PKCS1WithSHA1,
  178. ECDSAWithSHA1,
  179. }
  180. // ConnectionState records basic TLS details about the connection.
  181. type ConnectionState struct {
  182. ConnectionID []byte // Random unique connection id
  183. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  184. HandshakeComplete bool // TLS handshake is complete
  185. DidResume bool // connection resumes a previous TLS connection
  186. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  187. NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
  188. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
  189. ServerName string // server name requested by client, if any (server side only)
  190. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  191. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  192. SignedCertificateTimestamps [][]byte // SCTs from the server, if any
  193. OCSPResponse []byte // stapled OCSP response from server, if any
  194. DelegatedCredential []byte // Delegated credential sent by the server, if any
  195. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  196. // 5929, section 3). For resumed sessions this value will be nil
  197. // because resumption does not include enough context (see
  198. // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
  199. // change in future versions of Go once the TLS master-secret fix has
  200. // been standardized and implemented.
  201. TLSUnique []byte
  202. // HandshakeConfirmed is true once all data returned by Read
  203. // (past and future) is guaranteed not to be replayed.
  204. HandshakeConfirmed bool
  205. // Unique0RTTToken is a value that never repeats, and can be used
  206. // to detect replay attacks against 0-RTT connections.
  207. // Unique0RTTToken is only present if HandshakeConfirmed is false.
  208. Unique0RTTToken []byte
  209. ClientHello []byte // ClientHello packet
  210. }
  211. // ClientAuthType declares the policy the server will follow for
  212. // TLS Client Authentication.
  213. type ClientAuthType int
  214. const (
  215. NoClientCert ClientAuthType = iota
  216. RequestClientCert
  217. RequireAnyClientCert
  218. VerifyClientCertIfGiven
  219. RequireAndVerifyClientCert
  220. )
  221. // ClientSessionState contains the state needed by clients to resume TLS
  222. // sessions.
  223. type ClientSessionState struct {
  224. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  225. vers uint16 // SSL/TLS version negotiated for the session
  226. cipherSuite uint16 // Ciphersuite negotiated for the session
  227. masterSecret []byte // MasterSecret generated by client on a full handshake
  228. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  229. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  230. useEMS bool // State of extended master secret
  231. }
  232. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  233. // by a client to resume a TLS session with a given server. ClientSessionCache
  234. // implementations should expect to be called concurrently from different
  235. // goroutines. Only ticket-based resumption is supported, not SessionID-based
  236. // resumption.
  237. type ClientSessionCache interface {
  238. // Get searches for a ClientSessionState associated with the given key.
  239. // On return, ok is true if one was found.
  240. Get(sessionKey string) (session *ClientSessionState, ok bool)
  241. // Put adds the ClientSessionState to the cache with the given key.
  242. Put(sessionKey string, cs *ClientSessionState)
  243. }
  244. // SignatureScheme identifies a signature algorithm supported by TLS. See
  245. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
  246. type SignatureScheme uint16
  247. const (
  248. PKCS1WithSHA1 SignatureScheme = 0x0201
  249. PKCS1WithSHA256 SignatureScheme = 0x0401
  250. PKCS1WithSHA384 SignatureScheme = 0x0501
  251. PKCS1WithSHA512 SignatureScheme = 0x0601
  252. PSSWithSHA256 SignatureScheme = 0x0804
  253. PSSWithSHA384 SignatureScheme = 0x0805
  254. PSSWithSHA512 SignatureScheme = 0x0806
  255. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  256. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  257. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  258. // Legacy signature and hash algorithms for TLS 1.2.
  259. ECDSAWithSHA1 SignatureScheme = 0x0203
  260. )
  261. // ClientHelloInfo contains information from a ClientHello message in order to
  262. // guide certificate selection in the GetCertificate callback.
  263. type ClientHelloInfo struct {
  264. // CipherSuites lists the CipherSuites supported by the client (e.g.
  265. // TLS_RSA_WITH_RC4_128_SHA).
  266. CipherSuites []uint16
  267. // ServerName indicates the name of the server requested by the client
  268. // in order to support virtual hosting. ServerName is only set if the
  269. // client is using SNI (see
  270. // http://tools.ietf.org/html/rfc4366#section-3.1).
  271. ServerName string
  272. // SupportedCurves lists the elliptic curves supported by the client.
  273. // SupportedCurves is set only if the Supported Elliptic Curves
  274. // Extension is being used (see
  275. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  276. SupportedCurves []CurveID
  277. // SupportedPoints lists the point formats supported by the client.
  278. // SupportedPoints is set only if the Supported Point Formats Extension
  279. // is being used (see
  280. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  281. SupportedPoints []uint8
  282. // SignatureSchemes lists the signature and hash schemes that the client
  283. // is willing to verify. SignatureSchemes is set only if the Signature
  284. // Algorithms Extension is being used (see
  285. // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  286. SignatureSchemes []SignatureScheme
  287. // SupportedProtos lists the application protocols supported by the client.
  288. // SupportedProtos is set only if the Application-Layer Protocol
  289. // Negotiation Extension is being used (see
  290. // https://tools.ietf.org/html/rfc7301#section-3.1).
  291. //
  292. // Servers can select a protocol by setting Config.NextProtos in a
  293. // GetConfigForClient return value.
  294. SupportedProtos []string
  295. // SupportedVersions lists the TLS versions supported by the client.
  296. // For TLS versions less than 1.3, this is extrapolated from the max
  297. // version advertised by the client, so values other than the greatest
  298. // might be rejected if used.
  299. SupportedVersions []uint16
  300. // Conn is the underlying net.Conn for the connection. Do not read
  301. // from, or write to, this connection; that will cause the TLS
  302. // connection to fail.
  303. Conn net.Conn
  304. // Offered0RTTData is true if the client announced that it will send
  305. // 0-RTT data. If the server Config.Accept0RTTData is true, and the
  306. // client offered a session ticket valid for that purpose, it will
  307. // be notified that the 0-RTT data is accepted and it will be made
  308. // immediately available for Read.
  309. Offered0RTTData bool
  310. // AcceptsDelegatedCredential is true if the client indicated willingness
  311. // to negotiate the delegated credential extension.
  312. AcceptsDelegatedCredential bool
  313. // The Fingerprint is an sequence of bytes unique to this Client Hello.
  314. // It can be used to prevent or mitigate 0-RTT data replays as it's
  315. // guaranteed that a replayed connection will have the same Fingerprint.
  316. Fingerprint []byte
  317. }
  318. // CertificateRequestInfo contains information from a server's
  319. // CertificateRequest message, which is used to demand a certificate and proof
  320. // of control from a client.
  321. type CertificateRequestInfo struct {
  322. // AcceptableCAs contains zero or more, DER-encoded, X.501
  323. // Distinguished Names. These are the names of root or intermediate CAs
  324. // that the server wishes the returned certificate to be signed by. An
  325. // empty slice indicates that the server has no preference.
  326. AcceptableCAs [][]byte
  327. // SignatureSchemes lists the signature schemes that the server is
  328. // willing to verify.
  329. SignatureSchemes []SignatureScheme
  330. }
  331. // RenegotiationSupport enumerates the different levels of support for TLS
  332. // renegotiation. TLS renegotiation is the act of performing subsequent
  333. // handshakes on a connection after the first. This significantly complicates
  334. // the state machine and has been the source of numerous, subtle security
  335. // issues. Initiating a renegotiation is not supported, but support for
  336. // accepting renegotiation requests may be enabled.
  337. //
  338. // Even when enabled, the server may not change its identity between handshakes
  339. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  340. // handshake and application data flow is not permitted so renegotiation can
  341. // only be used with protocols that synchronise with the renegotiation, such as
  342. // HTTPS.
  343. type RenegotiationSupport int
  344. const (
  345. // RenegotiateNever disables renegotiation.
  346. RenegotiateNever RenegotiationSupport = iota
  347. // RenegotiateOnceAsClient allows a remote server to request
  348. // renegotiation once per connection.
  349. RenegotiateOnceAsClient
  350. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  351. // request renegotiation.
  352. RenegotiateFreelyAsClient
  353. )
  354. // A Config structure is used to configure a TLS client or server.
  355. // After one has been passed to a TLS function it must not be
  356. // modified. A Config may be reused; the tls package will also not
  357. // modify it.
  358. type Config struct {
  359. // Rand provides the source of entropy for nonces and RSA blinding.
  360. // If Rand is nil, TLS uses the cryptographic random reader in package
  361. // crypto/rand.
  362. // The Reader must be safe for use by multiple goroutines.
  363. Rand io.Reader
  364. // Time returns the current time as the number of seconds since the epoch.
  365. // If Time is nil, TLS uses time.Now.
  366. Time func() time.Time
  367. // Certificates contains one or more certificate chains to present to
  368. // the other side of the connection. Server configurations must include
  369. // at least one certificate or else set GetCertificate. Clients doing
  370. // client-authentication may set either Certificates or
  371. // GetClientCertificate.
  372. Certificates []Certificate
  373. // NameToCertificate maps from a certificate name to an element of
  374. // Certificates. Note that a certificate name can be of the form
  375. // '*.example.com' and so doesn't have to be a domain name as such.
  376. // See Config.BuildNameToCertificate
  377. // The nil value causes the first element of Certificates to be used
  378. // for all connections.
  379. NameToCertificate map[string]*Certificate
  380. // GetCertificate returns a Certificate based on the given
  381. // ClientHelloInfo. It will only be called if the client supplies SNI
  382. // information or if Certificates is empty.
  383. //
  384. // If GetCertificate is nil or returns nil, then the certificate is
  385. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  386. // first element of Certificates will be used.
  387. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  388. // GetClientCertificate, if not nil, is called when a server requests a
  389. // certificate from a client. If set, the contents of Certificates will
  390. // be ignored.
  391. //
  392. // If GetClientCertificate returns an error, the handshake will be
  393. // aborted and that error will be returned. Otherwise
  394. // GetClientCertificate must return a non-nil Certificate. If
  395. // Certificate.Certificate is empty then no certificate will be sent to
  396. // the server. If this is unacceptable to the server then it may abort
  397. // the handshake.
  398. //
  399. // GetClientCertificate may be called multiple times for the same
  400. // connection if renegotiation occurs or if TLS 1.3 is in use.
  401. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  402. // GetConfigForClient, if not nil, is called after a ClientHello is
  403. // received from a client. It may return a non-nil Config in order to
  404. // change the Config that will be used to handle this connection. If
  405. // the returned Config is nil, the original Config will be used. The
  406. // Config returned by this callback may not be subsequently modified.
  407. //
  408. // If GetConfigForClient is nil, the Config passed to Server() will be
  409. // used for all connections.
  410. //
  411. // Uniquely for the fields in the returned Config, session ticket keys
  412. // will be duplicated from the original Config if not set.
  413. // Specifically, if SetSessionTicketKeys was called on the original
  414. // config but not on the returned config then the ticket keys from the
  415. // original config will be copied into the new config before use.
  416. // Otherwise, if SessionTicketKey was set in the original config but
  417. // not in the returned config then it will be copied into the returned
  418. // config before use. If neither of those cases applies then the key
  419. // material from the returned config will be used for session tickets.
  420. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  421. // VerifyPeerCertificate, if not nil, is called after normal
  422. // certificate verification by either a TLS client or server. It
  423. // receives the raw ASN.1 certificates provided by the peer and also
  424. // any verified chains that normal processing found. If it returns a
  425. // non-nil error, the handshake is aborted and that error results.
  426. //
  427. // If normal verification fails then the handshake will abort before
  428. // considering this callback. If normal verification is disabled by
  429. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  430. // RequestClientCert or RequireAnyClientCert, then this callback will
  431. // be considered but the verifiedChains argument will always be nil.
  432. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  433. // RootCAs defines the set of root certificate authorities
  434. // that clients use when verifying server certificates.
  435. // If RootCAs is nil, TLS uses the host's root CA set.
  436. RootCAs *x509.CertPool
  437. // NextProtos is a list of supported, application level protocols.
  438. NextProtos []string
  439. // ServerName is used to verify the hostname on the returned
  440. // certificates unless InsecureSkipVerify is given. It is also included
  441. // in the client's handshake to support virtual hosting unless it is
  442. // an IP address.
  443. ServerName string
  444. // ClientAuth determines the server's policy for
  445. // TLS Client Authentication. The default is NoClientCert.
  446. ClientAuth ClientAuthType
  447. // ClientCAs defines the set of root certificate authorities
  448. // that servers use if required to verify a client certificate
  449. // by the policy in ClientAuth.
  450. ClientCAs *x509.CertPool
  451. // InsecureSkipVerify controls whether a client verifies the
  452. // server's certificate chain and host name.
  453. // If InsecureSkipVerify is true, TLS accepts any certificate
  454. // presented by the server and any host name in that certificate.
  455. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  456. // This should be used only for testing.
  457. InsecureSkipVerify bool
  458. // CipherSuites is a list of supported cipher suites to be used in
  459. // TLS 1.0-1.2. If CipherSuites is nil, TLS uses a list of suites
  460. // supported by the implementation.
  461. CipherSuites []uint16
  462. // PreferServerCipherSuites controls whether the server selects the
  463. // client's most preferred ciphersuite, or the server's most preferred
  464. // ciphersuite. If true then the server's preference, as expressed in
  465. // the order of elements in CipherSuites, is used.
  466. PreferServerCipherSuites bool
  467. // SessionTicketsDisabled may be set to true to disable session ticket
  468. // (resumption) support.
  469. SessionTicketsDisabled bool
  470. // SessionTicketKey is used by TLS servers to provide session
  471. // resumption. See RFC 5077. If zero, it will be filled with
  472. // random data before the first server handshake.
  473. //
  474. // If multiple servers are terminating connections for the same host
  475. // they should all have the same SessionTicketKey. If the
  476. // SessionTicketKey leaks, previously recorded and future TLS
  477. // connections using that key are compromised.
  478. SessionTicketKey [32]byte
  479. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  480. // session resumption.
  481. ClientSessionCache ClientSessionCache
  482. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  483. // If zero, then TLS 1.0 is taken as the minimum.
  484. MinVersion uint16
  485. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  486. // If zero, then the maximum version supported by this package is used,
  487. // which is currently TLS 1.2.
  488. MaxVersion uint16
  489. // CurvePreferences contains the elliptic curves that will be used in
  490. // an ECDHE handshake, in preference order. If empty, the default will
  491. // be used.
  492. CurvePreferences []CurveID
  493. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  494. // When true, the largest possible TLS record size is always used. When
  495. // false, the size of TLS records may be adjusted in an attempt to
  496. // improve latency.
  497. DynamicRecordSizingDisabled bool
  498. // Renegotiation controls what types of renegotiation are supported.
  499. // The default, none, is correct for the vast majority of applications.
  500. Renegotiation RenegotiationSupport
  501. // KeyLogWriter optionally specifies a destination for TLS master secrets
  502. // in NSS key log format that can be used to allow external programs
  503. // such as Wireshark to decrypt TLS connections.
  504. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  505. // Use of KeyLogWriter compromises security and should only be
  506. // used for debugging.
  507. KeyLogWriter io.Writer
  508. // If Max0RTTDataSize is not zero, the client will be allowed to use
  509. // session tickets to send at most this number of bytes of 0-RTT data.
  510. // 0-RTT data is subject to replay and has memory DoS implications.
  511. // The server will later be able to refuse the 0-RTT data with
  512. // Accept0RTTData, or wait for the client to prove that it's not
  513. // replayed with Conn.ConfirmHandshake.
  514. //
  515. // It has no meaning on the client.
  516. //
  517. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  518. Max0RTTDataSize uint32
  519. // Accept0RTTData makes the 0-RTT data received from the client
  520. // immediately available to Read. 0-RTT data is subject to replay.
  521. // Use Conn.ConfirmHandshake to wait until the data is known not
  522. // to be replayed after reading it.
  523. //
  524. // It has no meaning on the client.
  525. //
  526. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  527. Accept0RTTData bool
  528. // SessionTicketSealer, if not nil, is used to wrap and unwrap
  529. // session tickets, instead of SessionTicketKey.
  530. SessionTicketSealer SessionTicketSealer
  531. // AcceptDelegatedCredential is true if the client is willing to negotiate
  532. // the delegated credential extension.
  533. //
  534. // This value has no meaning for the server.
  535. //
  536. // See https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.
  537. AcceptDelegatedCredential bool
  538. // GetDelegatedCredential returns a DC and its private key for use in the
  539. // delegated credential extension. The inputs to the callback are some
  540. // information parsed from the ClientHello, as well as the protocol version
  541. // selected by the server. This is necessary because the DC is bound to the
  542. // protocol version in which it's used. The return value is the raw DC
  543. // encoded in the wire format specified in
  544. // https://tools.ietf.org/html/draft-ietf-tls-subcerts-02. If the return
  545. // value is nil, then the server will not offer negotiate the extension.
  546. //
  547. // This value has no meaning for the client.
  548. GetDelegatedCredential func(*ClientHelloInfo, uint16) ([]byte, crypto.PrivateKey, error)
  549. serverInitOnce sync.Once // guards calling (*Config).serverInit
  550. // mutex protects sessionTicketKeys.
  551. mutex sync.RWMutex
  552. // sessionTicketKeys contains zero or more ticket keys. If the length
  553. // is zero, SessionTicketsDisabled must be true. The first key is used
  554. // for new tickets and any subsequent keys can be used to decrypt old
  555. // tickets.
  556. sessionTicketKeys []ticketKey
  557. // UseExtendedMasterSecret indicates whether or not the connection
  558. // should use the extended master secret computation if available
  559. UseExtendedMasterSecret bool
  560. // [Psiphon]
  561. // ClientHelloPRNGSeed is a seeded PRNG which allows for optional replay of
  562. // same randomized Client Hello.
  563. ClientHelloPRNGSeed *prng.Seed
  564. // [Psiphon]
  565. // UseObfuscatedSessionTickets should be set when using obfuscated session
  566. // tickets. This setting ensures that checkForResumption operates in a way
  567. // that is compatible with the obfuscated session ticket scheme.
  568. //
  569. // This flag doesn't fully configure obfuscated session tickets.
  570. // SessionTicketKey and SetSessionTicketKeys must also be intialized. See the
  571. // setup in psiphon/server.MeekServer.makeMeekTLSConfig.
  572. //
  573. // See the comment for NewObfuscatedClientSessionState for more details on
  574. // obfuscated session tickets.
  575. UseObfuscatedSessionTickets bool
  576. // [Psiphon]
  577. // PassthroughAddress, when not blank, enables passthrough mode. It is a
  578. // network address, host and port, to which client traffic is relayed when
  579. // the client fails anti-probing tests.
  580. //
  581. // The PassthroughAddress is expected to be a TCP endpoint. Passthrough is
  582. // triggered when a ClientHello random field doesn't have a valid value, as
  583. // determined by PassthroughKey.
  584. PassthroughAddress string
  585. // [Psiphon]
  586. // PassthroughKey must be set, to a value generated by
  587. // obfuscator.DerivePassthroughKey, when passthrough mode is enabled.
  588. PassthroughKey []byte
  589. // [Psiphon]
  590. // PassthroughHistoryAddNew must be set when passthough mode is enabled. The
  591. // function should check that a ClientHello random value has not been
  592. // previously observed, returning true only for a newly observed value. Any
  593. // logging is the callback's responsibility.
  594. PassthroughHistoryAddNew func(
  595. clientIP string,
  596. clientRandom []byte) bool
  597. // [Psiphon]
  598. // PassthroughLogInvalidMessage must be set when passthough mode is enabled.
  599. // The function should log an invalid ClientHello random value event.
  600. PassthroughLogInvalidMessage func(clientIP string)
  601. }
  602. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  603. // an encrypted session ticket in order to identify the key used to encrypt it.
  604. const ticketKeyNameLen = 16
  605. // ticketKey is the internal representation of a session ticket key.
  606. type ticketKey struct {
  607. // keyName is an opaque byte string that serves to identify the session
  608. // ticket key. It's exposed as plaintext in every session ticket.
  609. keyName [ticketKeyNameLen]byte
  610. aesKey [16]byte
  611. hmacKey [16]byte
  612. }
  613. // ticketKeyFromBytes converts from the external representation of a session
  614. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  615. // bytes and this function expands that into sufficient name and key material.
  616. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  617. hashed := sha512.Sum512(b[:])
  618. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  619. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  620. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  621. return key
  622. }
  623. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  624. // being used concurrently by a TLS client or server.
  625. func (c *Config) Clone() *Config {
  626. // Running serverInit ensures that it's safe to read
  627. // SessionTicketsDisabled.
  628. c.serverInitOnce.Do(func() { c.serverInit(nil) })
  629. var sessionTicketKeys []ticketKey
  630. c.mutex.RLock()
  631. sessionTicketKeys = c.sessionTicketKeys
  632. c.mutex.RUnlock()
  633. return &Config{
  634. Rand: c.Rand,
  635. Time: c.Time,
  636. Certificates: c.Certificates,
  637. NameToCertificate: c.NameToCertificate,
  638. GetCertificate: c.GetCertificate,
  639. GetClientCertificate: c.GetClientCertificate,
  640. GetConfigForClient: c.GetConfigForClient,
  641. VerifyPeerCertificate: c.VerifyPeerCertificate,
  642. RootCAs: c.RootCAs,
  643. NextProtos: c.NextProtos,
  644. ServerName: c.ServerName,
  645. ClientAuth: c.ClientAuth,
  646. ClientCAs: c.ClientCAs,
  647. InsecureSkipVerify: c.InsecureSkipVerify,
  648. CipherSuites: c.CipherSuites,
  649. PreferServerCipherSuites: c.PreferServerCipherSuites,
  650. SessionTicketsDisabled: c.SessionTicketsDisabled,
  651. SessionTicketKey: c.SessionTicketKey,
  652. ClientSessionCache: c.ClientSessionCache,
  653. MinVersion: c.MinVersion,
  654. MaxVersion: c.MaxVersion,
  655. CurvePreferences: c.CurvePreferences,
  656. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  657. Renegotiation: c.Renegotiation,
  658. KeyLogWriter: c.KeyLogWriter,
  659. Accept0RTTData: c.Accept0RTTData,
  660. Max0RTTDataSize: c.Max0RTTDataSize,
  661. SessionTicketSealer: c.SessionTicketSealer,
  662. AcceptDelegatedCredential: c.AcceptDelegatedCredential,
  663. GetDelegatedCredential: c.GetDelegatedCredential,
  664. sessionTicketKeys: sessionTicketKeys,
  665. UseExtendedMasterSecret: c.UseExtendedMasterSecret,
  666. }
  667. }
  668. // serverInit is run under c.serverInitOnce to do initialization of c. If c was
  669. // returned by a GetConfigForClient callback then the argument should be the
  670. // Config that was passed to Server, otherwise it should be nil.
  671. func (c *Config) serverInit(originalConfig *Config) {
  672. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 || c.SessionTicketSealer != nil {
  673. return
  674. }
  675. alreadySet := false
  676. for _, b := range c.SessionTicketKey {
  677. if b != 0 {
  678. alreadySet = true
  679. break
  680. }
  681. }
  682. if !alreadySet {
  683. if originalConfig != nil {
  684. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  685. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  686. c.SessionTicketsDisabled = true
  687. return
  688. }
  689. }
  690. if originalConfig != nil {
  691. originalConfig.mutex.RLock()
  692. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  693. originalConfig.mutex.RUnlock()
  694. } else {
  695. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  696. }
  697. }
  698. func (c *Config) ticketKeys() []ticketKey {
  699. c.mutex.RLock()
  700. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  701. // will only update it by replacing it with a new value.
  702. ret := c.sessionTicketKeys
  703. c.mutex.RUnlock()
  704. return ret
  705. }
  706. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  707. // key will be used when creating new tickets, while all keys can be used for
  708. // decrypting tickets. It is safe to call this function while the server is
  709. // running in order to rotate the session ticket keys. The function will panic
  710. // if keys is empty.
  711. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  712. if len(keys) == 0 {
  713. panic("tls: keys must have at least one key")
  714. }
  715. newKeys := make([]ticketKey, len(keys))
  716. for i, bytes := range keys {
  717. newKeys[i] = ticketKeyFromBytes(bytes)
  718. }
  719. c.mutex.Lock()
  720. c.sessionTicketKeys = newKeys
  721. c.mutex.Unlock()
  722. }
  723. func (c *Config) rand() io.Reader {
  724. r := c.Rand
  725. if r == nil {
  726. return rand.Reader
  727. }
  728. return r
  729. }
  730. func (c *Config) time() time.Time {
  731. t := c.Time
  732. if t == nil {
  733. t = time.Now
  734. }
  735. return t()
  736. }
  737. func hasOverlappingCipherSuites(cs1, cs2 []uint16) bool {
  738. for _, c1 := range cs1 {
  739. for _, c2 := range cs2 {
  740. if c1 == c2 {
  741. return true
  742. }
  743. }
  744. }
  745. return false
  746. }
  747. func (c *Config) cipherSuites() []uint16 {
  748. s := c.CipherSuites
  749. if s == nil {
  750. s = defaultCipherSuites()
  751. } else if c.maxVersion() >= VersionTLS13 {
  752. // Ensure that TLS 1.3 suites are always present, but respect
  753. // the application cipher suite preferences.
  754. s13 := defaultTLS13CipherSuites()
  755. if !hasOverlappingCipherSuites(s, s13) {
  756. allSuites := make([]uint16, len(s13)+len(s))
  757. allSuites = append(allSuites, s13...)
  758. s = append(allSuites, s...)
  759. }
  760. }
  761. return s
  762. }
  763. func (c *Config) minVersion() uint16 {
  764. if c == nil || c.MinVersion == 0 {
  765. return minVersion
  766. }
  767. return c.MinVersion
  768. }
  769. func (c *Config) maxVersion() uint16 {
  770. if c == nil || c.MaxVersion == 0 {
  771. return maxVersion
  772. }
  773. return c.MaxVersion
  774. }
  775. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  776. func (c *Config) curvePreferences() []CurveID {
  777. if c == nil || len(c.CurvePreferences) == 0 {
  778. return defaultCurvePreferences
  779. }
  780. return c.CurvePreferences
  781. }
  782. // mutualVersion returns the protocol version to use given the advertised
  783. // version of the peer using the legacy non-extension methods.
  784. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  785. minVersion := c.minVersion()
  786. maxVersion := c.maxVersion()
  787. // Version 1.3 and higher are not negotiated via this mechanism.
  788. if maxVersion > VersionTLS12 {
  789. maxVersion = VersionTLS12
  790. }
  791. if vers < minVersion {
  792. return 0, false
  793. }
  794. if vers > maxVersion {
  795. vers = maxVersion
  796. }
  797. return vers, true
  798. }
  799. // pickVersion returns the protocol version to use given the advertised
  800. // versions of the peer using the Supported Versions extension.
  801. func (c *Config) pickVersion(peerSupportedVersions []uint16) (uint16, bool) {
  802. supportedVersions := c.getSupportedVersions()
  803. for _, supportedVersion := range supportedVersions {
  804. for _, version := range peerSupportedVersions {
  805. if version == supportedVersion {
  806. return version, true
  807. }
  808. }
  809. }
  810. return 0, false
  811. }
  812. // configSuppVersArray is the backing array of Config.getSupportedVersions
  813. var configSuppVersArray = [...]uint16{VersionTLS13, VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  814. // getSupportedVersions returns the protocol versions that are supported by the
  815. // current configuration.
  816. func (c *Config) getSupportedVersions() []uint16 {
  817. minVersion := c.minVersion()
  818. maxVersion := c.maxVersion()
  819. // Sanity check to avoid advertising unsupported versions.
  820. if minVersion < VersionSSL30 {
  821. minVersion = VersionSSL30
  822. }
  823. if maxVersion > VersionTLS13 {
  824. maxVersion = VersionTLS13
  825. }
  826. if maxVersion < minVersion {
  827. return nil
  828. }
  829. return configSuppVersArray[VersionTLS13-maxVersion : VersionTLS13-minVersion+1]
  830. }
  831. // getCertificate returns the best certificate for the given ClientHelloInfo,
  832. // defaulting to the first element of c.Certificates.
  833. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  834. if c.GetCertificate != nil &&
  835. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  836. cert, err := c.GetCertificate(clientHello)
  837. if cert != nil || err != nil {
  838. return cert, err
  839. }
  840. }
  841. if len(c.Certificates) == 0 {
  842. return nil, errors.New("tls: no certificates configured")
  843. }
  844. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  845. // There's only one choice, so no point doing any work.
  846. return &c.Certificates[0], nil
  847. }
  848. name := strings.ToLower(clientHello.ServerName)
  849. for len(name) > 0 && name[len(name)-1] == '.' {
  850. name = name[:len(name)-1]
  851. }
  852. if cert, ok := c.NameToCertificate[name]; ok {
  853. return cert, nil
  854. }
  855. // try replacing labels in the name with wildcards until we get a
  856. // match.
  857. labels := strings.Split(name, ".")
  858. for i := range labels {
  859. labels[i] = "*"
  860. candidate := strings.Join(labels, ".")
  861. if cert, ok := c.NameToCertificate[candidate]; ok {
  862. return cert, nil
  863. }
  864. }
  865. // If nothing matches, return the first certificate.
  866. return &c.Certificates[0], nil
  867. }
  868. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  869. // from the CommonName and SubjectAlternateName fields of each of the leaf
  870. // certificates.
  871. func (c *Config) BuildNameToCertificate() {
  872. c.NameToCertificate = make(map[string]*Certificate)
  873. for i := range c.Certificates {
  874. cert := &c.Certificates[i]
  875. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  876. if err != nil {
  877. continue
  878. }
  879. if len(x509Cert.Subject.CommonName) > 0 {
  880. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  881. }
  882. for _, san := range x509Cert.DNSNames {
  883. c.NameToCertificate[san] = cert
  884. }
  885. }
  886. }
  887. // writeKeyLog logs client random and master secret if logging was enabled by
  888. // setting c.KeyLogWriter.
  889. func (c *Config) writeKeyLog(what string, clientRandom, masterSecret []byte) error {
  890. if c.KeyLogWriter == nil {
  891. return nil
  892. }
  893. logLine := []byte(fmt.Sprintf("%s %x %x\n", what, clientRandom, masterSecret))
  894. writerMutex.Lock()
  895. _, err := c.KeyLogWriter.Write(logLine)
  896. writerMutex.Unlock()
  897. return err
  898. }
  899. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  900. // and is only for debugging, so a global mutex saves space.
  901. var writerMutex sync.Mutex
  902. // A Certificate is a chain of one or more certificates, leaf first.
  903. type Certificate struct {
  904. Certificate [][]byte
  905. // PrivateKey contains the private key corresponding to the public key
  906. // in Leaf. For a server, this must implement crypto.Signer and/or
  907. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  908. // (performing client authentication), this must be a crypto.Signer
  909. // with an RSA or ECDSA PublicKey.
  910. PrivateKey crypto.PrivateKey
  911. // OCSPStaple contains an optional OCSP response which will be served
  912. // to clients that request it.
  913. OCSPStaple []byte
  914. // SignedCertificateTimestamps contains an optional list of Signed
  915. // Certificate Timestamps which will be served to clients that request it.
  916. SignedCertificateTimestamps [][]byte
  917. // Leaf is the parsed form of the leaf certificate, which may be
  918. // initialized using x509.ParseCertificate to reduce per-handshake
  919. // processing for TLS clients doing client authentication. If nil, the
  920. // leaf certificate will be parsed as needed.
  921. Leaf *x509.Certificate
  922. }
  923. type handshakeMessage interface {
  924. marshal() []byte
  925. unmarshal([]byte) alert
  926. }
  927. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  928. // caching strategy.
  929. type lruSessionCache struct {
  930. sync.Mutex
  931. m map[string]*list.Element
  932. q *list.List
  933. capacity int
  934. }
  935. type lruSessionCacheEntry struct {
  936. sessionKey string
  937. state *ClientSessionState
  938. }
  939. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  940. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  941. // is used instead.
  942. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  943. const defaultSessionCacheCapacity = 64
  944. if capacity < 1 {
  945. capacity = defaultSessionCacheCapacity
  946. }
  947. return &lruSessionCache{
  948. m: make(map[string]*list.Element),
  949. q: list.New(),
  950. capacity: capacity,
  951. }
  952. }
  953. // Put adds the provided (sessionKey, cs) pair to the cache.
  954. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  955. c.Lock()
  956. defer c.Unlock()
  957. if elem, ok := c.m[sessionKey]; ok {
  958. entry := elem.Value.(*lruSessionCacheEntry)
  959. entry.state = cs
  960. c.q.MoveToFront(elem)
  961. return
  962. }
  963. if c.q.Len() < c.capacity {
  964. entry := &lruSessionCacheEntry{sessionKey, cs}
  965. c.m[sessionKey] = c.q.PushFront(entry)
  966. return
  967. }
  968. elem := c.q.Back()
  969. entry := elem.Value.(*lruSessionCacheEntry)
  970. delete(c.m, entry.sessionKey)
  971. entry.sessionKey = sessionKey
  972. entry.state = cs
  973. c.q.MoveToFront(elem)
  974. c.m[sessionKey] = elem
  975. }
  976. // Get returns the ClientSessionState value associated with a given key. It
  977. // returns (nil, false) if no value is found.
  978. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  979. c.Lock()
  980. defer c.Unlock()
  981. if elem, ok := c.m[sessionKey]; ok {
  982. c.q.MoveToFront(elem)
  983. return elem.Value.(*lruSessionCacheEntry).state, true
  984. }
  985. return nil, false
  986. }
  987. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  988. type dsaSignature struct {
  989. R, S *big.Int
  990. }
  991. type ecdsaSignature dsaSignature
  992. var emptyConfig Config
  993. func defaultConfig() *Config {
  994. return &emptyConfig
  995. }
  996. var (
  997. once sync.Once
  998. varDefaultCipherSuites []uint16
  999. varDefaultTLS13CipherSuites []uint16
  1000. )
  1001. func defaultCipherSuites() []uint16 {
  1002. once.Do(initDefaultCipherSuites)
  1003. return varDefaultCipherSuites
  1004. }
  1005. func defaultTLS13CipherSuites() []uint16 {
  1006. once.Do(initDefaultCipherSuites)
  1007. return varDefaultTLS13CipherSuites
  1008. }
  1009. func initDefaultCipherSuites() {
  1010. var topCipherSuites, topTLS13CipherSuites []uint16
  1011. if cipherhw.AESGCMSupport() {
  1012. // If AES-GCM hardware is provided then prioritise AES-GCM
  1013. // cipher suites.
  1014. topTLS13CipherSuites = []uint16{
  1015. TLS_AES_128_GCM_SHA256,
  1016. TLS_AES_256_GCM_SHA384,
  1017. TLS_CHACHA20_POLY1305_SHA256,
  1018. }
  1019. topCipherSuites = []uint16{
  1020. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1021. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1022. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1023. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1024. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1025. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1026. }
  1027. } else {
  1028. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1029. // cipher suites first.
  1030. topTLS13CipherSuites = []uint16{
  1031. TLS_CHACHA20_POLY1305_SHA256,
  1032. TLS_AES_128_GCM_SHA256,
  1033. TLS_AES_256_GCM_SHA384,
  1034. }
  1035. topCipherSuites = []uint16{
  1036. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1037. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1038. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1039. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1040. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1041. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1042. }
  1043. }
  1044. varDefaultTLS13CipherSuites = make([]uint16, 0, len(cipherSuites))
  1045. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, topTLS13CipherSuites...)
  1046. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1047. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1048. NextCipherSuite:
  1049. for _, suite := range cipherSuites {
  1050. if suite.flags&suiteDefaultOff != 0 {
  1051. continue
  1052. }
  1053. if suite.flags&suiteTLS13 != 0 {
  1054. for _, existing := range varDefaultTLS13CipherSuites {
  1055. if existing == suite.id {
  1056. continue NextCipherSuite
  1057. }
  1058. }
  1059. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, suite.id)
  1060. } else {
  1061. for _, existing := range varDefaultCipherSuites {
  1062. if existing == suite.id {
  1063. continue NextCipherSuite
  1064. }
  1065. }
  1066. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1067. }
  1068. }
  1069. varDefaultCipherSuites = append(varDefaultTLS13CipherSuites, varDefaultCipherSuites...)
  1070. }
  1071. func unexpectedMessageError(wanted, got interface{}) error {
  1072. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1073. }
  1074. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1075. for _, s := range supportedSignatureAlgorithms {
  1076. if s == sigAlg {
  1077. return true
  1078. }
  1079. }
  1080. return false
  1081. }
  1082. // signatureFromSignatureScheme maps a signature algorithm to the underlying
  1083. // signature method (without hash function).
  1084. func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1085. switch signatureAlgorithm {
  1086. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1087. return signaturePKCS1v15
  1088. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1089. return signatureRSAPSS
  1090. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1091. return signatureECDSA
  1092. default:
  1093. return 0
  1094. }
  1095. }
  1096. // TODO(kk): Use variable length encoding?
  1097. func getUint24(b []byte) int {
  1098. n := int(b[2])
  1099. n += int(b[1] << 8)
  1100. n += int(b[0] << 16)
  1101. return n
  1102. }
  1103. func putUint24(b []byte, n int) {
  1104. b[0] = byte(n >> 16)
  1105. b[1] = byte(n >> 8)
  1106. b[2] = byte(n & 0xff)
  1107. }