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

common.go 40 KiB

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