-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
5022 lines (4362 loc) · 195 KB
/
app.py
File metadata and controls
5022 lines (4362 loc) · 195 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
bWall - Firewall Management Dashboard Backend
Flask API for managing iptables rules with MariaDB synchronization
Developed by bunit.net
"""
import os
import sys
import subprocess
import json
import csv
import ipaddress
import requests
import threading
import time
import secrets
import bcrypt
import socket
import re
from datetime import datetime, timedelta
from flask import Flask, request, jsonify, send_file, session, redirect, url_for
from flask_cors import CORS
import pymysql
from werkzeug.utils import secure_filename
# Load environment variables from .env file
try:
from utils import load_env_file
load_env_file()
except ImportError:
# Fallback if utils.py not available
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
# Fallback: Load .env manually if python-dotenv is not installed
if os.path.exists('.env'):
print("[INFO] Loading .env file manually (python-dotenv not installed)...")
with open('.env') as f:
for line in f:
line = line.strip()
if '=' in line and not line.startswith('#'):
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
print("[INFO] .env file loaded successfully")
else:
print("[INFO] No .env file found, using environment variables or defaults")
# Check Python version - OIDC has known issues with Python 3.13
# The 'future' package used by flask_pyoidc has regex compatibility issues with Python 3.13
python_version = sys.version_info
OIDC_AVAILABLE = False
OIDCAuthentication = None
ProviderConfiguration = None
ClientMetadata = None
if python_version.major == 3 and python_version.minor >= 13:
print("=" * 60)
print("Warning: Python 3.13 detected")
print("OIDC authentication disabled due to compatibility issues.")
print(" The 'future' package used by flask_pyoidc is incompatible")
print(" with Python 3.13's stricter regex parser.")
print("")
print("Options:")
print(" 1. Run without OIDC (current - application will work)")
print(" 2. Use Python 3.11 or 3.12 for OIDC support")
print("=" * 60)
print()
else:
# Try to import OIDC for Python < 3.13
try:
from flask_pyoidc import OIDCAuthentication
from flask_pyoidc.provider_configuration import ProviderConfiguration, ClientMetadata
OIDC_AVAILABLE = True
except (ImportError, Exception) as e:
print(f"Warning: flask_pyoidc not available: {e}")
print("OIDC authentication will be disabled.")
OIDC_AVAILABLE = False
from log_monitor import LogMonitor
from abuseipdb import AbuseIPDB
# Load environment variables from .env file if it exists
if os.path.exists('.env'):
with open('.env', 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
# Get the directory where this script is located
APP_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'change-this-secret-key-in-production')
# OIDC Configuration
OIDC_ISSUER = os.getenv('OIDC_ISSUER', 'https://your-pocketid-instance.example.com')
OIDC_CLIENT_ID = os.getenv('OIDC_CLIENT_ID', '')
OIDC_CLIENT_SECRET = os.getenv('OIDC_CLIENT_SECRET', '')
# Get host from environment or default to localhost
APP_HOST = os.getenv('APP_HOST', '0.0.0.0')
APP_PORT = int(os.getenv('APP_PORT', '5000'))
BASE_URL = os.getenv('BASE_URL', f'http://{APP_HOST if APP_HOST != "0.0.0.0" else "localhost"}:{APP_PORT}')
OIDC_REDIRECT_URI = os.getenv('OIDC_REDIRECT_URI', f'{BASE_URL}/oidc_callback')
OIDC_POST_LOGOUT_REDIRECT_URI = os.getenv('OIDC_POST_LOGOUT_REDIRECT_URI', f'{BASE_URL}/')
# Configure CORS with credentials support for OIDC
# Allow all origins for installer, restrict for production
cors_origins = os.getenv('CORS_ORIGINS', f'{BASE_URL},http://localhost:{APP_PORT},http://127.0.0.1:{APP_PORT}')
CORS(app, supports_credentials=True, origins=cors_origins.split(','))
# Authentication Type Configuration
AUTH_TYPE = os.getenv('AUTH_TYPE', '').strip().upper()
if not AUTH_TYPE:
# Default: try ENV first (has defaults), then OIDC if available, otherwise local auth
auth_list = []
# ENV auth has defaults, so include it
auth_list.append('ENV')
if OIDC_AVAILABLE and OIDC_CLIENT_ID and OIDC_CLIENT_SECRET and OIDC_ISSUER:
auth_list.append('OIDC')
auth_list.append('LOCAL')
AUTH_TYPE = ','.join(auth_list)
# Parse comma-separated auth types
AUTH_TYPES = [t.strip().upper() for t in AUTH_TYPE.split(',') if t.strip()]
ENV_AUTH_ENABLED = 'ENV' in AUTH_TYPES
OIDC_AUTH_ENABLED = 'OIDC' in AUTH_TYPES
LOCAL_AUTH_ENABLED = 'LOCAL' in AUTH_TYPES
# ENV Authentication Configuration
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'bwall').strip()
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'ReadGoodBooks&BadNetworks').strip()
ENV_AUTH_CONFIGURED = bool(ADMIN_USERNAME and ADMIN_PASSWORD)
if ENV_AUTH_ENABLED and not ENV_AUTH_CONFIGURED:
print("Warning: AUTH_TYPE includes ENV but ADMIN_USERNAME or ADMIN_PASSWORD not set")
print(" ENV authentication will be disabled")
# Initialize OIDC Authentication if configured
auth = None
if OIDC_AUTH_ENABLED and OIDC_AVAILABLE and OIDC_CLIENT_ID and OIDC_CLIENT_SECRET and OIDC_ISSUER:
try:
client_metadata = ClientMetadata(
client_id=OIDC_CLIENT_ID,
client_secret=OIDC_CLIENT_SECRET,
post_logout_redirect_uris=[OIDC_POST_LOGOUT_REDIRECT_URI]
)
provider_config = ProviderConfiguration(
issuer=OIDC_ISSUER,
client_metadata=client_metadata
)
auth = OIDCAuthentication({'default': provider_config}, app)
print("OIDC authentication configured successfully")
except Exception as e:
print(f"Warning: OIDC configuration failed: {e}")
print("Application will run without OIDC authentication")
OIDC_AUTH_ENABLED = False
elif OIDC_AUTH_ENABLED and not OIDC_AVAILABLE:
if python_version.major == 3 and python_version.minor >= 13:
print("Note: OIDC disabled due to Python 3.13 compatibility issues with 'future' package.")
print(" To use OIDC, consider using Python 3.11 or 3.12.")
else:
print("Warning: OIDC libraries not available. Install with: pip install 'future>=0.18.3' 'Flask-pyoidc==3.0.0'")
print("OIDC authentication will be disabled")
OIDC_AUTH_ENABLED = False
elif OIDC_AUTH_ENABLED:
print("Warning: OIDC credentials not configured. Set OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, and OIDC_ISSUER environment variables.")
OIDC_AUTH_ENABLED = False
# Print authentication configuration
print(f"[AUTH] Authentication types enabled: {', '.join(AUTH_TYPES)}")
if ENV_AUTH_ENABLED:
print(f"[AUTH] ENV auth: {'configured' if ENV_AUTH_CONFIGURED else 'not configured (missing ADMIN_USERNAME/ADMIN_PASSWORD)'}")
if OIDC_AUTH_ENABLED:
print(f"[AUTH] OIDC auth: {'configured' if auth else 'not configured'}")
if LOCAL_AUTH_ENABLED:
print(f"[AUTH] LOCAL auth: enabled (database-backed)")
# Configuration
UPLOAD_FOLDER = '/tmp/iptables_uploads'
ALLOWED_EXTENSIONS = {'json', 'csv', 'txt'}
# Database configuration
DB_CONFIG = {
'host': os.getenv('DB_HOST', 'localhost'),
'user': os.getenv('DB_USER', 'iptables_user'),
'password': os.getenv('DB_PASSWORD', 'iptables_pass'),
'database': os.getenv('DB_NAME', 'iptables_db'),
'charset': 'utf8mb4'
}
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Get system information for sanitization
def get_system_info():
"""Get system IP addresses and hostname for sanitization"""
system_info = {
'hostname': socket.gethostname(),
'fqdn': socket.getfqdn(),
'ip_addresses': []
}
try:
# Get all IP addresses
hostname = socket.gethostname()
primary_ip = socket.gethostbyname(hostname)
system_info['ip_addresses'].append(primary_ip)
# Try to get additional IPs
try:
_, _, ip_list = socket.gethostbyname_ex(hostname)
system_info['ip_addresses'].extend(ip_list)
except:
pass
# Get localhost IPs
system_info['ip_addresses'].extend(['127.0.0.1', '::1', 'localhost'])
# Get IP from environment if available
app_host = os.getenv('APP_HOST', '')
if app_host and app_host != '0.0.0.0':
system_info['ip_addresses'].append(app_host)
# Remove duplicates while preserving order
seen = set()
unique_ips = []
for ip in system_info['ip_addresses']:
if ip not in seen:
seen.add(ip)
unique_ips.append(ip)
system_info['ip_addresses'] = unique_ips
except Exception as e:
print(f"[SANITIZE] Warning: Could not get all system info: {e}")
return system_info
SYSTEM_INFO = get_system_info()
def sanitize_abuseipdb_comment(comment, reported_ip):
"""
Sanitize AbuseIPDB comment to remove system-specific information
Args:
comment: Original comment text
reported_ip: The IP being reported (to preserve in comment)
Returns:
Sanitized comment with "bWall: " prefix
"""
if not comment:
comment = ""
# Remove system hostname and FQDN
if SYSTEM_INFO['hostname']:
comment = re.sub(re.escape(SYSTEM_INFO['hostname']), '[HOSTNAME]', comment, flags=re.IGNORECASE)
if SYSTEM_INFO['fqdn']:
comment = re.sub(re.escape(SYSTEM_INFO['fqdn']), '[FQDN]', comment, flags=re.IGNORECASE)
# Remove system IP addresses (but keep the reported IP)
for ip in SYSTEM_INFO['ip_addresses']:
if ip and ip != reported_ip:
# Match IP as whole word or in common patterns
ip_pattern = r'\b' + re.escape(ip) + r'\b'
comment = re.sub(ip_pattern, '[SYSTEM_IP]', comment, flags=re.IGNORECASE)
# Remove common local network patterns (but preserve reported IP)
# First, identify all private IPs in the comment
private_ip_patterns = [
(r'\b10\.\d+\.\d+\.\d+\b', '10.x.x.x'),
(r'\b172\.(1[6-9]|2[0-9]|3[0-1])\.\d+\.\d+\b', '172.16-31.x.x'),
(r'\b192\.168\.\d+\.\d+\b', '192.168.x.x'),
(r'\bfc00::[0-9a-fA-F:]+', 'IPv6 ULA'),
(r'\bfe80::[0-9a-fA-F:]+', 'IPv6 link-local'),
]
for pattern, _ in private_ip_patterns:
# Find all matches
matches = re.finditer(pattern, comment)
# Process in reverse to maintain positions
for match in list(matches)[::-1]:
matched_ip = match.group(0)
# Only replace if it's not the reported IP
if matched_ip != reported_ip:
start, end = match.span()
comment = comment[:start] + '[PRIVATE_IP]' + comment[end:]
# Remove file paths that might reveal system info
comment = re.sub(r'/[^\s]+', '[PATH]', comment)
comment = re.sub(r'[A-Z]:\\[^\s]+', '[PATH]', comment)
# Remove email addresses (might reveal domain info)
comment = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '[EMAIL]', comment)
# Clean up multiple spaces
comment = re.sub(r'\s+', ' ', comment).strip()
# Prepend "bWall: " if not already present
if not comment.startswith('bWall:'):
comment = f"bWall: {comment}"
return comment
# Initialize AbuseIPDB client
abuseipdb = AbuseIPDB()
# AbuseIPDB reporting mode: 'log_only', 'log_and_hold', 'automatic'
ABUSEIPDB_MODE = os.getenv('ABUSEIPDB_MODE', 'automatic').lower()
if ABUSEIPDB_MODE not in ['log_only', 'log_and_hold', 'automatic']:
ABUSEIPDB_MODE = 'automatic'
print(f"[AbuseIPDB] Invalid mode, defaulting to 'automatic'")
# Initialize log monitor
log_monitor = None
def init_log_monitor():
"""Initialize log monitoring system"""
global log_monitor
if not log_monitor:
def block_callback(ip, service=None, attack_type=None):
"""Callback when IP is auto-blocked"""
# Check if IP is whitelisted before processing
if is_ip_whitelisted(ip):
print(f"[WHITELIST] Ignoring whitelisted IP {ip} - skipping block and AbuseIPDB reporting")
return
apply_blacklist_rule(ip)
# Handle AbuseIPDB reporting based on mode
if abuseipdb.enabled:
# Double-check whitelist before reporting
if is_ip_whitelisted(ip):
print(f"[WHITELIST] Ignoring whitelisted IP {ip} - skipping AbuseIPDB reporting")
return
try:
categories = abuseipdb.map_attack_type_to_categories(
attack_type or 'other',
service or ''
)
comment = f"Auto-blocked: {service or 'unknown'} {attack_type or 'attack'}"
# Sanitize comment before reporting
sanitized_comment = sanitize_abuseipdb_comment(comment, ip)
if ABUSEIPDB_MODE == 'automatic':
# Report immediately
result = abuseipdb.report_ip(ip, categories, sanitized_comment)
if 'error' not in result:
print(f"[AbuseIPDB] Reported IP {ip} successfully (automatic)")
log_activity('report_abuseipdb', 'abuseipdb', ip, 'success')
else:
print(f"[AbuseIPDB] Failed to report IP {ip}: {result.get('error', 'Unknown error')}")
log_activity('report_abuseipdb', 'abuseipdb', ip, 'error')
elif ABUSEIPDB_MODE == 'log_and_hold':
# Queue for review (store original comment, sanitize on submit)
queue_abuseipdb_report(ip, categories, comment, service, attack_type, 'auto')
print(f"[AbuseIPDB] Queued IP {ip} for review (log_and_hold mode)")
log_activity('queue_abuseipdb', 'abuseipdb', ip, 'pending')
elif ABUSEIPDB_MODE == 'log_only':
# Just log, don't report or queue
print(f"[AbuseIPDB] Logged IP {ip} (log_only mode - not reporting)")
log_activity('log_abuseipdb', 'abuseipdb', ip, 'logged')
except Exception as e:
print(f"[AbuseIPDB] Error processing IP {ip}: {e}")
log_activity('error_abuseipdb', 'abuseipdb', ip, 'error')
log_monitor = LogMonitor(DB_CONFIG, block_callback=block_callback)
return log_monitor
def hash_password(password):
"""Hash a password using bcrypt"""
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
def verify_password(password, password_hash):
"""Verify a password against a hash"""
try:
return bcrypt.checkpw(password.encode('utf-8'), password_hash.encode('utf-8'))
except Exception:
return False
def validate_password(password):
"""Validate password meets security requirements"""
if len(password) < 8:
return False, "Password must be at least 8 characters long"
if not any(c.isupper() for c in password):
return False, "Password must contain at least one uppercase letter"
if not any(c.islower() for c in password):
return False, "Password must contain at least one lowercase letter"
if not any(c.isdigit() for c in password):
return False, "Password must contain at least one number"
if not any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password):
return False, "Password must contain at least one special character"
return True, "Password is valid"
def check_env_auth():
"""Check if user is authenticated via ENV (simple username/password from .env)"""
if not ENV_AUTH_ENABLED or not ENV_AUTH_CONFIGURED:
return False
if 'env_auth_username' not in session:
return False
# ENV auth is simple - if session has the username and it matches, they're authenticated
session_username = session.get('env_auth_username')
return session_username == ADMIN_USERNAME
def check_local_auth():
"""Check if user is authenticated via local auth (database-backed)"""
if not LOCAL_AUTH_ENABLED:
return False
if 'local_auth_token' not in session:
return False
token = session.get('local_auth_token')
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute("""
SELECT us.*, u.username, u.is_admin, u.is_active
FROM user_sessions us
JOIN users u ON us.user_id = u.id
WHERE us.session_token = %s
AND us.expires_at > NOW()
AND u.is_active = TRUE
""", (token,))
session_data = cursor.fetchone()
if session_data:
# Update last login
cursor.execute("""
UPDATE users SET last_login = NOW() WHERE id = %s
""", (session_data['user_id'],))
conn.commit()
return True
else:
# Invalid or expired session
session.pop('local_auth_token', None)
return False
except Exception as e:
print(f"[AUTH] Error checking local auth: {e}")
return False
finally:
conn.close()
def require_auth(f):
"""Decorator to require authentication for routes - respects AUTH_TYPE order"""
def check_auth_in_order():
"""Check authentication in the order specified by AUTH_TYPE"""
# Check in order of AUTH_TYPES
for auth_type in AUTH_TYPES:
if auth_type == 'ENV':
if check_env_auth():
return True, 'env'
elif auth_type == 'OIDC':
if auth and OIDC_AVAILABLE:
try:
if 'user' in session:
return True, 'oidc'
except:
pass
elif auth_type == 'LOCAL':
if check_local_auth():
return True, 'local'
return False, None
def wrapper(*args, **kwargs):
authenticated, auth_method = check_auth_in_order()
if authenticated:
return f(*args, **kwargs)
# Not authenticated - return 401
return jsonify({
'error': 'Authentication required',
'authenticated': False,
'auth_types_available': AUTH_TYPES,
'env_auth_available': ENV_AUTH_ENABLED and ENV_AUTH_CONFIGURED,
'oidc_auth_available': OIDC_AUTH_ENABLED and auth is not None,
'local_auth_available': LOCAL_AUTH_ENABLED
}), 401
# If OIDC is in the auth types and configured, wrap with OIDC auth
if OIDC_AUTH_ENABLED and auth and OIDC_AVAILABLE:
def oidc_wrapper(*args, **kwargs):
try:
# Try OIDC first if it's the first in the list
if AUTH_TYPES[0] == 'OIDC':
return auth.oidc_auth('default')(f)(*args, **kwargs)
else:
# OIDC is not first, check in order
authenticated, auth_method = check_auth_in_order()
if authenticated:
return f(*args, **kwargs)
# If not authenticated and OIDC is available, try OIDC redirect
if OIDC_AUTH_ENABLED:
return auth.oidc_auth('default')(f)(*args, **kwargs)
return jsonify({'error': 'Authentication required'}), 401
except Exception as e:
# If OIDC fails, try other auth methods
authenticated, auth_method = check_auth_in_order()
if authenticated:
return f(*args, **kwargs)
return jsonify({'error': 'Authentication required'}), 401
oidc_wrapper.__name__ = f.__name__
return oidc_wrapper
# No OIDC wrapper needed, use standard wrapper
wrapper.__name__ = f.__name__
return wrapper
def get_user_info():
"""Get current user information from session - checks all auth types"""
# Try ENV auth first
if ENV_AUTH_ENABLED and ENV_AUTH_CONFIGURED and check_env_auth():
return {
'username': ADMIN_USERNAME,
'auth_type': 'env',
'is_admin': True
}
# Try OIDC
if OIDC_AUTH_ENABLED and auth and 'user' in session:
user_data = session.get('user', {})
user_data['auth_type'] = 'oidc'
return user_data
# Try local auth
if LOCAL_AUTH_ENABLED and 'local_auth_token' in session:
token = session.get('local_auth_token')
conn = get_db_connection()
if not conn:
return None
try:
with conn.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute("""
SELECT u.id, u.username, u.email, u.full_name, u.is_admin
FROM user_sessions us
JOIN users u ON us.user_id = u.id
WHERE us.session_token = %s
AND us.expires_at > NOW()
AND u.is_active = TRUE
""", (token,))
user_data = cursor.fetchone()
if user_data:
return {
'id': user_data['id'],
'username': user_data['username'],
'email': user_data['email'],
'full_name': user_data['full_name'],
'is_admin': user_data['is_admin'],
'auth_type': 'local'
}
except Exception as e:
print(f"[AUTH] Error getting user info: {e}")
finally:
conn.close()
return None
def get_db_connection():
"""Create and return a database connection"""
try:
# Check if database is configured
if not all([DB_CONFIG.get('host'), DB_CONFIG.get('user'),
DB_CONFIG.get('password'), DB_CONFIG.get('database')]):
print("Database configuration incomplete. Missing required fields.")
return None
# Try to connect
conn = pymysql.connect(**DB_CONFIG)
return conn
except pymysql.Error as e:
error_code, error_msg = e.args
print(f"Database connection error ({error_code}): {error_msg}")
print(f"Attempted connection with:")
print(f" Host: {DB_CONFIG.get('host')}")
print(f" User: {DB_CONFIG.get('user')}")
print(f" Database: {DB_CONFIG.get('database')}")
print(f" Password: {'*' * len(DB_CONFIG.get('password', '')) if DB_CONFIG.get('password') else 'NOT SET'}")
return None
except Exception as e:
print(f"Database connection error: {e}")
import traceback
traceback.print_exc()
return None
def init_database():
"""Initialize database tables if they don't exist"""
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor() as cursor:
# Whitelist table
cursor.execute("""
CREATE TABLE IF NOT EXISTS whitelist (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL UNIQUE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_ip (ip_address)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Blacklist table
cursor.execute("""
CREATE TABLE IF NOT EXISTS blacklist (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL UNIQUE,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_ip (ip_address)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Rules table
cursor.execute("""
CREATE TABLE IF NOT EXISTS rules (
id INT AUTO_INCREMENT PRIMARY KEY,
chain VARCHAR(50),
target VARCHAR(50),
protocol VARCHAR(10),
source VARCHAR(45),
destination VARCHAR(45),
options TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Activity log table
cursor.execute("""
CREATE TABLE IF NOT EXISTS activity_log (
id INT AUTO_INCREMENT PRIMARY KEY,
action VARCHAR(50) NOT NULL,
type VARCHAR(20),
entry VARCHAR(255),
status VARCHAR(20),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_timestamp (timestamp)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Sync log table
cursor.execute("""
CREATE TABLE IF NOT EXISTS sync_log (
id INT AUTO_INCREMENT PRIMARY KEY,
direction VARCHAR(20),
whitelist_synced INT DEFAULT 0,
blacklist_synced INT DEFAULT 0,
rules_synced INT DEFAULT 0,
status VARCHAR(20),
message TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# AbuseIPDB report queue table
cursor.execute("""
CREATE TABLE IF NOT EXISTS abuseipdb_queue (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL,
categories JSON NOT NULL,
comment TEXT,
service VARCHAR(50),
attack_type VARCHAR(50),
source VARCHAR(20) DEFAULT 'auto',
status VARCHAR(20) DEFAULT 'pending',
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
submitted_at TIMESTAMP NULL,
INDEX idx_status (status),
INDEX idx_ip (ip_address),
INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# URL-based IP lists table
cursor.execute("""
CREATE TABLE IF NOT EXISTS url_lists (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
url TEXT NOT NULL,
list_type VARCHAR(20) NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
auto_sync BOOLEAN DEFAULT FALSE,
sync_interval INT DEFAULT 3600,
last_sync TIMESTAMP NULL,
last_success TIMESTAMP NULL,
last_error TEXT,
entry_count INT DEFAULT 0,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_type (list_type),
INDEX idx_enabled (enabled),
INDEX idx_last_sync (last_sync)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Users table for local authentication
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
email VARCHAR(255),
full_name VARCHAR(255),
is_active BOOLEAN DEFAULT TRUE,
is_admin BOOLEAN DEFAULT FALSE,
failed_login_attempts INT DEFAULT 0,
locked_until TIMESTAMP NULL,
last_login TIMESTAMP NULL,
password_changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_username (username),
INDEX idx_active (is_active),
INDEX idx_locked (locked_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# User sessions table for secure session management
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
session_token VARCHAR(255) NOT NULL UNIQUE,
ip_address VARCHAR(45),
user_agent TEXT,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user (user_id),
INDEX idx_token (session_token),
INDEX idx_expires (expires_at),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# System settings table for customization
cursor.execute("""
CREATE TABLE IF NOT EXISTS system_settings (
id INT AUTO_INCREMENT PRIMARY KEY,
setting_key VARCHAR(100) NOT NULL UNIQUE,
setting_value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_key (setting_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Monitored services configuration table
cursor.execute("""
CREATE TABLE IF NOT EXISTS monitored_services (
id INT AUTO_INCREMENT PRIMARY KEY,
service_name VARCHAR(50) NOT NULL UNIQUE,
enabled BOOLEAN DEFAULT TRUE,
threshold INT DEFAULT 5,
duration_minutes INT DEFAULT 60,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_enabled (enabled),
INDEX idx_service (service_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Permanent ban blacklist table
cursor.execute("""
CREATE TABLE IF NOT EXISTS permaban_blacklist (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL UNIQUE,
abuse_count INT DEFAULT 0,
abuse_score INT DEFAULT 0,
first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
reason TEXT,
INDEX idx_ip (ip_address),
INDEX idx_score (abuse_score),
INDEX idx_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Abuse history table for tracking all monitoring events
cursor.execute("""
CREATE TABLE IF NOT EXISTS abuse_history (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45) NOT NULL,
service VARCHAR(50),
attack_type VARCHAR(50),
severity VARCHAR(20) DEFAULT 'medium',
blocked BOOLEAN DEFAULT FALSE,
reported_to_abuseipdb BOOLEAN DEFAULT FALSE,
permabanned BOOLEAN DEFAULT FALSE,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_ip (ip_address),
INDEX idx_timestamp (timestamp),
INDEX idx_service (service),
INDEX idx_blocked (blocked)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# Initialize default settings if not exist
default_settings = [
('theme', 'btheme'),
('system_name', 'bWall'),
('login_banner', ''),
('footer_text', 'bWall by bunit.net'),
('proxy_enabled', 'false'),
('proxy_servers', ''),
('proxy_username', ''),
('proxy_password', ''),
('no_proxy', 'localhost,127.0.0.1,*.local')
]
for key, value in default_settings:
cursor.execute("""
INSERT IGNORE INTO system_settings (setting_key, setting_value)
VALUES (%s, %s)
""", (key, value))
# Initialize default crowdsource list (3FIFTYnet)
cursor.execute("SELECT COUNT(*) FROM url_lists WHERE url LIKE '%3FIFTYnet%'")
if cursor.fetchone()[0] == 0:
cursor.execute("""
INSERT INTO url_lists (name, url, list_type, description, enabled, auto_sync, sync_interval)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (
'3FIFTYnet Abusive Subnets',
'https://raw.githubusercontent.com/3FIFTYnet/dbl/refs/heads/main/abusive_subnet_24_blacklist.txt',
'blacklist',
'Community-maintained list of abusive /24 subnets from 3FIFTYnet. Based on known and verifiable abusive and excessive network traffic.',
True,
True,
86400 # Daily sync
))
print("[CROWDSOURCE] Added default 3FIFTYnet abusive subnet blacklist")
# Create default admin user if no users exist
cursor.execute("SELECT COUNT(*) FROM users")
if cursor.fetchone()[0] == 0:
try:
# Create default admin user with password 'admin' (must be changed on first login)
default_password = 'admin'
password_hash = bcrypt.hashpw(default_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
cursor.execute("""
INSERT INTO users (username, password_hash, email, full_name, is_admin, is_active)
VALUES (%s, %s, %s, %s, %s, %s)
""", ('admin', password_hash, 'admin@localhost', 'Administrator', True, True))
print("[AUTH] Created default admin user (username: admin, password: admin)")
print("[AUTH] WARNING: Change the default password immediately!")
except Exception as e:
print(f"[AUTH] Error creating default admin user: {e}")
conn.commit()
return True
except Exception as e:
print(f"Database initialization error: {e}")
return False
finally:
conn.close()
def validate_ip(ip_str):
"""Validate IP address or CIDR notation"""
try:
ipaddress.ip_network(ip_str, strict=False)
return True
except ValueError:
return False
def is_ip_whitelisted(ip_address):
"""
Check if an IP address is whitelisted (including CIDR matching)
Args:
ip_address: IP address to check (string)
Returns:
bool: True if IP is whitelisted, False otherwise
"""
if not ip_address:
return False
try:
# Parse the IP to check
check_ip = ipaddress.ip_address(ip_address.split('/')[0])
except ValueError:
return False
conn = get_db_connection()
if not conn:
return False
try:
with conn.cursor() as cursor:
# Get all whitelist entries
cursor.execute("SELECT ip_address FROM whitelist")
whitelist_entries = cursor.fetchall()
for entry in whitelist_entries:
whitelist_ip = entry[0]
try:
# Check if it's a CIDR range
if '/' in whitelist_ip:
network = ipaddress.ip_network(whitelist_ip, strict=False)
if check_ip in network:
return True
else:
# Direct IP match
if str(check_ip) == whitelist_ip:
return True
except (ValueError, ipaddress.AddressValueError):
# Invalid entry, skip
continue
return False
except Exception as e:
print(f"[WHITELIST] Error checking whitelist for {ip_address}: {e}")
return False
finally:
conn.close()
def log_activity(action, type, entry, status='success'):
"""Log activity to database"""
conn = get_db_connection()
if not conn:
return
try:
with conn.cursor() as cursor:
cursor.execute("""
INSERT INTO activity_log (action, type, entry, status)
VALUES (%s, %s, %s, %s)
""", (action, type, entry, status))
conn.commit()
except Exception as e:
print(f"Error logging activity: {e}")
finally:
conn.close()
def queue_abuseipdb_report(ip_address, categories, comment, service=None, attack_type=None, source='manual'):
"""Queue an AbuseIPDB report for review"""
# Check if IP is whitelisted - don't queue whitelisted IPs
if is_ip_whitelisted(ip_address):
print(f"[WHITELIST] Ignoring whitelisted IP {ip_address} - not queueing for AbuseIPDB")
return False
conn = get_db_connection()
if not conn:
return False
try:
import json
with conn.cursor() as cursor:
cursor.execute("""
INSERT INTO abuseipdb_queue (ip_address, categories, comment, service, attack_type, source, status)
VALUES (%s, %s, %s, %s, %s, %s, 'pending')
""", (ip_address, json.dumps(categories), comment, service, attack_type, source))
conn.commit()
return True
except Exception as e:
print(f"Error queueing AbuseIPDB report: {e}")
return False
finally:
conn.close()
def execute_iptables_command(command):
"""Execute iptables command safely"""
try:
# Validate command for security
if not command.startswith('iptables '):
return False, "Invalid command"
# Check if running as root or with sudo capability
import os
is_root = os.geteuid() == 0
# Split command into parts
cmd_parts = command.split()
# Try running the command
result = subprocess.run(
cmd_parts,
capture_output=True,
text=True,
timeout=10
)