tls.go 20 KB

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