Run Untrusted Code in AWS Lambda Without a VPS
In this article
- What "Untrusted Code" Means in This Context
- How Lambda Isolates Your Code
- Setting Up a Safe Lambda Sandbox
- Common Problems and How to Avoid Them
- Comparing Lambda to Other Sandbox Options
- Cost and Performance Considerations
- Safety and Legal Considerations
- Alternatives to Lambda for Untrusted Code
- Frequently Asked Questions
Yes, you can run untrusted code in AWS Lambda without putting it on your own VPS, by using Lambda's isolation model, short timeouts, minimal IAM permissions, and treating the function as a disposable sandbox. This article explains how to do it safely, what the real risks are, and how to avoid the common mistakes that turn a Lambda sandbox into a liability.
What "Untrusted Code" Means in This Context
Untrusted code is any code you did not write and cannot fully audit—someone else's script, a plugin, a package from an unknown author, or a snippet you copied from a forum. The danger is not just malicious intent; even well-meaning code can have bugs that consume resources, access data it shouldn't, or hang forever. In a traditional VPS, that code runs on a machine you own, with your operating system, your files, and your network. A single mistake can compromise everything else on that box.
Lambda changes that model. Each invocation runs in a fresh, short-lived container (or on a reused warm one, but still isolated from other customers). The function has no persistent filesystem unless you add one, no SSH access, and no ability to listen on network ports. The execution environment is owned and patched by AWS. You are essentially renting a tiny, disposable sandbox that disappears after the function returns.
How Lambda Isolates Your Code
Lambda functions run on AWS-managed infrastructure. Each function gets its own runtime environment, and AWS uses a combination of Firecracker microVMs and container isolation to separate customers. The key properties for running untrusted code are:
- No inbound network: Lambda cannot accept incoming TCP connections. It can only make outbound requests.
- No persistent local storage: The /tmp directory is ephemeral and only exists for the lifetime of the invocation (or warm container). It is not shared with other functions.
- Limited execution time: You set a timeout, up to 15 minutes. After that, AWS kills the execution.
- Resource caps: Memory (and proportional CPU) is fixed at invocation time. The function cannot exceed its allocated memory.
- No root access: The code runs as a non-root user. You cannot install system packages or modify the kernel.
These constraints make Lambda a reasonable sandbox for many kinds of untrusted code—provided you accept the limits. If the code needs to open a listening port, write to a database, or run for longer than 15 minutes, Lambda is not the right tool.
Setting Up a Safe Lambda Sandbox
To run untrusted code in Lambda safely, follow these steps:
- Create a dedicated IAM role with no permissions other than writing to CloudWatch Logs (for logging). Do not attach any other policies. The function should not be able to touch S3, DynamoDB, or any other AWS service unless you explicitly add a narrow policy.
- Put the function in a private VPC with no internet access (or with a NAT gateway that only allows specific destinations). This prevents the untrusted code from exfiltrating data or calling external services. If the code needs internet, use a VPC endpoint or a tightly controlled proxy.
- Set a short timeout (e.g., 10 seconds) and a low memory limit (e.g., 128 MB). This limits the blast radius if the code tries to consume resources.
- Pass input as a JSON payload and treat it as untrusted data. Validate and sanitize it before passing it to the code.
- Use a separate AWS account for the most sensitive cases. Even with a locked-down IAM role, a vulnerability in Lambda or the runtime could theoretically allow cross-account access. A dedicated account is the strongest isolation.
- Log everything and set up CloudWatch alarms for unexpected behavior (e.g., high invocation count, long durations).
Common Problems and How to Avoid Them
The most common mistake is giving the Lambda function too many permissions. A typical example: you create a function to run a user-submitted Python script, and you attach the default "Lambda basic execution role" and also add a policy that allows it to read from S3. Now the untrusted code can read any S3 bucket your account can access. The fix is to use the principle of least privilege—start with zero permissions and add only what is absolutely necessary.
Another issue is the /tmp directory. If your function uses /tmp to store intermediate files, be aware that on a warm container, /tmp persists between invocations. Untrusted code could read leftover data from a previous invocation. Always clear /tmp at the start of your function, or use a fresh container by setting a low memory (which reduces the chance of warm reuse).
Network access is a third problem. By default, Lambda functions have internet access. If you don't want the untrusted code to call out to a command-and-control server, you must place the function in a VPC without a route to the internet. But then the function cannot reach any public API either. Plan for that trade-off.
Comparing Lambda to Other Sandbox Options
Lambda is not the only way to run untrusted code. Here is how it compares to the alternatives:
- Your own VPS: Full control, but you are responsible for patching, isolation, and cleanup. A single misstep can compromise the whole machine.
- Docker containers on a server: Better isolation than a bare VPS, but you still manage the host. A kernel vulnerability could escape the container.
- Firecracker microVMs: The same technology Lambda uses, but you have to run it yourself. More setup, but more control.
- Online judges (like LeetCode): Good for small snippets, but you don't control the environment or the limits.
- Cloud sandbox services (like AWS Cloud9 or Google Colab): Convenient, but they are not designed for production untrusted code.
Lambda's advantage is that AWS manages the isolation and patching. The downside is that you have less visibility into the underlying infrastructure, and you have to work within Lambda's constraints.
Cost and Performance Considerations
Lambda pricing is based on the number of requests and the duration (in GB-seconds). For short, low-memory functions, the cost is tiny—often fractions of a cent per invocation. But if you run untrusted code that is CPU-intensive or runs for minutes, costs can add up. For example, a 1 GB function running for 5 minutes would cost about $0.008 per invocation (at the time of writing). If you invoke it a million times, that's $8,000—not trivial.
Performance is also a factor. Lambda has a cold start delay (typically 200ms to 1 second) when a new container is spun up. If your untrusted code is called frequently, you might want to keep the function warm by using a scheduled invocation or a provisioned concurrency, but that adds cost.
Safety and Legal Considerations
Running untrusted code is not just a technical problem. If the code is malicious, it could attempt to attack other systems, send spam, or mine cryptocurrency. Even if your Lambda function is locked down, the code could still use the network (if you allow it) to attack external targets. That could put you in legal trouble, even if you didn't intend it.
Also, be aware of AWS's Acceptable Use Policy. You are responsible for what your functions do. If someone submits code that violates the policy, you could have your account suspended. To mitigate this, you can add a simple content filter or rate limit, but the best defense is to not allow arbitrary network access.
Alternatives to Lambda for Untrusted Code
If Lambda's constraints are too limiting, consider these alternatives:
- A dedicated EC2 instance in a security group that only allows outbound traffic to a whitelist: More control, but you have to patch and maintain it.
- A container service like ECS or Fargate: You can run a long-lived container with a read-only filesystem and no network access.
- A serverless function with a custom runtime: Lambda supports custom runtimes, so you can use a language like Rust or Go to get better isolation.
- A third-party sandbox service: There are services that specialize in running untrusted code, but they have their own costs and limitations.
For most cases, Lambda is the simplest and most cost-effective option, as long as you accept the 15-minute limit and the lack of inbound networking.
Frequently Asked Questions
Can Lambda run code that needs a database?
Yes, but you must give the function permission to access the database (e.g., via IAM or a VPC). That means the untrusted code could potentially access that database. To reduce risk, use a separate database instance with only the necessary tables, and use short-lived credentials.
How do I prevent the code from accessing my other AWS resources?
Use a dedicated IAM role with no permissions, and place the function in a VPC without a route to the internet. Also, consider using AWS Organizations to create a separate account for the sandbox, so even if the role is misconfigured, the blast radius is limited.
What happens if the code tries to fork bomb or allocate infinite memory?
Lambda has hard limits on memory and CPU. A fork bomb would quickly hit the process limit and be killed. Memory over-allocation would result in an out-of-memory error and the invocation would fail. The function cannot affect other functions on the same host.
Can I run code that requires a specific OS or library?
Lambda supports several runtimes (Python, Node.js, Java, Go, etc.) and you can provide custom binaries in the deployment package. But you cannot install system packages at runtime. If you need a specific OS library, you must include it in the zip file, which can be tricky for compiled libraries.
Is Lambda truly safe for running code from strangers?
No system is 100% safe. Lambda's isolation is strong, but vulnerabilities have been found in the past. For highly sensitive cases, use a separate AWS account and consider using a more restrictive sandbox like Firecracker directly. For most low-risk scenarios, Lambda with a locked-down role is sufficient.