LUKS – disks encrypt

#!/bin/bash

# Variables
DISKS=("/dev/sdb" "/dev/sdc") # List of disks to encrypt
KEYFILE="/etc/luks/keyfile"   # Keyfile path
MOUNT_POINTS=("/mnt/disk1" "/mnt/disk2") # Corresponding mount points

# Check for root privileges
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root. Exiting."
    exit 1
fi

# Create the keyfile if it doesn't exist
if [ ! -f "$KEYFILE" ]; then
    echo "Creating LUKS keyfile..."
    mkdir -p "$(dirname "$KEYFILE")"
    dd if=/dev/urandom of="$KEYFILE" bs=4096 count=1
    chmod 600 "$KEYFILE"
fi

# Function to encrypt and set up a disk
encrypt_disk() {
    local DISK=$1
    local MAPPER_NAME=$2
    local MOUNT_POINT=$3

    echo "Processing $DISK..."
    
    # Check if the disk is already encrypted
    if cryptsetup isLuks "$DISK"; then
        echo "$DISK is already encrypted. Skipping."
        return
    fi

    # Format the disk with LUKS encryption
    echo "Encrypting $DISK..."
    cryptsetup luksFormat "$DISK" "$KEYFILE"
    if [ $? -ne 0 ]; then
        echo "Failed to encrypt $DISK. Exiting."
        exit 1
    fi

    # Open the encrypted disk
    echo "Opening $DISK..."
    cryptsetup luksOpen "$DISK" "$MAPPER_NAME" --key-file "$KEYFILE"

    # Create a filesystem on the encrypted disk
    echo "Creating filesystem on /dev/mapper/$MAPPER_NAME..."
    mkfs.ext4 "/dev/mapper/$MAPPER_NAME"

    # Create the mount point if it doesn't exist
    mkdir -p "$MOUNT_POINT"

    # Add entry to /etc/fstab for automatic mounting
    echo "Adding $DISK to /etc/fstab..."
    UUID=$(blkid -s UUID -o value "/dev/mapper/$MAPPER_NAME")
    echo "UUID=$UUID $MOUNT_POINT ext4 defaults 0 2" >> /etc/fstab

    # Mount the disk
    echo "Mounting $MOUNT_POINT..."
    mount "$MOUNT_POINT"
}

# Loop through disks and encrypt each one
for i in "${!DISKS[@]}"; do
    DISK="${DISKS[$i]}"
    MAPPER_NAME="luks_disk_$i"
    MOUNT_POINT="${MOUNT_POINTS[$i]}"

    encrypt_disk "$DISK" "$MAPPER_NAME" "$MOUNT_POINT"
done

echo "All disks have been encrypted and mounted."

Leave a comment