admin_routes.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. import hashlib
  2. import os
  3. import re
  4. import stat
  5. from flask import (
  6. Blueprint,
  7. current_app,
  8. flash,
  9. jsonify,
  10. redirect,
  11. render_template,
  12. request,
  13. url_for,
  14. )
  15. from flask_babel import gettext as _
  16. from loguru import logger
  17. from config import Config
  18. from database.database import get_session
  19. from database.models.models import BlacklistDomain
  20. from routes.admin.helpers import json_error, json_success
  21. from services.auth.auth_service import AuthService, admin_required, api_auth_required
  22. from services.auth.user_service import (
  23. create_user as service_create_user,
  24. )
  25. from services.auth.user_service import (
  26. delete_user as service_delete_user,
  27. )
  28. from services.auth.user_service import (
  29. get_all_users as service_get_all_users,
  30. )
  31. from services.auth.user_service import (
  32. update_user as service_update_user,
  33. )
  34. from services.database.admin_helpers import (
  35. load_env_vars,
  36. save_env_vars,
  37. )
  38. from services.database.db_admin_service import (
  39. delete_table_data as service_delete_table_data,
  40. )
  41. from services.notifications.telegram_config_service import (
  42. load_config as load_telegram_config,
  43. )
  44. from services.security.blacklist_service import (
  45. delete_blacklist_by_source_url,
  46. get_url_blacklists_with_counts,
  47. import_domains_from_file,
  48. import_domains_from_url,
  49. merge_and_save_blacklist,
  50. save_custom_list,
  51. test_pihole_connection,
  52. )
  53. from services.squid.acls_service import add_acl as service_add_acl
  54. from services.squid.acls_service import delete_acl as service_delete_acl
  55. from services.squid.acls_service import edit_acl as service_edit_acl
  56. from services.squid.config_service import save_config as service_save_config
  57. from services.squid.delay_pools_service import (
  58. add_delay_pool as service_add_delay_pool,
  59. )
  60. from services.squid.delay_pools_service import (
  61. delete_delay_pool as service_delete_delay_pool,
  62. )
  63. from services.squid.delay_pools_service import (
  64. edit_delay_pool as service_edit_delay_pool,
  65. )
  66. from services.squid.http_access_service import (
  67. add_http_access as service_add_http_access,
  68. )
  69. from services.squid.http_access_service import (
  70. add_http_deny_blocklist as service_add_http_deny_blocklist,
  71. )
  72. from services.squid.http_access_service import (
  73. delete_http_access as service_delete_http_access,
  74. )
  75. from services.squid.http_access_service import (
  76. edit_http_access as service_edit_http_access,
  77. )
  78. from services.squid.http_access_service import (
  79. move_http_access as service_move_http_access,
  80. )
  81. from services.squid.http_access_service import (
  82. remove_http_deny_blocklist as service_remove_http_deny_blocklist,
  83. )
  84. from services.squid.split_config_service import (
  85. get_split_files_info as service_get_split_files_info,
  86. )
  87. from services.squid.split_config_service import (
  88. get_split_view_data as service_get_split_view_data,
  89. )
  90. from services.squid.split_config_service import (
  91. split_config as service_split_config,
  92. )
  93. from services.squid.squid_config_splitter import SquidConfigSplitter
  94. from services.system.logs_service import read_logs as service_read_logs
  95. from services.system.system_service import (
  96. reload_squid as service_reload_squid,
  97. )
  98. from services.system.system_service import (
  99. restart_squid as service_restart_squid,
  100. )
  101. from utils.admin import SquidConfigManager
  102. admin_bp = Blueprint("admin", __name__)
  103. # Global manager instance
  104. config_manager = SquidConfigManager()
  105. @admin_bp.route("/")
  106. @admin_required
  107. def admin_dashboard():
  108. acls = config_manager.get_acls()
  109. delay_pools = config_manager.get_delay_pools()
  110. http_access_rules = config_manager.get_http_access_rules()
  111. stats = {
  112. "total_acls": len(acls),
  113. "total_delay_pools": len(delay_pools),
  114. "total_http_rules": len(http_access_rules),
  115. }
  116. status = config_manager.get_status()
  117. return render_template("admin/dashboardAdmin.html", stats=stats, status=status)
  118. @admin_bp.route("/config")
  119. @admin_required
  120. def view_config():
  121. env_vars = load_env_vars()
  122. cfg = load_telegram_config()
  123. return render_template(
  124. "admin/config.html",
  125. config_content=config_manager.config_content,
  126. env_vars=env_vars,
  127. cfg=cfg,
  128. )
  129. @admin_bp.route("/config/edit", methods=["GET", "POST"])
  130. @admin_required
  131. def edit_config():
  132. if request.method == "POST":
  133. new_content = request.form["config_content"]
  134. ok, message = service_save_config(new_content, config_manager)
  135. if ok:
  136. flash(message, "success")
  137. return redirect(url_for("admin.view_config"))
  138. else:
  139. try:
  140. show_details = bool(current_app.debug)
  141. except RuntimeError:
  142. show_details = False
  143. if show_details:
  144. flash(
  145. _("Error saving configuration: %(message)s") % {"message": message},
  146. "error",
  147. )
  148. else:
  149. flash(_("Error saving configuration"), "error")
  150. return render_template(
  151. "admin/edit_config.html", config_content=config_manager.config_content
  152. )
  153. @admin_bp.route("/config/env/save", methods=["POST"])
  154. @admin_required
  155. def save_env():
  156. # Variables sensibles que no se pueden modificar desde la interfaz
  157. sensitive_vars = {"VERSION"}
  158. env_vars = {}
  159. for key in request.form:
  160. if key != "csrf_token" and key not in sensitive_vars:
  161. env_vars[key] = request.form[key]
  162. # Cargar variables existentes para mantener las sensibles
  163. existing_vars = load_env_vars()
  164. # Solo actualizar las no sensibles
  165. for key, value in env_vars.items():
  166. existing_vars[key] = value
  167. save_env_vars(existing_vars)
  168. flash(_("Variables de entorno guardadas exitosamente"), "success")
  169. return redirect(url_for("admin.view_config"))
  170. @admin_bp.route("/acls")
  171. @admin_required
  172. def manage_acls():
  173. """Display ACLs management interface with categorization and metadata."""
  174. acls = config_manager.get_acls()
  175. return render_template("admin/acls_new.html", acls=acls)
  176. @admin_bp.route("/acls/add", methods=["POST"])
  177. @admin_required
  178. def add_acl():
  179. """Add a new ACL with options, multiple values, and comment."""
  180. name = request.form.get("name")
  181. acl_type = request.form.get("type")
  182. values = request.form.getlist("values[]")
  183. options = request.form.getlist("options[]")
  184. comment = request.form.get("comment", "").strip()
  185. success, message = service_add_acl(
  186. name, acl_type, values, options, comment, config_manager
  187. )
  188. flash(message, "success" if success else "error")
  189. return redirect(url_for("admin.manage_acls"))
  190. @admin_bp.route("/acls/edit", methods=["POST"])
  191. @admin_required
  192. def edit_acl():
  193. """Edit an existing ACL using line number for precise targeting."""
  194. acl_id = request.form.get("id")
  195. new_name = request.form.get("name")
  196. acl_type = request.form.get("type")
  197. values = request.form.getlist("values[]")
  198. options = request.form.getlist("options[]")
  199. comment = request.form.get("comment", "").strip()
  200. try:
  201. acl_index = int(acl_id)
  202. except (ValueError, TypeError):
  203. flash(_("ID de ACL inválido"), "error")
  204. return redirect(url_for("admin.manage_acls"))
  205. success, message = service_edit_acl(
  206. acl_index, new_name, acl_type, values, options, comment, config_manager
  207. )
  208. flash(message, "success" if success else "error")
  209. return redirect(url_for("admin.manage_acls"))
  210. @admin_bp.route("/acls/delete", methods=["POST"])
  211. @admin_required
  212. def delete_acl():
  213. """Delete an ACL using its ID (index) and line number."""
  214. acl_id = request.form.get("id")
  215. try:
  216. acl_index = int(acl_id)
  217. except (ValueError, TypeError):
  218. flash(_("ID de ACL inválido"), "error")
  219. return redirect(url_for("admin.manage_acls"))
  220. success, message = service_delete_acl(acl_index, config_manager)
  221. flash(message, "success" if success else "error")
  222. return redirect(url_for("admin.manage_acls"))
  223. @admin_bp.route("/delay-pools")
  224. @admin_required
  225. def manage_delay_pools():
  226. delay_pools = config_manager.get_delay_pools()
  227. authenticated = AuthService.is_authenticated()
  228. return render_template(
  229. "admin/delay_pools.html",
  230. delay_pools=delay_pools,
  231. authenticated=authenticated,
  232. )
  233. @admin_bp.route("/http-access")
  234. @admin_required
  235. def manage_http_access():
  236. rules = config_manager.get_http_access_rules()
  237. return render_template("admin/http_access.html", rules=rules)
  238. @admin_bp.route("/blacklist", methods=["GET"])
  239. @admin_required
  240. def manage_blacklist():
  241. """Render the blacklist management UI."""
  242. env_vars = load_env_vars()
  243. # Provide current blacklist domains to the template — now read from DB
  244. session = get_session()
  245. try:
  246. # Only show entries that were added via the 'custom' source
  247. rows = (
  248. session.query(BlacklistDomain)
  249. .filter(
  250. BlacklistDomain.active == 1,
  251. BlacklistDomain.source.in_(["custom", "env_migration"]),
  252. )
  253. .order_by(BlacklistDomain.domain)
  254. .all()
  255. )
  256. # Provide domains separated by newlines so the custom textarea can be pre-filled
  257. blacklist = "\n".join([r.domain for r in rows])
  258. finally:
  259. session.close()
  260. url_lists = get_url_blacklists_with_counts()
  261. # Determine which lists are currently enforced in Squid config
  262. enforced_urls = _get_enforced_blocklist_urls(config_manager)
  263. for item in url_lists:
  264. item["enforced"] = item["source_url"] in enforced_urls
  265. custom_enforced = "__custom__" in enforced_urls
  266. return render_template(
  267. "admin/blacklist.html",
  268. env_vars=env_vars,
  269. blacklist=blacklist,
  270. url_lists=url_lists,
  271. custom_enforced=custom_enforced,
  272. )
  273. @admin_bp.route("/blacklist/test-connection", methods=["POST"])
  274. @admin_required
  275. def blacklist_test_connection():
  276. host = request.form.get("host") or request.form.get("pihole_host")
  277. token = request.form.get("token") or request.form.get("api_token")
  278. if not host:
  279. flash(_("Host de Pi-hole no proporcionado"), "error")
  280. return redirect(url_for("admin.manage_blacklist"))
  281. success, msg = test_pihole_connection(host, token)
  282. flash(msg, "success" if success else "error")
  283. return redirect(url_for("admin.manage_blacklist"))
  284. @admin_bp.route("/blacklist/sync", methods=["POST"])
  285. @admin_required
  286. def blacklist_sync():
  287. # Placeholder: kick off background sync job in production
  288. # For now just flash success and return
  289. flash(_("Sincronización de listas iniciada (en segundo plano)"), "success")
  290. return redirect(url_for("admin.manage_blacklist"))
  291. @admin_bp.route("/blacklist/import", methods=["POST"])
  292. @admin_required
  293. def blacklist_import():
  294. # Import domains from uploaded file or URL and append to BLACKLIST_DOMAINS
  295. file_domains = set()
  296. url_domains = set()
  297. # Handle file upload
  298. uploaded = request.files.get("file")
  299. if uploaded and uploaded.filename:
  300. try:
  301. file_domains = import_domains_from_file(uploaded)
  302. flash(_("Archivo importado correctamente"), "success")
  303. except Exception as e:
  304. logger.exception("Error importando archivo de blacklist")
  305. try:
  306. show_details = bool(current_app.debug)
  307. except RuntimeError:
  308. show_details = False
  309. if show_details:
  310. flash(
  311. _("Error al procesar el archivo: %(error)s") % {"error": str(e)},
  312. "error",
  313. )
  314. else:
  315. flash(_("Error al procesar el archivo"), "error")
  316. return redirect(url_for("admin.manage_blacklist"))
  317. # Handle URL import
  318. url = request.form.get("url")
  319. if url:
  320. ok, imported_url_domains, err = import_domains_from_url(url)
  321. if ok:
  322. url_domains.update(imported_url_domains)
  323. flash(_("Lista importada desde URL correctamente"), "success")
  324. else:
  325. flash(_("Error importando desde URL: %(err)s") % {"err": err}, "error")
  326. # Merge with existing and save, preserving source metadata
  327. try:
  328. if file_domains:
  329. merge_and_save_blacklist(file_domains, source="file")
  330. if url_domains:
  331. merge_and_save_blacklist(url_domains, source="url", source_url=url)
  332. if not file_domains and not url_domains:
  333. flash(_("No se encontraron dominios para importar"), "warning")
  334. else:
  335. flash(_("Blacklist actualizada exitosamente"), "success")
  336. except Exception as e:
  337. logger.exception("Error guardando BLACKLIST_DOMAINS")
  338. try:
  339. show_details = bool(current_app.debug)
  340. except RuntimeError:
  341. show_details = False
  342. if show_details:
  343. flash(
  344. _("Error al guardar blacklist: %(error)s") % {"error": str(e)}, "error"
  345. )
  346. else:
  347. flash(_("Error al guardar blacklist"), "error")
  348. return redirect(url_for("admin.manage_blacklist"))
  349. @admin_bp.route("/blacklist/save-custom", methods=["POST"])
  350. @admin_required
  351. def blacklist_save_custom():
  352. custom = request.form.get("custom_list", "")
  353. if not custom.strip():
  354. flash(_("Lista personalizada vacía"), "error")
  355. return redirect(url_for("admin.manage_blacklist"))
  356. # parse lines and commas
  357. items = []
  358. for line in custom.splitlines():
  359. for part in line.split(","):
  360. d = part.strip()
  361. if d:
  362. items.append(d)
  363. try:
  364. save_custom_list(items)
  365. flash(_("Lista personalizada guardada en BLACKLIST_DOMAINS"), "success")
  366. except Exception as e:
  367. logger.exception("Error guardando lista personalizada")
  368. try:
  369. show_details = bool(current_app.debug)
  370. except RuntimeError:
  371. show_details = False
  372. if show_details:
  373. flash(
  374. _("Error al guardar la lista: %(error)s") % {"error": str(e)}, "error"
  375. )
  376. else:
  377. flash(_("Error al guardar la lista"), "error")
  378. return redirect(url_for("admin.manage_blacklist"))
  379. @admin_bp.route("/http-access/delete", methods=["POST"])
  380. @admin_required
  381. def delete_http_access():
  382. index = request.form.get("index")
  383. try:
  384. rule_index = int(index)
  385. except (ValueError, TypeError):
  386. flash(_("Índice de regla inválido"), "error")
  387. return redirect(url_for("admin.manage_http_access"))
  388. success, message = service_delete_http_access(rule_index, config_manager)
  389. flash(message, "success" if success else "error")
  390. return redirect(url_for("admin.manage_http_access"))
  391. @admin_bp.route("/http-access/edit", methods=["POST"])
  392. @admin_required
  393. def edit_http_access():
  394. """Edit an http_access rule with support for multiple ACLs and description"""
  395. index = request.form.get("index")
  396. action = request.form.get("action")
  397. acls = request.form.getlist("acls[]")
  398. description = request.form.get("description", "").strip()
  399. try:
  400. rule_index = int(index)
  401. except (ValueError, TypeError):
  402. flash(_("Índice de regla inválido"), "error")
  403. return redirect(url_for("admin.manage_http_access"))
  404. success, message = service_edit_http_access(
  405. rule_index, action, acls, description, config_manager
  406. )
  407. flash(message, "success" if success else "error")
  408. return redirect(url_for("admin.manage_http_access"))
  409. @admin_bp.route("/http-access/add", methods=["POST"])
  410. @admin_required
  411. def add_http_access():
  412. """Add a new http_access rule"""
  413. action = request.form.get("action")
  414. acls = request.form.getlist("acls[]")
  415. description = request.form.get("description", "").strip()
  416. success, message = service_add_http_access(
  417. action, acls, description, config_manager
  418. )
  419. flash(message, "success" if success else "error")
  420. return redirect(url_for("admin.manage_http_access"))
  421. @admin_bp.route("/http-access/move", methods=["POST"])
  422. @admin_required
  423. def move_http_access():
  424. """Move an http_access rule up or down"""
  425. index = request.form.get("index")
  426. direction = request.form.get("direction") # 'up' or 'down'
  427. try:
  428. rule_index = int(index)
  429. except (ValueError, TypeError):
  430. flash(_("Índice de regla inválido"), "error")
  431. return redirect(url_for("admin.manage_http_access"))
  432. success, message = service_move_http_access(rule_index, direction, config_manager)
  433. flash(message, "success" if success else "error")
  434. return redirect(url_for("admin.manage_http_access"))
  435. @admin_bp.route("/delay-pools/delete", methods=["POST"])
  436. @admin_required
  437. def delete_delay_pool():
  438. """Delete all directives related to a specific delay pool"""
  439. pool_number = request.form.get("pool_number")
  440. success, message = service_delete_delay_pool(pool_number, config_manager)
  441. flash(message, "success" if success else "error")
  442. return redirect(url_for("admin.manage_delay_pools"))
  443. @admin_bp.route("/delay-pools/edit", methods=["POST"])
  444. @admin_required
  445. def edit_delay_pool():
  446. """Edit all directives related to a specific delay pool"""
  447. pool_number = request.form.get("pool_number")
  448. pool_class = request.form.get("pool_class")
  449. parameters = request.form.get("parameters")
  450. access_actions = request.form.getlist("access_action[]")
  451. access_acls = request.form.getlist("access_acl[]")
  452. success, message = service_edit_delay_pool(
  453. pool_number, pool_class, parameters, access_actions, access_acls, config_manager
  454. )
  455. flash(message, "success" if success else "error")
  456. return redirect(url_for("admin.manage_delay_pools"))
  457. @admin_bp.route("/delay-pools/add", methods=["POST"])
  458. @admin_required
  459. def add_delay_pool():
  460. """Add a new delay pool with all its directives"""
  461. pool_number = request.form.get("pool_number")
  462. pool_class = request.form.get("pool_class")
  463. parameters = request.form.get("parameters")
  464. access_actions = request.form.getlist("access_action[]")
  465. access_acls = request.form.getlist("access_acl[]")
  466. success, message = service_add_delay_pool(
  467. pool_number, pool_class, parameters, access_actions, access_acls, config_manager
  468. )
  469. flash(message, "success" if success else "error")
  470. return redirect(url_for("admin.manage_delay_pools"))
  471. @admin_bp.route("/view-logs")
  472. @admin_required
  473. def view_logs():
  474. # Get the requested number of lines (default 250, maximum 1000)
  475. max_lines = request.args.get("lines", 250, type=int)
  476. max_lines = min(max(max_lines, 10), 1000) # Between 10 and 1000 lines
  477. log_files = [Config.SQUID_LOG, Config.SQUID_CACHE_LOG]
  478. logs = service_read_logs(log_files, max_lines, debug=bool(current_app.debug))
  479. return render_template("admin/logs.html", logs=logs, max_lines=max_lines)
  480. @admin_bp.route("/users")
  481. @admin_required
  482. def manage_users():
  483. users = service_get_all_users()
  484. return render_template("admin/users.html", users=users)
  485. @admin_bp.route("/users/create", methods=["GET", "POST"])
  486. @admin_required
  487. def create_user():
  488. if request.method == "POST":
  489. username = request.form.get("username")
  490. password = request.form.get("password")
  491. role = request.form.get("role", "admin")
  492. ok, message = service_create_user(username, password, role)
  493. flash(message, "success" if ok else "error")
  494. if ok:
  495. return redirect(url_for("admin.manage_users"))
  496. return render_template("admin/user_form.html", user=None, action="create")
  497. @admin_bp.route("/users/<int:user_id>/edit", methods=["GET", "POST"])
  498. @admin_required
  499. def edit_user(user_id):
  500. if request.method == "POST":
  501. username = request.form.get("username")
  502. password = request.form.get("password")
  503. role = request.form.get("role")
  504. is_active = 1 if request.form.get("is_active") else 0
  505. ok, message = service_update_user(user_id, username, password, role, is_active)
  506. flash(message, "success" if ok else "error")
  507. if ok:
  508. return redirect(url_for("admin.manage_users"))
  509. users = AuthService.get_all_users()
  510. user = next((u for u in users if u["id"] == user_id), None)
  511. if not user:
  512. flash(_("Usuario no encontrado"), "error")
  513. return redirect(url_for("admin.manage_users"))
  514. return render_template("admin/user_form.html", user=user, action="edit")
  515. @admin_bp.route("/users/<int:user_id>/delete", methods=["POST"])
  516. @admin_required
  517. def delete_user(user_id):
  518. ok, message = service_delete_user(user_id)
  519. flash(message, "success" if ok else "error")
  520. return redirect(url_for("admin.manage_users"))
  521. @admin_bp.route("/api/restart-squid", methods=["POST"])
  522. @api_auth_required
  523. def restart_squid():
  524. success, message, details = service_restart_squid()
  525. if success:
  526. return json_success(message)
  527. return json_error(
  528. message or "Could not restart squid",
  529. 500,
  530. details=str(details) if details else None,
  531. )
  532. @admin_bp.route("/api/reload-squid", methods=["POST"])
  533. @api_auth_required
  534. def reload_squid():
  535. success, message, details = service_reload_squid()
  536. if success:
  537. return json_success(message)
  538. return json_error(
  539. message or "Could not reload squid",
  540. 500,
  541. details=str(details) if details else None,
  542. )
  543. # @admin_bp.route("/api/get-tables", methods=["GET"])
  544. # @api_auth_required
  545. # def get_tables():
  546. # resp, code = service_get_tables_info()
  547. # return jsonify(resp), code
  548. @admin_bp.route("/clean-data")
  549. @admin_required
  550. def clean_data():
  551. """View for cleaning database tables."""
  552. return render_template("admin/clean_data.html")
  553. @admin_bp.route("/api/delete-table-data", methods=["POST"])
  554. @api_auth_required
  555. def delete_table_data():
  556. """API endpoint to delete all data from a table."""
  557. try:
  558. data = request.get_json()
  559. table_name = data.get("table_name")
  560. if not table_name:
  561. return jsonify(
  562. {"status": "error", "message": _("Nombre de tabla no proporcionado")}
  563. ), 400
  564. # Validate table name to prevent SQL injection
  565. import re
  566. if not re.match(r"^[a-zA-Z0-9_]+$", table_name):
  567. return jsonify(
  568. {"status": "error", "message": _("Nombre de tabla inválido")}
  569. ), 400
  570. # Prevent deletion of critical tables like admin_users and alembic_version
  571. if table_name == "admin_users" or table_name == "alembic_version":
  572. return jsonify(
  573. {
  574. "status": "error",
  575. "message": _("No se puede eliminar estas tablas críticas"),
  576. }
  577. ), 400
  578. resp, code = service_delete_table_data(table_name)
  579. return jsonify(resp), code
  580. except Exception as e:
  581. logger.exception("Error deleting data from table")
  582. try:
  583. show_details = bool(current_app.debug)
  584. except RuntimeError:
  585. show_details = False
  586. resp = {"status": "error", "message": _("Error interno del servidor")}
  587. if show_details:
  588. resp["details"] = str(e)
  589. return jsonify(resp), 500
  590. @admin_bp.route("/config/split")
  591. @admin_required
  592. def split_config_view():
  593. """Vista para dividir el archivo squid.conf en archivos modulares."""
  594. try:
  595. data = service_get_split_view_data()
  596. return render_template(
  597. "admin/split_config.html",
  598. split_info=data["split_info"],
  599. output_dir=data["output_dir"],
  600. input_file=data["input_file"],
  601. output_exists=data["output_exists"],
  602. files_count=data["files_count"],
  603. )
  604. except Exception as e:
  605. logger.exception("Error al cargar la vista de división de configuración")
  606. try:
  607. show_details = bool(current_app.debug)
  608. except RuntimeError:
  609. show_details = False
  610. if show_details:
  611. flash(_("Error al cargar la vista: %(error)s") % {"error": str(e)}, "error")
  612. else:
  613. flash(_("Error al cargar la vista"), "error")
  614. return redirect(url_for("admin.admin_dashboard"))
  615. @admin_bp.route("/api/split-config", methods=["POST"])
  616. @api_auth_required
  617. def split_config():
  618. """API endpoint para dividir el archivo squid.conf en archivos modulares."""
  619. try:
  620. data = request.get_json() or {}
  621. strict = data.get("strict", False)
  622. resp, code = service_split_config(strict=strict)
  623. # Reload config_manager to detect modular configuration if successful
  624. if code == 200:
  625. global config_manager
  626. config_manager = SquidConfigManager()
  627. logger.info("Config manager reloaded after splitting configuration")
  628. return jsonify(resp), code
  629. except FileNotFoundError as e:
  630. logger.error(f"Archivo no encontrado: {e}")
  631. return jsonify(
  632. {
  633. "status": "error",
  634. "message": _(
  635. "Archivo requerido no encontrado. Verifique la configuración del archivo squid.conf."
  636. ),
  637. }
  638. ), 404
  639. except PermissionError as e:
  640. logger.error(f"Error de permisos: {e}")
  641. return jsonify(
  642. {
  643. "status": "error",
  644. "message": _(
  645. "No se tienen permisos suficientes para crear los archivos"
  646. ),
  647. }
  648. ), 403
  649. except RuntimeError as e:
  650. logger.error(f"Error de validación: {e}")
  651. return jsonify(
  652. {
  653. "status": "error",
  654. "message": _("Error de validación de la configuración"),
  655. }
  656. ), 400
  657. except Exception as e:
  658. logger.exception("Error al dividir el archivo de configuración")
  659. try:
  660. show_details = bool(current_app.debug)
  661. except RuntimeError:
  662. show_details = False
  663. resp = {
  664. "status": "error",
  665. "message": _("Error interno al dividir la configuración"),
  666. }
  667. if show_details:
  668. resp["details"] = str(e)
  669. return jsonify(resp), 500
  670. @admin_bp.route("/api/get-split-files", methods=["GET"])
  671. @api_auth_required
  672. def get_split_files():
  673. """API endpoint para obtener la lista de archivos generados en squid.d."""
  674. splitter = SquidConfigSplitter()
  675. result = service_get_split_files_info(splitter.output_dir)
  676. if result.get("status") == "success":
  677. return jsonify(result)
  678. return jsonify(result), result.get("code", 500)
  679. @admin_bp.route("/blacklist/delete-list", methods=["POST"])
  680. @admin_required
  681. def blacklist_delete_list():
  682. url = request.form.get("source_url")
  683. if not url:
  684. flash(_("URL no proporcionada"), "error")
  685. return redirect(url_for("admin.manage_blacklist"))
  686. count = delete_blacklist_by_source_url(url)
  687. # Also disable enforcement if the list was enforced
  688. _disable_single_blocklist(url, config_manager)
  689. flash(
  690. _("Lista eliminada: %(url)s (%(count)s dominios)")
  691. % {"url": url, "count": count},
  692. "success",
  693. )
  694. return redirect(url_for("admin.manage_blacklist"))
  695. # ---------------------------------------------------------------------------
  696. # Blocklist enforcement helpers & API
  697. # ---------------------------------------------------------------------------
  698. BLOCKLIST_ACL_NAME = "squidstats_blocklist"
  699. def _is_allowed_blocklist_filename(filename: str) -> bool:
  700. """Allow only expected generated blocklist filenames."""
  701. from services.squid.acls_service import BLOCKLIST_PREFIX
  702. if not filename:
  703. return False
  704. # Never allow path separators or traversal sequences in filenames
  705. if os.path.basename(filename) != filename:
  706. return False
  707. if "/" in filename or "\\" in filename or ".." in filename:
  708. return False
  709. pattern = rf"^{re.escape(BLOCKLIST_PREFIX)}(?:custom|[a-f0-9]{{64}})\.txt$"
  710. return bool(re.fullmatch(pattern, filename))
  711. def _build_blocklist_filename(source_url: str | None) -> str:
  712. """Build a deterministic safe filename for a blocklist source URL."""
  713. from services.squid.acls_service import BLOCKLIST_PREFIX
  714. if source_url is None:
  715. filename = f"{BLOCKLIST_PREFIX}custom.txt"
  716. else:
  717. if not _validate_source_url(source_url):
  718. raise ValueError("Invalid source URL")
  719. digest = hashlib.sha256(source_url.encode("utf-8")).hexdigest().lower()
  720. filename = f"{BLOCKLIST_PREFIX}{digest}.txt"
  721. if not _is_allowed_blocklist_filename(filename):
  722. raise ValueError("Invalid blocklist filename")
  723. return filename
  724. def _resolve_safe_blocklist_path(base_dir: str, filename: str) -> str | None:
  725. """Resolve and validate a blocklist file path to prevent path traversal.
  726. Ensures the resolved path is within base_dir using os.path.commonpath.
  727. Returns the safe path or None if traversal is detected.
  728. """
  729. if not _is_allowed_blocklist_filename(filename):
  730. return None
  731. base_dir = os.path.realpath(base_dir)
  732. candidate = os.path.realpath(os.path.join(base_dir, filename))
  733. try:
  734. if os.path.commonpath([base_dir, candidate]) != base_dir:
  735. return None
  736. except ValueError:
  737. # commonpath raises ValueError if paths are on different drives (Windows)
  738. return None
  739. return candidate
  740. def _validate_source_url(source_url: str | None) -> bool:
  741. """Validate that source_url is a well-formed URL."""
  742. if not source_url:
  743. return True # None is allowed for custom lists
  744. from urllib.parse import urlparse
  745. parsed = urlparse(source_url)
  746. # Ensure it's a proper URL with scheme and netloc
  747. if not (parsed.scheme and parsed.netloc):
  748. return False
  749. # Reject URLs with suspicious path traversal patterns
  750. if ".." in source_url or source_url.startswith("/") or "\\" in source_url:
  751. return False
  752. # Additional validation: reject control characters and other suspicious patterns
  753. if any(c in source_url for c in ["\x00", "\n", "\r", "\t"]):
  754. return False
  755. # Ensure URL is reasonably sized to prevent DoS
  756. if len(source_url) > 2048:
  757. return False
  758. return True
  759. def _get_enforced_blocklist_urls(cm) -> set[str]:
  760. """Return the set of source_url values currently enforced as Squid ACLs.
  761. Parses the ACL config to find ``acl squidstats_blocklist dstdomain "..."``
  762. lines and maps each file back to its source_url. Custom lists are
  763. represented by the sentinel ``__custom__``.
  764. """
  765. from services.squid.acls_service import BLOCKLIST_PREFIX
  766. enforced: set[str] = set()
  767. # Read configuration
  768. if cm.is_modular:
  769. content = cm.read_modular_config("100_acls.conf")
  770. else:
  771. content = cm.config_content
  772. if not content:
  773. return enforced
  774. # Pre-fetch all source URLs from DB to avoid queries in loop
  775. session = get_session()
  776. try:
  777. url_to_filename = {}
  778. urls = (
  779. session.query(BlacklistDomain.source_url)
  780. .filter(BlacklistDomain.source_url.isnot(None))
  781. .distinct()
  782. .all()
  783. )
  784. for (url,) in urls:
  785. from services.squid.acls_service import _sanitize_filename
  786. # Current safe naming (hash-based)
  787. try:
  788. url_to_filename[_build_blocklist_filename(url)] = url
  789. except ValueError:
  790. logger.warning("Skipping invalid blacklist source_url in DB mapping")
  791. # Legacy naming fallback for previously generated ACL entries
  792. url_to_filename[_sanitize_filename(url)] = url
  793. finally:
  794. session.close()
  795. for line in content.split("\n"):
  796. stripped = line.strip()
  797. if (
  798. stripped.startswith(f"acl {BLOCKLIST_ACL_NAME} ")
  799. and "dstdomain" in stripped
  800. and BLOCKLIST_PREFIX in stripped
  801. ):
  802. # Extract file path between quotes
  803. start = stripped.find('"')
  804. end = stripped.rfind('"')
  805. if start != -1 and end > start:
  806. filepath = stripped[start + 1 : end]
  807. fname = os.path.basename(filepath)
  808. if fname == f"{BLOCKLIST_PREFIX}custom.txt":
  809. enforced.add("__custom__")
  810. else:
  811. # Lookup source_url from pre-fetched mapping
  812. source_url = url_to_filename.get(fname)
  813. if source_url:
  814. enforced.add(source_url)
  815. return enforced
  816. def _get_enforced_blocklist_paths(cm) -> dict[str, str]:
  817. """Return validated enforced blocklist paths keyed by filename."""
  818. from services.squid.acls_service import (
  819. BLOCKLIST_PREFIX,
  820. _get_blocklists_dir,
  821. )
  822. enforced_paths: dict[str, str] = {}
  823. blocklists_dir = _get_blocklists_dir(cm)
  824. if cm.is_modular:
  825. content = cm.read_modular_config("100_acls.conf")
  826. else:
  827. content = cm.config_content
  828. if not content:
  829. return enforced_paths
  830. for line in content.split("\n"):
  831. stripped = line.strip()
  832. if (
  833. stripped.startswith(f"acl {BLOCKLIST_ACL_NAME} ")
  834. and "dstdomain" in stripped
  835. and BLOCKLIST_PREFIX in stripped
  836. ):
  837. match = re.search(r"""dstdomain\s+["']([^"']+)["']""", stripped)
  838. if not match:
  839. continue
  840. filepath = match.group(1)
  841. filename = os.path.basename(filepath)
  842. safe_path = _resolve_safe_blocklist_path(blocklists_dir, filename)
  843. if safe_path:
  844. enforced_paths[filename] = safe_path
  845. return enforced_paths
  846. def _enable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
  847. """Enable Squid enforcement for a single blocklist (by source_url).
  848. - Writes the domain file for that source.
  849. - Adds the ACL directive.
  850. - Ensures the http_access deny rule exists.
  851. """
  852. from services.squid.acls_service import (
  853. _get_blocklists_dir,
  854. _write_domains_file,
  855. )
  856. # Validate source_url if provided
  857. if source_url is not None and not _validate_source_url(source_url):
  858. return False, "URL de fuente inválida"
  859. session = get_session()
  860. try:
  861. if source_url:
  862. rows = (
  863. session.query(BlacklistDomain.domain)
  864. .filter(
  865. BlacklistDomain.active == 1,
  866. BlacklistDomain.source_url == source_url,
  867. )
  868. .order_by(BlacklistDomain.domain)
  869. .all()
  870. )
  871. label = source_url
  872. else:
  873. rows = (
  874. session.query(BlacklistDomain.domain)
  875. .filter(
  876. BlacklistDomain.active == 1,
  877. BlacklistDomain.source_url.is_(None),
  878. )
  879. .order_by(BlacklistDomain.domain)
  880. .all()
  881. )
  882. label = "custom"
  883. except Exception:
  884. logger.exception("Error consultando dominios para activar blocklist")
  885. return False, "Error al consultar dominios"
  886. finally:
  887. session.close()
  888. try:
  889. filename = _build_blocklist_filename(source_url if source_url else None)
  890. except ValueError:
  891. return False, "URL de fuente inválida"
  892. domains = [d[0] for d in rows]
  893. if not domains:
  894. return False, f"No hay dominios activos para '{label}'"
  895. # Write file
  896. blocklists_dir = _get_blocklists_dir(cm)
  897. safe_path = _resolve_safe_blocklist_path(blocklists_dir, filename)
  898. if not safe_path:
  899. logger.error("Path traversal blocked for source: %s", label)
  900. return False, f"Nombre de archivo inválido para: '{label}'"
  901. ok, written_count = _write_domains_file(safe_path, domains, blocklists_dir)
  902. if not ok:
  903. return False, f"Error escribiendo archivo para '{label}'"
  904. # Add ACL directive (append without removing others)
  905. acl_line = f'acl {BLOCKLIST_ACL_NAME} dstdomain "{safe_path}"'
  906. comment_line = f"# Blocklist: {label} ({written_count} dominios)"
  907. try:
  908. if cm.is_modular:
  909. acl_content = cm.read_modular_config("100_acls.conf")
  910. if acl_content is not None:
  911. lines = acl_content.split("\n")
  912. # Remove only this specific file's ACL if it exists already
  913. lines = [
  914. ln
  915. for ln in lines
  916. if not (
  917. ln.strip() == acl_line
  918. or ln.strip() == acl_line.replace('"', "'")
  919. )
  920. ]
  921. # Remove orphaned comments for this label
  922. lines = [ln for ln in lines if not ln.strip() == comment_line]
  923. lines.append(comment_line)
  924. lines.append(acl_line)
  925. new_content = "\n".join(lines)
  926. if not cm.save_modular_config("100_acls.conf", new_content):
  927. return False, "Error guardando ACL en config modular"
  928. else:
  929. return False, "No se pudo leer la config modular"
  930. else:
  931. lines = cm.config_content.split("\n")
  932. lines = [
  933. ln
  934. for ln in lines
  935. if not (
  936. ln.strip() == acl_line or ln.strip() == acl_line.replace('"', "'")
  937. )
  938. ]
  939. lines = [ln for ln in lines if not ln.strip() == comment_line]
  940. acl_section_end = -1
  941. for i, line in enumerate(lines):
  942. if line.strip().startswith("acl "):
  943. acl_section_end = i
  944. if acl_section_end != -1:
  945. lines.insert(acl_section_end + 1, comment_line)
  946. lines.insert(acl_section_end + 2, acl_line)
  947. else:
  948. lines.append(comment_line)
  949. lines.append(acl_line)
  950. new_content = "\n".join(lines)
  951. cm.save_config(new_content)
  952. except Exception:
  953. logger.exception("Error agregando ACL para blocklist individual")
  954. return False, "Error al agregar ACL"
  955. # Ensure http_access deny rule exists
  956. ok, msg = service_add_http_deny_blocklist(BLOCKLIST_ACL_NAME, cm)
  957. if not ok:
  958. return False, msg
  959. return True, f"Blocklist '{label}' activada con {len(domains)} dominios"
  960. def _disable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
  961. """Disable Squid enforcement for a single blocklist.
  962. - Removes the ACL line for this source.
  963. - Deletes the domain file.
  964. - If no blocklist ACLs remain, also removes the http_access deny rule.
  965. """
  966. # Validate source_url if provided
  967. if source_url is not None:
  968. if not isinstance(source_url, str):
  969. return False, "Formato de URL inválido"
  970. if not _validate_source_url(source_url):
  971. return False, "URL de fuente inválida"
  972. if source_url:
  973. label = source_url
  974. else:
  975. label = "custom"
  976. try:
  977. candidate_filename = _build_blocklist_filename(
  978. source_url if source_url else None
  979. )
  980. except ValueError:
  981. return False, "URL de fuente inválida"
  982. enforced_paths = _get_enforced_blocklist_paths(cm)
  983. safe_path = enforced_paths.get(candidate_filename)
  984. if not safe_path:
  985. return False, f"Blocklist '{label}' no está activada"
  986. acl_line = f'acl {BLOCKLIST_ACL_NAME} dstdomain "{safe_path}"'
  987. # Remove ACL directive
  988. try:
  989. if cm.is_modular:
  990. acl_content = cm.read_modular_config("100_acls.conf")
  991. if acl_content is not None:
  992. lines = acl_content.split("\n")
  993. new_lines = []
  994. for ln in lines:
  995. stripped = ln.strip()
  996. if stripped == acl_line or stripped == acl_line.replace('"', "'"):
  997. # Also remove the comment above
  998. if new_lines and new_lines[-1].strip().startswith(
  999. "# Blocklist:"
  1000. ):
  1001. new_lines.pop()
  1002. continue
  1003. new_lines.append(ln)
  1004. new_content = "\n".join(new_lines)
  1005. cm.save_modular_config("100_acls.conf", new_content)
  1006. lines = cm.config_content.split("\n")
  1007. new_lines = []
  1008. for ln in lines:
  1009. stripped = ln.strip()
  1010. if stripped == acl_line or stripped == acl_line.replace('"', "'"):
  1011. if new_lines and new_lines[-1].strip().startswith("# Blocklist:"):
  1012. new_lines.pop()
  1013. continue
  1014. new_lines.append(ln)
  1015. new_content = "\n".join(new_lines)
  1016. cm.save_config(new_content)
  1017. except Exception:
  1018. logger.exception("Error eliminando ACL de blocklist individual")
  1019. return False, "Error al eliminar ACL"
  1020. # Delete file
  1021. if os.path.isfile(safe_path):
  1022. try:
  1023. st = os.lstat(safe_path)
  1024. if not stat.S_ISREG(st.st_mode):
  1025. logger.error(f"Archivo no regular: {safe_path}")
  1026. return False, "Archivo no regular"
  1027. os.remove(safe_path)
  1028. except OSError:
  1029. logger.exception(f"Error eliminando archivo: {safe_path}")
  1030. # Check if any blocklist ACLs remain; if not, remove http_access deny rule too
  1031. remaining = _get_enforced_blocklist_urls(cm)
  1032. if not remaining:
  1033. service_remove_http_deny_blocklist(BLOCKLIST_ACL_NAME, cm)
  1034. return True, f"Blocklist '{label}' desactivada"
  1035. @admin_bp.route("/api/blocklist/toggle", methods=["POST"])
  1036. @api_auth_required
  1037. def blocklist_toggle():
  1038. """Toggle Squid enforcement for a single blocklist.
  1039. Expects JSON: ``{"source_url": "...", "enable": true/false}``
  1040. Use ``source_url: null`` for the custom/manual list.
  1041. """
  1042. data = request.get_json()
  1043. if data is None:
  1044. return jsonify({"status": "error", "message": _("JSON inválido")}), 400
  1045. source_url = data.get("source_url") # None for custom
  1046. enable = data.get("enable", False)
  1047. try:
  1048. if enable:
  1049. ok, msg = _enable_single_blocklist(source_url, config_manager)
  1050. else:
  1051. ok, msg = _disable_single_blocklist(source_url, config_manager)
  1052. if ok:
  1053. return jsonify({"status": "success", "message": msg})
  1054. return jsonify({"status": "error", "message": msg}), 400
  1055. except Exception as e:
  1056. logger.exception("Error en toggle de blocklist")
  1057. try:
  1058. show_details = bool(current_app.debug)
  1059. except RuntimeError:
  1060. show_details = False
  1061. resp = {
  1062. "status": "error",
  1063. "message": _("Error interno al cambiar estado de blocklist"),
  1064. }
  1065. if show_details:
  1066. resp["details"] = str(e)
  1067. return jsonify(resp), 500