tls.go 22 KB

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