| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468 |
- import re
- from loguru import logger
- _KERBEROS_ACCESS_START = "# BEGIN SquidStats Kerberos access rule"
- _KERBEROS_ACCESS_END = "# END SquidStats Kerberos access rule"
- _KERBEROS_CHALLENGE_RE = re.compile(r"^http_access\s+deny\s+!\S+\s*$", re.I)
- def _is_local_cache_manager_allow(parts: list[str]) -> bool:
- """Recognise either conventional order of the local manager exception.
- Squid evaluates ACLs in an access rule as a conjunction, so both
- ``allow manager localhost`` and ``allow localhost manager`` are the
- conventional narrow exception. Do not accept extra/negated ACLs here:
- generic edits must not gain a way to place a client allow before the
- Kerberos challenge.
- """
- lowered = [part.casefold() for part in parts]
- return (
- len(lowered) == 4
- and lowered[:2] == ["http_access", "allow"]
- and set(lowered[2:]) == {"manager", "localhost"}
- )
- def _find_http_lines(lines):
- return [
- i
- for i, line in enumerate(lines)
- if line.strip().startswith("http_access ") and not line.strip().startswith("#")
- ]
- def _is_managed_kerberos_access_line(lines: list[str], line_index: int) -> bool:
- """Return whether an HTTP rule belongs to the Kerberos managed block."""
- in_kerberos_block = False
- for index, line in enumerate(lines):
- marker = line.strip()
- if marker == _KERBEROS_ACCESS_START:
- in_kerberos_block = True
- elif marker == _KERBEROS_ACCESS_END:
- in_kerberos_block = False
- if index == line_index:
- return in_kerberos_block
- return False
- def _editable_http_line(
- lines: list[str], http_lines_indices: list[int], rule_index: int
- ) -> tuple[int | None, str | None]:
- """Resolve a UI index while preserving the dedicated Kerberos rule."""
- if rule_index < 0 or rule_index >= len(http_lines_indices):
- return None, "Índice de regla inválido"
- line_index = http_lines_indices[rule_index]
- if _is_managed_kerberos_access_line(lines, line_index):
- return (
- None,
- "La regla Kerberos administrada se modifica desde Kerberos / SPNEGO, no desde HTTP Access.",
- )
- return line_index, None
- def _kerberos_policy_error(lines: list[str]) -> str | None:
- """Reject an edit that would put a normal allow before Kerberos.
- The dedicated screen owns the challenge line, but changing a neighboring
- rule through the generic editor can be equally dangerous. A narrow local
- Cache Manager exception is the only positive allow permitted beforehand.
- """
- starts = [
- index
- for index, line in enumerate(lines)
- if line.strip() == _KERBEROS_ACCESS_START
- ]
- ends = [
- index
- for index, line in enumerate(lines)
- if line.strip() == _KERBEROS_ACCESS_END
- ]
- if not starts and not ends:
- return None
- if len(starts) != 1 or len(ends) != 1 or ends[0] <= starts[0]:
- return (
- "El bloque Kerberos administrado está incompleto; revísalo desde "
- "Kerberos / SPNEGO antes de modificar reglas HTTP Access."
- )
- challenge_indices = [
- index
- for index in range(starts[0] + 1, ends[0])
- if _KERBEROS_CHALLENGE_RE.fullmatch(
- lines[index].strip().split("#", 1)[0].strip()
- )
- ]
- if len(challenge_indices) != 1:
- return (
- "No se pudo verificar el desafío Kerberos administrado; modifica "
- "la política desde Kerberos / SPNEGO."
- )
- for line in lines[: challenge_indices[0]]:
- parts = line.strip().split("#", 1)[0].strip().split()
- lowered = [part.casefold() for part in parts]
- if lowered[:2] != ["http_access", "allow"]:
- continue
- if _is_local_cache_manager_allow(parts):
- continue
- return (
- "La regla dejaría un allow antes del desafío Kerberos. Modifica la "
- "política desde Kerberos / SPNEGO o conserva solo la excepción local del manager."
- )
- return None
- def delete_http_access(rule_index: int, config_manager) -> tuple[bool, str]:
- try:
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- line_index, error = _editable_http_line(
- lines, http_lines_indices, rule_index
- )
- if error:
- return False, error
- # remove the line
- del lines[line_index]
- new_content = "\n".join(lines)
- if config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return True, "Regla HTTP Access eliminada exitosamente"
- else:
- return False, "Error al eliminar la regla modular"
- # Fallback to main config
- lines = config_manager.config_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- line_index, error = _editable_http_line(lines, http_lines_indices, rule_index)
- if error:
- return False, error
- del lines[line_index]
- new_content = "\n".join(lines)
- if config_manager.save_config(new_content):
- return True, "Regla HTTP Access eliminada exitosamente"
- return False, "Error al eliminar la regla HTTP Access"
- except Exception:
- logger.exception("Error eliminando http_access")
- return False, "Error interno al eliminar regla http_access"
- def edit_http_access(
- rule_index: int, action: str, acls: list, description: str, config_manager
- ) -> tuple[bool, str]:
- try:
- acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
- if not acl_string:
- return False, "Debe especificar al menos una ACL"
- new_rule = f"http_access {action} {acl_string}"
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- i, error = _editable_http_line(lines, http_lines_indices, rule_index)
- if error:
- return False, error
- if description:
- if i > 0 and lines[i - 1].strip().startswith("#"):
- lines[i - 1] = f"# {description}"
- else:
- lines.insert(i, f"# {description}")
- i += 1
- lines[i] = new_rule
- if error := _kerberos_policy_error(lines):
- return False, error
- new_content = "\n".join(lines)
- if config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return True, "Regla HTTP Access actualizada exitosamente"
- else:
- return False, "Error al guardar regla modular"
- # Fallback to main config
- lines = config_manager.config_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- i, error = _editable_http_line(lines, http_lines_indices, rule_index)
- if error:
- return False, error
- if description:
- if i > 0 and lines[i - 1].strip().startswith("#"):
- lines[i - 1] = f"# {description}"
- else:
- lines.insert(i, f"# {description}")
- i += 1
- lines[i] = new_rule
- if error := _kerberos_policy_error(lines):
- return False, error
- new_content = "\n".join(lines)
- if config_manager.save_config(new_content):
- return True, "Regla HTTP Access actualizada exitosamente"
- return False, "Error al guardar la regla HTTP Access"
- except Exception:
- logger.exception("Error actualizando http_access")
- return False, "Error interno al actualizar regla http_access"
- def add_http_access(
- action: str, acls: list, description: str, config_manager
- ) -> tuple[bool, str]:
- try:
- acl_string = " ".join([acl.strip() for acl in acls if acl.strip()])
- if not acl_string:
- return False, "Debe especificar al menos una ACL"
- new_rule = f"http_access {action} {acl_string}"
- lines_to_add = []
- if description:
- lines_to_add.append(f"# {description}")
- lines_to_add.append(new_rule)
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- lines.extend(lines_to_add)
- new_content = "\n".join(lines)
- if config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return True, "Regla HTTP Access agregada exitosamente"
- else:
- return False, "Error al guardar regla modular"
- lines = config_manager.config_content.split("\n")
- lines.extend(lines_to_add)
- new_content = "\n".join(lines)
- if config_manager.save_config(new_content):
- return True, "Regla HTTP Access agregada exitosamente"
- return False, "Error al guardar la regla HTTP Access"
- except Exception:
- logger.exception("Error agregando http_access")
- return False, "Error interno al agregar regla http_access"
- def add_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
- """Add an ``http_access deny <acl_name>`` rule for the blocklist.
- The deny rule is inserted **before** the first ``http_access allow`` rule
- so that blocked domains are rejected before any allow rule can match.
- If a deny rule for this ACL already exists, it is not duplicated.
- Args:
- acl_name: Name of the blocklist ACL (must match the ACL created by
- :func:`add_acl_blocklist`).
- config_manager: A :class:`SquidConfigManager` instance.
- Returns:
- ``(success, message)`` tuple.
- """
- if not acl_name:
- return False, "Debe proporcionar el nombre de la ACL de blocklist"
- deny_rule = f"http_access deny {acl_name}"
- comment = f"# Deny blocklist gestionada por SquidStats ({acl_name})"
- try:
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- # Check if the deny rule already exists
- for line in lines:
- if line.strip() == deny_rule:
- return True, f"La regla deny para '{acl_name}' ya existe"
- # Find the first http_access allow to insert before it
- insert_idx = len(lines)
- for i, line in enumerate(lines):
- stripped = line.strip()
- if stripped.startswith("http_access allow"):
- insert_idx = i
- break
- lines.insert(insert_idx, comment)
- lines.insert(insert_idx + 1, deny_rule)
- new_content = "\n".join(lines)
- if config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return (
- True,
- f"Regla 'http_access deny {acl_name}' agregada exitosamente",
- )
- else:
- return False, "Error al guardar regla deny modular"
- # Fallback to main config
- lines = config_manager.config_content.split("\n")
- for line in lines:
- if line.strip() == deny_rule:
- return True, f"La regla deny para '{acl_name}' ya existe"
- insert_idx = len(lines)
- for i, line in enumerate(lines):
- stripped = line.strip()
- if stripped.startswith("http_access allow"):
- insert_idx = i
- break
- lines.insert(insert_idx, comment)
- lines.insert(insert_idx + 1, deny_rule)
- new_content = "\n".join(lines)
- if config_manager.save_config(new_content):
- return (
- True,
- f"Regla 'http_access deny {acl_name}' agregada exitosamente",
- )
- return False, "Error al guardar la regla deny"
- except Exception:
- logger.exception("Error agregando http_access deny para blocklist")
- return False, "Error interno al agregar regla http_access deny"
- def remove_http_deny_blocklist(acl_name: str, config_manager) -> tuple[bool, str]:
- """Remove the ``http_access deny <acl_name>`` rule and its comment.
- Supports both modular (``120_http_access.conf``) and monolithic config.
- Args:
- acl_name: Name of the blocklist ACL whose deny rule should be removed.
- config_manager: A :class:`SquidConfigManager` instance.
- Returns:
- ``(success, message)`` tuple.
- """
- if not acl_name:
- return False, "Debe proporcionar el nombre de la ACL de blocklist"
- deny_rule = f"http_access deny {acl_name}"
- def _strip_deny(lines: list[str]) -> list[str]:
- """Return lines without the deny rule and its preceding comment."""
- result: list[str] = []
- # skip_next = False
- i = 0
- while i < len(lines):
- stripped = lines[i].strip()
- # Check if this is our deny rule
- if stripped == deny_rule:
- # Also remove the comment immediately above if it belongs to us
- if result and result[-1].strip().startswith(
- "# Deny blocklist gestionada por SquidStats"
- ):
- result.pop()
- i += 1
- continue
- result.append(lines[i])
- i += 1
- return result
- try:
- removed = False
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- cleaned = _strip_deny(lines)
- if len(cleaned) != len(lines):
- removed = True
- new_content = "\n".join(cleaned)
- if not config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return False, "Error guardando config modular de http_access"
- # Also clean main config
- lines = config_manager.config_content.split("\n")
- cleaned = _strip_deny(lines)
- if len(cleaned) != len(lines):
- removed = True
- new_content = "\n".join(cleaned)
- if not config_manager.save_config(new_content):
- return False, "Error guardando config principal de http_access"
- if removed:
- return (
- True,
- f"Regla 'http_access deny {acl_name}' eliminada exitosamente",
- )
- return True, f"No se encontró regla deny para '{acl_name}' (ya eliminada)"
- except Exception:
- logger.exception("Error eliminando http_access deny para blocklist")
- return False, "Error interno al eliminar regla http_access deny"
- def move_http_access(
- rule_index: int, direction: str, config_manager
- ) -> tuple[bool, str]:
- try:
- if config_manager.is_modular:
- http_content = config_manager.read_modular_config("120_http_access.conf")
- if http_content is not None:
- lines = http_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- current, error = _editable_http_line(
- lines, http_lines_indices, rule_index
- )
- if error:
- return False, error
- if direction == "up" and rule_index > 0:
- target = http_lines_indices[rule_index - 1]
- if _is_managed_kerberos_access_line(lines, target):
- return (
- False,
- "No se puede mover una regla a través del bloque Kerberos administrado.",
- )
- lines[current], lines[target] = lines[target], lines[current]
- elif direction == "down" and rule_index < len(http_lines_indices) - 1:
- target = http_lines_indices[rule_index + 1]
- if _is_managed_kerberos_access_line(lines, target):
- return (
- False,
- "No se puede mover una regla a través del bloque Kerberos administrado.",
- )
- lines[current], lines[target] = lines[target], lines[current]
- new_content = "\n".join(lines)
- if config_manager.save_modular_config(
- "120_http_access.conf", new_content
- ):
- return True, "Regla movida exitosamente"
- return False, "Error al guardar regla modular"
- lines = config_manager.config_content.split("\n")
- http_lines_indices = _find_http_lines(lines)
- current, error = _editable_http_line(lines, http_lines_indices, rule_index)
- if error:
- return False, error
- if direction == "up" and rule_index > 0:
- target = http_lines_indices[rule_index - 1]
- if _is_managed_kerberos_access_line(lines, target):
- return (
- False,
- "No se puede mover una regla a través del bloque Kerberos administrado.",
- )
- lines[current], lines[target] = lines[target], lines[current]
- elif direction == "down" and rule_index < len(http_lines_indices) - 1:
- target = http_lines_indices[rule_index + 1]
- if _is_managed_kerberos_access_line(lines, target):
- return (
- False,
- "No se puede mover una regla a través del bloque Kerberos administrado.",
- )
- lines[current], lines[target] = lines[target], lines[current]
- new_content = "\n".join(lines)
- if config_manager.save_config(new_content):
- return True, "Regla movida exitosamente"
- return False, "Error al guardar la regla HTTP Access"
- except Exception:
- logger.exception("Error moviendo http_access")
- return False, "Error interno al mover regla http_access"
|