common.go 35 KB

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