diff --git a/.github/workflows/build-deb.yml b/.github/workflows/build-deb.yml index fb6e888..568b44d 100644 --- a/.github/workflows/build-deb.yml +++ b/.github/workflows/build-deb.yml @@ -156,6 +156,83 @@ jobs: echo "All verification checks passed!" + # Ubuntu e2e convert/boot coverage for the DEB packages: run + # tests/test-convert.sh against the prepared noble test image (dracut + # pre-installed) with the freshly built cryptpilot-fde-guest deb, in both + # bootloader modes. grub exercises the DEB install path and grubenv + # creation; uki additionally exercises the small-ESP growth. + test-convert: + runs-on: ubuntu-latest + needs: [build, test] + strategy: + fail-fast: false + matrix: + bootloader: [grub, uki] + defaults: + run: + shell: bash + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + submodules: 'true' + + - name: Load NBD kernel module + run: | + sudo modprobe nbd max_part=16 + lsmod | grep nbd + + # Minimal tool set for the test harness itself (wget, qemu-nbd, + # cryptsetup, lvm, mkfs.ext4, sgdisk) plus dosfstools for the UKI ESP + # re-creation. cryptpilot-convert installs anything else it needs. + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y \ + wget \ + qemu-utils \ + cryptsetup-bin \ + lvm2 \ + e2fsprogs \ + gdisk \ + parted \ + dosfstools + + - name: Pull Ubuntu test image + run: | + docker pull ghcr.io/${{ github.repository_owner }}/cryptpilot-fde-test-image:noble-dracut-20260518 + + - name: Extract qcow2 from container + run: | + TEST_IMAGE="ghcr.io/${{ github.repository_owner }}/cryptpilot-fde-test-image:noble-dracut-20260518" + docker create --name temp-extract "$TEST_IMAGE" /bin/true + docker cp temp-extract:/image.qcow2 ./test-image.qcow2 + docker rm temp-extract + docker rmi "$TEST_IMAGE" + ls -lh ./test-image.qcow2 + + - name: Download DEB packages + uses: actions/download-artifact@v8 + with: + name: deb-packages-x86_64 + path: ./deb-packages/ + + - name: Run conversion test + run: | + GUEST_DEB=$(ls ./deb-packages/cryptpilot-fde-guest_*.deb | head -1) + sudo ./tests/test-convert.sh \ + --distro ubuntu \ + --package "$GUEST_DEB" \ + --bootloader ${{ matrix.bootloader }} \ + --rootfs-enc \ + --delta-location ram \ + --input "${{ github.workspace }}/test-image.qcow2" + + - name: Print convert diagnostic log + if: always() + run: | + sudo cat /tmp/.cryptpilot-convert.log 2>/dev/null || echo "(log file not available)" + release: if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest diff --git a/.github/workflows/build-test-image.yml b/.github/workflows/build-test-image.yml index 6673018..8343043 100644 --- a/.github/workflows/build-test-image.yml +++ b/.github/workflows/build-test-image.yml @@ -3,12 +3,20 @@ name: Build Test Image on: workflow_dispatch: inputs: - url: - description: 'URL of the qcow2 image to download' + distro: + description: 'Distribution type: "direct" for a ready qcow2 image, "ubuntu" for a Noble cloud image that gets dracut pre-installed' required: true + type: choice + default: direct + options: + - direct + - ubuntu + url: + description: 'URL of the qcow2 image to download (only used when distro is "direct")' + required: false type: string tag: - description: 'Tag for the resulting image (e.g., alinux3-20251030)' + description: 'Tag for the resulting image (e.g., alinux3-20251030, noble-dracut-20260518)' required: true type: string @@ -38,13 +46,138 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + # --- Direct mode: download a ready qcow2 image from a URL --- - name: Download qcow2 image + if: inputs.distro == 'direct' run: | echo "Downloading image from: ${{ inputs.url }}" mkdir -p /tmp/qcow2-image wget -O /tmp/qcow2-image/test-image.qcow2 "${{ inputs.url }}" ls -lh /tmp/qcow2-image/test-image.qcow2 + # --- Ubuntu mode: prepare a Noble cloud image --- + - name: Install dependencies (ubuntu mode) + if: inputs.distro == 'ubuntu' + run: | + sudo apt-get update + sudo apt-get install -y \ + qemu-utils \ + parted \ + util-linux \ + kmod \ + dosfstools \ + e2fsprogs + + - name: Download Ubuntu Noble cloud image (ubuntu mode) + if: inputs.distro == 'ubuntu' + run: | + mkdir -p /tmp/qcow2-image + # Pinned daily build so the kernel/dracut versions in the test + # image stay stable across rebuilds. + wget -O /tmp/qcow2-image/test-image.qcow2 \ + https://cloud-images.ubuntu.com/noble/20260518/noble-server-cloudimg-amd64.img + ls -lh /tmp/qcow2-image/test-image.qcow2 + + # Prepare via qemu-nbd + chroot (no libguestfs): set a root password so + # the serial console is usable for debugging, grow the disk so the + # converted layout fits, and pre-install dracut plus the systemd UEFI + # stub needed for UKI builds. + - name: Prepare Ubuntu image (password, resize, GPT fix, install dracut) + if: inputs.distro == 'ubuntu' + run: | + IMAGE=/tmp/qcow2-image/test-image.qcow2 + MOUNT_POINT=/tmp/img-mnt + + # ---------- Step 1: Set root password ---------- + sudo modprobe nbd max_part=16 || true + sudo qemu-nbd --connect=/dev/nbd0 --format=qcow2 "$IMAGE" + sleep 2 + sudo partprobe /dev/nbd0 2>/dev/null || true + sleep 1 + + # Find root partition: look for ext4 partition + sudo mkdir -p $MOUNT_POINT + ROOT_PART="" + for p in /dev/nbd0p1 /dev/nbd0p2 /dev/nbd0p3 /dev/nbd0p4; do + if [ -e "$p" ]; then + FSTYPE=$(sudo blkid -s TYPE -o value "$p" 2>/dev/null || true) + if [ "$FSTYPE" = "ext4" ]; then + ROOT_PART="$p" + break + fi + fi + done + if [ -z "$ROOT_PART" ]; then + echo "ERROR: Cannot find ext4 root partition" + sudo blkid /dev/nbd0p* 2>/dev/null || true + sudo lsblk /dev/nbd0 2>/dev/null || true + exit 1 + fi + echo "Root partition: $ROOT_PART" + sudo mount "$ROOT_PART" $MOUNT_POINT + sudo chroot $MOUNT_POINT /bin/bash -c 'echo "root:cryptpilot" | chpasswd' + sudo umount $MOUNT_POINT + sudo qemu-nbd --disconnect /dev/nbd0 >/dev/null 2>&1 || true + sleep 1 + + # ---------- Step 2: Resize disk ---------- + qemu-img resize "$IMAGE" 10G + + # ---------- Step 3: Fix GPT partition table ---------- + sudo qemu-nbd --connect=/dev/nbd0 --format=qcow2 "$IMAGE" + sleep 2 + sudo partprobe /dev/nbd0 2>/dev/null || true + sleep 1 + sudo parted /dev/nbd0 print >/dev/null 2>&1 || true + sudo parted /dev/nbd0 resizepart 1 100% -s 2>/dev/null || true + sudo partprobe /dev/nbd0 2>/dev/null || true + sudo lsblk /dev/nbd0 + sudo qemu-nbd --disconnect /dev/nbd0 >/dev/null 2>&1 || true + sleep 1 + + # ---------- Step 4: Install dracut and systemd-boot ---------- + sudo modprobe nbd max_part=16 || true + sudo qemu-nbd --connect=/dev/nbd0 --format=qcow2 "$IMAGE" + sleep 2 + sudo partprobe /dev/nbd0 2>/dev/null || true + sleep 1 + + ROOT_PART="" + for p in /dev/nbd0p1 /dev/nbd0p2 /dev/nbd0p3 /dev/nbd0p4; do + if [ -e "$p" ]; then + FSTYPE=$(sudo blkid -s TYPE -o value "$p" 2>/dev/null || true) + if [ "$FSTYPE" = "ext4" ]; then + ROOT_PART="$p" + break + fi + fi + done + if [ -z "$ROOT_PART" ]; then + echo "ERROR: Cannot find ext4 root partition after resize" + exit 1 + fi + echo "Root partition (after resize): $ROOT_PART" + sudo mkdir -p $MOUNT_POINT + sudo mount "$ROOT_PART" $MOUNT_POINT + + sudo mount --bind /dev $MOUNT_POINT/dev + sudo mount --bind /proc $MOUNT_POINT/proc + sudo mount --bind /sys $MOUNT_POINT/sys + sudo mount --bind /run $MOUNT_POINT/run 2>/dev/null || true + + sudo chroot $MOUNT_POINT /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y dracut dracut-core systemd-boot-efi' + + sudo umount $MOUNT_POINT/run 2>/dev/null || true + sudo umount $MOUNT_POINT/sys 2>/dev/null || true + sudo umount $MOUNT_POINT/proc 2>/dev/null || true + sudo umount $MOUNT_POINT/dev 2>/dev/null || true + sudo umount $MOUNT_POINT + sudo qemu-nbd --disconnect /dev/nbd0 >/dev/null 2>&1 || true + sleep 1 + + echo "Ubuntu image preparation complete!" + + # --- Common: build container image --- - name: Copy Dockerfile run: | cp tests/test-image.Dockerfile /tmp/qcow2-image/Dockerfile @@ -58,7 +191,8 @@ jobs: labels: | org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} org.opencontainers.image.description=Test image with qcow2 for cryptpilot-convert integration tests - qcow2.source.url=${{ inputs.url }} + qcow2.source.distro=${{ inputs.distro }} + qcow2.source.url=${{ inputs.url || '' }} - name: Output image reference run: | diff --git a/README.md b/README.md index 50f94be..42c68e6 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,7 @@ mount /dev/mapper/data0 /mnt/data0 - [Anolis OS 23](https://openanolis.cn/anolisos/23) - [Alibaba Cloud Linux 3](https://www.aliyun.com/product/alinux) - [Alibaba Cloud Linux 4](https://www.aliyun.com/product/alinux) +- [Ubuntu 24.04 LTS (Noble)](https://releases.ubuntu.com/noble/) ## Documentation diff --git a/README_zh.md b/README_zh.md index e307b07..e588560 100644 --- a/README_zh.md +++ b/README_zh.md @@ -125,6 +125,7 @@ mount /dev/mapper/data0 /mnt/data0 - [Anolis OS 23](https://openanolis.cn/anolisos/23) - [Alibaba Cloud Linux 3](https://www.aliyun.com/product/alinux) - [Alibaba Cloud Linux 4](https://www.aliyun.com/product/alinux) +- [Ubuntu 24.04 LTS (Noble)](https://releases.ubuntu.com/noble/) ## 文档 diff --git a/cryptpilot-convert.sh b/cryptpilot-convert.sh index c74fc55..71adfa9 100755 --- a/cryptpilot-convert.sh +++ b/cryptpilot-convert.sh @@ -20,6 +20,13 @@ BOOT_PART_SIZE="512M" # Partition alignment in sectors (aligned to 1 MiB boundary) readonly PARTITION_SECTOR_ALIGNMENT=2048 +# UKI mode needs an ESP big enough for the UKI itself plus the scratch files +# firmware writes while booting it. Some cloud images ship a much smaller ESP +# (Ubuntu noble: ~106M), so in UKI mode an output ESP below the minimum is +# grown to the target size; see disk::grow_uki_efi_partition. +readonly UKI_EFI_MIN_SIZE_BYTES=$((250 * 1024 * 1024)) +readonly UKI_EFI_TARGET_SIZE_BYTES=$((512 * 1024 * 1024)) + # Set up logging: redirect stdout/stderr to both terminal and log file, # and enable shell tracing into the same log. log::setup_log_file() { @@ -530,8 +537,8 @@ install_zram_module_if_needed() { kernel_version=$(chroot "${rootfs_mount_point}" bash -c "ls /boot/vmlinuz-* 2>/dev/null | sed 's#.*/vmlinuz-##' | grep -v rescue | sort -V | tail -n1") if [ -z "$kernel_version" ]; then - log::error "Could not determine kernel version, zram module installation failed" - return 1 + log::warn "Could not determine standard Ubuntu kernel version, skipping zram installation" + return 0 fi log::info "Detected kernel version: $kernel_version" @@ -566,7 +573,7 @@ install_zram_module_if_needed() { done if [ "$installed" = false ]; then - log::error "Could not install zram modules, possibly due to disk space constraints or missing package" + log::warn "Could not install zram modules, possibly due to disk space constraints or missing package" return 1 fi fi @@ -693,10 +700,7 @@ disk::install_deb_on_rootfs() { # Install user-provided packages if [ ${#user_packages[@]} -gt 0 ]; then - chroot "${rootfs_mount_point}" bash -c "dpkg --configure -a || true" - chroot "${rootfs_mount_point}" bash -c "dpkg -i $(printf '%s ' "${user_packages[@]}"| sed 's/ $//')" || true - - # Fix dependencies + # First ensure apt indexes are available chroot "${rootfs_mount_point}" /usr/bin/env ${http_proxy:+http_proxy=$http_proxy} \ ${https_proxy:+https_proxy=$https_proxy} \ ${ftp_proxy:+ftp_proxy=$ftp_proxy} \ @@ -705,7 +709,20 @@ disk::install_deb_on_rootfs() { ${no_proxy:+no_proxy=$no_proxy} \ apt-get update || true - # Fix dependencies + # Pre-install common deb dependencies (dracut, dracut-network are required by cryptpilot-fde-guest) + chroot "${rootfs_mount_point}" /usr/bin/env ${http_proxy:+http_proxy=$http_proxy} \ + ${https_proxy:+https_proxy=$https_proxy} \ + ${ftp_proxy:+ftp_proxy=$ftp_proxy} \ + ${rsync_proxy:+rsync_proxy=$rsync_proxy} \ + ${all_proxy:+all_proxy=$all_proxy} \ + ${no_proxy:+no_proxy=$no_proxy} \ + apt-get install -y dracut dracut-network lvm2 cryptsetup-bin || true + + # Now install the deb packages + chroot "${rootfs_mount_point}" bash -c "dpkg --configure -a || true" + chroot "${rootfs_mount_point}" bash -c "dpkg -i $(printf '%s ' "${user_packages[@]}"| sed 's/ $//')" || true + + # Fix any remaining dependency issues chroot "${rootfs_mount_point}" /usr/bin/env ${http_proxy:+http_proxy=$http_proxy} \ ${https_proxy:+https_proxy=$https_proxy} \ ${ftp_proxy:+ftp_proxy=$ftp_proxy} \ @@ -718,12 +735,15 @@ disk::install_deb_on_rootfs() { # Step 2: Build essential packages list local cryptpilot_fde_version="" - # Try to query the version of cryptpilot-fde-host from the current system + # Try to query the version of cryptpilot-fde-host from the current system. + # The 2>/dev/null must stay INSIDE the $(...) with the || fallback outside: + # rpm writes its "package ... is not installed" message to stdout, so an + # "|| true" inside the substitution would capture that text as the version + # on hosts that have rpm but no cryptpilot-fde-host installed. if command -v rpm >/dev/null 2>&1; then - cryptpilot_fde_version=$(rpm -q cryptpilot-fde-host --qf '%{VERSION}-%{RELEASE}' 2>/dev/null || true) + cryptpilot_fde_version=$(rpm -q cryptpilot-fde-host --qf '%{VERSION}-%{RELEASE}' 2>/dev/null) || cryptpilot_fde_version="" elif command -v dpkg-query >/dev/null 2>&1; then - # Extract version from dpkg-query output, removing epoch if present - cryptpilot_fde_version=$(dpkg-query -W -f='${Version}' cryptpilot-fde-host 2>/dev/null || true) + cryptpilot_fde_version=$(dpkg-query -W -f='${Version}' cryptpilot-fde-host 2>/dev/null) || cryptpilot_fde_version="" fi local essential_packages_with_version=() @@ -758,19 +778,26 @@ disk::install_deb_on_rootfs() { fi done - # Install missing essential packages - if [ ${#packages_to_install[@]} -gt 0 ]; then + # Install missing essential packages. cryptpilot-fde-guest is skipped when + # it was already installed via dpkg -i above: the version string detected + # on an RPM-based host does not match any apt candidate, so apt-get would + # fail on it. + local non_cryptpilot=() + for pkg in "${packages_to_install[@]}"; do + case "$pkg" in cryptpilot-fde-guest*) ;; *) non_cryptpilot+=("$pkg") ;; esac + done + if [ ${#non_cryptpilot[@]} -gt 0 ]; then chroot "${rootfs_mount_point}" /usr/bin/env ${http_proxy:+http_proxy=$http_proxy} \ ${https_proxy:+https_proxy=$https_proxy} \ ${ftp_proxy:+ftp_proxy=$ftp_proxy} \ ${rsync_proxy:+rsync_proxy=$rsync_proxy} \ ${all_proxy:+all_proxy=$all_proxy} \ ${no_proxy:+no_proxy=$no_proxy} \ - apt-get -y install "${packages_to_install[@]}" + apt-get -y install "${non_cryptpilot[@]}" fi - # Step 4: Install zram kernel module for Ubuntu - install_zram_module_if_needed "${rootfs_mount_point}" + # Step 4: Install zram kernel module for Ubuntu (best-effort only) + install_zram_module_if_needed "${rootfs_mount_point}" || log::warn "zram module installation skipped; may not be available for this kernel" # Step 5: Lock version for all essential packages (using base package name) chroot "${rootfs_mount_point}" apt-mark hold "${essential_package_names[@]}" @@ -1077,6 +1104,21 @@ if [ "${uki:-false}" = false ]; then grub_add_args "GRUB_CMDLINE_LINUX_DEFAULT" fi + # Disable os-prober: it scans all block devices and fails with + # "Device or resource busy" when this script runs inside a container with + # NBD devices attached, and the failure makes grub2-mkconfig emit a + # grub.cfg without any menuentry. + if [ -f /etc/default/grub ]; then + if grep -q "^GRUB_DISABLE_OS_PROBER=" /etc/default/grub; then + sed -i 's/^GRUB_DISABLE_OS_PROBER=.*/GRUB_DISABLE_OS_PROBER=true/' /etc/default/grub + else + echo "GRUB_DISABLE_OS_PROBER=true" >> /etc/default/grub + fi + fi + if [ -d /etc/default/grub.d ]; then + echo "GRUB_DISABLE_OS_PROBER=true" > /etc/default/grub.d/99-disable-os-prober.cfg + fi + echo "Updating grub2.cfg" grub2_cfg="" if [ -e /etc/grub2.cfg ] ; then @@ -1170,6 +1212,68 @@ if [ "${uki:-false}" = false ]; then fi done + # Ensure grubenv exists with saved_entry set. + # RHEL-based images ship with a grubenv, but Ubuntu cloud images may not + # have one. cryptpilot-fde-host show-reference-value requires saved_entry + # to be present. + echo "Ensuring grubenv with saved_entry exists..." + grubenv_path="" + if [ -f /boot/grub2/grubenv ]; then + grubenv_path=/boot/grub2/grubenv + elif [ -f /boot/grub/grubenv ]; then + grubenv_path=/boot/grub/grubenv + fi + if [ -z "$grubenv_path" ]; then + # Create a fresh grubenv file (1024-byte GRUB environment block) + echo "Creating grubenv file..." + mkdir -p /boot/grub + grubenv_path=/boot/grub/grubenv + # grub-editenv create generates a valid 1024-byte grubenv file + if command -v grub-editenv >/dev/null 2>&1; then + grub-editenv "$grubenv_path" create + elif command -v grub2-editenv >/dev/null 2>&1; then + grub2-editenv "$grubenv_path" create + else + # Fallback: GRUB env header followed by zero padding to 1024 bytes + { printf '# GRUB Environment Version 1.0\n'; dd if=/dev/zero bs=1 count=992 2>/dev/null; } > "$grubenv_path" + fi + fi + + # Determine the kernel entry to set as saved_entry. + # The value should match the menuentry title/id in grub.cfg. + # Ubuntu menuentries carry the version (e.g. "Ubuntu, with Linux + # 6.8.0-35-generic"), so strip the vmlinuz- prefix from the newest + # non-rescue kernel file. + kernel_entry="" + if [ -n "$(ls /boot/vmlinuz-* 2>/dev/null | grep -v rescue)" ]; then + kernel_file=$(ls /boot/vmlinuz-* 2>/dev/null | grep -v rescue | sort -V | tail -1) + kernel_entry=$(basename "$kernel_file" | sed 's/^vmlinuz-//') + else + kernel_file=$(ls /boot/vmlinuz* 2>/dev/null | sort -V | tail -1) + kernel_entry=$(basename "$kernel_file" | sed 's/^vmlinuz-//') + fi + + if [ -n "$kernel_entry" ] && [ -f "$grubenv_path" ]; then + echo "Setting saved_entry to $kernel_entry" + if command -v grub-editenv >/dev/null 2>&1; then + grub-editenv "$grubenv_path" set saved_entry="$kernel_entry" + elif command -v grub2-editenv >/dev/null 2>&1; then + grub2-editenv "$grubenv_path" set saved_entry="$kernel_entry" + else + # Fallback: replace the text before the padding block + sed -i '/^saved_entry=/d' "$grubenv_path" + sed -i "1a saved_entry=$kernel_entry" "$grubenv_path" + fi + fi + + # Also ensure GRUB_DEFAULT=saved so GRUB actually uses saved_entry + if [ -f /etc/default/grub ]; then + sed -i 's/^GRUB_DEFAULT=.*/GRUB_DEFAULT=saved/' /etc/default/grub + fi + for f in /etc/default/grub.d/*.cfg; do + [ -f "$f" ] && sed -i 's/^GRUB_DEFAULT=.*/GRUB_DEFAULT=saved/' "$f" + done + echo "Cleaning up package manager cache..." if command -v yum >/dev/null 2>&1; then yum clean all @@ -1873,6 +1977,158 @@ step::shrink_rootfs() { # data source for the later steps. } +# In UKI mode, grow the output ESP when the source image ships one too small +# for a UKI (below UKI_EFI_MIN_SIZE_BYTES). The partition is enlarged to +# UKI_EFI_TARGET_SIZE_BYTES at its current start; every partition that starts +# after it is shifted behind the enlarged ESP, keeping its type, uuid and +# size, with starts re-aligned to PARTITION_SECTOR_ALIGNMENT like +# disk::align_start_sector. The last partition may shrink when the shifted +# layout would run past the end of the disk. Partition UUIDs must survive +# because the guest's grub.cfg references them as PART_UUIDs. +# +# The current layout is parsed from "sfdisk --dump --json" and the new one is +# emitted as a fresh sfdisk script, both via python3 (no jq; python3 is +# already required for the UKI section layout work). Sets +# uki_efi_resized=true when the table was rewritten so step::copy_partitions +# knows the output ESP must be re-created instead of dd'd. +disk::grow_uki_efi_partition() { + local device=$1 + local sector_size=$2 + local efi_part_num=$3 + + uki_efi_resized=false + + local json_file="${workdir}/partition_table.json" + sfdisk --dump --json "${device}" >"${json_file}" 2>/dev/null || + proc::fatal "failed to dump the partition table of ${device}" + + local script_file="${workdir}/uki_efi_partition_table.sfdisk" + # The || fallback must stay on the heredoc line: on its own line it is + # swallowed into the heredoc body and the failure is silently ignored. + local layout_rc=0 + python3 - "${json_file}" "${sector_size}" "${efi_part_num}" \ + "${UKI_EFI_MIN_SIZE_BYTES}" "${UKI_EFI_TARGET_SIZE_BYTES}" \ + "${PARTITION_SECTOR_ALIGNMENT}" >"${script_file}" <<'PYEOF' || layout_rc=1 +import json +import re +import sys + +json_path, sector_size, efi_part_num = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) +min_bytes, target_bytes, alignment = ( + int(sys.argv[4]), + int(sys.argv[5]), + int(sys.argv[6]), +) + +with open(json_path) as f: + table = json.load(f)["partitiontable"] +parts = table.get("partitions") or [] + + +def part_num(p): + m = re.search(r"(\d+)$", p.get("node", "")) + return int(m.group(1)) if m else None + + +def fail(msg): + sys.stderr.write("ERROR: %s\n" % msg) + sys.exit(1) + + +efi = next((p for p in parts if part_num(p) == efi_part_num), None) +if efi is None: + fail("partition p%d not found in the table" % efi_part_num) + +efi_start = int(efi["start"]) +if int(efi["size"]) * sector_size >= min_bytes: + # Large enough already: print nothing, the caller skips the rewrite. + sys.exit(0) + +# Partitions that start before the EFI partition stay untouched; the ones +# after it are shifted behind the enlarged ESP in their original start order. +before = [p for p in parts if int(p["start"]) < efi_start] +after = sorted((p for p in parts if int(p["start"]) > efi_start), key=lambda p: int(p["start"])) +if len(before) + len(after) + 1 != len(parts): + fail("a partition shares the EFI partition start; layout not supported") + + +def align_up(sector): + return (sector + alignment - 1) // alignment * alignment + + +target_size = target_bytes // sector_size +last_lba = int(table.get("lastlba") or 0) + +cursor = align_up(efi_start + target_size) +moved = {} +for p in after: + start = cursor + size = int(p["size"]) + if last_lba and start + size - 1 > last_lba: + # Only the final partition may shrink, and only to fit the disk. + size = last_lba - start + 1 + if size <= 0: + fail("partition %s does not fit after the enlarged ESP" % p.get("node")) + moved[id(p)] = (start, size) + cursor = align_up(start + size) + + +def entry_line(p, start, size): + line = "start=%d, size=%d, type=%s" % (start, size, p["type"]) + if "uuid" in p: + line += ", uuid=%s" % p["uuid"] + if "name" in p: + line += ', name="%s"' % p["name"] + # The "p :" prefix is what makes sfdisk keep the original + # partition numbers; without it entries are renumbered sequentially. + if "node" in p: + line = "%s : %s" % (p["node"], line) + return line + + +# Emit entries in the original order so partition numbers are unchanged. +out = ["label: %s" % table["label"]] +if "id" in table: + out.append("label-id: %s" % table["id"]) +out.append("unit: sectors") +if "firstlba" in table: + out.append("first-lba: %d" % int(table["firstlba"])) +if last_lba: + out.append("last-lba: %d" % last_lba) +out.append("") +for p in parts: + if p is efi: + out.append(entry_line(p, efi_start, target_size)) + elif id(p) in moved: + start, size = moved[id(p)] + out.append(entry_line(p, start, size)) + else: + out.append(entry_line(p, int(p["start"]), int(p["size"]))) +print("\n".join(out)) +PYEOF + if [ "${layout_rc}" -ne 0 ]; then + proc::fatal "failed to compute the enlarged-ESP partition layout" + fi + if [ ! -s "${script_file}" ]; then + log::info "EFI partition is large enough; no resize needed" + return 0 + fi + + log::info "Growing EFI partition p${efi_part_num} to $((UKI_EFI_TARGET_SIZE_BYTES / 1024 / 1024))M and shifting later partitions" + cat "${script_file}" + if ! sfdisk "${device}" <"${script_file}"; then + log::error "Failed to write the enlarged-ESP partition table to ${device}" + return 1 + fi + partprobe "${device}" 2>/dev/null || true + udevadm settle --timeout=10 + + local new_efi_size + new_efi_size=$(blockdev --getsize64 "${device}p${efi_part_num}") + log::info "New EFI partition size: $((new_efi_size / 1024 / 1024))M" + uki_efi_resized=true +} + # Fork the source into two snapshots sharing source-mod as qcow2 backing file: # source-read freezes the shrunk source data for the later copy and verity # reads, source-write takes the later writes. Then mirror the source partition @@ -1990,6 +2246,14 @@ step::prepare_output_and_snapshots() { udevadm settle --timeout=10 fi + # UKI mode: enlarge the output ESP when the source image ships one too + # small for the UKI. Must run after the partition table copy above; it + # rewrites the output table only (source snapshots are untouched). + if [ "$uki" = true ]; then + disk::grow_uki_efi_partition "${output_device}" "${sector_size}" "${efi_part_num}" || + proc::fatal "failed to grow the EFI partition for UKI mode" + fi + log::info "source-read device: ${source_read_device}" log::info "source-write device: ${source_write_device}" log::info "output device: ${output_device}" @@ -1999,9 +2263,40 @@ step::prepare_output_and_snapshots() { step::copy_partitions() { - # dd EFI partition (preserve UUID, labels, all metadata) - log::info "Copying EFI partition" - dd if="${source_read_device}p${efi_part_num}" of="${output_device}p${efi_part_num}" bs=4M status=progress + if [ "${uki_efi_resized:-false}" = "true" ]; then + # The output ESP was enlarged: dd'ing the source partition would + # restore the small vfat superblock and leave dracut hitting ENOSPC + # inside a partition that looks full-size. Create a fresh filesystem + # spanning the whole partition and copy the source content instead. + # The vfat label matters (Ubuntu's fstab mounts the ESP by + # LABEL=UEFI); the FAT serial does not (nothing references it). + log::info "Creating vfat filesystem on enlarged EFI partition and copying source content" + local efi_label + efi_label=$(blkid -o value -s LABEL "${source_read_device}p${efi_part_num}") + + local mkfs_vfat_args=(-I) + if [ -n "${efi_label}" ]; then + mkfs_vfat_args+=(-n "${efi_label}") + fi + mkfs.vfat "${mkfs_vfat_args[@]}" "${output_device}p${efi_part_num}" + + local efi_src_mount="${workdir}/efi_src" + local efi_dst_mount="${workdir}/efi_dst" + mkdir -p "${efi_src_mount}" "${efi_dst_mount}" + proc::hook_exit "mountpoint -q ${efi_src_mount} && disk::umount_wait_busy ${efi_src_mount}" + proc::hook_exit "mountpoint -q ${efi_dst_mount} && disk::umount_wait_busy ${efi_dst_mount}" + + mount -o ro "${source_read_device}p${efi_part_num}" "${efi_src_mount}" + mount "${output_device}p${efi_part_num}" "${efi_dst_mount}" + # vfat cannot store unix ownership, so -a alone fails on every file. + cp -a --no-preserve=ownership "${efi_src_mount}/." "${efi_dst_mount}/" + disk::umount_wait_busy "${efi_dst_mount}" + disk::umount_wait_busy "${efi_src_mount}" + else + # dd EFI partition (preserve UUID, labels, all metadata) + log::info "Copying EFI partition" + dd if="${source_read_device}p${efi_part_num}" of="${output_device}p${efi_part_num}" bs=4M status=progress + fi # Populate the output boot partition. # Cases: @@ -2163,6 +2458,7 @@ main() { local source_read_device local source_write_device local uki=false + local uki_efi_resized=false local uki_append_cmdline="console=tty0 console=ttyS0,115200n8" local uki_stub_version="distro" @@ -2298,7 +2594,9 @@ main() { if command -v apt-get >/dev/null 2>&1; then local tool_packages=(qemu-utils cryptsetup lvm2 parted grub2-common e2fsprogs lsof fdisk gdisk gawk udev) if [[ "$uki" == "true" ]]; then - tool_packages+=(grub2-tools) # Required for UKI (Unified Kernel Image) boot setup + # grub2-tools for the UKI boot setup; dosfstools (mkfs.vfat) to + # re-create an enlarged ESP (see disk::grow_uki_efi_partition). + tool_packages+=(grub2-tools dosfstools) fi # A pinned stub from the Arch Linux Archive is a .pkg.tar.zst, so the # Arch path needs curl (download), zstd + tar (extract), sha256sum (log). @@ -2310,7 +2608,9 @@ main() { else local tool_packages=(qemu-img cryptsetup veritysetup lvm2 parted e2fsprogs lsof gdisk systemd-udev) # systemd-udev provides udevadm if [[ "$uki" == "true" ]]; then - tool_packages+=(grub2-tools) # Required for UKI (Unified Kernel Image) boot setup + # grub2-tools for the UKI boot setup; dosfstools (mkfs.vfat) to + # re-create an enlarged ESP (see disk::grow_uki_efi_partition). + tool_packages+=(grub2-tools dosfstools) fi if [[ "$uki" == "true" && "$uki_stub_version" != "distro" ]]; then tool_packages+=(curl zstd tar) diff --git a/cryptpilot-enhance.sh b/cryptpilot-enhance.sh index 135e689..3447d3f 100755 --- a/cryptpilot-enhance.sh +++ b/cryptpilot-enhance.sh @@ -177,6 +177,7 @@ add_run_cmd() { # ============================= # 1. Uninstall Cloud Assistant Agent (Aliyun Assist) # ============================= +# shellcheck disable=SC2016 add_run_cmd ' # Stop Cloud Assistant daemon /usr/local/share/assist-daemon/assist_daemon --stop @@ -187,8 +188,16 @@ systemctl stop aliyun.service # Remove Cloud Assistant daemon /usr/local/share/assist-daemon/assist_daemon --delete -# Uninstall package -rpm -qa | grep aliyun_assist | xargs rpm -e +# Uninstall package (RPM or DEB) +if command -v rpm >/dev/null 2>&1; then + rpm -qa | grep aliyun_assist | xargs rpm -e +elif command -v dpkg >/dev/null 2>&1; then + # ${binary:Package} is the supported field name; the ${dpkg-Package} + # spelling expands to nothing on noble, which would silently purge + # nothing. The '\'' splices a real single quote into this string so the + # guest shell passes the field to dpkg-query instead of expanding it. + dpkg-query -W -f='\''${binary:Package}\n'\'' | grep aliyun | xargs -r dpkg --purge 2>/dev/null || true +fi # Clean up leftover files and service configurations rm -rf /usr/local/share/aliyun-assist @@ -222,7 +231,11 @@ systemctl mask rpcbind.socket # 4. Remove cloud-init # ============================= add_run_cmd ' -yum remove -y cloud-init +if command -v yum >/dev/null 2>&1; then + yum remove -y cloud-init +elif command -v apt-get >/dev/null 2>&1; then + DEBIAN_FRONTEND=noninteractive apt-get remove -y cloud-init +fi ' # ============================= @@ -230,20 +243,32 @@ yum remove -y cloud-init # ============================= if [[ "$MODE" == "full" ]]; then add_run_cmd ' - yum remove -y openssh-server + if command -v yum >/dev/null 2>&1; then + yum remove -y openssh-server + elif command -v apt-get >/dev/null 2>&1; then + DEBIAN_FRONTEND=noninteractive apt-get remove -y openssh-server + fi ' elif [[ "$MODE" == "partial" ]]; then + # shellcheck disable=SC2016 add_run_cmd ' - # Disable password login, allow public key only - sed -i "s/^#*PasswordAuthentication.*/PasswordAuthentication no/" /etc/ssh/sshd_config - sed -i "s/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/" /etc/ssh/sshd_config - - # Prevent root password login, but allow key-based login - sed -i "s/^#*PermitRootLogin.*/PermitRootLogin prohibit-password/" /etc/ssh/sshd_config - - # Disable high-risk features - sed -i "s/^#*X11Forwarding.*/X11Forwarding no/" /etc/ssh/sshd_config - sed -i "s/^#*AllowTcpForwarding.*/AllowTcpForwarding no/" /etc/ssh/sshd_config + sshd_conf=/etc/ssh/sshd_config + # Ubuntu puts distro defaults in /etc/ssh/sshd_config.d/ drop-ins, which + # are read after the main file, so they must be fixed too or they override + # the hardened values. + for f in /etc/ssh/sshd_config.d/*.conf; do + [ -f "$f" ] || continue + sed -i "s/^#*PasswordAuthentication.*/PasswordAuthentication no/" "$f" + sed -i "s/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/" "$f" + sed -i "s/^#*PermitRootLogin.*/PermitRootLogin prohibit-password/" "$f" + sed -i "s/^#*X11Forwarding.*/X11Forwarding no/" "$f" + sed -i "s/^#*AllowTcpForwarding.*/AllowTcpForwarding no/" "$f" + done + sed -i "s/^#*PasswordAuthentication.*/PasswordAuthentication no/" "$sshd_conf" + sed -i "s/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/" "$sshd_conf" + sed -i "s/^#*PermitRootLogin.*/PermitRootLogin prohibit-password/" "$sshd_conf" + sed -i "s/^#*X11Forwarding.*/X11Forwarding no/" "$sshd_conf" + sed -i "s/^#*AllowTcpForwarding.*/AllowTcpForwarding no/" "$sshd_conf" ' fi @@ -252,7 +277,7 @@ fi # ============================= # shellcheck disable=SC2016 add_run_cmd ' -#!/bin/bash +#!/bin/sh # 1. Lock root and admin account passwords: echo "1. Locking root and admin account passwords..." @@ -261,34 +286,30 @@ sed -i "s/\(^admin:\)[^:]*/\1!!/" /etc/shadow echo "1. Root and admin account passwords locked!" echo "2. Processing other user accounts (excluding root and admin)..." -# Define list of excluded usernames -exclude_users=("root" "admin") - while IFS=: read -r username _ _ _ _ homedir user_shell; do # Check if shell is one of the interactive shells case $user_shell in - "/bin/bash"|"/bin/sh"|"/bin/zsh" \ - |"/usr/bin/bash"|"/usr/bin/sh"|"/usr/bin/zsh" \ - |"/usr/local/bin/bash"|"/usr/local/bin/sh"|"/usr/local/bin/zsh") - - # Skip if username is in exclude list - if [[ " ${exclude_users[@]} " =~ " $username " ]]; then - continue - fi - + /bin/bash|/bin/sh|/bin/zsh \ + |/usr/bin/bash|/usr/bin/sh|/usr/bin/zsh \ + |/usr/local/bin/bash|/usr/local/bin/sh|/usr/local/bin/zsh) + + # Skip if username is root or admin + case "$username" in + root|admin) continue ;; + esac + # Read password field from shadow - pass=$(grep "^$username:" /etc/shadow | cut -d: -f2) - + pass=$(grep "^${username}:" /etc/shadow | cut -d: -f2) + # If already locked (!, !!, *, etc.), skip deletion - if [[ "$pass" == "!" || "$pass" == "!!" || "$pass" == *\!* || "$pass" == "*" ]]; then - echo "Account $username is already locked or disabled, skipping." - continue - fi - + case "$pass" in + "!"*|"*"|"") echo "Account $username is already locked or disabled, skipping." ; continue ;; + esac + # Delete eligible user account and home directory echo "Removing account: $username" userdel -r "$username" 2>/dev/null || true - if [[ -d "$homedir" ]]; then + if [ -d "$homedir" ]; then rm -rf "$homedir" 2>/dev/null || true fi ;; @@ -305,10 +326,10 @@ echo "3. Removing directories ending with .DEL in home folders..." # Scan /etc/passwd again and clean *.DEL directories in valid home paths while IFS=: read -r username _ _ _ _ homedir user_shell; do case $user_shell in - "/bin/bash"|"/bin/sh"|"/bin/zsh" \ - |"/usr/bin/bash"|"/usr/bin/sh"|"/usr/bin/zsh" \ - |"/usr/local/bin/bash"|"/usr/local/bin/sh"|"/usr/local/bin/zsh") - if [[ -d "$homedir" ]]; then + /bin/bash|/bin/sh|/bin/zsh \ + |/usr/bin/bash|/usr/bin/sh|/usr/bin/zsh \ + |/usr/local/bin/bash|/usr/local/bin/sh|/usr/local/bin/zsh) + if [ -d "$homedir" ]; then find "$homedir" -maxdepth 1 -type d -name "*.DEL" -exec rm -rf {} \; fi ;; @@ -321,7 +342,10 @@ echo "3. Cleanup of *.DEL directories completed!" # 7. Clear Bash History # ============================= add_run_cmd ' -history -c && history -w +# Remove all bash history files; history -c would only affect the current +# virt-customize shell session, not the files on disk. +rm -f /root/.bash_history /home/*/.bash_history 2>/dev/null || true +: > /var/log/history 2>/dev/null || true ' # ============================= diff --git a/tests/test-convert.sh b/tests/test-convert.sh index c858329..5f5de7c 100755 --- a/tests/test-convert.sh +++ b/tests/test-convert.sh @@ -14,7 +14,7 @@ # host MemTotal. # # Usage: -# ./tests/test-convert.sh --rpm --bootloader --rootfs-enc|--rootfs-noenc --delta-location +# ./tests/test-convert.sh (--rpm|--deb|--package) --bootloader --rootfs-enc|--rootfs-noenc --delta-location # ./tests/test-convert.sh --help # Show usage # @@ -32,16 +32,26 @@ readonly YELLOW='\033[1;33m' readonly CYAN='\033[0;36m' readonly NC='\033[0m' # No Color -# Test configuration -readonly TEST_IMAGE_URL="https://alinux3.oss-cn-hangzhou.aliyuncs.com/aliyun_3_x64_20G_nocloud_alibase_20251030.qcow2" -readonly TEST_IMAGE_CACHE="/tmp/test-input-alinux3.qcow2" +# Test image URLs and cache paths per distro +readonly ALINUX3_IMAGE_URL="https://alinux3.oss-cn-hangzhou.aliyuncs.com/aliyun_3_x64_20G_nocloud_alibase_20251030.qcow2" +readonly ALINUX3_IMAGE_CACHE="/tmp/test-input-alinux3.qcow2" +readonly UBUNTU_IMAGE_URL="https://cloud-images.ubuntu.com/noble/20260518/noble-server-cloudimg-amd64.img" +readonly UBUNTU_IMAGE_CACHE="/tmp/test-input-ubuntu.qcow2" + readonly TEST_PASSPHRASE="test-passphrase-12345" # Source image path (can be overridden via --input) SOURCE_IMAGE="" -# Path to cryptpilot-fde-guest RPM package (required) -CRYPTPILOT_FDE_RPM="" +# Set when --input is used: a custom input image is treated as already +# prepared, so cryptpilot-enhance is skipped for it. +USE_CUSTOM_INPUT=false + +# Path to cryptpilot-fde-guest package (.rpm or .deb) +CRYPTPILOT_FDE_PACKAGE="" + +# Distro: "alinux3" (default) or "ubuntu" +DISTRO="alinux3" # Delta key provider for the test config: "otp" (default, recreates the delta # every boot — preserves the original CI behavior) or "stable" (exec provider @@ -117,7 +127,7 @@ check_tools() { # gracefully when the binary is absent or unusable (e.g. on Alinux 4, # where supermin cannot detect the distro's package manager). All other # tools are mandatory for the convert/boot flow itself. - local tools=("wget" "qemu-img" "qemu-nbd" "cryptsetup" "lvm" "parted" "blkid" "mkfs.ext4") + local tools=("wget" "qemu-img" "qemu-nbd" "cryptsetup" "lvm" "parted" "blkid" "mkfs.ext4" "sgdisk") local missing=() for tool in "${tools[@]}"; do @@ -252,25 +262,28 @@ cleanup() { # Test image functions # ============================================================================ -# Download test image with caching -download_test_image() { - if [[ -f "${TEST_IMAGE_CACHE}" ]]; then - log::info "Using cached test image: ${TEST_IMAGE_CACHE}" +# Download a file with caching and retry support +download_file() { + local url="$1" + local cache_path="$2" + + if [[ -f "${cache_path}" ]]; then + log::info "Using cached image: ${cache_path}" return 0 fi log::step "Downloading test image..." - log::info "URL: ${TEST_IMAGE_URL}" - log::info "Destination: ${TEST_IMAGE_CACHE}" + log::info "URL: ${url}" + log::info "Destination: ${cache_path}" - local tmp_file="${TEST_IMAGE_CACHE}.downloading" + local tmp_file="${cache_path}.downloading" # Download with resume support and retry local retry=0 local max_retries=3 while [[ $retry -lt $max_retries ]]; do - if wget -c -O "${tmp_file}" "${TEST_IMAGE_URL}"; then - mv "${tmp_file}" "${TEST_IMAGE_CACHE}" + if wget -c -O "${tmp_file}" "${url}"; then + mv "${tmp_file}" "${cache_path}" log::success "Test image downloaded successfully" return 0 fi @@ -283,6 +296,62 @@ download_test_image() { fatal "Failed to download test image after $max_retries attempts" } +# Prepare the Ubuntu image: the stock noble cloud image is only ~2.2G, too +# small to hold boot + ESP + the LVM volumes the conversion produces, so grow +# it to 10G and relocate the backup GPT to the new disk end (sgdisk -e). +# dracut is installed by the conversion itself (install_deb_on_rootfs +# pre-installs it), so no guest customization is needed here. +prepare_ubuntu_image() { + download_file "${UBUNTU_IMAGE_URL}" "${UBUNTU_IMAGE_CACHE}" + + local virtual_size + virtual_size=$(qemu-img info --output=json "${UBUNTU_IMAGE_CACHE}" | sed -n 's/.*"virtual-size": \([0-9]*\).*/\1/p') + if [[ -n "${virtual_size}" && "${virtual_size}" -ge $((10 * 1024 * 1024 * 1024)) ]]; then + return 0 + fi + + log::step "Resizing Ubuntu image to 10G and repairing the GPT..." + qemu-img resize "${UBUNTU_IMAGE_CACHE}" 10G + + local nbd_device + nbd_device=$(get_available_nbd) + if ! qemu-nbd --connect="${nbd_device}" "${UBUNTU_IMAGE_CACHE}"; then + log::error "Failed to connect Ubuntu image to NBD: ${UBUNTU_IMAGE_CACHE}" + return 1 + fi + local rc=0 + if ! ( set -e + sleep 2 + partprobe "${nbd_device}" 2>/dev/null || true + sleep 1 + sgdisk -e "${nbd_device}" + ); then + rc=1 + fi + qemu-nbd --disconnect "${nbd_device}" >/dev/null 2>&1 || true + sleep 1 + if [[ $rc -ne 0 ]]; then + log::error "Failed to repair the GPT of ${UBUNTU_IMAGE_CACHE}" + return 1 + fi + log::success "Ubuntu image prepared successfully" +} + +# Download and cache the test image based on distro +download_test_image() { + case "${DISTRO}" in + alinux3) + download_file "${ALINUX3_IMAGE_URL}" "${ALINUX3_IMAGE_CACHE}" + ;; + ubuntu) + prepare_ubuntu_image + ;; + *) + fatal "Unknown distro: ${DISTRO}" + ;; + esac +} + # Create test configuration directory. delta_key controls the delta key # provider ("otp" recreates the delta every boot; "stable" uses an exec # provider with the same passphrase as rootfs so the delta persists across @@ -345,6 +414,13 @@ run_enhance() { log::step "Running cryptpilot-enhance for test: ${test_name}" + # A custom --input image is already prepared; hardening it again is not + # the point of the test that uses it. + if [[ "${USE_CUSTOM_INPUT}" == "true" ]]; then + log::info "Skipping cryptpilot-enhance (custom input image)" + return 0 + fi + # Use 'direct' backend to avoid libvirtd dependency in CI/containers export LIBGUESTFS_BACKEND=direct @@ -476,7 +552,7 @@ run_convert() { cmd+=("--rootfs-no-encryption") fi - cmd+=("--package" "${CRYPTPILOT_FDE_RPM}") + cmd+=("--package" "${CRYPTPILOT_FDE_PACKAGE}") log::info "Command: ${cmd[*]}" @@ -726,7 +802,9 @@ test_qemu_boot() { log::info "QEMU container started: ${container_name}" # Stream logs to file and check for boot status - local timeout=540 # 9 minutes; TCG under GitHub runner contention can push a 2-min boot well past 6. + # 15 minutes; TCG under GitHub runner contention can push a 2-min boot + # well past 6, and Ubuntu's systemd reaches the login getty late. + local timeout=900 local elapsed=0 local check_interval=2 local boot_success=false @@ -746,7 +824,15 @@ test_qemu_boot() { fi # Check for login prompt (success) - if grep -q -i " on an x86_64" "${boot_log}" 2>/dev/null; then + # RHEL/Alibaba Cloud Linux: " on an x86_64" + # Ubuntu: no prompt on serial until a getty starts; "Welcome to + # Ubuntu", a ttyN login: line, or systemd reaching multi-user all + # count as booted. + if grep -q -i " on an x86_64" "${boot_log}" 2>/dev/null || + grep -q -i "Welcome to Ubuntu" "${boot_log}" 2>/dev/null || + grep -q -E "[Tt]ty[0-9]+ login:" "${boot_log}" 2>/dev/null || + grep -q -E "Reached target.*Multi-User" "${boot_log}" 2>/dev/null || + grep -q -E "Started.*serial-getty" "${boot_log}" 2>/dev/null; then log::success "Login prompt detected - boot successful!" boot_success=true break @@ -862,7 +948,10 @@ exec qemu-system-x86_64 \ local timeout=540 elapsed=0 boot_success=false while [[ $elapsed -lt $timeout ]]; do sleep 5; elapsed=$((elapsed+5)) - if grep -q -i " on an x86_64" "${boot_log}" 2>/dev/null; then + if grep -q -i " on an x86_64" "${boot_log}" 2>/dev/null || + grep -q -i "Welcome to Ubuntu" "${boot_log}" 2>/dev/null || + grep -q -E "[Tt]ty[0-9]+ login:" "${boot_log}" 2>/dev/null || + grep -q -E "Reached target.*Multi-User" "${boot_log}" 2>/dev/null; then if [[ -z "${require_pattern}" ]] || grep -q -F "${require_pattern}" "${boot_log}" 2>/dev/null; then log::success "Login prompt detected - boot successful!" boot_success=true @@ -1182,18 +1271,21 @@ run_test_case() { show_help() { cat < --bootloader --rootfs-enc|--rootfs-noenc --delta-location [OPTIONS] +Usage: $(basename "$0") (--rpm|--deb|--package) --bootloader --rootfs-enc|--rootfs-noenc --delta-location [OPTIONS] Integration tests for cryptpilot-convert Required: - --rpm Path to cryptpilot-fde-guest RPM package --bootloader Boot mode --rootfs-enc Enable rootfs encryption --rootfs-noenc Disable rootfs encryption --delta-location Delta partition location: ram | disk | disk-persist + --rpm Path to cryptpilot-fde-guest RPM package (alinux3) + --deb Path to cryptpilot-fde-guest DEB package (ubuntu) + --package Path to a package file (.rpm or .deb) Options: + --distro Target distro (default: alinux3) --input Use specified qcow2 image instead of downloading --boot-matrix Space-separated "cpu:ram" tokens to boot the converted image with, e.g. "2:4G 4:8G 8:16G 12:16G 16:16G". The @@ -1217,6 +1309,7 @@ Options: Examples: $(basename "$0") --rpm ./cryptpilot-fde-guest-*.rpm --bootloader uki --rootfs-enc --delta-location ram $(basename "$0") --rpm ./cryptpilot-fde-guest-*.rpm --bootloader grub --rootfs-noenc --delta-location disk --input /path/to/image.qcow2 + $(basename "$0") --deb ./cryptpilot-fde-guest-*.deb --distro ubuntu --bootloader grub --rootfs-enc --delta-location ram # Issue #141 regression (disk-persist + integrity=true, first-boot failure): $(basename "$0") --rpm ./cryptpilot-fde-guest-*.rpm --bootloader uki --rootfs-enc --delta-location disk-persist --delta-key stable --integrity true # Issue #140 regression (disk-persist, stable key, second-boot resize failure): @@ -1229,12 +1322,27 @@ main() { local rootfs_enc="" local delta_location="" local custom_input="" + local rpm_path="" + local deb_path="" + local pkg_path="" # Parse arguments while [[ $# -gt 0 ]]; do case "$1" in --rpm) - CRYPTPILOT_FDE_RPM="$2" + rpm_path="$2" + shift 2 + ;; + --deb) + deb_path="$2" + shift 2 + ;; + --package) + pkg_path="$2" + shift 2 + ;; + --distro) + DISTRO="$2" shift 2 ;; --bootloader) @@ -1291,15 +1399,35 @@ main() { esac done - # Validate required --rpm argument - if [[ -z "${CRYPTPILOT_FDE_RPM}" ]]; then + # --rpm, --deb and --package are aliases for the same slot; exactly one + # is required. + local pkg_count=0 + [[ -n "${rpm_path}" ]] && pkg_count=$((pkg_count + 1)) + [[ -n "${deb_path}" ]] && pkg_count=$((pkg_count + 1)) + [[ -n "${pkg_path}" ]] && pkg_count=$((pkg_count + 1)) + if [[ $pkg_count -gt 1 ]]; then + fatal "--rpm, --deb, and --package are mutually exclusive; specify only one" + fi + if [[ $pkg_count -eq 0 ]]; then show_help - fatal "Missing required argument: --rpm " + fatal "Missing required argument: --rpm, --deb, or --package " + fi + if [[ -n "${pkg_path}" ]]; then + CRYPTPILOT_FDE_PACKAGE="${pkg_path}" + elif [[ -n "${rpm_path}" ]]; then + CRYPTPILOT_FDE_PACKAGE="${rpm_path}" + else + CRYPTPILOT_FDE_PACKAGE="${deb_path}" fi - if [[ ! -f "${CRYPTPILOT_FDE_RPM}" ]]; then - fatal "cryptpilot-fde-guest RPM package not found: ${CRYPTPILOT_FDE_RPM}" + if [[ ! -f "${CRYPTPILOT_FDE_PACKAGE}" ]]; then + fatal "cryptpilot-fde-guest package not found: ${CRYPTPILOT_FDE_PACKAGE}" + fi + log::info "Using cryptpilot-fde-guest package: ${CRYPTPILOT_FDE_PACKAGE}" + + # Validate --distro + if [[ "${DISTRO}" != "alinux3" && "${DISTRO}" != "ubuntu" ]]; then + fatal "Invalid --distro: must be 'alinux3' or 'ubuntu'" fi - log::info "Using cryptpilot-fde-guest RPM: ${CRYPTPILOT_FDE_RPM}" # Validate --bootloader if [[ "${bootloader}" != "uki" && "${bootloader}" != "grub" ]]; then @@ -1360,6 +1488,7 @@ main() { [[ "${bootloader}" == "uki" ]] && use_uki="true" [[ "${rootfs_enc}" == "enc" ]] && use_encryption="true" local test_name="${bootloader}-${rootfs_enc}-${delta_location}" + [[ "${DISTRO}" != "alinux3" ]] && test_name="${DISTRO}-${test_name}" # Append a suffix for non-default options so logs/artifacts are distinct. [[ "${DELTA_KEY}" == "stable" ]] && test_name="${test_name}-stable" [[ "${INTEGRITY}" == "true" ]] && test_name="${test_name}-integ" @@ -1382,11 +1511,19 @@ main() { # Set source image path if [[ -n "${custom_input}" ]]; then SOURCE_IMAGE="${custom_input}" + USE_CUSTOM_INPUT=true log::info "Using custom input image: ${SOURCE_IMAGE}" else - # Download test image if not using custom input + # Download/prepare the test image for the selected distro download_test_image - SOURCE_IMAGE="${TEST_IMAGE_CACHE}" + case "${DISTRO}" in + alinux3) + SOURCE_IMAGE="${ALINUX3_IMAGE_CACHE}" + ;; + ubuntu) + SOURCE_IMAGE="${UBUNTU_IMAGE_CACHE}" + ;; + esac fi # Run test