fbpx

How to secure your SaaS tenant data in DynamoDB with ABAC and client-side encryption

If you’re a SaaS vendor, you may need to store and process personal and sensitive data for large numbers of customers across different geographies. When processing sensitive data at scale, you have an increased responsibility to secure this data end-to-end. Client-side encryption of data, such as your customers’ contact information, provides an additional mechanism that can help you protect your customers and earn their trust.

   <p>In this blog post, we show how to implement client-side encryption of your SaaS application’s tenant data in <a href="https://aws.amazon.com/dynamodb/" target="_blank" rel="noopener">Amazon DynamoDB</a> with the <a href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/index.html" target="_blank" rel="noopener">Amazon DynamoDB Encryption Client</a>. This is accomplished by leveraging <a href="https://aws.amazon.com/iam/" target="_blank" rel="noopener">AWS Identity and Access Management (IAM)</a> together with <a href="https://aws.amazon.com/kms/" target="_blank" rel="noopener">AWS Key Management Service (AWS KMS)</a> for a more secure and cost-effective isolation of the client-side encrypted data in DynamoDB, both at run-time and at rest.</p> 
   <h2>Encrypting data in Amazon DynamoDB</h2> 
   <p>Amazon DynamoDB supports data encryption at rest using encryption keys stored in AWS KMS. This functionality helps reduce operational burden and complexity involved in protecting sensitive data. In this post, you’ll learn about the benefits of adding client-side encryption to achieve end-to-end encryption in transit and at rest for your data, from its source to storage in DynamoDB. Client-side encryption helps ensure that your plaintext data isn’t available to any third party, including AWS.</p> 
   <p>You can use the Amazon DynamoDB Encryption Client to implement client-side encryption with DynamoDB. In the solution in this post, <em>client-side encryption</em> refers to the cryptographic operations that are performed on the application-side in the application’s Lambda function, before the data is sent to or retrieved from DynamoDB. The solution in this post uses the DynamoDB Encryption Client with the <a href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/direct-kms-provider.html" target="_blank" rel="noopener">Direct KMS Materials Provider</a> so that your data is encrypted by using AWS KMS. However, the underlying concept of the solution is not limited to the use of the DynamoDB Encryption Client, you can apply it to any client-side use of AWS KMS, for example using the <a href="https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html" target="_blank" rel="noopener">AWS Encryption SDK</a>.</p> 
   <p>For detailed information about using the DynamoDB Encryption Client, see the blog post <a href="https://aws.amazon.com/blogs/security/how-to-encrypt-and-sign-dynamodb-data-in-your-application/" target="_blank" rel="noopener">How to encrypt and sign DynamoDB data in your application</a>. This is a great place to start if you are not yet familiar with DynamoDB Encryption Client. If you are unsure about whether you should use client-side encryption, see <a href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/client-server-side.html" target="_blank" rel="noopener">Client-side and server-side encryption</a> in the Amazon DynamoDB Encryption Client Developer Guide to help you with the decision.</p> 
   <h2>AWS KMS encryption context</h2> 
   <p>AWS KMS gives you the ability to add an additional layer of authentication for your <a href="https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html" target="_blank" rel="noopener">AWS KMS API decrypt operations</a> by using <a href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context" target="_blank" rel="noopener">encryption context</a>. The encryption context is one or more key-value pairs of additional data that you want associated with AWS KMS protected information.</p> 
   <p>Encryption context helps you defend against the risks of ciphertexts being tampered with, modified, or replaced — whether intentionally or unintentionally. Encryption context helps defend against both an unauthorized user replacing one ciphertext with another, as well as problems like operational events. To use encryption context, you specify associated key-value pairs on encrypt. You must provide the exact same key-value pairs in the encryption context on decrypt, or the operation will fail. Encryption context is not secret, and is not an access-control mechanism. The encryption context is a means of authenticating the data, not the caller.</p> 
   <p>The <a href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/direct-kms-provider.html" target="_blank" rel="noopener">Direct KMS Materials Provider</a> used in this blog post transparently generates a unique data key by using AWS KMS for each item stored in the DynamoDB table. It automatically sets the item’s partition key and sort key (if any) as AWS KMS encryption context key-value pairs.</p> 
   <p>The solution in this blog post relies on the partition key of each table item being defined in the encryption context. If you encrypt data with your own implementation, make sure to add your tenant ID to the encryption context in all your AWS KMS API calls.</p> 
   <p>For more information about the concept of AWS KMS encryption context, see the blog post <a href="https://aws.amazon.com/blogs/security/how-to-protect-the-integrity-of-your-encrypted-data-by-using-aws-key-management-service-and-encryptioncontext/" target="_blank" rel="noopener">How to Protect the Integrity of Your Encrypted Data by Using AWS Key Management Service and EncryptionContext</a>. You can also see another example in <a href="https://document-bucket.awssecworkshops.com/encryption-context/" target="_blank" rel="noopener">Exercise 3 of the Busy Engineer’s Document Bucket Workshop</a>.</p> 
   <h2>Attribute-based access control for AWS</h2> 
   <p><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_attribute-based-access-control.html" target="_blank" rel="noopener">Attribute-based access control (ABAC)</a> is an authorization strategy that defines permissions based on attributes. In AWS, these attributes are called <em>tags</em>. In the solution in this post, ABAC helps you create tenant-isolated access policies for your application, without the need to provision tenant specific AWS IAM roles.</p> 
   <p>If you are new to ABAC, or need a refresher on the concepts and the different isolation methods, see the blog post <a href="https://aws.amazon.com/blogs/security/how-to-implement-saas-tenant-isolation-with-abac-and-aws-iam/" target="_blank" rel="noopener">How to implement SaaS tenant isolation with ABAC and AWS IAM</a>.</p> 
   <h2>Solution overview</h2> 
   <p>If you are a SaaS vendor expecting large numbers of tenants, it is important that your underlying architecture can cost effectively scale with minimal complexity to support the required number of tenants, without compromising on security. One way to meet these criteria is to store your tenant data in a single pooled DynamoDB table, and to encrypt the data using a single AWS KMS key.</p> 
   <p>Using a single shared KMS key to read and write encrypted data in DynamoDB for multiple tenants reduces your per-tenant costs. This may be especially relevant to manage your costs if you have users on your organization’s free tier, with no direct revenue to offset your costs.</p> 
   <p>When you use shared resources such as a single pooled DynamoDB table encrypted by using a single KMS key, you need a mechanism to help prevent cross-tenant access to the sensitive data. This is where you can use ABAC for AWS. By using ABAC, you can build an application with strong tenant isolation capabilities, while still using shared and pooled underlying resources for storing your sensitive tenant data.</p> 
   <p>You can find the solution described in this blog post in the <a href="https://github.com/aws-samples/aws-dynamodb-encrypt-with-abac" target="_blank" rel="noopener">aws-dynamodb-encrypt-with-abac</a> GitHub repository. This solution uses ABAC combined with KMS encryption context to provide isolation of tenant data, both at rest and at run time. By using a single KMS key, the application encrypts tenant data on the client-side, and stores it in a pooled DynamoDB table, which is partitioned by a tenant ID.</p> 
   <h3>Solution Architecture</h3> 
   <div id="attachment_27860" class="wp-caption aligncenter"> 
    <img aria-describedby="caption-attachment-27860" src="https://infracom.com.sg/wp-content/uploads/2022/12/img1-7.png" alt="Figure 1: Components of solution architecture" width="710" height="321" class="size-full wp-image-27860"> 
    <p id="caption-attachment-27860" class="wp-caption-text">Figure 1: Components of solution architecture</p> 
   </div> 
   <p>The presented solution implements an API with a single AWS Lambda function behind an <a href="https://aws.amazon.com/api-gateway/" target="_blank" rel="noopener">Amazon API Gateway</a>, and implements processing for two types of requests:</p> 
   <ol> 
    <li><span>GET</span> request: fetch any key-value pairs stored in the tenant data store for the given tenant ID.</li> 
    <li><span>POST</span> request: store the provided key-value pairs in the tenant data store for the given tenant ID, overwriting any existing data for the same tenant ID.</li> 
   </ol> 
   <p>The application is written in Python, it uses <a href="https://awslabs.github.io/aws-lambda-powertools-python/latest/" target="_blank" rel="noopener">AWS Lambda Powertools for Python</a>, and you deploy it by using the <a href="https://aws.amazon.com/cdk/" target="_blank" rel="noopener">AWS CDK</a>.</p> 
   <p>It also uses the DynamoDB Encryption Client for Python, which includes <a href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/python-using.html#python-helpers" target="_blank" rel="noopener">several helper classes</a> that mirror the AWS SDK for Python (Boto3) classes for DynamoDB. This solution uses the <a href="https://aws-dynamodb-encryption-python.readthedocs.io/en/latest/lib/encrypted/resource.html" target="_blank" rel="noopener">EncryptedResource</a> helper class which provides Boto3 compatible <span>get_item</span> and <span>put_item</span> methods. The helper class is used together with the KMS Materials Provider to handle encryption and decryption with AWS KMS transparently for the application.</p> 
   <blockquote> 
    <p><strong>Note</strong>: This example solution provides no authentication of the caller identity. See chapter “Considerations for authentication and authorization” for further guidance.</p> 
   </blockquote> 
   <h3>How it works</h3> 
   <div id="attachment_27861" class="wp-caption aligncenter"> 
    <img aria-describedby="caption-attachment-27861" src="https://infracom.com.sg/wp-content/uploads/2022/12/img2-10.png" alt="Figure 2: Detailed architecture for storing new or updated tenant data" width="760" class="size-full wp-image-27861"> 
    <p id="caption-attachment-27861" class="wp-caption-text">Figure 2: Detailed architecture for storing new or updated tenant data</p> 
   </div> 
   <p>As requests are made into the application’s API, they are routed by API Gateway to the application’s Lambda function (1). The Lambda function begins to run with the IAM permissions that its IAM execution role (DefaultExecutionRole) has been granted. These permissions do not grant any access to the DynamoDB table or the KMS key. In order to access these resources, the Lambda function first needs to assume the ResourceAccessRole, which does have the necessary permissions. To implement ABAC more securely in this use case, it is important that the application maintains clear separation of IAM permissions between the assumed ResourceAccessRole and the DefaultExecutionRole.</p> 
   <p>As the application assumes the ResourceAccessRole using <a href="https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html" target="_blank" rel="noopener">the AssumeRole</a> API call (2), it also sets a TenantID session tag. <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html" target="_blank" rel="noopener">Session tags</a> are key-value pairs that can be passed when you assume an IAM role in AWS Simple Token Service (AWS STS), and are a fundamental core building block of ABAC on AWS. When the session credentials (3) are used to make a subsequent request, the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html#AccessPolicyLanguage_RequestContext" target="_blank" rel="noopener">request context</a> includes the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag" target="_blank" rel="noopener">aws:PrincipalTag</a> context key, which can be used to access the session’s tags. The chapter “The ResourceAccessRole policy” describes how the aws:PrincipalTag context key is used in IAM policy condition statements to implement ABAC for this solution. Note that for demonstration purposes, this solution receives the value for the TenantID tag directly from the request URL, and it is not authenticated.</p> 
   <p>The trust policy of the ResourceAccessRole defines the principals that are allowed to assume the role, and to tag the assumed role session. Make sure to limit the principals to the least needed for your application to function. In this solution, the application Lambda function is the only trusted principal defined in the trust policy.</p> 
   <p>Next, the Lambda function prepares to encrypt or decrypt the data (4). To do so, it uses the DynamoDB Encryption Client. The KMS Materials Provider and the EncryptedResource helper class are both initialized with sessions by using the temporary credentials from the AssumeRole API call. This allows the Lambda function to access the KMS key and DynamoDB table resources, with access restricted to operations on data belonging only to the specific tenant ID.</p> 
   <p>Finally, using the EncryptedResource helper class provided by the DynamoDB Encryption Library, the data is written to and read from the DynamoDB table (5).</p> 
   <h3>Considerations for authentication and authorization</h3> 
   <p>The solution in this blog post intentionally does not implement authentication or authorization of the client requests. Instead, the requested tenant ID from the request URL is passed as the tenant identity. Your own applications should always authenticate and authorize tenant requests. There are multiple ways you can achieve this.</p> 
   <p>Modern web applications commonly use OpenID Connect (OIDC) for authentication, and OAuth for authorization. JSON Web Tokens (JWTs) can be used to pass the resulting authorization data from client to the application. You can validate a JWT when using AWS API Gateway with one of the following methods:</p> 
   <ol> 
    <li>When using a REST or a HTTP API, you can use a <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html" target="_blank" rel="noopener">Lambda authorizer</a></li> 
    <li>When using a HTTP API, you can use a <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html" target="_blank" rel="noopener">JWT authorizer</a></li> 
    <li>You can validate the token directly in your application code</li> 
   </ol> 
   <p>If you write your own authorizer code, you can pick a popular open source library or you can choose <a href="https://github.com/awslabs/aws-jwt-verify" target="_blank" rel="noopener">the AWS provided open source library</a>. To learn more about using a JWT authorizer, see the blog post <a href="https://aws.amazon.com/blogs/security/how-to-secure-api-gateway-http-endpoints-with-jwt-authorizer/" target="_blank" rel="noopener">How to secure API Gateway HTTP endpoints with JWT authorizer</a>.</p> 
   <p>Regardless of the chosen method, you must be able to map a suitable claim from the user’s JWT, such as the subject, to the tenant ID, so that it can be used as the session tag in this solution.</p> 
   <h3>The ResourceAccessRole policy</h3> 
   <p>A critical part of the correct operation of ABAC in this solution is with the definition of the IAM access policy for the ResourceAccessRole. In the following policy, be sure to replace <span></span>, <span></span>, <span></span>, and <span></span> with your own values.</p> 
   <div class="hide-language"> 
    <pre><code class="lang-text">{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "dynamodb:DescribeTable",
            "dynamodb:GetItem",
            "dynamodb:PutItem"
        ],
        "Resource": [
            "arn:aws:dynamodb:<span></span>:<span></span>:table/<span></span>",
       ],
        "Condition": {
            "ForAllValues:StringEquals": {
                "dynamodb:LeadingKeys": [
                    "${aws:PrincipalTag/TenantID}"
                ]
            }
        }
    },
    {
        "Effect": "Allow",
        "Action": [
            "kms:Decrypt",
            "kms:GenerateDataKey",
        ],
        "Resource": "arn:aws:kms:<span></span>:<span></span>:key/<span></span>",
        "Condition": {
            "StringEquals": {
                "kms:EncryptionContext:tenant_id": "${aws:PrincipalTag/TenantID}"
            }
        }
    }
]

}

   The policy defines two access statements, both of which apply separate ABAC conditions:</p> 
   <ol> 
    <li>The first statement grants access to the DynamoDB table with the condition that the partition key of the item matches the <span>TenantID</span> session tag in the caller’s session.</li> 
    <li>The second statement grants access to the KMS key with the condition that one of the key-value pairs in the encryption context of the API call has a key called <span>tenant_id</span> with a value that matches the <span>TenantID</span> session tag in the caller’s session.</li> 
   </ol> 
   <blockquote> 
    <p><strong>Warning</strong>: Do not use a <span>ForAnyValue</span> or <span>ForAllValues</span> set operator with the <span>kms:EncryptionContext</span> single-valued condition key. These set operators can create a policy condition that does not require values you intend to require, and allows values you intend to forbid.</p> 
   </blockquote> 
   <h2>Deploying and testing the solution</h2> 
   <h3>Prerequisites</h3> 
   <p>To deploy and test the solution, you need the following:
   <h3>Deploying the solution</h3> 
   <p>After you have the prerequisites installed, run the following steps in a command line environment to deploy the solution. Make sure that your <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html" target="_blank" rel="noopener">AWS CLI is configured</a> with your AWS account credentials. Note that standard AWS service charges apply to this solution. For more information about pricing, see the <a href="https://aws.amazon.com/pricing/" target="_blank" rel="noopener">AWS Pricing</a> page.</p> 
   <p><strong>To deploy the solution into your AWS account</strong></p> 
   <ol> 
    <li>Use the following command to download the source code: 
     <div class="hide-language"> 
      <pre><code class="lang-text">git clone https://github.com/aws-samples/aws-dynamodb-encrypt-with-abac

cd aws-dynamodb-encrypt-with-abac

    <li>(Optional) You will need an AWS CDK version compatible with the application (2.37.0) to deploy. The simplest way is to install a local copy with npm, but you can also use a globally installed version if you already have one. To install locally, use the following command to use npm to install the AWS CDK: 
     <div class="hide-language"> 
      <pre><code>npm install cdk@2.37.0</code></pre> 
     </div> </li> 
    <li>Use the following commands to initialize a Python virtual environment: 
     <div class="hide-language"> 
      <pre><code class="lang-text">python3 -m venv demoenv

source demoenv/bin/activate
python3 -m pip install -r requirements.txt

  • (Optional) If you have not used AWS CDK with this account and Region before, you first need to bootstrap the environment:
    npx cdk bootstrap
  • Use the following command to deploy the application with the AWS CDK:
    npx cdk deploy
  • Make note of the API endpoint URL https:///prod/ in the Outputs section of the CDK command. You will need this URL for the next steps.
    Outputs:
    DemoappStack.ApiEndpoint4F160690 = https:///prod/

 

   <h3>Testing the solution with example API calls</h3> 
   With the application deployed, you can test the solution by making API calls against the API URL that you captured from the deployment output. You can start with a simple HTTP POST request to insert data for a tenant. The API expects a JSON string as the data to store, so make sure to post <a href="https://www.w3schools.com/js/js_json_intro.asp" target="_blank" rel="noopener">properly formatted JSON</a> in the body of the request.</p> 
   <p>An example request using curl -command looks like:</p> 
   <div class="hide-language"> 
    <pre><code>curl https:///prod/tenant/ -X POST --data '{"email":""}'</code></pre> 
   </div> 
   <p>You can then read the same data back with an HTTP GET request:</p> 
   <div class="hide-language"> 
    <pre><code>curl https:///prod/tenant/</code></pre> 
   </div> 
   <p>You can store and retrieve data for any number of tenants, and can store as many attributes as you like. Each time you store data for a tenant, any previously stored data is overwritten.</p> 
   <h3>Additional considerations</h3> 
   <p>A tenant ID is used as the DynamoDB table’s partition key in the example application in this solution. You can replace the tenant ID with another unique partition key, such as a product ID, as long as the ID is consistently used in the IAM access policy, the IAM session tag, and the KMS encryption context. In addition, while this solution does not use a sort key in the table, you can modify the application to support a sort key with only a few changes. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html" target="_blank" rel="noopener">Working with tables and data in DynamoDB</a>.</p> 
   <h3>Clean up</h3> 
   <p>To clean up the application resources that you deployed while testing the solution, in the solution’s home directory, run the command <span>cdk destroy</span>.</p> 
   <p>Then, if you no longer plan to deploy to this account and Region using AWS CDK, you can also use the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html" target="_blank" rel="noopener">AWS CloudFormation console to delete the bootstrap stack (CDKToolKit)</a>.</p> 
   <h2>Conclusion</h2> 
   <p>In this post, you learned a method for simple and cost-efficient client-side encryption for your tenant data. By using the DynamoDB Encryption Client, you were able to implement the encryption with less effort, all while using a standard Boto3 DynamoDB Table resource compatible interface.</p> 
   <p>Adding to the client-side encryption, you also learned how to apply attribute-based access control (ABAC) to your IAM access policies. You used ABAC for tenant isolation by applying conditions for both the DynamoDB table access, as well as access to the KMS key that is used for encryption of the tenant data in the DynamoDB table. By combining client-side encryption with ABAC, you have increased your data protection with multiple layers of security.</p> 
   <p>You can start experimenting today on your own by using the provided solution. If you have feedback about this post, submit comments in the<strong> Comments</strong> section below. If you have questions on the content, consider submitting them to <a href="https://repost.aws/" target="_blank" rel="noopener">AWS re:Post</a></p> 
   <p><strong>Want more AWS Security news? Follow us on <a title="Twitter" href="https://twitter.com/AWSsecurityinfo" target="_blank" rel="noopener noreferrer">Twitter</a>.</strong>
   <!-- '"` -->