Alternative TLS implementation in Go
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

715 строки
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. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  173. }
  174. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  175. // by a client to resume a TLS session with a given server. ClientSessionCache
  176. // implementations should expect to be called concurrently from different
  177. // goroutines.
  178. type ClientSessionCache interface {
  179. // Get searches for a ClientSessionState associated with the given key.
  180. // On return, ok is true if one was found.
  181. Get(sessionKey string) (session *ClientSessionState, ok bool)
  182. // Put adds the ClientSessionState to the cache with the given key.
  183. Put(sessionKey string, cs *ClientSessionState)
  184. }
  185. // ClientHelloInfo contains information from a ClientHello message in order to
  186. // guide certificate selection in the GetCertificate callback.
  187. type ClientHelloInfo struct {
  188. // CipherSuites lists the CipherSuites supported by the client (e.g.
  189. // TLS_RSA_WITH_RC4_128_SHA).
  190. CipherSuites []uint16
  191. // ServerName indicates the name of the server requested by the client
  192. // in order to support virtual hosting. ServerName is only set if the
  193. // client is using SNI (see
  194. // http://tools.ietf.org/html/rfc4366#section-3.1).
  195. ServerName string
  196. // SupportedCurves lists the elliptic curves supported by the client.
  197. // SupportedCurves is set only if the Supported Elliptic Curves
  198. // Extension is being used (see
  199. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  200. SupportedCurves []CurveID
  201. // SupportedPoints lists the point formats supported by the client.
  202. // SupportedPoints is set only if the Supported Point Formats Extension
  203. // is being used (see
  204. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  205. SupportedPoints []uint8
  206. }
  207. // A Config structure is used to configure a TLS client or server.
  208. // After one has been passed to a TLS function it must not be
  209. // modified. A Config may be reused; the tls package will also not
  210. // modify it.
  211. type Config struct {
  212. // Rand provides the source of entropy for nonces and RSA blinding.
  213. // If Rand is nil, TLS uses the cryptographic random reader in package
  214. // crypto/rand.
  215. // The Reader must be safe for use by multiple goroutines.
  216. Rand io.Reader
  217. // Time returns the current time as the number of seconds since the epoch.
  218. // If Time is nil, TLS uses time.Now.
  219. Time func() time.Time
  220. // Certificates contains one or more certificate chains
  221. // to present to the other side of the connection.
  222. // Server configurations must include at least one certificate
  223. // or else set GetCertificate.
  224. Certificates []Certificate
  225. // NameToCertificate maps from a certificate name to an element of
  226. // Certificates. Note that a certificate name can be of the form
  227. // '*.example.com' and so doesn't have to be a domain name as such.
  228. // See Config.BuildNameToCertificate
  229. // The nil value causes the first element of Certificates to be used
  230. // for all connections.
  231. NameToCertificate map[string]*Certificate
  232. // GetCertificate returns a Certificate based on the given
  233. // ClientHelloInfo. It will only be called if the client supplies SNI
  234. // information or if Certificates is empty.
  235. //
  236. // If GetCertificate is nil or returns nil, then the certificate is
  237. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  238. // first element of Certificates will be used.
  239. GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
  240. // RootCAs defines the set of root certificate authorities
  241. // that clients use when verifying server certificates.
  242. // If RootCAs is nil, TLS uses the host's root CA set.
  243. RootCAs *x509.CertPool
  244. // NextProtos is a list of supported, application level protocols.
  245. NextProtos []string
  246. // ServerName is used to verify the hostname on the returned
  247. // certificates unless InsecureSkipVerify is given. It is also included
  248. // in the client's handshake to support virtual hosting unless it is
  249. // an IP address.
  250. ServerName string
  251. // ClientAuth determines the server's policy for
  252. // TLS Client Authentication. The default is NoClientCert.
  253. ClientAuth ClientAuthType
  254. // ClientCAs defines the set of root certificate authorities
  255. // that servers use if required to verify a client certificate
  256. // by the policy in ClientAuth.
  257. ClientCAs *x509.CertPool
  258. // InsecureSkipVerify controls whether a client verifies the
  259. // server's certificate chain and host name.
  260. // If InsecureSkipVerify is true, TLS accepts any certificate
  261. // presented by the server and any host name in that certificate.
  262. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  263. // This should be used only for testing.
  264. InsecureSkipVerify bool
  265. // CipherSuites is a list of supported cipher suites. If CipherSuites
  266. // is nil, TLS uses a list of suites supported by the implementation.
  267. CipherSuites []uint16
  268. // PreferServerCipherSuites controls whether the server selects the
  269. // client's most preferred ciphersuite, or the server's most preferred
  270. // ciphersuite. If true then the server's preference, as expressed in
  271. // the order of elements in CipherSuites, is used.
  272. PreferServerCipherSuites bool
  273. // SessionTicketsDisabled may be set to true to disable session ticket
  274. // (resumption) support.
  275. SessionTicketsDisabled bool
  276. // SessionTicketKey is used by TLS servers to provide session
  277. // resumption. See RFC 5077. If zero, it will be filled with
  278. // random data before the first server handshake.
  279. //
  280. // If multiple servers are terminating connections for the same host
  281. // they should all have the same SessionTicketKey. If the
  282. // SessionTicketKey leaks, previously recorded and future TLS
  283. // connections using that key are compromised.
  284. SessionTicketKey [32]byte
  285. // SessionCache is a cache of ClientSessionState entries for TLS session
  286. // resumption.
  287. ClientSessionCache ClientSessionCache
  288. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  289. // If zero, then TLS 1.0 is taken as the minimum.
  290. MinVersion uint16
  291. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  292. // If zero, then the maximum version supported by this package is used,
  293. // which is currently TLS 1.2.
  294. MaxVersion uint16
  295. // CurvePreferences contains the elliptic curves that will be used in
  296. // an ECDHE handshake, in preference order. If empty, the default will
  297. // be used.
  298. CurvePreferences []CurveID
  299. serverInitOnce sync.Once // guards calling (*Config).serverInit
  300. // mutex protects sessionTicketKeys
  301. mutex sync.RWMutex
  302. // sessionTicketKeys contains zero or more ticket keys. If the length
  303. // is zero, SessionTicketsDisabled must be true. The first key is used
  304. // for new tickets and any subsequent keys can be used to decrypt old
  305. // tickets.
  306. sessionTicketKeys []ticketKey
  307. }
  308. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  309. // an encrypted session ticket in order to identify the key used to encrypt it.
  310. const ticketKeyNameLen = 16
  311. // ticketKey is the internal representation of a session ticket key.
  312. type ticketKey struct {
  313. // keyName is an opaque byte string that serves to identify the session
  314. // ticket key. It's exposed as plaintext in every session ticket.
  315. keyName [ticketKeyNameLen]byte
  316. aesKey [16]byte
  317. hmacKey [16]byte
  318. }
  319. // ticketKeyFromBytes converts from the external representation of a session
  320. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  321. // bytes and this function expands that into sufficient name and key material.
  322. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  323. hashed := sha512.Sum512(b[:])
  324. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  325. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  326. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  327. return key
  328. }
  329. func (c *Config) serverInit() {
  330. if c.SessionTicketsDisabled {
  331. return
  332. }
  333. alreadySet := false
  334. for _, b := range c.SessionTicketKey {
  335. if b != 0 {
  336. alreadySet = true
  337. break
  338. }
  339. }
  340. if !alreadySet {
  341. if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  342. c.SessionTicketsDisabled = true
  343. return
  344. }
  345. }
  346. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  347. }
  348. func (c *Config) ticketKeys() []ticketKey {
  349. c.mutex.RLock()
  350. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  351. // will only update it by replacing it with a new value.
  352. ret := c.sessionTicketKeys
  353. c.mutex.RUnlock()
  354. return ret
  355. }
  356. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  357. // key will be used when creating new tickets, while all keys can be used for
  358. // decrypting tickets. It is safe to call this function while the server is
  359. // running in order to rotate the session ticket keys. The function will panic
  360. // if keys is empty.
  361. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  362. if len(keys) == 0 {
  363. panic("tls: keys must have at least one key")
  364. }
  365. newKeys := make([]ticketKey, len(keys))
  366. for i, bytes := range keys {
  367. newKeys[i] = ticketKeyFromBytes(bytes)
  368. }
  369. c.mutex.Lock()
  370. c.sessionTicketKeys = newKeys
  371. c.mutex.Unlock()
  372. }
  373. func (c *Config) rand() io.Reader {
  374. r := c.Rand
  375. if r == nil {
  376. return rand.Reader
  377. }
  378. return r
  379. }
  380. func (c *Config) time() time.Time {
  381. t := c.Time
  382. if t == nil {
  383. t = time.Now
  384. }
  385. return t()
  386. }
  387. func (c *Config) cipherSuites() []uint16 {
  388. s := c.CipherSuites
  389. if s == nil {
  390. s = defaultCipherSuites()
  391. }
  392. return s
  393. }
  394. func (c *Config) minVersion() uint16 {
  395. if c == nil || c.MinVersion == 0 {
  396. return minVersion
  397. }
  398. return c.MinVersion
  399. }
  400. func (c *Config) maxVersion() uint16 {
  401. if c == nil || c.MaxVersion == 0 {
  402. return maxVersion
  403. }
  404. return c.MaxVersion
  405. }
  406. var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
  407. func (c *Config) curvePreferences() []CurveID {
  408. if c == nil || len(c.CurvePreferences) == 0 {
  409. return defaultCurvePreferences
  410. }
  411. return c.CurvePreferences
  412. }
  413. // mutualVersion returns the protocol version to use given the advertised
  414. // version of the peer.
  415. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  416. minVersion := c.minVersion()
  417. maxVersion := c.maxVersion()
  418. if vers < minVersion {
  419. return 0, false
  420. }
  421. if vers > maxVersion {
  422. vers = maxVersion
  423. }
  424. return vers, true
  425. }
  426. // getCertificate returns the best certificate for the given ClientHelloInfo,
  427. // defaulting to the first element of c.Certificates.
  428. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  429. if c.GetCertificate != nil &&
  430. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  431. cert, err := c.GetCertificate(clientHello)
  432. if cert != nil || err != nil {
  433. return cert, err
  434. }
  435. }
  436. if len(c.Certificates) == 0 {
  437. return nil, errors.New("crypto/tls: no certificates configured")
  438. }
  439. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  440. // There's only one choice, so no point doing any work.
  441. return &c.Certificates[0], nil
  442. }
  443. name := strings.ToLower(clientHello.ServerName)
  444. for len(name) > 0 && name[len(name)-1] == '.' {
  445. name = name[:len(name)-1]
  446. }
  447. if cert, ok := c.NameToCertificate[name]; ok {
  448. return cert, nil
  449. }
  450. // try replacing labels in the name with wildcards until we get a
  451. // match.
  452. labels := strings.Split(name, ".")
  453. for i := range labels {
  454. labels[i] = "*"
  455. candidate := strings.Join(labels, ".")
  456. if cert, ok := c.NameToCertificate[candidate]; ok {
  457. return cert, nil
  458. }
  459. }
  460. // If nothing matches, return the first certificate.
  461. return &c.Certificates[0], nil
  462. }
  463. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  464. // from the CommonName and SubjectAlternateName fields of each of the leaf
  465. // certificates.
  466. func (c *Config) BuildNameToCertificate() {
  467. c.NameToCertificate = make(map[string]*Certificate)
  468. for i := range c.Certificates {
  469. cert := &c.Certificates[i]
  470. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  471. if err != nil {
  472. continue
  473. }
  474. if len(x509Cert.Subject.CommonName) > 0 {
  475. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  476. }
  477. for _, san := range x509Cert.DNSNames {
  478. c.NameToCertificate[san] = cert
  479. }
  480. }
  481. }
  482. // A Certificate is a chain of one or more certificates, leaf first.
  483. type Certificate struct {
  484. Certificate [][]byte
  485. // PrivateKey contains the private key corresponding to the public key
  486. // in Leaf. For a server, this must implement crypto.Signer and/or
  487. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  488. // (performing client authentication), this must be a crypto.Signer
  489. // with an RSA or ECDSA PublicKey.
  490. PrivateKey crypto.PrivateKey
  491. // OCSPStaple contains an optional OCSP response which will be served
  492. // to clients that request it.
  493. OCSPStaple []byte
  494. // SignedCertificateTimestamps contains an optional list of Signed
  495. // Certificate Timestamps which will be served to clients that request it.
  496. SignedCertificateTimestamps [][]byte
  497. // Leaf is the parsed form of the leaf certificate, which may be
  498. // initialized using x509.ParseCertificate to reduce per-handshake
  499. // processing for TLS clients doing client authentication. If nil, the
  500. // leaf certificate will be parsed as needed.
  501. Leaf *x509.Certificate
  502. }
  503. // A TLS record.
  504. type record struct {
  505. contentType recordType
  506. major, minor uint8
  507. payload []byte
  508. }
  509. type handshakeMessage interface {
  510. marshal() []byte
  511. unmarshal([]byte) bool
  512. }
  513. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  514. // caching strategy.
  515. type lruSessionCache struct {
  516. sync.Mutex
  517. m map[string]*list.Element
  518. q *list.List
  519. capacity int
  520. }
  521. type lruSessionCacheEntry struct {
  522. sessionKey string
  523. state *ClientSessionState
  524. }
  525. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  526. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  527. // is used instead.
  528. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  529. const defaultSessionCacheCapacity = 64
  530. if capacity < 1 {
  531. capacity = defaultSessionCacheCapacity
  532. }
  533. return &lruSessionCache{
  534. m: make(map[string]*list.Element),
  535. q: list.New(),
  536. capacity: capacity,
  537. }
  538. }
  539. // Put adds the provided (sessionKey, cs) pair to the cache.
  540. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  541. c.Lock()
  542. defer c.Unlock()
  543. if elem, ok := c.m[sessionKey]; ok {
  544. entry := elem.Value.(*lruSessionCacheEntry)
  545. entry.state = cs
  546. c.q.MoveToFront(elem)
  547. return
  548. }
  549. if c.q.Len() < c.capacity {
  550. entry := &lruSessionCacheEntry{sessionKey, cs}
  551. c.m[sessionKey] = c.q.PushFront(entry)
  552. return
  553. }
  554. elem := c.q.Back()
  555. entry := elem.Value.(*lruSessionCacheEntry)
  556. delete(c.m, entry.sessionKey)
  557. entry.sessionKey = sessionKey
  558. entry.state = cs
  559. c.q.MoveToFront(elem)
  560. c.m[sessionKey] = elem
  561. }
  562. // Get returns the ClientSessionState value associated with a given key. It
  563. // returns (nil, false) if no value is found.
  564. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  565. c.Lock()
  566. defer c.Unlock()
  567. if elem, ok := c.m[sessionKey]; ok {
  568. c.q.MoveToFront(elem)
  569. return elem.Value.(*lruSessionCacheEntry).state, true
  570. }
  571. return nil, false
  572. }
  573. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  574. type dsaSignature struct {
  575. R, S *big.Int
  576. }
  577. type ecdsaSignature dsaSignature
  578. var emptyConfig Config
  579. func defaultConfig() *Config {
  580. return &emptyConfig
  581. }
  582. var (
  583. once sync.Once
  584. varDefaultCipherSuites []uint16
  585. )
  586. func defaultCipherSuites() []uint16 {
  587. once.Do(initDefaultCipherSuites)
  588. return varDefaultCipherSuites
  589. }
  590. func initDefaultCipherSuites() {
  591. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  592. for _, suite := range cipherSuites {
  593. if suite.flags&suiteDefaultOff != 0 {
  594. continue
  595. }
  596. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  597. }
  598. }
  599. func unexpectedMessageError(wanted, got interface{}) error {
  600. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  601. }
  602. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  603. for _, s := range sigHashes {
  604. if s == sigHash {
  605. return true
  606. }
  607. }
  608. return false
  609. }