tls.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "crypto/x509/pkix"
  8. "encoding/asn1"
  9. "encoding/base64"
  10. "encoding/json"
  11. "encoding/pem"
  12. "fmt"
  13. "math/big"
  14. "net"
  15. "net/http"
  16. "strings"
  17. "time"
  18. "github.com/pkg/errors"
  19. "golang.org/x/crypto/ssh"
  20. "go.step.sm/crypto/jose"
  21. "go.step.sm/crypto/keyutil"
  22. "go.step.sm/crypto/pemutil"
  23. "go.step.sm/crypto/x509util"
  24. "github.com/smallstep/certificates/authority/config"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. casapi "github.com/smallstep/certificates/cas/apiv1"
  27. "github.com/smallstep/certificates/db"
  28. "github.com/smallstep/certificates/errs"
  29. "github.com/smallstep/certificates/webhook"
  30. "github.com/smallstep/nosql/database"
  31. )
  32. type tokenKey struct{}
  33. // NewTokenContext adds the given token to the context.
  34. func NewTokenContext(ctx context.Context, token string) context.Context {
  35. return context.WithValue(ctx, tokenKey{}, token)
  36. }
  37. // TokenFromContext returns the token from the given context.
  38. func TokenFromContext(ctx context.Context) (token string, ok bool) {
  39. token, ok = ctx.Value(tokenKey{}).(string)
  40. return
  41. }
  42. // GetTLSOptions returns the tls options configured.
  43. func (a *Authority) GetTLSOptions() *config.TLSOptions {
  44. return a.config.TLS
  45. }
  46. var (
  47. oidAuthorityKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 35}
  48. oidSubjectKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 14}
  49. oidExtensionIssuingDistributionPoint = asn1.ObjectIdentifier{2, 5, 29, 28}
  50. )
  51. func withDefaultASN1DN(def *config.ASN1DN) provisioner.CertificateModifierFunc {
  52. return func(crt *x509.Certificate, _ provisioner.SignOptions) error {
  53. if def == nil {
  54. return errors.New("default ASN1DN template cannot be nil")
  55. }
  56. if len(crt.Subject.Country) == 0 && def.Country != "" {
  57. crt.Subject.Country = append(crt.Subject.Country, def.Country)
  58. }
  59. if len(crt.Subject.Organization) == 0 && def.Organization != "" {
  60. crt.Subject.Organization = append(crt.Subject.Organization, def.Organization)
  61. }
  62. if len(crt.Subject.OrganizationalUnit) == 0 && def.OrganizationalUnit != "" {
  63. crt.Subject.OrganizationalUnit = append(crt.Subject.OrganizationalUnit, def.OrganizationalUnit)
  64. }
  65. if len(crt.Subject.Locality) == 0 && def.Locality != "" {
  66. crt.Subject.Locality = append(crt.Subject.Locality, def.Locality)
  67. }
  68. if len(crt.Subject.Province) == 0 && def.Province != "" {
  69. crt.Subject.Province = append(crt.Subject.Province, def.Province)
  70. }
  71. if len(crt.Subject.StreetAddress) == 0 && def.StreetAddress != "" {
  72. crt.Subject.StreetAddress = append(crt.Subject.StreetAddress, def.StreetAddress)
  73. }
  74. if crt.Subject.SerialNumber == "" && def.SerialNumber != "" {
  75. crt.Subject.SerialNumber = def.SerialNumber
  76. }
  77. if crt.Subject.CommonName == "" && def.CommonName != "" {
  78. crt.Subject.CommonName = def.CommonName
  79. }
  80. return nil
  81. }
  82. }
  83. // GetX509Signer returns a [crypto.Signer] implementation using the intermediate
  84. // key.
  85. //
  86. // This method can return a [NotImplementedError] if the CA is configured with a
  87. // Certificate Authority Service (CAS) that does not implement the
  88. // CertificateAuthoritySigner interface.
  89. //
  90. // [NotImplementedError]: https://pkg.go.dev/github.com/smallstep/certificates/cas/apiv1#NotImplementedError
  91. func (a *Authority) GetX509Signer() (crypto.Signer, error) {
  92. if s, ok := a.x509CAService.(casapi.CertificateAuthoritySigner); ok {
  93. return s.GetSigner()
  94. }
  95. return nil, casapi.NotImplementedError{}
  96. }
  97. // Sign creates a signed certificate from a certificate signing request. It
  98. // creates a new context.Context, and calls into SignWithContext.
  99. //
  100. // Deprecated: Use authority.SignWithContext with an actual context.Context.
  101. func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  102. return a.SignWithContext(context.Background(), csr, signOpts, extraOpts...)
  103. }
  104. // SignWithContext creates a signed certificate from a certificate signing
  105. // request, taking the provided context.Context.
  106. func (a *Authority) SignWithContext(ctx context.Context, csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  107. chain, prov, err := a.signX509(ctx, csr, signOpts, extraOpts...)
  108. a.meter.X509Signed(chain, prov, err)
  109. return chain, err
  110. }
  111. func (a *Authority) signX509(ctx context.Context, csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, provisioner.Interface, error) {
  112. var (
  113. certOptions []x509util.Option
  114. certValidators []provisioner.CertificateValidator
  115. certModifiers []provisioner.CertificateModifier
  116. certEnforcers []provisioner.CertificateEnforcer
  117. )
  118. opts := []any{errs.WithKeyVal("csr", csr), errs.WithKeyVal("signOptions", signOpts)}
  119. if err := csr.CheckSignature(); err != nil {
  120. return nil, nil, errs.ApplyOptions(
  121. errs.BadRequestErr(err, "invalid certificate request"),
  122. opts...,
  123. )
  124. }
  125. // Set backdate with the configured value
  126. signOpts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  127. var (
  128. prov provisioner.Interface
  129. pInfo *casapi.ProvisionerInfo
  130. attData *provisioner.AttestationData
  131. webhookCtl webhookController
  132. )
  133. for _, op := range extraOpts {
  134. switch k := op.(type) {
  135. // Capture current provisioner
  136. case provisioner.Interface:
  137. prov = k
  138. pInfo = &casapi.ProvisionerInfo{
  139. ID: prov.GetID(),
  140. Type: prov.GetType().String(),
  141. Name: prov.GetName(),
  142. }
  143. // Adds new options to NewCertificate
  144. case provisioner.CertificateOptions:
  145. certOptions = append(certOptions, k.Options(signOpts)...)
  146. // Validate the given certificate request.
  147. case provisioner.CertificateRequestValidator:
  148. if err := k.Valid(csr); err != nil {
  149. return nil, prov, errs.ApplyOptions(
  150. errs.ForbiddenErr(err, "error validating certificate request"),
  151. opts...,
  152. )
  153. }
  154. // Validates the unsigned certificate template.
  155. case provisioner.CertificateValidator:
  156. certValidators = append(certValidators, k)
  157. // Modifies a certificate before validating it.
  158. case provisioner.CertificateModifier:
  159. certModifiers = append(certModifiers, k)
  160. // Modifies a certificate after validating it.
  161. case provisioner.CertificateEnforcer:
  162. certEnforcers = append(certEnforcers, k)
  163. // Extra information from ACME attestations.
  164. case provisioner.AttestationData:
  165. attData = &k
  166. // Capture the provisioner's webhook controller
  167. case webhookController:
  168. webhookCtl = k
  169. default:
  170. return nil, prov, errs.InternalServer("authority.Sign; invalid extra option type %T", append([]any{k}, opts...)...)
  171. }
  172. }
  173. if err := a.callEnrichingWebhooksX509(ctx, prov, webhookCtl, attData, csr); err != nil {
  174. return nil, prov, errs.ApplyOptions(
  175. errs.ForbiddenErr(err, "%s", err.Error()),
  176. errs.WithKeyVal("csr", csr),
  177. errs.WithKeyVal("signOptions", signOpts),
  178. )
  179. }
  180. crt, err := x509util.NewCertificate(csr, certOptions...)
  181. if err != nil {
  182. var te *x509util.TemplateError
  183. switch {
  184. case errors.As(err, &te):
  185. return nil, prov, errs.ApplyOptions(
  186. errs.BadRequestErr(err, "%s", err.Error()),
  187. errs.WithKeyVal("csr", csr),
  188. errs.WithKeyVal("signOptions", signOpts),
  189. )
  190. case strings.HasPrefix(err.Error(), "error unmarshaling certificate"):
  191. // explicitly check for unmarshaling errors, which are most probably caused by JSON template (syntax) errors
  192. return nil, prov, errs.InternalServerErr(templatingError(err),
  193. errs.WithKeyVal("csr", csr),
  194. errs.WithKeyVal("signOptions", signOpts),
  195. errs.WithMessage("error applying certificate template"),
  196. )
  197. default:
  198. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign", opts...)
  199. }
  200. }
  201. // Certificate modifiers before validation
  202. leaf := crt.GetCertificate()
  203. // Set default subject
  204. if err := withDefaultASN1DN(a.config.AuthorityConfig.Template).Modify(leaf, signOpts); err != nil {
  205. return nil, prov, errs.ApplyOptions(
  206. errs.ForbiddenErr(err, "error creating certificate"),
  207. opts...,
  208. )
  209. }
  210. for _, m := range certModifiers {
  211. if err := m.Modify(leaf, signOpts); err != nil {
  212. return nil, prov, errs.ApplyOptions(
  213. errs.ForbiddenErr(err, "error creating certificate"),
  214. opts...,
  215. )
  216. }
  217. }
  218. // Certificate validation.
  219. for _, v := range certValidators {
  220. if err := v.Valid(leaf, signOpts); err != nil {
  221. return nil, prov, errs.ApplyOptions(
  222. errs.ForbiddenErr(err, "error validating certificate"),
  223. opts...,
  224. )
  225. }
  226. }
  227. // Certificate modifiers after validation
  228. for _, m := range certEnforcers {
  229. if err = m.Enforce(leaf); err != nil {
  230. return nil, prov, errs.ApplyOptions(
  231. errs.ForbiddenErr(err, "error creating certificate"),
  232. opts...,
  233. )
  234. }
  235. }
  236. // Process injected modifiers after validation
  237. for _, m := range a.x509Enforcers {
  238. if err = m.Enforce(leaf); err != nil {
  239. return nil, prov, errs.ApplyOptions(
  240. errs.ForbiddenErr(err, "error creating certificate"),
  241. opts...,
  242. )
  243. }
  244. }
  245. // Check if authority is allowed to sign the certificate
  246. if err = a.isAllowedToSignX509Certificate(leaf); err != nil {
  247. var ee *errs.Error
  248. if errors.As(err, &ee) {
  249. return nil, prov, errs.ApplyOptions(ee, opts...)
  250. }
  251. return nil, prov, errs.InternalServerErr(err,
  252. errs.WithKeyVal("csr", csr),
  253. errs.WithKeyVal("signOptions", signOpts),
  254. errs.WithMessage("error creating certificate"),
  255. )
  256. }
  257. // Send certificate to webhooks for authorization
  258. if err := a.callAuthorizingWebhooksX509(ctx, prov, webhookCtl, crt, leaf, attData); err != nil {
  259. return nil, prov, errs.ApplyOptions(
  260. errs.ForbiddenErr(err, "error creating certificate"),
  261. opts...,
  262. )
  263. }
  264. // Sign certificate
  265. lifetime := leaf.NotAfter.Sub(leaf.NotBefore.Add(signOpts.Backdate))
  266. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  267. Template: leaf,
  268. CSR: csr,
  269. Lifetime: lifetime,
  270. Backdate: signOpts.Backdate,
  271. Provisioner: pInfo,
  272. })
  273. if err != nil {
  274. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error creating certificate", opts...)
  275. }
  276. chain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  277. // Wrap provisioner with extra information, if not nil
  278. if prov != nil {
  279. prov = wrapProvisioner(prov, attData)
  280. }
  281. // Store certificate in the db.
  282. if err := a.storeCertificate(prov, chain); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  283. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error storing certificate in db", opts...)
  284. }
  285. return chain, prov, nil
  286. }
  287. // isAllowedToSignX509Certificate checks if the Authority is allowed
  288. // to sign the X.509 certificate.
  289. func (a *Authority) isAllowedToSignX509Certificate(cert *x509.Certificate) error {
  290. if err := a.constraintsEngine.ValidateCertificate(cert); err != nil {
  291. return err
  292. }
  293. return a.policyEngine.IsX509CertificateAllowed(cert)
  294. }
  295. // AreSANsAllowed evaluates the provided sans against the
  296. // authority X.509 policy.
  297. func (a *Authority) AreSANsAllowed(_ context.Context, sans []string) error {
  298. return a.policyEngine.AreSANsAllowed(sans)
  299. }
  300. // Renew creates a new Certificate identical to the old certificate, except with
  301. // a validity window that begins 'now'.
  302. func (a *Authority) Renew(oldCert *x509.Certificate) ([]*x509.Certificate, error) {
  303. return a.RenewContext(context.Background(), oldCert, nil)
  304. }
  305. // Rekey is used for rekeying and renewing based on the public key. If the
  306. // public key is 'nil' then it's assumed that the cert should be renewed using
  307. // the existing public key. If the public key is not 'nil' then it's assumed
  308. // that the cert should be rekeyed.
  309. //
  310. // For both Rekey and Renew all other attributes of the new certificate should
  311. // match the old certificate. The exceptions are 'AuthorityKeyId' (which may
  312. // have changed), 'SubjectKeyId' (different in case of rekey), and
  313. // 'NotBefore/NotAfter' (the validity duration of the new certificate should be
  314. // equal to the old one, but starting 'now').
  315. func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  316. return a.RenewContext(context.Background(), oldCert, pk)
  317. }
  318. // RenewContext creates a new certificate identical to the old one, but it can
  319. // optionally replace the public key with the given one. When running on RA
  320. // mode, it can only renew a certificate using a renew token instead.
  321. //
  322. // For both rekey and renew operations, all other attributes of the new
  323. // certificate should match the old certificate. The exceptions are
  324. // 'AuthorityKeyId' (which may have changed), 'SubjectKeyId' (different in case
  325. // of rekey), and 'NotBefore/NotAfter' (the validity duration of the new
  326. // certificate should be equal to the old one, but starting 'now').
  327. func (a *Authority) RenewContext(ctx context.Context, oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  328. chain, prov, err := a.renewContext(ctx, oldCert, pk)
  329. if pk == nil {
  330. a.meter.X509Renewed(chain, prov, err)
  331. } else {
  332. a.meter.X509Rekeyed(chain, prov, err)
  333. }
  334. return chain, err
  335. }
  336. func (a *Authority) renewContext(ctx context.Context, oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, provisioner.Interface, error) {
  337. isRekey := (pk != nil)
  338. opts := []errs.Option{
  339. errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String()),
  340. }
  341. // Check step provisioner extensions
  342. prov, err := a.authorizeRenew(ctx, oldCert)
  343. if err != nil {
  344. return nil, prov, errs.StatusCodeError(http.StatusInternalServerError, err, opts...)
  345. }
  346. // Durations
  347. backdate := a.config.AuthorityConfig.Backdate.Duration
  348. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  349. lifetime := duration - backdate
  350. // Create new certificate from previous values.
  351. // Issuer, NotBefore, NotAfter and SubjectKeyId will be set by the CAS.
  352. newCert := &x509.Certificate{
  353. RawSubject: oldCert.RawSubject,
  354. KeyUsage: oldCert.KeyUsage,
  355. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  356. ExtKeyUsage: oldCert.ExtKeyUsage,
  357. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  358. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  359. IsCA: oldCert.IsCA,
  360. MaxPathLen: oldCert.MaxPathLen,
  361. MaxPathLenZero: oldCert.MaxPathLenZero,
  362. OCSPServer: oldCert.OCSPServer,
  363. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  364. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  365. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  366. DNSNames: oldCert.DNSNames,
  367. EmailAddresses: oldCert.EmailAddresses,
  368. IPAddresses: oldCert.IPAddresses,
  369. URIs: oldCert.URIs,
  370. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  371. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  372. PermittedIPRanges: oldCert.PermittedIPRanges,
  373. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  374. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  375. PermittedURIDomains: oldCert.PermittedURIDomains,
  376. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  377. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  378. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  379. }
  380. if isRekey {
  381. newCert.PublicKey = pk
  382. } else {
  383. newCert.PublicKey = oldCert.PublicKey
  384. }
  385. // Copy all extensions except:
  386. //
  387. // 1. Authority Key Identifier - This one might be different if we rotate
  388. // the intermediate certificate and it will cause a TLS bad certificate
  389. // error.
  390. //
  391. // 2. Subject Key Identifier, if rekey - For rekey, SubjectKeyIdentifier
  392. // extension will be calculated for the new public key by
  393. // x509util.CreateCertificate()
  394. for _, ext := range oldCert.Extensions {
  395. if ext.Id.Equal(oidAuthorityKeyIdentifier) {
  396. continue
  397. }
  398. if ext.Id.Equal(oidSubjectKeyIdentifier) && isRekey {
  399. newCert.SubjectKeyId = nil
  400. continue
  401. }
  402. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  403. }
  404. // Check if the certificate is allowed to be renewed, name constraints might
  405. // change over time.
  406. //
  407. // TODO(hslatman,maraino): consider adding policies too and consider if
  408. // RenewSSH should check policies.
  409. if err = a.constraintsEngine.ValidateCertificate(newCert); err != nil {
  410. var ee *errs.Error
  411. switch {
  412. case errors.As(err, &ee):
  413. return nil, prov, errs.StatusCodeError(ee.StatusCode(), err, opts...)
  414. default:
  415. return nil, prov, errs.InternalServerErr(err,
  416. errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String()),
  417. errs.WithMessage("error renewing certificate"),
  418. )
  419. }
  420. }
  421. // The token can optionally be in the context. If the CA is running in RA
  422. // mode, this can be used to renew a certificate.
  423. token, _ := TokenFromContext(ctx)
  424. resp, err := a.x509CAService.RenewCertificate(&casapi.RenewCertificateRequest{
  425. Template: newCert,
  426. Lifetime: lifetime,
  427. Backdate: backdate,
  428. Token: token,
  429. })
  430. if err != nil {
  431. return nil, prov, errs.StatusCodeError(http.StatusInternalServerError, err, opts...)
  432. }
  433. chain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  434. if err = a.storeRenewedCertificate(oldCert, chain); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  435. return nil, prov, errs.StatusCodeError(http.StatusInternalServerError, err, opts...)
  436. }
  437. return chain, prov, nil
  438. }
  439. // storeCertificate allows to use an extension of the db.AuthDB interface that
  440. // can log the full chain of certificates.
  441. //
  442. // TODO: at some point we should replace the db.AuthDB interface to implement
  443. // `StoreCertificate(...*x509.Certificate) error` instead of just
  444. // `StoreCertificate(*x509.Certificate) error`.
  445. func (a *Authority) storeCertificate(prov provisioner.Interface, fullchain []*x509.Certificate) error {
  446. type certificateChainStorer interface {
  447. StoreCertificateChain(provisioner.Interface, ...*x509.Certificate) error
  448. }
  449. type certificateChainSimpleStorer interface {
  450. StoreCertificateChain(...*x509.Certificate) error
  451. }
  452. // Store certificate in linkedca
  453. switch s := a.adminDB.(type) {
  454. case certificateChainStorer:
  455. return s.StoreCertificateChain(prov, fullchain...)
  456. case certificateChainSimpleStorer:
  457. return s.StoreCertificateChain(fullchain...)
  458. }
  459. // Store certificate in local db
  460. switch s := a.db.(type) {
  461. case certificateChainStorer:
  462. return s.StoreCertificateChain(prov, fullchain...)
  463. case certificateChainSimpleStorer:
  464. return s.StoreCertificateChain(fullchain...)
  465. case db.CertificateStorer:
  466. return s.StoreCertificate(fullchain[0])
  467. default:
  468. return nil
  469. }
  470. }
  471. // storeRenewedCertificate allows to use an extension of the db.AuthDB interface
  472. // that can log if a certificate has been renewed or rekeyed.
  473. //
  474. // TODO: at some point we should implement this in the standard implementation.
  475. func (a *Authority) storeRenewedCertificate(oldCert *x509.Certificate, fullchain []*x509.Certificate) error {
  476. type renewedCertificateChainStorer interface {
  477. StoreRenewedCertificate(*x509.Certificate, ...*x509.Certificate) error
  478. }
  479. // Store certificate in linkedca
  480. if s, ok := a.adminDB.(renewedCertificateChainStorer); ok {
  481. return s.StoreRenewedCertificate(oldCert, fullchain...)
  482. }
  483. // Store certificate in local db
  484. switch s := a.db.(type) {
  485. case renewedCertificateChainStorer:
  486. return s.StoreRenewedCertificate(oldCert, fullchain...)
  487. case db.CertificateStorer:
  488. return s.StoreCertificate(fullchain[0])
  489. default:
  490. return nil
  491. }
  492. }
  493. // RevokeOptions are the options for the Revoke API.
  494. type RevokeOptions struct {
  495. Serial string
  496. Reason string
  497. ReasonCode int
  498. PassiveOnly bool
  499. MTLS bool
  500. ACME bool
  501. Crt *x509.Certificate
  502. OTT string
  503. }
  504. // AdministrativeRevokeOptions contains options for RevokeAdministratively.
  505. type AdministrativeRevokeOptions struct {
  506. Certificate *x509.Certificate
  507. Reason string
  508. ReasonCode int
  509. PassiveOnly bool
  510. }
  511. // RevokeAdministratively revokes an X.509 certificate without performing
  512. // provisioner authorization. Callers must authorize the operation before
  513. // invoking this method. Revocation is propagated to the configured CAS and
  514. // persistence layers, and a CRL is generated when configured.
  515. func (a *Authority) RevokeAdministratively(_ context.Context, revokeOpts *AdministrativeRevokeOptions) error {
  516. if revokeOpts == nil || revokeOpts.Certificate == nil {
  517. return errs.BadRequest("authority.RevokeAdministratively; certificate is required")
  518. }
  519. crt := revokeOpts.Certificate
  520. if crt.SerialNumber == nil {
  521. return errs.BadRequest("authority.RevokeAdministratively; certificate serial number is required")
  522. }
  523. serial := crt.SerialNumber.String()
  524. opts := []interface{}{
  525. errs.WithKeyVal("serialNumber", serial),
  526. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  527. errs.WithKeyVal("reason", revokeOpts.Reason),
  528. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  529. }
  530. rci := &db.RevokedCertificateInfo{
  531. Serial: serial,
  532. ReasonCode: revokeOpts.ReasonCode,
  533. Reason: revokeOpts.Reason,
  534. RevokedAt: time.Now().UTC(),
  535. ExpiresAt: crt.NotAfter,
  536. }
  537. var provisionerID string
  538. if certificateDataDB, ok := a.db.(interface {
  539. GetCertificateData(string) (*db.CertificateData, error)
  540. }); ok {
  541. if data, err := certificateDataDB.GetCertificateData(serial); err == nil && data != nil && data.Provisioner != nil {
  542. provisionerID = data.Provisioner.ID
  543. }
  544. }
  545. if provisionerID == "" {
  546. if p, err := a.LoadProvisionerByCertificate(crt); err == nil {
  547. provisionerID = p.GetID()
  548. }
  549. }
  550. if provisionerID != "" {
  551. rci.ProvisionerID = provisionerID
  552. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  553. }
  554. return a.revokeX509(&RevokeOptions{
  555. Serial: serial,
  556. Reason: revokeOpts.Reason,
  557. ReasonCode: revokeOpts.ReasonCode,
  558. PassiveOnly: revokeOpts.PassiveOnly,
  559. Crt: crt,
  560. }, rci, "authority.RevokeAdministratively", opts...)
  561. }
  562. // Revoke revokes a certificate.
  563. //
  564. // NOTE: Only supports passive revocation - prevent existing certificates from
  565. // being renewed.
  566. //
  567. // TODO: Add OCSP and CRL support.
  568. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  569. opts := []interface{}{
  570. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  571. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  572. errs.WithKeyVal("reason", revokeOpts.Reason),
  573. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  574. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  575. errs.WithKeyVal("ACME", revokeOpts.ACME),
  576. errs.WithKeyVal("context", provisioner.MethodFromContext(ctx).String()),
  577. }
  578. if revokeOpts.MTLS || revokeOpts.ACME {
  579. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  580. } else {
  581. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  582. }
  583. rci := &db.RevokedCertificateInfo{
  584. Serial: revokeOpts.Serial,
  585. ReasonCode: revokeOpts.ReasonCode,
  586. Reason: revokeOpts.Reason,
  587. MTLS: revokeOpts.MTLS,
  588. ACME: revokeOpts.ACME,
  589. RevokedAt: time.Now().UTC(),
  590. }
  591. // For X509 CRLs attempt to get the expiration date of the certificate.
  592. if provisioner.MethodFromContext(ctx) == provisioner.RevokeMethod {
  593. if revokeOpts.Crt == nil {
  594. cert, err := a.db.GetCertificate(revokeOpts.Serial)
  595. if err == nil {
  596. rci.ExpiresAt = cert.NotAfter
  597. }
  598. } else {
  599. rci.ExpiresAt = revokeOpts.Crt.NotAfter
  600. }
  601. }
  602. // If not mTLS nor ACME, then get the TokenID of the token.
  603. if !revokeOpts.MTLS && !revokeOpts.ACME {
  604. token, err := jose.ParseSigned(revokeOpts.OTT)
  605. if err != nil {
  606. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke; error parsing token", opts...)
  607. }
  608. // Get claims w/out verification.
  609. var claims Claims
  610. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  611. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  612. }
  613. // Verify that the serial in the token matches the serial from the request.
  614. if revokeOpts.Serial != claims.Subject {
  615. return errs.ApplyOptions(
  616. errs.Forbidden(
  617. "request serial number %q and token subject %q do not match",
  618. revokeOpts.Serial, claims.Subject,
  619. ), opts...,
  620. )
  621. }
  622. // This method will also validate the audiences for JWK provisioners.
  623. p, err := a.LoadProvisionerByToken(token, &claims.Claims)
  624. if err != nil {
  625. return err
  626. }
  627. rci.ProvisionerID = p.GetID()
  628. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  629. if err != nil && !errors.Is(err, provisioner.ErrAllowTokenReuse) {
  630. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke; could not get ID for token")
  631. }
  632. opts = append(opts,
  633. errs.WithKeyVal("provisionerID", rci.ProvisionerID),
  634. errs.WithKeyVal("tokenID", rci.TokenID),
  635. )
  636. } else if p, err := a.LoadProvisionerByCertificate(revokeOpts.Crt); err == nil {
  637. // Load the Certificate provisioner if one exists.
  638. rci.ProvisionerID = p.GetID()
  639. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  640. }
  641. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  642. if err := a.revokeSSH(nil, rci); err != nil {
  643. return revokeError(err, rci.Serial, "authority.Revoke", opts...)
  644. }
  645. } else {
  646. return a.revokeX509(revokeOpts, rci, "authority.Revoke", opts...)
  647. }
  648. return nil
  649. }
  650. func (a *Authority) revokeX509(revokeOpts *RevokeOptions, rci *db.RevokedCertificateInfo, operation string, opts ...interface{}) error {
  651. // Revoke an X.509 certificate using CAS. If the certificate is not provided,
  652. // try to read it from the database. If the lookup fails, the CAS decides
  653. // whether a certificate is required.
  654. var revokedCert *x509.Certificate
  655. if revokeOpts.Crt != nil {
  656. revokedCert = revokeOpts.Crt
  657. } else if rci.Serial != "" {
  658. revokedCert, _ = a.db.GetCertificate(rci.Serial)
  659. }
  660. // SoftCAS is a no-op; persistence below records the revocation.
  661. _, err := a.x509CAService.RevokeCertificate(&casapi.RevokeCertificateRequest{
  662. Certificate: revokedCert,
  663. SerialNumber: rci.Serial,
  664. Reason: rci.Reason,
  665. ReasonCode: rci.ReasonCode,
  666. PassiveOnly: revokeOpts.PassiveOnly,
  667. })
  668. if err != nil {
  669. return errs.Wrap(http.StatusInternalServerError, err, operation, opts...)
  670. }
  671. // Persist the revocation.
  672. if err := a.revoke(revokedCert, rci); err != nil {
  673. return revokeError(err, rci.Serial, operation, opts...)
  674. }
  675. // Generate a new CRL so CRL requesters will always get an up-to-date
  676. // CRL whenever they request it.
  677. if a.config.CRL.IsEnabled() && a.config.CRL.GenerateOnRevoke {
  678. if err := a.GenerateCertificateRevocationList(); err != nil {
  679. return errs.Wrap(http.StatusInternalServerError, err, operation, opts...)
  680. }
  681. }
  682. return nil
  683. }
  684. func revokeError(err error, serial, operation string, opts ...interface{}) error {
  685. switch {
  686. case errors.Is(err, db.ErrNotImplemented):
  687. return errs.NotImplemented(operation+"; no persistence layer configured", opts...)
  688. case errors.Is(err, db.ErrAlreadyExists):
  689. return errs.ApplyOptions(
  690. errs.BadRequest("certificate with serial number '%s' is already revoked", serial),
  691. opts...,
  692. )
  693. default:
  694. return errs.Wrap(http.StatusInternalServerError, err, operation, opts...)
  695. }
  696. }
  697. func (a *Authority) revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  698. if lca, ok := a.adminDB.(interface {
  699. Revoke(*x509.Certificate, *db.RevokedCertificateInfo) error
  700. }); ok {
  701. return lca.Revoke(crt, rci)
  702. }
  703. return a.db.Revoke(rci)
  704. }
  705. func (a *Authority) revokeSSH(crt *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  706. if lca, ok := a.adminDB.(interface {
  707. RevokeSSH(*ssh.Certificate, *db.RevokedCertificateInfo) error
  708. }); ok {
  709. return lca.RevokeSSH(crt, rci)
  710. }
  711. return a.db.RevokeSSH(rci)
  712. }
  713. // CertificateRevocationListInfo contains a CRL in DER format and associated metadata.
  714. type CertificateRevocationListInfo struct {
  715. Number int64
  716. ExpiresAt time.Time
  717. Duration time.Duration
  718. Data []byte
  719. }
  720. // GetCertificateRevocationList will return the currently generated CRL from the DB, or a not implemented
  721. // error if the underlying AuthDB does not support CRLs
  722. func (a *Authority) GetCertificateRevocationList() (*CertificateRevocationListInfo, error) {
  723. if !a.config.CRL.IsEnabled() {
  724. return nil, errs.Wrap(http.StatusNotFound, errors.Errorf("Certificate Revocation Lists are not enabled"), "authority.GetCertificateRevocationList")
  725. }
  726. crlDB, ok := a.db.(db.CertificateRevocationListDB)
  727. if !ok {
  728. return nil, errs.Wrap(http.StatusNotImplemented, errors.Errorf("Database does not support Certificate Revocation Lists"), "authority.GetCertificateRevocationList")
  729. }
  730. crlInfo, err := crlDB.GetCRL()
  731. if err != nil {
  732. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetCertificateRevocationList")
  733. }
  734. return &CertificateRevocationListInfo{
  735. Number: crlInfo.Number,
  736. ExpiresAt: crlInfo.ExpiresAt,
  737. Duration: crlInfo.Duration,
  738. Data: crlInfo.DER,
  739. }, nil
  740. }
  741. // GenerateCertificateRevocationList generates a DER representation of a signed CRL and stores it in the
  742. // database. Returns nil if CRL generation has been disabled in the config
  743. func (a *Authority) GenerateCertificateRevocationList() error {
  744. if !a.config.CRL.IsEnabled() {
  745. return nil
  746. }
  747. crlDB, ok := a.db.(db.CertificateRevocationListDB)
  748. if !ok {
  749. return errors.Errorf("Database does not support CRL generation")
  750. }
  751. // some CAS may not implement the CRLGenerator interface, so check before we proceed
  752. caCRLGenerator, ok := a.x509CAService.(casapi.CertificateAuthorityCRLGenerator)
  753. if !ok {
  754. return errors.Errorf("CA does not support CRL Generation")
  755. }
  756. // use a mutex to ensure only one CRL is generated at a time to avoid
  757. // concurrency issues
  758. a.crlMutex.Lock()
  759. defer a.crlMutex.Unlock()
  760. crlInfo, err := crlDB.GetCRL()
  761. if err != nil && !database.IsErrNotFound(err) {
  762. return errors.Wrap(err, "could not retrieve CRL from database")
  763. }
  764. now := time.Now().Truncate(time.Second).UTC()
  765. revokedList, err := crlDB.GetRevokedCertificates()
  766. if err != nil {
  767. return errors.Wrap(err, "could not retrieve revoked certificates list from database")
  768. }
  769. // Number is a monotonically increasing integer (essentially the CRL version
  770. // number) that we need to keep track of and increase every time we generate
  771. // a new CRL
  772. var bn big.Int
  773. if crlInfo != nil {
  774. bn.SetInt64(crlInfo.Number + 1)
  775. }
  776. // Convert our database db.RevokedCertificateInfo types into the x509
  777. // representation ready for the CAS to sign it
  778. var revokedCertificateEntries []x509.RevocationListEntry
  779. skipExpiredTime := now.Add(-config.DefaultCRLExpiredDuration)
  780. for _, revokedCert := range *revokedList {
  781. // skip expired certificates
  782. if !revokedCert.ExpiresAt.IsZero() && revokedCert.ExpiresAt.Before(skipExpiredTime) {
  783. continue
  784. }
  785. var sn big.Int
  786. sn.SetString(revokedCert.Serial, 10)
  787. revokedCertificateEntries = append(revokedCertificateEntries, x509.RevocationListEntry{
  788. SerialNumber: &sn,
  789. RevocationTime: revokedCert.RevokedAt,
  790. ReasonCode: revokedCert.ReasonCode,
  791. })
  792. }
  793. var updateDuration time.Duration
  794. if a.config.CRL.CacheDuration != nil {
  795. updateDuration = a.config.CRL.CacheDuration.Duration
  796. } else if crlInfo != nil {
  797. updateDuration = crlInfo.Duration
  798. }
  799. // Create a RevocationList representation ready for the CAS to sign
  800. // TODO: allow SignatureAlgorithm to be specified?
  801. revocationList := x509.RevocationList{
  802. SignatureAlgorithm: 0,
  803. RevokedCertificateEntries: revokedCertificateEntries,
  804. Number: &bn,
  805. ThisUpdate: now,
  806. NextUpdate: now.Add(updateDuration),
  807. }
  808. // Set CRL IDP to config item, otherwise, leave as default
  809. var fullName string
  810. if a.config.CRL.IDPurl != "" {
  811. fullName = a.config.CRL.IDPurl
  812. } else {
  813. fullName = a.config.Audience("/1.0/crl")[0]
  814. }
  815. // Add distribution point.
  816. //
  817. // Note that this is currently using the port 443 by default.
  818. if b, err := marshalDistributionPoint(fullName); err == nil {
  819. revocationList.ExtraExtensions = []pkix.Extension{
  820. {Id: oidExtensionIssuingDistributionPoint, Critical: true, Value: b},
  821. }
  822. }
  823. certificateRevocationList, err := caCRLGenerator.CreateCRL(&casapi.CreateCRLRequest{RevocationList: &revocationList})
  824. if err != nil {
  825. return errors.Wrap(err, "could not create CRL")
  826. }
  827. // Create a new db.CertificateRevocationListInfo, which stores the new Number we just generated, the
  828. // expiry time, duration, and the DER-encoded CRL
  829. newCRLInfo := db.CertificateRevocationListInfo{
  830. Number: bn.Int64(),
  831. ExpiresAt: revocationList.NextUpdate,
  832. DER: certificateRevocationList.CRL,
  833. Duration: updateDuration,
  834. }
  835. // Store the CRL in the database ready for retrieval by api endpoints
  836. err = crlDB.StoreCRL(&newCRLInfo)
  837. if err != nil {
  838. return errors.Wrap(err, "could not store CRL in database")
  839. }
  840. return nil
  841. }
  842. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  843. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  844. fatal := func(err error) (*tls.Certificate, error) {
  845. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  846. }
  847. // Generate default key.
  848. priv, err := keyutil.GenerateDefaultKey()
  849. if err != nil {
  850. return fatal(err)
  851. }
  852. signer, ok := priv.(crypto.Signer)
  853. if !ok {
  854. return fatal(errors.New("private key is not a crypto.Signer"))
  855. }
  856. // prepare the sans: IPv6 DNS hostname representations are converted to their IP representation
  857. sans := make([]string, len(a.config.DNSNames))
  858. for i, san := range a.config.DNSNames {
  859. if strings.HasPrefix(san, "[") && strings.HasSuffix(san, "]") {
  860. if ip := net.ParseIP(san[1 : len(san)-1]); ip != nil {
  861. san = ip.String()
  862. }
  863. }
  864. sans[i] = san
  865. }
  866. // Create initial certificate request.
  867. cr, err := x509util.CreateCertificateRequest(a.config.CommonName, sans, signer)
  868. if err != nil {
  869. return fatal(err)
  870. }
  871. // Generate certificate template directly from the certificate request.
  872. template, err := x509util.NewCertificate(cr)
  873. if err != nil {
  874. return fatal(err)
  875. }
  876. // Get x509 certificate template, set validity and sign it.
  877. now := time.Now()
  878. certTpl := template.GetCertificate()
  879. certTpl.NotBefore = now.Add(-1 * time.Minute)
  880. certTpl.NotAfter = now.Add(24 * time.Hour)
  881. // Policy and constraints require this fields to be set. At this moment they
  882. // are only present in the extra extension.
  883. certTpl.DNSNames = cr.DNSNames
  884. certTpl.IPAddresses = cr.IPAddresses
  885. certTpl.EmailAddresses = cr.EmailAddresses
  886. certTpl.URIs = cr.URIs
  887. // Fail if name constraints do not allow the server names.
  888. if err := a.constraintsEngine.ValidateCertificate(certTpl); err != nil {
  889. return fatal(err)
  890. }
  891. // Set the cert lifetime as follows:
  892. // i) If the CA is not a StepCAS RA use 24h, else
  893. // ii) if the CA is a StepCAS RA, leave the lifetime empty and
  894. // let the provisioner of the CA decide the lifetime of the RA cert.
  895. var lifetime time.Duration
  896. if casapi.TypeOf(a.x509CAService) != casapi.StepCAS {
  897. lifetime = 24 * time.Hour
  898. }
  899. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  900. Template: certTpl,
  901. CSR: cr,
  902. Lifetime: lifetime,
  903. Backdate: 1 * time.Minute,
  904. IsCAServerCert: true,
  905. })
  906. if err != nil {
  907. return fatal(err)
  908. }
  909. // Generate PEM blocks to create tls.Certificate
  910. pemBlocks := pem.EncodeToMemory(&pem.Block{
  911. Type: "CERTIFICATE",
  912. Bytes: resp.Certificate.Raw,
  913. })
  914. for _, crt := range resp.CertificateChain {
  915. pemBlocks = append(pemBlocks, pem.EncodeToMemory(&pem.Block{
  916. Type: "CERTIFICATE",
  917. Bytes: crt.Raw,
  918. })...)
  919. }
  920. keyPEM, err := pemutil.Serialize(priv)
  921. if err != nil {
  922. return fatal(err)
  923. }
  924. tlsCrt, err := tls.X509KeyPair(pemBlocks, pem.EncodeToMemory(keyPEM))
  925. if err != nil {
  926. return fatal(err)
  927. }
  928. // Set leaf certificate
  929. tlsCrt.Leaf = resp.Certificate
  930. return &tlsCrt, nil
  931. }
  932. // RFC 5280, 5.2.5
  933. type distributionPoint struct {
  934. DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  935. OnlyContainsUserCerts bool `asn1:"optional,tag:1"`
  936. OnlyContainsCACerts bool `asn1:"optional,tag:2"`
  937. OnlySomeReasons asn1.BitString `asn1:"optional,tag:3"`
  938. IndirectCRL bool `asn1:"optional,tag:4"`
  939. OnlyContainsAttributeCerts bool `asn1:"optional,tag:5"`
  940. }
  941. type distributionPointName struct {
  942. FullName []asn1.RawValue `asn1:"optional,tag:0"`
  943. RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  944. }
  945. /*
  946. marshalDistributionPoint currently marshals only DP, citing spec
  947. https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5:
  948. That is, if onlyContainsUserCerts, onlyContainsCACerts, indirectCRL, and
  949. onlyContainsAttributeCerts are all FALSE, then either the
  950. distributionPoint field or the onlySomeReasons field MUST be present.
  951. */
  952. func marshalDistributionPoint(fullName string) ([]byte, error) {
  953. return asn1.Marshal(distributionPoint{
  954. DistributionPoint: distributionPointName{
  955. FullName: []asn1.RawValue{
  956. {Class: 2, Tag: 6, Bytes: []byte(fullName)},
  957. },
  958. },
  959. })
  960. }
  961. // templatingError tries to extract more information about the cause of
  962. // an error related to (most probably) malformed template data and adds
  963. // this to the error message.
  964. func templatingError(err error) error {
  965. cause := errors.Cause(err)
  966. var (
  967. syntaxError *json.SyntaxError
  968. typeError *json.UnmarshalTypeError
  969. )
  970. if errors.As(err, &syntaxError) {
  971. // offset is arguably not super clear to the user, but it's the best we can do here
  972. cause = fmt.Errorf("%w at offset %d", cause, syntaxError.Offset)
  973. } else if errors.As(err, &typeError) {
  974. // slightly rewriting the default error message to include the offset
  975. cause = fmt.Errorf("cannot unmarshal %s at offset %d into Go value of type %s", typeError.Value, typeError.Offset, typeError.Type)
  976. }
  977. return errors.Wrap(cause, "error applying certificate template")
  978. }
  979. func (a *Authority) callEnrichingWebhooksX509(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, attData *provisioner.AttestationData, csr *x509.CertificateRequest) (err error) {
  980. if webhookCtl == nil {
  981. return
  982. }
  983. defer func() { a.meter.X509WebhookEnriched(prov, err) }()
  984. var attested *webhook.AttestationData
  985. if attData != nil {
  986. attested = &webhook.AttestationData{
  987. PermanentIdentifier: attData.PermanentIdentifier,
  988. }
  989. }
  990. var whEnrichReq *webhook.RequestBody
  991. if whEnrichReq, err = webhook.NewRequestBody(
  992. webhook.WithX509CertificateRequest(csr),
  993. webhook.WithAttestationData(attested),
  994. webhook.WithProvisionerName(prov),
  995. ); err == nil {
  996. err = webhookCtl.Enrich(ctx, whEnrichReq)
  997. }
  998. return
  999. }
  1000. func (a *Authority) callAuthorizingWebhooksX509(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, cert *x509util.Certificate, leaf *x509.Certificate, attData *provisioner.AttestationData) (err error) {
  1001. if webhookCtl == nil {
  1002. return
  1003. }
  1004. defer func() { a.meter.X509WebhookAuthorized(prov, err) }()
  1005. var attested *webhook.AttestationData
  1006. if attData != nil {
  1007. attested = &webhook.AttestationData{
  1008. PermanentIdentifier: attData.PermanentIdentifier,
  1009. }
  1010. }
  1011. var whAuthBody *webhook.RequestBody
  1012. if whAuthBody, err = webhook.NewRequestBody(
  1013. webhook.WithX509Certificate(cert, leaf),
  1014. webhook.WithAttestationData(attested),
  1015. webhook.WithProvisionerName(prov),
  1016. ); err == nil {
  1017. err = webhookCtl.Authorize(ctx, whAuthBody)
  1018. }
  1019. return
  1020. }