cloudcas.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. "github.com/smallstep/certificates/cas/apiv1"
  17. "go.step.sm/crypto/x509util"
  18. "google.golang.org/api/option"
  19. "google.golang.org/grpc/codes"
  20. "google.golang.org/grpc/status"
  21. durationpb "google.golang.org/protobuf/types/known/durationpb"
  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.WithCredentialsFile(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. // GetCertificateAuthority returns the root certificate for the given
  144. // certificate authority. It implements apiv1.CertificateAuthorityGetter
  145. // interface.
  146. func (c *CloudCAS) GetCertificateAuthority(req *apiv1.GetCertificateAuthorityRequest) (*apiv1.GetCertificateAuthorityResponse, error) {
  147. name := req.Name
  148. if name == "" {
  149. name = c.certificateAuthority
  150. }
  151. ctx, cancel := defaultContext()
  152. defer cancel()
  153. resp, err := c.client.GetCertificateAuthority(ctx, &pb.GetCertificateAuthorityRequest{
  154. Name: name,
  155. })
  156. if err != nil {
  157. return nil, errors.Wrap(err, "cloudCAS GetCertificateAuthority failed")
  158. }
  159. if len(resp.PemCaCertificates) == 0 {
  160. return nil, errors.New("cloudCAS GetCertificateAuthority: PemCACertificate should not be empty")
  161. }
  162. // Last certificate in the chain is the root.
  163. root, err := parseCertificate(resp.PemCaCertificates[len(resp.PemCaCertificates)-1])
  164. if err != nil {
  165. return nil, err
  166. }
  167. return &apiv1.GetCertificateAuthorityResponse{
  168. RootCertificate: root,
  169. }, nil
  170. }
  171. // CreateCertificate signs a new certificate using Google Cloud CAS.
  172. func (c *CloudCAS) CreateCertificate(req *apiv1.CreateCertificateRequest) (*apiv1.CreateCertificateResponse, error) {
  173. switch {
  174. case req.Template == nil:
  175. return nil, errors.New("createCertificateRequest `template` cannot be nil")
  176. case req.Lifetime == 0:
  177. return nil, errors.New("createCertificateRequest `lifetime` cannot be 0")
  178. }
  179. cert, chain, err := c.createCertificate(req.Template, req.Lifetime, req.RequestID)
  180. if err != nil {
  181. return nil, err
  182. }
  183. return &apiv1.CreateCertificateResponse{
  184. Certificate: cert,
  185. CertificateChain: chain,
  186. }, nil
  187. }
  188. // RenewCertificate renews the given certificate using Google Cloud CAS.
  189. // Google's CAS does not support the renew operation, so this method uses
  190. // CreateCertificate.
  191. func (c *CloudCAS) RenewCertificate(req *apiv1.RenewCertificateRequest) (*apiv1.RenewCertificateResponse, error) {
  192. switch {
  193. case req.Template == nil:
  194. return nil, errors.New("renewCertificateRequest `template` cannot be nil")
  195. case req.Lifetime == 0:
  196. return nil, errors.New("renewCertificateRequest `lifetime` cannot be 0")
  197. }
  198. cert, chain, err := c.createCertificate(req.Template, req.Lifetime, req.RequestID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return &apiv1.RenewCertificateResponse{
  203. Certificate: cert,
  204. CertificateChain: chain,
  205. }, nil
  206. }
  207. // RevokeCertificate revokes a certificate using Google Cloud CAS.
  208. func (c *CloudCAS) RevokeCertificate(req *apiv1.RevokeCertificateRequest) (*apiv1.RevokeCertificateResponse, error) {
  209. reason, ok := revocationCodeMap[req.ReasonCode]
  210. switch {
  211. case !ok:
  212. return nil, errors.Errorf("revokeCertificate 'reasonCode=%d' is invalid or not supported", req.ReasonCode)
  213. case req.Certificate == nil:
  214. return nil, errors.New("revokeCertificateRequest `certificate` cannot be nil")
  215. }
  216. ext, ok := apiv1.FindCertificateAuthorityExtension(req.Certificate)
  217. if !ok {
  218. return nil, errors.New("error revoking certificate: certificate authority extension was not found")
  219. }
  220. var cae apiv1.CertificateAuthorityExtension
  221. if _, err := asn1.Unmarshal(ext.Value, &cae); err != nil {
  222. return nil, errors.Wrap(err, "error unmarshaling certificate authority extension")
  223. }
  224. ctx, cancel := defaultContext()
  225. defer cancel()
  226. certpb, err := c.client.RevokeCertificate(ctx, &pb.RevokeCertificateRequest{
  227. Name: c.certificateAuthority + "/certificates/" + cae.CertificateID,
  228. Reason: reason,
  229. RequestId: req.RequestID,
  230. })
  231. if err != nil {
  232. return nil, errors.Wrap(err, "cloudCAS RevokeCertificate failed")
  233. }
  234. cert, chain, err := getCertificateAndChain(certpb)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return &apiv1.RevokeCertificateResponse{
  239. Certificate: cert,
  240. CertificateChain: chain,
  241. }, nil
  242. }
  243. // CreateCertificateAuthority creates a new root or intermediate certificate
  244. // using Google Cloud CAS.
  245. func (c *CloudCAS) CreateCertificateAuthority(req *apiv1.CreateCertificateAuthorityRequest) (*apiv1.CreateCertificateAuthorityResponse, error) {
  246. switch {
  247. case c.project == "":
  248. return nil, errors.New("cloudCAS `project` cannot be empty")
  249. case c.location == "":
  250. return nil, errors.New("cloudCAS `location` cannot be empty")
  251. case c.caPool == "":
  252. return nil, errors.New("cloudCAS `caPool` cannot be empty")
  253. case c.caPoolTier == 0:
  254. return nil, errors.New("cloudCAS `caPoolTier` cannot be empty")
  255. case req.Template == nil:
  256. return nil, errors.New("createCertificateAuthorityRequest `template` cannot be nil")
  257. case req.Lifetime == 0:
  258. return nil, errors.New("createCertificateAuthorityRequest `lifetime` cannot be 0")
  259. case req.Type == apiv1.IntermediateCA && req.Parent == nil:
  260. return nil, errors.New("createCertificateAuthorityRequest `parent` cannot be nil")
  261. case req.Type == apiv1.IntermediateCA && req.Parent.Name == "" && (req.Parent.Certificate == nil || req.Parent.Signer == nil):
  262. return nil, errors.New("createCertificateAuthorityRequest `parent.name` cannot be empty")
  263. }
  264. var caType pb.CertificateAuthority_Type
  265. switch req.Type {
  266. case apiv1.RootCA:
  267. caType = pb.CertificateAuthority_SELF_SIGNED
  268. case apiv1.IntermediateCA:
  269. caType = pb.CertificateAuthority_SUBORDINATE
  270. default:
  271. return nil, errors.Errorf("createCertificateAuthorityRequest `type=%d' is invalid or not supported", req.Type)
  272. }
  273. // Select key and signature algorithm to use
  274. var err error
  275. var keySpec *pb.CertificateAuthority_KeyVersionSpec
  276. if req.CreateKey == nil {
  277. if keySpec, err = createKeyVersionSpec(0, 0); err != nil {
  278. return nil, errors.Wrap(err, "createCertificateAuthorityRequest `createKey` is not valid")
  279. }
  280. } else {
  281. if keySpec, err = createKeyVersionSpec(req.CreateKey.SignatureAlgorithm, req.CreateKey.Bits); err != nil {
  282. return nil, errors.Wrap(err, "createCertificateAuthorityRequest `createKey` is not valid")
  283. }
  284. }
  285. // Normalize or generate id.
  286. caID := normalizeCertificateAuthorityName(req.Name)
  287. if caID == "" {
  288. id, err := createCertificateID()
  289. if err != nil {
  290. return nil, err
  291. }
  292. caID = id
  293. }
  294. // Add CertificateAuthority extension
  295. casExtension, err := apiv1.CreateCertificateAuthorityExtension(apiv1.CloudCAS, caID)
  296. if err != nil {
  297. return nil, err
  298. }
  299. req.Template.ExtraExtensions = append(req.Template.ExtraExtensions, casExtension)
  300. // Create the caPool if necessary
  301. parent, err := c.createCaPoolIfNecessary()
  302. if err != nil {
  303. return nil, err
  304. }
  305. // Prepare CreateCertificateAuthorityRequest
  306. pbReq := &pb.CreateCertificateAuthorityRequest{
  307. Parent: parent,
  308. CertificateAuthorityId: caID,
  309. RequestId: req.RequestID,
  310. CertificateAuthority: &pb.CertificateAuthority{
  311. Type: caType,
  312. Config: &pb.CertificateConfig{
  313. SubjectConfig: &pb.CertificateConfig_SubjectConfig{
  314. Subject: createSubject(req.Template),
  315. SubjectAltName: createSubjectAlternativeNames(req.Template),
  316. },
  317. X509Config: createX509Parameters(req.Template),
  318. },
  319. Lifetime: durationpb.New(req.Lifetime),
  320. KeySpec: keySpec,
  321. GcsBucket: c.gcsBucket,
  322. Labels: map[string]string{},
  323. },
  324. }
  325. // Create certificate authority.
  326. ctx, cancel := defaultContext()
  327. defer cancel()
  328. resp, err := c.client.CreateCertificateAuthority(ctx, pbReq)
  329. if err != nil {
  330. return nil, errors.Wrap(err, "cloudCAS CreateCertificateAuthority failed")
  331. }
  332. // Wait for the long-running operation.
  333. ctx, cancel = defaultInitiatorContext()
  334. defer cancel()
  335. ca, err := resp.Wait(ctx)
  336. if err != nil {
  337. return nil, errors.Wrap(err, "cloudCAS CreateCertificateAuthority failed")
  338. }
  339. // Sign Intermediate CAs with the parent.
  340. if req.Type == apiv1.IntermediateCA {
  341. ca, err = c.signIntermediateCA(parent, ca.Name, req)
  342. if err != nil {
  343. return nil, err
  344. }
  345. }
  346. // Enable Certificate Authority.
  347. ca, err = c.enableCertificateAuthority(ca)
  348. if err != nil {
  349. return nil, err
  350. }
  351. if len(ca.PemCaCertificates) == 0 {
  352. return nil, errors.New("cloudCAS CreateCertificateAuthority failed: PemCaCertificates is empty")
  353. }
  354. cert, err := parseCertificate(ca.PemCaCertificates[0])
  355. if err != nil {
  356. return nil, err
  357. }
  358. var chain []*x509.Certificate
  359. if pemChain := ca.PemCaCertificates[1:]; len(pemChain) > 0 {
  360. chain = make([]*x509.Certificate, len(pemChain))
  361. for i, s := range pemChain {
  362. if chain[i], err = parseCertificate(s); err != nil {
  363. return nil, err
  364. }
  365. }
  366. }
  367. return &apiv1.CreateCertificateAuthorityResponse{
  368. Name: ca.Name,
  369. Certificate: cert,
  370. CertificateChain: chain,
  371. }, nil
  372. }
  373. func (c *CloudCAS) createCaPoolIfNecessary() (string, error) {
  374. ctx, cancel := defaultContext()
  375. defer cancel()
  376. pool, err := c.client.GetCaPool(ctx, &pb.GetCaPoolRequest{
  377. Name: "projects/" + c.project + "/locations/" + c.location + "/caPools/" + c.caPool,
  378. })
  379. if err == nil {
  380. return pool.Name, nil
  381. }
  382. if status.Code(err) != codes.NotFound {
  383. return "", errors.Wrap(err, "cloudCAS GetCaPool failed")
  384. }
  385. // PublishCrl is only supported by the enterprise tier
  386. var publishCrl bool
  387. if c.caPoolTier == pb.CaPool_ENTERPRISE {
  388. publishCrl = true
  389. }
  390. ctx, cancel = defaultContext()
  391. defer cancel()
  392. op, err := c.client.CreateCaPool(ctx, &pb.CreateCaPoolRequest{
  393. Parent: "projects/" + c.project + "/locations/" + c.location,
  394. CaPoolId: c.caPool,
  395. CaPool: &pb.CaPool{
  396. Tier: c.caPoolTier,
  397. IssuancePolicy: nil,
  398. PublishingOptions: &pb.CaPool_PublishingOptions{
  399. PublishCaCert: true,
  400. PublishCrl: publishCrl,
  401. },
  402. },
  403. })
  404. if err != nil {
  405. return "", errors.Wrap(err, "cloudCAS CreateCaPool failed")
  406. }
  407. ctx, cancel = defaultInitiatorContext()
  408. defer cancel()
  409. pool, err = op.Wait(ctx)
  410. if err != nil {
  411. return "", errors.Wrap(err, "cloudCAS CreateCaPool failed")
  412. }
  413. return pool.Name, nil
  414. }
  415. func (c *CloudCAS) enableCertificateAuthority(ca *pb.CertificateAuthority) (*pb.CertificateAuthority, error) {
  416. if ca.State == pb.CertificateAuthority_ENABLED {
  417. return ca, nil
  418. }
  419. ctx, cancel := defaultContext()
  420. defer cancel()
  421. resp, err := c.client.EnableCertificateAuthority(ctx, &pb.EnableCertificateAuthorityRequest{
  422. Name: ca.Name,
  423. })
  424. if err != nil {
  425. return nil, errors.Wrap(err, "cloudCAS EnableCertificateAuthority failed")
  426. }
  427. ctx, cancel = defaultInitiatorContext()
  428. defer cancel()
  429. ca, err = resp.Wait(ctx)
  430. if err != nil {
  431. return nil, errors.Wrap(err, "cloudCAS EnableCertificateAuthority failed")
  432. }
  433. return ca, nil
  434. }
  435. func (c *CloudCAS) createCertificate(tpl *x509.Certificate, lifetime time.Duration, requestID string) (*x509.Certificate, []*x509.Certificate, error) {
  436. // Removes the CAS extension if it exists.
  437. apiv1.RemoveCertificateAuthorityExtension(tpl)
  438. // Create new CAS extension with the certificate id.
  439. id, err := createCertificateID()
  440. if err != nil {
  441. return nil, nil, err
  442. }
  443. casExtension, err := apiv1.CreateCertificateAuthorityExtension(apiv1.CloudCAS, id)
  444. if err != nil {
  445. return nil, nil, err
  446. }
  447. tpl.ExtraExtensions = append(tpl.ExtraExtensions, casExtension)
  448. // Create and submit certificate
  449. certConfig, err := createCertificateConfig(tpl)
  450. if err != nil {
  451. return nil, nil, err
  452. }
  453. ctx, cancel := defaultContext()
  454. defer cancel()
  455. cert, err := c.client.CreateCertificate(ctx, &pb.CreateCertificateRequest{
  456. Parent: "projects/" + c.project + "/locations/" + c.location + "/caPools/" + c.caPool,
  457. CertificateId: id,
  458. Certificate: &pb.Certificate{
  459. CertificateConfig: certConfig,
  460. Lifetime: durationpb.New(lifetime),
  461. Labels: map[string]string{},
  462. },
  463. IssuingCertificateAuthorityId: getResourceName(c.certificateAuthority),
  464. RequestId: requestID,
  465. })
  466. if err != nil {
  467. return nil, nil, errors.Wrap(err, "cloudCAS CreateCertificate failed")
  468. }
  469. // Return certificate and certificate chain
  470. return getCertificateAndChain(cert)
  471. }
  472. func (c *CloudCAS) signIntermediateCA(parent, name string, req *apiv1.CreateCertificateAuthorityRequest) (*pb.CertificateAuthority, error) {
  473. id, err := createCertificateID()
  474. if err != nil {
  475. return nil, err
  476. }
  477. // Fetch intermediate CSR
  478. ctx, cancel := defaultInitiatorContext()
  479. defer cancel()
  480. csr, err := c.client.FetchCertificateAuthorityCsr(ctx, &pb.FetchCertificateAuthorityCsrRequest{
  481. Name: name,
  482. })
  483. if err != nil {
  484. return nil, errors.Wrap(err, "cloudCAS FetchCertificateAuthorityCsr failed")
  485. }
  486. // Sign the CSR with the ca.
  487. var cert *pb.Certificate
  488. if req.Parent.Certificate != nil && req.Parent.Signer != nil {
  489. // Using a local certificate and key.
  490. cr, err := parseCertificateRequest(csr.PemCsr)
  491. if err != nil {
  492. return nil, err
  493. }
  494. template, err := x509util.CreateCertificateTemplate(cr)
  495. if err != nil {
  496. return nil, err
  497. }
  498. t := now()
  499. template.NotBefore = t.Add(-1 * req.Backdate)
  500. template.NotAfter = t.Add(req.Lifetime)
  501. // Sign certificate
  502. crt, err := x509util.CreateCertificate(template, req.Parent.Certificate, template.PublicKey, req.Parent.Signer)
  503. if err != nil {
  504. return nil, err
  505. }
  506. // Build pb.Certificate for activaion
  507. chain := []string{
  508. encodeCertificate(req.Parent.Certificate),
  509. }
  510. for _, c := range req.Parent.CertificateChain {
  511. chain = append(chain, encodeCertificate(c))
  512. }
  513. cert = &pb.Certificate{
  514. PemCertificate: encodeCertificate(crt),
  515. PemCertificateChain: chain,
  516. }
  517. } else {
  518. // Using the parent in CloudCAS.
  519. ctx, cancel = defaultInitiatorContext()
  520. defer cancel()
  521. cert, err = c.client.CreateCertificate(ctx, &pb.CreateCertificateRequest{
  522. Parent: parent,
  523. CertificateId: id,
  524. Certificate: &pb.Certificate{
  525. CertificateConfig: &pb.Certificate_PemCsr{
  526. PemCsr: csr.PemCsr,
  527. },
  528. Lifetime: durationpb.New(req.Lifetime),
  529. Labels: map[string]string{},
  530. },
  531. IssuingCertificateAuthorityId: getResourceName(req.Parent.Name),
  532. RequestId: req.RequestID,
  533. })
  534. if err != nil {
  535. return nil, errors.Wrap(err, "cloudCAS CreateCertificate failed")
  536. }
  537. }
  538. // Activate the intermediate certificate.
  539. ctx, cancel = defaultInitiatorContext()
  540. defer cancel()
  541. resp, err := c.client.ActivateCertificateAuthority(ctx, &pb.ActivateCertificateAuthorityRequest{
  542. Name: name,
  543. PemCaCertificate: cert.PemCertificate,
  544. SubordinateConfig: &pb.SubordinateConfig{
  545. SubordinateConfig: &pb.SubordinateConfig_PemIssuerChain{
  546. PemIssuerChain: &pb.SubordinateConfig_SubordinateConfigChain{
  547. PemCertificates: cert.PemCertificateChain,
  548. },
  549. },
  550. },
  551. RequestId: req.RequestID,
  552. })
  553. if err != nil {
  554. return nil, errors.Wrap(err, "cloudCAS ActivateCertificateAuthority1 failed")
  555. }
  556. // Wait for the long-running operation.
  557. ctx, cancel = defaultInitiatorContext()
  558. defer cancel()
  559. ca, err := resp.Wait(ctx)
  560. if err != nil {
  561. return nil, errors.Wrap(err, "cloudCAS ActivateCertificateAuthority failed")
  562. }
  563. return ca, nil
  564. }
  565. func defaultContext() (context.Context, context.CancelFunc) {
  566. return context.WithTimeout(context.Background(), 15*time.Second)
  567. }
  568. func defaultInitiatorContext() (context.Context, context.CancelFunc) {
  569. return context.WithTimeout(context.Background(), 60*time.Second)
  570. }
  571. func createCertificateID() (string, error) {
  572. id, err := uuid.NewRandomFromReader(rand.Reader)
  573. if err != nil {
  574. return "", errors.Wrap(err, "error creating certificate id")
  575. }
  576. return id.String(), nil
  577. }
  578. func parseCertificate(pemCert string) (*x509.Certificate, error) {
  579. block, _ := pem.Decode([]byte(pemCert))
  580. if block == nil {
  581. return nil, errors.New("error decoding certificate: not a valid PEM encoded block")
  582. }
  583. cert, err := x509.ParseCertificate(block.Bytes)
  584. if err != nil {
  585. return nil, errors.Wrap(err, "error parsing certificate")
  586. }
  587. return cert, nil
  588. }
  589. func parseCertificateRequest(pemCsr string) (*x509.CertificateRequest, error) {
  590. block, _ := pem.Decode([]byte(pemCsr))
  591. if block == nil {
  592. return nil, errors.New("error decoding certificate request: not a valid PEM encoded block")
  593. }
  594. cr, err := x509.ParseCertificateRequest(block.Bytes)
  595. if err != nil {
  596. return nil, errors.Wrap(err, "error parsing certificate request")
  597. }
  598. return cr, nil
  599. }
  600. func encodeCertificate(cert *x509.Certificate) string {
  601. return string(pem.EncodeToMemory(&pem.Block{
  602. Type: "CERTIFICATE",
  603. Bytes: cert.Raw,
  604. }))
  605. }
  606. func getCertificateAndChain(certpb *pb.Certificate) (*x509.Certificate, []*x509.Certificate, error) {
  607. cert, err := parseCertificate(certpb.PemCertificate)
  608. if err != nil {
  609. return nil, nil, err
  610. }
  611. pemChain := certpb.PemCertificateChain[:len(certpb.PemCertificateChain)-1]
  612. chain := make([]*x509.Certificate, len(pemChain))
  613. for i := range pemChain {
  614. chain[i], err = parseCertificate(pemChain[i])
  615. if err != nil {
  616. return nil, nil, err
  617. }
  618. }
  619. return cert, chain, nil
  620. }
  621. // getResourceName returns the last part of a resource.
  622. func getResourceName(name string) string {
  623. parts := strings.Split(name, "/")
  624. return parts[len(parts)-1]
  625. }
  626. // Normalize a certificate authority name to comply with [a-zA-Z0-9-_].
  627. func normalizeCertificateAuthorityName(name string) string {
  628. return strings.Map(func(r rune) rune {
  629. switch {
  630. case r >= 'a' && r <= 'z':
  631. return r
  632. case r >= 'A' && r <= 'Z':
  633. return r
  634. case r >= '0' && r <= '9':
  635. return r
  636. case r == '-':
  637. return r
  638. case r == '_':
  639. return r
  640. default:
  641. return '-'
  642. }
  643. }, name)
  644. }