#!/usr/bin/env python3
"""
Vulnerability Scanner
Scan container images for vulnerabilities using Trivy.
Usage:
# Scan image
python vulnerability_scanner.py scan --image gcr.io/my-project/my-app:latest
# Check compliance
python vulnerability_scanner.py compliance --image gcr.io/my-project/my-app:latest
# Export results
python vulnerability_scanner.py scan --image my-image --output results.json
"""
import argparse
import json
import subprocess
import sys
from typing import Dict, List, Optional
class VulnerabilityScanner:
"""Scan container images for vulnerabilities using Trivy."""
def __init__(self, trivy_path: str = 'trivy'):
"""
Initialize vulnerability scanner.
Args:
trivy_path: Path to trivy binary (default: 'trivy')
"""
self.trivy_path = trivy_path
def scan_image(
self,
image: str,
severity: str = 'HIGH,CRITICAL',
format: str = 'json'
) -> Dict:
"""
Scan container image for vulnerabilities.
Args:
image: Container image to scan
severity: Severity levels to include (default: HIGH,CRITICAL)
format: Output format (json, table) (default: json)
Returns:
Dictionary with scan results
"""
try:
result = subprocess.run(
[
self.trivy_path,
'image',
'--severity', severity,
'--format', format,
'--no-progress',
image
],
capture_output=True,
text=True,
check=False
)
if format == 'json':
try:
data = json.loads(result.stdout)
vulnerabilities = []
for result_item in data.get('Results', []):
for vuln in result_item.get('Vulnerabilities', []):
vulnerabilities.append({
'id': vuln.get('VulnerabilityID'),
'severity': vuln.get('Severity'),
'package': vuln.get('PkgName'),
'installed_version': vuln.get('InstalledVersion'),
'fixed_version': vuln.get('FixedVersion'),
'title': vuln.get('Title'),
'description': vuln.get('Description'),
})
return {
'image': image,
'vulnerabilities': vulnerabilities,
'total': len(vulnerabilities),
'critical': len([v for v in vulnerabilities if v['severity'] == 'CRITICAL']),
'high': len([v for v in vulnerabilities if v['severity'] == 'HIGH']),
}
except json.JSONDecodeError:
return {
'error': 'Failed to parse JSON output',
'stdout': result.stdout,
'stderr': result.stderr,
}
else:
return {
'image': image,
'output': result.stdout,
}
except FileNotFoundError:
return {
'error': f'Trivy not found at {self.trivy_path}. Install Trivy first.',
}
except Exception as e:
return {
'error': str(e),
}
def check_compliance(self, image: str) -> Dict:
"""
Check image against CIS benchmarks and security checks.
Args:
image: Container image to check
Returns:
Dictionary with compliance results
"""
try:
result = subprocess.run(
[
self.trivy_path,
'image',
'--security-checks', 'config',
'--format', 'json',
'--no-progress',
image
],
capture_output=True,
text=True,
check=False
)
try:
data = json.loads(result.stdout)
issues = []
for result_item in data.get('Results', []):
for misconf in result_item.get('Misconfigurations', []):
issues.append({
'id': misconf.get('ID'),
'type': misconf.get('Type'),
'severity': misconf.get('Severity'),
'title': misconf.get('Title'),
'description': misconf.get('Description'),
'status': misconf.get('Status'),
})
return {
'image': image,
'compliant': len(issues) == 0,
'issues': issues,
'total_issues': len(issues),
'critical': len([i for i in issues if i['severity'] == 'CRITICAL']),
'high': len([i for i in issues if i['severity'] == 'HIGH']),
}
except json.JSONDecodeError:
return {
'error': 'Failed to parse JSON output',
'stdout': result.stdout,
}
except FileNotFoundError:
return {
'error': f'Trivy not found at {self.trivy_path}. Install Trivy first.',
}
except Exception as e:
return {
'error': str(e),
}
def main():
"""CLI entry point."""
parser = argparse.ArgumentParser(
description="Vulnerability Scanner - Scan container images for vulnerabilities",
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--trivy-path",
default="trivy",
help="Path to trivy binary (default: trivy)"
)
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
# Scan command
scan_parser = subparsers.add_parser("scan", help="Scan image for vulnerabilities")
scan_parser.add_argument("--image", required=True, help="Container image to scan")
scan_parser.add_argument("--severity", default="HIGH,CRITICAL", help="Severity levels (default: HIGH,CRITICAL)")
scan_parser.add_argument("--format", choices=["json", "table"], default="json", help="Output format")
scan_parser.add_argument("--output", help="Output file path (JSON)")
# Compliance command
compliance_parser = subparsers.add_parser("compliance", help="Check image compliance")
compliance_parser.add_argument("--image", required=True, help="Container image to check")
compliance_parser.add_argument("--output", help="Output file path (JSON)")
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
try:
scanner = VulnerabilityScanner(trivy_path=args.trivy_path)
if args.command == "scan":
results = scanner.scan_image(
args.image,
severity=args.severity,
format=args.format
)
if 'error' in results:
print(f"❌ Error: {results['error']}", file=sys.stderr)
return 1
if args.output:
with open(args.output, 'w') as f:
json.dump(results, f, indent=2)
print(f"✅ Results saved to {args.output}")
else:
print(json.dumps(results, indent=2))
elif args.command == "compliance":
results = scanner.check_compliance(args.image)
if 'error' in results:
print(f"❌ Error: {results['error']}", file=sys.stderr)
return 1
if args.output:
with open(args.output, 'w') as f:
json.dump(results, f, indent=2)
print(f"✅ Results saved to {args.output}")
else:
print(json.dumps(results, indent=2))
if results.get('compliant'):
print("\n✅ Image is compliant")
else:
print(f"\n❌ Image has {results.get('total_issues', 0)} compliance issues")
return 0
except Exception as e:
print(f"❌ Error: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
exit(main())