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

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