common.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. "os"
  17. "strings"
  18. "sync"
  19. "time"
  20. "golang.org/x/sys/cpu"
  21. )
  22. const (
  23. VersionTLS10 = 0x0301
  24. VersionTLS11 = 0x0302
  25. VersionTLS12 = 0x0303
  26. VersionTLS13 = 0x0304
  27. // Deprecated: SSLv3 is cryptographically broken, and will be
  28. // removed in Go 1.14. See golang.org/issue/32716.
  29. VersionSSL30 = 0x0300
  30. )
  31. const (
  32. maxPlaintext = 16384 // maximum plaintext payload length
  33. maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
  34. maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3
  35. recordHeaderLen = 5 // record header length
  36. maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
  37. maxUselessRecords = 16 // maximum number of consecutive non-advancing records
  38. )
  39. // TLS record types.
  40. type recordType uint8
  41. const (
  42. recordTypeChangeCipherSpec recordType = 20
  43. recordTypeAlert recordType = 21
  44. recordTypeHandshake recordType = 22
  45. recordTypeApplicationData recordType = 23
  46. )
  47. // TLS handshake message types.
  48. const (
  49. typeHelloRequest uint8 = 0
  50. typeClientHello uint8 = 1
  51. typeServerHello uint8 = 2
  52. typeNewSessionTicket uint8 = 4
  53. typeEndOfEarlyData uint8 = 5
  54. typeEncryptedExtensions uint8 = 8
  55. typeCertificate uint8 = 11
  56. typeServerKeyExchange uint8 = 12
  57. typeCertificateRequest uint8 = 13
  58. typeServerHelloDone uint8 = 14
  59. typeCertificateVerify uint8 = 15
  60. typeClientKeyExchange uint8 = 16
  61. typeFinished uint8 = 20
  62. typeCertificateStatus uint8 = 22
  63. typeKeyUpdate uint8 = 24
  64. typeNextProtocol uint8 = 67 // Not IANA assigned
  65. typeMessageHash uint8 = 254 // synthetic message
  66. )
  67. // TLS compression types.
  68. const (
  69. compressionNone uint8 = 0
  70. )
  71. type Extension struct {
  72. Type uint16
  73. Data []byte
  74. }
  75. // TLS extension numbers
  76. const (
  77. extensionServerName uint16 = 0
  78. extensionStatusRequest uint16 = 5
  79. extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
  80. extensionSupportedPoints uint16 = 11
  81. extensionSignatureAlgorithms uint16 = 13
  82. extensionALPN uint16 = 16
  83. extensionSCT uint16 = 18
  84. extensionSessionTicket uint16 = 35
  85. extensionPreSharedKey uint16 = 41
  86. extensionEarlyData uint16 = 42
  87. extensionSupportedVersions uint16 = 43
  88. extensionCookie uint16 = 44
  89. extensionPSKModes uint16 = 45
  90. extensionCertificateAuthorities uint16 = 47
  91. extensionSignatureAlgorithmsCert uint16 = 50
  92. extensionKeyShare uint16 = 51
  93. extensionNextProtoNeg uint16 = 13172 // not IANA assigned
  94. extensionRenegotiationInfo uint16 = 0xff01
  95. )
  96. // TLS signaling cipher suite values
  97. const (
  98. scsvRenegotiation uint16 = 0x00ff
  99. )
  100. type EncryptionLevel uint8
  101. const (
  102. EncryptionHandshake EncryptionLevel = iota
  103. EncryptionApplication
  104. )
  105. // CurveID is a tls.CurveID
  106. type CurveID = tls.CurveID
  107. const (
  108. CurveP256 CurveID = 23
  109. CurveP384 CurveID = 24
  110. CurveP521 CurveID = 25
  111. X25519 CurveID = 29
  112. )
  113. // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
  114. type keyShare struct {
  115. group CurveID
  116. data []byte
  117. }
  118. // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
  119. const (
  120. pskModePlain uint8 = 0
  121. pskModeDHE uint8 = 1
  122. )
  123. // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
  124. // session. See RFC 8446, Section 4.2.11.
  125. type pskIdentity struct {
  126. label []byte
  127. obfuscatedTicketAge uint32
  128. }
  129. // TLS Elliptic Curve Point Formats
  130. // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
  131. const (
  132. pointFormatUncompressed uint8 = 0
  133. )
  134. // TLS CertificateStatusType (RFC 3546)
  135. const (
  136. statusTypeOCSP uint8 = 1
  137. )
  138. // Certificate types (for certificateRequestMsg)
  139. const (
  140. certTypeRSASign = 1
  141. certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
  142. )
  143. // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
  144. // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
  145. const (
  146. signaturePKCS1v15 uint8 = iota + 225
  147. signatureRSAPSS
  148. signatureECDSA
  149. signatureEd25519
  150. )
  151. // directSigning is a standard Hash value that signals that no pre-hashing
  152. // should be performed, and that the input should be signed directly. It is the
  153. // hash function associated with the Ed25519 signature scheme.
  154. var directSigning crypto.Hash = 0
  155. // supportedSignatureAlgorithms contains the signature and hash algorithms that
  156. // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
  157. // CertificateRequest. The two fields are merged to match with TLS 1.3.
  158. // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
  159. var supportedSignatureAlgorithms = []SignatureScheme{
  160. PSSWithSHA256,
  161. ECDSAWithP256AndSHA256,
  162. Ed25519,
  163. PSSWithSHA384,
  164. PSSWithSHA512,
  165. PKCS1WithSHA256,
  166. PKCS1WithSHA384,
  167. PKCS1WithSHA512,
  168. ECDSAWithP384AndSHA384,
  169. ECDSAWithP521AndSHA512,
  170. PKCS1WithSHA1,
  171. ECDSAWithSHA1,
  172. }
  173. // supportedSignatureAlgorithmsTLS12 contains the signature and hash algorithms
  174. // that are supported in TLS 1.2, where it is possible to distinguish the
  175. // protocol version. This is temporary, see Issue 32425.
  176. var supportedSignatureAlgorithmsTLS12 = []SignatureScheme{
  177. PKCS1WithSHA256,
  178. ECDSAWithP256AndSHA256,
  179. Ed25519,
  180. PKCS1WithSHA384,
  181. PKCS1WithSHA512,
  182. ECDSAWithP384AndSHA384,
  183. ECDSAWithP521AndSHA512,
  184. PKCS1WithSHA1,
  185. ECDSAWithSHA1,
  186. }
  187. // helloRetryRequestRandom is set as the Random value of a ServerHello
  188. // to signal that the message is actually a HelloRetryRequest.
  189. var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
  190. 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
  191. 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
  192. 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
  193. 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
  194. }
  195. const (
  196. // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
  197. // random as a downgrade protection if the server would be capable of
  198. // negotiating a higher version. See RFC 8446, Section 4.1.3.
  199. downgradeCanaryTLS12 = "DOWNGRD\x01"
  200. downgradeCanaryTLS11 = "DOWNGRD\x00"
  201. )
  202. // ConnectionState records basic TLS details about the connection.
  203. type ConnectionState struct {
  204. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  205. HandshakeComplete bool // TLS handshake is complete
  206. DidResume bool // connection resumes a previous TLS connection
  207. CipherSuite uint16 // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
  208. NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
  209. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
  210. ServerName string // server name requested by client, if any (server side only)
  211. PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
  212. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  213. SignedCertificateTimestamps [][]byte // SCTs from the peer, if any
  214. OCSPResponse []byte // stapled OCSP response from peer, if any
  215. // ekm is a closure exposed via ExportKeyingMaterial.
  216. ekm func(label string, context []byte, length int) ([]byte, error)
  217. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  218. // 5929, section 3). For resumed sessions this value will be nil
  219. // because resumption does not include enough context (see
  220. // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
  221. // change in future versions of Go once the TLS master-secret fix has
  222. // been standardized and implemented. It is not defined in TLS 1.3.
  223. TLSUnique []byte
  224. }
  225. // ExportKeyingMaterial returns length bytes of exported key material in a new
  226. // slice as defined in RFC 5705. If context is nil, it is not used as part of
  227. // the seed. If the connection was set to allow renegotiation via
  228. // Config.Renegotiation, this function will return an error.
  229. func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
  230. return cs.ekm(label, context, length)
  231. }
  232. // ClientAuthType is tls.ClientAuthType
  233. type ClientAuthType = tls.ClientAuthType
  234. const (
  235. NoClientCert ClientAuthType = iota
  236. RequestClientCert
  237. RequireAnyClientCert
  238. VerifyClientCertIfGiven
  239. RequireAndVerifyClientCert
  240. )
  241. // requiresClientCert reports whether the ClientAuthType requires a client
  242. // certificate to be provided.
  243. func requiresClientCert(c ClientAuthType) bool {
  244. switch c {
  245. case RequireAnyClientCert, RequireAndVerifyClientCert:
  246. return true
  247. default:
  248. return false
  249. }
  250. }
  251. // ClientSessionState contains the state needed by clients to resume TLS
  252. // sessions.
  253. type ClientSessionState struct {
  254. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  255. vers uint16 // SSL/TLS version negotiated for the session
  256. cipherSuite uint16 // Ciphersuite negotiated for the session
  257. masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
  258. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  259. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  260. receivedAt time.Time // When the session ticket was received from the server
  261. // TLS 1.3 fields.
  262. nonce []byte // Ticket nonce sent by the server, to derive PSK
  263. useBy time.Time // Expiration of the ticket lifetime as set by the server
  264. ageAdd uint32 // Random obfuscation factor for sending the ticket age
  265. }
  266. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  267. // by a client to resume a TLS session with a given server. ClientSessionCache
  268. // implementations should expect to be called concurrently from different
  269. // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
  270. // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
  271. // are supported via this interface.
  272. type ClientSessionCache interface {
  273. // Get searches for a ClientSessionState associated with the given key.
  274. // On return, ok is true if one was found.
  275. Get(sessionKey string) (session *ClientSessionState, ok bool)
  276. // Put adds the ClientSessionState to the cache with the given key. It might
  277. // get called multiple times in a connection if a TLS 1.3 server provides
  278. // more than one session ticket. If called with a nil *ClientSessionState,
  279. // it should remove the cache entry.
  280. Put(sessionKey string, cs *ClientSessionState)
  281. }
  282. // SignatureScheme is a tls.SignatureScheme
  283. type SignatureScheme = tls.SignatureScheme
  284. const (
  285. // RSASSA-PKCS1-v1_5 algorithms.
  286. PKCS1WithSHA256 SignatureScheme = 0x0401
  287. PKCS1WithSHA384 SignatureScheme = 0x0501
  288. PKCS1WithSHA512 SignatureScheme = 0x0601
  289. // RSASSA-PSS algorithms with public key OID rsaEncryption.
  290. PSSWithSHA256 SignatureScheme = 0x0804
  291. PSSWithSHA384 SignatureScheme = 0x0805
  292. PSSWithSHA512 SignatureScheme = 0x0806
  293. // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
  294. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  295. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  296. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  297. // EdDSA algorithms.
  298. Ed25519 SignatureScheme = 0x0807
  299. // Legacy signature and hash algorithms for TLS 1.2.
  300. PKCS1WithSHA1 SignatureScheme = 0x0201
  301. ECDSAWithSHA1 SignatureScheme = 0x0203
  302. )
  303. // A ClientHelloInfo is a tls.ClientHelloInfo
  304. type ClientHelloInfo = tls.ClientHelloInfo
  305. // The CertificateRequestInfo is a tls.CertificateRequestInfo
  306. type CertificateRequestInfo = tls.CertificateRequestInfo
  307. // RenegotiationSupport enumerates the different levels of support for TLS
  308. // renegotiation. TLS renegotiation is the act of performing subsequent
  309. // handshakes on a connection after the first. This significantly complicates
  310. // the state machine and has been the source of numerous, subtle security
  311. // issues. Initiating a renegotiation is not supported, but support for
  312. // accepting renegotiation requests may be enabled.
  313. //
  314. // Even when enabled, the server may not change its identity between handshakes
  315. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  316. // handshake and application data flow is not permitted so renegotiation can
  317. // only be used with protocols that synchronise with the renegotiation, such as
  318. // HTTPS.
  319. //
  320. // Renegotiation is not defined in TLS 1.3.
  321. type RenegotiationSupport int
  322. const (
  323. // RenegotiateNever disables renegotiation.
  324. RenegotiateNever RenegotiationSupport = iota
  325. // RenegotiateOnceAsClient allows a remote server to request
  326. // renegotiation once per connection.
  327. RenegotiateOnceAsClient
  328. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  329. // request renegotiation.
  330. RenegotiateFreelyAsClient
  331. )
  332. // A Config structure is used to configure a TLS client or server.
  333. // After one has been passed to a TLS function it must not be
  334. // modified. A Config may be reused; the tls package will also not
  335. // modify it.
  336. type Config struct {
  337. // Rand provides the source of entropy for nonces and RSA blinding.
  338. // If Rand is nil, TLS uses the cryptographic random reader in package
  339. // crypto/rand.
  340. // The Reader must be safe for use by multiple goroutines.
  341. Rand io.Reader
  342. // Time returns the current time as the number of seconds since the epoch.
  343. // If Time is nil, TLS uses time.Now.
  344. Time func() time.Time
  345. // Certificates contains one or more certificate chains to present to
  346. // the other side of the connection. Server configurations must include
  347. // at least one certificate or else set GetCertificate. Clients doing
  348. // client-authentication may set either Certificates or
  349. // GetClientCertificate.
  350. Certificates []Certificate
  351. // NameToCertificate maps from a certificate name to an element of
  352. // Certificates. Note that a certificate name can be of the form
  353. // '*.example.com' and so doesn't have to be a domain name as such.
  354. // See Config.BuildNameToCertificate
  355. // The nil value causes the first element of Certificates to be used
  356. // for all connections.
  357. NameToCertificate map[string]*Certificate
  358. // GetCertificate returns a Certificate based on the given
  359. // ClientHelloInfo. It will only be called if the client supplies SNI
  360. // information or if Certificates is empty.
  361. //
  362. // If GetCertificate is nil or returns nil, then the certificate is
  363. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  364. // first element of Certificates will be used.
  365. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  366. // GetClientCertificate, if not nil, is called when a server requests a
  367. // certificate from a client. If set, the contents of Certificates will
  368. // be ignored.
  369. //
  370. // If GetClientCertificate returns an error, the handshake will be
  371. // aborted and that error will be returned. Otherwise
  372. // GetClientCertificate must return a non-nil Certificate. If
  373. // Certificate.Certificate is empty then no certificate will be sent to
  374. // the server. If this is unacceptable to the server then it may abort
  375. // the handshake.
  376. //
  377. // GetClientCertificate may be called multiple times for the same
  378. // connection if renegotiation occurs or if TLS 1.3 is in use.
  379. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  380. // GetConfigForClient, if not nil, is called after a ClientHello is
  381. // received from a client. It may return a non-nil Config in order to
  382. // change the Config that will be used to handle this connection. If
  383. // the returned Config is nil, the original Config will be used. The
  384. // Config returned by this callback may not be subsequently modified.
  385. //
  386. // If GetConfigForClient is nil, the Config passed to Server() will be
  387. // used for all connections.
  388. //
  389. // Uniquely for the fields in the returned Config, session ticket keys
  390. // will be duplicated from the original Config if not set.
  391. // Specifically, if SetSessionTicketKeys was called on the original
  392. // config but not on the returned config then the ticket keys from the
  393. // original config will be copied into the new config before use.
  394. // Otherwise, if SessionTicketKey was set in the original config but
  395. // not in the returned config then it will be copied into the returned
  396. // config before use. If neither of those cases applies then the key
  397. // material from the returned config will be used for session tickets.
  398. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  399. // VerifyPeerCertificate, if not nil, is called after normal
  400. // certificate verification by either a TLS client or server. It
  401. // receives the raw ASN.1 certificates provided by the peer and also
  402. // any verified chains that normal processing found. If it returns a
  403. // non-nil error, the handshake is aborted and that error results.
  404. //
  405. // If normal verification fails then the handshake will abort before
  406. // considering this callback. If normal verification is disabled by
  407. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  408. // RequestClientCert or RequireAnyClientCert, then this callback will
  409. // be considered but the verifiedChains argument will always be nil.
  410. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  411. // RootCAs defines the set of root certificate authorities
  412. // that clients use when verifying server certificates.
  413. // If RootCAs is nil, TLS uses the host's root CA set.
  414. RootCAs *x509.CertPool
  415. // NextProtos is a list of supported application level protocols, in
  416. // order of preference.
  417. NextProtos []string
  418. // ServerName is used to verify the hostname on the returned
  419. // certificates unless InsecureSkipVerify is given. It is also included
  420. // in the client's handshake to support virtual hosting unless it is
  421. // an IP address.
  422. ServerName string
  423. // ClientAuth determines the server's policy for
  424. // TLS Client Authentication. The default is NoClientCert.
  425. ClientAuth ClientAuthType
  426. // ClientCAs defines the set of root certificate authorities
  427. // that servers use if required to verify a client certificate
  428. // by the policy in ClientAuth.
  429. ClientCAs *x509.CertPool
  430. // InsecureSkipVerify controls whether a client verifies the
  431. // server's certificate chain and host name.
  432. // If InsecureSkipVerify is true, TLS accepts any certificate
  433. // presented by the server and any host name in that certificate.
  434. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  435. // This should be used only for testing.
  436. InsecureSkipVerify bool
  437. // CipherSuites is a list of supported cipher suites for TLS versions up to
  438. // TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
  439. // is used, with a preference order based on hardware performance. The
  440. // default cipher suites might change over Go versions. Note that TLS 1.3
  441. // ciphersuites are not configurable.
  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 and
  449. // PSK (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 resumption.
  453. // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
  454. // with 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 might be 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.3.
  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. The client will use the first preference as the type for
  474. // its key share in TLS 1.3. This may change in the future.
  475. CurvePreferences []CurveID
  476. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  477. // When true, the largest possible TLS record size is always used. When
  478. // false, the size of TLS records may be adjusted in an attempt to
  479. // improve latency.
  480. DynamicRecordSizingDisabled bool
  481. // Renegotiation controls what types of renegotiation are supported.
  482. // The default, none, is correct for the vast majority of applications.
  483. Renegotiation RenegotiationSupport
  484. // KeyLogWriter optionally specifies a destination for TLS master secrets
  485. // in NSS key log format that can be used to allow external programs
  486. // such as Wireshark to decrypt TLS connections.
  487. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  488. // Use of KeyLogWriter compromises security and should only be
  489. // used for debugging.
  490. KeyLogWriter io.Writer
  491. // GetExtensions, if not nil, is called before a message that allows
  492. // sending of extensions is sent.
  493. // Currently only implemented for the ClientHello message (for the client)
  494. // and for the EncryptedExtensions message (for the server).
  495. // Only valid for TLS 1.3.
  496. GetExtensions func(handshakeMessageType uint8) []Extension
  497. // ReceivedExtensions, if not nil, is called when a message that allows the
  498. // inclusion of extensions is received.
  499. // It is called with an empty slice of extensions, if the message didn't
  500. // contain any extensions.
  501. // Currently only implemented for the ClientHello message (sent by the
  502. // client) and for the EncryptedExtensions message (sent by the server).
  503. // Only valid for TLS 1.3.
  504. ReceivedExtensions func(handshakeMessageType uint8, exts []Extension)
  505. serverInitOnce sync.Once // guards calling (*Config).serverInit
  506. // mutex protects sessionTicketKeys.
  507. mutex sync.RWMutex
  508. // sessionTicketKeys contains zero or more ticket keys. If the length
  509. // is zero, SessionTicketsDisabled must be true. The first key is used
  510. // for new tickets and any subsequent keys can be used to decrypt old
  511. // tickets.
  512. sessionTicketKeys []ticketKey
  513. // AlternativeRecordLayer is used by QUIC
  514. AlternativeRecordLayer RecordLayer
  515. // Enforce the selection of a supported application protocol.
  516. // Only works for TLS 1.3.
  517. // If enabled, client and server have to agree on an application protocol.
  518. // Otherwise, connection establishment fails.
  519. EnforceNextProtoSelection bool
  520. }
  521. type RecordLayer interface {
  522. SetReadKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
  523. SetWriteKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
  524. ReadHandshakeMessage() ([]byte, error)
  525. WriteRecord([]byte) (int, error)
  526. SendAlert(uint8)
  527. }
  528. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  529. // an encrypted session ticket in order to identify the key used to encrypt it.
  530. const ticketKeyNameLen = 16
  531. // ticketKey is the internal representation of a session ticket key.
  532. type ticketKey struct {
  533. // keyName is an opaque byte string that serves to identify the session
  534. // ticket key. It's exposed as plaintext in every session ticket.
  535. keyName [ticketKeyNameLen]byte
  536. aesKey [16]byte
  537. hmacKey [16]byte
  538. }
  539. // ticketKeyFromBytes converts from the external representation of a session
  540. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  541. // bytes and this function expands that into sufficient name and key material.
  542. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  543. hashed := sha512.Sum512(b[:])
  544. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  545. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  546. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  547. return key
  548. }
  549. // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
  550. // ticket, and the lifetime we set for tickets we send.
  551. const maxSessionTicketLifetime = 7 * 24 * time.Hour
  552. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  553. // being used concurrently by a TLS client or server.
  554. func (c *Config) Clone() *Config {
  555. // Running serverInit ensures that it's safe to read
  556. // SessionTicketsDisabled.
  557. c.serverInitOnce.Do(func() { c.serverInit(nil) })
  558. var sessionTicketKeys []ticketKey
  559. c.mutex.RLock()
  560. sessionTicketKeys = c.sessionTicketKeys
  561. c.mutex.RUnlock()
  562. return &Config{
  563. Rand: c.Rand,
  564. Time: c.Time,
  565. Certificates: c.Certificates,
  566. NameToCertificate: c.NameToCertificate,
  567. GetCertificate: c.GetCertificate,
  568. GetClientCertificate: c.GetClientCertificate,
  569. GetConfigForClient: c.GetConfigForClient,
  570. VerifyPeerCertificate: c.VerifyPeerCertificate,
  571. RootCAs: c.RootCAs,
  572. NextProtos: c.NextProtos,
  573. ServerName: c.ServerName,
  574. ClientAuth: c.ClientAuth,
  575. ClientCAs: c.ClientCAs,
  576. InsecureSkipVerify: c.InsecureSkipVerify,
  577. CipherSuites: c.CipherSuites,
  578. PreferServerCipherSuites: c.PreferServerCipherSuites,
  579. SessionTicketsDisabled: c.SessionTicketsDisabled,
  580. SessionTicketKey: c.SessionTicketKey,
  581. ClientSessionCache: c.ClientSessionCache,
  582. MinVersion: c.MinVersion,
  583. MaxVersion: c.MaxVersion,
  584. CurvePreferences: c.CurvePreferences,
  585. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  586. Renegotiation: c.Renegotiation,
  587. KeyLogWriter: c.KeyLogWriter,
  588. GetExtensions: c.GetExtensions,
  589. ReceivedExtensions: c.ReceivedExtensions,
  590. sessionTicketKeys: sessionTicketKeys,
  591. EnforceNextProtoSelection: c.EnforceNextProtoSelection,
  592. }
  593. }
  594. // serverInit is run under c.serverInitOnce to do initialization of c. If c was
  595. // returned by a GetConfigForClient callback then the argument should be the
  596. // Config that was passed to Server, otherwise it should be nil.
  597. func (c *Config) serverInit(originalConfig *Config) {
  598. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
  599. return
  600. }
  601. alreadySet := false
  602. for _, b := range c.SessionTicketKey {
  603. if b != 0 {
  604. alreadySet = true
  605. break
  606. }
  607. }
  608. if !alreadySet {
  609. if originalConfig != nil {
  610. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  611. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  612. c.SessionTicketsDisabled = true
  613. return
  614. }
  615. }
  616. if originalConfig != nil {
  617. originalConfig.mutex.RLock()
  618. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  619. originalConfig.mutex.RUnlock()
  620. } else {
  621. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  622. }
  623. }
  624. func (c *Config) ticketKeys() []ticketKey {
  625. c.mutex.RLock()
  626. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  627. // will only update it by replacing it with a new value.
  628. ret := c.sessionTicketKeys
  629. c.mutex.RUnlock()
  630. return ret
  631. }
  632. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  633. // key will be used when creating new tickets, while all keys can be used for
  634. // decrypting tickets. It is safe to call this function while the server is
  635. // running in order to rotate the session ticket keys. The function will panic
  636. // if keys is empty.
  637. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  638. if len(keys) == 0 {
  639. panic("tls: keys must have at least one key")
  640. }
  641. newKeys := make([]ticketKey, len(keys))
  642. for i, bytes := range keys {
  643. newKeys[i] = ticketKeyFromBytes(bytes)
  644. }
  645. c.mutex.Lock()
  646. c.sessionTicketKeys = newKeys
  647. c.mutex.Unlock()
  648. }
  649. func (c *Config) rand() io.Reader {
  650. r := c.Rand
  651. if r == nil {
  652. return rand.Reader
  653. }
  654. return r
  655. }
  656. func (c *Config) time() time.Time {
  657. t := c.Time
  658. if t == nil {
  659. t = time.Now
  660. }
  661. return t()
  662. }
  663. func (c *Config) cipherSuites() []uint16 {
  664. s := c.CipherSuites
  665. if s == nil {
  666. s = defaultCipherSuites()
  667. }
  668. return s
  669. }
  670. var supportedVersions = []uint16{
  671. VersionTLS13,
  672. VersionTLS12,
  673. VersionTLS11,
  674. VersionTLS10,
  675. VersionSSL30,
  676. }
  677. func (c *Config) supportedVersions(isClient bool) []uint16 {
  678. versions := make([]uint16, 0, len(supportedVersions))
  679. for _, v := range supportedVersions {
  680. // TLS 1.0 is the default minimum version.
  681. if (c == nil || c.MinVersion == 0) && v < VersionTLS10 {
  682. continue
  683. }
  684. if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  685. continue
  686. }
  687. if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  688. continue
  689. }
  690. // TLS 1.0 is the minimum version supported as a client.
  691. if isClient && v < VersionTLS10 {
  692. continue
  693. }
  694. // TLS 1.3 is opt-out in Go 1.13.
  695. if v == VersionTLS13 && !isTLS13Supported() {
  696. continue
  697. }
  698. versions = append(versions, v)
  699. }
  700. return versions
  701. }
  702. // tls13Support caches the result for isTLS13Supported.
  703. var tls13Support struct {
  704. sync.Once
  705. cached bool
  706. }
  707. // isTLS13Supported returns whether the program enabled TLS 1.3 by not opting
  708. // out with GODEBUG=tls13=0. It's cached after the first execution.
  709. func isTLS13Supported() bool {
  710. return true
  711. tls13Support.Do(func() {
  712. tls13Support.cached = goDebugString("tls13") != "0"
  713. })
  714. return tls13Support.cached
  715. }
  716. // goDebugString returns the value of the named GODEBUG key.
  717. // GODEBUG is of the form "key=val,key2=val2".
  718. func goDebugString(key string) string {
  719. s := os.Getenv("GODEBUG")
  720. for i := 0; i < len(s)-len(key)-1; i++ {
  721. if i > 0 && s[i-1] != ',' {
  722. continue
  723. }
  724. afterKey := s[i+len(key):]
  725. if afterKey[0] != '=' || s[i:i+len(key)] != key {
  726. continue
  727. }
  728. val := afterKey[1:]
  729. for i, b := range val {
  730. if b == ',' {
  731. return val[:i]
  732. }
  733. }
  734. return val
  735. }
  736. return ""
  737. }
  738. func (c *Config) maxSupportedVersion(isClient bool) uint16 {
  739. supportedVersions := c.supportedVersions(isClient)
  740. if len(supportedVersions) == 0 {
  741. return 0
  742. }
  743. return supportedVersions[0]
  744. }
  745. // supportedVersionsFromMax returns a list of supported versions derived from a
  746. // legacy maximum version value. Note that only versions supported by this
  747. // library are returned. Any newer peer will use supportedVersions anyway.
  748. func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  749. versions := make([]uint16, 0, len(supportedVersions))
  750. for _, v := range supportedVersions {
  751. if v > maxVersion {
  752. continue
  753. }
  754. versions = append(versions, v)
  755. }
  756. return versions
  757. }
  758. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  759. func (c *Config) curvePreferences() []CurveID {
  760. if c == nil || len(c.CurvePreferences) == 0 {
  761. return defaultCurvePreferences
  762. }
  763. return c.CurvePreferences
  764. }
  765. // mutualVersion returns the protocol version to use given the advertised
  766. // versions of the peer. Priority is given to the peer preference order.
  767. func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
  768. supportedVersions := c.supportedVersions(isClient)
  769. for _, peerVersion := range peerVersions {
  770. for _, v := range supportedVersions {
  771. if v == peerVersion {
  772. return v, true
  773. }
  774. }
  775. }
  776. return 0, false
  777. }
  778. // getCertificate returns the best certificate for the given ClientHelloInfo,
  779. // defaulting to the first element of c.Certificates.
  780. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  781. if c.GetCertificate != nil &&
  782. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  783. cert, err := c.GetCertificate(clientHello)
  784. if cert != nil || err != nil {
  785. return cert, err
  786. }
  787. }
  788. if len(c.Certificates) == 0 {
  789. return nil, errors.New("tls: no certificates configured")
  790. }
  791. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  792. // There's only one choice, so no point doing any work.
  793. return &c.Certificates[0], nil
  794. }
  795. name := strings.ToLower(clientHello.ServerName)
  796. for len(name) > 0 && name[len(name)-1] == '.' {
  797. name = name[:len(name)-1]
  798. }
  799. if cert, ok := c.NameToCertificate[name]; ok {
  800. return cert, nil
  801. }
  802. // try replacing labels in the name with wildcards until we get a
  803. // match.
  804. labels := strings.Split(name, ".")
  805. for i := range labels {
  806. labels[i] = "*"
  807. candidate := strings.Join(labels, ".")
  808. if cert, ok := c.NameToCertificate[candidate]; ok {
  809. return cert, nil
  810. }
  811. }
  812. // If nothing matches, return the first certificate.
  813. return &c.Certificates[0], nil
  814. }
  815. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  816. // from the CommonName and SubjectAlternateName fields of each of the leaf
  817. // certificates.
  818. func (c *Config) BuildNameToCertificate() {
  819. c.NameToCertificate = make(map[string]*Certificate)
  820. for i := range c.Certificates {
  821. cert := &c.Certificates[i]
  822. x509Cert := cert.Leaf
  823. if x509Cert == nil {
  824. var err error
  825. x509Cert, err = x509.ParseCertificate(cert.Certificate[0])
  826. if err != nil {
  827. continue
  828. }
  829. }
  830. if len(x509Cert.Subject.CommonName) > 0 {
  831. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  832. }
  833. for _, san := range x509Cert.DNSNames {
  834. c.NameToCertificate[san] = cert
  835. }
  836. }
  837. }
  838. const (
  839. keyLogLabelTLS12 = "CLIENT_RANDOM"
  840. keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  841. keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  842. keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"
  843. keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"
  844. )
  845. func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
  846. if c.KeyLogWriter == nil {
  847. return nil
  848. }
  849. logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
  850. writerMutex.Lock()
  851. _, err := c.KeyLogWriter.Write(logLine)
  852. writerMutex.Unlock()
  853. return err
  854. }
  855. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  856. // and is only for debugging, so a global mutex saves space.
  857. var writerMutex sync.Mutex
  858. // A Certificate is a tls.Certificate
  859. type Certificate = tls.Certificate
  860. type handshakeMessage interface {
  861. marshal() []byte
  862. unmarshal([]byte) bool
  863. }
  864. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  865. // caching strategy.
  866. type lruSessionCache struct {
  867. sync.Mutex
  868. m map[string]*list.Element
  869. q *list.List
  870. capacity int
  871. }
  872. type lruSessionCacheEntry struct {
  873. sessionKey string
  874. state *ClientSessionState
  875. }
  876. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  877. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  878. // is used instead.
  879. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  880. const defaultSessionCacheCapacity = 64
  881. if capacity < 1 {
  882. capacity = defaultSessionCacheCapacity
  883. }
  884. return &lruSessionCache{
  885. m: make(map[string]*list.Element),
  886. q: list.New(),
  887. capacity: capacity,
  888. }
  889. }
  890. // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  891. // corresponding to sessionKey is removed from the cache instead.
  892. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  893. c.Lock()
  894. defer c.Unlock()
  895. if elem, ok := c.m[sessionKey]; ok {
  896. if cs == nil {
  897. c.q.Remove(elem)
  898. delete(c.m, sessionKey)
  899. } else {
  900. entry := elem.Value.(*lruSessionCacheEntry)
  901. entry.state = cs
  902. c.q.MoveToFront(elem)
  903. }
  904. return
  905. }
  906. if c.q.Len() < c.capacity {
  907. entry := &lruSessionCacheEntry{sessionKey, cs}
  908. c.m[sessionKey] = c.q.PushFront(entry)
  909. return
  910. }
  911. elem := c.q.Back()
  912. entry := elem.Value.(*lruSessionCacheEntry)
  913. delete(c.m, entry.sessionKey)
  914. entry.sessionKey = sessionKey
  915. entry.state = cs
  916. c.q.MoveToFront(elem)
  917. c.m[sessionKey] = elem
  918. }
  919. // Get returns the ClientSessionState value associated with a given key. It
  920. // returns (nil, false) if no value is found.
  921. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  922. c.Lock()
  923. defer c.Unlock()
  924. if elem, ok := c.m[sessionKey]; ok {
  925. c.q.MoveToFront(elem)
  926. return elem.Value.(*lruSessionCacheEntry).state, true
  927. }
  928. return nil, false
  929. }
  930. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  931. type dsaSignature struct {
  932. R, S *big.Int
  933. }
  934. type ecdsaSignature dsaSignature
  935. var emptyConfig Config
  936. func defaultConfig() *Config {
  937. return &emptyConfig
  938. }
  939. var (
  940. once sync.Once
  941. varDefaultCipherSuites []uint16
  942. varDefaultCipherSuitesTLS13 []uint16
  943. )
  944. func defaultCipherSuites() []uint16 {
  945. once.Do(initDefaultCipherSuites)
  946. return varDefaultCipherSuites
  947. }
  948. func defaultCipherSuitesTLS13() []uint16 {
  949. once.Do(initDefaultCipherSuites)
  950. return varDefaultCipherSuitesTLS13
  951. }
  952. func initDefaultCipherSuites() {
  953. var topCipherSuites []uint16
  954. // Check the cpu flags for each platform that has optimized GCM implementations.
  955. // Worst case, these variables will just all be false.
  956. var (
  957. hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
  958. hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
  959. // Keep in sync with crypto/aes/cipher_s390x.go.
  960. // TODO: check for s390
  961. // hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
  962. hasGCMAsmS390X = false
  963. hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
  964. )
  965. // x/sys/cpu does not respect GODEBUG=cpu.all=off. As a workaround,
  966. // check it here. See https://github.com/golang/go/issues/33963
  967. if strings.Contains(os.Getenv("GODEBUG"), "cpu.all=off") {
  968. hasGCMAsm = false
  969. }
  970. if hasGCMAsm {
  971. // If AES-GCM hardware is provided then prioritise AES-GCM
  972. // cipher suites.
  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. varDefaultCipherSuitesTLS13 = []uint16{
  982. TLS_AES_128_GCM_SHA256,
  983. TLS_CHACHA20_POLY1305_SHA256,
  984. TLS_AES_256_GCM_SHA384,
  985. }
  986. } else {
  987. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  988. // cipher suites first.
  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. varDefaultCipherSuitesTLS13 = []uint16{
  998. TLS_CHACHA20_POLY1305_SHA256,
  999. TLS_AES_128_GCM_SHA256,
  1000. TLS_AES_256_GCM_SHA384,
  1001. }
  1002. }
  1003. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1004. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1005. NextCipherSuite:
  1006. for _, suite := range cipherSuites {
  1007. if suite.flags&suiteDefaultOff != 0 {
  1008. continue
  1009. }
  1010. for _, existing := range varDefaultCipherSuites {
  1011. if existing == suite.id {
  1012. continue NextCipherSuite
  1013. }
  1014. }
  1015. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1016. }
  1017. }
  1018. func unexpectedMessageError(wanted, got interface{}) error {
  1019. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1020. }
  1021. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1022. for _, s := range supportedSignatureAlgorithms {
  1023. if s == sigAlg {
  1024. return true
  1025. }
  1026. }
  1027. return false
  1028. }
  1029. // signatureFromSignatureScheme maps a signature algorithm to the underlying
  1030. // signature method (without hash function).
  1031. func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1032. switch signatureAlgorithm {
  1033. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1034. return signaturePKCS1v15
  1035. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1036. return signatureRSAPSS
  1037. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1038. return signatureECDSA
  1039. case Ed25519:
  1040. return signatureEd25519
  1041. default:
  1042. return 0
  1043. }
  1044. }