-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecure_admin_auth.py
More file actions
265 lines (216 loc) · 9.36 KB
/
secure_admin_auth.py
File metadata and controls
265 lines (216 loc) · 9.36 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
"""
Secure Admin Authentication System
Multiple layers of security for admin panel access
"""
import hashlib
import secrets
import time
from flask_login import UserMixin
from datetime import datetime
import json
import os
class User(UserMixin):
"""User class for admin authentication"""
def __init__(self, user_id, username, is_admin=False):
self.id = user_id
self.username = username
self.is_admin = is_admin
class AdminAuthSystem:
"""Manages admin authentication with multiple security layers"""
def __init__(self, auth_file: str = "admin_auth.json"):
self.auth_file = auth_file
self.rate_limit_storage = {} # IP -> [timestamps]
self.failed_attempts = {} # IP -> count
self.lockout_until = {} # IP -> timestamp
# Initialize auth file if doesn't exist
if not os.path.exists(auth_file):
self._create_default_admin()
else:
# If ADMIN_PASSWORD env var is set, ensure the admin account
# matches it — handles cases where the env var changed after
# the auth file was first created.
self._sync_admin_password()
def _sync_admin_password(self):
"""Re-hash the default admin password if ADMIN_PASSWORD env var is set
and the stored hash no longer matches it."""
env_password = os.environ.get('ADMIN_PASSWORD')
if not env_password:
print("Note: ADMIN_PASSWORD env var not set — admin password unchanged")
return
data = self._load_auth_data()
admin = data["admins"].get("admin")
if not admin:
return
# Only update if the current hash doesn't match the env password
if not self._verify_password(env_password, admin["password_hash"]):
admin["password_hash"] = self._hash_password(env_password)
self._save_auth_data(data)
print("Admin password synced with ADMIN_PASSWORD environment variable")
def _create_default_admin(self):
"""Create default admin account on first run"""
default_password = os.environ.get('ADMIN_PASSWORD', 'admin')
admin_data = {
"admins": {
"admin": {
"password_hash": self._hash_password(default_password),
"created_at": datetime.now().isoformat(),
"last_login": None,
"is_active": True
}
},
"sessions": {},
"audit_log": []
}
with open(self.auth_file, 'w') as f:
json.dump(admin_data, f, indent=2)
print("=" * 60)
print("ADMIN ACCOUNT CREATED")
print("=" * 60)
print(f"Username: admin")
if default_password == 'admin':
print(f"Password: admin (default — set ADMIN_PASSWORD env var to change)")
else:
print(f"Password: (from ADMIN_PASSWORD environment variable)")
print("=" * 60)
def _hash_password(self, password: str) -> str:
"""Hash password with salt"""
salt = secrets.token_hex(16)
pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
return f"{salt}${pwd_hash.hex()}"
def _verify_password(self, password: str, password_hash: str) -> bool:
"""Verify password against hash"""
try:
salt, hash_value = password_hash.split('$')
pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
return pwd_hash.hex() == hash_value
except Exception:
return False
def _load_auth_data(self) -> dict:
"""Load authentication data"""
with open(self.auth_file, 'r') as f:
return json.load(f)
def _save_auth_data(self, data: dict):
"""Save authentication data"""
with open(self.auth_file, 'w') as f:
json.dump(data, f, indent=2)
def _log_audit_event(self, event_type: str, username: str, ip: str, details: str):
"""Log security events"""
data = self._load_auth_data()
data["audit_log"].append({
"timestamp": datetime.now().isoformat(),
"event": event_type,
"username": username,
"ip": ip,
"details": details
})
# Keep only last 1000 events
data["audit_log"] = data["audit_log"][-1000:]
self._save_auth_data(data)
def check_rate_limit(self, ip: str, max_requests: int = 5, window_seconds: int = 60) -> bool:
"""
Rate limiting to prevent brute force attacks
Returns True if under limit, False if over
"""
now = time.time()
# Clean old timestamps
if ip in self.rate_limit_storage:
self.rate_limit_storage[ip] = [
ts for ts in self.rate_limit_storage[ip]
if now - ts < window_seconds
]
else:
self.rate_limit_storage[ip] = []
# Check if over limit
if len(self.rate_limit_storage[ip]) >= max_requests:
return False
# Add current request
self.rate_limit_storage[ip].append(now)
return True
def is_locked_out(self, ip: str) -> bool:
"""Check if IP is temporarily locked out"""
if ip in self.lockout_until:
if time.time() < self.lockout_until[ip]:
return True
else:
# Lockout expired
del self.lockout_until[ip]
self.failed_attempts[ip] = 0
return False
def record_failed_attempt(self, ip: str):
"""Record failed login attempt"""
self.failed_attempts[ip] = self.failed_attempts.get(ip, 0) + 1
# Lock out after 5 failed attempts for 15 minutes
if self.failed_attempts[ip] >= 5:
self.lockout_until[ip] = time.time() + (15 * 60)
def reset_failed_attempts(self, ip: str):
"""Reset failed attempts after successful login"""
if ip in self.failed_attempts:
del self.failed_attempts[ip]
def authenticate(self, username: str, password: str, ip: str) -> dict:
"""
Authenticate admin user
Returns: {"success": bool, "user": User or None, "error": str}
"""
# Load admin data
data = self._load_auth_data()
# Check if user exists
if username not in data["admins"]:
self._log_audit_event("LOGIN_FAIL", username, ip, "Invalid username")
return {"success": False, "error": "Invalid credentials"}
admin = data["admins"][username]
# Check if account is active
if not admin.get("is_active", True):
self._log_audit_event("LOGIN_FAIL", username, ip, "Account disabled")
return {"success": False, "error": "Account is disabled"}
# Verify password
if not self._verify_password(password, admin["password_hash"]):
self._log_audit_event("LOGIN_FAIL", username, ip, "Invalid password")
return {"success": False, "error": "Invalid credentials"}
# Success - update last login
admin["last_login"] = datetime.now().isoformat()
self._save_auth_data(data)
self._log_audit_event("LOGIN_SUCCESS", username, ip, "Successful login")
return {
"success": True,
"user": User(username, username, is_admin=True),
"error": None
}
def change_password(self, username: str, old_password: str, new_password: str) -> dict:
"""Change admin password"""
data = self._load_auth_data()
if username not in data["admins"]:
return {"success": False, "error": "User not found"}
admin = data["admins"][username]
# Verify old password
if not self._verify_password(old_password, admin["password_hash"]):
return {"success": False, "error": "Invalid current password"}
# Validate new password strength
if len(new_password) < 12:
return {"success": False, "error": "Password must be at least 12 characters"}
# Update password
admin["password_hash"] = self._hash_password(new_password)
admin["password_changed_at"] = datetime.now().isoformat()
self._save_auth_data(data)
self._log_audit_event("PASSWORD_CHANGE", username, "system", "Password changed")
return {"success": True, "message": "Password changed successfully"}
def create_admin(self, username: str, password: str, creator: str) -> dict:
"""Create new admin account"""
data = self._load_auth_data()
if username in data["admins"]:
return {"success": False, "error": "Username already exists"}
if len(password) < 12:
return {"success": False, "error": "Password must be at least 12 characters"}
data["admins"][username] = {
"password_hash": self._hash_password(password),
"created_at": datetime.now().isoformat(),
"created_by": creator,
"last_login": None,
"is_active": True
}
self._save_auth_data(data)
self._log_audit_event("ADMIN_CREATED", username, "system", f"Created by {creator}")
return {"success": True, "message": f"Admin account '{username}' created"}
def get_audit_log(self, limit: int = 100) -> list:
"""Get recent audit log entries"""
data = self._load_auth_data()
return data["audit_log"][-limit:]