Skip to content

11Compute and containersService 11 of 13

Compute Enginesecurity hardening

Harden Compute Engine VMs: dedicated service accounts, OS Login with 2SV, no external IPs, Shielded and Confidential VM, serial port, patching and CMEK disks.

Baseline
12 controls
Category
Compute and containers
Updated
Reading
10 min read

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.

ControlWhyHow to checkCIS / SCC
Use a dedicated service account per workloadThe default SA often holds Editorgcloud compute instances list --format="value(name,serviceAccounts[].email)"CIS 4.1, DEFAULT_SERVICE_ACCOUNT_USED
Never pair the default SA with full API scopeToken can call every API as EditorScopes column in gcloud compute instances describeCIS 4.2, FULL_API_ACCESS
Enable OS LoginSSH access becomes IAM, not metadatagcloud compute project-info describeCIS 4.4, OS_LOGIN_DISABLED
Block project-wide SSH keysOne key must not open every VMblock-project-ssh-keys metadataCIS 4.3, COMPUTE_PROJECT_WIDE_SSH_KEYS_ALLOWED
Disable serial port accessBypasses network controlsserial-port-enable metadataCIS 4.5, COMPUTE_SERIAL_PORTS_ENABLED
Disable IP forwardingVM could route traffic it should not--filter="canIpForward=true"CIS 4.6, IP_FORWARDING_ENABLED
Enable Shielded VM with Secure BootBlocks bootkits and unsigned kernelsshieldedInstanceConfig in describeCIS 4.8, SHIELDED_VM_DISABLED, COMPUTE_SECURE_BOOT_DISABLED
Remove external IP addressesFewer internet-reachable hosts--filter="networkInterfaces.accessConfigs:*"CIS 4.9, PUBLIC_IP_ADDRESS
Use Confidential VM for sensitive dataEncrypts memory in useconfidentialInstanceConfig in describeCIS 4.11, CONFIDENTIAL_COMPUTING_DISABLED
Patch with VM ManagerKnown CVEs are the easiest way inVM Manager > Patch complianceCIS 4.12
Encrypt sensitive disks with CMEKYou control and can revoke the keydiskEncryptionKey on the diskDISK_CMEK_DISABLED
Restrict images to trusted projectsStops unvetted public imagescompute.trustedImageProjects policyn/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:

RoleGrants
roles/compute.osLoginLog in as a standard user
roles/compute.osAdminLoginLog in with sudo
roles/compute.osLoginExternalUserNeeded 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 constraint compute.vmExternalIpAccess): deny external IPv4 addresses, with tag-based exemptions for the VMs that genuinely need one.
  • compute.managed.vmCanIpForward (legacy compute.vmCanIpForward): deny IP forwarding except on tagged appliances.
  • compute.managed.disableSerialPortAccess (legacy compute.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-script values are readable by any process on the VM and by anyone with compute.instances.get on 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/token with the Metadata-Flavor: Google header. 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.setCommonInstanceMetadata and v1.compute.instances.setMetadata (new SSH keys, startup scripts, OS Login turned off).
  • v1.compute.instances.setServiceAccount (identity swap on a VM).
  • v1.compute.instances.insert with 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.automaticIamGrantsForDefaultServiceAccounts unenforced, so every new project starts over.
  • Enabling OS Login but leaving roles/compute.instanceAdmin.v1 widely granted. Anyone with it can turn OS Login off on an instance or add a startup script.
  • Keeping secrets in startup-script or custom metadata because it is convenient. They are visible to every process on the VM.
  • Granting roles/compute.osAdminLogin at 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

About the author

Security engineer writing practical, benchmark-aligned guides to hardening Google Cloud organizations, projects and workloads.

Related services

All services