cloudcas.go 23 KB

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