4
0

cloudcas.go 23 KB

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