PCI DSS on AWS
Understand PCI DSS v4.0.1 well enough to design a small cardholder data environment on AWS: what is in scope, how tokenisation and segmentation shrink it, what AWS's attestation covers and what it doesn't, and how to gather evidence for your QSA. Concepts only — your QSA decides.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.KeyManagementService 4.x) · AWS CLI v2 · PCI DSS v4.0.1 · Region us-east-1. Verified against official sources on 2026-11-18.
Read this first
This lesson teaches concepts so you can talk to your compliance team and Qualified Security Assessor (QSA) with confidence. It is not compliance advice. Nothing on this platform — no architecture, Config rule, conformance pack or code sample — makes a system PCI DSS compliant. Scope, segmentation adequacy and compensating controls are decided by your organisation and its QSA. Requirement numbers below refer to PCI DSS v4.0.1; always read the standard itself before relying on them.
Learning objectives
By the end of this lesson you can:
- Explain what PCI DSS is, who sets it, the current version (v4.0.1) and how merchants, service providers and issuers relate to it.
- Classify systems as cardholder data environment (CDE), connected-to / security-impacting, or out of scope, and explain why scope is the biggest cost driver.
- Design scope reduction on AWS with tokenisation, account-level segmentation and network segmentation, and describe how segmentation is tested.
- Describe the AWS PCI DSS attestation: where to get the Attestation of Compliance (AOC) and Responsibility Summary in AWS Artifact, and what you can and cannot inherit.
- Build a simple tokenisation service in .NET that validates, encrypts with KMS, fingerprints with a keyed hash, and masks PANs — using official test card numbers only.
- Use Security Hub CSPM's PCI DSS v4.0.1 standard and the AWS Config PCI DSS 4.0 conformance pack as evidence aids, not as proof of compliance.
Prerequisites
- Threat modelling with STRIDE
- Segmentation, private endpoints and egress filtering
- Boundaries, SCPs, RCPs and resource policies
- The KMS and data classification lessons in this module (module overview)
- Tools: .NET 10 SDK; AWS CLI v2 with
learn-sandboxonly for the optional read-only commands
Why this matters in banking
Harbourline issues debit and credit cards and also accepts card payments for its own products (for example, paying off a credit card from a card at another bank). That makes it both a card issuer and a merchant, and every system that touches a card number is subject to PCI DSS through its contracts with the card brands and acquirers.
Two outcomes are possible when a bank moves card workloads to AWS:
- Scope sprawl. The card number travels through the API, the logs, the data lake and the analytics accounts. Hundreds of systems and every engineer with access to them fall into scope. The annual assessment takes months, every change needs PCI review, and a single log line with a PAN creates a finding.
- Scope by design. The card number enters one small, isolated tokenisation service and nothing else ever sees it. Everything else handles tokens. The CDE is a handful of resources in one account; the assessment focuses there.
The difference is architectural, and it's decided in the first design sessions. That's why a cloud engineer needs to understand scope, even though the QSA has the final word.
The idea in plain language
PCI DSS (Payment Card Industry Data Security Standard) is a security standard maintained by the PCI Security Standards Council (PCI SSC), founded by the major card brands. It applies to any organisation that stores, processes or transmits cardholder data or sensitive authentication data, or that can affect their security. It is enforced contractually through the card brands and acquirers, not by a government.
Key terms:
| Term | Meaning |
|---|---|
| PAN | Primary account number — the long card number. The defining element of cardholder data |
| Cardholder data (CHD) | PAN, plus cardholder name, expiry date and service code when stored with the PAN |
| Sensitive authentication data (SAD) | Full track data, card verification code (CVV2/CVC2), PINs and PIN blocks. Must not be stored after authorisation (issuers have narrow exceptions with business justification) |
| CDE | Cardholder data environment — people, processes and technology that store, process or transmit CHD/SAD, plus systems with unrestricted connectivity to them |
| Connected-to / security-impacting systems | Not in the CDE, but can affect its security: identity providers, logging, patch servers, CI/CD that deploys into the CDE, jump hosts |
| Out of scope | Systems with no access to CHD and no ability to affect the CDE's security, proven by segmentation |
| QSA | Qualified Security Assessor — the independent assessor who validates compliance and signs the Report on Compliance (ROC) |
| AOC / ROC | Attestation of Compliance (summary) / Report on Compliance (full assessment) |
| Tokenisation | Replacing a PAN with a surrogate value (token) that is useless if stolen; the mapping lives in a protected vault |
Version facts (verified 2026-11-18): PCI DSS v4.0.1 (a limited revision published in 2024 with clarifications, no new requirements) is the active version; v4.0 was retired at the end of 2024. Requirements that v4.0 had marked "future-dated" became mandatory on 31 March 2025. The PCI SSC ran a request-for-comments on v4.0.1 in mid-2026 to inform the next version, so check the PCI SSC document library for any newer release before an assessment. ⚠ VERIFY before relying on it.
PCI DSS has 12 principal requirements grouped under six goals: build and maintain secure networks and systems (1–2), protect account data (3–4), maintain a vulnerability-management programme (5–6), implement strong access control (7–9), regularly monitor and test networks (10–11), and maintain an information security policy (12).
Analogy: think of the CDE as the bank's cash-handling room. PCI DSS sets the rules for the room: locks, cameras, who can enter, how the cash is counted. Scope reduction is designing the branch so cash only ever goes into one small room through one hatch, instead of letting every desk keep a drawer of notes. Tokenisation is giving customers a numbered receipt instead of their cash — the receipt is worthless to a thief unless they also break into the room.
What problem the AWS services solve
AWS is assessed annually as a PCI DSS Level 1 service provider by an independent QSA. That attestation covers AWS's responsibilities for the services in scope: physical security of data centres, the hypervisor, the underlying network, and the managed parts of services such as RDS or Lambda.
| AWS capability | How it helps a PCI workload | What it does not do |
|---|---|---|
| AWS Artifact — PCI DSS AOC and Responsibility Summary | Gives your QSA AWS's attestation; the responsibility summary explains, per requirement, what AWS covers, what you cover, and what is shared. AWS also publishes the package in OSCAL (machine-readable) form | Does not cover how you configure services. Your QSA can rely on AWS's AOC for AWS's part without retesting it |
| AWS Services in Scope by Compliance Program | Lists which services AWS includes in its PCI assessment | Using an in-scope service doesn't make your use of it compliant; using an out-of-scope service in the CDE is a conversation with your QSA |
| AWS Organizations, SCPs, RCPs | A dedicated CDE account with strong guardrails is the simplest, clearest segmentation boundary | SCPs don't apply to the management account; segmentation still has to be tested |
| VPC, security groups, NACLs, Network Firewall, PrivateLink | Network security controls (requirement 1) and segmentation inside and between accounts | Rules must be reviewed at least every six months (requirement 1.2.7 ⚠ VERIFY) — that's your process |
| KMS, CloudHSM, AWS Payment Cryptography | Rendering PAN unreadable (requirement 3) and key management; CloudHSM and AWS Payment Cryptography hold PCI PIN attestations, and Payment Cryptography is a PCI P2PE certified decryption component | Key management procedures (custodians, split knowledge where needed) are yours |
| CloudTrail, CloudWatch Logs, S3 Object Lock | Audit trails (requirement 10) and tamper resistance | Daily review (now expected to be automated, 10.4.1.1 ⚠ VERIFY) is yours |
| Inspector, ECR scanning, Systems Manager Patch Manager | Vulnerability identification and patching (requirements 6 and 11) | Quarterly ASV external scans and penetration tests are separate obligations |
| Security Hub CSPM — PCI DSS v4.0.1 standard | Automated checks of AWS resource configuration mapped to PCI DSS v4.0.1 (v3.2.1 is still available; AWS recommends v4.0.1) | Checks configuration only; many requirements (policies, training, processes) can't be checked automatically |
| AWS Config conformance pack "Operational Best Practices for PCI DSS 4.0" | Continuous configuration evidence; two variants, including or excluding global resource types | AWS states explicitly that sample conformance packs are not designed to ensure compliance |
Honest limitations:
- There is no "PCI mode" on AWS. Every control is a configuration and process you own.
- AWS Audit Manager is in maintenance and can't be set up in new accounts from 2026-04-30, so don't plan evidence collection around its PCI framework.
- Your QSA may disagree with your scope. Bring them in at design time, not at the assessment.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Microsoft Service Trust Portal (PCI AOC, responsibility matrix) | AWS Artifact (AOC, Responsibility Summary, also in OSCAL) | Artifact is in the AWS console and needs IAM permissions to download reports |
| Azure Policy regulatory-compliance initiative "PCI DSS v4" | Security Hub CSPM PCI DSS v4.0.1 standard + Config PCI DSS 4.0 conformance pack | Two services instead of one initiative; both are evidence aids, not attestations |
| Azure landing zone with a dedicated "corp-cde" subscription | Dedicated CDE account in its own OU with SCPs/RCPs | AWS accounts are a hard isolation boundary for IAM, network and quotas by default |
| Azure Payment HSM | AWS Payment Cryptography (managed), AWS CloudHSM | Payment Cryptography is a managed API for payment key operations (PIN, CVV, MAC) |
| Azure Key Vault Managed HSM for PAN encryption keys | KMS customer managed key (FIPS 140-3 validated HSMs) or CloudHSM | KMS key policies and encryption context give per-tenant or per-purpose controls |
Architecture
The target: a small CDE account that is the only place a full PAN exists. Everything else uses tokens.
Security-boundary (scope) view
| Zone | Examples | Scope (typical — your QSA decides) | Why |
|---|---|---|---|
| CDE | Tokenisation API, vault, authorisation adapter, their KMS keys | In scope | Stores, processes or transmits PAN |
| Connected-to / security-impacting | Identity Center, log archive, CI/CD pipelines deploying to the CDE, Network Firewall inspecting CDE traffic | In scope (for relevant requirements) | Can affect the security of the CDE |
| Tokens only, segmented | Payments API, data lake, analytics, mobile backend | Potentially out of scope | Never sees PAN; can't reach the vault's detokenise operation; segmentation tested |
| Customer's browser page hosting the iframe | Harbourline's web app | Partly in scope — payment page script requirements (6.4.3, 11.6.1 ⚠ VERIFY) apply to pages that embed payment forms | Scripts on the parent page could interfere with card entry |
Step-by-step implementation
Find every place card data exists today (data discovery)
Before designing scope, find where PANs actually are: databases, logs, file shares, S3 buckets, support tickets. On AWS, Amazon Macie can find credit-card-number patterns in S3, and CloudWatch Logs data protection policies can detect and mask card numbers in logs. Results usually surprise people. Every location found is in scope until it is removed.
Decide whether you need the PAN at all
Ask for each flow: does this system need the full PAN, or only a reference to it? Analytics, customer service screens, fraud features and refunds usually work with a token plus the last four digits. Outsourcing card capture to a PCI-validated payment provider (hosted payment page, iframe, or network tokens from the card scheme) removes most of the PAN from your estate; this is scope transfer, and your contract and the provider's AOC become evidence.
Put everything that must see PAN in a dedicated CDE account
Create an OU PCI with a CDE account. Apply SCPs that deny leaving the organisation, disabling CloudTrail/Config/GuardDuty, creating internet gateways except in approved VPCs, and using Regions you don't operate in. Use RCPs to stop CDE resources (KMS keys, S3, Secrets Manager) being shared outside the organisation. Only the tokenisation and authorisation components run here.
Tokenise at the edge
Capture card details in a hosted field served from the CDE (or from a PCI-validated provider). The tokenisation service validates the PAN, encrypts it with a KMS key, creates a random token, computes a keyed hash for duplicate detection, and returns { token, last4, brand }. Only the authorisation adapter, inside the CDE, may detokenise.
Segment and prove it
Restrict network paths into the CDE to the tokenise endpoint (via PrivateLink from the workload account) and the outbound acquirer connection. Deny everything else. Then test segmentation: at least every 12 months and after significant changes for merchants, and every six months for service providers (11.4.5 / 11.4.6 ⚠ VERIFY), typically by a penetration tester trying to reach the CDE from out-of-scope networks.
Turn on evidence collection
In the CDE account, enable Security Hub CSPM with the PCI DSS v4.0.1 standard, deploy the Config PCI DSS 4.0 conformance pack, send CloudTrail and VPC Flow Logs to the log archive, and download AWS's AOC and Responsibility Summary from Artifact for your QSA. Map each finding to an owner. Remember the automated checks cover only part of the standard.
Confirm scope every year
PCI DSS v4 requires entities to document and confirm scope at least every 12 months and after significant changes (service providers every six months) — 12.5.2 / 12.5.2.1 ⚠ VERIFY. Re-run data discovery; check new data flows in the threat model; record the review.
AWS Console instructions
All read-only, and free:
- AWS Artifact: Console → AWS Artifact → Reports. Search for
PCI. Open the PCI DSS report package (AOC and Responsibility Summary), accept the terms that appear, and download. Your role needs Artifact permissions (artifact:ListReports,artifact:GetReport, and the terms-acceptance actions ⚠ VERIFY current action names). Treat downloaded reports as confidential: the terms restrict sharing them. - Services in scope: open the public AWS Services in Scope by Compliance Program page and filter by PCI. Note any service in your design that is not listed.
- Security Hub CSPM: Console → Security Hub CSPM → Security standards. You can view the PCI DSS v4.0.1 standard's controls without enabling it. Enabling it starts charges after the free trial — skip that in the sandbox unless you are doing the trial-based detection lab, and disable it in the same session.
- AWS Config: Console → AWS Config → Conformance packs → Deploy conformance pack → Use sample template and look for Operational Best Practices for PCI DSS 4.0. Read the rules it would deploy, then cancel — deploying creates rule evaluations that cost money.
AWS CLI
# 1. List PCI reports available in AWS Artifact (read-only; your role needs Artifact permissions).
aws artifact list-reports --query "reports[?contains(name, 'PCI')].{id:id,name:name,version:version}" \
--output table --profile learn-sandbox
# 2. If Security Hub CSPM is already enabled, list the available standards and find PCI DSS v4.0.1.
aws securityhub describe-standards \
--query "Standards[?contains(Name, 'PCI')].{name:Name,arn:StandardsArn}" --output table --profile learn-sandbox
# 3. List Macie findings for financial data (card numbers) in S3 (only if Macie is enabled; reading is free).
aws macie2 list-findings --profile learn-sandbox --finding-criteria '{"criterion":{"type":{"eq":["SensitiveData:S3Object/Financial"]}}}' || echo "Macie not enabled - skip"
# 4. Check the CDE account cannot share KMS keys outside the org: list key policies for review.
aws kms get-key-policy --key-id alias/hl-m05-pan-vault --policy-name default --output text --profile learn-sandboxaws artifact list-reports uses the AWS Artifact API introduced in 2024 ⚠ VERIFY the exact output shape in your CLI version with aws artifact list-reports help. Commands 2–4 return errors if the services or key aren't set up; that's expected in a fresh sandbox.
Infrastructure as Code
A guardrail SCP for the PCI OU. It denies the actions that would most obviously break segmentation or evidence. Test SCPs in a non-production OU first — see Boundaries, SCPs, RCPs and resource policies.
using System.Collections.Generic;
using System.Text.Json;
using Amazon.CDK;
using Amazon.CDK.AWS.Organizations;
using Constructs;
namespace Harbourline.Platform.Infra;
/// <summary>Deploy from the management or delegated policy-admin account only.</summary>
public sealed class PciGuardrailsStack : Stack
{
public PciGuardrailsStack(Construct scope, string id, string pciOuId, IStackProps? props = null) : base(scope, id, props)
{
var policy = new
{
Version = "2012-10-17",
Statement = new object[]
{
new
{
Sid = "ProtectEvidence",
Effect = "Deny",
Action = new[]
{
"cloudtrail:StopLogging", "cloudtrail:DeleteTrail", "cloudtrail:UpdateTrail",
"config:StopConfigurationRecorder", "config:DeleteConfigurationRecorder",
"guardduty:DeleteDetector", "guardduty:DisassociateFromMasterAccount",
"securityhub:DisableSecurityHub",
},
Resource = "*",
},
new
{
Sid = "NoNewInternetPaths",
Effect = "Deny",
Action = new[] { "ec2:CreateInternetGateway", "ec2:AttachInternetGateway", "ec2:CreateVpcPeeringConnection" },
Resource = "*",
Condition = new Dictionary<string, object>
{
["ArnNotLike"] = new Dictionary<string, string> { ["aws:PrincipalArn"] = "arn:aws:iam::*:role/hl-pci-network-admin" },
},
},
new
{
Sid = "NoLeavingOrg",
Effect = "Deny",
Action = new[] { "organizations:LeaveOrganization" },
Resource = "*",
},
},
};
_ = new CfnPolicy(this, "PciGuardrails", new CfnPolicyProps
{
Name = "hl-pci-guardrails",
Description = "Evidence and segmentation guardrails for the PCI OU (lab)",
Type = "SERVICE_CONTROL_POLICY",
Content = JsonSerializer.Serialize(policy),
TargetIds = new[] { pciOuId },
});
}
}SCPs are free. In the single-account sandbox you can't attach them (you need an organisation); treat this as a design exercise unless you have a lab organisation.
Complete code
A minimal tokenisation service core. It is not a production token vault — those need HSM-backed keys with strict custody, detokenisation authorisation, rate limiting, monitoring and a QSA's review — but it shows each control the standard cares about.
namespace Harbourline.Cards.Tokenisation;
/// <summary>A validated primary account number. Never log or serialise this type.</summary>
public sealed class Pan
{
private readonly string _digits;
private Pan(string digits) => _digits = digits;
public static Pan Parse(string input)
{
ArgumentNullException.ThrowIfNull(input);
var digits = new string(input.Where(char.IsAsciiDigit).ToArray());
if (digits.Length is < 12 or > 19)
throw new FormatException("A PAN has 12 to 19 digits.");
if (!PassesLuhn(digits))
throw new FormatException("PAN failed the Luhn check.");
return new Pan(digits);
}
public string Last4 => _digits[^4..];
/// <summary>At most the BIN (first six) and last four may be displayed; we show only the last four.</summary>
public string Masked => new string('•', _digits.Length - 4) + Last4;
internal string Reveal() => _digits; // used only by the vault, inside the CDE
public override string ToString() => Masked; // so accidental logging never prints the PAN
private static bool PassesLuhn(string digits)
{
var sum = 0;
var doubleIt = false;
for (var i = digits.Length - 1; i >= 0; i--)
{
var d = digits[i] - '0';
if (doubleIt)
{
d *= 2;
if (d > 9) d -= 9;
}
sum += d;
doubleIt = !doubleIt;
}
return sum % 10 == 0;
}
}using System.Security.Cryptography;
using System.Text;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
namespace Harbourline.Cards.Tokenisation;
public sealed record TokenisedCard(string Token, string Last4, string Fingerprint);
/// <summary>Where vault records are kept (DynamoDB in the CDE account in production).</summary>
public interface IVaultStore
{
Task<string?> FindTokenByFingerprintAsync(string fingerprint, CancellationToken ct);
Task SaveAsync(string token, string fingerprint, byte[] ciphertext, string last4, CancellationToken ct);
Task<byte[]?> GetCiphertextAsync(string token, CancellationToken ct);
}
/// <param name="encryptionKeyId">Symmetric KMS key (ENCRYPT_DECRYPT) for PANs, e.g. alias/hl-m05-pan-vault.</param>
/// <param name="hmacKeyId">KMS HMAC key (GENERATE_VERIFY_MAC, HMAC_256) for fingerprints.</param>
public sealed class TokenVault(IAmazonKeyManagementService kms, IVaultStore store, string encryptionKeyId, string hmacKeyId)
{
private const string Purpose = "pan-vault";
public async Task<TokenisedCard> TokeniseAsync(Pan pan, CancellationToken ct = default)
{
// 1. Keyed hash of the full PAN: lets us detect the same card twice without storing a plain hash.
var fingerprint = await FingerprintAsync(pan, ct).ConfigureAwait(false);
var existing = await store.FindTokenByFingerprintAsync(fingerprint, ct).ConfigureAwait(false);
if (existing is not null)
return new TokenisedCard(existing, pan.Last4, fingerprint);
// 2. Encrypt the PAN with KMS. The encryption context is bound to the ciphertext and logged in CloudTrail.
var token = NewToken();
var encrypt = await kms.EncryptAsync(new EncryptRequest
{
KeyId = encryptionKeyId,
Plaintext = new MemoryStream(Encoding.ASCII.GetBytes(pan.Reveal())),
EncryptionContext = new Dictionary<string, string> { ["purpose"] = Purpose, ["token"] = token },
}, ct).ConfigureAwait(false);
// 3. Store only ciphertext, fingerprint and last four.
await store.SaveAsync(token, fingerprint, encrypt.CiphertextBlob.ToArray(), pan.Last4, ct).ConfigureAwait(false);
return new TokenisedCard(token, pan.Last4, fingerprint);
}
/// <summary>Only callable by the authorisation adapter's role (enforced by the KMS key policy).</summary>
public async Task<Pan> DetokeniseAsync(string token, CancellationToken ct = default)
{
var ciphertext = await store.GetCiphertextAsync(token, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException("Unknown token.");
var decrypt = await kms.DecryptAsync(new DecryptRequest
{
KeyId = encryptionKeyId,
CiphertextBlob = new MemoryStream(ciphertext),
EncryptionContext = new Dictionary<string, string> { ["purpose"] = Purpose, ["token"] = token },
}, ct).ConfigureAwait(false);
return Pan.Parse(Encoding.ASCII.GetString(decrypt.Plaintext.ToArray()));
}
private async Task<string> FingerprintAsync(Pan pan, CancellationToken ct)
{
var mac = await kms.GenerateMacAsync(new GenerateMacRequest
{
KeyId = hmacKeyId,
MacAlgorithm = MacAlgorithmSpec.HMAC_SHA_256,
Message = new MemoryStream(Encoding.ASCII.GetBytes(pan.Reveal())),
}, ct).ConfigureAwait(false);
return Convert.ToHexStringLower(mac.Mac.ToArray());
}
/// <summary>Random, not derived from the PAN, so a token reveals nothing about the card.</summary>
private static string NewToken() => "tok_" + Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
}using Harbourline.Cards.Tokenisation;
using Xunit;
public class PanTests
{
// Official public test PANs only (Stripe test cards). Never use real card numbers in code or tests.
[Theory]
[InlineData("4242424242424242")]
[InlineData("4242 4242 4242 4242")]
[InlineData("5555555555554444")]
public void Valid_test_pans_parse_and_mask(string input)
{
var pan = Pan.Parse(input);
Assert.EndsWith(input.Replace(" ", "")[^4..], pan.Masked);
Assert.DoesNotContain(input.Replace(" ", "")[..12], pan.ToString());
}
[Theory]
[InlineData("4242424242424241")] // Luhn failure
[InlineData("12345")] // too short
public void Invalid_pans_are_rejected(string input) =>
Assert.Throws<FormatException>(() => Pan.Parse(input));
[Fact]
public void String_interpolation_never_leaks_the_pan()
{
var pan = Pan.Parse("4242424242424242");
var logLine = $"Tokenising card {pan}";
Assert.DoesNotContain("424242424242", logLine);
}
}In tests, mock IAmazonKeyManagementService to return fixed ciphertext and MACs, and use an in-memory IVaultStore. The tests run without an AWS account.
Code explained line by line
Pan
sealed class Panwith a private field — the PAN is wrapped in a type whoseToString()returns the masked value. Accidentallogger.LogInformation("{Card}", pan)prints dots and four digits, not the PAN (a direct defence against PANs in logs, requirement 3 and 10 territory).Parsestrips non-digits and checks length 12–19 and the Luhn checksum, rejecting typos and junk before any crypto call.Masked— the standard allows displaying at most the BIN and last four digits to people without a business need to see more; showing only the last four is stricter and simpler.Reveal()isinternal— only code inside the tokenisation assembly (inside the CDE) can get the digits.
TokenVault
- Primary constructor injection of
IAmazonKeyManagementServiceandIVaultStore— testable without AWS, and in production the client is registered withAddAWSService<IAmazonKeyManagementService>(). FingerprintAsyncuses KMSGenerateMacwith an HMAC key. PCI DSS v4 expects hashes of PANs to be keyed cryptographic hashes (3.5.1.1 ⚠ VERIFY): a plain SHA-256 of a PAN can be brute-forced because PANs have limited entropy (known BIN, Luhn digit). The HMAC key never leaves KMS.FindTokenByFingerprintAsync— returning the existing token for the same card avoids creating many tokens for one PAN.EncryptAsyncwith encryption context{purpose, token}— the ciphertext can only be decrypted by a caller supplying the same context. A stolen ciphertext row can't be decrypted under a different token, and every decrypt appears in CloudTrail with the token, giving an audit trail of detokenisation.- PANs are under 4 KB, so direct
Encryptis fine; envelope encryption is for larger data. SaveAsync(token, fingerprint, ciphertext, last4)— the vault never stores the PAN in clear, nor CVV (SAD must not be stored after authorisation).DetokeniseAsync— authorisation is enforced by the KMS key policy: only the authorisation adapter's role is allowedkms:Decrypton this key, with a condition onkms:EncryptionContext:purpose.NewToken— random 128-bit tokens, not derived from the PAN. Format-preserving tokens (looking like a 16-digit number) are sometimes needed for legacy systems, but they risk being mistaken for real PANs and need careful design.
Security considerations
⚠ Learning shortcut — not for production
This lesson's vault uses KMS and a mocked store, with no rate limiting, no detokenisation approval workflow and no key-custodian procedures. A production token vault is itself a high-value CDE system: it needs documented key management (requirement 3.6/3.7), strict detokenisation authorisation and monitoring, protection against token enumeration, regular penetration tests and QSA review. Many banks buy tokenisation from a PCI-validated provider or use card-scheme network tokens rather than build one.
- Never use real card numbers in code, tests, tickets or logs — only official test PANs.
- Never store SAD (CVV2, PIN, full track) after authorisation. Issuers have narrow exceptions; that's a QSA conversation, not a code decision.
- Logs are in scope if they can contain PAN. Use CloudWatch Logs data protection policies to detect and mask card numbers as a safety net, and treat any detection as an incident.
- CI/CD that deploys into the CDE is security-impacting. Pipeline roles, artifact buckets and build images need the same rigour as production.
- Penetration testing on AWS doesn't require pre-approval for a list of common services, but the AWS penetration testing policy lists prohibited activities (such as DoS testing without approval) ⚠ VERIFY the current policy before your segmentation test.
Banking use case
Harbourline's "pay off your credit card from another bank's debit card" feature used to post card details through the main web application into the core banking database. The QSA scoped 140 systems, including the data warehouse, because PANs appeared in nightly extracts.
The redesign:
- Card details are entered into an iframe served by the tokenisation service in the CDE account; the web app's page never touches the PAN, though its scripts are inventoried and monitored for the payment-page requirements.
- The tokenisation service returns a token and last four digits to the Payments API in the workload account over PrivateLink.
- The warehouse receives tokens and last four only. Macie scans confirm no PAN patterns in the data lake buckets.
- Segmentation testing from the workload and analytics accounts shows no path to the vault or KMS keys.
The QSA's scope shrank to the CDE account, the identity, logging and CI/CD systems that affect it, and the payment page. The assessment took weeks instead of months. The bank didn't become "compliant by architecture"; it became assessable, with a much smaller surface to protect and prove.
Common mistakes
- "We use AWS, and AWS is PCI compliant, so we're compliant" → AWS's AOC covers AWS's part only; read the Responsibility Summary.
- Flat network "for now" → without segmentation, everything connected to the CDE is in scope. Design the CDE account first.
- Plain SHA-256 of PANs for matching → brute-forceable; use a keyed hash (HMAC) with a protected key.
- PANs in logs, exceptions or analytics → wrap PANs in a type that masks on
ToString(), add log data protection, and scan with Macie. - Forgetting security-impacting systems → identity, logging, CI/CD and admin workstations are in scope for relevant requirements.
- Treating Security Hub CSPM's PCI score as a compliance score → it checks resource configuration, not the many process requirements.
- Bringing in the QSA after the build → scope decisions are expensive to change; involve them at design.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
InvalidCiphertextException on detokenise | Encryption context differs from the one used at encryption (wrong token, typo in purpose) | Use exactly the same context keys and values |
AccessDeniedException on kms:GenerateMac | Key is not an HMAC key, or role not allowed | Create a key with key spec HMAC_256 and usage GENERATE_VERIFY_MAC; update the key policy |
| Macie reports card numbers in a "tokens-only" bucket | A system writes PANs, or test data contains test PANs that match patterns | Trace the writer; for test data, label and isolate test buckets |
| Security Hub CSPM PCI controls show "No data" | AWS Config not recording the required resource types | Enable Config recording for the resources the controls need |
| QSA rejects your segmentation | Paths exist through shared services (DNS, NAT, peering, shared endpoints) | Map every path; restrict with security groups, endpoint policies and SCPs; retest |
aws artifact list-reports returns AccessDenied | Missing Artifact permissions | Add the AWS Artifact read permissions to the role |
Cost and cleanup
This lesson is free as written: design work, local .NET code with mocks, Artifact downloads and read-only CLI commands.
Optional costs if you deploy the vault keys to try the code against real KMS: about USD 1 per month per key (prorated hourly), so two keys for one day is about USD 0.07, plus request charges within the free tier for symmetric and HMAC calls ⚠ VERIFY whether HMAC requests count towards the free tier. Clean up:
aws kms schedule-key-deletion --key-id alias/hl-m05-pan-vault --pending-window-in-days 7 --profile learn-sandbox
aws kms schedule-key-deletion --key-id alias/hl-m05-pan-hmac --pending-window-in-days 7 --profile learn-sandbox
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m05-pci --profile learn-sandboxDo not enable Security Hub CSPM standards or deploy the conformance pack in the sandbox for this lesson; both incur ongoing charges.
Exercises
- 🟢 Guided: Download the PCI DSS Responsibility Summary from AWS Artifact (or, if you can't, use the public AWS PCI DSS FAQ). For requirement 3 (protect stored account data) and requirement 10 (logging), write down in a table what AWS is responsible for, what Harbourline is responsible for, and what is shared, for a design that uses DynamoDB, KMS and Fargate.
- 🟡 Challenge: Draw the scope diagram for a design where the mobile app sends card details to the Payments API, which then calls the tokenisation service. Mark which components are now in scope, and propose a change that takes the Payments API out of scope again.
- 🔴 Live problem: A data scientist asks for "real card numbers, hashed" in the analytics account so they can link card transactions across products for a fraud model. Respond with what you can offer instead.
Assignment
Write a two-page scope and design note for a card-tokenisation capability at Harbourline: the data flows (Mermaid), the CDE account boundary, a table classifying each component (CDE / connected-to / out of scope, marked "proposed — QSA to confirm"), the AWS services used and whether each is on AWS's in-scope list, and the evidence you'd collect for requirement 3 and 10. Add the Pan and TokenVault code with tests to your portfolio repository.
Solutions
Typical split (confirm against the actual Responsibility Summary):
| Area | AWS | Harbourline | Shared |
|---|---|---|---|
| Req 3 — stored data | Physical media destruction; HSM security for KMS; service-side encryption mechanics | Deciding what to store; enabling encryption with appropriate keys; key policies; data retention and deletion; masking | Key management: AWS operates the HSMs, Harbourline controls key policies, rotation and usage |
| Req 10 — logging | Logging of AWS infrastructure; CloudTrail service availability | Enabling CloudTrail, application logs, VPC Flow Logs; retention (at least 12 months, 3 months immediately available ⚠ VERIFY); daily review; protecting logs | Time synchronisation (AWS provides time sources; you configure clients) |
Why: the Responsibility Summary is how a QSA expects you to reason about inherited controls. Anything in the "Harbourline" column needs your own evidence.
If the mobile app sends PANs to the Payments API, the API (and its logs, its task role, its load balancer, its WAF logs, and any service it shares a network with) handles PAN and enters the CDE. Its CI/CD becomes security-impacting.
Fix: the mobile app calls the tokenisation endpoint in the CDE directly (or uses a payment provider's SDK) and sends only the token to the Payments API. The Payments API then never sees PAN and, with tested segmentation, can be proposed as out of scope.
Why: scope follows the data. The single decision of which endpoint receives the PAN determines the scope of a whole service and its dependencies.
"Hashed card numbers" are still cardholder data in practice if they can be reversed by brute force, and moving them into analytics would pull the analytics account into scope. Offer instead: (1) the token (stable per card, because the vault deduplicates by keyed fingerprint), which links transactions across products without any PAN; (2) the last four digits and BIN-level attributes (card brand, issuing country) if the fraud model needs them; (3) if they truly need a separate pseudonymous ID, an HMAC produced inside the CDE with a dedicated key, reviewed with the QSA and the data-protection team. Record the decision in the threat model and data-flow inventory.
Knowledge check
Answer: AWS's AOC covers the controls AWS is responsible for in the in-scope services (physical, infrastructure, managed service components). A QSA can rely on it for that portion without retesting. Everything about how the customer configures and operates services, plus the customer's processes, must be assessed separately. The Responsibility Summary in AWS Artifact explains the split.
Answer: Systems that are not in the CDE but can affect its security — identity providers, logging and SIEM, CI/CD that deploys to the CDE, jump hosts, DNS, patch servers. They are in scope for the requirements relevant to their role, so they must be included in scope and protected.
Answer: PANs have limited entropy (known BIN ranges and a Luhn check digit), so an attacker can compute hashes for all plausible PANs and match them. PCI DSS v4 expects keyed cryptographic hashes; an HMAC with a key held in KMS or an HSM prevents offline brute force.
Answer: No. It continuously checks the configuration of AWS resources against controls mapped to PCI DSS. It can't assess policies, training, physical processes, application code, or many operational requirements, and a QSA makes the compliance determination.
Answer: Systems that only handle tokens (which can't be used to recover the PAN without access to the vault) don't store, process or transmit cardholder data. If they also can't affect the vault's security (segmentation), the QSA can treat them as out of scope. Only the vault and components that see PANs remain in the CDE.
Interview questions
- "How would you design a card-processing workload on AWS for PCI DSS?" — Start with data discovery and minimise where PAN exists; tokenise at the edge or outsource capture to a validated provider; dedicate an account in a PCI OU with SCPs/RCPs; PrivateLink and tight security groups for the few flows in and out; KMS keys with key policies that restrict decrypt to the authorisation component; logging into a separate archive; evidence via Security Hub CSPM and Config; segmentation testing; and the QSA involved from design.
- "What does AWS's PCI attestation give you?" — Assurance for AWS's part of shared controls, which a QSA can rely on without retesting; not compliance for my workload.
- "What is the difference between encryption and tokenisation for scope?" — Encrypted PAN is still cardholder data and the systems with access to the keys remain in scope; tokenisation removes PAN from downstream systems entirely, so they can potentially be out of scope.
- "What changed in PCI DSS v4?" — More emphasis on continuous security and flexibility: the customised approach, targeted risk analyses, MFA for all access into the CDE, keyed hashes for PAN, automated log review, payment-page script controls, and scope confirmation every year. The future-dated requirements became mandatory on 31 March 2025.
Certification practice
An auditor asks a bank for AWS's PCI DSS Attestation of Compliance for the services the bank uses. Where should the security engineer obtain it?
A. Open an AWS Support case to request the report. B. Download it from AWS Artifact. C. Generate it from AWS Security Hub CSPM's PCI DSS standard. D. Export it from AWS Config's PCI DSS conformance pack.
Answer: B. AWS Artifact provides on-demand access to AWS's compliance reports, including the PCI DSS AOC and Responsibility Summary. A isn't necessary. C and D produce findings about the customer's configuration, not AWS's attestation.
A company processes card payments in a single AWS account that also hosts its analytics platform. The QSA has placed the analytics systems in scope because they share network paths with the payment systems. Which design change MOST reduces PCI DSS scope?
A. Enable encryption at rest on all analytics data stores. B. Move payment processing to a dedicated account, tokenise card numbers so analytics receives only tokens, and allow only specific private connectivity between the accounts. C. Add AWS WAF to the analytics platform. D. Enable Amazon GuardDuty in the account.
Answer: B. Account separation plus tokenisation removes cardholder data from analytics and creates a testable segmentation boundary. A protects data but encrypted PAN is still in scope. C and D add controls without changing scope.
A tokenisation service must detect whether a card has already been tokenised without storing the PAN in clear and without allowing offline brute-force of stored values. Which approach meets the requirement?
A. Store an unsalted SHA-256 hash of each PAN. B. Store a SHA-256 hash with a per-record random salt. C. Store an HMAC of each PAN computed with an AWS KMS HMAC key. D. Store the PAN encrypted with an AWS managed key and compare ciphertexts.
Answer: C. An HMAC with a protected key is deterministic (so duplicates match) and can't be brute-forced without the key. A is brute-forceable. B prevents duplicate matching because each salt differs. D — KMS encryption is non-deterministic, so ciphertexts of the same PAN differ.
Completion checklist
- I can explain CDE, connected-to/security-impacting and out-of-scope systems
- I know where to find AWS's PCI AOC and Responsibility Summary and what they cover
- I can design scope reduction with tokenisation and account segmentation
- I ran the
Pantests and understand why the type masks itself - I can explain why Security Hub CSPM and Config conformance packs are evidence aids, not compliance
- I created no ongoing charges (or scheduled any KMS keys for deletion)
Key takeaways
- PCI DSS v4.0.1 applies wherever cardholder data is stored, processed or transmitted, and to systems that can affect its security; scope is the biggest cost driver.
- Tokenisation, a dedicated CDE account and tested segmentation are the main levers for reducing scope; scope follows the data.
- AWS is a PCI DSS Level 1 service provider; its AOC and Responsibility Summary in AWS Artifact cover AWS's part only.
- Use keyed hashes for PAN fingerprints, never store SAD after authorisation, and keep PANs out of logs by design.
- Security Hub CSPM and Config packs help produce evidence. Compliance is determined by your organisation's assessment with its QSA.
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.
Secure code review checklist for .NET on AWS
Review every Harbourline pull request against twenty concrete checks — from object-level authorisation and idempotent payments to AWS credentials, logging of personal data and SSRF — each with a bad and a good C# example.
UK GDPR and data residency
Design AWS workloads that respect UK GDPR: lawful basis, minimisation, the right to erasure versus immutable logs (pseudonymisation and crypto-shredding in .NET), international transfers, Region choice and residency guardrails. Concepts only — legal and DPO review required.