#!/usr/bin/env python3
"""
Sherlock's Autonomous Patch Management Bot
==========================================
This bot automates patch management with the following capabilities:
- **Patch Discovery**: Fetches vulnerabilities/patches from NVD API (simplified; extend to vendor APIs like Microsoft, RedHat).
- **Risk Sequencing**: Prioritizes by CVSS score, exploitability, and affected asset count.
- **Sandbox Testing**: Deploys patches in Docker-based sandboxes mimicking production environments.
- **Change Window Coordination**: Integrates with a mock ITSM calendar (e.g., Google Calendar API or ServiceNow; extend as needed).
- **Autonomous Remediation**: Deploys high-risk patches first during approved windows.
Requirements:
- pip install requests docker beautifulsoup4 APScheduler cve-search (optional for local CVE DB)
- Docker daemon running for sandboxes.
- Extend with real integrations: Ansible for deployment, Prometheus for monitoring.
Run: python patch_bot.py
"""
import json
import logging
import os
import subprocess
import time
from datetime import datetime, timedelta
from typing import List, Dict, Any
from dataclasses import dataclass
from concurrent.futures import ThreadPoolExecutor
import requests
from docker import from_env
from apscheduler.schedulers.background import BackgroundScheduler
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@dataclass
class Patch:
id: str
cve_id: str
cvss_score: float
description: str
affected_assets: List[str]
risk_level: str # HIGH, MEDIUM, LOW
status: str = "pending" # pending, tested, approved, deployed
class SandboxTester:
"""Tests patches in isolated Docker sandboxes."""
def __init__(self, base_image: str = "ubuntu:22.04"):
self.client = from_env()
self.base_image = base_image
def create_sandbox(self, env_name: str) -> str:
"""Spin up a sandbox container."""
container = self.client.containers.run(
self.base_image,
detach=True,
name=env_name,
privileged=True,
environment={"DEBIAN_FRONTEND": "noninteractive"}
)
return container.id
def apply_patch(self, container_id: str, patch_cmd: str) -> bool:
"""Apply patch via exec (simulate apt/yum update)."""
try:
exec_result = self.client.api.exec_create(container_id, ["/bin/bash", "-c", patch_cmd])
output = self.client.api.exec_start(exec_result)
logger.info(f"Patch applied: {output.decode()}")
return True
except Exception as e:
logger.error(f"Patch application failed: {e}")
return False
def run_tests(self, container_id: str) -> Dict[str, Any]:
"""Run smoke tests (e.g., service health, perf checks)."""
tests = [
"apt update && apt list --upgradable", # Check for breaks
"systemctl is-active ssh", # Hypothetical service check
"stress --cpu 1 --timeout 30s" # Basic perf test
]
results = {}
for test in tests:
exec_result = self.client.api.exec_create(container_id, ["/bin/bash", "-c", test])
output = self.client.api.exec_start(exec_result)
results[test] = output.decode().strip()
return {"passed": True, "details": results} # Simplified; add assertions
def test_patch(self, patch: Patch) -> Dict[str, Any]:
"""Full test cycle."""
sandbox_id = f"sandbox-{patch.id}"
try:
cid = self.create_sandbox(sandbox_id)
patch_cmd = f"apt update && apt install -y {patch.id}" # Mock; customize per OS/vendor
if self.apply_patch(cid, patch_cmd):
test_results = self.run_tests(cid)
self.client.containers.get(cid).stop()
self.client.containers.get(cid).remove()
return {"passed": test_results["passed"], "sandbox_id": cid, **test_results}
else:
return {"passed": False}
except Exception as e:
logger.error(f"Sandbox test failed for {patch.id}: {e}")
return {"passed": False}
class ChangeWindowCoordinator:
"""Coordinates deployments with approved change windows."""
def __init__(self, windows_file: str = "change_windows.json"):
self.windows_file = windows_file
self.load_windows()
def load_windows(self):
"""Load approved windows from JSON (mock ITSM integration)."""
if os.path.exists(self.windows_file):
with open(self.windows_file, 'r') as f:
self.windows = json.load(f)
else:
# Default windows: Weekdays 2-4 AM UTC
self.windows = [
{"start": "2024-01-01T02:00:00Z", "end": "2024-01-01T04:00:00Z", "approved": True}
]
def is_window_open(self, now: datetime = None) -> bool:
if now is None:
now = datetime.utcnow()
for window in self.windows:
start = datetime.fromisoformat(window["start"].replace('Z', '+00:00'))
end = datetime.fromisoformat(window["end"].replace('Z', '+00:00'))
if start <= now <= end:
return True
return False
def next_window(self) -> datetime:
"""Find next available window."""
now = datetime.utcnow()
for window in sorted(self.windows, key=lambda w: datetime.fromisoformat(w["start"].replace('Z', '+00:00'))):
start = datetime.fromisoformat(window["start"].replace('Z', '+00:00'))
if start > now:
return start
return now + timedelta(days=7) # Fallback
class PatchManager:
"""Core orchestrator for autonomous patch management."""
def __init__(self):
self.tester = SandboxTester()
self.coordinator = ChangeWindowCoordinator()
self.patches: List[Patch] = []
def discover_patches(self) -> List[Patch]:
"""Fetch patches from NVD API (top recent CVEs as mock)."""
url = "https://services.nvd.nist.gov/rest/json/cves/2.0/?resultsPerPage=10&startIndex=0"
try:
resp = requests.get(url, timeout=10)
data = resp.json()
patches = []
for vuln in data['vulnerabilities']:
cve = vuln['cve']
cvss = cve.get('metrics', {}).get('cvssMetricV31', [{}])[0].get('cvssData', {}).get('baseScore', 0)
risk = "HIGH" if cvss >= 7 else "MEDIUM" if cvss >= 4 else "LOW"
patches.append(Patch(
id=f"patch-{cve['id'].split(':')[-1]}",
cve_id=cve['id'],
cvss_score=cvss,
description=cve['descriptions'][0]['value'][:100],
affected_assets=["server-01", "server-02"], # Mock; query CMDB
risk_level=risk
))
self.patches = sorted(patches, key=lambda p: p.cvss_score, reverse=True)
logger.info(f"Discovered {len(self.patches)} patches, prioritized by risk.")
return self.patches
except Exception as e:
logger.error(f"Patch discovery failed: {e}")
return []
def sequence_by_risk(self) -> List[Patch]:
"""Ensure patches are sorted by risk (CVSS desc)."""
return sorted(self.patches, key=lambda p: (p.cvss_score, len(p.affected_assets)), reverse=True)
def test_patches(self, max_concurrent: int = 3):
"""Test pending patches in parallel sandboxes."""
pending = [p for p in self.patches if p.status == "pending"]
with ThreadPoolExecutor(max_workers=max_concurrent) as executor:
futures = [executor.submit(self.tester.test_patch, p) for p in pending]
for future, patch in zip(futures, pending):
result = future.result()
patch.status = "tested" if result["passed"] else "failed"
logger.info(f"Patch {patch.id}: {'PASSED' if result['passed'] else 'FAILED'}")
def deploy_patch(self, patch: Patch):
"""Deploy approved patch (mock Ansible/SSH)."""
if patch.status != "approved":
return
cmd = f"ansible-playbook -i inventory deploy_{patch.id}.yml" # Extend with real playbook
try:
subprocess.run(cmd, shell=True, check=True, capture_output=True)
patch.status = "deployed"
logger.info(f"Deployed {patch.id}")
except subprocess.CalledProcessError as e:
logger.error(f"Deployment failed for {patch.id}: {e}")
def run_cycle(self):
"""Full autonomous cycle: Discover -> Test -> Sequence -> Deploy in windows."""
logger.info("Starting patch management cycle...")
# 1. Discover and sequence
self.discover_patches()
high_risk = [p for p in self.sequence_by_risk() if p.risk_level == "HIGH"]
# 2. Test in sandboxes
self.test_patches()
approved = [p for p in high_risk if p.status == "tested"]
for p in approved:
p.status = "approved"
# 3. Coordinate windows and deploy
if self.coordinator.is_window_open():
for patch in approved:
self.deploy_patch(patch)
else:
next_win = self.coordinator.next_window()
logger.info(f"Next change window: {next_win}. Sleeping...")
time.sleep((next_win - datetime.utcnow()).total_seconds())
def main():
manager = PatchManager()
scheduler = BackgroundScheduler()
scheduler.add_job(func=manager.run_cycle, trigger="interval", hours=24) # Daily cycle
scheduler.start()
# Run once immediately
manager.run_cycle()
try:
# Keep running
while True:
time.sleep(3600) # Check hourly
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
if __name__ == "__main__":
main()
How It Works
Discovery: Pulls recent CVEs from NIST NVD API, mocks patches with risk scoring (CVSS-based). Extend with vendor feeds (e.g., requests.get('https://api.github.com/repos/microsoft/wsus-offline/releases')).
Risk Sequencing: Sorts by CVSS score descending, then affected assets.
Sandbox Testing: Uses Docker to create ephemeral Ubuntu containers, applies patches, runs tests (extend with custom images/scripts for your stack: Windows via mcr.microsoft.com/windows/servercore).
Change Windows: Checks JSON config for windows (replace with Google Calendar API, ServiceNow REST, or PagerDuty).
Autonomy: APScheduler runs daily cycles. Deploys only tested/approved patches during windows.
Extensibility:
Real Deployment: Integrate Ansible Tower/AWX, SaltStack, or cloud APIs (AWS SSM, Azure Update Management).
Asset Inventory: Query CMDB (e.g., ServiceNow CMDB API) for affected_assets.
Monitoring: Add Prometheus hooks for post-deploy alerts.
Rollback: Extend deploy_patch with pre/post snapshots (e.g., Docker volumes or VM snapshots).