tls.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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. // Revoke revokes a certificate.
  505. //
  506. // NOTE: Only supports passive revocation - prevent existing certificates from
  507. // being renewed.
  508. //
  509. // TODO: Add OCSP and CRL support.
  510. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  511. opts := []any{
  512. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  513. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  514. errs.WithKeyVal("reason", revokeOpts.Reason),
  515. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  516. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  517. errs.WithKeyVal("ACME", revokeOpts.ACME),
  518. errs.WithKeyVal("context", provisioner.MethodFromContext(ctx).String()),
  519. }
  520. if revokeOpts.MTLS || revokeOpts.ACME {
  521. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  522. } else {
  523. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  524. }
  525. rci := &db.RevokedCertificateInfo{
  526. Serial: revokeOpts.Serial,
  527. ReasonCode: revokeOpts.ReasonCode,
  528. Reason: revokeOpts.Reason,
  529. MTLS: revokeOpts.MTLS,
  530. ACME: revokeOpts.ACME,
  531. RevokedAt: time.Now().UTC(),
  532. }
  533. // For X509 CRLs attempt to get the expiration date of the certificate.
  534. if provisioner.MethodFromContext(ctx) == provisioner.RevokeMethod {
  535. if revokeOpts.Crt == nil {
  536. cert, err := a.db.GetCertificate(revokeOpts.Serial)
  537. if err == nil {
  538. rci.ExpiresAt = cert.NotAfter
  539. }
  540. } else {
  541. rci.ExpiresAt = revokeOpts.Crt.NotAfter
  542. }
  543. }
  544. // If not mTLS nor ACME, then get the TokenID of the token.
  545. if !revokeOpts.MTLS && !revokeOpts.ACME {
  546. token, err := jose.ParseSigned(revokeOpts.OTT)
  547. if err != nil {
  548. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke; error parsing token", opts...)
  549. }
  550. // Get claims w/out verification.
  551. var claims Claims
  552. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  553. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  554. }
  555. // Verify that the serial in the token matches the serial from the request.
  556. if revokeOpts.Serial != claims.Subject {
  557. return errs.ApplyOptions(
  558. errs.Forbidden(
  559. "request serial number %q and token subject %q do not match",
  560. revokeOpts.Serial, claims.Subject,
  561. ), opts...,
  562. )
  563. }
  564. // This method will also validate the audiences for JWK provisioners.
  565. p, err := a.LoadProvisionerByToken(token, &claims.Claims)
  566. if err != nil {
  567. return err
  568. }
  569. rci.ProvisionerID = p.GetID()
  570. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  571. if err != nil && !errors.Is(err, provisioner.ErrAllowTokenReuse) {
  572. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke; could not get ID for token")
  573. }
  574. opts = append(opts,
  575. errs.WithKeyVal("provisionerID", rci.ProvisionerID),
  576. errs.WithKeyVal("tokenID", rci.TokenID),
  577. )
  578. } else if p, err := a.LoadProvisionerByCertificate(revokeOpts.Crt); err == nil {
  579. // Load the Certificate provisioner if one exists.
  580. rci.ProvisionerID = p.GetID()
  581. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  582. }
  583. failRevoke := func(err error) error {
  584. switch {
  585. case errors.Is(err, db.ErrNotImplemented):
  586. return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...)
  587. case errors.Is(err, db.ErrAlreadyExists):
  588. return errs.ApplyOptions(
  589. errs.BadRequest("certificate with serial number '%s' is already revoked", rci.Serial),
  590. opts...,
  591. )
  592. default:
  593. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  594. }
  595. }
  596. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  597. if err := a.revokeSSH(nil, rci); err != nil {
  598. return failRevoke(err)
  599. }
  600. } else {
  601. // Revoke an X.509 certificate using CAS. If the certificate is not
  602. // provided we will try to read it from the db. If the read fails we
  603. // won't throw an error as it will be responsibility of the CAS
  604. // implementation to require a certificate.
  605. var revokedCert *x509.Certificate
  606. if revokeOpts.Crt != nil {
  607. revokedCert = revokeOpts.Crt
  608. } else if rci.Serial != "" {
  609. revokedCert, _ = a.db.GetCertificate(rci.Serial)
  610. }
  611. // CAS operation, note that SoftCAS (default) is a noop.
  612. // The revoke happens when this is stored in the db.
  613. _, err := a.x509CAService.RevokeCertificate(&casapi.RevokeCertificateRequest{
  614. Certificate: revokedCert,
  615. SerialNumber: rci.Serial,
  616. Reason: rci.Reason,
  617. ReasonCode: rci.ReasonCode,
  618. PassiveOnly: revokeOpts.PassiveOnly,
  619. })
  620. if err != nil {
  621. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  622. }
  623. // Save as revoked in the Db.
  624. if err := a.revoke(revokedCert, rci); err != nil {
  625. return failRevoke(err)
  626. }
  627. // Generate a new CRL so CRL requesters will always get an up-to-date
  628. // CRL whenever they request it.
  629. if a.config.CRL.IsEnabled() && a.config.CRL.GenerateOnRevoke {
  630. if err := a.GenerateCertificateRevocationList(); err != nil {
  631. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  632. }
  633. }
  634. }
  635. return nil
  636. }
  637. func (a *Authority) revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  638. if lca, ok := a.adminDB.(interface {
  639. Revoke(*x509.Certificate, *db.RevokedCertificateInfo) error
  640. }); ok {
  641. return lca.Revoke(crt, rci)
  642. }
  643. return a.db.Revoke(rci)
  644. }
  645. func (a *Authority) revokeSSH(crt *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  646. if lca, ok := a.adminDB.(interface {
  647. RevokeSSH(*ssh.Certificate, *db.RevokedCertificateInfo) error
  648. }); ok {
  649. return lca.RevokeSSH(crt, rci)
  650. }
  651. return a.db.RevokeSSH(rci)
  652. }
  653. // CertificateRevocationListInfo contains a CRL in DER format and associated metadata.
  654. type CertificateRevocationListInfo struct {
  655. Number int64
  656. ExpiresAt time.Time
  657. Duration time.Duration
  658. Data []byte
  659. }
  660. // GetCertificateRevocationList will return the currently generated CRL from the DB, or a not implemented
  661. // error if the underlying AuthDB does not support CRLs
  662. func (a *Authority) GetCertificateRevocationList() (*CertificateRevocationListInfo, error) {
  663. if !a.config.CRL.IsEnabled() {
  664. return nil, errs.Wrap(http.StatusNotFound, errors.Errorf("Certificate Revocation Lists are not enabled"), "authority.GetCertificateRevocationList")
  665. }
  666. crlDB, ok := a.db.(db.CertificateRevocationListDB)
  667. if !ok {
  668. return nil, errs.Wrap(http.StatusNotImplemented, errors.Errorf("Database does not support Certificate Revocation Lists"), "authority.GetCertificateRevocationList")
  669. }
  670. crlInfo, err := crlDB.GetCRL()
  671. if err != nil {
  672. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetCertificateRevocationList")
  673. }
  674. return &CertificateRevocationListInfo{
  675. Number: crlInfo.Number,
  676. ExpiresAt: crlInfo.ExpiresAt,
  677. Duration: crlInfo.Duration,
  678. Data: crlInfo.DER,
  679. }, nil
  680. }
  681. // GenerateCertificateRevocationList generates a DER representation of a signed CRL and stores it in the
  682. // database. Returns nil if CRL generation has been disabled in the config
  683. func (a *Authority) GenerateCertificateRevocationList() error {
  684. if !a.config.CRL.IsEnabled() {
  685. return nil
  686. }
  687. crlDB, ok := a.db.(db.CertificateRevocationListDB)
  688. if !ok {
  689. return errors.Errorf("Database does not support CRL generation")
  690. }
  691. // some CAS may not implement the CRLGenerator interface, so check before we proceed
  692. caCRLGenerator, ok := a.x509CAService.(casapi.CertificateAuthorityCRLGenerator)
  693. if !ok {
  694. return errors.Errorf("CA does not support CRL Generation")
  695. }
  696. // use a mutex to ensure only one CRL is generated at a time to avoid
  697. // concurrency issues
  698. a.crlMutex.Lock()
  699. defer a.crlMutex.Unlock()
  700. crlInfo, err := crlDB.GetCRL()
  701. if err != nil && !database.IsErrNotFound(err) {
  702. return errors.Wrap(err, "could not retrieve CRL from database")
  703. }
  704. now := time.Now().Truncate(time.Second).UTC()
  705. revokedList, err := crlDB.GetRevokedCertificates()
  706. if err != nil {
  707. return errors.Wrap(err, "could not retrieve revoked certificates list from database")
  708. }
  709. // Number is a monotonically increasing integer (essentially the CRL version
  710. // number) that we need to keep track of and increase every time we generate
  711. // a new CRL
  712. var bn big.Int
  713. if crlInfo != nil {
  714. bn.SetInt64(crlInfo.Number + 1)
  715. }
  716. // Convert our database db.RevokedCertificateInfo types into the x509
  717. // representation ready for the CAS to sign it
  718. var revokedCertificateEntries []x509.RevocationListEntry
  719. skipExpiredTime := now.Add(-config.DefaultCRLExpiredDuration)
  720. for _, revokedCert := range *revokedList {
  721. // skip expired certificates
  722. if !revokedCert.ExpiresAt.IsZero() && revokedCert.ExpiresAt.Before(skipExpiredTime) {
  723. continue
  724. }
  725. var sn big.Int
  726. sn.SetString(revokedCert.Serial, 10)
  727. revokedCertificateEntries = append(revokedCertificateEntries, x509.RevocationListEntry{
  728. SerialNumber: &sn,
  729. RevocationTime: revokedCert.RevokedAt,
  730. ReasonCode: revokedCert.ReasonCode,
  731. })
  732. }
  733. var updateDuration time.Duration
  734. if a.config.CRL.CacheDuration != nil {
  735. updateDuration = a.config.CRL.CacheDuration.Duration
  736. } else if crlInfo != nil {
  737. updateDuration = crlInfo.Duration
  738. }
  739. // Create a RevocationList representation ready for the CAS to sign
  740. // TODO: allow SignatureAlgorithm to be specified?
  741. revocationList := x509.RevocationList{
  742. SignatureAlgorithm: 0,
  743. RevokedCertificateEntries: revokedCertificateEntries,
  744. Number: &bn,
  745. ThisUpdate: now,
  746. NextUpdate: now.Add(updateDuration),
  747. }
  748. // Set CRL IDP to config item, otherwise, leave as default
  749. var fullName string
  750. if a.config.CRL.IDPurl != "" {
  751. fullName = a.config.CRL.IDPurl
  752. } else {
  753. fullName = a.config.Audience("/1.0/crl")[0]
  754. }
  755. // Add distribution point.
  756. //
  757. // Note that this is currently using the port 443 by default.
  758. if b, err := marshalDistributionPoint(fullName); err == nil {
  759. revocationList.ExtraExtensions = []pkix.Extension{
  760. {Id: oidExtensionIssuingDistributionPoint, Critical: true, Value: b},
  761. }
  762. }
  763. certificateRevocationList, err := caCRLGenerator.CreateCRL(&casapi.CreateCRLRequest{RevocationList: &revocationList})
  764. if err != nil {
  765. return errors.Wrap(err, "could not create CRL")
  766. }
  767. // Create a new db.CertificateRevocationListInfo, which stores the new Number we just generated, the
  768. // expiry time, duration, and the DER-encoded CRL
  769. newCRLInfo := db.CertificateRevocationListInfo{
  770. Number: bn.Int64(),
  771. ExpiresAt: revocationList.NextUpdate,
  772. DER: certificateRevocationList.CRL,
  773. Duration: updateDuration,
  774. }
  775. // Store the CRL in the database ready for retrieval by api endpoints
  776. err = crlDB.StoreCRL(&newCRLInfo)
  777. if err != nil {
  778. return errors.Wrap(err, "could not store CRL in database")
  779. }
  780. return nil
  781. }
  782. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  783. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  784. fatal := func(err error) (*tls.Certificate, error) {
  785. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  786. }
  787. // Generate default key.
  788. priv, err := keyutil.GenerateDefaultKey()
  789. if err != nil {
  790. return fatal(err)
  791. }
  792. signer, ok := priv.(crypto.Signer)
  793. if !ok {
  794. return fatal(errors.New("private key is not a crypto.Signer"))
  795. }
  796. // prepare the sans: IPv6 DNS hostname representations are converted to their IP representation
  797. sans := make([]string, len(a.config.DNSNames))
  798. for i, san := range a.config.DNSNames {
  799. if strings.HasPrefix(san, "[") && strings.HasSuffix(san, "]") {
  800. if ip := net.ParseIP(san[1 : len(san)-1]); ip != nil {
  801. san = ip.String()
  802. }
  803. }
  804. sans[i] = san
  805. }
  806. // Create initial certificate request.
  807. cr, err := x509util.CreateCertificateRequest(a.config.CommonName, sans, signer)
  808. if err != nil {
  809. return fatal(err)
  810. }
  811. // Generate certificate template directly from the certificate request.
  812. template, err := x509util.NewCertificate(cr)
  813. if err != nil {
  814. return fatal(err)
  815. }
  816. // Get x509 certificate template, set validity and sign it.
  817. now := time.Now()
  818. certTpl := template.GetCertificate()
  819. certTpl.NotBefore = now.Add(-1 * time.Minute)
  820. certTpl.NotAfter = now.Add(24 * time.Hour)
  821. // Policy and constraints require this fields to be set. At this moment they
  822. // are only present in the extra extension.
  823. certTpl.DNSNames = cr.DNSNames
  824. certTpl.IPAddresses = cr.IPAddresses
  825. certTpl.EmailAddresses = cr.EmailAddresses
  826. certTpl.URIs = cr.URIs
  827. // Fail if name constraints do not allow the server names.
  828. if err := a.constraintsEngine.ValidateCertificate(certTpl); err != nil {
  829. return fatal(err)
  830. }
  831. // Set the cert lifetime as follows:
  832. // i) If the CA is not a StepCAS RA use 24h, else
  833. // ii) if the CA is a StepCAS RA, leave the lifetime empty and
  834. // let the provisioner of the CA decide the lifetime of the RA cert.
  835. var lifetime time.Duration
  836. if casapi.TypeOf(a.x509CAService) != casapi.StepCAS {
  837. lifetime = 24 * time.Hour
  838. }
  839. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  840. Template: certTpl,
  841. CSR: cr,
  842. Lifetime: lifetime,
  843. Backdate: 1 * time.Minute,
  844. IsCAServerCert: true,
  845. })
  846. if err != nil {
  847. return fatal(err)
  848. }
  849. // Generate PEM blocks to create tls.Certificate
  850. pemBlocks := pem.EncodeToMemory(&pem.Block{
  851. Type: "CERTIFICATE",
  852. Bytes: resp.Certificate.Raw,
  853. })
  854. for _, crt := range resp.CertificateChain {
  855. pemBlocks = append(pemBlocks, pem.EncodeToMemory(&pem.Block{
  856. Type: "CERTIFICATE",
  857. Bytes: crt.Raw,
  858. })...)
  859. }
  860. keyPEM, err := pemutil.Serialize(priv)
  861. if err != nil {
  862. return fatal(err)
  863. }
  864. tlsCrt, err := tls.X509KeyPair(pemBlocks, pem.EncodeToMemory(keyPEM))
  865. if err != nil {
  866. return fatal(err)
  867. }
  868. // Set leaf certificate
  869. tlsCrt.Leaf = resp.Certificate
  870. return &tlsCrt, nil
  871. }
  872. // RFC 5280, 5.2.5
  873. type distributionPoint struct {
  874. DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  875. OnlyContainsUserCerts bool `asn1:"optional,tag:1"`
  876. OnlyContainsCACerts bool `asn1:"optional,tag:2"`
  877. OnlySomeReasons asn1.BitString `asn1:"optional,tag:3"`
  878. IndirectCRL bool `asn1:"optional,tag:4"`
  879. OnlyContainsAttributeCerts bool `asn1:"optional,tag:5"`
  880. }
  881. type distributionPointName struct {
  882. FullName []asn1.RawValue `asn1:"optional,tag:0"`
  883. RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  884. }
  885. /*
  886. marshalDistributionPoint currently marshals only DP, citing spec
  887. https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5:
  888. That is, if onlyContainsUserCerts, onlyContainsCACerts, indirectCRL, and
  889. onlyContainsAttributeCerts are all FALSE, then either the
  890. distributionPoint field or the onlySomeReasons field MUST be present.
  891. */
  892. func marshalDistributionPoint(fullName string) ([]byte, error) {
  893. return asn1.Marshal(distributionPoint{
  894. DistributionPoint: distributionPointName{
  895. FullName: []asn1.RawValue{
  896. {Class: 2, Tag: 6, Bytes: []byte(fullName)},
  897. },
  898. },
  899. })
  900. }
  901. // templatingError tries to extract more information about the cause of
  902. // an error related to (most probably) malformed template data and adds
  903. // this to the error message.
  904. func templatingError(err error) error {
  905. cause := errors.Cause(err)
  906. var (
  907. syntaxError *json.SyntaxError
  908. typeError *json.UnmarshalTypeError
  909. )
  910. if errors.As(err, &syntaxError) {
  911. // offset is arguably not super clear to the user, but it's the best we can do here
  912. cause = fmt.Errorf("%w at offset %d", cause, syntaxError.Offset)
  913. } else if errors.As(err, &typeError) {
  914. // slightly rewriting the default error message to include the offset
  915. cause = fmt.Errorf("cannot unmarshal %s at offset %d into Go value of type %s", typeError.Value, typeError.Offset, typeError.Type)
  916. }
  917. return errors.Wrap(cause, "error applying certificate template")
  918. }
  919. func (a *Authority) callEnrichingWebhooksX509(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, attData *provisioner.AttestationData, csr *x509.CertificateRequest) (err error) {
  920. if webhookCtl == nil {
  921. return
  922. }
  923. defer func() { a.meter.X509WebhookEnriched(prov, err) }()
  924. var attested *webhook.AttestationData
  925. if attData != nil {
  926. attested = &webhook.AttestationData{
  927. PermanentIdentifier: attData.PermanentIdentifier,
  928. }
  929. }
  930. var whEnrichReq *webhook.RequestBody
  931. if whEnrichReq, err = webhook.NewRequestBody(
  932. webhook.WithX509CertificateRequest(csr),
  933. webhook.WithAttestationData(attested),
  934. webhook.WithProvisionerName(prov),
  935. ); err == nil {
  936. err = webhookCtl.Enrich(ctx, whEnrichReq)
  937. }
  938. return
  939. }
  940. func (a *Authority) callAuthorizingWebhooksX509(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, cert *x509util.Certificate, leaf *x509.Certificate, attData *provisioner.AttestationData) (err error) {
  941. if webhookCtl == nil {
  942. return
  943. }
  944. defer func() { a.meter.X509WebhookAuthorized(prov, err) }()
  945. var attested *webhook.AttestationData
  946. if attData != nil {
  947. attested = &webhook.AttestationData{
  948. PermanentIdentifier: attData.PermanentIdentifier,
  949. }
  950. }
  951. var whAuthBody *webhook.RequestBody
  952. if whAuthBody, err = webhook.NewRequestBody(
  953. webhook.WithX509Certificate(cert, leaf),
  954. webhook.WithAttestationData(attested),
  955. webhook.WithProvisionerName(prov),
  956. ); err == nil {
  957. err = webhookCtl.Authorize(ctx, whAuthBody)
  958. }
  959. return
  960. }