Home Linux & Systems Cybersecurity Cloud & DevOps Networks & Infrastructure SIEM & Monitoring DFIR & Threat Intel Development & Other All categories Projects About Tools

Guide to protect your Pendrive in Linux: LUKS + VeraCrypt + Automation

Leer en espanol
Guide to protect your Pendrive in Linux: LUKS + VeraCrypt + Automation

Table of contents

This guide will teach you how to: Encrypt all p ===

USB devices are extremely practical, but they are also very easy to lose. If your data is not encrypted, anyone could access it.

This guide will teach you how to:

  • Encrypt the entire pendrive with LUKS (AES-256).
  • Create a folder encrypted with VeraCrypt inside the pendrive for a double layer of security.
  • Use an automated mount/unmount script.
  • Configure cron to automatically unmount if the pendrive remains mounted.

Completely encrypt the pendrive with LUKS

Advertencia: Esto borrará todos los datos del pendrive. Haz una copia de seguridad.

Identify the USB device

Connect the pendrive and execute:

CODE
lsblk
sdd      8:48   1 28.9G  0 disk
└─sdd1   8:49   1 28.9G  0 part

Erase any previous traces

BASH
sudo wipefs --all /dev/sdd
sudo dd if=/dev/zero of=/dev/sdd bs=1M status=progress

Encrypt partition with LUKS

BASH
sudo cryptsetup luksFormat /dev/sdd1
Confirma con YES y usa una contraseña fuerte.

(Optional) Back up the LUKS header

    BASH
    sudo cryptsetup luksHeaderBackup /dev/sdd1 --header-backup-file /media/usuario/DATOS/backup_pendrive

    Open LUKS volume

    BASH
    sudo cryptsetup luksOpen /dev/sdd1 pendrive
    
    Esto creará /dev/mapper/pendrive.

    Create file system

    BASH
    sudo mkfs.ext4 /dev/mapper/pendrive
    

    Mount the LUKS volume

    BASH
    sudo mkdir -p /media/pendrive
    sudo mount /dev/mapper/pendrive /media/pendrive
    

    Create a folder encrypted with VeraCrypt

    Download and install VeraCrypt

    Since VeraCrypt is not usually in major repositories, manual download is required. Make sure you install the version of console (-console) if you just need the script.

    BASH
    wget https://launchpad.net/veracrypt/trunk/1.26.24/+download/veracrypt-console-1.26.24-Debian-13-amd64.deb
    sudo apt install ./veracrypt-console-*.deb

    Create an encrypted container

    Navigate to the mounted LUKS volume and create the container file. A different password than LUKS is recommended.

    SQL
    cd /mnt/pendrive
    veracrypt --text --create seguro.vc \
        --size 2G \
        --encryption AES \
        --hash SHA-512 \
        --volume-type normal \
        --filesystem ext4 \
        --pim 0 \
        --random-source /dev/urandom
    

    Explanation:

    • seguro.vc → container name.
    • AES encryption → AES-256 encryption
    • SHA-512 hash →hash to derive the key
    • filesystem ext4 → internal file system
    • pim 0 → no additional delay

    Assemble the container

    BASH
    sudo mkdir -p /mnt/secure
    veracrypt --text --mount /mnt/pendrive/seguro.vc /mnt/secure --protect-hidden=no
    

    –protect-hidden=does not avoid the hidden volume question.
    /mnt/secure will be the encrypted folder.

    Dismantle container and LUKS

    BASH
    veracrypt -d /mnt/secure
    sudo umount /mnt/pendrive
    sudo cryptsetup luksClose pendrive
    

    Automatic mount/unmount script

    We have improved the script to handle disassembly failures (umount -l) and clean up any remaining VeraCrypt mappings, which resolved the “device busy” issues.

    Create the script in /usr/local/bin/pendrive_secure.sh:

    BASH
    #!/bin/bash
    # ===============================================================
    # Script: pendrive_secure.sh
    # Monta o desmonta un pendrive cifrado LUKS + contenedor VeraCrypt
    # ===============================================================
    
    # CONFIGURACIÓN
    DEVICE="/dev/sdd1"              # Cambia según tu USB
    MAPPER_NAME="pendrive"
    MOUNT_POINT="/media/pendrive"
    SECURE_POINT="/media/secure"
    VC_FILE="$MOUNT_POINT/seguro.vc"
    
    # COMPROBACIÓN DE ROOT
    if [ "$EUID" -ne 0 ]; then
        echo "Debe ejecutarse como root o sudo."
        exit 1
    fi
    
    # FUNCIÓN DE MONTAJE
    montar() {
        # Abrir LUKS si no está abierto
        if [ ! -e "/dev/mapper/$MAPPER_NAME" ]; then
            echo "Abriendo volumen LUKS..."
            if ! cryptsetup luksOpen "$DEVICE" "$MAPPER_NAME"; then
                echo "Error al abrir LUKS"
                exit 1
            fi
        else
            echo "LUKS ya abierto, saltando..."
        fi
    
        # Crear directorio de montaje
        mkdir -p "$MOUNT_POINT"
    
        # Verificar filesystem, crear si no existe
        FS_TYPE=$(blkid -o value -s TYPE "/dev/mapper/$MAPPER_NAME")
        if [ -z "$FS_TYPE" ]; then
            echo "Creando filesystem ext4 en LUKS..."
            mkfs.ext4 "/dev/mapper/$MAPPER_NAME"
        fi
    
        # Montar LUKS
        echo "Montando LUKS en $MOUNT_POINT..."
        if ! mount "/dev/mapper/$MAPPER_NAME" "$MOUNT_POINT"; then
            echo "Error al montar LUKS"
            cryptsetup luksClose "$MAPPER_NAME"
            exit 1
        fi
    
        # Montar VeraCrypt si existe
        if [ -f "$VC_FILE" ]; then
            mkdir -p "$SECURE_POINT"
            echo "Montando contenedor VeraCrypt..."
            if ! veracrypt --text --mount "$VC_FILE" "$SECURE_POINT" --protect-hidden=no; then
                echo "Error al montar VeraCrypt"
                umount "$MOUNT_POINT"
                cryptsetup luksClose "$MAPPER_NAME"
                exit 1
            fi
            echo "LUKS y VeraCrypt montados correctamente"
        else
            echo "No se encontró $VC_FILE. Solo LUKS montado."
        fi
    }
    
    # FUNCIÓN DE DESMONTAJE
    desmontar() {
        echo "Desmontando..."
    
        if mountpoint -q "$SECURE_POINT"; then
            veracrypt -d "$SECURE_POINT"
        fi
    
        if mountpoint -q "$MOUNT_POINT"; then
            umount "$MOUNT_POINT"
        fi
    
        if [ -e "/dev/mapper/$MAPPER_NAME" ]; then
            cryptsetup luksClose "$MAPPER_NAME"
        fi
    
        echo "Pendrive desmontado y cerrado"
    }
    
    # DETECCIÓN AUTOMÁTICA
    if mountpoint -q "$SECURE_POINT" || mountpoint -q "$MOUNT_POINT"; then
        desmontar
    else
        montar
    fi
    

    Give permissions:

    BASH
    sudo chmod +x /usr/local/bin/pendrive_secure.sh
    

    Automate teardown with cron

    Add a task to cron so that he script run periodically, automatically disassembling if it detects that the drive is mounted.

    CODE
    */30 * * * * /usr/local/bin/pendrive_secure.sh >> /var/log/pendrive_secure.log 2>&1
    
    Explicación:
    */30 * * * *: Ejecuta el script cada 30 minutos.
    >> /var/log/pendrive_secure.log 2>&1: Redirige tanto la salida estándar como los errores a un archivo de registro para su revisión.

    :wq!

    Comments