Prepare and test your skills
Prepare and test your skills
Metadata security controls are the Identity and Access Management (IAM), service account, shell-access, and guest-firewall settings that limit who can manage virtual machine (VM) metadata and which processes can read it. Every Compute Engine (opens in a new tab) instance can query the metadata server (opens in a new tab) automatically without extra authorization, and the request and response never leave the physical host that runs the VM. Any process that can reach the metadata query URL can read all values on the server, including custom metadata (opens in a new tab), client certificates, and private keys, so both outside management and inside guest access must be restricted.
The metadata trust boundary is the physical host that runs the VM. Traffic between the VM and the metadata server never leaves that host, but inside the guest there is no per-user check by default. A workload on the VM can request service account tokens from the metadata server, and any local process with network access to the query URL receives the same full set of values.
Google recommends caution when writing sensitive values to metadata, sandboxing any process that should not have access, and avoiding confidential hints in service account email addresses. For example, jenkins@deployment-project-123.iam.gserviceaccount.com reveals both the project ID and that the project runs Jenkins, while deployer@deployment-project-123.iam.gserviceaccount.com avoids disclosing the software type. Viewing an allow policy in another project can expose those email addresses because many roles including basic Viewer include *.getIamPolicy permission. If a service account is granted access to a less tightly controlled project such as a sandbox or development project, its email becomes visible to a wider audience. The destination project controls the policy that grants access, not the project that owns the service account, so choose generic names when cross-project access is required.
Identity and Access Management (IAM) (opens in a new tab) controls metadata management from outside the VM at the project, zone settings, instance, and attached service account levels. Querying metadata programmatically from inside the VM requires only permission to connect to the instance, while viewing or changing metadata from the console, Google Cloud CLI, or REST API requires Compute Engine and service account permissions. When VMs use service accounts, callers also need iam.serviceAccounts.actAs on the service account or project, enforced through the Service Account User role (roles/iam.serviceAccountUser) and Compute Instance Admin (v1) role (roles/compute.instanceAdmin.v1).
The permissions for outside-VM management depend on the metadata scope:
| Metadata scope | Permission to view from outside the VM | Permission to add, update, or remove from outside the VM |
|---|---|---|
| Project metadata | compute.projects.get on the project | compute.projects.get plus compute.projects.setCommonInstanceMetadata on the project |
| Zonal metadata | compute.instanceSettings.get on the zone settings | compute.instanceSettings.get plus compute.instanceSettings.update on the zone settings |
| Instance metadata | compute.instances.get on the VM | compute.instances.get plus compute.instances.setMetadata on the VM |
Do not manage service account access at the project or folder level when least privilege is required. Granting Service Account Token Creator at the project level lets the user impersonate any service account in that project and potentially reach resources outside the project that those accounts can access. Manage access on each individual service account instead of inheriting broad access from folders or the organization node.
Shell access to a VM with a privileged service account is equivalent to the ability to act as that service account. A shell user can query the metadata server for access tokens and ID tokens, so untrusted code creates the same risk. Risky sources include application code, user-submitted server-side scripts, code pulled from remote repositories in CI/CD systems, startup and shutdown scripts from Cloud Storage, and guest policies from VM Manager. Remote code sources and storage locations must be at least as well secured as the attached service account, or an attacker can inject code that escalates privilege through the service account.
OS Login enforces a stronger binding between shell access and the service account on Linux. To connect to a VM with OS Login enabled, the user must be allowed to use OS Login and must also hold iam.serviceAccounts.actAs on the attached service account. Identity-Aware Proxy (IAP) provides an additional gate for VMs without OS Login by requiring the IAP-Secured Tunnel User role (roles/iap.tunnelResourceAccessor) only for users who should authenticate as the attached service account.
Exam tip: OS Login checks iam.serviceAccounts.actAs on every SSH connection, while metadata-based SSH keys and Windows passwords check metadata access plus iam.serviceAccounts.actAs only when the key is published or the credential is requested, with no IAM check on later logins.
The same continuous check does not apply to metadata-based SSH keys, Windows instances, custom Linux pluggable authentication modules, or Active Directory domain members. Publishing an SSH key to metadata or requesting Windows credentials requires metadata access and iam.serviceAccounts.actAs, but subsequent logins bypass IAM checks. A custom authentication module or domain membership can also admit users who lack permission to act as the service account.
In-guest access to the metadata server is unrestricted by default. Even low-privilege identities such as nobody on Linux or LocalService on Windows can obtain tokens for the attached service account. The control plane does not distinguish between the application owner and a third-party process once traffic reaches the metadata server from inside the VM.
The fix is enforced in the guest operating system firewall, which filters outbound connections to the metadata server by user or group before the request leaves the VM. On Linux, an iptables rule with --uid-owner and --gid-owner applies only to selected users or groups for outbound connections to the metadata server. On Windows, a firewall rule customized with Set-NetFirewallSecurityFilter applies only to selected users or groups. This approach lets only approved service users reach the token and metadata endpoints while blocking sandboxed or untrusted processes. Combine firewall filtering with process sandboxing when third-party code must run on the same VM as a privileged service account.
Metadata endpoints are the HTTP and HTTPS URLs that expose the same metadata entries to the VM. HTTP endpoints use http://metadata.google.internal/computeMetadata/v1, http://169.254.169.254/computeMetadata/v1, and for IPv6-only instances http://fd20:ce::254/computeMetadata/v1. Shielded VMs (opens in a new tab) additionally support HTTPS endpoints in Preview at https://metadata.google.internal/computeMetadata/v1, https://169.254.169.254/computeMetadata/v1, and https://fd20:ce::254/computeMetadata/v1, with the DNS name recommended.
Host maintenance events can interrupt the metadata server for less than one second and return HTTP Error 503. Applications that query metadata should implement retry logic so brief maintenance does not cause failure. Calls made from inside the VM do not incur egress or service charges and do not consume compute.googleapis.com rate limits, regional quotas, or global IAM API quotas, though internal throttling limits still apply. Managing metadata from outside the VM with the gcloud CLI or Compute Engine API remains subject to standard project API quotas.
Metadata storage is bounded, which affects hardening choices such as storing keys and scripts. Compute Engine enforces these limits:
ssh-keys key count toward the 256 KB value limit, so unused keys must be removed before new keys fit.Instance metadata risk is the risk that configuration and identity data served to a Compute Engine VM becomes a path to credential theft, privilege escalation, and data breach. The internal metadata service can expose service account access tokens, SSH keys, startup scripts, and network attributes during startup and runtime. Any process that can reach the metadata service inherits the identity and permissions of the attached service account, so abuse of that internal trust turns exposure into theft, then escalation, then breach.
Instance metadata is a high-value target because it directly provides the credentials that Google Cloud uses for authentication. A request from inside the VM to the metadata service can return short-lived OAuth access tokens, service account identity, and instance attributes without a password prompt. An attacker who reads that response can copy the token from memory, logs, or application output and reuse it from another machine as the VM service account.
The value increases when the attached service account is over-privileged or when instance attributes control access. Findings such as Persistence: GCE Admin Added SSH Key and Persistence: GCE Admin Added Startup Script show the persistence impact: control of instance configuration lets an attacker add an SSH key for return access or add a startup script that runs as root on every reboot. Compromised OAuth tokens stored in gcloud CLI configuration files and downloaded service account key files (opens in a new tab) create the same risk on developer workstations and shared devices.
Server-Side Request Forgery (SSRF) is the primary way an external attacker reaches an internal-only metadata service. Web Security Scanner (opens in a new tab) detects the Server side request forgery finding type for web applications. In an SSRF attack, traffic flows from the attacker to a vulnerable web application on the VM, then from that application to the metadata service, then back to the attacker in the HTTP response. The metadata service trusts the request because it comes from inside the VM network boundary, even though the attacker controls it from outside.
This bypasses the normal network trust model because the vulnerable application acts as a confused proxy. The attacker does not need inbound SSH or RDP access to the VM; the attacker only needs the application to fetch a URL the attacker supplies. Once the application fetches metadata URLs, the attacker learns tokens, project attributes, and service account email addresses that enable the next stage of impersonation and lateral movement.
Misconfigured firewall rules create external exposure by allowing inbound traffic from untrusted sources to reach the VM. Security Command Center findings (opens in a new tab) include firewall misconfigurations such as open database, mail, remote-access, and management ports. A misconfigured rule that allows inbound traffic from 0.0.0.0/0 removes the network boundary that should isolate the VM. Behavior-based scans have confirmed cases where a service was externally reachable from the public internet via port 22, which may allow unauthorized access if not properly secured.
Exploitation of external exposure has been observed leading to cloud credential harvesting and cryptocurrency mining. Examples of overly permissive access include:
Open SSH port and Open RDP port for remote server accessOpen Telnet port, Open SMTP port, and Open pop3 port for legacy and mail servicesOpen MySQL port, Open PostgreSQL port, Open OracleDB port, and Open Redis port for databasesOpen NetBIOS port for name-service and file-sharing protocolsRemediation for external exposure is to configure the instance to use only a Private IP, restrict firewall rules to block all inbound traffic from untrusted sources, create a Google Cloud Armor security policy to detect and block exploitation attempts, and enable logging and threat detection for suspicious activity.
Exam tip: An open firewall rule allows inbound traffic from the internet to the VM, while SSRF allows an already-inside application to make outbound requests to the metadata service; SSRF can steal metadata even when inbound firewall rules are correct.
Credential theft from metadata turns into a multi-step attack chain when the stolen service account has IAM permissions beyond the single VM. Event Threat Detection (opens in a new tab) tracks this progression with privilege-escalation and exfiltration findings that link a compromised identity to wider cloud access.
The attack progression follows an ordered sequence:
Privilege Escalation: Anomalous Multistep Service Account Delegation for Admin Activity, Privilege Escalation: Anomalous Multistep Service Account Delegation for Data Access, and Privilege Escalation: Suspicious Token Generation for cross-project access tokens, OpenID tokens, implicit delegation, and sign-JWT calls.Privilege Escalation: Dormant Service Account Granted Sensitive Role, Privilege Escalation: New Service Account is Owner or Editor, and Exfiltration: Cloud SQL Over-Privileged Grant.Malicious Script Executed, Malware: Bad IP, Malware: Cryptomining Bad Domain, and Malware: Outgoing DoS.Exfiltration: Cloud SQL Data Exfiltration and Exfiltration: Cloud SQL Restore Backup to External Organization.Detection responsibility depends on the layer that observes the behavior:
| Detection source | What it observes | Example metadata-related risk |
|---|---|---|
| Security Health Analytics | Configuration and firewall posture | Open SSH, RDP, or database port that allows initial access to the VM |
| Web Security Scanner | Web-application flaws | SSRF flaw that lets an external user force the app to query metadata |
| Event Threat Detection | Log-based threat behavior | Anomalous delegation, suspicious token generation, and Cloud SQL exfiltration after theft |
The chain depends on two relationships: the workflow depends on the attached service account, and the service account depends on IAM role grants. Least privilege breaks the chain by ensuring a stolen VM token grants only the smallest required roles at the smallest scope, so credential theft does not automatically become project-wide privilege escalation and data breach.
Secure access to metadata servers means only code running on the instance can reach the metadata service, while traffic from the public internet cannot reach the instance or the metadata endpoint. In Google Cloud, Compute Engine (opens in a new tab) instances obtain identity, configuration, and short-lived credentials from the link-local metadata server at 169.254.169.254, so any external reachability to the instance creates a path for credential harvesting and exfiltration. Protection therefore combines private addressing, restrictive firewall rules, egress control, and continuous monitoring to keep instance-to-metadata traffic inside the trust boundary.
Removing external reachability eliminates the internet-to-instance path that exposes metadata-mediated credentials. A behavior-based scan that finds a service externally reachable via port 22 is treated as CRITICAL with finding class EXTERNAL_EXPOSURE because unauthorized access may follow if the service is not properly secured. The remediation order is explicit:
Traffic therefore flows only from authorized internal callers to the instance, and the metadata server remains reachable only from inside that isolated instance boundary.
Virtual Private Cloud (VPC) (opens in a new tab) design provides the network boundary that keeps metadata requests on-instance and denies internet services unless specifically enabled. Custom VPC networks with custom firewall rules replace default permissive networking, so no internet gateway path exists to the instance or to 169.254.169.254 except where an explicit rule allows it. This boundary places the instance and its metadata client on the trusted side, and places untrusted internet sources on the untrusted side with no allowed ingress.
Isolation depends on a set of complementary firewall controls:
Exam tip: Configure the instance for Private IP only to remove external reachability; use restrictive firewall rules to block inbound from untrusted sources only when a public address cannot be removed.
Egress and endpoint controls ensure that even if application code is compromised, stolen metadata credentials cannot easily leave the environment. The deny-all egress rule depends on explicit allow exceptions, so outbound traffic from the compromised instance to an attacker-controlled destination is denied by default and only approved update, logging, or service endpoints are permitted. Secure metadata endpoints extend this control by requiring that metadata queries originate from the local instance network stack and include the expected validation headers, so a remote caller replaying a request without on-instance origin and headers fails validation.
The choice between addressing models determines how strong that boundary is:
| Access model | Ingress boundary | Residual risk |
|---|---|---|
| Private-IP-only instance | No public address; inbound flows only from VPC-internal sources | Lowest exposure, preferred when direct internet access is not required |
| Firewall-restricted public instance | Public address remains but firewall denies all inbound from untrusted sources | Higher operational risk because a rule error re-exposes SSH, RDP, or application ports |
Choose the private-IP-only model when workloads can operate behind NAT, Identity-Aware Proxy, or private interconnect paths, and reserve firewall-restricted public access for cases with a documented need for direct ingress. The cloud controls (opens in a new tab) for deny-all egress depend on those narrow allow exceptions to keep required services working.
Validation and monitoring confirm that firewall and endpoint controls continue to block unauthorized metadata access over time. Continuous network traffic monitoring, audit log storage, and threat detection collect flow and audit evidence from the VPC, the instance, and the security policy, and near real-time event analysis flags anomalous credential use, mining activity, or new external exposure. Protecting developer credentials (opens in a new tab) is part of the same monitoring task, since stolen tokens reused off-instance appear as anomalous use.
When a finding reappears, the workflow depends on the same containment sequence: first isolate the instance with private addressing and corrected firewall rules, then tighten the Cloud Armor policy, and only after containment re-allow narrowly scoped business traffic under change management.
iam.serviceAccounts.actAs on every SSH connection, while metadata-based SSH keys and Windows logins check it only when the key or credential is issued.OS Login checks iam.serviceAccounts.actAs on every SSH connection, while metadata-based SSH keys require metadata access plus iam.serviceAccounts.actAs only when the key is published and perform no Identity and Access Management check on later logins. Shell access to a virtual machine with a privileged service account is equivalent to the ability to act as that service account because a shell user can query the metadata server for access tokens and ID tokens.
The guest operating system firewall filters outbound connections to the metadata server by user or group before the request leaves the virtual machine, so only approved service users can reach the token and metadata endpoints while sandboxed or untrusted processes are blocked. On Linux this uses an iptables rule with --uid-owner and --gid-owner selection for outbound connections and on Windows it uses a firewall rule customized with Set-NetFirewallSecurityFilter, combined with process sandboxing when third-party code must run with a privileged service account.
Compute Engine enforces a combined total of 512 KB for all metadata entries, with each key limited to 128 bytes and each value limited to 256 KB. SSH keys stored under the ssh-keys key count toward the 256 KB value limit so unused keys must be removed before new keys fit, and startup and shutdown script contents stored directly in metadata count toward the same limits so large scripts should be hosted externally such as in Cloud Storage and downloaded by URL.
A financial enterprise is hardening its Compute Engine infrastructure in Google Cloud. Security auditors found that developers have excessive privileges that allow them to view and modify sensitive custom instance metadata keys and deploy instances using privileged workload identities.
The security engineer must implement least-privilege access controls with the following requirements:
iam.serviceAccounts.actAs).Which configuration should the security engineer implement?
Grant developers roles/compute.securityAdmin on the project, assign iam.serviceAccounts.actAs directly to developers on the project root, and disable the metadata server via firewall rules.
Grant developers a role with compute.instances.get on the VM instances, do not grant roles/iam.serviceAccountUser, and set the https://www.googleapis.com/auth/cloud-platform access scope on instances while restricting workload permissions strictly via IAM roles on the attached service account.
Grant developers roles/compute.viewer combined with roles/iam.serviceAccountAdmin on the service account, and enforce access tokens with https://www.googleapis.com/auth/devstorage.read_only scope.
Grant developers the predefined roles/compute.instanceAdmin.v1 and roles/iam.serviceAccountUser roles at the project level, and configure VM instances with the restricted https://www.googleapis.com/auth/compute.readonly access scope.
Last updated