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
為什麼要學合規自動化?
合規自動化 是 security-compliance 課程的核心章節之一。
在真實世界中
合規自動化 並不是課本上的理論——它在真實的軟體開發中頻繁出現。無論你是正在接案、準備面試,還是想要提升自己的技術深度,理解這個主題都能讓你直接受益。
你將從本章獲得
- 🎯 完整的知識體系:從核心原理到實作細節,條理分明
- 💻 可運行的程式碼:每段程式碼都是完整的,可直接執行
- 🔍 除錯技巧:常見錯誤的分析與解決方案
- 🚀 下一步指引:學完後該往哪個方向繼續深入
銜接下一章
本章為你建立了 合規自動化 的完整知識基礎。下一章將在此基礎上,帶你探索更進階的真實世界應用場景——你將學會如何將本章所學應用到更複雜的問題中。