25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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