gcp.go 13 KB

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