gcp.go 14 KB

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