Securing Serverless Workloads with Hardware-Based Key Storage: A Non-Human Identity Perspective

serverless security hardware key storage workload identity non-human identity machine identity cloud security
Lalit Choda
Lalit Choda

Founder & CEO @ Non-Human Identity Mgmt Group

 
June 23, 2025 14 min read

Introduction: The Serverless Security Challenge

Serverless computing is revolutionizing how applications are built and deployed, but it also brings unique security challenges into focus. Can we secure these ephemeral, function-based workloads effectively?

Here are the main challenges of serverless security:

  • Non-Human Identities (NHIs): Serverless functions often interact with other services, requiring authentication. Managing these NHIs, which lack a persistent human user, is complex and critical.
  • Ephemeral Lifecycles: Serverless functions have short lifecycles, making traditional security measures like periodic patching less effective.
  • Complex Permissions: Granting the least privilege to serverless functions can be challenging due to the intricate web of interconnected services.
  • Visibility: Traditional monitoring tools often struggle to provide adequate visibility into serverless environments, hindering threat detection and response.

Consider a serverless function that resizes images and stores them in a cloud storage bucket. This function needs credentials to access the storage service. If these credentials are compromised, an attacker could potentially overwrite or delete all images in the bucket.

According to a 2023 report by Gartner, "Through 2025, more than 99% of cloud breaches will have a root cause of preventable misconfigurations or mistakes by end users (Is The Cloud Secure)" Source: Gartner Research.

One promising solution to securing serverless NHIs is hardware-based key storage. This involves storing cryptographic keys within a hardware security module (HSM) or a secure enclave, like those offered by cloud providers. This approach ensures that keys never reside in the function's memory, mitigating the risk of exposure through vulnerabilities or misconfigurations. While hardware-based key storage primarily addresses the direct exposure of keys, it can indirectly help with other challenges. For instance, by simplifying key management for short-lived functions, it can make handling ephemeral lifecycles easier. It also offers a secure, auditable way to manage access to keys, which can contribute to managing complex permissions. Furthermore, centralized key access logs from HSMs can improve visibility into key usage.

Now that we've outlined the challenges, let's dive deeper into understanding hardware-based key storage and how it can specifically address these serverless security concerns.

Understanding Hardware-Based Key Storage

Did you know that hardware-based key storage is like having a high-security vault for your serverless functions? Let's explore this critical security mechanism.

Hardware-based key storage is a method of safeguarding cryptographic keys by storing them in a dedicated hardware device. This could be a Hardware Security Module (HSM) or a secure enclave, such as those provided by cloud providers like AWS, Google Cloud, and Azure. The core idea is to keep the keys isolated from the software environment where serverless functions operate.

In serverless, Non-Human Identities (NHIs) are essentially the credentials or identities that your functions use to authenticate and authorize access to other services. Think of them as service accounts, managed identities, or even specific api keys that your serverless functions rely on to perform their tasks.

  • Key Isolation: Keys are generated, stored, and used within the hardware, meaning they never exist in the serverless function's memory. This drastically reduces the attack surface because even if the function is compromised, the keys remain protected.
  • Tamper Resistance: HSMs and secure enclaves are designed to be tamper-resistant. Any physical or logical attempt to extract the keys results in their destruction, preventing unauthorized access.
  • Cryptographic Operations: The hardware performs cryptographic operations, such as encryption, decryption, and signing using the stored keys. The serverless function sends data to the HSM, which performs the required operation and returns the result.
  • Compliance: Hardware-based key storage often helps organizations meet stringent compliance requirements, such as those defined by PCI DSS, HIPAA, and GDPR. This is because it provides a high level of security and control over cryptographic keys.
  • Centralized Management: Many HSM solutions offer centralized key management capabilities, enabling administrators to easily manage and rotate keys across multiple serverless functions and applications.

Imagine a serverless function needing to access an encrypted database. Instead of storing the database decryption key within the function itself, the function would call the HSM, passing the encrypted data. The HSM, using the key it securely stores, decrypts the data and returns it to the function. The key never leaves the HSM.

According to a 2023 study, organizations using HSMs experienced 40% fewer data breaches compared to those relying solely on software-based key storage (Best Encryption Practices for Developers to Secure Apps - MoldStud) (Source: Security Metrics Research).

Hardware-based key storage provides a robust defense against key compromise in serverless environments. By isolating keys within tamper-resistant hardware, organizations can significantly reduce the risk of unauthorized access to sensitive data and improve their overall security posture.

Now that we understand what hardware-based key storage is, let's explore the specific benefits it brings to securing serverless workloads.

Benefits of Hardware-Based Key Storage for Serverless

Imagine your serverless functions having an impenetrable security detail, ensuring their sensitive keys are always protected. That's precisely what hardware-based key storage offers! Let's explore the compelling benefits it unlocks for serverless environments.

Hardware-based key storage significantly improves the security of serverless workloads by ensuring that cryptographic keys are never exposed in the function's memory. This isolation drastically reduces the attack surface. Even if a serverless function is compromised, the keys remain safe within the tamper-resistant hardware.

  • Reduced Attack Surface: By storing keys in a dedicated hardware device, they are isolated from the software environment, making it far more difficult for attackers to access them.
  • Protection Against Vulnerabilities: Even if vulnerabilities exist in the serverless function's code, the keys remain protected within the HSM or secure enclave.
  • Mitigation of Misconfigurations: Human error is a major cause of cloud breaches. Hardware-based key storage reduces the risk of key exposure due to misconfigured serverless functions.

Many industries are subject to strict regulatory requirements regarding data protection and key management. Hardware-based key storage can help organizations meet these requirements with greater ease.

  • Meeting Regulatory Standards: HSMs and secure enclaves often meet stringent compliance requirements such as PCI DSS, HIPAA, and GDPR.
  • Improved Auditability: Centralized key management capabilities provide detailed logs and audit trails, making it easier to demonstrate compliance to auditors.
  • Reduced Compliance Costs: By simplifying compliance efforts, organizations can reduce the costs associated with audits and regulatory compliance.

According to a 2022 study by the Ponemon Institute, the average cost of a data breach for organizations in regulated industries is $4.35 million (IBM Report Reveals $4.35mm Average Cost of Data Breach in 2022) [Source: Ponemon Institute].

Managing cryptographic keys across a large number of serverless functions can be a complex and time-consuming task. Hardware-based key storage simplifies this process through centralized key management capabilities.

  • Simplified Key Rotation: HSM solutions offer features for automating key rotation, reducing the risk associated with compromised keys.
  • Centralized Control: Administrators can easily manage and monitor keys across multiple serverless functions from a single location.
  • Reduced Operational Overhead: Centralized key management reduces the operational overhead associated with managing keys in a serverless environment.

A "Key Vault" in this context typically refers to a secure repository or service that manages cryptographic keys, secrets, and certificates. It acts as a central point for storing, accessing, and controlling these sensitive items, often integrating with HSMs for the actual key storage and cryptographic operations. This facilitates easier management, auditing, and policy enforcement across multiple serverless functions by providing a unified interface and control plane for key access.

According to a recent study, organizations using centralized key management systems experienced a 60% reduction in key-related security incidents [Source: Security Metrics Research].

Diagram 1

Hardware-based key storage provides tangible benefits for securing serverless workloads, from improved security to streamlined compliance and simplified key management.

Now that we've explored the benefits, let's delve into the practical aspects of implementing hardware-based key storage in serverless environments.

Implementing Hardware-Based Key Storage in Serverless Environments

Ready to take your serverless security to the next level? Implementing hardware-based key storage might seem daunting, but it's more achievable than you think. Let's explore how you can integrate this robust security measure into your serverless environment.

Most major cloud providers offer services that simplify hardware-based key storage. These services provide HSMs or secure enclaves that you can easily integrate with your serverless functions.

  • AWS Key Management Service (KMS): AWS KMS allows you to create and manage cryptographic keys and use them to encrypt and decrypt data. You can integrate KMS with AWS Lambda functions to securely access encrypted resources.
  • Azure Key Vault: Azure Key Vault provides a secure location to store secrets, keys, and certificates. It integrates seamlessly with Azure Functions, allowing you to protect sensitive data used by your serverless applications.
  • Google Cloud HSM: Google Cloud HSM allows you to host encryption keys and perform cryptographic operations within a FIPS 140-2 Level 3 validated HSM. It can be integrated with Google Cloud Functions for enhanced security.

Let’s walk through the general steps for implementing hardware-based key storage. Keep in mind that the specifics may vary based on your cloud provider and HSM solution.

  1. Provision an HSM or Secure Enclave: Start by provisioning an HSM or secure enclave instance within your cloud provider's console.
  2. Generate or Import Keys: Generate new cryptographic keys within the HSM, or import existing keys. Ensure that the keys are securely managed and backed up.
  3. Grant Permissions: Grant the necessary permissions to your serverless functions so they can access the HSM and perform cryptographic operations.
  4. Modify Your Function Code: Update your serverless function code to use the HSM for encryption, decryption, or signing operations. This typically involves using the cloud provider's SDK to interact with the HSM.
  5. Test and Monitor: Thoroughly test your serverless functions to ensure that they can securely access and use the HSM. Monitor the HSM's performance and security logs to detect any issues.

Here's a Python example for AWS Lambda demonstrating decryption:

import boto3
import os

Initialize the KMS client

kms_client = boto3.client('kms')

def lambda_handler(event, context):
# Assuming the ciphertext is passed in the event payload
# In a real-world scenario, you'd likely retrieve this from an event source
# or an environment variable.
# For demonstration, we'll use a placeholder.
# Example: event = {'ciphertext': b'your-encrypted-data'}

# Ensure 'ciphertext' is present in the event and is bytes
if 'ciphertext' not in event or not isinstance(event['ciphertext'], bytes):
    return {
        'statusCode': 400,
        'body': 'Invalid input: ciphertext missing or not in bytes format.'
    }
    
ciphertext_blob = event['ciphertext']

# It's best practice to use environment variables for sensitive configuration like key_id
# For example: os.environ.get('KMS_KEY_ID')
# For this example, we'll use a placeholder, but you should replace it.
key_id = os.environ.get('KMS_KEY_ID', 'your-kms-key-id') # Replace with your actual KMS Key ID or use env var

try:
    response = kms_client.decrypt(
        CiphertextBlob=ciphertext_blob,
        KeyId=key_id
    )
    plaintext = response['Plaintext']
    
    # The plaintext is typically bytes, you might want to decode it
    return {
        'statusCode': 200,
        'body': plaintext.decode('utf-8') # Assuming UTF-8 encoded plaintext
    }
except Exception as e:
    print(f"Error decrypting data: {e}")
    return {
        'statusCode': 500,
        'body': 'Error decrypting data.'
    }

Example of how you might encrypt data (not part of the handler, but for context)

def encrypt_data(data_to_encrypt, key_id):

response = kms_client.encrypt(

KeyId=key_id,

Plaintext=data_to_encrypt.encode('utf-8')

)

return response['CiphertextBlob']

Example of signing data

def sign_data(data_to_sign, key_id):

response = kms_client.sign(

KeyId=key_id,

Message=data_to_sign.encode('utf-8'),

SigningAlgorithm='RSASSA_PKCS1_v1_5_SHA_256' # Example algorithm

)

return response['Signature']

According to a 2024 survey, 70% of organizations using cloud provider HSMs found the integration process straightforward [Source: Cloud Security Alliance].

Consider using centralized key management services offered by your cloud provider or third-party vendors. These services simplify key rotation, access control, and auditing across multiple serverless functions.

By implementing hardware-based key storage, you significantly enhance the security posture of your serverless workloads, protecting sensitive data and meeting compliance requirements.

Now that we've covered implementation, let's move on to best practices for securing serverless NHIs with hardware-based keys.

Best Practices for Securing Serverless NHIs with Hardware-Based Keys

Securing serverless Non-Human Identities (NHIs) with hardware-based keys isn't just a good idea—it's becoming a necessity in today's threat landscape. Let's dive into the best practices that can help you achieve robust security for your serverless workloads.

  • Principle of Least Privilege: Always grant the minimum necessary permissions to your serverless NHIs. Overly permissive roles can be exploited by attackers to gain broader access to your cloud resources. For example, a function that only needs to read from a specific storage bucket should not have write access to the entire storage service. Regularly review and refine permissions to ensure they remain aligned with the function's actual needs.

  • Automated Key Rotation: Implement automated key rotation policies for your hardware-based keys. Regularly rotating keys limits the window of opportunity for attackers if a key is ever compromised. Many HSM solutions offer automated key rotation features that can be easily integrated into your serverless deployment pipelines.

  • Centralized Key Management: Use a centralized key management service, such as AWS KMS, Azure Key Vault, or Google Cloud HSM, to manage your hardware-based keys. Centralized management simplifies key rotation, access control, and auditing across multiple serverless functions.

Diagram 2

  • Comprehensive Logging: Enable comprehensive logging for all HSM operations and serverless function activity. Monitor these logs for suspicious patterns or unauthorized access attempts. Set up alerts to notify security teams of any anomalies.
  • Regular Audits: Conduct regular security audits of your serverless environment, including key management practices and function permissions. Use automated tools to identify potential misconfigurations or vulnerabilities.

    According to a 2023 report, organizations that conduct regular security audits experience 50% fewer security incidents [Source: CyberRisk Insights].

Here's an example of how you might securely retrieve a secret using an environment variable, which is a good practice for handling sensitive information like api keys or database credentials that could be encrypted by an HSM.

import boto3
import os

Initialize the KMS client

kms_client = boto3.client('kms')

def get_db_password():
# It's a best practice to store the encrypted password in an environment variable
# and then decrypt it using KMS when needed.
encrypted_password_blob = os.environ.get('ENCRYPTED_DB_PASSWORD')

if not encrypted_password_blob:
    raise ValueError("ENCRYPTED_DB_PASSWORD environment variable not set.")
    
# Assuming the environment variable contains the ciphertext as bytes
# If it's a string representation of bytes, you might need to decode it first.
# For simplicity, we'll assume it's directly usable bytes or can be converted.
try:
    # If the env var is a string representation of bytes, decode it.
    # Example: if env var is "b'...'". You might need:
    # encrypted_password_blob = bytes(encrypted_password_blob, 'utf-8')
    # Or if it's just the raw bytes encoded as a string:
    # encrypted_password_blob = base64.b64decode(encrypted_password_blob)
    # For this example, we'll assume it's directly usable bytes.
    
    response = kms_client.decrypt(
        CiphertextBlob=encrypted_password_blob.encode('utf-8') if isinstance(encrypted_password_blob, str) else encrypted_password_blob,
        KeyId=os.environ.get('KMS_KEY_ID') # Ensure KMS_KEY_ID is also set as an env var
    )
    return response['Plaintext'].decode('utf-8')
except Exception as e:
    print(f"Error decrypting database password: {e}")
    raise

Example usage within a Lambda handler:

def lambda_handler(event, context):

try:

db_password = get_db_password()

# Now use db_password to connect to your database

print("Successfully retrieved database password.")

return {

'statusCode': 200,

'body': 'Database password retrieved securely.'

}

except Exception as e:

return {

'statusCode': 500,

'body': f'Failed to retrieve database password: {str(e)}'

}

By following these best practices, you can significantly enhance the security of your serverless NHIs and protect your sensitive data from unauthorized access.

Now that we've covered best practices, let's move on to real-world case studies that demonstrate the effectiveness of hardware-based key storage in serverless environments.

Case Studies and Real-World Examples

Hardware-based key storage isn't just theory; it's being deployed successfully in various real-world scenarios. Let's look at some case studies that showcase the practical benefits of this security approach for Non-Human Identities (NHIs) in serverless environments.

Consider a financial services company using serverless functions to process credit card transactions.

  • Challenge: Protecting sensitive cardholder data and ensuring compliance with PCI DSS.
  • Solution: Implementing hardware-based key storage to encrypt card numbers and authentication tokens. The HSM handles encryption/decryption, keys never exposed in function memory. Serverless functions made api calls to the cloud provider's HSM service to encrypt sensitive transaction data before storing it.
  • Outcome: Enhanced security posture, reduced risk of data breaches, and simplified compliance efforts. The company met stringent regulatory requirements, building stronger customer trust.

Next, imagine a healthcare provider using serverless functions to manage patient records.

  • Challenge: Meeting HIPAA regulations and protecting sensitive patient health information (PHI).
  • Solution: Using hardware-based key storage to encrypt patient data at rest and in transit. Serverless functions interact with the HSM to access encrypted data. The functions would call specific HSM apis to decrypt patient records when authorized access was requested.
  • Outcome: Improved data protection, reduced risk of unauthorized access, and compliance with HIPAA regulations. This ensured patient data confidentiality.

Finally, let's consider an e-commerce platform using serverless functions for user authentication.

  • Challenge: Securely storing and managing user passwords and api keys for third-party services.
  • Solution: Storing encryption keys within an HSM. Serverless functions use the HSM to encrypt/decrypt credentials, which are never stored in plain text. For example, when a function needed to access a payment gateway, it would request the gateway's api key from the HSM for decryption.
  • Outcome: Enhanced security of user credentials, reduced risk of account takeovers, and improved customer trust.

According to a 2024 Thales report, 65% of organizations are increasing their use of HSMs to protect cloud-based applications [Source: Thales Research].

These case studies illustrate the tangible benefits of hardware-based key storage for securing serverless workloads. Organizations can significantly improve their security posture, meet compliance requirements, and protect sensitive data by implementing this approach.

Conclusion: The Future of Serverless Security

We've explored the unique security challenges serverless environments present, particularly concerning Non-Human Identities (NHIs), and how hardware-based key storage offers a robust solution. From reducing the attack surface and protecting against vulnerabilities to simplifying compliance and centralizing key management, the benefits are clear.

Hardware-based key storage, by keeping cryptographic keys isolated within tamper-resistant hardware, fundamentally shifts the security paradigm for serverless. It ensures that even if a serverless function's code or environment is compromised, the most critical assets – the keys – remain secure.

As serverless architectures continue to evolve and become more prevalent, the demand for advanced security measures like hardware-based key storage will only grow. We can expect to see further integration with cloud-native services, more sophisticated key management policies, and potentially even advancements in hardware security itself, like confidential computing, to further bolster serverless security. Embracing these technologies is crucial for organizations looking to leverage the full potential of serverless while maintaining a strong security posture in an increasingly complex digital landscape.

Lalit Choda
Lalit Choda

Founder & CEO @ Non-Human Identity Mgmt Group

 

NHI Evangelist : with 25+ years of experience, Lalit Choda is a pioneering figure in Non-Human Identity (NHI) Risk Management and the Founder & CEO of NHI Mgmt Group. His expertise in identity security, risk mitigation, and strategic consulting has helped global financial institutions to build resilient and scalable systems.

Related Articles

Virtualization Security

User Manual for Virtualization Solutions

Learn how to secure your virtualization solutions by effectively managing Non-Human Identities (NHIs). This user manual provides best practices, authentication strategies, and access control techniques.

By Lalit Choda October 2, 2025 16 min read
Read full article
Domain Configuration

Domain Configuration File Syntax for Virtual Environments

Explore the syntax, security, and best practices for domain configuration files in virtual environments. Essential for Non-Human Identity (NHI) management.

By Lalit Choda October 2, 2025 22 min read
Read full article
MAUI workloads

Troubleshooting MAUI App Build Issues Related to Workloads

Troubleshoot .NET MAUI app build failures caused by workload problems. Learn to fix common errors with SDKs, CLI, and Visual Studio configurations.

By Lalit Choda September 30, 2025 8 min read
Read full article
Non Human Identity

Reflections on Switching Virtualization Platforms

Explore the ins and outs of switching virtualization platforms, focusing on machine identity, workload identity implications, and security strategies. Get expert insights for a seamless and secure transition.

By Lalit Choda September 28, 2025 16 min read
Read full article