From c9cfdbf86f2bf620c986abb2f67dcaabf5b01047 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Tue, 22 Sep 2026 17:00:53 -0700 Subject: Add support for hcloud openbsd image snapshot --- .gitignore | 4 +- Makefile | 72 --------- build-hcloud-snapshot.sh | 69 ++++++++ build-openbsd-image.sh | 58 +++++++ configs/doas.conf | 1 - hcloud-snapshot/main.pkr.hcl | 22 +++ hcloud-snapshot/snapshot.pkr.hcl | 10 ++ hcloud-snapshot/variables.pkr.hcl | 33 ++++ openbsd-image/Makefile | 73 +++++++++ openbsd-image/configs/doas.conf | 1 + openbsd-image/locals.pkr.hcl | 4 + openbsd-image/main.pkr.hcl | 23 +++ openbsd-image/openbsd-amd64.pkr.hcl | 42 +++++ openbsd-image/openbsd-arm64.pkr.hcl | 51 ++++++ openbsd-image/scripts/harden-root.sh | 12 ++ openbsd-image/scripts/setup.sh | 32 ++++ openbsd-image/templates/install.conf.pkrtpl.hcl | 16 ++ openbsd-image/variables.pkr.hcl | 55 +++++++ openbsd.pkr.hcl | 182 --------------------- openbsd79-amd64.pkvars.hcl | 7 - openbsd79-arm64.pkvars.hcl | 7 - scripts/harden-root.sh | 12 -- scripts/setup.sh | 32 ---- templates/install.conf.pkrtpl.hcl | 16 -- tools/create_openbsd_hetzner_snapshot.py | 204 ------------------------ 25 files changed, 503 insertions(+), 535 deletions(-) delete mode 100644 Makefile create mode 100755 build-hcloud-snapshot.sh create mode 100755 build-openbsd-image.sh delete mode 100644 configs/doas.conf create mode 100644 hcloud-snapshot/main.pkr.hcl create mode 100644 hcloud-snapshot/snapshot.pkr.hcl create mode 100644 hcloud-snapshot/variables.pkr.hcl create mode 100644 openbsd-image/Makefile create mode 100644 openbsd-image/configs/doas.conf create mode 100644 openbsd-image/locals.pkr.hcl create mode 100644 openbsd-image/main.pkr.hcl create mode 100644 openbsd-image/openbsd-amd64.pkr.hcl create mode 100644 openbsd-image/openbsd-arm64.pkr.hcl create mode 100755 openbsd-image/scripts/harden-root.sh create mode 100755 openbsd-image/scripts/setup.sh create mode 100644 openbsd-image/templates/install.conf.pkrtpl.hcl create mode 100644 openbsd-image/variables.pkr.hcl delete mode 100644 openbsd.pkr.hcl delete mode 100644 openbsd79-amd64.pkvars.hcl delete mode 100644 openbsd79-arm64.pkvars.hcl delete mode 100755 scripts/harden-root.sh delete mode 100755 scripts/setup.sh delete mode 100644 templates/install.conf.pkrtpl.hcl delete mode 100644 tools/create_openbsd_hetzner_snapshot.py diff --git a/.gitignore b/.gitignore index cd31339..fa9020f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/build -/edk2-arm-vars.fd +/openbsd-image/build +/openbsd-iamge/edk2-arm-vars.fd diff --git a/Makefile b/Makefile deleted file mode 100644 index c1343f9..0000000 --- a/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -SHELL := /bin/sh - -ARCH ?= arm64 -BUILD_DIR := build -EDK2_DIR := /opt/homebrew/share/qemu -SSH_PORT := 2222 -SSH_USER := admin -SSH_KEY := ~/.ssh/id_rsa -CPU := 1 -MEMORY := 4096M -PACKER_LOG := 1 - -VERSION := 7.9 -VERSION_SHORT := 79 -QEMU_ARCH := $(if $(filter arm64,$(ARCH)),aarch64,x86_64) -VARS_FILE := openbsd$(VERSION_SHORT)-$(ARCH).pkvars.hcl -DISK := $(BUILD_DIR)/openbsd-$(VERSION)-$(QEMU_ARCH).qcow2 -EFIVARS_RUN := $(BUILD_DIR)/efivars-run.fd -EDK2_CODE := $(EDK2_DIR)/edk2-aarch64-code.fd -EDK2_VARS := edk2-arm-vars.fd - -export PACKER_LOG - -.PHONY: all init build run ssh clean - -all: build - -init: - packer init . - -build: init clean -ifeq ($(ARCH),arm64) - cp $(EDK2_DIR)/$(EDK2_VARS) ./$(EDK2_VARS) -endif - packer build -only qemu.openbsd-$(ARCH) -var-file=$(VARS_FILE) . - -# Run the headless VM (SSH via port-forwarded localhost:$(SSH_PORT)) -run: -ifeq ($(ARCH),arm64) - cp ./$(EDK2_VARS) $(EFIVARS_RUN) - qemu-system-aarch64 \ - -machine type=virt,accel=hvf \ - -cpu host \ - -m $(MEMORY) \ - -smp $(CPU) \ - -nographic \ - -device qemu-xhci,id=xhci \ - -device usb-kbd,bus=xhci.0 \ - -device virtio-gpu-pci \ - -netdev user,id=net0,hostfwd=tcp::$(SSH_PORT)-:22 \ - -device virtio-net,netdev=net0 \ - -drive file=$(DISK),if=virtio,cache=writeback,discard=ignore,format=qcow2 \ - -drive file=$(EDK2_CODE),if=pflash,unit=0,format=raw,readonly=on \ - -drive file=$(EFIVARS_RUN),if=pflash,unit=1,format=raw -else - qemu-system-x86_64 \ - -machine type=q35,accel=tcg \ - -cpu max \ - -m $(MEMORY) \ - -smp $(CPU) \ - -nographic \ - -netdev user,id=net0,hostfwd=tcp::$(SSH_PORT)-:22 \ - -device virtio-net,netdev=net0 \ - -drive file=$(DISK),if=virtio,cache=writeback,discard=ignore,format=qcow2 -endif - -ssh: - ssh -i $(SSH_KEY) -p $(SSH_PORT) $(SSH_USER)@127.0.0.1 - -clean: - rm -rf $(BUILD_DIR) - diff --git a/build-hcloud-snapshot.sh b/build-hcloud-snapshot.sh new file mode 100755 index 0000000..40f3dcb --- /dev/null +++ b/build-hcloud-snapshot.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# +# DESCRIPTION: +# Create a OpenBSD snapshot in Hetzner Cloud. +# +# USAGE: +# ./build-openbsd-image.sh +# export HCLOUD_TOKEN="xxxxx-xxxxx" +# ./build-hcloud-snapshot.sh +# +set -o nounset +set -o errexit + +export PACKER_LOG=1 +SCRIPTDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P) + +VERSION=7.9 +ARCH=amd64 +PUBLIC_SSH_KEY="$HOME/.ssh/id_rsa.pub" + +main() ( + parse_args "$@" + img_path="${SCRIPTDIR}/openbsd-image/build/openbsd-${VERSION}-${ARCH}.raw" + build_compressed_image "$img_path" + cd "$SCRIPTDIR/hcloud-snapshot/" + packer init . + packer build \ + -var "hcloud_token=${HCLOUD_TOKEN:?}" \ + -var "image_path=${img_path}.zst" \ + -var "version=$VERSION" \ + -var "arch=$ARCH" \ + -var "ssh_key=$(get_ssh_key_name "$PUBLIC_SSH_KEY")" \ + . +) + +parse_args() { + while [ $# -gt 0 ]; do + case "$1" in + --version) + VERSION="$2" + shift 2 + ;; + --arch) + ARCH="$2" + shift 2 + ;; + --public-ssh-key) + PUBLIC_SSH_KEY="$2" + shift 2 + ;; + *) + echo "Unknown option: $1" + shift + ;; + esac + done +} + +build_compressed_image() ( + if [ ! -e "$1.zst" ]; then + zstd -T0 "$1" -o "$1.zst" + fi +) + +get_ssh_key_name() { + awk '{print $3}' "$1" +} + +main "$@" diff --git a/build-openbsd-image.sh b/build-openbsd-image.sh new file mode 100755 index 0000000..b31ebfa --- /dev/null +++ b/build-openbsd-image.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# +# DESCRIPTION: +# Create an OpenBSD image with Packer and QEMU. +# +# USAGE: +# ./build-openbsd-image.sh +set -o nounset +set -o errexit + +VERSION=7.9 +ARCH=amd64 +DISK_SIZE_GB=36 +PUBLIC_SSH_KEY="$HOME/.ssh/id_rsa.pub" + +export PACKER_LOG=1 + +main() ( + parse_args "$@" + cd openbsd-image/ + packer init . + packer build \ + -only "qemu.openbsd-$ARCH" \ + -var "arch=$ARCH" \ + -var "disk_size=$DISK_SIZE_GB" \ + -var "version=$VERSION" \ + -var "ssh_key=$(cat "$PUBLIC_SSH_KEY")" \ + . +) + +parse_args() { + while [ $# -gt 0 ]; do + case "$1" in + --version) + VERSION="$2" + shift 2 + ;; + --arch) + ARCH="$2" + shift 2 + ;; + --disk-size-gb) + DISK_SIZE_GB="$2" + shift 2 + ;; + --public-ssh-key) + PUBLIC_SSH_KEY="$2" + shift 2 + ;; + *) + echo "Unknown option: $1" + shift + ;; + esac + done +} + +main "$@" diff --git a/configs/doas.conf b/configs/doas.conf deleted file mode 100644 index 96cf24d..0000000 --- a/configs/doas.conf +++ /dev/null @@ -1 +0,0 @@ -permit nopass keepenv :wheel diff --git a/hcloud-snapshot/main.pkr.hcl b/hcloud-snapshot/main.pkr.hcl new file mode 100644 index 0000000..920eeae --- /dev/null +++ b/hcloud-snapshot/main.pkr.hcl @@ -0,0 +1,22 @@ +packer { + required_plugins { + hcloud = { source = "github.com/hetznercloud/hcloud", version = "~> 1" } + } +} + +build { + sources = ["source.hcloud.openbsd"] + + provisioner "file" { + source = var.image_path + destination = "/tmp/openbsd.raw.zst" + } + + provisioner "shell" { + inline = [ + "which zstd || apt-get install --assume-yes zstd", + "zstd --decompress --stdout /tmp/openbsd.raw.zst | dd of=/dev/sda bs=4M status=progress", + "sync", + ] + } +} diff --git a/hcloud-snapshot/snapshot.pkr.hcl b/hcloud-snapshot/snapshot.pkr.hcl new file mode 100644 index 0000000..d8834c8 --- /dev/null +++ b/hcloud-snapshot/snapshot.pkr.hcl @@ -0,0 +1,10 @@ +source "hcloud" "openbsd" { + token = var.hcloud_token + rescue = "linux64" + image = "debian-13" + server_type = "cx23" + location = "nbg1" + ssh_username = "root" + ssh_keys = [var.ssh_key] + snapshot_name = "openbsd-${var.version}-${var.arch}-golden" +} diff --git a/hcloud-snapshot/variables.pkr.hcl b/hcloud-snapshot/variables.pkr.hcl new file mode 100644 index 0000000..a02e433 --- /dev/null +++ b/hcloud-snapshot/variables.pkr.hcl @@ -0,0 +1,33 @@ +variable "hcloud_token" { + type = string + description = "Hetnzer API token" + sensitive = true +} + +variable "image_path" { + type = string + description = "Path to the built OpenBSD raw zstd compressed image" +} + +variable "version" { + type = string + description = "Version of OpenBSD to build" + validation { + condition = can(regex("^\\d\\.\\d$", var.version)) + error_message = "The version must be a single-digit followed by a period followed by another single digit." + } +} + +variable "arch" { + type = string + validation { + condition = contains(["amd64", "arm64"], var.arch) + error_message = "The arch must be one of: amd64, arm64." + } +} + +variable "ssh_key" { + type = string + description = "SSH key name in Hetzner to add to the image on launch" +} + diff --git a/openbsd-image/Makefile b/openbsd-image/Makefile new file mode 100644 index 0000000..0c3ae00 --- /dev/null +++ b/openbsd-image/Makefile @@ -0,0 +1,73 @@ +# TODO: Replace with run-openbsd-image.sh and add ARM support to build-openbsd-image.sh +SHELL := /bin/sh + +ARCH ?= arm64 +BUILD_DIR := build +EDK2_DIR := /opt/homebrew/share/qemu +SSH_PORT := 2222 +SSH_USER := admin +SSH_KEY := ~/.ssh/id_rsa +CPU := 8 +MEMORY := 32768M +PACKER_LOG := 1 + +VERSION := 7.9 +VERSION_SHORT := 79 +QEMU_ARCH := $(if $(filter arm64,$(ARCH)),aarch64,x86_64) +VARS_FILE := openbsd$(VERSION_SHORT)-$(ARCH).pkvars.hcl +DISK := $(BUILD_DIR)/openbsd-$(VERSION)-$(QEMU_ARCH).qcow2 +EFIVARS_RUN := $(BUILD_DIR)/efivars-run.fd +EDK2_CODE := $(EDK2_DIR)/edk2-aarch64-code.fd +EDK2_VARS := edk2-arm-vars.fd + +export PACKER_LOG + +.PHONY: all init build run ssh clean + +all: build + +init: + packer init . + +build: init clean +ifeq ($(ARCH),arm64) + cp $(EDK2_DIR)/$(EDK2_VARS) ./$(EDK2_VARS) +endif + packer build -only qemu.openbsd-$(ARCH) -var-file=$(VARS_FILE) . + +# Run the headless VM (SSH via port-forwarded localhost:$(SSH_PORT)) +run: +ifeq ($(ARCH),arm64) + cp ./$(EDK2_VARS) $(EFIVARS_RUN) + qemu-system-aarch64 \ + -machine type=virt,accel=hvf \ + -cpu host \ + -m $(MEMORY) \ + -smp $(CPU) \ + -nographic \ + -device qemu-xhci,id=xhci \ + -device usb-kbd,bus=xhci.0 \ + -device virtio-gpu-pci \ + -netdev user,id=net0,hostfwd=tcp::$(SSH_PORT)-:22 \ + -device virtio-net,netdev=net0 \ + -drive file=$(DISK),if=virtio,cache=writeback,discard=ignore,format=qcow2 \ + -drive file=$(EDK2_CODE),if=pflash,unit=0,format=raw,readonly=on \ + -drive file=$(EFIVARS_RUN),if=pflash,unit=1,format=raw +else + qemu-system-x86_64 \ + -machine type=q35,accel=tcg \ + -cpu max \ + -m $(MEMORY) \ + -smp $(CPU) \ + -nographic \ + -netdev user,id=net0,hostfwd=tcp::$(SSH_PORT)-:22 \ + -device virtio-net,netdev=net0 \ + -drive file=$(DISK),if=virtio,cache=writeback,discard=ignore,format=qcow2 +endif + +ssh: + ssh -i $(SSH_KEY) -p $(SSH_PORT) $(SSH_USER)@127.0.0.1 + +clean: + rm -rf $(BUILD_DIR) + diff --git a/openbsd-image/configs/doas.conf b/openbsd-image/configs/doas.conf new file mode 100644 index 0000000..96cf24d --- /dev/null +++ b/openbsd-image/configs/doas.conf @@ -0,0 +1 @@ +permit nopass keepenv :wheel diff --git a/openbsd-image/locals.pkr.hcl b/openbsd-image/locals.pkr.hcl new file mode 100644 index 0000000..f88100f --- /dev/null +++ b/openbsd-image/locals.pkr.hcl @@ -0,0 +1,4 @@ +locals { + version_short = replace(var.version, ".", "") + root_password = "temp" +} diff --git a/openbsd-image/main.pkr.hcl b/openbsd-image/main.pkr.hcl new file mode 100644 index 0000000..43d01dd --- /dev/null +++ b/openbsd-image/main.pkr.hcl @@ -0,0 +1,23 @@ +packer { + required_plugins { + qemu = { source = "github.com/hashicorp/qemu", version = ">= 1.1.0" } + } +} + +build { + sources = ["source.qemu.openbsd-amd64", "source.qemu.openbsd-arm64"] + + provisioner "file" { + source = "configs/doas.conf" + destination = "/etc/doas.conf" + } + + provisioner "shell" { + script = "scripts/setup.sh" + environment_vars = ["ADMIN_USER=${var.admin_user}"] + } + + provisioner "shell" { + script = "scripts/harden-root.sh" + } +} diff --git a/openbsd-image/openbsd-amd64.pkr.hcl b/openbsd-image/openbsd-amd64.pkr.hcl new file mode 100644 index 0000000..5d2c9f7 --- /dev/null +++ b/openbsd-image/openbsd-amd64.pkr.hcl @@ -0,0 +1,42 @@ +source "qemu" "openbsd-amd64" { + vm_name = "openbsd-${var.version}-amd64.raw" + iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" + iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" + output_directory = "build" + qemu_binary = "qemu-system-x86_64" + machine_type = "q35" + cpu_model = "max" + accelerator = "tcg" + memory = var.memory + disk_interface = "virtio" + disk_size = "${var.disk_size}G" + disk_compression = true + format = "raw" + ssh_username = "root" + ssh_password = local.root_password + ssh_timeout = "30m" + + http_content = { + "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { + hostname = var.hostname + user = var.admin_user + ssh_key = var.ssh_public_key + root_password = local.root_password + mirror = var.mirror + version = var.version + version_short = local.version_short + arch = var.arch + }) + } + + boot_command = [ + "S", + "set tty com0", + "autoinstall", + "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf", + ] + boot_wait = "20s" + shutdown_command = "shutdown -p now" + headless = false + qemuargs = [["-display", "cocoa"]] +} diff --git a/openbsd-image/openbsd-arm64.pkr.hcl b/openbsd-image/openbsd-arm64.pkr.hcl new file mode 100644 index 0000000..dbe5833 --- /dev/null +++ b/openbsd-image/openbsd-arm64.pkr.hcl @@ -0,0 +1,51 @@ +source "qemu" "openbsd-arm64" { + vm_name = "openbsd-${var.version}-aarch64.qcow2" + iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" + iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" + output_directory = "build" + qemu_binary = "qemu-system-aarch64" + machine_type = "virt" + cpu_model = "host" + accelerator = "hvf" + memory = var.memory + disk_interface = "virtio" + disk_size = "${var.disk_size}G" + disk_compression = true + format = "qcow2" + ssh_username = "root" + ssh_password = local.root_password + ssh_timeout = "10m" + + http_content = { + "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { + hostname = var.hostname + user = var.admin_user + ssh_key = var.ssh_public_key + root_password = local.root_password + mirror = var.mirror + version = var.version + version_short = local.version_short + arch = var.arch + }) + } + + boot_command = [ + "S", + "set tty com0", + "autoinstall", + "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf", + ] + boot_wait = "20s" + shutdown_command = "shutdown -p now" + use_default_display = true + headless = false + qemuargs = [ + ["-device", "qemu-xhci,id=xhci"], + ["-device", "usb-kbd,bus=xhci.0"], + ["-device", "virtio-gpu-pci"], + ["-display", "cocoa"], + ] + efi_firmware_code = "/opt/homebrew/share/qemu/edk2-aarch64-code.fd" + efi_firmware_vars = "./edk2-arm-vars.fd" +} + diff --git a/openbsd-image/scripts/harden-root.sh b/openbsd-image/scripts/harden-root.sh new file mode 100755 index 0000000..c8e267a --- /dev/null +++ b/openbsd-image/scripts/harden-root.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -e + +main() { + chown root:wheel /etc/doas.conf + chmod 0640 /etc/doas.conf + usermod -p '*' root + sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config + rcctl reload sshd +} + +main "$@" diff --git a/openbsd-image/scripts/setup.sh b/openbsd-image/scripts/setup.sh new file mode 100755 index 0000000..320d93d --- /dev/null +++ b/openbsd-image/scripts/setup.sh @@ -0,0 +1,32 @@ +#!/bin/sh +set -e + +: "${ADMIN_USER:?ADMIN_USER must be set}" + +main() { + update_pkgs + install_system_maintenance_cron_jobs "$ADMIN_USER" + allow_user_non_root_shutdown "$ADMIN_USER" +} + +update_pkgs() { + # Ensure the time is in sync. If it is not, things like upgrading the system + # packages via pkg_add -u fail. + rdate -n pool.ntp.org + pkg_add -u + fw_update +} + +install_system_maintenance_cron_jobs() { + ( + echo "MAILTO=$1" # Send mail about root cron jobs to the admin user. + crontab -l 2>/dev/null # Print existing cron file; redirect stderr if empty cron file error. + echo "10 12 * * * /usr/sbin/syspatch -c" # Install any outstanding patches everyday at 12:10 + ) | crontab - +} + +allow_user_non_root_shutdown() { + usermod -G _shutdown "$1" +} + +main "$@" diff --git a/openbsd-image/templates/install.conf.pkrtpl.hcl b/openbsd-image/templates/install.conf.pkrtpl.hcl new file mode 100644 index 0000000..9df18ce --- /dev/null +++ b/openbsd-image/templates/install.conf.pkrtpl.hcl @@ -0,0 +1,16 @@ +System hostname = ${hostname} +Setup a user = ${user} +SSH key for user = ${ssh_key} +Password for user = none +Password for root = ${root_password} +Allow root ssh login = yes +Which disk is the root disk = sd0 +Use (W)hole disk or (E)dit the MBR = whole +Location of sets = http +HTTP proxy = none +HTTP Server = ${mirror} +Server directory = pub/OpenBSD/${version}/${arch} +Set name(s) = base comp man -game*.tgz -x*.tgz +Directory does not contain SHA256.sig. Continue without verification = no +Change the default console to com0 = yes +Which speed should com0 use = 115200 diff --git a/openbsd-image/variables.pkr.hcl b/openbsd-image/variables.pkr.hcl new file mode 100644 index 0000000..4bc0860 --- /dev/null +++ b/openbsd-image/variables.pkr.hcl @@ -0,0 +1,55 @@ +variable "version" { + type = string + description = "Version of OpenBSD to build" + validation { + condition = can(regex("^\\d\\.\\d$", var.version)) + error_message = "The version must be a single-digit followed by a period followed by another single digit." + } +} + +variable "arch" { + type = string + validation { + condition = contains(["amd64", "arm64"], var.arch) + error_message = "The arch must be one of: amd64, arm64." + } +} + +variable "admin_user" { + type = string + description = "Username of the admin user on the VM" + default = "admin" +} + +variable "ssh_public_key" { + type = string + description = "Public SSH key to associate with the admin user for login" +} + +variable "mirror" { + type = string + description = "URL basename for where to download the OpenBSD ISO." + default = "https://cdn.openbsd.org" + validation { + condition = can(regex("^(https?)://", var.mirror)) && !endswith(var.mirror, "/") + error_message = "URL must start with http(s):// and must not have a trailing slash." + } +} + +variable "hostname" { + type = string + description = "Hostname for the VM" + default = "openbsd-vm" +} + +variable "memory" { + type = number + description = "Memory to allocate to the VM in MB while building the ISO" + default = 4096 +} + +variable "disk_size" { + type = number + description = "Size of the disk in GB while building the ISO" + default = 16 +} diff --git a/openbsd.pkr.hcl b/openbsd.pkr.hcl deleted file mode 100644 index bba0327..0000000 --- a/openbsd.pkr.hcl +++ /dev/null @@ -1,182 +0,0 @@ -packer { - required_plugins { - qemu = { source = "github.com/hashicorp/qemu", version = ">= 1.1.0" } - } -} - -variable "version" { - type = string - validation { - condition = can(regex("^\\d\\.\\d$", var.version)) - error_message = "The version must be a single-digit followed by a period followed by another single digit." - } -} - -variable "ssh_public_key" { - type = string - description = "Public SSH key to associate with the admin user for login" -} - -variable "ssh_private_key_file" { - type = string - description = "Private SSH key to associate with the admin user for login" -} - -variable "arch" { - type = string - validation { - condition = contains(["amd64", "arm64"], var.arch) - error_message = "The arch must be one of: amd64, arm64." - } -} - -variable "admin_user" { - type = string - description = "Username of the admin user on the VM" - default = "admin" -} - -variable "mirror" { - type = string - description = "URL basename for where to download the OpenBSD ISO." - default = "https://cdn.openbsd.org" - validation { - condition = can(regex("^(https?)://", var.mirror)) && !endswith(var.mirror, "/") - error_message = "URL must start with http(s):// and must not have a trailing slash." - } -} - -variable "hostname" { - type = string - description = "Hostname for the VM" - default = "openbsd-vm" -} - -variable "memory" { - type = number - description = "Memory to allocate to the VM in MB" - default = 4096 -} - -variable "disk_size" { - type = number - description = "Size of the disk in GB" - default = 16 -} - -locals { - version_short = replace(var.version, ".", "") - root_password = "temp" -} - -source "qemu" "openbsd-amd64" { - vm_name = "openbsd-${var.version}-amd64.qcow2" - iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" - iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" - output_directory = "build" - qemu_binary = "qemu-system-x86_64" - machine_type = "q35" - cpu_model = "max" - accelerator = "tcg" - memory = var.memory - disk_interface = "virtio" - disk_size = "${var.disk_size}G" - disk_compression = true - format = "qcow2" - ssh_username = "root" - ssh_password = local.root_password - ssh_timeout = "30m" - - http_content = { - "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { - hostname = var.hostname - user = var.admin_user - ssh_key = var.ssh_public_key - root_password = local.root_password - mirror = var.mirror - version = var.version - version_short = local.version_short - arch = var.arch - }) - } - - boot_command = [ - "S", - "set tty com0", - "autoinstall", - "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf", - ] - boot_wait = "20s" - shutdown_command = "shutdown -p now" - headless = false - qemuargs = [["-display", "cocoa"]] -} - -source "qemu" "openbsd-arm64" { - vm_name = "openbsd-${var.version}-aarch64.qcow2" - iso_url = "${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/install${local.version_short}.iso" - iso_checksum = "file:${var.mirror}/pub/OpenBSD/${var.version}/${var.arch}/SHA256" - output_directory = "build" - qemu_binary = "qemu-system-aarch64" - machine_type = "virt" - cpu_model = "host" - accelerator = "hvf" - memory = var.memory - disk_interface = "virtio" - disk_size = "${var.disk_size}G" - disk_compression = true - format = "qcow2" - ssh_username = "root" - ssh_password = local.root_password - ssh_timeout = "10m" - - http_content = { - "/install.conf" = templatefile("${path.root}/templates/install.conf.pkrtpl.hcl", { - hostname = var.hostname - user = var.admin_user - ssh_key = var.ssh_public_key - root_password = local.root_password - mirror = var.mirror - version = var.version - version_short = local.version_short - arch = var.arch - }) - } - - boot_command = [ - "S", - "set tty com0", - "autoinstall", - "http://{{ .HTTPIP }}:{{ .HTTPPort }}/install.conf", - ] - boot_wait = "20s" - shutdown_command = "shutdown -p now" - use_default_display = true - headless = false - qemuargs = [ - ["-device", "qemu-xhci,id=xhci"], - ["-device", "usb-kbd,bus=xhci.0"], - ["-device", "virtio-gpu-pci"], - ["-display", "cocoa"], - ] - efi_firmware_code = "/opt/homebrew/share/qemu/edk2-aarch64-code.fd" - efi_firmware_vars = "./edk2-arm-vars.fd" -} - -build { - sources = ["source.qemu.openbsd-amd64", "source.qemu.openbsd-arm64"] - - provisioner "file" { - source = "configs/doas.conf" - destination = "/etc/doas.conf" - } - - provisioner "shell" { - script = "scripts/setup.sh" - environment_vars = ["ADMIN_USER=${var.admin_user}"] - } - - provisioner "shell" { - script = "scripts/harden-root.sh" - } -} diff --git a/openbsd79-amd64.pkvars.hcl b/openbsd79-amd64.pkvars.hcl deleted file mode 100644 index 7ed83a6..0000000 --- a/openbsd79-amd64.pkvars.hcl +++ /dev/null @@ -1,7 +0,0 @@ -version = "7.9" -arch = "amd64" -disk_size = 40 -ssh_public_key = <<-EOF -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC31SiCeUZSJN3CueH6/+7UQvxwxkT/QkaDK6ZGdnkdpCWxRVp+0CTO4WG3u0PVEVd9DvSd81CEqrFaKxtKyiSh+4Va0A/mqY27tX7NZzEQLM/zLQrdESmaHY6EyQM0wlCtBKfNzuQqCa9QEw4TwkyMLOJzyI+bRsfeSHNCfxqnqGIMKKFiaF0ygakvQz57nWuKLOgqWsWkzFTuJKGI0OhefFBcZ4VzoCLV8i1zbB2AebhsmbyMza9OUF3px44atSM3o33Jto3gy7LTWtxU83NZU+wLEqY6IvcWx9BbSQZxAwEwXxUFmnzcX+FTkTiOs/Q2nXiLl2ggsGJffAq9Z1SGMCNGxT+Syyta5UtfBVVQdn6xtUxpppHwrdGC+TR8C5F9U12gsZRzvKkz0SSt5M4WHG2gna5rDgTisDbrEAsrqpmUqY9iSBzgAyk5xOi6fdI+r67gpjRSs+PNvDle3gImfIkPnEQg4eWJ54iKjfH+yd8vBk25T/ahu3J9rGgxp18= eugene@laptop -EOF -ssh_private_key_file = "~/.ssh/id_rsa" diff --git a/openbsd79-arm64.pkvars.hcl b/openbsd79-arm64.pkvars.hcl deleted file mode 100644 index 62e0e5e..0000000 --- a/openbsd79-arm64.pkvars.hcl +++ /dev/null @@ -1,7 +0,0 @@ -version = "7.9" -arch = "arm64" -disk_size = 16 -ssh_public_key = <<-EOF -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC31SiCeUZSJN3CueH6/+7UQvxwxkT/QkaDK6ZGdnkdpCWxRVp+0CTO4WG3u0PVEVd9DvSd81CEqrFaKxtKyiSh+4Va0A/mqY27tX7NZzEQLM/zLQrdESmaHY6EyQM0wlCtBKfNzuQqCa9QEw4TwkyMLOJzyI+bRsfeSHNCfxqnqGIMKKFiaF0ygakvQz57nWuKLOgqWsWkzFTuJKGI0OhefFBcZ4VzoCLV8i1zbB2AebhsmbyMza9OUF3px44atSM3o33Jto3gy7LTWtxU83NZU+wLEqY6IvcWx9BbSQZxAwEwXxUFmnzcX+FTkTiOs/Q2nXiLl2ggsGJffAq9Z1SGMCNGxT+Syyta5UtfBVVQdn6xtUxpppHwrdGC+TR8C5F9U12gsZRzvKkz0SSt5M4WHG2gna5rDgTisDbrEAsrqpmUqY9iSBzgAyk5xOi6fdI+r67gpjRSs+PNvDle3gImfIkPnEQg4eWJ54iKjfH+yd8vBk25T/ahu3J9rGgxp18= eugene@laptop -EOF -ssh_private_key_file = "~/.ssh/id_rsa" diff --git a/scripts/harden-root.sh b/scripts/harden-root.sh deleted file mode 100755 index c8e267a..0000000 --- a/scripts/harden-root.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -set -e - -main() { - chown root:wheel /etc/doas.conf - chmod 0640 /etc/doas.conf - usermod -p '*' root - sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config - rcctl reload sshd -} - -main "$@" diff --git a/scripts/setup.sh b/scripts/setup.sh deleted file mode 100755 index 320d93d..0000000 --- a/scripts/setup.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh -set -e - -: "${ADMIN_USER:?ADMIN_USER must be set}" - -main() { - update_pkgs - install_system_maintenance_cron_jobs "$ADMIN_USER" - allow_user_non_root_shutdown "$ADMIN_USER" -} - -update_pkgs() { - # Ensure the time is in sync. If it is not, things like upgrading the system - # packages via pkg_add -u fail. - rdate -n pool.ntp.org - pkg_add -u - fw_update -} - -install_system_maintenance_cron_jobs() { - ( - echo "MAILTO=$1" # Send mail about root cron jobs to the admin user. - crontab -l 2>/dev/null # Print existing cron file; redirect stderr if empty cron file error. - echo "10 12 * * * /usr/sbin/syspatch -c" # Install any outstanding patches everyday at 12:10 - ) | crontab - -} - -allow_user_non_root_shutdown() { - usermod -G _shutdown "$1" -} - -main "$@" diff --git a/templates/install.conf.pkrtpl.hcl b/templates/install.conf.pkrtpl.hcl deleted file mode 100644 index 9df18ce..0000000 --- a/templates/install.conf.pkrtpl.hcl +++ /dev/null @@ -1,16 +0,0 @@ -System hostname = ${hostname} -Setup a user = ${user} -SSH key for user = ${ssh_key} -Password for user = none -Password for root = ${root_password} -Allow root ssh login = yes -Which disk is the root disk = sd0 -Use (W)hole disk or (E)dit the MBR = whole -Location of sets = http -HTTP proxy = none -HTTP Server = ${mirror} -Server directory = pub/OpenBSD/${version}/${arch} -Set name(s) = base comp man -game*.tgz -x*.tgz -Directory does not contain SHA256.sig. Continue without verification = no -Change the default console to com0 = yes -Which speed should com0 use = 115200 diff --git a/tools/create_openbsd_hetzner_snapshot.py b/tools/create_openbsd_hetzner_snapshot.py deleted file mode 100644 index 613b9e6..0000000 --- a/tools/create_openbsd_hetzner_snapshot.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env -S uv run --script -# /// script -# dependencies = [ -# "hcloud==2.24.0", -# ] -# /// - -import abc -import argparse -import logging -import os -import pathlib -import re -import shlex -import subprocess -import sys -import time - -import hcloud -from hcloud.images import Image -from hcloud.locations import Location -from hcloud.server_types import ServerType -from hcloud.ssh_keys import SSHKey - -logging.basicConfig( - level=logging.DEBUG if os.getenv("DEBUG") == "true" else logging.INFO, - format="[%(levelname)s] %(message)s", - stream=sys.stderr, -) - -log = logging.getLogger(__name__) - -ROOT_PATH = pathlib.Path(__file__).parent.parent - - -def main(): - args = parse_args() - builder = OpenBsdBuilder(args.arch, args.version) - builder.build() - - -class ProgArgs(argparse.Namespace): - def __init__(self): - self.arch = "amd64" - self.version = "7.9" - - -def parse_args() -> ProgArgs: - def openbsd_version(v: str): - v = v.strip() - if not re.compile(r"^\d\.\d$").match(v): - raise argparse.ArgumentTypeError("must be a version in the form `X.X`") - return v - - parser = argparse.ArgumentParser() - parser.add_argument( - "--arch", - choices=["amd64", "arm64"], - help="Target architecture", - ) - parser.add_argument( - "--version", - type=openbsd_version, - help="OpenBSD Version number", - ) - return parser.parse_args(namespace=ProgArgs()) - - -class OpenBsdBuilder: - def __init__(self, arch: str, version: str): - self._arch = arch - self._version = version - - def build(self): - server_name = "openbsd-builder" - key_name = "eugene@laptop" - img_path = self._build_img() - # try: - ip = self._start_server(server_name, key_name) - self._write_img_to_build_drive(img_path, ip) - self._reboot_server(server_name) - # self._verify_server(ip) - # self._create_snapshot(server_name, f"openbsd-{self._version}-{self._arch}") - # finally: - # self._delete_server(server_name) - - def _build_img(self) -> pathlib.Path: - # run("make", env={"ARCH": self._arch}, cwd=ROOT_PATH) - return ROOT_PATH / "build" / f"openbsd-{self._version}-{self._arch}.qcow2" - - def _start_server(self, name: str, key_name: str) -> str: - run(f"""hcloud server create \ - --name {name} \ - --type cx23 \ - --location nbg1 \ - --image debian-13 \ - --ssh-key {key_name}""") - run(f"hcloud server enable-rescue {name} --ssh-key {key_name}") - run(f"hcloud server poweron {name}") - time.sleep(30) - return run(f"hcloud server ip {name}", capture_output=True).stdout.strip() - - def _write_img_to_build_drive(self, img_path: pathlib.Path, ip: str): - run( - f"qemu-img convert -O raw '{img_path}' - | zstd -T0 | " - + f"ssh -o StrictHostKeyChecking=no root@{ip} " - + "'zstd -d | dd of=/dev/sda bs=4M status=progress conv=fsync'", - shell=True, - ) - - def _reboot_server(self, name: str): - run(f"hcloud server poweroff {name}") - run(f"hcloud server poweron {name}") - - def _verify_server(self, ip: str): - run(f"ssh -o StrictHostKeyChecking=no 'uname -a' 'admin@{ip}'") - - def _create_snapshot(self, name: str, snapshot_name: str): - run( - f"hcloud server create-image {name} " - + f"--type snapshot --description {snapshot_name}", - shell=True, - ) - - def _delete_server(self, name: str): - run(f"hcloud server delete {name}") - - -class VPSProvider(abc.ABC): - @abc.abstractmethod - def create_server(self, name: str, key_name: str) -> str: - pass - - @abc.abstractmethod - def reboot_server(self, name: str): - pass - - -class HetznerProvider(VPSProvider): - def __init__(self): - self._client = hcloud.Client(token=os.environ["HETZNER_API_TOKEN"]) - - def create_server(self, name: str, key_name: str) -> str: - resp = self._client.servers.create( - name=name, - server_type=ServerType(name="cx23"), - location=Location(name="nbg1"), - image=Image(name="debian-13"), - ssh_keys=[SSHKey(name=key_name)], - ) - resp.action.wait_until_finished() - resp.server.enable_rescue(ssh_keys=[key_name]).action.wait_until_finished() - resp.action.wait_until_finished() - resp.server.power_on().wait_until_finished() - server = self._client.servers.get_by_name(name) - assert server is not None, f"Expected {name} server to exist" - assert ( - server.public_net is not None - ), f"Expect {name} server to have to public address" - assert ( - server.public_net.ipv4 is not None - ), f"Expect {name} server to have to public IPv4 address" - return server.public_net.ipv4.ip - - def _write_img_to_build_drive(self, img_path: pathlib.Path, ip: str): - run( - f"qemu-img convert -O raw '{img_path}' - | zstd -T0 | " - + f"ssh -o StrictHostKeyChecking=no root@{ip} " - + "'zstd -d | dd of=/dev/sda bs=4M status=progress conv=fsync'", - shell=True, - ) - - def reboot_server(self, name: str): - server = self._client.servers.get_by_name(name) - assert server is not None, f"Expect server with {server} to exist" - self._client.servers.power_off(server).wait_until_finished() - self._client.servers.power_on(server).wait_until_finished() - - -def run( - cmd: str, - shell: bool = False, - env: dict[str, str] = {}, - cwd: pathlib.Path | str | None = None, - capture_output: bool = False, -) -> subprocess.CompletedProcess[str]: - full_env = None - if env is not None: - full_env = os.environ.copy() - full_env.update(env) - - return subprocess.run( - cmd if shell else shlex.split(cmd), - check=True, - env=full_env, - cwd=cwd, - shell=shell, - text=True, - capture_output=capture_output, - ) - - -if __name__ == "__main__": - main() -- cgit v1.2.3