gcp.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. package provisioner
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "time"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/linkedca"
  16. "go.step.sm/crypto/jose"
  17. "go.step.sm/crypto/sshutil"
  18. "go.step.sm/crypto/x509util"
  19. "github.com/smallstep/certificates/authority/provisioner/gcp"
  20. "github.com/smallstep/certificates/errs"
  21. "github.com/smallstep/certificates/webhook"
  22. )
  23. // gcpCertsURL is the url that serves Google OAuth2 public keys.
  24. const gcpCertsURL = "https://www.googleapis.com/oauth2/v3/certs"
  25. // gcpIdentityURL is the base url for the identity document in GCP.
  26. const gcpIdentityURL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity"
  27. // DefaultDisableSSHCAHost is the default value for SSH Host CA used when DisableSSHCAHost is not set
  28. var DefaultDisableSSHCAHost = false
  29. // DefaultDisableSSHCAUser is the default value for SSH User CA used when DisableSSHCAUser is not set
  30. var DefaultDisableSSHCAUser = true
  31. // gcpPayload extends jwt.Claims with custom GCP attributes.
  32. type gcpPayload struct {
  33. jose.Claims
  34. AuthorizedParty string `json:"azp"`
  35. Email string `json:"email"`
  36. EmailVerified bool `json:"email_verified"`
  37. Google gcpGooglePayload `json:"google"`
  38. }
  39. type gcpGooglePayload struct {
  40. ComputeEngine gcpComputeEnginePayload `json:"compute_engine"`
  41. }
  42. type gcpComputeEnginePayload struct {
  43. InstanceID string `json:"instance_id"`
  44. InstanceName string `json:"instance_name"`
  45. InstanceCreationTimestamp *jose.NumericDate `json:"instance_creation_timestamp"`
  46. ProjectID string `json:"project_id"`
  47. ProjectNumber int64 `json:"project_number"`
  48. Zone string `json:"zone"`
  49. LicenseID []string `json:"license_id"`
  50. }
  51. type gcpConfig struct {
  52. CertsURL string
  53. IdentityURL string
  54. }
  55. func newGCPConfig() *gcpConfig {
  56. return &gcpConfig{
  57. CertsURL: gcpCertsURL,
  58. IdentityURL: gcpIdentityURL,
  59. }
  60. }
  61. // projectValidator is an interface to enable testing without using
  62. // gcp.OrganizationProjectValidator.
  63. type projectValidator interface {
  64. ValidateProject(ctx context.Context, projectID string) error
  65. }
  66. // GCP is the provisioner that supports identity tokens created by the Google
  67. // Cloud Platform metadata API.
  68. //
  69. // If DisableCustomSANs is true, only the internal DNS and IP will be added as a
  70. // SAN. By default it will accept any SAN in the CSR.
  71. //
  72. // If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
  73. // with the same instance will be accepted. By default only the first request
  74. // will be accepted.
  75. //
  76. // If InstanceAge is set, only the instances with an instance_creation_timestamp
  77. // within the given period will be accepted.
  78. //
  79. // Google Identity docs are available at
  80. // https://cloud.google.com/compute/docs/instances/verifying-instance-identity
  81. type GCP struct {
  82. *base
  83. ID string `json:"-"`
  84. Type string `json:"type"`
  85. Name string `json:"name"`
  86. ServiceAccounts []string `json:"serviceAccounts,omitempty"`
  87. ProjectIDs []string `json:"projectIDs,omitempty"`
  88. OrganizationID string `json:"organizationID,omitempty"`
  89. DisableCustomSANs bool `json:"disableCustomSANs"`
  90. DisableTrustOnFirstUse bool `json:"disableTrustOnFirstUse"`
  91. DisableSSHCAUser *bool `json:"disableSSHCAUser,omitempty"`
  92. DisableSSHCAHost *bool `json:"disableSSHCAHost,omitempty"`
  93. InstanceAge Duration `json:"instanceAge"`
  94. Claims *Claims `json:"claims,omitempty"`
  95. Options *Options `json:"options,omitempty"`
  96. config *gcpConfig
  97. keyStore *keyStore
  98. ctl *Controller
  99. projectValidator projectValidator
  100. }
  101. // GetID returns the provisioner unique identifier. The name should uniquely
  102. // identify any GCP provisioner.
  103. func (p *GCP) GetID() string {
  104. if p.ID != "" {
  105. return p.ID
  106. }
  107. return p.GetIDForToken()
  108. }
  109. // GetIDForToken returns an identifier that will be used to load the provisioner
  110. // from a token.
  111. func (p *GCP) GetIDForToken() string {
  112. return "gcp/" + p.Name
  113. }
  114. // GetTokenID returns the identifier of the token. The default value for GCP the
  115. // SHA256 of "provisioner_id.instance_id", but if DisableTrustOnFirstUse is set
  116. // to true, then it will be the SHA256 of the token.
  117. func (p *GCP) GetTokenID(token string) (string, error) {
  118. jwt, err := jose.ParseSigned(token)
  119. if err != nil {
  120. return "", errors.Wrap(err, "error parsing token")
  121. }
  122. // If TOFU is disabled create an ID for the token, so it cannot be reused.
  123. if p.DisableTrustOnFirstUse {
  124. sum := sha256.Sum256([]byte(token))
  125. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  126. }
  127. // Get claims w/out verification.
  128. var claims gcpPayload
  129. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  130. return "", errors.Wrap(err, "error verifying claims")
  131. }
  132. // Create unique ID for Trust On First Use (TOFU). Only the first instance
  133. // per provisioner is allowed as we don't have a way to trust the given
  134. // sans.
  135. unique := fmt.Sprintf("%s.%s", p.GetIDForToken(), claims.Google.ComputeEngine.InstanceID)
  136. sum := sha256.Sum256([]byte(unique))
  137. return strings.ToLower(hex.EncodeToString(sum[:])), nil
  138. }
  139. // GetName returns the name of the provisioner.
  140. func (p *GCP) GetName() string {
  141. return p.Name
  142. }
  143. // GetType returns the type of provisioner.
  144. func (p *GCP) GetType() Type {
  145. return TypeGCP
  146. }
  147. // GetEncryptedKey is not available in a GCP provisioner.
  148. func (p *GCP) GetEncryptedKey() (kid, key string, ok bool) {
  149. return "", "", false
  150. }
  151. // GetIdentityURL returns the url that generates the GCP token.
  152. func (p *GCP) GetIdentityURL(audience string) string {
  153. // Initialize config if required
  154. p.assertConfig()
  155. q := url.Values{}
  156. q.Add("audience", audience)
  157. q.Add("format", "full")
  158. q.Add("licenses", "FALSE")
  159. return fmt.Sprintf("%s?%s", p.config.IdentityURL, q.Encode())
  160. }
  161. // GetIdentityToken does an HTTP request to the identity url.
  162. func (p *GCP) GetIdentityToken(subject, caURL string) (string, error) {
  163. _ = subject // unused input
  164. audience, err := generateSignAudience(caURL, p.GetIDForToken())
  165. if err != nil {
  166. return "", err
  167. }
  168. req, err := http.NewRequest("GET", p.GetIdentityURL(audience), http.NoBody)
  169. if err != nil {
  170. return "", errors.Wrap(err, "error creating identity request")
  171. }
  172. req.Header.Set("Metadata-Flavor", "Google")
  173. resp, err := http.DefaultClient.Do(req)
  174. if err != nil {
  175. return "", errors.Wrap(err, "error doing identity request, are you in a GCP VM?")
  176. }
  177. defer resp.Body.Close()
  178. b, err := io.ReadAll(resp.Body)
  179. if err != nil {
  180. return "", errors.Wrap(err, "error on identity request")
  181. }
  182. if resp.StatusCode >= 400 {
  183. return "", errors.Errorf("error on identity request: status=%d, response=%s", resp.StatusCode, b)
  184. }
  185. return string(bytes.TrimSpace(b)), nil
  186. }
  187. // Init validates and initializes the GCP provisioner.
  188. func (p *GCP) Init(config Config) (err error) {
  189. if p.DisableSSHCAHost == nil {
  190. p.DisableSSHCAHost = &DefaultDisableSSHCAHost
  191. }
  192. if p.DisableSSHCAUser == nil {
  193. p.DisableSSHCAUser = &DefaultDisableSSHCAUser
  194. }
  195. switch {
  196. case p.Type == "":
  197. return errors.New("provisioner type cannot be empty")
  198. case p.Name == "":
  199. return errors.New("provisioner name cannot be empty")
  200. case p.InstanceAge.Value() < 0:
  201. return errors.New("provisioner instanceAge cannot be negative")
  202. }
  203. if len(p.ProjectIDs) > 0 && p.OrganizationID != "" {
  204. return errors.New("provisioner cannot have both `projectIDs` and `organizationID` set")
  205. }
  206. // Initialize config
  207. p.assertConfig()
  208. // Initialize key store
  209. if p.keyStore, err = newKeyStore(http.DefaultClient, p.config.CertsURL); err != nil {
  210. return
  211. }
  212. // Initialize the project validator
  213. if p.projectValidator, err = gcp.NewOrganizationValidator(p.ProjectIDs, p.OrganizationID); err != nil {
  214. return
  215. }
  216. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  217. if p.ctl, err = NewController(p, p.Claims, config, p.Options); err != nil {
  218. return
  219. }
  220. return
  221. }
  222. // AuthorizeSign validates the given token and returns the sign options that
  223. // will be used on certificate creation.
  224. func (p *GCP) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  225. claims, err := p.authorizeToken(ctx, token)
  226. if err != nil {
  227. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSign")
  228. }
  229. ce := claims.Google.ComputeEngine
  230. // Template options
  231. data := x509util.NewTemplateData()
  232. data.SetCommonName(ce.InstanceName)
  233. if v, err := unsafeParseSigned(token); err == nil {
  234. data.SetToken(v)
  235. }
  236. // Enforce known common name and default DNS if configured.
  237. // By default we we'll accept the CN and SANs in the CSR.
  238. // There's no way to trust them other than TOFU.
  239. var so []SignOption
  240. if p.DisableCustomSANs {
  241. dnsName1 := fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID)
  242. dnsName2 := fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID)
  243. so = append(so,
  244. commonNameSliceValidator([]string{
  245. ce.InstanceName, ce.InstanceID, dnsName1, dnsName2,
  246. }),
  247. dnsNamesSubsetValidator([]string{
  248. dnsName1, dnsName2,
  249. }),
  250. ipAddressesValidator(nil),
  251. emailAddressesValidator(nil),
  252. newURIsValidator(ctx, nil),
  253. )
  254. // Template SANs
  255. data.SetSANs([]string{dnsName1, dnsName2})
  256. }
  257. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultIIDLeafTemplate)
  258. if err != nil {
  259. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSign")
  260. }
  261. return append(so,
  262. p,
  263. templateOptions,
  264. // modifiers / withOptions
  265. newProvisionerExtensionOption(TypeGCP, p.Name, claims.Subject, "InstanceID", ce.InstanceID, "InstanceName", ce.InstanceName).WithControllerOptions(p.ctl),
  266. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  267. // validators
  268. defaultPublicKeyValidator{},
  269. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  270. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  271. p.ctl.newWebhookController(
  272. data,
  273. linkedca.Webhook_X509,
  274. webhook.WithAuthorizationPrincipal(ce.InstanceID),
  275. ),
  276. ), nil
  277. }
  278. // AuthorizeRenew returns an error if the renewal is disabled.
  279. func (p *GCP) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  280. return p.ctl.AuthorizeRenew(ctx, cert)
  281. }
  282. // assertConfig initializes the config if it has not been initialized.
  283. func (p *GCP) assertConfig() {
  284. if p.config == nil {
  285. p.config = newGCPConfig()
  286. }
  287. }
  288. // authorizeToken performs common jwt authorization actions and returns the
  289. // claims for case specific downstream parsing.
  290. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  291. func (p *GCP) authorizeToken(ctx context.Context, token string) (*gcpPayload, error) {
  292. jwt, err := jose.ParseSigned(token)
  293. if err != nil {
  294. return nil, errs.Wrap(http.StatusUnauthorized, err, "gcp.authorizeToken; error parsing gcp token")
  295. }
  296. if len(jwt.Headers) == 0 {
  297. return nil, errs.Unauthorized("gcp.authorizeToken; error parsing gcp token - header is missing")
  298. }
  299. var found bool
  300. var claims gcpPayload
  301. kid := jwt.Headers[0].KeyID
  302. keys := p.keyStore.Get(kid)
  303. for _, key := range keys {
  304. if err := jwt.Claims(key.Public(), &claims); err == nil {
  305. found = true
  306. break
  307. }
  308. }
  309. if !found {
  310. return nil, errs.Unauthorized("gcp.authorizeToken; failed to validate gcp token payload - cannot find key for kid %s", kid)
  311. }
  312. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  313. // more than a few minutes.
  314. now := time.Now().UTC()
  315. if err = claims.ValidateWithLeeway(jose.Expected{
  316. Issuer: "https://accounts.google.com",
  317. Time: now,
  318. }, time.Minute); err != nil {
  319. return nil, errs.Wrap(http.StatusUnauthorized, err, "gcp.authorizeToken; invalid gcp token payload")
  320. }
  321. // validate audiences with the defaults
  322. if !matchesAudience(claims.Audience, p.ctl.Audiences.Sign) {
  323. return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid audience claim (aud)")
  324. }
  325. // validate subject (service account)
  326. if len(p.ServiceAccounts) > 0 {
  327. var found bool
  328. for _, sa := range p.ServiceAccounts {
  329. if sa == claims.Subject || sa == claims.Email {
  330. found = true
  331. break
  332. }
  333. }
  334. if !found {
  335. return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid subject claim")
  336. }
  337. }
  338. // validate projects
  339. if err := p.projectValidator.ValidateProject(ctx, claims.Google.ComputeEngine.ProjectID); err != nil {
  340. return nil, err
  341. }
  342. // validate instance age
  343. if d := p.InstanceAge.Value(); d > 0 {
  344. if now.Sub(claims.Google.ComputeEngine.InstanceCreationTimestamp.Time()) > d {
  345. return nil, errs.Unauthorized("gcp.authorizeToken; token google.compute_engine.instance_creation_timestamp is too old")
  346. }
  347. }
  348. switch {
  349. case claims.Google.ComputeEngine.InstanceID == "":
  350. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.instance_id cannot be empty")
  351. case claims.Google.ComputeEngine.InstanceName == "":
  352. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.instance_name cannot be empty")
  353. case claims.Google.ComputeEngine.ProjectID == "":
  354. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.project_id cannot be empty")
  355. case claims.Google.ComputeEngine.Zone == "":
  356. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.zone cannot be empty")
  357. }
  358. return &claims, nil
  359. }
  360. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  361. func (p *GCP) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  362. certType, hasCertType := CertTypeFromContext(ctx)
  363. if !hasCertType {
  364. certType = SSHHostCert
  365. }
  366. err := p.isUnauthorizedToIssueSSHCert(certType)
  367. if err != nil {
  368. return nil, err
  369. }
  370. claims, err := p.authorizeToken(ctx, token)
  371. if err != nil {
  372. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSSHSign")
  373. }
  374. var principals []string
  375. var keyID string
  376. var defaults SignSSHOptions
  377. var ct sshutil.CertType
  378. var template string
  379. switch certType {
  380. case SSHHostCert:
  381. defaults, keyID, principals, ct, template = p.genHostOptions(ctx, claims)
  382. case SSHUserCert:
  383. defaults, keyID, principals, ct, template = p.genUserOptions(ctx, claims)
  384. default:
  385. return nil, errs.Unauthorized("gcp.AuthorizeSSHSign; invalid requested certType")
  386. }
  387. signOptions := []SignOption{}
  388. // Only enforce known principals if disable custom sans is true, or it is a user cert request
  389. if p.DisableCustomSANs || certType == SSHUserCert {
  390. defaults.Principals = principals
  391. } else {
  392. // Check that at least one principal is sent in the request.
  393. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  394. Principals: true,
  395. })
  396. }
  397. // Certificate templates.
  398. data := sshutil.CreateTemplateData(ct, keyID, principals)
  399. if v, err := unsafeParseSigned(token); err == nil {
  400. data.SetToken(v)
  401. }
  402. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, template)
  403. if err != nil {
  404. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSSHSign")
  405. }
  406. signOptions = append(signOptions, templateOptions)
  407. return append(signOptions,
  408. p,
  409. // Validate user SignSSHOptions.
  410. sshCertOptionsValidator(defaults),
  411. // Set the validity bounds if not set.
  412. &sshDefaultDuration{p.ctl.Claimer},
  413. // Validate public key
  414. &sshDefaultPublicKeyValidator{},
  415. // Validate the validity period.
  416. &sshCertValidityValidator{p.ctl.Claimer},
  417. // Require all the fields in the SSH certificate
  418. &sshCertDefaultValidator{},
  419. // Ensure that all principal names are allowed
  420. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), p.ctl.getPolicy().getSSHUser()),
  421. // Call webhooks
  422. p.ctl.newWebhookController(
  423. data,
  424. linkedca.Webhook_SSH,
  425. webhook.WithAuthorizationPrincipal(keyID),
  426. ),
  427. ), nil
  428. }
  429. func (p *GCP) genHostOptions(_ context.Context, claims *gcpPayload) (SignSSHOptions, string, []string, sshutil.CertType, string) {
  430. ce := claims.Google.ComputeEngine
  431. keyID := ce.InstanceName
  432. principals := []string{
  433. fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
  434. fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
  435. }
  436. return SignSSHOptions{CertType: SSHHostCert}, keyID, principals, sshutil.HostCert, sshutil.DefaultIIDTemplate
  437. }
  438. func FormatServiceAccountUsername(serviceAccountID string) string {
  439. return fmt.Sprintf("sa_%v", serviceAccountID)
  440. }
  441. func (p *GCP) genUserOptions(_ context.Context, claims *gcpPayload) (SignSSHOptions, string, []string, sshutil.CertType, string) {
  442. keyID := claims.Email
  443. principals := []string{
  444. FormatServiceAccountUsername(claims.Subject),
  445. claims.Email,
  446. }
  447. return SignSSHOptions{CertType: SSHUserCert}, keyID, principals, sshutil.UserCert, sshutil.DefaultTemplate
  448. }
  449. func (p *GCP) isUnauthorizedToIssueSSHCert(certType string) error {
  450. if !p.ctl.Claimer.IsSSHCAEnabled() {
  451. return errs.Unauthorized("gcp.AuthorizeSSHSign; sshCA is disabled for gcp provisioner '%s'", p.GetName())
  452. }
  453. if certType == SSHHostCert && *p.DisableSSHCAHost {
  454. return errs.Unauthorized("gcp.AuthorizeSSHSign; sshCA for Hosts is disabled for gcp provisioner '%s'", p.GetName())
  455. }
  456. if certType == SSHUserCert && *p.DisableSSHCAUser {
  457. return errs.Unauthorized("gcp.AuthorizeSSHSign; sshCA for Users is disabled for gcp provisioner '%s'", p.GetName())
  458. }
  459. return nil
  460. }