Alternative TLS implementation in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1244 line
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 tls
  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. }
  215. // ClientAuthType declares the policy the server will follow for
  216. // TLS Client Authentication.
  217. type ClientAuthType int
  218. const (
  219. NoClientCert ClientAuthType = iota
  220. RequestClientCert
  221. RequireAnyClientCert
  222. VerifyClientCertIfGiven
  223. RequireAndVerifyClientCert
  224. )
  225. // ClientSessionState contains the state needed by clients to resume TLS
  226. // sessions.
  227. type ClientSessionState struct {
  228. sessionTicket []uint8 // Encrypted ticket used for session resumption with server
  229. vers uint16 // SSL/TLS version negotiated for the session
  230. cipherSuite uint16 // Ciphersuite negotiated for the session
  231. masterSecret []byte // MasterSecret generated by client on a full handshake
  232. serverCertificates []*x509.Certificate // Certificate chain presented by the server
  233. verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
  234. useEMS bool // State of extended master secret
  235. }
  236. // ClientSessionCache is a cache of ClientSessionState objects that can be used
  237. // by a client to resume a TLS session with a given server. ClientSessionCache
  238. // implementations should expect to be called concurrently from different
  239. // goroutines. Only ticket-based resumption is supported, not SessionID-based
  240. // resumption.
  241. type ClientSessionCache interface {
  242. // Get searches for a ClientSessionState associated with the given key.
  243. // On return, ok is true if one was found.
  244. Get(sessionKey string) (session *ClientSessionState, ok bool)
  245. // Put adds the ClientSessionState to the cache with the given key.
  246. Put(sessionKey string, cs *ClientSessionState)
  247. }
  248. // SignatureScheme identifies a signature algorithm supported by TLS. See
  249. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
  250. type SignatureScheme uint16
  251. const (
  252. PKCS1WithSHA1 SignatureScheme = 0x0201
  253. PKCS1WithSHA256 SignatureScheme = 0x0401
  254. PKCS1WithSHA384 SignatureScheme = 0x0501
  255. PKCS1WithSHA512 SignatureScheme = 0x0601
  256. PSSWithSHA256 SignatureScheme = 0x0804
  257. PSSWithSHA384 SignatureScheme = 0x0805
  258. PSSWithSHA512 SignatureScheme = 0x0806
  259. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  260. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  261. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  262. // Legacy signature and hash algorithms for TLS 1.2.
  263. ECDSAWithSHA1 SignatureScheme = 0x0203
  264. )
  265. // ClientHelloInfo contains information from a ClientHello message in order to
  266. // guide certificate selection in the GetCertificate callback.
  267. type ClientHelloInfo struct {
  268. // CipherSuites lists the CipherSuites supported by the client (e.g.
  269. // TLS_RSA_WITH_RC4_128_SHA).
  270. CipherSuites []uint16
  271. // ServerName indicates the name of the server requested by the client
  272. // in order to support virtual hosting. ServerName is only set if the
  273. // client is using SNI (see
  274. // http://tools.ietf.org/html/rfc4366#section-3.1).
  275. ServerName string
  276. // SupportedCurves lists the elliptic curves supported by the client.
  277. // SupportedCurves is set only if the Supported Elliptic Curves
  278. // Extension is being used (see
  279. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  280. SupportedCurves []CurveID
  281. // SupportedPoints lists the point formats supported by the client.
  282. // SupportedPoints is set only if the Supported Point Formats Extension
  283. // is being used (see
  284. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  285. SupportedPoints []uint8
  286. // SignatureSchemes lists the signature and hash schemes that the client
  287. // is willing to verify. SignatureSchemes is set only if the Signature
  288. // Algorithms Extension is being used (see
  289. // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  290. SignatureSchemes []SignatureScheme
  291. // SupportedProtos lists the application protocols supported by the client.
  292. // SupportedProtos is set only if the Application-Layer Protocol
  293. // Negotiation Extension is being used (see
  294. // https://tools.ietf.org/html/rfc7301#section-3.1).
  295. //
  296. // Servers can select a protocol by setting Config.NextProtos in a
  297. // GetConfigForClient return value.
  298. SupportedProtos []string
  299. // SupportedVersions lists the TLS versions supported by the client.
  300. // For TLS versions less than 1.3, this is extrapolated from the max
  301. // version advertised by the client, so values other than the greatest
  302. // might be rejected if used.
  303. SupportedVersions []uint16
  304. // Conn is the underlying net.Conn for the connection. Do not read
  305. // from, or write to, this connection; that will cause the TLS
  306. // connection to fail.
  307. Conn net.Conn
  308. // Offered0RTTData is true if the client announced that it will send
  309. // 0-RTT data. If the server Config.Accept0RTTData is true, and the
  310. // client offered a session ticket valid for that purpose, it will
  311. // be notified that the 0-RTT data is accepted and it will be made
  312. // immediately available for Read.
  313. Offered0RTTData bool
  314. // AcceptsDelegatedCredential is true if the client indicated willingness
  315. // to negotiate the delegated credential extension.
  316. AcceptsDelegatedCredential bool
  317. // The Fingerprint is an sequence of bytes unique to this Client Hello.
  318. // It can be used to prevent or mitigate 0-RTT data replays as it's
  319. // guaranteed that a replayed connection will have the same Fingerprint.
  320. Fingerprint []byte
  321. }
  322. // CertificateRequestInfo contains information from a server's
  323. // CertificateRequest message, which is used to demand a certificate and proof
  324. // of control from a client.
  325. type CertificateRequestInfo struct {
  326. // AcceptableCAs contains zero or more, DER-encoded, X.501
  327. // Distinguished Names. These are the names of root or intermediate CAs
  328. // that the server wishes the returned certificate to be signed by. An
  329. // empty slice indicates that the server has no preference.
  330. AcceptableCAs [][]byte
  331. // SignatureSchemes lists the signature schemes that the server is
  332. // willing to verify.
  333. SignatureSchemes []SignatureScheme
  334. }
  335. // RenegotiationSupport enumerates the different levels of support for TLS
  336. // renegotiation. TLS renegotiation is the act of performing subsequent
  337. // handshakes on a connection after the first. This significantly complicates
  338. // the state machine and has been the source of numerous, subtle security
  339. // issues. Initiating a renegotiation is not supported, but support for
  340. // accepting renegotiation requests may be enabled.
  341. //
  342. // Even when enabled, the server may not change its identity between handshakes
  343. // (i.e. the leaf certificate must be the same). Additionally, concurrent
  344. // handshake and application data flow is not permitted so renegotiation can
  345. // only be used with protocols that synchronise with the renegotiation, such as
  346. // HTTPS.
  347. type RenegotiationSupport int
  348. const (
  349. // RenegotiateNever disables renegotiation.
  350. RenegotiateNever RenegotiationSupport = iota
  351. // RenegotiateOnceAsClient allows a remote server to request
  352. // renegotiation once per connection.
  353. RenegotiateOnceAsClient
  354. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  355. // request renegotiation.
  356. RenegotiateFreelyAsClient
  357. )
  358. // A Config structure is used to configure a TLS client or server.
  359. // After one has been passed to a TLS function it must not be
  360. // modified. A Config may be reused; the tls package will also not
  361. // modify it.
  362. type Config struct {
  363. // Rand provides the source of entropy for nonces and RSA blinding.
  364. // If Rand is nil, TLS uses the cryptographic random reader in package
  365. // crypto/rand.
  366. // The Reader must be safe for use by multiple goroutines.
  367. Rand io.Reader
  368. // Time returns the current time as the number of seconds since the epoch.
  369. // If Time is nil, TLS uses time.Now.
  370. Time func() time.Time
  371. // Certificates contains one or more certificate chains to present to
  372. // the other side of the connection. Server configurations must include
  373. // at least one certificate or else set GetCertificate. Clients doing
  374. // client-authentication may set either Certificates or
  375. // GetClientCertificate.
  376. Certificates []Certificate
  377. // NameToCertificate maps from a certificate name to an element of
  378. // Certificates. Note that a certificate name can be of the form
  379. // '*.example.com' and so doesn't have to be a domain name as such.
  380. // See Config.BuildNameToCertificate
  381. // The nil value causes the first element of Certificates to be used
  382. // for all connections.
  383. NameToCertificate map[string]*Certificate
  384. // GetCertificate returns a Certificate based on the given
  385. // ClientHelloInfo. It will only be called if the client supplies SNI
  386. // information or if Certificates is empty.
  387. //
  388. // If GetCertificate is nil or returns nil, then the certificate is
  389. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  390. // first element of Certificates will be used.
  391. GetCertificate func(*ClientHelloInfo) (*Certificate, error)
  392. // GetClientCertificate, if not nil, is called when a server requests a
  393. // certificate from a client. If set, the contents of Certificates will
  394. // be ignored.
  395. //
  396. // If GetClientCertificate returns an error, the handshake will be
  397. // aborted and that error will be returned. Otherwise
  398. // GetClientCertificate must return a non-nil Certificate. If
  399. // Certificate.Certificate is empty then no certificate will be sent to
  400. // the server. If this is unacceptable to the server then it may abort
  401. // the handshake.
  402. //
  403. // GetClientCertificate may be called multiple times for the same
  404. // connection if renegotiation occurs or if TLS 1.3 is in use.
  405. GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
  406. // GetConfigForClient, if not nil, is called after a ClientHello is
  407. // received from a client. It may return a non-nil Config in order to
  408. // change the Config that will be used to handle this connection. If
  409. // the returned Config is nil, the original Config will be used. The
  410. // Config returned by this callback may not be subsequently modified.
  411. //
  412. // If GetConfigForClient is nil, the Config passed to Server() will be
  413. // used for all connections.
  414. //
  415. // Uniquely for the fields in the returned Config, session ticket keys
  416. // will be duplicated from the original Config if not set.
  417. // Specifically, if SetSessionTicketKeys was called on the original
  418. // config but not on the returned config then the ticket keys from the
  419. // original config will be copied into the new config before use.
  420. // Otherwise, if SessionTicketKey was set in the original config but
  421. // not in the returned config then it will be copied into the returned
  422. // config before use. If neither of those cases applies then the key
  423. // material from the returned config will be used for session tickets.
  424. GetConfigForClient func(*ClientHelloInfo) (*Config, error)
  425. // VerifyPeerCertificate, if not nil, is called after normal
  426. // certificate verification by either a TLS client or server. It
  427. // receives the raw ASN.1 certificates provided by the peer and also
  428. // any verified chains that normal processing found. If it returns a
  429. // non-nil error, the handshake is aborted and that error results.
  430. //
  431. // If normal verification fails then the handshake will abort before
  432. // considering this callback. If normal verification is disabled by
  433. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  434. // RequestClientCert or RequireAnyClientCert, then this callback will
  435. // be considered but the verifiedChains argument will always be nil.
  436. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  437. // RootCAs defines the set of root certificate authorities
  438. // that clients use when verifying server certificates.
  439. // If RootCAs is nil, TLS uses the host's root CA set.
  440. RootCAs *x509.CertPool
  441. // NextProtos is a list of supported, application level protocols.
  442. NextProtos []string
  443. // ServerName is used to verify the hostname on the returned
  444. // certificates unless InsecureSkipVerify is given. It is also included
  445. // in the client's handshake to support virtual hosting unless it is
  446. // an IP address.
  447. ServerName string
  448. // ClientAuth determines the server's policy for
  449. // TLS Client Authentication. The default is NoClientCert.
  450. ClientAuth ClientAuthType
  451. // ClientCAs defines the set of root certificate authorities
  452. // that servers use if required to verify a client certificate
  453. // by the policy in ClientAuth.
  454. ClientCAs *x509.CertPool
  455. // InsecureSkipVerify controls whether a client verifies the
  456. // server's certificate chain and host name.
  457. // If InsecureSkipVerify is true, TLS accepts any certificate
  458. // presented by the server and any host name in that certificate.
  459. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  460. // This should be used only for testing.
  461. InsecureSkipVerify bool
  462. // CipherSuites is a list of supported cipher suites to be used in
  463. // TLS 1.0-1.2. If CipherSuites is nil, TLS uses a list of suites
  464. // supported by the implementation.
  465. CipherSuites []uint16
  466. // PreferServerCipherSuites controls whether the server selects the
  467. // client's most preferred ciphersuite, or the server's most preferred
  468. // ciphersuite. If true then the server's preference, as expressed in
  469. // the order of elements in CipherSuites, is used.
  470. PreferServerCipherSuites bool
  471. // SessionTicketsDisabled may be set to true to disable session ticket
  472. // (resumption) support. Note that on clients, session ticket support is
  473. // also disabled if ClientSessionCache is nil.
  474. SessionTicketsDisabled bool
  475. // SessionTicketKey is used by TLS servers to provide session
  476. // resumption. See RFC 5077. If zero, it will be filled with
  477. // random data before the first server handshake.
  478. //
  479. // If multiple servers are terminating connections for the same host
  480. // they should all have the same SessionTicketKey. If the
  481. // SessionTicketKey leaks, previously recorded and future TLS
  482. // connections using that key are compromised.
  483. SessionTicketKey [32]byte
  484. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  485. // session resumption. It is only used by clients.
  486. ClientSessionCache ClientSessionCache
  487. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  488. // If zero, then TLS 1.0 is taken as the minimum.
  489. MinVersion uint16
  490. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  491. // If zero, then the maximum version supported by this package is used,
  492. // which is currently TLS 1.2.
  493. MaxVersion uint16
  494. // CurvePreferences contains the elliptic curves that will be used in
  495. // an ECDHE handshake, in preference order. If empty, the default will
  496. // be used.
  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. // If Max0RTTDataSize is not zero, the client will be allowed to use
  514. // session tickets to send at most this number of bytes of 0-RTT data.
  515. // 0-RTT data is subject to replay and has memory DoS implications.
  516. // The server will later be able to refuse the 0-RTT data with
  517. // Accept0RTTData, or wait for the client to prove that it's not
  518. // replayed with Conn.ConfirmHandshake.
  519. //
  520. // It has no meaning on the client.
  521. //
  522. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  523. Max0RTTDataSize uint32
  524. // Accept0RTTData makes the 0-RTT data received from the client
  525. // immediately available to Read. 0-RTT data is subject to replay.
  526. // Use Conn.ConfirmHandshake to wait until the data is known not
  527. // to be replayed after reading it.
  528. //
  529. // It has no meaning on the client.
  530. //
  531. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2.3.
  532. Accept0RTTData bool
  533. // SessionTicketSealer, if not nil, is used to wrap and unwrap
  534. // session tickets, instead of SessionTicketKey.
  535. SessionTicketSealer SessionTicketSealer
  536. // AcceptDelegatedCredential is true if the client is willing to negotiate
  537. // the delegated credential extension.
  538. //
  539. // This value has no meaning for the server.
  540. //
  541. // See https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.
  542. AcceptDelegatedCredential bool
  543. // GetDelegatedCredential returns a DC and its private key for use in the
  544. // delegated credential extension. The inputs to the callback are some
  545. // information parsed from the ClientHello, as well as the protocol version
  546. // selected by the server. This is necessary because the DC is bound to the
  547. // protocol version in which it's used. The return value is the raw DC
  548. // encoded in the wire format specified in
  549. // https://tools.ietf.org/html/draft-ietf-tls-subcerts-02. If the return
  550. // value is nil, then the server will not offer negotiate the extension.
  551. //
  552. // This value has no meaning for the client.
  553. GetDelegatedCredential func(*ClientHelloInfo, uint16) ([]byte, crypto.PrivateKey, error)
  554. serverInitOnce sync.Once // guards calling (*Config).serverInit
  555. // mutex protects sessionTicketKeys.
  556. mutex sync.RWMutex
  557. // sessionTicketKeys contains zero or more ticket keys. If the length
  558. // is zero, SessionTicketsDisabled must be true. The first key is used
  559. // for new tickets and any subsequent keys can be used to decrypt old
  560. // tickets.
  561. sessionTicketKeys []ticketKey
  562. // UseExtendedMasterSecret indicates whether or not the connection
  563. // should use the extended master secret computation if available
  564. UseExtendedMasterSecret bool
  565. }
  566. // ticketKeyNameLen is the number of bytes of identifier that is prepended to
  567. // an encrypted session ticket in order to identify the key used to encrypt it.
  568. const ticketKeyNameLen = 16
  569. // ticketKey is the internal representation of a session ticket key.
  570. type ticketKey struct {
  571. // keyName is an opaque byte string that serves to identify the session
  572. // ticket key. It's exposed as plaintext in every session ticket.
  573. keyName [ticketKeyNameLen]byte
  574. aesKey [16]byte
  575. hmacKey [16]byte
  576. }
  577. // ticketKeyFromBytes converts from the external representation of a session
  578. // ticket key to a ticketKey. Externally, session ticket keys are 32 random
  579. // bytes and this function expands that into sufficient name and key material.
  580. func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
  581. hashed := sha512.Sum512(b[:])
  582. copy(key.keyName[:], hashed[:ticketKeyNameLen])
  583. copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
  584. copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
  585. return key
  586. }
  587. // Clone returns a shallow clone of c. It is safe to clone a Config that is
  588. // being used concurrently by a TLS client or server.
  589. func (c *Config) Clone() *Config {
  590. // Running serverInit ensures that it's safe to read
  591. // SessionTicketsDisabled.
  592. c.serverInitOnce.Do(func() { c.serverInit(nil) })
  593. var sessionTicketKeys []ticketKey
  594. c.mutex.RLock()
  595. sessionTicketKeys = c.sessionTicketKeys
  596. c.mutex.RUnlock()
  597. return &Config{
  598. Rand: c.Rand,
  599. Time: c.Time,
  600. Certificates: c.Certificates,
  601. NameToCertificate: c.NameToCertificate,
  602. GetCertificate: c.GetCertificate,
  603. GetClientCertificate: c.GetClientCertificate,
  604. GetConfigForClient: c.GetConfigForClient,
  605. VerifyPeerCertificate: c.VerifyPeerCertificate,
  606. RootCAs: c.RootCAs,
  607. NextProtos: c.NextProtos,
  608. ServerName: c.ServerName,
  609. ClientAuth: c.ClientAuth,
  610. ClientCAs: c.ClientCAs,
  611. InsecureSkipVerify: c.InsecureSkipVerify,
  612. CipherSuites: c.CipherSuites,
  613. PreferServerCipherSuites: c.PreferServerCipherSuites,
  614. SessionTicketsDisabled: c.SessionTicketsDisabled,
  615. SessionTicketKey: c.SessionTicketKey,
  616. ClientSessionCache: c.ClientSessionCache,
  617. MinVersion: c.MinVersion,
  618. MaxVersion: c.MaxVersion,
  619. CurvePreferences: c.CurvePreferences,
  620. DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
  621. Renegotiation: c.Renegotiation,
  622. KeyLogWriter: c.KeyLogWriter,
  623. Accept0RTTData: c.Accept0RTTData,
  624. Max0RTTDataSize: c.Max0RTTDataSize,
  625. SessionTicketSealer: c.SessionTicketSealer,
  626. AcceptDelegatedCredential: c.AcceptDelegatedCredential,
  627. GetDelegatedCredential: c.GetDelegatedCredential,
  628. sessionTicketKeys: sessionTicketKeys,
  629. UseExtendedMasterSecret: c.UseExtendedMasterSecret,
  630. }
  631. }
  632. // serverInit is run under c.serverInitOnce to do initialization of c. If c was
  633. // returned by a GetConfigForClient callback then the argument should be the
  634. // Config that was passed to Server, otherwise it should be nil.
  635. func (c *Config) serverInit(originalConfig *Config) {
  636. if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 || c.SessionTicketSealer != nil {
  637. return
  638. }
  639. alreadySet := false
  640. for _, b := range c.SessionTicketKey {
  641. if b != 0 {
  642. alreadySet = true
  643. break
  644. }
  645. }
  646. if !alreadySet {
  647. if originalConfig != nil {
  648. copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
  649. } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
  650. c.SessionTicketsDisabled = true
  651. return
  652. }
  653. }
  654. if originalConfig != nil {
  655. originalConfig.mutex.RLock()
  656. c.sessionTicketKeys = originalConfig.sessionTicketKeys
  657. originalConfig.mutex.RUnlock()
  658. } else {
  659. c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
  660. }
  661. }
  662. func (c *Config) ticketKeys() []ticketKey {
  663. c.mutex.RLock()
  664. // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
  665. // will only update it by replacing it with a new value.
  666. ret := c.sessionTicketKeys
  667. c.mutex.RUnlock()
  668. return ret
  669. }
  670. // SetSessionTicketKeys updates the session ticket keys for a server. The first
  671. // key will be used when creating new tickets, while all keys can be used for
  672. // decrypting tickets. It is safe to call this function while the server is
  673. // running in order to rotate the session ticket keys. The function will panic
  674. // if keys is empty.
  675. func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
  676. if len(keys) == 0 {
  677. panic("tls: keys must have at least one key")
  678. }
  679. newKeys := make([]ticketKey, len(keys))
  680. for i, bytes := range keys {
  681. newKeys[i] = ticketKeyFromBytes(bytes)
  682. }
  683. c.mutex.Lock()
  684. c.sessionTicketKeys = newKeys
  685. c.mutex.Unlock()
  686. }
  687. func (c *Config) rand() io.Reader {
  688. r := c.Rand
  689. if r == nil {
  690. return rand.Reader
  691. }
  692. return r
  693. }
  694. func (c *Config) time() time.Time {
  695. t := c.Time
  696. if t == nil {
  697. t = time.Now
  698. }
  699. return t()
  700. }
  701. func hasOverlappingCipherSuites(cs1, cs2 []uint16) bool {
  702. for _, c1 := range cs1 {
  703. for _, c2 := range cs2 {
  704. if c1 == c2 {
  705. return true
  706. }
  707. }
  708. }
  709. return false
  710. }
  711. func (c *Config) cipherSuites() []uint16 {
  712. s := c.CipherSuites
  713. if s == nil {
  714. s = defaultCipherSuites()
  715. } else if c.maxVersion() >= VersionTLS13 {
  716. // Ensure that TLS 1.3 suites are always present, but respect
  717. // the application cipher suite preferences.
  718. s13 := defaultTLS13CipherSuites()
  719. if !hasOverlappingCipherSuites(s, s13) {
  720. allSuites := make([]uint16, len(s13)+len(s))
  721. allSuites = append(allSuites, s13...)
  722. s = append(allSuites, s...)
  723. }
  724. }
  725. return s
  726. }
  727. func (c *Config) minVersion() uint16 {
  728. if c == nil || c.MinVersion == 0 {
  729. return minVersion
  730. }
  731. return c.MinVersion
  732. }
  733. func (c *Config) maxVersion() uint16 {
  734. if c == nil || c.MaxVersion == 0 {
  735. return maxVersion
  736. }
  737. return c.MaxVersion
  738. }
  739. var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  740. func (c *Config) curvePreferences() []CurveID {
  741. if c == nil || len(c.CurvePreferences) == 0 {
  742. return defaultCurvePreferences
  743. }
  744. return c.CurvePreferences
  745. }
  746. // mutualVersion returns the protocol version to use given the advertised
  747. // version of the peer using the legacy non-extension methods.
  748. func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
  749. minVersion := c.minVersion()
  750. maxVersion := c.maxVersion()
  751. // Version 1.3 and higher are not negotiated via this mechanism.
  752. if maxVersion > VersionTLS12 {
  753. maxVersion = VersionTLS12
  754. }
  755. if vers < minVersion {
  756. return 0, false
  757. }
  758. if vers > maxVersion {
  759. vers = maxVersion
  760. }
  761. return vers, true
  762. }
  763. // pickVersion returns the protocol version to use given the advertised
  764. // versions of the peer using the Supported Versions extension.
  765. func (c *Config) pickVersion(peerSupportedVersions []uint16) (uint16, bool) {
  766. supportedVersions := c.getSupportedVersions()
  767. for _, supportedVersion := range supportedVersions {
  768. for _, version := range peerSupportedVersions {
  769. if version == supportedVersion {
  770. return version, true
  771. }
  772. }
  773. }
  774. return 0, false
  775. }
  776. // configSuppVersArray is the backing array of Config.getSupportedVersions
  777. var configSuppVersArray = [...]uint16{VersionTLS13, VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  778. // getSupportedVersions returns the protocol versions that are supported by the
  779. // current configuration.
  780. func (c *Config) getSupportedVersions() []uint16 {
  781. minVersion := c.minVersion()
  782. maxVersion := c.maxVersion()
  783. // Sanity check to avoid advertising unsupported versions.
  784. if minVersion < VersionSSL30 {
  785. minVersion = VersionSSL30
  786. }
  787. if maxVersion > VersionTLS13 {
  788. maxVersion = VersionTLS13
  789. }
  790. if maxVersion < minVersion {
  791. return nil
  792. }
  793. return configSuppVersArray[VersionTLS13-maxVersion : VersionTLS13-minVersion+1]
  794. }
  795. // getCertificate returns the best certificate for the given ClientHelloInfo,
  796. // defaulting to the first element of c.Certificates.
  797. func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  798. if c.GetCertificate != nil &&
  799. (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  800. cert, err := c.GetCertificate(clientHello)
  801. if cert != nil || err != nil {
  802. return cert, err
  803. }
  804. }
  805. if len(c.Certificates) == 0 {
  806. return nil, errors.New("tls: no certificates configured")
  807. }
  808. if len(c.Certificates) == 1 || c.NameToCertificate == nil {
  809. // There's only one choice, so no point doing any work.
  810. return &c.Certificates[0], nil
  811. }
  812. name := strings.ToLower(clientHello.ServerName)
  813. for len(name) > 0 && name[len(name)-1] == '.' {
  814. name = name[:len(name)-1]
  815. }
  816. if cert, ok := c.NameToCertificate[name]; ok {
  817. return cert, nil
  818. }
  819. // try replacing labels in the name with wildcards until we get a
  820. // match.
  821. labels := strings.Split(name, ".")
  822. for i := range labels {
  823. labels[i] = "*"
  824. candidate := strings.Join(labels, ".")
  825. if cert, ok := c.NameToCertificate[candidate]; ok {
  826. return cert, nil
  827. }
  828. }
  829. // If nothing matches, return the first certificate.
  830. return &c.Certificates[0], nil
  831. }
  832. // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  833. // from the CommonName and SubjectAlternateName fields of each of the leaf
  834. // certificates.
  835. func (c *Config) BuildNameToCertificate() {
  836. c.NameToCertificate = make(map[string]*Certificate)
  837. for i := range c.Certificates {
  838. cert := &c.Certificates[i]
  839. x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
  840. if err != nil {
  841. continue
  842. }
  843. if len(x509Cert.Subject.CommonName) > 0 {
  844. c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  845. }
  846. for _, san := range x509Cert.DNSNames {
  847. c.NameToCertificate[san] = cert
  848. }
  849. }
  850. }
  851. // writeKeyLog logs client random and master secret if logging was enabled by
  852. // setting c.KeyLogWriter.
  853. func (c *Config) writeKeyLog(what string, clientRandom, masterSecret []byte) error {
  854. if c.KeyLogWriter == nil {
  855. return nil
  856. }
  857. logLine := []byte(fmt.Sprintf("%s %x %x\n", what, clientRandom, masterSecret))
  858. writerMutex.Lock()
  859. _, err := c.KeyLogWriter.Write(logLine)
  860. writerMutex.Unlock()
  861. return err
  862. }
  863. // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  864. // and is only for debugging, so a global mutex saves space.
  865. var writerMutex sync.Mutex
  866. // A Certificate is a chain of one or more certificates, leaf first.
  867. type Certificate struct {
  868. Certificate [][]byte
  869. // PrivateKey contains the private key corresponding to the public key
  870. // in Leaf. For a server, this must implement crypto.Signer and/or
  871. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  872. // (performing client authentication), this must be a crypto.Signer
  873. // with an RSA or ECDSA PublicKey.
  874. PrivateKey crypto.PrivateKey
  875. // OCSPStaple contains an optional OCSP response which will be served
  876. // to clients that request it.
  877. OCSPStaple []byte
  878. // SignedCertificateTimestamps contains an optional list of Signed
  879. // Certificate Timestamps which will be served to clients that request it.
  880. SignedCertificateTimestamps [][]byte
  881. // Leaf is the parsed form of the leaf certificate, which may be
  882. // initialized using x509.ParseCertificate to reduce per-handshake
  883. // processing for TLS clients doing client authentication. If nil, the
  884. // leaf certificate will be parsed as needed.
  885. Leaf *x509.Certificate
  886. }
  887. type handshakeMessage interface {
  888. marshal() []byte
  889. unmarshal([]byte) alert
  890. }
  891. // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  892. // caching strategy.
  893. type lruSessionCache struct {
  894. sync.Mutex
  895. m map[string]*list.Element
  896. q *list.List
  897. capacity int
  898. }
  899. type lruSessionCacheEntry struct {
  900. sessionKey string
  901. state *ClientSessionState
  902. }
  903. // NewLRUClientSessionCache returns a ClientSessionCache with the given
  904. // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  905. // is used instead.
  906. func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  907. const defaultSessionCacheCapacity = 64
  908. if capacity < 1 {
  909. capacity = defaultSessionCacheCapacity
  910. }
  911. return &lruSessionCache{
  912. m: make(map[string]*list.Element),
  913. q: list.New(),
  914. capacity: capacity,
  915. }
  916. }
  917. // Put adds the provided (sessionKey, cs) pair to the cache.
  918. func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  919. c.Lock()
  920. defer c.Unlock()
  921. if elem, ok := c.m[sessionKey]; ok {
  922. entry := elem.Value.(*lruSessionCacheEntry)
  923. entry.state = cs
  924. c.q.MoveToFront(elem)
  925. return
  926. }
  927. if c.q.Len() < c.capacity {
  928. entry := &lruSessionCacheEntry{sessionKey, cs}
  929. c.m[sessionKey] = c.q.PushFront(entry)
  930. return
  931. }
  932. elem := c.q.Back()
  933. entry := elem.Value.(*lruSessionCacheEntry)
  934. delete(c.m, entry.sessionKey)
  935. entry.sessionKey = sessionKey
  936. entry.state = cs
  937. c.q.MoveToFront(elem)
  938. c.m[sessionKey] = elem
  939. }
  940. // Get returns the ClientSessionState value associated with a given key. It
  941. // returns (nil, false) if no value is found.
  942. func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  943. c.Lock()
  944. defer c.Unlock()
  945. if elem, ok := c.m[sessionKey]; ok {
  946. c.q.MoveToFront(elem)
  947. return elem.Value.(*lruSessionCacheEntry).state, true
  948. }
  949. return nil, false
  950. }
  951. // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  952. type dsaSignature struct {
  953. R, S *big.Int
  954. }
  955. type ecdsaSignature dsaSignature
  956. var emptyConfig Config
  957. func defaultConfig() *Config {
  958. return &emptyConfig
  959. }
  960. var (
  961. once sync.Once
  962. varDefaultCipherSuites []uint16
  963. varDefaultTLS13CipherSuites []uint16
  964. )
  965. func defaultCipherSuites() []uint16 {
  966. once.Do(initDefaultCipherSuites)
  967. return varDefaultCipherSuites
  968. }
  969. func defaultTLS13CipherSuites() []uint16 {
  970. once.Do(initDefaultCipherSuites)
  971. return varDefaultTLS13CipherSuites
  972. }
  973. func initDefaultCipherSuites() {
  974. var topCipherSuites, topTLS13CipherSuites []uint16
  975. // Check the cpu flags for each platform that has optimized GCM implementations.
  976. // Worst case, these variables will just all be false
  977. hasGCMAsmAMD64 := cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
  978. hasGCMAsmARM64 := cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
  979. // Keep in sync with crypto/aes/cipher_s390x.go.
  980. hasGCMAsmS390X := cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
  981. hasGCMAsm := hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
  982. if hasGCMAsm {
  983. // If AES-GCM hardware is provided then prioritise AES-GCM
  984. // cipher suites.
  985. topTLS13CipherSuites = []uint16{
  986. TLS_AES_128_GCM_SHA256,
  987. TLS_AES_256_GCM_SHA384,
  988. TLS_CHACHA20_POLY1305_SHA256,
  989. }
  990. topCipherSuites = []uint16{
  991. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  992. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  993. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  994. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  995. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  996. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  997. }
  998. } else {
  999. // Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1000. // cipher suites first.
  1001. topTLS13CipherSuites = []uint16{
  1002. TLS_CHACHA20_POLY1305_SHA256,
  1003. TLS_AES_128_GCM_SHA256,
  1004. TLS_AES_256_GCM_SHA384,
  1005. }
  1006. topCipherSuites = []uint16{
  1007. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1008. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1009. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1010. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1011. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1012. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1013. }
  1014. }
  1015. varDefaultTLS13CipherSuites = make([]uint16, 0, len(cipherSuites))
  1016. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, topTLS13CipherSuites...)
  1017. varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1018. varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1019. NextCipherSuite:
  1020. for _, suite := range cipherSuites {
  1021. if suite.flags&suiteDefaultOff != 0 {
  1022. continue
  1023. }
  1024. if suite.flags&suiteTLS13 != 0 {
  1025. for _, existing := range varDefaultTLS13CipherSuites {
  1026. if existing == suite.id {
  1027. continue NextCipherSuite
  1028. }
  1029. }
  1030. varDefaultTLS13CipherSuites = append(varDefaultTLS13CipherSuites, suite.id)
  1031. } else {
  1032. for _, existing := range varDefaultCipherSuites {
  1033. if existing == suite.id {
  1034. continue NextCipherSuite
  1035. }
  1036. }
  1037. varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1038. }
  1039. }
  1040. varDefaultCipherSuites = append(varDefaultTLS13CipherSuites, varDefaultCipherSuites...)
  1041. }
  1042. func unexpectedMessageError(wanted, got interface{}) error {
  1043. return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1044. }
  1045. func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1046. for _, s := range supportedSignatureAlgorithms {
  1047. if s == sigAlg {
  1048. return true
  1049. }
  1050. }
  1051. return false
  1052. }
  1053. // signatureFromSignatureScheme maps a signature algorithm to the underlying
  1054. // signature method (without hash function).
  1055. func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1056. switch signatureAlgorithm {
  1057. case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1058. return signaturePKCS1v15
  1059. case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1060. return signatureRSAPSS
  1061. case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1062. return signatureECDSA
  1063. default:
  1064. return 0
  1065. }
  1066. }
  1067. // TODO(kk): Use variable length encoding?
  1068. func getUint24(b []byte) int {
  1069. n := int(b[2])
  1070. n += int(b[1] << 8)
  1071. n += int(b[0] << 16)
  1072. return n
  1073. }
  1074. func putUint24(b []byte, n int) {
  1075. b[0] = byte(n >> 16)
  1076. b[1] = byte(n >> 8)
  1077. b[2] = byte(n & 0xff)
  1078. }