"""
Modular Compliance Evidence Factory
===================================
This is a Python-based factory system for automating compliance evidence collection,
mapping to control frameworks (e.g., NIST 800-53, ISO 27001, SOC 2), and tracking
expiration dates. It uses a modular design with abstract base classes for extensibility.
Key Features:
- **Auto-Collection**: Pluggable collectors for artifacts (e.g., certs, configs, logs).
- **Mapping**: YAML/JSON configs map artifacts to controls.
- **Expiration Tracking**: Monitors dates (e.g., cert expiry) with SQLite persistence.
- **Factory Pattern**: Central orchestrator generates evidence reports.
- **Scheduling**: Built-in scheduler for periodic collection (using APScheduler).
Dependencies:
pip install pyyaml apscheduler cryptography boto3 # Add more for collectors (e.g., boto3 for AWS)
Usage:
1. Configure mappings in `control_mappings.yaml`.
2. Implement/extend collectors as needed.
3. Run `EvidenceFactory().run_cycle(framework='nist-800-53')`.
"""
import abc
import os
import sqlite3
import yaml
import json
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from apscheduler.schedulers.background import BackgroundScheduler
import boto3 # Example for AWS collector
# Database for tracking artifacts and expirations
DB_PATH = 'compliance_evidence.db'
class ComplianceDB:
"""SQLite wrapper for artifact storage and expiration tracking."""
def __init__(self, db_path: str = DB_PATH):
self.db_path = db_path
self.init_db()
def init_db(self):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS artifacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collector_id TEXT,
artifact_type TEXT,
data TEXT, -- JSON serialized artifact
control_ids TEXT, -- Comma-separated control IDs
collected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP,
status TEXT DEFAULT 'active' -- active, expired, archived
)
''')
conn.commit()
conn.close()
def store_artifact(self, collector_id: str, artifact_type: str, data: Dict[str, Any],
control_ids: List[str], expires_at: Optional[datetime] = None):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO artifacts (collector_id, artifact_type, data, control_ids, expires_at)
VALUES (?, ?, ?, ?, ?)
''', (collector_id, artifact_type, json.dumps(data), ','.join(control_ids),
expires_at.isoformat() if expires_at else None))
conn.commit()
conn.close()
def get_expiring_artifacts(self, days_ahead: int = 30) -> List[Dict[str, Any]]:
threshold = datetime.now() + timedelta(days=days_ahead)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM artifacts WHERE expires_at IS NOT NULL
AND datetime(expires_at) <= datetime(?) AND status = 'active'
''', (threshold.isoformat(),))
rows = cursor.fetchall()
conn.close()
return [dict(zip([col[0] for col in cursor.description], row)) for row in rows]
def mark_expired(self, artifact_id: int):
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('UPDATE artifacts SET status = "expired" WHERE id = ?', (artifact_id,))
conn.commit()
conn.close()
# Abstract Base Classes for Modularity
class ArtifactCollector(abc.ABC):
"""Abstract collector for compliance artifacts."""
@abc.abstractmethod
def collect(self) -> List[Dict[str, Any]]:
"""Return list of artifacts as dicts with metadata."""
pass
@abc.abstractmethod
def get_expiry(self, artifact: Dict[str, Any]) -> Optional[datetime]:
"""Extract expiry date from artifact, if applicable."""
pass
class ControlMapper(abc.ABC):
"""Maps artifacts to control frameworks."""
def __init__(self, mapping_file: str):
with open(mapping_file, 'r') as f:
self.mappings = yaml.safe_load(f) # {framework: {artifact_type: [control_ids]}}
def map_controls(self, framework: str, artifact_type: str) -> List[str]:
return self.mappings.get(framework, {}).get(artifact_type, [])
class ExpirationTracker:
"""Tracks and alerts on expirations."""
def __init__(self, db: ComplianceDB):
self.db = db
def check_expirations(self) -> List[Dict[str, Any]]:
expiring = self.db.get_expiring_artifacts()
for art in expiring:
if datetime.fromisoformat(art['expires_at']) < datetime.now():
self.db.mark_expired(art['id'])
return expiring
# Concrete Collectors (Extensible)
class CertificateCollector(ArtifactCollector):
"""Collects SSL/TLS certificates from filesystem."""
def __init__(self, cert_paths: List[str]):
self.cert_paths = cert_paths
def collect(self) -> List[Dict[str, Any]]:
artifacts = []
for path in self.cert_paths:
if os.path.exists(path):
with open(path, 'rb') as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
artifacts.append({
'path': path,
'subject': cert.subject.rfc4514_string(),
'serial': cert.serial_number,
'not_valid_after': cert.not_valid_after.isoformat()
})
return artifacts
def get_expiry(self, artifact: Dict[str, Any]) -> Optional[datetime]:
return datetime.fromisoformat(artifact['not_valid_after'])
class AWSConfigCollector(ArtifactCollector):
"""Collects AWS config snapshots (e.g., IAM policies)."""
def __init__(self, regions: List[str] = ['us-east-1']):
self.regions = regions
def collect(self) -> List[Dict[str, Any]]:
artifacts = []
for region in self.regions:
client = boto3.client('config', region_name=region)
# Example: Fetch conformance packs (extend as needed)
packs = client.list_conformance_packs()['ConformancePackNames']
artifacts.append({
'region': region,
'conformance_packs': packs,
'snapshot_time': datetime.now().isoformat()
})
return artifacts
def get_expiry(self, artifact: Dict[str, Any]) -> None:
return None # AWS configs typically don't expire
# Example Mapping Config (Save as control_mappings.yaml)
"""
nist-800-53:
certificate:
- SC-17
- IA-5
aws_config:
- AC-2
- AU-2
iso-27001:
certificate:
- A.10.1.2
aws_config:
- A.12.4.1
soc2:
certificate:
- CC6.1
aws_config:
- CC7.3
"""
# Central Factory
class EvidenceFactory:
"""Orchestrates collection, mapping, storage, and reporting."""
def __init__(self, collectors: List[ArtifactCollector], mapper: ControlMapper, db: ComplianceDB):
self.collectors = {c.__class__.__name__: c for c in collectors}
self.mapper = mapper
self.db = db
self.tracker = ExpirationTracker(db)
def run_collection_cycle(self, framework: str):
"""Full cycle: Collect, map, store, check expirations."""
for coll_id, collector in self.collectors.items():
artifacts = collector.collect()
for art in artifacts:
art_type = list(art.keys())[0] if art else 'unknown' # Infer type
control_ids = self.mapper.map_controls(framework, art_type)
expiry = collector.get_expiry(art)
self.db.store_artifact(coll_id, art_type, art, control_ids, expiry)
# Check expirations
expiring = self.tracker.check_expirations()
if expiring:
print(f"⚠️ Expiring artifacts: {len(expiring)}")
for e in expiring:
print(f" - {e['artifact_type']} expires {e['expires_at']}")
self.generate_report(framework)
def generate_report(self, framework: str) -> Dict[str, Any]:
"""Generate JSON report of current evidence."""
conn = sqlite3.connect(self.db.db_path)
cursor = conn.cursor()
cursor.execute('SELECT * FROM artifacts WHERE control_ids LIKE ? AND status="active"',
(f'%{framework}%',)) # Simplified filter
rows = cursor.fetchall()
report = {'framework': framework, 'artifacts': [dict(zip([c[0] for c in cursor.description], row)) for row in rows]}
conn.close()
with open(f'{framework}_evidence_report.json', 'w') as f:
json.dump(report, f, indent=2, default=str)
print(f"📊 Report generated: {framework}_evidence_report.json")
return report
def start_scheduler(self, framework: str, interval_minutes: int = 1440): # Daily
"""Start background scheduler."""
scheduler = BackgroundScheduler()
scheduler.add_job(self.run_collection_cycle, 'interval', minutes=interval_minutes, args=[framework])
scheduler.start()
print(f"🔄 Scheduler started for {framework} (every {interval_minutes} min)")
# Example Usage
if __name__ == "__main__":
# Setup
db = ComplianceDB()
mapper = ControlMapper('control_mappings.yaml') # Ensure file exists
collectors = [
CertificateCollector(['/etc/ssl/certs/server.crt']), # Customize paths
AWSConfigCollector()
]
factory = EvidenceFactory(collectors, mapper, db)
# Run once
factory.run_collection_cycle('nist-800-53')
# Or schedule
# factory.start_scheduler('nist-800-53')
Quick Start Guide
- Create
control_mappings.yaml with your framework mappings (example provided in code).
- Customize Collectors: Extend
ArtifactCollector for Kubernetes, Azure, logs, etc.
- Run:
python evidence_factory.py – collects, maps, stores, reports.
- Extend Mapping: Add frameworks/controls in YAML.
- Monitor: Query DB or use
factory.tracker.check_expirations().
- Production: Integrate with cron/APScheduler, add auth, web UI (e.g., Flask).
This factory is fully modular—plug in new collectors/mappers without changing the core. Scalable for enterprise compliance! 🕵️♂️