1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
| #!/usr/bin/env python3
"""
Certificate Compliance Report Generator
"""
import json
import ssl
import socket
from datetime import datetime
from jinja2 import Template
class ComplianceReporter:
def __init__(self):
self.compliance_rules = {
'min_key_size': 2048,
'max_validity_days': 398, # CA/B Forum 要求
'required_key_usage': ['Digital Signature', 'Key Encipherment'],
'weak_algorithms': ['MD5', 'SHA1', 'RC4', 'DES']
}
def analyze_certificate(self, hostname, port=443):
"""分析憑證合規狀態"""
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
cert_bin = ssock.getpeercert(binary_form=True)
# 解析憑證詳情(簡化版)
findings = []
# 檢查有效期
not_after = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
not_before = datetime.strptime(cert['notBefore'], '%b %d %H:%M:%S %Y %Z')
validity_days = (not_after - not_before).days
if validity_days > self.compliance_rules['max_validity_days']:
findings.append({
'severity': 'warning',
'rule': 'max_validity_days',
'message': f'Certificate validity ({validity_days} days) exceeds recommended maximum'
})
return {
'hostname': hostname,
'subject': dict(x[0] for x in cert['subject']),
'issuer': dict(x[0] for x in cert['issuer']),
'not_before': not_before.isoformat(),
'not_after': not_after.isoformat(),
'validity_days': validity_days,
'serial_number': cert.get('serialNumber', 'N/A'),
'findings': findings,
'compliant': len([f for f in findings if f['severity'] == 'critical']) == 0
}
def generate_report(self, endpoints):
"""產生合規報告"""
results = []
for endpoint in endpoints:
hostname, port = endpoint.split(':')
try:
result = self.analyze_certificate(hostname, int(port))
results.append(result)
except Exception as e:
results.append({
'hostname': hostname,
'error': str(e),
'compliant': False
})
return self._render_report(results)
def _render_report(self, results):
"""渲染報告為 HTML"""
template = Template('''
<!DOCTYPE html>
<html>
<head>
<title>Certificate Compliance Report</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background-color: #4CAF50; color: white; }
.compliant { color: green; }
.non-compliant { color: red; }
.warning { color: orange; }
</style>
</head>
<body>
<h1>Certificate Compliance Report</h1>
<p>Generated: {{ timestamp }}</p>
<h2>Summary</h2>
<ul>
<li>Total Certificates Analyzed: {{ total }}</li>
<li>Compliant: {{ compliant }}</li>
<li>Non-Compliant: {{ non_compliant }}</li>
</ul>
<h2>Details</h2>
<table>
<tr>
<th>Hostname</th>
<th>Subject</th>
<th>Issuer</th>
<th>Expiry</th>
<th>Status</th>
</tr>
{% for result in results %}
<tr>
<td>{{ result.hostname }}</td>
<td>{{ result.subject.get('commonName', 'N/A') if result.subject else 'Error' }}</td>
<td>{{ result.issuer.get('commonName', 'N/A') if result.issuer else 'Error' }}</td>
<td>{{ result.not_after if result.not_after else 'N/A' }}</td>
<td class="{{ 'compliant' if result.compliant else 'non-compliant' }}">
{{ 'COMPLIANT' if result.compliant else 'NON-COMPLIANT' }}
</td>
</tr>
{% endfor %}
</table>
<h2>Findings</h2>
{% for result in results %}
{% if result.findings %}
<h3>{{ result.hostname }}</h3>
<ul>
{% for finding in result.findings %}
<li class="{{ finding.severity }}">
[{{ finding.severity | upper }}] {{ finding.message }}
</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</body>
</html>
''')
compliant_count = sum(1 for r in results if r.get('compliant', False))
return template.render(
results=results,
timestamp=datetime.now().isoformat(),
total=len(results),
compliant=compliant_count,
non_compliant=len(results) - compliant_count
)
# 使用範例
if __name__ == "__main__":
reporter = ComplianceReporter()
endpoints = [
'www.example.com:443',
'api.example.com:443',
'mail.example.com:993'
]
report = reporter.generate_report(endpoints)
with open('compliance_report.html', 'w') as f:
f.write(report)
print("Report generated: compliance_report.html")
|