gcp.go 12 KB

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