tls.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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/policy"
  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. for _, op := range extraOpts {
  88. switch k := op.(type) {
  89. // Capture current provisioner
  90. case provisioner.Interface:
  91. prov = k
  92. pInfo = &casapi.ProvisionerInfo{
  93. ID: prov.GetID(),
  94. Type: prov.GetType().String(),
  95. Name: prov.GetName(),
  96. }
  97. // Adds new options to NewCertificate
  98. case provisioner.CertificateOptions:
  99. certOptions = append(certOptions, k.Options(signOpts)...)
  100. // Validate the given certificate request.
  101. case provisioner.CertificateRequestValidator:
  102. if err := k.Valid(csr); err != nil {
  103. return nil, errs.ApplyOptions(
  104. errs.ForbiddenErr(err, "error validating certificate"),
  105. opts...,
  106. )
  107. }
  108. // Validates the unsigned certificate template.
  109. case provisioner.CertificateValidator:
  110. certValidators = append(certValidators, k)
  111. // Modifies a certificate before validating it.
  112. case provisioner.CertificateModifier:
  113. certModifiers = append(certModifiers, k)
  114. // Modifies a certificate after validating it.
  115. case provisioner.CertificateEnforcer:
  116. certEnforcers = append(certEnforcers, k)
  117. // Extra information from ACME attestations.
  118. case provisioner.AttestationData:
  119. attData = k
  120. // TODO(mariano,areed): remove me once attData is used.
  121. _ = attData
  122. default:
  123. return nil, errs.InternalServer("authority.Sign; invalid extra option type %T", append([]interface{}{k}, opts...)...)
  124. }
  125. }
  126. cert, err := x509util.NewCertificate(csr, certOptions...)
  127. if err != nil {
  128. var te *x509util.TemplateError
  129. if errors.As(err, &te) {
  130. return nil, errs.ApplyOptions(
  131. errs.BadRequestErr(err, err.Error()),
  132. errs.WithKeyVal("csr", csr),
  133. errs.WithKeyVal("signOptions", signOpts),
  134. )
  135. }
  136. // explicitly check for unmarshaling errors, which are most probably caused by JSON template (syntax) errors
  137. if strings.HasPrefix(err.Error(), "error unmarshaling certificate") {
  138. return nil, errs.InternalServerErr(templatingError(err),
  139. errs.WithKeyVal("csr", csr),
  140. errs.WithKeyVal("signOptions", signOpts),
  141. errs.WithMessage("error applying certificate template"),
  142. )
  143. }
  144. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign", opts...)
  145. }
  146. // Certificate modifiers before validation
  147. leaf := cert.GetCertificate()
  148. // Set default subject
  149. if err := withDefaultASN1DN(a.config.AuthorityConfig.Template).Modify(leaf, signOpts); err != nil {
  150. return nil, errs.ApplyOptions(
  151. errs.ForbiddenErr(err, "error creating certificate"),
  152. opts...,
  153. )
  154. }
  155. for _, m := range certModifiers {
  156. if err := m.Modify(leaf, signOpts); err != nil {
  157. return nil, errs.ApplyOptions(
  158. errs.ForbiddenErr(err, "error creating certificate"),
  159. opts...,
  160. )
  161. }
  162. }
  163. // Certificate validation.
  164. for _, v := range certValidators {
  165. if err := v.Valid(leaf, signOpts); err != nil {
  166. return nil, errs.ApplyOptions(
  167. errs.ForbiddenErr(err, "error validating certificate"),
  168. opts...,
  169. )
  170. }
  171. }
  172. // Certificate modifiers after validation
  173. for _, m := range certEnforcers {
  174. if err := m.Enforce(leaf); err != nil {
  175. return nil, errs.ApplyOptions(
  176. errs.ForbiddenErr(err, "error creating certificate"),
  177. opts...,
  178. )
  179. }
  180. }
  181. // Process injected modifiers after validation
  182. for _, m := range a.x509Enforcers {
  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. // Check if authority is allowed to sign the certificate
  191. if err := a.isAllowedToSignX509Certificate(leaf); err != nil {
  192. var pe *policy.NamePolicyError
  193. if errors.As(err, &pe) && pe.Reason == policy.NotAllowed {
  194. return nil, errs.ApplyOptions(&errs.Error{
  195. // NOTE: custom forbidden error, so that denied name is sent to client
  196. // as well as shown in the logs.
  197. Status: http.StatusForbidden,
  198. Err: fmt.Errorf("authority not allowed to sign: %w", err),
  199. Msg: fmt.Sprintf("The request was forbidden by the certificate authority: %s", err.Error()),
  200. }, opts...)
  201. }
  202. return nil, errs.InternalServerErr(err,
  203. errs.WithKeyVal("csr", csr),
  204. errs.WithKeyVal("signOptions", signOpts),
  205. errs.WithMessage("error creating certificate"),
  206. )
  207. }
  208. // Sign certificate
  209. lifetime := leaf.NotAfter.Sub(leaf.NotBefore.Add(signOpts.Backdate))
  210. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  211. Template: leaf,
  212. CSR: csr,
  213. Lifetime: lifetime,
  214. Backdate: signOpts.Backdate,
  215. Provisioner: pInfo,
  216. })
  217. if err != nil {
  218. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error creating certificate", opts...)
  219. }
  220. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  221. if err = a.storeCertificate(prov, fullchain); err != nil {
  222. if !errors.Is(err, db.ErrNotImplemented) {
  223. return nil, errs.Wrap(http.StatusInternalServerError, err,
  224. "authority.Sign; error storing certificate in db", opts...)
  225. }
  226. }
  227. return fullchain, nil
  228. }
  229. // isAllowedToSignX509Certificate checks if the Authority is allowed
  230. // to sign the X.509 certificate.
  231. func (a *Authority) isAllowedToSignX509Certificate(cert *x509.Certificate) error {
  232. return a.policyEngine.IsX509CertificateAllowed(cert)
  233. }
  234. // AreSANsAllowed evaluates the provided sans against the
  235. // authority X.509 policy.
  236. func (a *Authority) AreSANsAllowed(ctx context.Context, sans []string) error {
  237. return a.policyEngine.AreSANsAllowed(sans)
  238. }
  239. // Renew creates a new Certificate identical to the old certificate, except
  240. // with a validity window that begins 'now'.
  241. func (a *Authority) Renew(oldCert *x509.Certificate) ([]*x509.Certificate, error) {
  242. return a.Rekey(oldCert, nil)
  243. }
  244. // Rekey is used for rekeying and renewing based on the public key.
  245. // If the public key is 'nil' then it's assumed that the cert should be renewed
  246. // using the existing public key. If the public key is not 'nil' then it's
  247. // assumed that the cert should be rekeyed.
  248. // For both Rekey and Renew all other attributes of the new certificate should
  249. // match the old certificate. The exceptions are 'AuthorityKeyId' (which may
  250. // have changed), 'SubjectKeyId' (different in case of rekey), and
  251. // 'NotBefore/NotAfter' (the validity duration of the new certificate should be
  252. // equal to the old one, but starting 'now').
  253. func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error) {
  254. isRekey := (pk != nil)
  255. opts := []interface{}{errs.WithKeyVal("serialNumber", oldCert.SerialNumber.String())}
  256. // Check step provisioner extensions
  257. if err := a.authorizeRenew(oldCert); err != nil {
  258. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  259. }
  260. // Durations
  261. backdate := a.config.AuthorityConfig.Backdate.Duration
  262. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  263. lifetime := duration - backdate
  264. // Create new certificate from previous values.
  265. // Issuer, NotBefore, NotAfter and SubjectKeyId will be set by the CAS.
  266. newCert := &x509.Certificate{
  267. Subject: oldCert.Subject,
  268. KeyUsage: oldCert.KeyUsage,
  269. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  270. ExtKeyUsage: oldCert.ExtKeyUsage,
  271. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  272. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  273. IsCA: oldCert.IsCA,
  274. MaxPathLen: oldCert.MaxPathLen,
  275. MaxPathLenZero: oldCert.MaxPathLenZero,
  276. OCSPServer: oldCert.OCSPServer,
  277. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  278. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  279. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  280. DNSNames: oldCert.DNSNames,
  281. EmailAddresses: oldCert.EmailAddresses,
  282. IPAddresses: oldCert.IPAddresses,
  283. URIs: oldCert.URIs,
  284. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  285. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  286. PermittedIPRanges: oldCert.PermittedIPRanges,
  287. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  288. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  289. PermittedURIDomains: oldCert.PermittedURIDomains,
  290. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  291. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  292. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  293. }
  294. if isRekey {
  295. newCert.PublicKey = pk
  296. } else {
  297. newCert.PublicKey = oldCert.PublicKey
  298. }
  299. // Copy all extensions except:
  300. //
  301. // 1. Authority Key Identifier - This one might be different if we rotate
  302. // the intermediate certificate and it will cause a TLS bad certificate
  303. // error.
  304. //
  305. // 2. Subject Key Identifier, if rekey - For rekey, SubjectKeyIdentifier
  306. // extension will be calculated for the new public key by
  307. // x509util.CreateCertificate()
  308. for _, ext := range oldCert.Extensions {
  309. if ext.Id.Equal(oidAuthorityKeyIdentifier) {
  310. continue
  311. }
  312. if ext.Id.Equal(oidSubjectKeyIdentifier) && isRekey {
  313. newCert.SubjectKeyId = nil
  314. continue
  315. }
  316. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  317. }
  318. resp, err := a.x509CAService.RenewCertificate(&casapi.RenewCertificateRequest{
  319. Template: newCert,
  320. Lifetime: lifetime,
  321. Backdate: backdate,
  322. })
  323. if err != nil {
  324. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey", opts...)
  325. }
  326. fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...)
  327. if err = a.storeRenewedCertificate(oldCert, fullchain); err != nil {
  328. if !errors.Is(err, db.ErrNotImplemented) {
  329. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey; error storing certificate in db", opts...)
  330. }
  331. }
  332. return fullchain, nil
  333. }
  334. // storeCertificate allows to use an extension of the db.AuthDB interface that
  335. // can log the full chain of certificates.
  336. //
  337. // TODO: at some point we should replace the db.AuthDB interface to implement
  338. // `StoreCertificate(...*x509.Certificate) error` instead of just
  339. // `StoreCertificate(*x509.Certificate) error`.
  340. func (a *Authority) storeCertificate(prov provisioner.Interface, fullchain []*x509.Certificate) error {
  341. type certificateChainStorer interface {
  342. StoreCertificateChain(provisioner.Interface, ...*x509.Certificate) error
  343. }
  344. type certificateChainSimpleStorer interface {
  345. StoreCertificateChain(...*x509.Certificate) error
  346. }
  347. // Store certificate in linkedca
  348. switch s := a.adminDB.(type) {
  349. case certificateChainStorer:
  350. return s.StoreCertificateChain(prov, fullchain...)
  351. case certificateChainSimpleStorer:
  352. return s.StoreCertificateChain(fullchain...)
  353. }
  354. // Store certificate in local db
  355. switch s := a.db.(type) {
  356. case certificateChainStorer:
  357. return s.StoreCertificateChain(prov, fullchain...)
  358. case certificateChainSimpleStorer:
  359. return s.StoreCertificateChain(fullchain...)
  360. case db.CertificateStorer:
  361. return s.StoreCertificate(fullchain[0])
  362. default:
  363. return nil
  364. }
  365. }
  366. // storeRenewedCertificate allows to use an extension of the db.AuthDB interface
  367. // that can log if a certificate has been renewed or rekeyed.
  368. //
  369. // TODO: at some point we should implement this in the standard implementation.
  370. func (a *Authority) storeRenewedCertificate(oldCert *x509.Certificate, fullchain []*x509.Certificate) error {
  371. type renewedCertificateChainStorer interface {
  372. StoreRenewedCertificate(*x509.Certificate, ...*x509.Certificate) error
  373. }
  374. // Store certificate in linkedca
  375. if s, ok := a.adminDB.(renewedCertificateChainStorer); ok {
  376. return s.StoreRenewedCertificate(oldCert, fullchain...)
  377. }
  378. // Store certificate in local db
  379. switch s := a.db.(type) {
  380. case renewedCertificateChainStorer:
  381. return s.StoreRenewedCertificate(oldCert, fullchain...)
  382. case db.CertificateStorer:
  383. return s.StoreCertificate(fullchain[0])
  384. default:
  385. return nil
  386. }
  387. }
  388. // RevokeOptions are the options for the Revoke API.
  389. type RevokeOptions struct {
  390. Serial string
  391. Reason string
  392. ReasonCode int
  393. PassiveOnly bool
  394. MTLS bool
  395. ACME bool
  396. Crt *x509.Certificate
  397. OTT string
  398. }
  399. // Revoke revokes a certificate.
  400. //
  401. // NOTE: Only supports passive revocation - prevent existing certificates from
  402. // being renewed.
  403. //
  404. // TODO: Add OCSP and CRL support.
  405. func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error {
  406. opts := []interface{}{
  407. errs.WithKeyVal("serialNumber", revokeOpts.Serial),
  408. errs.WithKeyVal("reasonCode", revokeOpts.ReasonCode),
  409. errs.WithKeyVal("reason", revokeOpts.Reason),
  410. errs.WithKeyVal("passiveOnly", revokeOpts.PassiveOnly),
  411. errs.WithKeyVal("MTLS", revokeOpts.MTLS),
  412. errs.WithKeyVal("ACME", revokeOpts.ACME),
  413. errs.WithKeyVal("context", provisioner.MethodFromContext(ctx).String()),
  414. }
  415. if revokeOpts.MTLS || revokeOpts.ACME {
  416. opts = append(opts, errs.WithKeyVal("certificate", base64.StdEncoding.EncodeToString(revokeOpts.Crt.Raw)))
  417. } else {
  418. opts = append(opts, errs.WithKeyVal("token", revokeOpts.OTT))
  419. }
  420. rci := &db.RevokedCertificateInfo{
  421. Serial: revokeOpts.Serial,
  422. ReasonCode: revokeOpts.ReasonCode,
  423. Reason: revokeOpts.Reason,
  424. MTLS: revokeOpts.MTLS,
  425. ACME: revokeOpts.ACME,
  426. RevokedAt: time.Now().UTC(),
  427. }
  428. var (
  429. p provisioner.Interface
  430. err error
  431. )
  432. // If not mTLS nor ACME, then get the TokenID of the token.
  433. if !(revokeOpts.MTLS || revokeOpts.ACME) {
  434. token, err := jose.ParseSigned(revokeOpts.OTT)
  435. if err != nil {
  436. return errs.Wrap(http.StatusUnauthorized, err,
  437. "authority.Revoke; error parsing token", opts...)
  438. }
  439. // Get claims w/out verification.
  440. var claims Claims
  441. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  442. return errs.Wrap(http.StatusUnauthorized, err, "authority.Revoke", opts...)
  443. }
  444. // This method will also validate the audiences for JWK provisioners.
  445. p, err = a.LoadProvisionerByToken(token, &claims.Claims)
  446. if err != nil {
  447. return err
  448. }
  449. rci.ProvisionerID = p.GetID()
  450. rci.TokenID, err = p.GetTokenID(revokeOpts.OTT)
  451. if err != nil && !errors.Is(err, provisioner.ErrAllowTokenReuse) {
  452. return errs.Wrap(http.StatusInternalServerError, err,
  453. "authority.Revoke; could not get ID for token")
  454. }
  455. opts = append(opts,
  456. errs.WithKeyVal("provisionerID", rci.ProvisionerID),
  457. errs.WithKeyVal("tokenID", rci.TokenID),
  458. )
  459. } else if p, err = a.LoadProvisionerByCertificate(revokeOpts.Crt); err == nil {
  460. // Load the Certificate provisioner if one exists.
  461. rci.ProvisionerID = p.GetID()
  462. opts = append(opts, errs.WithKeyVal("provisionerID", rci.ProvisionerID))
  463. }
  464. if provisioner.MethodFromContext(ctx) == provisioner.SSHRevokeMethod {
  465. err = a.revokeSSH(nil, rci)
  466. } else {
  467. // Revoke an X.509 certificate using CAS. If the certificate is not
  468. // provided we will try to read it from the db. If the read fails we
  469. // won't throw an error as it will be responsibility of the CAS
  470. // implementation to require a certificate.
  471. var revokedCert *x509.Certificate
  472. if revokeOpts.Crt != nil {
  473. revokedCert = revokeOpts.Crt
  474. } else if rci.Serial != "" {
  475. revokedCert, _ = a.db.GetCertificate(rci.Serial)
  476. }
  477. // CAS operation, note that SoftCAS (default) is a noop.
  478. // The revoke happens when this is stored in the db.
  479. _, err = a.x509CAService.RevokeCertificate(&casapi.RevokeCertificateRequest{
  480. Certificate: revokedCert,
  481. SerialNumber: rci.Serial,
  482. Reason: rci.Reason,
  483. ReasonCode: rci.ReasonCode,
  484. PassiveOnly: revokeOpts.PassiveOnly,
  485. })
  486. if err != nil {
  487. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  488. }
  489. // Save as revoked in the Db.
  490. err = a.revoke(revokedCert, rci)
  491. }
  492. switch {
  493. case err == nil:
  494. return nil
  495. case errors.Is(err, db.ErrNotImplemented):
  496. return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...)
  497. case errors.Is(err, db.ErrAlreadyExists):
  498. return errs.ApplyOptions(
  499. errs.BadRequest("certificate with serial number '%s' is already revoked", rci.Serial),
  500. opts...,
  501. )
  502. default:
  503. return errs.Wrap(http.StatusInternalServerError, err, "authority.Revoke", opts...)
  504. }
  505. }
  506. func (a *Authority) revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  507. if lca, ok := a.adminDB.(interface {
  508. Revoke(*x509.Certificate, *db.RevokedCertificateInfo) error
  509. }); ok {
  510. return lca.Revoke(crt, rci)
  511. }
  512. return a.db.Revoke(rci)
  513. }
  514. func (a *Authority) revokeSSH(crt *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  515. if lca, ok := a.adminDB.(interface {
  516. RevokeSSH(*ssh.Certificate, *db.RevokedCertificateInfo) error
  517. }); ok {
  518. return lca.RevokeSSH(crt, rci)
  519. }
  520. return a.db.RevokeSSH(rci)
  521. }
  522. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  523. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  524. fatal := func(err error) (*tls.Certificate, error) {
  525. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.GetTLSCertificate")
  526. }
  527. // Generate default key.
  528. priv, err := keyutil.GenerateDefaultKey()
  529. if err != nil {
  530. return fatal(err)
  531. }
  532. signer, ok := priv.(crypto.Signer)
  533. if !ok {
  534. return fatal(errors.New("private key is not a crypto.Signer"))
  535. }
  536. // prepare the sans: IPv6 DNS hostname representations are converted to their IP representation
  537. sans := make([]string, len(a.config.DNSNames))
  538. for i, san := range a.config.DNSNames {
  539. if strings.HasPrefix(san, "[") && strings.HasSuffix(san, "]") {
  540. if ip := net.ParseIP(san[1 : len(san)-1]); ip != nil {
  541. san = ip.String()
  542. }
  543. }
  544. sans[i] = san
  545. }
  546. // Create initial certificate request.
  547. cr, err := x509util.CreateCertificateRequest(a.config.CommonName, sans, signer)
  548. if err != nil {
  549. return fatal(err)
  550. }
  551. // Generate certificate template directly from the certificate request.
  552. template, err := x509util.NewCertificate(cr)
  553. if err != nil {
  554. return fatal(err)
  555. }
  556. // Get x509 certificate template, set validity and sign it.
  557. now := time.Now()
  558. certTpl := template.GetCertificate()
  559. certTpl.NotBefore = now.Add(-1 * time.Minute)
  560. certTpl.NotAfter = now.Add(24 * time.Hour)
  561. resp, err := a.x509CAService.CreateCertificate(&casapi.CreateCertificateRequest{
  562. Template: certTpl,
  563. CSR: cr,
  564. Lifetime: 24 * time.Hour,
  565. Backdate: 1 * time.Minute,
  566. IsCAServerCert: true,
  567. })
  568. if err != nil {
  569. return fatal(err)
  570. }
  571. // Generate PEM blocks to create tls.Certificate
  572. pemBlocks := pem.EncodeToMemory(&pem.Block{
  573. Type: "CERTIFICATE",
  574. Bytes: resp.Certificate.Raw,
  575. })
  576. for _, crt := range resp.CertificateChain {
  577. pemBlocks = append(pemBlocks, pem.EncodeToMemory(&pem.Block{
  578. Type: "CERTIFICATE",
  579. Bytes: crt.Raw,
  580. })...)
  581. }
  582. keyPEM, err := pemutil.Serialize(priv)
  583. if err != nil {
  584. return fatal(err)
  585. }
  586. tlsCrt, err := tls.X509KeyPair(pemBlocks, pem.EncodeToMemory(keyPEM))
  587. if err != nil {
  588. return fatal(err)
  589. }
  590. // Set leaf certificate
  591. tlsCrt.Leaf = resp.Certificate
  592. return &tlsCrt, nil
  593. }
  594. // templatingError tries to extract more information about the cause of
  595. // an error related to (most probably) malformed template data and adds
  596. // this to the error message.
  597. func templatingError(err error) error {
  598. cause := errors.Cause(err)
  599. var (
  600. syntaxError *json.SyntaxError
  601. typeError *json.UnmarshalTypeError
  602. )
  603. if errors.As(err, &syntaxError) {
  604. // offset is arguably not super clear to the user, but it's the best we can do here
  605. cause = fmt.Errorf("%w at offset %d", cause, syntaxError.Offset)
  606. } else if errors.As(err, &typeError) {
  607. // slightly rewriting the default error message to include the offset
  608. cause = fmt.Errorf("cannot unmarshal %s at offset %d into Go value of type %s", typeError.Value, typeError.Offset, typeError.Type)
  609. }
  610. return errors.Wrap(cause, "error applying certificate template")
  611. }