Alternative TLS implementation in Go
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

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