tls.go 21 KB

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