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.
 
 
 
 
 
 

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