tls.go 32 KB

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