common.go 41 KB

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