gcp.go 14 KB

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