linkedca.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/hex"
  9. "encoding/pem"
  10. "fmt"
  11. "net/url"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "github.com/pkg/errors"
  16. "golang.org/x/crypto/ssh"
  17. "google.golang.org/grpc"
  18. "google.golang.org/grpc/credentials"
  19. "go.step.sm/crypto/jose"
  20. "go.step.sm/crypto/keyutil"
  21. "go.step.sm/crypto/tlsutil"
  22. "go.step.sm/crypto/x509util"
  23. "go.step.sm/linkedca"
  24. "github.com/smallstep/certificates/authority/admin"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. "github.com/smallstep/certificates/db"
  27. )
  28. const uuidPattern = "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
  29. type linkedCaClient struct {
  30. renewer *tlsutil.Renewer
  31. client linkedca.MajordomoClient
  32. authorityID string
  33. }
  34. // interface guard
  35. var _ admin.DB = (*linkedCaClient)(nil)
  36. type linkedCAClaims struct {
  37. jose.Claims
  38. SANs []string `json:"sans"`
  39. SHA string `json:"sha"`
  40. }
  41. func newLinkedCAClient(token string) (*linkedCaClient, error) {
  42. tok, err := jose.ParseSigned(token)
  43. if err != nil {
  44. return nil, errors.Wrap(err, "error parsing token")
  45. }
  46. var claims linkedCAClaims
  47. if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  48. return nil, errors.Wrap(err, "error parsing token")
  49. }
  50. // Validate claims
  51. if len(claims.Audience) != 1 {
  52. return nil, errors.New("error parsing token: invalid aud claim")
  53. }
  54. if claims.SHA == "" {
  55. return nil, errors.New("error parsing token: invalid sha claim")
  56. }
  57. // Get linkedCA endpoint from audience.
  58. u, err := url.Parse(claims.Audience[0])
  59. if err != nil {
  60. return nil, errors.New("error parsing token: invalid aud claim")
  61. }
  62. // Get authority from SANs
  63. authority, err := getAuthority(claims.SANs)
  64. if err != nil {
  65. return nil, err
  66. }
  67. // Create csr to login with
  68. signer, err := keyutil.GenerateDefaultSigner()
  69. if err != nil {
  70. return nil, err
  71. }
  72. csr, err := x509util.CreateCertificateRequest(claims.Subject, claims.SANs, signer)
  73. if err != nil {
  74. return nil, err
  75. }
  76. // Get and verify root certificate
  77. root, err := getRootCertificate(u.Host, claims.SHA)
  78. if err != nil {
  79. return nil, err
  80. }
  81. pool := x509.NewCertPool()
  82. pool.AddCert(root)
  83. // Login with majordomo and get certificates
  84. cert, tlsConfig, err := login(authority, token, csr, signer, u.Host, pool)
  85. if err != nil {
  86. return nil, err
  87. }
  88. // Start TLS renewer and set the GetClientCertificate callback to it.
  89. renewer, err := tlsutil.NewRenewer(cert, tlsConfig, func() (*tls.Certificate, *tls.Config, error) {
  90. return login(authority, token, csr, signer, u.Host, pool)
  91. })
  92. if err != nil {
  93. return nil, err
  94. }
  95. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  96. // Start mTLS client
  97. conn, err := grpc.Dial(u.Host, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
  98. if err != nil {
  99. return nil, errors.Wrapf(err, "error connecting %s", u.Host)
  100. }
  101. return &linkedCaClient{
  102. renewer: renewer,
  103. client: linkedca.NewMajordomoClient(conn),
  104. authorityID: authority,
  105. }, nil
  106. }
  107. // IsLinkedCA is a sentinel function that can be used to
  108. // check if a linkedCaClient is the underlying type of an
  109. // admin.DB interface.
  110. func (c *linkedCaClient) IsLinkedCA() bool {
  111. return true
  112. }
  113. func (c *linkedCaClient) Run() {
  114. c.renewer.Run()
  115. }
  116. func (c *linkedCaClient) Stop() {
  117. c.renewer.Stop()
  118. }
  119. func (c *linkedCaClient) CreateProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  120. resp, err := c.client.CreateProvisioner(ctx, &linkedca.CreateProvisionerRequest{
  121. Type: prov.Type,
  122. Name: prov.Name,
  123. Details: prov.Details,
  124. Claims: prov.Claims,
  125. X509Template: prov.X509Template,
  126. SshTemplate: prov.SshTemplate,
  127. })
  128. if err != nil {
  129. return errors.Wrap(err, "error creating provisioner")
  130. }
  131. prov.Id = resp.Id
  132. prov.AuthorityId = resp.AuthorityId
  133. return nil
  134. }
  135. func (c *linkedCaClient) GetProvisioner(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  136. resp, err := c.client.GetProvisioner(ctx, &linkedca.GetProvisionerRequest{
  137. Id: id,
  138. })
  139. if err != nil {
  140. return nil, errors.Wrap(err, "error getting provisioners")
  141. }
  142. return resp, nil
  143. }
  144. func (c *linkedCaClient) GetProvisioners(ctx context.Context) ([]*linkedca.Provisioner, error) {
  145. resp, err := c.GetConfiguration(ctx)
  146. if err != nil {
  147. return nil, err
  148. }
  149. return resp.Provisioners, nil
  150. }
  151. func (c *linkedCaClient) GetConfiguration(ctx context.Context) (*linkedca.ConfigurationResponse, error) {
  152. resp, err := c.client.GetConfiguration(ctx, &linkedca.ConfigurationRequest{
  153. AuthorityId: c.authorityID,
  154. })
  155. if err != nil {
  156. return nil, errors.Wrap(err, "error getting configuration")
  157. }
  158. return resp, nil
  159. }
  160. func (c *linkedCaClient) UpdateProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  161. _, err := c.client.UpdateProvisioner(ctx, &linkedca.UpdateProvisionerRequest{
  162. Id: prov.Id,
  163. Name: prov.Name,
  164. Details: prov.Details,
  165. Claims: prov.Claims,
  166. X509Template: prov.X509Template,
  167. SshTemplate: prov.SshTemplate,
  168. })
  169. return errors.Wrap(err, "error updating provisioner")
  170. }
  171. func (c *linkedCaClient) DeleteProvisioner(ctx context.Context, id string) error {
  172. _, err := c.client.DeleteProvisioner(ctx, &linkedca.DeleteProvisionerRequest{
  173. Id: id,
  174. })
  175. return errors.Wrap(err, "error deleting provisioner")
  176. }
  177. func (c *linkedCaClient) CreateAdmin(ctx context.Context, adm *linkedca.Admin) error {
  178. resp, err := c.client.CreateAdmin(ctx, &linkedca.CreateAdminRequest{
  179. Subject: adm.Subject,
  180. ProvisionerId: adm.ProvisionerId,
  181. Type: adm.Type,
  182. })
  183. if err != nil {
  184. return errors.Wrap(err, "error creating admin")
  185. }
  186. adm.Id = resp.Id
  187. adm.AuthorityId = resp.AuthorityId
  188. return nil
  189. }
  190. func (c *linkedCaClient) GetAdmin(ctx context.Context, id string) (*linkedca.Admin, error) {
  191. resp, err := c.client.GetAdmin(ctx, &linkedca.GetAdminRequest{
  192. Id: id,
  193. })
  194. if err != nil {
  195. return nil, errors.Wrap(err, "error getting admins")
  196. }
  197. return resp, nil
  198. }
  199. func (c *linkedCaClient) GetAdmins(ctx context.Context) ([]*linkedca.Admin, error) {
  200. resp, err := c.GetConfiguration(ctx)
  201. if err != nil {
  202. return nil, err
  203. }
  204. return resp.Admins, nil
  205. }
  206. func (c *linkedCaClient) UpdateAdmin(ctx context.Context, adm *linkedca.Admin) error {
  207. _, err := c.client.UpdateAdmin(ctx, &linkedca.UpdateAdminRequest{
  208. Id: adm.Id,
  209. Type: adm.Type,
  210. })
  211. return errors.Wrap(err, "error updating admin")
  212. }
  213. func (c *linkedCaClient) DeleteAdmin(ctx context.Context, id string) error {
  214. _, err := c.client.DeleteAdmin(ctx, &linkedca.DeleteAdminRequest{
  215. Id: id,
  216. })
  217. return errors.Wrap(err, "error deleting admin")
  218. }
  219. func (c *linkedCaClient) GetCertificateData(serial string) (*db.CertificateData, error) {
  220. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  221. defer cancel()
  222. resp, err := c.client.GetCertificate(ctx, &linkedca.GetCertificateRequest{
  223. Serial: serial,
  224. })
  225. if err != nil {
  226. return nil, err
  227. }
  228. var pd *db.ProvisionerData
  229. if p := resp.Provisioner; p != nil {
  230. pd = &db.ProvisionerData{
  231. ID: p.Id, Name: p.Name, Type: p.Type.String(),
  232. }
  233. }
  234. var raInfo *provisioner.RAInfo
  235. if p := resp.RaProvisioner; p != nil && p.Provisioner != nil {
  236. raInfo = &provisioner.RAInfo{
  237. AuthorityID: p.AuthorityId,
  238. ProvisionerID: p.Provisioner.Id,
  239. ProvisionerType: p.Provisioner.Type.String(),
  240. ProvisionerName: p.Provisioner.Name,
  241. }
  242. }
  243. return &db.CertificateData{
  244. Provisioner: pd,
  245. RaInfo: raInfo,
  246. }, nil
  247. }
  248. func (c *linkedCaClient) StoreCertificateChain(p provisioner.Interface, fullchain ...*x509.Certificate) error {
  249. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  250. defer cancel()
  251. raProvisioner, endpointID := createRegistrationAuthorityProvisioner(p)
  252. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  253. PemCertificate: serializeCertificateChain(fullchain[0]),
  254. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  255. Provisioner: createProvisionerIdentity(p),
  256. AttestationData: createAttestationData(p),
  257. RaProvisioner: raProvisioner,
  258. EndpointId: endpointID,
  259. })
  260. return errors.Wrap(err, "error posting certificate")
  261. }
  262. func (c *linkedCaClient) StoreRenewedCertificate(parent *x509.Certificate, fullchain ...*x509.Certificate) error {
  263. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  264. defer cancel()
  265. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  266. PemCertificate: serializeCertificateChain(fullchain[0]),
  267. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  268. PemParentCertificate: serializeCertificateChain(parent),
  269. })
  270. return errors.Wrap(err, "error posting renewed certificate")
  271. }
  272. func (c *linkedCaClient) StoreSSHCertificate(p provisioner.Interface, crt *ssh.Certificate) error {
  273. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  274. defer cancel()
  275. _, err := c.client.PostSSHCertificate(ctx, &linkedca.SSHCertificateRequest{
  276. Certificate: string(ssh.MarshalAuthorizedKey(crt)),
  277. Provisioner: createProvisionerIdentity(p),
  278. })
  279. return errors.Wrap(err, "error posting ssh certificate")
  280. }
  281. func (c *linkedCaClient) StoreRenewedSSHCertificate(p provisioner.Interface, parent, crt *ssh.Certificate) error {
  282. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  283. defer cancel()
  284. _, err := c.client.PostSSHCertificate(ctx, &linkedca.SSHCertificateRequest{
  285. Certificate: string(ssh.MarshalAuthorizedKey(crt)),
  286. ParentCertificate: string(ssh.MarshalAuthorizedKey(parent)),
  287. Provisioner: createProvisionerIdentity(p),
  288. })
  289. return errors.Wrap(err, "error posting renewed ssh certificate")
  290. }
  291. func (c *linkedCaClient) Revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  292. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  293. defer cancel()
  294. _, err := c.client.RevokeCertificate(ctx, &linkedca.RevokeCertificateRequest{
  295. Serial: rci.Serial,
  296. PemCertificate: serializeCertificate(crt),
  297. Reason: rci.Reason,
  298. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  299. Passive: true,
  300. })
  301. return errors.Wrap(err, "error revoking certificate")
  302. }
  303. func (c *linkedCaClient) RevokeSSH(cert *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  304. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  305. defer cancel()
  306. _, err := c.client.RevokeSSHCertificate(ctx, &linkedca.RevokeSSHCertificateRequest{
  307. Serial: rci.Serial,
  308. Certificate: serializeSSHCertificate(cert),
  309. Reason: rci.Reason,
  310. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  311. Passive: true,
  312. })
  313. return errors.Wrap(err, "error revoking ssh certificate")
  314. }
  315. func (c *linkedCaClient) IsRevoked(serial string) (bool, error) {
  316. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  317. defer cancel()
  318. resp, err := c.client.GetCertificateStatus(ctx, &linkedca.GetCertificateStatusRequest{
  319. Serial: serial,
  320. })
  321. if err != nil {
  322. return false, errors.Wrap(err, "error getting certificate status")
  323. }
  324. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  325. }
  326. func (c *linkedCaClient) IsSSHRevoked(serial string) (bool, error) {
  327. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  328. defer cancel()
  329. resp, err := c.client.GetSSHCertificateStatus(ctx, &linkedca.GetSSHCertificateStatusRequest{
  330. Serial: serial,
  331. })
  332. if err != nil {
  333. return false, errors.Wrap(err, "error getting certificate status")
  334. }
  335. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  336. }
  337. func (c *linkedCaClient) CreateAuthorityPolicy(_ context.Context, _ *linkedca.Policy) error {
  338. return errors.New("not implemented yet")
  339. }
  340. func (c *linkedCaClient) GetAuthorityPolicy(context.Context) (*linkedca.Policy, error) {
  341. return nil, errors.New("not implemented yet")
  342. }
  343. func (c *linkedCaClient) UpdateAuthorityPolicy(_ context.Context, _ *linkedca.Policy) error {
  344. return errors.New("not implemented yet")
  345. }
  346. func (c *linkedCaClient) DeleteAuthorityPolicy(context.Context) error {
  347. return errors.New("not implemented yet")
  348. }
  349. func createProvisionerIdentity(p provisioner.Interface) *linkedca.ProvisionerIdentity {
  350. if p == nil {
  351. return nil
  352. }
  353. return &linkedca.ProvisionerIdentity{
  354. Id: p.GetID(),
  355. Type: linkedca.Provisioner_Type(p.GetType()),
  356. Name: p.GetName(),
  357. }
  358. }
  359. func createRegistrationAuthorityProvisioner(p provisioner.Interface) (*linkedca.RegistrationAuthorityProvisioner, string) {
  360. if rap, ok := p.(raProvisioner); ok {
  361. if info := rap.RAInfo(); info != nil {
  362. typ := linkedca.Provisioner_Type_value[strings.ToUpper(info.ProvisionerType)]
  363. return &linkedca.RegistrationAuthorityProvisioner{
  364. AuthorityId: info.AuthorityID,
  365. Provisioner: &linkedca.ProvisionerIdentity{
  366. Id: info.ProvisionerID,
  367. Type: linkedca.Provisioner_Type(typ),
  368. Name: info.ProvisionerName,
  369. },
  370. }, info.EndpointID
  371. }
  372. }
  373. return nil, ""
  374. }
  375. func createAttestationData(p provisioner.Interface) *linkedca.AttestationData {
  376. if ap, ok := p.(attProvisioner); ok {
  377. if data := ap.AttestationData(); data != nil {
  378. return &linkedca.AttestationData{
  379. PermanentIdentifier: data.PermanentIdentifier,
  380. }
  381. }
  382. }
  383. return nil
  384. }
  385. func serializeCertificate(crt *x509.Certificate) string {
  386. if crt == nil {
  387. return ""
  388. }
  389. return string(pem.EncodeToMemory(&pem.Block{
  390. Type: "CERTIFICATE",
  391. Bytes: crt.Raw,
  392. }))
  393. }
  394. func serializeCertificateChain(fullchain ...*x509.Certificate) string {
  395. var chain string
  396. for _, crt := range fullchain {
  397. chain += string(pem.EncodeToMemory(&pem.Block{
  398. Type: "CERTIFICATE",
  399. Bytes: crt.Raw,
  400. }))
  401. }
  402. return chain
  403. }
  404. func serializeSSHCertificate(crt *ssh.Certificate) string {
  405. if crt == nil {
  406. return ""
  407. }
  408. return string(ssh.MarshalAuthorizedKey(crt))
  409. }
  410. func getAuthority(sans []string) (string, error) {
  411. for _, s := range sans {
  412. if strings.HasPrefix(s, "urn:smallstep:authority:") {
  413. if regexp.MustCompile(uuidPattern).MatchString(s[24:]) {
  414. return s[24:], nil
  415. }
  416. }
  417. }
  418. return "", fmt.Errorf("error parsing token: invalid sans claim")
  419. }
  420. // getRootCertificate creates an insecure majordomo client and returns the
  421. // verified root certificate.
  422. func getRootCertificate(endpoint, fingerprint string) (*x509.Certificate, error) {
  423. ctx, cancel := context.WithCancel(context.Background())
  424. defer cancel()
  425. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  426. //nolint:gosec // used in bootstrap protocol
  427. InsecureSkipVerify: true, // lgtm[go/disabled-certificate-check]
  428. })))
  429. if err != nil {
  430. return nil, errors.Wrapf(err, "error connecting %s", endpoint)
  431. }
  432. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  433. defer cancel()
  434. client := linkedca.NewMajordomoClient(conn)
  435. resp, err := client.GetRootCertificate(ctx, &linkedca.GetRootCertificateRequest{
  436. Fingerprint: fingerprint,
  437. })
  438. if err != nil {
  439. return nil, fmt.Errorf("error getting root certificate: %w", err)
  440. }
  441. var block *pem.Block
  442. b := []byte(resp.PemCertificate)
  443. for len(b) > 0 {
  444. block, b = pem.Decode(b)
  445. if block == nil {
  446. break
  447. }
  448. if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
  449. continue
  450. }
  451. cert, err := x509.ParseCertificate(block.Bytes)
  452. if err != nil {
  453. return nil, fmt.Errorf("error parsing certificate: %w", err)
  454. }
  455. // verify the sha256
  456. sum := sha256.Sum256(cert.Raw)
  457. if !strings.EqualFold(fingerprint, hex.EncodeToString(sum[:])) {
  458. return nil, fmt.Errorf("error verifying certificate: SHA256 fingerprint does not match")
  459. }
  460. return cert, nil
  461. }
  462. return nil, fmt.Errorf("error getting root certificate: certificate not found")
  463. }
  464. // login creates a new majordomo client with just the root ca pool and returns
  465. // the signed certificate and tls configuration.
  466. func login(authority, token string, csr *x509.CertificateRequest, signer crypto.PrivateKey, endpoint string, rootCAs *x509.CertPool) (*tls.Certificate, *tls.Config, error) {
  467. // Connect to majordomo
  468. ctx, cancel := context.WithCancel(context.Background())
  469. defer cancel()
  470. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  471. MinVersion: tls.VersionTLS12,
  472. RootCAs: rootCAs,
  473. })))
  474. if err != nil {
  475. return nil, nil, errors.Wrapf(err, "error connecting %s", endpoint)
  476. }
  477. // Login to get the signed certificate
  478. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  479. defer cancel()
  480. client := linkedca.NewMajordomoClient(conn)
  481. resp, err := client.Login(ctx, &linkedca.LoginRequest{
  482. AuthorityId: authority,
  483. Token: token,
  484. PemCertificateRequest: string(pem.EncodeToMemory(&pem.Block{
  485. Type: "CERTIFICATE REQUEST",
  486. Bytes: csr.Raw,
  487. })),
  488. })
  489. if err != nil {
  490. return nil, nil, errors.Wrapf(err, "error logging in %s", endpoint)
  491. }
  492. // Parse login response
  493. var block *pem.Block
  494. var bundle []*x509.Certificate
  495. rest := []byte(resp.PemCertificateChain)
  496. for {
  497. block, rest = pem.Decode(rest)
  498. if block == nil {
  499. break
  500. }
  501. if block.Type != "CERTIFICATE" {
  502. return nil, nil, errors.New("error decoding login response: pemCertificateChain is not a certificate bundle")
  503. }
  504. crt, err := x509.ParseCertificate(block.Bytes)
  505. if err != nil {
  506. return nil, nil, errors.Wrap(err, "error parsing login response")
  507. }
  508. bundle = append(bundle, crt)
  509. }
  510. if len(bundle) == 0 {
  511. return nil, nil, errors.New("error decoding login response: pemCertificateChain should not be empty")
  512. }
  513. // Build tls.Certificate with PemCertificate and intermediates in the
  514. // PemCertificateChain
  515. cert := &tls.Certificate{
  516. PrivateKey: signer,
  517. }
  518. rest = []byte(resp.PemCertificate)
  519. for {
  520. block, rest = pem.Decode(rest)
  521. if block == nil {
  522. break
  523. }
  524. if block.Type == "CERTIFICATE" {
  525. leaf, err := x509.ParseCertificate(block.Bytes)
  526. if err != nil {
  527. return nil, nil, errors.Wrap(err, "error parsing pemCertificate")
  528. }
  529. cert.Certificate = append(cert.Certificate, block.Bytes)
  530. cert.Leaf = leaf
  531. }
  532. }
  533. // Add intermediates to the tls.Certificate
  534. last := len(bundle) - 1
  535. for i := 0; i < last; i++ {
  536. cert.Certificate = append(cert.Certificate, bundle[i].Raw)
  537. }
  538. // Add root to the pool if it's not there yet
  539. rootCAs.AddCert(bundle[last])
  540. return cert, &tls.Config{
  541. MinVersion: tls.VersionTLS12,
  542. RootCAs: rootCAs,
  543. }, nil
  544. }