Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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