SMBstack — Samba Server Stack
|
Many small and medium-sized businesses need to share files on their local network. They may also need to recover deleted files, review access records, manage files through a browser and control storage usage. Dedicated NAS devices often provide these functions, but their cost can be a barrier in some environments. One alternative is to use Samba on Linux. A standard installation lets you share files and folders; additional components are needed for the other functions. SMBstack provides part of this infrastructure using Samba on Ubuntu as its base. Samba remains responsible for file sharing and permission management. SMBstack adds a recycle bin with separate channels for each source, audit logging through In the background, |
Muchas pequeñas y medianas empresas necesitan compartir archivos en su red local. Además, pueden necesitar recuperar archivos eliminados, consultar los accesos, gestionar archivos desde un navegador y controlar el espacio utilizado. Estas funciones suelen ofrecerse en dispositivos NAS, cuyo costo puede ser una barrera en algunos entornos. Una alternativa es usar Samba en Linux. La instalación estándar permite compartir archivos y carpetas; para añadir las demás funciones se necesitan componentes adicionales. SMBstack proporciona parte de esta infraestructura utilizando Samba sobre Ubuntu como base. Samba sigue a cargo de compartir archivos y gestionar permisos. SMBstack añade una papelera con canales separados según el origen de los archivos, auditoría mediante En segundo plano, |
- Apache2 and PHP (
apache2,apache2-utils,libapache2-mod-php,php) rsyslog,logrotateacl,openssl,cron,iproute2,sudo,systemd,util-linux,zip(checked bysmbsetup.sh)inotify-tools,procps,coreutils,findutils,cron,util-linux,sed,grep(checked bytools/smbwatch.sh)procps,samba,winbind,util-linux,coreutils,sed,systemd(checked bytools/smbload.sh)zip,coreutils,util-linux,cron(checked bytools/smbbk.sh)findutils,coreutils,util-linux,cron,php-cli(checked bytools/smbreport.sh)
apt-get install -y apache2 apache2-utils libapache2-mod-php php rsyslog logrotate \
acl openssl cron iproute2 sudo systemd util-linux sed grep inotify-tools \
procps coreutils findutils zipThe Samba packages (samba, samba-common, samba-common-bin, smbclient, winbind, cifs-utils) are installed by smbsetup.sh itself.
Important
|
Importante
|
|
Each view can be opened in two ways:
Both forms of access are valid. |
Cada vista puede abrirse de dos maneras:
Ambas formas de acceso son válidas. |
|
The audit view is one of the three tabs of the web panel. It is accessed through The audit view reads Date, IP, action and text filters are applied in the browser to the records already received. You can view the results in pages of 50, 100, 200 or 500 records. The Export PDF button opens the browser's print window with three columns: date and time, IP and file. You can save or print the document there; the server does not generate the PDF. |
La vista de auditoría es una de las tres pestañas del panel web. Se accede mediante La vista consulta Los filtros de fecha, IP, acción y texto se aplican en el navegador a los registros recibidos. Puedes ver los resultados en páginas de 50, 100, 200 o 500 registros. El botón Export PDF abre la ventana de impresión del navegador con tres columnas: fecha y hora, IP y archivo. Desde allí puedes guardar o imprimir el documento; el servidor no genera el PDF. |
|
The web panel is an Apache VirtualHost listening on port The Shared tab displays the contents of the shared folder. From there a document can be opened, downloaded or moved to the recycle bin. The root of the shared folder is read-only: you cannot upload files, create folders or delete items there. These actions are available inside subfolders. Apache runs the panel as the The light and dark themes are selected from the top bar. The selection is stored in the browser and applied to the three tabs. |
El panel web es un VirtualHost de Apache que escucha en el puerto La pestaña Shared muestra el contenido de la carpeta compartida. Desde allí se puede abrir un documento, descargarlo o moverlo a la papelera de reciclaje. La raíz de la carpeta compartida es de solo lectura: desde allí no puedes subir archivos, crear carpetas ni eliminar elementos. Estas acciones están disponibles dentro de las subcarpetas. Apache ejecuta el panel como el usuario Los temas claro y oscuro se seleccionan desde la barra superior. La selección se guarda en el navegador y se aplica a las tres pestañas. |
|
|
|
The report view is the third tab of the web panel. It is accessed through It contains three tables: the thirty extensions with the largest total size, the thirty folders with the largest total size, and the fifty largest files, with their full path. The extensions table includes the file count, the average size and the share they represent of the total.
The view requests the data from The report excludes the recycle bin, so its files do not appear in the tables. The JSON file is also unavailable over HTTP: |
La vista de informe es la tercera pestaña del panel web. Se accede mediante Contiene tres tablas: las treinta extensiones con mayor tamaño total, las treinta carpetas con mayor tamaño total y los cincuenta archivos más grandes, con su ruta completa. La tabla de extensiones incluye el número de archivos, el tamaño promedio y la proporción que representan sobre el total.
La vista solicita los datos a El informe no incluye la papelera, por lo que sus archivos no aparecen en las tablas. El archivo JSON tampoco está disponible por HTTP: |
What SMBstack does:
|
Lo que SMBstack hace:
|
Out of scope (not implemented):
|
Fuera de alcance (no implementado):
|
smbstack/
├── acl/ # Static access-control lists for Samba
│ └── commonveto.txt # Veto list for common unwanted file types (active by default in smb.conf)
│
├── conf/ # Samba, rsyslog and Apache configuration
│ ├── fullaudit.conf # rsyslog full audit rule
│ ├── smb.conf # Samba main config (placeholders: your_user, compartida)
│ └── smbweb.conf # Apache vhost (:3092/?tab=shared, ?tab=audit and ?tab=report)
│
├── tools/ # Background watchdog and maintenance scripts
│ ├── smbbk.sh # Configuration backup for smbstack
│ ├── smbload.sh # Service watchdog (smbd + winbind + smbwatch)
│ ├── smbreport.sh # Disk usage report for the shared folder (daily cron)
│ └── smbwatch.sh # Shared folder size monitor (self-managed)
│
├── web/ # Web front-end: shared-folder browser, audit log viewer and disk report
│ ├── icon.svg # PWA / apple-touch icon
│ ├── index.php # Main page (Shared / Audit / Report tabs)
│ ├── manifest.json # PWA manifest
│ ├── smbshared.php # Shared folder dynamic browser
│ ├── smbapi.php # Audit log and disk report reader API
│ ├── smbaudit-diagnostic.php # Audit log diagnostic tool
│ ├── smbaudit.html # Audit log viewer UI
│ ├── smbreport.html # Disk report viewer UI
│ └── sw.js # PWA service worker (app-shell cache only)
│
└── smbsetup.sh # Installer: install, update, uninstall, status
| Files and directories generated at runtime (not included in the repository): | Archivos y directorios generados en runtime (no incluidos en el repositorio): |
/var/www/smbstack/
├── .size_cache/ # Folder size cache used by smbshared.php (www-data, pruned daily by cron)
└── web/ # Deployed copy of web/ (served by Apache on :3092)
└── smbreport.json # Disk report written by tools/smbreport.sh (root:www-data, 640)
/etc/smbstack/
├── acl/ # Deployed copy of acl/ (root:root, 644)
│ └── commonveto.txt # Veto list included by smb.conf
├── tools/ # Deployed copy of tools/*.sh (root:root, 755)
└── smbstack.env # Saved install config (user, paths, network, trusted proxies, watch limit, max log lines)
/etc/bak/smbstack/ # Archives written by tools/smbbk.sh (smbbk_<YYYYMMDD_HHMMSS>.zip, last 3 kept),
# run by --update before overwriting application code, and by its own monthly cron
/etc/cron.d/smbstack # All cron entries of the project, one file
/var/log/smbwatch.log # smbwatch.sh runtime log (root:root, 640)
/var/log/smbload.log # smbload.sh runtime log, rewritten on each run
/var/log/smbstack.log # smbbk.sh and smbreport.sh runtime log, shared
smbsetup.log # In smbsetup.sh's own directory, rewritten on each run
/home/$local_user/shared/ # Shared folder (independent of the installer)
├── .recycle/ # Recycle Bin (smbguest/, www-data/, smbwatch/)
└── DEMO/ # Demo folder
/etc/logrotate.d/samba # Generated by installer (heredoc)
/etc/logrotate.d/smbwatch # Generated by installer (heredoc), rotates /var/log/smbwatch.log
/var/log/samba/log.audit # Created by rsyslog
/var/log/samba/log.samba # Created by installer, written directly by smbd
Every cron entry of the project lives in
/etc/cron.d/smbstack.smbsetup.sh,tools/smbwatch.sh,tools/smbreport.shandtools/smbbk.shadd or remove their own line in that file.Each line names the user that runs the task, as required by the
/etc/cron.dformat. The scripts add or remove only their own entries in/etc/cron.d/smbstack.
--uninstalldeletes the file.Installations made before this change keep their entries in root's crontab. The installer removes them, identified by the full script path.
Todas las entradas de cron del proyecto viven en
/etc/cron.d/smbstack.smbsetup.sh,tools/smbwatch.sh,tools/smbreport.shytools/smbbk.shagregan o eliminan su propia línea en ese archivo.Cada línea indica el usuario que ejecutará la tarea, como requiere el formato de
/etc/cron.d. Los scripts agregan o eliminan únicamente sus propias entradas en/etc/cron.d/smbstack.
--uninstallelimina el archivo.Las instalaciones anteriores a este cambio conservan sus entradas en el crontab de root. El instalador las retira, identificadas por la ruta completa del script.
| Download the repository and run the installer: | Descarga el repositorio y ejecuta el instalador: |
git clone --depth=1 https://github.com/maravento/smbstack.git
cd smbstack
sudo bash smbsetup.sh
# or, to skip the menu and install directly | o, para saltar el menú e instalar directamente
sudo bash smbsetup.sh --install| The installer will prompt for: | El instalador preguntará por: |
| Prompt | Description | Descripción |
|---|---|---|
| Shared folder name | Name for the shared folder (created under /home/$local_user/) |
Nombre de la carpeta compartida (creada bajo /home/$local_user/) |
| Network interface | Selected from available interfaces listed. The Samba network is derived from its address and prefix | Seleccionada de las interfaces disponibles listadas. La red de Samba se deriva de su dirección y prefijo |
| Samba username | Samba account to create | Cuenta de Samba a crear |
| Overwrite smb.conf | Only asked if /etc/samba/smb.conf already exists |
Solo se pregunta si /etc/samba/smb.conf ya existe |
|
Set
Another installer deploying SMBstack can use this variable to provide the interface it already knows.
The installer looks for an account whose UID falls within the range in That account owns the shared folder and provides the base name for the Samba username. |
Define
Otro instalador que despliega SMBstack puede utilizar esta variable para proporcionar la interfaz que ya conoce.
El instalador busca una cuenta con UID dentro del rango de Usa esa cuenta como propietaria de la carpeta compartida y como base para el nombre de usuario de Samba. |
| To update or uninstall SMBstack, download the updated repository, enter the folder and run: | Para actualizar o desinstalar SMBstack, descarga el repositorio actualizado, entra a la carpeta y ejecuta: |
cd smbstack
sudo bash smbsetup.sh --update
# or | o
sudo bash smbsetup.sh --uninstall| File | --update |
--uninstall |
|---|---|---|
conf/smb.conf |
⛔ not touched (user-customized) | ✅ restored from .bak if it exists (only created when the installer overwrote a pre-existing smb.conf; on a fresh install, no .bak exists and smb.conf is left untouched) |
conf/fullaudit.conf |
⛔ not touched (user-customized) | ✅ removed |
conf/smbweb.conf |
⛔ not touched (user-customized) | ✅ removed |
web/index.php |
✅ overwritten | ✅ removed |
web/smbaudit.html |
✅ overwritten | ✅ removed |
web/smbapi.php |
✅ overwritten | ✅ removed |
web/smbaudit-diagnostic.php |
✅ overwritten | ✅ removed |
web/smbshared.php |
✅ overwritten | ✅ removed |
web/manifest.json |
✅ overwritten | ✅ removed |
web/sw.js |
✅ overwritten | ✅ removed |
web/icon.svg |
✅ overwritten | ✅ removed |
tools/smbbk.sh |
✅ overwritten | ✅ removed (its cron entry is deregistered first) |
tools/smbload.sh |
✅ overwritten | ✅ removed |
tools/smbreport.sh |
✅ overwritten | ✅ removed (its cron entry is deregistered first) |
tools/smbwatch.sh |
✅ overwritten | ✅ removed |
/etc/smbstack/smbstack.env |
⛔ preserved | ✅ removed |
Shared folder (/home/$local_user/shared/) |
⛔ never touched | ⛔ never touched |
The shared folder is independent of the installer. To remove it, do so manually:
rm -rf /home/$local_user/sharedLa carpeta compartida es independiente del instalador. Para eliminarla, hazlo manualmente:
rm -rf /home/$local_user/shared
|
Before updating files, It only updates the application code: the web viewers in PHP and HTML and The configuration files deployed during the installation, To incorporate changes to those files after an update, compare them with the versions in |
Antes de actualizar los archivos, Solo actualiza el código de la aplicación: los visores web en PHP y HTML y Los archivos de configuración desplegados en la instalación, Para incorporar cambios en esos archivos después de actualizar, compáralos con las versiones de |
sudo bash smbsetup.sh --status|
Shows the status of the |
Muestra el estado de los servicios |
| After installation, the main configuration files are: | Tras la instalación, los archivos de configuración principales son: |
| Description | File |
|---|---|
| Samba main config | /etc/samba/smb.conf |
| Audit rsyslog rule | /etc/rsyslog.d/fullaudit.conf |
| Web vhost (audit + shared) | /etc/apache2/sites-available/smbweb.conf |
| Log rotation (Samba logs) | /etc/logrotate.d/samba |
Log rotation (smbwatch.sh) |
/etc/logrotate.d/smbwatch |
| Install config | /etc/smbstack/smbstack.env |
smbsetup.sh writes the nine keys below during install and never overwrites the file on update. smbwatch.sh install adds two more of its own, WATCH_LIMIT_GB and WATCH_EXCLUDE; see the smbwatch section.
|
smbsetup.sh escribe las nueve claves de abajo durante install y no sobrescribe el archivo en update. smbwatch.sh install añade dos propias, WATCH_LIMIT_GB y WATCH_EXCLUDE; ver la sección de smbwatch.
|
| Variable | Read by | Description | Descripción |
|---|---|---|---|
LOCAL_USER |
smbbk.sh |
Non-root local user that owns the shared folder and the backups | Usuario local sin privilegios que posee la carpeta compartida y las copias |
SHARED_NAME |
smbshared.php |
Share name as the SMB clients see it | Nombre del recurso tal como lo ven los clientes SMB |
SHARED_PATH |
smbwatch.sh, smbreport.sh, smbshared.php |
Absolute path of the shared folder | Ruta absoluta de la carpeta compartida |
SMB_NET |
smbsetup.sh |
LAN subnet in CIDR form allowed to reach the share | Subred LAN en formato CIDR autorizada a acceder al recurso |
SMB_IFACE |
smbsetup.sh |
Interface Samba binds to | Interfaz a la que se enlaza Samba |
SERVER_IP |
smbsetup.sh, smbshared.php |
Server's own IPv4 on that interface | IPv4 del servidor en esa interfaz |
SMBNAME |
smbsetup.sh |
Samba account created for the share | Cuenta de Samba creada para el recurso |
MAX_LOG_LINES |
smbapi.php, smbaudit-diagnostic.php |
Maximum lines read from the current audit log per request; default 50000. The audit viewer's own request uses a fixed limit in its JavaScript, so raising this does not change what the UI asks for |
Máximo de líneas que se leen del log de auditoría vigente por petición; valor predeterminado 50000. La petición del visor usa un límite fijo en su JavaScript, así que subir esta clave no cambia lo que pide la interfaz |
TRUSTED_PROXIES |
smbshared.php |
IPv4 addresses, comma-separated, whose REMOTE_ADDR is trusted to carry the real client IP in a header; default 127.0.0.1 |
Direcciones IPv4 separadas por comas cuyo REMOTE_ADDR se considera fiable para traer la IP real del cliente en un encabezado; valor predeterminado 127.0.0.1 |
|
This setting tells The setting has no effect on direct access from the LAN. |
Esta configuración indica a La configuración no tiene efecto sobre el acceso directo desde la LAN. |
# Verify Samba config | Verificar configuración de Samba
testparm
# Restart services | Reiniciar servicios
sudo systemctl restart smbd winbind
# View audit log | Ver log de auditoría
tail -f /var/log/samba/log.audit
# List Samba users | Listar usuarios de Samba
sudo pdbedit -L|
To use a shared folder located outside |
Para utilizar una carpeta compartida ubicada fuera de |
|
SMBstack uses the Samba |
SMBstack utiliza el módulo |
|
SMBstack uses three independent channels to write to the recycle bin, each running under a different system context: |
SMBstack utiliza tres canales independientes para escribir en la papelera de reciclaje, cada uno ejecutándose bajo un contexto de sistema diferente: |
| Path | Written by | Purpose | Propósito |
|---|---|---|---|
.recycle/smbguest/ |
SMB clients on the LAN, through vfs_recycle (smbguest, set by force user in smb.conf) |
Holds files deleted by users from Windows or Linux over the network | Guarda los archivos borrados por los usuarios desde Windows o Linux por la red |
.recycle/www-data/ |
The web interface running under Apache (www-data) |
Holds files deleted from the browser panel | Guarda los archivos borrados desde el panel web |
.recycle/smbwatch/ |
tools/smbwatch.sh (root:root) |
Holds files moved out automatically when a monitored folder exceeds its size limit | Guarda los archivos retirados automáticamente cuando una carpeta monitoreada supera su límite de tamaño |
| This is why the recycle bin directory contains one subdirectory per channel: | Por eso el directorio de la papelera contiene un subdirectorio por canal: |
.recycle/
├── smbguest/ # Files deleted by Windows/Linux SMB clients on the LAN
│ └── DOCUMENTS/
│ ├── report.docx
│ └── Copy #1 of report.docx
├── www-data/ # Files deleted via the web browser interface
│ └── 20260623/
│ └── invoice.pdf
└── smbwatch/ # Files auto-moved by the size-limit watchdog
└── 20260711/
└── bigfile.iso
the recycle bin lives inside the shared folder itself, so that recycling a file is a
mvwithin the same filesystem: instantaneous and without copying data, something that would not happen if the bin were on another disk. For the details of each channel, see the Web Interface, smbwatch and Configuration reference sections.
la papelera vive dentro de la propia carpeta compartida para que reciclar un archivo sea un
mvdentro del mismo sistema de archivos: instantáneo y sin copiar datos, algo que no ocurriría si la papelera estuviera en otro disco. Para conocer el detalle de cada canal, consulta las secciones Web Interface, smbwatch y Configuration reference.
|
The weekly cleanup deletes items based on their modification date. Each channel therefore updates that date when moving an item to the recycle bin. Otherwise, an old file could be deleted during the next cleanup even though it had only just been recycled. Each channel updates the item's modification date with the current date when moving it to the bin: |
La limpieza semanal elimina elementos según su fecha de modificación. Por eso, al mover un archivo a la papelera, cada canal actualiza esa fecha. Si se conservara la fecha original, un archivo antiguo podría eliminarse en la siguiente limpieza aunque acabara de reciclarse. Cada canal actualiza la fecha de modificación del elemento con la fecha actual al moverlo a la papelera: |
| Channel | Stamped by |
|---|---|
| SMB (LAN clients) | recycle:touch = yes in smb.conf |
| Web interface (Apache) | recycle_touch() in web/smbshared.php, applied recursively so a recycled folder carries its contents |
| Size-limit watchdog | touch after the move, in tools/smbwatch.sh |
A restored item therefore carries the date it was recycled, not its original one.
Por eso un elemento restaurado conserva la fecha en que fue reciclado, no la original.
|
When |
Cuando |
.recycle/smbguest/DOCUMENTS/
├── report.docx ← first deletion
└── Copy #1 of report.docx ← second deletion of the same file
To exclude specific file types from versioning, use recycle:noversions. These types are still recycled, but repeated deletions overwrite the previous copy in the bin rather than creating a numbered duplicate:
|
Para excluir tipos de archivo del versionado, usa recycle:noversions. Estos archivos siguen yendo a la papelera, pero eliminaciones repetidas sobreescriben la copia anterior en lugar de crear una nueva numerada:
|
# All files keep multiple versions:
recycle:versions = yes
# These types are recycled but NOT versioned — second delete overwrites the first:
recycle:noversions = *.dat,*.ini
Use noversions for files where accumulating copies adds no value: runtime data files, config dumps, ini snapshots, and similar.
|
Usa noversions para archivos donde acumular copias no aporta valor: archivos de datos en tiempo de ejecución, volcados de configuración, snapshots de ini y similares.
|
| Parameter | Value | Purpose | Propósito |
|---|---|---|---|
recycle:repository |
.recycle/%U |
SMB channel recycle bin, resolves to smbguest |
Papelera del canal SMB, resuelve a smbguest |
recycle:directory_mode |
0775 |
Group-writable recycle directory | Directorio escribible por el grupo |
recycle:keeptree |
yes |
Preserve original folder structure | Preservar estructura de carpetas |
recycle:versions |
yes |
Keep multiple versions of deleted files | Mantener múltiples versiones |
recycle:noversions |
*.dat,*.ini |
Exclude patterns from versioning | Excluir patrones del versionado |
recycle:touch |
yes |
Update access time when recycled | Actualizar tiempo de acceso al reciclar |
recycle:exclude |
*.tmp,*.temp,*.o,… |
Permanently delete matching files | Eliminar permanentemente archivos que coincidan |
recycle:exclude_dir |
/temp,/tmp,/cache,/.Trash-1000 |
Bypass recycle bin for directories | Omitir papelera para directorios |
recycle:maxsize |
1073741824 |
Max file size (1 GB) | Tamaño máximo (1 GB) |
hide files |
/.recycle/ |
Hide recycle directory from clients | Ocultar papelera a los clientes |
|
The installer registers a weekly cron job, run as |
El instalador registra una tarea cron semanal, ejecutada como |
@weekly root find "/home/$local_user/shared/.recycle/" -depth -mindepth 1 -mtime +6 -delete >/dev/null 2>&1The cleanup runs once a week and removes items older than six days, so an item remains in the bin for 7 to almost 14 days, depending on when it was moved there.
Como la limpieza se ejecuta una vez por semana y elimina elementos con más de seis días, estos permanecen en la papelera entre 7 y casi 14 días, según cuándo se hayan movido allí.
| To adjust the retention period, edit the project cron file. To inspect its entries, display the file: | Para ajustar el período de retención, edita el archivo de tareas del proyecto. Para consultar sus entradas, muestra el archivo: |
# Edit project cron entries
sudo nano /etc/cron.d/smbstack
# Inspect project cron entries
sudo cat /etc/cron.d/smbstack|
SMBstack uses the Samba |
SMBstack utiliza el módulo |
| Parameter | Value | Description | Descripción |
|---|---|---|---|
full_audit:logfile |
/var/log/samba/log.audit |
Destination log file, written via the rsyslog rule in /etc/rsyslog.d/fullaudit.conf. |
Archivo de log de destino, escrito mediante la regla rsyslog en /etc/rsyslog.d/fullaudit.conf. |
full_audit:prefix |
%I|%m|%S |
Fields prepended to each log entry: %I = client IP address, %m = client machine name, %S = share name. |
Campos que se anteponen a cada entrada del log: %I = IP del cliente, %m = nombre del equipo cliente, %S = nombre del share. |
full_audit:success |
mkdirat renameat unlinkat pwrite |
VFS operations logged when they succeed. See table below. | Operaciones VFS que se registran cuando tienen éxito. Ver tabla a continuación. |
full_audit:failure |
none |
No failed operations are logged. | No se registran operaciones fallidas. |
full_audit:facility |
LOCAL5 |
rsyslog facility used to route audit entries to the dedicated log file, keeping them separate from general system logs. | Facility de rsyslog usada para enrutar las entradas de auditoría al archivo dedicado, manteniéndolas separadas de los logs generales del sistema. |
full_audit:priority |
notice |
Syslog priority level assigned to audit entries. | Nivel de prioridad syslog asignado a las entradas de auditoría. |
| Samba syscall | Triggered by | Desencadenado por |
|---|---|---|
mkdirat |
Creating a directory via SMB or the web interface | Creación de un directorio vía SMB o la interfaz web |
renameat |
Renaming or moving a file or folder. Also triggered by Windows clients when saving a file (temp file + rename pattern). | Renombrado o movimiento de archivo o carpeta. También lo disparan los clientes Windows al guardar un archivo (patrón de archivo temporal + renombrado). |
unlinkat |
File deletion — permanent or moved to the recycle bin. See caveat below. | Borrado de archivo — permanente o movido a la papelera. Ver matiz abajo. |
pwrite |
Data written to an open file, via SMB or via the web interface. See caveat below. | Datos escritos en un archivo abierto, vía SMB o vía la interfaz web. Ver matiz abajo. |
|
|
|
Every file or directory open generates an entry, including browsing, reads and downloads, not only writes. A single Explorer window open on a busy folder can produce dozens of near-identical lines per second. This volume of records can hide the events actually worth reviewing, and adds no further traceability, since This is a project configuration decision, not a Samba limitation. To audit opens and reads as well, add it manually in
Then run |
Se evaluó y se decidió excluir Cada apertura de archivo o carpeta genera una entrada, incluida la navegación, las lecturas y las descargas, no solo las escrituras. Una sola ventana del Explorador abierta sobre una carpeta con actividad puede producir decenas de líneas casi idénticas por segundo. Este volumen de registros puede ocultar los eventos que sí conviene revisar y no aporta trazabilidad adicional, ya que Esta es una decisión de configuración del proyecto, no una limitación de Samba. Para auditar también las aperturas y lecturas, agréguelo manualmente en
Luego, ejecute |
|
It also checks that The installer adds |
También comprueba que El instalador registra automáticamente |
# sudo cat /etc/cron.d/smbstack
*/5 * * * * root /etc/smbstack/tools/smbload.sh
smbload.shreads no configuration of its own. It only checks whether the watcher is running and callssmbwatch.sh startif it is not. Untilsmbwatch.sh installhas been run from a terminal, that call aborts on its own key check, sosmbload.shlogs a-- alertwarning pointing atsmbwatch.log, where the missing or invalid key is named.
smbload.shno lee configuración propia. Solo comprueba si el vigilante corre y llama asmbwatch.sh startsi no. Hasta que se haya ejecutadosmbwatch.sh installdesde un terminal, esa llamada aborta en su propia verificación de claves, así quesmbload.shregistra un aviso-- alertque apunta asmbwatch.log, donde se nombra la clave que falta o es inválida.
|
If a folder exceeds its configured size limit, a newly completed or moved-in file is moved to
The folder list is built once, when the watcher starts. First-level folders can only be created by the administrator from the server shell, since SMB clients and the web panel are blocked at the share root. After creating one, run |
Si una carpeta supera el límite configurado, mueve a
La lista de carpetas se construye una sola vez, al arrancar el vigilante. Las carpetas de primer nivel solo las crea el administrador desde la consola del servidor, porque los clientes SMB y el panel web no pueden escribir en la raíz del recurso. Después de crear una, ejecuta |
smbstack.env variable |
Default | Purpose | Propósito |
|---|---|---|---|
WATCH_LIMIT_GB |
10 |
Size limit per monitored folder, in GB | Límite de tamaño por carpeta monitoreada, en GB |
WATCH_EXCLUDE |
NONE |
Comma-separated folder names excluded from monitoring (e.g. FINANCE,LEGAL) |
Nombres de carpetas separados por comas excluidas del monitoreo |
The watcher checks a file when writing finishes or when the file arrives by a move or rename. This prevents a file moved from an excluded folder from bypassing the limit. Renaming a file inside a folder that is already over the limit also sends it to the recycle bin. Moving an entire folder is not monitored.
smbwatch revisa los archivos cuando termina su escritura o cuando llegan por movimiento o renombrado; por eso, mover un archivo desde una carpeta excluida no evita el límite. Si renombras un archivo dentro de una carpeta que ya superó el límite, también se moverá a la papelera. El monitor no detecta el traslado de una carpeta completa.
# Install (interactive: asks for the two keys, writes them, adds the @reboot
# cron entry and starts the watcher). Run this once, from a terminal.
sudo /etc/smbstack/tools/smbwatch.sh install
# Start
sudo /etc/smbstack/tools/smbwatch.sh start
# Stop
sudo /etc/smbstack/tools/smbwatch.sh stop
# Status
sudo /etc/smbstack/tools/smbwatch.sh status
# Uninstall (stops it, removes the cron entry and both keys)
sudo /etc/smbstack/tools/smbwatch.sh uninstall|
|
|
ERROR: WATCH_LIMIT_GB missing line
ERROR: WATCH_EXCLUDE missing line
ERROR: 2 key(s) invalid in smbstack.env
ERROR: run 'smbwatch.sh install' first -- abort
|
The list of monitored folders is built once, when After adding a folder, restart |
La lista de carpetas monitoreadas se genera una sola vez al iniciar Después de agregar una carpeta, reinicia |
startregisters the@rebootentry in/etc/cron.d/smbstack, andstopremoves it. A watcher stopped on purpose stays stopped across a reboot.
startregistra la entrada@rebooten/etc/cron.d/smbstack, ystopla elimina. Un vigilante detenido a propósito sigue detenido tras un reinicio.
|
It does not back up the shared folder's data, the logs or the ACLs of the shared folder itself. It only keeps the configuration needed to reproduce the stack. |
No respalda los datos de la carpeta compartida, los registros ni las ACL de la propia carpeta compartida. Solo conserva la configuración necesaria para reproducir el stack. |
| Command | Description | Descripción |
|---|---|---|
sudo bash smbbk.sh |
Create a backup now | Crear una copia ahora |
sudo bash smbbk.sh install |
Register the @monthly cron entry |
Registrar la entrada mensual en cron |
sudo bash smbbk.sh uninstall |
Remove the cron entry, keeping the archives | Quitar la entrada de cron, conservando los comprimidos |
Backs up SMBstack into
/etc/bak/smbstack/smbbk_<YYYYMMDD_HHMMSS>.zip, keeping up to 3 archives. Paths that do not exist are skipped. Restore by unzipping it over/.Respalda SMBstack en
/etc/bak/smbstack/smbbk_<YYYYMMDD_HHMMSS>.zip, conservando hasta 3 comprimidos. Las rutas que no existan se omiten. Para restaurar, descomprímalo sobre/.
|
This project uses two kinds of backup, with different purposes and rules. Project backup It is a copy of SMBstack's configuration intended for the administrator. It is stored in Only Routine-operation backup It is the copy a script takes of one specific file right before modifying it, to allow the change to be undone. It is stored next to the original file with the Some examples are |
Este proyecto utiliza dos tipos de respaldo, con propósitos y reglas diferentes. Respaldo de proyecto Es una copia de la configuración de SMBstack destinada al administrador. Se almacena en Solo Respaldo de operación rutinaria Es una copia que un script realiza de un archivo concreto justo antes de modificarlo, para permitir deshacer el cambio. Se almacena junto al archivo original con el sufijo Algunos ejemplos son |
|
NetBIOS is a legacy protocol with security limitations, among them unauthenticated name resolution and exposure to spoofing and name poisoning attacks, such as NBT-NS poisoning. For this reason, NetBIOS remains disabled by default through Environments that need compatibility with legacy Windows clients must enable NetBIOS manually after the installation. |
NetBIOS es un protocolo legado que presenta limitaciones de seguridad, entre ellas la resolución de nombres sin autenticación y la exposición a ataques de suplantación y envenenamiento de nombres, como NBT-NS poisoning. Por este motivo, NetBIOS permanece deshabilitado de forma predeterminada mediante Los entornos que necesiten compatibilidad con clientes Windows antiguos deben habilitar NetBIOS manualmente después de la instalación. |
# Enable NetBIOS in smb.conf
sudo sed -i 's/^\s*disable netbios\s*=.*/ disable netbios = no/' /etc/samba/smb.conf
sudo sed -i "s/^;\s*netbios name\s*=.*/ netbios name = YOUR_HOSTNAME/" /etc/samba/smb.conf
# Start nmbd
sudo systemctl enable --now nmbd.service
sudo systemctl restart smbd
# Open the required ports (adjust IFACE to your Samba interface)
sudo iptables -A INPUT -i IFACE -p udp -m multiport --dports 137,138 -j ACCEPT
sudo iptables -A FORWARD -i IFACE -p udp -m multiport --dports 137,138 -j ACCEPT
sudo iptables -A INPUT -i IFACE -p tcp --dport 139 -j ACCEPT
sudo iptables -A FORWARD -i IFACE -p tcp --dport 139 -j ACCEPT
# Optional: rotate nmbd's log
sudo tee -a /etc/logrotate.d/samba > /dev/null <<'EOF'
/var/log/samba/log.nmbd {
weekly
missingok
rotate 7
postrotate
systemctl reload nmbd 2>/dev/null || true
endscript
compress
notifempty
}
EOF| 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. |
CSRF protection.
web/smbshared.phphas no login by design. Guest access for the whole LAN, and for the tunnel when it is enabled, is intentional.What it does have is a per-session token on the four forms that change state: upload, new folder, new file and recycle. A POST is accepted only if the page was actually loaded first.
This blocks a malicious site from silently auto-submitting a form to your server through a visitor's browser. It does not restrict who can use the browser itself: that is still governed by network reachability, LAN or tunnel.
Protección CSRF.
web/smbshared.phpno tiene login por diseño. El acceso de invitado para toda la LAN, y para el túnel cuando está activo, es intencional.Lo que sí tiene es un token por sesión en los cuatro formularios que modifican estado: subir, nueva carpeta, nuevo archivo y papelera. Un POST se acepta solo si la página se cargó antes.
Esto impide que un sitio malicioso envíe en silencio un formulario a su servidor a través del navegador de un visitante. No restringe quién puede usar el navegador: eso lo sigue gobernando el alcance de red, LAN o túnel.
Folder size display. The total size shown for the folder being browsed in
web/smbshared.phpis cached for 30 seconds per path, to avoid re-walking a potentially large subtree on every page load.The number can therefore lag up to 30 seconds behind the real content. That is purely cosmetic: quota enforcement is handled independently by
smbwatch.shand its own size checks, not by this displayed value.Tamaño de carpeta mostrado. El tamaño total que se muestra para la carpeta que se está navegando en
web/smbshared.phpse cachea 30 segundos por ruta, para evitar recorrer un subárbol potencialmente grande en cada carga de página.Por eso el número puede quedar hasta 30 segundos desactualizado respecto al contenido real. Es puramente cosmético: el cumplimiento de la cuota lo maneja de forma independiente
smbwatch.shcon sus propios chequeos de tamaño, no este valor mostrado.
Optional tunnel:
This repository
|
Este repositorio
|
| 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 | |
| RAG, Workers, Specialized Modules, Docs |
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.






