-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
462 lines (396 loc) · 19.3 KB
/
Copy pathapp.py
File metadata and controls
462 lines (396 loc) · 19.3 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
from flask import Flask, jsonify, render_template, send_from_directory
from flask_cors import CORS
import os
import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path
import json
app = Flask(__name__)
CORS(app)
# Configuration
SCAP_REPORTS_ROOT = os.path.join(os.path.dirname(__file__), 'SCAP-Reports', 'Windows')
# XML namespace mappings
NAMESPACES = {
'cdf': 'http://checklists.nist.gov/xccdf/1.2',
'dc': 'http://purl.org/dc/elements/1.1/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
}
def severity_to_category(severity):
"""Map severity to STIG category."""
severity_lower = severity.lower() if severity else ''
if severity_lower == 'high':
return 'CAT I'
elif severity_lower == 'medium':
return 'CAT II'
elif severity_lower == 'low':
return 'CAT III'
return 'Unknown'
def parse_scap_report(xml_path):
"""Parse a SCAP XML report and extract relevant information."""
try:
tree = ET.parse(xml_path)
root = tree.getroot()
# The root element IS the Benchmark (check if tag contains Benchmark)
# If root is Benchmark, use it directly; otherwise search for it
if 'Benchmark' in root.tag:
benchmark = root
else:
benchmark = root.find('.//cdf:Benchmark', NAMESPACES)
benchmark_info = {}
if benchmark is not None:
benchmark_info = {
'id': benchmark.get('id', ''),
'title': benchmark.findtext('cdf:title', default='', namespaces=NAMESPACES),
'version': benchmark.findtext('cdf:version', default='', namespaces=NAMESPACES),
'description': benchmark.findtext('cdf:description', default='', namespaces=NAMESPACES)
}
# Extract all Rule definitions from Benchmark
rule_definitions = {}
# First, build a map of groups to their IDs
group_map = {}
if benchmark is not None:
for group in benchmark.findall('.//cdf:Group', NAMESPACES):
group_id = group.get('id', '').replace('xccdf_mil.disa.stig_group_', '')
# Store all rules in this group
for rule in group.findall('.//cdf:Rule', NAMESPACES):
rule_id = rule.get('id', '')
if rule_id:
group_map[rule_id] = group_id
# Now extract rule details - search for all rules in the benchmark
# Rules can be directly under Benchmark or under Groups
all_rules = []
if benchmark is not None:
# Get rules directly under benchmark
all_rules.extend(benchmark.findall('.//cdf:Rule', NAMESPACES))
for rule in all_rules:
rule_id = rule.get('id', '')
if rule_id:
# Extract title
title = rule.findtext('cdf:title', default='', namespaces=NAMESPACES)
# Extract description
desc_elem = rule.find('cdf:description', NAMESPACES)
description = desc_elem.text if desc_elem is not None and desc_elem.text else ''
# Extract fixtext - get all text content including from nested elements
fixtext_elem = rule.find('cdf:fixtext', NAMESPACES)
fixtext = ''
if fixtext_elem is not None:
# Use itertext() to get all text content, including from nested elements
fixtext = ''.join(fixtext_elem.itertext()).strip()
# Extract severity
severity = rule.get('severity', '')
# Extract version
version = rule.findtext('cdf:version', default='', namespaces=NAMESPACES)
# Extract all CCI identifiers
cci_list = []
for ident in rule.findall('cdf:ident', NAMESPACES):
if ident.text:
cci_list.append(ident.text)
# Get Group ID from map
group_id = group_map.get(rule_id, '')
rule_definitions[rule_id] = {
'title': title,
'description': description,
'fixtext': fixtext,
'severity': severity,
'category': severity_to_category(severity),
'version': version,
'cci': cci_list,
'group_id': group_id
}
# Extract TestResult
test_result = root.find('.//cdf:TestResult', NAMESPACES)
if test_result is None:
return None
# Extract system information
system_info = {}
# Extract target (hostname)
target = test_result.findtext('cdf:target', default='', namespaces=NAMESPACES)
if target:
system_info['hostname'] = target
# Extract target addresses (IP addresses)
target_addresses = []
for addr in test_result.findall('cdf:target-address', NAMESPACES):
if addr.text:
target_addresses.append(addr.text)
if target_addresses:
system_info['ip_addresses'] = target_addresses
# Extract identity (user)
identity = test_result.findtext('cdf:identity', default='', namespaces=NAMESPACES)
if identity:
system_info['identity'] = identity
# Extract organization
organization = test_result.findtext('cdf:organization', default='', namespaces=NAMESPACES)
if organization:
system_info['organization'] = organization
# Extract target facts
target_facts = test_result.find('cdf:target-facts', NAMESPACES)
interfaces = []
current_interface = {}
if target_facts is not None:
for fact in target_facts.findall('cdf:fact', NAMESPACES):
fact_name = fact.get('name', '')
fact_value = fact.text if fact.text else ''
# Handle network interfaces (they appear as sequential facts)
if 'interface_name' in fact_name:
# Save previous interface if exists
if current_interface and current_interface.get('name'):
interfaces.append(current_interface)
# Start new interface
current_interface = {'name': fact_value, 'ip_addresses': [], 'mac_address': ''}
elif 'ipv4' in fact_name and current_interface:
if fact_value:
current_interface['ip_addresses'].append(fact_value)
elif 'mac' in fact_name and current_interface:
current_interface['mac_address'] = fact_value if fact_value else 'MAC not found'
# Map other fact names to readable labels
elif 'host_name' in fact_name:
system_info['hostname'] = fact_value
elif 'domain' in fact_name:
system_info['domain'] = fact_value
elif 'fqdn' in fact_name:
system_info['fqdn'] = fact_value
elif 'os_name' in fact_name:
system_info['os_name'] = fact_value
elif 'os_version' in fact_name:
system_info['os_version'] = fact_value
elif 'processor' in fact_name and 'architecture' not in fact_name and 'mhz' not in fact_name:
system_info['processor'] = fact_value
elif 'processor_architecture' in fact_name:
system_info['processor_architecture'] = fact_value
elif 'processor_mhz' in fact_name:
system_info['processor_mhz'] = fact_value
elif 'physical_memory' in fact_name:
system_info['physical_memory'] = fact_value
elif 'manufacturer' in fact_name:
system_info['manufacturer'] = fact_value
elif 'model' in fact_name:
system_info['model'] = fact_value
elif 'bios_version' in fact_name:
system_info['bios_version'] = fact_value
elif 'ein' in fact_name: # Serial number (EIN)
system_info['serial_number'] = fact_value
# Add last interface if exists
if current_interface and current_interface.get('name'):
interfaces.append(current_interface)
if interfaces:
system_info['interfaces'] = interfaces
result_data = {
'id': test_result.get('id', ''),
'start_time': test_result.get('start-time', ''),
'end_time': test_result.get('end-time', ''),
'test_system': test_result.get('test-system', ''),
'version': test_result.get('version', ''),
'benchmark': benchmark_info,
'system_info': system_info,
'scores': {},
'rule_results': [],
'rules_by_category': {'CAT I': [], 'CAT II': [], 'CAT III': [], 'Unknown': []}
}
# Extract scores
for score in test_result.findall('.//cdf:score', NAMESPACES):
system = score.get('system', '')
value = score.get('maximum', '')
text = score.text
if system:
result_data['scores'][system] = {
'value': float(text) if text else 0,
'maximum': float(value) if value else 100
}
# Extract rule results and match with definitions
rule_results = test_result.findall('.//cdf:rule-result', NAMESPACES)
pass_count = 0
fail_count = 0
notapplicable_count = 0
notchecked_count = 0
error_count = 0
unknown_count = 0
for rule_result in rule_results:
rule_id = rule_result.get('idref', '')
result = rule_result.findtext('cdf:result', default='unknown', namespaces=NAMESPACES)
severity = rule_result.get('severity', '')
version = rule_result.get('version', '')
weight = rule_result.get('weight', '0')
time = rule_result.get('time', '')
# Count results
if result == 'pass':
pass_count += 1
elif result == 'fail':
fail_count += 1
elif result == 'notapplicable':
notapplicable_count += 1
elif result == 'notchecked':
notchecked_count += 1
elif result == 'error':
error_count += 1
else:
unknown_count += 1
# Extract message
message_elem = rule_result.find('cdf:message', NAMESPACES)
message = message_elem.text if message_elem is not None and message_elem.text else ''
# Extract CCI identifiers from rule-result
cci_list = []
for ident in rule_result.findall('cdf:ident', NAMESPACES):
if ident.text:
cci_list.append(ident.text)
# Get rule definition if available
rule_def = rule_definitions.get(rule_id, {})
# Determine category
category = rule_def.get('category', severity_to_category(severity))
rule_data = {
'id': rule_id,
'result': result,
'severity': severity,
'category': category,
'version': version,
'weight': float(weight) if weight else 0,
'time': time,
'message': message,
'cci': cci_list if cci_list else (rule_def.get('cci', []) if rule_def else []),
'title': rule_def.get('title', ''),
'description': rule_def.get('description', ''),
'fixtext': rule_def.get('fixtext', ''),
'group_id': rule_def.get('group_id', '')
}
result_data['rule_results'].append(rule_data)
result_data['rules_by_category'][category].append(rule_data)
result_data['summary'] = {
'pass': pass_count,
'fail': fail_count,
'notapplicable': notapplicable_count,
'notchecked': notchecked_count,
'error': error_count,
'unknown': unknown_count,
'total': len(rule_results)
}
# Category counts
result_data['category_counts'] = {
'CAT I': len(result_data['rules_by_category']['CAT I']),
'CAT II': len(result_data['rules_by_category']['CAT II']),
'CAT III': len(result_data['rules_by_category']['CAT III']),
'Unknown': len(result_data['rules_by_category']['Unknown'])
}
return result_data
except Exception as e:
print(f"Error parsing {xml_path}: {str(e)}")
import traceback
traceback.print_exc()
return None
@app.route('/')
def index():
"""Serve the main dashboard page."""
return render_template('index.html')
@app.route('/api/computers')
def get_computers():
"""Get list of all computers with their reports."""
computers = []
if not os.path.exists(SCAP_REPORTS_ROOT):
return jsonify(computers)
for computer_dir in os.listdir(SCAP_REPORTS_ROOT):
computer_path = os.path.join(SCAP_REPORTS_ROOT, computer_dir)
if os.path.isdir(computer_path):
reports = []
# Find all XML files in the computer directory
for file in os.listdir(computer_path):
if file.endswith('.xml'):
file_path = os.path.join(computer_path, file)
file_stat = os.stat(file_path)
# Parse the report to get basic info
report_data = parse_scap_report(file_path)
report_info = {
'filename': file,
'path': file_path,
'modified': datetime.fromtimestamp(file_stat.st_mtime).isoformat(),
'size': file_stat.st_size
}
if report_data:
report_info.update({
'start_time': report_data.get('start_time', ''),
'end_time': report_data.get('end_time', ''),
'score': report_data.get('scores', {}).get('urn:xccdf:scoring:default', {}).get('value', 0),
'summary': report_data.get('summary', {}),
'system_info': report_data.get('system_info', {})
})
reports.append(report_info)
# Sort reports by modified date (newest first)
reports.sort(key=lambda x: x['modified'], reverse=True)
if reports:
# Get latest report summary for computer overview
latest_report = reports[0]
# Extract OS, benchmark, and system info from latest report if available
os_name = 'Unknown'
benchmark_info = {}
system_info = {}
if latest_report.get('path'):
try:
report_data = parse_scap_report(latest_report['path'])
if report_data:
if report_data.get('benchmark'):
benchmark_info = report_data['benchmark']
benchmark_title = benchmark_info.get('title', '')
# Extract OS from benchmark title (e.g., "Microsoft Windows 11 STIG...")
if 'Windows 11' in benchmark_title:
os_name = 'Windows 11'
elif 'Windows 10' in benchmark_title:
os_name = 'Windows 10'
elif 'Windows' in benchmark_title:
os_name = 'Windows'
elif 'Linux' in benchmark_title:
os_name = 'Linux'
elif 'RHEL' in benchmark_title or 'Red Hat' in benchmark_title:
os_name = 'Red Hat Enterprise Linux'
elif 'Ubuntu' in benchmark_title:
os_name = 'Ubuntu'
elif 'macOS' in benchmark_title or 'Mac OS' in benchmark_title:
os_name = 'macOS'
# Get system info from latest report
if report_data.get('system_info'):
system_info = report_data['system_info']
# Use OS from system info if available and more specific
if system_info.get('os_name'):
os_name = system_info['os_name']
except:
pass
computer_info = {
'hostname': computer_dir,
'report_count': len(reports),
'latest_report': latest_report.get('modified', ''),
'latest_score': latest_report.get('score', 0),
'latest_summary': latest_report.get('summary', {}),
'os': os_name,
'benchmark': benchmark_info,
'system_info': system_info,
'reports': reports
}
computers.append(computer_info)
# Sort computers by hostname
computers.sort(key=lambda x: x['hostname'])
return jsonify(computers)
@app.route('/api/report/<path:computer>/<filename>')
def get_report(computer, filename):
"""Get detailed information for a specific report."""
# Normalize path separators for Windows compatibility
computer = computer.replace('\\', os.sep).replace('/', os.sep)
report_path = os.path.join(SCAP_REPORTS_ROOT, computer, filename)
if not os.path.exists(report_path):
return jsonify({'error': 'Report not found'}), 404
report_data = parse_scap_report(report_path)
if report_data is None:
return jsonify({'error': 'Failed to parse report'}), 500
# Add file metadata
file_stat = os.stat(report_path)
report_data['file_info'] = {
'filename': filename,
'path': report_path,
'modified': datetime.fromtimestamp(file_stat.st_mtime).isoformat(),
'size': file_stat.st_size
}
return jsonify(report_data)
@app.route('/api/report/<path:computer>/<filename>/download')
def download_report(computer, filename):
"""Download the raw XML report file."""
# Normalize path separators for Windows compatibility
computer = computer.replace('\\', os.sep).replace('/', os.sep)
directory = os.path.join(SCAP_REPORTS_ROOT, computer)
return send_from_directory(directory, filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)