gcp.go 14 KB

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