gcp.go 17 KB

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