Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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