cloudcas.go 23 KB

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