common.go 41 KB

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