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

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