kerberos_config_service.py 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361
  1. """Managed Kerberos/SPNEGO configuration for Squid.
  2. This module deliberately manages the Squid configuration, not the LDAP client
  3. configuration used by SquidStats itself. A Kerberos keytab is never uploaded,
  4. stored, or returned by this module: an administrator provisions it on the
  5. Squid host and this service only references its path.
  6. """
  7. from __future__ import annotations
  8. import fnmatch
  9. import glob
  10. import ipaddress
  11. import json
  12. import os
  13. import pwd
  14. import re
  15. import shutil
  16. import stat
  17. import subprocess # nosec B404 - commands below use fixed executable/arguments
  18. import threading
  19. from collections.abc import Callable, Mapping
  20. from dataclasses import asdict, dataclass
  21. from pathlib import Path, PurePosixPath
  22. from typing import Any
  23. from loguru import logger
  24. from utils.admin import squid_config_write_lock
  25. from utils.custom_types import PREDEFINED_ACLS
  26. AUTH_MODULE_FILENAME = "50_auth.conf"
  27. ACL_MODULE_FILENAME = "100_acls.conf"
  28. HTTP_ACCESS_MODULE_FILENAME = "120_http_access.conf"
  29. MANAGED_AUTH_START = "# BEGIN SquidStats Kerberos authentication"
  30. MANAGED_AUTH_END = "# END SquidStats Kerberos authentication"
  31. MANAGED_ACCESS_START = "# BEGIN SquidStats Kerberos access rule"
  32. MANAGED_ACCESS_END = "# END SquidStats Kerberos access rule"
  33. # Markers used by the experimental implementation that was never merged into
  34. # main. Recognising them lets an administrator migrate away from its unsafe
  35. # block (which mixed http_access into the auth module) without duplicate rules.
  36. LEGACY_MANAGED_AUTH_START = "# SQUIDSTATS KERBEROS AUTH START"
  37. LEGACY_MANAGED_AUTH_END = "# SQUIDSTATS KERBEROS AUTH END"
  38. DEFAULT_HELPER_PATH = "/usr/lib/squid/negotiate_kerberos_auth"
  39. DEFAULT_KEYTAB_PATH = "/var/run/squid/HTTP.keytab"
  40. DEFAULT_ACL_NAME = "kerberos_auth"
  41. DEFAULT_DOCKER_CONTAINER = "squid_proxy"
  42. DEFAULT_DOCKER_CONFIG_PATH = "/etc/squid/squid.conf"
  43. _MAX_INCLUDED_CONFIG_BYTES = 1024 * 1024
  44. # The Debian unit deliberately uses ``manual``: ``ProtectSystem=full`` keeps
  45. # /etc read-only for the unprivileged web process. Keep the default managed
  46. # for source, container, and legacy deployments; if an operator sets an
  47. # unrecognised value, fail closed rather than presenting write controls that
  48. # will fail under a hardened unit.
  49. _SQUID_CONFIG_WRITE_MODE_ENV = "SQUIDSTATS_SQUID_CONFIG_WRITE_MODE"
  50. _SQUID_CONFIG_WRITE_MODE_MANAGED = "managed"
  51. _SQUID_CONFIG_WRITE_MODE_MANUAL = "manual"
  52. # This is the quota feature's generated ACL/rule pair. A ``proxy_auth`` ACL
  53. # can itself make Squid look up credentials, so it must run after the
  54. # Kerberos challenge (and the local Cache Manager exception) when both
  55. # features are active. Keep the handling deliberately narrow: arbitrary
  56. # administrator-owned proxy_auth rules are not reordered here.
  57. _QUOTA_PROXY_AUTH_ACL_NAME = "usuarios_bloqueados"
  58. _QUOTA_PROXY_AUTH_DENY = "http_access deny usuarios_bloqueados"
  59. _SAFE_PATH_RE = re.compile(r"^/[A-Za-z0-9._+/@:=,-]+$")
  60. _PRINCIPAL_RE = re.compile(
  61. r"^HTTP/[A-Za-z0-9][A-Za-z0-9.-]*(?:@[A-Za-z0-9][A-Za-z0-9._-]*)?$"
  62. )
  63. _ACL_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
  64. _CONTAINER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
  65. _RUNTIME_USER_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.:-]*$")
  66. _SQUID_VERSION_RE = re.compile(r"Squid Cache:\s*Version\s+(\d+(?:\.\d+)*)", re.I)
  67. _SQUID_DEFAULT_USER_RE = re.compile(
  68. r"--with-default-user(?:=|\s+)(?:'([^']+)'|\"([^\"]+)\"|([^\s'\"]+))"
  69. )
  70. _HTTP_ACCESS_RE = re.compile(r"^http_access\s+(allow|deny)\s+(.+)$", re.I)
  71. _INCLUDE_RE = re.compile(r"^include\s+(.+)$", re.I)
  72. _CACHE_EFFECTIVE_USER_RE = re.compile(r"^cache_effective_user\s+(\S+)", re.I)
  73. _PORT_DIRECTIVE_RE = re.compile(r"^(?:http|https)_port\b", re.I)
  74. _RESERVED_ACL_NAMES = {name.casefold() for name in PREDEFINED_ACLS}
  75. _RUNTIME_PREFERENCES = frozenset({"auto", "local", "docker"})
  76. _APPLY_LOCK = threading.RLock()
  77. class KerberosConfigurationError(ValueError):
  78. """A configuration error safe to display to an administrator."""
  79. def _squid_config_write_mode() -> str:
  80. """Return whether this deployment permits panel-managed Squid writes.
  81. The setting is an explicit deployment contract, rather than an unreliable
  82. attempt to infer systemd mount namespaces from the web process. It is
  83. intentionally not a privilege grant: a package administrator must first
  84. deploy a narrowly scoped, audited write mechanism before opting in.
  85. """
  86. configured = os.getenv(_SQUID_CONFIG_WRITE_MODE_ENV, "").strip().casefold()
  87. if not configured or configured == _SQUID_CONFIG_WRITE_MODE_MANAGED:
  88. return _SQUID_CONFIG_WRITE_MODE_MANAGED
  89. return _SQUID_CONFIG_WRITE_MODE_MANUAL
  90. def _manual_squid_write_message() -> str | None:
  91. """Explain the packaged read-only mode without suggesting unsafe grants."""
  92. if _squid_config_write_mode() != _SQUID_CONFIG_WRITE_MODE_MANUAL:
  93. return None
  94. return (
  95. "Este despliegue ejecuta SquidStats en modo manual para squid.conf. "
  96. "La unidad Debian incluida protege /etc/squid y no permite escrituras desde el panel. "
  97. "Puedes copiar la vista previa y aplicarla mediante el procedimiento administrativo "
  98. "controlado. No cambies este modo hasta disponer de un mecanismo privilegiado "
  99. "restringido y auditado."
  100. )
  101. @dataclass(frozen=True)
  102. class KerberosSettings:
  103. """Values accepted by the Kerberos configuration form/API."""
  104. enabled: bool = False
  105. helper_path: str = DEFAULT_HELPER_PATH
  106. keytab_path: str = DEFAULT_KEYTAB_PATH
  107. service_principal: str = ""
  108. children: int = 10
  109. startup: int = 5
  110. idle: int = 3
  111. keep_alive: bool = True
  112. strip_realm: bool = False
  113. acl_name: str = DEFAULT_ACL_NAME
  114. enforce_auth: bool = True
  115. replace_existing_negotiate: bool = False
  116. reload_squid: bool = True
  117. def to_dict(self) -> dict[str, Any]:
  118. return asdict(self)
  119. @dataclass
  120. class _ConfigTarget:
  121. """An in-memory editable Squid configuration target."""
  122. name: str
  123. path: Path
  124. original: str
  125. content: str
  126. existed: bool
  127. save: Callable[[str], bool]
  128. @dataclass(frozen=True)
  129. class _SquidRuntime:
  130. """A local Squid binary or a running Docker container with Squid."""
  131. kind: str
  132. executable: str
  133. container_name: str | None = None
  134. container_config_path: str | None = None
  135. def default_settings() -> KerberosSettings:
  136. """Return safe form defaults without inventing a domain-specific SPN."""
  137. return KerberosSettings()
  138. def _as_bool(value: Any, default: bool = False) -> bool:
  139. if value is None:
  140. return default
  141. if isinstance(value, bool):
  142. return value
  143. if isinstance(value, (int, float)):
  144. return bool(value)
  145. return str(value).strip().casefold() in {"1", "true", "yes", "on", "si", "sí"}
  146. def _text(data: Mapping[str, Any], key: str, default: str = "") -> str:
  147. value = data.get(key, default)
  148. return str(value if value is not None else default).strip()
  149. def _integer(
  150. data: Mapping[str, Any], key: str, default: int, minimum: int, maximum: int
  151. ) -> int:
  152. raw_value = data.get(key, default)
  153. if raw_value is None or str(raw_value).strip() == "":
  154. return default
  155. try:
  156. value = int(str(raw_value).strip())
  157. except (TypeError, ValueError) as exc:
  158. raise KerberosConfigurationError(
  159. f"{key} debe ser un número entero entre {minimum} y {maximum}."
  160. ) from exc
  161. if not minimum <= value <= maximum:
  162. raise KerberosConfigurationError(
  163. f"{key} debe estar entre {minimum} y {maximum}."
  164. )
  165. return value
  166. def _validate_path(value: str, field_name: str) -> str:
  167. if not value:
  168. raise KerberosConfigurationError(f"Debes indicar {field_name}.")
  169. if not _SAFE_PATH_RE.fullmatch(value):
  170. raise KerberosConfigurationError(
  171. f"{field_name} debe ser una ruta absoluta sin espacios ni caracteres "
  172. "que puedan alterar squid.conf."
  173. )
  174. return value
  175. def _validate_principal(value: str) -> str:
  176. if not _PRINCIPAL_RE.fullmatch(value) or "\\" in value:
  177. raise KerberosConfigurationError(
  178. "El SPN debe tener el formato HTTP/proxy.ejemplo@REALM "
  179. "(o HTTP/proxy.ejemplo si Kerberos resuelve el realm predeterminado), "
  180. "sin barras de escape."
  181. )
  182. hostname = value.split("/", 1)[1].split("@", 1)[0]
  183. if "." not in hostname:
  184. raise KerberosConfigurationError(
  185. "El SPN debe usar el FQDN real que utilizan los clientes para el proxy."
  186. )
  187. return value
  188. def _keytab_contains_principal(output: str, service_principal: str) -> bool:
  189. """Match a service principal in ``klist`` output without prefix matches.
  190. An explicit realm is preferred. The helper also permits ``HTTP/fqdn`` and
  191. resolves its default realm, so accept any keytab principal with exactly
  192. that service/host portion in that case.
  193. """
  194. principals = re.findall(
  195. r"HTTP/[A-Za-z0-9][A-Za-z0-9.-]*(?:@[A-Za-z0-9][A-Za-z0-9._-]*)?",
  196. output,
  197. flags=re.IGNORECASE,
  198. )
  199. expected_service_host, separator, expected_realm = service_principal.partition("@")
  200. for principal in principals:
  201. candidate_service_host, candidate_separator, candidate_realm = (
  202. principal.partition("@")
  203. )
  204. # DNS host names are case-insensitive, while a Kerberos realm is an
  205. # opaque, case-sensitive component. Folding the complete principal
  206. # would turn ``@realm`` into a false match for ``@REALM``.
  207. if candidate_service_host.casefold() != expected_service_host.casefold():
  208. continue
  209. if not separator:
  210. return True
  211. if candidate_separator and candidate_realm == expected_realm:
  212. return True
  213. return False
  214. def normalise_settings(data: Mapping[str, Any] | None) -> KerberosSettings:
  215. """Validate and normalise form or JSON data before it reaches squid.conf."""
  216. data = data or {}
  217. defaults = default_settings()
  218. enabled = _as_bool(data.get("enabled"), defaults.enabled)
  219. # A recovery/disable action must still work when an administrator has
  220. # cleared or mistyped another form field. None of those values is emitted
  221. # while the feature is disabled.
  222. if not enabled:
  223. return KerberosSettings(
  224. enabled=False,
  225. helper_path=_text(data, "helper_path", defaults.helper_path),
  226. keytab_path=_text(data, "keytab_path", defaults.keytab_path),
  227. service_principal=_text(
  228. data, "service_principal", defaults.service_principal
  229. ),
  230. children=defaults.children,
  231. startup=defaults.startup,
  232. idle=defaults.idle,
  233. keep_alive=_as_bool(data.get("keep_alive"), defaults.keep_alive),
  234. strip_realm=_as_bool(data.get("strip_realm"), defaults.strip_realm),
  235. acl_name=_text(data, "acl_name", defaults.acl_name),
  236. enforce_auth=_as_bool(data.get("enforce_auth"), defaults.enforce_auth),
  237. replace_existing_negotiate=_as_bool(
  238. data.get("replace_existing_negotiate"),
  239. defaults.replace_existing_negotiate,
  240. ),
  241. reload_squid=_as_bool(data.get("reload_squid"), defaults.reload_squid),
  242. )
  243. children = _integer(data, "children", defaults.children, 1, 128)
  244. startup = _integer(data, "startup", defaults.startup, 0, 128)
  245. idle = _integer(data, "idle", defaults.idle, 0, 128)
  246. if startup > children:
  247. raise KerberosConfigurationError("startup no puede ser mayor que children.")
  248. if idle > children:
  249. raise KerberosConfigurationError("idle no puede ser mayor que children.")
  250. settings = KerberosSettings(
  251. enabled=enabled,
  252. helper_path=_text(data, "helper_path", defaults.helper_path),
  253. keytab_path=_text(data, "keytab_path", defaults.keytab_path),
  254. service_principal=_text(data, "service_principal", defaults.service_principal),
  255. children=children,
  256. startup=startup,
  257. idle=idle,
  258. keep_alive=_as_bool(data.get("keep_alive"), defaults.keep_alive),
  259. strip_realm=_as_bool(data.get("strip_realm"), defaults.strip_realm),
  260. acl_name=_text(data, "acl_name", defaults.acl_name),
  261. enforce_auth=_as_bool(data.get("enforce_auth"), defaults.enforce_auth),
  262. replace_existing_negotiate=_as_bool(
  263. data.get("replace_existing_negotiate"),
  264. defaults.replace_existing_negotiate,
  265. ),
  266. reload_squid=_as_bool(data.get("reload_squid"), defaults.reload_squid),
  267. )
  268. helper_path = _validate_path(settings.helper_path, "la ruta del helper")
  269. keytab_path = _validate_path(settings.keytab_path, "la ruta del keytab")
  270. service_principal = _validate_principal(settings.service_principal)
  271. if not _ACL_NAME_RE.fullmatch(settings.acl_name):
  272. raise KerberosConfigurationError(
  273. "El nombre de ACL solo puede contener letras, números, guion y guion bajo."
  274. )
  275. if settings.acl_name.casefold() in _RESERVED_ACL_NAMES:
  276. raise KerberosConfigurationError(
  277. "El nombre de ACL no puede reemplazar una ACL predefinida de Squid."
  278. )
  279. return KerberosSettings(
  280. **{
  281. **settings.to_dict(),
  282. "helper_path": helper_path,
  283. "keytab_path": keytab_path,
  284. "service_principal": service_principal,
  285. }
  286. )
  287. def _validated_settings(
  288. data: KerberosSettings | Mapping[str, Any] | None,
  289. ) -> KerberosSettings:
  290. """Validate settings even when an internal caller supplies a dataclass."""
  291. if isinstance(data, KerberosSettings):
  292. return normalise_settings(data.to_dict())
  293. return normalise_settings(data)
  294. def _uncommented(line: str) -> str:
  295. """Return a directive without its trailing Squid comment."""
  296. return line.split("#", 1)[0].strip()
  297. def _logical_squid_lines(content: str) -> list[str]:
  298. """Join Squid continuation lines before inspecting directives."""
  299. logical_lines: list[str] = []
  300. pending = ""
  301. for raw_line in content.splitlines():
  302. line = _uncommented(raw_line)
  303. if not line:
  304. continue
  305. if pending:
  306. line = f"{pending} {line.lstrip()}"
  307. stripped = line.rstrip()
  308. if stripped.endswith("\\"):
  309. pending = stripped[:-1].rstrip()
  310. continue
  311. logical_lines.append(line)
  312. pending = ""
  313. if pending:
  314. logical_lines.append(pending)
  315. return logical_lines
  316. def _logical_squid_line_locations(
  317. lines: list[str],
  318. ) -> list[tuple[int, int, str]]:
  319. """Return logical Squid directives with their physical line positions.
  320. Include directives are allowed to use a trailing backslash. Writers need
  321. the original positions to insert safely, while policy checks need the
  322. joined directive, so inspecting ``splitlines`` alone can duplicate an
  323. already-active module.
  324. """
  325. locations: list[tuple[int, int, str]] = []
  326. pending = ""
  327. start_index: int | None = None
  328. for index, raw_line in enumerate(lines):
  329. line = _uncommented(raw_line)
  330. if not line:
  331. continue
  332. if pending:
  333. line = f"{pending} {line.lstrip()}"
  334. else:
  335. start_index = index
  336. stripped = line.rstrip()
  337. if stripped.endswith("\\"):
  338. pending = stripped[:-1].rstrip()
  339. continue
  340. locations.append(
  341. (start_index if start_index is not None else index, index, line)
  342. )
  343. pending = ""
  344. start_index = None
  345. if pending:
  346. locations.append(
  347. (
  348. start_index if start_index is not None else len(lines) - 1,
  349. len(lines) - 1,
  350. pending,
  351. )
  352. )
  353. return locations
  354. def _is_http_access_line(line: str) -> bool:
  355. return _HTTP_ACCESS_RE.fullmatch(_uncommented(line)) is not None
  356. def _remove_complete_blocks(content: str, start: str, end: str) -> str:
  357. """Remove complete managed blocks and reject incomplete markers safely."""
  358. while True:
  359. start_index = content.find(start)
  360. if start_index < 0:
  361. return content
  362. end_index = content.find(end, start_index + len(start))
  363. if end_index < 0:
  364. raise KerberosConfigurationError(
  365. "Se encontró un bloque Kerberos incompleto; revísalo manualmente antes de continuar."
  366. )
  367. end_index += len(end)
  368. newline_index = content.find("\n", end_index)
  369. remove_end = len(content) if newline_index < 0 else newline_index + 1
  370. content = content[:start_index] + content[remove_end:]
  371. def _assert_complete_managed_blocks(content: str) -> None:
  372. """Reject a hand-edited managed block that cannot be safely interpreted.
  373. The status page must stay available in this situation, but it must explain
  374. why applying another change is unsafe. Checking this independently of
  375. removal also catches a broken marker when the block has no auth directive.
  376. """
  377. pairs = (
  378. (MANAGED_AUTH_START, MANAGED_AUTH_END),
  379. (MANAGED_ACCESS_START, MANAGED_ACCESS_END),
  380. (LEGACY_MANAGED_AUTH_START, LEGACY_MANAGED_AUTH_END),
  381. )
  382. for start, end in pairs:
  383. offset = 0
  384. while True:
  385. start_index = content.find(start, offset)
  386. if start_index < 0:
  387. break
  388. end_index = content.find(end, start_index + len(start))
  389. if end_index < 0:
  390. raise KerberosConfigurationError(
  391. "Se encontró un bloque Kerberos incompleto; revísalo manualmente antes de continuar."
  392. )
  393. offset = end_index + len(end)
  394. def _remove_managed_auth(content: str) -> str:
  395. content = _remove_complete_blocks(content, MANAGED_AUTH_START, MANAGED_AUTH_END)
  396. return _remove_complete_blocks(
  397. content, LEGACY_MANAGED_AUTH_START, LEGACY_MANAGED_AUTH_END
  398. )
  399. def _remove_managed_access(content: str) -> str:
  400. return _remove_complete_blocks(content, MANAGED_ACCESS_START, MANAGED_ACCESS_END)
  401. def _find_complete_block(content: str, start: str, end: str) -> str | None:
  402. start_index = content.find(start)
  403. if start_index < 0:
  404. return None
  405. end_index = content.find(end, start_index + len(start))
  406. if end_index < 0:
  407. return None
  408. return content[start_index : end_index + len(end)]
  409. def _auth_block(settings: KerberosSettings) -> str:
  410. helper_arguments = [
  411. settings.helper_path,
  412. "-k",
  413. settings.keytab_path,
  414. ]
  415. if settings.strip_realm:
  416. helper_arguments.append("-r")
  417. helper_arguments.extend(["-s", settings.service_principal])
  418. helper = " ".join(helper_arguments)
  419. keep_alive = "on" if settings.keep_alive else "off"
  420. return "\n".join(
  421. [
  422. MANAGED_AUTH_START,
  423. "# SPNEGO/Kerberos authentication managed by SquidStats.",
  424. f"auth_param negotiate program {helper}",
  425. "auth_param negotiate children "
  426. f"{settings.children} startup={settings.startup} idle={settings.idle}",
  427. f"auth_param negotiate keep_alive {keep_alive}",
  428. f"acl {settings.acl_name} proxy_auth REQUIRED",
  429. MANAGED_AUTH_END,
  430. "",
  431. ]
  432. )
  433. def _access_block(settings: KerberosSettings) -> str:
  434. return "\n".join(
  435. [
  436. MANAGED_ACCESS_START,
  437. "# Keep this after security denies and before client allow rules.",
  438. # A negated proxy_auth ACL is deliberate. Squid documents this
  439. # form because an `allow proxy_auth` rule alone may not challenge
  440. # a client that initially presents no credentials; a later
  441. # `allow localnet` could then grant anonymous access.
  442. f"http_access deny !{settings.acl_name}",
  443. MANAGED_ACCESS_END,
  444. "",
  445. ]
  446. )
  447. def render_preview(settings: KerberosSettings | Mapping[str, Any]) -> str:
  448. """Render the directives that will be managed, without changing files."""
  449. settings = _validated_settings(settings)
  450. if not settings.enabled:
  451. return (
  452. "# Kerberos authentication is disabled; managed blocks will be removed.\n"
  453. )
  454. preview = _auth_block(settings)
  455. if settings.enforce_auth:
  456. preview += "\n" + _access_block(settings)
  457. return preview
  458. def _insert_before_first_http_access(
  459. content: str, block: str, *, config_path: Path | None = None
  460. ) -> str:
  461. """Insert auth directives before every direct authentication consumer.
  462. Squid needs ``auth_param`` before an ``acl ... proxy_auth`` (and before
  463. external ACL types that ask for ``%LOGIN``), not merely before the first
  464. ``http_access`` line. A quota ACL commonly appears near the top of a
  465. monolithic configuration, so placing the helper only at the access-policy
  466. boundary can leave an invalid configuration. When an on-disk path is
  467. known, inspect direct includes recursively as well: the helper must be
  468. loaded before a parent fragment that defines such an ACL.
  469. """
  470. lines = content.splitlines(keepends=True)
  471. insertion_indices = [
  472. start_index
  473. for start_index, _end_index, logical_line in _logical_squid_line_locations(
  474. lines
  475. )
  476. if _is_http_access_line(logical_line)
  477. or _is_auth_dependent_directive(logical_line)
  478. ]
  479. if config_path is not None:
  480. insertion_indices.extend(
  481. _direct_auth_dependency_indices(content, config_path.parent)
  482. )
  483. if insertion_indices:
  484. index = min(insertion_indices)
  485. prefix = "" if index == 0 or lines[index - 1].endswith("\n\n") else "\n"
  486. lines.insert(index, prefix + block)
  487. return "".join(lines)
  488. if not content.strip():
  489. return block
  490. return content.rstrip() + "\n\n" + block
  491. def _is_negotiate_directive(line: str) -> bool:
  492. parts = _uncommented(line).split()
  493. return (
  494. len(parts) >= 3
  495. and parts[0].casefold() == "auth_param"
  496. and parts[1].casefold() == "negotiate"
  497. )
  498. def _negotiate_directive_lines(content: str) -> list[str]:
  499. """Return active Negotiate directives, including logical continuations."""
  500. return [
  501. line for line in _logical_squid_lines(content) if _is_negotiate_directive(line)
  502. ]
  503. def _other_auth_program_schemes(content: str) -> set[str]:
  504. """Return active helper schemes other than Negotiate.
  505. Squid may offer several authentication schemes at once, but user agents
  506. can choose among them. This managed flow deliberately configures a single
  507. Kerberos/SPNEGO scheme instead of silently turning an NTLM/Basic fallback
  508. into an alternate way around the intended policy.
  509. """
  510. schemes: set[str] = set()
  511. for line in _logical_squid_lines(content):
  512. parts = line.split()
  513. if (
  514. len(parts) >= 4
  515. and parts[0].casefold() == "auth_param"
  516. and parts[2].casefold() == "program"
  517. and parts[1].casefold() != "negotiate"
  518. ):
  519. schemes.add(parts[1].casefold())
  520. return schemes
  521. def _remove_conflicting_negotiate_directives(content: str) -> str:
  522. """Remove reviewed Negotiate directives, including continuation lines."""
  523. kept: list[str] = []
  524. lines = content.splitlines(keepends=True)
  525. index = 0
  526. while index < len(lines):
  527. line = lines[index]
  528. if _is_negotiate_directive(line):
  529. # A multiline helper declaration must be removed as one logical
  530. # directive. Leaving its next ``-k``/``-s`` line behind would make
  531. # the configuration invalid after a deliberate replacement.
  532. while index < len(lines):
  533. continued = _uncommented(lines[index]).rstrip().endswith("\\")
  534. index += 1
  535. if not continued:
  536. break
  537. continue
  538. kept.append(line)
  539. index += 1
  540. return "".join(kept)
  541. def _remove_acl(content: str, acl_name: str) -> str:
  542. acl_re = re.compile(
  543. rf"^acl\s+{re.escape(acl_name)}\s+(?:-\S+\s+)*proxy_auth\s+REQUIRED(?:\s|$)",
  544. re.I,
  545. )
  546. return "".join(
  547. line
  548. for line in content.splitlines(keepends=True)
  549. if not acl_re.match(_uncommented(line))
  550. )
  551. def _has_acl_definition(content: str, acl_name: str) -> bool:
  552. """Return whether a non-comment ACL already owns this name."""
  553. return any(
  554. len(parts := _uncommented(line).split()) >= 2
  555. and parts[0].casefold() == "acl"
  556. and parts[1].casefold() == acl_name.casefold()
  557. for line in content.splitlines()
  558. )
  559. def _remove_access_rule(content: str, acl_name: str) -> str:
  560. expected = {
  561. f"http_access deny !{acl_name}".casefold(),
  562. f"http_access allow {acl_name}".casefold(),
  563. }
  564. return "".join(
  565. line
  566. for line in content.splitlines(keepends=True)
  567. if _uncommented(line).casefold() not in expected
  568. )
  569. def _has_proxy_auth_quota_acl(contents: list[str]) -> bool:
  570. """Return whether the active quota ACL uses authenticated identities.
  571. The quota feature also has an IP-based fallback with the same access-rule
  572. name. Moving that fallback would change its established policy, whereas
  573. the proxy-auth form can start authentication before Kerberos gets its
  574. intended chance to challenge. Only the latter is relevant here.
  575. """
  576. for content in contents:
  577. for line in _logical_squid_lines(content):
  578. parts = line.split()
  579. if (
  580. len(parts) >= 3
  581. and parts[0].casefold() == "acl"
  582. and parts[1].casefold() == _QUOTA_PROXY_AUTH_ACL_NAME
  583. and parts[2].casefold() == "proxy_auth"
  584. ):
  585. return True
  586. return False
  587. def _take_proxy_auth_quota_deny(
  588. content: str, acl_contents: list[str]
  589. ) -> tuple[str, str | None]:
  590. """Temporarily remove the generated quota denial before inserting auth.
  591. Returning the first physical rule preserves an administrator's harmless
  592. inline comment. Duplicate generated rules are collapsed while the rule
  593. is restored, matching the quota sync's single-rule invariant.
  594. """
  595. if not _has_proxy_auth_quota_acl(acl_contents):
  596. return content, None
  597. quota_rule: str | None = None
  598. kept: list[str] = []
  599. for line in content.splitlines(keepends=True):
  600. if _uncommented(line).casefold() == _QUOTA_PROXY_AUTH_DENY:
  601. if quota_rule is None:
  602. quota_rule = line.rstrip("\r\n")
  603. continue
  604. kept.append(line)
  605. return "".join(kept), quota_rule
  606. def _restore_proxy_auth_quota_deny(content: str, quota_rule: str) -> str:
  607. """Put the generated proxy-auth quota rule after the Kerberos challenge."""
  608. lines = content.splitlines(keepends=True)
  609. for index, line in enumerate(lines):
  610. if line.strip() != MANAGED_ACCESS_END:
  611. continue
  612. newline = "" if line.endswith("\n") else "\n"
  613. lines.insert(index + 1, f"{newline}{quota_rule}\n")
  614. return "".join(lines)
  615. raise KerberosConfigurationError(
  616. "No se pudo ubicar el bloque Kerberos para reordenar la regla de cuota."
  617. )
  618. def _is_management_exception(acls: list[str]) -> bool:
  619. """Keep only an explicit Cache Manager exception ahead of auth.
  620. A standalone ``allow localhost`` grants normal proxy access from loopback,
  621. so it must not silently bypass the Kerberos challenge. The only exception
  622. retained ahead of the challenge is the conventional *local* Cache Manager
  623. rule, with positive ``manager`` and ``localhost`` ACLs.
  624. """
  625. # Negating ``manager`` changes the rule completely: ``allow !manager``
  626. # matches ordinary proxy traffic and would let it bypass the challenge.
  627. # Only the conventional, positive Cache Manager ACL (optionally limited
  628. # to positive ``localhost``) is safe to leave before Kerberos.
  629. normalised = {acl.casefold() for acl in acls}
  630. return normalised == {"manager", "localhost"}
  631. def _active_acl_definitions(
  632. contents: list[str], name: str
  633. ) -> list[tuple[str, list[str]]]:
  634. """Collect active definitions of an ACL name, including Squid options."""
  635. definitions: list[tuple[str, list[str]]] = []
  636. for content in contents:
  637. for line in _logical_squid_lines(content):
  638. parts = line.split()
  639. if (
  640. len(parts) < 3
  641. or parts[0].casefold() != "acl"
  642. or parts[1].casefold() != name.casefold()
  643. ):
  644. continue
  645. type_index = 2
  646. while type_index < len(parts) and parts[type_index].startswith("-"):
  647. type_index += 1
  648. if type_index >= len(parts):
  649. definitions.append(("", []))
  650. else:
  651. definitions.append(
  652. (parts[type_index].casefold(), parts[type_index + 1 :])
  653. )
  654. return definitions
  655. def _is_loopback_acl_value(value: str) -> bool:
  656. """Whether an ACL source value is an IP address/network limited to loopback."""
  657. try:
  658. return ipaddress.ip_network(value, strict=False).is_loopback
  659. except ValueError:
  660. return False
  661. def _assert_management_exception_acls_safe(contents: list[str]) -> None:
  662. """Reject a broad ``manager localhost`` exception before auth.
  663. The rule is only safe when ``manager`` is restricted to cache-object
  664. requests and every explicitly declared ``localhost`` source is loopback.
  665. Missing definitions are left for Squid's syntax validation: an undefined
  666. ACL cannot authorize anonymous traffic, whereas a broad declaration can.
  667. """
  668. manager_definitions = _active_acl_definitions(contents, "manager")
  669. if manager_definitions and any(
  670. acl_type != "proto" or values != ["cache_object"]
  671. for acl_type, values in manager_definitions
  672. ):
  673. raise KerberosConfigurationError(
  674. "La ACL manager no está limitada a 'proto cache_object'; no es seguro "
  675. "dejar su excepción antes del desafío Kerberos."
  676. )
  677. localhost_definitions = _active_acl_definitions(contents, "localhost")
  678. if localhost_definitions and any(
  679. acl_type != "src"
  680. or not values
  681. or not all(_is_loopback_acl_value(value) for value in values)
  682. for acl_type, values in localhost_definitions
  683. ):
  684. raise KerberosConfigurationError(
  685. "La ACL localhost no está limitada a direcciones loopback; no es seguro "
  686. "dejar su excepción antes del desafío Kerberos."
  687. )
  688. def _add_access_block(
  689. content: str,
  690. settings: KerberosSettings,
  691. *,
  692. acl_contents: list[str] | None = None,
  693. ) -> str:
  694. """Insert an authentication challenge without bypassing later denies.
  695. ``http_access deny !kerberos_auth`` is the documented way to reliably
  696. trigger an authentication challenge. It must be before the first normal
  697. client allow rule but after all security denies. Rather than silently
  698. altering an ambiguous policy, this routine refuses to insert the rule when
  699. a denial follows that point.
  700. """
  701. lines = content.splitlines(keepends=True)
  702. parsed: list[tuple[int, str, list[str]]] = []
  703. final_deny_index: int | None = None
  704. first_client_allow: int | None = None
  705. for index, line in enumerate(lines):
  706. match = _HTTP_ACCESS_RE.fullmatch(_uncommented(line))
  707. if not match:
  708. continue
  709. action = match.group(1).casefold()
  710. acls = match.group(2).split()
  711. parsed.append((index, action, acls))
  712. if action == "deny" and [item.casefold() for item in acls] == ["all"]:
  713. if final_deny_index is None:
  714. final_deny_index = index
  715. continue
  716. if (
  717. action == "allow"
  718. and index
  719. < (final_deny_index if final_deny_index is not None else len(lines))
  720. and not _is_management_exception(acls)
  721. and first_client_allow is None
  722. ):
  723. first_client_allow = index
  724. # final_deny_index was discovered while iterating, so establish the first
  725. # client allow again with the final boundary known.
  726. if final_deny_index is not None:
  727. first_client_allow = next(
  728. (
  729. index
  730. for index, action, acls in parsed
  731. if index < final_deny_index
  732. and action == "allow"
  733. and not _is_management_exception(acls)
  734. ),
  735. None,
  736. )
  737. if final_deny_index is None:
  738. raise KerberosConfigurationError(
  739. "No se encontró 'http_access deny all'; no es seguro insertar la regla Kerberos."
  740. )
  741. if any(index > final_deny_index for index, _action, _acls in parsed):
  742. raise KerberosConfigurationError(
  743. "'http_access deny all' no es la última regla de acceso; ordénala manualmente antes de activar Kerberos."
  744. )
  745. if first_client_allow is None:
  746. raise KerberosConfigurationError(
  747. "No se encontró una regla 'http_access allow' para clientes antes de 'deny all'; "
  748. "Kerberos podría autenticarlos pero no autorizarlos. Define primero tu política de acceso."
  749. )
  750. if any(
  751. action == "allow" and _is_management_exception(acls)
  752. for _index, action, acls in parsed
  753. ):
  754. _assert_management_exception_acls_safe(acl_contents or [content])
  755. insertion_index = first_client_allow
  756. later_denies = [
  757. index
  758. for index, action, acls in parsed
  759. if insertion_index < index < final_deny_index
  760. and action == "deny"
  761. and [item.casefold() for item in acls] != ["all"]
  762. ]
  763. if later_denies:
  764. raise KerberosConfigurationError(
  765. "La política http_access tiene denegaciones después del primer allow de clientes; "
  766. "ordénala manualmente antes de activar Kerberos para no omitir restricciones."
  767. )
  768. block = _access_block(settings)
  769. prefix = (
  770. ""
  771. if insertion_index == 0 or lines[insertion_index - 1].endswith("\n\n")
  772. else "\n"
  773. )
  774. lines.insert(insertion_index, prefix + block)
  775. return "".join(lines)
  776. def _target_from_main(config_manager) -> _ConfigTarget:
  777. original = str(getattr(config_manager, "config_content", "") or "")
  778. config_path = Path(str(getattr(config_manager, "config_path", "squid.conf")))
  779. return _ConfigTarget(
  780. name="squid.conf",
  781. path=config_path,
  782. original=original,
  783. content=original,
  784. existed=True,
  785. save=config_manager.save_config,
  786. )
  787. def _read_optional_module(
  788. config_manager, filename: str, *, require_readable: bool = False
  789. ) -> str | None:
  790. """Read a conventional module, distinguishing absence from read failure.
  791. ``SquidConfigManager.read_modular_config`` intentionally returns ``None``
  792. both for a missing file and for a failed read. That is convenient for
  793. generic UI views, but unsafe for a configuration writer: directory write
  794. permission alone can otherwise replace an unreadable existing module.
  795. """
  796. config_dir = str(getattr(config_manager, "config_dir", "") or "")
  797. if config_dir:
  798. module_path = Path(config_dir) / filename
  799. try:
  800. module_stat = module_path.stat()
  801. except FileNotFoundError:
  802. return None
  803. except OSError as exc:
  804. if require_readable:
  805. raise KerberosConfigurationError(
  806. f"No se pudo inspeccionar el módulo estándar {filename}; "
  807. "no se modificó ninguna configuración."
  808. ) from exc
  809. return None
  810. if not stat.S_ISREG(module_stat.st_mode):
  811. if require_readable:
  812. raise KerberosConfigurationError(
  813. f"El módulo estándar {filename} no es un archivo regular; "
  814. "no se modificó ninguna configuración."
  815. )
  816. return None
  817. try:
  818. content = config_manager.read_modular_config(filename)
  819. except Exception as exc:
  820. if require_readable:
  821. raise KerberosConfigurationError(
  822. f"No se pudo leer el módulo estándar {filename}; "
  823. "no se modificó ninguna configuración."
  824. ) from exc
  825. return None
  826. if content is None:
  827. if require_readable:
  828. raise KerberosConfigurationError(
  829. f"No se pudo leer el módulo estándar {filename}; "
  830. "no se modificó ninguna configuración."
  831. )
  832. return None
  833. if not isinstance(content, str):
  834. if require_readable:
  835. raise KerberosConfigurationError(
  836. f"El módulo estándar {filename} no contiene texto válido; "
  837. "no se modificó ninguna configuración."
  838. )
  839. return None
  840. return content
  841. def _target_from_module(config_manager, filename: str) -> _ConfigTarget:
  842. config_dir = Path(str(getattr(config_manager, "config_dir", "")))
  843. existing = _read_optional_module(config_manager, filename, require_readable=True)
  844. original = existing if existing is not None else ""
  845. return _ConfigTarget(
  846. name=filename,
  847. path=config_dir / filename,
  848. original=original,
  849. content=original,
  850. existed=existing is not None,
  851. save=lambda content: config_manager.save_modular_config(filename, content),
  852. )
  853. def _same_target(first: _ConfigTarget, second: _ConfigTarget) -> bool:
  854. return first.name == second.name and first.path == second.path
  855. def _unique_targets(targets: list[_ConfigTarget]) -> list[_ConfigTarget]:
  856. unique: list[_ConfigTarget] = []
  857. for target in targets:
  858. if not any(_same_target(target, known) for known in unique):
  859. unique.append(target)
  860. return unique
  861. def _active_http_access(content: str) -> bool:
  862. return any(
  863. _HTTP_ACCESS_RE.fullmatch(line) is not None
  864. for line in _logical_squid_lines(content)
  865. )
  866. def _unexpected_included_http_access_sources(
  867. config_manager, expected_module_path: Path
  868. ) -> list[str]:
  869. """Return active rule sources outside the one this feature can manage.
  870. The generic ``is_modular`` flag also covers custom ``*.conf`` layouts.
  871. Adding a challenge to ``120_http_access.conf`` while an earlier custom
  872. fragment already allows clients would silently leave those clients
  873. unauthenticated. We only write the conventional module, so reject such
  874. layouts instead of guessing at cross-file policy order.
  875. """
  876. expected_path = os.path.realpath(str(expected_module_path))
  877. return [
  878. path
  879. for path, content in _active_included_configuration_sources(config_manager)
  880. if os.path.realpath(path) != expected_path and _active_http_access(content)
  881. ]
  882. def _access_target(
  883. config_manager,
  884. main: _ConfigTarget,
  885. modular: bool,
  886. module: _ConfigTarget | None = None,
  887. ) -> _ConfigTarget:
  888. if not modular:
  889. # An extensionless/custom include does not necessarily make the
  890. # generic configuration manager call the layout "modular". Its
  891. # rules are nevertheless active at the include position, so adding
  892. # the challenge to squid.conf could leave an earlier allow rule able
  893. # to bypass Kerberos. We do not know how to safely rewrite that
  894. # external policy source; require an administrator to consolidate it.
  895. unexpected_sources = _unexpected_included_http_access_sources(
  896. config_manager, main.path
  897. )
  898. if unexpected_sources:
  899. filenames = ", ".join(
  900. sorted({Path(path).name for path in unexpected_sources})
  901. )
  902. raise KerberosConfigurationError(
  903. "Se detectaron reglas http_access activas en archivos incluidos "
  904. f"fuera de squid.conf ({filenames}). Muévelas a squid.conf o "
  905. "termina de modularizar la política antes de activar Kerberos."
  906. )
  907. return main
  908. module = module or _target_from_module(config_manager, HTTP_ACCESS_MODULE_FILENAME)
  909. unexpected_sources = _unexpected_included_http_access_sources(
  910. config_manager, module.path
  911. )
  912. if unexpected_sources:
  913. filenames = ", ".join(sorted({Path(path).name for path in unexpected_sources}))
  914. raise KerberosConfigurationError(
  915. "Se detectaron reglas http_access activas fuera de squid.conf/"
  916. f"{HTTP_ACCESS_MODULE_FILENAME} ({filenames}). La política modular es ambigua; "
  917. "muévela a 120_http_access.conf antes de activar Kerberos."
  918. )
  919. main_has_rules = _active_http_access(main.content)
  920. module_has_rules = _active_http_access(module.content)
  921. module_is_active = any(
  922. os.path.realpath(path) == os.path.realpath(str(module.path))
  923. for path, _content in _active_included_configuration_sources(config_manager)
  924. )
  925. if main_has_rules and module_has_rules:
  926. raise KerberosConfigurationError(
  927. "Hay reglas http_access tanto en squid.conf como en 120_http_access.conf; "
  928. "la política es ambigua y no se modificó."
  929. )
  930. if main_has_rules and module_is_active:
  931. # Even an empty active 120 module is unsafe here: the generic HTTP
  932. # Access editor writes to that conventional file when it exists. A
  933. # later allow rule would be evaluated before the challenge kept in
  934. # squid.conf. Do not enable Kerberos in a layout that can become a
  935. # bypass through another first-party UI.
  936. raise KerberosConfigurationError(
  937. "120_http_access.conf está incluido antes de reglas en squid.conf. "
  938. "Aunque esté vacío, el editor HTTP Access podría añadir reglas antes del "
  939. "desafío Kerberos; mueve la política a un único origen antes de activar."
  940. )
  941. if main_has_rules:
  942. return main
  943. if module_has_rules and not module_is_active:
  944. raise KerberosConfigurationError(
  945. "120_http_access.conf contiene reglas pero no está incluido activamente; "
  946. "no es seguro activarlas al configurar Kerberos. Inclúyelo o mueve la política "
  947. "a squid.conf antes de continuar."
  948. )
  949. return module
  950. def _include_path(line: str) -> str | None:
  951. match = _INCLUDE_RE.fullmatch(_uncommented(line))
  952. if not match:
  953. return None
  954. return match.group(1).strip().strip('"')
  955. def _include_rank(include_path: str) -> int:
  956. match = re.match(r"^(\d+)_", Path(include_path).name)
  957. return int(match.group(1)) if match else 1000
  958. def _resolved_include_path(include_path: str, config_directory: Path) -> str:
  959. raw_include_path = os.path.expanduser(include_path)
  960. return os.path.abspath(
  961. raw_include_path
  962. if os.path.isabs(raw_include_path)
  963. else str(config_directory / raw_include_path)
  964. )
  965. def _include_matches_module(
  966. include_path: str, module_path: Path, config_directory: Path
  967. ) -> bool:
  968. desired = os.path.abspath(str(module_path))
  969. expanded = _resolved_include_path(include_path, config_directory)
  970. desired_real = os.path.realpath(desired)
  971. expanded_real = os.path.realpath(expanded)
  972. return (
  973. expanded == desired
  974. or fnmatch.fnmatch(desired, expanded)
  975. or expanded_real == desired_real
  976. or fnmatch.fnmatch(desired_real, expanded_real)
  977. )
  978. def _is_auth_dependent_directive(line: str) -> bool:
  979. """Return whether an active directive needs authentication first.
  980. ``proxy_auth`` ACLs are registered against an authentication scheme while
  981. Squid parses its configuration. An external ACL type with ``%LOGIN`` is
  982. similarly dependent on a proxy login. Keeping these deliberately narrow
  983. avoids treating arbitrary ACL value lists as configuration dependencies.
  984. """
  985. parts = _uncommented(line).split()
  986. if not parts:
  987. return False
  988. lowered = [part.casefold() for part in parts]
  989. if lowered[0] == "acl":
  990. return any(part.startswith("proxy_auth") for part in lowered[2:])
  991. return lowered[0] == "external_acl_type" and "%login" in lowered[1:]
  992. def _include_tree_requires_auth(
  993. content: str, directory: Path, seen: set[str], depth: int = 0
  994. ) -> bool:
  995. """Inspect one included source tree for proxy-auth configuration.
  996. This is intentionally fail-closed. The caller is about to move the
  997. generated auth include in relation to the tree, so an unreadable or too
  998. deeply nested source cannot safely be treated as unrelated.
  999. """
  1000. if any(
  1001. _is_auth_dependent_directive(line) for line in _logical_squid_lines(content)
  1002. ):
  1003. return True
  1004. if depth >= 8:
  1005. if any(_include_path(line) for line in _logical_squid_lines(content)):
  1006. raise KerberosConfigurationError(
  1007. "No se pudo verificar la profundidad de un include antes de la "
  1008. "autenticación; revísalo manualmente antes de activar Kerberos."
  1009. )
  1010. return False
  1011. for line in _logical_squid_lines(content):
  1012. include_path = _include_path(line)
  1013. if not include_path:
  1014. continue
  1015. pattern = _resolved_include_path(include_path, directory)
  1016. try:
  1017. candidates = sorted(glob.glob(pattern))
  1018. except OSError as exc:
  1019. raise KerberosConfigurationError(
  1020. "No se pudo resolver un include antes de la autenticación; "
  1021. "revísalo manualmente antes de activar Kerberos."
  1022. ) from exc
  1023. for candidate in candidates:
  1024. canonical_path = os.path.realpath(candidate)
  1025. if canonical_path in seen:
  1026. continue
  1027. try:
  1028. source_stat = os.stat(canonical_path)
  1029. except OSError as exc:
  1030. raise KerberosConfigurationError(
  1031. "No se pudo inspeccionar un include antes de la autenticación; "
  1032. "no se modificó ninguna configuración."
  1033. ) from exc
  1034. if not stat.S_ISREG(source_stat.st_mode):
  1035. raise KerberosConfigurationError(
  1036. "Un include antes de la autenticación no es un archivo regular; "
  1037. "no se modificó ninguna configuración."
  1038. )
  1039. if source_stat.st_size > _MAX_INCLUDED_CONFIG_BYTES:
  1040. raise KerberosConfigurationError(
  1041. "Un include antes de la autenticación supera el límite de inspección; "
  1042. "revísalo manualmente antes de activar Kerberos."
  1043. )
  1044. seen.add(canonical_path)
  1045. try:
  1046. included_content = Path(canonical_path).read_text(encoding="utf-8")
  1047. except (OSError, UnicodeDecodeError) as exc:
  1048. raise KerberosConfigurationError(
  1049. "No se pudo leer un include antes de la autenticación; "
  1050. "no se modificó ninguna configuración."
  1051. ) from exc
  1052. if _include_tree_requires_auth(
  1053. included_content, Path(canonical_path).parent, seen, depth + 1
  1054. ):
  1055. return True
  1056. return False
  1057. def _direct_auth_dependency_indices(content: str, config_directory: Path) -> list[int]:
  1058. """Return direct include locations that load proxy-auth dependencies."""
  1059. lines = content.splitlines(keepends=True)
  1060. indices: list[int] = []
  1061. for start_index, _end_index, logical_line in _logical_squid_line_locations(lines):
  1062. include_path = _include_path(logical_line)
  1063. if not include_path:
  1064. continue
  1065. pattern = _resolved_include_path(include_path, config_directory)
  1066. try:
  1067. candidates = sorted(glob.glob(pattern))
  1068. except OSError as exc:
  1069. raise KerberosConfigurationError(
  1070. "No se pudo resolver un include antes de la autenticación; "
  1071. "revísalo manualmente antes de activar Kerberos."
  1072. ) from exc
  1073. for candidate in candidates:
  1074. canonical_path = os.path.realpath(candidate)
  1075. try:
  1076. source_stat = os.stat(canonical_path)
  1077. except OSError as exc:
  1078. raise KerberosConfigurationError(
  1079. "No se pudo inspeccionar un include antes de la autenticación; "
  1080. "no se modificó ninguna configuración."
  1081. ) from exc
  1082. if not stat.S_ISREG(source_stat.st_mode):
  1083. raise KerberosConfigurationError(
  1084. "Un include antes de la autenticación no es un archivo regular; "
  1085. "no se modificó ninguna configuración."
  1086. )
  1087. if source_stat.st_size > _MAX_INCLUDED_CONFIG_BYTES:
  1088. raise KerberosConfigurationError(
  1089. "Un include antes de la autenticación supera el límite de inspección; "
  1090. "revísalo manualmente antes de activar Kerberos."
  1091. )
  1092. try:
  1093. included_content = Path(canonical_path).read_text(encoding="utf-8")
  1094. except (OSError, UnicodeDecodeError) as exc:
  1095. raise KerberosConfigurationError(
  1096. "No se pudo leer un include antes de la autenticación; "
  1097. "no se modificó ninguna configuración."
  1098. ) from exc
  1099. if _include_tree_requires_auth(
  1100. included_content,
  1101. Path(canonical_path).parent,
  1102. {canonical_path},
  1103. ):
  1104. indices.append(start_index)
  1105. break
  1106. return indices
  1107. def _active_included_configuration_sources(
  1108. config_manager, *, inspection_errors: list[str] | None = None
  1109. ) -> list[tuple[str, str]]:
  1110. """Read active included configuration files without following cycles.
  1111. Squid installations often use a wildcard include, but administrators may
  1112. also split authentication, ports, or cache settings into custom files.
  1113. Looking only at the standard filenames would miss active helpers and port
  1114. modes in those layouts. Files larger than one MiB are not read to avoid
  1115. loading a value-list-sized file; callers that request inspection errors
  1116. are told to review them manually before a write is allowed.
  1117. """
  1118. main_content = str(getattr(config_manager, "config_content", "") or "")
  1119. main_path = Path(str(getattr(config_manager, "config_path", "squid.conf")))
  1120. seen = {os.path.realpath(str(main_path))}
  1121. sources: list[tuple[str, str]] = []
  1122. def record_inspection_error(path: str, reason: str) -> None:
  1123. if inspection_errors is None:
  1124. return
  1125. filename = Path(path).name or path
  1126. inspection_errors.append(
  1127. f"No se pudo inspeccionar el archivo incluido activo {filename} ({reason}). "
  1128. "No se modificó ninguna configuración."
  1129. )
  1130. def visit(content: str, directory: Path, depth: int = 0) -> None:
  1131. if depth >= 8:
  1132. logger.warning(
  1133. "Maximum Squid include depth reached while checking Kerberos"
  1134. )
  1135. if any(_include_path(line) for line in _logical_squid_lines(content)):
  1136. record_inspection_error(
  1137. str(directory), "se alcanzó la profundidad máxima de includes"
  1138. )
  1139. return
  1140. for line in _logical_squid_lines(content):
  1141. include_path = _include_path(line)
  1142. if not include_path:
  1143. continue
  1144. pattern = _resolved_include_path(include_path, directory)
  1145. try:
  1146. paths = sorted(glob.glob(pattern))
  1147. except OSError:
  1148. record_inspection_error(pattern, "no se pudo resolver el include")
  1149. continue
  1150. for candidate in paths:
  1151. canonical_path = os.path.realpath(candidate)
  1152. if canonical_path in seen:
  1153. continue
  1154. try:
  1155. source_stat = os.stat(canonical_path)
  1156. except OSError:
  1157. record_inspection_error(canonical_path, "no se pudo consultar")
  1158. continue
  1159. if not stat.S_ISREG(source_stat.st_mode):
  1160. continue
  1161. seen.add(canonical_path)
  1162. if source_stat.st_size > _MAX_INCLUDED_CONFIG_BYTES:
  1163. record_inspection_error(
  1164. canonical_path,
  1165. f"supera el límite de {_MAX_INCLUDED_CONFIG_BYTES // 1024 // 1024} MiB",
  1166. )
  1167. continue
  1168. try:
  1169. included_content = Path(canonical_path).read_text(encoding="utf-8")
  1170. except (OSError, UnicodeDecodeError):
  1171. record_inspection_error(
  1172. canonical_path, "no se pudo leer como UTF-8"
  1173. )
  1174. continue
  1175. sources.append((canonical_path, included_content))
  1176. visit(included_content, Path(canonical_path).parent, depth + 1)
  1177. visit(main_content, main_path.parent)
  1178. return sources
  1179. def _configuration_source_inspection_errors(config_manager) -> list[str]:
  1180. """Return blockers when an active or writable target cannot be inspected.
  1181. Before doing a read-modify-write operation, the service must be able to
  1182. see all active include fragments as well as its conventional output files.
  1183. Otherwise a directory-level atomic replacement could erase unseen policy.
  1184. """
  1185. errors: list[str] = []
  1186. _active_included_configuration_sources(config_manager, inspection_errors=errors)
  1187. if bool(getattr(config_manager, "is_modular", False)):
  1188. for filename in (
  1189. AUTH_MODULE_FILENAME,
  1190. ACL_MODULE_FILENAME,
  1191. HTTP_ACCESS_MODULE_FILENAME,
  1192. ):
  1193. try:
  1194. _read_optional_module(config_manager, filename, require_readable=True)
  1195. except KerberosConfigurationError as exc:
  1196. errors.append(str(exc))
  1197. return list(dict.fromkeys(errors))
  1198. def _main_directly_includes_module(main: _ConfigTarget, module_path: Path) -> bool:
  1199. """Whether ``squid.conf`` itself loads a module (possibly via a glob)."""
  1200. lines = main.content.splitlines(keepends=True)
  1201. return any(
  1202. (include_path := _include_path(logical_line))
  1203. and _include_matches_module(include_path, module_path, main.path.parent)
  1204. for _start, _end, logical_line in _logical_squid_line_locations(lines)
  1205. )
  1206. def _reject_indirect_active_module(
  1207. config_manager, main: _ConfigTarget, module: _ConfigTarget
  1208. ) -> None:
  1209. """Reject a module loaded only through a parent include.
  1210. Editing its contents is safe, but inserting another direct include would
  1211. load the helper or ACL twice. Determining the order through arbitrary
  1212. nested fragments is outside this narrowly managed workflow, so require a
  1213. deliberate manual migration instead.
  1214. """
  1215. module_path = os.path.realpath(str(module.path))
  1216. is_active = any(
  1217. os.path.realpath(path) == module_path
  1218. for path, _content in _active_included_configuration_sources(config_manager)
  1219. )
  1220. if is_active and not _main_directly_includes_module(main, module.path):
  1221. raise KerberosConfigurationError(
  1222. f"{module.name} se carga mediante un include indirecto. SquidStats no puede "
  1223. "verificar su orden sin arriesgar una carga duplicada; mueve su include a "
  1224. "squid.conf antes de activar Kerberos."
  1225. )
  1226. def _ensure_include(
  1227. content: str,
  1228. module_path: Path,
  1229. config_directory: Path | None = None,
  1230. *,
  1231. include_value: str | Path | None = None,
  1232. ) -> str:
  1233. """Ensure a generated modular file is loaded in numerical file order."""
  1234. config_directory = config_directory or module_path.parent.parent
  1235. lines = content.splitlines(keepends=True)
  1236. include_entries: list[tuple[int, int]] = []
  1237. for start_index, _end_index, logical_line in _logical_squid_line_locations(lines):
  1238. path = _include_path(logical_line)
  1239. if not path:
  1240. continue
  1241. if _include_matches_module(path, module_path, config_directory):
  1242. return content
  1243. include_entries.append((start_index, _include_rank(path)))
  1244. desired_rank = _include_rank(str(module_path))
  1245. insertion_index = len(lines)
  1246. for index, rank in include_entries:
  1247. if rank > desired_rank:
  1248. insertion_index = index
  1249. break
  1250. if insertion_index == len(lines) and include_entries:
  1251. insertion_index = include_entries[-1][0] + 1
  1252. include_line = (
  1253. f"include {include_value if include_value is not None else module_path}\n"
  1254. )
  1255. if insertion_index == len(lines):
  1256. if lines and not lines[-1].endswith("\n"):
  1257. lines[-1] += "\n"
  1258. if lines and lines[-1].strip():
  1259. include_line = "\n" + include_line
  1260. lines.insert(insertion_index, include_line)
  1261. return "".join(lines)
  1262. def _ensure_auth_include_before_access(
  1263. content: str,
  1264. module_path: Path,
  1265. config_directory: Path,
  1266. access_module_path: Path | None = None,
  1267. acl_module_path: Path | None = None,
  1268. *,
  1269. include_value: str | Path | None = None,
  1270. ) -> str:
  1271. """Load an auth module before access rules and proxy-auth dependencies.
  1272. A wildcard or explicit include after direct access rules, an ACL using
  1273. ``proxy_auth``, or an ``external_acl_type`` that asks for ``%LOGIN``
  1274. would define the authentication scheme too late. Adding another include
  1275. in that situation could load the helper twice, so reject the ambiguous
  1276. layout instead.
  1277. """
  1278. lines = content.splitlines(keepends=True)
  1279. logical_locations = _logical_squid_line_locations(lines)
  1280. matching_include_indices = [
  1281. start_index
  1282. for start_index, _end_index, logical_line in logical_locations
  1283. if (include_path := _include_path(logical_line))
  1284. and _include_matches_module(include_path, module_path, config_directory)
  1285. ]
  1286. access_indices = [
  1287. start_index
  1288. for start_index, _end_index, logical_line in logical_locations
  1289. if _is_http_access_line(logical_line)
  1290. ]
  1291. for consumer_module_path in (access_module_path, acl_module_path):
  1292. if consumer_module_path is None:
  1293. continue
  1294. access_indices.extend(
  1295. start_index
  1296. for start_index, _end_index, logical_line in logical_locations
  1297. if (include_path := _include_path(logical_line))
  1298. and _include_matches_module(
  1299. include_path, consumer_module_path, config_directory
  1300. )
  1301. )
  1302. dependency_indices = _direct_auth_dependency_indices(content, config_directory)
  1303. consumer_indices = [*access_indices, *dependency_indices]
  1304. first_consumer = min(consumer_indices) if consumer_indices else None
  1305. if matching_include_indices:
  1306. if first_consumer is not None and any(
  1307. index > first_consumer for index in matching_include_indices
  1308. ):
  1309. raise KerberosConfigurationError(
  1310. "El include de autenticación queda después de una regla o ACL que "
  1311. "depende de autenticación. Muévelo antes de esas reglas o termina de "
  1312. "modularizar la política antes de activar Kerberos."
  1313. )
  1314. return content
  1315. if first_consumer is None:
  1316. return _ensure_include(
  1317. content,
  1318. module_path,
  1319. config_directory,
  1320. include_value=include_value,
  1321. )
  1322. include_line = (
  1323. f"include {include_value if include_value is not None else module_path}\n"
  1324. )
  1325. prefix = (
  1326. ""
  1327. if first_consumer == 0 or lines[first_consumer - 1].endswith("\n\n")
  1328. else "\n"
  1329. )
  1330. lines.insert(first_consumer, prefix + include_line)
  1331. return "".join(lines)
  1332. def _find_squid_binary() -> str | None:
  1333. binary = shutil.which("squid")
  1334. if binary:
  1335. return binary
  1336. for candidate in ("/usr/sbin/squid", "/usr/local/sbin/squid"):
  1337. if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
  1338. return candidate
  1339. return None
  1340. def _configured_docker_container() -> str | None:
  1341. """Return a safe Docker container name, if Docker validation is enabled."""
  1342. container_name = os.getenv(
  1343. "SQUID_DOCKER_CONTAINER", DEFAULT_DOCKER_CONTAINER
  1344. ).strip()
  1345. return container_name if _CONTAINER_NAME_RE.fullmatch(container_name) else None
  1346. def _configured_docker_config_path() -> str | None:
  1347. """Return the in-container Squid config path, or None when unsafe."""
  1348. configured_path = os.getenv("SQUID_CONTAINER_CONFIG_PATH", "").strip()
  1349. if not configured_path:
  1350. return DEFAULT_DOCKER_CONFIG_PATH
  1351. return configured_path if _SAFE_PATH_RE.fullmatch(configured_path) else None
  1352. def _docker_runtime() -> _SquidRuntime | None:
  1353. """Find the running Squid Docker container without relying on a shell."""
  1354. docker_binary = shutil.which("docker")
  1355. container_name = _configured_docker_container()
  1356. if not docker_binary or not container_name:
  1357. return None
  1358. try:
  1359. result = subprocess.run( # nosec B603 # noqa: S603
  1360. [
  1361. docker_binary,
  1362. "container",
  1363. "inspect",
  1364. "--format",
  1365. "{{.State.Running}}",
  1366. container_name,
  1367. ],
  1368. capture_output=True,
  1369. text=True,
  1370. timeout=5,
  1371. check=False,
  1372. )
  1373. except (OSError, subprocess.TimeoutExpired):
  1374. return None
  1375. if result.returncode != 0 or result.stdout.strip().casefold() != "true":
  1376. return None
  1377. return _SquidRuntime(
  1378. kind="docker",
  1379. executable=docker_binary,
  1380. container_name=container_name,
  1381. container_config_path=_configured_docker_config_path(),
  1382. )
  1383. def _docker_mounts(
  1384. runtime: _SquidRuntime,
  1385. ) -> list[tuple[Path, PurePosixPath]] | None:
  1386. """Return a single, sanitized snapshot of Docker mounts for *runtime*.
  1387. ``None`` means inspection failed; an empty list means Docker answered but
  1388. no usable mount was present. Callers reuse a snapshot through one apply
  1389. transaction so a changing mount table cannot produce inconsistent checks.
  1390. """
  1391. if runtime.kind != "docker" or not runtime.container_name:
  1392. return None
  1393. try:
  1394. result = subprocess.run( # nosec B603 # noqa: S603
  1395. [runtime.executable, "container", "inspect", runtime.container_name],
  1396. capture_output=True,
  1397. text=True,
  1398. timeout=10,
  1399. check=False,
  1400. )
  1401. except (OSError, subprocess.TimeoutExpired):
  1402. return None
  1403. if result.returncode != 0:
  1404. return None
  1405. try:
  1406. inspected = json.loads(result.stdout)
  1407. raw_mounts = inspected[0].get("Mounts", []) if inspected else []
  1408. except (TypeError, ValueError, IndexError, AttributeError):
  1409. return None
  1410. mounts: list[tuple[Path, PurePosixPath]] = []
  1411. for mount in raw_mounts:
  1412. source = mount.get("Source") if isinstance(mount, dict) else None
  1413. destination = mount.get("Destination") if isinstance(mount, dict) else None
  1414. if not isinstance(source, str) or not isinstance(destination, str):
  1415. continue
  1416. destination_path = PurePosixPath(destination)
  1417. if not destination_path.is_absolute():
  1418. continue
  1419. mounts.append((Path(os.path.realpath(source)), destination_path))
  1420. return mounts
  1421. def _docker_path_mapping_status(
  1422. host_path: Path,
  1423. mounts: list[tuple[Path, PurePosixPath]] | None,
  1424. *,
  1425. expected_container_path: str | None = None,
  1426. mounts_checked: bool = True,
  1427. ) -> dict[str, Any]:
  1428. """Map a host config file to its visible path inside a Docker container.
  1429. Docker permits overlapping mounts. A host path matching a broad mount is
  1430. not usable if a more-specific mount hides its resulting container path, so
  1431. both namespaces are checked before reporting a mapping as valid.
  1432. """
  1433. status: dict[str, Any] = {
  1434. "checked": mounts_checked and mounts is not None,
  1435. "mapped": None,
  1436. "container_path": None,
  1437. "symlink": False,
  1438. }
  1439. if not mounts_checked or mounts is None:
  1440. return status
  1441. # SquidConfigManager resolves a final symlink before atomically replacing
  1442. # its target. Map that same real path rather than rejecting a valid
  1443. # package-provided ``squid.conf`` symlink.
  1444. status["symlink"] = host_path.is_symlink()
  1445. resolved_host_path = Path(os.path.realpath(str(host_path)))
  1446. host_matches: list[tuple[Path, PurePosixPath, Path]] = []
  1447. for source, destination in mounts:
  1448. try:
  1449. relative_path = resolved_host_path.relative_to(source)
  1450. except ValueError:
  1451. continue
  1452. host_matches.append((source, destination, relative_path))
  1453. if not host_matches:
  1454. status["mapped"] = False
  1455. return status
  1456. # The narrowest host source identifies the mount responsible for this
  1457. # particular host path.
  1458. source, destination, relative_path = max(
  1459. host_matches, key=lambda match: len(match[0].parts)
  1460. )
  1461. mapped_path = destination / PurePosixPath(relative_path.as_posix())
  1462. status["container_path"] = str(mapped_path)
  1463. # A separate, more-specific mount at the container destination can hide
  1464. # the path above. In that case the file we edit is not what Squid sees.
  1465. visible_mounts = []
  1466. for visible_source, visible_destination in mounts:
  1467. try:
  1468. mapped_path.relative_to(visible_destination)
  1469. except ValueError:
  1470. continue
  1471. visible_mounts.append((visible_source, visible_destination))
  1472. if visible_mounts:
  1473. visible_source, visible_destination = max(
  1474. visible_mounts, key=lambda match: len(match[1].parts)
  1475. )
  1476. if visible_source != source or visible_destination != destination:
  1477. status["mapped"] = False
  1478. return status
  1479. if expected_container_path is None:
  1480. status["mapped"] = True
  1481. else:
  1482. status["mapped"] = str(mapped_path) == str(
  1483. PurePosixPath(expected_container_path)
  1484. )
  1485. return status
  1486. def _docker_config_mount_status(
  1487. runtime: _SquidRuntime,
  1488. config_path: Path,
  1489. *,
  1490. mounts: list[tuple[Path, PurePosixPath]] | None = None,
  1491. mounts_checked: bool = False,
  1492. ) -> dict[str, Any]:
  1493. """Verify that the editable host main config maps to Squid's config path."""
  1494. if not mounts_checked:
  1495. mounts = _docker_mounts(runtime)
  1496. mounts_checked = True
  1497. status = _docker_path_mapping_status(
  1498. config_path,
  1499. mounts,
  1500. expected_container_path=runtime.container_config_path,
  1501. mounts_checked=mounts_checked,
  1502. )
  1503. status["container_config_path"] = runtime.container_config_path
  1504. return status
  1505. def _docker_target_mapping_statuses(
  1506. runtime: _SquidRuntime,
  1507. targets: list[_ConfigTarget],
  1508. main_path: Path,
  1509. mounts: list[tuple[Path, PurePosixPath]] | None,
  1510. *,
  1511. mounts_checked: bool,
  1512. ) -> dict[str, dict[str, Any]]:
  1513. """Return mount status for every in-memory target using one snapshot."""
  1514. main_realpath = os.path.realpath(str(main_path))
  1515. return {
  1516. str(target.path): _docker_path_mapping_status(
  1517. target.path,
  1518. mounts,
  1519. expected_container_path=(
  1520. runtime.container_config_path
  1521. if os.path.realpath(str(target.path)) == main_realpath
  1522. else None
  1523. ),
  1524. mounts_checked=mounts_checked,
  1525. )
  1526. for target in _unique_targets(targets)
  1527. }
  1528. def _require_mapped_docker_targets(
  1529. targets: list[_ConfigTarget],
  1530. mapping_statuses: Mapping[str, Mapping[str, Any]],
  1531. *,
  1532. main_target: _ConfigTarget,
  1533. ) -> None:
  1534. """Refuse writes for changed config files that Docker cannot see safely."""
  1535. changed_names = [
  1536. target.name
  1537. for target in _unique_targets(targets)
  1538. if target.content != target.original
  1539. ]
  1540. unmapped = [
  1541. target.name
  1542. for target in _unique_targets(targets)
  1543. if target.name in changed_names
  1544. and mapping_statuses.get(str(target.path), {}).get("mapped") is not True
  1545. ]
  1546. # A changed included module is only meaningful if the daemon also loads
  1547. # the exact main config that we validated for this transaction.
  1548. if changed_names and (
  1549. mapping_statuses.get(str(main_target.path), {}).get("mapped") is not True
  1550. ):
  1551. unmapped.append(main_target.name)
  1552. if unmapped:
  1553. raise KerberosConfigurationError(
  1554. "No se pudo comprobar que los archivos que cambiarán estén montados en Docker "
  1555. f"({', '.join(dict.fromkeys(unmapped))}). Revisa SQUID_CONTAINER_CONFIG_PATH y los volúmenes."
  1556. )
  1557. def _docker_container_path_for_target(
  1558. target: _ConfigTarget, mapping_statuses: Mapping[str, Mapping[str, Any]]
  1559. ) -> Path:
  1560. """Return the validated in-container path used in generated includes."""
  1561. status = mapping_statuses.get(str(target.path), {})
  1562. container_path = status.get("container_path")
  1563. if status.get("mapped") is not True or not isinstance(container_path, str):
  1564. raise KerberosConfigurationError(
  1565. f"No se pudo determinar la ruta Docker del módulo {target.name}."
  1566. )
  1567. return Path(container_path)
  1568. def _docker_relative_include_value(
  1569. main_target: _ConfigTarget,
  1570. target: _ConfigTarget,
  1571. mapping_statuses: Mapping[str, Mapping[str, Any]],
  1572. ) -> str:
  1573. """Return an include path that resolves to *target* in both namespaces.
  1574. The editable configuration is on the host, while Squid parses the same
  1575. text in the container. Writing an absolute container path makes a later
  1576. host-side ``SquidConfigManager`` select a nonexistent module directory.
  1577. A relative include is safe only when both mount layouts preserve the same
  1578. path from ``squid.conf`` to the module; otherwise fail before writing.
  1579. """
  1580. main_status = mapping_statuses.get(str(main_target.path), {})
  1581. target_status = mapping_statuses.get(str(target.path), {})
  1582. main_container_path = main_status.get("container_path")
  1583. target_container_path = target_status.get("container_path")
  1584. if (
  1585. main_status.get("mapped") is not True
  1586. or target_status.get("mapped") is not True
  1587. or not isinstance(main_container_path, str)
  1588. or not isinstance(target_container_path, str)
  1589. ):
  1590. raise KerberosConfigurationError(
  1591. f"No se pudo determinar una ruta Docker segura para el módulo {target.name}."
  1592. )
  1593. host_main_directory = Path(os.path.realpath(str(main_target.path))).parent
  1594. host_target_path = Path(os.path.realpath(str(target.path)))
  1595. host_relative = os.path.relpath(host_target_path, host_main_directory).replace(
  1596. os.sep, "/"
  1597. )
  1598. try:
  1599. container_relative = str(
  1600. PurePosixPath(target_container_path).relative_to(
  1601. PurePosixPath(main_container_path).parent
  1602. )
  1603. )
  1604. except ValueError as exc:
  1605. raise KerberosConfigurationError(
  1606. "Los volúmenes Docker no conservan una ruta relativa segura entre squid.conf y "
  1607. f"{target.name}. Configura un include activo manualmente antes de continuar."
  1608. ) from exc
  1609. if host_relative != container_relative:
  1610. raise KerberosConfigurationError(
  1611. "Los volúmenes Docker no conservan la misma ruta relativa entre squid.conf y "
  1612. f"{target.name}. Configura un include activo manualmente antes de continuar."
  1613. )
  1614. return host_relative
  1615. def _runtime_preference() -> str | None:
  1616. """Return a valid runtime preference, without silently accepting typos."""
  1617. preference = os.getenv("SQUID_RUNTIME", "auto").strip().casefold()
  1618. return preference if preference in _RUNTIME_PREFERENCES else None
  1619. def _find_squid_runtime() -> _SquidRuntime | None:
  1620. """Choose the runtime that owns the configured Squid instance.
  1621. ``auto`` is deliberately conservative: when both a local binary and a
  1622. Docker container are available, choosing the local one could validate and
  1623. reload the wrong proxy. Administrators must select ``local`` or ``docker``
  1624. explicitly in that case.
  1625. """
  1626. preference = _runtime_preference()
  1627. if preference is None:
  1628. logger.warning("Invalid SQUID_RUNTIME value; expected auto, local, or docker")
  1629. return None
  1630. local_runtime = None
  1631. docker_runtime = None
  1632. if preference in {"auto", "local"}:
  1633. squid_binary = _find_squid_binary()
  1634. if squid_binary:
  1635. local_runtime = _SquidRuntime(kind="local", executable=squid_binary)
  1636. if preference in {"auto", "docker"}:
  1637. docker_runtime = _docker_runtime()
  1638. if preference == "auto" and local_runtime and docker_runtime:
  1639. logger.warning(
  1640. "Both local and Docker Squid runtimes are available; set SQUID_RUNTIME explicitly"
  1641. )
  1642. return None
  1643. return local_runtime or docker_runtime
  1644. def _runtime_selection_error() -> str | None:
  1645. """Explain a runtime selection failure that cannot be inferred from None."""
  1646. preference = _runtime_preference()
  1647. if preference is None:
  1648. return "SQUID_RUNTIME debe ser auto, local o docker."
  1649. if preference == "local":
  1650. if not _find_squid_binary():
  1651. return (
  1652. "SQUID_RUNTIME=local está configurado, pero no se encontró Squid local."
  1653. )
  1654. return None
  1655. if preference == "docker":
  1656. if not _docker_runtime():
  1657. return (
  1658. "SQUID_RUNTIME=docker está configurado, pero no se encontró el "
  1659. "contenedor Squid en ejecución."
  1660. )
  1661. return None
  1662. if _find_squid_binary() and _docker_runtime():
  1663. return (
  1664. "Se detectaron Squid local y Docker; define SQUID_RUNTIME=local o "
  1665. "SQUID_RUNTIME=docker para no validar la instancia equivocada."
  1666. )
  1667. return None
  1668. def _squid_runtime_command(
  1669. runtime: _SquidRuntime, action: str, config_path: str | Path
  1670. ) -> list[str]:
  1671. if runtime.kind == "local":
  1672. return [runtime.executable, "-f", str(config_path), "-k", action]
  1673. command = [runtime.executable, "exec", str(runtime.container_name), "squid"]
  1674. if runtime.container_config_path:
  1675. command.extend(["-f", runtime.container_config_path])
  1676. command.extend(["-k", action])
  1677. return command
  1678. def _runtime_description(runtime: _SquidRuntime | None) -> dict[str, Any]:
  1679. if runtime is None:
  1680. return {"available": False, "kind": None, "container": None}
  1681. return {
  1682. "available": True,
  1683. "kind": runtime.kind,
  1684. "container": runtime.container_name,
  1685. }
  1686. def _default_squid_user(version_output: str) -> str | None:
  1687. """Extract Squid's configured build-time user when it is safely known."""
  1688. match = _SQUID_DEFAULT_USER_RE.search(version_output)
  1689. if match is None:
  1690. return None
  1691. candidate = next((value for value in match.groups() if value), None)
  1692. return candidate if candidate and _RUNTIME_USER_RE.fullmatch(candidate) else None
  1693. def _squid_version_status(runtime: _SquidRuntime | None) -> dict[str, Any]:
  1694. """Return a minimal, non-sensitive Squid version capability status.
  1695. ``auth_param`` is the directive required by this feature and was removed
  1696. in Squid v8. Parsing after a write remains the final authority, but this
  1697. early check avoids writing a known-incompatible configuration.
  1698. """
  1699. status: dict[str, Any] = {
  1700. "checked": False,
  1701. "version": None,
  1702. "supports_auth_param": None,
  1703. "default_user": None,
  1704. }
  1705. if runtime is None:
  1706. return status
  1707. try:
  1708. if runtime.kind == "docker":
  1709. result = _docker_exec(runtime, ["squid", "-v"])
  1710. else:
  1711. result = subprocess.run( # nosec B603 # noqa: S603
  1712. [runtime.executable, "-v"],
  1713. capture_output=True,
  1714. text=True,
  1715. timeout=10,
  1716. check=False,
  1717. )
  1718. except (OSError, subprocess.TimeoutExpired):
  1719. return status
  1720. if result is None or result.returncode != 0:
  1721. return status
  1722. status["checked"] = True
  1723. version_output = f"{result.stdout}\n{result.stderr}"
  1724. status["default_user"] = _default_squid_user(version_output)
  1725. version_match = _SQUID_VERSION_RE.search(version_output)
  1726. if not version_match:
  1727. return status
  1728. version = version_match.group(1)
  1729. status["version"] = version
  1730. status["supports_auth_param"] = int(version.split(".", 1)[0]) < 8
  1731. return status
  1732. def validate_squid_configuration(
  1733. config_path: str | Path, runtime: _SquidRuntime | None = None
  1734. ) -> dict[str, Any]:
  1735. """Run a syntax parse against the local or configured Docker runtime."""
  1736. runtime = runtime or _find_squid_runtime()
  1737. runtime_error = _runtime_selection_error() if runtime is None else None
  1738. if runtime is None:
  1739. return {
  1740. "available": False,
  1741. "valid": None,
  1742. "message": runtime_error
  1743. or "No se encontró un runtime Squid local ni Docker.",
  1744. }
  1745. if runtime.kind == "docker":
  1746. if not runtime.container_config_path:
  1747. return {
  1748. "available": True,
  1749. "valid": False,
  1750. "message": (
  1751. "SQUID_CONTAINER_CONFIG_PATH no es una ruta absoluta segura dentro del contenedor."
  1752. ),
  1753. }
  1754. mount_status = _docker_config_mount_status(
  1755. runtime,
  1756. Path(config_path),
  1757. mounts=_docker_mounts(runtime),
  1758. mounts_checked=True,
  1759. )
  1760. if mount_status.get("mapped") is not True:
  1761. return {
  1762. "available": True,
  1763. "valid": False,
  1764. "message": (
  1765. "No se pudo comprobar que el squid.conf que edita SquidStats esté montado como "
  1766. "el archivo cargado por el contenedor Docker. Revisa SQUID_CONTAINER_CONFIG_PATH y el volumen."
  1767. ),
  1768. }
  1769. try:
  1770. result = subprocess.run( # nosec B603 # noqa: S603
  1771. _squid_runtime_command(runtime, "parse", config_path),
  1772. capture_output=True,
  1773. text=True,
  1774. timeout=30,
  1775. check=False,
  1776. )
  1777. except (OSError, subprocess.TimeoutExpired) as exc:
  1778. logger.warning("Unable to parse Squid configuration: {}", exc)
  1779. return {
  1780. "available": True,
  1781. "valid": False,
  1782. "message": "No se pudo validar Squid.",
  1783. }
  1784. if result.returncode == 0:
  1785. return {"available": True, "valid": True, "message": "Configuración validada."}
  1786. logger.error(
  1787. "Squid parse failed for {}: {}\n{}",
  1788. config_path,
  1789. result.stdout,
  1790. result.stderr,
  1791. )
  1792. return {
  1793. "available": True,
  1794. "valid": False,
  1795. "message": "Squid rechazó la configuración.",
  1796. }
  1797. def reconfigure_squid(
  1798. config_path: str | Path, runtime: _SquidRuntime | None = None
  1799. ) -> tuple[bool, str]:
  1800. """Ask a local or Docker Squid runtime to reload a parsed configuration."""
  1801. runtime = runtime or _find_squid_runtime()
  1802. if runtime is None:
  1803. return False, "No se encontró un runtime Squid para recargar la configuración."
  1804. if runtime.kind == "docker":
  1805. if not runtime.container_config_path:
  1806. return (
  1807. False,
  1808. "SQUID_CONTAINER_CONFIG_PATH no es una ruta absoluta segura dentro del contenedor.",
  1809. )
  1810. mount_status = _docker_config_mount_status(
  1811. runtime,
  1812. Path(config_path),
  1813. mounts=_docker_mounts(runtime),
  1814. mounts_checked=True,
  1815. )
  1816. if mount_status.get("mapped") is not True:
  1817. return (
  1818. False,
  1819. "No se pudo comprobar que el squid.conf que edita SquidStats esté montado como "
  1820. "el archivo cargado por el contenedor Docker. Revisa SQUID_CONTAINER_CONFIG_PATH y el volumen.",
  1821. )
  1822. try:
  1823. result = subprocess.run( # nosec B603 # noqa: S603
  1824. _squid_runtime_command(runtime, "reconfigure", config_path),
  1825. capture_output=True,
  1826. text=True,
  1827. timeout=30,
  1828. check=False,
  1829. )
  1830. except (OSError, subprocess.TimeoutExpired) as exc:
  1831. logger.warning("Unable to reconfigure Squid: {}", exc)
  1832. return False, "No se pudo recargar Squid."
  1833. if result.returncode == 0:
  1834. return True, "Squid recargado."
  1835. logger.error(
  1836. "Squid reconfigure failed for {}: {}\n{}",
  1837. config_path,
  1838. result.stdout,
  1839. result.stderr,
  1840. )
  1841. return False, "Squid no pudo recargar la configuración."
  1842. def _user_has_unix_file_access(
  1843. path: Path,
  1844. username: str | None,
  1845. owner_bit: int,
  1846. group_bit: int,
  1847. other_bit: int,
  1848. ) -> bool | None:
  1849. """Estimate whether a Squid account can access a file and traverse parents.
  1850. This deliberately does not impersonate the service account or read a
  1851. keytab. POSIX ACLs are not introspected, so a ``False`` is a conservative
  1852. mode/group result rather than a replacement for ``sudo -u squid``.
  1853. """
  1854. if not username:
  1855. return None
  1856. try:
  1857. account = (
  1858. pwd.getpwuid(int(username))
  1859. if username.isdecimal()
  1860. else pwd.getpwnam(username)
  1861. )
  1862. except (KeyError, OSError, OverflowError, ValueError):
  1863. return None
  1864. groups = {account.pw_gid}
  1865. try:
  1866. groups.update(os.getgrouplist(username, account.pw_gid))
  1867. except (AttributeError, OSError):
  1868. pass
  1869. def has_permission(
  1870. file_stat: os.stat_result, owner_bit: int, group_bit: int, other_bit: int
  1871. ) -> bool:
  1872. if account.pw_uid == 0:
  1873. return True
  1874. if file_stat.st_uid == account.pw_uid:
  1875. return bool(file_stat.st_mode & owner_bit)
  1876. if file_stat.st_gid in groups:
  1877. return bool(file_stat.st_mode & group_bit)
  1878. return bool(file_stat.st_mode & other_bit)
  1879. try:
  1880. file_stat = path.stat()
  1881. if not has_permission(file_stat, owner_bit, group_bit, other_bit):
  1882. return False
  1883. directory = path.parent
  1884. while directory != directory.parent:
  1885. if not has_permission(
  1886. directory.stat(), stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH
  1887. ):
  1888. return False
  1889. directory = directory.parent
  1890. except OSError:
  1891. return False
  1892. return True
  1893. def _user_has_unix_read_access(path: Path, username: str | None) -> bool | None:
  1894. """Estimate whether a configured Squid user can traverse/read *path*."""
  1895. return _user_has_unix_file_access(
  1896. path, username, stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH
  1897. )
  1898. def _user_has_unix_execute_access(path: Path, username: str | None) -> bool | None:
  1899. """Estimate whether a configured Squid user can execute *path*."""
  1900. return _user_has_unix_file_access(
  1901. path, username, stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH
  1902. )
  1903. def _docker_exec(
  1904. runtime: _SquidRuntime, arguments: list[str], *, user: str | None = None
  1905. ) -> subprocess.CompletedProcess[str] | None:
  1906. """Execute a fixed Docker command without returning its potentially sensitive output."""
  1907. if runtime.kind != "docker" or not runtime.container_name:
  1908. return None
  1909. command = [runtime.executable, "exec"]
  1910. if user and _RUNTIME_USER_RE.fullmatch(user):
  1911. command.extend(["--user", user])
  1912. command.extend([runtime.container_name, *arguments])
  1913. try:
  1914. return subprocess.run( # nosec B603 # noqa: S603
  1915. command,
  1916. capture_output=True,
  1917. text=True,
  1918. timeout=10,
  1919. check=False,
  1920. )
  1921. except (OSError, subprocess.TimeoutExpired):
  1922. return None
  1923. def _docker_test(
  1924. runtime: _SquidRuntime, option: str, path: str, *, user: str | None = None
  1925. ) -> bool | None:
  1926. """Return a Docker runtime file-test result, or None when it could not run."""
  1927. result = _docker_exec(runtime, ["test", option, path], user=user)
  1928. if result is None:
  1929. return None
  1930. return result.returncode == 0
  1931. def _mode_from_stat_output(output: str) -> int | None:
  1932. """Parse the permission mode emitted by ``stat -c %a`` safely."""
  1933. match = re.fullmatch(r"\s*([0-7]{3,4})\s*", output)
  1934. return int(match.group(1), 8) if match else None
  1935. def _keytab_status(
  1936. keytab_path: str,
  1937. service_principal: str,
  1938. squid_user: str | None = None,
  1939. runtime: _SquidRuntime | None = None,
  1940. ) -> dict[str, Any]:
  1941. path = Path(keytab_path)
  1942. status: dict[str, Any] = {
  1943. "path": str(path),
  1944. "check_available": True,
  1945. "exists": False,
  1946. "regular_file": False,
  1947. "application_readable": False,
  1948. "runtime_default_readable": None,
  1949. "mode": None,
  1950. "permissions_checked": False,
  1951. "world_readable": False,
  1952. "group_writable": False,
  1953. "world_writable": False,
  1954. "squid_user": squid_user,
  1955. "squid_user_readable": None,
  1956. "checked_in_runtime": bool(runtime and runtime.kind == "docker"),
  1957. "spn_checked": False,
  1958. "spn_present": None,
  1959. }
  1960. if runtime and runtime.kind == "docker":
  1961. exists = _docker_test(runtime, "-e", keytab_path)
  1962. regular_file = _docker_test(runtime, "-f", keytab_path)
  1963. readable = _docker_test(runtime, "-r", keytab_path)
  1964. checks = (exists, regular_file, readable)
  1965. status.update(
  1966. {
  1967. "check_available": all(result is not None for result in checks),
  1968. "exists": exists is True,
  1969. "regular_file": regular_file is True,
  1970. # This check uses Docker's default exec user (commonly root),
  1971. # so it must not be presented as Squid's effective access.
  1972. "runtime_default_readable": readable is True,
  1973. "application_readable": None,
  1974. }
  1975. )
  1976. if not status["check_available"]:
  1977. return status
  1978. if status["regular_file"]:
  1979. mode_result = _docker_exec(runtime, ["stat", "-c", "%a", keytab_path])
  1980. if mode_result and mode_result.returncode == 0:
  1981. mode = _mode_from_stat_output(mode_result.stdout)
  1982. if mode is not None:
  1983. status["permissions_checked"] = True
  1984. status["mode"] = f"{mode:04o}"
  1985. status["world_readable"] = bool(mode & stat.S_IROTH)
  1986. status["group_writable"] = bool(mode & stat.S_IWGRP)
  1987. status["world_writable"] = bool(mode & stat.S_IWOTH)
  1988. if squid_user:
  1989. if not _RUNTIME_USER_RE.fullmatch(squid_user):
  1990. status["check_available"] = False
  1991. return status
  1992. squid_user_readable = _docker_test(
  1993. runtime, "-r", keytab_path, user=squid_user
  1994. )
  1995. status["squid_user_readable"] = squid_user_readable
  1996. if squid_user_readable is None:
  1997. status["check_available"] = False
  1998. return status
  1999. # The helper is started by Squid's effective user, not necessarily
  2000. # by Docker's default exec user (often root).
  2001. status["application_readable"] = squid_user_readable is True
  2002. if not status["regular_file"] or not status["application_readable"]:
  2003. return status
  2004. result = _docker_exec(runtime, ["klist", "-k", keytab_path], user=squid_user)
  2005. if result and result.returncode == 0:
  2006. status["spn_checked"] = True
  2007. output = f"{result.stdout}\n{result.stderr}"
  2008. status["spn_present"] = _keytab_contains_principal(
  2009. output, service_principal
  2010. )
  2011. return status
  2012. try:
  2013. file_stat = path.stat()
  2014. except OSError:
  2015. return status
  2016. status.update(
  2017. {
  2018. "exists": True,
  2019. "regular_file": stat.S_ISREG(file_stat.st_mode),
  2020. "application_readable": os.access(path, os.R_OK),
  2021. "mode": f"{stat.S_IMODE(file_stat.st_mode):04o}",
  2022. "permissions_checked": True,
  2023. "world_readable": bool(file_stat.st_mode & stat.S_IROTH),
  2024. "group_writable": bool(file_stat.st_mode & stat.S_IWGRP),
  2025. "world_writable": bool(file_stat.st_mode & stat.S_IWOTH),
  2026. }
  2027. )
  2028. status["squid_user_readable"] = _user_has_unix_read_access(path, squid_user)
  2029. if (
  2030. not status["regular_file"]
  2031. or not status["application_readable"]
  2032. or not service_principal
  2033. ):
  2034. return status
  2035. klist = shutil.which("klist")
  2036. if not klist:
  2037. return status
  2038. try:
  2039. result = subprocess.run( # nosec B603 # noqa: S603
  2040. [klist, "-k", str(path)],
  2041. capture_output=True,
  2042. text=True,
  2043. timeout=10,
  2044. check=False,
  2045. )
  2046. except (OSError, subprocess.TimeoutExpired):
  2047. return status
  2048. if result.returncode == 0:
  2049. status["spn_checked"] = True
  2050. output = f"{result.stdout}\n{result.stderr}"
  2051. status["spn_present"] = _keytab_contains_principal(output, service_principal)
  2052. return status
  2053. def _helper_status(
  2054. helper_path: str,
  2055. runtime: _SquidRuntime | None = None,
  2056. squid_user: str | None = None,
  2057. ) -> dict[str, Any]:
  2058. """Check helper execution from the perspective of Squid's account."""
  2059. if runtime and runtime.kind == "docker":
  2060. if squid_user and not _RUNTIME_USER_RE.fullmatch(squid_user):
  2061. return {
  2062. "path": helper_path,
  2063. "check_available": False,
  2064. "exists": False,
  2065. "executable": False,
  2066. "checked_in_runtime": True,
  2067. "squid_user": squid_user,
  2068. "squid_user_executable": None,
  2069. }
  2070. user = squid_user
  2071. exists = _docker_test(runtime, "-f", helper_path, user=user)
  2072. executable = _docker_test(runtime, "-x", helper_path, user=user)
  2073. return {
  2074. "path": helper_path,
  2075. "check_available": exists is not None and executable is not None,
  2076. "exists": exists is True,
  2077. "executable": executable is True,
  2078. "checked_in_runtime": True,
  2079. "squid_user": squid_user,
  2080. "squid_user_executable": executable if user else None,
  2081. }
  2082. path = Path(helper_path)
  2083. application_executable = path.is_file() and os.access(path, os.X_OK)
  2084. squid_user_executable = _user_has_unix_execute_access(path, squid_user)
  2085. return {
  2086. "path": str(path),
  2087. "check_available": True,
  2088. "exists": path.is_file(),
  2089. "executable": (
  2090. squid_user_executable
  2091. if squid_user_executable is not None
  2092. else application_executable
  2093. ),
  2094. "application_executable": application_executable,
  2095. "squid_user": squid_user,
  2096. "squid_user_executable": squid_user_executable,
  2097. "checked_in_runtime": False,
  2098. }
  2099. def _proxy_mode_status(config_manager) -> dict[str, Any]:
  2100. main_content = str(getattr(config_manager, "config_content", "") or "")
  2101. included_sources = _active_included_configuration_sources(config_manager)
  2102. content_sources = [main_content, *(content for _path, content in included_sources)]
  2103. # Keep compatibility with lightweight/legacy managers that know they are
  2104. # modular but do not expose their active include lines to this service.
  2105. if bool(getattr(config_manager, "is_modular", False)) and not included_sources:
  2106. ports_content = _read_optional_module(config_manager, "00_ports.conf")
  2107. if ports_content is not None:
  2108. content_sources.append(ports_content)
  2109. ports = [
  2110. line.casefold()
  2111. for content in content_sources
  2112. for line in _logical_squid_lines(content)
  2113. if _PORT_DIRECTIVE_RE.match(line)
  2114. ]
  2115. intercepted = [
  2116. line
  2117. for line in ports
  2118. if re.search(r"(?:^|\s)(?:intercept|transparent|tproxy)(?:\s|$)", line)
  2119. ]
  2120. # ``accel`` turns a listener into reverse/accelerator mode. It is not an
  2121. # explicit forward proxy even though it lacks the interception keywords;
  2122. # Negotiate's Proxy-Authorization exchange cannot be used there.
  2123. accelerated = [line for line in ports if re.search(r"(?:^|\s)accel(?:\s|$)", line)]
  2124. # Connection-oriented authentication is how Negotiate/Kerberos works on
  2125. # a forward-proxy listener. Squid documents connection-auth=off as
  2126. # disabling forwarding of those exchanges, so a listener with that option
  2127. # cannot be counted as usable for this feature.
  2128. connection_auth_disabled = [
  2129. line
  2130. for line in ports
  2131. if re.search(r"(?:^|\s)connection-auth\s*=\s*off(?:\s|$)", line)
  2132. ]
  2133. incompatible = [
  2134. line
  2135. for line in ports
  2136. if line in intercepted
  2137. or line in accelerated
  2138. or line in connection_auth_disabled
  2139. ]
  2140. explicit = [line for line in ports if line not in incompatible]
  2141. return {
  2142. "ports_found": bool(ports),
  2143. "explicit_proxy_available": bool(explicit) if ports else None,
  2144. "intercept_ports": len(intercepted),
  2145. "reverse_proxy_ports": len(accelerated),
  2146. "connection_auth_disabled_ports": len(connection_auth_disabled),
  2147. "incompatible_ports": len(incompatible),
  2148. }
  2149. def _find_cache_effective_user(config_manager) -> str | None:
  2150. included_sources = _active_included_configuration_sources(config_manager)
  2151. contents = [
  2152. str(getattr(config_manager, "config_content", "") or ""),
  2153. *(content for _path, content in included_sources),
  2154. ]
  2155. if bool(getattr(config_manager, "is_modular", False)) and not included_sources:
  2156. for filename in ("10_misc.conf", "30_cache.conf", "00_ports.conf"):
  2157. content = _read_optional_module(config_manager, filename)
  2158. if content:
  2159. contents.append(content)
  2160. for content in contents:
  2161. for line in _logical_squid_lines(content):
  2162. match = _CACHE_EFFECTIVE_USER_RE.match(line)
  2163. if match:
  2164. return match.group(1)
  2165. return None
  2166. def _has_unmanaged_negotiate(content: str) -> bool:
  2167. cleaned = _remove_managed_auth(content)
  2168. return bool(_negotiate_directive_lines(cleaned))
  2169. def get_preflight(
  2170. config_manager,
  2171. settings: KerberosSettings | Mapping[str, Any],
  2172. runtime: _SquidRuntime | None = None,
  2173. *,
  2174. docker_mounts: list[tuple[Path, PurePosixPath]] | None = None,
  2175. docker_mounts_checked: bool = False,
  2176. ) -> dict[str, Any]:
  2177. """Inspect prerequisites without exposing keytab bytes or command output."""
  2178. settings = _validated_settings(settings)
  2179. manager_valid = bool(getattr(config_manager, "is_valid", False))
  2180. config_path = Path(str(getattr(config_manager, "config_path", "squid.conf")))
  2181. errors = (
  2182. list(getattr(config_manager, "errors", []) or []) if not manager_valid else []
  2183. )
  2184. if manager_valid:
  2185. errors.extend(_configuration_source_inspection_errors(config_manager))
  2186. warnings: list[str] = []
  2187. runtime = runtime or _find_squid_runtime()
  2188. runtime_error = _runtime_selection_error() if runtime is None else None
  2189. squid_version = _squid_version_status(runtime)
  2190. if runtime is not None and runtime.kind == "docker" and not docker_mounts_checked:
  2191. docker_mounts = _docker_mounts(runtime)
  2192. docker_mounts_checked = True
  2193. docker_config = (
  2194. _docker_config_mount_status(
  2195. runtime,
  2196. config_path,
  2197. mounts=docker_mounts,
  2198. mounts_checked=docker_mounts_checked,
  2199. )
  2200. if runtime is not None and runtime.kind == "docker"
  2201. else None
  2202. )
  2203. configured_squid_user = _find_cache_effective_user(config_manager)
  2204. squid_user = configured_squid_user or squid_version.get("default_user")
  2205. squid_user_source = (
  2206. "cache_effective_user"
  2207. if configured_squid_user
  2208. else "build_default"
  2209. if squid_user
  2210. else None
  2211. )
  2212. helper = (
  2213. _helper_status(settings.helper_path, runtime, squid_user)
  2214. if settings.enabled
  2215. else None
  2216. )
  2217. keytab = (
  2218. _keytab_status(
  2219. settings.keytab_path,
  2220. settings.service_principal,
  2221. squid_user,
  2222. runtime,
  2223. )
  2224. if settings.enabled
  2225. else None
  2226. )
  2227. proxy_mode = _proxy_mode_status(config_manager)
  2228. manual_write_message = _manual_squid_write_message()
  2229. config_writable = (
  2230. manager_valid
  2231. and manual_write_message is None
  2232. and os.access(config_path, os.W_OK)
  2233. )
  2234. if manual_write_message:
  2235. errors.append(manual_write_message)
  2236. elif manager_valid and not config_writable:
  2237. errors.append(
  2238. "SquidStats no tiene permiso para escribir el squid.conf configurado."
  2239. )
  2240. if manual_write_message is None and bool(
  2241. getattr(config_manager, "is_modular", False)
  2242. ):
  2243. config_dir = Path(str(getattr(config_manager, "config_dir", "")))
  2244. if not config_dir.is_dir() or not os.access(config_dir, os.W_OK):
  2245. errors.append(
  2246. "SquidStats no tiene permiso para escribir el directorio de configuración modular."
  2247. )
  2248. if settings.enabled:
  2249. if runtime_error:
  2250. errors.append(runtime_error)
  2251. if settings.reload_squid and runtime is None:
  2252. if not runtime_error:
  2253. errors.append(
  2254. "No se encontró un runtime Squid local ni Docker para validar y recargar. "
  2255. "Desmarca la recarga solo si harás ambas operaciones manualmente."
  2256. )
  2257. if runtime is not None and runtime.kind == "docker":
  2258. if not runtime.container_config_path:
  2259. errors.append(
  2260. "SQUID_CONTAINER_CONFIG_PATH no es una ruta absoluta segura dentro del contenedor."
  2261. )
  2262. elif docker_config is None or docker_config["mapped"] is not True:
  2263. errors.append(
  2264. "No se pudo comprobar que el squid.conf que edita SquidStats esté montado como "
  2265. "el archivo cargado por el contenedor Docker. Revisa SQUID_CONTAINER_CONFIG_PATH y el volumen."
  2266. )
  2267. if not squid_user:
  2268. errors.append(
  2269. "No se pudo determinar el usuario efectivo de Squid. Declara cache_effective_user "
  2270. "o usa un runtime que informe su usuario predeterminado antes de aplicar, para "
  2271. "comprobar el acceso real al keytab."
  2272. )
  2273. if squid_version["supports_auth_param"] is False:
  2274. errors.append(
  2275. "La versión de Squid detectada no admite auth_param; Kerberos/SPNEGO debe configurarse con un método compatible con Squid v8."
  2276. )
  2277. if not helper["check_available"]:
  2278. errors.append("No se pudo comprobar el helper Kerberos en el runtime.")
  2279. elif not helper["exists"]:
  2280. errors.append("No se encontró el helper Kerberos indicado.")
  2281. elif not helper["executable"]:
  2282. errors.append("El helper Kerberos no tiene permiso de ejecución.")
  2283. if not keytab["check_available"]:
  2284. errors.append("No se pudo comprobar el keytab en el runtime de Squid.")
  2285. elif not keytab["exists"]:
  2286. errors.append("No se encontró el keytab indicado.")
  2287. elif not keytab["regular_file"]:
  2288. errors.append("La ruta del keytab no es un archivo regular.")
  2289. elif (
  2290. runtime is not None
  2291. and runtime.kind == "docker"
  2292. and not keytab.get("permissions_checked", False)
  2293. ):
  2294. errors.append(
  2295. "No se pudieron comprobar los permisos del keytab dentro del contenedor Docker."
  2296. )
  2297. elif not keytab["application_readable"] and not keytab["checked_in_runtime"]:
  2298. warnings.append(
  2299. "SquidStats no puede leer el keytab; verifica que el usuario efectivo de Squid sí pueda hacerlo."
  2300. )
  2301. elif keytab["application_readable"] is False:
  2302. warnings.append(
  2303. "El usuario efectivo de Squid no pudo leer el keytab dentro del runtime Docker; verifica el montaje y sus permisos."
  2304. )
  2305. elif keytab["application_readable"] is None:
  2306. warnings.append(
  2307. "No se pudo verificar el acceso del usuario efectivo de Squid al keytab dentro del runtime Docker."
  2308. )
  2309. if (
  2310. runtime is not None
  2311. and runtime.kind == "docker"
  2312. and keytab["squid_user"]
  2313. and keytab["squid_user_readable"] is False
  2314. ):
  2315. errors.append(
  2316. "El usuario efectivo de Squid no puede leer el keytab dentro del contenedor. "
  2317. "Corrige el montaje, propietario o grupo antes de aplicar."
  2318. )
  2319. elif keytab["squid_user"] and keytab["squid_user_readable"] is False:
  2320. errors.append(
  2321. "Los permisos Unix actuales no permiten leer el keytab al usuario efectivo de Squid. "
  2322. "Corrige propietario, grupo, ACLs o directorios padre antes de aplicar."
  2323. )
  2324. elif (
  2325. keytab["squid_user"]
  2326. and keytab["exists"]
  2327. and keytab["regular_file"]
  2328. and keytab["squid_user_readable"] is None
  2329. ):
  2330. errors.append(
  2331. "No se pudo verificar que el usuario efectivo de Squid exista y pueda leer el "
  2332. "keytab. Corrige cache_effective_user o los permisos antes de aplicar."
  2333. )
  2334. elif squid_user_source == "build_default":
  2335. warnings.append(
  2336. "cache_effective_user no se declaró; se usó el usuario predeterminado "
  2337. f"compilado de Squid ({squid_user}) para la comprobación. Confírmalo o "
  2338. "decláralo explícitamente."
  2339. )
  2340. if keytab.get("world_readable"):
  2341. errors.append(
  2342. "El keytab es legible por todos los usuarios; restringe sus permisos antes de aplicar."
  2343. )
  2344. if keytab.get("group_writable") or keytab.get("world_writable"):
  2345. errors.append(
  2346. "El keytab es modificable por usuarios que no son su propietario; restringe "
  2347. "los permisos de escritura antes de aplicar."
  2348. )
  2349. if keytab["spn_checked"] and not keytab["spn_present"]:
  2350. errors.append("El keytab no contiene el SPN configurado.")
  2351. elif not keytab["spn_checked"]:
  2352. warnings.append(
  2353. "No se pudo comprobar el SPN con klist; verifica el keytab en el runtime de Squid."
  2354. )
  2355. if proxy_mode["incompatible_ports"]:
  2356. errors.append(
  2357. "Kerberos/Negotiate no puede coexistir con puertos intercept, transparent, tproxy, accel "
  2358. "(reverse proxy) ni connection-auth=off; sepáralos o elimina ese modo antes de aplicar."
  2359. )
  2360. elif proxy_mode["explicit_proxy_available"] is False:
  2361. errors.append(
  2362. "Kerberos/Negotiate requiere un proxy explícito; intercept, transparent, tproxy, accel y connection-auth=off no son compatibles."
  2363. )
  2364. elif proxy_mode["explicit_proxy_available"] is None:
  2365. warnings.append(
  2366. "No se encontraron puertos http_port/https_port para comprobar si el proxy es explícito."
  2367. )
  2368. return {
  2369. "ready": not errors,
  2370. "errors": errors,
  2371. "warnings": warnings,
  2372. "config": {
  2373. "path": str(config_path),
  2374. "writable": config_writable,
  2375. "write_mode": _squid_config_write_mode(),
  2376. "modular": bool(getattr(config_manager, "is_modular", False)),
  2377. },
  2378. "helper": helper,
  2379. "keytab": keytab,
  2380. "proxy_mode": proxy_mode,
  2381. "squid_user": squid_user,
  2382. "squid_user_source": squid_user_source,
  2383. "runtime": _runtime_description(runtime),
  2384. "docker_config": docker_config,
  2385. "squid_version": squid_version,
  2386. "squid_binary_available": runtime is not None,
  2387. }
  2388. def _parse_auth_content(content: str) -> tuple[KerberosSettings, bool, bool]:
  2389. """Return settings, whether Kerberos was found, and marker ownership."""
  2390. managed_block = _find_complete_block(content, MANAGED_AUTH_START, MANAGED_AUTH_END)
  2391. legacy_block = _find_complete_block(
  2392. content, LEGACY_MANAGED_AUTH_START, LEGACY_MANAGED_AUTH_END
  2393. )
  2394. candidate = managed_block or legacy_block or content
  2395. managed = managed_block is not None
  2396. settings = default_settings()
  2397. found = False
  2398. for line in _logical_squid_lines(candidate):
  2399. parts = line.split()
  2400. lowered = [part.casefold() for part in parts]
  2401. if len(parts) >= 4 and lowered[:3] == ["auth_param", "negotiate", "program"]:
  2402. found = True
  2403. helper_path = parts[3]
  2404. keytab_path = settings.keytab_path
  2405. service_principal = settings.service_principal
  2406. strip_realm = "-r" in parts[4:]
  2407. for index, item in enumerate(parts[4:], start=4):
  2408. if item == "-k" and index + 1 < len(parts):
  2409. keytab_path = parts[index + 1]
  2410. if item == "-s" and index + 1 < len(parts):
  2411. service_principal = parts[index + 1]
  2412. settings = KerberosSettings(
  2413. **{
  2414. **settings.to_dict(),
  2415. "enabled": True,
  2416. "helper_path": helper_path,
  2417. "keytab_path": keytab_path,
  2418. "service_principal": service_principal,
  2419. "strip_realm": strip_realm,
  2420. }
  2421. )
  2422. elif len(parts) >= 4 and lowered[:3] == ["auth_param", "negotiate", "children"]:
  2423. values = {
  2424. item.split("=", 1)[0]: item.split("=", 1)[1]
  2425. for item in parts[4:]
  2426. if "=" in item
  2427. }
  2428. try:
  2429. settings = KerberosSettings(
  2430. **{
  2431. **settings.to_dict(),
  2432. "children": int(parts[3]),
  2433. "startup": int(values.get("startup", settings.startup)),
  2434. "idle": int(values.get("idle", settings.idle)),
  2435. }
  2436. )
  2437. except ValueError:
  2438. pass
  2439. elif len(parts) >= 4 and lowered[:3] == [
  2440. "auth_param",
  2441. "negotiate",
  2442. "keep_alive",
  2443. ]:
  2444. settings = KerberosSettings(
  2445. **{
  2446. **settings.to_dict(),
  2447. "keep_alive": parts[3].casefold() == "on",
  2448. }
  2449. )
  2450. elif (
  2451. len(parts) >= 4
  2452. and lowered[0] == "acl"
  2453. and lowered[-2:] == ["proxy_auth", "required"]
  2454. ):
  2455. settings = KerberosSettings(**{**settings.to_dict(), "acl_name": parts[1]})
  2456. return settings, found, managed
  2457. def _has_access_rule(content: str, acl_name: str) -> bool:
  2458. expected = {
  2459. f"http_access deny !{acl_name}".casefold(),
  2460. # Recognise a manually maintained older form for status display. It
  2461. # is not generated because it does not reliably force a challenge.
  2462. f"http_access allow {acl_name}".casefold(),
  2463. }
  2464. return any(
  2465. _uncommented(line).casefold() in expected for line in content.splitlines()
  2466. )
  2467. def load_configuration(config_manager) -> dict[str, Any]:
  2468. """Read current Squid Kerberos settings for the frontend without secrets."""
  2469. main = _target_from_main(config_manager)
  2470. modular = bool(getattr(config_manager, "is_modular", False))
  2471. candidates: list[tuple[str, str]] = [("squid.conf", main.content)]
  2472. access_contents = [main.content]
  2473. included_sources = _active_included_configuration_sources(config_manager)
  2474. active_paths = {os.path.realpath(path) for path, _content in included_sources}
  2475. inactive_conventional_sources: list[str] = []
  2476. auth: _ConfigTarget | None = None
  2477. if modular:
  2478. auth = _target_from_module(config_manager, AUTH_MODULE_FILENAME)
  2479. access = _target_from_module(config_manager, HTTP_ACCESS_MODULE_FILENAME)
  2480. if os.path.realpath(str(auth.path)) in active_paths:
  2481. candidates.append((AUTH_MODULE_FILENAME, auth.content))
  2482. elif auth.content and (
  2483. _negotiate_directive_lines(auth.content)
  2484. or MANAGED_AUTH_START in auth.content
  2485. or LEGACY_MANAGED_AUTH_START in auth.content
  2486. ):
  2487. # Do not report inactive files as live Kerberos configuration.
  2488. # Keep their presence visible so an administrator can decide
  2489. # whether to remove them or include them deliberately.
  2490. inactive_conventional_sources.append(AUTH_MODULE_FILENAME)
  2491. if os.path.realpath(str(access.path)) in active_paths:
  2492. access_contents.append(access.content)
  2493. elif access.content and MANAGED_ACCESS_START in access.content:
  2494. inactive_conventional_sources.append(HTTP_ACCESS_MODULE_FILENAME)
  2495. managed_candidate_paths = {
  2496. os.path.realpath(str(main.path)),
  2497. *([os.path.realpath(str(auth.path))] if auth is not None else []),
  2498. }
  2499. external_candidates = [
  2500. (path, content)
  2501. for path, content in included_sources
  2502. if os.path.realpath(path) not in managed_candidate_paths
  2503. ]
  2504. # Preserve the conventional files as the preferred source, but show an
  2505. # active helper from a custom include instead of presenting the UI as
  2506. # "not configured". Such a source is deliberately not writable by this
  2507. # managed flow; apply_configuration will require manual migration first.
  2508. candidates.extend(external_candidates)
  2509. candidate_contents = [content for _source, content in candidates]
  2510. access_contents.extend(content for _source, content in included_sources)
  2511. for _source, content in candidates:
  2512. _assert_complete_managed_blocks(content)
  2513. for content in access_contents:
  2514. _assert_complete_managed_blocks(content)
  2515. selected_source = "squid.conf"
  2516. settings = default_settings()
  2517. detected = False
  2518. managed = False
  2519. for source, content in candidates:
  2520. parsed, found, owns_block = _parse_auth_content(content)
  2521. if found:
  2522. settings = parsed
  2523. selected_source = source
  2524. detected = True
  2525. managed = owns_block and source in {
  2526. "squid.conf",
  2527. AUTH_MODULE_FILENAME,
  2528. }
  2529. break
  2530. if detected:
  2531. access_managed = any(
  2532. MANAGED_ACCESS_START in content for content in access_contents
  2533. )
  2534. access_present = any(
  2535. _has_access_rule(content, settings.acl_name) for content in access_contents
  2536. )
  2537. settings = KerberosSettings(
  2538. **{
  2539. **settings.to_dict(),
  2540. "enforce_auth": access_managed or access_present,
  2541. "reload_squid": True,
  2542. }
  2543. )
  2544. return {
  2545. "settings": settings.to_dict(),
  2546. "detected": detected,
  2547. "managed": managed,
  2548. "source": selected_source,
  2549. "unmanaged_negotiate": any(
  2550. _has_unmanaged_negotiate(content) for content in candidate_contents
  2551. )
  2552. or any(
  2553. _negotiate_directive_lines(content)
  2554. for _path, content in external_candidates
  2555. ),
  2556. "other_auth_schemes": sorted(
  2557. {
  2558. scheme
  2559. for content in [
  2560. *candidate_contents,
  2561. *(content for _path, content in included_sources),
  2562. ]
  2563. for scheme in _other_auth_program_schemes(content)
  2564. }
  2565. ),
  2566. "inactive_conventional_sources": inactive_conventional_sources,
  2567. }
  2568. def get_status(config_manager) -> dict[str, Any]:
  2569. """Return UI data and non-sensitive server-side prerequisite status."""
  2570. load_error = None
  2571. try:
  2572. configuration = load_configuration(config_manager)
  2573. except KerberosConfigurationError as exc:
  2574. # Do not let a partially hand-edited marker hide the recovery UI.
  2575. # Applying a change remains blocked by the same marker check until an
  2576. # administrator repairs it manually.
  2577. load_error = str(exc)
  2578. configuration = {
  2579. "settings": default_settings().to_dict(),
  2580. "detected": False,
  2581. "managed": False,
  2582. "source": "squid.conf",
  2583. "unmanaged_negotiate": False,
  2584. "other_auth_schemes": [],
  2585. "inactive_conventional_sources": [],
  2586. }
  2587. try:
  2588. settings = normalise_settings(configuration["settings"])
  2589. preview = render_preview(settings)
  2590. preflight = get_preflight(config_manager, settings)
  2591. configuration_error = load_error
  2592. if load_error:
  2593. preflight["ready"] = False
  2594. preflight["errors"].insert(0, load_error)
  2595. except KerberosConfigurationError as exc:
  2596. # A hand-edited, incomplete configuration should remain visible in the
  2597. # form instead of turning the administration page into a 500 error.
  2598. settings = KerberosSettings(**configuration["settings"])
  2599. preview = "# La configuración existente tiene valores inválidos; corrígelos antes de aplicar.\n"
  2600. runtime = _find_squid_runtime()
  2601. squid_version = _squid_version_status(runtime)
  2602. manual_write_message = _manual_squid_write_message()
  2603. preflight = {
  2604. "ready": False,
  2605. "errors": [
  2606. str(exc),
  2607. *([manual_write_message] if manual_write_message else []),
  2608. ],
  2609. "warnings": [],
  2610. "config": {
  2611. "path": str(getattr(config_manager, "config_path", "squid.conf")),
  2612. "writable": bool(getattr(config_manager, "is_valid", False))
  2613. and manual_write_message is None
  2614. and os.access(str(getattr(config_manager, "config_path", "")), os.W_OK),
  2615. "write_mode": _squid_config_write_mode(),
  2616. "modular": bool(getattr(config_manager, "is_modular", False)),
  2617. },
  2618. "helper": None,
  2619. "keytab": None,
  2620. "proxy_mode": _proxy_mode_status(config_manager),
  2621. "squid_user": _find_cache_effective_user(config_manager),
  2622. "squid_user_source": None,
  2623. "runtime": _runtime_description(runtime),
  2624. "docker_config": None,
  2625. "squid_version": squid_version,
  2626. "squid_binary_available": runtime is not None,
  2627. }
  2628. configuration_error = str(exc)
  2629. return {
  2630. **configuration,
  2631. "preflight": preflight,
  2632. "preview": preview,
  2633. "configuration_error": configuration_error,
  2634. }
  2635. def _write_targets(targets: list[_ConfigTarget]) -> list[_ConfigTarget]:
  2636. written: list[_ConfigTarget] = []
  2637. for target in _unique_targets(targets):
  2638. if target.content == target.original:
  2639. continue
  2640. try:
  2641. saved = target.save(target.content)
  2642. except Exception as exc:
  2643. rollback_failures = _rollback_targets([*written, target])
  2644. result = _rollback_result_message(
  2645. f"No se pudo guardar {target.name}.", rollback_failures
  2646. )
  2647. raise KerberosConfigurationError(result) from exc
  2648. if not saved:
  2649. # Most managers return False before changing a file, but include
  2650. # the failed target as well in case an implementation wrote before
  2651. # reporting its error.
  2652. rollback_failures = _rollback_targets([*written, target])
  2653. raise KerberosConfigurationError(
  2654. _rollback_result_message(
  2655. f"No se pudo guardar {target.name}.", rollback_failures
  2656. )
  2657. )
  2658. written.append(target)
  2659. return written
  2660. def _rollback_targets(targets: list[_ConfigTarget]) -> list[str]:
  2661. """Best-effort restore and return targets that could not be restored."""
  2662. failures: list[str] = []
  2663. for target in reversed(_unique_targets(targets)):
  2664. try:
  2665. # Empty, newly-created modules are harmless and avoid deleting a
  2666. # path we did not own before the transaction.
  2667. if not target.save(target.original):
  2668. failures.append(target.name)
  2669. except Exception:
  2670. logger.exception("Could not roll back Kerberos target {}", target.name)
  2671. failures.append(target.name)
  2672. return failures
  2673. def _rollback_result_message(message: str, failures: list[str]) -> str:
  2674. """Describe rollback truthfully without leaking implementation details."""
  2675. if failures:
  2676. return (
  2677. f"{message} No se pudieron restaurar: {', '.join(dict.fromkeys(failures))}. "
  2678. "Revisa los respaldos y el estado de Squid antes de continuar."
  2679. )
  2680. return f"{message} Se restauró la configuración anterior."
  2681. def _validate_prerequisites(
  2682. config_manager,
  2683. settings: KerberosSettings,
  2684. runtime: _SquidRuntime | None = None,
  2685. *,
  2686. docker_mounts: list[tuple[Path, PurePosixPath]] | None = None,
  2687. docker_mounts_checked: bool = False,
  2688. ) -> dict[str, Any]:
  2689. preflight = get_preflight(
  2690. config_manager,
  2691. settings,
  2692. runtime,
  2693. docker_mounts=docker_mounts,
  2694. docker_mounts_checked=docker_mounts_checked,
  2695. )
  2696. if preflight["errors"]:
  2697. raise KerberosConfigurationError(" ".join(preflight["errors"]))
  2698. if not preflight["config"]["writable"]:
  2699. raise KerberosConfigurationError(
  2700. "SquidStats no tiene permiso para escribir el squid.conf configurado."
  2701. )
  2702. return preflight
  2703. def apply_configuration(
  2704. data: Mapping[str, Any] | KerberosSettings, config_manager
  2705. ) -> dict[str, Any]:
  2706. """Apply one Kerberos change at a time against freshly loaded config."""
  2707. with _APPLY_LOCK:
  2708. config_path = str(getattr(config_manager, "config_path", "squid.conf"))
  2709. with squid_config_write_lock(config_path):
  2710. _refresh_config_manager(config_manager)
  2711. return _apply_configuration(data, config_manager)
  2712. def _refresh_config_manager(config_manager) -> None:
  2713. """Avoid overwriting a change made since the shared manager was created."""
  2714. if not bool(getattr(config_manager, "is_valid", False)):
  2715. return
  2716. load_config = getattr(config_manager, "load_config", None)
  2717. if not callable(load_config):
  2718. return
  2719. try:
  2720. if load_config() is False:
  2721. raise KerberosConfigurationError(
  2722. "No se pudo recargar squid.conf antes de aplicar Kerberos."
  2723. )
  2724. refresh_layout = getattr(config_manager, "_check_modular_config", None)
  2725. if callable(refresh_layout):
  2726. refresh_layout()
  2727. except KerberosConfigurationError:
  2728. raise
  2729. except Exception as exc:
  2730. raise KerberosConfigurationError(
  2731. "No se pudo recargar squid.conf antes de aplicar Kerberos."
  2732. ) from exc
  2733. def _apply_configuration(
  2734. data: Mapping[str, Any] | KerberosSettings, config_manager
  2735. ) -> dict[str, Any]:
  2736. """Safely add, update, or remove the managed Kerberos Squid directives.
  2737. The writes are rolled back if parsing or the optional live reconfiguration
  2738. fails. No keytab bytes are ever read or copied by this operation.
  2739. """
  2740. settings = _validated_settings(data)
  2741. if manual_write_message := _manual_squid_write_message():
  2742. # This also prevents a "disable" request from attempting a write.
  2743. # The packaged Debian service cannot escape ProtectSystem=full, even
  2744. # when the Unix mode bits themselves appear writable.
  2745. raise KerberosConfigurationError(manual_write_message)
  2746. if not bool(getattr(config_manager, "is_valid", False)):
  2747. raise KerberosConfigurationError(
  2748. "La configuración de Squid no está disponible para escritura."
  2749. )
  2750. inspection_errors = _configuration_source_inspection_errors(config_manager)
  2751. if inspection_errors:
  2752. raise KerberosConfigurationError(" ".join(inspection_errors))
  2753. main = _target_from_main(config_manager)
  2754. modular = bool(getattr(config_manager, "is_modular", False))
  2755. auth = (
  2756. _target_from_module(config_manager, AUTH_MODULE_FILENAME) if modular else main
  2757. )
  2758. acl_module = (
  2759. _target_from_module(config_manager, ACL_MODULE_FILENAME) if modular else main
  2760. )
  2761. access_module = (
  2762. _target_from_module(config_manager, HTTP_ACCESS_MODULE_FILENAME)
  2763. if modular
  2764. else main
  2765. )
  2766. access = (
  2767. _access_target(config_manager, main, modular, access_module)
  2768. if settings.enabled and settings.enforce_auth
  2769. else access_module
  2770. )
  2771. # Always include both possible access locations so turning enforcement off
  2772. # (or migrating layouts) cannot leave a stale managed challenge behind.
  2773. # Write generated modules before squid.conf starts including them; rollback
  2774. # then happens in the opposite order and removes the includes first.
  2775. targets = _unique_targets(
  2776. [auth, acl_module, access_module, access, main] if modular else [main]
  2777. )
  2778. if settings.enabled and modular:
  2779. _reject_indirect_active_module(config_manager, main, auth)
  2780. if settings.enforce_auth and not _same_target(access, main):
  2781. _reject_indirect_active_module(config_manager, main, access)
  2782. # Discover this only once. In particular, an explicit Docker preference
  2783. # must be honoured for both validation and the subsequent reconfigure.
  2784. runtime = _find_squid_runtime()
  2785. docker_mounts_checked = bool(runtime and runtime.kind == "docker")
  2786. if docker_mounts_checked and not runtime.container_config_path:
  2787. raise KerberosConfigurationError(
  2788. "SQUID_CONTAINER_CONFIG_PATH no es una ruta absoluta segura dentro del contenedor."
  2789. )
  2790. docker_mounts = _docker_mounts(runtime) if docker_mounts_checked else None
  2791. docker_target_mappings = (
  2792. _docker_target_mapping_statuses(
  2793. runtime,
  2794. targets,
  2795. main.path,
  2796. docker_mounts,
  2797. mounts_checked=docker_mounts_checked,
  2798. )
  2799. if docker_mounts_checked
  2800. else {}
  2801. )
  2802. # Remove blocks from both possible locations. This also migrates the old
  2803. # experimental marker safely if an administrator had used it before.
  2804. for target in targets:
  2805. target.content = _remove_managed_auth(target.content)
  2806. target.content = _remove_managed_access(target.content)
  2807. if not settings.enabled:
  2808. written: list[_ConfigTarget] = []
  2809. try:
  2810. if docker_mounts_checked:
  2811. _require_mapped_docker_targets(
  2812. targets, docker_target_mappings, main_target=main
  2813. )
  2814. written = _write_targets(targets)
  2815. validation = validate_squid_configuration(main.path, runtime)
  2816. if validation["available"] and not validation["valid"]:
  2817. raise KerberosConfigurationError(
  2818. "Squid rechazó la configuración tras retirar Kerberos."
  2819. )
  2820. except Exception as exc:
  2821. if not written and isinstance(exc, KerberosConfigurationError):
  2822. raise
  2823. rollback_failures = _rollback_targets(written)
  2824. raise KerberosConfigurationError(
  2825. _rollback_result_message(
  2826. "No se pudo retirar Kerberos.", rollback_failures
  2827. )
  2828. ) from exc
  2829. return {
  2830. "status": "success",
  2831. "message": "Bloques Kerberos administrados eliminados. Reinicia Squid para deshabilitar el esquema de autenticación.",
  2832. "validation": validation,
  2833. "reconfigured": False,
  2834. "restart_required": True,
  2835. "settings": settings.to_dict(),
  2836. }
  2837. preflight = _validate_prerequisites(
  2838. config_manager,
  2839. settings,
  2840. runtime,
  2841. docker_mounts=docker_mounts,
  2842. docker_mounts_checked=docker_mounts_checked,
  2843. )
  2844. negotiate_targets = _unique_targets([main, auth])
  2845. acl_targets = _unique_targets([main, auth, acl_module])
  2846. included_sources = _active_included_configuration_sources(config_manager)
  2847. managed_target_paths = {
  2848. os.path.realpath(str(target.path)) for target in negotiate_targets
  2849. }
  2850. external_negotiate_sources = [
  2851. path
  2852. for path, content in included_sources
  2853. if os.path.realpath(path) not in managed_target_paths
  2854. and _negotiate_directive_lines(content)
  2855. ]
  2856. if external_negotiate_sources:
  2857. raise KerberosConfigurationError(
  2858. "Se detectó una directiva Negotiate en un archivo incluido fuera de squid.conf/50_auth.conf. "
  2859. "SquidStats no puede reemplazarlo de forma segura; migra esa configuración manualmente antes de continuar."
  2860. )
  2861. other_schemes = sorted(
  2862. {
  2863. scheme
  2864. for content in [
  2865. *(target.content for target in negotiate_targets),
  2866. *(content for _path, content in included_sources),
  2867. ]
  2868. for scheme in _other_auth_program_schemes(content)
  2869. }
  2870. )
  2871. if other_schemes:
  2872. raise KerberosConfigurationError(
  2873. "Se detectaron helpers de autenticación alternativos "
  2874. f"({', '.join(other_schemes)}). Esta pantalla configura solo Negotiate/Kerberos; "
  2875. "revísalos y desactívalos manualmente antes de continuar."
  2876. )
  2877. if (
  2878. any(_has_unmanaged_negotiate(target.content) for target in negotiate_targets)
  2879. and not settings.replace_existing_negotiate
  2880. ):
  2881. raise KerberosConfigurationError(
  2882. "Ya existe una directiva Negotiate no administrada. Activa 'reemplazar configuración existente' "
  2883. "solo después de revisarlo."
  2884. )
  2885. if settings.replace_existing_negotiate:
  2886. for target in negotiate_targets:
  2887. target.content = _remove_conflicting_negotiate_directives(target.content)
  2888. for target in acl_targets:
  2889. target.content = _remove_acl(target.content, settings.acl_name)
  2890. # An ACL name is global to the complete active configuration. Looking at
  2891. # only the conventional main/auth/ACL modules misses a definition in a
  2892. # custom or access include, producing a syntactically valid-looking
  2893. # preview that Squid later rejects. Use each target's in-memory content
  2894. # (managed blocks have already been removed there) and inspect every other
  2895. # active include without trying to rewrite administrator-owned fragments.
  2896. target_contents = {
  2897. os.path.realpath(str(target.path)): target.content
  2898. for target in _unique_targets(targets)
  2899. }
  2900. acl_name_sources: list[str] = []
  2901. for target in _unique_targets(targets):
  2902. if _has_acl_definition(target.content, settings.acl_name):
  2903. acl_name_sources.append(target.name)
  2904. for path, content in included_sources:
  2905. canonical_path = os.path.realpath(path)
  2906. if canonical_path in target_contents:
  2907. continue
  2908. if _has_acl_definition(content, settings.acl_name):
  2909. acl_name_sources.append(Path(path).name)
  2910. if acl_name_sources:
  2911. raise KerberosConfigurationError(
  2912. f"Ya existe una ACL llamada '{settings.acl_name}' en "
  2913. f"{', '.join(dict.fromkeys(acl_name_sources))}; SquidStats no puede reemplazarla de forma segura. "
  2914. "Usa otro nombre o revísala manualmente antes de continuar."
  2915. )
  2916. auth.content = _insert_before_first_http_access(
  2917. auth.content, _auth_block(settings), config_path=auth.path
  2918. )
  2919. if settings.enforce_auth:
  2920. if (
  2921. _has_access_rule(access.content, settings.acl_name)
  2922. and not settings.replace_existing_negotiate
  2923. ):
  2924. raise KerberosConfigurationError(
  2925. "Ya existe una regla http_access manual para esta ACL. Activa el reemplazo "
  2926. "solo después de revisarla, o usa otra ACL."
  2927. )
  2928. if settings.replace_existing_negotiate:
  2929. access.content = _remove_access_rule(access.content, settings.acl_name)
  2930. # A previous quota sync may have generated this denial before
  2931. # Kerberos existed. Remove it while choosing the safe challenge
  2932. # location, then put it immediately after the managed challenge.
  2933. # Besides avoiding a premature proxy_auth lookup, this lets us repair
  2934. # a stale quota rule that had drifted below a normal client allow.
  2935. active_acl_contents = [
  2936. main.content,
  2937. *(content for _path, content in included_sources),
  2938. ]
  2939. access.content, quota_proxy_auth_deny = _take_proxy_auth_quota_deny(
  2940. access.content, active_acl_contents
  2941. )
  2942. access.content = _add_access_block(
  2943. access.content, settings, acl_contents=active_acl_contents
  2944. )
  2945. if quota_proxy_auth_deny is not None:
  2946. access.content = _restore_proxy_auth_quota_deny(
  2947. access.content, quota_proxy_auth_deny
  2948. )
  2949. if modular:
  2950. include_directory = main.path.parent
  2951. auth_include_path = auth.path
  2952. access_include_path = access.path
  2953. auth_include_value: str | Path = auth.path
  2954. access_include_value: str | Path = access.path
  2955. if docker_mounts_checked:
  2956. # Match existing include directives in the host namespace, but
  2957. # write a relative path that resolves to the same module in both
  2958. # the host and container namespaces.
  2959. auth_include_value = _docker_relative_include_value(
  2960. main, auth, docker_target_mappings
  2961. )
  2962. if settings.enforce_auth and not _same_target(access, main):
  2963. access_include_value = _docker_relative_include_value(
  2964. main, access, docker_target_mappings
  2965. )
  2966. if not _same_target(auth, main):
  2967. main.content = _ensure_auth_include_before_access(
  2968. main.content,
  2969. auth_include_path,
  2970. include_directory,
  2971. None if _same_target(access, main) else access_include_path,
  2972. acl_module.path,
  2973. include_value=auth_include_value,
  2974. )
  2975. if settings.enforce_auth and not _same_target(access, main):
  2976. main.content = _ensure_include(
  2977. main.content,
  2978. access_include_path,
  2979. include_directory,
  2980. include_value=access_include_value,
  2981. )
  2982. if docker_mounts_checked:
  2983. _require_mapped_docker_targets(
  2984. targets, docker_target_mappings, main_target=main
  2985. )
  2986. written: list[_ConfigTarget] = []
  2987. reconfiguration_attempted = False
  2988. try:
  2989. written = _write_targets(targets)
  2990. validation = validate_squid_configuration(main.path, runtime)
  2991. if validation["available"] and not validation["valid"]:
  2992. raise KerberosConfigurationError("Squid rechazó la configuración.")
  2993. if settings.reload_squid:
  2994. if not validation["available"]:
  2995. raise KerberosConfigurationError(
  2996. "No se encontró Squid para validar y recargar; desmarca la recarga solo si la harás manualmente."
  2997. )
  2998. reconfiguration_attempted = True
  2999. reconfigured, reload_message = reconfigure_squid(main.path, runtime)
  3000. if not reconfigured:
  3001. raise KerberosConfigurationError(reload_message)
  3002. else:
  3003. reconfigured = False
  3004. warning = None
  3005. if not settings.reload_squid:
  3006. warning = (
  3007. "La configuración se escribió, pero no se recargó. Valida y recarga "
  3008. "(o reinicia) Squid manualmente para activarla."
  3009. )
  3010. return {
  3011. "status": "warning" if warning else "success",
  3012. "message": warning or "Autenticación Kerberos configurada en Squid.",
  3013. "validation": validation,
  3014. "reconfigured": reconfigured,
  3015. "restart_required": not settings.reload_squid,
  3016. "reload_required": not settings.reload_squid,
  3017. "settings": settings.to_dict(),
  3018. "preflight": preflight,
  3019. }
  3020. except Exception as exc:
  3021. # A write failure has already performed its own targeted rollback.
  3022. # If no target was written, there is nothing to restore here.
  3023. if not written:
  3024. if isinstance(exc, KerberosConfigurationError):
  3025. raise
  3026. raise KerberosConfigurationError(
  3027. "No se pudo completar la configuración Kerberos antes de modificar Squid."
  3028. ) from exc
  3029. rollback_failures = _rollback_targets(written)
  3030. runtime_recovery_error = None
  3031. if reconfiguration_attempted and not rollback_failures:
  3032. restored, restore_message = reconfigure_squid(main.path, runtime)
  3033. if not restored:
  3034. runtime_recovery_error = restore_message
  3035. message = _rollback_result_message(str(exc), rollback_failures)
  3036. if runtime_recovery_error:
  3037. message += (
  3038. " No se pudo recargar la configuración restaurada "
  3039. f"({runtime_recovery_error}). Reinicia Squid y revisa los respaldos antes de continuar."
  3040. )
  3041. raise KerberosConfigurationError(message) from exc