Skip to content

Automate remediation via Lambda functions

With SecureCloudDB and AWS Security Hub integration you will be able to automatically respond to any alert generated by developing a corresponding Lambda function and deploying it via a CloudFormation template.

SecureCloudDB remediations

We have currently developed different remediations that can be used to respond to alerts based on Security Rules.

For example, to respond to alerts generated for security rule AwsRdsEnsureDeletionProtectionIsEnabled, follow the steps below:

  1. Begin the Quick Create form

  2. Provide the VPC and IAM Configurations

  3. Acknowledge that this stack might create a new IAM role in your account (if you haven't specified one) and click Create Stack button to finish.

You can repeat the above steps for the following Security Rules:

Custom remediations

While we expand the above list of remediations, you can use them as a sample guideline to create your own remediation based on any alert generated by SecureCloudDB.

Here is an example of a CloudFormation template you can download and modify for your own needs:

  1. Make sure you have setup SecureCloudDB to publish Alerts to AWS Security Hub

  2. Write your own lambda function to address remediation of your configured alert. Check the following code snippet as an example.

    AwsRdsEnsureDeletionProtectionIsEnabled lambda function (JAVA)
    public class AwsRdsEnsureDeletionProtectionHandler implements RequestHandler<InputStream, String> {
    
      @Override
      public String handleRequest(InputStream event, Context context) {
        // Parse arn of the target resource 
        Arn arn = readResourceArnFromStream(event);
    
        // Extract instance id and region from parsed arn
        String region = arn.region().orElse("");
        String instanceIdentifier = arn.resource().resource();
    
        // Build RDS client
        RdsClient rdsClient =
            RdsClient.builder()
                .region(Region.of(region))
                .credentialsProvider(
                    AwsCredentialsProviderChain.builder()
                        .addCredentialsProvider(DefaultCredentialsProvider.create())
                        .build())
                .build();
    
        // Enable instance deletion protection
        ModifyDbInstanceRequest modifyDbInstanceRequest =
            ModifyDbInstanceRequest.builder()
                .dbInstanceIdentifier(instanceIdentifier)
                .deletionProtection(true)
                .build();
    
        rdsClient.modifyDBInstance(modifyDbInstanceRequest);
    
        return "Success!";
      }
    
      /**
       * Parses Json document to find the resource ARN, and returns the parsed ARN. Json is expected in
       * the format: { "detail": { "findings": [{ "Resources": [{ "Id": "arn" ... }] ... }] } ... }
       *
       * @param json - The input stream to read the JSON from.
       * @return - ARN of the resource in need of remediation
       */
      public static Arn readResourceArnFromStream(InputStream json) {
        Arn.Builder arn = Arn.builder();
    
        // ToDo your parsing implementation
    
        return arn.build();
      }
    }
    

    More Java examples here.

    Note

    This article is based on Java lambda functions but you can use any other language of your preference.

  3. Compile and upload your lambda to a S3 bucket.

  4. Copy the contents of the following sample CloudFormation template and save it to a file.

    AwsRdsEnsureDeletionProtectionIsEnabled CloudFormation template
    AWSTemplateFormatVersion: 2010-09-09
    Description: |
      Creates a Lambda to automatically remediate the rule RdsEnsureDeletionProtection.
    Metadata:
      'AWS::CloudFormation::Interface':
        ParameterGroups:
          - Label:
              default: 'S3 Bucket Configuration'
            Parameters:
              - remediationsS3Bucket
              - remediationsS3BucketKey
          - Label:
              default: 'VPC Configuration'
            Parameters:
              - securityGroups
              - subnets
          - Label:
              default: 'IAM Configuration'
            Parameters:
              - lambdaRoleArn
        ParameterLabels:
          remediationsS3Bucket:
            default: 'S3 Bucket with remediations.jar'
          remediationsS3BucketKey:
            default: 'S3 Key for remediations.jar'
          lambdaRoleArn:
            default: 'Lambda Role'
          securityGroups:
            default: 'Security Groups'
          subnets:
            default: 'Subnets'
      'AWS::CloudFormation::Designer':
        1330904e-6d62-47c2-895d-582a7b5f0a0a:
          size:
            width: 60
            height: 60
          position:
            x: 950
            'y': 260
          z: 0
          embeds: []
        568f783e-f78d-4ef3-a128-34020e6c9f88:
          size:
            width: 60
            height: 60
          position:
            x: 950
            'y': 150
          z: 0
          embeds: []
        3ce4c348-daac-4062-b4fb-4dea40104955:
          size:
            width: 60
            height: 60
          position:
            x: 750
            'y': 260
          z: 0
          embeds: []
        f69b304d-e360-4cda-858f-eddf3a865104:
          size:
            width: 60
            height: 60
          position:
            x: 850
            'y': 260
          z: 0
          embeds: []
          isassociatedwith:
            - 1330904e-6d62-47c2-895d-582a7b5f0a0a
    Resources:
      LambdaRole:
        Type: 'AWS::IAM::Role'
        Properties:
          Policies:
            - PolicyName: LambdaPolicy
              PolicyDocument:
                Version: 2012-10-17
                Statement:
                  - Effect: Allow
                    Action:
                      - 'rds:DescribeDBInstances'
                      - 'rds:ModifyDBInstance'
                    Resource: '*'
          AssumeRolePolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Principal:
                  Service: lambda.amazonaws.com
                Action:
                  - 'sts:AssumeRole'
          ManagedPolicyArns:
            - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
            - 'arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole'
        Metadata:
          'AWS::CloudFormation::Designer':
            id: 568f783e-f78d-4ef3-a128-34020e6c9f88
        Condition: CreateNewLambdaRole
      LambdaPermission:
        Type: 'AWS::Lambda::Permission'
        Properties:
          FunctionName: !Ref Remediation
          Action: 'lambda:InvokeFunction'
          Principal: events.amazonaws.com
          SourceArn:
            'Fn::GetAtt':
              - EventRule
              - Arn
        Metadata:
          'AWS::CloudFormation::Designer':
            id: f69b304d-e360-4cda-858f-eddf3a865104
      EventRule:
        Type: 'AWS::Events::Rule'
        Properties:
          Description: >-
            A custom rule to route SecureCloudDB findings to the corresponding
            remediation lambda.
          EventPattern:
            source:
              - aws.securityhub
            detail-type:
              - Security Hub Findings - Imported
            detail:
              findings:
                Title:
                  - awsRdsEnsureDeletionProtectionIsEnabled
          State: ENABLED
          Targets:
            - Arn:
                'Fn::GetAtt':
                  - Remediation
                  - Arn
              Id: LambdaRdsEnsureDeletionProtection
        Metadata:
          'AWS::CloudFormation::Designer':
            id: 3ce4c348-daac-4062-b4fb-4dea40104955
      Remediation:
        Type: 'AWS::Lambda::Function'
        Properties:
          Code:
            S3Bucket: !Ref remediationsS3Bucket
            S3Key: !Ref remediationsS3BucketKey
          Description: >-
            Automatically remediates the rule rdsEnsureDeletionProtectionIsEnabled by enabling
            the parameter 'deletionProtection' on the failing database instance.
          FunctionName: SecureCloudDB-rdsDeletionProtection-Remediation
          Handler: >-
            com.secureclouddb.remediations.rds.AwsRdsEnsureDeletionProtectionHandler::handleRequest
          MemorySize: 256
          Role:
            'Fn::If':
              - CreateNewLambdaRole
              - 'Fn::GetAtt':
                  - LambdaRole
                  - Arn
              - Ref: lambdaRoleArn
          Runtime: java11
          Timeout: 300
          VpcConfig:
            SecurityGroupIds: !Ref securityGroups
            SubnetIds: !Ref subnets
        Metadata:
          'AWS::CloudFormation::Designer':
            id: 1330904e-6d62-47c2-895d-582a7b5f0a0a
    Parameters:
      remediationsS3Bucket:
        Description: The S3 bucket where the remediations.jar is stored.
        Type: String
        Default: SecureCloudDB
      remediationsS3BucketKey:
        Description: The key for remediations.jar in the S3 bucket.
        Type: String
        Default: remediation/remediations.jar
      securityGroups:
        Description: Security Groups within the deployment VPC
        Type: 'List<AWS::EC2::SecurityGroup::Id>'
      subnets:
        Description: Subnets within the deployment VPC
        Type: 'List<AWS::EC2::Subnet::Id>'
      lambdaRoleArn:
        Description: >-
          Optional - A valid role Amazon Resource Name (ARN) that is used by the
          Lambda during execution. Default - A role will be created with the
          necessary permissions
        Type: String
        Default: ''
    Conditions:
      CreateNewLambdaRole:
        'Fn::Equals':
          - Ref: lambdaRoleArn
          - ''
    
  5. Modify the above CloudFormation template to meet your needs. Important sections you will need to review:

    • LambdaRole.Properties.Policies to adjust the permissions your lambda needs to fix target resource.
    • EventRule.Properties.EventPattern.detail.findings.title to configure the alert that will trigger the lambda function.

      Note

      By default, the title is the name of the Alert Policy except for Security Rules for which the title matches the Security Rule ID.

    • Remediation.Properties.Handler to configure the handler of your own lambda function.

  6. Create a new CloudFormation stack for your remediation by uploading the modified CloudFormation template. Click Next and finish configuring your stack.