Serverless Security Best Practices

a man with a long beard sticking his tongue out
By Yarden Sade

Updated March 13, 2024.

Serverless Security Best Practices

Serverless architectures are the present (and future) of the cloud. Unlike traditional server-based models, serverless computing removes the infrastructure layer, enabling developers to focus solely on code without managing servers. 

As of 2022, 53% of companies used serverless, a jump from the 30% who used this framework in 2020. And this growth isn’t surprising - with IT systems becoming increasingly complex, serverless takes considerable weight off devs’ shoulders. 

But the newfound freedom from infrastructure management doesn't mean serverless is impervious to security threats. From inadequate access controls to insecure function dependencies and event injection – serverless systems are far from attack-proof.

What is Serverless Architecture?

In a serverless architecture, the cloud provider dynamically manages the allocation of machine resources, freeing developers from server management and maintenance complexities. 

This model allows your applications to be broken down into individual functions that run in response to events, such as HTTP requests, database operations, or queue services. Each function is stateless and executes in a highly controlled, ephemeral environment, typically lasting only as long as the request or event is being processed.

The allure of serverless – its ability to free developers from the complexities of server management – also brings forth considerations around security. Despite the lack of traditional infrastructure to manage, the responsibility model for security shifts significantly. While cloud providers secure the infrastructure, the security of the code running in serverless functions and their interactions with other services rests entirely with the developers.

Traditional Architecture

The disillusion of serverless: flexibility, at what cost?

Serverless architecture offers unparalleled scalability and agility, freeing developers from provisioning, scaling, or maintaining servers. But this doesn’t mean it is an infrastructure-free technology. There are costs to handing the management of your infrastructure layer to a third-party cloud vendor. 

For starters, vendor lock-in limits the portability of your applications and the features you can access. Managing performance and troubleshooting issues can be challenging because you don’t have control over your infrastructure. 

While serverless architectures can be more cost-effective at scale, the pricing models based on executions, memory usage, and execution time can introduce cost unpredictability. This extends to security, where the costs of monitoring and securing your applications can vary with usage patterns.

Outsourcing infrastructure management inherently reduces visibility over the state of your systems. The lock-in effect complicates efforts to implement uniform security measures across environments or migrate services without impacting security postures. 

Serverless Security: The Top Challenges

1. Inadequate Access Controls

The decentralization of serverless architectures can lead to complex and potentially inconsistent access control implementations. The lack of stringent, function-level access controls can expose these elements to unauthorized access or privilege escalation. 

Weak Identity and Access Management components, such as deficient authentication protocols, ineffective authorization controls, and inadequate monitoring and logging, are particularly harmful when functions interact with sensitive data or other critical system components. The risk is heightened when functions are dynamically scaled.

2. Data Exposure and Insecure Storage

Serverless functions automatically scale in response to the number of requests, creating and destroying instances as needed. This dynamic environment complicates the management of access controls and encryption keys. Any misconfiguration in permissions can inadvertently expose sensitive data. 

This is compounded by their stateless nature, which requires applications to store state externally. If storage services are not adequately secured – data is at risk.

3. Insecure Function Dependencies

Dependence on third-party libraries and external APIs can be a source of vulnerabilities if not properly managed. The transient runtime environment of serverless functions exacerbates this risk, as outdated or vulnerable dependencies may not be as visible or consistently monitored as in traditional, long-running server environments. For example, an outdated version of a third-party image processing library could allow attackers to upload a specially crafted image, triggering a malicious code execution.

Establish a process for regular audits of all third-party dependencies and consider integrating automated dependency monitor tools into your development workflow.

4. Limited Visibility and Monitoring

Instead of a monolithic application running on a single server or set of servers, you have numerous functions executing in parallel, potentially across multiple regions and environments. This decentralization makes it challenging to track which function was executed in response to a specific event. 

Traditional security event tracking relies on persistent environments where logs and monitoring ages can continuously collect data. In contrast, serverless functions require specialized monitoring solutions that aggregate and analyze disparate function logs and metrics for anomaly detection and security incident identification.

5. Event Injection and Insecure Deserialization

Event-based attacks like injection and insecure deserialization exploit how serverless functions process input data. If inputs are not properly sanitized, an attacker can inject malicious code that the function executes on the backend services. Attackers can also exploit deserialization to send crafted data that, when deserialized, leads to the execution of malicious code. To combat these susceptibilities, serverless functions require strict input validation and secure coding practices to prevent unauthorized actions and code execution within the runtime environment.

Blind Lambda Event Injections without Outbound Connections

8 Best Practices for Serverless Security

1. Function Segmentation for Controlled Blast Radius

Adopt a granular approach to function deployment. By segmenting functions, you create smaller, isolated units of execution, which limits the extent of potential damage in case of a security breach. Function segmentation also affects speed, modularity, and even cost efficiency. 

For instance, separate user authentication and data processing functions ensure that a compromise in one area doesn't spill over into others. This microservices-like approach not only enhances security but also aids in easier management and scaling of applications.

2. Secure API Gateway

Establishing a fortified API gateway is key in serverless architectures, as it acts as a gatekeeper for all function invocations. Consider using advanced protocols like OAuth 2.0, which are great for thoroughly checking user or service credentials without directly exposing them. 

Moreover, integrating rate limiting can thwart DDoS attacks, and schema validation can prevent malformed requests, ensuring only legitimate and well-formed traffic reaches your serverless functions. Tools like Amazon API Gateway, Azure API Management, and Google Cloud Endpoints offer these capabilities, allowing you to set up custom authorization workflows and request validation rules that align with your security requirements.


3. Immutable Function Deployments

Enforce immutability in your serverless functions so they are not alterable at runtime. For instance, the system automatically generates a new immutable version whenever you update and publish your Lambda function in AWS Lambda. 

If you're using container images for your Lambda functions, it's essential to have these images signed. AWS facilitates this through services like AWS CodeArtifact and AWS KMS. This process entails creating a trusted artifact – your container image – and then applying a digital signature. Upon deploying the Lambda function, AWS checks this signature to confirm the image has not been tampered with. 

In Azure, leveraging Azure Container Registry for image storage facilitates the secure deployment of immutable containerized functions. With Google Cloud Platform (GCP), these functions are available through Cloud Build and Container Registry.

4. Serverless Secrets Management

Utilize specialized tools like AWS Secrets Manager or HashiCorp Vault for secrets management in your serverless environments. These tools keep sensitive data out of function code and configurations and bring advanced features to the table:

Utilize specialized tools like AWS Secrets Manager, HashiCorp Vault,  or Azure Key Vault for secrets management in your serverless environments. These tools keep sensitive data out of function code and configurations and bring advanced features to the table:

  • Automatic Rotation of Secrets – Dynamically refresh credentials and keys, following a schedule you set — perhaps every few weeks or months. Align rotation schedules with risk assessments and operational capacities to ensure credentials and keys are refreshed at appropriate intervals. This automated process dramatically reduces the risk associated with static, long-lived secrets.
  • Fine-Grained Access Policies – Implement granular access rules to dictate the exact services or functions that can interact with specific secrets. For instance, you might configure the system so that only certain microservices or specific Lambda functions in your architecture have the clearance to retrieve database passwords. 
  • Auditing Capabilities – Sophisticated monitoring capabilities enable you to see who accessed what secret and when. You can have a detailed and timestamped log of private interactions – a critical resource for maintaining compliance and quickly identifying the source and scope of any security incidents.

5. Runtime Environment Hardening

Focus on applying the principle of least privilege throughout your serverless runtime environment. This means assigning only the necessary permissions for each function's specific tasks. For instance, if you're using a platform like Google Cloud Functions, you can assign tailored roles to each function, restricting their access to other parts of the Google Cloud ecosystem.

Fine-tune the settings of your runtime environment, including specifying runtime versions, memory allocations, and execution timeouts.  Proper configuration of these settings can prevent inefficient resource usage and reduce the window of opportunity for potential attacks:

  • Always specify the runtime environment and avoid using the default or latest tag. For example, explicitly set your Node.js functions to use a specific LTS (Long-Term Support) version to ensure stability and security.
  • Monitor the memory usage of your serverless functions and adjust the allocated memory size accordingly. Over-provisioning can increase costs and extend a function’s execution time, leading to timeout-related issues. 
  • Configure function timeouts to be as short as possible. For instance, if a function typically completes within three sections, setting a timeout of 5 seconds rather than the default (which can be significantly higher) minimizes risk.

6. Serverless Code Security Testing

Like any other software, serverless applications can contain vulnerabilities that attackers may exploit. Regular security testing is necessary to pinpoint and rectify these vulnerabilities effectively. For this, you need security tools such as DAST, SAST, and/or dependency scanning.

Jit unifies code-to-cloud security tooling under a single developer UX – including SAST, secrets detection, dependency scanning, SBOM, IaC scanning, CSPM, and more. These scans are automatically invoked after every PR or deployment, ensuring that new code is vetted against potential vulnerabilities and compliance issues before it goes live. 

DevSecOps Orchestration Platform

7. Security Monitoring for Threat Detection

Signature-based detection methods offer a precise mechanism for identifying known malicious activities within serverless architectures. This technique leverages an extensive database of unique identifiers or patterns characteristic of specific security threats, such as SQL injections, cross-site scripting (XSS), or remote code execution attempts. 

By systematically scanning logs and input data against these signatures, a detection system can pinpoint activities that match known attack vectors. Upon detecting a match, the system can automatically trigger alerts and initiate predefined mitigation actions. This could involve quarantining affected functions or revoking access tokens. 

8. Automated Compliance Checks 

Due to their transient and distributed nature, traditional compliance monitoring methods fall short for serverless applications as they often assume a stable set of resources to monitor over time. To address this challenge, tools like Jit offer a sophisticated approach that automates compliance checks – particularly against dynamic and evolving standards such as GDPR, HIPAA, or PCI DSS

Jit embeds directly within your development environment, so there’s no need to navigate away from your usual environment or learn new tools. Then you can configure Jit to scan for non-compliant configurations automatically. For example, it can detect instances where S3 buckets are publicly accessible or data stores lack the required encryption standards. These scans are not just point-in-time checks – they occur continuously, verifying that compliance is maintained as the environment evolves.

Jit’s platform then goes one step further by providing code-level remediation for more than 200 IaC misconfigurations so you address these issues quickly and easily. 

Secure Your Serverless Future with Jit

By liberating developers from the intricacies of server management, serverless enables innovation and speed - two of the critical focuses of dev teams. When it comes to security, it’s essential that you take matters into your own hands, implement basic best practices, and streamline security scanning so that all grounds are covered.  

Jit’s DevSecOps platform enables you to fully automate security testing, compliance assessments, and configuration management – which makes security exceptionally easy for developers to integrate into their day-to-day routines. Jit creates pull requests for IaC misconfigurations and runtime misconfigurations (for AWS, CGP, and Azure), with easy-to-follow suggestions to address each issue. 

With a robust suite of powerful tools seamlessly integrated into the CI/CD pipeline, Jit empowers developers to easily protect their serverless environments, requiring minimal time and expertise. Explore more here.