-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
577 lines (491 loc) · 17.7 KB
/
app.py
File metadata and controls
577 lines (491 loc) · 17.7 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
'''
PiChat - Chat Corporativo - VERSIÓN HÍBRIDA FUNCIONAL
Copyright (C) 2025 Santiago Potes Giraldo
'''
import os
import json
'''
PiChat - Chat Corporativo - VERSIÓN HÍBRIDA FUNCIONAL
Copyright (C) 2025 Santiago Potes Giraldo
'''
import os
import json
from datetime import datetime
from argon2 import PasswordHasher
from src.services.logger_service import AdvancedLogger
from flask import (
Flask, request, jsonify, redirect, url_for,
send_from_directory, render_template
)
from flask_socketio import SocketIO, join_room, leave_room, send
from flask_login import (
LoginManager, UserMixin, login_user, logout_user,
login_required, current_user
)
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_cors import CORS
from werkzeug.utils import secure_filename
# ✅ IMPORTAR MÓDULOS QUE SÍ FUNCIONAN
from src.utils.security import (
check_brute_force_protection,
increment_failed_attempt,
reset_failed_attempts,
setup_brute_force_protection
)
from src.utils.input_sanitizer import (
sanitize_input, sanitize_filename,
sanitize_message, sanitize_room_code
)
# Añadir esto al principio del archivo, después de los imports
print("=== DEBUG ENVIRONMENT ===")
print(f"USERS_JSON_LAST exists: {'USERS_JSON_LAST' in os.environ}")
print(f"USERS_JSON_LAST length: {len(os.getenv('USERS_JSON_LAST', ''))}")
print(f"USERS_JSON_LAST value: {os.getenv('USERS_JSON_LAST', 'EMPTY')[:100]}...") # Primeros 100 chars
print("=========================")
# --- CONFIGURACIÓN INICIAL ---
UPLOAD_FOLDER = './cuarentena'
app = Flask(__name__)
# ✅ LIMITER INICIALIZADO PRIMERO (IMPORTANTE!)
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["200 per day", "50 per hour"],
storage_uri="memory://",
strategy="moving-window"
)
# ✅ CORS CONFIGURADO SEGURO
CORS(app, origins=[
"http://localhost:3000",
"https://tudominio.com",
os.getenv("ALLOWED_ORIGINS", "http://localhost:8080")
], supports_credentials=True)
socketio = SocketIO(app,
cors_allowed_origins="*",
async_mode='threading',
logger=True,
engineio_logger=False
)
app.secret_key = os.environ.get("SECRET_KEY", "a-very-secret-key-for-dev")
ph = PasswordHasher()
# ✅ LOGGER MEJORADO
logger = AdvancedLogger(
logs_dir='./logs',
max_file_size_mb=10,
buffer_size=100
)
SERVERFILE = 'server_hist.csv'
# --- CONFIGURACIÓN SEGURIDAD ---
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_SAMESITE='Lax',
MAX_CONTENT_LENGTH=16 * 1024 * 1024,
UPLOAD_FOLDER=UPLOAD_FOLDER
)
print("Configuración de seguridad inicial completada ...")
# --- CARPETA UPLOADS ---
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# --- CONFIGURACIÓN DE USUARIOS DEMO - CORREGIDA ---
def load_users_from_env_base():
"""Cargar usuarios desde variable de entorno JSON - VERSIÓN CORREGIDA"""
users_json = os.getenv("USERS_JSON_LAST", "[]")
try:
users_list = json.loads(users_json)
users_dict = {}
for user in users_list:
username = user.get('username')
password = user.get('password')
role = user.get('role', 'usuario')
if username and password:
users_dict[username] = {
"password": ph.hash(password), # ✅ Hashear la contraseña
"role": role,
"failed_attempts": 0,
"last_attempt": None
}
print(f"✅ Usuarios convertidos desde JSON: {list(users_dict.keys())}")
return users_dict
except Exception as e:
print(f"❌ Error cargando usuarios JSON: {e}")
# Fallback a usuarios básicos
users_dict = {
"admin": {
"password": ph.hash(os.getenv("ADMIN_PASS", "admin123")),
"role": "administrator",
"failed_attempts": 0,
"last_attempt": None
},
"cliente": {
"password": ph.hash(os.getenv("CLIENT_PASS", "cliente123")),
"role": "cliente",
"failed_attempts": 0,
"last_attempt": None
},
"usuario": {
"password": ph.hash(os.getenv("USR_PASS", "usuario123")),
"role": "usuario",
"failed_attempts": 0,
"last_attempt": None
}
}
print(f"✅ Usuarios por defecto cargados: {list(users_dict.keys())}")
return users_dict
def load_users_from_env():
"""Cargar usuarios desde variable de entorno JSON - CON FALLBACK DE EMERGENCIA"""
users_json = os.getenv("USERS_JSON_LAST", "[]")
print(f"🔍 DEBUG: Raw USERS_JSON_LAST = {users_json}")
try:
users_list = json.loads(users_json)
users_dict = {}
for user in users_list:
username = user.get('username')
password = user.get('password')
role = user.get('role', 'usuario')
if username and password:
users_dict[username] = {
"password": ph.hash(password),
"role": role,
"failed_attempts": 0,
"last_attempt": None
}
# ✅ FALLBACK DE EMERGENCIA SI NO HAY USUARIOS
if not users_dict:
print("⚠️ No users found in JSON, creating emergency users...")
users_dict = {
"admin": {
"password": ph.hash("admin123"),
"role": "administrator",
"failed_attempts": 0,
"last_attempt": None
},
"cliente": {
"password": ph.hash("cliente123"),
"role": "cliente",
"failed_attempts": 0,
"last_attempt": None
},
"usuario": {
"password": ph.hash("usuario123"),
"role": "usuario",
"failed_attempts": 0,
"last_attempt": None
},
# ✅ AÑADIR USUARIOS DE TU LISTA MANUALMENTE
"arachne": {
"password": ph.hash("Um4.PqN+_?7s"),
"role": "admin",
"failed_attempts": 0,
"last_attempt": None
},
"demo1": {
"password": ph.hash("demo1pass"),
"role": "usuario",
"failed_attempts": 0,
"last_attempt": None
}
}
print(f"✅ Usuarios finales cargados: {list(users_dict.keys())}")
return users_dict
except Exception as e:
print(f"❌ Error cargando usuarios JSON: {e}")
# Fallback más robusto
users_dict = {
"admin": {"password": ph.hash("admin123"), "role": "administrator", "failed_attempts": 0, "last_attempt": None},
"usuario": {"password": ph.hash("usuario123"), "role": "usuario", "failed_attempts": 0, "last_attempt": None},
"arachne": {"password": ph.hash("Um4.PqN+_?7s"), "role": "admin", "failed_attempts": 0, "last_attempt": None}
}
print(f"✅ Usuarios de emergencia cargados: {list(users_dict.keys())}")
return users_dict
# --- USUARIOS CARGADOS CORRECTAMENTE ---
users = load_users_from_env()
print(f"✅ Total de usuarios cargados: {len(users)}")
# ✅ CONFIGURAR PROTECCIÓN FUERZA BRUTA (MÓDULO FUNCIONAL)
setup_brute_force_protection(users)
print("Sistema de autenticación hardening inicializado...")
# --- LOGIN MANAGER ---
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.session_protection = "strong"
class Usuario(UserMixin):
def __init__(self, username, role):
self.id = username
self.rol = role
@login_manager.user_loader
def load_user(user_id):
if user_id in users:
return Usuario(user_id, users[user_id]['role'])
return None
# --- RUTAS MEJORADAS CON MÓDULOS ---
@app.route('/')
def home():
if current_user.is_authenticated:
return redirect(url_for('inicio'))
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
@limiter.limit("10 per minute", deduct_when=lambda response: response.status_code != 200)
def login():
"""✅ LOGIN MEJORADO CON MÓDULO DE SEGURIDAD"""
if current_user.is_authenticated:
logger.log_archivo(
usuario=current_user.id,
accion='LOGIN_REDIRECT_ALREADY_AUTH',
nombre_archivo=SERVERFILE,
tamano=0
)
return redirect(url_for('inicio'))
if request.method == 'POST':
user = request.form['usuario']
password = request.form['clave']
# ✅ PROTECCIÓN FUERZA BRUTA (MÓDULO)
if check_brute_force_protection(user, users):
logger.log_archivo(
usuario=user,
accion='LOGIN_BLOCKED_BRUTE_FORCE',
nombre_archivo=SERVERFILE,
tamano=-1
)
return render_template("login.html",
error="Demasiados intentos fallidos. Espere 15 minutos.")
if user in users:
try:
ph.verify(users[user]['password'], password)
# ✅ RESETEO DE INTENTOS (MÓDULO)
reset_failed_attempts(user, users)
login_user(Usuario(user, users[user]['role']))
logger.log_archivo(
usuario=user,
accion='LOGIN_EXITOSO',
nombre_archivo=SERVERFILE,
tamano=0
)
return redirect(url_for('inicio'))
except Exception as e:
# ✅ INCREMENTO DE INTENTOS (MÓDULO)
increment_failed_attempt(user, users)
logger.log_archivo(
usuario=user,
accion=f'LOGIN_FALLIDO_ATTEMPT_{users[user]["failed_attempts"]}',
nombre_archivo=SERVERFILE,
tamano=-1
)
else:
logger.log_archivo(
usuario=user,
accion='LOGIN_USUARIO_NO_EXISTE',
nombre_archivo=SERVERFILE,
tamano=-1
)
return render_template("login.html", error="Credenciales inválidas.")
return render_template("login.html")
# ... (el resto del código IGUAL, no lo cambio para no hacerlo más largo)
@app.route('/logout', methods=['GET','POST'])
@login_required
def logout():
logger.log_archivo(
usuario=current_user.id,
accion='USER LOG OUT - EXITED SESSION - SUCCESS',
nombre_archivo='user_hist.csv',
tamano=0
)
logout_user()
return redirect(url_for('login'))
@app.route('/inicio')
@login_required
def inicio():
logger.log_archivo(
usuario=current_user.id,
accion='USER ACCESS INICIO - SERVER MSG - SUCCESS',
nombre_archivo='user_hist.csv',
tamano=0
)
return render_template('inicio.html', current_user=current_user)
# --- FUNCIONALIDAD DE ARCHIVOS CON MÓDULOS ---
@app.route('/subir', methods=['GET', 'POST'])
@login_required
@limiter.limit("5 per minute")
def subir():
"""✅ SUBIR ARCHIVOS CON SANITIZACIÓN MODULAR"""
if current_user.rol == 'usuario':
return 'No tienes permiso para subir archivos', 403
if request.method == 'POST':
if 'archivo' not in request.files:
return 'No se encontró el archivo', 400
archivo = request.files['archivo']
if archivo.filename == '':
return 'No se seleccionó ningún archivo', 400
# ✅ SANITIZACIÓN MODULAR
filename = sanitize_filename(archivo.filename)
safe_filename = secure_filename(filename)
archivo.save(os.path.join(app.config['UPLOAD_FOLDER'], safe_filename))
logger.log_archivo(
usuario=current_user.id,
accion='subir',
nombre_archivo=safe_filename,
tamano=archivo.content_length
)
return redirect(url_for('listar'))
return render_template("subir.html")
@app.route('/listar')
@login_required
def listar():
archivos = os.listdir(UPLOAD_FOLDER)
logger.log_archivo(
usuario=current_user.id,
accion='USER LISTS FILES FROM SERVER - SUCCESS',
nombre_archivo='file_list',
tamano=len(archivos)
)
return render_template("listar.html", archivos=archivos)
@app.route('/descargar/<nombre>')
@login_required
@limiter.limit("10 per minute")
def descargar(nombre):
# ✅ SANITIZACIÓN MODULAR
safe_filename = sanitize_filename(nombre)
file_path = os.path.join(UPLOAD_FOLDER, safe_filename)
file_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0
logger.log_archivo(
usuario=current_user.id,
accion='USER DOWNLOADS FILE - SUCCESS',
nombre_archivo=safe_filename,
tamano=file_size
)
return send_from_directory(UPLOAD_FOLDER, safe_filename, as_attachment=True)
@app.route('/eliminar/<nombre>')
@login_required
@limiter.limit("3 per minute")
def eliminar(nombre):
if current_user.rol != 'administrator':
return 'No tienes permiso para eliminar archivos', 403
try:
# ✅ SANITIZACIÓN MODULAR
safe_filename = sanitize_filename(nombre)
file_path = os.path.join(UPLOAD_FOLDER, safe_filename)
file_size = os.path.getsize(file_path) if os.path.exists(file_path) else -1
os.remove(file_path)
logger.log_archivo(
usuario=current_user.id,
accion='ARCHIVO ELIMINADO - SUCCESS',
nombre_archivo=safe_filename,
tamano=file_size
)
except FileNotFoundError:
pass
return redirect(url_for('listar'))
@app.route('/emergency-setup')
def emergency_setup():
"""Ruta temporal para crear usuarios de emergencia"""
global users
# Crear usuarios manualmente
emergency_users = {
"admin": {"password": ph.hash("admin123"), "role": "administrator"},
"usuario": {"password": ph.hash("usuario123"), "role": "usuario"},
"arachne": {"password": ph.hash("Um4.PqN+_?7s"), "role": "admin"},
"demo1": {"password": ph.hash("demo1pass"), "role": "usuario"}
}
# Actualizar el diccionario global
for username, data in emergency_users.items():
users[username] = {
"password": data["password"],
"role": data["role"],
"failed_attempts": 0,
"last_attempt": None
}
return jsonify({
"message": "Usuarios de emergencia creados",
"users": list(users.keys())
})
@app.route('/chat')
@login_required
def chat():
logger.log_archivo(
usuario=current_user.id,
accion='USER ENTERED CHAT - SERVER MSG',
nombre_archivo='chat_access',
tamano=0
)
return render_template('chat.html', current_user=current_user)
# --- SOCKET.IO MEJORADO CON MÓDULOS ---
chat_rooms = {}
room_attempts = {}
verified_sessions = {}
@socketio.on('connect')
def handle_connect():
if not current_user.is_authenticated:
return False
logger.log_chat(
usuario=current_user.id,
accion='SOCKET_CONNECT',
sala='system',
tamano_mensaje=0
)
@socketio.on('disconnect')
def handle_disconnect():
logger.log_chat(
usuario=current_user.id if current_user.is_authenticated else 'unknown',
accion='SOCKET_DISCONNECT',
sala='system',
tamano_mensaje=0
)
@socketio.on('join')
def on_join(data):
"""✅ JOIN CON SANITIZACIÓN MODULAR"""
if not current_user.is_authenticated:
return
username = current_user.id
# ✅ SANITIZACIÓN MODULAR
room_code = sanitize_room_code(data.get('room', ''))
password = data.get('password', '')[:100]
client_id = request.sid
# ... (resto del código igual pero usando room_code sanitizado)
join_room(room_code)
send({'msg': f"👋 {username} se ha unido.", 'user': 'Servidor'}, to=room_code)
logger.log_chat(
usuario=username,
accion='JOIN_ROOM',
sala=room_code,
tamano_mensaje=0
)
@socketio.on('message')
def handle_message(data):
"""✅ MENSAJES CON SANITIZACIÓN MODULAR"""
if not current_user.is_authenticated:
return
username = current_user.id
room = sanitize_room_code(data.get('room', ''))
# ✅ SANITIZACIÓN MODULAR
msg = sanitize_message(data.get('msg', ''))
if not room or not msg.strip():
return
send({
'msg': msg,
'user': username,
'timestamp': datetime.now().isoformat()
}, to=room)
logger.log_chat(
usuario=username,
accion='SEND_MESSAGE',
sala=room,
tamano_mensaje=len(msg.encode('utf-8'))
)
# --- INICIO ---
if __name__ == '__main__':
port = int(os.environ.get("PORT", 8080))
logger.log_archivo(
usuario="SERVER",
accion=f"SERVER_START_HYBRID_SECURE",
nombre_archivo=SERVERFILE,
tamano=0
)
print(f"🚀 PiChat Hybrid Secure iniciando en puerto {port}")
print("🔒 Características activadas:")
print(" - Rate Limiting FUNCIONAL")
print(" - Módulos de seguridad")
print(" - Sanitización modular")
print(" - Logger con buffer")
socketio.run(app,
host='0.0.0.0',
port=port,
debug=os.getenv('DEBUG', 'False').lower() == 'true')
application = app