common.go 41 KB

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