gcp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package provisioner
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "time"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/certificates/errs"
  16. "go.step.sm/crypto/jose"
  17. "go.step.sm/crypto/sshutil"
  18. "go.step.sm/crypto/x509util"
  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. claimer *Claimer
  82. config *gcpConfig
  83. keyStore *keyStore
  84. audiences Audiences
  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 string, 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 := ioutil.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) error {
  173. var err error
  174. switch {
  175. case p.Type == "":
  176. return errors.New("provisioner type cannot be empty")
  177. case p.Name == "":
  178. return errors.New("provisioner name cannot be empty")
  179. case p.InstanceAge.Value() < 0:
  180. return errors.New("provisioner instanceAge cannot be negative")
  181. }
  182. // Initialize config
  183. p.assertConfig()
  184. // Update claims with global ones
  185. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  186. return err
  187. }
  188. // Initialize key store
  189. p.keyStore, err = newKeyStore(p.config.CertsURL)
  190. if err != nil {
  191. return err
  192. }
  193. p.audiences = config.Audiences.WithFragment(p.GetIDForToken())
  194. return nil
  195. }
  196. // AuthorizeSign validates the given token and returns the sign options that
  197. // will be used on certificate creation.
  198. func (p *GCP) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  199. claims, err := p.authorizeToken(token)
  200. if err != nil {
  201. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSign")
  202. }
  203. ce := claims.Google.ComputeEngine
  204. // Template options
  205. data := x509util.NewTemplateData()
  206. data.SetCommonName(ce.InstanceName)
  207. if v, err := unsafeParseSigned(token); err == nil {
  208. data.SetToken(v)
  209. }
  210. // Enforce known common name and default DNS if configured.
  211. // By default we we'll accept the CN and SANs in the CSR.
  212. // There's no way to trust them other than TOFU.
  213. var so []SignOption
  214. if p.DisableCustomSANs {
  215. dnsName1 := fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID)
  216. dnsName2 := fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID)
  217. so = append(so, commonNameSliceValidator([]string{
  218. ce.InstanceName, ce.InstanceID, dnsName1, dnsName2,
  219. }))
  220. so = append(so, dnsNamesValidator([]string{
  221. dnsName1, dnsName2,
  222. }))
  223. so = append(so, ipAddressesValidator(nil))
  224. so = append(so, emailAddressesValidator(nil))
  225. so = append(so, urisValidator(nil))
  226. // Template SANs
  227. data.SetSANs([]string{dnsName1, dnsName2})
  228. }
  229. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultIIDLeafTemplate)
  230. if err != nil {
  231. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSign")
  232. }
  233. return append(so,
  234. templateOptions,
  235. // modifiers / withOptions
  236. newProvisionerExtensionOption(TypeGCP, p.Name, claims.Subject, "InstanceID", ce.InstanceID, "InstanceName", ce.InstanceName),
  237. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  238. // validators
  239. defaultPublicKeyValidator{},
  240. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  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. if p.claimer.IsDisableRenewal() {
  246. return errs.Unauthorized("gcp.AuthorizeRenew; renew is disabled for gcp provisioner '%s'", p.GetName())
  247. }
  248. return nil
  249. }
  250. // assertConfig initializes the config if it has not been initialized.
  251. func (p *GCP) assertConfig() {
  252. if p.config == nil {
  253. p.config = newGCPConfig()
  254. }
  255. }
  256. // authorizeToken performs common jwt authorization actions and returns the
  257. // claims for case specific downstream parsing.
  258. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  259. func (p *GCP) authorizeToken(token string) (*gcpPayload, error) {
  260. jwt, err := jose.ParseSigned(token)
  261. if err != nil {
  262. return nil, errs.Wrap(http.StatusUnauthorized, err, "gcp.authorizeToken; error parsing gcp token")
  263. }
  264. if len(jwt.Headers) == 0 {
  265. return nil, errs.Unauthorized("gcp.authorizeToken; error parsing gcp token - header is missing")
  266. }
  267. var found bool
  268. var claims gcpPayload
  269. kid := jwt.Headers[0].KeyID
  270. keys := p.keyStore.Get(kid)
  271. for _, key := range keys {
  272. if err := jwt.Claims(key.Public(), &claims); err == nil {
  273. found = true
  274. break
  275. }
  276. }
  277. if !found {
  278. return nil, errs.Unauthorized("gcp.authorizeToken; failed to validate gcp token payload - cannot find key for kid %s", kid)
  279. }
  280. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  281. // more than a few minutes.
  282. now := time.Now().UTC()
  283. if err = claims.ValidateWithLeeway(jose.Expected{
  284. Issuer: "https://accounts.google.com",
  285. Time: now,
  286. }, time.Minute); err != nil {
  287. return nil, errs.Wrap(http.StatusUnauthorized, err, "gcp.authorizeToken; invalid gcp token payload")
  288. }
  289. // validate audiences with the defaults
  290. if !matchesAudience(claims.Audience, p.audiences.Sign) {
  291. return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid audience claim (aud)")
  292. }
  293. // validate subject (service account)
  294. if len(p.ServiceAccounts) > 0 {
  295. var found bool
  296. for _, sa := range p.ServiceAccounts {
  297. if sa == claims.Subject || sa == claims.Email {
  298. found = true
  299. break
  300. }
  301. }
  302. if !found {
  303. return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid subject claim")
  304. }
  305. }
  306. // validate projects
  307. if len(p.ProjectIDs) > 0 {
  308. var found bool
  309. for _, pi := range p.ProjectIDs {
  310. if pi == claims.Google.ComputeEngine.ProjectID {
  311. found = true
  312. break
  313. }
  314. }
  315. if !found {
  316. return nil, errs.Unauthorized("gcp.authorizeToken; invalid gcp token - invalid project id")
  317. }
  318. }
  319. // validate instance age
  320. if d := p.InstanceAge.Value(); d > 0 {
  321. if now.Sub(claims.Google.ComputeEngine.InstanceCreationTimestamp.Time()) > d {
  322. return nil, errs.Unauthorized("gcp.authorizeToken; token google.compute_engine.instance_creation_timestamp is too old")
  323. }
  324. }
  325. switch {
  326. case claims.Google.ComputeEngine.InstanceID == "":
  327. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.instance_id cannot be empty")
  328. case claims.Google.ComputeEngine.InstanceName == "":
  329. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.instance_name cannot be empty")
  330. case claims.Google.ComputeEngine.ProjectID == "":
  331. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.project_id cannot be empty")
  332. case claims.Google.ComputeEngine.Zone == "":
  333. return nil, errs.Unauthorized("gcp.authorizeToken; gcp token google.compute_engine.zone cannot be empty")
  334. }
  335. return &claims, nil
  336. }
  337. // AuthorizeSSHSign returns the list of SignOption for a SignSSH request.
  338. func (p *GCP) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  339. if !p.claimer.IsSSHCAEnabled() {
  340. return nil, errs.Unauthorized("gcp.AuthorizeSSHSign; sshCA is disabled for gcp provisioner '%s'", p.GetName())
  341. }
  342. claims, err := p.authorizeToken(token)
  343. if err != nil {
  344. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSSHSign")
  345. }
  346. ce := claims.Google.ComputeEngine
  347. signOptions := []SignOption{}
  348. // Enforce host certificate.
  349. defaults := SignSSHOptions{
  350. CertType: SSHHostCert,
  351. }
  352. // Validated principals.
  353. principals := []string{
  354. fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
  355. fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
  356. }
  357. // Only enforce known principals if disable custom sans is true.
  358. if p.DisableCustomSANs {
  359. defaults.Principals = principals
  360. } else {
  361. // Check that at least one principal is sent in the request.
  362. signOptions = append(signOptions, &sshCertOptionsRequireValidator{
  363. Principals: true,
  364. })
  365. }
  366. // Certificate templates.
  367. data := sshutil.CreateTemplateData(sshutil.HostCert, ce.InstanceName, principals)
  368. if v, err := unsafeParseSigned(token); err == nil {
  369. data.SetToken(v)
  370. }
  371. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.DefaultIIDTemplate)
  372. if err != nil {
  373. return nil, errs.Wrap(http.StatusInternalServerError, err, "gcp.AuthorizeSSHSign")
  374. }
  375. signOptions = append(signOptions, templateOptions)
  376. return append(signOptions,
  377. // Validate user SignSSHOptions.
  378. sshCertOptionsValidator(defaults),
  379. // Set the validity bounds if not set.
  380. &sshDefaultDuration{p.claimer},
  381. // Validate public key
  382. &sshDefaultPublicKeyValidator{},
  383. // Validate the validity period.
  384. &sshCertValidityValidator{p.claimer},
  385. // Require all the fields in the SSH certificate
  386. &sshCertDefaultValidator{},
  387. ), nil
  388. }