tls.go 36 KB

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