Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

773 righe
25 KiB

  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. "strings"
  16. "sync"
  17. "time"
  18. )
  19. const (
  20. VersionSSL30 = 0x0300
  21. VersionTLS10 = 0x0301
  22. VersionTLS11 = 0x0302
  23. VersionTLS12 = 0x0303
  24. )
  25. const (
  26. maxPlaintext = 16384 // maximum plaintext payload length
  27. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  28. recordHeaderLen = 5 // record header length
  29. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  30. minVersion = VersionTLS10
  31. maxVersion = VersionTLS12
  32. )
  33. // TLS record types.
  34. type recordType uint8
  35. const (
  36. recordTypeChangeCipherSpec recordType = 20
  37. recordTypeAlert recordType = 21
  38. recordTypeHandshake recordType = 22
  39. recordTypeApplicationData recordType = 23
  40. )
  41. // TLS handshake message types.
  42. const (
  43. typeHelloRequest uint8 = 0
  44. typeClientHello uint8 = 1
  45. typeServerHello uint8 = 2
  46. typeNewSessionTicket uint8 = 4
  47. typeCertificate uint8 = 11
  48. typeServerKeyExchange uint8 = 12
  49. typeCertificateRequest uint8 = 13
  50. typeServerHelloDone uint8 = 14
  51. typeCertificateVerify uint8 = 15
  52. typeClientKeyExchange uint8 = 16
  53. typeFinished uint8 = 20
  54. typeCertificateStatus uint8 = 22
  55. typeNextProtocol uint8 = 67 // Not IANA assigned
  56. )
  57. // TLS compression types.
  58. const (
  59. compressionNone uint8 = 0
  60. )
  61. // TLS extension numbers
  62. const (
  63. extensionServerName uint16 = 0
  64. extensionStatusRequest uint16 = 5
  65. extensionSupportedCurves uint16 = 10
  66. extensionSupportedPoints uint16 = 11
  67. extensionSignatureAlgorithms uint16 = 13
  68. extensionALPN uint16 = 16
  69. extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
  70. extensionSessionTicket uint16 = 35
  71. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  72. extensionRenegotiationInfo uint16 = 0xff01
  73. )
  74. // TLS signaling cipher suite values
  75. const (
  76. scsvRenegotiation uint16 = 0x00ff
  77. )
  78. // CurveID is the type of a TLS identifier for an elliptic curve. See
  79. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  80. type CurveID uint16
  81. const (
  82. CurveP256 CurveID = 23
  83. CurveP384 CurveID = 24
  84. CurveP521 CurveID = 25
  85. )
  86. // TLS Elliptic Curve Point Formats
  87. // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  88. const (
  89. pointFormatUncompressed uint8 = 0
  90. )
  91. // TLS CertificateStatusType (RFC 3546)
  92. const (
  93. statusTypeOCSP uint8 = 1
  94. )
  95. // Certificate types (for certificateRequestMsg)
  96. const (
  97. certTypeRSASign = 1 // A certificate containing an RSA key
  98. certTypeDSSSign = 2 // A certificate containing a DSA key
  99. certTypeRSAFixedDH = 3 // A certificate containing a static DH key
  100. certTypeDSSFixedDH = 4 // A certificate containing a static DH key
  101. // See RFC 4492 sections 3 and 5.5.
  102. certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
  103. certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
  104. certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
  105. // Rest of these are reserved by the TLS spec
  106. )
  107. // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
  108. const (
  109. hashSHA1 uint8 = 2
  110. hashSHA256 uint8 = 4
  111. hashSHA384 uint8 = 5
  112. )
  113. // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
  114. const (
  115. signatureRSA uint8 = 1
  116. signatureECDSA uint8 = 3
  117. )
  118. // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
  119. // RFC 5246, section A.4.1.
  120. type signatureAndHash struct {
  121. hash, signature uint8
  122. }
  123. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  124. // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
  125. // CertificateRequest.
  126. var supportedSignatureAlgorithms = []signatureAndHash{
  127. {hashSHA256, signatureRSA},
  128. {hashSHA256, signatureECDSA},
  129. {hashSHA384, signatureRSA},
  130. {hashSHA384, signatureECDSA},
  131. {hashSHA1, signatureRSA},
  132. {hashSHA1, signatureECDSA},
  133. }
  134. // ConnectionState records basic TLS details about the connection.
  135. type ConnectionState struct {
  136. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  137. HandshakeComplete bool // TLS handshake is complete
  138. DidResume bool // connection resumes a previous TLS connection
  139. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
  140. NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
  141. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
  142. ServerName string // server name requested by client, if any (server side only)
  143. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  144. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  145. SignedCertificateTimestamps [][]byte // SCTs from the server, if any
  146. OCSPResponse []byte // stapled OCSP response from server, if any
  147. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  148. // 5929, section 3). For resumed sessions this value will be nil
  149. // because resumption does not include enough context (see
  150. // https://secure-resumption.com/#channelbindings). This will change in
  151. // future versions of Go once the TLS master-secret fix has been
  152. // standardized and implemented.
  153. TLSUnique []byte
  154. }
  155. // ClientAuthType declares the policy the server will follow for
  156. // TLS Client Authentication.
  157. type ClientAuthType int
  158. const (
  159. NoClientCert ClientAuthType = iota
  160. RequestClientCert
  161. RequireAnyClientCert
  162. VerifyClientCertIfGiven
  163. RequireAndVerifyClientCert
  164. )
  165. // ClientSessionState contains the state needed by clients to resume TLS
  166. // sessions.
  167. type ClientSessionState struct {
  168. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  169. vers uint16 // SSL/TLS version negotiated for the session
  170. cipherSuite uint16 // Ciphersuite negotiated for the session
  171. masterSecret []byte // MasterSecret generated by client on a full handshake
  172. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  173. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  174. }
  175. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  176. // by a client to resume a TLS session with a given server. ClientSessionCache
  177. // implementations should expect to be called concurrently from different
  178. // goroutines.
  179. type ClientSessionCache interface {
  180. // Get searches for a ClientSessionState associated with the given key.
  181. // On return, ok is true if one was found.
  182. Get(sessionKey string) (session *ClientSessionState, ok bool)
  183. // Put adds the ClientSessionState to the cache with the given key.
  184. Put(sessionKey string, cs *ClientSessionState)
  185. }
  186. // ClientHelloInfo contains information from a ClientHello message in order to
  187. // guide certificate selection in the GetCertificate callback.
  188. type ClientHelloInfo struct {
  189. // CipherSuites lists the CipherSuites supported by the client (e.g.
  190. // TLS_RSA_WITH_RC4_128_SHA).
  191. CipherSuites []uint16
  192. // ServerName indicates the name of the server requested by the client
  193. // in order to support virtual hosting. ServerName is only set if the
  194. // client is using SNI (see
  195. // http://tools.ietf.org/html/rfc4366#section-3.1).
  196. ServerName string
  197. // SupportedCurves lists the elliptic curves supported by the client.
  198. // SupportedCurves is set only if the Supported Elliptic Curves
  199. // Extension is being used (see
  200. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  201. SupportedCurves []CurveID
  202. // SupportedPoints lists the point formats supported by the client.
  203. // SupportedPoints is set only if the Supported Point Formats Extension
  204. // is being used (see
  205. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  206. SupportedPoints []uint8
  207. }
  208. // RenegotiationSupport enumerates the different levels of support for TLS
  209. // renegotiation. TLS renegotiation is the act of performing subsequent
  210. // handshakes on a connection after the first. This significantly complicates
  211. // the state machine and has been the source of numerous, subtle security
  212. // issues. Initiating a renegotiation is not supported, but support for
  213. // accepting renegotiation requests may be enabled.
  214. //
  215. // Even when enabled, the server may not change its identity between handshakes
  216. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  217. // handshake and application data flow is not permitted so renegotiation can
  218. // only be used with protocols that synchronise with the renegotiation, such as
  219. // HTTPS.
  220. type RenegotiationSupport int
  221. const (
  222. // RenegotiateNever disables renegotiation.
  223. RenegotiateNever RenegotiationSupport = iota
  224. // RenegotiateOnceAsClient allows a remote server to request
  225. // renegotiation once per connection.
  226. RenegotiateOnceAsClient
  227. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  228. // request renegotiation.
  229. RenegotiateFreelyAsClient
  230. )
  231. // A Config structure is used to configure a TLS client or server.
  232. // After one has been passed to a TLS function it must not be
  233. // modified. A Config may be reused; the tls package will also not
  234. // modify it.
  235. type Config struct {
  236. // Rand provides the source of entropy for nonces and RSA blinding.
  237. // If Rand is nil, TLS uses the cryptographic random reader in package
  238. // crypto/rand.
  239. // The Reader must be safe for use by multiple goroutines.
  240. Rand io.Reader
  241. // Time returns the current time as the number of seconds since the epoch.
  242. // If Time is nil, TLS uses time.Now.
  243. Time func() time.Time
  244. // Certificates contains one or more certificate chains
  245. // to present to the other side of the connection.
  246. // Server configurations must include at least one certificate
  247. // or else set GetCertificate.
  248. Certificates []Certificate
  249. // NameToCertificate maps from a certificate name to an element of
  250. // Certificates. Note that a certificate name can be of the form
  251. // '*.example.com' and so doesn't have to be a domain name as such.
  252. // See Config.BuildNameToCertificate
  253. // The nil value causes the first element of Certificates to be used
  254. // for all connections.
  255. NameToCertificate map[string]*Certificate
  256. // GetCertificate returns a Certificate based on the given
  257. // ClientHelloInfo. It will only be called if the client supplies SNI
  258. // information or if Certificates is empty.
  259. //
  260. // If GetCertificate is nil or returns nil, then the certificate is
  261. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  262. // first element of Certificates will be used.
  263. GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
  264. // RootCAs defines the set of root certificate authorities
  265. // that clients use when verifying server certificates.
  266. // If RootCAs is nil, TLS uses the host's root CA set.
  267. RootCAs *x509.CertPool
  268. // NextProtos is a list of supported, application level protocols.
  269. NextProtos []string
  270. // ServerName is used to verify the hostname on the returned
  271. // certificates unless InsecureSkipVerify is given. It is also included
  272. // in the client's handshake to support virtual hosting unless it is
  273. // an IP address.
  274. ServerName string
  275. // ClientAuth determines the server's policy for
  276. // TLS Client Authentication. The default is NoClientCert.
  277. ClientAuth ClientAuthType
  278. // ClientCAs defines the set of root certificate authorities
  279. // that servers use if required to verify a client certificate
  280. // by the policy in ClientAuth.
  281. ClientCAs *x509.CertPool
  282. // InsecureSkipVerify controls whether a client verifies the
  283. // server's certificate chain and host name.
  284. // If InsecureSkipVerify is true, TLS accepts any certificate
  285. // presented by the server and any host name in that certificate.
  286. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  287. // This should be used only for testing.
  288. InsecureSkipVerify bool
  289. // CipherSuites is a list of supported cipher suites. If CipherSuites
  290. // is nil, TLS uses a list of suites supported by the implementation.
  291. CipherSuites []uint16
  292. // PreferServerCipherSuites controls whether the server selects the
  293. // client's most preferred ciphersuite, or the server's most preferred
  294. // ciphersuite. If true then the server's preference, as expressed in
  295. // the order of elements in CipherSuites, is used.
  296. PreferServerCipherSuites bool
  297. // SessionTicketsDisabled may be set to true to disable session ticket
  298. // (resumption) support.
  299. SessionTicketsDisabled bool
  300. // SessionTicketKey is used by TLS servers to provide session
  301. // resumption. See RFC 5077. If zero, it will be filled with
  302. // random data before the first server handshake.
  303. //
  304. // If multiple servers are terminating connections for the same host
  305. // they should all have the same SessionTicketKey. If the
  306. // SessionTicketKey leaks, previously recorded and future TLS
  307. // connections using that key are compromised.
  308. SessionTicketKey [32]byte
  309. // SessionCache is a cache of ClientSessionState entries for TLS session
  310. // resumption.
  311. ClientSessionCache ClientSessionCache
  312. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  313. // If zero, then TLS 1.0 is taken as the minimum.
  314. MinVersion uint16
  315. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  316. // If zero, then the maximum version supported by this package is used,
  317. // which is currently TLS 1.2.
  318. MaxVersion uint16
  319. // CurvePreferences contains the elliptic curves that will be used in
  320. // an ECDHE handshake, in preference order. If empty, the default will
  321. // be used.
  322. CurvePreferences []CurveID
  323. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  324. // When true, the largest possible TLS record size is always used. When
  325. // false, the size of TLS records may be adjusted in an attempt to
  326. // improve latency.
  327. DynamicRecordSizingDisabled bool
  328. // Renegotiation controls what types of renegotiation are supported.
  329. // The default, none, is correct for the vast majority of applications.
  330. Renegotiation RenegotiationSupport
  331. serverInitOnce sync.Once // guards calling (*Config).serverInit
  332. // mutex protects sessionTicketKeys
  333. mutex sync.RWMutex
  334. // sessionTicketKeys contains zero or more ticket keys. If the length
  335. // is zero, SessionTicketsDisabled must be true. The first key is used
  336. // for new tickets and any subsequent keys can be used to decrypt old
  337. // tickets.
  338. sessionTicketKeys []ticketKey
  339. }
  340. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  341. // an encrypted session ticket in order to identify the key used to encrypt it.
  342. const ticketKeyNameLen = 16
  343. // ticketKey is the internal representation of a session ticket key.
  344. type ticketKey struct {
  345. // keyName is an opaque byte string that serves to identify the session
  346. // ticket key. It's exposed as plaintext in every session ticket.
  347. keyName [ticketKeyNameLen]byte
  348. aesKey [16]byte
  349. hmacKey [16]byte
  350. }
  351. // ticketKeyFromBytes converts from the external representation of a session
  352. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  353. // bytes and this function expands that into sufficient name and key material.
  354. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  355. hashed := sha512.Sum512(b[:])
  356. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  357. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  358. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  359. return key
  360. }
  361. // clone returns a copy of c. Only the exported fields are copied.
  362. func (c *Config) clone() *Config {
  363. return &Config{
  364. Rand: c.Rand,
  365. Time: c.Time,
  366. Certificates: c.Certificates,
  367. NameToCertificate: c.NameToCertificate,
  368. GetCertificate: c.GetCertificate,
  369. RootCAs: c.RootCAs,
  370. NextProtos: c.NextProtos,
  371. ServerName: c.ServerName,
  372. ClientAuth: c.ClientAuth,
  373. ClientCAs: c.ClientCAs,
  374. InsecureSkipVerify: c.InsecureSkipVerify,
  375. CipherSuites: c.CipherSuites,
  376. PreferServerCipherSuites: c.PreferServerCipherSuites,
  377. SessionTicketsDisabled: c.SessionTicketsDisabled,
  378. SessionTicketKey: c.SessionTicketKey,
  379. ClientSessionCache: c.ClientSessionCache,
  380. MinVersion: c.MinVersion,
  381. MaxVersion: c.MaxVersion,
  382. CurvePreferences: c.CurvePreferences,
  383. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  384. Renegotiation: c.Renegotiation,
  385. }
  386. }
  387. func (c *Config) serverInit() {
  388. if c.SessionTicketsDisabled {
  389. return
  390. }
  391. alreadySet := false
  392. for _, b := range c.SessionTicketKey {
  393. if b != 0 {
  394. alreadySet = true
  395. break
  396. }
  397. }
  398. if !alreadySet {
  399. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  400. c.SessionTicketsDisabled = true
  401. return
  402. }
  403. }
  404. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  405. }
  406. func (c *Config) ticketKeys() []ticketKey {
  407. c.mutex.RLock()
  408. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  409. // will only update it by replacing it with a new value.
  410. ret := c.sessionTicketKeys
  411. c.mutex.RUnlock()
  412. return ret
  413. }
  414. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  415. // key will be used when creating new tickets, while all keys can be used for
  416. // decrypting tickets. It is safe to call this function while the server is
  417. // running in order to rotate the session ticket keys. The function will panic
  418. // if keys is empty.
  419. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  420. if len(keys) == 0 {
  421. panic("tls: keys must have at least one key")
  422. }
  423. newKeys := make([]ticketKey, len(keys))
  424. for i, bytes := range keys {
  425. newKeys[i] = ticketKeyFromBytes(bytes)
  426. }
  427. c.mutex.Lock()
  428. c.sessionTicketKeys = newKeys
  429. c.mutex.Unlock()
  430. }
  431. func (c *Config) rand() io.Reader {
  432. r := c.Rand
  433. if r == nil {
  434. return rand.Reader
  435. }
  436. return r
  437. }
  438. func (c *Config) time() time.Time {
  439. t := c.Time
  440. if t == nil {
  441. t = time.Now
  442. }
  443. return t()
  444. }
  445. func (c *Config) cipherSuites() []uint16 {
  446. s := c.CipherSuites
  447. if s == nil {
  448. s = defaultCipherSuites()
  449. }
  450. return s
  451. }
  452. func (c *Config) minVersion() uint16 {
  453. if c == nil || c.MinVersion == 0 {
  454. return minVersion
  455. }
  456. return c.MinVersion
  457. }
  458. func (c *Config) maxVersion() uint16 {
  459. if c == nil || c.MaxVersion == 0 {
  460. return maxVersion
  461. }
  462. return c.MaxVersion
  463. }
  464. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  465. func (c *Config) curvePreferences() []CurveID {
  466. if c == nil || len(c.CurvePreferences) == 0 {
  467. return defaultCurvePreferences
  468. }
  469. return c.CurvePreferences
  470. }
  471. // mutualVersion returns the protocol version to use given the advertised
  472. // version of the peer.
  473. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  474. minVersion := c.minVersion()
  475. maxVersion := c.maxVersion()
  476. if vers < minVersion {
  477. return 0, false
  478. }
  479. if vers > maxVersion {
  480. vers = maxVersion
  481. }
  482. return vers, true
  483. }
  484. // getCertificate returns the best certificate for the given ClientHelloInfo,
  485. // defaulting to the first element of c.Certificates.
  486. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  487. if c.GetCertificate != nil &&
  488. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  489. cert, err := c.GetCertificate(clientHello)
  490. if cert != nil || err != nil {
  491. return cert, err
  492. }
  493. }
  494. if len(c.Certificates) == 0 {
  495. return nil, errors.New("tls: no certificates configured")
  496. }
  497. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  498. // There's only one choice, so no point doing any work.
  499. return &c.Certificates[0], nil
  500. }
  501. name := strings.ToLower(clientHello.ServerName)
  502. for len(name) > 0 && name[len(name)-1] == '.' {
  503. name = name[:len(name)-1]
  504. }
  505. if cert, ok := c.NameToCertificate[name]; ok {
  506. return cert, nil
  507. }
  508. // try replacing labels in the name with wildcards until we get a
  509. // match.
  510. labels := strings.Split(name, ".")
  511. for i := range labels {
  512. labels[i] = "*"
  513. candidate := strings.Join(labels, ".")
  514. if cert, ok := c.NameToCertificate[candidate]; ok {
  515. return cert, nil
  516. }
  517. }
  518. // If nothing matches, return the first certificate.
  519. return &c.Certificates[0], nil
  520. }
  521. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  522. // from the CommonName and SubjectAlternateName fields of each of the leaf
  523. // certificates.
  524. func (c *Config) BuildNameToCertificate() {
  525. c.NameToCertificate = make(map[string]*Certificate)
  526. for i := range c.Certificates {
  527. cert := &c.Certificates[i]
  528. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  529. if err != nil {
  530. continue
  531. }
  532. if len(x509Cert.Subject.CommonName) > 0 {
  533. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  534. }
  535. for _, san := range x509Cert.DNSNames {
  536. c.NameToCertificate[san] = cert
  537. }
  538. }
  539. }
  540. // A Certificate is a chain of one or more certificates, leaf first.
  541. type Certificate struct {
  542. Certificate [][]byte
  543. // PrivateKey contains the private key corresponding to the public key
  544. // in Leaf. For a server, this must implement crypto.Signer and/or
  545. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  546. // (performing client authentication), this must be a crypto.Signer
  547. // with an RSA or ECDSA PublicKey.
  548. PrivateKey crypto.PrivateKey
  549. // OCSPStaple contains an optional OCSP response which will be served
  550. // to clients that request it.
  551. OCSPStaple []byte
  552. // SignedCertificateTimestamps contains an optional list of Signed
  553. // Certificate Timestamps which will be served to clients that request it.
  554. SignedCertificateTimestamps [][]byte
  555. // Leaf is the parsed form of the leaf certificate, which may be
  556. // initialized using x509.ParseCertificate to reduce per-handshake
  557. // processing for TLS clients doing client authentication. If nil, the
  558. // leaf certificate will be parsed as needed.
  559. Leaf *x509.Certificate
  560. }
  561. type handshakeMessage interface {
  562. marshal() []byte
  563. unmarshal([]byte) bool
  564. }
  565. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  566. // caching strategy.
  567. type lruSessionCache struct {
  568. sync.Mutex
  569. m map[string]*list.Element
  570. q *list.List
  571. capacity int
  572. }
  573. type lruSessionCacheEntry struct {
  574. sessionKey string
  575. state *ClientSessionState
  576. }
  577. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  578. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  579. // is used instead.
  580. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  581. const defaultSessionCacheCapacity = 64
  582. if capacity < 1 {
  583. capacity = defaultSessionCacheCapacity
  584. }
  585. return &lruSessionCache{
  586. m: make(map[string]*list.Element),
  587. q: list.New(),
  588. capacity: capacity,
  589. }
  590. }
  591. // Put adds the provided (sessionKey, cs) pair to the cache.
  592. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  593. c.Lock()
  594. defer c.Unlock()
  595. if elem, ok := c.m[sessionKey]; ok {
  596. entry := elem.Value.(*lruSessionCacheEntry)
  597. entry.state = cs
  598. c.q.MoveToFront(elem)
  599. return
  600. }
  601. if c.q.Len() < c.capacity {
  602. entry := &lruSessionCacheEntry{sessionKey, cs}
  603. c.m[sessionKey] = c.q.PushFront(entry)
  604. return
  605. }
  606. elem := c.q.Back()
  607. entry := elem.Value.(*lruSessionCacheEntry)
  608. delete(c.m, entry.sessionKey)
  609. entry.sessionKey = sessionKey
  610. entry.state = cs
  611. c.q.MoveToFront(elem)
  612. c.m[sessionKey] = elem
  613. }
  614. // Get returns the ClientSessionState value associated with a given key. It
  615. // returns (nil, false) if no value is found.
  616. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  617. c.Lock()
  618. defer c.Unlock()
  619. if elem, ok := c.m[sessionKey]; ok {
  620. c.q.MoveToFront(elem)
  621. return elem.Value.(*lruSessionCacheEntry).state, true
  622. }
  623. return nil, false
  624. }
  625. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  626. type dsaSignature struct {
  627. R, S *big.Int
  628. }
  629. type ecdsaSignature dsaSignature
  630. var emptyConfig Config
  631. func defaultConfig() *Config {
  632. return &emptyConfig
  633. }
  634. var (
  635. once sync.Once
  636. varDefaultCipherSuites []uint16
  637. )
  638. func defaultCipherSuites() []uint16 {
  639. once.Do(initDefaultCipherSuites)
  640. return varDefaultCipherSuites
  641. }
  642. func initDefaultCipherSuites() {
  643. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  644. for _, suite := range cipherSuites {
  645. if suite.flags&suiteDefaultOff != 0 {
  646. continue
  647. }
  648. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  649. }
  650. }
  651. func unexpectedMessageError(wanted, got interface{}) error {
  652. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  653. }
  654. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  655. for _, s := range sigHashes {
  656. if s == sigHash {
  657. return true
  658. }
  659. }
  660. return false
  661. }