gcp.go 14 KB

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