diff --git a/cvmassistants/disktool/__init__.py b/cvmassistants/disktool/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/cvmassistants/disktool/encryptedDisk.py b/cvmassistants/disktool/encryptedDisk.py deleted file mode 100644 index 92b5aab..0000000 --- a/cvmassistants/disktool/encryptedDisk.py +++ /dev/null @@ -1,89 +0,0 @@ -import os -import subprocess -import sys - -path = os.getenv('path') -if path is None: - print('error: mount directory is null') - sys.exit(1) - -disk = os.getenv('disk') -if disk is None: - print('error: disk dev name is null') - sys.exit(1) -diskpath = '/dev/' + disk -part_disk= diskpath + '1' -keyType = os.getenv('keyType') -if keyType == "none" : - if not os.path.exists(path): - os.makedirs(path) - else: - cmd = 'umount ' + path - ret = subprocess.run(cmd, shell=True) - - # this is a new disk, need to encrypt first - if not os.path.exists(part_disk): - ret = subprocess.run('fdisk ' + diskpath, input="n\np\n1\n\n\nw\n".encode(), shell=True) - ret = subprocess.run('mkfs.ext4 ' + part_disk, shell=True) - - ret = subprocess.run('mount ' + part_disk + ' ' + path, shell=True) - if ret.returncode: - print('fail to mount') - sys.exit(2) - else: - print(os.listdir(path)) -else: - key = os.getenv('wrapkey') - if key is None: - print('error: wrapkey is null') - sys.exit(1) - print("mount directory is " + path) - - mappername = disk + '1' - if not os.path.exists(path): - os.makedirs(path) - - try: - # CONFIG_VIRTIO_BLK=y, CONFIG_VIRTIO_NET=y, CONFIG_DM_CRYPT=y - open_info = subprocess.check_output("cryptsetup " + "luksOpen " + part_disk + " testname", shell=True, stderr=subprocess.STDOUT, universal_newlines=True,input=key) - print("open luks disk successful") - ret = subprocess.run('cryptsetup close ' + "testname", shell=True) - except subprocess.CalledProcessError as e : - print(e.output) - open_info=e.output - if "already mapped or mounted" in open_info: - print("already correct mounted") - sys.exit(0) - ##todo - elif "not a valid LUKS device" in open_info: - print("not a LUKS device") - ret = subprocess.run('cryptsetup luksFormat ' + part_disk, input=key.encode(), shell=True) - ret = subprocess.run('cryptsetup open ' + part_disk + ' ' + mappername, input=key.encode(), shell=True) - ret = subprocess.run('mkfs.ext4 /dev/mapper/' + mappername, shell=True) - ret = subprocess.run('cryptsetup close ' + mappername, shell=True) - elif "doesn't exist or access denied" in open_info: - print("not a exist device") - print('encrypt a new disk of ' + diskpath) - ret = subprocess.run('fdisk ' + diskpath, input="n\np\n1\n\n\nw\n".encode(), shell=True) - ret = subprocess.run('cryptsetup luksFormat ' + part_disk, input=key.encode(), shell=True) - ret = subprocess.run('cryptsetup open ' + part_disk + ' ' + mappername, input=key.encode(), shell=True) - ret = subprocess.run('mkfs.ext4 /dev/mapper/' + mappername, shell=True) - ret = subprocess.run('cryptsetup close ' + mappername, shell=True) - elif "No key available" in open_info: - print("password error") - sys.exit(2) - else: - print("could not know the status") - sys.exit(3) - ret = subprocess.run('cryptsetup open ' + part_disk + ' ' + mappername, input=key.encode(), shell=True) - if ret.returncode: - print('fail to cryptsetup open') - sys.exit(1) - mnt_cmd = 'mount /dev/mapper/' + mappername + ' ' + path - ret = subprocess.run(mnt_cmd, shell=True) - if ret.returncode: - print('fail to mount') - sys.exit(2) - else: - print(os.listdir(path)) -print("mount dir succussful") \ No newline at end of file diff --git a/cvmassistants/disktool/encryptedDisk.sh b/cvmassistants/disktool/encryptedDisk.sh new file mode 100755 index 0000000..a18d965 --- /dev/null +++ b/cvmassistants/disktool/encryptedDisk.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +############################################################################### +# Script: encryptedDisk.sh +# Description: Configure encrypted or unencrypted disk partitions on Ubuntu systems (e.g., TDX environment) +# +# This script partitions, formats, and mounts disk devices. Supports both +# encrypted (LUKS) and unencrypted disks. Environment variables control behavior: +# `mount_path` (mount point), `disk` (device name), `keyType` (only wrapkey supported), +# and `wrapkey` (encryption key). +# +# Requirements: +# - Must be run as root +# - cryptsetup must be installed (for encrypted disks) +# - fdisk must be installed +# - mkfs.ext4 must be available +# +############################################################################### + +log_info() { + echo -e "[INFO] $*" +} + +log_fatal() { + echo -e "[ERROR] $*" >&2 + exit 1 +} + +# Create a new partition on a disk +# Arguments: disk_device +detect_or_create_partition() { + local disk_dev="$1" + local suffix + + # Try both possible partition naming schemes (e.g., /dev/sda1 or /dev/nvme0n1p1) + part_disk="" + for suffix in "1" "p1"; do + if [[ -e "${disk_dev}${suffix}" ]]; then + part_disk="${disk_dev}${suffix}" + mappername="${mappername}${suffix}" + log_info "Partition $part_disk already exists for device $disk_dev" + return 0 + fi + done + + log_info "Creating partition on $disk_dev with the following passed fdisk parameters: + n = new partition + p = primary partition + 1 = partition number 1 + = default start and end sectors + w = write changes" + # Create the partition using fdisk + # fdisk may return non-zero due to partition table re-read warning, but partition is created + echo -e "n\np\n1\n\n\nw\n" | fdisk "$disk_dev" >/dev/null 2>&1 || true + + # Force kernel to re-read the partition table + if command -v partprobe >/dev/null 2>&1; then + partprobe "$disk_dev" >/dev/null 2>&1 || log_fatal "partprobe failed on $disk_dev" + elif command -v partx >/dev/null 2>&1; then + partx -u "$disk_dev" >/dev/null 2>&1 || log_fatal "partx failed on $disk_dev" + fi + + # Wait a moment for partition to appear + sleep 1 + + # Try both possible partition naming schemes + for suffix in "1" "p1"; do + part_disk="${disk_dev}${suffix}" + if [[ -e "$part_disk" ]]; then + mappername="${mappername}${suffix}" + log_info "Partition $part_disk successfully created on $disk_dev" + return 0 + fi + done + + log_fatal "Failed to create partition on $disk_dev — no partition device detected after fdisk" +} + +# Format and encrypt a partition +# Arguments: key partition_device mapper_name +format_and_encrypt_partition() { + local key="$1" + local part_dev="$2" + local mapper="$3" + + echo "$key" | cryptsetup luksFormat --key-file=- "$part_dev" + [[ $? -ne 0 ]] && log_fatal "Failed to format partition $part_dev in luks format" + log_info "Partition $part_dev formatted successfully in luks format" + + echo "$key" | cryptsetup open --key-file=- "$part_dev" "$mapper" + [[ $? -ne 0 ]] && log_fatal "Failed to open partition $part_dev in luks format" + log_info "Partition $part_dev opened successfully in luks format" + + mkfs.ext4 "/dev/mapper/$mapper" + [[ $? -ne 0 ]] && log_fatal "Failed to format partition /dev/mapper/$mapper in ext4 format" + log_info "Partition /dev/mapper/$mapper successfully formatted in ext4 format" + + cryptsetup close "$mapper" + [[ $? -ne 0 ]] && log_fatal "Failed to close partition /dev/mapper/$mapper" + log_info "Partition /dev/mapper/$mapper closed successfully" +} + +# Mount a device to a mount point +# Arguments: device_path mount_point +mount_device() { + local device="$1" + local mount_point="$2" + + mount "$device" "$mount_point" + [[ $? -ne 0 ]] && log_fatal "Failed to mount $device to $mount_point" + log_info "Mounted $device to $mount_point" +} + +log_info "Starting encrypted disk configuration..." + +# Check required environment variables +[[ -z "$mount_path" ]] && log_fatal "Mount directory is null" +[[ -z "$disk" ]] && log_fatal "Disk dev name is null" +# Handle only encrypted disk case +[ "$keyType" != "wrapkey" ] && log_fatal "keyType $keyType is not supported" + +log_info "Handling encrypted disk case" +[[ -z "$wrapkey" ]] && log_fatal "wrapkey is null" + +if [ ! -d "$mount_path" ]; then + log_info "Mount directory $mount_path does not exist" + mkdir -p "$mount_path" && log_info "Created mount directory $mount_path" +else + umount "$mount_path" 2>/dev/null && log_info "Unmounted $mount_path" +fi + +diskpath="/dev/$disk" # /dev/vda +part_disk="" + +mappername="${disk}" +detect_or_create_partition "$diskpath" # assign part_disk and mappername +device_to_mount="/dev/mapper/$mappername" +[ -e "$device_to_mount" ] && log_fatal "Mapper $device_to_mount already exists" + +# Format and encrypt the partition (and check if it opens correctly) +format_and_encrypt_partition "$wrapkey" "$part_disk" "$mappername" + +# Open the encrypted device in its mapper +echo "$wrapkey" | cryptsetup open --key-file=- "$part_disk" "$mappername" +[[ $? -ne 0 ]] && log_fatal "cryptsetup open --key-file=- "$part_disk" "$mappername": failed" +log_info "cryptsetup open --key-file=- "$part_disk" "$mappername": success" + +# Mount the device +mount_device "$device_to_mount" "$mount_path" && log_info "Mounted $device_to_mount to $mount_path" + +log_info "Encrypted disk configuration completed." diff --git a/cvmassistants/disktool/readme.md b/cvmassistants/disktool/readme.md new file mode 100644 index 0000000..0157e77 --- /dev/null +++ b/cvmassistants/disktool/readme.md @@ -0,0 +1,8 @@ +**Warning:** ⚠️ +This script will **forcefully format the specified partition**. +All existing data on the partition will be **permanently lost**. + +Specifically: + +- The disk is defined via the `disk` environment variable (e.g., `vda`). +- The partition affected is the **first partition** of that disk \ No newline at end of file