You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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