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.
 
 
 
 
 
 

1158 lines
39 KiB

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