common.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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/tls/cipherhw"
  20. )
  21. const (
  22. VersionSSL30 = 0x0300
  23. VersionTLS10 = 0x0301
  24. VersionTLS11 = 0x0302
  25. VersionTLS12 = 0x0303
  26. )
  27. const (
  28. maxPlaintext = 16384 // maximum plaintext payload length
  29. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  30. recordHeaderLen = 5 // record header length
  31. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  32. minVersion = VersionTLS10
  33. maxVersion = VersionTLS12
  34. )
  35. // TLS record types.
  36. type recordType uint8
  37. const (
  38. recordTypeChangeCipherSpec recordType = 20
  39. recordTypeAlert recordType = 21
  40. recordTypeHandshake recordType = 22
  41. recordTypeApplicationData recordType = 23
  42. )
  43. // TLS handshake message types.
  44. const (
  45. typeHelloRequest uint8 = 0
  46. typeClientHello uint8 = 1
  47. typeServerHello uint8 = 2
  48. typeNewSessionTicket uint8 = 4
  49. typeCertificate uint8 = 11
  50. typeServerKeyExchange uint8 = 12
  51. typeCertificateRequest uint8 = 13
  52. typeServerHelloDone uint8 = 14
  53. typeCertificateVerify uint8 = 15
  54. typeClientKeyExchange uint8 = 16
  55. typeFinished uint8 = 20
  56. typeCertificateStatus uint8 = 22
  57. typeNextProtocol uint8 = 67 // Not IANA assigned
  58. )
  59. // TLS compression types.
  60. const (
  61. compressionNone uint8 = 0
  62. )
  63. // TLS extension numbers
  64. const (
  65. extensionServerName uint16 = 0
  66. extensionStatusRequest uint16 = 5
  67. extensionSupportedCurves uint16 = 10
  68. extensionSupportedPoints uint16 = 11
  69. extensionSignatureAlgorithms uint16 = 13
  70. extensionALPN uint16 = 16
  71. extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
  72. extensionSessionTicket uint16 = 35
  73. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  74. extensionRenegotiationInfo uint16 = 0xff01
  75. // [Psiphon]
  76. // Additional extensions required for EmulateChrome.
  77. extensionPadding uint16 = 21
  78. extensionExtendedMasterSecret uint16 = 23
  79. extensionChannelID uint16 = 30032 // not IANA assigned
  80. )
  81. // TLS signaling cipher suite values
  82. const (
  83. scsvRenegotiation uint16 = 0x00ff
  84. )
  85. // CurveID is the type of a TLS identifier for an elliptic curve. See
  86. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  87. type CurveID uint16
  88. const (
  89. CurveP256 CurveID = 23
  90. CurveP384 CurveID = 24
  91. CurveP521 CurveID = 25
  92. X25519 CurveID = 29
  93. )
  94. // TLS Elliptic Curve Point Formats
  95. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  96. const (
  97. pointFormatUncompressed uint8 = 0
  98. )
  99. // TLS CertificateStatusType (RFC 3546)
  100. const (
  101. statusTypeOCSP uint8 = 1
  102. )
  103. // Certificate types (for certificateRequestMsg)
  104. const (
  105. certTypeRSASign = 1 // A certificate containing an RSA key
  106. certTypeDSSSign = 2 // A certificate containing a DSA key
  107. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  108. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  109. // See RFC 4492 sections 3 and 5.5.
  110. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  111. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  112. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  113. // Rest of these are reserved by the TLS spec
  114. )
  115. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  116. const (
  117. hashSHA1 uint8 = 2
  118. hashSHA256 uint8 = 4
  119. hashSHA384 uint8 = 5
  120. // [Psiphon]
  121. // hashSHA512 is required for EmulateChrome.
  122. hashSHA512 uint8 = 6
  123. )
  124. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  125. const (
  126. signatureRSA uint8 = 1
  127. signatureECDSA uint8 = 3
  128. )
  129. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  130. // RFC 5246, section A.4.1.
  131. type signatureAndHash struct {
  132. hash, signature uint8
  133. }
  134. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  135. // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
  136. // CertificateRequest.
  137. var supportedSignatureAlgorithms = []signatureAndHash{
  138. {hashSHA256, signatureRSA},
  139. {hashSHA256, signatureECDSA},
  140. {hashSHA384, signatureRSA},
  141. {hashSHA384, signatureECDSA},
  142. {hashSHA1, signatureRSA},
  143. {hashSHA1, signatureECDSA},
  144. // [Psiphon]
  145. {hashSHA512, signatureRSA},
  146. }
  147. // ConnectionState records basic TLS details about the connection.
  148. type ConnectionState struct {
  149. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  150. HandshakeComplete bool // TLS handshake is complete
  151. DidResume bool // connection resumes a previous TLS connection
  152. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  153. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  154. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  155. ServerName string // server name requested by client, if any (server side only)
  156. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  157. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  158. SignedCertificateTimestamps [][]byte // SCTs from the server, if any
  159. OCSPResponse []byte // stapled OCSP response from server, if any
  160. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  161. // 5929, section 3). For resumed sessions this value will be nil
  162. // because resumption does not include enough context (see
  163. // https://secure-resumption.com/#channelbindings). This will change in
  164. // future versions of Go once the TLS master-secret fix has been
  165. // standardized and implemented.
  166. TLSUnique []byte
  167. }
  168. // ClientAuthType declares the policy the server will follow for
  169. // TLS Client Authentication.
  170. type ClientAuthType int
  171. const (
  172. NoClientCert ClientAuthType = iota
  173. RequestClientCert
  174. RequireAnyClientCert
  175. VerifyClientCertIfGiven
  176. RequireAndVerifyClientCert
  177. )
  178. // ClientSessionState contains the state needed by clients to resume TLS
  179. // sessions.
  180. type ClientSessionState struct {
  181. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  182. vers uint16 // SSL/TLS version negotiated for the session
  183. cipherSuite uint16 // Ciphersuite negotiated for the session
  184. masterSecret []byte // MasterSecret generated by client on a full handshake
  185. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  186. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  187. extendedMasterSecret bool // [Psiphon] Whether an extended master secret was used to generate the session
  188. }
  189. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  190. // by a client to resume a TLS session with a given server. ClientSessionCache
  191. // implementations should expect to be called concurrently from different
  192. // goroutines.
  193. type ClientSessionCache interface {
  194. // Get searches for a ClientSessionState associated with the given key.
  195. // On return, ok is true if one was found.
  196. Get(sessionKey string) (session *ClientSessionState, ok bool)
  197. // Put adds the ClientSessionState to the cache with the given key.
  198. Put(sessionKey string, cs *ClientSessionState)
  199. }
  200. // SignatureScheme identifies a signature algorithm supported by TLS. See
  201. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
  202. type SignatureScheme uint16
  203. const (
  204. PKCS1WithSHA1 SignatureScheme = 0x0201
  205. PKCS1WithSHA256 SignatureScheme = 0x0401
  206. PKCS1WithSHA384 SignatureScheme = 0x0501
  207. PKCS1WithSHA512 SignatureScheme = 0x0601
  208. PSSWithSHA256 SignatureScheme = 0x0804
  209. PSSWithSHA384 SignatureScheme = 0x0805
  210. PSSWithSHA512 SignatureScheme = 0x0806
  211. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  212. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  213. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  214. )
  215. // ClientHelloInfo contains information from a ClientHello message in order to
  216. // guide certificate selection in the GetCertificate callback.
  217. type ClientHelloInfo struct {
  218. // CipherSuites lists the CipherSuites supported by the client (e.g.
  219. // TLS_RSA_WITH_RC4_128_SHA).
  220. CipherSuites []uint16
  221. // ServerName indicates the name of the server requested by the client
  222. // in order to support virtual hosting. ServerName is only set if the
  223. // client is using SNI (see
  224. // http://tools.ietf.org/html/rfc4366#section-3.1).
  225. ServerName string
  226. // SupportedCurves lists the elliptic curves supported by the client.
  227. // SupportedCurves is set only if the Supported Elliptic Curves
  228. // Extension is being used (see
  229. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  230. SupportedCurves []CurveID
  231. // SupportedPoints lists the point formats supported by the client.
  232. // SupportedPoints is set only if the Supported Point Formats Extension
  233. // is being used (see
  234. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  235. SupportedPoints []uint8
  236. // SignatureSchemes lists the signature and hash schemes that the client
  237. // is willing to verify. SignatureSchemes is set only if the Signature
  238. // Algorithms Extension is being used (see
  239. // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  240. SignatureSchemes []SignatureScheme
  241. // SupportedProtos lists the application protocols supported by the client.
  242. // SupportedProtos is set only if the Application-Layer Protocol
  243. // Negotiation Extension is being used (see
  244. // https://tools.ietf.org/html/rfc7301#section-3.1).
  245. //
  246. // Servers can select a protocol by setting Config.NextProtos in a
  247. // GetConfigForClient return value.
  248. SupportedProtos []string
  249. // SupportedVersions lists the TLS versions supported by the client.
  250. // For TLS versions less than 1.3, this is extrapolated from the max
  251. // version advertised by the client, so values other than the greatest
  252. // might be rejected if used.
  253. SupportedVersions []uint16
  254. // Conn is the underlying net.Conn for the connection. Do not read
  255. // from, or write to, this connection; that will cause the TLS
  256. // connection to fail.
  257. Conn net.Conn
  258. }
  259. // CertificateRequestInfo contains information from a server's
  260. // CertificateRequest message, which is used to demand a certificate and proof
  261. // of control from a client.
  262. type CertificateRequestInfo struct {
  263. // AcceptableCAs contains zero or more, DER-encoded, X.501
  264. // Distinguished Names. These are the names of root or intermediate CAs
  265. // that the server wishes the returned certificate to be signed by. An
  266. // empty slice indicates that the server has no preference.
  267. AcceptableCAs [][]byte
  268. // SignatureSchemes lists the signature schemes that the server is
  269. // willing to verify.
  270. SignatureSchemes []SignatureScheme
  271. }
  272. // RenegotiationSupport enumerates the different levels of support for TLS
  273. // renegotiation. TLS renegotiation is the act of performing subsequent
  274. // handshakes on a connection after the first. This significantly complicates
  275. // the state machine and has been the source of numerous, subtle security
  276. // issues. Initiating a renegotiation is not supported, but support for
  277. // accepting renegotiation requests may be enabled.
  278. //
  279. // Even when enabled, the server may not change its identity between handshakes
  280. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  281. // handshake and application data flow is not permitted so renegotiation can
  282. // only be used with protocols that synchronise with the renegotiation, such as
  283. // HTTPS.
  284. type RenegotiationSupport int
  285. const (
  286. // RenegotiateNever disables renegotiation.
  287. RenegotiateNever RenegotiationSupport = iota
  288. // RenegotiateOnceAsClient allows a remote server to request
  289. // renegotiation once per connection.
  290. RenegotiateOnceAsClient
  291. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  292. // request renegotiation.
  293. RenegotiateFreelyAsClient
  294. )
  295. // A Config structure is used to configure a TLS client or server.
  296. // After one has been passed to a TLS function it must not be
  297. // modified. A Config may be reused; the tls package will also not
  298. // modify it.
  299. type Config struct {
  300. // Rand provides the source of entropy for nonces and RSA blinding.
  301. // If Rand is nil, TLS uses the cryptographic random reader in package
  302. // crypto/rand.
  303. // The Reader must be safe for use by multiple goroutines.
  304. Rand io.Reader
  305. // Time returns the current time as the number of seconds since the epoch.
  306. // If Time is nil, TLS uses time.Now.
  307. Time func() time.Time
  308. // Certificates contains one or more certificate chains to present to
  309. // the other side of the connection. Server configurations must include
  310. // at least one certificate or else set GetCertificate. Clients doing
  311. // client-authentication may set either Certificates or
  312. // GetClientCertificate.
  313. Certificates []Certificate
  314. // NameToCertificate maps from a certificate name to an element of
  315. // Certificates. Note that a certificate name can be of the form
  316. // '*.example.com' and so doesn't have to be a domain name as such.
  317. // See Config.BuildNameToCertificate
  318. // The nil value causes the first element of Certificates to be used
  319. // for all connections.
  320. NameToCertificate map[string]*Certificate
  321. // GetCertificate returns a Certificate based on the given
  322. // ClientHelloInfo. It will only be called if the client supplies SNI
  323. // information or if Certificates is empty.
  324. //
  325. // If GetCertificate is nil or returns nil, then the certificate is
  326. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  327. // first element of Certificates will be used.
  328. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  329. // GetClientCertificate, if not nil, is called when a server requests a
  330. // certificate from a client. If set, the contents of Certificates will
  331. // be ignored.
  332. //
  333. // If GetClientCertificate returns an error, the handshake will be
  334. // aborted and that error will be returned. Otherwise
  335. // GetClientCertificate must return a non-nil Certificate. If
  336. // Certificate.Certificate is empty then no certificate will be sent to
  337. // the server. If this is unacceptable to the server then it may abort
  338. // the handshake.
  339. //
  340. // GetClientCertificate may be called multiple times for the same
  341. // connection if renegotiation occurs or if TLS 1.3 is in use.
  342. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  343. // GetConfigForClient, if not nil, is called after a ClientHello is
  344. // received from a client. It may return a non-nil Config in order to
  345. // change the Config that will be used to handle this connection. If
  346. // the returned Config is nil, the original Config will be used. The
  347. // Config returned by this callback may not be subsequently modified.
  348. //
  349. // If GetConfigForClient is nil, the Config passed to Server() will be
  350. // used for all connections.
  351. //
  352. // Uniquely for the fields in the returned Config, session ticket keys
  353. // will be duplicated from the original Config if not set.
  354. // Specifically, if SetSessionTicketKeys was called on the original
  355. // config but not on the returned config then the ticket keys from the
  356. // original config will be copied into the new config before use.
  357. // Otherwise, if SessionTicketKey was set in the original config but
  358. // not in the returned config then it will be copied into the returned
  359. // config before use. If neither of those cases applies then the key
  360. // material from the returned config will be used for session tickets.
  361. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  362. // VerifyPeerCertificate, if not nil, is called after normal
  363. // certificate verification by either a TLS client or server. It
  364. // receives the raw ASN.1 certificates provided by the peer and also
  365. // any verified chains that normal processing found. If it returns a
  366. // non-nil error, the handshake is aborted and that error results.
  367. //
  368. // If normal verification fails then the handshake will abort before
  369. // considering this callback. If normal verification is disabled by
  370. // setting InsecureSkipVerify then this callback will be considered but
  371. // the verifiedChains argument will always be nil.
  372. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  373. // RootCAs defines the set of root certificate authorities
  374. // that clients use when verifying server certificates.
  375. // If RootCAs is nil, TLS uses the host's root CA set.
  376. RootCAs *x509.CertPool
  377. // NextProtos is a list of supported, application level protocols.
  378. NextProtos []string
  379. // ServerName is used to verify the hostname on the returned
  380. // certificates unless InsecureSkipVerify is given. It is also included
  381. // in the client's handshake to support virtual hosting unless it is
  382. // an IP address.
  383. ServerName string
  384. // ClientAuth determines the server's policy for
  385. // TLS Client Authentication. The default is NoClientCert.
  386. ClientAuth ClientAuthType
  387. // ClientCAs defines the set of root certificate authorities
  388. // that servers use if required to verify a client certificate
  389. // by the policy in ClientAuth.
  390. ClientCAs *x509.CertPool
  391. // InsecureSkipVerify controls whether a client verifies the
  392. // server's certificate chain and host name.
  393. // If InsecureSkipVerify is true, TLS accepts any certificate
  394. // presented by the server and any host name in that certificate.
  395. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  396. // This should be used only for testing.
  397. InsecureSkipVerify bool
  398. // CipherSuites is a list of supported cipher suites. If CipherSuites
  399. // is nil, TLS uses a list of suites supported by the implementation.
  400. CipherSuites []uint16
  401. // PreferServerCipherSuites controls whether the server selects the
  402. // client's most preferred ciphersuite, or the server's most preferred
  403. // ciphersuite. If true then the server's preference, as expressed in
  404. // the order of elements in CipherSuites, is used.
  405. PreferServerCipherSuites bool
  406. // SessionTicketsDisabled may be set to true to disable session ticket
  407. // (resumption) support.
  408. SessionTicketsDisabled bool
  409. // SessionTicketKey is used by TLS servers to provide session
  410. // resumption. See RFC 5077. If zero, it will be filled with
  411. // random data before the first server handshake.
  412. //
  413. // If multiple servers are terminating connections for the same host
  414. // they should all have the same SessionTicketKey. If the
  415. // SessionTicketKey leaks, previously recorded and future TLS
  416. // connections using that key are compromised.
  417. SessionTicketKey [32]byte
  418. // SessionCache is a cache of ClientSessionState entries for TLS session
  419. // resumption.
  420. ClientSessionCache ClientSessionCache
  421. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  422. // If zero, then TLS 1.0 is taken as the minimum.
  423. MinVersion uint16
  424. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  425. // If zero, then the maximum version supported by this package is used,
  426. // which is currently TLS 1.2.
  427. MaxVersion uint16
  428. // CurvePreferences contains the elliptic curves that will be used in
  429. // an ECDHE handshake, in preference order. If empty, the default will
  430. // be used.
  431. CurvePreferences []CurveID
  432. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  433. // When true, the largest possible TLS record size is always used. When
  434. // false, the size of TLS records may be adjusted in an attempt to
  435. // improve latency.
  436. DynamicRecordSizingDisabled bool
  437. // Renegotiation controls what types of renegotiation are supported.
  438. // The default, none, is correct for the vast majority of applications.
  439. Renegotiation RenegotiationSupport
  440. // KeyLogWriter optionally specifies a destination for TLS master secrets
  441. // in NSS key log format that can be used to allow external programs
  442. // such as Wireshark to decrypt TLS connections.
  443. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  444. // Use of KeyLogWriter compromises security and should only be
  445. // used for debugging.
  446. KeyLogWriter io.Writer
  447. // [Psiphon]
  448. // EmulateChrome enables a network traffic obfuscation facility that
  449. // configures the client hello to match the traffic signature of modern
  450. // Chrome browsers using BoringSSL. This affects the selection and
  451. // preference order of ciphersuites, and selection and order of extentions.
  452. // CipherSuites is ignored when EmulateChrome is on.
  453. EmulateChrome bool
  454. serverInitOnce sync.Once // guards calling (*Config).serverInit
  455. // mutex protects sessionTicketKeys and originalConfig.
  456. mutex sync.RWMutex
  457. // sessionTicketKeys contains zero or more ticket keys. If the length
  458. // is zero, SessionTicketsDisabled must be true. The first key is used
  459. // for new tickets and any subsequent keys can be used to decrypt old
  460. // tickets.
  461. sessionTicketKeys []ticketKey
  462. // originalConfig is set to the Config that was passed to Server if
  463. // this Config is returned by a GetConfigForClient callback. It's used
  464. // by serverInit in order to copy session ticket keys if needed.
  465. originalConfig *Config
  466. }
  467. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  468. // an encrypted session ticket in order to identify the key used to encrypt it.
  469. const ticketKeyNameLen = 16
  470. // ticketKey is the internal representation of a session ticket key.
  471. type ticketKey struct {
  472. // keyName is an opaque byte string that serves to identify the session
  473. // ticket key. It's exposed as plaintext in every session ticket.
  474. keyName [ticketKeyNameLen]byte
  475. aesKey [16]byte
  476. hmacKey [16]byte
  477. }
  478. // ticketKeyFromBytes converts from the external representation of a session
  479. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  480. // bytes and this function expands that into sufficient name and key material.
  481. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  482. hashed := sha512.Sum512(b[:])
  483. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  484. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  485. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  486. return key
  487. }
  488. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  489. // being used concurrently by a TLS client or server.
  490. func (c *Config) Clone() *Config {
  491. // Running serverInit ensures that it's safe to read
  492. // SessionTicketsDisabled.
  493. c.serverInitOnce.Do(c.serverInit)
  494. var sessionTicketKeys []ticketKey
  495. c.mutex.RLock()
  496. sessionTicketKeys = c.sessionTicketKeys
  497. c.mutex.RUnlock()
  498. return &Config{
  499. Rand: c.Rand,
  500. Time: c.Time,
  501. Certificates: c.Certificates,
  502. NameToCertificate: c.NameToCertificate,
  503. GetCertificate: c.GetCertificate,
  504. GetConfigForClient: c.GetConfigForClient,
  505. VerifyPeerCertificate: c.VerifyPeerCertificate,
  506. RootCAs: c.RootCAs,
  507. NextProtos: c.NextProtos,
  508. ServerName: c.ServerName,
  509. ClientAuth: c.ClientAuth,
  510. ClientCAs: c.ClientCAs,
  511. InsecureSkipVerify: c.InsecureSkipVerify,
  512. CipherSuites: c.CipherSuites,
  513. PreferServerCipherSuites: c.PreferServerCipherSuites,
  514. SessionTicketsDisabled: c.SessionTicketsDisabled,
  515. SessionTicketKey: c.SessionTicketKey,
  516. ClientSessionCache: c.ClientSessionCache,
  517. MinVersion: c.MinVersion,
  518. MaxVersion: c.MaxVersion,
  519. CurvePreferences: c.CurvePreferences,
  520. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  521. Renegotiation: c.Renegotiation,
  522. KeyLogWriter: c.KeyLogWriter,
  523. sessionTicketKeys: sessionTicketKeys,
  524. // originalConfig is deliberately not duplicated.
  525. }
  526. }
  527. func (c *Config) serverInit() {
  528. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
  529. return
  530. }
  531. var originalConfig *Config
  532. c.mutex.Lock()
  533. originalConfig, c.originalConfig = c.originalConfig, nil
  534. c.mutex.Unlock()
  535. alreadySet := false
  536. for _, b := range c.SessionTicketKey {
  537. if b != 0 {
  538. alreadySet = true
  539. break
  540. }
  541. }
  542. if !alreadySet {
  543. if originalConfig != nil {
  544. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  545. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  546. c.SessionTicketsDisabled = true
  547. return
  548. }
  549. }
  550. if originalConfig != nil {
  551. originalConfig.mutex.RLock()
  552. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  553. originalConfig.mutex.RUnlock()
  554. } else {
  555. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  556. }
  557. }
  558. func (c *Config) ticketKeys() []ticketKey {
  559. c.mutex.RLock()
  560. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  561. // will only update it by replacing it with a new value.
  562. ret := c.sessionTicketKeys
  563. c.mutex.RUnlock()
  564. return ret
  565. }
  566. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  567. // key will be used when creating new tickets, while all keys can be used for
  568. // decrypting tickets. It is safe to call this function while the server is
  569. // running in order to rotate the session ticket keys. The function will panic
  570. // if keys is empty.
  571. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  572. if len(keys) == 0 {
  573. panic("tls: keys must have at least one key")
  574. }
  575. newKeys := make([]ticketKey, len(keys))
  576. for i, bytes := range keys {
  577. newKeys[i] = ticketKeyFromBytes(bytes)
  578. }
  579. c.mutex.Lock()
  580. c.sessionTicketKeys = newKeys
  581. c.mutex.Unlock()
  582. }
  583. func (c *Config) rand() io.Reader {
  584. r := c.Rand
  585. if r == nil {
  586. return rand.Reader
  587. }
  588. return r
  589. }
  590. func (c *Config) time() time.Time {
  591. t := c.Time
  592. if t == nil {
  593. t = time.Now
  594. }
  595. return t()
  596. }
  597. func (c *Config) cipherSuites() []uint16 {
  598. s := c.CipherSuites
  599. if s == nil {
  600. s = defaultCipherSuites()
  601. }
  602. return s
  603. }
  604. func (c *Config) minVersion() uint16 {
  605. if c == nil || c.MinVersion == 0 {
  606. return minVersion
  607. }
  608. return c.MinVersion
  609. }
  610. func (c *Config) maxVersion() uint16 {
  611. if c == nil || c.MaxVersion == 0 {
  612. return maxVersion
  613. }
  614. return c.MaxVersion
  615. }
  616. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  617. func (c *Config) curvePreferences() []CurveID {
  618. if c == nil || len(c.CurvePreferences) == 0 {
  619. return defaultCurvePreferences
  620. }
  621. return c.CurvePreferences
  622. }
  623. // mutualVersion returns the protocol version to use given the advertised
  624. // version of the peer.
  625. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  626. minVersion := c.minVersion()
  627. maxVersion := c.maxVersion()
  628. if vers < minVersion {
  629. return 0, false
  630. }
  631. if vers > maxVersion {
  632. vers = maxVersion
  633. }
  634. return vers, true
  635. }
  636. // getCertificate returns the best certificate for the given ClientHelloInfo,
  637. // defaulting to the first element of c.Certificates.
  638. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  639. if c.GetCertificate != nil &&
  640. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  641. cert, err := c.GetCertificate(clientHello)
  642. if cert != nil || err != nil {
  643. return cert, err
  644. }
  645. }
  646. if len(c.Certificates) == 0 {
  647. return nil, errors.New("tls: no certificates configured")
  648. }
  649. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  650. // There's only one choice, so no point doing any work.
  651. return &c.Certificates[0], nil
  652. }
  653. name := strings.ToLower(clientHello.ServerName)
  654. for len(name) > 0 && name[len(name)-1] == '.' {
  655. name = name[:len(name)-1]
  656. }
  657. if cert, ok := c.NameToCertificate[name]; ok {
  658. return cert, nil
  659. }
  660. // try replacing labels in the name with wildcards until we get a
  661. // match.
  662. labels := strings.Split(name, ".")
  663. for i := range labels {
  664. labels[i] = "*"
  665. candidate := strings.Join(labels, ".")
  666. if cert, ok := c.NameToCertificate[candidate]; ok {
  667. return cert, nil
  668. }
  669. }
  670. // If nothing matches, return the first certificate.
  671. return &c.Certificates[0], nil
  672. }
  673. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  674. // from the CommonName and SubjectAlternateName fields of each of the leaf
  675. // certificates.
  676. func (c *Config) BuildNameToCertificate() {
  677. c.NameToCertificate = make(map[string]*Certificate)
  678. for i := range c.Certificates {
  679. cert := &c.Certificates[i]
  680. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  681. if err != nil {
  682. continue
  683. }
  684. if len(x509Cert.Subject.CommonName) > 0 {
  685. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  686. }
  687. for _, san := range x509Cert.DNSNames {
  688. c.NameToCertificate[san] = cert
  689. }
  690. }
  691. }
  692. // writeKeyLog logs client random and master secret if logging was enabled by
  693. // setting c.KeyLogWriter.
  694. func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
  695. if c.KeyLogWriter == nil {
  696. return nil
  697. }
  698. logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
  699. writerMutex.Lock()
  700. _, err := c.KeyLogWriter.Write(logLine)
  701. writerMutex.Unlock()
  702. return err
  703. }
  704. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  705. // and is only for debugging, so a global mutex saves space.
  706. var writerMutex sync.Mutex
  707. // A Certificate is a chain of one or more certificates, leaf first.
  708. type Certificate struct {
  709. Certificate [][]byte
  710. // PrivateKey contains the private key corresponding to the public key
  711. // in Leaf. For a server, this must implement crypto.Signer and/or
  712. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  713. // (performing client authentication), this must be a crypto.Signer
  714. // with an RSA or ECDSA PublicKey.
  715. PrivateKey crypto.PrivateKey
  716. // OCSPStaple contains an optional OCSP response which will be served
  717. // to clients that request it.
  718. OCSPStaple []byte
  719. // SignedCertificateTimestamps contains an optional list of Signed
  720. // Certificate Timestamps which will be served to clients that request it.
  721. SignedCertificateTimestamps [][]byte
  722. // Leaf is the parsed form of the leaf certificate, which may be
  723. // initialized using x509.ParseCertificate to reduce per-handshake
  724. // processing for TLS clients doing client authentication. If nil, the
  725. // leaf certificate will be parsed as needed.
  726. Leaf *x509.Certificate
  727. }
  728. type handshakeMessage interface {
  729. marshal() []byte
  730. unmarshal([]byte) bool
  731. }
  732. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  733. // caching strategy.
  734. type lruSessionCache struct {
  735. sync.Mutex
  736. m map[string]*list.Element
  737. q *list.List
  738. capacity int
  739. }
  740. type lruSessionCacheEntry struct {
  741. sessionKey string
  742. state *ClientSessionState
  743. }
  744. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  745. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  746. // is used instead.
  747. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  748. const defaultSessionCacheCapacity = 64
  749. if capacity < 1 {
  750. capacity = defaultSessionCacheCapacity
  751. }
  752. return &lruSessionCache{
  753. m: make(map[string]*list.Element),
  754. q: list.New(),
  755. capacity: capacity,
  756. }
  757. }
  758. // Put adds the provided (sessionKey, cs) pair to the cache.
  759. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  760. c.Lock()
  761. defer c.Unlock()
  762. if elem, ok := c.m[sessionKey]; ok {
  763. entry := elem.Value.(*lruSessionCacheEntry)
  764. entry.state = cs
  765. c.q.MoveToFront(elem)
  766. return
  767. }
  768. if c.q.Len() < c.capacity {
  769. entry := &lruSessionCacheEntry{sessionKey, cs}
  770. c.m[sessionKey] = c.q.PushFront(entry)
  771. return
  772. }
  773. elem := c.q.Back()
  774. entry := elem.Value.(*lruSessionCacheEntry)
  775. delete(c.m, entry.sessionKey)
  776. entry.sessionKey = sessionKey
  777. entry.state = cs
  778. c.q.MoveToFront(elem)
  779. c.m[sessionKey] = elem
  780. }
  781. // Get returns the ClientSessionState value associated with a given key. It
  782. // returns (nil, false) if no value is found.
  783. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  784. c.Lock()
  785. defer c.Unlock()
  786. if elem, ok := c.m[sessionKey]; ok {
  787. c.q.MoveToFront(elem)
  788. return elem.Value.(*lruSessionCacheEntry).state, true
  789. }
  790. return nil, false
  791. }
  792. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  793. type dsaSignature struct {
  794. R, S *big.Int
  795. }
  796. type ecdsaSignature dsaSignature
  797. var emptyConfig Config
  798. func defaultConfig() *Config {
  799. return &emptyConfig
  800. }
  801. var (
  802. once sync.Once
  803. varDefaultCipherSuites []uint16
  804. )
  805. func defaultCipherSuites() []uint16 {
  806. once.Do(initDefaultCipherSuites)
  807. return varDefaultCipherSuites
  808. }
  809. func initDefaultCipherSuites() {
  810. var topCipherSuites []uint16
  811. if cipherhw.AESGCMSupport() {
  812. // If AES-GCM hardware is provided then prioritise AES-GCM
  813. // cipher suites.
  814. topCipherSuites = []uint16{
  815. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  816. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  817. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  818. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  819. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  820. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  821. }
  822. } else {
  823. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  824. // cipher suites first.
  825. topCipherSuites = []uint16{
  826. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  827. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  828. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  829. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  830. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  831. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  832. }
  833. }
  834. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  835. for _, topCipher := range topCipherSuites {
  836. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipher)
  837. }
  838. NextCipherSuite:
  839. for _, suite := range cipherSuites {
  840. if suite.flags&suiteDefaultOff != 0 {
  841. continue
  842. }
  843. for _, existing := range varDefaultCipherSuites {
  844. if existing == suite.id {
  845. continue NextCipherSuite
  846. }
  847. }
  848. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  849. }
  850. }
  851. func unexpectedMessageError(wanted, got interface{}) error {
  852. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  853. }
  854. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  855. for _, s := range sigHashes {
  856. if s == sigHash {
  857. return true
  858. }
  859. }
  860. return false
  861. }