tls.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/base64"
  9. "encoding/json"
  10. "encoding/pem"
  11. "fmt"
  12. "net"
  13. "net/http"
  14. "strings"
  15. "time"
  16. "github.com/pkg/errors"
  17. "golang.org/x/crypto/ssh"
  18. "go.step.sm/crypto/jose"
  19. "go.step.sm/crypto/keyutil"
  20. "go.step.sm/crypto/pemutil"
  21. "go.step.sm/crypto/x509util"
  22. "github.com/smallstep/certificates/authority/config"
  23. "github.com/smallstep/certificates/authority/provisioner"
  24. casapi "github.com/smallstep/certificates/cas/apiv1"
  25. "github.com/smallstep/certificates/db"
  26. "github.com/smallstep/certificates/errs"
  27. "github.com/smallstep/certificates/webhook"
  28. )
  29. // GetTLSOptions returns the tls options configured.
  30. func (a *Authority) GetTLSOptions() *config.TLSOptions {
  31. return a.config.TLS
  32. }
  33. var oidAuthorityKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 35}
  34. var oidSubjectKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 14}
  35. func withDefaultASN1DN(def *config.ASN1DN) provisioner.CertificateModifierFunc {
  36. return func(crt *x509.Certificate, opts provisioner.SignOptions) error {
  37. if def == nil {
  38. return errors.New("default ASN1DN template cannot be nil")
  39. }
  40. if len(crt.Subject.Country) == 0 && def.Country != "" {
  41. crt.Subject.Country = append(crt.Subject.Country, def.Country)
  42. }
  43. if len(crt.Subject.Organization) == 0 && def.Organization != "" {
  44. crt.Subject.Organization = append(crt.Subject.Organization, def.Organization)
  45. }
  46. if len(crt.Subject.OrganizationalUnit) == 0 && def.OrganizationalUnit != "" {
  47. crt.Subject.OrganizationalUnit = append(crt.Subject.OrganizationalUnit, def.OrganizationalUnit)
  48. }
  49. if len(crt.Subject.Locality) == 0 && def.Locality != "" {
  50. crt.Subject.Locality = append(crt.Subject.Locality, def.Locality)
  51. }
  52. if len(crt.Subject.Province) == 0 && def.Province != "" {
  53. crt.Subject.Province = append(crt.Subject.Province, def.Province)
  54. }
  55. if len(crt.Subject.StreetAddress) == 0 && def.StreetAddress != "" {
  56. crt.Subject.StreetAddress = append(crt.Subject.StreetAddress, def.StreetAddress)
  57. }
  58. if crt.Subject.SerialNumber == "" && def.SerialNumber != "" {
  59. crt.Subject.SerialNumber = def.SerialNumber
  60. }
  61. if crt.Subject.CommonName == "" && def.CommonName != "" {
  62. crt.Subject.CommonName = def.CommonName
  63. }
  64. return nil
  65. }
  66. }
  67. // Sign creates a signed certificate from a certificate signing request.
  68. func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  69. var (
  70. certOptions []x509util.Option
  71. certValidators []provisioner.CertificateValidator
  72. certModifiers []provisioner.CertificateModifier
  73. certEnforcers []provisioner.CertificateEnforcer
  74. )
  75. opts := []interface{}{errs.WithKeyVal("csr", csr), errs.WithKeyVal("signOptions", signOpts)}
  76. if err := csr.CheckSignature(); err != nil {
  77. return nil, errs.ApplyOptions(
  78. errs.BadRequestErr(err, "invalid certificate request"),
  79. opts...,
  80. )
  81. }
  82. // Set backdate with the configured value
  83. signOpts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  84. var prov provisioner.Interface
  85. var pInfo *casapi.ProvisionerInfo
  86. var attData *provisioner.AttestationData
  87. var webhookCtl webhookController
  88. for _, op := range extraOpts {
  89. switch k := op.(type) {
  90. // Capture current provisioner
  91. case provisioner.Interface:
  92. prov = k
  93. pInfo = &casapi.ProvisionerInfo{
  94. ID: prov.GetID(),
  95. Type: prov.GetType().String(),
  96. Name: prov.GetName(),
  97. }
  98. // Adds new options to NewCertificate
  99. case provisioner.CertificateOptions:
  100. certOptions = append(certOptions, k.Options(signOpts)...)
  101. // Validate the given certificate request.
  102. case provisioner.CertificateRequestValidator:
  103. if err := k.Valid(csr); err != nil {
  104. return nil, errs.ApplyOptions(
  105. errs.ForbiddenErr(err, "error validating certificate"),
  106. opts...,
  107. )
  108. }
  109. // Validates the unsigned certificate template.
  110. case provisioner.CertificateValidator:
  111. certValidators = append(certValidators, k)
  112. // Modifies a certificate before validating it.
  113. case provisioner.CertificateModifier:
  114. certModifiers = append(certModifiers, k)
  115. // Modifies a certificate after validating it.
  116. case provisioner.CertificateEnforcer:
  117. certEnforcers = append(certEnforcers, k)
  118. // Extra information from ACME attestations.
  119. case provisioner.AttestationData:
  120. attData = &k
  121. // Capture the provisioner's webhook controller
  122. case webhookController:
  123. webhookCtl = k
  124. default:
  125. return nil, errs.InternalServer("authority.Sign; invalid extra option type %T", append([]interface{}{k}, opts...)...)
  126. }
  127. }
  128. if err := callEnrichingWebhooksX509(webhookCtl, attData, csr); err != nil {
  129. return nil, errs.ApplyOptions(
  130. errs.ForbiddenErr(err, err.Error()),
  131. errs.WithKeyVal("csr", csr),
  132. errs.WithKeyVal("signOptions", signOpts),
  133. )
  134. }
  135. cert, err := x509util.NewCertificate(csr, certOptions...)
  136. if err != nil {
  137. var te *x509util.TemplateError
  138. if errors.As(err, &te) {
  139. return nil, errs.ApplyOptions(
  140. errs.BadRequestErr(err, err.Error()),
  141. errs.WithKeyVal("csr", csr),
  142. errs.WithKeyVal("signOptions", signOpts),
  143. )
  144. }
  145. // explicitly check for unmarshaling errors, which are most probably caused by JSON template (syntax) errors
  146. if strings.HasPrefix(err.Error(), "error unmarshaling certificate") {
  147. return nil, errs.InternalServerErr(templatingError(err),
  148. errs.WithKeyVal("csr", csr),
  149. errs.WithKeyVal("signOptions", signOpts),
  150. errs.WithMessage("error applying certificate template"),
  151. )
  152. }
  153. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign", opts...)
  154. }
  155. // Certificate modifiers before validation
  156. leaf := cert.GetCertificate()
  157. // Set default subject
  158. if err := withDefaultASN1DN(a.config.AuthorityConfig.Template).Modify(leaf, signOpts); err != nil {
  159. return nil, errs.ApplyOptions(
  160. errs.ForbiddenErr(err, "error creating certificate"),
  161. opts...,
  162. )
  163. }
  164. for _, m := range certModifiers {
  165. if err := m.Modify(leaf, signOpts); err != nil {
  166. return nil, errs.ApplyOptions(
  167. errs.ForbiddenErr(err, "error creating certificate"),
  168. opts...,
  169. )
  170. }
  171. }
  172. // Certificate validation.
  173. for _, v := range certValidators {
  174. if err := v.Valid(leaf, signOpts); err != nil {
  175. return nil, errs.ApplyOptions(
  176. errs.ForbiddenErr(err, "error validating certificate"),
  177. opts...,
  178. )
  179. }
  180. }
  181. // Certificate modifiers after validation
  182. for _, m := range certEnforcers {
  183. if err := m.Enforce(leaf); err != nil {
  184. return nil, errs.ApplyOptions(
  185. errs.ForbiddenErr(err, "error creating certificate"),
  186. opts...,
  187. )
  188. }
  189. }
  190. // Process injected modifiers after validation
  191. for _, m := range a.x509Enforcers {
  192. if err := m.Enforce(leaf); err != nil {
  193. return nil, errs.ApplyOptions(
  194. errs.ForbiddenErr(err, "error creating certificate"),
  195. opts...,
  196. )
  197. }
  198. }
  199. // Check if authority is allowed to sign the certificate
  200. if err := a.isAllowedToSignX509Certificate(leaf); err != nil {
  201. var ee *errs.Error
  202. if errors.As(err, &ee) {
  203. return nil, errs.ApplyOptions(ee, opts...)
  204. }
  205. return nil, errs.InternalServerErr(err,
  206. errs.WithKeyVal("csr", csr),
  207. errs.WithKeyVal("signOptions", signOpts),
  208. errs.WithMessage("error creating certificate"),
  209. )
  210. }
  211. // Send certificate to webhooks for authorization
  212. if err := callAuthorizingWebhooksX509(webhookCtl, cert, leaf, attData); err != nil {
  213. return nil, errs.ApplyOptions(
  214. errs.ForbiddenErr(err, "error creating certificate"),
  215. opts...,
  216. )
  217. }
  218. // Sign certificate
  219. lifetime := leaf.NotAfter.Sub(leaf.NotBefore.Add(signOpts.Backdate))
  220. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  221. Template: leaf,
  222. CSR: csr,
  223. Lifetime: lifetime,
  224. Backdate: signOpts.Backdate,
  225. Provisioner: pInfo,
  226. })
  227. if err != nil {
  228. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error creating certificate", opts...)
  229. }
  230. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  231. // Wrap provisioner with extra information.
  232. prov = wrapProvisioner(prov, attData)
  233. // Store certificate in the db.
  234. if err = a.storeCertificate(prov, fullchain); err != nil {
  235. if !errors.Is(err, db.ErrNotImplemented) {
  236. return nil, errs.Wrap(http.StatusInternalServerError, err,
  237. "authority.Sign; error storing certificate in db", opts...)
  238. }
  239. }
  240. return fullchain, nil
  241. }
  242. // isAllowedToSignX509Certificate checks if the Authority is allowed
  243. // to sign the X.509 certificate.
  244. func (a *Authority) isAllowedToSignX509Certificate(cert *x509.Certificate) error {
  245. if err := a.constraintsEngine.ValidateCertificate(cert); err != nil {
  246. return err
  247. }
  248. return a.policyEngine.IsX509CertificateAllowed(cert)
  249. }
  250. // AreSANsAllowed evaluates the provided sans against the
  251. // authority X.509 policy.
  252. func (a *Authority) AreSANsAllowed(ctx context.Context, sans []string) error {
  253. return a.policyEngine.AreSANsAllowed(sans)
  254. }
  255. // Renew creates a new Certificate identical to the old certificate, except
  256. // with a validity window that begins 'now'.
  257. func (a *Authority) Renew(oldCert *x509.Certificate) ([]*x509.Certificate, error) {
  258. return a.Rekey(oldCert, nil)
  259. }
  260. // Rekey is used for rekeying and renewing based on the public key.
  261. // If the public key is 'nil' then it's assumed that the cert should be renewed
  262. // using the existing public key. If the public key is not 'nil' then it's
  263. // assumed that the cert should be rekeyed.
  264. // For both Rekey and Renew all other attributes of the new certificate should
  265. // match the old certificate. The exceptions are 'AuthorityKeyId' (which may
  266. // have changed), 'SubjectKeyId' (different in case of rekey), and
  267. // 'NotBefore/NotAfter' (the validity duration of the new certificate should be
  268. // equal to the old one, but starting 'now').
  269. func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  270. isRekey := (pk != nil)
  271. opts := []interface{}{errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String())}
  272. // Check step provisioner extensions
  273. if err := a.authorizeRenew(oldCert); err != nil {
  274. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  275. }
  276. // Durations
  277. backdate := a.config.AuthorityConfig.Backdate.Duration
  278. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  279. lifetime := duration - backdate
  280. // Create new certificate from previous values.
  281. // Issuer, NotBefore, NotAfter and SubjectKeyId will be set by the CAS.
  282. newCert := &x509.Certificate{
  283. Subject: oldCert.Subject,
  284. KeyUsage: oldCert.KeyUsage,
  285. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  286. ExtKeyUsage: oldCert.ExtKeyUsage,
  287. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  288. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  289. IsCA: oldCert.IsCA,
  290. MaxPathLen: oldCert.MaxPathLen,
  291. MaxPathLenZero: oldCert.MaxPathLenZero,
  292. OCSPServer: oldCert.OCSPServer,
  293. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  294. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  295. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  296. DNSNames: oldCert.DNSNames,
  297. EmailAddresses: oldCert.EmailAddresses,
  298. IPAddresses: oldCert.IPAddresses,
  299. URIs: oldCert.URIs,
  300. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  301. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  302. PermittedIPRanges: oldCert.PermittedIPRanges,
  303. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  304. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  305. PermittedURIDomains: oldCert.PermittedURIDomains,
  306. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  307. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  308. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  309. }
  310. if isRekey {
  311. newCert.PublicKey = pk
  312. } else {
  313. newCert.PublicKey = oldCert.PublicKey
  314. }
  315. // Copy all extensions except:
  316. //
  317. // 1. Authority Key Identifier - This one might be different if we rotate
  318. // the intermediate certificate and it will cause a TLS bad certificate
  319. // error.
  320. //
  321. // 2. Subject Key Identifier, if rekey - For rekey, SubjectKeyIdentifier
  322. // extension will be calculated for the new public key by
  323. // x509util.CreateCertificate()
  324. for _, ext := range oldCert.Extensions {
  325. if ext.Id.Equal(oidAuthorityKeyIdentifier) {
  326. continue
  327. }
  328. if ext.Id.Equal(oidSubjectKeyIdentifier) && isRekey {
  329. newCert.SubjectKeyId = nil
  330. continue
  331. }
  332. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  333. }
  334. // Check if the certificate is allowed to be renewed, name constraints might
  335. // change over time.
  336. //
  337. // TODO(hslatman,maraino): consider adding policies too and consider if
  338. // RenewSSH should check policies.
  339. if err := a.constraintsEngine.ValidateCertificate(newCert); err != nil {
  340. var ee *errs.Error
  341. if errors.As(err, &ee) {
  342. return nil, errs.ApplyOptions(ee, opts...)
  343. }
  344. return nil, errs.InternalServerErr(err,
  345. errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String()),
  346. errs.WithMessage("error renewing certificate"),
  347. )
  348. }
  349. resp, err := a.x509CAService.RenewCertificate(&casapi.RenewCertificateRequest{
  350. Template: newCert,
  351. Lifetime: lifetime,
  352. Backdate: backdate,
  353. })
  354. if err != nil {
  355. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  356. }
  357. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  358. if err = a.storeRenewedCertificate(oldCert, fullchain); err != nil {
  359. if !errors.Is(err, db.ErrNotImplemented) {
  360. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey; error storing certificate in db", opts...)
  361. }
  362. }
  363. return fullchain, nil
  364. }
  365. // storeCertificate allows to use an extension of the db.AuthDB interface that
  366. // can log the full chain of certificates.
  367. //
  368. // TODO: at some point we should replace the db.AuthDB interface to implement
  369. // `StoreCertificate(...*x509.Certificate) error` instead of just
  370. // `StoreCertificate(*x509.Certificate) error`.
  371. func (a *Authority) storeCertificate(prov provisioner.Interface, fullchain []*x509.Certificate) error {
  372. type certificateChainStorer interface {
  373. StoreCertificateChain(provisioner.Interface, ...*x509.Certificate) error
  374. }
  375. type certificateChainSimpleStorer interface {
  376. StoreCertificateChain(...*x509.Certificate) error
  377. }
  378. // Store certificate in linkedca
  379. switch s := a.adminDB.(type) {
  380. case certificateChainStorer:
  381. return s.StoreCertificateChain(prov, fullchain...)
  382. case certificateChainSimpleStorer:
  383. return s.StoreCertificateChain(fullchain...)
  384. }
  385. // Store certificate in local db
  386. switch s := a.db.(type) {
  387. case certificateChainStorer:
  388. return s.StoreCertificateChain(prov, fullchain...)
  389. case certificateChainSimpleStorer:
  390. return s.StoreCertificateChain(fullchain...)
  391. case db.CertificateStorer:
  392. return s.StoreCertificate(fullchain[0])
  393. default:
  394. return nil
  395. }
  396. }
  397. // storeRenewedCertificate allows to use an extension of the db.AuthDB interface
  398. // that can log if a certificate has been renewed or rekeyed.
  399. //
  400. // TODO: at some point we should implement this in the standard implementation.
  401. func (a *Authority) storeRenewedCertificate(oldCert *x509.Certificate, fullchain []*x509.Certificate) error {
  402. type renewedCertificateChainStorer interface {
  403. StoreRenewedCertificate(*x509.Certificate, ...*x509.Certificate) error
  404. }
  405. // Store certificate in linkedca
  406. if s, ok := a.adminDB.(renewedCertificateChainStorer); ok {
  407. return s.StoreRenewedCertificate(oldCert, fullchain...)
  408. }
  409. // Store certificate in local db
  410. switch s := a.db.(type) {
  411. case renewedCertificateChainStorer:
  412. return s.StoreRenewedCertificate(oldCert, fullchain...)
  413. case db.CertificateStorer:
  414. return s.StoreCertificate(fullchain[0])
  415. default:
  416. return nil
  417. }
  418. }
  419. // RevokeOptions are the options for the Revoke API.
  420. type RevokeOptions struct {
  421. Serial string
  422. Reason string
  423. ReasonCode int
  424. PassiveOnly bool
  425. MTLS bool
  426. ACME bool
  427. Crt *x509.Certificate
  428. OTT string
  429. }
  430. // Revoke revokes a certificate.
  431. //
  432. // NOTE: Only supports passive revocation - prevent existing certificates from
  433. // being renewed.
  434. //
  435. // TODO: Add OCSP and CRL support.
  436. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  437. opts := []interface{}{
  438. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  439. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  440. errs.WithKeyVal("reason", revokeOpts.Reason),
  441. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  442. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  443. errs.WithKeyVal("ACME", revokeOpts.ACME),
  444. errs.WithKeyVal("context", provisioner.MethodFromContext(ctx).String()),
  445. }
  446. if revokeOpts.MTLS || revokeOpts.ACME {
  447. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  448. } else {
  449. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  450. }
  451. rci := &db.RevokedCertificateInfo{
  452. Serial: revokeOpts.Serial,
  453. ReasonCode: revokeOpts.ReasonCode,
  454. Reason: revokeOpts.Reason,
  455. MTLS: revokeOpts.MTLS,
  456. ACME: revokeOpts.ACME,
  457. RevokedAt: time.Now().UTC(),
  458. }
  459. var (
  460. p provisioner.Interface
  461. err error
  462. )
  463. // If not mTLS nor ACME, then get the TokenID of the token.
  464. if !(revokeOpts.MTLS || revokeOpts.ACME) {
  465. token, err := jose.ParseSigned(revokeOpts.OTT)
  466. if err != nil {
  467. return errs.Wrap(http.StatusUnauthorized, err,
  468. "authority.Revoke; error parsing token", opts...)
  469. }
  470. // Get claims w/out verification.
  471. var claims Claims
  472. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  473. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  474. }
  475. // This method will also validate the audiences for JWK provisioners.
  476. p, err = a.LoadProvisionerByToken(token, &claims.Claims)
  477. if err != nil {
  478. return err
  479. }
  480. rci.ProvisionerID = p.GetID()
  481. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  482. if err != nil && !errors.Is(err, provisioner.ErrAllowTokenReuse) {
  483. return errs.Wrap(http.StatusInternalServerError, err,
  484. "authority.Revoke; could not get ID for token")
  485. }
  486. opts = append(opts,
  487. errs.WithKeyVal("provisionerID", rci.ProvisionerID),
  488. errs.WithKeyVal("tokenID", rci.TokenID),
  489. )
  490. } else if p, err = a.LoadProvisionerByCertificate(revokeOpts.Crt); err == nil {
  491. // Load the Certificate provisioner if one exists.
  492. rci.ProvisionerID = p.GetID()
  493. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  494. }
  495. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  496. err = a.revokeSSH(nil, rci)
  497. } else {
  498. // Revoke an X.509 certificate using CAS. If the certificate is not
  499. // provided we will try to read it from the db. If the read fails we
  500. // won't throw an error as it will be responsibility of the CAS
  501. // implementation to require a certificate.
  502. var revokedCert *x509.Certificate
  503. if revokeOpts.Crt != nil {
  504. revokedCert = revokeOpts.Crt
  505. } else if rci.Serial != "" {
  506. revokedCert, _ = a.db.GetCertificate(rci.Serial)
  507. }
  508. // CAS operation, note that SoftCAS (default) is a noop.
  509. // The revoke happens when this is stored in the db.
  510. _, err = a.x509CAService.RevokeCertificate(&casapi.RevokeCertificateRequest{
  511. Certificate: revokedCert,
  512. SerialNumber: rci.Serial,
  513. Reason: rci.Reason,
  514. ReasonCode: rci.ReasonCode,
  515. PassiveOnly: revokeOpts.PassiveOnly,
  516. })
  517. if err != nil {
  518. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  519. }
  520. // Save as revoked in the Db.
  521. err = a.revoke(revokedCert, rci)
  522. }
  523. switch {
  524. case err == nil:
  525. return nil
  526. case errors.Is(err, db.ErrNotImplemented):
  527. return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...)
  528. case errors.Is(err, db.ErrAlreadyExists):
  529. return errs.ApplyOptions(
  530. errs.BadRequest("certificate with serial number '%s' is already revoked", rci.Serial),
  531. opts...,
  532. )
  533. default:
  534. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  535. }
  536. }
  537. func (a *Authority) revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  538. if lca, ok := a.adminDB.(interface {
  539. Revoke(*x509.Certificate, *db.RevokedCertificateInfo) error
  540. }); ok {
  541. return lca.Revoke(crt, rci)
  542. }
  543. return a.db.Revoke(rci)
  544. }
  545. func (a *Authority) revokeSSH(crt *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  546. if lca, ok := a.adminDB.(interface {
  547. RevokeSSH(*ssh.Certificate, *db.RevokedCertificateInfo) error
  548. }); ok {
  549. return lca.RevokeSSH(crt, rci)
  550. }
  551. return a.db.RevokeSSH(rci)
  552. }
  553. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  554. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  555. fatal := func(err error) (*tls.Certificate, error) {
  556. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  557. }
  558. // Generate default key.
  559. priv, err := keyutil.GenerateDefaultKey()
  560. if err != nil {
  561. return fatal(err)
  562. }
  563. signer, ok := priv.(crypto.Signer)
  564. if !ok {
  565. return fatal(errors.New("private key is not a crypto.Signer"))
  566. }
  567. // prepare the sans: IPv6 DNS hostname representations are converted to their IP representation
  568. sans := make([]string, len(a.config.DNSNames))
  569. for i, san := range a.config.DNSNames {
  570. if strings.HasPrefix(san, "[") && strings.HasSuffix(san, "]") {
  571. if ip := net.ParseIP(san[1 : len(san)-1]); ip != nil {
  572. san = ip.String()
  573. }
  574. }
  575. sans[i] = san
  576. }
  577. // Create initial certificate request.
  578. cr, err := x509util.CreateCertificateRequest(a.config.CommonName, sans, signer)
  579. if err != nil {
  580. return fatal(err)
  581. }
  582. // Generate certificate template directly from the certificate request.
  583. template, err := x509util.NewCertificate(cr)
  584. if err != nil {
  585. return fatal(err)
  586. }
  587. // Get x509 certificate template, set validity and sign it.
  588. now := time.Now()
  589. certTpl := template.GetCertificate()
  590. certTpl.NotBefore = now.Add(-1 * time.Minute)
  591. certTpl.NotAfter = now.Add(24 * time.Hour)
  592. // Policy and constraints require this fields to be set. At this moment they
  593. // are only present in the extra extension.
  594. certTpl.DNSNames = cr.DNSNames
  595. certTpl.IPAddresses = cr.IPAddresses
  596. certTpl.EmailAddresses = cr.EmailAddresses
  597. certTpl.URIs = cr.URIs
  598. // Fail if name constraints do not allow the server names.
  599. if err := a.constraintsEngine.ValidateCertificate(certTpl); err != nil {
  600. return fatal(err)
  601. }
  602. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  603. Template: certTpl,
  604. CSR: cr,
  605. Lifetime: 24 * time.Hour,
  606. Backdate: 1 * time.Minute,
  607. IsCAServerCert: true,
  608. })
  609. if err != nil {
  610. return fatal(err)
  611. }
  612. // Generate PEM blocks to create tls.Certificate
  613. pemBlocks := pem.EncodeToMemory(&pem.Block{
  614. Type: "CERTIFICATE",
  615. Bytes: resp.Certificate.Raw,
  616. })
  617. for _, crt := range resp.CertificateChain {
  618. pemBlocks = append(pemBlocks, pem.EncodeToMemory(&pem.Block{
  619. Type: "CERTIFICATE",
  620. Bytes: crt.Raw,
  621. })...)
  622. }
  623. keyPEM, err := pemutil.Serialize(priv)
  624. if err != nil {
  625. return fatal(err)
  626. }
  627. tlsCrt, err := tls.X509KeyPair(pemBlocks, pem.EncodeToMemory(keyPEM))
  628. if err != nil {
  629. return fatal(err)
  630. }
  631. // Set leaf certificate
  632. tlsCrt.Leaf = resp.Certificate
  633. return &tlsCrt, nil
  634. }
  635. // templatingError tries to extract more information about the cause of
  636. // an error related to (most probably) malformed template data and adds
  637. // this to the error message.
  638. func templatingError(err error) error {
  639. cause := errors.Cause(err)
  640. var (
  641. syntaxError *json.SyntaxError
  642. typeError *json.UnmarshalTypeError
  643. )
  644. if errors.As(err, &syntaxError) {
  645. // offset is arguably not super clear to the user, but it's the best we can do here
  646. cause = fmt.Errorf("%w at offset %d", cause, syntaxError.Offset)
  647. } else if errors.As(err, &typeError) {
  648. // slightly rewriting the default error message to include the offset
  649. cause = fmt.Errorf("cannot unmarshal %s at offset %d into Go value of type %s", typeError.Value, typeError.Offset, typeError.Type)
  650. }
  651. return errors.Wrap(cause, "error applying certificate template")
  652. }
  653. func callEnrichingWebhooksX509(webhookCtl webhookController, attData *provisioner.AttestationData, csr *x509.CertificateRequest) error {
  654. if webhookCtl == nil {
  655. return nil
  656. }
  657. var attested *webhook.AttestationData
  658. if attData != nil {
  659. attested = &webhook.AttestationData{
  660. PermanentIdentifier: attData.PermanentIdentifier,
  661. }
  662. }
  663. whEnrichReq, err := webhook.NewRequestBody(
  664. webhook.WithX509CertificateRequest(csr),
  665. webhook.WithAttestationData(attested),
  666. )
  667. if err != nil {
  668. return err
  669. }
  670. if err := webhookCtl.Enrich(whEnrichReq); err != nil {
  671. return err
  672. }
  673. return nil
  674. }
  675. func callAuthorizingWebhooksX509(webhookCtl webhookController, cert *x509util.Certificate, leaf *x509.Certificate, attData *provisioner.AttestationData) error {
  676. if webhookCtl == nil {
  677. return nil
  678. }
  679. var attested *webhook.AttestationData
  680. if attData != nil {
  681. attested = &webhook.AttestationData{
  682. PermanentIdentifier: attData.PermanentIdentifier,
  683. }
  684. }
  685. whAuthBody, err := webhook.NewRequestBody(
  686. webhook.WithX509Certificate(cert, leaf),
  687. webhook.WithAttestationData(attested),
  688. )
  689. if err != nil {
  690. return err
  691. }
  692. if err := webhookCtl.Authorize(whAuthBody); err != nil {
  693. return err
  694. }
  695. return nil
  696. }