SkillSprout
Chapter 9 · Lesson 3
Intermediate
5 min read

Sensitive Data: Classification, Masking and Sanitisation

Overview

Not all data deserves the same protection. PII (personally identifiable information such as names, emails and national IDs) and PHI (protected health information) carry legal duties under regulations like GDPR and HIPAA. Data classification tags data by sensitivity so you can apply the right controls: encryption, access limits, retention and logging.

Think of classification as colour-coded folders in an office: public brochures sit on an open shelf, internal memos in a filing cabinet and personnel records in a locked safe.

Developers must also mask or sanitise sensitive values in logs, responses and test data so a debug log or a lower environment never becomes a data leak.

Key Concepts

  • Classification levels commonly include public, internal, confidential and restricted; controls scale with the level.
  • Amazon Macie discovers and classifies sensitive data (PII, credentials) in S3 using managed and custom data identifiers.
  • CloudWatch Logs data protection policies detect and mask sensitive values in log events automatically.
  • Masking hides part of a value (****1234); tokenisation swaps it for a random token stored in a vault; hashing is one-way.
  • Sanitisation also means validating and escaping input and removing sensitive fields from outputs and exceptions.
  • Environment variables are encrypted at rest but visible to anyone with lambda:GetFunctionConfiguration; use Secrets Manager for real secrets.
  • Minimise and retain briefly: collect only needed data and delete it with TTL and lifecycle rules.
  • Use separate accounts or environments and synthetic data for development and testing.

Detailed Notes

Classification and controls

ClassExamplesTypical controls
PublicMarketing pagesIntegrity only
InternalDesign docsAuthentication, TLS
ConfidentialCustomer listsKMS CMK, least privilege, access logging
RestrictedPHI, card data, credentialsClient-side or field-level encryption, tokenisation, strict retention, MFA delete

Tag resources with a DataClass tag and write IAM or SCP conditions on it (aws:ResourceTag/DataClass) so only approved roles reach restricted data.

Finding sensitive data with Macie

Enable Macie, create a classification job over buckets, and review findings such as SensitiveData:S3Object/Personal. Findings flow to EventBridge and Security Hub so you can auto-remediate, for example by quarantining the object or alerting its owner. Macie also reports publicly accessible and unencrypted buckets.

Masking in logs

Logs are the most common accidental leak. Never log full request bodies or tokens. Mask before logging and use platform features as a safety net.

python
import re, logging
log = logging.getLogger()

def mask_email(v): return re.sub(r"(^.).*(@.*$)", r"\1***\2", v)
def mask_card(v):  return "**** **** **** " + v[-4:]

def handler(event, context):
    body = json.loads(event["body"])
    log.info("order received user=%s card=%s", mask_email(body["email"]), mask_card(body["card"]))

A CloudWatch Logs data protection policy masks matching patterns (email addresses, credit cards, AWS secret keys) for all readers except those with the logs:Unmask permission.

json
{
  "Name": "mask-pii",
  "Version": "2021-06-01",
  "Statement": [{
    "Sid": "audit", "DataIdentifier": ["arn:aws:dataprotection::aws:data-identifier/EmailAddress",
                                       "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"],
    "Operation": { "Audit": { "FindingsDestination": {} } }
  }, {
    "Sid": "redact", "DataIdentifier": ["arn:aws:dataprotection::aws:data-identifier/EmailAddress",
                                        "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber"],
    "Operation": { "Deidentify": { "MaskConfig": {} } }
  }]
}

Tokenisation and field-level protection

Replace a card number with a random token and keep the mapping in a locked-down store. Downstream systems use the token only. For field-level protection in a document, encrypt only the sensitive attributes (client-side) and keep others searchable.

python
import secrets
def tokenise(pan):
    token = "tok_" + secrets.token_urlsafe(16)
    vault.put_item(Item={"token": token, "pan_enc": encrypt(pan)})   # vault table, strict IAM, KMS CMK
    return token

Environment variables and configuration

Encryption at rest of Lambda environment variables uses KMS, but values show in plaintext in the console and API to authorised users. For secrets, store a secret ARN in the variable and fetch the value at runtime with caching. Enable encryption helpers (client-side encryption of a variable with a CMK) for extra protection.

Test data and lower environments

Do not copy production PII into dev. Generate synthetic data, or mask a copy with a controlled job (for example a Glue job or SQL script) before it leaves production boundaries. Use separate AWS accounts for environments, and restrict snapshot sharing.

Response and error sanitisation

Return generic errors to clients and log detail internally. Strip internal fields (password hashes, internal IDs) from API responses using response mappings or serialisation allow-lists. Validate and escape all input to prevent injection, and use parameterised queries.

Retention and deletion

Keep data only as long as needed: DynamoDB TTL, S3 lifecycle expiry, CloudWatch Logs retention and Secrets Manager scheduled deletion. Support deletion requests by keeping an index of where a subject's data lives.

Real World Example

A health-tech startup found patient emails in CloudWatch Logs after a developer logged entire request bodies during an incident. They removed body logging, added masking helpers, and attached a CloudWatch Logs data protection policy that redacts email and phone patterns. Macie now scans their S3 export buckets weekly and posts findings to Security Hub, and staging uses synthetic patients generated by a seed script.

Architecture Diagram

Protecting sensitive data end to end
Architecture
Data protection
S3 datatagged by class
MaciePII findings
EventBridge
Logsmasked

Classify, protect, mask and audit across storage and logs.

  1. 1Data is tagged with a classification level when stored.
  2. 2Macie scans S3 and reports sensitive data findings.
  3. 3EventBridge routes findings to remediation or alerting.
  4. 4Application logs are masked so sensitive values never reach readers.

Best Practices

  • ✓Classify data and tie IAM, encryption and retention to the class.
  • ✓Never log secrets, tokens or full request bodies; mask PII before logging.
  • ✓Use Macie and CloudWatch Logs data protection as detective safety nets.
  • ✓Keep real secrets in Secrets Manager, not plain environment variables.
  • ✓Use synthetic or masked data in non-production environments.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • 'Discover PII in S3' means Amazon Macie.
  • Automatic masking in log events is a CloudWatch Logs data protection policy.
  • Secrets belong in Secrets Manager or SecureString, not plain environment variables.
  • Lower environments should not contain production PII; use synthetic or masked data.

Finished this lesson?

0 of 46 lessons done · 0% of the course