-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcot_server_admin.py
More file actions
3210 lines (2714 loc) · 120 KB
/
cot_server_admin.py
File metadata and controls
3210 lines (2714 loc) · 120 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
"""
CoT Server Admin - Administration Tool for TAK Server
Provides a complete web-based interface for TAK Server configuration and management
Copyright 2024-2025 BlackDot Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
DISCLAIMER:
This software is not affiliated with, endorsed by, or connected to the TAK Product
Center, U.S. Department of Defense, or any government agency. "TAK", "ATAK", "WinTAK",
and "iTAK" are products of the U.S. Government. This is an independent, open-source
administration tool designed to work with TAK Server.
"""
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, session, send_file, Response, g, abort
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.utils import secure_filename
import os
import sys
import json
import subprocess
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
import psycopg2
from pathlib import Path
import secrets
import logging
import zipfile
import io
import base64
import hashlib
import shutil
import socket
import functools
import threading
import time
import uuid
import re
import hmac
# QR Code generation (optional - graceful fallback if not installed)
try:
import qrcode
from qrcode.image.pure import PyPNGImage
QR_AVAILABLE = True
except ImportError:
QR_AVAILABLE = False
logging.warning("qrcode library not installed - QR code generation disabled")
# ============================================================================
# SECURITY UTILITY FUNCTIONS
# ============================================================================
def safe_error_response(error, default_message="An error occurred"):
"""
Create a safe error response without exposing internal details.
Logs the full error but returns a sanitized message to the client.
"""
logger.error(f"Error: {error}")
return default_message
def validate_password(password):
"""
Validate password meets security requirements.
Returns (is_valid, error_message)
"""
if len(password) < 8:
return False, "Password must be at least 8 characters long"
if not re.search(r'[A-Z]', password):
return False, "Password must contain at least one uppercase letter"
if not re.search(r'[a-z]', password):
return False, "Password must contain at least one lowercase letter"
if not re.search(r'\d', password):
return False, "Password must contain at least one number"
return True, None
def validate_username(username):
"""
Validate username format.
Returns (is_valid, error_message)
"""
if not username:
return False, "Username is required"
if len(username) < 3:
return False, "Username must be at least 3 characters"
if len(username) > 32:
return False, "Username must be 32 characters or less"
if not re.match(r'^[a-zA-Z][a-zA-Z0-9_-]*$', username):
return False, "Username must start with a letter and contain only letters, numbers, underscores, and hyphens"
return True, None
def sanitize_filename_strict(filename):
"""Strictly sanitize filename - only allow alphanumeric, dash, underscore, dot"""
if not filename:
return None
# Use secure_filename first
filename = secure_filename(filename)
# Additional sanitization
filename = re.sub(r'[^a-zA-Z0-9._-]', '', filename)
# Prevent directory traversal
filename = filename.replace('..', '')
# Ensure not empty after sanitization
if not filename or filename.startswith('.'):
return None
return filename
def generate_csrf_token():
"""Generate a CSRF token for the session"""
if 'csrf_token' not in session:
session['csrf_token'] = secrets.token_hex(32)
return session['csrf_token']
def validate_csrf_token(token):
"""Validate CSRF token"""
session_token = session.get('csrf_token')
if not session_token or not token:
return False
return hmac.compare_digest(session_token, token)
app = Flask(__name__)
# Configure app for running behind reverse proxy (nginx)
# This ensures correct handling of X-Forwarded-* headers
app.wsgi_app = ProxyFix(
app.wsgi_app,
x_for=1, # Number of proxies setting X-Forwarded-For
x_proto=1, # Number of proxies setting X-Forwarded-Proto
x_host=1, # Number of proxies setting X-Forwarded-Host
x_port=1 # Number of proxies setting X-Forwarded-Port
)
# Secret key: use environment variable or generate secure random key
app.secret_key = os.environ.get('TAK_SECRET_KEY', secrets.token_hex(32))
# Session security settings
SESSION_TIMEOUT_MINUTES = int(os.environ.get('TAK_SESSION_TIMEOUT', '30'))
MAX_LOGIN_ATTEMPTS = int(os.environ.get('TAK_MAX_LOGIN_ATTEMPTS', '5'))
LOGIN_LOCKOUT_MINUTES = int(os.environ.get('TAK_LOGIN_LOCKOUT_MINUTES', '15'))
MAX_CONCURRENT_SESSIONS = int(os.environ.get('TAK_MAX_CONCURRENT_SESSIONS', '3'))
app.config.update(
SESSION_COOKIE_SECURE=os.environ.get('TAK_HTTPS_ENABLED', 'true').lower() == 'true',
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
MAX_CONTENT_LENGTH=100 * 1024 * 1024, # 100MB max upload
PERMANENT_SESSION_LIFETIME=timedelta(minutes=SESSION_TIMEOUT_MINUTES),
)
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('cot-server-admin')
# ============================================================================
# SECURITY MIDDLEWARE
# ============================================================================
@app.after_request
def add_security_headers(response):
"""Add security headers to all responses"""
# Prevent MIME type sniffing
response.headers['X-Content-Type-Options'] = 'nosniff'
# Prevent clickjacking
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
# XSS Protection (legacy, but still useful)
response.headers['X-XSS-Protection'] = '1; mode=block'
# Referrer policy
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# Content Security Policy
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"font-src 'self'; "
"connect-src 'self'"
)
# Cache control for sensitive pages
if request.endpoint and request.endpoint not in ['static']:
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
return response
def csrf_protect(f):
"""Decorator to enforce CSRF protection on routes"""
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if request.method in ['POST', 'PUT', 'DELETE', 'PATCH']:
token = request.headers.get('X-CSRF-Token') or request.form.get('csrf_token')
if not validate_csrf_token(token):
audit.log(
action='csrf_validation_failed',
category=AuditLogger.CATEGORY_SECURITY,
level=AuditLogger.LEVEL_WARNING,
success=False,
details=f'Endpoint: {request.endpoint}'
)
return jsonify({'success': False, 'error': 'Invalid or missing CSRF token'}), 403
return f(*args, **kwargs)
return decorated_function
@app.context_processor
def inject_csrf_token():
"""Make CSRF token available in all templates"""
return dict(csrf_token=generate_csrf_token)
# ============================================================================
# RATE LIMITING
# ============================================================================
class RateLimiter:
"""Simple in-memory rate limiter"""
def __init__(self, max_requests=60, window_seconds=60):
self.max_requests = max_requests
self.window_seconds = window_seconds
self._requests = {}
self._lock = threading.Lock()
def is_allowed(self, key):
"""Check if request is allowed"""
now = time.time()
with self._lock:
# Clean old entries
cutoff = now - self.window_seconds
self._requests = {k: [t for t in v if t > cutoff]
for k, v in self._requests.items()}
# Check and record
if key not in self._requests:
self._requests[key] = []
if len(self._requests[key]) >= self.max_requests:
return False
self._requests[key].append(now)
return True
# Global rate limiter - 60 requests per minute per IP
api_rate_limiter = RateLimiter(max_requests=60, window_seconds=60)
@app.before_request
def check_rate_limit():
"""Check rate limit on API endpoints"""
if request.endpoint and request.endpoint.startswith('api_') or request.path.startswith('/api/'):
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
if ',' in client_ip:
client_ip = client_ip.split(',')[0].strip()
if not api_rate_limiter.is_allowed(client_ip):
logger.warning(f"Rate limit exceeded for IP: {client_ip}")
return jsonify({'success': False, 'error': 'Rate limit exceeded. Please slow down.'}), 429
# Configuration
TAK_DIR = os.environ.get('TAK_DIR', '/opt/tak')
CONFIG_FILE = os.path.join(TAK_DIR, "CoreConfig.xml")
CERTS_DIR = os.path.join(TAK_DIR, "certs")
USERS_FILE = os.path.join(TAK_DIR, "users.json")
CREDENTIALS_FILE = os.path.join(TAK_DIR, ".credentials")
DATA_PACKAGES_DIR = os.path.join(TAK_DIR, "data-packages")
CONNECTION_PROFILES_DIR = os.path.join(TAK_DIR, "connection-profiles")
BACKUPS_DIR = os.path.join(TAK_DIR, "backups")
CRL_FILE = os.path.join(CERTS_DIR, "crl.pem")
CRL_INDEX_FILE = os.path.join(CERTS_DIR, "index.txt")
CRL_SERIAL_FILE = os.path.join(CERTS_DIR, "crlnumber")
AUDIT_LOG_FILE = os.path.join(TAK_DIR, "audit.log")
SESSIONS_FILE = os.path.join(TAK_DIR, ".sessions")
SECURITY_FILE = os.path.join(TAK_DIR, ".security")
# Allowed file extensions for data packages
ALLOWED_EXTENSIONS = {'zip', 'dpk'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# ============================================================================
# AUDIT LOGGING SYSTEM
# ============================================================================
class AuditLogger:
"""Thread-safe audit logging system"""
# Audit event categories
CATEGORY_AUTH = 'authentication'
CATEGORY_USER = 'user_management'
CATEGORY_CERT = 'certificate'
CATEGORY_CONFIG = 'configuration'
CATEGORY_BACKUP = 'backup'
CATEGORY_SYSTEM = 'system'
CATEGORY_SECURITY = 'security'
# Severity levels
LEVEL_INFO = 'info'
LEVEL_WARNING = 'warning'
LEVEL_CRITICAL = 'critical'
def __init__(self, log_file):
self.log_file = log_file
self._lock = threading.Lock()
self._ensure_log_file()
def _ensure_log_file(self):
"""Ensure audit log file exists with proper permissions"""
if not os.path.exists(self.log_file):
os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
with open(self.log_file, 'w') as f:
f.write('')
os.chmod(self.log_file, 0o600)
def log(self, action, category, level=LEVEL_INFO, user=None, target=None,
details=None, success=True, ip_address=None):
"""Log an audit event"""
try:
event = {
'timestamp': datetime.now().isoformat(),
'action': action,
'category': category,
'level': level,
'user': user or (current_user.id if current_user and current_user.is_authenticated else 'anonymous'),
'ip_address': ip_address or self._get_client_ip(),
'target': target,
'success': success,
'details': details,
'session_id': session.get('session_id', 'unknown')
}
with self._lock:
with open(self.log_file, 'a') as f:
f.write(json.dumps(event) + '\n')
# Also log to application logger for critical events
if level == self.LEVEL_CRITICAL:
logger.warning(f"AUDIT CRITICAL: {action} by {event['user']} from {event['ip_address']}")
except Exception as e:
logger.error(f"Failed to write audit log: {e}")
def _get_client_ip(self):
"""Get client IP address, accounting for proxy"""
if request:
# Check for forwarded IP (when behind proxy)
forwarded = request.headers.get('X-Forwarded-For', '')
if forwarded:
return forwarded.split(',')[0].strip()
return request.remote_addr
return 'unknown'
def get_logs(self, limit=100, offset=0, category=None, user=None,
start_date=None, end_date=None, level=None):
"""Retrieve audit logs with filtering"""
logs = []
try:
with self._lock:
with open(self.log_file, 'r') as f:
for line in f:
if line.strip():
try:
event = json.loads(line)
logs.append(event)
except json.JSONDecodeError:
continue
# Apply filters
if category:
logs = [l for l in logs if l.get('category') == category]
if user:
logs = [l for l in logs if l.get('user') == user]
if level:
logs = [l for l in logs if l.get('level') == level]
if start_date:
logs = [l for l in logs if l.get('timestamp', '') >= start_date]
if end_date:
logs = [l for l in logs if l.get('timestamp', '') <= end_date]
# Sort by timestamp descending (newest first)
logs.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
# Apply pagination
total = len(logs)
logs = logs[offset:offset + limit]
return {'logs': logs, 'total': total}
except Exception as e:
logger.error(f"Failed to read audit logs: {e}")
return {'logs': [], 'total': 0}
def get_stats(self, days=7):
"""Get audit log statistics"""
try:
cutoff = (datetime.now() - timedelta(days=days)).isoformat()
logs = self.get_logs(limit=10000)['logs']
recent = [l for l in logs if l.get('timestamp', '') >= cutoff]
stats = {
'total_events': len(recent),
'by_category': {},
'by_level': {},
'by_user': {},
'failed_logins': 0,
'successful_logins': 0
}
for log in recent:
cat = log.get('category', 'unknown')
level = log.get('level', 'info')
user = log.get('user', 'unknown')
stats['by_category'][cat] = stats['by_category'].get(cat, 0) + 1
stats['by_level'][level] = stats['by_level'].get(level, 0) + 1
stats['by_user'][user] = stats['by_user'].get(user, 0) + 1
if log.get('action') == 'login_attempt':
if log.get('success'):
stats['successful_logins'] += 1
else:
stats['failed_logins'] += 1
return stats
except Exception as e:
logger.error(f"Failed to get audit stats: {e}")
return {}
# Initialize audit logger
audit = AuditLogger(AUDIT_LOG_FILE)
def audit_log(action, category=AuditLogger.CATEGORY_SYSTEM, level=AuditLogger.LEVEL_INFO):
"""Decorator to automatically audit function calls"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
target = None
success = True
details = None
try:
result = f(*args, **kwargs)
# Try to extract target from kwargs or result
if 'filename' in kwargs:
target = kwargs['filename']
elif 'client_name' in kwargs:
target = kwargs['client_name']
# Check if result indicates failure
if isinstance(result, tuple) and len(result) > 1:
response, status_code = result
if status_code >= 400:
success = False
return result
except Exception as e:
success = False
details = str(e)
raise
finally:
audit.log(
action=action,
category=category,
level=level,
target=target,
success=success,
details=details
)
return wrapper
return decorator
# ============================================================================
# SESSION SECURITY SYSTEM
# ============================================================================
class SessionManager:
"""Manages user sessions with security features"""
def __init__(self, sessions_file, security_file):
self.sessions_file = sessions_file
self.security_file = security_file
self._lock = threading.Lock()
self._ensure_files()
def _ensure_files(self):
"""Ensure session files exist"""
for f in [self.sessions_file, self.security_file]:
if not os.path.exists(f):
os.makedirs(os.path.dirname(f), exist_ok=True)
with open(f, 'w') as file:
json.dump({}, file)
os.chmod(f, 0o600)
def _load_sessions(self):
"""Load active sessions"""
try:
with open(self.sessions_file, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError, PermissionError):
return {}
def _save_sessions(self, sessions):
"""Save active sessions"""
with open(self.sessions_file, 'w') as f:
json.dump(sessions, f, indent=2)
def _load_security(self):
"""Load security data (login attempts, lockouts)"""
try:
with open(self.security_file, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError, PermissionError):
return {'login_attempts': {}, 'lockouts': {}}
def _save_security(self, data):
"""Save security data"""
with open(self.security_file, 'w') as f:
json.dump(data, f, indent=2)
def create_session(self, username, ip_address, user_agent):
"""Create a new session for a user"""
session_id = str(uuid.uuid4())
with self._lock:
sessions = self._load_sessions()
# Get user's current sessions
user_sessions = [s for s in sessions.values() if s.get('username') == username]
# Enforce max concurrent sessions
if len(user_sessions) >= MAX_CONCURRENT_SESSIONS:
# Remove oldest session
oldest = min(user_sessions, key=lambda x: x.get('created', ''))
for sid, sdata in list(sessions.items()):
if sdata.get('username') == username and sdata.get('created') == oldest.get('created'):
del sessions[sid]
audit.log(
action='session_force_expired',
category=AuditLogger.CATEGORY_SECURITY,
level=AuditLogger.LEVEL_WARNING,
user=username,
details=f'Max concurrent sessions ({MAX_CONCURRENT_SESSIONS}) exceeded'
)
break
# Create new session
sessions[session_id] = {
'username': username,
'ip_address': ip_address,
'user_agent': user_agent[:200] if user_agent else 'unknown',
'created': datetime.now().isoformat(),
'last_activity': datetime.now().isoformat(),
'expires': (datetime.now() + timedelta(minutes=SESSION_TIMEOUT_MINUTES)).isoformat()
}
self._save_sessions(sessions)
return session_id
def validate_session(self, session_id):
"""Validate a session and update last activity"""
if not session_id:
return False
with self._lock:
sessions = self._load_sessions()
if session_id not in sessions:
return False
sess = sessions[session_id]
# Check expiration
expires = datetime.fromisoformat(sess['expires'])
if datetime.now() > expires:
del sessions[session_id]
self._save_sessions(sessions)
return False
# Update last activity and extend expiration
sess['last_activity'] = datetime.now().isoformat()
sess['expires'] = (datetime.now() + timedelta(minutes=SESSION_TIMEOUT_MINUTES)).isoformat()
sessions[session_id] = sess
self._save_sessions(sessions)
return True
def end_session(self, session_id):
"""End a specific session"""
with self._lock:
sessions = self._load_sessions()
if session_id in sessions:
del sessions[session_id]
self._save_sessions(sessions)
return True
return False
def end_all_user_sessions(self, username, except_session=None):
"""End all sessions for a user (optionally except current)"""
with self._lock:
sessions = self._load_sessions()
to_remove = [
sid for sid, sdata in sessions.items()
if sdata.get('username') == username and sid != except_session
]
for sid in to_remove:
del sessions[sid]
self._save_sessions(sessions)
return len(to_remove)
def get_active_sessions(self, username=None):
"""Get all active sessions, optionally filtered by user"""
with self._lock:
sessions = self._load_sessions()
# Clean expired sessions
now = datetime.now()
valid_sessions = {}
for sid, sdata in sessions.items():
expires = datetime.fromisoformat(sdata.get('expires', '2000-01-01'))
if now < expires:
valid_sessions[sid] = sdata
if len(valid_sessions) != len(sessions):
self._save_sessions(valid_sessions)
if username:
return {sid: s for sid, s in valid_sessions.items() if s.get('username') == username}
return valid_sessions
def record_login_attempt(self, username, ip_address, success):
"""Record a login attempt for rate limiting"""
with self._lock:
security = self._load_security()
key = f"{username}:{ip_address}"
now = datetime.now()
if key not in security['login_attempts']:
security['login_attempts'][key] = []
# Add this attempt
security['login_attempts'][key].append({
'timestamp': now.isoformat(),
'success': success
})
# Keep only attempts from last lockout period
cutoff = (now - timedelta(minutes=LOGIN_LOCKOUT_MINUTES)).isoformat()
security['login_attempts'][key] = [
a for a in security['login_attempts'][key]
if a['timestamp'] >= cutoff
]
# Check if should be locked out
failed_attempts = [a for a in security['login_attempts'][key] if not a['success']]
if len(failed_attempts) >= MAX_LOGIN_ATTEMPTS:
security['lockouts'][key] = (now + timedelta(minutes=LOGIN_LOCKOUT_MINUTES)).isoformat()
audit.log(
action='account_locked',
category=AuditLogger.CATEGORY_SECURITY,
level=AuditLogger.LEVEL_CRITICAL,
user=username,
ip_address=ip_address,
details=f'Account locked after {MAX_LOGIN_ATTEMPTS} failed attempts'
)
self._save_security(security)
def is_locked_out(self, username, ip_address):
"""Check if a user/IP is locked out"""
with self._lock:
security = self._load_security()
key = f"{username}:{ip_address}"
if key in security['lockouts']:
lockout_until = datetime.fromisoformat(security['lockouts'][key])
if datetime.now() < lockout_until:
return True, lockout_until
else:
# Lockout expired, remove it
del security['lockouts'][key]
self._save_security(security)
return False, None
def clear_lockout(self, username, ip_address=None):
"""Clear lockout for a user (admin function)"""
with self._lock:
security = self._load_security()
if ip_address:
key = f"{username}:{ip_address}"
if key in security['lockouts']:
del security['lockouts'][key]
else:
# Clear all lockouts for this user
to_remove = [k for k in security['lockouts'] if k.startswith(f"{username}:")]
for k in to_remove:
del security['lockouts'][k]
self._save_security(security)
def get_failed_attempts(self, username, ip_address):
"""Get number of recent failed login attempts"""
with self._lock:
security = self._load_security()
key = f"{username}:{ip_address}"
if key not in security['login_attempts']:
return 0
cutoff = (datetime.now() - timedelta(minutes=LOGIN_LOCKOUT_MINUTES)).isoformat()
recent = [a for a in security['login_attempts'][key]
if a['timestamp'] >= cutoff and not a['success']]
return len(recent)
# Initialize session manager
session_mgr = SessionManager(SESSIONS_FILE, SECURITY_FILE)
@app.before_request
def check_session_validity():
"""Check session validity on each request"""
# Skip for static files and login page
if request.endpoint in ['login', 'static', None]:
return
if current_user and current_user.is_authenticated:
session_id = session.get('session_id')
if session_id and not session_mgr.validate_session(session_id):
logout_user()
session.clear()
flash('Your session has expired. Please log in again.', 'warning')
audit.log(
action='session_expired',
category=AuditLogger.CATEGORY_AUTH,
level=AuditLogger.LEVEL_INFO
)
return redirect(url_for('login'))
def load_credentials():
"""Load credentials from environment variables or credentials file"""
creds = {
'db_password': os.environ.get('TAK_DB_PASSWORD'),
'cert_password': os.environ.get('TAK_CERT_PASSWORD'),
'web_admin_password': os.environ.get('TAK_WEB_ADMIN_PASSWORD')
}
# Fall back to credentials file if env vars not set
if os.path.exists(CREDENTIALS_FILE) and not all(creds.values()):
try:
with open(CREDENTIALS_FILE, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
key = key.strip().lower()
value = value.strip()
if key == 'tak_db_password' and not creds['db_password']:
creds['db_password'] = value
elif key == 'tak_cert_password' and not creds['cert_password']:
creds['cert_password'] = value
elif key == 'cot_admin_password' and not creds['web_admin_password']:
creds['web_admin_password'] = value
except Exception as e:
print(f"Warning: Could not load credentials file: {e}")
return creds
# Load credentials
_credentials = load_credentials()
# Database configuration - uses environment variable or credentials file
DB_CONFIG = {
'host': os.environ.get('TAK_DB_HOST', 'localhost'),
'database': os.environ.get('TAK_DB_NAME', 'takserver'),
'user': os.environ.get('TAK_DB_USER', 'takserver'),
'password': _credentials.get('db_password') or os.environ.get('TAK_DB_PASSWORD', '')
}
# Certificate password for generating client certs
CERT_PASSWORD = _credentials.get('cert_password') or os.environ.get('TAK_CERT_PASSWORD', '')
# Login Manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin):
def __init__(self, username):
self.id = username
self.username = username
# User storage (in production, use a proper database)
def load_users():
if os.path.exists(USERS_FILE):
with open(USERS_FILE, 'r') as f:
return json.load(f)
return {}
def save_users(users):
with open(USERS_FILE, 'w') as f:
json.dump(users, f, indent=2)
@login_manager.user_loader
def load_user(username):
users = load_users()
if username in users:
return User(username)
return None
# Routes
@app.route('/')
@login_required
def index():
return render_template('dashboard.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username', '').strip()
password = request.form.get('password', '')
ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
if ',' in ip_address:
ip_address = ip_address.split(',')[0].strip()
user_agent = request.headers.get('User-Agent', 'unknown')
# Check if account is locked out
is_locked, lockout_until = session_mgr.is_locked_out(username, ip_address)
if is_locked:
remaining = (lockout_until - datetime.now()).seconds // 60 + 1
flash(f'Account temporarily locked. Try again in {remaining} minutes.', 'error')
audit.log(
action='login_blocked',
category=AuditLogger.CATEGORY_AUTH,
level=AuditLogger.LEVEL_WARNING,
user=username,
ip_address=ip_address,
success=False,
details='Account locked due to too many failed attempts'
)
return render_template('login.html')
users = load_users()
# Create default admin user if no users exist
if not users:
default_password = _credentials.get('web_admin_password') or secrets.token_urlsafe(16)
users['admin'] = {'password': generate_password_hash(default_password), 'role': 'admin'}
save_users(users)
logger.info(f"Default admin user created. Check {CREDENTIALS_FILE} for password.")
# Validate credentials
if username in users and check_password_hash(users[username]['password'], password):
# Successful login
user = User(username)
login_user(user, remember=False)
session.permanent = True
# Create session
session_id = session_mgr.create_session(username, ip_address, user_agent)
session['session_id'] = session_id
session['login_time'] = datetime.now().isoformat()
# Record successful login
session_mgr.record_login_attempt(username, ip_address, True)
# Audit log
audit.log(
action='login_success',
category=AuditLogger.CATEGORY_AUTH,
level=AuditLogger.LEVEL_INFO,
user=username,
ip_address=ip_address,
success=True,
details=f'User agent: {user_agent[:100]}'
)
logger.info(f"User '{username}' logged in from {ip_address}")
# Redirect to originally requested page or dashboard
next_page = request.args.get('next')
if next_page and next_page.startswith('/'):
return redirect(next_page)
return redirect(url_for('index'))
# Failed login
session_mgr.record_login_attempt(username, ip_address, False)
failed_count = session_mgr.get_failed_attempts(username, ip_address)
remaining_attempts = MAX_LOGIN_ATTEMPTS - failed_count
audit.log(
action='login_failed',
category=AuditLogger.CATEGORY_AUTH,
level=AuditLogger.LEVEL_WARNING,
user=username,
ip_address=ip_address,
success=False,
details=f'Invalid credentials. {remaining_attempts} attempts remaining.'
)
if remaining_attempts > 0:
flash(f'Invalid username or password. {remaining_attempts} attempts remaining.', 'error')
else:
flash(f'Account locked for {LOGIN_LOCKOUT_MINUTES} minutes due to too many failed attempts.', 'error')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
username = current_user.id if current_user and current_user.is_authenticated else 'unknown'
session_id = session.get('session_id')
# End the session
if session_id:
session_mgr.end_session(session_id)
# Audit log
audit.log(
action='logout',
category=AuditLogger.CATEGORY_AUTH,
level=AuditLogger.LEVEL_INFO,
user=username,
success=True
)
logout_user()
session.clear()
flash('You have been logged out.', 'success')
return redirect(url_for('login'))
@app.route('/api/system/status')
@login_required
def system_status():
"""Get system and TAK Server status"""
try:
# Check if TAK Server is running
tak_status = subprocess.run(['systemctl', 'is-active', 'takserver'],
capture_output=True, text=True)
tak_running = tak_status.stdout.strip() == 'active'
# Check PostgreSQL status
pg_status = subprocess.run(['systemctl', 'is-active', 'postgresql'],
capture_output=True, text=True)
pg_running = pg_status.stdout.strip() == 'active'
# Get system info
uptime = subprocess.run(['uptime', '-p'], capture_output=True, text=True).stdout.strip()
memory = subprocess.run(['free', '-h'], capture_output=True, text=True).stdout
# Get connected clients count from database
connected_clients = 0
try:
conn = psycopg2.connect(**DB_CONFIG)
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM cot_router WHERE last_event_time > NOW() - INTERVAL '5 minutes'")
result = cur.fetchone()
connected_clients = result[0] if result else 0
cur.close()
conn.close()
except (psycopg2.Error, TypeError, IndexError):
# Database not available or query failed - continue with 0 clients
connected_clients = 0
return jsonify({
'success': True,
'tak_server': {
'running': tak_running,
'status': 'Running' if tak_running else 'Stopped'
},
'postgresql': {
'running': pg_running,
'status': 'Running' if pg_running else 'Stopped'
},
'system': {
'uptime': uptime,
'memory': memory
},
'stats': {
'connected_clients': connected_clients
}
})
except Exception as e:
logger.error(f"System status error: {e}")
return jsonify({'success': False, 'error': 'Failed to get system status'}), 500
@app.route('/api/server/control/<action>', methods=['POST'])
@login_required
def server_control(action):