Compliance Automation
🔥 Vibe Prompt
"Automate compliance: continuous monitoring, evidence collection, automated remediation."
Compliance Automation Stack
┌─────────────────────────────────────────────┐
│ Compliance Dashboard (Vanta / Drata) │
├─────────────────────────────────────────────┤
│ Evidence Collection (Screenshots, API) │
├─────────────────────────────────────────────┤
│ Policy as Code (Checkov, OPA) │
├─────────────────────────────────────────────┤
│ CSPM (Wiz / Lacework / AWS Security Hub) │
├─────────────────────────────────────────────┤
│ Infrastructure (Terraform, K8s) │
└─────────────────────────────────────────────┘
Automated Evidence with Python
import boto3, json, os
from datetime import datetime
class ComplianceBot:
def __init__(self):
self.evidence = []
self.iam = boto3.client('iam')
self.s3 = boto3.client('s3')
self.config = boto3.client('config')
def collect_all(self):
self.collect_iam()
self.collect_s3()
self.collect_config()
self.export_report()
def collect_iam(self):
# MFA usage
users = self.iam.list_users()['Users']
no_mfa = 0
for user in users:
mfa = self.iam.list_mfa_devices(UserName=user['UserName'])
if not mfa['MFADevices']:
no_mfa += 1
self.evidence.append({
"control": "CC6.3 (MFA)",
"status": "FAIL" if no_mfa > 0 else "PASS",
"detail": f"{no_mfa}/{len(users)} users without MFA",
"timestamp": datetime.now().isoformat(),
"screenshot": self.take_screenshot("iam/mfa-report")
})
# Access keys age
old_keys = 0
for user in users:
keys = self.iam.list_access_keys(UserName=user['UserName'])['AccessKeyMetadata']
for key in keys:
age = (datetime.now() - key['CreateDate'].replace(tzinfo=None)).days
if age > 90:
old_keys += 1
self.evidence.append({
"control": "CC6.1 (Key Rotation)",
"status": "FAIL" if old_keys > 0 else "PASS",
"detail": f"{old_keys} keys > 90 days old",
"timestamp": datetime.now().isoformat()
})
def collect_s3(self):
buckets = self.s3.list_buckets()['Buckets']
public_buckets = 0
for bucket in buckets:
try:
acl = self.s3.get_public_access_block(Bucket=bucket['Name'])
if not acl['PublicAccessBlockConfiguration']['BlockPublicAcls']:
public_buckets += 1
except:
public_buckets += 1
self.evidence.append({
"control": "CC6.2 (Public Access)",
"status": "FAIL" if public_buckets > 0 else "PASS",
"detail": f"{public_buckets} publicly accessible buckets",
"timestamp": datetime.now().isoformat()
})
def take_screenshot(self, path):
# Puppeteer screenshot of AWS console
return f"screenshots/{path}_{datetime.now().strftime('%Y%m%d')}.png"
def export_report(self):
report = {
"company": "MyApp Inc.",
"generated_at": datetime.now().isoformat(),
"framework": "SOC 2",
"status": "COMPLIANT" if all(e['status'] == 'PASS' for e in self.evidence) else "NON_COMPLIANT",
"evidence_count": len(self.evidence),
"evidence": self.evidence
}
with open(f"compliance_report_{datetime.now().strftime('%Y%m%d')}.json", "w") as f:
json.dump(report, f, indent=2)
print(f"Report generated: {len(self.evidence)} evidence items")
if __name__ == "__main__":
bot = ComplianceBot()
bot.collect_all()
Automated Remediation
def auto_remediate():
bot = ComplianceBot()
evidence = bot.collect_all()
for item in evidence:
if item['status'] == 'FAIL':
if 'MFA' in item['control']:
# Apply SCP requiring MFA
apply_scp_policy("force-mfa")
elif 'Public Access' in item['control']:
# Block public access on all buckets
s3 = boto3.client('s3')
buckets = s3.list_buckets()['Buckets']
for bucket in buckets:
s3.put_public_access_block(
Bucket=bucket['Name'],
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'BlockPublicPolicy': True,
'IgnorePublicAcls': True,
'RestrictPublicBuckets': True
}
)
elif 'Key Rotation' in item['control']:
# Disable old keys
iam = boto3.client('iam')
for detail in item['detail']:
# Extract user and key info
iam.update_access_key(
UserName=detail['user'],
AccessKeyId=detail['key'],
Status='Inactive'
)
return "Auto-remediation complete!"
Compliance as Code
# Terraform compliance checks
resource "aws_s3_bucket_public_access_block" "all" {
bucket = aws_s3_bucket.data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# Enforce encryption
resource "aws_s3_bucket_server_side_encryption_configuration" "all" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
# Enforce versioning
resource "aws_s3_bucket_versioning" "all" {
bucket = aws_s3_bucket.data.id
versioning_configuration {
status = "Enabled"
}
}
GRC Tools Comparison
| Tool | Focus | Features | Price | |------|-------|----------|-------| | Vanta | SOC 2, HIPAA | Auto-evidence, integrations, reporting | $12K/yr | | Drata | SOC 2, GDPR | 100+ integrations, continuous monitoring | $12K/yr | | Secureframe | SOC 2, ISO 27001 | Questionnaire automation | $12K/yr | | AWS Audit Manager | AWS-specific | Automated evidence collection | Per assessment |
Compliance Course Complete! 🎉
- ✅ GDPR
- ✅ SOC 2
- ✅ PCI DSS
- ✅ ISO 27001
- ✅ Compliance Automation
Security Track Complete! 🎉
- ✅ Cryptography
- ✅ Network Security
- ✅ IAM
- ✅ Cloud Security
- ✅ DevSecOps
- ✅ Pentesting Advanced
- ✅ Compliance
合規自動化:用程式碼管理合規
為什麼需要自動化?
| 問題 | 手動方式 | 自動化方式 | |:----|:--------|:----------| | 稽核準備 | 人工收集證據 | 自動產生稽核報告 | | 政策檢查 | 人工檢查設定 | CI/CD 自動掃描 | | 修復 | 人工修改 | 自動修復腳本 | | 監控 | 定期手動檢查 | 即時監控 + 告警 |
實作自動化合規
# .github/workflows/compliance.yml
name: 合規檢查
on: [push, pull_request]
jobs:
compliance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 基礎設施掃描
run: terraform validate
- name: 安全掃描
run: checkov -d terraform/
- name: 合規報告
run: |
# 自動產生合規報告
python generate_report.py
課程總結
這堂合規課程從 ISO 27001、SOC 2、PCI DSS、合規自動化——你現在知道如何建立與維護合規系統。