Alternative TLS implementation in Go
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1245 行
43 KiB

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