cloudcas.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. package cloudcas
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/x509"
  6. "encoding/asn1"
  7. "encoding/pem"
  8. "regexp"
  9. "strings"
  10. "time"
  11. privateca "cloud.google.com/go/security/privateca/apiv1beta1"
  12. "github.com/google/uuid"
  13. gax "github.com/googleapis/gax-go/v2"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/certificates/cas/apiv1"
  16. "go.step.sm/crypto/x509util"
  17. "google.golang.org/api/option"
  18. pb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1"
  19. durationpb "google.golang.org/protobuf/types/known/durationpb"
  20. )
  21. func init() {
  22. apiv1.Register(apiv1.CloudCAS, func(ctx context.Context, opts apiv1.Options) (apiv1.CertificateAuthorityService, error) {
  23. return New(ctx, opts)
  24. })
  25. }
  26. var now = func() time.Time {
  27. return time.Now()
  28. }
  29. // The actual regular expression that matches a certificate authority is:
  30. // ^projects/[a-z][a-z0-9-]{4,28}[a-z0-9]/locations/[a-z0-9-]+/certificateAuthorities/[a-zA-Z0-9-_]+$
  31. // But we will allow a more flexible one to fail if this changes.
  32. var caRegexp = regexp.MustCompile("^projects/[^/]+/locations/[^/]+/certificateAuthorities/[^/]+$")
  33. // CertificateAuthorityClient is the interface implemented by the Google CAS
  34. // client.
  35. type CertificateAuthorityClient interface {
  36. CreateCertificate(ctx context.Context, req *pb.CreateCertificateRequest, opts ...gax.CallOption) (*pb.Certificate, error)
  37. RevokeCertificate(ctx context.Context, req *pb.RevokeCertificateRequest, opts ...gax.CallOption) (*pb.Certificate, error)
  38. GetCertificateAuthority(ctx context.Context, req *pb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*pb.CertificateAuthority, error)
  39. CreateCertificateAuthority(ctx context.Context, req *pb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*privateca.CreateCertificateAuthorityOperation, error)
  40. FetchCertificateAuthorityCsr(ctx context.Context, req *pb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*pb.FetchCertificateAuthorityCsrResponse, error)
  41. ActivateCertificateAuthority(ctx context.Context, req *pb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*privateca.ActivateCertificateAuthorityOperation, error)
  42. }
  43. // recocationCodeMap maps revocation reason codes from RFC 5280, to Google CAS
  44. // revocation reasons. Revocation reason 7 is not used, and revocation reason 8
  45. // (removeFromCRL) is not supported by Google CAS.
  46. var revocationCodeMap = map[int]pb.RevocationReason{
  47. 0: pb.RevocationReason_REVOCATION_REASON_UNSPECIFIED,
  48. 1: pb.RevocationReason_KEY_COMPROMISE,
  49. 2: pb.RevocationReason_CERTIFICATE_AUTHORITY_COMPROMISE,
  50. 3: pb.RevocationReason_AFFILIATION_CHANGED,
  51. 4: pb.RevocationReason_SUPERSEDED,
  52. 5: pb.RevocationReason_CESSATION_OF_OPERATION,
  53. 6: pb.RevocationReason_CERTIFICATE_HOLD,
  54. 9: pb.RevocationReason_PRIVILEGE_WITHDRAWN,
  55. 10: pb.RevocationReason_ATTRIBUTE_AUTHORITY_COMPROMISE,
  56. }
  57. // CloudCAS implements a Certificate Authority Service using Google Cloud CAS.
  58. type CloudCAS struct {
  59. client CertificateAuthorityClient
  60. certificateAuthority string
  61. project string
  62. location string
  63. }
  64. // newCertificateAuthorityClient creates the certificate authority client. This
  65. // function is used for testing purposes.
  66. var newCertificateAuthorityClient = func(ctx context.Context, credentialsFile string) (CertificateAuthorityClient, error) {
  67. var cloudOpts []option.ClientOption
  68. if credentialsFile != "" {
  69. cloudOpts = append(cloudOpts, option.WithCredentialsFile(credentialsFile))
  70. }
  71. client, err := privateca.NewCertificateAuthorityClient(ctx, cloudOpts...)
  72. if err != nil {
  73. return nil, errors.Wrap(err, "error creating client")
  74. }
  75. return client, nil
  76. }
  77. // New creates a new CertificateAuthorityService implementation using Google
  78. // Cloud CAS.
  79. func New(ctx context.Context, opts apiv1.Options) (*CloudCAS, error) {
  80. if opts.IsCreator {
  81. switch {
  82. case opts.Project == "":
  83. return nil, errors.New("cloudCAS 'project' cannot be empty")
  84. case opts.Location == "":
  85. return nil, errors.New("cloudCAS 'location' cannot be empty")
  86. }
  87. } else {
  88. if opts.CertificateAuthority == "" {
  89. return nil, errors.New("cloudCAS 'certificateAuthority' cannot be empty")
  90. }
  91. if !caRegexp.MatchString(opts.CertificateAuthority) {
  92. return nil, errors.New("cloudCAS 'certificateAuthority' is not valid certificate authority resource")
  93. }
  94. // Extract project and location from CertificateAuthority
  95. if parts := strings.Split(opts.CertificateAuthority, "/"); len(parts) == 6 {
  96. if opts.Project == "" {
  97. opts.Project = parts[1]
  98. }
  99. if opts.Location == "" {
  100. opts.Location = parts[3]
  101. }
  102. }
  103. }
  104. client, err := newCertificateAuthorityClient(ctx, opts.CredentialsFile)
  105. if err != nil {
  106. return nil, err
  107. }
  108. return &CloudCAS{
  109. client: client,
  110. certificateAuthority: opts.CertificateAuthority,
  111. project: opts.Project,
  112. location: opts.Location,
  113. }, nil
  114. }
  115. // GetCertificateAuthority returns the root certificate for the given
  116. // certificate authority. It implements apiv1.CertificateAuthorityGetter
  117. // interface.
  118. func (c *CloudCAS) GetCertificateAuthority(req *apiv1.GetCertificateAuthorityRequest) (*apiv1.GetCertificateAuthorityResponse, error) {
  119. name := req.Name
  120. if name == "" {
  121. name = c.certificateAuthority
  122. }
  123. ctx, cancel := defaultContext()
  124. defer cancel()
  125. resp, err := c.client.GetCertificateAuthority(ctx, &pb.GetCertificateAuthorityRequest{
  126. Name: name,
  127. })
  128. if err != nil {
  129. println(name)
  130. return nil, errors.Wrap(err, "cloudCAS GetCertificateAuthority failed")
  131. }
  132. if len(resp.PemCaCertificates) == 0 {
  133. return nil, errors.New("cloudCAS GetCertificateAuthority: PemCACertificate should not be empty")
  134. }
  135. // Last certificate in the chain is the root.
  136. root, err := parseCertificate(resp.PemCaCertificates[len(resp.PemCaCertificates)-1])
  137. if err != nil {
  138. return nil, err
  139. }
  140. return &apiv1.GetCertificateAuthorityResponse{
  141. RootCertificate: root,
  142. }, nil
  143. }
  144. // CreateCertificate signs a new certificate using Google Cloud CAS.
  145. func (c *CloudCAS) CreateCertificate(req *apiv1.CreateCertificateRequest) (*apiv1.CreateCertificateResponse, error) {
  146. switch {
  147. case req.Template == nil:
  148. return nil, errors.New("createCertificateRequest `template` cannot be nil")
  149. case req.Lifetime == 0:
  150. return nil, errors.New("createCertificateRequest `lifetime` cannot be 0")
  151. }
  152. cert, chain, err := c.createCertificate(req.Template, req.Lifetime, req.RequestID)
  153. if err != nil {
  154. return nil, err
  155. }
  156. return &apiv1.CreateCertificateResponse{
  157. Certificate: cert,
  158. CertificateChain: chain,
  159. }, nil
  160. }
  161. // RenewCertificate renews the given certificate using Google Cloud CAS.
  162. // Google's CAS does not support the renew operation, so this method uses
  163. // CreateCertificate.
  164. func (c *CloudCAS) RenewCertificate(req *apiv1.RenewCertificateRequest) (*apiv1.RenewCertificateResponse, error) {
  165. switch {
  166. case req.Template == nil:
  167. return nil, errors.New("renewCertificateRequest `template` cannot be nil")
  168. case req.Lifetime == 0:
  169. return nil, errors.New("renewCertificateRequest `lifetime` cannot be 0")
  170. }
  171. cert, chain, err := c.createCertificate(req.Template, req.Lifetime, req.RequestID)
  172. if err != nil {
  173. return nil, err
  174. }
  175. return &apiv1.RenewCertificateResponse{
  176. Certificate: cert,
  177. CertificateChain: chain,
  178. }, nil
  179. }
  180. // RevokeCertificate revokes a certificate using Google Cloud CAS.
  181. func (c *CloudCAS) RevokeCertificate(req *apiv1.RevokeCertificateRequest) (*apiv1.RevokeCertificateResponse, error) {
  182. reason, ok := revocationCodeMap[req.ReasonCode]
  183. switch {
  184. case !ok:
  185. return nil, errors.Errorf("revokeCertificate 'reasonCode=%d' is invalid or not supported", req.ReasonCode)
  186. case req.Certificate == nil:
  187. return nil, errors.New("revokeCertificateRequest `certificate` cannot be nil")
  188. }
  189. ext, ok := apiv1.FindCertificateAuthorityExtension(req.Certificate)
  190. if !ok {
  191. return nil, errors.New("error revoking certificate: certificate authority extension was not found")
  192. }
  193. var cae apiv1.CertificateAuthorityExtension
  194. if _, err := asn1.Unmarshal(ext.Value, &cae); err != nil {
  195. return nil, errors.Wrap(err, "error unmarshaling certificate authority extension")
  196. }
  197. ctx, cancel := defaultContext()
  198. defer cancel()
  199. certpb, err := c.client.RevokeCertificate(ctx, &pb.RevokeCertificateRequest{
  200. Name: c.certificateAuthority + "/certificates/" + cae.CertificateID,
  201. Reason: reason,
  202. RequestId: req.RequestID,
  203. })
  204. if err != nil {
  205. return nil, errors.Wrap(err, "cloudCAS RevokeCertificate failed")
  206. }
  207. cert, chain, err := getCertificateAndChain(certpb)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return &apiv1.RevokeCertificateResponse{
  212. Certificate: cert,
  213. CertificateChain: chain,
  214. }, nil
  215. }
  216. // CreateCertificateAuthority creates a new root or intermediate certificate
  217. // using Google Cloud CAS.
  218. func (c *CloudCAS) CreateCertificateAuthority(req *apiv1.CreateCertificateAuthorityRequest) (*apiv1.CreateCertificateAuthorityResponse, error) {
  219. switch {
  220. case c.project == "":
  221. return nil, errors.New("cloudCAS `project` cannot be empty")
  222. case c.location == "":
  223. return nil, errors.New("cloudCAS `location` cannot be empty")
  224. case req.Template == nil:
  225. return nil, errors.New("createCertificateAuthorityRequest `template` cannot be nil")
  226. case req.Lifetime == 0:
  227. return nil, errors.New("createCertificateAuthorityRequest `lifetime` cannot be 0")
  228. case req.Type == apiv1.IntermediateCA && req.Parent == nil:
  229. return nil, errors.New("createCertificateAuthorityRequest `parent` cannot be nil")
  230. case req.Type == apiv1.IntermediateCA && req.Parent.Name == "" && (req.Parent.Certificate == nil || req.Parent.Signer == nil):
  231. return nil, errors.New("createCertificateAuthorityRequest `parent.name` cannot be empty")
  232. }
  233. var caType pb.CertificateAuthority_Type
  234. switch req.Type {
  235. case apiv1.RootCA:
  236. caType = pb.CertificateAuthority_SELF_SIGNED
  237. case apiv1.IntermediateCA:
  238. caType = pb.CertificateAuthority_SUBORDINATE
  239. default:
  240. return nil, errors.Errorf("createCertificateAuthorityRequest `type=%d' is invalid or not supported", req.Type)
  241. }
  242. // Select key and signature algorithm to use
  243. var err error
  244. var keySpec *pb.CertificateAuthority_KeyVersionSpec
  245. if req.CreateKey == nil {
  246. if keySpec, err = createKeyVersionSpec(0, 0); err != nil {
  247. return nil, errors.Wrap(err, "createCertificateAuthorityRequest `createKey` is not valid")
  248. }
  249. } else {
  250. if keySpec, err = createKeyVersionSpec(req.CreateKey.SignatureAlgorithm, req.CreateKey.Bits); err != nil {
  251. return nil, errors.Wrap(err, "createCertificateAuthorityRequest `createKey` is not valid")
  252. }
  253. }
  254. // Normalize or generate id.
  255. caID := normalizeCertificateAuthorityName(req.Name)
  256. if caID == "" {
  257. id, err := createCertificateID()
  258. if err != nil {
  259. return nil, err
  260. }
  261. caID = id
  262. }
  263. // Add CertificateAuthority extension
  264. casExtension, err := apiv1.CreateCertificateAuthorityExtension(apiv1.CloudCAS, caID)
  265. if err != nil {
  266. return nil, err
  267. }
  268. req.Template.ExtraExtensions = append(req.Template.ExtraExtensions, casExtension)
  269. // Prepare CreateCertificateAuthorityRequest
  270. pbReq := &pb.CreateCertificateAuthorityRequest{
  271. Parent: "projects/" + c.project + "/locations/" + c.location,
  272. CertificateAuthorityId: caID,
  273. RequestId: req.RequestID,
  274. CertificateAuthority: &pb.CertificateAuthority{
  275. Type: caType,
  276. Tier: pb.CertificateAuthority_ENTERPRISE,
  277. Config: &pb.CertificateConfig{
  278. SubjectConfig: &pb.CertificateConfig_SubjectConfig{
  279. Subject: createSubject(req.Template),
  280. CommonName: req.Template.Subject.CommonName,
  281. },
  282. ReusableConfig: createReusableConfig(req.Template),
  283. },
  284. Lifetime: durationpb.New(req.Lifetime),
  285. KeySpec: keySpec,
  286. IssuingOptions: &pb.CertificateAuthority_IssuingOptions{
  287. IncludeCaCertUrl: true,
  288. IncludeCrlAccessUrl: true,
  289. },
  290. Labels: map[string]string{},
  291. },
  292. }
  293. // Create certificate authority.
  294. ctx, cancel := defaultContext()
  295. defer cancel()
  296. resp, err := c.client.CreateCertificateAuthority(ctx, pbReq)
  297. if err != nil {
  298. return nil, errors.Wrap(err, "cloudCAS CreateCertificateAuthority failed")
  299. }
  300. // Wait for the long-running operation.
  301. ctx, cancel = defaultInitiatorContext()
  302. defer cancel()
  303. ca, err := resp.Wait(ctx)
  304. if err != nil {
  305. return nil, errors.Wrap(err, "cloudCAS CreateCertificateAuthority failed")
  306. }
  307. // Sign Intermediate CAs with the parent.
  308. if req.Type == apiv1.IntermediateCA {
  309. ca, err = c.signIntermediateCA(ca.Name, req)
  310. if err != nil {
  311. return nil, err
  312. }
  313. }
  314. if len(ca.PemCaCertificates) == 0 {
  315. return nil, errors.New("cloudCAS CreateCertificateAuthority failed: PemCaCertificates is empty")
  316. }
  317. cert, err := parseCertificate(ca.PemCaCertificates[0])
  318. if err != nil {
  319. return nil, err
  320. }
  321. var chain []*x509.Certificate
  322. if pemChain := ca.PemCaCertificates[1:]; len(pemChain) > 0 {
  323. chain = make([]*x509.Certificate, len(pemChain))
  324. for i, s := range pemChain {
  325. if chain[i], err = parseCertificate(s); err != nil {
  326. return nil, err
  327. }
  328. }
  329. }
  330. return &apiv1.CreateCertificateAuthorityResponse{
  331. Name: ca.Name,
  332. Certificate: cert,
  333. CertificateChain: chain,
  334. }, nil
  335. }
  336. func (c *CloudCAS) createCertificate(tpl *x509.Certificate, lifetime time.Duration, requestID string) (*x509.Certificate, []*x509.Certificate, error) {
  337. // Removes the CAS extension if it exists.
  338. apiv1.RemoveCertificateAuthorityExtension(tpl)
  339. // Create new CAS extension with the certificate id.
  340. id, err := createCertificateID()
  341. if err != nil {
  342. return nil, nil, err
  343. }
  344. casExtension, err := apiv1.CreateCertificateAuthorityExtension(apiv1.CloudCAS, id)
  345. if err != nil {
  346. return nil, nil, err
  347. }
  348. tpl.ExtraExtensions = append(tpl.ExtraExtensions, casExtension)
  349. // Create and submit certificate
  350. certConfig, err := createCertificateConfig(tpl)
  351. if err != nil {
  352. return nil, nil, err
  353. }
  354. ctx, cancel := defaultContext()
  355. defer cancel()
  356. cert, err := c.client.CreateCertificate(ctx, &pb.CreateCertificateRequest{
  357. Parent: c.certificateAuthority,
  358. CertificateId: id,
  359. Certificate: &pb.Certificate{
  360. CertificateConfig: certConfig,
  361. Lifetime: durationpb.New(lifetime),
  362. Labels: map[string]string{},
  363. },
  364. RequestId: requestID,
  365. })
  366. if err != nil {
  367. return nil, nil, errors.Wrap(err, "cloudCAS CreateCertificate failed")
  368. }
  369. // Return certificate and certificate chain
  370. return getCertificateAndChain(cert)
  371. }
  372. func (c *CloudCAS) signIntermediateCA(name string, req *apiv1.CreateCertificateAuthorityRequest) (*pb.CertificateAuthority, error) {
  373. id, err := createCertificateID()
  374. if err != nil {
  375. return nil, err
  376. }
  377. // Fetch intermediate CSR
  378. ctx, cancel := defaultInitiatorContext()
  379. defer cancel()
  380. csr, err := c.client.FetchCertificateAuthorityCsr(ctx, &pb.FetchCertificateAuthorityCsrRequest{
  381. Name: name,
  382. })
  383. if err != nil {
  384. return nil, errors.Wrap(err, "cloudCAS FetchCertificateAuthorityCsr failed")
  385. }
  386. // Sign the CSR with the ca.
  387. var cert *pb.Certificate
  388. if req.Parent.Certificate != nil && req.Parent.Signer != nil {
  389. // Using a local certificate and key.
  390. cr, err := parseCertificateRequest(csr.PemCsr)
  391. if err != nil {
  392. return nil, err
  393. }
  394. template, err := x509util.CreateCertificateTemplate(cr)
  395. if err != nil {
  396. return nil, err
  397. }
  398. t := now()
  399. template.NotBefore = t.Add(-1 * req.Backdate)
  400. template.NotAfter = t.Add(req.Lifetime)
  401. // Sign certificate
  402. crt, err := x509util.CreateCertificate(template, req.Parent.Certificate, template.PublicKey, req.Parent.Signer)
  403. if err != nil {
  404. return nil, err
  405. }
  406. // Build pb.Certificate for activaion
  407. chain := []string{
  408. encodeCertificate(req.Parent.Certificate),
  409. }
  410. for _, c := range req.Parent.CertificateChain {
  411. chain = append(chain, encodeCertificate(c))
  412. }
  413. cert = &pb.Certificate{
  414. PemCertificate: encodeCertificate(crt),
  415. PemCertificateChain: chain,
  416. }
  417. } else {
  418. // Using the parent in CloudCAS.
  419. ctx, cancel = defaultInitiatorContext()
  420. defer cancel()
  421. cert, err = c.client.CreateCertificate(ctx, &pb.CreateCertificateRequest{
  422. Parent: req.Parent.Name,
  423. CertificateId: id,
  424. Certificate: &pb.Certificate{
  425. CertificateConfig: &pb.Certificate_PemCsr{
  426. PemCsr: csr.PemCsr,
  427. },
  428. Lifetime: durationpb.New(req.Lifetime),
  429. Labels: map[string]string{},
  430. },
  431. RequestId: req.RequestID,
  432. })
  433. if err != nil {
  434. return nil, errors.Wrap(err, "cloudCAS CreateCertificate failed")
  435. }
  436. }
  437. // Activate the intermediate certificate.
  438. ctx, cancel = defaultInitiatorContext()
  439. defer cancel()
  440. resp, err := c.client.ActivateCertificateAuthority(ctx, &pb.ActivateCertificateAuthorityRequest{
  441. Name: name,
  442. PemCaCertificate: cert.PemCertificate,
  443. SubordinateConfig: &pb.SubordinateConfig{
  444. SubordinateConfig: &pb.SubordinateConfig_PemIssuerChain{
  445. PemIssuerChain: &pb.SubordinateConfig_SubordinateConfigChain{
  446. PemCertificates: cert.PemCertificateChain,
  447. },
  448. },
  449. },
  450. RequestId: req.RequestID,
  451. })
  452. if err != nil {
  453. return nil, errors.Wrap(err, "cloudCAS ActivateCertificateAuthority1 failed")
  454. }
  455. // Wait for the long-running operation.
  456. ctx, cancel = defaultInitiatorContext()
  457. defer cancel()
  458. ca, err := resp.Wait(ctx)
  459. if err != nil {
  460. return nil, errors.Wrap(err, "cloudCAS ActivateCertificateAuthority failed")
  461. }
  462. return ca, nil
  463. }
  464. func defaultContext() (context.Context, context.CancelFunc) {
  465. return context.WithTimeout(context.Background(), 15*time.Second)
  466. }
  467. func defaultInitiatorContext() (context.Context, context.CancelFunc) {
  468. return context.WithTimeout(context.Background(), 60*time.Second)
  469. }
  470. func createCertificateID() (string, error) {
  471. id, err := uuid.NewRandomFromReader(rand.Reader)
  472. if err != nil {
  473. return "", errors.Wrap(err, "error creating certificate id")
  474. }
  475. return id.String(), nil
  476. }
  477. func parseCertificate(pemCert string) (*x509.Certificate, error) {
  478. block, _ := pem.Decode([]byte(pemCert))
  479. if block == nil {
  480. return nil, errors.New("error decoding certificate: not a valid PEM encoded block")
  481. }
  482. cert, err := x509.ParseCertificate(block.Bytes)
  483. if err != nil {
  484. return nil, errors.Wrap(err, "error parsing certificate")
  485. }
  486. return cert, nil
  487. }
  488. func parseCertificateRequest(pemCsr string) (*x509.CertificateRequest, error) {
  489. block, _ := pem.Decode([]byte(pemCsr))
  490. if block == nil {
  491. return nil, errors.New("error decoding certificate request: not a valid PEM encoded block")
  492. }
  493. cr, err := x509.ParseCertificateRequest(block.Bytes)
  494. if err != nil {
  495. return nil, errors.Wrap(err, "error parsing certificate request")
  496. }
  497. return cr, nil
  498. }
  499. func encodeCertificate(cert *x509.Certificate) string {
  500. return string(pem.EncodeToMemory(&pem.Block{
  501. Type: "CERTIFICATE",
  502. Bytes: cert.Raw,
  503. }))
  504. }
  505. func getCertificateAndChain(certpb *pb.Certificate) (*x509.Certificate, []*x509.Certificate, error) {
  506. cert, err := parseCertificate(certpb.PemCertificate)
  507. if err != nil {
  508. return nil, nil, err
  509. }
  510. pemChain := certpb.PemCertificateChain[:len(certpb.PemCertificateChain)-1]
  511. chain := make([]*x509.Certificate, len(pemChain))
  512. for i := range pemChain {
  513. chain[i], err = parseCertificate(pemChain[i])
  514. if err != nil {
  515. return nil, nil, err
  516. }
  517. }
  518. return cert, chain, nil
  519. }
  520. // Normalize a certificate authority name to comply with [a-zA-Z0-9-_].
  521. func normalizeCertificateAuthorityName(name string) string {
  522. return strings.Map(func(r rune) rune {
  523. switch {
  524. case r >= 'a' && r <= 'z':
  525. return r
  526. case r >= 'A' && r <= 'Z':
  527. return r
  528. case r >= '0' && r <= '9':
  529. return r
  530. case r == '-':
  531. return r
  532. case r == '_':
  533. return r
  534. default:
  535. return '-'
  536. }
  537. }, name)
  538. }