tls.go 20 KB

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