common.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. // PassthroughVerifyMessage must be set when passthrough mode is enabled. The
  587. // function must return true for valid passthrough messages and false
  588. // otherwise.
  589. PassthroughVerifyMessage func([]byte) bool
  590. // [Psiphon]
  591. // PassthroughHistoryAddNew must be set when passthough mode is enabled. The
  592. // function should check that a ClientHello random value has not been
  593. // previously observed, returning true only for a newly observed value. Any
  594. // logging is the callback's responsibility.
  595. PassthroughHistoryAddNew func(
  596. clientIP string,
  597. clientRandom []byte) bool
  598. // [Psiphon]
  599. // PassthroughLogInvalidMessage must be set when passthough mode is enabled.
  600. // The function should log an invalid ClientHello random value event.
  601. PassthroughLogInvalidMessage func(clientIP string)
  602. }
  603. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  604. // an encrypted session ticket in order to identify the key used to encrypt it.
  605. const ticketKeyNameLen = 16
  606. // ticketKey is the internal representation of a session ticket key.
  607. type ticketKey struct {
  608. // keyName is an opaque byte string that serves to identify the session
  609. // ticket key. It's exposed as plaintext in every session ticket.
  610. keyName [ticketKeyNameLen]byte
  611. aesKey [16]byte
  612. hmacKey [16]byte
  613. }
  614. // ticketKeyFromBytes converts from the external representation of a session
  615. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  616. // bytes and this function expands that into sufficient name and key material.
  617. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  618. hashed := sha512.Sum512(b[:])
  619. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  620. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  621. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  622. return key
  623. }
  624. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  625. // being used concurrently by a TLS client or server.
  626. func (c *Config) Clone() *Config {
  627. // Running serverInit ensures that it's safe to read
  628. // SessionTicketsDisabled.
  629. c.serverInitOnce.Do(func() { c.serverInit(nil) })
  630. var sessionTicketKeys []ticketKey
  631. c.mutex.RLock()
  632. sessionTicketKeys = c.sessionTicketKeys
  633. c.mutex.RUnlock()
  634. return &Config{
  635. Rand: c.Rand,
  636. Time: c.Time,
  637. Certificates: c.Certificates,
  638. NameToCertificate: c.NameToCertificate,
  639. GetCertificate: c.GetCertificate,
  640. GetClientCertificate: c.GetClientCertificate,
  641. GetConfigForClient: c.GetConfigForClient,
  642. VerifyPeerCertificate: c.VerifyPeerCertificate,
  643. RootCAs: c.RootCAs,
  644. NextProtos: c.NextProtos,
  645. ServerName: c.ServerName,
  646. ClientAuth: c.ClientAuth,
  647. ClientCAs: c.ClientCAs,
  648. InsecureSkipVerify: c.InsecureSkipVerify,
  649. CipherSuites: c.CipherSuites,
  650. PreferServerCipherSuites: c.PreferServerCipherSuites,
  651. SessionTicketsDisabled: c.SessionTicketsDisabled,
  652. SessionTicketKey: c.SessionTicketKey,
  653. ClientSessionCache: c.ClientSessionCache,
  654. MinVersion: c.MinVersion,
  655. MaxVersion: c.MaxVersion,
  656. CurvePreferences: c.CurvePreferences,
  657. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  658. Renegotiation: c.Renegotiation,
  659. KeyLogWriter: c.KeyLogWriter,
  660. Accept0RTTData: c.Accept0RTTData,
  661. Max0RTTDataSize: c.Max0RTTDataSize,
  662. SessionTicketSealer: c.SessionTicketSealer,
  663. AcceptDelegatedCredential: c.AcceptDelegatedCredential,
  664. GetDelegatedCredential: c.GetDelegatedCredential,
  665. sessionTicketKeys: sessionTicketKeys,
  666. UseExtendedMasterSecret: c.UseExtendedMasterSecret,
  667. }
  668. }
  669. // serverInit is run under c.serverInitOnce to do initialization of c. If c was
  670. // returned by a GetConfigForClient callback then the argument should be the
  671. // Config that was passed to Server, otherwise it should be nil.
  672. func (c *Config) serverInit(originalConfig *Config) {
  673. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 || c.SessionTicketSealer != nil {
  674. return
  675. }
  676. alreadySet := false
  677. for _, b := range c.SessionTicketKey {
  678. if b != 0 {
  679. alreadySet = true
  680. break
  681. }
  682. }
  683. if !alreadySet {
  684. if originalConfig != nil {
  685. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  686. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  687. c.SessionTicketsDisabled = true
  688. return
  689. }
  690. }
  691. if originalConfig != nil {
  692. originalConfig.mutex.RLock()
  693. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  694. originalConfig.mutex.RUnlock()
  695. } else {
  696. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  697. }
  698. }
  699. func (c *Config) ticketKeys() []ticketKey {
  700. c.mutex.RLock()
  701. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  702. // will only update it by replacing it with a new value.
  703. ret := c.sessionTicketKeys
  704. c.mutex.RUnlock()
  705. return ret
  706. }
  707. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  708. // key will be used when creating new tickets, while all keys can be used for
  709. // decrypting tickets. It is safe to call this function while the server is
  710. // running in order to rotate the session ticket keys. The function will panic
  711. // if keys is empty.
  712. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  713. if len(keys) == 0 {
  714. panic("tls: keys must have at least one key")
  715. }
  716. newKeys := make([]ticketKey, len(keys))
  717. for i, bytes := range keys {
  718. newKeys[i] = ticketKeyFromBytes(bytes)
  719. }
  720. c.mutex.Lock()
  721. c.sessionTicketKeys = newKeys
  722. c.mutex.Unlock()
  723. }
  724. func (c *Config) rand() io.Reader {
  725. r := c.Rand
  726. if r == nil {
  727. return rand.Reader
  728. }
  729. return r
  730. }
  731. func (c *Config) time() time.Time {
  732. t := c.Time
  733. if t == nil {
  734. t = time.Now
  735. }
  736. return t()
  737. }
  738. func hasOverlappingCipherSuites(cs1, cs2 []uint16) bool {
  739. for _, c1 := range cs1 {
  740. for _, c2 := range cs2 {
  741. if c1 == c2 {
  742. return true
  743. }
  744. }
  745. }
  746. return false
  747. }
  748. func (c *Config) cipherSuites() []uint16 {
  749. s := c.CipherSuites
  750. if s == nil {
  751. s = defaultCipherSuites()
  752. } else if c.maxVersion() >= VersionTLS13 {
  753. // Ensure that TLS 1.3 suites are always present, but respect
  754. // the application cipher suite preferences.
  755. s13 := defaultTLS13CipherSuites()
  756. if !hasOverlappingCipherSuites(s, s13) {
  757. allSuites := make([]uint16, len(s13)+len(s))
  758. allSuites = append(allSuites, s13...)
  759. s = append(allSuites, s...)
  760. }
  761. }
  762. return s
  763. }
  764. func (c *Config) minVersion() uint16 {
  765. if c == nil || c.MinVersion == 0 {
  766. return minVersion
  767. }
  768. return c.MinVersion
  769. }
  770. func (c *Config) maxVersion() uint16 {
  771. if c == nil || c.MaxVersion == 0 {
  772. return maxVersion
  773. }
  774. return c.MaxVersion
  775. }
  776. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  777. func (c *Config) curvePreferences() []CurveID {
  778. if c == nil || len(c.CurvePreferences) == 0 {
  779. return defaultCurvePreferences
  780. }
  781. return c.CurvePreferences
  782. }
  783. // mutualVersion returns the protocol version to use given the advertised
  784. // version of the peer using the legacy non-extension methods.
  785. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  786. minVersion := c.minVersion()
  787. maxVersion := c.maxVersion()
  788. // Version 1.3 and higher are not negotiated via this mechanism.
  789. if maxVersion > VersionTLS12 {
  790. maxVersion = VersionTLS12
  791. }
  792. if vers < minVersion {
  793. return 0, false
  794. }
  795. if vers > maxVersion {
  796. vers = maxVersion
  797. }
  798. return vers, true
  799. }
  800. // pickVersion returns the protocol version to use given the advertised
  801. // versions of the peer using the Supported Versions extension.
  802. func (c *Config) pickVersion(peerSupportedVersions []uint16) (uint16, bool) {
  803. supportedVersions := c.getSupportedVersions()
  804. for _, supportedVersion := range supportedVersions {
  805. for _, version := range peerSupportedVersions {
  806. if version == supportedVersion {
  807. return version, true
  808. }
  809. }
  810. }
  811. return 0, false
  812. }
  813. // configSuppVersArray is the backing array of Config.getSupportedVersions
  814. var configSuppVersArray = [...]uint16{VersionTLS13, VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  815. // getSupportedVersions returns the protocol versions that are supported by the
  816. // current configuration.
  817. func (c *Config) getSupportedVersions() []uint16 {
  818. minVersion := c.minVersion()
  819. maxVersion := c.maxVersion()
  820. // Sanity check to avoid advertising unsupported versions.
  821. if minVersion < VersionSSL30 {
  822. minVersion = VersionSSL30
  823. }
  824. if maxVersion > VersionTLS13 {
  825. maxVersion = VersionTLS13
  826. }
  827. if maxVersion < minVersion {
  828. return nil
  829. }
  830. return configSuppVersArray[VersionTLS13-maxVersion : VersionTLS13-minVersion+1]
  831. }
  832. // getCertificate returns the best certificate for the given ClientHelloInfo,
  833. // defaulting to the first element of c.Certificates.
  834. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  835. if c.GetCertificate != nil &&
  836. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  837. cert, err := c.GetCertificate(clientHello)
  838. if cert != nil || err != nil {
  839. return cert, err
  840. }
  841. }
  842. if len(c.Certificates) == 0 {
  843. return nil, errors.New("tls: no certificates configured")
  844. }
  845. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  846. // There's only one choice, so no point doing any work.
  847. return &c.Certificates[0], nil
  848. }
  849. name := strings.ToLower(clientHello.ServerName)
  850. for len(name) > 0 && name[len(name)-1] == '.' {
  851. name = name[:len(name)-1]
  852. }
  853. if cert, ok := c.NameToCertificate[name]; ok {
  854. return cert, nil
  855. }
  856. // try replacing labels in the name with wildcards until we get a
  857. // match.
  858. labels := strings.Split(name, ".")
  859. for i := range labels {
  860. labels[i] = "*"
  861. candidate := strings.Join(labels, ".")
  862. if cert, ok := c.NameToCertificate[candidate]; ok {
  863. return cert, nil
  864. }
  865. }
  866. // If nothing matches, return the first certificate.
  867. return &c.Certificates[0], nil
  868. }
  869. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  870. // from the CommonName and SubjectAlternateName fields of each of the leaf
  871. // certificates.
  872. func (c *Config) BuildNameToCertificate() {
  873. c.NameToCertificate = make(map[string]*Certificate)
  874. for i := range c.Certificates {
  875. cert := &c.Certificates[i]
  876. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  877. if err != nil {
  878. continue
  879. }
  880. if len(x509Cert.Subject.CommonName) > 0 {
  881. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  882. }
  883. for _, san := range x509Cert.DNSNames {
  884. c.NameToCertificate[san] = cert
  885. }
  886. }
  887. }
  888. // writeKeyLog logs client random and master secret if logging was enabled by
  889. // setting c.KeyLogWriter.
  890. func (c *Config) writeKeyLog(what string, clientRandom, masterSecret []byte) error {
  891. if c.KeyLogWriter == nil {
  892. return nil
  893. }
  894. logLine := []byte(fmt.Sprintf("%s %x %x\n", what, clientRandom, masterSecret))
  895. writerMutex.Lock()
  896. _, err := c.KeyLogWriter.Write(logLine)
  897. writerMutex.Unlock()
  898. return err
  899. }
  900. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  901. // and is only for debugging, so a global mutex saves space.
  902. var writerMutex sync.Mutex
  903. // A Certificate is a chain of one or more certificates, leaf first.
  904. type Certificate struct {
  905. Certificate [][]byte
  906. // PrivateKey contains the private key corresponding to the public key
  907. // in Leaf. For a server, this must implement crypto.Signer and/or
  908. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  909. // (performing client authentication), this must be a crypto.Signer
  910. // with an RSA or ECDSA PublicKey.
  911. PrivateKey crypto.PrivateKey
  912. // OCSPStaple contains an optional OCSP response which will be served
  913. // to clients that request it.
  914. OCSPStaple []byte
  915. // SignedCertificateTimestamps contains an optional list of Signed
  916. // Certificate Timestamps which will be served to clients that request it.
  917. SignedCertificateTimestamps [][]byte
  918. // Leaf is the parsed form of the leaf certificate, which may be
  919. // initialized using x509.ParseCertificate to reduce per-handshake
  920. // processing for TLS clients doing client authentication. If nil, the
  921. // leaf certificate will be parsed as needed.
  922. Leaf *x509.Certificate
  923. }
  924. type handshakeMessage interface {
  925. marshal() []byte
  926. unmarshal([]byte) alert
  927. }
  928. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  929. // caching strategy.
  930. type lruSessionCache struct {
  931. sync.Mutex
  932. m map[string]*list.Element
  933. q *list.List
  934. capacity int
  935. }
  936. type lruSessionCacheEntry struct {
  937. sessionKey string
  938. state *ClientSessionState
  939. }
  940. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  941. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  942. // is used instead.
  943. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  944. const defaultSessionCacheCapacity = 64
  945. if capacity < 1 {
  946. capacity = defaultSessionCacheCapacity
  947. }
  948. return &lruSessionCache{
  949. m: make(map[string]*list.Element),
  950. q: list.New(),
  951. capacity: capacity,
  952. }
  953. }
  954. // Put adds the provided (sessionKey, cs) pair to the cache.
  955. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  956. c.Lock()
  957. defer c.Unlock()
  958. if elem, ok := c.m[sessionKey]; ok {
  959. entry := elem.Value.(*lruSessionCacheEntry)
  960. entry.state = cs
  961. c.q.MoveToFront(elem)
  962. return
  963. }
  964. if c.q.Len() < c.capacity {
  965. entry := &lruSessionCacheEntry{sessionKey, cs}
  966. c.m[sessionKey] = c.q.PushFront(entry)
  967. return
  968. }
  969. elem := c.q.Back()
  970. entry := elem.Value.(*lruSessionCacheEntry)
  971. delete(c.m, entry.sessionKey)
  972. entry.sessionKey = sessionKey
  973. entry.state = cs
  974. c.q.MoveToFront(elem)
  975. c.m[sessionKey] = elem
  976. }
  977. // Get returns the ClientSessionState value associated with a given key. It
  978. // returns (nil, false) if no value is found.
  979. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  980. c.Lock()
  981. defer c.Unlock()
  982. if elem, ok := c.m[sessionKey]; ok {
  983. c.q.MoveToFront(elem)
  984. return elem.Value.(*lruSessionCacheEntry).state, true
  985. }
  986. return nil, false
  987. }
  988. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  989. type dsaSignature struct {
  990. R, S *big.Int
  991. }
  992. type ecdsaSignature dsaSignature
  993. var emptyConfig Config
  994. func defaultConfig() *Config {
  995. return &emptyConfig
  996. }
  997. var (
  998. once sync.Once
  999. varDefaultCipherSuites []uint16
  1000. varDefaultTLS13CipherSuites []uint16
  1001. )
  1002. func defaultCipherSuites() []uint16 {
  1003. once.Do(initDefaultCipherSuites)
  1004. return varDefaultCipherSuites
  1005. }
  1006. func defaultTLS13CipherSuites() []uint16 {
  1007. once.Do(initDefaultCipherSuites)
  1008. return varDefaultTLS13CipherSuites
  1009. }
  1010. func initDefaultCipherSuites() {
  1011. var topCipherSuites, topTLS13CipherSuites []uint16
  1012. if cipherhw.AESGCMSupport() {
  1013. // If AES-GCM hardware is provided then prioritise AES-GCM
  1014. // cipher suites.
  1015. topTLS13CipherSuites = []uint16{
  1016. TLS_AES_128_GCM_SHA256,
  1017. TLS_AES_256_GCM_SHA384,
  1018. TLS_CHACHA20_POLY1305_SHA256,
  1019. }
  1020. topCipherSuites = []uint16{
  1021. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1022. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1023. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1024. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1025. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1026. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1027. }
  1028. } else {
  1029. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1030. // cipher suites first.
  1031. topTLS13CipherSuites = []uint16{
  1032. TLS_CHACHA20_POLY1305_SHA256,
  1033. TLS_AES_128_GCM_SHA256,
  1034. TLS_AES_256_GCM_SHA384,
  1035. }
  1036. topCipherSuites = []uint16{
  1037. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1038. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1039. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1040. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1041. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1042. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1043. }
  1044. }
  1045. varDefaultTLS13CipherSuites = make([]uint16, 0, len(cipherSuites))
  1046. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, topTLS13CipherSuites...)
  1047. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1048. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1049. NextCipherSuite:
  1050. for _, suite := range cipherSuites {
  1051. if suite.flags&suiteDefaultOff != 0 {
  1052. continue
  1053. }
  1054. if suite.flags&suiteTLS13 != 0 {
  1055. for _, existing := range varDefaultTLS13CipherSuites {
  1056. if existing == suite.id {
  1057. continue NextCipherSuite
  1058. }
  1059. }
  1060. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, suite.id)
  1061. } else {
  1062. for _, existing := range varDefaultCipherSuites {
  1063. if existing == suite.id {
  1064. continue NextCipherSuite
  1065. }
  1066. }
  1067. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1068. }
  1069. }
  1070. varDefaultCipherSuites = append(varDefaultTLS13CipherSuites, varDefaultCipherSuites...)
  1071. }
  1072. func unexpectedMessageError(wanted, got interface{}) error {
  1073. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1074. }
  1075. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1076. for _, s := range supportedSignatureAlgorithms {
  1077. if s == sigAlg {
  1078. return true
  1079. }
  1080. }
  1081. return false
  1082. }
  1083. // signatureFromSignatureScheme maps a signature algorithm to the underlying
  1084. // signature method (without hash function).
  1085. func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1086. switch signatureAlgorithm {
  1087. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1088. return signaturePKCS1v15
  1089. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1090. return signatureRSAPSS
  1091. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1092. return signatureECDSA
  1093. default:
  1094. return 0
  1095. }
  1096. }
  1097. // TODO(kk): Use variable length encoding?
  1098. func getUint24(b []byte) int {
  1099. n := int(b[2])
  1100. n += int(b[1] << 8)
  1101. n += int(b[0] << 16)
  1102. return n
  1103. }
  1104. func putUint24(b []byte, n int) {
  1105. b[0] = byte(n >> 16)
  1106. b[1] = byte(n >> 8)
  1107. b[2] = byte(n & 0xff)
  1108. }