Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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