delegated_credentials.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. // Copyright 2020-2021 Cloudflare, Inc. All rights reserved. Use of this source code
  2. // is governed by a BSD-style license that can be found in the LICENSE file.
  3. package tls
  4. // Delegated Credentials for TLS
  5. // (https://tools.ietf.org/html/draft-ietf-tls-subcerts) is an IETF Internet
  6. // draft and proposed TLS extension. If the client or server supports this
  7. // extension, then the server or client may use a "delegated credential" as the
  8. // signing key in the handshake. A delegated credential is a short lived
  9. // public/secret key pair delegated to the peer by an entity trusted by the
  10. // corresponding peer. This allows a reverse proxy to terminate a TLS connection
  11. // on behalf of the entity. Credentials can't be revoked; in order to
  12. // mitigate risk in case the reverse proxy is compromised, the credential is only
  13. // valid for a short time (days, hours, or even minutes).
  14. import (
  15. "bytes"
  16. "crypto"
  17. "crypto/ecdsa"
  18. "crypto/ed25519"
  19. "crypto/elliptic"
  20. "crypto/rand"
  21. "crypto/rsa"
  22. "crypto/x509"
  23. "encoding/binary"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "time"
  28. "golang.org/x/crypto/cryptobyte"
  29. )
  30. const (
  31. // In the absence of an application profile standard specifying otherwise,
  32. // the maximum validity period is set to 7 days.
  33. dcMaxTTLSeconds = 60 * 60 * 24 * 7
  34. dcMaxTTL = time.Duration(dcMaxTTLSeconds * time.Second)
  35. dcMaxPubLen = (1 << 24) - 1 // Bytes
  36. dcMaxSignatureLen = (1 << 16) - 1 // Bytes
  37. )
  38. const (
  39. undefinedSignatureScheme SignatureScheme = 0x0000
  40. )
  41. var extensionDelegatedCredential = []int{1, 3, 6, 1, 4, 1, 44363, 44}
  42. // isValidForDelegation returns true if a certificate can be used for Delegated
  43. // Credentials.
  44. func isValidForDelegation(cert *x509.Certificate) bool {
  45. // Check that the digitalSignature key usage is set.
  46. // The certificate must contains the digitalSignature KeyUsage.
  47. if (cert.KeyUsage & x509.KeyUsageDigitalSignature) == 0 {
  48. return false
  49. }
  50. // Check that the certificate has the DelegationUsage extension and that
  51. // it's marked as non-critical (See Section 4.2 of RFC5280).
  52. for _, extension := range cert.Extensions {
  53. if extension.Id.Equal(extensionDelegatedCredential) {
  54. if extension.Critical {
  55. return false
  56. }
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. // isExpired returns true if the credential has expired. The end of the validity
  63. // interval is defined as the delegator certificate's notBefore field ('start')
  64. // plus dc.cred.validTime seconds. This function simply checks that the current time
  65. // ('now') is before the end of the validity interval.
  66. func (dc *DelegatedCredential) isExpired(start, now time.Time) bool {
  67. end := start.Add(dc.cred.validTime)
  68. return !now.Before(end)
  69. }
  70. // invalidTTL returns true if the credential's validity period is longer than the
  71. // maximum permitted. This is defined by the certificate's notBefore field
  72. // ('start') plus the dc.validTime, minus the current time ('now').
  73. func (dc *DelegatedCredential) invalidTTL(start, now time.Time) bool {
  74. return dc.cred.validTime > (now.Sub(start) + dcMaxTTL).Round(time.Second)
  75. }
  76. // credential stores the public components of a Delegated Credential.
  77. type credential struct {
  78. // The amount of time for which the credential is valid. Specifically, the
  79. // the credential expires 'validTime' seconds after the 'notBefore' of the
  80. // delegation certificate. The delegator shall not issue Delegated
  81. // Credentials that are valid for more than 7 days from the current time.
  82. //
  83. // When this data structure is serialized, this value is converted to a
  84. // uint32 representing the duration in seconds.
  85. validTime time.Duration
  86. // The signature scheme associated with the credential public key.
  87. // This is expected to be the same as the CertificateVerify.algorithm
  88. // sent by the client or server.
  89. expCertVerfAlgo SignatureScheme
  90. // The credential's public key.
  91. publicKey crypto.PublicKey
  92. }
  93. // DelegatedCredential stores a Delegated Credential with the credential and its
  94. // signature.
  95. type DelegatedCredential struct {
  96. // The serialized form of the Delegated Credential.
  97. raw []byte
  98. // Cred stores the public components of a Delegated Credential.
  99. cred *credential
  100. // The signature scheme used to sign the Delegated Credential.
  101. algorithm SignatureScheme
  102. // The Credential's delegation: a signature that binds the credential to
  103. // the end-entity certificate's public key.
  104. signature []byte
  105. }
  106. // marshalPublicKeyInfo returns a DER encoded PublicKeyInfo
  107. // from a Delegated Credential (as defined in the X.509 standard).
  108. // The following key types are currently supported: *ecdsa.PublicKey
  109. // and ed25519.PublicKey. Unsupported key types result in an error.
  110. // rsa.PublicKey is not supported as defined by the draft.
  111. func (cred *credential) marshalPublicKeyInfo() ([]byte, error) {
  112. switch cred.expCertVerfAlgo {
  113. case ECDSAWithP256AndSHA256,
  114. ECDSAWithP384AndSHA384,
  115. ECDSAWithP521AndSHA512,
  116. Ed25519:
  117. rawPub, err := x509.MarshalPKIXPublicKey(cred.publicKey)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return rawPub, nil
  122. default:
  123. return nil, fmt.Errorf("tls: unsupported signature scheme: 0x%04x", cred.expCertVerfAlgo)
  124. }
  125. }
  126. // marshal encodes the credential struct of the Delegated Credential.
  127. func (cred *credential) marshal() ([]byte, error) {
  128. var b cryptobyte.Builder
  129. b.AddUint32(uint32(cred.validTime / time.Second))
  130. b.AddUint16(uint16(cred.expCertVerfAlgo))
  131. // Encode the public key
  132. rawPub, err := cred.marshalPublicKeyInfo()
  133. if err != nil {
  134. return nil, err
  135. }
  136. // Assert that the public key encoding is no longer than 2^24-1 bytes.
  137. if len(rawPub) > dcMaxPubLen {
  138. return nil, errors.New("tls: public key length exceeds 2^24-1 limit")
  139. }
  140. b.AddUint24(uint32(len(rawPub)))
  141. b.AddBytes(rawPub)
  142. raw := b.BytesOrPanic()
  143. return raw, nil
  144. }
  145. // unmarshalCredential decodes serialized bytes and returns a credential, if possible.
  146. func unmarshalCredential(raw []byte) (*credential, error) {
  147. if len(raw) < 10 {
  148. return nil, errors.New("tls: Delegated Credential is not valid: invalid length")
  149. }
  150. s := cryptobyte.String(raw)
  151. var t uint32
  152. if !s.ReadUint32(&t) {
  153. return nil, errors.New("tls: Delegated Credential is not valid")
  154. }
  155. validTime := time.Duration(t) * time.Second
  156. var pubAlgo uint16
  157. if !s.ReadUint16(&pubAlgo) {
  158. return nil, errors.New("tls: Delegated Credential is not valid")
  159. }
  160. algo := SignatureScheme(pubAlgo)
  161. var pubLen uint32
  162. s.ReadUint24(&pubLen)
  163. pubKey, err := x509.ParsePKIXPublicKey(s)
  164. if err != nil {
  165. return nil, err
  166. }
  167. return &credential{validTime, algo, pubKey}, nil
  168. }
  169. // getCredentialLen returns the number of bytes comprising the serialized
  170. // credential struct inside the Delegated Credential.
  171. func getCredentialLen(raw []byte) (int, error) {
  172. if len(raw) < 10 {
  173. return 0, errors.New("tls: Delegated Credential is not valid")
  174. }
  175. var read []byte
  176. s := cryptobyte.String(raw)
  177. s.ReadBytes(&read, 6)
  178. var pubLen uint32
  179. s.ReadUint24(&pubLen)
  180. if !(pubLen > 0) {
  181. return 0, errors.New("tls: Delegated Credential is not valid")
  182. }
  183. raw = raw[6:]
  184. if len(raw) < int(pubLen) {
  185. return 0, errors.New("tls: Delegated Credential is not valid")
  186. }
  187. return 9 + int(pubLen), nil
  188. }
  189. // getHash maps the SignatureScheme to its corresponding hash function.
  190. func getHash(scheme SignatureScheme) crypto.Hash {
  191. switch scheme {
  192. case ECDSAWithP256AndSHA256:
  193. return crypto.SHA256
  194. case ECDSAWithP384AndSHA384:
  195. return crypto.SHA384
  196. case ECDSAWithP521AndSHA512:
  197. return crypto.SHA512
  198. case Ed25519:
  199. return directSigning
  200. case PKCS1WithSHA256, PSSWithSHA256:
  201. return crypto.SHA256
  202. case PSSWithSHA384:
  203. return crypto.SHA384
  204. case PSSWithSHA512:
  205. return crypto.SHA512
  206. default:
  207. return 0 // Unknown hash function
  208. }
  209. }
  210. // getECDSACurve maps the SignatureScheme to its corresponding ecdsa elliptic.Curve.
  211. func getECDSACurve(scheme SignatureScheme) elliptic.Curve {
  212. switch scheme {
  213. case ECDSAWithP256AndSHA256:
  214. return elliptic.P256()
  215. case ECDSAWithP384AndSHA384:
  216. return elliptic.P384()
  217. case ECDSAWithP521AndSHA512:
  218. return elliptic.P521()
  219. default:
  220. return nil
  221. }
  222. }
  223. // prepareDelegationSignatureInput returns the message that the delegator is going to sign.
  224. func prepareDelegationSignatureInput(hash crypto.Hash, cred *credential, dCert []byte, algo SignatureScheme, isClient bool) ([]byte, error) {
  225. header := make([]byte, 64)
  226. for i := range header {
  227. header[i] = 0x20
  228. }
  229. var context string
  230. if !isClient {
  231. context = "TLS, server delegated credentials\x00"
  232. } else {
  233. context = "TLS, client delegated credentials\x00"
  234. }
  235. rawCred, err := cred.marshal()
  236. if err != nil {
  237. return nil, err
  238. }
  239. var rawAlgo [2]byte
  240. binary.BigEndian.PutUint16(rawAlgo[:], uint16(algo))
  241. if hash == directSigning {
  242. b := &bytes.Buffer{}
  243. b.Write(header)
  244. io.WriteString(b, context)
  245. b.Write(dCert)
  246. b.Write(rawCred)
  247. b.Write(rawAlgo[:])
  248. return b.Bytes(), nil
  249. }
  250. h := hash.New()
  251. h.Write(header)
  252. io.WriteString(h, context)
  253. h.Write(dCert)
  254. h.Write(rawCred)
  255. h.Write(rawAlgo[:])
  256. return h.Sum(nil), nil
  257. }
  258. // Extract the algorithm used to sign the Delegated Credential from the
  259. // end-entity (leaf) certificate.
  260. func getSignatureAlgorithm(cert *Certificate) (SignatureScheme, error) {
  261. switch sk := cert.PrivateKey.(type) {
  262. case *ecdsa.PrivateKey:
  263. pk := sk.Public().(*ecdsa.PublicKey)
  264. curveName := pk.Curve.Params().Name
  265. certAlg := cert.Leaf.PublicKeyAlgorithm
  266. if certAlg == x509.ECDSA && curveName == "P-256" {
  267. return ECDSAWithP256AndSHA256, nil
  268. } else if certAlg == x509.ECDSA && curveName == "P-384" {
  269. return ECDSAWithP384AndSHA384, nil
  270. } else if certAlg == x509.ECDSA && curveName == "P-521" {
  271. return ECDSAWithP521AndSHA512, nil
  272. } else {
  273. return undefinedSignatureScheme, fmt.Errorf("using curve %s for %s is not supported", curveName, cert.Leaf.SignatureAlgorithm)
  274. }
  275. case ed25519.PrivateKey:
  276. return Ed25519, nil
  277. case *rsa.PrivateKey:
  278. // If the certificate has the RSAEncryption OID there are a number of valid signature schemes that may sign the DC.
  279. // In the absence of better information, we make a reasonable choice.
  280. return PSSWithSHA256, nil
  281. default:
  282. return undefinedSignatureScheme, fmt.Errorf("tls: unsupported algorithm for signing Delegated Credential")
  283. }
  284. }
  285. // NewDelegatedCredential creates a new Delegated Credential using 'cert' for
  286. // delegation, depending if the caller is the client or the server (defined by
  287. // 'isClient'). It generates a public/private key pair for the provided signature
  288. // algorithm ('pubAlgo') and it defines a validity interval (defined
  289. // by 'cert.Leaf.notBefore' and 'validTime'). It signs the Delegated Credential
  290. // using 'cert.PrivateKey'.
  291. func NewDelegatedCredential(cert *Certificate, pubAlgo SignatureScheme, validTime time.Duration, isClient bool) (*DelegatedCredential, crypto.PrivateKey, error) {
  292. // The granularity of DC validity is seconds.
  293. validTime = validTime.Round(time.Second)
  294. // Parse the leaf certificate if needed.
  295. var err error
  296. if cert.Leaf == nil {
  297. if len(cert.Certificate[0]) == 0 {
  298. return nil, nil, errors.New("tls: missing leaf certificate for Delegated Credential")
  299. }
  300. cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
  301. if err != nil {
  302. return nil, nil, err
  303. }
  304. }
  305. // Check that the leaf certificate can be used for delegation.
  306. if !isValidForDelegation(cert.Leaf) {
  307. return nil, nil, errors.New("tls: certificate not authorized for delegation")
  308. }
  309. sigAlgo, err := getSignatureAlgorithm(cert)
  310. if err != nil {
  311. return nil, nil, err
  312. }
  313. // Generate the Delegated Credential key pair based on the provided scheme
  314. var privK crypto.PrivateKey
  315. var pubK crypto.PublicKey
  316. switch pubAlgo {
  317. case ECDSAWithP256AndSHA256,
  318. ECDSAWithP384AndSHA384,
  319. ECDSAWithP521AndSHA512:
  320. privK, err = ecdsa.GenerateKey(getECDSACurve(pubAlgo), rand.Reader)
  321. if err != nil {
  322. return nil, nil, err
  323. }
  324. pubK = privK.(*ecdsa.PrivateKey).Public()
  325. case Ed25519:
  326. pubK, privK, err = ed25519.GenerateKey(rand.Reader)
  327. if err != nil {
  328. return nil, nil, err
  329. }
  330. default:
  331. return nil, nil, fmt.Errorf("tls: unsupported algorithm for Delegated Credential: %s", pubAlgo)
  332. }
  333. // Prepare the credential for signing
  334. hash := getHash(sigAlgo)
  335. credential := &credential{validTime, pubAlgo, pubK}
  336. values, err := prepareDelegationSignatureInput(hash, credential, cert.Leaf.Raw, sigAlgo, isClient)
  337. if err != nil {
  338. return nil, nil, err
  339. }
  340. var sig []byte
  341. switch sk := cert.PrivateKey.(type) {
  342. case *ecdsa.PrivateKey:
  343. opts := crypto.SignerOpts(hash)
  344. sig, err = sk.Sign(rand.Reader, values, opts)
  345. if err != nil {
  346. return nil, nil, err
  347. }
  348. case ed25519.PrivateKey:
  349. opts := crypto.SignerOpts(hash)
  350. sig, err = sk.Sign(rand.Reader, values, opts)
  351. if err != nil {
  352. return nil, nil, err
  353. }
  354. case *rsa.PrivateKey:
  355. opts := &rsa.PSSOptions{
  356. SaltLength: rsa.PSSSaltLengthEqualsHash,
  357. Hash: hash,
  358. }
  359. sig, err = rsa.SignPSS(rand.Reader, sk, hash, values, opts)
  360. if err != nil {
  361. return nil, nil, err
  362. }
  363. default:
  364. return nil, nil, fmt.Errorf("tls: unsupported key type for Delegated Credential")
  365. }
  366. if len(sig) > dcMaxSignatureLen {
  367. return nil, nil, errors.New("tls: unable to create a Delegated Credential")
  368. }
  369. return &DelegatedCredential{
  370. cred: credential,
  371. algorithm: sigAlgo,
  372. signature: sig,
  373. }, privK, nil
  374. }
  375. // Validate validates the Delegated Credential by checking that the signature is
  376. // valid, that it hasn't expired, and that the TTL is valid. It also checks that
  377. // certificate can be used for delegation.
  378. func (dc *DelegatedCredential) Validate(cert *x509.Certificate, isClient bool, now time.Time, certVerifyMsg *certificateVerifyMsg) bool {
  379. if dc.isExpired(cert.NotBefore, now) {
  380. return false
  381. }
  382. if dc.invalidTTL(cert.NotBefore, now) {
  383. return false
  384. }
  385. if dc.cred.expCertVerfAlgo != certVerifyMsg.signatureAlgorithm {
  386. return false
  387. }
  388. if !isValidForDelegation(cert) {
  389. return false
  390. }
  391. hash := getHash(dc.algorithm)
  392. in, err := prepareDelegationSignatureInput(hash, dc.cred, cert.Raw, dc.algorithm, isClient)
  393. if err != nil {
  394. return false
  395. }
  396. switch dc.algorithm {
  397. case ECDSAWithP256AndSHA256,
  398. ECDSAWithP384AndSHA384,
  399. ECDSAWithP521AndSHA512:
  400. pk, ok := cert.PublicKey.(*ecdsa.PublicKey)
  401. if !ok {
  402. return false
  403. }
  404. return ecdsa.VerifyASN1(pk, in, dc.signature)
  405. case Ed25519:
  406. pk, ok := cert.PublicKey.(ed25519.PublicKey)
  407. if !ok {
  408. return false
  409. }
  410. return ed25519.Verify(pk, in, dc.signature)
  411. case PSSWithSHA256,
  412. PSSWithSHA384,
  413. PSSWithSHA512:
  414. pk, ok := cert.PublicKey.(*rsa.PublicKey)
  415. if !ok {
  416. return false
  417. }
  418. hash := getHash(dc.algorithm)
  419. return rsa.VerifyPSS(pk, hash, in, dc.signature, nil) == nil
  420. default:
  421. return false
  422. }
  423. }
  424. // Marshal encodes a DelegatedCredential structure. It also sets dc.Raw to that
  425. // encoding.
  426. func (dc *DelegatedCredential) Marshal() ([]byte, error) {
  427. if len(dc.signature) > dcMaxSignatureLen {
  428. return nil, errors.New("tls: delegated credential is not valid")
  429. }
  430. if len(dc.signature) == 0 {
  431. return nil, errors.New("tls: delegated credential has no signature")
  432. }
  433. raw, err := dc.cred.marshal()
  434. if err != nil {
  435. return nil, err
  436. }
  437. var b cryptobyte.Builder
  438. b.AddBytes(raw)
  439. b.AddUint16(uint16(dc.algorithm))
  440. b.AddUint16(uint16(len(dc.signature)))
  441. b.AddBytes(dc.signature)
  442. dc.raw = b.BytesOrPanic()
  443. return dc.raw, nil
  444. }
  445. // UnmarshalDelegatedCredential decodes a DelegatedCredential structure.
  446. func UnmarshalDelegatedCredential(raw []byte) (*DelegatedCredential, error) {
  447. rawCredentialLen, err := getCredentialLen(raw)
  448. if err != nil {
  449. return nil, err
  450. }
  451. credential, err := unmarshalCredential(raw[:rawCredentialLen])
  452. if err != nil {
  453. return nil, err
  454. }
  455. raw = raw[rawCredentialLen:]
  456. if len(raw) < 4 {
  457. return nil, errors.New("tls: Delegated Credential is not valid")
  458. }
  459. s := cryptobyte.String(raw)
  460. var algo uint16
  461. if !s.ReadUint16(&algo) {
  462. return nil, errors.New("tls: Delegated Credential is not valid")
  463. }
  464. var rawSignatureLen uint16
  465. if !s.ReadUint16(&rawSignatureLen) {
  466. return nil, errors.New("tls: Delegated Credential is not valid")
  467. }
  468. var sig []byte
  469. if !s.ReadBytes(&sig, int(rawSignatureLen)) {
  470. return nil, errors.New("tls: Delegated Credential is not valid")
  471. }
  472. return &DelegatedCredential{
  473. cred: credential,
  474. algorithm: SignatureScheme(algo),
  475. signature: sig,
  476. }, nil
  477. }