tls.go 22 KB

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