The Risk of Exposed Cloud Functions and How to Harden

6 hours ago 4

Written by: Corné de Jong


Introduction 

Mandiant security assessments frequently identify publicly exposed serverless applications that lack authentication, often as a result of specific business requirements. Serverless deployments typically run custom-developed code that incorporates third-party packages, making them targets for a wide range of application-level attacks, including:

  • Local and Remote File Inclusion (LFI/RFI)

  • Command Injection

Successful exploitation of these vulnerabilities can grant an attacker full control over the underlying container instance. Such access can serve as a foothold that may ultimately lead to a full compromise of the victim’s cloud environment.

Based on lessons learned in customer engagements, in this blog post we describe attack scenarios and provide actionable guidance on how to secure serverless environments. While this analysis focuses on hardening strategies for Google Cloud Run services and functions that must remain publicly accessible, these principles apply universally to any public serverless deployment.

What are Serverless Applications?

Serverless applications, also described as Function-as-a-Service (FaaS), allow the deployment of individual blocks of code as microservices within a flexible, decoupled, and event-driven cloud architecture without the need to manage underlying infrastructure. These services enable applications and automations to scale automatically and deploy instantly, removing operational overhead. Serverless services underpin major e-commerce, media, payment processing applications, and AI usage. 

The rapid expansion of generative AI adoption is a significant driver of increased serverless architecture use. AI workflows, including chatbot interactions, image generation, “vibe-coding”, and multi-step AI agents rely on serverless functions to complete tasks for users. This growth has made securing serverless environments a more pressing challenge for enterprise security teams. 

Risks of Serverless Application Attacks

Publicly exposed serverless workloads can serve as an initial access point for threat actors. As noted, these services may contain vulnerabilities within the code, imported packages, or the underlying runtime environment.

Once an entry point is exploited, attackers typically attempt to escalate privileges or move laterally. Common techniques observed include:

  • Extracting secrets stored directly within the application code.

  • Reviewing application logic and sensitive data to identify further attack vectors within the environment.

  • Exfiltrating service account bearer tokens from the metadata server following successful Remote Code Execution (RCE).

Leveraging these compromised secrets or service accounts allows threat actors to pivot to adjacent systems and workloads, potentially resulting in a total environment takeover if proper hardening strategies are not in place.

Example Attack Scenarios

The following simplified scenarios illustrate how serverless functions can be compromised and how attackers pivot after achieving initial code execution.

Local File Inclusion (LFI) 

In the following Cloud Run example, a Python/Flask function accepts user-controlled input to open a file without performing proper validation. This pattern is an example of a Local File Inclusion (LFI) vulnerability.

import functions_framework @functions_framework.http def hello_http(request): request_json = request.get_json(silent=True) request_args = request.args if request_json and 'file' in request_json: file = request_json['file'] elif request_args and 'file' in request_args: file = request_args['file'] # VULNERABILITY: The 'file' parameter is used directly in open() # without validation, allowing arbitrary file access with open(file, 'r') as resp: filedata = resp.read() return 'local file data {}!'.format(filedata)

Figure 1: Vulnerable Python/Flask function accepting unvalidated user input to open files

This vulnerability allows an attacker to request sensitive files from the Cloud Run instance by using curl to send a POST request via the file parameter:

curl -X POST https://cloudrun01-abc.europe-west3.run.app/ -H "Content-Type: application/json" -d '{"file": "main.py"}'

Figure 2: curl POST request targeting the file parameter

The response provides the complete main.py source code. An attacker can analyze the code for:

  • Hardcoded secrets such as API keys, database credentials, or authentication tokens

  • Business logic flaws and additional injection points

  • Internal service endpoints and architecture details

  • Import statements revealing the technology stack and potential CVE exposure

Additionally, attackers can leverage standard ../ directory traversal sequences to retrieve sensitive system files:

curl -X POST https://cloudrun01-abc.europe-west3.run.app/ -H "Content-Type: application/json" -d '{"file": "../../../etc/passwd"}'

Figure 3: curl POST request leveraging directory traversal sequences

An LFI vulnerability allows an attacker to retrieve and fuzz various files directly from the container. Key examples include:

  • requirements.txt, package.json, go.mod: Used to identify installed packages and versions with known vulnerabilities.

  • .env files: Frequently contain sensitive environment variables or hard coded secrets.

  • Application configuration files: May contain database credentials, API keys, or service endpoints if not securely managed.

  • /etc/passwd, /proc/self/environ: Contains user information, environment variables.

  • Application logs: may contain auth tokens or PII data.

Best Practice: Never store secrets or credentials within the source code or local container files. Utilize a dedicated secrets management solution, such as Secret Manager.

Code Execution/Command Injection

In the following scenario, a Python function uses shell execution methods with unsanitized user input, allowing an attacker to execute arbitrary commands.

import functions_framework import subprocess @functions_framework.http def hello_http(request): request_json = request.get_json(silent=True) request_args = request.args if request_json and 'input' in request_json: input = request_json['input'] elif request_args and 'input' in request_args: input = request_args['input'] result = subprocess.run(input, shell=True,capture_output=True, text=True) return format(result)

Figure 4: Python function utilizing shell execution with unsanitized user input

This allows an attacker to execute a subsequent curl request targeting the GCP metadata service to retrieve the service account’s bearer token. 

The following request extracts the service account's OAuth 2.0 bearer token, which remains valid for 1 hour:

curl -X POST https://cloudrun02-abc.europe-west3.run.app/ -H "Content-Type: application/json" -d "{\"input\": \"curl 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' -H 'Metadata-Flavor: Google'\"}"

Figure 5: Extraction of a GCP service account bearer token via a curl request

Once obtained, an attacker can use it on an attacker-controlled system to execute Google Cloud CLI commands. For example the CLOUDSDK_AUTH_ACCESS_TOKEN environment variable can be set using the stolen bearer token.

export CLOUDSDK_AUTH_ACCESS_TOKEN=”obtain bearer token”

Figure 6: Defining CLOUDSDK_AUTH_ACCESS_TOKEN environment variable

Attackers can then leverage Google Cloud Cloud CLI within the security context of the Cloud Run Compute service account. If deployed without best practices and thoughtful configuration controls, for example, if the  Cloud Run service runs as the default compute service account with Editor permissions, this would be equivalent to a full GCP project takeover, and allow the attacker to:

  • Read/write/delete most GCP resources

  • Deploy new services and modify existing configurations

  • Access secrets and encryption keys

  • Exfiltrate data across all accessible storage systems

  • Establish persistent backdoors through new service accounts or SSH keys.

Hardening Recommendations

Mandiant recommends that organizations implement parallel approaches for effective serverless security:

  • Secure Software Development Lifecycle (S-SDLC): integrate security scanning, code review, least-privilege IAM into CI/CD pipelines before deployment and integrate continuous security testing; 

  • Vibe Coding: Mandiant recommends multi-layered security enforcement for AI-generated code or "vibe coding." Organizations should isolate AI experimentation within dedicated sandbox environments and enforce strict data egress controls to protect production systems and internal data. Furthermore, development environments should be restricted to approved IDEs with human-in-the-loop capabilities, utilizing only verified plugins operating under least privilege to mitigate supply chain vulnerabilities. Finally, organizations must ensure this AI-generated software follows Secure Software Development Lifecycle (S-SDLC) controls while establishing clear internal guidelines regarding permitted use cases. Comprehensive security fundamentals for vibe coding are documented in detail within the Wiz Vibe Coding Security Fundamentals blog.

  • Compensating Runtime Controls: Implement the following defense-in-depth measures to limit and contain compromise even when application vulnerabilities exist;

Segregate Public Services

Host public-facing Cloud Run services consumed by untrusted external entities in a dedicated, isolated Google Cloud project. This ensures a compromise does not provide an immediate path to critical internal resources. The implementation of this 'Service Project' model is beyond the scope of this post; however, it is documented in detail within the secured serverless architecture blueprint.

Identity and Access Management (IAM)

Mandiant recommends using a custom service account for service authentication rather than the default Compute Engine service account, following the principle of least privilege. Grant only the specific permissions necessary for the Cloud Run function to operate, for example:

  • Cloud Storage Bucket Access: If the service only requires read access to objects from a Cloud Storage bucket, grant the Storage Object Viewer (roles/storage.objectViewer) role restricted to that specific bucket.

  • Secret Manager Access:  If the service requires access to secrets, grant the Secret Manager Secret Accessor (roles/secretmanager.secretAccessor) role only to the individual secrets required. For further details on secret access from Cloud Run, refer to the GCP documentation on configuring secrets.

Layer 7 Application Load Balancer (ALB) Architecture

Restrict ingress traffic for serverless functions to internal only and use an external Layer 7 ALB to manage internet exposure. This provides:

  • Centralized Traffic Management: Granular control over headers and SSL policies.

  • Cloud Armor Integration: Web Application Firewall (WAF) support to harden applications against vulnerabilities such as Local/Remote File Inclusion (LFI/RFI) and Server-Side Request Forgery (SSRF).

  • Traffic Shaping: Implementation of rate limits and request limitations to prevent abuse.

  • Enhanced Visibility: Robust logging and log-forwarding capabilities for security monitoring.

  • Identity-Aware Proxy (IAP): integration support for scenarios requiring specific identity-based authentication for internal users.

Web Application Firewall (WAF) Cloud Armor

Cloud Armor provides WAF protections that can be integrated with the Load Balancer to filter malicious traffic. The following examples demonstrate how to configure Cloud Armor security policies to block the specific local file inclusions, remote code execution and traversal attacks previously outlined.

Local File Inclusion

The lfi-v33-stable preconfigured WAF rules can block common local file inclusion attacks (local file inclusion reference).

evaluatePreconfiguredWaf('lfi-v33-stable', {'sensitivity': 3})

Figure 7: Cloud Armor lfi-v33-stable WAF rule configuration

Blocking a path traversal request ../../../etc/passwd resulting in a 403 forbidden:

curl -X POST https://exampleabc01.com -H "Content-Type: application/json" -d '{"file": "../../../etc/passwd}' <!doctype html><meta charset="utf-8"><meta name=viewport content="width=device-width, initial-scale=1"><title>403</title>403 Forbidden

Figure 8: Verification of Cloud Armor blocking path traversal request, resulting in a 403 forbidden

evaluatePreconfiguredWaf('rce-v33-stable', {'sensitivity': 3})

Figure 9: Cloud Armor rce-v33-stable WAF rule configuration

Blocking the remote code execution request from the previous example results in a 403 forbidden:

curl -X POST https://exampleabc01.com -H "Contencurl -X POST https://exampleabc01.com -H "Content-Type: application/json" -d "{\"input\": \"curl 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' -H 'Metadata-Flavor: Google'\"}" <!doctype html><meta charset="utf-8"><meta name=viewport content="width=device-width, initial-scale=1"><title>403</title>403 Forbidden

Figure 10: Verification of Cloud Armor blocking Remote Code execution, resulting in a 403 forbidden

Serverless Architecture Controls

Hardening Cloud Run services is only one part of a secure architecture. Because these services often connect to other Google Cloud resources, a single compromise can expose additional services. Implementing defense-in-depth is critical. Specifically, when using direct VPC egress or VPC Access connectors, use VPC Service Controls to restrict lateral movement and exfiltration through granular access policies.

Secure Software Development Lifecycle (S-SDLC)

While the previously outlined hardening strategies are critical, the ideal standard remains the proactive identification of vulnerabilities during the initial development stages. A deep dive into "Shift-Left" security is beyond the scope of this analysis, which focuses on mitigating risks within existing code. However, a Secure Software Development Lifecycle (S-SDLC) remains a fundamental principle. Robust code validation and continuous security testing are essential to neutralize threats before serverless functions are published externally.

Cloud Run Threat Detection

Beyond the hardening recommendations outlined in this post, Google Cloud Security Command Center (SCC) provides built-in services to detect control plane attacks against Cloud Run resources. These include detectors for credential access, reconnaissance, and the execution of scripts or reverse shells. The Cloud Run Threat Detection service is available for Premium and Enterprise tiers.

Conclusion

Serverless applications drive agility and rapid business value. While "vibe-coding" has made it easier than ever to deploy code, this breakneck speed demands that teams integrate security early in the development lifecycle, move beyond default configurations, and prioritize a defense-in-depth strategy centered on identity and architecture. 

Acknowledgements

This analysis would not have been possible without the assistance of Ischa Rijff, Phil Pearce, and Juraj Sucik.

Posted in
Read Entire Article