gcp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 MethodFromContext(ctx) == SignSSHMethod {
  191. if !p.claimer.IsSSHCAEnabled() {
  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. // modifiers / withOptions
  213. newProvisionerExtensionOption(TypeGCP, p.Name, claims.Subject, "InstanceID", ce.InstanceID, "InstanceName", ce.InstanceName),
  214. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  215. // validators
  216. defaultPublicKeyValidator{},
  217. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  218. ), nil
  219. }
  220. // AuthorizeRenewal returns an error if the renewal is disabled.
  221. func (p *GCP) AuthorizeRenewal(cert *x509.Certificate) error {
  222. if p.claimer.IsDisableRenewal() {
  223. return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
  224. }
  225. return nil
  226. }
  227. // AuthorizeRevoke returns an error because revoke is not supported on GCP
  228. // provisioners.
  229. func (p *GCP) AuthorizeRevoke(token string) error {
  230. return errors.New("revoke is not supported on a GCP provisioner")
  231. }
  232. // assertConfig initializes the config if it has not been initialized.
  233. func (p *GCP) assertConfig() {
  234. if p.config == nil {
  235. p.config = newGCPConfig()
  236. }
  237. }
  238. // authorizeToken performs common jwt authorization actions and returns the
  239. // claims for case specific downstream parsing.
  240. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  241. func (p *GCP) authorizeToken(token string) (*gcpPayload, error) {
  242. jwt, err := jose.ParseSigned(token)
  243. if err != nil {
  244. return nil, errors.Wrapf(err, "error parsing token")
  245. }
  246. if len(jwt.Headers) == 0 {
  247. return nil, errors.New("error parsing token: header is missing")
  248. }
  249. var found bool
  250. var claims gcpPayload
  251. kid := jwt.Headers[0].KeyID
  252. keys := p.keyStore.Get(kid)
  253. for _, key := range keys {
  254. if err := jwt.Claims(key.Public(), &claims); err == nil {
  255. found = true
  256. break
  257. }
  258. }
  259. if !found {
  260. return nil, errors.Errorf("failed to validate payload: cannot find key for kid %s", kid)
  261. }
  262. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  263. // more than a few minutes.
  264. now := time.Now().UTC()
  265. if err = claims.ValidateWithLeeway(jose.Expected{
  266. Issuer: "https://accounts.google.com",
  267. Time: now,
  268. }, time.Minute); err != nil {
  269. return nil, errors.Wrapf(err, "invalid token")
  270. }
  271. // validate audiences with the defaults
  272. if !matchesAudience(claims.Audience, p.audiences.Sign) {
  273. return nil, errors.New("invalid token: invalid audience claim (aud)")
  274. }
  275. // validate subject (service account)
  276. if len(p.ServiceAccounts) > 0 {
  277. var found bool
  278. for _, sa := range p.ServiceAccounts {
  279. if sa == claims.Subject || sa == claims.Email {
  280. found = true
  281. break
  282. }
  283. }
  284. if !found {
  285. return nil, errors.New("invalid token: invalid subject claim")
  286. }
  287. }
  288. // validate projects
  289. if len(p.ProjectIDs) > 0 {
  290. var found bool
  291. for _, pi := range p.ProjectIDs {
  292. if pi == claims.Google.ComputeEngine.ProjectID {
  293. found = true
  294. break
  295. }
  296. }
  297. if !found {
  298. return nil, errors.New("invalid token: invalid project id")
  299. }
  300. }
  301. // validate instance age
  302. if d := p.InstanceAge.Value(); d > 0 {
  303. if now.Sub(claims.Google.ComputeEngine.InstanceCreationTimestamp.Time()) > d {
  304. return nil, errors.New("token google.compute_engine.instance_creation_timestamp is too old")
  305. }
  306. }
  307. switch {
  308. case claims.Google.ComputeEngine.InstanceID == "":
  309. return nil, errors.New("token google.compute_engine.instance_id cannot be empty")
  310. case claims.Google.ComputeEngine.InstanceName == "":
  311. return nil, errors.New("token google.compute_engine.instance_name cannot be empty")
  312. case claims.Google.ComputeEngine.ProjectID == "":
  313. return nil, errors.New("token google.compute_engine.project_id cannot be empty")
  314. case claims.Google.ComputeEngine.Zone == "":
  315. return nil, errors.New("token google.compute_engine.zone cannot be empty")
  316. }
  317. return &claims, nil
  318. }
  319. // authorizeSSHSign returns the list of SignOption for a SignSSH request.
  320. func (p *GCP) authorizeSSHSign(claims *gcpPayload) ([]SignOption, error) {
  321. ce := claims.Google.ComputeEngine
  322. signOptions := []SignOption{
  323. // set the key id to the token subject
  324. sshCertificateKeyIDModifier(ce.InstanceName),
  325. }
  326. // Default to host + known hostnames
  327. defaults := SSHOptions{
  328. CertType: SSHHostCert,
  329. Principals: []string{
  330. fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
  331. fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
  332. },
  333. }
  334. // Validate user options
  335. signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
  336. // Set defaults if not given as user options
  337. signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
  338. return append(signOptions,
  339. // Set the default extensions
  340. &sshDefaultExtensionModifier{},
  341. // Set the validity bounds if not set.
  342. sshDefaultValidityModifier(p.claimer),
  343. // Validate public key
  344. &sshDefaultPublicKeyValidator{},
  345. // Validate the validity period.
  346. &sshCertificateValidityValidator{p.claimer},
  347. // Require all the fields in the SSH certificate
  348. &sshCertificateDefaultValidator{},
  349. ), nil
  350. }