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