Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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