Alternative TLS implementation in Go
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
pirms 9 gadiem
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
pirms 9 gadiem
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. // TLS13CipherSuites is a list of supported cipher suites to be used in
  442. // TLS 1.3. If nil, uses a list of suites supported by the implementation.
  443. TLS13CipherSuites []uint16
  444. // PreferServerCipherSuites controls whether the server selects the
  445. // client's most preferred ciphersuite, or the server's most preferred
  446. // ciphersuite. If true then the server's preference, as expressed in
  447. // the order of elements in CipherSuites, is used.
  448. PreferServerCipherSuites bool
  449. // SessionTicketsDisabled may be set to true to disable session ticket
  450. // (resumption) support.
  451. SessionTicketsDisabled bool
  452. // SessionTicketKey is used by TLS servers to provide session
  453. // resumption. See RFC 5077. If zero, it will be filled with
  454. // random data before the first server handshake.
  455. //
  456. // If multiple servers are terminating connections for the same host
  457. // they should all have the same SessionTicketKey. If the
  458. // SessionTicketKey leaks, previously recorded and future TLS
  459. // connections using that key are compromised.
  460. SessionTicketKey [32]byte
  461. // SessionCache is a cache of ClientSessionState entries for TLS session
  462. // resumption.
  463. ClientSessionCache ClientSessionCache
  464. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  465. // If zero, then TLS 1.0 is taken as the minimum.
  466. MinVersion uint16
  467. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  468. // If zero, then the maximum version supported by this package is used,
  469. // which is currently TLS 1.2.
  470. MaxVersion uint16
  471. // CurvePreferences contains the elliptic curves that will be used in
  472. // an ECDHE handshake, in preference order. If empty, the default will
  473. // be used.
  474. CurvePreferences []CurveID
  475. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  476. // When true, the largest possible TLS record size is always used. When
  477. // false, the size of TLS records may be adjusted in an attempt to
  478. // improve latency.
  479. DynamicRecordSizingDisabled bool
  480. // Renegotiation controls what types of renegotiation are supported.
  481. // The default, none, is correct for the vast majority of applications.
  482. Renegotiation RenegotiationSupport
  483. // KeyLogWriter optionally specifies a destination for TLS master secrets
  484. // in NSS key log format that can be used to allow external programs
  485. // such as Wireshark to decrypt TLS connections.
  486. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  487. // Use of KeyLogWriter compromises security and should only be
  488. // used for debugging.
  489. KeyLogWriter io.Writer
  490. // If Max0RTTDataSize is not zero, the client will be allowed to use
  491. // session tickets to send at most this number of bytes of 0-RTT data.
  492. // 0-RTT data is subject to replay and has memory DoS implications.
  493. // The server will later be able to refuse the 0-RTT data with
  494. // Accept0RTTData, or wait for the client to prove that it's not
  495. // replayed with Conn.ConfirmHandshake.
  496. //
  497. // It has no meaning on the client.
  498. //
  499. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  500. Max0RTTDataSize uint32
  501. // Accept0RTTData makes the 0-RTT data received from the client
  502. // immediately available to Read. 0-RTT data is subject to replay.
  503. // Use Conn.ConfirmHandshake to wait until the data is known not
  504. // to be replayed after reading it.
  505. //
  506. // It has no meaning on the client.
  507. //
  508. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  509. Accept0RTTData bool
  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. TLS13CipherSuites: c.TLS13CipherSuites,
  567. PreferServerCipherSuites: c.PreferServerCipherSuites,
  568. SessionTicketsDisabled: c.SessionTicketsDisabled,
  569. SessionTicketKey: c.SessionTicketKey,
  570. ClientSessionCache: c.ClientSessionCache,
  571. MinVersion: c.MinVersion,
  572. MaxVersion: c.MaxVersion,
  573. CurvePreferences: c.CurvePreferences,
  574. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  575. Renegotiation: c.Renegotiation,
  576. KeyLogWriter: c.KeyLogWriter,
  577. Accept0RTTData: c.Accept0RTTData,
  578. Max0RTTDataSize: c.Max0RTTDataSize,
  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 {
  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 (c *Config) cipherSuites(version uint16) []uint16 {
  652. if version >= VersionTLS13 {
  653. s := c.TLS13CipherSuites
  654. if s == nil {
  655. s = defaultTLS13CipherSuites()
  656. }
  657. return s
  658. }
  659. s := c.CipherSuites
  660. if s == nil {
  661. s = defaultCipherSuites()
  662. }
  663. return s
  664. }
  665. func (c *Config) minVersion() uint16 {
  666. if c == nil || c.MinVersion == 0 {
  667. return minVersion
  668. }
  669. return c.MinVersion
  670. }
  671. func (c *Config) maxVersion() uint16 {
  672. if c == nil || c.MaxVersion == 0 {
  673. return maxVersion
  674. }
  675. return c.MaxVersion
  676. }
  677. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  678. func (c *Config) curvePreferences() []CurveID {
  679. if c == nil || len(c.CurvePreferences) == 0 {
  680. return defaultCurvePreferences
  681. }
  682. return c.CurvePreferences
  683. }
  684. // mutualVersion returns the protocol version to use given the advertised
  685. // version of the peer using the legacy non-extension methods.
  686. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  687. minVersion := c.minVersion()
  688. maxVersion := c.maxVersion()
  689. // Version 1.3 and higher are not negotiated via this mechanism.
  690. if maxVersion > VersionTLS12 {
  691. maxVersion = VersionTLS12
  692. }
  693. if vers < minVersion {
  694. return 0, false
  695. }
  696. if vers > maxVersion {
  697. vers = maxVersion
  698. }
  699. return vers, true
  700. }
  701. // pickVersion returns the protocol version to use given the advertised
  702. // versions of the peer using the Supported Versions extension.
  703. func (c *Config) pickVersion(supportedVersions []uint16) (uint16, bool) {
  704. minVersion := c.minVersion()
  705. maxVersion := c.maxVersion()
  706. if c == nil || c.MaxVersion == 0 {
  707. maxVersion = VersionTLS13 // override the default if pickVersion is used
  708. }
  709. tls13Enabled := maxVersion >= VersionTLS13
  710. if maxVersion > VersionTLS12 {
  711. maxVersion = VersionTLS12
  712. }
  713. var vers uint16
  714. for _, v := range supportedVersions {
  715. if v >= minVersion && v <= maxVersion ||
  716. (tls13Enabled && v == VersionTLS13Draft18) {
  717. if v > vers {
  718. vers = v
  719. }
  720. }
  721. }
  722. return vers, vers != 0
  723. }
  724. // getCertificate returns the best certificate for the given ClientHelloInfo,
  725. // defaulting to the first element of c.Certificates.
  726. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  727. if c.GetCertificate != nil &&
  728. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  729. cert, err := c.GetCertificate(clientHello)
  730. if cert != nil || err != nil {
  731. return cert, err
  732. }
  733. }
  734. if len(c.Certificates) == 0 {
  735. return nil, errors.New("tls: no certificates configured")
  736. }
  737. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  738. // There's only one choice, so no point doing any work.
  739. return &c.Certificates[0], nil
  740. }
  741. name := strings.ToLower(clientHello.ServerName)
  742. for len(name) > 0 && name[len(name)-1] == '.' {
  743. name = name[:len(name)-1]
  744. }
  745. if cert, ok := c.NameToCertificate[name]; ok {
  746. return cert, nil
  747. }
  748. // try replacing labels in the name with wildcards until we get a
  749. // match.
  750. labels := strings.Split(name, ".")
  751. for i := range labels {
  752. labels[i] = "*"
  753. candidate := strings.Join(labels, ".")
  754. if cert, ok := c.NameToCertificate[candidate]; ok {
  755. return cert, nil
  756. }
  757. }
  758. // If nothing matches, return the first certificate.
  759. return &c.Certificates[0], nil
  760. }
  761. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  762. // from the CommonName and SubjectAlternateName fields of each of the leaf
  763. // certificates.
  764. func (c *Config) BuildNameToCertificate() {
  765. c.NameToCertificate = make(map[string]*Certificate)
  766. for i := range c.Certificates {
  767. cert := &c.Certificates[i]
  768. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  769. if err != nil {
  770. continue
  771. }
  772. if len(x509Cert.Subject.CommonName) > 0 {
  773. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  774. }
  775. for _, san := range x509Cert.DNSNames {
  776. c.NameToCertificate[san] = cert
  777. }
  778. }
  779. }
  780. // writeKeyLog logs client random and master secret if logging was enabled by
  781. // setting c.KeyLogWriter.
  782. func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
  783. if c.KeyLogWriter == nil {
  784. return nil
  785. }
  786. logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
  787. writerMutex.Lock()
  788. _, err := c.KeyLogWriter.Write(logLine)
  789. writerMutex.Unlock()
  790. return err
  791. }
  792. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  793. // and is only for debugging, so a global mutex saves space.
  794. var writerMutex sync.Mutex
  795. // A Certificate is a chain of one or more certificates, leaf first.
  796. type Certificate struct {
  797. Certificate [][]byte
  798. // PrivateKey contains the private key corresponding to the public key
  799. // in Leaf. For a server, this must implement crypto.Signer and/or
  800. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  801. // (performing client authentication), this must be a crypto.Signer
  802. // with an RSA or ECDSA PublicKey.
  803. PrivateKey crypto.PrivateKey
  804. // OCSPStaple contains an optional OCSP response which will be served
  805. // to clients that request it.
  806. OCSPStaple []byte
  807. // SignedCertificateTimestamps contains an optional list of Signed
  808. // Certificate Timestamps which will be served to clients that request it.
  809. SignedCertificateTimestamps [][]byte
  810. // Leaf is the parsed form of the leaf certificate, which may be
  811. // initialized using x509.ParseCertificate to reduce per-handshake
  812. // processing for TLS clients doing client authentication. If nil, the
  813. // leaf certificate will be parsed as needed.
  814. Leaf *x509.Certificate
  815. }
  816. type handshakeMessage interface {
  817. marshal() []byte
  818. unmarshal([]byte) alert
  819. }
  820. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  821. // caching strategy.
  822. type lruSessionCache struct {
  823. sync.Mutex
  824. m map[string]*list.Element
  825. q *list.List
  826. capacity int
  827. }
  828. type lruSessionCacheEntry struct {
  829. sessionKey string
  830. state *ClientSessionState
  831. }
  832. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  833. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  834. // is used instead.
  835. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  836. const defaultSessionCacheCapacity = 64
  837. if capacity < 1 {
  838. capacity = defaultSessionCacheCapacity
  839. }
  840. return &lruSessionCache{
  841. m: make(map[string]*list.Element),
  842. q: list.New(),
  843. capacity: capacity,
  844. }
  845. }
  846. // Put adds the provided (sessionKey, cs) pair to the cache.
  847. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  848. c.Lock()
  849. defer c.Unlock()
  850. if elem, ok := c.m[sessionKey]; ok {
  851. entry := elem.Value.(*lruSessionCacheEntry)
  852. entry.state = cs
  853. c.q.MoveToFront(elem)
  854. return
  855. }
  856. if c.q.Len() < c.capacity {
  857. entry := &lruSessionCacheEntry{sessionKey, cs}
  858. c.m[sessionKey] = c.q.PushFront(entry)
  859. return
  860. }
  861. elem := c.q.Back()
  862. entry := elem.Value.(*lruSessionCacheEntry)
  863. delete(c.m, entry.sessionKey)
  864. entry.sessionKey = sessionKey
  865. entry.state = cs
  866. c.q.MoveToFront(elem)
  867. c.m[sessionKey] = elem
  868. }
  869. // Get returns the ClientSessionState value associated with a given key. It
  870. // returns (nil, false) if no value is found.
  871. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  872. c.Lock()
  873. defer c.Unlock()
  874. if elem, ok := c.m[sessionKey]; ok {
  875. c.q.MoveToFront(elem)
  876. return elem.Value.(*lruSessionCacheEntry).state, true
  877. }
  878. return nil, false
  879. }
  880. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  881. type dsaSignature struct {
  882. R, S *big.Int
  883. }
  884. type ecdsaSignature dsaSignature
  885. var emptyConfig Config
  886. func defaultConfig() *Config {
  887. return &emptyConfig
  888. }
  889. var (
  890. once sync.Once
  891. varDefaultCipherSuites []uint16
  892. varDefaultTLS13CipherSuites []uint16
  893. )
  894. func defaultCipherSuites() []uint16 {
  895. once.Do(initDefaultCipherSuites)
  896. return varDefaultCipherSuites
  897. }
  898. func defaultTLS13CipherSuites() []uint16 {
  899. once.Do(initDefaultCipherSuites)
  900. return varDefaultTLS13CipherSuites
  901. }
  902. func initDefaultCipherSuites() {
  903. var topCipherSuites, topTLS13CipherSuites []uint16
  904. if cipherhw.AESGCMSupport() {
  905. // If AES-GCM hardware is provided then prioritise AES-GCM
  906. // cipher suites.
  907. topTLS13CipherSuites = []uint16{
  908. TLS_AES_128_GCM_SHA256,
  909. TLS_AES_256_GCM_SHA384,
  910. TLS_CHACHA20_POLY1305_SHA256,
  911. }
  912. topCipherSuites = []uint16{
  913. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  914. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  915. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  916. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  917. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  918. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  919. }
  920. } else {
  921. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  922. // cipher suites first.
  923. topTLS13CipherSuites = []uint16{
  924. TLS_CHACHA20_POLY1305_SHA256,
  925. TLS_AES_128_GCM_SHA256,
  926. TLS_AES_256_GCM_SHA384,
  927. }
  928. topCipherSuites = []uint16{
  929. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  930. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  931. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  932. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  933. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  934. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  935. }
  936. }
  937. varDefaultTLS13CipherSuites = make([]uint16, 0, len(cipherSuites))
  938. for _, topCipher := range topTLS13CipherSuites {
  939. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, topCipher)
  940. }
  941. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  942. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  943. NextCipherSuite:
  944. for _, suite := range cipherSuites {
  945. if suite.flags&suiteDefaultOff != 0 {
  946. continue
  947. }
  948. if suite.flags&suiteTLS13 != 0 {
  949. for _, existing := range varDefaultTLS13CipherSuites {
  950. if existing == suite.id {
  951. continue NextCipherSuite
  952. }
  953. }
  954. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, suite.id)
  955. } else {
  956. for _, existing := range varDefaultCipherSuites {
  957. if existing == suite.id {
  958. continue NextCipherSuite
  959. }
  960. }
  961. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  962. }
  963. }
  964. }
  965. func unexpectedMessageError(wanted, got interface{}) error {
  966. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  967. }
  968. func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
  969. for _, s := range sigHashes {
  970. if s == sigHash {
  971. return true
  972. }
  973. }
  974. return false
  975. }