tls.go 35 KB

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