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

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