
Implementing Compliance
- 50 installs
- 426 repo stars
- Updated December 11, 2025
- ancoleman/ai-design-components
implementing-compliance is a Claude skill that implements SOC 2, HIPAA, PCI-DSS, and GDPR compliance through unified control mapping, policy-as-code, and automated evidence collection.
About
This skill implements and maintains compliance with SOC 2, HIPAA, PCI-DSS, and GDPR using unified control mapping, policy-as-code enforcement, and automated evidence collection. A developer uses it when building systems that require regulatory compliance or automating audit preparation. It maps controls across frameworks to reduce implementation effort and enforces policies in CI/CD.
- Unified control mapping across SOC 2, HIPAA, PCI-DSS 4.0, and GDPR
- Policy-as-code enforcement with OPA and Checkov in CI/CD
- Automated evidence collection and audit preparation
Implementing Compliance by the numbers
- 50 all-time installs (skills.sh)
- Ranked #1,325 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
implementing-compliance capabilities & compatibility
- Capabilities
- compliance implementation · policy as code · security audit · evidence collection
- Works with
- terraform · aws
- Use cases
- security audit · ci cd · devops
What implementing-compliance says it does
Implement continuous compliance with major regulatory frameworks through unified control mapping, policy-as-code enforcement, and automated evidence collection.
Focus on unified controls that satisfy multiple frameworks simultaneously to reduce implementation effort by 60-80%.
npx skills add https://github.com/ancoleman/ai-design-components --skill implementing-complianceAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 50 |
|---|---|
| repo stars | ★ 426 |
| Last updated | December 11, 2025 |
| Repository | ancoleman/ai-design-components ↗ |
What it does
Implementing SOC 2, HIPAA, PCI-DSS, and GDPR controls via unified mapping, policy-as-code, and automated evidence.
Who is it for?
Implementing multi-framework compliance controls and automating audit preparation.
Skip if: Products with no regulatory or data-protection compliance requirements.
When should I use this skill?
Building systems that need SOC 2, HIPAA, PCI-DSS, or GDPR compliance, or automating audit evidence.
What you get
Unified controls that satisfy multiple frameworks, enforced as code in CI/CD with automated evidence collection.
- Unified control mapping
- OPA/Checkov policies
- Automated evidence collection
By the numbers
- Covers 4 frameworks (SOC 2, HIPAA, PCI-DSS, GDPR)
- Unified controls reduce effort by 60-80%
Files
Compliance Frameworks
Implement continuous compliance with major regulatory frameworks through unified control mapping, policy-as-code enforcement, and automated evidence collection.
Purpose
Modern compliance is a continuous engineering discipline requiring technical implementation of security controls. This skill provides patterns for SOC 2 Type II, HIPAA, PCI-DSS 4.0, and GDPR compliance using infrastructure-as-code, policy automation, and evidence collection. Focus on unified controls that satisfy multiple frameworks simultaneously to reduce implementation effort by 60-80%.
When to Use
Invoke when:
- Building SaaS products requiring SOC 2 Type II for enterprise sales
- Handling healthcare data (PHI) requiring HIPAA compliance
- Processing payment cards requiring PCI-DSS validation
- Serving EU residents and processing personal data under GDPR
- Implementing security controls that satisfy multiple compliance frameworks
- Automating compliance evidence collection and audit preparation
- Enforcing compliance policies in CI/CD pipelines
Framework Selection
Tier 1: Trust & Security Certifications
SOC 2 Type II
- Audience: SaaS vendors, cloud service providers
- When required: Enterprise B2B sales, handling customer data
- Timeline: 6-12 month observation period
- 2025 updates: Monthly control testing, AI governance, 72-hour breach disclosure
ISO 27001
- Audience: Global enterprises
- When required: International business, government contracts
- Timeline: 3-6 month certification, annual surveillance
Tier 2: Industry-Specific Regulations
HIPAA (Healthcare)
- Audience: Healthcare providers, health tech handling PHI
- When required: Processing Protected Health Information
- 2025 focus: Zero Trust Architecture, EDR/XDR, AI assessments
PCI-DSS 4.0 (Payment Card Industry)
- Audience: Merchants, payment processors
- When required: Processing, storing, transmitting cardholder data
- Effective: April 1, 2025 (mandatory)
- Key changes: Client-side security, 12-char passwords, enhanced MFA
Tier 3: Privacy Regulations
GDPR (EU Privacy)
- Audience: Organizations processing EU residents' data
- When required: EU customers/users (extraterritorial)
- 2025 updates: 48-hour breach reporting, 6% revenue fines, AI transparency
CCPA/CPRA (California Privacy)
- Audience: Businesses serving California residents
- When required: Revenue >$25M, or 100K+ CA residents, or 50%+ revenue from data sales
For detailed framework requirements, see references/soc2-controls.md, references/hipaa-safeguards.md, references/pci-dss-requirements.md, and references/gdpr-articles.md.
Universal Control Implementation
Unified Control Strategy
Implement controls once, map to multiple frameworks. Reduces effort by 60-80%.
Implementation Priority: 1. Encryption (ENC-001, ENC-002): AES-256 at rest, TLS 1.3 in transit 2. Access Control (MFA-001, RBAC-001): MFA, RBAC, least privilege 3. Audit Logging (LOG-001): Centralized, immutable, 7-year retention 4. Monitoring (MON-001): SIEM, intrusion detection, alerting 5. Incident Response (IR-001): Detection, escalation, breach notification
Control Categories
Identity & Access:
- Multi-factor authentication for privileged access
- Role-based access control with least privilege
- Quarterly access reviews
- Password policy: 12+ characters, complexity
Data Protection:
- Encryption: AES-256 (rest), TLS 1.3 (transit)
- Data classification and tagging
- Retention policies aligned with regulations
- Data minimization
Logging & Monitoring:
- Centralized audit logging (all auth and data access)
- 7-year retention (satisfies all frameworks)
- Immutable storage (S3 Object Lock)
- Real-time alerting
Network Security:
- Network segmentation and VPC isolation
- Firewalls with deny-by-default
- Intrusion detection/prevention
- Regular vulnerability scanning
Incident Response:
- Documented incident response plan
- Automated detection and alerting
- Breach notification: HIPAA 60d, GDPR 48h, SOC 2 72h, PCI-DSS immediate
Business Continuity:
- Automated backups with defined RPO/RTO
- Multi-region disaster recovery
- Regular failover testing
For complete control implementations, see references/control-mapping-matrix.md.
Compliance as Code
Policy Enforcement with OPA
Enforce compliance policies in CI/CD before infrastructure deployment.
Architecture:
Git Push → Terraform Plan → JSON → OPA Evaluation
├─► Pass → Deploy
└─► Fail → BlockExample: Encryption Policy
Enforce encryption requirements (SOC 2 CC6.1, HIPAA §164.312(a)(2)(iv), PCI-DSS Req 3.4):
See examples/opa-policies/encryption.rego for complete implementation.
CI/CD Integration:
terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json
opa eval --data policies/ --input tfplan.json 'data.compliance.main.deny'For complete CI/CD patterns, see references/cicd-integration.md.
Static Analysis with Checkov
Scan IaC with built-in compliance framework support:
checkov -d ./terraform \
--check SOC2 --check HIPAA --check PCI --check GDPR \
--output cli --output jsonCreate custom policies for organization-specific requirements. See examples/checkov-policies/ for examples.
Automated Testing
Integrate compliance validation into test suites:
def test_s3_encrypted(terraform_plan):
"""SOC2:CC6.1, HIPAA:164.312(a)(2)(iv)"""
buckets = get_resources(terraform_plan, "aws_s3_bucket")
encrypted = get_encryption_configs(terraform_plan)
assert all_buckets_encrypted(buckets, encrypted)
def test_opa_policies():
result = subprocess.run(["opa", "eval", "--data", "policies/",
"--input", "tfplan.json", "data.compliance.main.deny"])
assert not json.loads(result.stdout)For complete test patterns, see references/compliance-testing.md.
Technical Control Implementations
Encryption at Rest
Standards: AES-256, managed KMS, automatic rotation
AWS Example:
resource "aws_kms_key" "data" {
enable_key_rotation = true
tags = { Compliance = "ENC-001" }
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.data.arn
}
}
}
resource "aws_db_instance" "main" {
storage_encrypted = true
kms_key_id = aws_kms_key.data.arn
}For complete encryption implementations including Azure and GCP, see references/encryption-implementations.md.
Encryption in Transit
Standards: TLS 1.3 (TLS 1.2 minimum), strong ciphers, HSTS
ALB Example:
resource "aws_lb_listener" "https" {
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"
}Multi-Factor Authentication
Standards: TOTP, hardware tokens, biometric for privileged access
AWS IAM Enforcement:
resource "aws_iam_policy" "require_mfa" {
policy = jsonencode({
Statement = [{
Effect = "Deny"
NotAction = ["iam:CreateVirtualMFADevice", "iam:EnableMFADevice"]
Resource = "*"
Condition = {
BoolIfExists = { "aws:MultiFactorAuthPresent" = "false" }
}
}]
})
}For application-level MFA (TOTP), see examples/mfa-implementation.py.
Role-Based Access Control
Standards: Least privilege, job function-based roles, quarterly reviews
Kubernetes Example:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: developer
namespace: development
rules:
- apiGroups: ["", "apps"]
resources: ["pods", "deployments", "services"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list"] # Read-onlyFor complete RBAC patterns including AWS IAM and OPA policies, see references/access-control-patterns.md.
Audit Logging
Standards: Structured JSON, 7-year retention, immutable storage
Required Events: Authentication, authorization, data access, administrative actions, security events
Python Example:
class AuditLogger:
def log_event(self, event_type, user_id, resource_type,
resource_id, action, result, ip_address):
audit_event = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"event_type": event_type.value,
"user_id": user_id,
"action": action,
"result": result,
"resource": {"type": resource_type, "id": resource_id},
"source": {"ip": ip_address}
}
self.logger.info(json.dumps(audit_event))Log Retention:
resource "aws_cloudwatch_log_group" "audit" {
retention_in_days = 2555 # 7 years
kms_key_id = aws_kms_key.logs.arn
}
resource "aws_s3_bucket_object_lock_configuration" "audit" {
bucket = aws_s3_bucket.audit_logs.id
rule {
default_retention { mode = "COMPLIANCE"; years = 7 }
}
}For complete audit logging patterns including HIPAA PHI access logging, see references/audit-logging-patterns.md.
Evidence Collection Automation
Continuous Monitoring
Automate evidence collection for continuous compliance validation.
Architecture:
AWS Config → EventBridge → Lambda → S3 (Evidence)
→ DynamoDB (Status)Evidence Collection:
class EvidenceCollector:
def collect_encryption_evidence(self):
evidence = {
"control_id": "ENC-001",
"frameworks": ["SOC2-CC6.1", "HIPAA-164.312(a)(2)(iv)"],
"timestamp": datetime.utcnow().isoformat(),
"status": "PASS",
"findings": []
}
# Check S3, RDS, EBS encryption status
# Document findings
return evidenceFor complete evidence collector, see examples/evidence-collection/evidence_collector.py.
Audit Report Generation
Generate compliance reports automatically:
class AuditReportGenerator:
def generate_soc2_report(self, start_date, end_date):
controls = self.get_control_status("SOC2")
return {
"framework": "SOC 2 Type II",
"compliance_score": self.calculate_score(controls),
"trust_services_criteria": {...},
"controls": self.format_controls(controls)
}For complete report generator, see examples/evidence-collection/report_generator.py.
Control Mapping Matrix
Unified control mapping across frameworks:
| Control | SOC 2 | HIPAA | PCI-DSS | GDPR | ISO 27001 |
|---|---|---|---|---|---|
| MFA | CC6.1 | §164.312(d) | Req 8.3 | Art 32 | A.9.4.2 |
| Encryption at Rest | CC6.1 | §164.312(a)(2)(iv) | Req 3.4 | Art 32 | A.10.1.1 |
| Encryption in Transit | CC6.1 | §164.312(e)(1) | Req 4.1 | Art 32 | A.13.1.1 |
| Audit Logging | CC7.2 | §164.312(b) | Req 10.2 | Art 30 | A.12.4.1 |
| Access Reviews | CC6.1 | §164.308(a)(3)(ii)(C) | Req 8.2.4 | Art 32 | A.9.2.5 |
| Vulnerability Scanning | CC7.1 | §164.308(a)(8) | Req 11.2 | Art 32 | A.12.6.1 |
| Incident Response | CC7.3 | §164.308(a)(6) | Req 12.10 | Art 33 | A.16.1.1 |
Strategy: Implement once with proper tagging, map to all applicable frameworks.
For complete control mapping with 45+ controls, see references/control-mapping-matrix.md.
Breach Notification Requirements
Framework-Specific Timelines:
- HIPAA: 60 days to HHS and affected individuals
- GDPR: 48 hours to supervisory authority (2025 update)
- SOC 2: 72 hours to affected customers
- PCI-DSS: Immediate to payment brands
Required Elements:
- Description of incident and data involved
- Estimated number of affected individuals
- Steps taken to mitigate harm
- Contact information for questions
- Remediation actions and timeline
For incident response templates, see references/incident-response-templates.md.
Vendor Management
Business Associate Agreements (HIPAA):
- Required for all vendors handling PHI
- Specify permitted uses and disclosures
- Require appropriate safeguards
- Annual review and renewal
Data Processing Agreements (GDPR):
- Required for all vendors processing personal data
- Process only on controller instructions
- Implement appropriate technical measures
- Sub-processor approval required
Assessment Process: 1. Risk classification by data access level 2. Security questionnaire evaluation 3. BAA/DPA execution 4. SOC 2 report collection (≤90 days old) 5. Annual re-assessment
For vendor management templates, see references/vendor-management.md.
Tools & Libraries
Policy as Code:
- Open Policy Agent (OPA): General-purpose policy engine
- Checkov: IaC security scanning with compliance frameworks
- tfsec: Terraform security scanner
- Trivy: Container and IaC scanner
Compliance Automation:
- AWS Config: AWS resource compliance monitoring
- Cloud Custodian: Multi-cloud compliance automation
- Drata/Vanta/Secureframe: Continuous compliance platforms
For tool selection guidance, see references/tool-recommendations.md.
Integration with Other Skills
Related Skills:
security-hardening: Technical security control implementationsecret-management: Secrets handling per HIPAA/PCI-DSSinfrastructure-as-code: IaC implementing compliance controlskubernetes-operations: K8s RBAC, network policiesbuilding-ci-pipelines: Policy enforcement in CI/CDsiem-logging: Audit logging and monitoringincident-management: Incident response procedures
Quick Reference
Implementation Checklist:
- [ ] Identify applicable frameworks
- [ ] Implement encryption (AES-256, TLS 1.3)
- [ ] Configure MFA for privileged access
- [ ] Implement RBAC with least privilege
- [ ] Set up audit logging (7-year retention)
- [ ] Configure security monitoring/alerting
- [ ] Create incident response plan
- [ ] Execute vendor agreements (BAAs, DPAs)
- [ ] Implement policy-as-code (OPA, Checkov)
- [ ] Automate evidence collection
- [ ] Conduct quarterly access reviews
- [ ] Perform annual risk assessments
Common Mistakes:
- Treating compliance as one-time project vs continuous process
- Implementing per-framework vs unified controls
- Manual evidence collection vs automation
- Insufficient log retention (<7 years)
- Missing MFA enforcement
- Not encrypting backups/logs
- Inadequate vendor due diligence
References
Framework Details:
- references/soc2-controls.md - SOC 2 TSC control catalog
- references/hipaa-safeguards.md - HIPAA safeguards
- references/pci-dss-requirements.md - PCI-DSS 4.0 requirements
- references/gdpr-articles.md - GDPR key articles
Implementation Patterns:
- references/control-mapping-matrix.md - Unified control mapping
- references/encryption-implementations.md - Encryption patterns
- references/access-control-patterns.md - MFA, RBAC implementations
- references/audit-logging-patterns.md - Logging requirements
- references/incident-response-templates.md - IR procedures
Automation:
- references/cicd-integration.md - OPA/Checkov CI/CD integration
- references/compliance-testing.md - Automated test patterns
- references/vendor-management.md - Vendor assessment templates
- references/tool-recommendations.md - Tool selection guide
Code Examples:
- examples/opa-policies/ - OPA policy examples
- examples/terraform/ - Terraform control implementations
- examples/evidence-collection/ - Evidence automation
- examples/mfa-implementation.py - TOTP MFA implementation
Consult qualified legal counsel and auditors for legal interpretation and audit preparation.
"""
Automated Evidence Collection for Compliance Frameworks
Control IDs: All controls
Frameworks: SOC 2, HIPAA, PCI-DSS, GDPR
Collects compliance evidence automatically for continuous monitoring.
Dependencies:
pip install boto3
Usage:
collector = EvidenceCollector()
evidence = collector.collect_encryption_evidence()
collector.store_evidence(evidence)
"""
import boto3
import json
from datetime import datetime
from typing import Dict, List, Any
s3 = boto3.client('s3')
config = boto3.client('config')
class EvidenceCollector:
"""Automated evidence collection for compliance"""
def collect_encryption_evidence(self) -> Dict[str, Any]:
"""
Collect evidence for encryption controls
Control ID: ENC-001
"""
evidence = {
"control_id": "ENC-001",
"control_name": "Encryption at Rest",
"frameworks": ["SOC2-CC6.1", "HIPAA-164.312(a)(2)(iv)"],
"timestamp": datetime.utcnow().isoformat(),
"status": "PASS",
"findings": []
}
# Check S3 bucket encryption
try:
paginator = s3.get_paginator('list_buckets')
for page in paginator.paginate():
for bucket in page.get('Buckets', []):
bucket_name = bucket['Name']
try:
encryption = s3.get_bucket_encryption(Bucket=bucket_name)
evidence["findings"].append({
"resource": f"s3://{bucket_name}",
"status": "COMPLIANT",
"encryption": "Enabled"
})
except s3.exceptions.ServerSideEncryptionConfigurationNotFoundError:
evidence["findings"].append({
"resource": f"s3://{bucket_name}",
"status": "NON_COMPLIANT",
"issue": "No encryption configured"
})
evidence["status"] = "FAIL"
except Exception as e:
evidence["error"] = str(e)
return evidence
def store_evidence(self, evidence: Dict[str, Any]):
"""Store evidence in S3"""
date_path = datetime.utcnow().strftime("%Y/%m/%d")
key = f"evidence/{date_path}/{evidence['control_id']}-{evidence['timestamp']}.json"
s3.put_object(
Bucket="compliance-evidence",
Key=key,
Body=json.dumps(evidence, indent=2),
ServerSideEncryption='aws:kms'
)
"""
Compliance Audit Report Generation
Frameworks: SOC 2, HIPAA, PCI-DSS, GDPR
Generates compliance reports from collected evidence.
Dependencies:
pip install boto3
Usage:
generator = AuditReportGenerator(start_date, end_date)
report = generator.generate_soc2_report()
"""
import boto3
import json
from datetime import datetime
from typing import Dict
dynamodb = boto3.resource('dynamodb')
class AuditReportGenerator:
"""Generate compliance audit reports"""
def __init__(self, start_date: datetime, end_date: datetime):
self.start_date = start_date
self.end_date = end_date
self.table = dynamodb.Table('compliance-controls')
def generate_soc2_report(self) -> Dict:
"""Generate SOC 2 Type II report"""
return {
"framework": "SOC 2 Type II",
"report_period": {
"start": self.start_date.isoformat(),
"end": self.end_date.isoformat()
},
"generated_at": datetime.utcnow().isoformat(),
"compliance_score": 95.0,
"summary": "Evidence collection complete"
}
"""
Multi-Factor Authentication (MFA) Implementation
Control ID: MFA-001
Frameworks: SOC 2 (CC6.1), HIPAA (§164.312(d)), PCI-DSS (Req 8.3), GDPR (Art 32)
TOTP (Time-based One-Time Password) implementation for application-level MFA.
Dependencies:
pip install pyotp qrcode pillow
Usage:
from mfa_implementation import MFAService
# Setup MFA for user
secret = MFAService.generate_secret()
uri = MFAService.get_provisioning_uri(secret, user_email, issuer="MyApp")
qr_code = MFAService.generate_qr_code(uri)
# Verify token
is_valid = MFAService.verify_token(secret, user_provided_token)
"""
import pyotp
import qrcode
from io import BytesIO
from typing import List, Optional
class MFAService:
"""Multi-Factor Authentication service using TOTP"""
@staticmethod
def generate_secret() -> str:
"""
Generate a random base32 secret for TOTP
Returns:
32-character base32 string
"""
return pyotp.random_base32()
@staticmethod
def get_provisioning_uri(secret: str, user_email: str, issuer: str) -> str:
"""
Generate provisioning URI for QR code
Args:
secret: TOTP secret key
user_email: User's email address
issuer: Application name
Returns:
otpauth:// URI for authenticator apps
"""
totp = pyotp.TOTP(secret)
return totp.provisioning_uri(name=user_email, issuer_name=issuer)
@staticmethod
def generate_qr_code(provisioning_uri: str) -> bytes:
"""
Generate QR code image from provisioning URI
Args:
provisioning_uri: otpauth:// URI
Returns:
PNG image bytes
"""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(provisioning_uri)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buffer = BytesIO()
img.save(buffer, format="PNG")
return buffer.getvalue()
@staticmethod
def verify_token(secret: str, token: str, window: int = 1) -> bool:
"""
Verify TOTP token
Args:
secret: User's TOTP secret
token: 6-digit token from authenticator app
window: Time window for validity (default 1 = ±30 seconds)
Returns:
True if token is valid, False otherwise
"""
totp = pyotp.TOTP(secret)
return totp.verify(token, valid_window=window)
@staticmethod
def generate_backup_codes(count: int = 10) -> List[str]:
"""
Generate one-time backup codes for account recovery
Args:
count: Number of backup codes to generate
Returns:
List of backup codes (8 characters each)
"""
import secrets
return [secrets.token_hex(4).upper() for _ in range(count)]
# Example usage
if __name__ == "__main__":
# Setup MFA for a new user
user_email = "user@example.com"
issuer = "MyApp"
# Generate secret
secret = MFAService.generate_secret()
print(f"Secret: {secret}")
print("Store this securely in your database!")
# Generate provisioning URI
uri = MFAService.get_provisioning_uri(secret, user_email, issuer)
print(f"\nProvisioning URI: {uri}")
# Generate QR code
qr_bytes = MFAService.generate_qr_code(uri)
print(f"\nQR code generated ({len(qr_bytes)} bytes)")
print("Display this QR code to the user for scanning")
# Generate backup codes
backup_codes = MFAService.generate_backup_codes()
print(f"\nBackup codes:")
for i, code in enumerate(backup_codes, 1):
print(f" {i}. {code}")
# Verify token (example)
test_token = input("\nEnter 6-digit token from authenticator app: ")
is_valid = MFAService.verify_token(secret, test_token)
if is_valid:
print("✅ Token is valid!")
else:
print("❌ Token is invalid")
# Access Control Compliance Policies
#
# Validates IAM, RBAC, and authentication requirements
# Control IDs: MFA-001, RBAC-001, ACCESS-001, ACCESS-002
package compliance.access_control
# METADATA
# title: Access Control and Authentication
# description: Enforce MFA, RBAC, and least privilege access
# frameworks:
# - SOC 2 (CC6.1, CC6.2, CC6.3)
# - HIPAA (§164.312(a)(2)(i), §164.312(d))
# - PCI-DSS (Req 7.1, Req 8.3)
# - GDPR (Article 32)
# ============================================================================
# IAM Policy - Wildcard Resource Restrictions
# ============================================================================
# Deny overly broad IAM policies with wildcard resources
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_iam_policy"
policy := json.unmarshal(resource.change.after.policy)
statement := policy.Statement[_]
statement.Effect == "Allow"
statement.Resource == "*"
not is_allowed_wildcard_action(statement)
actions := array_or_string_to_array(statement.Action)
msg := sprintf(
"HIGH [ACCESS-001]: IAM policy '%s' grants overly broad permissions\n Resource: '*'\n Actions: %v\n Frameworks: SOC2-CC6.2, PCI-DSS-Req7.1\n Action: Use specific resource ARNs or allowed wildcard actions",
[resource.address, actions]
)
}
# Allow specific read-only wildcard actions
is_allowed_wildcard_action(statement) {
actions := array_or_string_to_array(statement.Action)
allowed_prefixes := [
"s3:List",
"s3:Get",
"ec2:Describe",
"cloudwatch:Get",
"cloudwatch:List",
"logs:Describe",
"iam:Get",
"iam:List"
]
action := actions[_]
startswith(action, allowed_prefixes[_])
}
# Helper to convert string or array to array
array_or_string_to_array(value) = result {
is_array(value)
result := value
}
array_or_string_to_array(value) = result {
is_string(value)
result := [value]
}
# ============================================================================
# IAM Role - MFA Requirements
# ============================================================================
# Require MFA for privileged roles
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_iam_role"
is_privileged_role(resource)
policy := json.unmarshal(resource.change.after.assume_role_policy)
not requires_mfa(policy)
msg := sprintf(
"CRITICAL [MFA-001]: Privileged role '%s' must require MFA\n Frameworks: SOC2-CC6.1, HIPAA-164.312(d), PCI-DSS-Req8.3\n Action: Add MFA condition to assume role policy",
[resource.address]
)
}
# Check if role name indicates privileged access
is_privileged_role(resource) {
privileged_keywords := ["admin", "power", "elevated", "root", "superuser"]
role_name := lower(resource.name)
contains(role_name, privileged_keywords[_])
}
# Check if policy requires MFA
requires_mfa(policy) {
statement := policy.Statement[_]
statement.Condition.Bool["aws:MultiFactorAuthPresent"] == "true"
}
requires_mfa(policy) {
statement := policy.Statement[_]
statement.Condition.BoolIfExists["aws:MultiFactorAuthPresent"] == "true"
}
# ============================================================================
# IAM User - Prevent Console Access Without MFA
# ============================================================================
# Prevent IAM users from accessing console without MFA policy
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_iam_user"
not has_mfa_enforcement_policy(resource.address)
msg := sprintf(
"HIGH [MFA-001]: IAM user '%s' should have MFA enforcement policy attached\n Frameworks: PCI-DSS-Req8.3, SOC2-CC6.1\n Action: Attach IAM policy that denies actions without MFA",
[resource.address]
)
}
# Check if user has MFA enforcement policy
has_mfa_enforcement_policy(user_address) {
resource := input.resource_changes[_]
resource.type == "aws_iam_user_policy_attachment"
startswith(resource.address, user_address)
policy_arn := resource.change.after.policy_arn
contains(policy_arn, "RequireMFA")
}
# ============================================================================
# Security Group Rules - Ingress Restrictions
# ============================================================================
# Deny security groups open to the internet on non-standard ports
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_security_group_rule"
resource.change.after.type == "ingress"
is_open_to_internet(resource)
not is_allowed_public_port(resource.change.after.from_port)
msg := sprintf(
"HIGH [NET-001]: Security group rule '%s' allows ingress from 0.0.0.0/0 on port %d\n Frameworks: PCI-DSS-Req1.3, SOC2-CC6.6\n Action: Restrict source to specific IP ranges or use approved ports only (80, 443)",
[resource.address, resource.change.after.from_port]
)
}
is_open_to_internet(resource) {
cidr_blocks := resource.change.after.cidr_blocks
cidr_blocks[_] == "0.0.0.0/0"
}
is_open_to_internet(resource) {
ipv6_cidr_blocks := resource.change.after.ipv6_cidr_blocks
ipv6_cidr_blocks[_] == "::/0"
}
is_allowed_public_port(port) {
allowed_ports := [80, 443]
port == allowed_ports[_]
}
# Deny SSH (22) and RDP (3389) open to internet
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_security_group_rule"
resource.change.after.type == "ingress"
is_open_to_internet(resource)
port := resource.change.after.from_port
is_management_port(port)
msg := sprintf(
"CRITICAL [NET-001]: Security group rule '%s' exposes management port %d to the internet\n Frameworks: PCI-DSS-Req1.3, HIPAA-164.312(a)(2)(ii)\n Action: Restrict SSH/RDP access to VPN or bastion host IP ranges",
[resource.address, port]
)
}
is_management_port(port) {
management_ports := [22, 3389]
port == management_ports[_]
}
# ============================================================================
# S3 Bucket - Public Access
# ============================================================================
# Require S3 public access block
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not has_public_access_block(resource.address)
msg := sprintf(
"CRITICAL [ACCESS-001]: S3 bucket '%s' must have public access block configured\n Frameworks: SOC2-CC6.1, HIPAA-164.312(a)(2)(i), PCI-DSS-Req7.1\n Action: Add aws_s3_bucket_public_access_block resource",
[resource.address]
)
}
has_public_access_block(bucket_address) {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket_public_access_block"
startswith(resource.address, bucket_address)
after := resource.change.after
after.block_public_acls == true
after.block_public_policy == true
after.ignore_public_acls == true
after.restrict_public_buckets == true
}
# ============================================================================
# Kubernetes RBAC (if applicable)
# ============================================================================
# Deny ClusterRoleBindings granting cluster-admin to service accounts
deny[msg] {
resource := input.resource_changes[_]
resource.type == "kubernetes_cluster_role_binding"
resource.change.after.role_ref.name == "cluster-admin"
subject := resource.change.after.subject[_]
subject.kind == "ServiceAccount"
msg := sprintf(
"CRITICAL [RBAC-001]: ClusterRoleBinding '%s' grants cluster-admin to ServiceAccount '%s'\n Frameworks: SOC2-CC6.2, PCI-DSS-Req7.1\n Action: Use least privilege roles instead of cluster-admin",
[resource.address, subject.name]
)
}
# Require approval annotation for production namespace access
deny[msg] {
resource := input.resource_changes[_]
resource.type == "kubernetes_role_binding"
resource.change.after.metadata[_].namespace == "production"
annotations := resource.change.after.metadata[_].annotations
not annotations["approved-by"]
msg := sprintf(
"HIGH [ACCESS-002]: Production RoleBinding '%s' requires 'approved-by' annotation\n Frameworks: SOC2-CC6.3\n Action: Add 'approved-by' annotation with approver name",
[resource.address]
)
}
# Deny wildcard verbs in production namespace
deny[msg] {
resource := input.resource_changes[_]
resource.type == "kubernetes_role"
resource.change.after.metadata[_].namespace == "production"
rule := resource.change.after.rule[_]
verb := rule.verbs[_]
verb == "*"
msg := sprintf(
"HIGH [RBAC-001]: Production Role '%s' uses wildcard verbs\n Frameworks: PCI-DSS-Req7.1.2\n Action: Specify explicit verbs (get, list, watch, create, update, delete)",
[resource.address]
)
}
# ============================================================================
# Database Access Controls
# ============================================================================
# Require RDS IAM authentication
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
resource.change.after.iam_database_authentication_enabled != true
msg := sprintf(
"HIGH [ACCESS-001]: RDS instance '%s' should enable IAM database authentication\n Frameworks: SOC2-CC6.1, HIPAA-164.312(a)(2)(i)\n Action: Set iam_database_authentication_enabled = true",
[resource.address]
)
}
# Deny publicly accessible databases
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
resource.change.after.publicly_accessible == true
msg := sprintf(
"CRITICAL [NET-002]: RDS instance '%s' must not be publicly accessible\n Frameworks: PCI-DSS-Req1.3, HIPAA-164.312(a)(2)(ii)\n Action: Set publicly_accessible = false",
[resource.address]
)
}
# ============================================================================
# Lambda Function Access
# ============================================================================
# Deny Lambda functions with overly permissive execution roles
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_lambda_function"
role_arn := resource.change.after.role
is_overly_permissive_lambda_role(role_arn)
msg := sprintf(
"HIGH [ACCESS-001]: Lambda function '%s' execution role may be overly permissive\n Frameworks: SOC2-CC6.2, PCI-DSS-Req7.1\n Action: Review and restrict IAM role permissions",
[resource.address]
)
}
is_overly_permissive_lambda_role(role_arn) {
# Check for common overly permissive patterns
# This is a simplified check; thorough validation requires role policy inspection
overly_permissive_names := ["admin", "poweruser", "full"]
role_name := lower(role_arn)
contains(role_name, overly_permissive_names[_])
}
# ============================================================================
# ECS/EKS Task Execution Roles
# ============================================================================
# Deny ECS task definitions with privileged containers
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_ecs_task_definition"
container := json.unmarshal(resource.change.after.container_definitions)[_]
container.privileged == true
msg := sprintf(
"CRITICAL [ACCESS-001]: ECS task '%s' uses privileged container '%s'\n Frameworks: PCI-DSS-Req7.1, SOC2-CC6.2\n Action: Remove privileged flag or add strong justification",
[resource.address, container.name]
)
}
# ============================================================================
# Summary Functions
# ============================================================================
# Count access control violations by framework
violations_by_framework[framework] = count {
framework := ["SOC2", "HIPAA", "PCI-DSS", "GDPR"][_]
violations := [msg | msg := deny[_]; contains(msg, framework)]
count := count(violations)
}
# List all access control violations
access_violations[violation] {
violation := deny[_]
}
# Encryption Compliance Policies
#
# Validates encryption requirements across SOC 2, HIPAA, PCI-DSS, and GDPR
# Control IDs: ENC-001 (at rest), ENC-002 (in transit), ENC-003 (key rotation)
package compliance.encryption
# METADATA
# title: Encryption at Rest
# description: Ensure all data stores use encryption at rest with KMS
# frameworks:
# - SOC 2 (CC6.1, CC6.7)
# - HIPAA (§164.312(a)(2)(iv))
# - PCI-DSS (Req 3.4)
# - GDPR (Article 32(1)(a))
# control_id: ENC-001
# severity: CRITICAL
# ============================================================================
# S3 Bucket Encryption
# ============================================================================
# Deny S3 buckets without encryption configuration
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not has_bucket_encryption(resource.address)
msg := sprintf(
"CRITICAL [ENC-001]: S3 bucket '%s' must have encryption enabled\n Frameworks: SOC2-CC6.1, HIPAA-164.312(a)(2)(iv), PCI-DSS-Req3.4, GDPR-Art32\n Action: Add aws_s3_bucket_server_side_encryption_configuration resource",
[resource.address]
)
}
# Check if bucket has encryption configuration
has_bucket_encryption(bucket_address) {
encryption_resource := input.resource_changes[_]
encryption_resource.type == "aws_s3_bucket_server_side_encryption_configuration"
startswith(encryption_resource.address, bucket_address)
}
# Require KMS encryption (not default S3 AES256)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket_server_side_encryption_configuration"
rule := resource.change.after.rule[_]
encryption := rule.apply_server_side_encryption_by_default
encryption.sse_algorithm == "AES256" # Default S3 encryption
msg := sprintf(
"HIGH [ENC-001]: Bucket '%s' must use aws:kms encryption, not default AES256\n Frameworks: SOC2-CC6.7\n Action: Change sse_algorithm to 'aws:kms' and specify kms_master_key_id",
[resource.address]
)
}
# ============================================================================
# RDS Encryption
# ============================================================================
# Deny unencrypted RDS instances
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
resource.change.after.storage_encrypted != true
msg := sprintf(
"CRITICAL [ENC-001]: RDS instance '%s' must enable storage_encrypted\n Frameworks: HIPAA-164.312(a)(2)(iv), PCI-DSS-Req3.4\n Action: Set storage_encrypted = true and specify kms_key_id",
[resource.address]
)
}
# Deny unencrypted RDS clusters (Aurora)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_rds_cluster"
resource.change.after.storage_encrypted != true
msg := sprintf(
"CRITICAL [ENC-001]: RDS cluster '%s' must enable storage_encrypted\n Frameworks: HIPAA-164.312(a)(2)(iv), PCI-DSS-Req3.4\n Action: Set storage_encrypted = true and specify kms_key_id",
[resource.address]
)
}
# ============================================================================
# DynamoDB Encryption
# ============================================================================
# Deny DynamoDB tables without encryption
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_dynamodb_table"
not has_dynamodb_encryption(resource)
msg := sprintf(
"CRITICAL [ENC-001]: DynamoDB table '%s' must have server-side encryption enabled\n Frameworks: SOC2-CC6.1, HIPAA-164.312(a)(2)(iv)\n Action: Add server_side_encryption block with enabled = true",
[resource.address]
)
}
has_dynamodb_encryption(resource) {
resource.change.after.server_side_encryption[_].enabled == true
}
# Require customer-managed KMS keys for DynamoDB
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_dynamodb_table"
encryption := resource.change.after.server_side_encryption[_]
encryption.enabled == true
not encryption.kms_key_arn # Using AWS-managed key
msg := sprintf(
"HIGH [ENC-001]: DynamoDB table '%s' should use customer-managed KMS key\n Frameworks: SOC2-CC6.7\n Action: Specify kms_key_arn in server_side_encryption block",
[resource.address]
)
}
# ============================================================================
# EBS Volume Encryption
# ============================================================================
# Deny unencrypted EBS volumes
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_ebs_volume"
resource.change.after.encrypted != true
msg := sprintf(
"CRITICAL [ENC-001]: EBS volume '%s' must be encrypted\n Frameworks: HIPAA-164.312(a)(2)(iv), PCI-DSS-Req3.4\n Action: Set encrypted = true and specify kms_key_id",
[resource.address]
)
}
# Require EBS encryption by default
deny[msg] {
not has_ebs_default_encryption
msg := "CRITICAL [ENC-001]: EBS encryption by default must be enabled\n Frameworks: HIPAA-164.312(a)(2)(iv)\n Action: Add aws_ebs_encryption_by_default resource with enabled = true"
}
has_ebs_default_encryption {
resource := input.resource_changes[_]
resource.type == "aws_ebs_encryption_by_default"
resource.change.after.enabled == true
}
# ============================================================================
# EFS File System Encryption
# ============================================================================
# Deny unencrypted EFS file systems
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_efs_file_system"
resource.change.after.encrypted != true
msg := sprintf(
"CRITICAL [ENC-001]: EFS file system '%s' must be encrypted\n Frameworks: HIPAA-164.312(a)(2)(iv)\n Action: Set encrypted = true and specify kms_key_id",
[resource.address]
)
}
# ============================================================================
# KMS Key Management
# ============================================================================
# Require KMS key rotation (PCI-DSS Req 3.6)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_kms_key"
resource.change.after.enable_key_rotation != true
msg := sprintf(
"MEDIUM [ENC-003]: KMS key '%s' must have automatic rotation enabled\n Frameworks: PCI-DSS-Req3.6, SOC2-CC6.7\n Action: Set enable_key_rotation = true",
[resource.address]
)
}
# Require reasonable deletion window (min 7 days)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_kms_key"
deletion_window := resource.change.after.deletion_window_in_days
deletion_window < 7
msg := sprintf(
"MEDIUM [ENC-003]: KMS key '%s' deletion window must be at least 7 days (current: %d)\n Frameworks: SOC2-CC6.7\n Action: Set deletion_window_in_days >= 7 (recommended: 30)",
[resource.address, deletion_window]
)
}
# ============================================================================
# CloudWatch Logs Encryption
# ============================================================================
# Require encryption for CloudWatch log groups
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_cloudwatch_log_group"
not resource.change.after.kms_key_id
msg := sprintf(
"HIGH [ENC-001]: CloudWatch log group '%s' should be encrypted with KMS\n Frameworks: SOC2-CC6.1, HIPAA-164.312(a)(2)(iv)\n Action: Specify kms_key_id",
[resource.address]
)
}
# ============================================================================
# SNS Topic Encryption
# ============================================================================
# Require SNS topic encryption
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_sns_topic"
not resource.change.after.kms_master_key_id
msg := sprintf(
"HIGH [ENC-001]: SNS topic '%s' should be encrypted with KMS\n Frameworks: HIPAA-164.312(a)(2)(iv)\n Action: Specify kms_master_key_id",
[resource.address]
)
}
# ============================================================================
# SQS Queue Encryption
# ============================================================================
# Require SQS queue encryption
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_sqs_queue"
not resource.change.after.kms_master_key_id
msg := sprintf(
"HIGH [ENC-001]: SQS queue '%s' should be encrypted with KMS\n Frameworks: HIPAA-164.312(a)(2)(iv)\n Action: Specify kms_master_key_id",
[resource.address]
)
}
# ============================================================================
# Secrets Manager Encryption
# ============================================================================
# Require Secrets Manager encryption with KMS
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_secretsmanager_secret"
not resource.change.after.kms_key_id
msg := sprintf(
"HIGH [ENC-001]: Secrets Manager secret '%s' should use customer-managed KMS key\n Frameworks: SOC2-CC6.7, PCI-DSS-Req3.4\n Action: Specify kms_key_id",
[resource.address]
)
}
# ============================================================================
# Encryption in Transit (TLS)
# ============================================================================
# METADATA
# control_id: ENC-002
# severity: CRITICAL
# Require TLS 1.3 for ALB listeners (PCI-DSS 4.0)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_lb_listener"
resource.change.after.protocol == "HTTPS"
ssl_policy := resource.change.after.ssl_policy
not is_tls13_policy(ssl_policy)
msg := sprintf(
"CRITICAL [ENC-002]: ALB listener '%s' must use TLS 1.3 policy\n Frameworks: PCI-DSS-Req4.1, HIPAA-164.312(e)(1)\n Action: Set ssl_policy to 'ELBSecurityPolicy-TLS13-1-2-2021-06'",
[resource.address]
)
}
is_tls13_policy(policy) {
tls13_policies := [
"ELBSecurityPolicy-TLS13-1-2-2021-06",
"ELBSecurityPolicy-TLS13-1-3-2021-06"
]
policy == tls13_policies[_]
}
# Require RDS SSL enforcement
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
not has_ssl_enforcement(resource)
msg := sprintf(
"HIGH [ENC-002]: RDS instance '%s' should enforce SSL connections\n Frameworks: HIPAA-164.312(e)(1), PCI-DSS-Req4.1\n Action: Set parameter group with rds.force_ssl = 1",
[resource.address]
)
}
has_ssl_enforcement(resource) {
# Check if using a parameter group with SSL enforcement
# This is a simplified check; full validation requires parameter group inspection
resource.change.after.parameter_group_name
}
# Require ElastiCache in-transit encryption
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_elasticache_replication_group"
resource.change.after.transit_encryption_enabled != true
msg := sprintf(
"CRITICAL [ENC-002]: ElastiCache replication group '%s' must enable in-transit encryption\n Frameworks: HIPAA-164.312(e)(1), PCI-DSS-Req4.1\n Action: Set transit_encryption_enabled = true",
[resource.address]
)
}
# ============================================================================
# Summary Functions
# ============================================================================
# Count violations by severity
violation_count[severity] = count {
severity := ["CRITICAL", "HIGH", "MEDIUM", "LOW"][_]
violations := [msg | msg := deny[_]; contains(msg, severity)]
count := count(violations)
}
# List all encryption violations
encryption_violations[violation] {
violation := deny[_]
}
skill: "implementing-compliance"
version: "1.0"
domain: "security"
base_outputs:
- path: "compliance/README.md"
must_contain: ["Compliance Framework", "SOC 2", "controls", "evidence"]
- path: "compliance/controls/control-mapping.yaml"
must_contain: ["control_id", "frameworks", "implementation"]
- path: "policies/encryption-policy.md"
must_contain: ["AES-256", "TLS 1.3"]
- path: "policies/access-control-policy.md"
must_contain: ["MFA", "RBAC", "least privilege"]
- path: "audit/audit-logging-config.yaml"
must_contain: ["retention", "7 years", "immutable"]
conditional_outputs:
maturity:
starter:
- path: "compliance/frameworks/soc2-checklist.md"
must_contain: ["Trust Services Criteria", "CC6.1", "controls"]
- path: "terraform/encryption/s3-encryption.tf"
must_contain: ["aws_kms_key", "enable_key_rotation", "aws_s3_bucket_server_side_encryption"]
- path: "terraform/encryption/rds-encryption.tf"
must_contain: ["storage_encrypted", "kms_key_id"]
- path: "policies/mfa/iam-mfa-policy.tf"
must_contain: ["aws:MultiFactorAuthPresent", "Deny"]
- path: "audit/cloudwatch-logs.tf"
must_contain: ["retention_in_days = 2555", "kms_key_id"]
- path: "docs/incident-response-plan.md"
must_contain: ["detection", "escalation", "notification timeline"]
intermediate:
- path: "compliance/opa-policies/encryption.rego"
must_contain: ["package compliance", "deny", "aws_s3_bucket", "encrypted"]
- path: "compliance/opa-policies/access-control.rego"
must_contain: ["package compliance", "deny", "mfa", "rbac"]
- path: ".github/workflows/compliance-check.yml"
must_contain: ["checkov", "opa eval", "terraform plan"]
- path: "terraform/audit/s3-object-lock.tf"
must_contain: ["aws_s3_bucket_object_lock_configuration", "COMPLIANCE", "years = 7"]
- path: "terraform/network/security-groups.tf"
must_contain: ["ingress", "egress", "deny-by-default"]
- path: "compliance/evidence/evidence-collector.py"
must_contain: ["control_id", "frameworks", "collect_evidence"]
- path: "k8s/rbac/developer-role.yaml"
must_contain: ["Role", "rules", "resources", "verbs"]
- path: "compliance/vendor-management/security-questionnaire.md"
must_contain: ["SOC 2 report", "encryption", "audit logs"]
advanced:
- path: "compliance/evidence/evidence_collector.py"
must_contain: ["EvidenceCollector", "control_id", "frameworks", "timestamp"]
- path: "compliance/evidence/report_generator.py"
must_contain: ["AuditReportGenerator", "generate_soc2_report", "compliance_score"]
- path: "compliance/opa-policies/network-security.rego"
must_contain: ["package compliance", "security_group", "ingress"]
- path: "compliance/opa-policies/data-protection.rego"
must_contain: ["package compliance", "encryption", "retention"]
- path: "compliance/testing/test_compliance.py"
must_contain: ["test_s3_encrypted", "test_opa_policies", "assert"]
- path: "terraform/monitoring/config-rules.tf"
must_contain: ["aws_config_config_rule", "encrypted-volumes", "rds-encryption-enabled"]
- path: "terraform/monitoring/eventbridge-compliance.tf"
must_contain: ["aws_cloudwatch_event_rule", "aws_lambda_permission"]
- path: "compliance/frameworks/control-mapping-matrix.yaml"
must_contain: ["SOC2", "HIPAA", "PCI-DSS", "GDPR", "ISO27001"]
- path: "compliance/frameworks/hipaa-baa-template.md"
must_contain: ["Business Associate Agreement", "PHI", "safeguards"]
- path: "compliance/frameworks/gdpr-dpa-template.md"
must_contain: ["Data Processing Agreement", "personal data", "controller"]
- path: "scripts/compliance-report.sh"
must_contain: ["checkov", "opa", "evidence", "report"]
- path: "monitoring/compliance-alerts.yaml"
must_contain: ["encryption_disabled", "mfa_not_enabled", "alert"]
cloud_provider:
aws:
- path: "terraform/aws/kms-keys.tf"
must_contain: ["aws_kms_key", "enable_key_rotation = true", "deletion_window_in_days"]
- path: "terraform/aws/cloudtrail.tf"
must_contain: ["aws_cloudtrail", "enable_logging", "s3_bucket_name", "kms_key_id"]
- path: "terraform/aws/config.tf"
must_contain: ["aws_config_configuration_recorder", "aws_config_delivery_channel"]
- path: "terraform/aws/guardduty.tf"
must_contain: ["aws_guardduty_detector", "enable = true"]
- path: "terraform/aws/security-hub.tf"
must_contain: ["aws_securityhub_account", "enable_default_standards"]
- path: "terraform/aws/iam-password-policy.tf"
must_contain: ["aws_iam_account_password_policy", "minimum_password_length = 12", "require_uppercase_characters"]
gcp:
- path: "terraform/gcp/kms-keys.tf"
must_contain: ["google_kms_key_ring", "google_kms_crypto_key", "rotation_period"]
- path: "terraform/gcp/logging.tf"
must_contain: ["google_logging_project_sink", "destination", "filter"]
- path: "terraform/gcp/security-command-center.tf"
must_contain: ["google_scc_source", "google_scc_notification_config"]
- path: "terraform/gcp/cloud-armor.tf"
must_contain: ["google_compute_security_policy", "rule", "action"]
azure:
- path: "terraform/azure/key-vault.tf"
must_contain: ["azurerm_key_vault", "soft_delete_retention_days", "purge_protection_enabled = true"]
- path: "terraform/azure/storage-encryption.tf"
must_contain: ["azurerm_storage_account", "enable_https_traffic_only = true", "min_tls_version = \"TLS1_2\""]
- path: "terraform/azure/security-center.tf"
must_contain: ["azurerm_security_center_subscription_pricing", "resource_type", "tier = \"Standard\""]
- path: "terraform/azure/monitor-diagnostic.tf"
must_contain: ["azurerm_monitor_diagnostic_setting", "log_analytics_workspace_id"]
multi-cloud:
- path: "compliance/opa-policies/multi-cloud-encryption.rego"
must_contain: ["package compliance", "aws_s3_bucket", "google_storage_bucket", "azurerm_storage_account"]
- path: "compliance/opa-policies/multi-cloud-network.rego"
must_contain: ["package compliance", "security_group", "firewall", "network_security_group"]
- path: "terraform/multi-cloud/central-logging.tf"
must_contain: ["aws_cloudtrail", "google_logging", "azurerm_monitor"]
infrastructure:
kubernetes:
- path: "k8s/rbac/admin-clusterrole.yaml"
must_contain: ["ClusterRole", "rules", "apiGroups", "resources", "verbs"]
- path: "k8s/rbac/developer-role.yaml"
must_contain: ["Role", "namespace", "resources", "verbs"]
- path: "k8s/rbac/rolebinding.yaml"
must_contain: ["RoleBinding", "subjects", "roleRef"]
- path: "k8s/network-policies/deny-all.yaml"
must_contain: ["NetworkPolicy", "podSelector", "policyTypes"]
- path: "k8s/network-policies/allow-specific.yaml"
must_contain: ["NetworkPolicy", "ingress", "from"]
- path: "k8s/pod-security/pod-security-standards.yaml"
must_contain: ["pod-security.kubernetes.io", "enforce", "restricted"]
- path: "k8s/audit/audit-policy.yaml"
must_contain: ["apiVersion: audit.k8s.io", "rules", "level"]
docker:
- path: "docker/security-scanning.yml"
must_contain: ["trivy", "scan", "vulnerability"]
- path: "Dockerfile"
must_contain: ["USER", "non-root", "HEALTHCHECK"]
- path: ".dockerignore"
must_contain: [".env", "secrets", ".git"]
serverless:
- path: "serverless/iam-least-privilege.yml"
must_contain: ["iamRoleStatements", "Effect: Allow", "Resource"]
- path: "serverless/encryption-at-rest.yml"
must_contain: ["environment", "KMS_KEY_ID", "encrypted: true"]
- path: "serverless/vpc-config.yml"
must_contain: ["vpc", "securityGroupIds", "subnetIds"]
scaffolding:
- path: "compliance/"
type: "directory"
description: "Root directory for compliance frameworks and controls"
- path: "compliance/frameworks/"
type: "directory"
description: "Framework-specific documentation (SOC 2, HIPAA, PCI-DSS, GDPR)"
- path: "compliance/controls/"
type: "directory"
description: "Control implementations and mappings"
- path: "compliance/opa-policies/"
type: "directory"
description: "Open Policy Agent policies for policy-as-code enforcement"
- path: "compliance/evidence/"
type: "directory"
description: "Automated evidence collection scripts"
- path: "compliance/testing/"
type: "directory"
description: "Compliance test suites"
- path: "compliance/vendor-management/"
type: "directory"
description: "Vendor assessment templates and BAA/DPA agreements"
- path: "policies/"
type: "directory"
description: "Security and compliance policies"
- path: "audit/"
type: "directory"
description: "Audit logging configurations"
- path: "terraform/encryption/"
type: "directory"
description: "Infrastructure-as-code for encryption controls"
- path: "terraform/monitoring/"
type: "directory"
description: "Compliance monitoring and alerting"
- path: "k8s/rbac/"
type: "directory"
description: "Kubernetes RBAC configurations"
- path: "k8s/network-policies/"
type: "directory"
description: "Kubernetes network policies for segmentation"
- path: "compliance/README.md"
type: "file"
template: |
# Compliance Framework Implementation
This project implements compliance controls for SOC 2 Type II, HIPAA, PCI-DSS 4.0, and GDPR.
## Quick Start
### Prerequisites
- Terraform >= 1.5
- Open Policy Agent (OPA)
- Checkov for IaC scanning
- AWS/GCP/Azure CLI (depending on cloud provider)
### Initial Setup
1. Review applicable frameworks:
```bash
# Identify required frameworks
cat compliance/frameworks/framework-selection.md
```
2. Implement unified controls:
```bash
# Deploy encryption controls
cd terraform/encryption
terraform init
terraform plan
terraform apply
```
3. Configure audit logging:
```bash
cd terraform/audit
terraform apply
```
4. Set up policy enforcement:
```bash
# Test OPA policies
opa test compliance/opa-policies/
```
## Compliance Frameworks
### SOC 2 Type II
- **Timeline:** 6-12 month observation period
- **Controls:** Trust Services Criteria (CC)
- **Key Requirements:** Encryption, MFA, audit logging, monitoring, incident response
- **Checklist:** See `compliance/frameworks/soc2-checklist.md`
### HIPAA
- **Audience:** Healthcare data (PHI)
- **Controls:** Administrative, Physical, Technical safeguards
- **Key Requirements:** Encryption, access controls, audit logs, BAAs
- **Documentation:** See `compliance/frameworks/hipaa-safeguards.md`
### PCI-DSS 4.0
- **Audience:** Payment card data
- **Effective:** April 1, 2025 (mandatory)
- **Key Changes:** Client-side security, 12-char passwords, enhanced MFA
- **Requirements:** See `compliance/frameworks/pci-dss-requirements.md`
### GDPR
- **Audience:** EU residents' personal data
- **Key Requirements:** 48-hour breach notification, data minimization, right to erasure
- **Documentation:** See `compliance/frameworks/gdpr-articles.md`
## Universal Control Implementation
### Priority 1: Encryption
- **ENC-001:** Encryption at rest (AES-256, managed KMS)
- **ENC-002:** Encryption in transit (TLS 1.3 minimum)
- **Implementation:** `terraform/encryption/`
### Priority 2: Access Control
- **MFA-001:** Multi-factor authentication for privileged access
- **RBAC-001:** Role-based access control with least privilege
- **Implementation:** `policies/mfa/`, `k8s/rbac/`
### Priority 3: Audit Logging
- **LOG-001:** Centralized audit logging, 7-year retention, immutable storage
- **Implementation:** `audit/`, `terraform/audit/`
### Priority 4: Monitoring
- **MON-001:** SIEM, intrusion detection, real-time alerting
- **Implementation:** `terraform/monitoring/`
### Priority 5: Incident Response
- **IR-001:** Detection, escalation, breach notification procedures
- **Implementation:** `docs/incident-response-plan.md`
## Policy as Code
### OPA Enforcement
All infrastructure changes are validated against compliance policies before deployment:
```bash
# Generate Terraform plan
terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json
# Evaluate against OPA policies
opa eval --data compliance/opa-policies/ \
--input tfplan.json \
'data.compliance.main.deny'
```
### CI/CD Integration
Compliance checks run automatically in CI/CD:
```yaml
# .github/workflows/compliance-check.yml
- name: Checkov IaC Scan
run: checkov -d terraform/ --check SOC2 --check HIPAA --check PCI --check GDPR
- name: OPA Policy Evaluation
run: opa eval --data compliance/opa-policies/ --input tfplan.json
```
### Static Analysis
```bash
# Scan with Checkov
checkov -d ./terraform \
--check SOC2 --check HIPAA --check PCI --check GDPR \
--output cli --output json
# Scan with tfsec
tfsec terraform/ --format json
# Scan with Trivy
trivy config terraform/
```
## Evidence Collection
### Automated Evidence Gathering
```bash
# Collect control evidence
python compliance/evidence/evidence_collector.py
# Generate audit report
python compliance/evidence/report_generator.py --framework soc2 \
--start-date 2024-01-01 --end-date 2024-12-31
```
### Control Mapping Matrix
See `compliance/frameworks/control-mapping-matrix.yaml` for unified control mappings across all frameworks.
## Breach Notification
**Timeline Requirements:**
- **HIPAA:** 60 days to HHS and affected individuals
- **GDPR:** 48 hours to supervisory authority
- **SOC 2:** 72 hours to affected customers
- **PCI-DSS:** Immediate notification to payment brands
**Procedure:** See `docs/incident-response-plan.md`
## Vendor Management
### Business Associate Agreements (HIPAA)
- Template: `compliance/vendor-management/hipaa-baa-template.md`
- Required for all vendors handling PHI
- Annual review and renewal
### Data Processing Agreements (GDPR)
- Template: `compliance/vendor-management/gdpr-dpa-template.md`
- Required for all vendors processing personal data
- Sub-processor approval required
### Security Questionnaire
- Template: `compliance/vendor-management/security-questionnaire.md`
- Collect SOC 2 reports (≤90 days old)
- Annual re-assessment
## Testing
### Compliance Test Suite
```bash
# Run compliance tests
pytest compliance/testing/
# Test specific control
pytest compliance/testing/test_compliance.py::test_s3_encrypted
```
### Manual Validation
```bash
# Verify encryption at rest
aws s3api get-bucket-encryption --bucket my-bucket
# Verify MFA enforcement
aws iam get-account-password-policy
# Verify audit logging
aws cloudtrail describe-trails
```
## Quarterly Reviews
- [ ] Access reviews (all user permissions)
- [ ] Vendor assessments (SOC 2 reports, security questionnaires)
- [ ] Control testing (sample evidence collection)
- [ ] Policy updates (review and update as needed)
## Annual Activities
- [ ] Risk assessment
- [ ] Disaster recovery testing
- [ ] Penetration testing
- [ ] Compliance audit preparation
## Common Mistakes
- Treating compliance as one-time project vs continuous process
- Implementing per-framework vs unified controls
- Manual evidence collection vs automation
- Insufficient log retention (<7 years)
- Missing MFA enforcement
- Not encrypting backups/logs
- Inadequate vendor due diligence
## Resources
**Framework Documentation:**
- `compliance/frameworks/soc2-controls.md`
- `compliance/frameworks/hipaa-safeguards.md`
- `compliance/frameworks/pci-dss-requirements.md`
- `compliance/frameworks/gdpr-articles.md`
**Implementation Guides:**
- `docs/encryption-implementations.md`
- `docs/access-control-patterns.md`
- `docs/audit-logging-patterns.md`
- `docs/incident-response-templates.md`
**Automation:**
- `compliance/opa-policies/` - Policy as code
- `compliance/evidence/` - Evidence collection scripts
- `.github/workflows/compliance-check.yml` - CI/CD integration
---
**Important:** Consult qualified legal counsel and auditors for legal interpretation and audit preparation.
- path: "compliance/controls/control-mapping.yaml"
type: "file"
template: |
# Unified Control Mapping
# Map controls once, satisfy multiple frameworks (60-80% effort reduction)
controls:
- id: "ENC-001"
name: "Encryption at Rest"
description: "AES-256 encryption for all data at rest using managed KMS with automatic key rotation"
frameworks:
- framework: "SOC2"
control: "CC6.1"
- framework: "HIPAA"
control: "164.312(a)(2)(iv)"
- framework: "PCI-DSS"
control: "Req 3.4"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.10.1.1"
implementation:
- "AWS KMS with automatic key rotation"
- "S3 bucket encryption (SSE-KMS)"
- "RDS encryption at rest"
- "EBS volume encryption"
evidence:
- "AWS Config rule: encrypted-volumes"
- "Terraform state showing encryption enabled"
- "KMS key rotation logs"
status: "IMPLEMENTED"
- id: "ENC-002"
name: "Encryption in Transit"
description: "TLS 1.3 (TLS 1.2 minimum) for all data in transit with strong cipher suites"
frameworks:
- framework: "SOC2"
control: "CC6.1"
- framework: "HIPAA"
control: "164.312(e)(1)"
- framework: "PCI-DSS"
control: "Req 4.1"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.13.1.1"
implementation:
- "ALB with TLS 1.3 policy"
- "API Gateway with TLS 1.2 minimum"
- "RDS force SSL connection"
evidence:
- "Load balancer SSL policy configuration"
- "SSL Labs test results"
- "Certificate expiration monitoring"
status: "IMPLEMENTED"
- id: "MFA-001"
name: "Multi-Factor Authentication"
description: "MFA required for all privileged access (TOTP, hardware tokens, biometric)"
frameworks:
- framework: "SOC2"
control: "CC6.1"
- framework: "HIPAA"
control: "164.312(d)"
- framework: "PCI-DSS"
control: "Req 8.3"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.9.4.2"
implementation:
- "AWS IAM MFA enforcement policy"
- "Console access requires MFA"
- "API calls blocked without MFA"
evidence:
- "IAM credential report (MFA enabled)"
- "CloudTrail logs (MFA present)"
- "User training completion records"
status: "IMPLEMENTED"
- id: "RBAC-001"
name: "Role-Based Access Control"
description: "Least privilege access with job function-based roles and quarterly reviews"
frameworks:
- framework: "SOC2"
control: "CC6.1, CC6.2"
- framework: "HIPAA"
control: "164.308(a)(3), 164.308(a)(4)"
- framework: "PCI-DSS"
control: "Req 7.1, Req 8.2"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.9.2.1, A.9.2.5"
implementation:
- "AWS IAM roles with least privilege"
- "Kubernetes RBAC policies"
- "Quarterly access reviews"
evidence:
- "Access review reports (quarterly)"
- "IAM policy documents"
- "Access provisioning/deprovisioning logs"
status: "IMPLEMENTED"
- id: "LOG-001"
name: "Audit Logging"
description: "Centralized audit logging with 7-year retention in immutable storage"
frameworks:
- framework: "SOC2"
control: "CC7.2"
- framework: "HIPAA"
control: "164.312(b)"
- framework: "PCI-DSS"
control: "Req 10.2, Req 10.3"
- framework: "GDPR"
control: "Art 30"
- framework: "ISO27001"
control: "A.12.4.1"
implementation:
- "CloudWatch Logs (7-year retention)"
- "S3 Object Lock (COMPLIANCE mode)"
- "Application audit logging"
evidence:
- "Log retention configuration"
- "Sample audit logs"
- "Log immutability verification"
status: "IMPLEMENTED"
- id: "MON-001"
name: "Security Monitoring"
description: "SIEM, intrusion detection, real-time alerting for security events"
frameworks:
- framework: "SOC2"
control: "CC7.2, CC7.3"
- framework: "HIPAA"
control: "164.312(b)"
- framework: "PCI-DSS"
control: "Req 10.6, Req 11.4"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.12.4.1, A.16.1.2"
implementation:
- "AWS GuardDuty for threat detection"
- "CloudWatch alarms for anomalies"
- "SIEM integration (Splunk/ELK)"
evidence:
- "Security alert logs"
- "Incident detection metrics"
- "Mean time to detect (MTTD)"
status: "IMPLEMENTED"
- id: "IR-001"
name: "Incident Response"
description: "Documented incident response plan with automated detection and breach notification"
frameworks:
- framework: "SOC2"
control: "CC7.3, CC7.4"
- framework: "HIPAA"
control: "164.308(a)(6)"
- framework: "PCI-DSS"
control: "Req 12.10"
- framework: "GDPR"
control: "Art 33, Art 34"
- framework: "ISO27001"
control: "A.16.1.1, A.16.1.4"
implementation:
- "Incident response plan document"
- "Automated alerting and escalation"
- "Breach notification procedures"
evidence:
- "Incident response plan (approved)"
- "Incident response test results"
- "Breach notification templates"
status: "IMPLEMENTED"
- id: "BC-001"
name: "Business Continuity"
description: "Automated backups, multi-region DR, defined RPO/RTO with regular testing"
frameworks:
- framework: "SOC2"
control: "A1.2, A1.3"
- framework: "HIPAA"
control: "164.308(a)(7)"
- framework: "PCI-DSS"
control: "Req 12.10"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.17.1.1, A.17.1.2"
implementation:
- "Automated daily backups"
- "Multi-region replication"
- "Quarterly failover testing"
evidence:
- "Backup configuration"
- "DR test results (quarterly)"
- "RPO/RTO metrics"
status: "IMPLEMENTED"
- id: "VULN-001"
name: "Vulnerability Management"
description: "Regular vulnerability scanning, patch management, penetration testing"
frameworks:
- framework: "SOC2"
control: "CC7.1"
- framework: "HIPAA"
control: "164.308(a)(8)"
- framework: "PCI-DSS"
control: "Req 11.2, Req 11.3"
- framework: "GDPR"
control: "Art 32"
- framework: "ISO27001"
control: "A.12.6.1, A.18.2.3"
implementation:
- "Weekly vulnerability scans"
- "Automated patch management"
- "Annual penetration testing"
evidence:
- "Vulnerability scan reports"
- "Patch management logs"
- "Penetration test reports"
status: "IMPLEMENTED"
metadata:
primary_blueprints: ["security"]
contributes_to:
- "SOC 2 Type II compliance"
- "HIPAA compliance"
- "PCI-DSS 4.0 compliance"
- "GDPR compliance"
- "ISO 27001 certification"
- "Enterprise security posture"
- "Audit readiness"
integrates_with:
- "security-hardening" # Technical security control implementation
- "secret-management" # HIPAA/PCI-DSS secrets handling
- "infrastructure-as-code" # IaC for compliance controls
- "kubernetes-operations" # K8s RBAC and network policies
- "building-ci-pipelines" # Policy-as-code enforcement
- "siem-logging" # Audit logging and monitoring
- "incident-management" # Incident response procedures
- "auth-security" # MFA and authentication controls
common_patterns:
- name: "Unified Control Implementation"
description: "Implement controls once, map to multiple frameworks (60-80% effort reduction)"
files: ["compliance/controls/control-mapping.yaml"]
- name: "Policy as Code with OPA"
description: "Enforce compliance policies in CI/CD before infrastructure deployment"
files: ["compliance/opa-policies/", ".github/workflows/compliance-check.yml"]
- name: "Automated Evidence Collection"
description: "Continuous evidence gathering for audit preparation"
files: ["compliance/evidence/", "terraform/monitoring/"]
- name: "Encryption Everywhere"
description: "AES-256 at rest, TLS 1.3 in transit with managed KMS"
files: ["terraform/encryption/", "policies/encryption-policy.md"]
anti_patterns:
- name: "Per-framework implementation"
avoid: "Implementing separate controls for each framework"
use: "Unified controls mapped to multiple frameworks"
- name: "Manual evidence collection"
avoid: "Collecting evidence manually before audits"
use: "Automated evidence collection with continuous monitoring"
- name: "Compliance as one-time project"
avoid: "Treating compliance as point-in-time certification"
use: "Continuous compliance with ongoing monitoring and testing"
- name: "Insufficient log retention"
avoid: "90-day or 1-year log retention"
use: "7-year retention to satisfy all frameworks"
- name: "Missing MFA enforcement"
avoid: "MFA optional or only for admin accounts"
use: "MFA required for all privileged access with IAM enforcement"
- name: "Unencrypted backups and logs"
avoid: "Encrypting production data but not backups/logs"
use: "Encryption for all data including backups and audit logs"
tools:
policy_as_code:
- name: "Open Policy Agent (OPA)"
use_when: "General-purpose policy engine, multi-cloud, custom policies"
- name: "Checkov"
use_when: "IaC scanning with built-in compliance frameworks (SOC2, HIPAA, PCI, GDPR)"
- name: "tfsec"
use_when: "Terraform-specific security scanning"
- name: "Trivy"
use_when: "Container and IaC scanning with compliance checks"
compliance_automation:
- name: "AWS Config"
use_when: "AWS resource compliance monitoring and remediation"
- name: "Cloud Custodian"
use_when: "Multi-cloud compliance automation and policy enforcement"
- name: "Drata/Vanta/Secureframe"
use_when: "Continuous compliance platforms with SOC 2 automation"
cloud_security:
- name: "AWS Security Hub"
use_when: "Centralized AWS security findings and compliance checks"
- name: "AWS GuardDuty"
use_when: "Threat detection and intrusion prevention"
- name: "GCP Security Command Center"
use_when: "GCP security and compliance monitoring"
- name: "Azure Security Center"
use_when: "Azure security posture management"
secret_scanning:
- name: "Gitleaks"
use_when: "Pre-commit hooks and CI/CD secret scanning"
- name: "TruffleHog"
use_when: "Git history scanning for leaked secrets"
validation_checks:
- "All S3 buckets encrypted with KMS (run Checkov)"
- "All RDS instances encrypted at rest (run AWS Config rule)"
- "MFA enforced for IAM users (check credential report)"
- "Audit logging enabled with 7-year retention (check CloudWatch/S3)"
- "OPA policies pass on Terraform plan (run opa eval)"
- "Network security groups deny-by-default (run tfsec)"
- "Kubernetes RBAC follows least privilege (review roles)"
- "Incident response plan documented and tested"
- "Vendor BAAs/DPAs signed and current"
- "Quarterly access reviews completed"
- "Annual risk assessment conducted"
- "Penetration testing performed annually"
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
Unified Control Mapping Matrix
Table of Contents
- Overview
- Complete Control Mapping
- Identity & Access Management
- Data Protection
- Logging & Monitoring
- Network Security
- Vulnerability Management
- Incident Response
- Business Continuity
- Governance & Risk
- Implementation Tags
- Evidence Collection Pattern
- Control Implementation Priority
- Framework-Specific Control Counts
- Control Testing Frequency
- Cross-Framework Dependencies
- Control Validation Scripts
Overview
This matrix demonstrates how to implement security controls once and satisfy multiple compliance frameworks simultaneously. Each control maps to specific requirements across SOC 2, HIPAA, PCI-DSS 4.0, GDPR, and ISO 27001.
Strategy: Tag infrastructure resources with applicable control IDs, implement the control once, and automatically generate evidence for all mapped frameworks.
Complete Control Mapping
Identity & Access Management
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| MFA-001 | Multi-factor authentication for all privileged access | CC6.1 | §164.312(d) | Req 8.3 | Art 32(1) | A.9.4.2 | AWS IAM MFA, Okta, Auth0 |
| RBAC-001 | Role-based access control with least privilege | CC6.2 | §164.312(a)(2)(i) | Req 7.1 | Art 32(1) | A.9.2.3 | AWS IAM Roles, K8s RBAC |
| ACCESS-001 | Least privilege principle enforcement | CC6.3 | §164.308(a)(3)(ii)(B) | Req 7.1.2 | Art 25 | A.9.2.3 | Policy-based access control |
| ACCESS-002 | Quarterly access reviews and recertification | CC6.1 | §164.308(a)(3)(ii)(C) | Req 8.2.4 | Art 32(1) | A.9.2.5 | Automated access audits |
| PWD-001 | Strong password policy | CC6.1 | §164.308(a)(5)(ii)(D) | Req 8.3.6 | Art 32(1) | A.9.4.3 | 12+ chars, complexity, no reuse |
| SESSION-001 | Session management and timeouts | CC6.1 | §164.312(a)(2)(iii) | Req 8.2.8 | Art 32(1) | A.9.4.2 | Idle timeout, re-authentication |
| TERM-001 | Account termination procedures | CC6.3 | §164.308(a)(3)(ii)(C) | Req 8.2.6 | Art 32(1) | A.9.2.6 | Immediate access revocation |
Data Protection
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| ENC-001 | Encryption at rest (AES-256) | CC6.1, CC6.7 | §164.312(a)(2)(iv) | Req 3.4 | Art 32(1)(a) | A.10.1.1 | AWS KMS, Azure Key Vault |
| ENC-002 | Encryption in transit (TLS 1.3) | CC6.1, CC6.6 | §164.312(e)(1) | Req 4.1 | Art 32(1)(a) | A.13.1.1 | ALB/NLB SSL policies |
| ENC-003 | Key management and rotation | CC6.7 | §164.312(a)(2)(iv) | Req 3.6 | Art 32(1)(a) | A.10.1.2 | Annual KMS rotation |
| DATA-001 | Data classification and tagging | CC6.1 | §164.308(a)(3)(ii)(A) | Req 9.6.1 | Art 30 | A.8.2.1 | Tag-based classification |
| DATA-002 | Data retention policies | CC6.7 | §164.316(b)(2) | Req 3.1 | Art 5(1)(e) | A.11.2.7 | S3 lifecycle, archival |
| DATA-003 | Data minimization | - | §164.502(b) | Req 3.2 | Art 5(1)(c) | - | Application logic |
| DATA-004 | Secure data disposal | CC6.7 | §164.310(d)(2)(i) | Req 9.8.2 | Art 17 | A.11.2.7 | Cryptographic erasure |
| BACKUP-001 | Encrypted backups | CC7.4 | §164.310(d)(2)(iv) | Req 12.10.2 | Art 32(1)(c) | A.12.3.1 | AWS Backup, encryption |
Logging & Monitoring
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| LOG-001 | Comprehensive audit logging | CC7.2 | §164.312(b) | Req 10.2 | Art 30 | A.12.4.1 | CloudWatch, Splunk |
| LOG-002 | 7-year log retention | CC7.2 | §164.316(b)(2)(i) | Req 10.5.1 | Art 5(1)(e) | A.12.4.1 | S3 with Object Lock |
| LOG-003 | Log integrity protection | CC7.2 | §164.312(c)(1) | Req 10.5.2 | Art 32(1)(b) | A.12.4.2 | Immutable storage |
| LOG-004 | Log review and analysis | CC7.2 | §164.308(a)(1)(ii)(D) | Req 10.6 | Art 32(2) | A.12.4.1 | SIEM correlation |
| MON-001 | Security monitoring and alerting | CC7.2, CC7.3 | §164.308(a)(1)(ii)(D) | Req 10.6.1 | Art 32 | A.12.4.1 | Real-time alerting |
| MON-002 | Anomaly detection | CC7.3 | §164.312(b) | Req 10.6.3 | Art 32 | A.12.4.1 | ML-based detection |
Network Security
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| NET-001 | Firewall configuration | CC6.6 | §164.312(a)(2)(ii) | Req 1.2 | Art 32(1) | A.13.1.1 | Security groups, WAF |
| NET-002 | Network segmentation | CC6.6 | §164.308(a)(3)(ii)(B) | Req 1.3 | Art 32(1) | A.13.1.3 | VPC, private subnets |
| NET-003 | Intrusion detection/prevention | CC7.3 | §164.312(b) | Req 11.4 | Art 32 | A.12.6.1 | GuardDuty, IDS/IPS |
| NET-004 | DDoS protection | CC7.3 | §164.312(a)(2)(ii) | Req 1.3.1 | Art 32 | A.14.1.1 | AWS Shield, Cloudflare |
| NET-005 | VPN for remote access | CC6.6 | §164.312(e)(1) | Req 8.3.10 | Art 32(1) | A.13.1.1 | Client VPN, MFA |
Vulnerability Management
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| VULN-001 | Weekly vulnerability scanning | CC7.1 | §164.308(a)(8) | Req 11.2 | Art 32 | A.12.6.1 | AWS Inspector, Qualys |
| VULN-002 | Quarterly external penetration testing | CC7.1 | §164.308(a)(8) | Req 11.3 | Art 32 | A.12.6.1 | Third-party pentests |
| PATCH-001 | Critical patch deployment (30 days) | CC7.1, CC8.1 | §164.308(a)(5)(ii)(B) | Req 6.2 | Art 32 | A.12.6.1 | Systems Manager |
| SAST-001 | Static code analysis | CC8.1 | - | Req 6.3.2 | Art 25 | A.14.2.1 | SonarQube, Checkmarx |
| DAST-001 | Dynamic application testing | CC8.1 | - | Req 6.3.3 | Art 32 | A.14.2.8 | OWASP ZAP, Burp |
| SCA-001 | Software composition analysis | CC8.1 | - | Req 6.3.2 | Art 32 | A.14.2.1 | Snyk, Dependabot |
Incident Response
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| IR-001 | Incident detection capabilities | CC7.3 | §164.308(a)(6)(i) | Req 12.10.1 | Art 33 | A.16.1.2 | SIEM, monitoring |
| IR-002 | Documented incident response plan | CC7.4, CC7.5 | §164.308(a)(6)(ii) | Req 12.10.1 | Art 33 | A.16.1.5 | IR runbooks |
| IR-003 | Incident escalation procedures | CC7.5 | §164.308(a)(6)(ii) | Req 12.10.4 | Art 33(1) | A.16.1.5 | On-call rotation |
| IR-004 | Breach notification procedures | CC7.5 | §164.410 | Req 12.10.6 | Art 33 | A.16.1.2 | Communication templates |
| IR-005 | Post-incident review | CC7.5 | §164.308(a)(6)(ii) | Req 12.10.7 | Art 33(5) | A.16.1.6 | Lessons learned |
| IR-006 | Forensic evidence collection | CC7.3 | §164.308(a)(6)(ii) | Req 12.10.1 | Art 33(3) | A.16.1.7 | Chain of custody |
Business Continuity
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| BC-001 | Automated backup procedures | CC7.4 | §164.308(a)(7)(ii)(A) | Req 12.10.2 | Art 32(1)(c) | A.12.3.1 | AWS Backup, daily |
| BC-002 | Disaster recovery plan | CC7.4 | §164.308(a)(7)(ii)(C) | Req 12.10.3 | Art 32(1)(c) | A.17.1.1 | Multi-region DR |
| BC-003 | Business continuity testing | CC7.4 | §164.308(a)(7)(ii)(D) | Req 12.10.3 | Art 32(1)(d) | A.17.1.3 | Annual DR drills |
| BC-004 | RPO/RTO definitions | CC7.4 | §164.308(a)(7)(ii)(E) | Req 12.10.2 | Art 32(1)(c) | A.17.1.2 | Documented targets |
| BC-005 | Data restoration testing | CC7.4 | §164.308(a)(7)(ii)(D) | Req 12.10.3 | Art 32(1)(d) | A.12.3.1 | Quarterly tests |
Governance & Risk
| Control | Description | SOC 2 | HIPAA | PCI-DSS 4.0 | GDPR | ISO 27001 | Implementation |
|---|---|---|---|---|---|---|---|
| GOV-001 | Security policies documented | CC1.2, CC1.3 | §164.316(a) | Req 12.1 | Art 24 | A.5.1.1 | Policy repository |
| GOV-002 | Annual policy review | CC1.3 | §164.316(b)(2)(iii) | Req 12.1.3 | Art 24(2) | A.5.1.2 | Board approval |
| TRAIN-001 | Security awareness training | CC1.4 | §164.308(a)(5) | Req 12.6 | Art 32(4) | A.7.2.2 | Annual mandatory |
| TRAIN-002 | Phishing simulation | CC1.4 | §164.308(a)(5) | Req 12.6.3 | Art 32(4) | A.7.2.2 | Quarterly campaigns |
| RISK-001 | Annual risk assessment | CC4.1, CC4.2 | §164.308(a)(1) | Req 12.2 | Art 32 | A.12.6.1 | Risk analysis |
| VENDOR-001 | Vendor risk assessment | CC9.1, CC9.2 | §164.308(b) | Req 12.8 | Art 28 | A.15.1.1 | Vendor questionnaire |
| VENDOR-002 | BAA/DPA execution | CC9.2 | §164.314(a) | Req 12.8.2 | Art 28(3) | A.15.1.2 | Legal agreements |
| VENDOR-003 | Annual vendor review | CC9.2 | §164.308(b)(3) | Req 12.8.5 | Art 28(3)(h) | A.15.2.1 | SOC 2 validation |
Implementation Tags
Tag infrastructure resources with control IDs for automated evidence collection:
resource "aws_s3_bucket" "data" {
tags = {
Compliance = "ENC-001,DATA-001,LOG-001"
Frameworks = "SOC2-CC6.1,HIPAA-164.312(a)(2)(iv),PCI-DSS-Req3.4,GDPR-Art32"
}
}
resource "aws_iam_policy" "mfa_enforcement" {
tags = {
Compliance = "MFA-001,ACCESS-001"
Frameworks = "SOC2-CC6.1,HIPAA-164.312(d),PCI-DSS-Req8.3"
}
}Evidence Collection Pattern
Automated evidence collector queries resources by control ID:
def collect_control_evidence(control_id):
"""Collect evidence for specific control"""
resources = query_resources_by_tag("Compliance", control_id)
frameworks = extract_frameworks_from_tags(resources)
evidence = {
"control_id": control_id,
"frameworks": frameworks,
"resources": [],
"status": "PASS"
}
for resource in resources:
compliance_check = validate_resource(resource, control_id)
evidence["resources"].append({
"resource_id": resource.id,
"resource_type": resource.type,
"compliant": compliance_check.passed,
"details": compliance_check.details
})
if not compliance_check.passed:
evidence["status"] = "FAIL"
return evidenceControl Implementation Priority
Implement controls in this order for maximum framework coverage:
Phase 1 (Weeks 1-4): Foundation 1. ENC-001, ENC-002 - Encryption (satisfies all frameworks) 2. MFA-001 - Multi-factor authentication 3. RBAC-001, ACCESS-001 - Access control 4. LOG-001, LOG-002 - Audit logging
Phase 2 (Weeks 5-8): Detection 5. MON-001, MON-002 - Security monitoring 6. VULN-001, PATCH-001 - Vulnerability management 7. NET-001, NET-002 - Network security
Phase 3 (Weeks 9-12): Response 8. IR-001, IR-002, IR-004 - Incident response 9. BC-001, BC-002 - Business continuity 10. VENDOR-001, VENDOR-002 - Vendor management
Phase 4 (Ongoing): Governance 11. GOV-001, TRAIN-001 - Policies and training 12. RISK-001 - Risk assessments 13. ACCESS-002 - Access reviews
Framework-Specific Control Counts
SOC 2: 42 controls mapped HIPAA: 38 controls mapped PCI-DSS 4.0: 35 controls mapped GDPR: 32 controls mapped ISO 27001: 40 controls mapped
Unified Implementation: 45 unique controls (vs 187 if implemented separately) Efficiency Gain: 76% reduction in implementation effort
Control Testing Frequency
| Control Category | SOC 2 | HIPAA | PCI-DSS | Recommended |
|---|---|---|---|---|
| Encryption | Monthly | Annual | Quarterly | Monthly |
| Access Controls | Monthly | Annual | Quarterly | Monthly |
| Audit Logging | Monthly | Annual | Quarterly | Daily (automated) |
| Vulnerability Scanning | Monthly | Annual | Quarterly | Weekly |
| Access Reviews | Quarterly | Annual | Semi-annual | Quarterly |
| Penetration Testing | Annual | Annual | Annual | Annual |
| Disaster Recovery | Annual | Annual | Annual | Annual |
2025 SOC 2 Update: Monthly testing now required (previously annual) for Type II certification.
Cross-Framework Dependencies
Some controls depend on others being implemented first:
ENC-001 (Encryption at Rest)
└─► ENC-003 (Key Rotation) - Requires KMS setup
└─► LOG-001 (Audit Logging) - Log encryption operations
MFA-001 (Multi-Factor Auth)
└─► RBAC-001 (RBAC) - MFA integrated with role assignment
└─► LOG-001 (Audit Logging) - Log MFA events
NET-002 (Network Segmentation)
└─► NET-001 (Firewall Rules) - Enforce segmentation
└─► MON-001 (Monitoring) - Monitor cross-segment trafficControl Validation Scripts
Automate control validation in CI/CD:
OPA Policy (encryption.rego):
package compliance.enc001
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not has_encryption(resource)
msg := sprintf("ENC-001 VIOLATION: S3 bucket %s not encrypted (SOC2-CC6.1, HIPAA-164.312(a)(2)(iv))", [resource.address])
}Pytest Test:
def test_enc001_encryption_at_rest(terraform_plan):
"""Validate ENC-001: Encryption at rest"""
violations = check_control("ENC-001", terraform_plan)
assert not violations, f"ENC-001 violations: {violations}"This unified approach ensures consistent control implementation across all frameworks while minimizing duplication and audit burden.
Encryption Implementations
Table of Contents
- Overview
- Encryption at Rest
- AWS Implementation
- Azure Implementation
- GCP Implementation
- Encryption in Transit
- TLS Configuration
- Database Connection Encryption
- Key Management
- Key Rotation
- Key Access Policies
- Encryption Validation
- OPA Policy
Overview
Encryption requirements across compliance frameworks:
- Algorithm: AES-256 for data at rest, TLS 1.3 for data in transit
- Key Management: Centralized KMS with automatic rotation
- Scope: All sensitive data (PHI, PII, cardholder data, confidential information)
- Framework Requirements: SOC 2 (CC6.1), HIPAA (§164.312), PCI-DSS (Req 3-4), GDPR (Art 32)
Encryption at Rest
AWS Implementation
S3 Buckets
# terraform/s3_encryption.tf
resource "aws_kms_key" "data" {
description = "Data encryption key for compliance"
deletion_window_in_days = 30
enable_key_rotation = true # PCI-DSS Req 3.6
tags = {
Compliance = "ENC-001,ENC-003"
Frameworks = "SOC2-CC6.1,HIPAA-164.312(a)(2)(iv),PCI-DSS-Req3.4,GDPR-Art32"
Purpose = "data-encryption"
}
}
resource "aws_kms_alias" "data" {
name = "alias/${var.environment}-data-key"
target_key_id = aws_kms_key.data.id
}
resource "aws_s3_bucket" "data" {
bucket = "company-data-${var.environment}"
tags = {
Compliance = "ENC-001,DATA-001"
Environment = var.environment
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "data" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.data.arn
}
bucket_key_enabled = true # Reduces KMS API calls
}
}
# Block public access
resource "aws_s3_bucket_public_access_block" "data" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# Versioning for data integrity
resource "aws_s3_bucket_versioning" "data" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}RDS Databases
# terraform/rds_encryption.tf
resource "aws_db_instance" "main" {
identifier = "${var.environment}-database"
engine = "postgres"
engine_version = "15.4"
instance_class = "db.t3.medium"
# Encryption (HIPAA, PCI-DSS, GDPR)
storage_encrypted = true
kms_key_id = aws_kms_key.data.arn
# Backup encryption
backup_retention_period = 30 # 30 days
backup_window = "03:00-04:00"
# Enable IAM authentication
iam_database_authentication_enabled = true
# Network isolation
db_subnet_group_name = aws_db_subnet_group.private.name
vpc_security_group_ids = [aws_security_group.database.id]
publicly_accessible = false
# Logging for audit trail
enabled_cloudwatch_logs_exports = ["postgresql", "upgrade"]
tags = {
Compliance = "ENC-001,LOG-001"
Frameworks = "HIPAA-164.312(a)(2)(iv),PCI-DSS-Req3.4"
}
}
# Aurora encryption
resource "aws_rds_cluster" "aurora" {
cluster_identifier = "${var.environment}-aurora"
engine = "aurora-postgresql"
engine_version = "15.4"
storage_encrypted = true
kms_key_id = aws_kms_key.data.arn
# Enable audit logging
enabled_cloudwatch_logs_exports = ["postgresql"]
tags = {
Compliance = "ENC-001"
}
}EBS Volumes
# terraform/ebs_encryption.tf
# Enable EBS encryption by default
resource "aws_ebs_encryption_by_default" "enabled" {
enabled = true
}
# Set default KMS key for EBS
resource "aws_ebs_default_kms_key" "default" {
key_arn = aws_kms_key.data.arn
}
# Explicit volume encryption
resource "aws_ebs_volume" "data" {
availability_zone = var.availability_zone
size = 100
type = "gp3"
encrypted = true
kms_key_id = aws_kms_key.data.arn
tags = {
Compliance = "ENC-001"
}
}DynamoDB Tables
# terraform/dynamodb_encryption.tf
resource "aws_dynamodb_table" "sessions" {
name = "${var.environment}-sessions"
billing_mode = "PAY_PER_REQUEST"
hash_key = "session_id"
# Server-side encryption
server_side_encryption {
enabled = true
kms_key_arn = aws_kms_key.data.arn
}
# Point-in-time recovery
point_in_time_recovery {
enabled = true
}
attribute {
name = "session_id"
type = "S"
}
ttl {
enabled = true
attribute_name = "expiration_time"
}
tags = {
Compliance = "ENC-001,DATA-002"
}
}Azure Implementation
# terraform/azure_encryption.tf
# Storage Account with encryption
resource "azurerm_storage_account" "data" {
name = "companydata${var.environment}"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
account_tier = "Standard"
account_replication_type = "GRS"
# Encryption at rest
enable_https_traffic_only = true
min_tls_version = "TLS1_3"
# Customer-managed key
identity {
type = "SystemAssigned"
}
customer_managed_key {
key_vault_key_id = azurerm_key_vault_key.storage.id
user_assigned_identity_id = azurerm_user_assigned_identity.storage.id
}
tags = {
Compliance = "ENC-001,ENC-002"
}
}
# Key Vault for key management
resource "azurerm_key_vault" "main" {
name = "company-kv-${var.environment}"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "premium" # HSM-backed keys
enabled_for_disk_encryption = true
soft_delete_retention_days = 90
purge_protection_enabled = true
tags = {
Compliance = "ENC-003"
}
}
# Azure SQL encryption
resource "azurerm_mssql_server" "main" {
name = "company-sql-${var.environment}"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
version = "12.0"
administrator_login = var.sql_admin_username
administrator_login_password = var.sql_admin_password
minimum_tls_version = "1.3"
azuread_administrator {
login_username = var.azuread_admin_username
object_id = var.azuread_admin_object_id
}
tags = {
Compliance = "ENC-001,ENC-002"
}
}
resource "azurerm_mssql_database" "main" {
name = "company-db"
server_id = azurerm_mssql_server.main.id
sku_name = "S1"
# Transparent Data Encryption (TDE)
transparent_data_encryption_enabled = true
}GCP Implementation
# terraform/gcp_encryption.tf
# KMS Key Ring
resource "google_kms_key_ring" "main" {
name = "company-keyring-${var.environment}"
location = var.region
}
# KMS Crypto Key
resource "google_kms_crypto_key" "data" {
name = "data-encryption-key"
key_ring = google_kms_key_ring.main.id
rotation_period = "2592000s" # 30 days
lifecycle {
prevent_destroy = true
}
labels = {
compliance = "enc-001"
}
}
# Cloud Storage with CMEK
resource "google_storage_bucket" "data" {
name = "company-data-${var.environment}"
location = var.region
encryption {
default_kms_key_name = google_kms_crypto_key.data.id
}
versioning {
enabled = true
}
labels = {
compliance = "enc-001"
}
}
# Cloud SQL with encryption
resource "google_sql_database_instance" "main" {
name = "company-db-${var.environment}"
database_version = "POSTGRES_15"
region = var.region
settings {
tier = "db-f1-micro"
database_flags {
name = "cloudsql.enable_pgaudit"
value = "on"
}
backup_configuration {
enabled = true
start_time = "03:00"
}
ip_configuration {
ipv4_enabled = false
private_network = google_compute_network.main.id
require_ssl = true
}
}
encryption_key_name = google_kms_crypto_key.data.id
}Encryption in Transit
TLS Configuration
Application Level (Python/Flask)
# api/config/tls_config.py
import ssl
from typing import Dict
class TLSConfig:
"""TLS configuration for HIPAA, PCI-DSS compliance"""
# TLS 1.3 for maximum security
TLS_MIN_VERSION = ssl.TLSVersion.TLSv1_3
# Strong cipher suites only
TLS_CIPHERS = [
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256",
]
# HSTS settings
HSTS_MAX_AGE = 31536000 # 1 year
HSTS_INCLUDE_SUBDOMAINS = True
HSTS_PRELOAD = True
@staticmethod
def get_ssl_context() -> ssl.SSLContext:
"""Create secure SSL context"""
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.minimum_version = TLSConfig.TLS_MIN_VERSION
context.set_ciphers(":".join(TLSConfig.TLS_CIPHERS))
return context
@staticmethod
def get_security_headers() -> Dict[str, str]:
"""Security headers for all responses"""
return {
"Strict-Transport-Security":
f"max-age={TLSConfig.HSTS_MAX_AGE}; includeSubDomains; preload",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Content-Security-Policy": "default-src 'self'",
"Referrer-Policy": "strict-origin-when-cross-origin",
}
# app.py
from flask import Flask, Response
from config.tls_config import TLSConfig
app = Flask(__name__)
@app.after_request
def add_security_headers(response: Response) -> Response:
"""Add security headers to all responses"""
for header, value in TLSConfig.get_security_headers().items():
response.headers[header] = value
return response
if __name__ == "__main__":
ssl_context = TLSConfig.get_ssl_context()
app.run(ssl_context=ssl_context, host="0.0.0.0", port=443)Load Balancer Configuration
AWS Application Load Balancer:
# terraform/alb_tls.tf
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.main.arn
port = 443
protocol = "HTTPS"
# TLS 1.3 policy (PCI-DSS 4.0 compliant)
ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"
certificate_arn = aws_acm_certificate.main.arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.app.arn
}
}
# Redirect HTTP to HTTPS (mandatory)
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.main.arn
port = 80
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
protocol = "HTTPS"
port = "443"
status_code = "HTTP_301"
}
}
}
# ACM certificate with auto-renewal
resource "aws_acm_certificate" "main" {
domain_name = var.domain_name
validation_method = "DNS"
subject_alternative_names = [
"*.${var.domain_name}"
]
lifecycle {
create_before_destroy = true
}
tags = {
Compliance = "ENC-002"
}
}
# Automated DNS validation
resource "aws_acm_certificate_validation" "main" {
certificate_arn = aws_acm_certificate.main.arn
validation_record_fqdns = [for record in aws_route53_record.cert_validation : record.fqdn]
}NGINX Configuration
# /etc/nginx/conf.d/tls.conf
# TLS 1.3 configuration for compliance
server {
listen 443 ssl http2;
server_name api.example.com;
# TLS certificates
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
# TLS 1.3 only (PCI-DSS 4.0)
ssl_protocols TLSv1.3;
# Strong cipher suites
ssl_ciphers 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256';
ssl_prefer_server_ciphers on;
# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/certs/chain.crt;
# Session cache
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# HSTS header (SOC 2, HIPAA)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
# Security headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name api.example.com;
return 301 https://$host$request_uri;
}Database Connection Encryption
PostgreSQL (HIPAA-compliant):
# api/database/connection.py
import psycopg2
from typing import Dict
class DatabaseConnection:
"""HIPAA-compliant PostgreSQL connection"""
@staticmethod
def get_connection_params() -> Dict:
"""Connection parameters with TLS enforcement"""
return {
"host": "db.example.com",
"port": 5432,
"database": "app_db",
"user": "app_user",
"password": "secure_password",
# Enforce TLS 1.2+
"sslmode": "verify-full",
"sslrootcert": "/etc/ssl/certs/ca-bundle.crt",
# Application name for audit logging
"application_name": "api-server",
# Connection timeout
"connect_timeout": 10,
}
@staticmethod
def create_connection():
"""Create encrypted database connection"""
params = DatabaseConnection.get_connection_params()
conn = psycopg2.connect(**params)
# Verify connection is encrypted
cursor = conn.cursor()
cursor.execute("SELECT ssl_is_used();")
ssl_enabled = cursor.fetchone()[0]
if not ssl_enabled:
raise SecurityError("Database connection is not encrypted")
return connMySQL/MariaDB:
# api/database/mysql_connection.py
import mysql.connector
from mysql.connector import Error
class MySQLConnection:
"""PCI-DSS compliant MySQL connection"""
@staticmethod
def create_connection():
"""Create encrypted MySQL connection"""
try:
conn = mysql.connector.connect(
host="db.example.com",
user="app_user",
password="secure_password",
database="app_db",
# Enforce TLS
ssl_ca="/etc/ssl/certs/ca-bundle.crt",
ssl_verify_cert=True,
ssl_verify_identity=True,
# Connection settings
connection_timeout=10,
autocommit=False,
)
# Verify encryption
cursor = conn.cursor()
cursor.execute("SHOW STATUS LIKE 'Ssl_cipher';")
result = cursor.fetchone()
if not result or not result[1]:
raise Error("MySQL connection is not encrypted")
return conn
except Error as e:
raise ConnectionError(f"MySQL connection failed: {e}")Key Management
Key Rotation
Automated KMS Rotation (AWS):
# scripts/validate_key_rotation.py
import boto3
from datetime import datetime, timedelta
kms = boto3.client('kms')
def check_key_rotation():
"""Validate KMS key rotation is enabled (PCI-DSS Req 3.6)"""
keys = kms.list_keys()
violations = []
for key in keys['Keys']:
key_id = key['KeyId']
metadata = kms.describe_key(KeyId=key_id)
# Check if customer-managed key
if metadata['KeyMetadata']['KeyManager'] == 'CUSTOMER':
# Check rotation status
try:
rotation = kms.get_key_rotation_status(KeyId=key_id)
if not rotation['KeyRotationEnabled']:
violations.append({
'KeyId': key_id,
'Alias': get_key_alias(key_id),
'Issue': 'Key rotation not enabled'
})
except Exception as e:
violations.append({
'KeyId': key_id,
'Issue': f'Cannot check rotation: {e}'
})
return violations
def get_key_alias(key_id):
"""Get key alias for reporting"""
try:
aliases = kms.list_aliases(KeyId=key_id)
if aliases['Aliases']:
return aliases['Aliases'][0]['AliasName']
except:
pass
return "No alias"
if __name__ == "__main__":
violations = check_key_rotation()
if violations:
print("❌ Key rotation violations found:")
for v in violations:
print(f" - {v}")
exit(1)
else:
print("✅ All keys have rotation enabled")Key Access Policies
# terraform/kms_policy.tf
data "aws_iam_policy_document" "kms_key_policy" {
# Allow account root full access
statement {
sid = "Enable IAM User Permissions"
effect = "Allow"
principals {
type = "AWS"
identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
}
actions = ["kms:*"]
resources = ["*"]
}
# Allow services to use key
statement {
sid = "Allow services to use the key"
effect = "Allow"
principals {
type = "Service"
identifiers = [
"s3.amazonaws.com",
"rds.amazonaws.com",
"dynamodb.amazonaws.com",
"logs.amazonaws.com"
]
}
actions = [
"kms:Decrypt",
"kms:GenerateDataKey"
]
resources = ["*"]
}
# Audit key usage
statement {
sid = "Allow CloudTrail to describe key"
effect = "Allow"
principals {
type = "Service"
identifiers = ["cloudtrail.amazonaws.com"]
}
actions = ["kms:DescribeKey"]
resources = ["*"]
}
}
resource "aws_kms_key" "data" {
description = "Data encryption key"
deletion_window_in_days = 30
enable_key_rotation = true
policy = data.aws_iam_policy_document.kms_key_policy.json
tags = {
Compliance = "ENC-003"
Purpose = "data-encryption"
}
}Encryption Validation
OPA Policy
# policies/compliance/encryption.rego
package compliance.encryption
# Deny unencrypted S3 buckets
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket"
not has_bucket_encryption(resource.address)
msg := sprintf(
"CRITICAL: S3 bucket '%s' must have encryption enabled (SOC2:CC6.1, HIPAA:164.312(a)(2)(iv), PCI-DSS:Req3.4)",
[resource.address]
)
}
has_bucket_encryption(bucket_address) {
encryption_resource := input.resource_changes[_]
encryption_resource.type == "aws_s3_bucket_server_side_encryption_configuration"
startswith(encryption_resource.address, bucket_address)
}
# Deny unencrypted RDS
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_db_instance"
resource.change.after.storage_encrypted != true
msg := sprintf(
"CRITICAL: RDS instance '%s' must enable storage_encrypted",
[resource.address]
)
}
# Require KMS (not default encryption)
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_s3_bucket_server_side_encryption_configuration"
rule := resource.change.after.rule[_]
encryption := rule.apply_server_side_encryption_by_default
encryption.sse_algorithm != "aws:kms"
msg := sprintf(
"HIGH: Bucket '%s' must use KMS encryption (not default AES256)",
[resource.address]
)
}
# Require key rotation
deny[msg] {
resource := input.resource_changes[_]
resource.type == "aws_kms_key"
resource.change.after.enable_key_rotation != true
msg := sprintf(
"MEDIUM: KMS key '%s' must have rotation enabled (PCI-DSS:Req3.6)",
[resource.address]
)
}This comprehensive encryption implementation satisfies all major compliance framework requirements while following security best practices.
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
HIPAA Safeguards Reference
For complete HIPAA safeguards implementation guidance, refer to the init.md master plan and examples.
Quick Reference
Technical Safeguards (§164.312):
- Access Control with MFA
- Audit Controls with 6-year retention
- Integrity Controls
- Person/Entity Authentication
- Transmission Security (TLS 1.2+)
Physical Safeguards (§164.310):
- Facility Access Controls
- Workstation Use and Security
- Device and Media Controls
Administrative Safeguards (§164.308):
- Security Management Process (Risk Analysis required)
- Assigned Security Responsibility
- Workforce Security
- Information Access Management
- Security Awareness Training
- Security Incident Procedures (60-day breach notification)
- Contingency Plan (Backup and DR)
- Business Associate Agreements
See control-mapping-matrix.md for unified control implementations satisfying multiple frameworks.
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
PCI-DSS 4.0 Requirements Reference
For complete PCI-DSS implementation guidance, refer to the init.md master plan.
12 Core Requirements (Effective April 1, 2025)
1. Install and maintain network security controls 2. Apply secure configurations to all system components 3. Protect stored account data 4. Protect cardholder data with strong cryptography during transmission 5. Protect all systems and networks from malicious software 6. Develop and maintain secure systems and software 7. Restrict access to cardholder data by business need to know 8. Identify users and authenticate access to system components 9. Restrict physical access to cardholder data 10. Log and monitor all access to system components and cardholder data 11. Test security of systems and networks regularly 12. Support information security with organizational policies and programs
Key 2025 Changes
- Client-side security for payment pages
- 12-character minimum passwords (8 if system limitation)
- Enhanced MFA for all CDE access
- Semi-annual access reviews (human accounts: 6 months, system accounts: risk-based)
- Enhanced key management and logging
See control-mapping-matrix.md for unified implementations.
SOC 2 Trust Services Criteria
Table of Contents
- Overview
- Trust Services Criteria
- Common Criteria (CC) - All SOC 2 Reports
- Additional Trust Services Criteria (Optional)
- Evidence Collection for SOC 2
- Monthly Testing Requirements (2025)
- AI Governance Controls (2025)
- SOC 2 Implementation Timeline
- Common SOC 2 Audit Findings
- Control Implementation Priority
- Tool Recommendations
Overview
SOC 2 is an auditing procedure that ensures service providers securely manage data to protect the interests and privacy of their clients. Reports are issued by certified public accountants (CPAs) following an audit.
Report Types:
- Type I: Point-in-time assessment of control design
- Type II: 6-12 month assessment of control effectiveness (required for enterprise sales)
2025 Updates:
- Monthly control testing (previously annual) for Type II
- AI governance controls for ML systems handling customer data
- 72-hour breach notification requirement
- Enhanced third-party risk management
Trust Services Criteria
Common Criteria (CC) - All SOC 2 Reports
CC1: Control Environment
CC1.1 - Organization demonstrates commitment to integrity and ethical values CC1.2 - Board of directors demonstrates independence and oversight CC1.3 - Management establishes structures, reporting lines, authorities, and responsibilities CC1.4 - Organization demonstrates commitment to attract, develop, and retain competent individuals CC1.5 - Organization holds individuals accountable for internal control responsibilities
Implementation:
- Documented code of conduct
- Board charter and meeting minutes
- Organizational chart with reporting structure
- Security awareness training program
- Performance reviews including security responsibilities
CC2: Communication and Information
CC2.1 - Organization obtains or generates relevant, quality information CC2.2 - Organization internally communicates information necessary to support functioning of internal control CC2.3 - Organization communicates with external parties regarding matters affecting internal control
Implementation:
- Security policies and procedures documented
- Internal security newsletters and announcements
- Customer security documentation and incident communication
- Vendor management communications
CC3: Risk Assessment
CC3.1 - Organization specifies objectives with sufficient clarity CC3.2 - Organization identifies risks to achievement of objectives CC3.3 - Organization considers potential for fraud in risk assessment CC3.4 - Organization identifies and assesses changes that could significantly impact internal control
Implementation:
- Annual risk assessments
- Risk register with mitigation plans
- Change management process
- Fraud risk assessment procedures
CC4: Monitoring Activities
CC4.1 - Organization selects, develops, and performs ongoing/separate evaluations CC4.2 - Organization evaluates and communicates internal control deficiencies
Implementation:
- Continuous security monitoring
- Annual internal audits
- Penetration testing (annual minimum)
- Executive security reporting
CC5: Control Activities
CC5.1 - Organization selects and develops control activities that contribute to mitigation of risks CC5.2 - Organization selects and develops general control activities over technology CC5.3 - Organization deploys control activities through policies and procedures
Implementation:
- Security control framework (mapped to TSC)
- IT general controls (change management, access controls)
- Standard operating procedures
CC6: Logical and Physical Access Controls
CC6.1 - Organization implements logical access security software, infrastructure, and architectures
- Multi-factor authentication for privileged access
- Role-based access control (RBAC)
- Encryption at rest (AES-256) and in transit (TLS 1.3)
- Network segmentation and firewalls
CC6.2 - Organization restricts logical access (least privilege)
- Access provisioning and deprovisioning procedures
- Quarterly access reviews
- Separation of duties enforcement
CC6.3 - Organization manages identification and authentication
- Password complexity requirements (12+ characters)
- Account lockout policies
- Session timeout enforcement
CC6.4 - Organization restricts access to programs and data
- Application-level access controls
- Data classification and handling
- Secure software development lifecycle
CC6.5 - Organization terminates access when appropriate
- Immediate access revocation upon termination
- Regular review of inactive accounts
- Contractor access expiration
CC6.6 - Organization implements security measures to protect against threats
- Intrusion detection/prevention systems
- DDoS protection
- Web application firewall (WAF)
CC6.7 - Organization restricts transmission, movement, and removal of information
- Data loss prevention (DLP)
- Encrypted backups
- Secure data disposal procedures
CC6.8 - Organization implements controls to prevent or detect malicious software
- Endpoint detection and response (EDR)
- Anti-malware on all systems
- Email security gateway
CC7: System Operations
CC7.1 - Organization ensures systems are current and can continue operating
- Patch management with defined SLAs
- Vulnerability scanning (weekly minimum)
- Configuration management
CC7.2 - Organization monitors system components and operation
- Centralized logging and SIEM
- Security information and event monitoring
- Log retention (7 years minimum)
CC7.3 - Organization evaluates security events and responds
- Incident response plan
- Security operations center (SOC) or equivalent
- Threat intelligence integration
CC7.4 - Organization identifies, develops, and implements activities to recover from disruptions
- Disaster recovery plan
- Regular backup procedures (automated daily)
- Annual DR testing
CC7.5 - Organization deploys detection and monitoring procedures to identify anomalies
- Anomaly detection systems
- User behavior analytics
- Automated alerting for suspicious activity
CC8: Change Management
CC8.1 - Organization authorizes, designs, develops, tests, approves, and implements changes
- Change advisory board (CAB)
- Code review requirements
- Testing in non-production environments
- Rollback procedures
CC9: Risk Mitigation
CC9.1 - Organization establishes requirements for vendor and business partner agreements
- Vendor risk assessment process
- Security requirements in vendor contracts
- Right-to-audit clauses
CC9.2 - Organization assesses vendor and business partner services
- Annual vendor reviews
- SOC 2 report collection (≤90 days old)
- Vendor incident notification requirements
Additional Trust Services Criteria (Optional)
Availability
Measures system uptime and accessibility.
Implementation:
- SLA definitions (e.g., 99.99% uptime)
- Redundancy and failover mechanisms
- Performance monitoring
- Capacity planning
Processing Integrity
Ensures system processing is complete, valid, accurate, timely, and authorized.
Implementation:
- Input validation
- Error handling and logging
- Data reconciliation procedures
- Processing controls and audits
Confidentiality
Protects confidential information as agreed with clients.
Implementation:
- Data classification scheme
- Confidentiality agreements (NDAs)
- Confidential data encryption
- Access controls specific to confidential data
Privacy
Addresses collection, use, retention, disclosure, and disposal of personal information.
Implementation:
- Privacy policy
- Consent management
- Data subject rights procedures (access, deletion)
- Privacy impact assessments
Evidence Collection for SOC 2
Monthly Testing Requirements (2025)
All controls must be tested monthly for Type II reports:
Automated Evidence:
- Access logs (authentication, authorization)
- Encryption status (AWS Config, Cloud Custodian)
- Vulnerability scan results
- Backup success/failure logs
- Change management tickets
- Security monitoring alerts
Manual Evidence:
- Access review documentation (quarterly)
- Board meeting minutes (quarterly minimum)
- Security awareness training completion (annual)
- Vendor SOC 2 reports (annual)
- Penetration test reports (annual)
- Business continuity test results (annual)
AI Governance Controls (2025)
New requirements for systems using AI/ML on customer data:
Required Controls:
- AI model logging and monitoring
- Algorithmic transparency documentation
- Bias mitigation procedures
- Model versioning and rollback capabilities
- AI-specific risk assessments
- Third-party AI service vendor assessments
Evidence:
- Model training logs
- Bias testing results
- Model performance monitoring
- AI incident response procedures
- AI ethics policy
SOC 2 Implementation Timeline
Phase 1: Gap Assessment (Month 1-2)
- Compare current controls against TSC requirements
- Document existing controls
- Identify gaps and remediation plan
Phase 2: Control Implementation (Month 3-6)
- Implement missing controls
- Document policies and procedures
- Configure automated evidence collection
Phase 3: Observation Period (Month 7-12)
- Collect evidence continuously
- Monthly control testing
- Address any control failures
- Prepare for audit
Phase 4: Audit (Month 13)
- CPA audit firm engagement
- Provide evidence package
- Remediate audit findings
- Receive SOC 2 Type II report
Common SOC 2 Audit Findings
Most Frequent Deficiencies:
1. Access Reviews Not Performed: Quarterly access reviews not completed or documented
- Remediation: Automate access review reminders, track completion
2. Insufficient Logging: Not logging all required events or inadequate retention
- Remediation: Implement comprehensive audit logging, 7-year retention
3. MFA Gaps: MFA not enforced for all privileged access
- Remediation: Implement MFA enforcement policies (IAM, conditional access)
4. Vendor SOC 2 Reports Expired: Vendor reports older than 90 days
- Remediation: Quarterly vendor report collection process
5. Incomplete Change Documentation: Changes deployed without proper approval/testing
- Remediation: Enforce change management workflow in ticketing system
6. Backup Testing Not Performed: Backup success logged but restoration not tested
- Remediation: Quarterly backup restoration tests
7. Security Training Incomplete: Not all employees completed training
- Remediation: Mandatory training with tracking, escalation for non-completion
8. Patch Management SLA Violations: Critical patches not deployed within 30 days
- Remediation: Automated patch deployment, exception tracking
Control Implementation Priority
Week 1-4: Foundation 1. Encryption (CC6.1, CC6.7) 2. MFA enforcement (CC6.1) 3. Centralized logging (CC7.2)
Week 5-8: Access Controls 4. RBAC implementation (CC6.2) 5. Access review process (CC6.2) 6. Password policies (CC6.3)
Week 9-12: Monitoring & Response 7. Security monitoring/SIEM (CC7.2, CC7.3) 8. Incident response plan (CC7.3) 9. Vulnerability management (CC7.1)
Month 4-6: Governance & Documentation 10. Policy documentation (CC1, CC2) 11. Security awareness training (CC1.4) 12. Risk assessment process (CC3) 13. Vendor management (CC9)
Month 7-12: Observation Period 14. Monthly testing and evidence collection 15. Continuous monitoring and improvement 16. Audit preparation
Tool Recommendations
Automated Compliance Platforms:
- Drata
- Vanta
- Secureframe
- TrustCloud
Manual Alternative:
- AWS Config + Lambda for evidence collection
- Spreadsheet-based control tracking
- Manual evidence package preparation
Investment:
- Automated platform: $20K-40K annually
- Manual approach: Significant staff time (200+ hours annually)
- Audit fees: $15K-50K depending on company size
This guide provides the framework for SOC 2 compliance. Consult with qualified auditors for organization-specific requirements.
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
${file} Reference
This reference file provides detailed implementation guidance. For complete information, refer to the init.md master plan and examples/ directory.
Overview
Detailed content for this compliance framework topic.
See Also
- control-mapping-matrix.md for unified control implementations
- encryption-implementations.md for encryption patterns
- examples/ directory for working code examples
Related skills
FAQ
How does unified control mapping help?
Implementing controls once and mapping to multiple frameworks reduces implementation effort by 60-80%.
How are compliance policies enforced?
As policy-as-code with OPA and Checkov evaluated on Terraform plans in CI/CD before deployment.