The Need
Laptop plus books came to nearly 30 jin (15 kg) in one bag — two 16-inch “bricks” — and I simply couldn’t carry it anymore. I recently came across Kasm Workspace; this container-based web app platform is a good fit for opening a browser on an iPad and connecting to my current workflow.
I use a fair number of applications day to day; 32-64G of RAM on the client is usually enough, and when it isn’t I can connect to a server.
After comparing options, I settled on a dedicated server from Hetzner. The model is the AX41-NVMe, with an AMD Ryzen 5 3600, 64G of RAM, two NVMe SSDs, one IPv4 address by default, and 1G up and down.
For the OS I picked Gentoo, which I’m more comfortable with. Hetzner doesn’t offer an automated Gentoo install, but you can boot into the Rescue System and install it manually.
Gentoo’s stage3 comes with either OpenRC or systemd as init. I use systemd day to day because it’s less hassle; I keep OpenRC for testing services in VMs.
For storage I used OpenZFS (ZoL is its former name), with native encryption on the root filesystem, except /boot.
/bootis unencrypted, so anyone with access to the disk can modify the kernel or initramfs and extract the ZFS passphrase the next time you boot — an Evil Maid attack. A machine on the public internet can mitigate this with UEFI Secure Boot; if you need more, look into booting GRUB from an encrypted partition.
The machine sits on the public internet, so I can’t assume it’s safe; encryption at least ensures that if the disk or a backup leaks, the data can’t be read directly. The question after encrypting is: how do you unlock the zpool at boot?
A keyfile has no good place to live; in the end I used a passphrase and built an initramfs with genkernel that includes zfs, ssh and networking. At boot it brings up the network, starts dropbear, waits for me to SSH in and unlock the zpool, then continues the normal boot.
Environment Setup
Hetzner’s Rescue System doesn’t ship ZFS tools by default. Run zpool and it prompts to install; accept the license (type y) and wait for it to finish. I didn’t take screenshots at the time.
zpool
Then create a directory for the ZFS cache file:
mkdir -pv /etc/zfs
zpool.cache records pool and vdev information; zfs-import-cache.service uses it to import the pool at boot, so a ZFS root filesystem doesn’t need an fstab entry. Non-ZFS partitions like /boot still do, and I’ll configure that later.
Installing Gentoo
Partitioning
I originally planned two zpools, using one disk for the system install, but hadn’t decided what to do with the second.
The AX41-NVMe has two NVMe drives, and a mirror would add a layer of redundancy and checksumming. I didn’t do that because I wanted to keep the second disk for a separate data pool. If you care more about data safety, just create the pool as a mirror — it’s less work.
Partition with fdisk or gdisk. I used GPT: MBR isn’t recommended on NVMe drives, GPT supports larger disks and more partitions, and UEFI boot generally goes with GPT.
gdisk /dev/nvme1n1
Partition table:
I didn’t notice at the time that I was partitioning the second disk, leaving the first one empty. It doesn’t affect the steps below, but don’t copy my mistake.
| Partition | Size | Type/File system | Mount point |
|---|---|---|---|
| nvme1n1p1 | 512M | EFI System Partition (ef00) | /boot/efi |
| nvme1n1p2 | 500M | ext4 (8300) | /boot |
| nvme1n1p3 | All remaining | Solaris Root (bf00) | zpool |
Initialize the filesystems on the EFI and boot partitions:
mkfs.vfat -F32 /dev/nvme1n1p1
mkfs.ext4 /dev/nvme1n1p2
Check the disk IDs:
ls -l /dev/disk/by-id/
Create the zpool:
zpool create -f -o ashift=12 -o cachefile=/etc/zfs/zpool.cache \
-O compression=zstd \
-O xattr=sa \
-O relatime=on \
-O acltype=posixacl \
-O dedup=off \
-O dnodesize=auto \
-O normalization=formD \
-O encryption=aes-256-gcm \
-O keyformat=passphrase \
-m none \
-R /mnt/gentoo rock /dev/disk/by-id/nvme-SAMSUNG_MZVL2512HCJQ-00B00_S675NX0T618385-part3
Going through the options one by one:
ashift=12: ashift is normally set automatically from the sector size the disk reports, but the reported value isn’t always accurate. Here I set it to 12 directly, i.e. 4K alignment. See the ZFS Tuning Guide and zpoolprops(7) for detailscompression=zstd: use zstd for compression; it balances speed and compression ratio well, see this post for real-world comparisonsxattr=sa: store extended attributes in the inode, avoiding the overhead of frequent xattr lookups on Linux, see openzfs/zfs#443 for whyrelatime=on: relatime, similar to ext4/XFSacltype=posixacl: enable POSIX ACLsdedup=off: with dedup on, identical data blocks are stored once, but the dedup table eats a lot of memory, so it’s generally not recommended in production. I turned it off herednodesize=auto: let ZFS choose the dnode size automatically, which helps workloads with lots of metadata such as container imagesnormalization=formD: normalize Unicode filenames so different encodings of the same name match. This property can’t be changed after creationencryption=aes-256-gcm: enable native encryption.encryption=onalso defaults to AES-256-GCM, so I spelled it out herekeyformat=passphrase: unlock with a passphraserock: pool name
After pressing Enter, enter the passphrase twice when prompted.
Create the datasets:
zfs create -o mountpoint=none -o canmount=off rock/os
zfs create -o mountpoint=/ rock/os/gentoo
Create the mount points and mount the boot partitions:
mkdir -pv /mnt/gentoo/boot
mount /dev/nvme1n1p2 /mnt/gentoo/boot
mkdir -pv /mnt/gentoo/boot/efi
mount /dev/nvme1n1p1 /mnt/gentoo/boot/efi
Partitioning is done at this point; check with lsblk that the sizes and mount points look right.
Installing stage3
Upstream stage3 comes in merged-usr and traditional layouts; I downloaded the amd64-systemd-mergedusr variant. A few commands pull the filename and path from latest-stage3.txt:
MIRRORS='https://bouncer.gentoo.org/fetch/root/all/releases/amd64/autobuilds'
ZIPFILENAME=`curl -L $MIRRORS/latest-stage3.txt |grep amd64-systemd-mergedusr|grep ^[0-9] |awk -F '[/ ]' '{if (NR==1) {print $2}}'`
FILENAME=`curl -L $MIRRORS/latest-stage3.txt 2>/dev/null|grep amd64-systemd-mergedusr |grep ^[0-9]|awk '{if (NR==1) {print $1}}'`
FILEURL="$MIRRORS/$FILENAME"
wget -T 3 -c -O /mnt/gentoo/$ZIPFILENAME $FILEURL
Extract stage3. Either cd to /mnt/gentoo first or pass -C to tar, so it doesn’t land somewhere else:
cd /mnt/gentoo
tar xpvf stage3-*.tar.xz --xattrs-include='*.*' --numeric-owner
Configuring Portage
MAKEOPTS and EMERGE_DEFAULT_OPTS control how much compilation runs in parallel. Portage is usually run as root, so these variables go in root’s shell config; if you run Portage as another user, put them in that user’s config instead.
First copy .bash_profile from /etc/skel. When you create a user, files in skel are copied to the new home directory too; here I’m doing it manually for root:
cp -v /mnt/gentoo/etc/skel/.bash_profile /mnt/gentoo/root/
Create and edit the file:
nano -w /mnt/gentoo/root/.bashrc
Contents:
export NUMCPUS=$(nproc)
export NUMCPUSPLUSONE=$(( NUMCPUS + 1 ))
export MAKEOPTS="-j${NUMCPUSPLUSONE} -l${NUMCPUS}"
export EMERGE_DEFAULT_OPTS="--jobs=${NUMCPUSPLUSONE} --load-average=${NUMCPUS}"
I added these to /etc/portage/make.conf:
# Accept all licenses
ACCEPT_LICENSE="*"
# No extra global USE flags
USE=""
# Use the stable branch
ACCEPT_KEYWORDS="amd64"
I accept all licenses and use the stable branch; I want a stable environment and don’t want to chase testing every day. I also don’t enable extra global USE flags — turn on what’s needed per package.
Create the Portage tree config directory and copy the default config over:
mkdir -p -v /mnt/gentoo/etc/portage/repos.conf
cp -v /mnt/gentoo/usr/share/portage/config/repos.conf /mnt/gentoo/etc/portage/repos.conf/gentoo.conf
Change sync-type:
nano -w /mnt/gentoo/etc/portage/repos.conf/gentoo.conf
Set sync-type to webrsync:
webrsyncdownloads snapshots over HTTPS rather than rsync, so thesync-uriline isn’t used in webrsync mode. I kept it in case I switch back to rsync later.
[DEFAULT]
main-repo = gentoo
[gentoo]
location = /var/db/repos/gentoo
sync-type = webrsync
sync-uri = rsync://rsync.gentoo.org/gentoo-portage
auto-sync = yes
sync-rsync-verify-jobs = 1
sync-rsync-verify-metamanifest = yes
sync-rsync-verify-max-age = 24
sync-openpgp-key-path = /usr/share/openpgp-keys/gentoo-release.asc
sync-openpgp-keyserver = hkps://keys.gentoo.org
sync-openpgp-key-refresh-retry-count = 40
sync-openpgp-key-refresh-retry-overall-timeout = 1200
sync-openpgp-key-refresh-retry-delay-exp-base = 2
sync-openpgp-key-refresh-retry-delay-max = 60
sync-openpgp-key-refresh-retry-delay-mult = 4
sync-webrsync-verify-signature = yes
Entering the chroot
Copy the DNS config and mount the necessary filesystems:
cp -v -L /etc/resolv.conf /mnt/gentoo/etc/
mount -v -t proc none /mnt/gentoo/proc
mount -v --rbind /sys /mnt/gentoo/sys
mount -v --rbind /dev /mnt/gentoo/dev
mount -v --make-rslave /mnt/gentoo/sys
mount -v --make-rslave /mnt/gentoo/dev
If you didn’t boot from a Gentoo LiveCD, /dev/shm may be a symlink to /run/shm; handle that as well:
test -L /dev/shm && rm /dev/shm && mkdir /dev/shm
mount --types tmpfs --options nosuid,nodev,noexec shm /dev/shm
chmod 1777 /dev/shm
Enter the chroot:
chroot /mnt/gentoo /bin/bash
If commands don’t work, source the environment first:
source /etc/profile
Then change PS1 so you can tell which environment you’re in:
export PS1="(chroot) $PS1"
Syncing the Portage Tree
emaint sync --auto
Updating the System
Once inside the chroot, do a full update first. The first one compiles a lot; be patient:
emerge -uDN @world
Locale and Time Zone
Set the time zone (Asia/Shanghai here):
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
Edit /etc/locale.gen and uncomment the locales you need:
nano -w /etc/locale.gen
At minimum, uncomment these lines:
en_US.UTF-8 UTF-8
zh_CN.UTF-8 UTF-8
Generate the locales:
locale-gen
Set the system default locale:
eselect locale set en_US.utf8
Reload the environment:
env-update && source /etc/profile && export PS1="(chroot) $PS1"
Installing Software
I manage common software with Portage sets. A set is a plain text file with one package per line under /etc/portage/sets/, and emerge @name installs the whole set. I split mine into:
- bootloader
- common-utils
- dev-utils
- filesystem
- kernel
The mapping is as follows:
| Package | sets | Purpose |
|---|---|---|
| sys-boot/grub | bootloader | Bootloader |
| app-portage/gentoolkit | common-utils | Tools that simplify Portage management |
| net-analyzer/mtr | common-utils | Network path testing tool |
| sys-apps/lm-sensors | common-utils | System sensor temperatures |
| net-misc/networkmanager | common-utils | Network management |
| app-admin/sysklogd | common-utils | Log management |
| sys-process/cronie | common-utils | Scheduled tasks |
| sys-apps/mlocate | common-utils | File indexing |
| net-misc/chrony | common-utils | Time synchronization |
| app-portage/pfl | common-utils | Look up which package owns a file |
| dev-util/pkgdev | common-utils | Toolkit for the Gentoo development workflow |
| app-eselect/eselect-repository | common-utils | Overlay management |
| app-admin/sudo | common-utils | sudo |
| net-dns/avahi | common-utils | Network discovery |
| app-shells/bash-completion | common-utils | Bash completion |
| app-misc/fastfetch | common-utils | System info display (neofetch is archived, replaced by the maintained fastfetch) |
| sys-process/htop | common-utils | View system load |
| sys-apps/usbutils | common-utils | USB device management |
| sys-fs/e2fsprogs | common-utils | ext filesystem tools, already included in @system by default |
| sys-process/btop | common-utils | View system load |
| sys-apps/edac-utils | common-utils | Userspace tools for the EDAC driver |
| app-containers/docker | dev-utils | Containers |
| app-containers/docker-compose | dev-utils | Container orchestration |
| app-editors/vim | dev-utils | vim editor |
| www-client/pybugz | dev-utils | Bugzilla command-line client |
| app-emulation/virt-manager | dev-utils | Virtual machine management |
| sys-apps/ripgrep | dev-utils | A faster grep replacement |
| dev-vcs/git | dev-utils | git tools |
| app-admin/ansible | dev-utils | Node management |
| app-containers/incus | dev-utils | Container and VM management (the fork the original community maintainers created after Canonical took over LXD) |
| app-misc/tmux | dev-utils | Session management |
| dev-libs/libisoburn | dev-utils | Needed by virt-install when installing from ISO |
| acct-group/libvirt | dev-utils | Group used by libvirtd |
| www-servers/nginx | dev-utils | Web server |
| app-crypt/certbot | dev-utils | Obtain SSL certificates |
| www-apps/hugo | dev-utils | Static site generator |
| sys-fs/zfs | filesystem | ZFS tools |
| sys-kernel/gentoo-kernel-bin | kernel | Kernel |
| sys-kernel/genkernel | kernel | Generate the initramfs |
Create the sets directory:
mkdir -pv /etc/portage/sets
/etc/portage/sets/common-utils:
app-portage/gentoolkit
net-analyzer/mtr
sys-apps/lm-sensors
net-misc/networkmanager
app-admin/sysklogd
sys-process/cronie
sys-apps/mlocate
net-misc/chrony
app-portage/pfl
dev-util/pkgdev
app-eselect/eselect-repository
app-admin/sudo
net-dns/avahi
app-shells/bash-completion
app-misc/fastfetch
sys-process/htop
sys-apps/usbutils
sys-fs/e2fsprogs
sys-process/btop
sys-apps/edac-utils
/etc/portage/sets/dev-utils:
app-containers/docker
app-containers/docker-compose
app-editors/vim
www-client/pybugz
app-emulation/virt-manager
sys-apps/ripgrep
dev-vcs/git
app-admin/ansible
app-containers/incus
app-misc/tmux
dev-libs/libisoburn
acct-group/libvirt
www-servers/nginx
app-crypt/certbot
www-apps/hugo
/etc/portage/sets/filesystem:
sys-fs/zfs
/etc/portage/sets/kernel:
sys-kernel/gentoo-kernel-bin
sys-kernel/genkernel
/etc/portage/sets/bootloader:
sys-boot/grub
Install common-utils:
emerge -av @common-utils
Install dev-utils:
emerge --autounmask-write=y --autounmask -av @dev-utils
If it tells you config files need updating, use etc-update and choose -5 to update them automatically.
Installing the Kernel
I used the binary gentoo-kernel-bin directly. Its initramfs USE flag calls dracut to generate an initramfs by default, but here I want genkernel to generate it, so I disabled it first:
mkdir -p /etc/portage/package.use
echo 'sys-kernel/gentoo-kernel-bin -initramfs' > /etc/portage/package.use/gentoo-kernel-bin
Install the kernel:
emerge -av @kernel
Installing ZFS
The ZFS modules have to be built against the kernel that’s already installed, so install it after the kernel:
emerge -av @filesystem
Generate a hostid:
zgenhostid
ZFS uses the host ID in /etc/hostid to tell whether a pool was exported by another machine. If this file is lost the pool may not import, so remember to back it up.
systemd
systemd needs some initialization too:
ln -sf /proc/self/mounts /etc/mtab
systemctl daemon-reexec
# Enable the zfs-related services from presets so I don't have to enable them by hand
systemctl preset-all
systemd-machine-id-setup
Interactively set the hostname, time zone and other basic settings:
systemd-firstboot --prompt --setup-machine-id
fstab Configuration
ZFS datasets are imported by zfs-import-cache.service and mounted by zfs-mount, so they don’t need fstab entries; but /boot and /boot/efi are ext4 and vfat and must be listed, or they won’t mount automatically at boot:
nano -w /etc/fstab
Add the following (adjust to your actual UUIDs or partition paths):
# /boot - ext4 partition
/dev/nvme1n1p2 /boot ext4 defaults,noatime 0 2
# /boot/efi - EFI System Partition
/dev/nvme1n1p1 /boot/efi vfat defaults 0 2
It’s worth checking the UUIDs with
blkidand replacing/dev/nvmeXnXpXwithUUID=xxxso mount points survive a change in disk order.
genkernel
genkernel’s --ssh reads /etc/dropbear/authorized_keys by default; put your public key there:
mkdir -pv /etc/dropbear/
vi /etc/dropbear/authorized_keys
Generate the initramfs. --zfs includes the ZFS tools and scripts, --ssh packs dropbear in:
genkernel --zfs --ssh initramfs
dropbear in the initramfs only accepts this public key and has password login disabled. It listens on a public port, so it’s best to restrict source IPs in the Hetzner Firewall rather than let scanners knock every day. The system’s own firewall isn’t up at this stage, so you only have the datacenter-side network firewall.
User Setup
Set a password for root. Password login over SSH is disabled, but single-user mode and emergency repairs still need it:
passwd root
Create the usual admin user:
chrisis my username; use your own.
useradd -m -G users,wheel,portage,usb,video,tty chris
Set the password:
passwd chris
Switch to that user:
su - chris
Create the .ssh directory and tighten permissions:
mkdir -pv .ssh
chmod 700 .ssh
Write the public key into .ssh/authorized_keys, then set it to 600:
vi .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
Exit the user:
exit
GRUB
Here /boot is a separate ext4 partition, so GRUB doesn’t need ZFS to read the kernel and initramfs; but enabling libzfs for GRUB does no harm and will work if I later move /boot into the pool:
echo 'sys-boot/grub libzfs' > /etc/portage/package.use/grub
Install GRUB:
emerge -av @bootloader
Edit /etc/default/grub and change GRUB_CMDLINE_LINUX:
The IP and gateway below are examples; replace them with your server’s public address. You can see them in the Rescue System with
ip addrandip route.
GRUB_CMDLINE_LINUX="dozfs root=ZFS=rock/os/gentoo ip=203.0.113.10/24 gk.net.gw=203.0.113.1 dosshd gk.sshd.port=2222 init=/lib/systemd/systemd net.ifnames=0"
dozfs: scan for importable zpools at bootdosshd: start dropbear in the initramfsroot=ZFS=rock/os/gentoo: specify the root datasetip=203.0.113.10/24: IP address during the initramfs stage (replace with the real one)gk.net.gw=203.0.113.1: gateway during the initramfs stage (replace with the real gateway)gk.sshd.port=2222: dropbear listen portinit=/lib/systemd/systemd: init to use after switching to the real systemnet.ifnames=0: use traditional NIC names likeeth0andeth1. Fine with a single NIC; with multiple NICs the names may not be stable
Install GRUB (UEFI):
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=gentoo
The amd64 profile builds in
efi-64by default. Ifgrub-installcomplains that it can’t findx86_64-efi, addGRUB_PLATFORMS="efi-64"tomake.conf, thenemerge --newuse sys-boot/gruband install again.
On older machines limited to BIOS, GPT also needs a roughly 1M partition of type
ef02(BIOS boot), thengrub-install /dev/nvme1n1. The current partition table doesn’t have one, so copying this directly will fail.
Generate the GRUB config:
grub-mkconfig -o /boot/grub/grub.cfg
Service Configuration
SSH
Turn off password login and allow keys only. Edit /etc/ssh/sshd_config:
PasswordAuthentication no
PermitEmptyPasswords no
PermitRootLogin prohibit-password
prohibit-password means root cannot log in with a password but can with a key. That way I can still get in as root in an emergency; if you want it stricter, change it to no and use a regular user with sudo day to day.
A few more settings are worth adding:
# Allow at most 3 authentication attempts
MaxAuthTries 3
# Start randomly dropping unauthenticated connections at 10, drop all at 60
MaxStartups 10:30:60
# Disconnect if authentication isn't done within 60 seconds
LoginGraceTime 60
Enable at boot:
systemctl enable sshd
NetworkManager
This machine gets its address over DHCP, so no extra configuration is needed:
systemctl enable NetworkManager
Docker
systemctl enable docker
usermod -aG docker chris
Membership in the docker group is effectively root: you can mount host directories and escalate privileges, so only add trusted users.
The root filesystem is ZFS, so Docker’s ZFS storage driver is a better fit:
mkdir -p /etc/docker
/etc/docker/daemon.json:
{
"storage-driver": "zfs"
}
With the ZFS driver, each image and container layer is a dataset/snapshot, so compression, snapshots and checksums come for free. Running overlay2 on ZFS stacks another union filesystem on top, which isn’t worth the performance cost, and many ZFS features go unused.
sudo Configuration
Edit /etc/sudoers with visudo; it checks the syntax on save, so a mistake won’t lock you out of sudo:
visudo
Let the wheel group escalate:
%wheel ALL=(ALL:ALL) ALL
This way every sudo asks for your own password. If you really need passwordless sudo, enable NOPASSWD for specific commands only, not the whole group.
Wrapping Up
Exit the chroot:
exit
Unmount the mount points and export the pool:
Run
zpool exportbefore rebooting so ZFS flushes its cache to disk and marks the pool as exported. Otherwise the new system may need-fto import it, and the cache file may not match.
umount -R /mnt/gentoo/boot/efi
umount -R /mnt/gentoo/boot
umount -R /mnt/gentoo
zpool export rock
Reboot:
reboot
Verification
After the reboot, keep pinging the public IP. If it responds, the initramfs has brought up the network; SSH into dropbear:
ssh [email protected] -p2222
Replace with your real IP.
Once connected, unlock the pool:
unlock-zfs
Enter the passphrase you set when creating the pool. After unlocking, continue the boot:
resume-boot
This command drops the SSH connection, which is normal. Once the system is up, log in as a regular user:
Then confirm the encryption status:
zpool status
zfs get -r encryption,keystatus rock
keystatus should be available, and both the pool and vdevs should be ONLINE in zpool status.
Configuration Backups
Things to back up:
/etc/sudoers/etc/default/grub- the whole
/etc/portagedirectory /etc/hostid(generated byzgenhostid, needed for ZFS import)/etc/dropbear/authorized_keys(public key for remote unlock in the initramfs)/etc/ssh/(SSH host keys, so fingerprints stay the same after a reinstall and you skip one alarm)/etc/zfs/zpool.cache(pool cache)/etc/fstab/etc/docker/daemon.json- each user’s
~/.ssh/authorized_keys
Back them up however you like. The root dataset can be snapshotted periodically and sent to another machine with zfs send; /boot is ext4 and not covered by snapshots, so back it up separately.
What to Do Next
- Configure UEFI Secure Boot with self-signed keys to block tampering with
/boot - Use fail2ban or nftables to curb SSH brute force; dropbear during the initramfs stage can only be restricted by source IP in the Hetzner Firewall
- Turn the second NVMe into a mirror, or create a separate data pool on it
- Use something like sanoid for automatic snapshots and send them to another machine with
zfs send
References
- Gentoo on ZFS
- Gentoo Wiki: PFL
- Gentoo Wiki: Pkgdev
- Gentoo Wiki: System set (Portage)
- Gentoo Wiki: Portage Tools
- Gentoo Wiki: Genkernel
- Gentoo Wiki: Systemd
- Gentoo Wiki: /etc/portage/sets
- Gentoo Wiki: Gentoolkit
- Gentoo Wiki: ZFS
- Gentoo Wiki: ZFS/rootfs
- Gentoo Wiki: EFI System Partition
- Gentoo Wiki: Localization Guide
- OpenZFS: Native Encryption
- OpenZFS: zpoolprops(7)
- Hetzner: Rescue System
Comments