Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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