Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

AWS Config: recording, rules, remediation and conformance packs

Use AWS Config to record how every Harbourline resource is configured over time, evaluate it continuously against managed and custom rules, auto-remediate drift, and package controls as conformance packs that produce audit evidence.

intermediate⏱ 2 h 🟡 Low costSCS-C03SAA-C03SOA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.ConfigService 4.1.1) · Amazon.Lambda.Core 3.4.0 · AWS CLI v2 · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Explain what AWS Config records — configuration items, configuration history and relationships — and choose between continuous and periodic recording and which resource types to record.
  • Deploy AWS managed rules, write a custom Lambda rule in C# and a Guard custom policy rule, and explain change-triggered versus periodic evaluation.
  • Attach automatic remediation using Systems Manager Automation documents, with safe retry limits.
  • Deploy conformance packs (including the sample "Operational Best Practices for PCI DSS" template) to one account or a whole organisation, and use aggregators for a multi-account view.
  • Estimate Config's cost and avoid the classic "recorder on everything" bill.

Prerequisites

Why this matters in banking

Harbourline's security standard says "databases must never be reachable from the internet" and "every S3 bucket holding customer data must block public access and use KMS encryption". Writing the standard is easy. Proving it — continuously, in 120 accounts, with history — is the hard part.

Three scenarios show the gap:

  1. Drift. A developer debugging at 2 a.m. opens port 5432 to 0.0.0.0/0 on a security group "just for ten minutes" and forgets. Preventive controls (SCPs, IaC review) didn't catch it because it was a console change in a sandbox that was later peered with a production-like VPC.
  2. Audit evidence. The PCI QSA asks: "Show me that the cardholder-data-environment security groups were compliant throughout the assessment period, and show me every change." Screenshots from today don't prove last March.
  3. Incident reconstruction. After an incident, investigators need to know what a resource looked like at 14:05 last Tuesday, and what it was connected to.

AWS Config records configuration state and its history, evaluates it against rules, and keeps a timeline of compliance. Note what has changed in 2026: AWS Audit Manager no longer onboards new accounts (since 2026-04-30), and AWS points customers to Config conformance packs, Control Tower controls and Security Hub CSPM standards for control evidence. There is no GDPR conformance pack, so UK GDPR evidence remains a compliance-led activity that Config only partly supports.

The idea in plain language

AWS Config does three things:

  1. Records. The configuration recorder watches supported resources and writes a configuration item (CI) each time one changes: a JSON snapshot of the resource's settings, its relationships (this security group is attached to these ENIs), and a link to the CloudTrail event that caused the change.
  2. Evaluates. Config rules check CIs against a desired state and mark each resource COMPLIANT, NON_COMPLIANT or NOT_APPLICABLE. Rules can run when a resource changes (change-triggered), on a schedule (periodic), or both. Since 2022, some rules can also run in proactive mode against a resource before it's deployed (for example, from CloudFormation hooks).
  3. Reports and fixes. Compliance history is stored; remediation can call an SSM Automation document to fix a resource automatically or on approval; conformance packs bundle many rules and remediations into one deployable unit; aggregators show compliance across accounts and Regions.

Analogy: If CloudTrail is CCTV ("who walked into the vault at 14:05"), AWS Config is the vault's inventory ledger with photos: every time something is moved, a dated photo of the shelf is filed, and an inspector checks each photo against the rulebook ("cash bags must be sealed") and marks it pass or fail.

What problem the AWS service solves

ConceptWhat it isNotes (checked 2026-11-18)
Configuration recorderRecords CIs for selected resource types in one RegionOne customer-managed recorder per Region per account; can record all supported types, a list, or all with exclusions
Recording frequencyContinuous (every change) or periodic (at most one CI per resource per 24 hours, only if changed)Can be overridden per resource type
Delivery channelWhere snapshots and history go: S3 bucket, optional SNS topicIn an organisation, point it at the log-archive account
Configuration itemJSON state of one resource at one time, plus relationships and related eventsSupplementary configuration holds extra details (for example S3 bucket policies and versioning)
Managed ruleAWS-written rule identified by a source identifier, e.g. S3_BUCKET_PUBLIC_READ_PROHIBITEDHundreds available; some take parameters
Custom Lambda ruleYour Lambda receives the CI and returns evaluations with PutEvaluationsFull flexibility, you own the code
Custom policy rule (Guard)Rule written in AWS CloudFormation Guard DSL, run by ConfigNo Lambda to maintain; initiated by configuration changes (no periodic trigger)
RemediationSSM Automation document run on non-compliant resourcesManual or automatic, with retry limits
Conformance packYAML template of rules (+ remediations) deployed as one unitSample templates for PCI DSS, NIST, CIS, FSBP-style controls and more
AggregatorRead-only multi-account, multi-Region view of config and complianceOrganisation-wide via AWS Organizations

Honest limitations:

  • Not real-time enforcement. Config detects after the fact (usually within minutes). It doesn't block a change — that's SCPs, IAM, CloudFormation hooks and proactive rules.
  • Coverage gaps. Not every resource type or property is recorded. Check the supported resource types list before you rely on a rule.
  • Cost scales with change volume. Auto Scaling groups, ephemeral containers and noisy resources can generate millions of CIs. Choose the recorded types and recording frequency deliberately.
  • Rules are only as good as their logic. A COMPLIANT result means "passed this check", not "secure" and certainly not "PCI compliant".

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure Resource Graph + change historyAWS Config configuration items and historyConfig history is per resource and recorded only for the types you choose
Azure Policy (audit / auditIfNotExists effects)Config rulesConfig rules evaluate; prevention is SCPs/RCPs, IAM or CloudFormation hooks, not Config
Azure Policy deployIfNotExists / remediation tasksConfig remediation with SSM AutomationRemediation runs an Automation document with an IAM role you provide
Azure Policy initiatives (e.g. PCI DSS v4 built-in initiative)Conformance packs (e.g. Operational Best Practices for PCI DSS)AWS sample packs are mappings, not certification
Azure Policy custom definitions (JSON)Custom Lambda rules (any language) or Guard rulesYou can write rules in C#
Management-group policy assignmentOrganisation conformance packs and organisation rulesDeployed from the management or a delegated administrator account
Defender for Cloud regulatory compliance dashboardSecurity Hub CSPM standards (uses Config under the hood)Security Hub CSPM's controls use service-linked Config rules — see Security Hub, GuardDuty, Inspector and Detective

Architecture

Who owns what: platform/security teams own the recorder, the delivery channel and organisation conformance packs (deployed from a delegated administrator account), so workload teams can't switch them off — back that up with an SCP denying config:StopConfigurationRecorder, config:DeleteConfigurationRecorder and config:DeleteDeliveryChannel. Workload teams can add their own rules in their accounts.

Evaluation flow for a change-triggered custom rule

Step-by-step implementation

Decide what to record

Start from your controls. If the standard covers security groups, S3 buckets, IAM, RDS, KMS keys and CloudTrail, record those types continuously. Record high-churn types (EC2 instances in Auto Scaling groups, ENIs in busy ECS clusters) periodically or not at all, unless a control needs them. Record global resources (IAM) in one Region only.

Set up the recorder and delivery channel

Create an IAM role with the AWS managed policy AWS_ConfigRole (or use the service-linked role), the recorder, and a delivery channel to an S3 bucket. In an organisation, deliver to the log-archive account bucket. Start the recorder.

Add managed rules for the baseline

Pick managed rules that map to your standard: S3_BUCKET_PUBLIC_READ_PROHIBITED, S3_BUCKET_SSL_REQUESTS_ONLY, RDS_STORAGE_ENCRYPTED, RDS_INSTANCE_PUBLIC_ACCESS_CHECK, INCOMING_SSH_DISABLED, CLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED, ACCESS_KEYS_ROTATED, ROOT_ACCOUNT_MFA_ENABLED. Use parameters (for example maxAccessKeyAge = 90).

Write custom rules for bank-specific controls

Where no managed rule exists, write one. Example: "no security group may allow database ports (1433, 3306, 5432) from 0.0.0.0/0 or ::/0" — the C# rule in this lesson. For simple property checks, prefer a Guard rule: no code to patch.

Add remediation carefully

Start with manual remediation (a button in the console, or a ticket). Turn on automatic remediation only for fixes that can't break production — for example turning on S3 Block Public Access on a bucket tagged DataClass=customer. Set MaximumAutomaticAttempts and RetryAttemptSeconds so a failing remediation doesn't loop.

Package as conformance packs

Put the rules (and remediations) in a conformance pack YAML stored in Git. Deploy it to all accounts with an organisation conformance pack from a delegated administrator. Version it like code.

Aggregate and alert

Create an organisation aggregator in the security tooling account. Send Config Rules Compliance Change events for critical rules to the SOC via EventBridge. Feed Config-based controls into Security Hub CSPM.

Produce evidence on a schedule

Each month, export compliance summaries and conformance pack compliance scores, and keep them with the change records. That's the evidence the auditor asks for (more in the Part 6 audit-evidence lesson listed in the module overview).

AWS Console instructions

  1. Console → AWS Config → Get started (first time) or Settings → Edit.
  2. Recording strategy: choose Specific resource types. Add AWS::EC2::SecurityGroup and AWS::S3::Bucket, frequency Continuous.
  3. Data governance: retention 7 years is the default; for the lab choose a short period ⚠ VERIFY the minimum allowed value. IAM role: use the service-linked role.
  4. Delivery method: create a bucket hl-m05-config-<account-id>.
  5. Rules: skip in the wizard, then Rules → Add rule → AWS managed rule → search s3-bucket-public-read-prohibited → Save. Repeat for restricted-ssh (source identifier INCOMING_SSH_DISABLED).
  6. Resources → filter by type AWS::EC2::SecurityGroup → open one → Resource timeline shows each CI and the CloudTrail event that caused it.
  7. Conformance packs → Deploy conformance pack → Use sample template → Operational Best Practices for PCI DSS (read the template first: it contains many rules, each billed per evaluation).

AWS CLI

PROFILE=learn-sandbox
ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile $PROFILE)

# 0. Service-linked role for Config (idempotent; errors if it already exists)
aws iam create-service-linked-role --aws-service-name config.amazonaws.com --profile $PROFILE

# 1. Recorder: only two resource types, continuous recording
aws configservice put-configuration-recorder --profile $PROFILE \
  --configuration-recorder "name=default,roleARN=arn:aws:iam::$ACCOUNT:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig" \
  --recording-group '{"allSupported":false,"includeGlobalResourceTypes":false,"resourceTypes":["AWS::EC2::SecurityGroup","AWS::S3::Bucket"]}' \
  --recording-mode '{"recordingFrequency":"CONTINUOUS"}'

# 2. Delivery channel to a bucket you created with the standard Config bucket policy
aws configservice put-delivery-channel --profile $PROFILE \
  --delivery-channel "name=default,s3BucketName=hl-m05-config-$ACCOUNT"

aws configservice start-configuration-recorder --configuration-recorder-name default --profile $PROFILE

# 3. Managed rules
aws configservice put-config-rule --profile $PROFILE --config-rule '{
  "ConfigRuleName": "hl-s3-bucket-public-read-prohibited",
  "Source": {"Owner": "AWS", "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED"},
  "Scope": {"ComplianceResourceTypes": ["AWS::S3::Bucket"]}
}'
aws configservice put-config-rule --profile $PROFILE --config-rule '{
  "ConfigRuleName": "hl-restricted-ssh",
  "Source": {"Owner": "AWS", "SourceIdentifier": "INCOMING_SSH_DISABLED"},
  "Scope": {"ComplianceResourceTypes": ["AWS::EC2::SecurityGroup"]}
}'

# 4. Guard custom policy rule: S3 buckets must have versioning enabled
aws configservice put-config-rule --profile $PROFILE --config-rule '{
  "ConfigRuleName": "hl-s3-versioning-guard",
  "Scope": {"ComplianceResourceTypes": ["AWS::S3::Bucket"]},
  "Source": {
    "Owner": "CUSTOM_POLICY",
    "SourceDetails": [{"EventSource": "aws.config", "MessageType": "ConfigurationItemChangeNotification"},
                      {"EventSource": "aws.config", "MessageType": "OversizedConfigurationItemChangeNotification"}],
    "CustomPolicyDetails": {
      "PolicyRuntime": "guard-2.x.x",
      "PolicyText": "rule s3_versioning when resourceType == \"AWS::S3::Bucket\" { supplementaryConfiguration.BucketVersioningConfiguration.status == \"Enabled\" }",
      "EnableDebugLogDelivery": false
    }
  }
}'

# 5. Re-evaluate on demand and read results
aws configservice start-config-rules-evaluation --config-rule-names hl-restricted-ssh hl-s3-bucket-public-read-prohibited --profile $PROFILE
aws configservice describe-compliance-by-config-rule --profile $PROFILE \
  --query "ComplianceByConfigRules[].{Rule:ConfigRuleName,Status:Compliance.ComplianceType}"
aws configservice get-compliance-details-by-config-rule --config-rule-name hl-restricted-ssh \
  --compliance-types NON_COMPLIANT --profile $PROFILE \
  --query "EvaluationResults[].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId"

# 6. What did this security group look like over time?
aws configservice get-resource-config-history --resource-type AWS::EC2::SecurityGroup \
  --resource-id sg-0123456789abcdef0 --limit 5 --profile $PROFILE \
  --query "configurationItems[].{Time:configurationItemCaptureTime,Status:configurationItemStatus}"

# 7. Advanced query (SQL-like) across recorded resources
aws configservice select-resource-config --profile $PROFILE --expression \
  "SELECT resourceId, configuration.groupName WHERE resourceType = 'AWS::EC2::SecurityGroup' AND configuration.ipPermissions.ipRanges.cidrIp = '0.0.0.0/0'"

# 8. Remediation: auto-enable S3 Block Public Access on non-compliant buckets (max 3 tries, 60 s apart)
aws configservice put-remediation-configurations --profile $PROFILE --remediation-configurations '[{
  "ConfigRuleName": "hl-s3-bucket-public-read-prohibited",
  "TargetType": "SSM_DOCUMENT",
  "TargetId": "AWSConfigRemediation-ConfigureS3BucketPublicAccessBlock",
  "Automatic": true,
  "MaximumAutomaticAttempts": 3,
  "RetryAttemptSeconds": 60,
  "Parameters": {
    "AutomationAssumeRole": {"StaticValue": {"Values": ["arn:aws:iam::'"$ACCOUNT"':role/hl-m05-config-remediation"]}},
    "BucketName": {"ResourceValue": {"Value": "RESOURCE_ID"}}
  }
}]'

# 9. Conformance pack from a local template
aws configservice put-conformance-pack --conformance-pack-name hl-m05-baseline \
  --template-body file://hl-baseline-pack.yaml --profile $PROFILE
aws configservice get-conformance-pack-compliance-summary --conformance-pack-names hl-m05-baseline --profile $PROFILE
hl-baseline-pack.yaml
# Harbourline baseline conformance pack (lab subset). Each rule is billed per evaluation.
Parameters:
  MaxAccessKeyAge:
    Type: String
    Default: "90"
Resources:
  S3PublicReadProhibited:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: hl-cp-s3-public-read-prohibited
      Scope:
        ComplianceResourceTypes: ["AWS::S3::Bucket"]
      Source:
        Owner: AWS
        SourceIdentifier: S3_BUCKET_PUBLIC_READ_PROHIBITED
  S3SslRequestsOnly:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: hl-cp-s3-ssl-requests-only
      Scope:
        ComplianceResourceTypes: ["AWS::S3::Bucket"]
      Source:
        Owner: AWS
        SourceIdentifier: S3_BUCKET_SSL_REQUESTS_ONLY
  RestrictedSsh:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: hl-cp-restricted-ssh
      Scope:
        ComplianceResourceTypes: ["AWS::EC2::SecurityGroup"]
      Source:
        Owner: AWS
        SourceIdentifier: INCOMING_SSH_DISABLED
  AccessKeysRotated:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: hl-cp-access-keys-rotated
      InputParameters:
        maxAccessKeyAge:
          Ref: MaxAccessKeyAge
      Source:
        Owner: AWS
        SourceIdentifier: ACCESS_KEYS_ROTATED
      MaximumExecutionFrequency: TwentyFour_Hours

For an organisation, the same template is deployed with aws configservice put-organization-conformance-pack --organization-conformance-pack-name hl-baseline --template-body file://hl-baseline-pack.yaml from the management or delegated administrator account.

Infrastructure as Code

ConfigBaselineStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Config;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AWS.S3;
using Constructs;

namespace Harbourline.Security.Infra;

public sealed class ConfigBaselineStack : Stack
{
    public ConfigBaselineStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        Tags.SetTag("Project", "cea-lab");
        Tags.SetTag("Lab", "m05-l18");
        Tags.SetTag("Environment", "learn");

        // --- Recorder + delivery channel (skip if Config is already set up in the account) ---
        var bucket = new Bucket(this, "ConfigBucket", new BucketProps
        {
            BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
            Encryption = BucketEncryption.S3_MANAGED,
            EnforceSSL = true,
            RemovalPolicy = RemovalPolicy.DESTROY,  // learning shortcut
            AutoDeleteObjects = true,
        });
        bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps
        {
            Principals = [new ServicePrincipal("config.amazonaws.com")],
            Actions = ["s3:GetBucketAcl", "s3:ListBucket"],
            Resources = [bucket.BucketArn],
            Conditions = new Dictionary<string, object> { ["StringEquals"] = new Dictionary<string, string> { ["AWS:SourceAccount"] = Account } },
        }));
        bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps
        {
            Principals = [new ServicePrincipal("config.amazonaws.com")],
            Actions = ["s3:PutObject"],
            Resources = [bucket.ArnForObjects($"AWSLogs/{Account}/Config/*")],
            Conditions = new Dictionary<string, object>
            {
                ["StringEquals"] = new Dictionary<string, string> { ["s3:x-amz-acl"] = "bucket-owner-full-control", ["AWS:SourceAccount"] = Account },
            },
        }));

        var recorderRole = new Role(this, "RecorderRole", new RoleProps
        {
            AssumedBy = new ServicePrincipal("config.amazonaws.com"),
            ManagedPolicies = [ManagedPolicy.FromAwsManagedPolicyName("service-role/AWS_ConfigRole")],
        });

        var recorder = new CfnConfigurationRecorder(this, "Recorder", new CfnConfigurationRecorderProps
        {
            RoleArn = recorderRole.RoleArn,
            RecordingGroup = new CfnConfigurationRecorder.RecordingGroupProperty
            {
                AllSupported = false,
                IncludeGlobalResourceTypes = false,
                ResourceTypes = ["AWS::EC2::SecurityGroup", "AWS::S3::Bucket"],
            },
            RecordingMode = new CfnConfigurationRecorder.RecordingModeProperty { RecordingFrequency = "CONTINUOUS" },
        });
        var channel = new CfnDeliveryChannel(this, "Channel", new CfnDeliveryChannelProps { S3BucketName = bucket.BucketName });

        // --- Managed rule ---
        var publicRead = new ManagedRule(this, "S3PublicRead", new ManagedRuleProps
        {
            ConfigRuleName = "hl-s3-bucket-public-read-prohibited",
            Identifier = ManagedRuleIdentifiers.S3_BUCKET_PUBLIC_READ_PROHIBITED,
            RuleScope = RuleScope.FromResources([ResourceType.S3_BUCKET]),
        });

        // --- Custom Lambda rule (C#) ---
        var fn = new Function(this, "DbPortsRuleFn", new FunctionProps
        {
            Runtime = Runtime.DOTNET_10,   // ⚠ VERIFY the constant name in your CDK version
            Handler = "Harbourline.Security.ConfigRules::Harbourline.Security.ConfigRules.DbPortsRule::HandleAsync",
            Code = Code.FromAsset("../ConfigRules/bin/Release/net10.0/publish"),
            MemorySize = 512,
            Timeout = Duration.Seconds(30),
            Architecture = Architecture.ARM_64,
            LogRetention = RetentionDays.ONE_WEEK,
        });

        var dbPorts = new CustomRule(this, "DbPortsRule", new CustomRuleProps
        {
            ConfigRuleName = "hl-no-public-db-ports",
            LambdaFunction = fn,
            ConfigurationChanges = true,
            RuleScope = RuleScope.FromResources([ResourceType.EC2_SECURITY_GROUP]),
            InputParameters = new Dictionary<string, object> { ["blockedPorts"] = "1433,3306,5432" },
        });

        // Rules need the recorder to exist first.
        publicRead.Node.AddDependency(recorder, channel);
        dbPorts.Node.AddDependency(recorder, channel);
    }
}

CustomRule grants Config permission to invoke the function, and the function needs config:PutEvaluations — CDK adds the AWS managed policy service-role/AWSConfigRulesExecutionRole to the function role ⚠ VERIFY in your CDK version; if not, add fn.AddToRolePolicy(...) for config:PutEvaluations.

Complete code

A custom Lambda rule written in C#. Config invokes it with an event whose invokingEvent property is a JSON string containing the configuration item. The function decides compliance and reports it back with PutEvaluations, passing the resultToken it received.

The rule: a security group is NON_COMPLIANT if any inbound permission opens a blocked database port (default 1433, 3306, 5432) to 0.0.0.0/0 or ::/0. The evaluation logic is a pure static method, so you can unit-test it without AWS.

ConfigRules/ConfigRules.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AssemblyName>Harbourline.Security.ConfigRules</AssemblyName>
    <RootNamespace>Harbourline.Security.ConfigRules</RootNamespace>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.Core" Version="3.4.0" />
    <PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="3.0.1" />
    <PackageReference Include="AWSSDK.ConfigService" Version="4.1.1" />
  </ItemGroup>
</Project>
ConfigRules/DbPortsRule.cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Amazon.ConfigService;
using Amazon.ConfigService.Model;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;

[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]

namespace Harbourline.Security.ConfigRules;

// The event AWS Config sends to a custom Lambda rule (only the fields we use).
public sealed record ConfigRuleEvent(
    [property: JsonPropertyName("invokingEvent")] string InvokingEvent,
    [property: JsonPropertyName("ruleParameters")] string? RuleParameters,
    [property: JsonPropertyName("resultToken")] string ResultToken,
    [property: JsonPropertyName("eventLeftScope")] bool EventLeftScope);

public sealed record RuleResult(string ComplianceType, string Annotation);

public sealed class DbPortsRule
{
    private static readonly int[] DefaultBlockedPorts = [1433, 3306, 5432];
    private readonly IAmazonConfigService _config;

    public DbPortsRule() : this(new AmazonConfigServiceClient()) { }
    public DbPortsRule(IAmazonConfigService config) => _config = config;

    public async Task HandleAsync(ConfigRuleEvent evt, ILambdaContext context)
    {
        using var invoking = JsonDocument.Parse(evt.InvokingEvent);
        var root = invoking.RootElement;
        var messageType = root.GetProperty("messageType").GetString();

        if (messageType != "ConfigurationItemChangeNotification")
        {
            // Oversized CIs and scheduled notifications need a different path (see notes).
            context.Logger.LogWarning($"Unsupported messageType {messageType}; skipping");
            return;
        }

        var ci = root.GetProperty("configurationItem");
        var resourceType = ci.GetProperty("resourceType").GetString()!;
        var resourceId = ci.GetProperty("resourceId").GetString()!;
        var captureTime = ci.GetProperty("configurationItemCaptureTime").GetDateTime();

        var result = evt.EventLeftScope
            ? new RuleResult("NOT_APPLICABLE", "Resource left the rule scope")
            : Evaluate(ci, ParseBlockedPorts(evt.RuleParameters));

        context.Logger.LogInformation($"{resourceId}: {result.ComplianceType} — {result.Annotation}");

        await _config.PutEvaluationsAsync(new PutEvaluationsRequest
        {
            ResultToken = evt.ResultToken,
            Evaluations =
            [
                new Evaluation
                {
                    ComplianceResourceType = resourceType,
                    ComplianceResourceId = resourceId,
                    ComplianceType = new ComplianceType(result.ComplianceType),
                    Annotation = result.Annotation.Length > 256 ? result.Annotation[..256] : result.Annotation,
                    OrderingTimestamp = captureTime,
                },
            ],
        });
    }

    public static int[] ParseBlockedPorts(string? ruleParameters)
    {
        if (string.IsNullOrWhiteSpace(ruleParameters)) return DefaultBlockedPorts;
        using var doc = JsonDocument.Parse(ruleParameters);
        if (!doc.RootElement.TryGetProperty("blockedPorts", out var p)) return DefaultBlockedPorts;
        return p.GetString()!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
                .Select(int.Parse).ToArray();
    }

    // Pure function: easy to unit-test with a saved configuration item.
    public static RuleResult Evaluate(JsonElement ci, int[] blockedPorts)
    {
        if (ci.GetProperty("configurationItemStatus").GetString() is "ResourceDeleted" or "ResourceNotRecorded")
            return new("NOT_APPLICABLE", "Resource deleted or not recorded");
        if (ci.GetProperty("resourceType").GetString() != "AWS::EC2::SecurityGroup")
            return new("NOT_APPLICABLE", "Not a security group");

        var problems = new List<string>();
        var config = ci.GetProperty("configuration");
        if (!config.TryGetProperty("ipPermissions", out var perms)) return new("COMPLIANT", "No inbound rules");

        foreach (var perm in perms.EnumerateArray())
        {
            var protocol = perm.GetProperty("ipProtocol").GetString();
            var allTraffic = protocol == "-1";
            if (!allTraffic && protocol != "tcp") continue;

            var from = allTraffic ? 0 : perm.TryGetProperty("fromPort", out var f) ? f.GetInt32() : 0;
            var to = allTraffic ? 65535 : perm.TryGetProperty("toPort", out var t) ? t.GetInt32() : 65535;

            var openToWorld = HasCidr(perm, "ipv4Ranges", "cidrIp", "0.0.0.0/0")
                           || HasCidr(perm, "ipv6Ranges", "cidrIpv6", "::/0");
            if (!openToWorld) continue;

            foreach (var port in blockedPorts.Where(p => p >= from && p <= to))
                problems.Add($"{port}/tcp open to the internet");
        }

        return problems.Count == 0
            ? new("COMPLIANT", "No database ports open to the internet")
            : new("NON_COMPLIANT", string.Join("; ", problems.Distinct()));
    }

    private static bool HasCidr(JsonElement perm, string listName, string field, string cidr) =>
        perm.TryGetProperty(listName, out var list) && list.ValueKind == JsonValueKind.Array &&
        list.EnumerateArray().Any(r => r.TryGetProperty(field, out var v) && v.GetString() == cidr);
}

A unit test using a trimmed configuration item (save real ones with get-resource-config-history and anonymise them):

ConfigRules.Tests/DbPortsRuleTests.cs
using System.Text.Json;
using Harbourline.Security.ConfigRules;
using Xunit;

public sealed class DbPortsRuleTests
{
    private static JsonElement Ci(string permissionsJson) => JsonDocument.Parse($$"""
        {
          "configurationItemStatus": "OK",
          "resourceType": "AWS::EC2::SecurityGroup",
          "resourceId": "sg-0abc",
          "configuration": { "ipPermissions": {{permissionsJson}} }
        }
        """).RootElement;

    [Fact]
    public void Postgres_open_to_world_is_non_compliant()
    {
        var ci = Ci("""[{ "ipProtocol": "tcp", "fromPort": 5432, "toPort": 5432, "ipv4Ranges": [{ "cidrIp": "0.0.0.0/0" }] }]""");
        var r = DbPortsRule.Evaluate(ci, [1433, 3306, 5432]);
        Assert.Equal("NON_COMPLIANT", r.ComplianceType);
        Assert.Contains("5432", r.Annotation);
    }

    [Fact]
    public void Postgres_open_to_vpc_only_is_compliant()
    {
        var ci = Ci("""[{ "ipProtocol": "tcp", "fromPort": 5432, "toPort": 5432, "ipv4Ranges": [{ "cidrIp": "10.20.0.0/16" }] }]""");
        Assert.Equal("COMPLIANT", DbPortsRule.Evaluate(ci, [5432]).ComplianceType);
    }

    [Fact]
    public void All_traffic_from_ipv6_world_is_non_compliant()
    {
        var ci = Ci("""[{ "ipProtocol": "-1", "ipv6Ranges": [{ "cidrIpv6": "::/0" }] }]""");
        Assert.Equal("NON_COMPLIANT", DbPortsRule.Evaluate(ci, [1433]).ComplianceType);
    }

    [Fact]
    public void Parses_rule_parameters() =>
        Assert.Equal([1521, 5432], DbPortsRule.ParseBlockedPorts("""{"blockedPorts":"1521, 5432"}"""));
}

Deploy with the CDK stack, or manually:

cd ConfigRules
dotnet lambda deploy-function hl-m05-db-ports-rule --function-runtime dotnet10 \
  --function-handler "Harbourline.Security.ConfigRules::Harbourline.Security.ConfigRules.DbPortsRule::HandleAsync" \
  --function-role hl-m05-config-rule-role --function-memory-size 512 --function-timeout 30 --profile learn-sandbox

aws lambda add-permission --function-name hl-m05-db-ports-rule --statement-id config \
  --action lambda:InvokeFunction --principal config.amazonaws.com --source-account $ACCOUNT --profile learn-sandbox

aws configservice put-config-rule --profile learn-sandbox --config-rule '{
  "ConfigRuleName": "hl-no-public-db-ports",
  "Scope": {"ComplianceResourceTypes": ["AWS::EC2::SecurityGroup"]},
  "InputParameters": "{\"blockedPorts\":\"1433,3306,5432\"}",
  "Source": {"Owner": "CUSTOM_LAMBDA",
             "SourceIdentifier": "arn:aws:lambda:us-east-1:'"$ACCOUNT"':function:hl-m05-db-ports-rule",
             "SourceDetails": [{"EventSource":"aws.config","MessageType":"ConfigurationItemChangeNotification"}]}
}'

Code explained line by line

  1. [assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))] — tells the .NET Lambda runtime to deserialise the incoming JSON event with System.Text.Json.
  2. ConfigRuleEvent — Config sends invokingEvent and ruleParameters as JSON strings inside JSON, so they're declared as string and parsed separately. Forgetting this is the most common bug in custom rules.
  3. eventLeftScope — true when a resource is no longer in the rule's scope (for example its tags changed); the right answer is NOT_APPLICABLE.
  4. Two constructors — the parameterless one is used by Lambda; the other lets tests inject a fake IAmazonConfigService.
  5. messageType — change-triggered rules get ConfigurationItemChangeNotification. Large resources produce OversizedConfigurationItemChangeNotification, which contains only a summary; production code would then call GetResourceConfigHistory to fetch the full CI.
  6. configurationItemCaptureTime → OrderingTimestamp — Config uses this to order evaluations; reporting the CI's time (not "now") keeps history accurate when events arrive out of order.
  7. ParseBlockedPorts — rule parameters make the same code reusable (for example, add Oracle's 1521 in another account) without redeploying.
  8. Evaluate is static and pure: it takes JSON and returns a result, which is why the tests need no AWS.
  9. ResourceDeleted / ResourceNotRecorded → NOT_APPLICABLE: deleted resources shouldn't stay NON_COMPLIANT forever.
  10. ipProtocol == "-1" means all protocols and ports, so it's treated as 0–65535.
  11. fromPort/toPort define a range; the code flags every blocked port inside it, so 0–65535 from the internet is caught.
  12. HasCidr checks both ipv4Ranges and ipv6Ranges — forgetting IPv6 is a real-world gap.
  13. Annotation is truncated to 256 characters, the documented maximum for an evaluation annotation ⚠ VERIFY.
  14. PutEvaluationsAsync with ResultToken — the token ties your answer to this specific invocation; without it Config rejects the call.
  15. In SDK v4, Evaluations is a list you assign explicitly; ComplianceType is an SDK constant class built from the string.

Security considerations

⚠ Learning shortcut — not for production

The lab records only two resource types in one account, uses a bucket in the same account with force_destroy/AutoDeleteObjects, and the remediation role is created by hand. In production: recorder and delivery channel managed centrally (Control Tower or a delegated administrator), delivery to the log-archive account with SSE-KMS and Object Lock, an SCP that stops anyone disabling Config, organisation conformance packs from Git, and remediation roles with least privilege scoped to the exact actions each Automation document needs.

  • Protect the recorder. An attacker's first move may be StopConfigurationRecorder. Deny it with an SCP and alert on the CloudTrail event.
  • Remediation roles are powerful. An automatic remediation role that can modify every security group is an attractive target. Scope it narrowly, and use conditions such as resource tags.
  • Automatic remediation can cause outages. Removing an "open" rule that a partner integration depends on is a self-inflicted incident. Use manual remediation or notification first, and automatic only for low-risk fixes.
  • CIs can contain sensitive data. Configuration items include resource policies, tags and sometimes environment-like settings. Never put secrets in tags or resource descriptions, and restrict who can read the Config bucket.
  • Custom rule code is security code. Review it, test it and pin dependencies — a bug that always returns COMPLIANT is worse than no rule.

Banking use case

Harbourline's control library maps each control to evidence. An extract:

Control (internal ID)Config implementationRemediationEvidence produced
NET-04 No database port reachable from the internetCustom rule hl-no-public-db-ports (C#)Notify the owning team; manual fix within 24 hMonthly compliance history export
DAT-02 Customer-data buckets block public accessS3_BUCKET_PUBLIC_READ_PROHIBITED + S3_BUCKET_LEVEL_PUBLIC_ACCESS_PROHIBITEDAutomatic Block Public Access for buckets tagged DataClass=customerRemediation execution history
DAT-05 Databases encrypted at restRDS_STORAGE_ENCRYPTEDNone (can't encrypt in place; requires migration)Exception register for legacy instances
LOG-01 Audit trail integrityCLOUD_TRAIL_LOG_FILE_VALIDATION_ENABLED, MULTI_REGION_CLOUD_TRAIL_ENABLEDNone (SCP prevents disabling)Compliance timeline + validate-logs reports
IAM-07 Access keys rotated within 90 daysACCESS_KEYS_ROTATED (maxAccessKeyAge=90)Ticket to the key ownerNon-compliant key list

For the cardholder data environment (CDE) accounts, the security team also deploys AWS's sample "Operational Best Practices for PCI DSS" conformance pack — after reviewing it, removing rules that don't apply and adding Harbourline's custom ones. The PCI programme manager explains to the QSA that the pack is a mapping aid that produces evidence for some technical requirements; it doesn't demonstrate PCI DSS compliance by itself.

Cost reasoning (fictional): 120 accounts × about 3,000 continuous CIs per month = 360,000 CIs × USD 0.003 = USD 1,080 a month. Rule evaluations: about 2 million a month — the first 100,000 at USD 0.001, the remainder at lower tier prices ⚠ VERIFY tier rates on the pricing page. Switching EC2 instances and ENIs in container accounts to periodic recording cut CI volume by 60%.

Common mistakes

  • Recording all resource types everywhere → surprise bill from high-churn resources → record what your controls need; use periodic recording or exclusions for noisy types.
  • Global resources recorded in every Region → duplicate IAM CIs and duplicate charges → includeGlobalResourceTypes in one Region only.
  • Parsing invokingEvent as an object → deserialisation errors in custom rules → it's a JSON string; parse it.
  • Not handling oversized CIs or deleted resources → rules silently fail or leave stale NON_COMPLIANT results → handle every messageType and configurationItemStatus.
  • Deploying the full PCI sample pack in a sandbox → many rules × many evaluations → read the template; deploy a subset.
  • Treating COMPLIANT as "secure" → rules check specific properties only → combine with threat detection, vulnerability management and reviews.
  • Automatic remediation without retry limits → remediation loops when something re-applies the bad setting (IaC drift fight) → fix the source (IaC), set MaximumAutomaticAttempts.

Troubleshooting

SymptomLikely causeFix
NoAvailableConfigurationRecorderException when adding rulesRecorder not created or not startedCreate the recorder and delivery channel, then start-configuration-recorder
InsufficientDeliveryPolicyExceptionBucket policy doesn't allow Config to writeAdd the GetBucketAcl/ListBucket and PutObject statements with AWS:SourceAccount
Custom rule shows No resultsLambda failing, missing invoke permission, or resource type not recordedCheck Lambda logs; aws lambda add-permission for config.amazonaws.com; record the type
InvalidResultTokenExceptionReused or test token, or calling PutEvaluations from a different accountUse the token from the actual event; for manual testing use TestMode = true on the request
Rule evaluates but the resource never changes complianceRule is periodic only, or the change isn't in the recorded propertiesAdd a configuration-change trigger; check the CI to see whether the property is recorded
Remediation fails with AccessDeniedAutomation assume role lacks permissions or trustTrust ssm.amazonaws.com; grant the actions the document runs
Conformance pack stuck in CREATE_FAILEDTemplate references an unsupported rule in the Region, or recorder offRead describe-conformance-pack-status; remove unsupported rules

Cost and cleanup

Item (checked 2026-11-18, us-east-1)PriceLab exposure
Configuration items — continuousUSD 0.003 per CIA few dozen CIs ≈ USD 0.10
Configuration items — periodicUSD 0.012 per CI (at most one per resource per day)Not used
Rule evaluationsUSD 0.001 each for the first 100,000 per month; lower tiers above ⚠ VERIFYA few hundred ≈ USD 0.30
Conformance pack evaluationsUSD 0.001 each for the first 100,000; lower tiers above ⚠ VERIFY4-rule pack ≈ cents
Lambda (custom rule)Free tier covers itFree
SSM AutomationFree for AWS-owned documents within quotas ⚠ VERIFYFree
S3 storageCentsCents

Lab total: under USD 1 if you tear down the same day. Free alternative: write the rule and run the unit tests locally, and author the conformance pack YAML without deploying it.

PROFILE=learn-sandbox
ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile $PROFILE)

aws configservice delete-conformance-pack --conformance-pack-name hl-m05-baseline --profile $PROFILE
aws configservice delete-remediation-configuration --config-rule-name hl-s3-bucket-public-read-prohibited --profile $PROFILE
for r in hl-s3-bucket-public-read-prohibited hl-restricted-ssh hl-s3-versioning-guard hl-no-public-db-ports; do
  aws configservice delete-config-rule --config-rule-name $r --profile $PROFILE
done
aws lambda delete-function --function-name hl-m05-db-ports-rule --profile $PROFILE

# Stop recording — this is what stops CI charges
aws configservice stop-configuration-recorder --configuration-recorder-name default --profile $PROFILE
aws configservice delete-delivery-channel --delivery-channel-name default --profile $PROFILE
aws configservice delete-configuration-recorder --configuration-recorder-name default --profile $PROFILE
aws s3 rb s3://hl-m05-config-$ACCOUNT --force --profile $PROFILE

# Or: cdk destroy / terraform destroy

# Confirm
aws configservice describe-configuration-recorder-status --profile $PROFILE
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --query "ResourceTagMappingList[].ResourceARN" --profile $PROFILE

If your account is managed by Control Tower, don't delete the Control Tower recorder — only remove what you added.

Exercises

  • 🟢 Guided: Set up the recorder for security groups and buckets, add INCOMING_SSH_DISABLED, then create a test security group allowing SSH from 0.0.0.0/0. Watch it become NON_COMPLIANT, open its Resource timeline, and find the CloudTrail event linked to the change. Remove the rule and watch it return to COMPLIANT.
  • 🟡 Challenge: Extend DbPortsRule to also flag ports open to any CIDR broader than /16 (for example 10.0.0.0/8), controlled by a new maxPrefixLength parameter. Add tests.
  • 🔴 Live problem: The FinOps team reports Config costs in the payments account jumped from USD 40 to USD 2,300 in a month. Nothing changed in the Config setup. Investigate and recommend changes that don't weaken the bank's controls.

Assignment

In your portfolio, publish a "control-to-Config mapping": a table of eight Harbourline controls with the Config rule (managed, Guard or custom) that evidences each one, the remediation decision and the evidence produced; the conformance pack YAML; the DbPortsRule project with tests; and a cost estimate for 50 accounts with your recording assumptions.

Solutions

Knowledge check

Interview questions

  • "How do you prove continuous compliance of security groups to an auditor?" — Config records every change with history; a rule evaluates each change; compliance history plus linked CloudTrail events show what changed, who did it and how long any non-compliance lasted; export it monthly as evidence.
  • "Managed rule, Guard rule or Lambda rule — how do you choose?" — Managed first (no code). Guard for simple property checks on a CI. Lambda when you need logic, lookups in other APIs or cross-resource checks — accepting that you own and patch the code.
  • "How do you roll out Config across 100+ accounts?" — Control Tower or a delegated administrator; organisation conformance packs from Git; an organisation aggregator; an SCP protecting recorders; delivery to the log-archive account; cost guardrails on recorded types.
  • "What are the risks of automatic remediation?" — Breaking production, fighting IaC drift in a loop, and over-privileged remediation roles. Mitigate with scoped roles, retry limits, tag-based scope, and fixing the IaC source.

Certification practice

Completion checklist

  • I can explain CIs, the recorder, rules, remediation, conformance packs and aggregators
  • I recorded two resource types and saw a resource timeline linked to CloudTrail
  • I wrote and unit-tested a C# custom Config rule
  • I deployed a small conformance pack and read its compliance score
  • I can estimate Config cost from CI and evaluation volumes
  • I deleted rules, the pack and the recorder (or left Control Tower's recorder alone) and confirmed nothing tagged remains

Key takeaways

  • AWS Config records resource state and history; CloudTrail records activity. Banks need both to prove controls over time.
  • Rules come in three forms — managed, Guard and Lambda — and evaluate on change or on a schedule. They detect; prevention lives elsewhere.
  • Remediation via SSM Automation is powerful but risky: scope roles tightly, limit retries, and fix drift at the IaC source.
  • Conformance packs package controls as code and are the main path for control evidence now that Audit Manager isn't available to new accounts; sample packs such as PCI DSS are mappings, not compliance. There's no GDPR pack.
  • Cost follows CI and evaluation volume. Record what your controls need, use periodic recording for churn, and avoid duplicate rules.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page