-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_app.py
More file actions
352 lines (295 loc) · 10.8 KB
/
web_app.py
File metadata and controls
352 lines (295 loc) · 10.8 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
#!/usr/bin/env python3
"""
Keyspace - Web Interface
Flask-based web application for remote access to Keyspace
"""
import os
import json
import threading
import time
from datetime import datetime
from pathlib import Path
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
import logging
# Import Keyspace components
from backend.brute_force_thread import BruteForceThread
from backend.security.session_encryption import SessionEncryption
from backend.security.audit_logger import AuditLogger, AuditEventType, AuditSeverity
from backend.security.permissions import PermissionManager, Permission, UserRole
from backend.security.compliance import ComplianceManager
from backend.integrations.api_integration import APIIntegration
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Flask app configuration
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'keyspace-secret-key-2024')
app.config['SESSION_TYPE'] = 'filesystem'
# Initialize security components
session_encryption = SessionEncryption()
audit_logger = AuditLogger()
permission_manager = PermissionManager()
compliance_manager = ComplianceManager(audit_logger)
# Global attack state
current_attack = None
attack_thread = None
attack_status = {
'running': False,
'progress': 0,
'speed': 0,
'eta': '00:00:00',
'attempts': 0,
'status': 'Ready'
}
# Initialize API integration
api_integration = APIIntegration(host='localhost', port=8080)
# Flask-Login setup
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin):
def __init__(self, user_id, username, role):
self.id = user_id
self.username = username
self.role = role
@login_manager.user_loader
def load_user(user_id):
user = permission_manager.get_user_by_id(user_id)
if user:
return User(user.user_id, user.username, user.role)
return None
# Routes
@app.route('/')
@login_required
def index():
"""Main dashboard"""
audit_logger.log_event(
AuditEventType.USER_LOGIN,
AuditSeverity.INFO,
"Web dashboard access",
"web_interface",
user_id=current_user.id
)
return render_template('index.html',
attack_status=attack_status,
user=current_user)
@app.route('/login', methods=['GET', 'POST'])
def login():
"""User login"""
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = permission_manager.authenticate_user(username, password)
if user:
flask_user = User(user.user_id, user.username, user.role)
login_user(flask_user)
audit_logger.log_event(
AuditEventType.USER_LOGIN,
AuditSeverity.INFO,
f"Web login successful for {username}",
"web_interface",
user_id=user.user_id
)
return redirect(url_for('index'))
else:
audit_logger.log_event(
AuditEventType.SECURITY_VIOLATION,
AuditSeverity.WARNING,
f"Failed web login attempt for {username}",
"web_interface"
)
flash('Invalid username or password')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
"""User logout"""
audit_logger.log_event(
AuditEventType.USER_LOGOUT,
AuditSeverity.INFO,
"Web logout",
"web_interface",
user_id=current_user.id
)
logout_user()
return redirect(url_for('login'))
@app.route('/api/start_attack', methods=['POST'])
@login_required
def start_attack():
"""Start a brute force attack"""
global attack_thread, current_attack, attack_status
if not permission_manager.has_permission(
permission_manager.get_user_by_id(current_user.id),
Permission.ATTACK_START
):
return jsonify({'error': 'Insufficient permissions'}), 403
if attack_status['running']:
return jsonify({'error': 'Attack already running'}), 400
try:
data = request.get_json()
target = data.get('target', '')
attack_type = data.get('attack_type', 'Dictionary Attack (WPA2)')
wordlist_path = data.get('wordlist_path', '')
min_length = data.get('min_length', 8)
max_length = data.get('max_length', 16)
charset = data.get('charset', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*')
# Validate inputs
if not target:
return jsonify({'error': 'Target is required'}), 400
if attack_type in ['Dictionary Attack (WPA2)', 'Rule-based Attack', 'Hybrid Attack', 'Combinator Attack']:
if not wordlist_path or not os.path.exists(wordlist_path):
return jsonify({'error': 'Valid wordlist path is required'}), 400
# Create attack thread
attack_thread = BruteForceThread(
target=target,
attack_type=attack_type,
wordlist_path=wordlist_path,
min_length=min_length,
max_length=max_length,
charset=charset
)
# Connect signals
attack_thread.progress_updated.connect(on_attack_progress)
attack_thread.status_updated.connect(on_attack_status)
attack_thread.result_updated.connect(on_attack_result)
attack_thread.error_occurred.connect(on_attack_error)
attack_thread.attack_log.connect(on_attack_log)
attack_thread.finished.connect(on_attack_finished)
# Start attack
attack_thread.start()
attack_status['running'] = True
audit_logger.log_event(
AuditEventType.ATTACK_START,
AuditSeverity.INFO,
f"Web attack started: {attack_type} on {target}",
"web_interface",
user_id=current_user.id
)
return jsonify({'message': 'Attack started successfully'})
except Exception as e:
logger.error(f"Failed to start web attack: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/api/stop_attack', methods=['POST'])
@login_required
def stop_attack():
"""Stop the current attack"""
global attack_thread, attack_status
if not permission_manager.has_permission(
permission_manager.get_user_by_id(current_user.id),
Permission.ATTACK_STOP
):
return jsonify({'error': 'Insufficient permissions'}), 403
if attack_thread and attack_status['running']:
attack_thread.stop()
audit_logger.log_event(
AuditEventType.ATTACK_END,
AuditSeverity.INFO,
"Web attack stopped",
"web_interface",
user_id=current_user.id
)
return jsonify({'message': 'Attack stopped'})
else:
return jsonify({'error': 'No attack running'}), 400
@app.route('/api/attack_status')
@login_required
def get_attack_status():
"""Get current attack status"""
return jsonify(attack_status)
@app.route('/api/compliance_report')
@login_required
def get_compliance_report():
"""Generate compliance report"""
if not permission_manager.has_permission(
permission_manager.get_user_by_id(current_user.id),
Permission.SECURITY_COMPLIANCE_VIEW
):
return jsonify({'error': 'Insufficient permissions'}), 403
try:
report = compliance_manager.generate_compliance_report()
return jsonify(report.to_dict())
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/audit_events')
@login_required
def get_audit_events():
"""Get audit events"""
if not permission_manager.has_permission(
permission_manager.get_user_by_id(current_user.id),
Permission.SECURITY_AUDIT_VIEW
):
return jsonify({'error': 'Insufficient permissions'}), 403
try:
limit = int(request.args.get('limit', 100))
events = audit_logger.get_events(limit=limit)
return jsonify([event.to_dict() for event in events])
except Exception as e:
return jsonify({'error': str(e)}), 500
# Signal handlers for attack thread
def on_attack_progress(progress, speed, eta, attempts):
"""Handle attack progress updates"""
global attack_status
attack_status.update({
'progress': progress,
'speed': speed,
'eta': eta,
'attempts': attempts
})
def on_attack_status(status):
"""Handle attack status updates"""
global attack_status
attack_status['status'] = status
def on_attack_result(result):
"""Handle attack results"""
# Could store results in a global variable or database
pass
def on_attack_log(log_entry):
"""Handle attack log entries"""
# Could store logs in a global variable or database
pass
def on_attack_error(error):
"""Handle attack errors"""
global attack_status
attack_status['status'] = f"Error: {error}"
def on_attack_finished():
"""Handle attack completion"""
global attack_status
attack_status.update({
'running': False,
'status': 'Completed'
})
# Template filters
@app.template_filter('format_datetime')
def format_datetime(value):
"""Format datetime for display"""
if isinstance(value, str):
try:
dt = datetime.fromisoformat(value.replace('Z', '+00:00'))
return dt.strftime('%Y-%m-%d %H:%M:%S')
except:
return value
return value
def create_templates():
"""Create basic HTML templates if they don't exist"""
templates_dir = Path('templates')
templates_dir.mkdir(exist_ok=True)
# This function would create templates, but they're already created
# Keeping for future use
pass
if __name__ == '__main__':
# Create templates directory if it doesn't exist
os.makedirs('templates', exist_ok=True)
# Create basic HTML templates
create_templates()
# Start API server
try:
if api_integration.start():
logger.info(f"API server started on http://localhost:8080")
else:
logger.warning("Failed to start API server")
except Exception as e:
logger.error(f"Error starting API server: {e}")
# Start Flask app
app.run(host='0.0.0.0', port=5000, debug=False)