Security Compliance & Audit: PCI-DSS, HIPAA, SOC 2, and ISO 27001
Organizations handling sensitive data must implement compliance frameworks with regular audits to meet legal requirements and earn customer trust.
Compliance Landscape
Framework Comparison
โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ Framework โ Scope โ Audit Type โ Frequency โ Cost Estimateโ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโค
โ PCI-DSS โ Payment data โ Required โ Annual/Qtr โ $50k-200k โ
โ HIPAA โ Health data โ Required โ 2-3 years โ $100k-500k โ
โ SOC 2 โ Services โ Optional โ Annual โ $30k-150k โ
โ ISO 27001 โ All info โ Optional โ Annual/3yr โ $80k-300k โ
โโโโโโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโค
โ Scope โ Mandatory if โ Compliance โ Ongoing โ Implementation
โ Coverage โ handle cards โ Certificationโmonitoring โ + audit
โโโโโโโโโโโโโโดโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโ
PCI-DSS (Payment Card Industry)
12 Core Requirements
class PCI_DSS_Compliance:
"""PCI-DSS v3.2.1 core requirements"""
def __init__(self):
self.requirements = {
1: {
'title': 'Install and maintain firewall',
'implementation': 'Multi-layer network architecture',
'testing': 'Verify firewall rules block unauthorized traffic'
},
2: {
'title': 'Do not use vendor defaults',
'implementation': 'Change all default passwords, disable unnecessary services',
'testing': 'Document all changes and verify hardening'
},
3: {
'title': 'Protect stored cardholder data',
'implementation': 'Encryption, tokenization, or masking',
'testing': 'Verify data is not stored in forbidden formats'
},
4: {
'title': 'Encrypt cardholder data in transit',
'implementation': 'TLS 1.2+, strong cryptography',
'testing': 'Network traffic analysis for plaintext'
},
5: {
'title': 'Use anti-malware software',
'implementation': 'Antivirus on all systems, regular updates',
'testing': 'Verify AV installed and signatures current'
},
6: {
'title': 'Secure development practices',
'implementation': 'SDLC, code review, vulnerability scanning',
'testing': 'Review development policies and test results'
},
7: {
'title': 'Restrict access by business need',
'implementation': 'Role-based access control (RBAC)',
'testing': 'Verify access is restricted to job duties'
},
8: {
'title': 'Identify and authenticate access',
'implementation': 'MFA, strong passwords (12+ chars)',
'testing': 'Test MFA, verify password policies'
},
9: {
'title': 'Restrict physical access',
'implementation': 'Access cards, badges, surveillance',
'testing': 'Observe physical security controls'
},
10: {
'title': 'Track and monitor network access',
'implementation': 'Logging, SIEM, audit trails',
'testing': 'Review logs for unauthorized activity'
},
11: {
'title': 'Regularly test security systems',
'implementation': 'Vulnerability scans, penetration testing, code reviews',
'testing': 'Annual assessments, quarterly network scans'
},
12: {
'title': 'Maintain information security policy',
'implementation': 'Documented policies, training, incident response',
'testing': 'Review policy documentation and training records'
}
}
def generate_compliance_checklist(self) -> list:
"""Generate implementation checklist"""
checklist = []
for req_num, req_data in self.requirements.items():
checklist.append({
'requirement': req_num,
'title': req_data['title'],
'implementation': req_data['implementation'],
'testing': req_data['testing'],
'status': 'Not Started'
})
return checklist
# Implementation example
pci = PCI_DSS_Compliance()
for item in pci.generate_compliance_checklist():
print(f"Req {item['requirement']}: {item['title']}")
HIPAA (Healthcare Data Protection)
Privacy & Security Rule
from cryptography.fernet import Fernet
from datetime import datetime
import hashlib
class HIPAA_Controls:
"""HIPAA Privacy & Security Rule implementation"""
def __init__(self):
self.encryption_key = Fernet.generate_key()
self.cipher = Fernet(self.encryption_key)
def encrypt_phi(self, phi_data: str) -> bytes:
"""Encrypt Protected Health Information"""
return self.cipher.encrypt(phi_data.encode())
def decrypt_phi(self, encrypted_data: bytes) -> str:
"""Decrypt PHI (audit-logged)"""
return self.cipher.decrypt(encrypted_data).decode()
def audit_log_access(self, user_id: str, phi_reference: str, action: str):
"""Log all PHI access for 6-year retention"""
log_entry = {
'timestamp': datetime.utcnow().isoformat(),
'user': user_id,
'action': action,
'phi_ref': hashlib.sha256(phi_reference.encode()).hexdigest(),
'ip_address': '192.168.1.100', # Would be captured from request
'result': 'success'
}
# Persist to immutable log
self._persist_audit_log(log_entry)
return log_entry
def implement_access_controls(self):
"""HIPAA Administrative Safeguards"""
controls = {
'authorization': {
'mfa_required': True,
'password_length': 14,
'password_expiry_days': 90,
'failed_login_lockout': 6
},
'user_management': {
'role_based_access': True,
'minimum_necessary': True, # Least privilege
'access_review_frequency': 'quarterly'
},
'session_management': {
'idle_timeout_minutes': 15,
'max_session_duration_hours': 8,
'concurrent_sessions_limit': 3
},
'encryption': {
'in_transit': 'TLS 1.2+',
'at_rest': 'AES-256',
'key_management': 'HSM'
}
}
return controls
def breach_notification(self, affected_individuals: int):
"""HIPAA Breach Notification Rule (60-day requirement)"""
notification_plan = {
'internal_notification': {
'timeline': '24 hours',
'recipients': ['Security Officer', 'CEO', 'Board'],
'content': 'Nature of breach, individuals affected, mitigation'
},
'individual_notification': {
'timeline': '60 days',
'method': 'Written notification or email',
'content': 'What happened, what data was affected, what to do',
'sample_language': 'We have determined that your Protected Health Information may have been accessed without authorization...'
},
'media_notification': {
'threshold': 500, # If 500+ individuals
'timeline': '60 days',
'recipients': 'Major media in area'
},
'hhs_notification': {
'threshold': 500,
'timeline': '60 days',
'recipients': 'U.S. Department of Health & Human Services'
}
}
return notification_plan
def _persist_audit_log(self, entry: dict):
"""Store audit log in immutable storage"""
# Implementation would write to secure audit log system
pass
# Usage
hipaa = HIPAA_Controls()
# Encrypt patient data
encrypted_ssn = hipaa.encrypt_phi("123-45-6789")
# Log access
hipaa.audit_log_access(
user_id='dr_smith',
phi_reference="123-45-6789",
action='view_patient_record'
)
# Get controls baseline
controls = hipaa.implement_access_controls()
print("Access Control Requirements:")
for category, details in controls.items():
print(f" {category}: {details}")
SOC 2 (Service Organization Control)
Type I vs Type II
from datetime import datetime, timedelta
class SOC2_Audit:
"""SOC 2 compliance framework"""
TRUST_PRINCIPLES = {
'CC': 'Common Criteria - Security',
'A': 'Availability',
'P': 'Processing Integrity',
'C': 'Confidentiality',
'PR': 'Privacy'
}
def generate_type1_report(self):
"""
Type I: Point-in-time assessment
- Single day or week snapshot
- Design of controls only (not operational effectiveness)
- $30-50k
- Validity: Immediate
"""
report = {
'report_type': 'Type I',
'scope': 'Design of controls as of [DATE]',
'period': '1 day',
'assessment_date': datetime.now().isoformat(),
'areas_tested': [
'Authorization and access control',
'Change management procedures',
'Encryption and key management',
'Incident response procedures'
],
'conclusion': 'Controls were designed appropriately to provide reasonable assurance'
}
return report
def generate_type2_report(self):
"""
Type II: Operating effectiveness assessment
- 6-12 month period of observation
- Tests ACTUAL OPERATION of controls
- $80-150k
- Validity: 1 year (recommended)
"""
start_date = datetime.now() - timedelta(days=180)
report = {
'report_type': 'Type II',
'scope': 'Operational effectiveness of controls',
'period': '6 months',
'testing_period_start': start_date.isoformat(),
'testing_period_end': datetime.now().isoformat(),
'areas_tested': [
'Authorization and access control - 47 control test points',
'Change management - 23 test points',
'Encryption and key management - 18 test points',
'Incident response - 15 test points',
'Logical & physical security - 34 test points'
],
'sample_tests': [
'Reviewed 50 user access requests - all approved by manager',
'Tested 12 production changes - all reviewed and tested',
'Examined 25 database backups - all encrypted with AES-256',
'Reviewed incident logs - all responded to within SLA'
],
'conclusion': 'Controls operated effectively throughout the six-month period'
}
return report
def map_to_trust_principles(self):
"""Map controls to SOC 2 trust principles"""
mapping = {
'CC': { # Common Criteria - Security
'controls': [
'CC6.1: Logical access control',
'CC6.2: Authentication',
'CC7.2: System monitoring',
'CC8.1: Change management'
],
'test_procedures': [
'Verify MFA is enabled for all users',
'Test that disabled users cannot access systems',
'Review change logs for unauthorized changes'
]
},
'A': { # Availability
'controls': [
'Redundant infrastructure',
'Backup and recovery procedures',
'Monitoring and alerting'
],
'metrics': [
'Uptime: 99.95% (monthly)',
'Recovery Time Objective (RTO): 4 hours',
'Recovery Point Objective (RPO): 1 hour'
]
},
'C': { # Confidentiality
'controls': [
'Data encryption in transit (TLS 1.2+)',
'Data encryption at rest (AES-256)',
'Access control and logging'
],
'test_procedures': [
'Network traffic analysis for encrypted protocols',
'Database encryption verification',
'Audit log review'
]
}
}
return mapping
# Usage
soc2 = SOC2_Audit()
print("=== Type I Report (Point-in-time) ===")
type1 = soc2.generate_type1_report()
print(f"Scope: {type1['scope']}")
print(f"Period: {type1['period']}")
print("\n=== Type II Report (Operational Effectiveness) ===")
type2 = soc2.generate_type2_report()
print(f"Scope: {type2['scope']}")
print(f"Period: {type2['period']}")
print(f"Sample test results: All controls operated effectively")
ISO 27001 (Information Security Management)
Implementation Framework
from enum import Enum
class ISO27001:
"""ISO 27001:2022 Information Security Management System"""
class ControlCategory(Enum):
ORGANIZATIONAL = 'A.5'
PEOPLE = 'A.6'
ASSET = 'A.7'
ACCESS = 'A.8'
CRYPTOGRAPHY = 'A.9'
PHYSICAL = 'A.10'
COMMUNICATIONS = 'A.11'
SYSTEMS = 'A.12'
SUPPLY_CHAIN = 'A.13'
INCIDENT = 'A.14'
BUSINESS_CONTINUITY = 'A.15'
COMPLIANCE = 'A.16'
def __init__(self):
self.controls = self._initialize_controls()
def _initialize_controls(self):
"""Define all 93 ISO 27001 controls"""
return {
'A.5': {
'category': 'Organizational Controls',
'controls': [
{
'id': 'A.5.1',
'name': 'Policies for information security',
'implementation': 'Create and maintain written info security policies',
'evidence': 'Policy documents, version control, approval records'
},
{
'id': 'A.5.2',
'name': 'Information security roles and responsibilities',
'implementation': 'Define security roles (CISO, security officer, etc)',
'evidence': 'Job descriptions, org chart, RACI matrix'
}
]
},
'A.6': {
'category': 'People Controls',
'controls': [
{
'id': 'A.6.1',
'name': 'Screening',
'implementation': 'Background checks for all employees',
'evidence': 'Screening procedures, check completion records'
},
{
'id': 'A.6.2',
'name': 'Terms and conditions of employment',
'implementation': 'Include security responsibilities in contracts',
'evidence': 'Employment contracts, NDA, acceptable use policy'
},
{
'id': 'A.6.3',
'name': 'Information security awareness, education and training',
'implementation': 'Annual training for all staff, role-specific training',
'evidence': 'Training records, attendance logs, test results'
}
]
},
'A.8': {
'category': 'Access Control',
'controls': [
{
'id': 'A.8.1',
'name': 'User registration and de-registration',
'implementation': 'Request process, approval workflow, timely termination',
'evidence': 'Access request forms, approval emails, termination checklist'
},
{
'id': 'A.8.2',
'name': 'User access provisioning',
'implementation': 'RBAC based on job requirements',
'evidence': 'Access matrix, role definitions, assignment records'
},
{
'id': 'A.8.3',
'name': 'Management of privileged access rights',
'implementation': 'MFA required, separate accounts, audit logging',
'evidence': 'PAM system logs, approval records, audit trails'
}
]
},
'A.9': {
'category': 'Cryptography',
'controls': [
{
'id': 'A.9.1',
'name': 'Cryptographic controls',
'implementation': 'Use approved algorithms (AES-256, RSA-2048+)',
'evidence': 'Encryption audit, key management procedures, standards'
},
{
'id': 'A.9.2',
'name': 'Cryptographic key management',
'implementation': 'Key generation, rotation (annually), destruction',
'evidence': 'Key inventory, rotation schedule, destruction certificates'
}
]
}
}
def audit_control_implementation(self, control_id: str) -> dict:
"""Assess implementation maturity of a control"""
maturity_levels = {
0: 'Not implemented',
1: 'Initial (informal, inconsistent)',
2: 'Developed (documented, somewhat consistent)',
3: 'Managed (standardized, consistently applied)',
4: 'Optimized (continuously improved)'
}
assessment = {
'control_id': control_id,
'current_maturity': 0,
'target_maturity': 3,
'gaps': [],
'remediation_plan': []
}
return assessment
def generate_statement_of_applicability(self, organization: str):
"""Generate SOA (required for certification)"""
soa = {
'organization': organization,
'issue_date': datetime.now().isoformat(),
'total_controls': 93,
'applicable_controls': 0,
'excluded_controls': 0,
'control_status': {
'implemented': 0,
'planned': 0,
'excluded': 0
},
'introduction': 'This Statement of Applicability describes the information security controls that are applicable to the organization...'
}
return soa
# Usage
iso = ISO27001()
# Assess control implementation
assessment = iso.audit_control_implementation('A.8.3')
print(f"Control {assessment['control_id']}")
print(f"Current maturity: {assessment['current_maturity']}/4")
print(f"Gap remediation: {assessment['remediation_plan']}")
# Generate SOA
soa = iso.generate_statement_of_applicability('Example Corp')
print(f"\nStatement of Applicability issued: {soa['issue_date']}")
print(f"Total controls: {soa['total_controls']}")
Continuous Compliance Monitoring
class ComplianceMonitoring:
"""Real-time compliance status tracking"""
def __init__(self):
self.compliance_status = {}
def monitor_access_controls(self) -> dict:
"""Continuous monitoring of access controls"""
status = {
'mfa_enabled': self._verify_mfa_percentage(),
'inactive_accounts': self._find_inactive_accounts(90),
'privileged_access': self._audit_privileged_access(),
'password_policy': self._verify_password_policy()
}
return status
def monitor_encryption(self) -> dict:
"""Monitor encryption deployment"""
return {
'tls_in_transit': self._check_tls_version('1.2'),
'encryption_at_rest': self._verify_database_encryption(),
'key_rotation': self._check_key_rotation(timedelta(days=365))
}
def generate_compliance_dashboard(self) -> dict:
"""Executive dashboard of compliance status"""
return {
'overall_compliance_score': 87.5,
'framework_status': {
'PCI-DSS': {'status': 'Compliant', 'next_audit': '2024-10-15'},
'HIPAA': {'status': 'Compliant', 'next_audit': '2025-03-20'},
'SOC2': {'status': 'In Progress', 'estimated': '2024-06-30'},
'ISO27001': {'status': 'Compliant', 'cert_expiry': '2025-01-10'}
},
'open_findings': 3,
'remediation_rate': 94,
'training_completion': 98
}
def _verify_mfa_percentage(self) -> float:
return 96.5 # 96.5% of users have MFA
def _find_inactive_accounts(self, days: int) -> int:
return 3 # 3 accounts inactive for 90+ days
def _audit_privileged_access(self) -> dict:
return {'total_privileged_users': 47, 'mfa_enabled': 47}
def _verify_password_policy(self) -> dict:
return {'min_length': 14, 'expiry_days': 90, 'enforced': True}
def _check_tls_version(self, required_version: str) -> bool:
return True
def _verify_database_encryption(self) -> bool:
return True
def _check_key_rotation(self, interval: timedelta) -> bool:
return True
Glossary
- Compliance: Meeting legal and regulatory requirements
- Audit: Third-party assessment of control implementation
- Control: Specific safeguard to prevent/detect security issues
- SOA: Statement of Applicability (list of applicable controls)
- Evidence: Documentation proving control implementation
- Gap: Control not yet implemented or matured
Resources
- PCI Security Standards Council
- HHS HIPAA Guidance
- AICPA SOC 2
- ISO 27001:2022 Standard
- Compliance Automation Tools
Comments