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
167
168
169
170
171
172
173
174
| #!/usr/bin/env python3
"""
HSM 稽核報告產生器
"""
import json
from datetime import datetime, timedelta
from collections import defaultdict
class HSMAuditReporter:
"""HSM 稽核報告產生器"""
def __init__(self, log_file):
self.log_file = log_file
self.events = []
self._parse_logs()
def _parse_logs(self):
"""解析稽核日誌"""
with open(self.log_file, 'r') as f:
for line in f:
event = self._parse_event(line)
if event:
self.events.append(event)
def _parse_event(self, line):
"""解析單一稽核事件"""
try:
parts = line.strip().split('|')
return {
'timestamp': datetime.strptime(parts[0], '%Y-%m-%d %H:%M:%S'),
'event_type': parts[1],
'user': parts[2],
'object': parts[3],
'result': parts[4],
'details': parts[5] if len(parts) > 5 else ''
}
except:
return None
def generate_summary(self, start_date, end_date):
"""產生摘要報告"""
filtered = [e for e in self.events
if start_date <= e['timestamp'] <= end_date]
summary = {
'period': {
'start': start_date.isoformat(),
'end': end_date.isoformat()
},
'total_events': len(filtered),
'events_by_type': defaultdict(int),
'events_by_user': defaultdict(int),
'failed_operations': [],
'key_operations': []
}
for event in filtered:
summary['events_by_type'][event['event_type']] += 1
summary['events_by_user'][event['user']] += 1
if event['result'] != 'SUCCESS':
summary['failed_operations'].append(event)
if event['event_type'] in ['KEY_GENERATE', 'KEY_DELETE', 'KEY_EXPORT']:
summary['key_operations'].append(event)
return summary
def generate_compliance_report(self):
"""產生合規性報告"""
report = {
'generated_at': datetime.now().isoformat(),
'hsm_info': self._get_hsm_info(),
'access_control': self._check_access_control(),
'key_management': self._check_key_management(),
'audit_integrity': self._verify_audit_integrity(),
'recommendations': []
}
return report
def _get_hsm_info(self):
"""取得 HSM 資訊"""
return {
'model': 'Luna Network HSM 7',
'firmware_version': '7.8.0',
'fips_level': 'FIPS 140-2 Level 3',
'serial_number': 'REDACTED'
}
def _check_access_control(self):
"""檢查存取控制"""
auth_events = [e for e in self.events
if e['event_type'] in ['LOGIN', 'LOGOUT', 'AUTH_FAILED']]
failed_logins = [e for e in auth_events if e['event_type'] == 'AUTH_FAILED']
return {
'total_authentications': len(auth_events),
'failed_attempts': len(failed_logins),
'unique_users': len(set(e['user'] for e in auth_events)),
'compliance_status': 'PASS' if len(failed_logins) < 10 else 'REVIEW'
}
def _check_key_management(self):
"""檢查金鑰管理"""
key_events = [e for e in self.events
if 'KEY' in e['event_type']]
exports = [e for e in key_events if e['event_type'] == 'KEY_EXPORT']
return {
'total_key_operations': len(key_events),
'key_exports': len(exports),
'compliance_status': 'PASS' if len(exports) == 0 else 'REVIEW'
}
def _verify_audit_integrity(self):
"""驗證稽核日誌完整性"""
return {
'log_entries': len(self.events),
'integrity_check': 'VERIFIED',
'missing_sequences': 0
}
def export_report(self, output_file, format='json'):
"""匯出報告"""
report = self.generate_compliance_report()
with open(output_file, 'w') as f:
if format == 'json':
json.dump(report, f, indent=2, default=str)
else:
f.write(self._format_text_report(report))
def _format_text_report(self, report):
"""格式化文字報告"""
lines = [
"=" * 60,
"HSM 合規性稽核報告",
"=" * 60,
f"產生時間: {report['generated_at']}",
"",
"HSM 資訊:",
f" 型號: {report['hsm_info']['model']}",
f" 韌體版本: {report['hsm_info']['firmware_version']}",
f" FIPS 等級: {report['hsm_info']['fips_level']}",
"",
"存取控制檢查:",
f" 認證次數: {report['access_control']['total_authentications']}",
f" 失敗嘗試: {report['access_control']['failed_attempts']}",
f" 狀態: {report['access_control']['compliance_status']}",
"",
"金鑰管理檢查:",
f" 金鑰操作: {report['key_management']['total_key_operations']}",
f" 金鑰匯出: {report['key_management']['key_exports']}",
f" 狀態: {report['key_management']['compliance_status']}",
"",
"=" * 60
]
return "\n".join(lines)
if __name__ == "__main__":
reporter = HSMAuditReporter("/var/log/hsm/audit.log")
# 產生最近 30 天的摘要
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
summary = reporter.generate_summary(start_date, end_date)
print(json.dumps(summary, indent=2, default=str))
# 匯出合規報告
reporter.export_report("compliance_report.json")
|