common.go 42 KB

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