Skip to content
maraventoPublic

About

Traffic management and auditing tool for Squid proxy server

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

27 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

status-maintained last commit Stargazers Twitter Follow

Proxy Monitor is a web application designed to work exclusively with the Squid-Cache proxy server. It requires the Apache2 web server.

It retrieves traffic information directly from Squid's access.log file and uses it to generate detailed statistics, reports and analysis tools for monitoring local network usage.

The dashboard organizes its features into modules, which you can open from the tabs at the top.

Proxy Monitor is also a preservation project for Squid analysis tools that, despite their usefulness, were abandoned and no longer receive support. Those tools are SqStat, SARG, LightSquid and SquidAnalyzer.

They are recovered, integrated and maintained inside the Proxy Monitor ecosystem, so they remain available and keep receiving support.

Three in-house modules—Monitor (Squidmon), LogView and AI (SquidAI)—complement the four preserved projects. Bandata works alongside Traffic (LightSquid) to enforce data-usage limits.
Proxy Monitor es una aplicación web diseñada para funcionar exclusivamente con el servidor proxy Squid-Cache. Requiere el servidor web Apache2.

Obtiene los datos de tráfico del archivo access.log de Squid y los presenta como estadísticas e informes para analizar el uso de la red local.

El panel organiza sus funciones en módulos, accesibles desde las pestañas superiores.

Proxy Monitor es también un proyecto de conservación de herramientas de análisis para Squid que, pese a su utilidad, fueron abandonadas y ya no reciben soporte. Esas herramientas son SqStat, SARG, LightSquid y SquidAnalyzer.

Se recuperan, integran y mantienen dentro del ecosistema de Proxy Monitor, de modo que sigan disponibles y con soporte.

Tres módulos propios —Monitor (Squidmon), LogView e IA (SquidAI)— complementan los cuatro proyectos preservados. Bandata trabaja junto con Traffic (LightSquid) para aplicar límites de consumo de datos.

REQUIREMENTS


⚠️ WARNING: Tested on Ubuntu 24.04/26.04 LTS. Use on other versions or distributions is at your own risk.

CPU RAM Storage Dependencies
Intel Core i5/Xeon/AMD Ryzen 5 (≥ 3.0 GHz) 16 GB 2 GB SSD Squid Cache v6.13, Apache v2.4.58, PHP 8.3.6

pmsetup.sh checks that Squid, Apache, PHP, and a set of supporting packages are installed before proceeding, but it does not install them for you — installation aborts with a list of missing packages if any of this hasn't been done first.

# other required packages (checked by pmsetup.sh, no extra setup needed)
apt install -y wget curl git zip unzip ipset nbtscan libcgi-session-perl libgd-perl \
                coreutils sarg fonts-lato fonts-liberation fonts-dejavu \
                perl cron sudo util-linux iproute2 passwd findutils sed \
                grep hostname ncurses-bin systemd libc-bin iptables \
                gawk gzip procps logrotate

# squid
apt install -y squid-openssl squid-langpack squid-common squidclient squid-purge
mkdir -p /var/log/squid &>/dev/null
touch /var/log/squid/{access,cache,store,deny}.log &>/dev/null
chown proxy:proxy /var/log/squid/*.log
chmod 640 /var/log/squid/*.log
for cache_type in rock ufs; do
    mkdir -p /var/spool/squid/${cache_type} 2>/dev/null
done
chown -R proxy:proxy /var/spool/squid
chmod -R 700 /var/spool/squid
usermod -aG proxy www-data
systemctl enable squid.service
squid -z
cp -f /etc/logrotate.d/squid{,.bak} &>/dev/null
sed -i '/sharedscripts/a \    create 0644 proxy proxy' /etc/logrotate.d/squid
sed -i 's/rotate 2/rotate 7/' /etc/logrotate.d/squid
sed -i 's/^	daily$/	monthly/' /etc/logrotate.d/squid

# php
apt install -y php libapache2-mod-php php-cli php-curl
# Detect PHP version
if command -v php &>/dev/null; then
    PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null)
    echo "PHP version detected: $PHP_VERSION"
else
    echo "Error: PHP not installed"
    exit 1
fi
# Ensure php.ini exists for Apache
if [ ! -f /etc/php/$PHP_VERSION/apache2/php.ini ]; then
    if [ -f /etc/php/$PHP_VERSION/cli/php.ini ]; then
        mkdir -p /etc/php/$PHP_VERSION/apache2
        cp /etc/php/$PHP_VERSION/cli/php.ini /etc/php/$PHP_VERSION/apache2/php.ini
        echo "php.ini copied to /etc/php/$PHP_VERSION/apache2/"
    else
        echo "Error: php.ini not found"
        exit 1
    fi
fi
cp -f /etc/php/$PHP_VERSION/apache2/php.ini{,.bak} &>/dev/null
sed -i \
  -e 's/^\s*;*\s*max_execution_time\s*=.*/max_execution_time = 120/' \
  -e 's/^\s*max_input_time\s*=.*/max_input_time = 120/' \
  -e 's/^;\s*max_input_time\s*=.*/max_input_time = 120/' \
  -e 's/^\s*memory_limit\s*=.*/memory_limit = 1024M/' \
  -e 's/^\s*post_max_size\s*=.*/post_max_size = 64M/' \
  -e 's/^\s*upload_max_filesize\s*=.*/upload_max_filesize = 64M/' \
  -e 's/^\s*;*\s*opcache.memory_consumption\s*=.*/opcache.memory_consumption = 256/' \
  -e 's/^\s*;*\s*realpath_cache_size\s*=.*/realpath_cache_size = 16M/' \
  /etc/php/$PHP_VERSION/apache2/php.ini

# apache
apt install -y apache2 apache2-doc apache2-utils apache2-dev \
                apache2-suexec-pristine libaprutil1t64 libaprutil1-dev \
                libtest-fatal-perl
systemctl enable apache2.service
apt -qq install -y --reinstall apache2-doc
cp -f /etc/apache2/mods-available/mpm_prefork.conf{,.bak} &>/dev/null
sed -i \
  -e 's/^\(StartServers[[:space:]]*\)5/\110/' \
  -e 's/^\(MinSpareServers[[:space:]]*\)5/\110/' \
  -e 's/^\(MaxSpareServers[[:space:]]*\)10/\115/' \
  -e 's/^\(MaxRequestWorkers[[:space:]]*\)150/\1200/' \
  -e 's/^\(MaxConnectionsPerChild[[:space:]]*\)0/\11000/' \
  /etc/apache2/mods-available/mpm_prefork.conf
# Enable modules
a2dismod -q mpm_event || true
a2enmod -q mpm_prefork || true
a2enmod -q php || true

REPOSITORY STRUCTURE


proxymon/
├── modules/                    # Web content served from /var/www/proxymon
│   ├── lightsquid/             # LightSquid reports
│   ├── logview/                # Live tail of Squid access.log
│   ├── sqstat/                 # SqStat active connections view
│   ├── squidai/                # SquidAI conversational assistant
│   ├── squidanalyzer/          # SquidAnalyzer reports
│   ├── squidmon/               # Squid Monitor: real-time traffic and ACL analysis
│   ├── warning/                # Captive portal warning page
│   └── index.html              # Main page with the module tabs
├── config/                     # Root-only files, installed to /etc/proxymon
│   ├── bandata/                # Data usage control (bandata.sh and its ACLs)
│   ├── tools/                  # Maintenance scripts
│   └── vhost/                  # Apache vhosts, installed to sites-available
└── pmsetup.sh                  # Installer: install, update, uninstall

HOW TO INSTALL


git clone --depth=1 https://github.com/maravento/proxymon.git
cd proxymon
sudo bash pmsetup.sh

Important Before Using

- IP addresses that bypass the Squid proxy do not appear in its reports. - Las direcciones IP de la red local cuyo tráfico no pase por el proxy Squid no aparecerán en sus informes.
- The results in Squidmon Search and Traffic Search are examples. Actual results vary with your environment, the amount of log history, and the resources available to process ACLs. - Los resultados de Squidmon Search y Traffic Search son ejemplos. Los resultados reales dependen del entorno, la cantidad de registros históricos y los recursos disponibles para procesar las ACL.

Features & Options

  • LightSquid traffic reporting module (fast reports, per-user statistics, and daily/monthly traffic)
  • SQStat for real-time monitoring
  • SARG report generator (detailed and customizable reports)
  • SquidAnalyzer log analysis module (graphical traffic statistics and usage trends)
  • Bandata script for bandwidth control, usage limits, and quota management (integrated with LightSquid), configured in /etc/proxymon/proxymon.env and syncing quota values to the warning portal on every run
  • Squidmon statistics module (advanced statistics, report printing, and ACL-driven operations)
  • Logview module (live tail of Squid access.log with search and filters)
  • SquidAI module (LLM-powered assistant for traffic reports and security incidents)
  • Warning portal for quota limit notifications
  • Automatic dependency checking
  • Crontab task management
  • Apache virtual host configuration
sudo ./pmsetup.sh              # Interactive menu
sudo ./pmsetup.sh install      # Install Proxy Monitor
sudo ./pmsetup.sh update       # Update Proxy Monitor code (live data preserved)
sudo ./pmsetup.sh uninstall    # Uninstall Proxy Monitor
sudo ./pmsetup.sh -h           # Show help message
install installs and configures Proxy Monitor, including Apache rules, proxymon.env, ACL lists, Apache/PHP/SARG settings, and scheduled tasks. If /var/www/proxymon already exists, it stops to avoid overwriting an installation. In that case, use update or uninstall.

update only refreshes the code and the permissions: the web content under /var/www/proxymon and the root scripts under /etc/proxymon. It never touches the Apache, PHP or SARG system configuration, the cron entries, the ACL lists or proxymon.env, and it never prompts.

The process stops Apache, creates a backup with pmbk.sh, replaces the code, resets permissions, and restarts Apache. The copy skips the live data, so that data is never written to.

Do not interrupt an update with Ctrl-C. Apache is stopped for the whole process, and the installer only guarantees to start it again on its own exit paths. A signal can leave the service down and the code half replaced. If it happens, start Apache with sudo systemctl start apache2 and run the update again.

update never writes to the following files and directories, so their contents are preserved:
install instala y configura Proxy Monitor, incluidas las reglas de Apache, el archivo proxymon.env, las listas ACL, los ajustes de Apache/PHP/SARG y las tareas programadas. Si /var/www/proxymon ya existe, se detiene para evitar sobrescribir una instalación. En ese caso, use update o uninstall.

update solo refresca el código y los permisos: el contenido web dentro de /var/www/proxymon y los scripts root dentro de /etc/proxymon. Nunca toca la configuración de Apache, PHP o SARG, las entradas de cron, las listas ACL ni proxymon.env, y nunca pide datos.

El proceso detiene Apache, crea una copia de seguridad con pmbk.sh, reemplaza el código, ajusta los permisos y vuelve a iniciar Apache. La copia omite los datos vivos, así que nunca se escribe sobre ellos.

No interrumpa una actualización con Ctrl-C. Apache queda detenido durante todo el proceso, y el instalador solo garantiza volver a iniciarlo en sus propias salidas. Una señal puede dejar el servicio caído y el código a medio reemplazar. Si ocurre, inicie Apache con sudo systemctl start apache2 y repita la actualización.

update nunca escribe en los siguientes archivos y directorios, así que su contenido se conserva:
Path Description Descripción
lightsquid/report Daily LightSquid reports Reportes diarios de LightSquid
lightsquid/realname.cfg Hostname mappings Mapeo de hostnames
lightsquid/skipuser.cfg Excluded users Usuarios excluidos
sarg/squid-reports SARG rendered reports Reportes generados por SARG
squidmon/etc/config SquidMon config file Archivo de configuración de SquidMon
squidanalyzer/output SquidAnalyzer rendered reports Reportes generados por SquidAnalyzer
sqstat/config.inc.php SQStat custom config (e.g. cachemgr credentials) Config personalizada de SQStat (ej. credenciales de cachemgr)
warning/warning.html Captive portal warning page Página de aviso del portal cautivo
/etc/proxymon/bandata/acl Bandata quota lists Listas de cuota de Bandata

Access Proxymon: http://localhost:18080

Warning for Bandata: http://192.168.X.X:18081 (LAN-only, not reachable via localhost)

proxymon.env

pmsetup.sh creates /etc/proxymon/proxymon.env during installation and never overwrites it on update. It is the one file the whole project reads: bandata.sh, squidtool.sh, logview/api.php and squidai/worker.php all load it. pmsetup.sh aborts if a key is missing from the file. pmsetup.sh crea /etc/proxymon/proxymon.env durante la instalación y no lo sobrescribe en update. Es el archivo que lee todo el proyecto: lo cargan bandata.sh, squidtool.sh, logview/api.php y squidai/worker.php. pmsetup.sh aborta si falta una clave.
Variable Read by Description Descripción
LAN bandata.sh LAN interface the quota rules apply to Interfaz LAN a la que se aplican las reglas de cuota
SERVER_IP pmsetup.sh, worker.php Server's own IPv4; added to SARG's usertab and excluded from the reports IPv4 del servidor; se añade al usertab de SARG y se excluye de los informes
RANGE pmsetup.sh CIDR allowed to reach the panel, written into proxymon.conf. It must be a network CIDR, not a filename glob: a glob belongs in REPORT_IP_GLOB. An invalid value keeps the default range and raises a WARNING CIDR autorizado a entrar al panel, escrito en proxymon.conf. Debe ser un CIDR de red, no un glob de nombre de archivo: el glob va en REPORT_IP_GLOB. Un valor inválido conserva el rango por omisión y emite un WARNING
REPORT_IP_GLOB bandata.sh Glob that matches the client IPs inside a LightSquid report Glob que localiza las IP de cliente dentro de un informe de LightSquid
LIGHTSQUID_DIR bandata.sh LightSquid installation directory Directorio de instalación de LightSquid
REPORT_PATH bandata.sh, worker.php Directory holding the daily LightSquid reports Directorio con los informes diarios de LightSquid
REALNAME_CFG, SKIPUSERS_CFG bandata.sh, worker.php LightSquid hostname mappings and excluded-user list Mapeo de hostnames y lista de usuarios excluidos de LightSquid
ACL_PATH, ACL_MAC_PATH, ACL_SQUID_PATH pmsetup.sh, bandata.sh, worker.php ACL tree shared with the other projects on the host, and its MAC and Squid branches Árbol de ACL compartido con los otros proyectos del host, y sus ramas MAC y Squid
ACL_BANDATA_PATH bandata.sh Directory holding Bandata's own quota lists Directorio con las listas de cuota propias de Bandata
ALLOW_LIST bandata.sh IPs exempt from every quota IP exentas de toda cuota
BLOCK_LIST_DAY, BLOCK_LIST_WEEK, BLOCK_LIST_MONTH bandata.sh The three lists Bandata rewrites, one per quota window Las tres listas que Bandata reescribe, una por ventana de cuota
SQUID_LOG_DIR, SQUID_LOG_FILE squidtool.sh, api.php, worker.php Squid log directory and access.log path Directorio de logs de Squid y ruta de access.log
WARNING_HTML bandata.sh Captive portal page where Bandata writes the current quota values Página del portal cautivo donde Bandata escribe los valores de cuota vigentes
CACHE_PATH pmsetup.sh, worker.php SquidAI cache directory, owned by www-data with mode 750 Directorio de caché de SquidAI, propiedad de www-data con permisos 750
MAX_BANDWIDTH_DAY, MAX_BANDWIDTH_WEEK, MAX_BANDWIDTH_MONTH bandata.sh The three quota limits; see BanData below Los tres límites de cuota; ver BanData más abajo
BANDATA_HOTSPOT, HOTSPOT_PATH bandata.sh Whether a UniFi hotspot is in use, and where its files live Si hay un hotspot UniFi en uso, y dónde están sus archivos
UPDATE_REALNAME bandata.sh Whether Bandata refreshes LightSquid's realname.cfg on each run Si Bandata refresca el realname.cfg de LightSquid en cada ejecución

/etc/proxymon/ holds a second file, .env, with the SquidAI credentials LLM_URL, LLM_API_KEY, LLM_MODEL and LLM_RESPONSE_FORMAT. See API Configuration.

/etc/proxymon/ contiene un segundo archivo, .env, con las credenciales de SquidAI LLM_URL, LLM_API_KEY, LLM_MODEL y LLM_RESPONSE_FORMAT. Ver «API Configuration».

HOW TO USE


MAIN MENU

proxymon_main

MONITOR (Squidmon)

squidmon

Squid Monitor (squidmon) provides detailed real-time traffic analysis and monitoring of your Squid proxy. It displays comprehensive statistics including blocked domains, blocked clients, traffic patterns, and ACL matching information. You can filter this activity and generate detailed reports on network traffic and blocked content. Squid Monitor (Squidmon) ofrece análisis del tráfico de Squid en tiempo real. Muestra estadísticas sobre dominios y clientes bloqueados, patrones de tráfico y coincidencias con las ACL. También permite filtrar la actividad y generar informes detallados sobre el tráfico de red y el contenido bloqueado.

Config

squidmon conf

This section defines the parameters that Squid Monitor uses to interpret and display network activity, including data sources (access control lists —ACLs—), the maximum number of lines to analyze from the Squid log, the time range of the data, and the automatic refresh interval. Each list is declared with its full path, one per line, and the module reads exactly that path: it never searches any directory. These are the lists it ships with: Aquí se configuran los parámetros que Squid Monitor usa para mostrar la actividad de la red: las listas de control de acceso (ACL), el máximo de líneas del registro de Squid que se analizarán, el período de consulta y el intervalo de actualización. Cada lista se declara con su ruta completa, una por línea. El módulo lee esa ruta y no busca en ningún directorio. Estas son las listas que trae:
/etc/acl/squid/blocktlds.txt=Blocked TLD
/etc/acl/squid/blockdomains.txt=Blocked Sites
regex:^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(:\d+)?=Block IPv4
regex:(adlinkfly|announce\.php\?passkey=|info_hash|iptv|jndi:|mtc[0-9]|\.onion|peer_id=|porn|psiphon|torrent|ultrasurf)=Blocked Patterns
To change the lists, enter each full path in the Config section, one per line, followed by = and its label. Squid Monitor opens exactly that path and searches no directory. If you move a list, edit its line in Config. Para cambiar las listas, indique en la sección Config la ruta completa de cada archivo, una por línea, seguida de = y su etiqueta. Squid Monitor abre esa ruta y no busca en ninguna carpeta. Si cambia una lista de sitio, edite su línea en Config.
sudo nano /etc/proxymon/proxymon.env
# path to ACLs folder
ACL_PATH=/etc/acl
⚠️ Important: For a rule to block traffic, it must be defined in both Squidmon configuration and squid.conf. Here is an example using the default ACLs: ⚠️ Importante: Para que una regla bloquee tráfico, debe estar definida tanto en la configuración de Squidmon como en squid.conf. Este es un ejemplo con las ACL predeterminadas:
sudo nano /etc/squid/squid.conf
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
include /etc/squid/conf.d/*.conf
# Block: TLDs
# For more information visit: https://github.com/maravento/proxymon
acl blocktlds dstdomain "/etc/acl/squid/blocktlds.txt"
http_access deny workdays blocktlds
# Block: domains
acl blockdomains dstdomain "/etc/acl/squid/blockdomains.txt"
http_access deny workdays blockdomains
⚠️ Warning: Default values are 24 hours and 50,000 lines from access.log. Increasing these values may slow down the module and raise system resource usage. Refer to the Squidmon Search section. To reset the filters to their default values, press the Reset to Default button. ⚠️ Advertencia: Los valores predeterminados son 24 horas y 50 000 líneas de access.log. Si los aumenta, el módulo podría tardar más y consumir más recursos. Consulte la sección Squidmon Search. Para restablecer los valores iniciales, pulse Reset to Default.

Top Blocked Domains & Clients

squidmon top_blocked

Top Blocked Domains: Shows the domains Squid blocks most often, along with the port and number of blocked requests. This helps identify frequently blocked sites or services and adjust access rules. Top Blocked Domains: Muestra los dominios que Squid bloquea con mayor frecuencia, junto con el puerto y el número de solicitudes bloqueadas. Esta información ayuda a identificar qué sitios o servicios se bloquean más y a ajustar las reglas de acceso.
Top Blocked Clients: Shows the client IP addresses with the most blocked requests. Each row includes the total number of requests, how many were blocked, and the percentage they represent. This helps identify clients that often try to access restricted content and may need follow-up. Top Blocked Clients: Muestra las IP de los clientes con más solicitudes bloqueadas. Cada fila incluye el total de solicitudes, cuántas se bloquearon y qué porcentaje representan. Así puedes identificar equipos que intentan acceder con frecuencia a contenido restringido y decidir si requieren seguimiento.

Traffic by Client IP

squidmon traffic

Expand a client IP to view its traffic statistics, including total, blocked, and allowed requests.

Filter by ACL, search for IP addresses or domains, and select a period of 24 hours, 7 days, or 30 days.

You can also generate a PDF report for each client.
Permite desplegar las IP de los clientes y consultar, para cada una, el total de solicitudes y cuántas fueron bloqueadas o permitidas.

Puedes filtrar por ACL, buscar IP o dominios y consultar períodos de 24 horas, 7 días o 30 días.

También puedes generar un informe PDF para cada cliente.

Filtering and Search

squidmon acl

Squidmon classifies traffic using ACLs (Access Control Lists), such as Blocked TLD, Blocked Sites, Blocked Patterns, Block IPv4 and Unknown ACL. The last one covers any rule defined in squid.conf that is not among the ACLs listed in Config.

Search by IP address or domain, and filter to show only blocked or only allowed traffic.

Select Clean Filters to clear the filters.
Squidmon clasifica el tráfico según las ACL, como Blocked TLD, Blocked Sites, Blocked Patterns, Block IPv4 y Unknown ACL. Esta última agrupa las reglas de squid.conf que no aparecen en la sección Config.

Puedes buscar por IP o dominio y filtrar para ver solo el tráfico bloqueado o solo el permitido.

Pulsa Clean Filters para borrar los filtros.

Report Generation

squidmon pdf

Generate PDF traffic reports.

Choose the last 24 hours, 7 days, or 30 days. You can also create a report for a client or domain and share it with anyone.

The Generate PDF Report button appears in the interface.
Puedes generar informes PDF de tráfico.

Puedes elegir las últimas 24 horas, los últimos 7 días o los últimos 30 días, y generar un informe para un cliente o dominio para compartirlo con quien quieras.

El botón Generate PDF Report aparece en la interfaz.

Blocked URLs Analysis

squidmon filter

Expand a client IP to see the blocked URLs, the matching ACL rule (for example, Blocked Sites), and how many times each URL was requested. This helps identify browsing patterns and adjust access rules. Al desplegar una IP, puedes consultar las URL bloqueadas, la regla de ACL que coincidió —por ejemplo, Blocked Sites— y cuántas veces se solicitó cada URL. Estos datos ayudan a reconocer patrones de navegación y ajustar las reglas de acceso.

Patterns

squidmon patterns

If a Squid ACL uses url_regex, Squid Monitor cannot read it from a file. Enter the expression directly in the module's Config section, as shown here: Si una ACL de Squid usa url_regex, Squid Monitor no puede leerla desde un archivo. Copie su expresión directamente en la sección Config del módulo, como en este ejemplo:
regex:(adlinkfly|announce\.php\?passkey=|info_hash|iptv|jndi:|mtc[0-9]|\.onion|peer_id=|porn|psiphon|torrent|ultrasurf)=Blocked Patterns
regex:^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(:\d+)?=Block IPv4

Squidmon Search

squidmon search

Result: 6 clients found in 0.08 seconds. Client IP-based filtering with domain resolution.
Data Source: Squid access logs /var/log/squid/access.log
Search Method: Real-time log parsing with ACL filtering
Use Case: Real-time client activity, immediate threat detection
Resultado: 6 clientes encontrados en 0.08 s. Filtrado basado en IP del cliente con resolución de dominio.
Fuente de Datos: Registros de acceso de Squid /var/log/squid/access.log
Método de Búsqueda: Análisis de registros en tiempo real con filtrado ACL
Caso de Uso: Actividad de cliente en tiempo real, detección inmediata de amenazas

Logrotate

Squidmon reads only the current access.log; it does not process rotated files.

Disable Squid's internal rotation with logfile_rotate 0, then configure logrotate to rotate the file at a frequency that suits your network, such as weekly or monthly.

In /etc/logrotate.d/squid, you can keep seven rotations with rotate 7.
Squidmon solo lee el access.log actual; no procesa los archivos rotados.

Desactive la rotación interna de Squid con logfile_rotate 0 y configure logrotate para rotar el archivo con una frecuencia adecuada para su red, por ejemplo semanal o mensual.

En /etc/logrotate.d/squid, puedes conservar siete rotaciones con rotate 7.
# Disable Squid internal rotation
sudo nano /etc/squid/squid.conf
#  TAG: logfile_rotate
logfile_rotate 0

# Logrotate
sudo sed -i 's/^	daily$/	weekly/' /etc/logrotate.d/squid
# or
sudo sed -i 's/^	daily$/	monthly/' /etc/logrotate.d/squid
# Optional:
sudo sed -i 's/rotate 2/rotate 7/' /etc/logrotate.d/squid

TRAFFIC (Lightsquid)

lightsquid report

Error

lightsquid error

The first time you open Traffic (LightSquid), reports may not be available yet. This happens if they have not been generated or your network traffic has not passed through Squid. The installer attempts to generate the initial report; if it does not appear, run this command: La primera vez que abras Traffic (LightSquid), puede que todavía no haya informes. Esto ocurre si aún no se han generado o si el tráfico de la red no ha pasado por Squid. El instalador intenta generar el informe inicial; si no aparece, ejecuta este comando:
sudo /var/www/proxymon/lightsquid/lightparser.pl today

Search Bar

lightsquid bar

In General Statistics, enter a word or value in the search bar and select SEARCH. The table will show matching rows, so you do not have to scan the entire report. En General Statistics, escribe una palabra o un valor en la barra de búsqueda y pulsa SEARCH. La tabla mostrará las filas coincidentes, sin que tengas que recorrer todo el informe.

lightsquid bar output

Traffic Search

lightsquid search

Result: 1,323 matches in 5.4 seconds. The search scans LightSquid daily reports for the entered term, regardless of letter case.

Data Source: LightSquid reports
/var/www/proxymon/lightsquid/report/YYYYMMDD/

Search Method: Reads report files and searches for the literal term

Use Case: Historical analysis, domain trends, bandwidth reports
Resultado: 1 323 coincidencias en 5,4 s. La búsqueda recorre los informes diarios de LightSquid y encuentra el texto indicado, sin distinguir mayúsculas de minúsculas.

Fuente de Datos: Reportes de LightSquid
/var/www/proxymon/lightsquid/report/YYYYMMDD/

Método de Búsqueda: Lectura de los archivos de informes y búsqueda literal del término

Caso de Uso: Análisis histórico, tendencias de dominios, reportes de ancho de banda

Traffic Cron Job

The installer schedules LightSquid report generation every 10 minutes. To change the frequency, edit its entry in /etc/cron.d/proxymon. El instalador programa la generación de informes de LightSquid cada 10 minutos. Para cambiar la frecuencia, edita la tarea de LightSquid en /etc/cron.d/proxymon.
sudo -u www-data crontab -e
*/10 * * * * /var/www/proxymon/lightsquid/lightparser.pl today

Add Users

You can add users manually to realname.cfg and exclude IP addresses from reports with skipuser.cfg.

Note: when UPDATE_REALNAME=true—the default for a new installation—Bandata generates realname.cfg from non-excluded MAC ACLs and, when enabled, data from uhm-auth.txt. It also generates skipuser.cfg from the IP addresses in mac-unlimited.txt and IPv4 entries in /etc/hosts. If it finds data, it replaces the contents of those files, so manual edits may be lost.
Puedes añadir usuarios manualmente a realname.cfg y excluir IP de los informes con skipuser.cfg.

Nota: cuando UPDATE_REALNAME=true —valor predeterminado al instalar—, Bandata genera realname.cfg con las ACL MAC no excluidas y, si corresponde, los datos de uhm-auth.txt. También genera skipuser.cfg con las IP de mac-unlimited.txt y las direcciones IPv4 de /etc/hosts. Si encuentra datos, reemplaza el contenido de esos archivos, por lo que los cambios manuales pueden perderse.
sudo nano /var/www/proxymon/lightsquid/realname.cfg
# example:
192.168.X.2 Client1
192.168.X.24 Client12
sudo nano /var/www/proxymon/lightsquid/skipuser.cfg
# example:
192.168.X.3 CEO

Exclude Users

To exclude IP addresses from reports, add them to skipuser.cfg. If UPDATE_REALNAME=true, Bandata normally rebuilds this file from mac-unlimited.txt and /etc/hosts, so manual changes may be replaced: Para excluir IP de los informes, añádelas a skipuser.cfg. Si UPDATE_REALNAME=true, Bandata normalmente vuelve a generar este archivo a partir de mac-unlimited.txt y /etc/hosts, por lo que puede reemplazar los cambios manuales:
sudo nano /var/www/proxymon/lightsquid/skipuser.cfg
# example
192.168.X.1

Netscan

To scan the devices on your local network, choose any of the following commands along with your network's IP range. e.g.: Para escanear los dispositivos de su red local, elija cualquiera de estos comandos y el rango de IP de su red. ej:
# Install required tools
sudo apt install -y nbtscan nmap arp-scan nast sudo netdiscover
# Run the following commands to scan your local network:
# 1. Using nbtscan
sudo nbtscan 192.168.X.0/24
# 2. Using nmap
sudo nmap -sn 192.168.X.0/24
# 3. Using arp-scan
sudo arp-scan --localnet
# 4. Using nast
sudo nast -m
# 5. Using netdiscover
sudo netdiscover

Lightsquid Theme

LightSquid includes two themes: metro, the default, and base, which has an older design. LightSquid incluye dos temas: metro, el predeterminado, y base, de diseño más antiguo.
sudo nano /var/www/proxymon/lightsquid/lightsquid.cfg
#$templatename        ="base";
$templatename        ="metro_tpl";

Data Statistics

LightSquid displays traffic statistics and identifies users who exceed the configured threshold. To change that threshold, edit lightsquid.cfg: LightSquid muestra las estadísticas de tráfico y señala a los usuarios que superan el umbral configurado. Para cambiar ese umbral, edita lightsquid.cfg:
sudo nano /var/www/proxymon/lightsquid/lightsquid.cfg

# Nomenclature: 10 = 10 MBytes, 512 = 512 Mbytes, 1000 = 1 Gbytes...
# By default it comes in 1000. Do not modify the value 1024.

#user maximum size per day limit (oversize)
$perusertrafficlimit = 1000*1024*1024;

Export Tools

lightsquid menu

In General Statistics, open Tools on the right side of the header to copy or print the table, or export it as PDF, XLSX, or CSV. En General Statistics, abre Tools, a la derecha del encabezado, para copiar o imprimir la tabla y exportarla como PDF, XLSX o CSV.

Reports

LightSquid can export reports, but its site view shows a selection of top domains. To collect the domains recorded in the daily reports and create a list for a Squid ACL, run: LightSquid permite exportar informes, pero su vista de sitios muestra una selección de los dominios principales. Para reunir los dominios registrados en los informes diarios y generar una lista para una ACL de Squid, ejecuta:
find /var/www/proxymon/lightsquid/report -type f -name '[0-9]*.[0-9]*.[0-9]*.[0-9]*' -exec grep -oE '[[:alnum:]_.-]+\.([[:alnum:]_.-]+)+' {} \; | sed 's/^\.//' | sed -r 's/^(www|ftp|ftps|ftpes|sftp|pop|pop3|smtp|imap|http|https)\.//g' | sed -r '/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/d' | tr -d ' ' | awk '{print "." $1}' | sort -u > domains.txt

BanData

bandata

Bandata is a script that sets data usage limits —daily, weekly, and monthly— for IP addresses on a LAN monitored with Squid, and automatically blocks those that exceed the established quotas.

Notes:
  • Weekends are excluded from the calculation.
  • The limits must match those configured in Squid Report.
  • Bandata can generate realname.cfg to map IP addresses to names and skipuser.cfg to exclude IP addresses from LightSquid reports. It reads MAC ACLs, /etc/hosts, and, when enabled, the captive portal's uhm-auth.txt.
  • On its first run Bandata writes /etc/logrotate.d/bandata if that file is missing, so /var/log/bandata.log never needs a manual truncate. The generated rule rotates the log daily, keeps seven rotations compressed, and recreates it as 640 root adm. An existing file is left untouched, so your own changes are preserved.
Bandata es un script que establece límites de consumo de datos —diario, semanal y mensual— para direcciones IP de una LAN monitorizada con Squid, y bloquea automáticamente aquellas que superan las cuotas establecidas.

Notas:
  • Los fines de semana quedan excluidos del cálculo.
  • Los límites deben coincidir con los configurados en Squid Report.
  • Bandata puede generar realname.cfg para asociar IP con nombres y skipuser.cfg para excluir IP de los informes de LightSquid. Toma los datos de las ACL MAC, de /etc/hosts y, si está activado, de uhm-auth.txt del portal cautivo.
  • En su primera ejecución, Bandata crea /etc/logrotate.d/bandata si ese archivo no existe, por lo que /var/log/bandata.log nunca necesita un truncado manual. La regla generada rota el log a diario, conserva siete rotaciones comprimidas y lo recrea como 640 root adm. Si el archivo ya existe, no lo modifica, así que tus cambios se conservan.
# Bandata - Monitor bandwidth usage and enforce data limits (every 5 minutes)
sudo crontab -e
*/5 * * * * /etc/proxymon/bandata/bandata.sh

bandata terminal

Warning Portal

warning

When an IP address exceeds its daily, weekly, or monthly quota, Bandata redirects its HTTP traffic to the Warning portal. Other traffic is blocked: Cuando una IP supera su cuota diaria, semanal o mensual, Bandata redirige su tráfico HTTP al portal de advertencia (Warning) y bloquea el resto del tráfico:
http://192.168.X.X:18081
Banned IPs
To view the blocked IP addresses: Para consultar las IP bloqueadas:
cat /etc/proxymon/bandata/acl/{banmonth,banweek,banday}.txt | uniq
Data Limit
You can enter limits in gigabytes, megabytes, or bytes; for example, 0.5G, 512M, or 536870912. The default limits are 1 GB per day, 5 GB per week, and 20 GB per month. Puedes indicar los límites en gigabytes, megabytes o bytes; por ejemplo, 0.5G, 512M o 536870912. Los valores predeterminados son 1 GB al día, 5 GB a la semana y 20 GB al mes.
By Day
Bandata compares the day's usage with the daily limit and blocks IP addresses that exceed it. On each weekday run, it recalculates the daily list from that day's report; it clears the list on weekends. An IP address is no longer blocked by the daily quota once it disappears from that list, though it may remain blocked if it appears in the weekly or monthly list. To change the daily limit, edit /etc/proxymon/proxymon.env: Bandata compara el consumo del día con el límite diario y bloquea las IP que lo superan. En cada ejecución de lunes a viernes recalcula la lista diaria con el informe de ese día; durante el fin de semana la vacía. La IP deja de estar bloqueada por cuota diaria cuando desaparece de esa lista, aunque puede seguir bloqueada si aparece en la lista semanal o mensual. Para cambiar el límite diario, edita /etc/proxymon/proxymon.env:
MAX_BANDWIDTH_DAY=1G
By Week
Every Monday, Bandata totals the usage recorded from Monday to Friday of the previous week and updates the weekly list. If an IP address exceeds the limit (5 GB by default), it remains blocked under the weekly quota until a later Monday calculation removes it from that list. It may also remain blocked if it appears in the daily or monthly list. To change the weekly limit, edit /etc/proxymon/proxymon.env: Cada lunes, Bandata suma el consumo registrado de lunes a viernes de la semana anterior y actualiza la lista semanal. Si una IP supera el límite —5 GB de forma predeterminada—, permanece bloqueada por cuota semanal hasta que el cálculo de un lunes posterior la quite de esa lista. También puede seguir bloqueada si aparece en la lista diaria o mensual. Para cambiar el límite semanal, edita /etc/proxymon/proxymon.env:
MAX_BANDWIDTH_WEEK=5G
By Month
On every run, Bandata totals usage recorded on weekdays in the current month and updates the monthly list. If an IP address exceeds the limit (20 GB by default), it remains blocked under the monthly quota while it appears on that list. At the start of the next month, the list is calculated from the new month's reports, removing blocks that applied only to the previous month. The IP may remain blocked if it appears in the daily or weekly list. To change the monthly limit, edit /etc/proxymon/proxymon.env: En cada ejecución, Bandata suma el consumo de los días hábiles del mes en curso y actualiza la lista mensual. Si una IP supera el límite —20 GB de forma predeterminada—, permanece bloqueada por cuota mensual mientras figure en esa lista. Al comenzar el mes siguiente, la lista se calcula con los informes del nuevo mes y elimina los bloqueos que solo correspondían al mes anterior. La IP puede seguir bloqueada si aparece en la lista diaria o semanal. Para cambiar el límite mensual, edita /etc/proxymon/proxymon.env:
MAX_BANDWIDTH_MONTH=20G
Bandata forma el conjunto de IP bloqueadas uniendo las listas diaria, semanal y mensual. Una IP deja de estar bloqueada cuando ya no aparece en ninguna de las tres. Bandata builds the blocked IP set by combining the daily, weekly, and monthly lists. An IP address is unblocked only when it no longer appears in any of the three.

REPORTS (SARG)

sarg

SARG (Squid Analysis Report Generator) provides detailed analysis of proxy traffic, generating comprehensive reports of user activity, bandwidth consumption, and accessed websites. It tracks connection statistics, data transfer volumes, cache efficiency, and elapsed time for each user or IP address on the network. SARG (Generador de Reportes de Análisis de Squid) proporciona análisis detallado del tráfico del proxy, generando reportes exhaustivos de la actividad de usuarios, consumo de ancho de banda y sitios web accedidos. Realiza un seguimiento de estadísticas de conexión, volúmenes de transferencia de datos, eficiencia de caché y tiempo transcurrido para cada usuario o dirección IP en la red.

Global Report

sarg global

The Global Report displays aggregated traffic statistics across all users and IP addresses. It shows the top visited websites, total bandwidth usage, connection counts, cache hit rates, and data transfer patterns. This overview helps administrators identify traffic trends, peak usage periods, and overall network behavior patterns. El Reporte Global muestra estadísticas de tráfico agregadas en todos los usuarios y direcciones IP. Presenta los sitios web más visitados, uso total de ancho de banda, conteos de conexión, tasas de acierto de caché y patrones de transferencia de datos. Esta visión general ayuda a los administradores a identificar tendencias de tráfico, períodos de uso máximo y patrones generales de comportamiento de la red.

Report by IP

sarg ip

The IP Report provides granular analysis for individual users or machines. It details specific browsing activity, showing accessed URLs, bandwidth consumption per user, connection frequency, cache efficiency, and time spent online. This enables administrators to monitor individual user behavior and enforce bandwidth policies on specific network devices. El Reporte por IP proporciona análisis detallado para usuarios o máquinas individuales. Detalla la actividad de navegación específica, mostrando URLs accedidas, consumo de ancho de banda por usuario, frecuencia de conexión, eficiencia de caché y tiempo dedicado en línea. Esto permite a los administradores monitorear el comportamiento de usuarios individuales e implementar políticas de ancho de banda en dispositivos de red específicos.

Report Rotation and Cleanup

SARG processes logs from the last 7 days, as set by lastlog 7 in /etc/sarg/sarg.conf.

Separately, a weekly task deletes SARG report directories older than 30 days.

To change these periods, edit both the configuration file and the scheduled task:
SARG procesa los registros de los últimos 7 días, según el parámetro lastlog 7 de /etc/sarg/sarg.conf.

Por separado, una tarea semanal elimina los directorios de informes de SARG que tengan más de 30 días.

Para cambiar estos períodos, modifica tanto el archivo de configuración como la tarea programada:
# Edit Sarg Config
sudo nano /etc/sarg/sarg.conf
# Change 7 to the desired number of days
lastlog 7 
# Edit crontab
sudo -u www-data crontab -l
# Replace: -mtime +30 with the desired number of days
@weekly find /var/www/proxymon/sarg/squid-reports -name "2*" -mtime +30 -type d -exec rm -rf "{}" \; &> /dev/null
# Restart cron
sudo systemctl restart cron

REALTIME (SQSTAT)

sqstat

SqStat shows the proxy's active connections. It uses the Cache Manager (cachemgr) protocol to query Squid. SqStat muestra las conexiones activas del proxy. Para consultar Squid, usa el protocolo Cache Manager (cachemgr).
The password in sqstat/config.inc.php, $cachemgr_passwd[0]="mypass";, must match the cachemgr_passwd directive of your Squid in squid.conf, cachemgr_passwd mypass all.

If you do not use those directives at all, leave both blank or commented out.

install fills this in automatically with the local user detected on the system. Edit it by hand afterwards if you use a different password in squid.conf.
La contraseña en sqstat/config.inc.php, $cachemgr_passwd[0]="mipass";, debe coincidir con la directiva cachemgr_passwd de su Squid en squid.conf, cachemgr_passwd mipass all.

Si no usa esas directivas, deje ambas en blanco o comentadas.

install la completa automáticamente con el usuario local detectado en el sistema. Edítela a mano después si usa otra contraseña en squid.conf.
Important: SqStat connects to Squid from the same server where the panel runs, using $squidhost[0] and $squidport[0] from sqstat/config.inc.php. The default is 127.0.0.1.

If your squid.conf binds http_port to a specific IP, for example http_port 192.168.1.2:3128, instead of just the port, Squid does not listen on loopback and SqStat fails with Error (111): Connection refused.

Add a loopback listener alongside the existing one:
http_port 127.0.0.1:3128
http_port 192.168.1.2:3128
Multiple http_port lines are valid as long as each IP:PORT pair is unique. A wildcard http_port 3128 cannot coexist with an explicit IP on the same port.

Then restart Squid with sudo systemctl restart squid. reload and reconfigure do not bind new ports. Verify with ss -tlnp | grep 3128: both listeners must appear.

Pointing $squidhost[0] at the LAN IP instead is not recommended. If your firewall filters traffic to that IP, the connection is dropped and SqStat fails with Error (110): Connection timed out. Loopback also satisfies Squid's usual http_access allow localhost manager rule.
Importante: SqStat se conecta a Squid desde el mismo servidor donde corre el panel, usando $squidhost[0] y $squidport[0] de sqstat/config.inc.php. El valor por defecto es 127.0.0.1.

Si su squid.conf ata http_port a una IP concreta, por ejemplo http_port 192.168.1.2:3128, en lugar de solo al puerto, Squid no escucha en loopback y SqStat falla con Error (111): Connection refused.

Agregue un listener de loopback junto al que ya tiene:
http_port 127.0.0.1:3128
http_port 192.168.1.2:3128
Varias líneas http_port son válidas siempre que cada par IP:PUERTO sea único. Un http_port 3128 comodín no puede coexistir con una IP explícita en el mismo puerto.

Luego reinicie Squid con sudo systemctl restart squid. reload y reconfigure no abren puertos nuevos. Verifique con ss -tlnp | grep 3128: deben aparecer ambos listeners.

No se recomienda apuntar $squidhost[0] a la IP de la LAN. Si su firewall filtra el tráfico hacia esa IP, la conexión se descarta y SqStat falla con Error (110): Connection timed out. Loopback además satisface la regla habitual http_access allow localhost manager de Squid.

Sqstat Themes

sqstat theme

To switch between the light and dark themes, run the corresponding command: Para cambiar entre los temas claro y oscuro, ejecuta el comando correspondiente:
# Dark Theme (Default)
sudo sed -i "s/sqstat\.css/sqstat-dark.css/" /var/www/proxymon/sqstat/sqstat.class.php
# Light Theme (Original)
sudo sed -i "s/sqstat-dark\.css/sqstat.css/" /var/www/proxymon/sqstat/sqstat.class.php

Auto Refresh

sqstat auto

Select at least 5 seconds: Seleccione al menos 5 segundos:

Reload

sqstat f5

If squid.conf contains a large ACL, SqStat may temporarily lose its connection while Squid restarts or reloads its configuration. Wait for the service to become available again, then press F5 to refresh the page. Si squid.conf contiene una ACL extensa, SqStat puede perder la conexión mientras Squid se reinicia o recarga su configuración. Espera a que el servicio vuelva a estar disponible y luego pulsa F5 para actualizar la página.

ANALYZER (SquidAnalyzer)

squidanalyzer

SquidAnalyzer parses Squid access logs and generates web reports about network traffic. Its views let you explore statistics by period, client, and domain, as well as traffic trends and transfer volumes. SquidAnalyzer analiza los registros de acceso de Squid y genera informes web sobre el tráfico. Sus vistas permiten explorar estadísticas por período, clientes y dominios, además de consultar tendencias y volúmenes de transferencia.

Analyzer Task

The installer schedules SquidAnalyzer to generate reports every day at 2:00 a.m. To change the time, edit its entry in /etc/cron.d/proxymon. El instalador programa SquidAnalyzer para generar informes todos los días a las 2:00 a. m. Para cambiar la hora, edita su tarea en /etc/cron.d/proxymon.
sudo -u www-data crontab -e
0 2 * * * cd /var/www/proxymon/squidanalyzer && perl -I. ./squid-analyzer -c etc/squidanalyzer.conf

LOGVIEW

logview

LogView displays new entries from /var/log/squid/access.log in a table that refreshes periodically.

Search the loaded entries, filter by cache code or HTTP status, and sort columns.

It also offers light and dark themes and a configurable refresh interval.
LogView muestra las nuevas entradas de /var/log/squid/access.log en una tabla que se actualiza periódicamente.

Puedes buscar entre las entradas cargadas, filtrar por código de caché o estado HTTP y ordenar las columnas.

También ofrece temas claro y oscuro y permite ajustar el intervalo de actualización.

logview_darkmode

Controls

logview_controls

Message Description Descripción
Filters by Squid cache code: TCP_HIT (cached), TCP_MISS (origin), TCP_MISS_ABORTED (aborted), TCP_DENIED (blocked), TCP_TUNNEL (HTTPS), TCP_MEM_HIT (memory cache), TCP_REFRESH_HIT/MISS (revalidated), TCP_REFRESH_UNMODIFIED/MODIFIED (revalidation result), NONE_NONE (invalid/error request). Filtra por código de caché de Squid: TCP_HIT (caché), TCP_MISS (origen), TCP_MISS_ABORTED (abortado), TCP_DENIED (bloqueado), TCP_TUNNEL (HTTPS), TCP_MEM_HIT (memoria), TCP_REFRESH_HIT/MISS (revalidado), TCP_REFRESH_UNMODIFIED/MODIFIED (resultado de revalidación), NONE_NONE (solicitud inválida/error).
Filters by HTTP response code: 200, 206, 301, 302, 400, 403, 404, 500. Color-coded: green (2xx), yellow (3xx), red (4xx/5xx). Filtra por código de respuesta HTTP: 200, 206, 301, 302, 400, 403, 404, 500. Codificado por color: verde (2xx), amarillo (3xx), rojo (4xx/5xx).
Number of lines loaded from access.log on startup: 200, 500, 1,000, 2,000, or 5,000. Número de líneas cargadas desde access.log al inicio: 200, 500, 1.000, 2.000 o 5.000.
Polling interval for new entries: 1s (default), 3s, 5s, 10s, or 30s. Intervalo de sondeo para nuevas entradas: 1s (por defecto), 3s, 5s, 10s o 30s.
Live mode active. LogView polls access.log automatically and prepends new rows with a green animation. Modo en vivo activo. LogView sondea el access.log automáticamente y agrega nuevas filas con animación verde.
Polling suspended. Indicator turns red and shows PAUSED. Click again to resume. Sondeo suspendido. El indicador cambia a rojo y muestra PAUSED. Haga clic nuevamente para reanudar.
Dark Mode button. Botón para activar el modo oscuro.

Search Bar

logview_search

The search bar filters loaded entries by IP address, URL, user, HTTP method, cache code, or HTTP response code. La barra filtra las entradas cargadas por IP, URL, usuario, método HTTP, código de caché o código de respuesta HTTP.
Message Description Descripción
Select this option to search the full log. Selecciona esta opción para buscar en el registro completo.
Select this option to return to the live view. Selecciona esta opción para volver a la vista en tiempo real.

AI

squidai

SquidAI is an assistant for network administrators. It uses BM25 to find relevant information in its data and a language model (LLM) to respond in natural language. It combines data from Squid, LightSquid reports, and ACL lists to help answer questions about user profiles, blocked activity, incidents, and network usage:
  • User profiles: Activity summary, most visited domains and blacklist verification for specific users.
  • Security incidents: Detection of direct IP access, Torrent/P2P traffic, Log4Shell patterns, .onion sites and other suspicious behaviors.
  • Blocked access: Which IPs attempted to access blocked domains or TLDs.
  • Network summary: Top consumers, most visited domains, total bandwidth usage and unique IPs.
  • Consumption thresholds: Users exceeding specific GB limits (e.g. "more than 3 GB").
  • User list: Complete list of registered users from realname.cfg (excluding skipuser.cfg) of LightSquid.
The assistant responds in Spanish or English, matching the language of the question, and presents its findings in tables and detailed analyses.
SquidAI es un asistente especializado para administradores de red. Usa BM25 para localizar información relevante en sus datos y un modelo de lenguaje (LLM) para responder en lenguaje natural. Combina respuestas basadas en datos de Squid, informes de LightSquid y listas ACL. Puede ayudar a consultar perfiles de usuario, actividad bloqueada, incidentes y consumo de la red:
  • Perfiles de usuario: Resumen de actividad, dominios más visitados y verificación en lista negra para usuarios específicos.
  • Incidentes de seguridad: Detección de accesos a IPs directas, tráfico Torrent/P2P, patrones Log4Shell, sitios .onion y otros comportamientos sospechosos.
  • Accesos bloqueados: Qué IPs intentaron acceder a dominios o TLDs bloqueados.
  • Resumen de red: Principales consumidores, dominios más visitados, uso total de ancho de banda e IPs únicas.
  • Umbrales de consumo: Usuarios que superan límites específicos en GB (ej: "más de 3 GB").
  • Lista de usuarios: Lista completa de usuarios registrados desde realname.cfg (excluyendo skipuser.cfg) de LightSquid.
El asistente responde en español o inglés, según el idioma de la consulta, y presenta la información en tablas y análisis detallados.

Examples

User queries:
"Show me JOHN-SMITH activity"
"What did CARLOS-GARCIA do today?"
"Report for ACCOUNTING-DEPT"
Consultas de usuario:
"Muéstrame la actividad de JOHN-SMITH"
"¿Qué hizo CARLOS-GARCIA hoy?"
"Reporte de CONTABILIDAD"
Network queries:
"Top 10 most visited domains today"
"Who consumes the most bandwidth?"
"Users who exceeded 3 GB"
Consultas de red:
"Top 10 dominios más visitados hoy"
"¿Quién consume más ancho de banda?"
"Usuarios que superaron 3 GB"
Security queries:
"Are there security incidents?"
"Detect any threat today?"
"Is there torrent traffic?"
Consultas de seguridad:
"¿Hay incidentes de seguridad?"
"¿Detectas alguna amenaza hoy?"
"¿Hay tráfico de torrents?"
Blocked accesses:
"Which IPs accessed blocked domains?"
"Show blocked TLD accesses"
Accesos bloqueados:
"¿Qué IPs accedieron a dominios bloqueados?"
"Muestra accesos a TLDs bloqueados"
User list:
"List all registered users"
"Show me all users"
Lista de usuarios:
"Lista todos los usuarios registrados"
"Muéstrame todos los usuarios"

Note: The user names in the examples are illustrative. For the assistant to recognize them, they must exist in realname.cfg (and not be excluded in skipuser.cfg), where LightSquid stores the IP/Hostname mapping.

Nota: Los nombres de usuario en los ejemplos son ilustrativos. Para que el asistente los reconozca, deben existir en realname.cfg (y no estar excluidos en skipuser.cfg), donde LightSquid almacena el mapeo de IP/Hostname.

Security Incident

⚠️ Important: For security incident detection, SquidAI uses /etc/acl/squid/blockpatterns.txt and direct IPv4 detection. Severity depends on the pattern type and number of matches; results can be classified as CRITICAL, HIGH, MEDIUM, or LOW. ⚠️ Importante: Para la detección de incidentes de seguridad, SquidAI utiliza /etc/acl/squid/blockpatterns.txt y detección de IPv4 directa. La severidad depende del tipo de patrón y del número de coincidencias; los resultados pueden clasificarse como CRITICAL, HIGH, MEDIUM o LOW.

API Configuration

🔧 API Setup: SquidAI requires an LLM provider to function. The configuration file is located outside the webroot for security:
sudo nano /etc/proxymon/.env
Note: /etc/proxymon/ contains two files: .env (SquidAI LLM credentials) and proxymon.env (Bandata network and quota settings). Do not confuse them. Set your provider URL, API key and response format:
LLM_URL=https://your-provider.com/endpoint
LLM_API_KEY=your_api_key
LLM_MODEL=model-name
LLM_RESPONSE_FORMAT=openai
Note: the URL format depends on the provider.
  • Some providers include the account ID or the model name in the URL, for example Cloudflare: …/accounts/ACCOUNT_ID/ai/run/MODEL_NAME.
  • Others use a fixed URL with the model in LLM_MODEL, for example OpenAI and Groq.
  • Others embed the API key as a URL parameter, for example Gemini: …?key=YOUR_KEY.
Check the commented examples in the .env file for each provider's exact format. Leave LLM_MODEL empty if the model is already part of the URL.

LLM_RESPONSE_FORMAT tells the worker how to read the response: openai (most providers), ollama (local Ollama), or gemini (Google Gemini passthrough).

The file includes commented examples for: Cloudflare Workers AI, OpenAI, Groq, OpenRouter, Together AI, Ollama (local), LM Studio (local) and Google Gemini. Uncomment one block and fill in your credentials.

🔒 Security: The .env file is stored in /etc/proxymon/, outside the Apache webroot. Permissions are set to 640 (root:www-data), allowing root and processes in the www-data group, including Apache PHP, to read the file.

🔄 Rate Limits & Retries: LLM APIs may experience congestion depending on demand. SquidAI implements an automatic retry mechanism: up to 4 attempts with progressive delays (4s, 8s, 15s) before giving up. If the API is temporarily unavailable, the assistant will display retry messages. After all attempts fail, it will show a message (check table).

🔧 Configuración de API: SquidAI requiere un proveedor LLM para funcionar. El archivo de configuración se encuentra fuera del webroot por seguridad:
sudo nano /etc/proxymon/.env
Nota: /etc/proxymon/ contiene dos archivos: .env (credenciales LLM de SquidAI) y proxymon.env (configuración de red y cuotas de Bandata). No los confunda. Configure la URL del proveedor, la API key y el formato de respuesta:
LLM_URL=https://su-proveedor.com/endpoint
LLM_API_KEY=su_api_key
LLM_MODEL=nombre-del-modelo
LLM_RESPONSE_FORMAT=openai
Nota: el formato de la URL depende del proveedor.
  • Algunos proveedores incluyen el Account ID o el nombre del modelo en la URL, por ejemplo Cloudflare: …/accounts/ACCOUNT_ID/ai/run/NOMBRE_MODELO.
  • Otros usan una URL fija con el modelo en LLM_MODEL, por ejemplo OpenAI y Groq.
  • Otros incrustan la clave de API como parámetro de la URL, por ejemplo Gemini: …?key=SU_CLAVE.
Consulte los ejemplos comentados del archivo .env para ver el formato exacto de cada proveedor. Deje LLM_MODEL vacío si el modelo ya forma parte de la URL.

LLM_RESPONSE_FORMAT indica al worker cómo leer la respuesta: openai (la mayoría de proveedores), ollama (Ollama local) o gemini (Google Gemini passthrough).

El archivo incluye ejemplos comentados para: Cloudflare Workers AI, OpenAI, Groq, OpenRouter, Together AI, Ollama (local), LM Studio (local) y Google Gemini. Descomente un bloque y complete sus credenciales.

🔒 Seguridad: El archivo .env se almacena en /etc/proxymon/, fuera del webroot de Apache. Los permisos son 640 (root:www-data): el archivo queda accesible para root y para los procesos del grupo www-data, incluido PHP de Apache.

🔄 Límites de tasa y reintentos: Las APIs LLM pueden experimentar congestión según la demanda. SquidAI implementa un mecanismo de reintento automático: hasta 4 intentos con retardos progresivos (4s, 8s, 15s) antes de desistir. Si la API no está disponible temporalmente, el asistente mostrará mensajes de reintento y al finalizar mostrará un mensaje (ver tabla).

Message Description Descripción
Example of the automatic retry message. Ejemplo del mensaje de reintento automático.
Example shown when the API is unavailable. Ejemplo de API no disponible.

LLM status

🔌 LLM Status: The LED indicates whether the connection is checking, connected, or offline. 🔌 Estado LLM: El LED indica si la conexión se está verificando, está conectada o está fuera de línea.
Message Description Descripción
Checking LLM connection Verificando conexión con el LLM
LLM connected and ready LLM conectado y listo
LLM unreachable or offline LLM inaccesible o fuera de línea

TOOLS

Description Descripción
Command-line utilities are installed in /etc/proxymon/tools and run from a terminal. The HTML reports they generate can be viewed from the panel. Las utilidades de consola se instalan en /etc/proxymon/tools y se ejecutan desde la terminal. Los informes HTML que generan se pueden consultar desde el panel.

Squidtool

Description Descripción
Squidtool is a command-line utility with two functions: generate a traffic report and search Squid logs. Run it with: Squidtool es una utilidad de consola con dos funciones: generar un informe de tráfico y buscar términos en los registros de Squid. Se ejecuta con:
sudo /etc/proxymon/tools/squidtool.sh

Each function generates an HTML report and replaces the previous report of the same type, so only the latest result is kept. The reports are written to /etc/proxymon/tools/reports, outside the Apache webroot, and the panel serves them read-only under the same LAN restriction. Tool activity is logged in /etc/proxymon/tools/squidtool.log.

Cada función genera un informe HTML y reemplaza el anterior del mismo tipo; solo se conserva el resultado más reciente. Los informes se escriben en /etc/proxymon/tools/reports, fuera del webroot de Apache, y el panel los publica en modo lectura con la misma restricción a la red local. La herramienta registra su actividad en /etc/proxymon/tools/squidtool.log.

Traffic Report

squidtool traffic

Description Descripción
Analyzes the requests recorded by Squid, grouping them by client IP and requested domain. It allows selecting a single IP or analyzing every IP, and defining the period to review. The analysis covers the current access.log and its rotated or compressed files. Requests are counted and sorted from the most active to the least. When every IP is analyzed, entries below 20 requests are excluded. Entries reaching or exceeding 300 requests are shown as alerts. The result is written to squid_traffic.html. Analiza las solicitudes registradas por Squid, agrupándolas por IP de cliente y dominio solicitado. Permite seleccionar una IP concreta o analizar todas las IP y definir el período que se desea revisar. El análisis incluye el access.log actual y sus archivos rotados o comprimidos. Las solicitudes se contabilizan y se ordenan de mayor a menor actividad. Cuando se analizan todas las IP, se excluyen las entradas con menos de 20 solicitudes. Las entradas que alcanzan o superan las 300 solicitudes se muestran como alertas. El resultado se genera en squid_traffic.html.
Log Search

squidtool search

Description Descripción
Searches for a specific term in the access.log and cache.log records, without distinguishing between uppercase and lowercase. The text is matched literally, not as a regular expression, so characters such as ?, &, = or * are searched as typed. The search includes the current, rotated and compressed files. In access.log it allows filtering by client IP and setting the search period. In cache.log the IP filter does not apply, because that record does not contain the client IP. The results from access.log and cache.log are shown separately, along with the number of matches found in each record. The result is written to squid_search.html.

For cache.log to record the ACL decisions -- which rule allowed or blocked each request -- Squid must have debug_options ALL,1 33,2 28,9 enabled in squid.conf. Without it the search still works, but that record only holds the usual service messages. Keep in mind that this directive makes cache.log grow considerably.
Busca un término específico en los registros access.log y cache.log, sin distinguir entre mayúsculas y minúsculas. El texto se busca de forma literal, no como expresión regular, de modo que caracteres como ?, &, = o * se buscan tal cual se escriben. La búsqueda incluye los archivos actuales, rotados y comprimidos. En access.log permite filtrar por IP de cliente y establecer el período de búsqueda. En cache.log no se aplica el filtro por IP porque este registro no contiene la IP del cliente. Los resultados de access.log y cache.log se muestran por separado, junto con la cantidad de coincidencias encontradas en cada registro. El resultado se genera en squid_search.html.

Para que cache.log registre las decisiones de ACL -- qué regla permitió o bloqueó cada petición -- Squid debe tener activada la directiva debug_options ALL,1 33,2 28,9 en squid.conf. Sin ella la búsqueda sigue funcionando, pero ese registro solo contendrá los mensajes habituales del servicio. Tenga en cuenta que esa directiva hace crecer cache.log de forma considerable.

pmbk

pmbk.sh creates a ZIP archive with the Proxy Monitor installation and configuration, including the paths listed below:
  • The project install tree, /var/www/proxymon, and /etc/proxymon.
  • The MAC and Squid ACL lists.
  • The Apache vhosts and the Apache and PHP hardening files.
  • SARG's configuration and its usertab.
  • The bandata logrotate configuration.
  • The project's /etc/cron.d/proxymon entry and the php.ini in use.
Paths that do not exist are skipped. pmsetup.sh update runs this backup before updating project files.
pmbk.sh crea un archivo ZIP con la instalación y configuración de Proxy Monitor, incluidas las rutas que se enumeran a continuación:
  • El árbol de instalación del proyecto, /var/www/proxymon, y /etc/proxymon.
  • Las listas ACL de MAC y de Squid.
  • Los vhosts de Apache y los archivos de hardening de Apache y PHP.
  • La configuración de SARG y su usertab.
  • La configuración de logrotate de bandata.
  • La entrada /etc/cron.d/proxymon del proyecto y el php.ini en uso.
Las rutas que no existan se omiten. pmsetup.sh update ejecuta esta copia de seguridad antes de actualizar los archivos del proyecto.
Command Description Descripción
sudo bash pmbk.sh Create a backup now Crear una copia ahora
sudo bash pmbk.sh install Register the @monthly cron entry Registrar la entrada mensual en cron
sudo bash pmbk.sh uninstall Remove the cron entry, keeping the archives Quitar la entrada de cron, conservando los comprimidos

Backs up Proxymon into /etc/bak/proxymon/pmbk_<YYYYMMDD_HHMMSS>.zip, keeping up to 3 archives. pmsetup.sh install registers the monthly cron entry automatically; pmsetup.sh uninstall removes it before removing the project. Restore by unzipping it over /.

Respalda Proxymon en /etc/bak/proxymon/pmbk_<YYYYMMDD_HHMMSS>.zip, conservando hasta 3 comprimidos. pmsetup.sh install registra la entrada mensual de cron automáticamente; pmsetup.sh uninstall la elimina antes de quitar el proyecto. Para restaurar, descomprímalo sobre /.

PROXYMON LOGS

/var/log/apache2/proxymon_access.log
/var/log/apache2/proxymon_error.log
/var/log/bandata.log                 # Rotated via /etc/logrotate.d/bandata
pmsetup.log                          # In pmsetup.sh's own directory, rewritten on each run
/etc/proxymon/tools/squidtool.log    # In squidtool.sh's own directory, rewritten on each run

ORIGINAL PROJECTS


Proxy Monitor preserves and integrates four Squid analysis tools that no longer receive maintenance: LightSquid, SARG, SqStat and SquidAnalyzer. The table lists their official versions and available community updates. Proxy Monitor preserva e integra cuatro herramientas de análisis para Squid que ya no reciben mantenimiento: LightSquid, SARG, SqStat y SquidAnalyzer. La tabla muestra sus versiones oficiales y las actualizaciones comunitarias disponibles.
Project / Developer Last Official Version Unofficial Update Additional
LightSquid v1.8-7 (2009) v1.8.1 (2021) Metro_tpl (2020)
SARG v2.4.0 (2020-01-16) N/A N/A
Sqstat - Alex Samorukov v1.20 (2006) N/A N/A
SquidAnalyzer github v6.6 (2017) N/A N/A

⚠️ WARNING: NETWORK ACCESS


This project is designed for use on a local network (LAN). It does not include the security hardening needed for direct exposure to the internet. If internet access is required, an on-demand tunnel is recommended instead of opening ports directly. This enables access when needed without leaving the server permanently exposed. Este proyecto está diseñado para usarse en una red local (LAN). No cuenta con las medidas de seguridad necesarias para exponerlo directamente a Internet. Si se requiere acceso desde Internet, se recomienda utilizar un túnel bajo demanda en lugar de abrir puertos directamente. Así, el acceso se habilita cuando hace falta y el servidor no queda expuesto permanentemente.

Optional tunnel:

NOTICE


This repository
  • May include third-party components.
  • Does not accept Pull Requests. Changes must be proposed via Issues.
Este repositorio
  • Puede incluir componentes de terceros.
  • No acepta Pull Requests. Los cambios deben proponerse mediante Issues.

SPONSOR THIS PROJECT


Image

PROJECT LICENSES


This project uses a dual-licensing model to balance software freedom with content protection: Este proyecto utiliza un modelo de licencia dual para equilibrar la libertad del software con la protección del contenido:
Content Licensed Under
Scripts, Binaries, Infrastructure GPL-3.0
RAG, Workers, Specialized Modules, Docs CC

DISCLAIMER


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

Traffic management and auditing tool for Squid proxy server

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages