admin_routes.py 41 KB

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