Compute Engine VMs inherit a lot of access from their defaults. Unless you change them, a VM runs as the Compute Engine default service account, which in older projects holds Editor on the whole project. Anyone who can add an SSH key to project metadata can log in to every VM. The VM gets an external IP, and code running on it can ask the metadata server for an access token. The result is a familiar incident pattern: one SSRF or remote code execution in a web application turns into a project-wide compromise through the cloud instance metadata API, and an attacker with compute.instances.setMetadata turns a small IAM grant into shell access on every machine. This page covers the instance-level controls from section 4 of the CIS Google Cloud Platform Foundation Benchmark plus the settings that remove those default paths. Hardening inside the guest operating system (SSH daemon configuration, kernel parameters, local firewall) still applies on top.
Baseline controls
Apply these to every VM and enforce the ones marked with a constraint at the organization node. CIS IDs refer to the CIS GCP Foundations Benchmark v5.0.1.
| Control | Why | How to check | CIS / SCC |
|---|---|---|---|
| Use a dedicated service account per workload | The default SA often holds Editor | gcloud compute instances list --format="value(name,serviceAccounts[].email)" | CIS 4.1, DEFAULT_SERVICE_ACCOUNT_USED |
| Never pair the default SA with full API scope | Token can call every API as Editor | Scopes column in gcloud compute instances describe | CIS 4.2, FULL_API_ACCESS |
| Enable OS Login | SSH access becomes IAM, not metadata | gcloud compute project-info describe | CIS 4.4, OS_LOGIN_DISABLED |
| Block project-wide SSH keys | One key must not open every VM | block-project-ssh-keys metadata | CIS 4.3, COMPUTE_PROJECT_WIDE_SSH_KEYS_ALLOWED |
| Disable serial port access | Bypasses network controls | serial-port-enable metadata | CIS 4.5, COMPUTE_SERIAL_PORTS_ENABLED |
| Disable IP forwarding | VM could route traffic it should not | --filter="canIpForward=true" | CIS 4.6, IP_FORWARDING_ENABLED |
| Enable Shielded VM with Secure Boot | Blocks bootkits and unsigned kernels | shieldedInstanceConfig in describe | CIS 4.8, SHIELDED_VM_DISABLED, COMPUTE_SECURE_BOOT_DISABLED |
| Remove external IP addresses | Fewer internet-reachable hosts | --filter="networkInterfaces.accessConfigs:*" | CIS 4.9, PUBLIC_IP_ADDRESS |
| Use Confidential VM for sensitive data | Encrypts memory in use | confidentialInstanceConfig in describe | CIS 4.11, CONFIDENTIAL_COMPUTING_DISABLED |
| Patch with VM Manager | Known CVEs are the easiest way in | VM Manager > Patch compliance | CIS 4.12 |
| Encrypt sensitive disks with CMEK | You control and can revoke the key | diskEncryptionKey on the disk | DISK_CMEK_DISABLED |
| Restrict images to trusted projects | Stops unvetted public images | compute.trustedImageProjects policy | n/a |
Service accounts and access scopes
Every project with the Compute Engine API enabled has a default service account named PROJECT_NUMBER-compute@developer.gserviceaccount.com. In projects created before the iam.automaticIamGrantsForDefaultServiceAccounts constraint was enforced, it was automatically granted roles/editor. VMs created without an explicit service account use it, so any code on any of those VMs can read and modify almost everything in the project.
Find VMs that use it:
gcloud compute instances list \
--format="table(name,zone.basename(),serviceAccounts[].email.list(),serviceAccounts[].scopes.list())" \
--filter="serviceAccounts.email~-compute@developer.gserviceaccount.com"
Create one service account per workload and grant only the roles it needs:
gcloud iam service-accounts create sa-web \
--project=prj-website-prod \
--display-name="Web tier VMs"
for role in roles/logging.logWriter roles/monitoring.metricWriter; do
gcloud projects add-iam-policy-binding prj-website-prod \
--member="serviceAccount:sa-web@prj-website-prod.iam.gserviceaccount.com" \
--role="$role"
done
Changing the service account of an existing VM requires stopping it:
gcloud compute instances stop web-1 --zone=europe-west1-b
gcloud compute instances set-service-account web-1 --zone=europe-west1-b \
--service-account=sa-web@prj-website-prod.iam.gserviceaccount.com \
--scopes=cloud-platform
gcloud compute instances start web-1 --zone=europe-west1-b
Then remove Editor from the default service account, or disable it once nothing uses it. Access scopes are a legacy mechanism that limits which APIs a VM token can call. With a dedicated, least-privilege service account, use the cloud-platform scope and let IAM do the restricting. The worst combination, flagged by CIS 4.2, is the default service account with full API access.
Enforce org-wide with iam.automaticIamGrantsForDefaultServiceAccounts (stops the automatic Editor grant in new projects) and the managed constraint iam.managed.preventPrivilegedBasicRolesForDefaultServiceAccounts, which blocks granting Owner or Editor to default service accounts afterwards. See Resource Manager and Organization Policy for the policy file format and IAM for service account design.
OS Login and SSH keys
By default, SSH keys live in project or instance metadata and the guest agent creates local accounts from them. Anyone with compute.projects.setCommonInstanceMetadata can add a key and log in to every VM in the project, and there is no central record of who has access.
OS Login links Linux accounts to Google identities and controls access with IAM. Enable it for the project, and require two-step verification on login:
gcloud compute project-info add-metadata \
--project=prj-website-prod \
--metadata=enable-oslogin=TRUE,enable-oslogin-2fa=TRUE
Grant login through roles, preferably to groups and at the narrowest level that works:
| Role | Grants |
|---|---|
roles/compute.osLogin | Log in as a standard user |
roles/compute.osAdminLogin | Log in with sudo |
roles/compute.osLoginExternalUser | Needed at organization level for users outside your organization |
gcloud compute instances add-iam-policy-binding web-1 \
--zone=europe-west1-b \
--member="group:web-sre@example.com" \
--role="roles/compute.osAdminLogin"
Users also need roles/iam.serviceAccountUser on the VM's service account if they log in to a VM that runs as one, so keep that grant scoped to the specific service account.
Where OS Login cannot be used on a specific VM (some Windows or appliance images), block project-wide keys on that instance at least:
gcloud compute instances add-metadata legacy-1 \
--zone=europe-west1-b \
--metadata=block-project-ssh-keys=TRUE
Combine this with IAP TCP forwarding so administrative SSH needs no external IP and every connection is authorized by IAM and logged (see VPC and firewall rules).
Console: Compute Engine > Settings > Metadata.
Verify:
gcloud compute project-info describe --project=prj-website-prod \
--format="value(commonInstanceMetadata.items)"
Enforce: compute.managed.requireOsLogin (legacy compute.requireOsLogin) requires OS Login and blocks metadata updates that disable it. compute.managed.blockProjectSshKeys requires block-project-ssh-keys on new VMs. Both managed constraints support tag-based exemptions for the few VMs that need them.
name: organizations/ORG_ID/policies/compute.managed.requireOsLogin
spec:
rules:
- enforce: true
gcloud org-policies set-policy require-oslogin.yaml
External IPs, IP forwarding and the serial console
VMs rarely need a public IP. Inbound traffic should come through a load balancer, administration through IAP, and outbound traffic through Cloud NAT. A VM created with the controls on this page:
gcloud compute instances create web-1 \
--project=prj-website-prod \
--zone=europe-west1-b \
--machine-type=e2-standard-2 \
--subnet=snet-prod-ew1 \
--no-address \
--service-account=sa-web@prj-website-prod.iam.gserviceaccount.com \
--scopes=cloud-platform \
--shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring \
--metadata=enable-oslogin=TRUE,block-project-ssh-keys=TRUE,serial-port-enable=FALSE \
--image-family=debian-12 --image-project=debian-cloud
Find VMs that still have an external IP, or IP forwarding enabled:
gcloud compute instances list \
--filter="networkInterfaces.accessConfigs:*" \
--format="table(name,zone.basename(),networkInterfaces[].accessConfigs[].natIP.flatten())"
gcloud compute instances list --filter="canIpForward=true" \
--format="table(name,zone.basename())"
IP forwarding lets a VM route packets not addressed to it. Only NAT gateways and network appliances need it, and it can only be set at creation time.
The interactive serial console lets anyone with the right IAM permissions interact with the VM even when networking is broken, bypassing firewall rules and IAP. Keep serial-port-enable=FALSE and enable it on a single VM only for the duration of a break-glass session.
Enforce org-wide:
compute.managed.vmExternalIpAccess(legacy list constraintcompute.vmExternalIpAccess): deny external IPv4 addresses, with tag-based exemptions for the VMs that genuinely need one.compute.managed.vmCanIpForward(legacycompute.vmCanIpForward): deny IP forwarding except on tagged appliances.compute.managed.disableSerialPortAccess(legacycompute.disableSerialPortAccess): deny serial port access.
Note that the managed constraints do not change existing VMs that already have the setting; they block new configurations and metadata updates. Fix existing instances with the commands above.
Shielded VM and Confidential VM
Shielded VM protects the boot chain:
- Secure Boot checks that the bootloader and kernel are signed by a trusted authority, blocking bootkits and unsigned kernel modules.
- vTPM provides a virtual Trusted Platform Module for measured boot and key sealing.
- Integrity monitoring compares each boot's measurements to a baseline and writes the result to Cloud Logging.
vTPM and integrity monitoring are on by default for Shielded VM images. Secure Boot is off by default because some custom images and third-party drivers are unsigned, so enable it explicitly. For an existing VM, stop it first:
gcloud compute instances stop web-1 --zone=europe-west1-b
gcloud compute instances update web-1 --zone=europe-west1-b \
--shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring
gcloud compute instances start web-1 --zone=europe-west1-b
After a legitimate kernel or bootloader update, accept the new baseline with gcloud compute instances update web-1 --shielded-learn-integrity-policy.
Confidential VM adds hardware memory encryption so that data in use is protected from the host. Choose the technology with --confidential-compute-type (SEV, SEV_SNP or TDX, depending on the machine series), and use --maintenance-policy=TERMINATE where live migration is not supported for that type. Use it for workloads handling regulated data or keys.
Console: Compute Engine > VM instances > (instance) > Security.
Enforce: compute.requireShieldedVm requires Shielded VM images with Secure Boot for new VMs. compute.restrictNonConfidentialComputing (or the managed compute.managed.restrictNonConfidentialComputing) requires Confidential VM on new instances; apply it to the folders that hold sensitive workloads rather than the whole organization.
Metadata and secrets
The metadata server is reachable from every process on the VM without authentication. Two consequences:
- Do not put secrets in metadata or startup scripts. Instance attributes and
startup-scriptvalues are readable by any process on the VM and by anyone withcompute.instances.geton the project. Store credentials in Secret Manager and fetch them at boot with the VM's service account. - Treat access tokens as the real secret. Any code on the VM can call
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/tokenwith theMetadata-Flavor: Googleheader. That is why a least-privilege service account per workload matters more than any other control on this page.
Also remove the ability to change metadata from people who do not need it: compute.instances.setMetadata and compute.projects.setCommonInstanceMetadata are effectively remote code execution permissions, because startup scripts and SSH keys are metadata. They are included in roles/compute.instanceAdmin.v1, so grant that role sparingly.
Patching, images and disk encryption
Patching. Use VM Manager OS patch management to run scheduled patch deployments and report compliance across the fleet (CIS 4.12). It needs the OS Config agent, which is installed on most Google-provided images, and the enable-osconfig=TRUE metadata key.
gcloud compute project-info add-metadata --project=prj-website-prod \
--metadata=enable-osconfig=TRUE
gcloud compute os-config patch-deployments create weekly-linux \
--project=prj-website-prod \
--file=patch-deployment.yaml
The compute.requireOsConfig constraint (managed: compute.managed.requireOsConfig) makes VM Manager enabled by default on new projects and VMs. Prefer managed instance groups built from templates, so a patched image rolls out by replacing instances.
Images. Build from Google-maintained public images or your own hardened images published to a dedicated image project. Restrict sources with compute.trustedImageProjects (managed: compute.managed.trustedImageProjects):
name: organizations/ORG_ID/policies/compute.trustedImageProjects
spec:
rules:
- values:
allowedValues:
- projects/prj-images
- projects/debian-cloud
- projects/cos-cloud
Disk encryption. Persistent disks are encrypted at rest by default with Google-managed keys. For sensitive workloads, use CMEK with --kms-key at disk or instance creation. The Compute Engine service agent (service-PROJECT_NUMBER@compute-system.iam.gserviceaccount.com) needs roles/cloudkms.cryptoKeyEncrypterDecrypter on the key. CIS 4.7 refers to customer-supplied keys (CSEK), where you send the raw key with each request; CMEK through Cloud KMS is easier to operate and is what most teams should use. Require it with the gcp.restrictNonCmekServices constraint listing compute.googleapis.com.
Logging and detection
Admin Activity audit logs for Compute Engine are always on. Alert on changes that open access paths:
v1.compute.projects.setCommonInstanceMetadataandv1.compute.instances.setMetadata(new SSH keys, startup scripts, OS Login turned off).v1.compute.instances.setServiceAccount(identity swap on a VM).v1.compute.instances.insertwith an access config (new external IP).
A log-based metric filter for instance and project metadata changes, where SSH keys and startup scripts live:
resource.type="gce_instance" OR resource.type="gce_project"
logName:"cloudaudit.googleapis.com%2Factivity"
protoPayload.methodName=("v1.compute.instances.setMetadata" OR "v1.compute.projects.setCommonInstanceMetadata")
This alerts on every metadata change, which is low volume in a well-run project. The audit entries also record which metadata keys were added or modified; inspect one in your project before narrowing the filter to ssh-keys, startup-script or enable-oslogin.
Shielded VM integrity failures:
logName="projects/PROJECT_ID/logs/compute.googleapis.com%2Fshielded_vm_integrity"
(jsonPayload.earlyBootReportEvent.policyEvaluationPassed=false
OR jsonPayload.lateBootReportEvent.policyEvaluationPassed=false)
In Security Command Center, Security Health Analytics raises the findings in the baseline table, and Event Threat Detection reports Persistence: GCE Admin Added SSH Key, Persistence: GCE Admin Added Startup Script and Persistence: Global Startup Script Added. Route these to your alerting as described in Security Command Center.
Common mistakes
- Removing Editor from the default service account in one project but leaving
iam.automaticIamGrantsForDefaultServiceAccountsunenforced, so every new project starts over. - Enabling OS Login but leaving
roles/compute.instanceAdmin.v1widely granted. Anyone with it can turn OS Login off on an instance or add a startup script. - Keeping secrets in
startup-scriptor custom metadata because it is convenient. They are visible to every process on the VM. - Granting
roles/compute.osAdminLoginat project level to individuals instead of groups at instance or folder level. - Assuming the managed constraints fix existing VMs. They block new configurations; you still need to remediate the instances already running.
- Leaving Secure Boot off because one custom image failed to boot once, instead of signing or replacing that image.
References
- Set up OS Login, Google Cloud documentation
- Service accounts for Compute Engine, Google Cloud documentation
- Shielded VM overview, Google Cloud documentation
- Confidential VM overview, Google Cloud documentation
- About VM Manager Patch, Google Cloud documentation
- Security Health Analytics findings, Google Cloud documentation
- CIS Google Cloud Platform Foundation Benchmark, Center for Internet Security
- T1552.005 Unsecured Credentials: Cloud Instance Metadata API, MITRE ATT&CK
- Privilege escalation in Google Cloud Platform, part 1, Rhino Security Labs
About the author
Florian AmetteSecurity engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.