Ir al contenido

Technical Manual: Backup Implementation (Full, Incremental, and Encrypted)

Step-by-step guide to configuring incremental, full, and encrypted backups with OpenSSL on Linux systems.

0views

Author: Full-Stack Innovator Pro (Technical Review)
Objective: Understand and execute the three types of backups following best practices (Ubuntu Guide) and implement an automated script with rotation.

  • Source: /home/user.portelcore
  • Destination: /var/backups/user_portelcore_backup
  • Control File (Snapshot): /var/backups/user_portelcore_backup/snapshot.snar
  • Encryption: AES-256-CBC (OpenSSL)

Before starting, we will prepare the folders and security keys.

Ventana de terminal
# 1. Crear directorios
sudo mkdir -p /var/backups/user_portelcore_backup
sudo mkdir -p /var/log/user_portelcore_backup
sudo mkdir -p /etc/backup_credentials
# 2. Generar clave de cifrado (Imprescindible para la copia cifrada)
openssl rand -base64 32 | sudo tee /etc/backup_credentials/backup.key
# 3. Proteger la clave
sudo chmod 400 /etc/backup_credentials/backup.key
sudo chmod 700 /var/backups/user_portelcore_backup

PART 2: The 3 Types of Backup (Manual Execution)

Sección titulada «PARTE 2: Los 3 Tipos de Copia (Ejecución Manual)»

Following the methodology, we will first perform each type manually to verify that it works correctly.

The logic is: “If the file snapshot.snar does not exist, TAR understands that it must perform a full backup and create the file again”.

Command:

Ventana de terminal
# Borramos el archivo de control si existe para forzar la copia completa
sudo rm -f /var/backups/user_portelcore_backup/snapshot.snar
# Ejecutamos la copia (creará el archivo snapshot.snar nuevo)
sudo tar --listed-incremental=/var/backups/user_portelcore_backup/snapshot.snar \
-czvf /var/backups/user_portelcore_backup/FULL_manual.tar.gz /home/user.portelcore

The logic is: “If the file snapshot.snar ALREADY exists, TAR only copies what has changed since last time”.

Test:

  1. We will create a new file: touch /home/user.portelcore/archivo_nuevo.txt
  2. We will run the command (it is identical to the previous one, but since the file .snar already exists, it acts differently):

Command:

Ventana de terminal
sudo tar --listed-incremental=/var/backups/user_portelcore_backup/snapshot.snar \
-czvf /var/backups/user_portelcore_backup/INC_manual.tar.gz /home/user.portelcore

Result: The file INC_manual.tar.gz will take up very little space.

The logic is: “Pipe the output of the TAR command through OpenSSL before saving it to disk”.

Command:

Ventana de terminal
sudo tar --listed-incremental=/var/backups/user_portelcore_backup/snapshot.snar \
-czf - /home/user.portelcore | \
openssl enc -aes-256-cbc -salt -pbkdf2 -pass file:/etc/backup_credentials/backup.key \
-out /var/backups/user_portelcore_backup/XIFRADA_manual.tar.gz.enc

This version includes: Locking, Rotation, Encryption, Cleanup, Root Verification, and Checksums. Remote copying has been removed.

Ventana de terminal
sudo nano /usr/local/bin/auto_backup_master.sh
#!/bin/bash
# ====================================================================
# 1. VALIDACIONES PREVIAS (ROOT + LOCKING)
# ====================================================================
# Validación de privilegios de Root
if [ "$(id -u)" -ne 0 ]; then
echo "Este script se debe ejecutar como root" >&2
exit 1
fi
# Validación de Locking (Evita que se ejecuten dos copias a la vez)
LOCK_FILE="/var/run/backup_user_portelcore.lock"
exec 200>$LOCK_FILE
flock -n 200 || { echo "El backup ya se está ejecutando. Saliendo." >> /var/log/user_portelcore_backup/backup.log; exit 1; }
# ====================================================================
# 2. CONFIGURACIÓN
# ====================================================================
USER_BACKUP="user.portelcore"
ORIGEN="/home/$USER_BACKUP"
DESTINO="/var/backups/user_portelcore_backup"
SNAPSHOT="/var/backups/user_portelcore_backup/snapshot.snar"
LOG="/var/log/user_portelcore_backup/backup.log"
CLAVE="/etc/backup_credentials/backup.key"
DIAS_RETENCION=30
# Fecha y Día (1=Lunes ... 7=Domingo)
FECHA=$(date +%Y-%m-%d_%H%M)
DIA=$(date +%u)
# ====================================================================
# 3. LÓGICA DE ROTACIÓN (IMPLEMENTACIÓN GUÍA UBUNTURISTA)
# ====================================================================
if [ "$DIA" -eq 7 ]; then
echo "[$FECHA] DOMINGO: Rotación de copias." >> $LOG
echo "[$FECHA] Borrando $SNAPSHOT para forzar COPIA COMPLETA..." >> $LOG
# Borrar el control fuerza a TAR a realizar un Nivel 0 (Full)
if [ -f "$SNAPSHOT" ]; then
rm "$SNAPSHOT"
fi
PREFIX="FULL"
else
# Si el archivo snapshot existe, TAR hará automáticamente INCREMENTAL
if [ ! -f "$SNAPSHOT" ]; then
echo "[$FECHA] AVISO: No existe snapshot. Se forzará COMPLETA." >> $LOG
PREFIX="FULL"
else
echo "[$FECHA] DIA $DIA: Realizando Copia INCREMENTAL..." >> $LOG
PREFIX="INC"
fi
fi
ARCHIVO_FINAL="$DESTINO/${PREFIX}_${FECHA}.tar.gz.enc"
# ====================================================================
# 4. EJECUCIÓN: TAR (con Exclusiones) + OPENSSL
# ====================================================================
# Mejora: --exclude evita copiar la papelera y la caché de los navegadores
tar --exclude='.cache' --exclude='.local/share/Trash' --exclude='Downloads/*.iso' \
-czg "$SNAPSHOT" -f - "$ORIGEN" 2>> $LOG | \
openssl enc -aes-256-cbc -salt -pbkdf2 -pass file:"$CLAVE" -out "$ARCHIVO_FINAL" 2>> $LOG
# ====================================================================
# 5. VERIFICACIÓN DE ERRORES E INTEGRIDAD
# ====================================================================
ESTADOS=(${PIPESTATUS[@]})
if [ ${ESTADOS[0]} -eq 0 ] && [ ${ESTADOS[1]} -eq 0 ]; then
echo "[$FECHA] ÉXITO: $PREFIX creado y cifrado en $ARCHIVO_FINAL" >> $LOG
# Generar Checksum SHA256 para verificar la integridad en el futuro
sha256sum "$ARCHIVO_FINAL" > "$ARCHIVO_FINAL.sha256"
# ====================================================================
# 6. POLÍTICA DE RETENCIÓN (LIMPIEZA)
# ====================================================================
# Borrar archivos .enc y .sha256 de más de 30 días
echo "[$FECHA] Limpiando archivos antiguos (+$DIAS_RETENCION días)..." >> $LOG
find "$DESTINO" -name "*.enc" -mtime +$DIAS_RETENCION -delete
find "$DESTINO" -name "*.sha256" -mtime +$DIAS_RETENCION -delete
else
echo "[$FECHA] ERROR: Tar salida=${ESTADOS[0]}, SSL salida=${ESTADOS[1]}" >> $LOG
fi
echo "------------------------------------------------------" >> $LOG
Ventana de terminal
sudo chmod +x /usr/local/bin/auto_backup_master.sh

Finally, we will automate the daily execution.

Ventana de terminal
sudo crontab -e

We will add the line:

Ventana de terminal
# Ejecutar cada día a las 03:00 AM
0 3 * * * /usr/local/bin/auto_backup_master.sh

How to recover the encrypted and incremental data?

Scenario: We want to recover the system state as it was on Tuesday (the day we have an incremental copy).

Steps:

  1. Decrypt and Decompress the FULL (Sunday):

    Ventana de terminal
    openssl enc -d -aes-256-cbc -pbkdf2 -pass file:/etc/backup_credentials/backup.key \
    -in /var/backups/user_portelcore_backup/FULL_Domingo.tar.gz.enc | \
    tar -xzg /dev/null -C /tmp/recuperacion
  2. Decrypt and Decompress the INCREMENTAL (Monday):

    Ventana de terminal
    openssl enc -d -aes-256-cbc -pbkdf2 -pass file:/etc/backup_credentials/backup.key \
    -in /var/backups/user_portelcore_backup/INC_Lunes.tar.gz.enc | \
    tar -xzg /dev/null -C /tmp/recuperacion
  3. Decrypt and Decompress the INCREMENTAL (Tuesday):

    Ventana de terminal
    openssl enc -d -aes-256-cbc -pbkdf2 -pass file:/etc/backup_credentials/backup.key \
    -in /var/backups/user_portelcore_backup/INC_Martes.tar.gz.enc | \
    tar -xzg /dev/null -C /tmp/recuperacion

PART 6: Verification and Validation (Automated Test)

Sección titulada «PARTE 6: Verificación y Validación (Test Automático)»

To ensure that the data is valid without having to type the filename manually.

This command automatically searches for the last created file (ls -t | head -1) and displays its content. We will copy and paste the entire block:

Ventana de terminal
# Detecta el último archivo creado automáticamente
ULTIMO_ARCHIVO=$(ls -t /var/backups/user_portelcore_backup/*.enc | head -1)
echo "Verificando el archivo: $ULTIMO_ARCHIVO"
# Desencripta y lista el contenido
openssl enc -d -aes-256-cbc -pbkdf2 -pass file:/etc/backup_credentials/backup.key \
-in "$ULTIMO_ARCHIVO" | tar -tzv | head -n 20

Expected Result (Real Example):
If the process is correct, we will see a list of directories and files similar to this:

Ventana de terminal
drwxr-x--- user.portelcore/user.portelcore 134 2026-02-09 19:05 home/user.portelcore/
drwxrwxr-x user.portelcore/user.portelcore 8 2026-02-02 18:51 home/user.portelcore/.local/
drwx------ user.portelcore/user.portelcore 7 2026-02-02 18:51 home/user.portelcore/.local/share/
drwx------ user.portelcore/user.portelcore 18 2026-02-02 17:08 home/user.portelcore/.ssh/
...

If we see this, the encryption key is valid and the TAR format is correct.

To ensure the file has not been corrupted on the disk.

Ventana de terminal
cd /var/backups/user_portelcore_backup/
sha256sum -c $(ls -t *.sha256 | head -1)

Expected Result:

Ventana de terminal
/var/backups/user_portelcore_backup/INC_2026-02-09_1933.tar.gz.enc: OK

The “OK” message confirms the mathematical integrity of the file.


We have successfully implemented a professional backup architecture in Linux that meets:

  1. Efficiency: Use of incremental backups to save space.
  2. Security: Military-grade AES-256 encryption.
  3. Reliability: Automatic integrity verification with SHA256.
  4. Maintainability: Weekly rotation and automatic cleanup of old files.