-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
468 lines (357 loc) · 15.9 KB
/
app.py
File metadata and controls
468 lines (357 loc) · 15.9 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
462
463
464
465
466
467
468
"""
RaidScanner Web Application
Flask-based GUI for vulnerability scanning
"""
# Eventlet monkey-patching must be done FIRST, before any other imports
import eventlet
eventlet.monkey_patch()
from flask import Flask, render_template, jsonify, request, send_from_directory, send_file
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import time
from pathlib import Path
from datetime import datetime
# Import core modules
from core.scanner_engine import ScannerEngine
from core.report_generator import ReportGenerator
from core.payload_loader import PayloadLoader
from utils.config import Config
# Initialize Flask app
app = Flask(__name__,
static_folder='web/static',
template_folder='web/templates')
app.config['SECRET_KEY'] = Config.SECRET_KEY
app.config['JSON_SORT_KEYS'] = False
# Enable CORS
CORS(app, resources={r"/api/*": {"origins": Config.CORS_ORIGINS}})
# Initialize SocketIO
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')
# Initialize core components
# Note: ScannerEngine is created per-scan to ensure isolation between concurrent scans
report_gen = ReportGenerator()
payload_loader = PayloadLoader()
# Ensure directories exist
Config.ensure_directories()
# ============================================================================
# WEB ROUTES
# ============================================================================
@app.route('/')
def index():
"""Main dashboard"""
return render_template('index.html')
@app.route('/scanner/<scan_type>')
def scanner_page(scan_type):
"""Scanner configuration page"""
return render_template('scanner.html', scan_type=scan_type)
@app.route('/reports')
def reports_page():
"""Reports viewer page"""
return render_template('reports.html')
# ============================================================================
# API ROUTES
# ============================================================================
@app.route('/api/payloads')
def get_payloads():
"""Get available payload files"""
try:
payloads = payload_loader.list_available_payloads()
return jsonify({'success': True, 'payloads': payloads})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/scan/lfi', methods=['POST'])
def scan_lfi():
"""LFI Scan Endpoint"""
try:
data = request.json
urls = data.get('urls', [])
threads = data.get('threads', 5)
success_criteria = data.get('success_criteria', ['root:x:0:'])
scan_id = data.get('scan_id') # Get scan ID from request
if not urls:
return jsonify({'success': False, 'error': 'No URLs provided'}), 400
# Load payloads
payloads = payload_loader.load_lfi_payloads()
# Create a new scanner instance for this scan (ensures isolation)
scanner = ScannerEngine()
def progress_callback(progress_data):
progress_data['scan_id'] = scan_id # Include scan ID in progress
socketio.emit('scan_progress', progress_data)
scanner.add_progress_callback(progress_callback)
# Run scan in background using socketio's background task (works with eventlet)
def run_scan():
try:
results = scanner.scan_lfi(urls, payloads, success_criteria, threads)
# Generate and save report
report_gen.generate_and_save('LFI', results, 'html')
report_gen.generate_and_save('LFI', results, 'json')
socketio.emit('scan_complete', {
'success': True,
'results': results,
'scan_id': scan_id # Include scan ID in completion
})
except Exception as e:
socketio.emit('scan_error', {
'success': False,
'error': str(e),
'scan_id': scan_id # Include scan ID in error
})
socketio.start_background_task(run_scan)
return jsonify({'success': True, 'message': 'Scan started'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/scan/sqli', methods=['POST'])
def scan_sqli():
"""SQLi Scan Endpoint"""
try:
data = request.json
urls = data.get('urls', [])
threads = data.get('threads', 5)
scan_id = data.get('scan_id') # Get scan ID from request
if not urls:
return jsonify({'success': False, 'error': 'No URLs provided'}), 400
# Load payloads
payloads = payload_loader.load_sqli_payloads()
# Create a new scanner instance for this scan (ensures isolation)
scanner = ScannerEngine()
def progress_callback(progress_data):
progress_data['scan_id'] = scan_id # Include scan ID in progress
socketio.emit('scan_progress', progress_data)
scanner.add_progress_callback(progress_callback)
# Run scan in background using socketio's background task (works with eventlet)
def run_scan():
try:
results = scanner.scan_sqli(urls, payloads, threads)
# Generate and save report
report_gen.generate_and_save('SQLi', results, 'html')
report_gen.generate_and_save('SQLi', results, 'json')
socketio.emit('scan_complete', {
'success': True,
'results': results,
'scan_id': scan_id # Include scan ID in completion
})
except Exception as e:
socketio.emit('scan_error', {
'success': False,
'error': str(e),
'scan_id': scan_id # Include scan ID in error
})
socketio.start_background_task(run_scan)
return jsonify({'success': True, 'message': 'Scan started'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/scan/xss', methods=['POST'])
def scan_xss():
"""XSS Scan Endpoint"""
try:
data = request.json
urls = data.get('urls', [])
threads = data.get('threads', 3)
scan_id = data.get('scan_id') # Get scan ID from request
if not urls:
return jsonify({'success': False, 'error': 'No URLs provided'}), 400
payloads = payload_loader.load_xss_payloads()
# Create a new scanner instance for this scan (ensures isolation)
scanner = ScannerEngine()
def progress_callback(progress_data):
progress_data['scan_id'] = scan_id # Include scan ID in progress
socketio.emit('scan_progress', progress_data)
scanner.add_progress_callback(progress_callback)
def run_scan():
try:
results = scanner.scan_xss(urls, payloads, threads)
# Generate and save report
report_gen.generate_and_save('XSS', results, 'html')
report_gen.generate_and_save('XSS', results, 'json')
socketio.emit('scan_complete', {
'success': True,
'results': results,
'scan_id': scan_id # Include scan ID in completion
})
except Exception as e:
socketio.emit('scan_error', {
'success': False,
'error': str(e),
'scan_id': scan_id # Include scan ID in error
})
socketio.start_background_task(run_scan)
return jsonify({'success': True, 'message': 'Scan started'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/scan/or', methods=['POST'])
def scan_or():
"""Open Redirect Scan Endpoint"""
try:
data = request.json
urls = data.get('urls', [])
threads = data.get('threads', 5)
scan_id = data.get('scan_id') # Get scan ID from request
if not urls:
return jsonify({'success': False, 'error': 'No URLs provided'}), 400
payloads = payload_loader.load_or_payloads()
# Create a new scanner instance for this scan (ensures isolation)
scanner = ScannerEngine()
def progress_callback(progress_data):
progress_data['scan_id'] = scan_id # Include scan ID in progress
socketio.emit('scan_progress', progress_data)
scanner.add_progress_callback(progress_callback)
def run_scan():
try:
results = scanner.scan_or(urls, payloads, threads)
# Generate and save report
report_gen.generate_and_save('OpenRedirect', results, 'html')
report_gen.generate_and_save('OpenRedirect', results, 'json')
socketio.emit('scan_complete', {
'success': True,
'results': results,
'scan_id': scan_id # Include scan ID in completion
})
except Exception as e:
socketio.emit('scan_error', {
'success': False,
'error': str(e),
'scan_id': scan_id # Include scan ID in error
})
socketio.start_background_task(run_scan)
return jsonify({'success': True, 'message': 'Scan started'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/scan/crlf', methods=['POST'])
def scan_crlf():
"""CRLF Injection Scan Endpoint"""
try:
data = request.json
urls = data.get('urls', [])
threads = data.get('threads', 5)
scan_id = data.get('scan_id') # Get scan ID from request
if not urls:
return jsonify({'success': False, 'error': 'No URLs provided'}), 400
# Create a new scanner instance for this scan (ensures isolation)
scanner = ScannerEngine()
def progress_callback(progress_data):
progress_data['scan_id'] = scan_id # Include scan ID in progress
socketio.emit('scan_progress', progress_data)
scanner.add_progress_callback(progress_callback)
def run_scan():
try:
results = scanner.scan_crlf(urls, threads)
# Generate and save report
report_gen.generate_and_save('CRLF', results, 'html')
report_gen.generate_and_save('CRLF', results, 'json')
socketio.emit('scan_complete', {
'success': True,
'results': results,
'scan_id': scan_id # Include scan ID in completion
})
except Exception as e:
socketio.emit('scan_error', {
'success': False,
'error': str(e),
'scan_id': scan_id # Include scan ID in error
})
socketio.start_background_task(run_scan)
return jsonify({'success': True, 'message': 'Scan started'})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/reports', methods=['GET'])
def get_reports():
"""List available reports"""
try:
reports_dir = Path(Config.REPORTS_DIR)
reports = []
if reports_dir.exists():
for report_file in reports_dir.glob('*.html'):
# Parse report metadata
name = report_file.stem
date = datetime.fromtimestamp(report_file.stat().st_mtime)
# Extract scan type from filename using prefix matching
scan_type = 'unknown'
name_lower = name.lower()
# Check most specific patterns first to avoid false positives
if name_lower.startswith('crlf_') or 'crlf_report' in name_lower:
scan_type = 'crlf'
elif name_lower.startswith('xss_') or 'xss_report' in name_lower:
scan_type = 'xss'
elif name_lower.startswith('sqli_') or 'sqli_report' in name_lower or 'sql_' in name_lower:
scan_type = 'sqli'
elif name_lower.startswith('lfi_') or 'lfi_report' in name_lower:
scan_type = 'lfi'
elif name_lower.startswith('openredirect_') or name_lower.startswith('or_'):
scan_type = 'or'
reports.append({
'name': name,
'type': scan_type,
'date': date.isoformat(),
'path': str(report_file),
'vulnerabilities': 0, # TODO: Parse from report
'urls_tested': 0, # TODO: Parse from report
'payloads': 0 # TODO: Parse from report
})
# Sort by date, newest first
reports.sort(key=lambda x: x['date'], reverse=True)
return jsonify({'reports': reports})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/reports/download')
def download_report():
"""Download a specific report"""
try:
report_path = request.args.get('path')
format_type = request.args.get('format', 'html')
if not report_path:
return jsonify({'error': 'Report path required'}), 400
file_path = Path(report_path)
if not file_path.exists():
return jsonify({'error': 'Report not found'}), 404
# Handle JSON format
if format_type == 'json':
json_path = file_path.with_suffix('.json')
if json_path.exists():
return send_file(json_path, as_attachment=True)
else:
return jsonify({'error': 'JSON report not found'}), 404
# Default to HTML
return send_file(file_path, as_attachment=True)
except Exception as e:
return jsonify({'error': str(e)}), 500
# ============================================================================
# WEBSOCKET EVENTS
# ============================================================================
@socketio.on('connect')
def handle_connect():
"""Client connected"""
emit('connected', {'message': 'Connected to RaidScanner', 'timestamp': time.time()})
@socketio.on('disconnect')
def handle_disconnect():
"""Client disconnected"""
print('Client disconnected')
@socketio.on('ping')
def handle_ping():
"""Ping/pong for connection check"""
emit('pong', {'timestamp': time.time()})
# ============================================================================
# ERROR HANDLERS
# ============================================================================
@app.errorhandler(404)
def not_found(error):
return jsonify({'success': False, 'error': 'Not found'}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({'success': False, 'error': 'Internal server error'}), 500
# ============================================================================
# MAIN
# ============================================================================
if __name__ == '__main__':
print("=" * 80)
print("🚀 RaidScanner Web Interface")
print("=" * 80)
print(f"📍 URL: http://{Config.HOST}:{Config.PORT}")
print(f"🔧 Debug Mode: {Config.DEBUG}")
print("=" * 80)
print("\nPress Ctrl+C to stop the server\n")
socketio.run(
app,
debug=Config.DEBUG,
host=Config.HOST,
port=Config.PORT,
allow_unsafe_werkzeug=True
)