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.

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