Major rewrite: switching back to Arch from NixOS

This commit is contained in:
ItsDrike 2024-10-02 14:37:28 +02:00
parent df585b737b
commit 254181c0fc
Signed by: ItsDrike
GPG key ID: FA2745890B7048C0
121 changed files with 5433 additions and 2371 deletions

367
guides/01_INSTALLATION.md Normal file
View file

@ -0,0 +1,367 @@
# Installation
This installation guide will walk you through the process of setting up Arch
Linux, getting you from live cd to a working OS.
This guide is written primarily as a reference for myself, but it can certainly
be a useful resource for you too, if you want to achieve a similar setup.
This guide includes steps for full disk encryption, and sets up the system with
some basic tools and my zsh configuration.
## Partitioning
First thing we will need to do is set up partitions. To do so, I recommend using
`fdisk`. Assuming you have a single-disk system, you will want to create 3
partitions:
- EFI (1 GB)
- Swap (same size as your RAM, or more)
- Data (rest)
The swap partition is optional, however I do recommend creating it (instead of
using a swap file), as it will allow you to hibernate your machine.
> [!NOTE]
> Don't forget to also set the type for these partitions (`t` command in `fdisk`).
>
> - EFI partition type: EFI System (1)
> - Swap partition type: Linux swap (19)
> - Data partition type: Linux filesystem (20)
### File-Systems
Now we'll to create file systems on these partitions, and give them disk labels:
```bash
mkfs.fat -F 32 /dev/sdX1
fatlabel /dev/sdX1 EFI
mkswap -L SWAP /dev/diskX2
cryptsetup luksFormat /dev/sdX3 --label CRYPTFS
cryptsetup open /dev/disk/by-label/CRYPTFS crypfs
mkfs.btrfs -L FS /dev/mapper/cryptfs
```
> [!NOTE]
> For the LUKS encrypted partitions, I'd heavily recommend that you back up the
> LUKS headers in case of a partial drive failure, so that you're still able to
> recover your remaining data. To do this, you can use the following command:
>
> ```bash
> cryptsetup luksHeaderBackup /dev/device --header-backup-file /mnt/backup/file.img
> ```
### BTRFS Subvolumes
Now we will split our btrfs partition into the following subvolumes:
- root: The subvolume for `/`.
- data: The subvolume for `/data`, containing my personal files, which should be
and backed up.
- snapshots: A subvolume that will be used to store snapshots (backups) of the
other subvolumes
```bash
mount /dev/mapper/cryptfs /mnt
btrfs subvolume create /mnt/root
btrfs subvolume create /mnt/data
btrfs subvolume create /mnt/snapshots
umount /mnt
```
### Mount the partitions and subvolumes
<!-- markdownlint-disable MD028 -->
> [!NOTE]
> Even though we're specifying the `compress` flag in the mount options of each
> btrfs subvolume, somewhat misleadingly, you can't actually use different
> compression levels for different subvolumes. Btrfs will share the same
> compression level across the whole partition, so it's pointless to attempt to
> set different values here.
> [!NOTE]
> You may have seen others use btrfs options such as `ssd`, `discard=async` and
> `space_cache=v2`. These are all default (with the `ssd` being auto-detected),
> so specifying them is pointless now.
<!-- markdownlint-enable MD028 -->
```bash
mount -o subvol=root,compress=zstd:3,noatime /dev/mapper/cryptfs /mnt
mount --mkdir -o subvol=home,compress=zstd:3,noatime /dev/mapper/cryptfs /mnt/data
mount --mkdir -o subvol=snapshots,compress=zstd:3,noatime /dev/mapper/cryptfs /mnt/snapshots
mount --mkdir -o compress=zstd:3,noatime /dev/mapper/cryptfs /mnt/.btrfs
mount --mkdir /dev/disk/by-label/EFI /mnt/efi
mkdir /mnt/efi/arch
mount --mkdir --bind /mnt/efi/arch /mnt/boot
swapon /dev/disk/by-label/SWAP
```
## Base installation
```bash
reflector --save /etc/pacman.d/mirrorlist --latest 10 --protocol https --sort rate
pacstrap -K /mnt base linux linux-firmware linux-headers amd-ucode # or intel-ucode
genfstab -U /mnt >> /mnt/etc/fstab
arch-chroot /mnt
```
Configure essentials
```bash
pacman -S git btrfs-progs neovim
ln -sf /usr/share/zoneinfo/CET /etc/localtime
hwclock --systohc
sed -i 's/^#en_US.UTF-8/en_US.UTF-8/g' /etc/locale.gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf
locale-gen
echo "pc" > /etc/hostname
passwd
```
## Basic configuration
Clone my dotfiles and run the install script
```bash
git clone --recursive https://github.com/ItsDrike/dotfiles ~/dots
cd ~/dots
./install_root.sh
```
Exit and reenter chroot, this time into zsh shell
```bash
exit
arch-chroot /mnt zsh
```
Create non-privileged user
```bash
useradd itsdrike
usermod -aG wheel itsdrike
install -o itsdrike -g itsdrike -d /home/itsdrike
passwd itsdrike
chsh -s /usr/bin/zsh itsdrike
su -l itsdrike # press q or esc in the default zsh options
```
Setup user account
```bash
git clone --recursive https://github.com/ItsDrike/dotfiles ~/dots
cd ~/dots
./install_user.sh
```
Exit (logout) the user and relogin, this time into configured zsh shell
```bash
exit
su -l itsdrike
```
Install LazyVim
```bash
git clone https://github.com/ItsDrike/lazyvim ~/.config/nvim
```
## Fstab adjustments
Finally, we'll want to make some slight modifications to `/etc/fstab` file, so
that we're using labels instead of UUIDs to mount our devices and also fix the
permissions for the EFI mount-point (the fmask & dmask options), as by default,
they're way too permissive. This is how I like to structure my fstab:
<!-- markdownlint-disable MD013 -->
```text
# Static information about the filesystems.
# See fstab(5) for details.
#
# <file system> <dir> <type> <options> <dump> <pass>
# region: Physical partitions
# /dev/nvme1n1p1 LABEL=EFI UUID=A34B-A020
/dev/disk/by-label/EFI /efi vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro 0 2
# /dev/nvme1n1p2 LABEL=SWAP UUID=d262a2e5-a1a3-42b1-ac83-18639f5e8f3d
/dev/disk/by-label/SWAP none swap defaults 0 0
# endregion
# region: BTRFS Subvolumes
# /dev/mapper/cryptfs LABEL=FS UUID=bffc7a62-0c7e-4aa9-b10e-fd68bac477e0
/dev/mapper/cryptfs / btrfs rw,noatime,compress=zstd:1,subvol=/root 0 1
/dev/mapper/cryptfs /data btrfs rw,noatime,compress=zstd:1,subvol=/data 0 2
/dev/mapper/cryptfs /snapshots btrfs rw,noatime,compress=zstd:1,subvol=/snapshots 0 2
/dev/mapper/cryptfs /.btrfs btrfs rw,noatime,compress=zstd:1 0 2
# endregion
# region: Bind mounts
# Write kernel images to /efi/arch, not directly to efi system partition (esp), to avoid conflicts when dual booting
/efi/arch /boot none rw,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro,bind 0 0
# endregion
```
<!-- markdownlint-enable MD013 -->
## Ask for LUKS password from initramfs
Ask for encryption password of the root partition in early userspace (only
relevant if you're using LUKS encryption), you'll also need to set cryptdevice
kernel parameter, specifying the device that should be unlocked here, and the
device mapping name. (shown later)
```bash
# Find the line with HOOKS=(...)
# Add `keyboard keymap` after `autodetect` (if these hooks are already there,
# just keep them, but make sure they're after `autodetect`).
# Lastly add `encrypt` before `filesystems`.
nvim /etc/mkinitcpio.conf
```
This will configure `mkinitcpio` to build support for the keyboard input, and
for decrypting LUKS devices from within the initial ramdisk environment.
If you wish, you can also follow the instructions below to auto-enable numlock:
```bash
sudo -u itsdrike paru -S mkinitcpio-numlock
# Go to HOOKS and add `numlock` after `keyboard` in:
nvim /etc/mkinitcpio.conf
```
Now regenerate the initial ramdisk environment image:
```bash
mkinitcpio -P
```
## Configure systemd-boot bootloader
> [!NOTE]
> If you wish to use another boot loader (like GRUB), just follow the Arch Wiki.
> This guide will only cover systemd-boot
### Make sure you're using UEFI
As a first step, you will want to confirm that you really are on a UEFI system.
If you're using any recent hardware, this is very likely the case. Nevertheless,
let's check and make sure:
```bash
bootctl status
```
Make sure the `Firmware` is reported as `UEFI`.
If you're still using BIOS instead of UEFI, you should check the wiki for
instructions on how to set up systemd-boot or choose a different boot manager,
that is more suited for BIOS firmware.
### Install systemd-boot
Install systemd-boot to the EFI system partition (ESP)
```bash
bootctl --esp-path=/efi install
# This might report a warning about permissions for the /efi mount point,
# these were addressed in the fstab file above (changed fmask and dmask),
# if you copied those to your fstab, the permissions will be fixed after reboot
```
Add boot menu entries
(Note that we're using LABEL= for cryptdevice, for which `udev` must be before
the `encrypt` hook in mkinitcpio `HOOKS`. This should however be the case by default.
If you wish, you can also use UUID= or just /dev/XYZ here)
Create a new file - `/efi/loader/entries/arch.conf`, with:
```bash
title Arch Linux
sort-key 0
linux /arch/vmlinuz-linux
initrd /arch/amd-ucode.img
initrd /arch/initramfs-linux.img
options cryptdevice=LABEL=CRYPTFS:cryptfs:allow-discards
options root=/dev/mapper/cryptfs rootflags=subvol=/root
options rw loglevel=3
```
And finally configure loader - `/efi/loader/loader.conf` (overwrite the contents):
```bash
default arch-hyprland.conf
timeout 4
console-mode auto
editor yes
auto-firmware yes
beep no
```
## Reboot
Take a deep breath.
```bash
exit # go back to live iso (exit chroot)
reboot
```
## Post-setup
Log in as an unpriviledged user, and:
Enable Network Time Protocol (time synchronization)
```bash
sudo timedatectl set-ntp true
timedatectl status
```
Connect to a wifi network
```bash
nmtui
```
## Graphical User Interface
Finally, you can run the `install_gui.sh` script in my dotfiles, to get all of
the packages necessary for a proper graphical experience with Hyprland WM and a
bunch of applications/toolings that I like to use.
This final script is definitely the most opinionated one and you might want to
make adjustments to it, depending on your preferences.
## We're done
If you got this far, good job! You should now be left with a fully functional
Arch Linux system, ready for daily use.
That said, you might find some of the other guides helpful if you wish to tinker
some more:
- If you have more encrypted partitions than just root, you should check out:
[automounting other encrypted
partitions](./02_AUTOMOUNTING_ENCRYPTED_PARTITIONS.md).
- You may be also interested in [setting up secure boot](./04_SECURE_BOOT.md).
- Having your encrypted root partition unlock automatically without compromising
on safety through [tpm unlocking](./06_TPM_UNLOCKING.md).
- The [theming guide](./99_THEMING.md), explaining how to configure qt, gtk,
cursor and fonts correctly.
- Setting up a display manager (DM) with optional automatic login: [greetd
guide](./99_GREETD.md)
- On laptops, you should check the [battery optimizations
guide](./99_BATTERY_OPTIMIZATIONS.md)

View file

@ -0,0 +1,138 @@
# Auto-mounting other encrypted partitions
If you've set up multiple encrypted partitions (a common reason to do so is
having multiple drives), you will likely want to have these other partitions
mounted automatically after the root partition, during the boot process.
> [!TIP]
> You can safely skip this guide if you only have a single encrypted partition
> (with the root).
## /etc/crypttab
Obviously, with encrypted partitions, you can't simply specify the mounting
instructions into your `/etc/fstab`, instead, there is a special file designed
precisely for this purpose: `/etc/crypttab`. Just like with `fstab`, systemd
will read `crypttab` during boot and attempt to mount the entries inside of it.
From here, you can add entries for mounting your encrypted partitions, like so:
```txt
# Configuration for encrypted block devices.
# See crypttab(5) for details.
# NOTE: Do not list your root (/) partition here, it must be set up
# beforehand by the initramfs (/etc/mkinitcpio.conf).
# <name> <device> <password> <options>
cryptdata LABEL=DATA none discard
```
> [!NOTE]
> The `discard` option is specified to enable TRIM on SSDs, which should improve
> their lifespan. It is not necessary if you're using an HDD.
The `<name>` option specifies the name of the decrypted mapper device, so in
this case, the decrypted device would be in `/dev/mapper/cryptdata`. We can then
add mounting instructions into `/etc/fstab`, that work with this mapper device.
Specifying a partition in here will result in you being prompted for a
decryption password each time during boot. If you only have one encrypted
partition like this, and your root partition isn't encrypted, this will be
sufficient for you.
## Key files
That said, if you have multiple encrypted partitions, or your root partition is
encrypted too, you might find it pretty annoying to have to enter a password for
each of your encrypted partitions every time.
For this reason, crypttab includes the `<password>` option, which we originally
left as `none`. We can use this field to specify a path to a "key file". This is
basically just a file that holds the encryption password.
> [!IMPORTANT]
> Storing the decryption password in a key file like this can only be done
> safely if that key file is stored on another encrypted partition, which we
> decrypted in another way (usually by being prompted for the password).
>
> In this example, we'll be storing the key files in `/etc/secrets`, which is
> safe as our root partition is encrypted.
LUKS encryption has support for having multiple keys for the same parition.
We'll utilize this support and add 2nd key slot to all of the partitions that we
wish to auto-mount.
```bash
mkdir -p /etc/secrets
dd if=/dev/random bs=4096 count=1 of=/etc/secrets/keyFile-data.bin
chmod -R 400 /etc/secrets
chmod 700 /etc/secrets
```
The bs argument signifies a block size (in bits), so this will create 4096-bit keys.
Now we can add this key into our LUKS encrypted data partition:
```bash
cryptsetup luksAddKey /dev/disk/by-label/DATA --new-keyfile /etc/secrets/keyFile-data.bin
```
Finally, we'll modify the `/etc/crypttab` record and add our new keyfile as the
password for this partition:
```txt
# Configuration for encrypted block devices.
# See crypttab(5) for details.
# NOTE: Do not list your root (/) partition here, it must be set up
# beforehand by the initramfs (/etc/mkinitcpio.conf).
# <name> <device> <password> <options>
cryptdata LABEL=DATA /etc/secrets/keyFile-data.bin discard
```
### /etc/fstab
While the crypttab file opens the encrypted block devices and creates the mapper
interfaces for them, to mount those to a concrete directory, we still use
/etc/fstab. Below is the /etc/fstab that I use on my system:
<!-- markdownlint-disable MD010 MD013 -->
```text
# Static information about the filesystems.
# See fstab(5) for details.
# <file system> <dir> <type> <options> <dump> <pass>
# region: Physical partitions
# /dev/nvme0n1p2 LABEL=SWAP UUID=d262a2e5-a1a3-42b1-ac83-18639f5e8f3d
/dev/disk/by-label/SWAP none swap defaults 0 0
# /dev/nvme0n1p1 LABEL=EFI UUID=44E8-EB26
/dev/disk/by-label/EFI /efi vfat rw,relatime,fmask=0137,dmask=0027,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro 0 2
# endregion
# region: BTRFS subvolumes on /dev/disk/by-label/ARCH (decrypted from ARCH_LUKS)
# /dev/mapper/cryptfs LABEL=ARCH UUID=bffc7a62-0c7e-4aa9-b10e-fd68bac477e0
/dev/mapper/cryptfs / btrfs rw,noatime,compress=zstd:1,ssd,space_cache=v2,subvol=/@ 0 1
/dev/mapper/cryptfs /home btrfs rw,noatime,compress=zstd:1,ssd,space_cache=v2,subvol=/@home 0 1
/dev/mapper/cryptfs /var/log btrfs rw,noatime,compress=zstd:2,ssd,space_cache=v2,subvol=/@log 0 1
/dev/mapper/cryptfs /var/cache btrfs rw,noatime,compress=zstd:3,ssd,space_cache=v2,subvol=/@cache 0 1
/dev/mapper/cryptfs /tmp btrfs rw,noatime,compress=no,ssd,space_cache=v2,subvol=/@tmp 0 1
/dev/mapper/cryptfs /data btrfs rw,noatime,compress=zstd:5,ssd,space_cache=v2,subvol=/@data 0 2
/dev/mapper/cryptfs /.btrfs btrfs rw,noatime,ssd,space_cache=v2 0 2 # btrfs root
# endregion
# region: Bind mounts
# Write kernel images to /efi/arch, not directly to efi system partition (esp), to avoid conflicts when dual booting
/efi/arch-1 /boot none rw,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro,bind 0 0
# endregion
```
<!-- markdownlint-enable MD010 MD013 -->

View file

@ -0,0 +1,205 @@
# Unified Kernel Images (UKI) booting
A Unified Kernel Image is a single executable (`.efi` file), which can be
booted directly from UEFI firmware, or be automatically sourced by boot loaders
with no extra configuration.
> [!NOTE]
> If you're still using BIOS, you will not be able to set up UKIs, they require
> UEFI.
A UKI will include:
- a UEFI stub loader like (systemd-stub)
- the kernel command line
- microcode
- an initramfs image
- a kernel image
- a splash screen
The most common reason why you might want to use UKIs is secure boot. That's
because a UKI is something that can be signed and represents an immutable
executable used for booting into your system.
This is good, because with a standalone bootloader, you would be allowed you to
edit the kernel parameters, or even change the kernel image by editing the
configuration inside of the (unencrypted) EFI partition. This is obviously
dangerous, and we don't want to allow this.
## Define kernel command line
Since UKI contains the kernel command line, we will need to define it so that
when the image is being built, it can pick it up.
This is a crucial step especially when you have encryption set up, as without
it, the kernel wouldn't know what root partition to use.
To set this up, we will use `/etc/kernel/cmdline`.
This is how I setup my kernel arguments (If you're unsure what arguments you
need, just check your current systemd-boot configuration, if you followed [the
INSTALLATION guide](./01_INSTALLATION.md), you will have it in:
`/efi/loader/entries/arch.conf`, all of the `options=` line contain
kernel command line args):
```bash
echo "rw loglevel=3" > /etc/kernel/cmdline
echo "cryptdevice=LABEL=CRYPTFS:cryptfs:allow-discards" >> /etc/kernel/cmdline
echo "root=/dev/mapper/cryptfs rootflags=subvol=/@" >> /etc/kernel/cmdline
```
<!-- markdownlint-disable MD028 -->
> [!TIP]
> If you prefer, you can also create `/etc/kernel/cmdline.d` directory, with
> individual files for various parts of the command line. At the end, all of the
> options from all files in this directory will be combined.
>
> You might find this useful if you set a lot of kernel parameters, so you might
> have for example: `root.conf`, `apparmor.conf`, ...
> [!IMPORTANT]
> Note that you **shouldn't** be specifying the `cryptdevice` or `root` kernel
> parameters if you're using `systemd` initramfs, rather than `BusyBox` one
> (which mkinitramfs generates by default).
>
> That said, you will still need `rootflags` to select the btrfs subvolume
> though, unless the root partition is your default subvolume.
>
> If you aren't sure which initramfs you're using, it's probably `BusyBox`.
<!-- markdownlint-disable MD028 -->
## Modify the linux preset for mkinitcpio to build UKIs
Now open `/etc/mkinitcpio.d/linux.preset`, where you'll want to:
- Uncomment `ALL_config`
- Comment `default_image`
- Uncomment `default_uki` (unified kernel image)
- Uncomment `default_options`
- Comment `fallback_image`
- Uncomment `fallback_uki`
## Recreate /efi
First, we'll need to unmount `/boot`, which is currently bind-mounted to
`/efi/EFI/arch`. This is because we'll no longer be storing the kernel,
initramfs, nor the microcode in the EFI partition at all. The EFI partition will
now only contain the final UKI, the rest can be left in `/boot`, which will now
be a part of the root partition, not mounted anywhere.
```bash
umount /boot
vim /etc/fstab # remove the bind mount entry for /boot
```
Now, we will clear the EFI partition and install `systemd-boot` again from
scratch:
```bash
rm -rf /efi/*
```
Now, we will create a `/efi/EFI/Linux` directory, which will contain all of our
UKIs. (You can change the location in `/etc/mkinitcpio.d/linux.preset` if you
wish to use some other directory in the EFI partition, or you want a different
name for the UKI file. Note that it is recommended that you stick with the same
directory, as most boot loaders will look there when searching for UKIs.)
```bash
mkdir -p /efi/EFI/Linux
```
Finally, we will reinstall the kernel and microcode, re-populating `/boot` (now
on the root partition).
This will also trigger a initramfs rebuild, which will now create the UKI image
based on the `linux.preset` file.
```bash
pacman -S linux amd-ucode # or intel-ucode
```
## Proceeding without a boot manager
Because the Unified Kernel Images can actually be booted into directly from the
UEFI, you don't need to have a boot manager installed at all. Instead, you can
simply add the UKIs as entries to the UEFI boot menu.
> [!NOTE]
> I prefer to still use a full boot manager alongside UKIs, as they allow you to
> have a nice graphical boot menu, from which you can dynamically override the
> kernel parameters during boot, or have extra entries for different operating
> systems, without having to rely on the specific implementation of the boot
> menu in your UEFI firmware (which might take really long to open, or just
> generally not provide that good/clean experience).
>
> Do note though that going without a boot manager is technically a safer
> approach, as it cuts out the middle-man entirely, whereas with a boot manager,
> your UEFI firmware will be booting the EFI image of your boot manager, only to
> then boot your own EFI image, being the UKI.
>
> Regardless, I still like to use `systemd-boot`, instead of booting UKIs
> directly. If you wish to do the same, skip this section.
<!-- markdownlint-disable MD013 -->
```bash
pacman -S efibootmgr
efibootmgr --create --disk /dev/disk/nvme0n1 --part 1 --label "Arch Linux" --loader 'EFI\Linux\arch-linux.efi' --unicode
efibootmgr -c -d /dev/disk/nvme0n1 -p 1 -L "Arch Linux Fallback" -l 'EFI\Linux\arch-linux-fallback.efi' -u
pacman -R systemd-boot
```
<!-- markdownlint-enable MD013 -->
You can also specify additional kernel parameters / override the default ones in
the UKI, by simply adding a string as a last positional argument to the
`efibootmgr` command, allowing you to create entires with different kernel
command lines easily.
## Proceeding with a boot manager
> [!NOTE]
> This is an alternative to the above, see the note in the previous section to
> understand the benefits/cons of either approach.
Most boot managers can handle loading your UKIs. The boot manager of my choice
is `systemd-boot`, but if you wish, you should be able to use grub, or any other
boot manager too. That said, this guide will only mention `systemd-boot`.
All that we'll need to do now is installing systemd-boot, just like during the
initial OS installation:
````bash
```bash
bootctl install --esp-path=/efi
````
We can now reboot. Systemd-boot will pick up any UKI images in `/efi/EFI/Linux`
automatically (this path is hard-coded), even without any entry configurations.
That said, if you do wish to do so, you can still add an explicit entry for your
configuration in `/efi/loader/entries/arch.conf`, like so:
```text
title Arch Linux
sort-key 0
efi /EFI/Linux/arch-linux.efi
# If you wish, you can also specify kernel options here, it will
# append/override those in the UKI image
#options rootflags=subvol=/@
#options rw loglevel=3
```
Although do note that if your UKI image is stored in `/efi/EFI/Linux`, because
systemd-boot picks it up automatically, you will see the entry twice, so you'll
likely want to change the target directory for the UKIs (in
`/etc/mkinitcpio.d/linux.preset`) to something else.
I however wouldn't recommend this approach, and I instead just let systemd-boot
autodetect the images, unless you need something specific.
If everything went well, you should see a new systemd based initramfs, from
where you'll be prompted for the LUKS2 password.

186
guides/04_SECURE_BOOT.md Normal file
View file

@ -0,0 +1,186 @@
# Secure Boot
This guide will show you how to set up UEFI Secure Boot with Arch Linux. Once
finished, you will be left with a system that doesn't allow booting any
untrusted EFI images (other operating systems, fraudulently modified kernels,
...) on your machine.
This guide assumes you're following from the
[INSTALLATION](./01_INSTALLATION.md) guide and that you're using [UNIFIED KERNEL
IMAGES](./03_UNIFIED_KERNEL_IMAGES.md) (UKIs) for booting.
## Security requirements
Meeting these requirements is optional, as it is possible to set up secure boot
without them. That said, if you don't meet these, setting up secure boot will
not be a very effective security measure and it might be more of a time waste
than a helpful means of enhancing your security.
First requirement is to set up a **BIOS Password**. This is a password that you
will be asked for every time you wish to enter the BIOS (UEFI). This is
necessary, as without it, an attacker could very easily just go to the BIOS and
disable Secure Boot.
The second requirement is having **disk encryption**, at least for the root
partition. This is important, because the UEFI signing keys will be stored here,
and you don't want someone to potentially be able to get access to them, as it
would allow them to sign any malicious images, making them pass secure boot.
> [!WARNING]
> Even after following all of these, you should be aware that Secure Boot isn't
> an unbreakable solution. In fact, if someone is able to get a hold of your
> machine, they can simply pull out the CMOS battery, which usually resets the
> UEFI. That means turning off Secure Boot, and getting rid of the BIOS
> password.
>
> While Secure Boot is generally a good extra measure to have, it is by no means
> a reliable way to completely prevent others from ever being able to boot
> untrusted systems, unless you use a specialized motherboard, which persists
> the UEFI state.
## Enter Setup mode
To allow us to upload new signing keys into secure boot, we will need to enter
"setup mode". This should be possible by going to the Secure Boot category in
your UEFI settings, and clicking on Delete/Clear certificates, or there could
even just be a "Setup Mode" option directly.
Once enabled, save the changes and boot back into Arch linux.
```bash
pacman -S sbctl
sbctl status
```
Make sure that `sbctl` reports that Setup Mode is Enabled.
## Create Secure Boot keys
We can now create our new signing keys for secure boot. These keys will be
stored in `/usr/share/secureboot` (so in our encrypted root partition). Once
created, we will add (enroll) these keys into the UEFI firmware (only possible
when in setup mode)
```bash
sbctl create-keys
sbctl enroll-keys -m
```
<!-- markdownlint-disable MD028 -->
> [!WARNING]
> The `-m` option (also known as `--microsoft`) will make sure to also include
> the Microsoft signing keys. This is required by most motherboards, not using
> it could brick your device.
> [!NOTE]
> If you encounter "File is immutable" warnings after running sbctl, it should
> be safe to simply add the `-i` (or `--ignore-immutable`) flag, which will run
> `chattr` and remove the immutable flags from these files for you.
>
> You can also do so manually with `chattr -i [file]` for all the listed
> immutable files and then re-run the enroll-keys command.
>
> This happens because the Linux kernel will sometimes mark the runtime EFI
> files as immutable for security - to prevent bricking the device with just `rm
-rf /*`, or similar stupid commands, however since we trust that `sbctl` will
> work and won't do anything malicious, we can just remove the immutable flag,
> and re-running will now work).
>
> If you still encounter errors even with this flag, it means you have probably
> done something wrong when entering the setup mode. Try looking for a option
> like "Reset keys" in your UEFI, then try this again.
<!-- markdownlint-enable MD028 -->
## Sign the bootloader and Unified Kernel Images
Finally then, we can sign the `.efi` executables that we'd like to use:
```bash
sbctl sign -s -o /usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed /usr/lib/systemd/boot/efi/systemd-bootx64.efi
sbctl sign -s /efi/EFI/BOOT/BOOTX64.EFI
sbctl sign -s /efi/EFI/systemd/systemd-bootx64.efi
sbctl sign -s /efi/EFI/Linux/arch-linux.efi
sbctl sign -s /efi/EFI/Linux/arch-linux-fallback.efi
```
(If you're booting directly from UKI images, only sign those - in `/efi/EFI/Linux`)
The `-s` flag means save: The files will be automatically re-signed when we
update the kernel (via a sbctl pacman hook).
> [!TIP]
> To make sure that this is the case, we can run `pacman -S linux` and check
> that messages about image signing appear.
>
> They should look something like this:
>
> ```text
> Signing /efi/EFI/Linux/arch-linux.efi
> ✓ Signed /efi/EFI/Linux/arch-linux.efi
> ...
> Signing /efi/EFI/Linux/arch-linux-fallback.efi
> ✓ Signed /efi/EFI/Linux/arch-linux-fallback.efi
> ...
> File has already been signed /efi/EFI/Linux/arch-linux-fallback.efi
> File has already been signed /efi/EFI/Linux/arch-linux.efi
> File has already been signed /efi/EFI/systemd/systemd-bootx64.efi
> File has already been signed /usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed
> File has already been signed /efi/EFI/BOOT/BOOTX64.EFI
> ```
When done, we can make sure that everything that needed to be signed really was
signed with:
```bash
sbctl verify
```
You can also check that setup mode got disabled after enrolling the keys:
```bash
sbctl status
```
Setup mode status should now report as `Disabled`. (Secure boot will still not
appear as enabled though.)
## Reboot with secure boot
We should now be ready to enable secure boot, as our `.efi` images were signed,
and the signing key was enrolled to UEFI firmware. So, all that remains is:
```bash
reboot
```
Boot into UEFI, go to the Secure Boot settings and enable it. (It might get
enabled automatically on some UEFI firmware after setup mode, but it's not
always the case.)
### Verify it worked
To make sure that it worked as expected, and you're booted with secure-boot
enabled, you can now run:
```bash
sbctl status
```
It should report `Secure Boot: enabled` or `Secure Boot: enabled (user)`.
## Why bother?
As I mentioned, secure boot can be bypassed if someone tries hard enough
(pulling the CMOS battery). That then brings to question whether it's even worth
it to set it up, when it doesn't really give you that much.
On its own, I probably wouldn't bother with setting up secure-boot, however
secure boot allows me to set up TPM (Trusted Platform Module) to automatically
release the decryption keys for my LUKS encrypted root partition, in a secure
way. This means I won't have to type my disk password every time I boot which is
actually the primary reason why I like having secure-boot enabled.
For more information on this, check out the follow-up guide:
[TPM_UNLOCKING](./06_TPM_UNLOCKING.md).

View file

@ -0,0 +1,211 @@
# Systemd initramfs
The initial ramdisk is in essence a very small environment (early userspace)
whihc loads various kernel modules and sets up necessary things before handing
control over to `init` program (systemd).
By default, Arch Linux uses a BusyBox+udev based initial ramdisk, generated by
`mkinitcpio`. This default initrd is essentially just a small script, that
executes other scripts, called hooks.
As an alternative to this, it's possible to have systemd run from the very
start, during that initial ramdisk phase. With this approach, the tasks ran at
this phase are determined by regular systemd unit files.
## Why?
Obviously, BusyBox initramfs works just fine, so why would you want to switch?
Well, there's a few reasons:
- **Consistency across boot phases:** The same systemd process that handles your
system after boot can also manage the early userspace during boot, providing
consistency in handling services, devices and dependencies throughout the
entire boot process.
- **Simplified troubleshooting:** The tools and logs available during the boot
process will be the same as those used once the system is fully booted,
allowing you to troubleshoot problems with familiar tools (`journalctl`,
`systemctl`, ...)
- **Consistent Unit Files:** Since systemd uses the same unit files in the
initramfs as it does in the fully booted system, the configuration for many
tasks (like mounting filesystems) is unified, reducing duplication of
configuration files.
- **TPM Unlocking Support:** Systemd has built-in support for requesting data
from TPM, allowing for a setup with TPM auto-unlocking an encrypted root
partition, without having to specify the decryption password.
- **Parallel Service Startup:** Systemd is known for the ability to start
services in parallel, which can potentially **speed up the boot process**
compared to sequential script-based approach.
- **Integrated Mount Handling:** With systemd, managing complex mount setup
(e.g. LVM RAID) can be more seamless, since it natively supports these and can
handle them with less custom scripting.
That said, it's important to also mention some downsides and reasons why you
might not want to use systemd-based initramfs:
- **Simplicity:** If you prefer a simple, more minimalistic approach,
BusyBox-based initramfs might be sufficient and easier to manage.
- **Size:** A systemd-based initramfs might be larger than a minimal
BusyBox-based initramfs, which could be a concern on systems with very limited
space.
- **Compatibility:** If you're running some custom scripts or hooks, they might
not work with a systemd-based initramfs.
## Switching to systemd initramfs
Open `/etc/mkinitcpio.conf` and find a line that starts with `HOOKS=`
- Change `udev` to `systemd`
- Change `keymap consolefont` to `sd-vconsole`
- Add `sd-encrypt` before `block`, and remove `encrypt`
- If you were using `mkinitcpio-numlock`, also remove `numlock`, it doesn't work
with systemd (we'll go over how to auto-enable numlock later)
Additionally, with systemd initramfs, you shouldn't be specifying `root` nor
`cryptdevice` kernel arguments, as systemd can actually pick those up
automatically (they'll be discovered by [systemd-cryptsetup-generator] and
auto-mounted from initramfs via [systemd-gpt-auto-generator]). We will however
still need the `rootflags` argument for selecting the btrfs subvolume (unless
your default subvolume is the root partition subvolume).
[systemd-cryptsetup-generator]: https://wiki.archlinux.org/title/Dm-crypt/System_configuration#Using_systemd-cryptsetup-generator
[systemd-gpt-auto-generator]: https://wiki.archlinux.org/title/Systemd#GPT_partition_automounting
So, let's edit our kernel parameters:
```bash
echo "rw loglevel=3" > /etc/kernel/cmdline # overwrite the existing cmdline
echo "rootflags=subvol=/@" >> /etc/kernel/cmdline
```
You'll also need to modify the `/etc/fstab`, as systemd will not use the
`/dev/mapper/cryptfs` name, but rather you'll have a `/dev/gpt-auto-root`
(there'll also be `/dev/gpt-auto-root-luks`, which is the encrypted partition).
If you prefer using a mapper device, you can also use `/dev/mapper/root`.
Alternatively, you can use the label to mount. (if you followed the
installation guide, that would be `/dev/disk/by-label/FS`.)
```bash
vim /etc/fstab
```
Finally, regenerate the initramfs with: `pacman -S linux` (you could also do
`mkinitcpio -P`, however that won't trigger the pacman hook which auto-signs our
UKI images for secure boot, so you'd have to re-sign them with `sbctl` manually,
if you're using secure-boot) and reboot to check if it worked.
## Activating numlock
Since we had to remove `mkinitcpio-numlock`, as that hook isintended for BusyBox
based initrd, we'll want to have an alternative available.
First though, we should also remove the package: `pacman -R mkinitcpio-numlock`.
### The simple, but imperfect option
There is a `systemd-numlockontty` AUR package which creates a systemd service
that enables numlock in TTYs after booting (you'll need to enable it), this
however doesn't happen in initramfs directly, only afterwards.
Depending on what you will need, this may be sufficient. If you are going to be
typing a decryption password at this early stage and you wish to have numlock
support there, you will need to do some more work.
### The proper solution
To enable numlock before you're prompted for the decryption password, we'll need
to create a custom initcpio hook, that will return a systemd service which will
do the enabling. We'll put this hook into `/usr/lib/initcpio/install/numlock`,
with the following content:
```bash
#!/bin/bash
build() {
add_binary /bin/bash
add_binary /usr/bin/setleds
add_binary /usr/local/bin/numlock
cat >"$BUILDROOT/usr/lib/systemd/system/numlock.service" <<EOF
[Unit]
Description=Enable numlock
Before=cryptsetup-pre.target
DefaultDependencies=no
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/numlock
EOF
add_systemd_unit cryptsetup-pre.target
cd "$BUILDROOT/usr/lib/systemd/system/sysinit.target.wants" || exit
ln -sf /usr/lib/systemd/system/cryptsetup-pre.target cryptsetup-pre.target
ln -sf /usr/lib/systemd/system/numlock.service numlock.service
}
help() {
cat <<EOF
This hook adds support to enable numlock before sd-encrypt hook is run.
EOF
}
```
This script is also present in my dotfiles, so you can just copy it from there:
```bash
cp ~/dots/root/usr/lib/initcpio/install/numlock /usr/lib/initcpio/install
```
Next we will need to create that `/usr/local/bin/numlock` script. This script
will do the actual enabling of numlock. Note that we can only use the binaries
that we explicitly included in our hook inside our script.
```bash
#!/bin/bash
for tty in /dev/tty[0-9]; do
/usr/bin/setleds -D +num < "$tty"
done
```
If you ran the `install_root.sh` script from my dotfiles during
[INSTALLATION](./01_INSTALLATION.md), this script will already be present in
your `/usr/local/bin`
Now we will need to add our custom new `numlock` hook to
`/etc/mkinitcpio.conf`, before the `sd-encrypt` hook (assuming you're using
encryption), but after the `keyboard` and `sd-vconsole` hooks.
Finally, we'll need to rebuild initramfs, which we should trigger with `sudo
pacman -S linux`, to make sure the secure-boot signing also runs. When
re-building the initramfs, pay attention on the output, you should see it pass
with no errors:
```text
-> Running build hook: [base]
-> Running build hook: [systemd]
-> Running build hook: [autodetect]
-> Running build hook: [microcode]
-> Running build hook: [modconf]
-> Running build hook: [kms]
-> Running build hook: [keyboard]
-> Running build hook: [sd-vconsole]
-> Running build hook: [numlock] # <-- make sure this is present
-> Running build hook: [sd-encrypt]
-> Running build hook: [block]
-> Running build hook: [filesystems]
-> Running build hook: [fsck]
```
> [!NOTE]
> If you see some warnings there, like:
> `==> WARNING: Possibly missing firmware for module: 'xyz'`, you can usually
> safely ignore these. Just make sure there's no `==> ERROR: ...`
If you didn't see any errors, you can now reboot.
> [!IMPORTANT]
> In some cases, the numlock led indicator might not turn on immediately, even
> though numlock was actually turned on. This may mislead you towards thinking
> it is not on, even though it actually is. I'd recommend trying it out by
> actually typing something it at this time.
>
> Note that after this early boot stage, the indicator should light up
> eventually.

227
guides/06_TPM_UNLOCKING.md Normal file
View file

@ -0,0 +1,227 @@
# TPM Unlocking
This will explain how to set up TPM (Trusted Platform Module) based automatic
unlocking of your LUKS encrypted partition(s). Encryption usually requires that
you manually type the password in each time you boot. This can however be pretty
annoying (especially if you use a long password, like I do). This guide aims to
fix this problem, without compromising security.
Once finished, this will basically store another decryption key(s) to your
encrypted partition(s) in the TPM module. During boot, while in initrd, we will
request this decryption key from TPM, which will only release it under certain
conditions, to ensure safety.
The guide assumes you have already a working Arch Linux system, that uses LUKS
encryption, having followed the [INSTALLATION guide](./01_INSTALLATION.md). You
will also need to set up secure-boot, as described in
[SECURE_BOOT](./04_SECURE_BOOT.md). This is a requirement, as while it is
possible to set up TPM unlocking without it, doing so is incredibly insecure,
and might lead to unauthorized users getting TPM to release your decryption
keys. Additionally, you will need to be using a [SYSTEMD BASED
INITRAMFS](./05_SYSTEMD_INITRAMFS.md), as the default BusyBox one doesn't
support TPM unlocking.
> [!WARNING]
> This solution will be mostly safe, however, it is technically possible to hook
> up wires to the motherboard, to listen to the communication coming from the
> TPM chip. In that case, the attacker would be able to observe the key as it
> gets released by the chip. They could then take out your SSD/HDD, and mount it
> on their machine, using these obtained keys to decrypt the contents. See:
> <https://astralvx.com/stealing-the-bitlocker-key-from-a-tpm/>
>
> If you can't afford to be vulnerable to this type of attack, you can still
> follow through with this, however instead of the TPM seamlessly releasing the
> decryption password, you can require a password to be entered, without which
> TPM won't release the decryption password.
>
> This can be useful if you use a very long encryption passwords, and you want
> to be able to enter a shorter passphrase instead (TPM has brute-force
> protection, so a short password isn't actually that unsafe to use).
## Check if you actually have the TPM module
First, you will want to verify that your machine even has the TPM v2 module. To
do so, you can use the following command:
```bash
bootctl status
```
You should see `TPM2 Support: yes` in the output.
## Choosing PCRs
PCR stands for Platform Configuration Register, and all TPM v2 modules have a
bunch of these registers, which hold hashes about the system's state. These
registers are read-only, and their value is set by the TPM module itself.
The data held by the TPM module (our LUKS encryption key) can then only be
accessed when all of the selected PCR registers contain the expected values. You
can find a list of the PCR registers on [Arch
Wiki](https://wiki.archlinux.org/title/Trusted_Platform_Module#Accessing_PCR_registers).
You can look at the current values of these registers with this command:
```bash
systemd-analyze pcrs
```
For our purposes, we will choose these:
- **PCR0:** Hash of the UEFI firmware executable code (may change if you update
UEFI)
- **PCR7:** Secure boot state - contains the certificates used to validate each
boot application
- **PCR12:** Overridden kernel command line, credentials
> [!IMPORTANT]
> If you're using a boot loader (rather than booting directly from the Unified
> Kernel Images - EFI files), it is crucial that we choose all 3, including
> PCR12, as many tutorials only recommend 0 and 7, which would however lead to a
> security hole, where an attacker would be able to remove the drive with the
> (unencrypted) EFI partition, and modify the boot loader config. (With
> systemd-boot, this would be `loaders/loader.conf`).
>
> From there, the attacker could simply add a kernel argument like
> `init=/bin/bash`, or just enable editor support, allowing them to edit the
> parameters from the boot menu on the fly (The editor is actually enabled by
> default for systemd-boot). This would then bypass systemd as the init system
> and instead make the kernel run bash executable as the PID=1 (init) program.
> This would mean you would get directly into bash console that is running as
> root, without any need to enter a password.
>
> From that bash console, they could get the TPM to release the decryption
> password manually, as all of the selected PCRs do match.
>
> This wouldn't violate secure boot, as the `.efi` image files were unchanged,
> and are still signed, so the attacker would be able to boot into the system
> without issues.
>
> However, with PCR12, this is prevented, as it detects that the kernel cmdline
> arguments which were used, and if they don't match the recorded parameters
> during enrollment, TPM will not release the key.
>
> The nice thing about also selecting PCR12 is that it will actually allow us to
> securely keep systemd-boot editor support, which can be very useful for
> debugging, as all that will happen if we do edit the kernel command line will
> be that the TPM module will not release the credentials, and the initrd will
> just ask us to enter the password manually.
Optionally, you may also consider these:
- **PCR1:** Hash of the UEFI firmware data (changes when you change your BIOS settings)
- **PCR4:** Boot manager (changes when you change the boot manager)
> [!NOTE]
> You may be tempted to also add **PCR11**, which is a hash of the Unified
> Kernel Image, so that no other UKI can be booted, but this isn't necessary,
> as we're signing our UKIs, which means untrusted ones wouldn't pass secure
> boot, and if secure boot got disabled, PCR7 wouldn't pass.
>
> Additionally, enabling PCR11 would mean that you'd need to update the TPM
> every time your kernel/microcode/initrd/... is updated, as these will change
> the UKI file.
## Enroll a new key into TPM
The following command will enroll a new randomly generated key into the TPM
module and add it as a new keyslot of the specified LUKS2 encrypted device.
We also specify `--tpm2-pcrs=0+7+12`, which selects the PCR registers that we
decided on above.
```bash
sudo systemd-cryptenroll --tpm2-device=auto --tpm2-pcrs=0+7+12 /dev/gpt-auto-root-luks
```
<!-- markdownlint-disable MD028 -->
> [!NOTE]
> If you already have something in the tpm2 module, you'll want to add
> `--wipe-slot=tpm2` too.
>
> Note that wiping the slot will also remove the LUKS key slot that was added
> in the partition.
> [!TIP]
> If you're extra paranoid, you can also provide `--tpm2-with-pin=yes`, to
> prompt for a PIN code (passphrase) on each boot.
>
> I have mentioned why you may want to do this in the beginning.
>
> In case you do want to go with a PIN, you can also safely drop PCR12, as you
> will be asked for credentials each time anyways, and at that point, the TPM
> unlocking is basically just as secure as regular passphrase unlocking, which
> systemd would fall back to if PCR12 wasn't met.
<!-- markdownlint-enable MD028 -->
You will now be prompted for an existing LUKS password (needed to add a new LUKS
keyslot).
## Reboot
All that remains now is rebooting. The system should now get unlocked
automatically, without prompting for the password / prompting for the TPM PIN
instead of a decryption password.
If you're using a bootloader, I'd recommend also trying to modify the kernel
parameters, to make sure that TPM does not release the key anymore, and you will
be prompted to enter it manually.
## Moving to a recovery key
Once you have confirmed that TPM unlocking is working, you can now optionally
get rid of your original LUKS key, in favor of a randomly generated recovery
key.
You might want to do this as this recovery key will be guaranteed to have high
entropy, likely making it a lot more secure than your original key, further
improving your chances, if someone attempts a brute-force decryption of your
drive.
To generate a recovery key, you can actually also just use `systemd-cryptenroll`
(though you can also do it manually with `cryptsetup`):
```bash
systemd-cryptenroll /dev/gpt-auto-root-luks --recovery-key
```
This will give you a randomized key, using characters that are easy to type. You
will even be given a QR code that can be scanned directly to save the password
on your phone.
Before proceeding with removing your own key, let's first make absolutely
certain that the recovery key you saved does in fact work. Without doing this,
you may get locked out!
```bash
cryptsetup luksOpen /dev/gpt-auto-root-luks crypttemp # enter the recovery key
cryptsetup luksClose crypttemp
```
If this worked, proceed to:
```bash
cryptsetup luksRemoveKey /dev/gpt-auto-root-luks # Enter the original key to be deleted
```
## Removing the key from TPM
In case you'd ever want to remove the LUKS key from TPM, you can do so simply
with:
```bash
csystemd-cryptenroll --wipe-slot=tpm2
```
This will actually also remove the LUKS key from the `/dev/gpt-auto-root-luks`
device as well as wiping it from the TPM2 chip.
## Sources / Attribution
- <https://nixos.wiki/wiki/TPM>
- <https://discourse.nixos.org/t/full-disk-encryption-tpm2/29454/6>
- <https://wiki.archlinux.org/title/systemd-cryptenroll>
- <https://wiki.archlinux.org/title/Trusted_Platform_Module#Accessing_PCR_registers>
- <https://pawitp.medium.com/full-disk-encryption-on-arch-linux-backed-by-tpm-2-0-c0892cab9704>

View file

@ -0,0 +1,280 @@
# Battery Optimizations
This guide goes over the various optimizations for laptops that you can
configure to improve your battery life.
> [!IMPORTANT]
> You will need to follow this guide even if you're using my dotfiles, as it
> requires enabling certain services which I don't enable automatically from
> the installation scripts.
>
> This is because not all devices need power management services running
> (desktop devices don't have a battery).
## UPower
UPower is a DBus service that provides power management support to
applications, which can request data about the current power state through this
DBus interface.
Additionally, UPower can perform a certain action when your battery life
reaches a critical point, like entering hibarnation when below 2%.
```bash
pacman -S upower
systemctl start --now upower
```
You can adjust UPower configuration in `/etc/UPower/UPower.conf`, I quite like
the defaults settings here. The relevant settings to look at are:
```conf
PercentageLow=20.0
PercentageCritical=5.0
PercentageAction=2.0
CriticalPowerAction=HybridSleep
```
## Acpid
Acpid is a daemon that can deliver ACPI power management events. When an event
occurs, it executes a program to handle that event. These events are:
- Pressing special keys, including the Power/Sleep/Suspend button, but also
things like wlan/airplane mode toggle button, volume buttons, brightness, ...
- Closing a notebook lid
- (Un)Plugging an AC power adapter from a notebook
- (Un)Plugging phone jack etc.
By default, these events would otherwise go unhandled, which isn't ideal.
```bash
pacman -S acpid
systemctl enable --now acpid
```
> [!TIP]
> By default `acpid` already has some basic handling of these ACPI events, so
> you shouldn't need to change anything, however, if you would want to run
> something custom on one of these events, you can configure it to do so in
> `/etc/acpi/handler.sh`
## Systemd suspend-then-hibernate
I like to use `systemctl suspend-then-hibernate` command when entering a
suspend state (usually configured from an idle daemon, such as hypridle or
swayidle). This command allows my system to remain suspended for some amount of
time, after which it will enter hibernation. This is really nice, because if I
forget that I had my laptop suspended and leave it like that while unplugged
for a long amount of time, this will prevent the battery from being drained for
no reason.
To configure automatic hibernation with this command, we'll want to modify
`/etc/systemd/sleep.conf`, and add:
```conf
HibernateDelaySec=10800
```
That will configure automatic hibernation after 3 hours of being in a suspend
state.
## Power Profiles Daemon
Many people like using something complex like TLP to manage power, however, in
many cases, you can achieve good results with something much simpler:
`power-profiles-daemon`.
Simply put, `power-profiles-daemon` is a CPU throttle, allowing you to switch
between various "power profiles" (power-saver, balanced, performance). I like
using a custom shell-script that checks the current battery percentage and
status (charging/discharging) and dynamically set the power profile based on
these values.
<!-- markdownlint-disable MD028 -->
> [!NOTE]
> Power Profiles Daemon only performs a subset of what TLP would do. Which of
> these tools you wish to use depends on your workfload and preferences:
>
> - If the laptop frequently runs under medium or high load, such as during
> video playback or compiling, using `power-saver` profile with
> `power-profiles-daemon` can provide similar energy savings as TLP.
> - However, TLP offers advantages over `power-profiles-daemon` when the laptop
> is idle, such as during periods of no user input or low load operations
> like text editing or browsing.
>
> In my personal opinion, `power-profiles-daemon` is quite sufficient and I
> don't have a great need for TLP. Also TLP is actually quite limiting in it's
> configuration in comparison to being able to use something like a shell script
> and switch profiles depending on both the charging state & the current
> percentage or any other custom rules whereas TLP only exposes some simple
> configuration options, that will enable performance/balanced mode when on AC
> power and power-safe when on battery power, but you can't really mess with
> anything more dynamic.
> [!TIP]
> If you think you'd prefer TLP over `power-profiles-daemon`, feel free to skip
> this section, the section below will cover TLP as an alternative to this.
> [!TIP]
> It may be worth it to look into
> [`system76-power`](https://github.com/pop-os/system76-power) as an
> alternative to `power-profiles-daemon`.
<!-- markdownlint-enable MD028 -->
To set up power-profiles-daemon, we'll first install it and enable it as a
systemd service:
```bash
pacman -S power-profiles-daemon
systemctl enable --now power-profiles-daemon
```
### Setting power profile manually
To try things out, you can set the power profile manually, using
`powerprofilesctl` command:
```bash
powerprofilesctl set power-saver
powerprofilesctl set balanced
powerprofilesctl set performance # won't work on all machines
```
However, having to set your power profile manually each time wouldn't be very
convenient, so I'm only showing this as an example / something you can try out
initially to see what results it can give you.
### Setting power profiles automatically
To make `power-profiles-daemon` actually useful and seamless, I like using a
shell script that monitors the battery state and switches the power mode
depending on certain conditions. I like placing my system-wide scripts into
`/usr/local/bin`, so let's use: `/usr/local/bin/power-profiles-monitor`:
<!-- markdownlint-disable MD013 -->
```bash
#!/usr/bin/env bash
set -euo pipefail
if [ "$EUID" -ne 0 ]; then
echo "You must run this script as root"
exit 1
fi
BAT=$(echo /sys/class/power_supply/BAT*) # only supports single-battery systems
BAT_STATUS="$BAT/status"
BAT_CAP="$BAT/capacity"
OVERRIDE_FLAG="/tmp/power-monitor-override"
POWER_SAVE_PERCENT=50 # Enter power-save mode if on bat and below this capacity
HAS_PERFORMANCE="$(powerprofilesctl list | grep "performance" || true)" # the || true ignores grep failing with non-zero code
# monitor loop
prev=0
while true; do
# check if override is set
if [ -f "$OVERRIDE_FLAG" ]; then
echo "Override flag set, waiting for release"
inotifywait -qq "$OVERRIDE_FLAG"
continue
fi
# read the current state
status="$(cat "$BAT_STATUS")"
capacity="$(cat "$BAT_CAP")"
if [[ $status == "Discharging" ]]; then
if [[ $capacity -le $POWER_SAVE_PERCENT ]]; then
profile="power-saver"
else
profile="balanced"
fi
else
if [[ -n $HAS_PERFORMANCE ]]; then
profile="performance"
else
profile="balanced"
fi
fi
# Set the new profile
if [[ "$profile" != "$prev" ]]; then
echo -en "Setting power profile to ${profile}\n"
powerprofilesctl set $profile
prev=$profile
fi
# wait for changes in status or capacity files
# i.e. for the next power change event
inotifywait -qq "$BAT_STATUS" "$BAT_CAP"
done
```
<!-- markdownlint-enable MD013 -->
> [!NOTE]
> You will need `inotify-tools` package installed for the `inotifywait` command
> to work.
As you can see, it's a pretty simple script, that will run forever, but spend
most time just waiting for the battery status to change, re-running once it
does.
We could now run this script manually, but that's not a great solution,
instead, we can create a custom systemd service which will run it for us
automatically. To do this, we'll create a new file:
`/etc/systemd/system/power-profiles-monitor.service` with the following
content:
```systemd
[Unit]
Description=Monitor the battery status, switching power profiles accordingly
Wants=power-profiles-daemon.service
[Service]
ExecStart=/usr/local/bin/power-profiles-monitor
Restart=on-failure
Type=simple
[Install]
WantedBy=default.target
```
With that, we can now enable our service:
```bash
systemctl daemon-reload # make systemd aware of the new service
systemctl enable --now power-profiles-monitor
```
> [!TIP]
> You may have noticed that the script
## TLP
> [!IMPORTANT]
> TLP is an alternative solution to handle power management, it cannot be used
> in combination with `power-profiles-daemon`.
TODO: This section is work-in-progress, as I'm not using TLP right now.
If you wish to set up TLP, I'd suggest that you check out the official [TLP
documentation](https://linrunner.de/tlp/introduction.html), alongside with a
guide on achieving a similar profile switching behavior as
`power-profiles-daemon` offers with it:
[here](https://linrunner.de/tlp/faq/ppd.html). Additionally, there is an [Arch
Linux Wiki page for TLP](https://wiki.archlinux.org/title/TLP).
## Sources
- <https://wiki.archlinux.org/title/Power_management>
- <https://wiki.archlinux.org/title/Acpid>
- <https://gitlab.freedesktop.org/upower/power-profiles-daemon>
- <https://linrunner.de/tlp/introduction.html>
- <https://linrunner.de/tlp/faq/ppd.html>
- <https://wiki.archlinux.org/title/TLP>

152
guides/99_GREETD.md Normal file
View file

@ -0,0 +1,152 @@
# Greetd
This guide goes over how to setup `greetd`, which is a minimalistic Display
Manager (DM) that starts right after boot and asks the user to log in.
A DM is useful for letting you pick which session you wish to load after
logging in (e.g. which WM/DE), but also to provide a slightly nicer UI in
comparison to the default `agetty` TTY based login screen.
Another neat feature that greetd offers is automatic login, which will allow
you to skip the login process entirely, logging you in right after the boot.
This can be useful if you're already typing in your LUKS encryption password
each time after a boot, which already acts as a sufficient layer of protection
against attackers trying to enter your system.
<!-- markdownlint-disable MD028 -->
> [!WARNING]
> If you've set up TPM unlocking for your LUKS encryption, setting up automatic
> login is not safe, unless you're using a TPM passphrase/PIN.
> [!IMPORTANT]
> If you're following while using my dotfiles, you will need to manually place
> the greetd config from the repo into `/etc/greed/config.toml`. The
> installation scripts don't do this, as many people prefer not using a
> greeter.
>
> You will also need to follow the installation instructions to download greetd
> and enable it.
<!-- markdownlint-enable MD028 -->
## Greetd + tuigreet
Since I prefer a minimalistic approach to most things in my system, I like to
use a terminal based greeter. Greetd itself is just a daemon that supports
various greeters. Most of these greeters are graphical, but there are terminal
based ones too, most notably `tuigreet`, which works right from the TTY.
First, install and enable greetd, to make sure it gets started on boot.
```bash
sudo pacman -S greetd greetd-tuigreet
sudo systemctl enable greetd
```
Now, we will want to define our greetd configuration in
`/etc/greetd/config.toml`. There should already be a default configuraion that
uses `agreety` greeter, which is similar to `agetty`, we'll want to change that
to `tuigreet`, which in my opinion looks a lot better. We can use the following
config:
<!-- markdownlint-disable MD013 -->
```toml
[terminal]
# The VT to run the greeter on. Can be "next", "current" or a number
# designating the VT.
vt = 1
# The default session, also known as the greeter.
[default_session]
command = "tuigreet --time --remember --remember-user-session --asterisks --greeting 'Stop staring and log in already' --theme 'border=magenta;text=cyan;prompt=green;time=red;action=white;button=yellow;container=black;input=gray' --sessions /usr/share/wayland-sessions --xsessions /usr/share/xsessions --session-wrapper /usr/local/bin/greetd-session-wrapper --xsession-wrapper /usr/local/bin/greetd-session-wrapper startx /usr/bin/env"
# The user to run the command as. The privileges this user must have depends
# on the greeter. A graphical greeter may for example require the user to be
# in the `video` group.
user = "greeter"
```
<!-- markdownlint-enable MD013 -->
> [!NOTE]
> I know the `tuigreet` command is really hard to orient in when written in a
> single line like this, however, attempting to use a multi-line string doesn't
> seem to work with greetd (even though it is a part of the TOML standard).
> This issue has already been
> [reported](https://lists.sr.ht/~kennylevinsen/greetd/<trinity-082b25fc-e1fa-4772-950c-d458f065024a-1648717080362@3c-app-mailcom-bs08>),
> yet it doesn't seem like it was addressed.
You may have noticed that I've referred to a
`/usr/local/bin/greetd-session-wrapper` script here, that's a custom script that
I wrote to get greetd to run the command to start the WM/DE session within a
running user shell (bash/zsh), so that the appropriate environment variables
will be set when the WM is launched.
This is the content of that script:
```bash
#!/bin/bash
set -euo pipefail
# This is a helper wrapper script for greetd.
#
# It will run the session / application using the appropriate shell configured for
# this user. That way, we can make sure all of the environment variables are set
# before the WM/DE session is started.
#
# This is very important, as without it, variables for things like qt theme
# will not be set, and applications executed by the WM/DE will not be themed properly.
script_name="$0"
shell="$(getent passwd "$USER" | awk -F: '{print $NF}')"
command=("$@")
exec "$shell" -c 'exec "$@"' "$script_name" "${command[@]}"
```
With this configuration, you can now reboot and check whether greetd works
properly. (You will still be asked for a password.)
```bash
reboot
```
If everything worked properly, you should've been presented with a custom
tuigreet login screen after booting.
> [!TIP]
> Feel free to adjust the `tuigreet` settings to your liking by editing the
> `command` in the greetd settings. If you need a reference for what settings
> are available, you can check out the
> [`tuigreet`](https://github.com/apognu/tuigreet) project page.
## Configuring automatic Login
To configure automatic login, we'll need to modify the `greetd` settings in
`/etc/greetd/config.toml` and add an initial session section:
```toml
[terminal]
# The VT to run the greeter on. Can be "next", "current" or a number
# designating the VT.
vt = 1
# Auto-login session, triggered right after boot.
# If the user logs out, greetd will render the default session
[initial_session]
user = "itsdrike" # TODO: CHANGE THIS
command = "/usr/local/bin/greetd-session-wrapper Hyprland"
# The default session, also known as the greeter.
[default_session]
command = "tuigreet --time --remember --remember-user-session --asterisks --greeting 'Stop staring and log in already' --theme 'border=magenta;text=cyan;prompt=green;time=red;action=white;button=yellow;container=black;input=gray' --sessions /usr/share/wayland-sessions --xsessions /usr/share/xsessions --session-wrapper /usr/local/bin/greetd-session-wrapper --xsession-wrapper /usr/local/bin/greetd-session-wrapper startx /usr/bin/env"
# The user to run the command as. The privileges this user must have depends
# on the greeter. A graphical greeter may for example require the user to be
# in the `video` group.
user = "greeter"
```

76
guides/99_PRINTING.md Normal file
View file

@ -0,0 +1,76 @@
# Printing
This guide explains how to set up printing and scanning on Arch Linux.
<!-- markdownlint-disable MD028 -->
> [!NOTE]
> This guide is still WIP and isn't very informative, I wrote it just as a quick
> reference for myself.
> [!NOTE]
> This guide focuses on HP brand printers. If you have a printer from another
> brand, you will not be able to fully follow it.
<!-- markdownlint-enable MD028 -->
## Installing
First, we'll need to install and enable `cups`, which is the printing daemon for
Linux.
```bash
sudo pacman -S --needed cups
systemctl enable --now cups
```
### HP printers
You'll want to use `hplip` if you're using an HP brand printer.
```bash
sudo pacman -S --needed hplip
```
> [!NOTE]
> You will only want to use the hplip package for terminal based interactions.
>
> Hplip should support UI too, however, it uses Qt 4, for which the necessary
> libraries are no longer shipped by pacman, as it's incredibly outdated. It is
> technically possible to install these through the AUR, but due to the nature
> of some of the dependencies for these outdated libraries, it would mean having
> to install python2 and a bunch of related packages.
>
> Additionally, because hplip was written for very early python 3, you are
> likely to see a lot of warnings when you run most commands. That said, the
> commands should work, as these are just warnings.
>
> Aren't drivers written by big companies that have no clue about Linux just the
> best?
To set up your printer, run:
```bash
sudo hp-setup -i
```
This will register the printer with CUPS and you should now be able to pick it
in the printing dialog.
## Scanning
To get scanning support, you will need to have `sane`:
```bash
sudo pacman -S sane
```
If you're using `hplip`, you can now trigger a scan with the following command:
```bash
hp-scan -o scan.png
```
> [!TIP]
> If the specified filename ends with `.pdf`, hplip will store a PDF document
> instead of a PNG image.

668
guides/99_THEMING.md Normal file
View file

@ -0,0 +1,668 @@
# Theming
This guide will go over setting up Qt and GTK themes on Arch Linux.
My preferred setup uses:
- [BreezeX-RosePine-Linux](https://github.com/rose-pine/cursor) cursor theme,
size 24.
- [Papirus-Dark](https://github.com/catppuccin/papirus-folders) icon theme from
catppuccin papirus folders, specifically the blue accent & mocha flavor
variant.
- The default font of my choice is [Noto
Sans](https://fonts.google.com/noto/specimen/Noto+Sans), size 10
- The default monospace font of my choice is [Monaspace
Krypton](https://monaspace.githubnext.com/)
- For GTK theme, I'm using
[Tokyonight-Dark](https://github.com/Fausto-Korpsvart/Tokyonight-GTK-Theme).
- For QT theme, I'm using
[Catppuccin-Mocha-Blue](https://github.com/catppuccin/Kvantum) kvantum theme.
> [!NOTE]
> My dotfiles already include most of the necessary theme configuration files,
> so if you're using them, you can skip a lot of the steps I mention here. This
> guide assumes a completely un-themed system, to make it easy for anyone to
> follow.
>
> If there is something that you're expected to do even if you've copied over
> all of the configuration files from my dotfiles repo, it will be explicitly
> mentioned in an _important_ markdown block.
## Packages
First, we'll install all the required packages:
```bash
paru -S --needed \
rose-pine-cursor \
papirus-folders-catppuccin-git \
noto-fonts otf-monaspace \
tokyonight-gtk-theme-git \
kvantum kvantum-qt5 qt5ct qt6ct kvantum-theme-catppuccin-git
```
## Dconf / Gsettings
Dconf is a low-level configuration system that works through D-Bus, serving as
backend to GSettings. It's a simple key-based config systems, with the keys
existing in an unstructured database.
You can use the `dconf` command manually to set specific keys to given values,
but it's often more a better idea to use `gsettings`, which provide some
abstractions and does consistency checking, but ultimately it will just store
the configured values into the `dconf` database.
Dconf is used by a lot of applications for various things, but a lot of the
dconf settings are related to theming and it's crucial that we set them, as some
applications will follow these instead of the configuration files.
> [!IMPORTANT]
> You will need to perform this step even if you're using my dotfiles. The
> dconf database is not a part of my dotfiles, so these values won't be set.
```bash
# Global configuration that tells applications to prefer dark mode
gsettings set org.gnome.desktop.interface color-scheme prefer-dark
# GTK theme
gsettings set org.gnome.desktop.interface gtk-theme Tokyonight-Dark
# Font settings
gsettings set org.gnome.desktop.interface font-name 'Noto Sans 10'
gsettings set org.gnome.desktop.interface document-font-name 'Noto Sans 10'
gsettings set org.gnome.desktop.interface monospace-font-name 'Source Code Pro 10'
# Cursor settings
gsettings set org.gnome.desktop.interface cursor-theme 'BreezeX-RosePine-Linux'
gsettings set org.gnome.desktop.interface cursor-size 24
```
> [!TIP]
> You can find all registered dconf schemas with `gsettings list-schemas`. To
> include the keys, you can `gsettings list-recursively`.
>
> You might want to set some of these according to your preferences.
## XSettings
Similarly to dconf/gsettings specification, there's also an XSETTINGS
specification, that is used by some Xorg applications (most notably GTK, Java
and Wine based apps). It is less useful on Wayland, but since a lot of
applications still don't have native wayland support, it may be worth setting
up anyways. XWayland applications may still depend on this.
Applications that rely on this specification will ask for the settings from the
Xorg server, which itself gets them from a daemon service. On GNOME desktop,
this would be `gnome-settings-daemon`, but anywhere else, you'll want to use
[`xsettingsd`](https://codeberg.org/derat/xsettingsd), which is a lightweight
alternative.
<!-- markdownlint-disable MD028 -->
> [!NOTE]
> This part of the guide is optional, you don't have to set up xsettings, most
> applications will work just fine without it.
> [!IMPORTANT]
> If you do wish to set up xsettings, you will need to follow these
> instructions, even if you've populated your system with the configuration
> files from my dotifiles, as it requires installing a package and activating a
> systemd service.
<!-- markdownlint-enable MD028 -->
First, you will want to install `xsettingd` package and activate the systemd
service, so that applications can ask for this daemon a specific setting:
```bash
pacman -S xsettingsd
systemctl --user enable --now xsettingsd
```
These settings can control various things, but for us, we'll focus on the
theming. XSettings are configured simply through a config file in:
`~/.config/xsettingsd/xsettingsd.conf`.
To configure theming in xsettings, you can put the following settings into your
`xsettingsd.conf` file:
```conf
Net/ThemeName "Tokyonight-Dark"
Net/IconThemeName "Papirus-Dark"
Gtk/CursorThemeName "BreezeX-RosePine-Linux"
Net/EnableEventSounds 1
EnableInputFeedbackSounds 0
Xft/Antialias 1
Xft/Hinting 1
Xft/HintStyle "hintslight"
Xft/RGBA "rgb"
```
## GTK
> [!TIP]
> We'll be setting things up manually, however, if you wish, you can also use
> [`nwg-look`](https://github.com/nwg-piotr/nwg-look) to configure GTK from a
> graphical settings application. Do note though that by default, it doesn't
> support GTK 4 theming (see: [this github
> issue](https://github.com/nwg-piotr/nwg-look/issues/22)).
>
> `nwg-look` is inspired by the more popular `lxappearance`, however, it is
> made for native wayland. That said, either will work, so you can also try
> `lxappearance` if you wish, even on wayland.
### GTK 2
For GTK 2, we'll first want to change the location of the `gtkrc` configuration
file, to follow proper XDG base directory specification and avoid it cluttering
`$HOME`. To do this, we'll need to set the following environment variable to be
exported by your shell:
```bash
export GTK2_RC_FILES="$XDG_CONFIG_HOME/gtk-2.0/gtkrc":"$XDG_CONFIG_HOME/gtk-2.0/gtkrc.mine"
```
We'll now create `~/.config/gtk-2.0` directory, and a `gtkrc` file inside of it,
with the following content:
```text
gtk-theme-name = "Tokyonight-Dark"
gtk-icon-theme-name = "Papirus-Dark"
gtk-cursor-theme-name = "BreezeX-RosePine-Linux"
gtk-cursor-theme-size = 24
gtk-font-name = "Noto Sans 10"
gtk-button-images=1
gtk-menu-images=1
gtk-enable-event-sounds=0
gtk-enable-input-feedback-sounds=0
gtk-toolbar-icon-size=GTK_ICON_SIZE_LARGE_TOOLBAR
gtk-toolbar-style=GTK_TOOLBAR_BOTH_HORIZ
gtk-xft-antialias=1
gtk-xft-hinting=1
gtk-xft-hintstyle="hintslight"
gtk-xft-rgba="rgb"
```
### GTK 3
For GTK 3, we'll put the following into `~/.config/gtk-3.0/settings.ini`:
```conf
[Settings]
gtk-application-prefer-dark-theme=true
gtk-theme-name=Tokyonight-Dark
gtk-icon-theme-name=Papirus-Dark
gtk-cursor-theme-name=BreezeX-RosePine-Linux
gtk-cursor-theme-size=24
gtk-font-name=Noto Sans 10
gtk-enable-animations=true
gtk-button-images=1
gtk-menu-images=1
gtk-enable-event-sounds=0
gtk-enable-input-feedback-sounds=0
gtk-error-bell=0
gtk-decoration-layout=appmenu:none
gtk-toolbar-icon-size=GTK_ICON_SIZE_LARGE_TOOLBAR
gtk-toolbar-style=GTK_TOOLBAR_BOTH_HORIZ
gtk-xft-antialias=1
gtk-xft-hinting=1
gtk-xft-hintstyle=hintslight
```
### GTK 4
For GTK 4, we'll put the following into `~/.config/gtk-4.0/settings.ini`:
```conf
[Settings]
gtk-application-prefer-dark-theme=true
gtk-theme-name=Tokyonight-Dark
gtk-icon-theme-name=Papirus-Dark
gtk-cursor-theme-name=BreezeX-RosePine-Linux
gtk-cursor-theme-size=24
gtk-font-name=Noto Sans 10
gtk-enable-event-sounds=0
gtk-enable-input-feedback-sounds=0
gtk-error-bell=0
gtk-decoration-layout=appmenu:none
gtk-xft-antialias=1
gtk-xft-hinting=1
gtk-xft-hintstyle=hintslight
```
For `libadwaita` based GTK 4 applications, you will need to force a GTK theme
with an environment variable, so you will also want to export the following:
```bash
export GTK_THEME="Tokyonight-Dark"
```
<!-- markdownlint-disable MD028 -->
> [!WARNING]
> This will only work if your theme has GTK 4 support.
> [!TIP]
> As an alternative to exporting the `GTK_THEME` env var like this, you can
> also install `libadwaita-without-adwaita-git` AUR package, which contains a
> patch to prevent GTK from overriding the system theme.
>
> Another option would be to import the theme in `gtk.css`: `~/.config/gtk-4.0/gtk.css`:
>
> ```css
> /**
> * GTK 4 reads the theme configured by gtk-theme-name, but ignores it.
> * It does however respect user CSS, so import the theme from here.
> **/
> @import url("file:///usr/share/themes/Tokyonight-Dark/gtk-4.0/gtk.css");
> ```
<!-- markdownlint-enable MD028 -->
### Make GTK follow XDG portal settings
Certain things, such as dialogs or file-pickers can be controlled via XDG
desktop portals, however, by default, GTK apps will not follow these settings.
To force them into doing so, you can export an environment variable:
```bash
export GTK_USE_PORTAL=1
```
## Qt
This section goes over configuring QT styles for qt 5 and qt 6.
### Kvantum
I like using `kvantum` to configure QT themes. Kvantum is an SVG style
customizer/engine, for which there's a bunch of plugins. It then turns these
plugins / kvantum themes into full QT themes. For theme creators, it simplifies
making a full QT theme.
> [!NOTE]
> Kvantum will only be useful for you if you actually want to use a kvantum
> theme. If you wish to use a full QT theme that doesn't need kvantum, you can
> skip this and instead achieve the same with qtct. (I'll say a bit more about
> qtct in icon theme section.)
Kvantum works as a Qt style instead of a Qt platform theme. To set kvantum for
all Qt applications, you can export the following env variable:
```bash
export QT_STYLE_OVERRIDE=kvantum
```
> [!NOTE]
> For backwards compatibility, in addition to the `kvantum` package, you will
> also need `kvantum-qt5` (`kvantum` works with qt6). If you followed the
> initial install instructions, you will have both installed already.
### Theme
We will now want to tell kvantum which theme to use. To do this, we will need to
create a settings file for Kvantum in `~/.config/Kvantum/kvantum.kvconfig`, with
the following content:
```conf
[General]
theme=catppuccin-mocha-blue
```
> [!TIP]
> The system-wide kvantum themes are located in `/usr/share/Kvantum`. The theme
> variable has to match the directory name of one of these themes.
>
> If you wish to use a custom theme that isn't available as a package, you can
> also add it as a user theme directly into `~/.config/Kvantum/`.
### Icon theme & qtct
As a theme qt engine, kvantum can't handle icons. For those, we will use qtct
platform theme.
> [!NOTE]
> You will need to install `qt5ct` & `qt6ct` packages. These will also be
> installed already if you followed the initial install command though.
Now we'll set the QT platform theme through an environment variable:
```bash
export QT_QPA_PLATFORMTHEME="qt5ct" # keep this value even for qt6ct
```
Finally, we can add a qtct configuration to use our preferred icon theme:
`~/.config/qt5ct/qt5ct.conf`:
```conf
[Appearance]
icon_theme=Papirus-Dark
```
Same thing for `~/.config/qt6ct/qt6ct.conf`.
> [!NOTE]
> qtct is a platform theme and it can do a lot more than just set the icon
> theme, however, we chose kvantum to serve as our style, so we don't need
> anything else from qtct.
>
> If you wish to instead use qtct for picking the qt style, unset the
> `QT_STYLE_OVERRIDE` variable and pick your theme in both `qt5ct` & `qt6ct`
> applications. This will modify the `qt5ct.conf` and the qt 6 variant.
### Additional things
There are some extra things that you'll probably want to set. To do so, we will
yet again use more environment variables. Specifically:
```bash
# Enables automatic scaling, based on the monitor's pixel density.
export QT_AUTO_SCREEN_SCALE_FACTOR="1"
# Run QT applications using the wayland plugin, falling back to xcb (X11) plugin
export QT_QPA_PLATFORM="wayland;xcb"
# Disable client side decorations
export QT_WAYLAND_DISABLE_WINDOWDECORATION="1"
```
## Cursor
### XCursor
XCursor is the default cursor format for cursor themes. Even though the name
might imply that it's connected to X11, it will work just fine on wayland too.
To select a cursor theme to be used, you'll want to export the following
environment variables:
```bash
export XCURSOR_THEME="BreezeX-RosePine-Linux"
export XCURSOR_SIZE="24"
```
Additionally, you might want to also modify/set `XCURSOR_PATH`, to make sure
that it includes `~/.local/share/icons`, as otherwise, xcursor will not look
here for cursor themes by default on some DEs/WMs.
```bash
export XCURSOR_PATH=$XCURSOR_PATH${XCURSOR_PATH:+:}~/.local/share/icons
```
### Default cursor config
The cursor theme name "default" is used by an application if it cannot pick up
on a configuration. The default cursor theme can live in:
`~/.local/share/icons/default` or `/usr/share/icons/default`.
To set the default cursor for your user, create a
`~/.local/share/icons/default/index.theme` file with the following:
```conf
[Icon Theme]
Name=Default
Comment=Default Cursor Theme
Inherits=BreezeX-RosePine-Linux
```
> [!TIP]
> Alternatively, we could also symlink the cursor theme into the `default`
> directory, like so:
>
> ```bash
> ln -s /usr/share/icons/BreezeX-RosePine-Linux/ ~/.local/share/icons/default
> ```
>
> That said, I prefer using `Inherits` here, as it allows me to easily store the
> default cursor config in my dotfiles.
### Cursor config for GTK
You may have noticed earlier that we've already touched on specifying the cursor
configuration for GTK in the gtkrc/gtk settings, this is done via the
`gtk-cursor-theme-name` and `gtk-cursor-theme-size` setting options. Because of
that, there's no need to do anything extra to get GTK apps to use the correct
cursor theme.
### Cursor config for Qt
There is no Qt configuration for cursors. Qt programs may pick up a cursor theme
from the desktop environment (server-side cursors), X resources, or lastly the
"default" cursor theme.
### Hyprcursor
[hyprcursor](https://github.com/hyprwm/hyprcursor) is a new and efficient a
cursor format, that allow for SVG based cursors, resulting in a much better
scaling experience and more space-efficient themes.
Hyprcursor is supported out of the box by Hyprland, so if you're using Hyprland,
you can benefit from it. That said, this part is entirely optional and you can
just stick with xcursor if you wish.
If you do want to use hyprcursor, you will want to install [hyprcursor version
of the rose-pine-cursor
theme](https://github.com/ndom91/rose-pine-cursor-hyprcursor). You can simply
git clone this repository right into `~/.local/share/icons` (sadly, there isn't
an AUR package available at this time):
```bash
cd ~/.local/share/icons
git clone https://github.com/ndom91/rose-pine-cursor-hyprcursor
```
Finally, you will want to set the following environment variables:
```bash
export HYPRCURSOR_THEME="rose-pine-hyprcursor"
export HYPRCURSOR_SIZE="24"
```
Alternatively, you can also set these variables right from your hyprland config:
```hyprlang
env = HYPRCURSOR_THEME,rose-pine-hyprcursor
env = HYPRCURSOR_SIZE,24
```
> [!WARNING]
> Make sure to keep the existing xcursor environment variables and themes, as
> although many apps do support server-side cursors (e.g. Qt, Chromium,
> Electron, ...), some still don't (looking at you GTK, but also some other,
> less common things). These applications will then fall back to XCursor (unless
> they have built-in hyprcursor support, which is rare).
>
> I would therefore also recommend leaving the default theme point to the
> XCursor theme, not to a hyprcursor theme.
## Fonts
Some applications use `gsettings`/`dconf` to figure out what font to use. We've
already configured these settings, so those applications should pick up which
font to use correctly.
Other applications will use GTK config to figure out the default fonts. We've
configured this earlier too. (Note that GTK config doesn't support specifying a
monospace font).
The rest of the applications will use generic font family names ("standard"
fonts), as defined through `fontconfig`.
Applications also often provide configuration files where you can define which
font you wish to be using, so sometimes, you will need to set the font on a
per-application basis. We will not cover this, as each application is different.
### Installing fonts
In the installation instructions above, I did specify the 2 default font
packages that I wanted to use for my system. That said, I did not specify an
emoji font there and there are many fonts that are just useful to have on the
system, for things like text editing. The command below will install most of the
fonts that you might need:
```bash
paru -S --needed \
libxft xorg-font-util \
ttf-joypixels otf-jost lexend-fonts-git ttf-sarasa-gothic \
ttf-roboto ttf-work-sans ttf-comic-neue \
gnu-free-fonts tex-gyre-fonts ttf-liberation otf-unifont \
inter-font ttf-lato ttf-dejavu noto-fonts noto-fonts-cjk \
noto-fonts-emoji ttf-material-design-icons-git \
ttf-font-awesome ttf-twemoji otf-openmoji \
adobe-source-code-pro-fonts adobe-source-han-mono-otc-fonts \
adobe-source-sans-fonts ttf-jetbrains-mono otf-monaspace \
ttf-ms-fonts
```
#### Nerd fonts
I have intentionally left out the `nerd-fonts` package from the above command,
as it is fairly large (about 8 gigabytes). If you wish, you can install it, as
it does contain some pretty useful fonts, however, if this package is too big
for you, you can instead install the fonts individually, as arch does ship all
nerd fonts in the package manager individually.
To install all nerd fonts, you can simply:
```bash
paru -S --needed nerd-fonts
```
If you instead wish to only install specific nerd fonts, you can use the
following command. Note that you may want to add more fonts from nerd-fonts.
```bash
paru -S --needed \
ttf-firacode-nerd otf-firamono-nerd ttf-iosevka-nerd ttf-nerd-fonts-symbols \
ttf-hack-nerd ttf-heavydata-nerd ttf-gohu-nerd
```
> [!IMPORTANT]
> If you wish to use all of nerd-fonts, you will need to run the above command
> even after going through the install scripts from my dotfiles, as they only
> install specific nerd fonts (the above).
### Setting standard fonts
These standard fonts are:
- `sans-serif`: Standard font for regular text (articles, menus, ...)
- `serif`: Like sans-serif, but pure sans fonts shouldn't have the decorative
lines or tapers (also known as "tails" or "feet"). Note that these should fall
back to `sans-serif` if unset.
- `monospace`: Standard font for fixed-width fonts (text editors, calculators,
...)
- `emoji`: Standard font for emoji glyphs
It is possible to register multiple fonts for the standard font, ordered by
priorities. That way, if the first font isn't found, or it doesn't contain the
given glyph, the search will fall back to the next font in line.
To set a standard font, you will need to create a fontconfig configuration file.
You can do this on a per-user basis, in `~/.config/fontconfig/fonts.conf` (or
`~/.config/fontconfig/conf.d/`) or system-wide in `/etc/fonts/local.conf` (don't
modify `/etc/fonts/fonts.conf` nor the files in `/etc/fonts/conf.d`, these are
managed by the package manager and could get overwritten). Note that the user
font settings will take priority if there are overlapping settings.
I prefer using the system-wide settings (`/etc/fonts/local.conf`):
```xml
<?xml version='1.0'?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
<alias binding="same">
<family>sans-serif</family>
<prefer>
<family>Noto Sans</family>
<family>Jost</family>
<family>Lexend</family>
<family>Iosevka Nerd Font</family>
<family>Symbols Nerd Font</family>
<family>Noto Color Emoji</family>
</prefer>
</alias>
<alias binding="same">
<family>serif</family>
<prefer>
<family>Noto Serif</family>
<family>Iosevka Nerd Font</family>
<family>Symbols Nerd Font</family>
<family>Noto Color Emoji</family>
</prefer>
</alias>
<alias binding="same">
<family>monospace</family>
<prefer>
<family>Monaspace Krypton</family>
<family>Source Code Pro Medium</family>
<family>Source Han Mono</family>
<family>Iosevka Nerd Font</family>
<family>Symbols Nerd Font</family>
<family>Noto Color Emoji</family>
</prefer>
</alias>
<alias binding="same">
<family>emoji</family>
<prefer>
<family>Noto Color Emoji</family>
<family>Iosevka Nerd Font</family>
<family>Symbols Nerd Font</family>
<family>Noto Color Emoji</family>
</prefer>
</alias>
</fontconfig>
```
You will now need to rebuild the font cache with:
```bash
fc-cache -vf
```
### Disable Caskaydia Cove Nerd Font
For some reason, having the Caskaydia font installed was causing some issues
with other fonts for me. Caskaydia comes from `nerd-fonts`, so if you installed
them, you might want to follow along with this too, if you're also facing
issues. I'm honestly not sue why that is, however, all that's needed to solve it
is disabling this font entirely. To do so, add the following to your
`fontconfig` config:
```xml
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
<selectfont>
<rejectfont>
<glob>/usr/share/fonts/nerd-fonts-git/TTF/Caskaydia*</glob>
</rejectfont>
</selectfont>
</fontconfig>
```
### Font Manager
To preview the installed fonts, I like using `font-manager`:
```bash
paru -S --needed font-manager
```
## Sources
- <https://askubuntu.com/questions/22313/what-is-dconf-what-is-its-function-and-how-do-i-use-it>
- <https://man.archlinux.org/man/dconf.1.en>
- <https://wiki.archlinux.org/title/Xsettingsd>
- <https://www.reddit.com/r/gnome/comments/wt8oml/is_gnomesettingsdaemon_no_longer_a_program_i_can/>
- <https://wiki.archlinux.org/title/GTK>
- <https://wiki.archlinux.org/title/XDG_Base_Directory>
- <https://wiki.archlinux.org/title/Uniform_look_for_Qt_and_GTK_applications>
- <https://wiki.archlinux.org/title/Qt>
- <https://wiki.archlinux.org/title/Cursor_themes>
- <https://wiki.hyprland.org/Hypr-Ecosystem/hyprcursor/>
- <https://wiki.archlinux.org/title/Font_configuration>
- <https://bbs.archlinux.org/viewtopic.php?id=275434>

View file

@ -1,414 +0,0 @@
# Installation
This is a full Arch Linux installation guide, from live cd to a working OS.
This installation includes steps for full disk encryption, and sets up the
system with some basic tools and my zsh configuration.
## Partition, format and mount the disks
This will depend on your setup, following are the commands I used for my
specific setup as a reference, however you'll very like want a different
disk structure, and you probably won't even have the drives in the same
configuration as I do.
Create partitions for the drives
```bash
fdisk /dev/nvme0n1
# Create new GPT table and make 3 partitions
# first for boot (1G), second for swap (16G),
# third for btrfs (root + /home + data) (rest of the space)
fdisk /dev/nvme0n2
# Create a single partition for btrfs data
```
Format partitions that shouldn't be encrypted
```bash
mkfs.fat -F 32 /dev/nvme0n1p1
fatlabel /dev/nvme0n1p1 EFI
mkswap -L SWAP /dev/nvme0n1p2
```
Format drives using LUKS for encryption and open them to mapper devices
```bash
cryptsetup luksFormat --type luks2 --label ARCH_LUKS /dev/nvme0n1p3
cryptsetup luksFormat --type luks2 --label DATA /dev/nvme0n2p1
cryptsetup luksOpen /dev/disk/by-label/ARCH_LUKS cryptroot
cryptsetup luksOpen /dev/disk/by-label/DATA cryptdata
```
Create BTRFS filesystem on the encrypted drives
```bash
mkfs.btrfs -f -L ARCH /dev/mapper/cryptroot
mkfs.btrfs -f -L DATA /dev/mapper/cryptdata
```
Mount btrfs and create subvolumes
```bash
# Cryptroot
# - We set `noatime` to disable updating of the file access time
# every time a file is read. This is done for performance improvements,
# especially on SSDs, and we don't really need to know this information
# anyway.
# - We set `compress=zstd:1` to enable level 1 zstd compression (lowest),
# which still provides quite fast read/write speeds, while saving some space.
mount -o noatime,compress=zstd:1 /dev/mapper/cryptroot /mnt
btrfs subvolume create /mnt/@ # / (root)
btrfs subvolume create /mnt/@home # /home
btrfs subvolume create /mnt/@log # /var/log
btrfs subvolume create /mnt/@cache # /var/cache
btrfs subvolume create /mnt/@tmp # /tmp
btrfs subvolume create /mnt/@data # /data
btrfs subvolume create /mnt/@snapshots
umount /mnt
# cryptdata
# - We use same options for mounting the root btrfs drive as
# we did for cryptroot here, however we will use a bigger compression
# rate for the individual subvolumes when mounting them.
mount -o noatime,compress=zstd:1 /dev/mapper/cryptdata /mnt
btrfs subvolume create /mnt/@data # /data2
btrfs subvolume create /mnt/@backups # /backups
btrfs subvolume create /mnt/@snapshots
umount /mnt
```
Mount the subvolumes and drives
```bash
# cryptroot btrfs subvolumes
mount -o defaults,noatime,compress=zstd:1,subvol=@ /dev/mapper/cryptroot /mnt
mount -o defaults,noatime,compress=zstd:1,subvol=@home /dev/mapper/cryptroot /mnt/home --mkdir
mount -o defaults,noatime,compress=zstd:2,subvol=@log /dev/mapper/cryptroot /mnt/var/log --mkdir
mount -o defaults,noatime,compress=zstd:3,subvol=@cache /dev/mapper/cryptroot /mnt/var/cache --mkdir
mount -o defaults,noatime,compress=no,subvol=@tmp /dev/mapper/cryptroot /mnt/tmp --mkdir
mount -o defaults,noatime,compress=zstd:5,subvol=@data /dev/mapper/cryptroot /mnt/data --mkdir
# cryptdata btrfs subvolumes
mount -o defaults,noatime,compress=zstd:5,subvol=@data /dev/mapper/cryptdata /mnt/data2 --mkdir
mount -o defaults,noatime,compress=zstd:10,subvol=@backups /dev/mapper/cryptdata /mnt/backups --mkdir
# physical partitions
mount /dev/disk/by-label/EFI /mnt/efi --mkdir
mkdir /mnt/efi/arch-1
mount --bind /mnt/efi/arch-1 /mnt/boot --mkdir
swapon /dev/disk/by-label/SWAP
```
## Base installation
```bash
reflector --save /etc/pacman.d/mirrorlist --latest 10 --protocol https --sort rate
pacstrap -K /mnt base linux linux-firmware linux-headers amd-ucode # or intel-ucode
genfstab -U /mnt >> /mnt/etc/fstab
# Note: We'll need to edit fstab later on, to use UUIDs, and to set proper compression levels
# as the generated options will just use zstd:1 everywhere, the final fstab is shown late.
# during bootloader config
arch-chroot /mnt
```
Configure essentials
```bash
pacman -S git btrfs-progs neovim
ln -sf /usr/share/zoneinfo/CET /etc/localtime
hwclock --systohc
sed -i 's/^#en_US.UTF-8/en_US.UTF-8/g' /etc/locale.gen
echo "LANG=en_US.UTF-8" > /etc/locale.conf
locale-gen
echo "pc" > /etc/hostname
passwd
```
## Basic configuration
Clone my dotfiles and run the install script
```bash
git clone --recursive https://github.com/ItsDrike/dotfiles ~/dots
cd ~/dots
./install_root.sh
```
Exit and reenter chroot, this time into zsh shell
```bash
exit
arch-chroot /mnt zsh
```
Create non-privileged user
```bash
useradd itsdrike
usermod -aG wheel itsdrike
install -o itsdrike -g itsdrike -d /home/itsdrike
passwd itsdrike
chsh -s /usr/bin/zsh itsdrike
su -l itsdrike # press q or esc in the default zsh options
```
Setup user account
```bash
git clone --recursive https://github.com/ItsDrike/dotfiles ~/dots
cd ~/dots
./install_user.sh
```
Exit (logout) the user and relogin, this time into configured zsh shell
```bash
exit
su -l itsdrike
```
Install astronvim
```bash
git clone https://github.com/AstroNvim/AstroNvim ~/.config/nvim
git clone https://github.com/ItsDrike/AstroNvimUser ~/.config/nvim/lua/user
```
## Auto-mounting encrypted partitions
We've created a LUKS encrypted partition to store our date into, however it
would be very inconvenient to have to mount it ourselves on each boot. Instead,
we'll probably want to set up a way to mount them automatically. Leaving only
the root partition that we'll need to enter a password for on boot.
### Key files
LUKS encryption has support for multiple keys to the same parition. We'll
utilize this support and add 2nd key slot to all of the partitions that we wish
to auto-mount.
For this 2nd key slot, we will use a key file, as opposed to the regular
user-entered text, so that we can store this key in the file system directly. We
will later be using this stored key to auto-mount. The key file will contain
random data that will be used as the key.
Note that it is very important to have these key files themselves stored on an
encrypted partition, in this case, we're storing them in /etc/secrets, and our
root is encrypted. If you don't have encrypted root partition, it is unsafe to
keep those files in there!
Note that you don't actually need the key files, and if you wish, you can also
be prompted to enter a password on each boot instead (for every partition). You
should prefer this approach if your root partition isn't encrypted, although
know that this can get pretty annoying with more than one encrypted device. If
you wish to do this, you can skip this section.
```bash
exit # Go back to root account
mkdir -p /etc/secrets
dd if=/dev/random bs=4096 count=1 of=/etc/secrets/keyFile-data.bin
chmod -R 400 /etc/secrets
chmod 700 /etc/secrets
```
The bs argument signifies a block size (in bits), so this will create 4096-bit keys.
Now we can add this key into our LUKS encrypted data partition:
```bash
cryptsetup luksAddKey /dev/disk/by-label/DATA --new-keyfile /etc/secrets/keyFile-data.bin
```
### /etc/crypttab
Now that we have the key files ready, we can utilize /etc/crypttab, which
is a file that systemd reads during boot (similarly to /etc/fstab), and contains
instructions for auto-mounting devices.
This is the `/etc/crypttab` file that I use:
<!-- markdownlint-disable MD010 MD013 -->
```txt
# Configuration for encrypted block devices.
# See crypttab(5) for details.
# NOTE: Do not list your root (/) partition here, it must be set up
# beforehand by the initramfs (/etc/mkinitcpio.conf).
# <name> <device> <password> <options>
cryptdata LABEL=DATA /etc/secrets/keyFile-data.bin discard
```
<!-- markdownlint-enable MD010 MD013 -->
If you want to be prompted for the password during boot instead of it being read
from a file, you can use `none` instead of the file path.
The `discard` option is specified to enable TRIM on SSDs, which should improve
their lifespan. It is not necessary if you're using an HDD.
### /etc/fstab
While the crypttab file opens the encrypted block devices and creates the mapper
interfaces for them, to mount those to a concrete directory, we still use
/etc/fstab. Below is the /etc/fstab that I use on my system:
<!-- markdownlint-disable MD010 MD013 -->
```txt
# Static information about the filesystems.
# See fstab(5) for details.
# <file system> <dir> <type> <options> <dump> <pass>
# region: Physical partitions
# /dev/nvme0n1p2 LABEL=SWAP UUID=d262a2e5-a1a3-42b1-ac83-18639f5e8f3d
/dev/disk/by-label/SWAP none swap defaults 0 0
# /dev/nvme0n1p1 LABEL=EFI UUID=44E8-EB26
/dev/disk/by-label/EFI /efi vfat rw,relatime,fmask=0137,dmask=0027,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro 0 2
# endregion
# region: BTRFS subvolumes on /dev/disk/by-label/ARCH (decrypted from ARCH_LUKS)
# /dev/mapper/cryptroot LABEL=ARCH UUID=bffc7a62-0c7e-4aa9-b10e-fd68bac477e0
/dev/mapper/cryptroot / btrfs rw,noatime,compress=zstd:1,ssd,space_cache=v2,subvol=/@ 0 1
/dev/mapper/cryptroot /home btrfs rw,noatime,compress=zstd:1,ssd,space_cache=v2,subvol=/@home 0 1
/dev/mapper/cryptroot /var/log btrfs rw,noatime,compress=zstd:2,ssd,space_cache=v2,subvol=/@log 0 1
/dev/mapper/cryptroot /var/cache btrfs rw,noatime,compress=zstd:3,ssd,space_cache=v2,subvol=/@cache 0 1
/dev/mapper/cryptroot /tmp btrfs rw,noatime,compress=no,ssd,space_cache=v2,subvol=/@tmp 0 1
/dev/mapper/cryptroot /data btrfs rw,noatime,compress=zstd:5,ssd,space_cache=v2,subvol=/@data 0 2
/dev/mapper/cryptroot /.btrfs btrfs rw,noatime,ssd,space_cache=v2 0 2 # btrfs root
# /dev/mapper/cryptdata LABEL=DATA UUID=...
/dev/mapper/cryptdata /data2 btrfs rw,noatime,compress=zstd:5,ssd,space_cache=v2,subvol=/@data 0 2
/dev/mapper/cryptdata /backups btrfs rw,noatime,compress=zstd:10,ssd,space_cache=v2,subvol=/@backups 0 2
/dev/mapper/cryptdata /.btrfs-data btrfs rw,noatime,ssd,space_cache=v2 0 2 # btrfs root
# endregion
# region: Bind mounts
# Write kernel images to /efi/arch-1, not directly to efi system partition (esp), to avoid conflicts when dual booting
/mnt/efi/arch-1 /boot none rw,fmask=0022,dmask=0022,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro,bind 0 0
# endregion
```
<!-- markdownlint-enable MD010 MD013 -->
## Bootloader
This guide uses systemd-boot (if you want to use GRUB, just follow the arch wiki).
### Ask for LUKS password from initramfs
Ask for encryption password of the root partition in early userspace (only
relevant if you're using LUKS encryption), you'll also need to set cryptdevice
kernel parameter, specifying the device that should be unlocked here, and the
device mapping name. (shown later)
```bash
# Find the line with HOOKS=(...)
# Add `keyboard keymap` after `autodetect` (if these hooks are already there,
# just keep them, but make sure they're after `autodetect`).
# Lastly add `encrypt` before `filesystems`.
nvim /etc/mkinitcpio.conf
```
This will configure `mkinitcpio` to build support for the keyboard input, and
support for decrypting LUKS devices from within the initial ramdisk
environment.
If you wish, you can also follow the instructions below to auto-enable numlock:
```bash
sudo -u itsdrike yay -S mkinitcpio-numlock
# Go to HOOKS and add `numlock` after `keyboard` in:
nvim /etc/mkinitcpio.conf
```
Now regenerate the initial ramdisk environment image:
```bash
mkinitcpio -P
```
### Configure systemd-boot
Install systemd-boot to the EFI system partition (ESP)
```bash
bootctl --esp-path=/efi install
# This might report a warning about permissions for the /efi mount point,
# these were addressed in the fstab file above (changed fmask and dmask),
# if you copied those to your fstab, the permissions will be fixed after reboot
```
Add boot menu entries
(Note that we're using LABEL= for cryptdevice, for which `udev` must be before
the `encrypt` hook in mkinitcpio `HOOKS`. This should however be the case by default.
If you wish, you can also use UUID= or just /dev/XYZ here)
Create a new file - `/efi/loader/entries/arch-hyprland.conf`, with:
```bash
title Arch Linux (Hyprland)
sort-key 0
linux /arch-1/vmlinuz-linux
initrd /arch-1/amd-ucode.img
initrd /arch-1/initramfs-linux.img
options cryptdevice=LABEL=ARCH_LUKS:cryptroot:allow-discards
options root=/dev/mapper/cryptroot rootflags=subvol=/@
options rw loglevel=3
```
And finally configure loader - `/efi/loader/loader.conf` (overwrite the contents):
```bash
default arch-hyprland.conf
timeout 4
console-mode auto
editor yes
auto-firmware yes
beep no
```
**Reboot**
```bash
exit # go back to live iso (exit chroot)
reboot
```
## Post-setup
Enable Network Time Protocol (time synchronization)
```bash
sudo timedatectl set-ntp true
timedatectl status
```
Connect to a wifi network
```bash
nmtui
```
## Footnotes
Note that this setup is based on my personal system, in which I dual boot
multiple (2) arch instances, one running hyprland, the other running KDE (I
mainly use the hyprland instance, the KDE one is purely there because it's X11
and supports my NVidia card, which Hyprland currenly doesn't).
The config here only really mentions how to get the first (hyprland)
installation ready, however if you wanted to set up both, it's essentially just
doing the same thing again, with some minor changes like in the systemd-boot
entry and some fstab/crypttab entries.
I do plan on writing a continuation guide for how to set up the system for GUI
(Hyprland) too eventually. Once it's done, I will mention it here.

View file

@ -1,423 +0,0 @@
# Secure boot + TPM unlocking
This guide assumes you already have a working Arch Linux system, set up by following the `installation.md` guide. That means you have an encrypted root partition, and that your computer has a TPM module.
This should mean that currently, every time you boot, you have to enter the LUKS password to decrypt your root partition. This can be pretty annoying though, and this guide aims to fix that, without compromising security.
Once finished, this will basically store the decryption key to your root partition in the TPM module, and so on boot, you'll be able to do so without manually entering your password. This is still perfectly secure, assuming you have a good login screen (in my case, I just use the default linux tty, which I trust fully), and you don't allow anyone to modify the kernel command line (which won't be possible due to secure boot, you'd have to re-sign the images to do so).
So, if the laptop gets stolen, and the drive is pulled out, it's contents will be LUKS encrypted, so the security here is the same. If the attacker boots up the system on the laptop, they will get past encryption, however they'll only see a login screen, and they'd have to also get past linux authentication to actually get anywhere, making this approach safe enough.
## Setup Unified Kernel Image (UKI)
A Unified Kernel Image is a single executable (`.efi` file), which can be booted directly from UEFI firmware, or be
automatically sourced by boot loaders with no extra configuration.
A UKI will include:
- a UEFI stub loader like (systemd-stub)
- the kernel command line
- microcode
- an initramfs image
- a kernel image
- a splash screen
To set up secure boot, this is a requirement, as it's something that can be signed and represents an immutable
executable used for booting into your system.
This is good, because with a standalone bootloader, you would be allowed you to edit the kernel parameters, or even
change the kernel image by editing the configuration inside of the (unencrypted) EFI partition. This is obviously
dangerous, and we don't want to allow this.
### Define kernel command line
Since UKI contains the kernel command line, we will need to define it so that when the image is being built, it can
pick it up.
This is a crucial step especially when you have encryption set up, as without it, the kernel wouldn't know what root
partition to use.
To set this up, we will use `/etc/kernel/cmdline`.
This is how I setup my kernel arguments (If you're unsure what arguments you need, just check your current
systemd-boot configuration, if you followed `installation.md`, you will have it in:
`/efi/loader/entries/arch-hyprland.conf`, all of the `options=` line contain kernel command line args):
```bash
echo "rw loglevel=3" > /etc/kernel/cmdline
echo "cryptdevice=LABEL=ARCH_LUKS:cryptroot:allow-discards" >> /etc/kernel/cmdline
echo "root=/dev/mapper/cryptroot rootflags=subvol=/@" >> /etc/kernel/cmdline
```
Note that you **shouldn't** be specifying the `cryptdevice` or `root` kernel parameters if you're using `systemd`
initramfs, rather than `udev` one (you do still need `rootflags` to select the btrfs subvolume though, unless the
root partition is your default subvolume). (If you haven't messed with it, you will be using `udev` initramfs).
### Modify the linux preset for mkinitcpio to build UKIs
Now open `/etc/mkinitcpio.d/linux.preset`, where you'll want to:
- Uncomment `ALL_config`
- Comment `default_image`
- Uncomment `default_uki` (unified kernel image)
- Uncomment `default_options`
- Comment `fallback_image`
- Uncomment `fallback_uki`
### Recreate /efi
First, we'll need to unmount `/mnt/boot`, which is currently bind mounted to `/efi/EFI/arch-1`. This is because we'll
no longer be storing the kernel, initramfs nor the microcode in the EFI partition at all. The EFI partition will now
only contain the UKI, the rest can be left in `/boot`, which will now be a part of the root partition, not mounted
anywhere.
```bash
umount /boot
vim /etc/fstab # remove the bind mount entry for /boot
```
Now, we will remove everything in the EFI partition, and start from scratch (this will erase the current systemd-boot configuration, you may want to back it up (`/efi/loader/loader.conf` and `/efi/loader/entries/`))
```bash
rm -rf /efi/*
```
Then, we will create the `/efi/EFI/Linux` directory, which will contain our UKIs. (You can change this location in
`/etc/mkinitcpio.d/linux.preset` if you wish to use some other directory in the EFI partition, however it is
recommended that you stick with Linux).
```bash
mkdir -p /efi/EFI/Linux
```
Finally, we will reinstall the kernel and microcode, populating
`/boot` (now on the root partition).
This will also trigger a initramfs rebuild, which will now create the UKI image based on the `linux.preset` file.
```bash
pacman -S linux amd-ucode
```
### Boot Manager
This step is optional, because the Unified Kernel Images can actually be booted into directly from the UEFI, if you
wish to do that, you can run the following to add them as entries in the UEFI boot menu:
```bash
pacman -S efibootmgr
efibootmgr --create --disk /dev/disk/nvme0n1 --part 1 --label "Arch Linux (Hyprland)" --loader 'EFI\Linux\arch-linux.efi' --unicode
efibootmgr -c -d /dev/disk/nvme0n1 -p 1 -L "Arch Linux (Hyprland) Fallback" -l 'EFI\Linux\arch-linux-fallback.efi' -u
pacman -R systemd-boot
```
You can also specify additional kernel parameters / override the default ones in the UKI, by simply adding a string as
a last positional argument to the `efibootmgr` command, allowing you to create entires with different kernel command
lines easily.
Doing the above is technically safer than going with a boot manager, as it cuts out the middle-man entirely, however it
can sometimes be nice to have boot manager, as it can show you a nice boot menu, and allow you to modify the kernel
parameters, or add entries for different operating systems very easily, without having to rely on the specific
implementation of the boot menu in your UEFI firmware (which might take really long to open, or just generally not
provide that good/clean experience). Because of that, I like to instead still install the `systemd-boot`. To do so, we can
just install normally with:
```bash
bootctl install --esp-path=/efi
```
We can now reboot. Systemd-boot will pick up any UKI images in `/efi/EFI/Linux` automatically (this path is
hard-coded), even without any entry configurations.
That said, if you do wish to do so, you can still add an explicit entry for your configuration in
`/efi/loader/entries/arch-hyprland.conf`:
```
title Arch Linux (Hyprland)
sort-key 0
efi /EFI/Linux/arch-linux.efi
# If you wish, you can also specify kernel options here, it will
# append/override those in the UKI image
#options rootflags=subvol=/@
#options rw loglevel=3
```
Although do note that if your UKI image is stored in `/efi/EFI/Linux`, because systemd-boot picks it up automatically,
you will see the entry twice, so you'll likely want to change the target directory for the UKIs (in
`/etc/mkinitcpio.d/linux.preset`) to something else.
I however wouldn't recommend this approach, and I instead just let systemd-boot autodetect the images, unless you need
something specific.
If everything went well, you should see a new systemd based initramfs, from where you'll be prompted for the LUKS2
password.
## Secure Boot
Now that we're booting with UKIs, we have images that that we'll be able to sign for secure boot, hence only allowing
us to boot from those images.
However before we can set signing up, we will need to create new signing keys, and upload them into secure boot.
### Enter Setup mode
To allow us to upload new signing keys into secure boot, we will need to enter "setup mode". This should be possible
by going to the Secure Boot category in your UEFI settings, and clicking on Delete/Clear certificates, or there could
even just be a "Setup Mode" option directly.
Once enabled, save the changes and boot back into Arch linux.
```bash
pacman -S sbctl
sbctl status
```
Make sure that `sbctl` reports that Setup Mode is Enabled.
### Create Secure Boot keys
We can now create our new signing keys for secure boot. These keys will be stored in `/usr/share/secureboot` (so in
our encrypted root partition). Once created, we will add (enroll) these keys into the UEFI firmware (only possible
when in setup mode)
```bash
sbctl create-keys
# the -m adds microsoft vendor key, required for most HW. Not using it could brick your device.
sbctl enroll-keys -m
```
Note: If you see messages about immutable files, run `chattr -i [file]` for all of the listed immutable files, then
re-run enroll-keys command. (Linux kernel will sometimes mark the runtime EFI files as immutable for security - to
prevent bricking the device with just `rm -rf /*`, or similar stupid commands, however since we trust that `sbctl`
will work and won't do anything malicious, we can just remove the immutable flag, and re-running will now work).
### Sign the bootloader and Unified Kernel Images
Finally then, we can sign the `.efi` executables that we'd like to use:
```bash
sbctl sign -s -o /usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed /usr/lib/systemd/boot/efi/systemd-bootx64.efi
sbctl sign -s /efi/EFI/BOOT/BOOTX64.EFI
sbctl sign -s /efi/EFI/systemd/systemd-bootx64.efi
sbctl sign -s /efi/EFI/Linux/arch-linux.efi
sbctl sign -s /efi/EFI/Linux/arch-linux-fallback.efi
```
(If you're not using `systemd-boot`, only sign the UKI images in `/efi/EFI/Linux`)
The `-s` flag means save: The files will be automatically re-signed when we update the kernel (via a sbctl pacman
hook). To make sure that this is the case, we can run `pacman -S linux` and check that messages about image
signing appear.
When done, we can make sure that everything that needed to be signed really was signed with:
```bash
sbctl verify
```
### Reboot and enable secure boot
We should now be ready to enable secure boot, as our .efi images were signed, and the signing key was uploaded.
```bash
sbctl status
```
If you see Secure Boot marked as Enabled, it worked!
## Set up TPM unlocking
We'll now set up the TPM module to store a LUKS encryption key for our root partition, which it can release if certain
conditions are met (I'll talk about the specific conditions a few sections later). This will allow us to set it up in
such a way, that allows automatic unlocking without having to enter the password at boot.
This is safe, because set up correctly, TPM will only release the password to unlock the drive if there wasn't any
editing done to the way the system was booted up, in which case we should always end up at a lockscreen after the
bootup, which will be our line of defense against attackers, rather than it being the encryption password itself.
Do make sure that if you go this route, your lockscreen doesn't have any vulnerabilities and can't be easily bypassed.
In my case, I'm using the default linux account login screen, which I do trust is safe enough to keep others without
password out. I also have PAM set up in such a way that after 3 failed attempts, the account will get locked for 10
minutes, which should prevent any brute-force attempts (this is actually the default).
Since TPM is a module integrated in the CPU or the motherboard, so if someone took out the physical drive with the
encrypted data, they would still need to have a LUKS decryption key to actually be able to read the contents of the
root partition.
### Make sure you have a TPM v2 module
```bash
pacman -S tpm2-tss tpm2-tools
```
Verify that your system does actually have a TPM v2 module
```bash
systemd-cryptenroll --tpm2-device=list
```
Make sure that there is a device listed.
### Switch from udev initramfs to systemd
By default, your initramfs will be using `udev`, however you can instead use `systemd`, which has a bunch of extra
capabilities, such as being able to pick up the key from TPM2 chip.
Open `/etc/mkinitcpio.conf` and find a line that starts with `HOOKS=`
- Change `udev` to `systemd`
- Change `keymap consolefont` to `sd-vconsole`
- Add `sd-encrypt` before `block`, and remove `encrypt`
- If you were using `mkinitcpio-numlock`, also remove `numlock`, it doesn't work with systemd
(As an alternative to `mkinitcpio-numlock`, there is `systemd-numlockontty`, which creates a systemd service that
enables numlock in TTYs after booting (you'll need to enable it), this however doesn't happen in initramfs directly,
only aftwerwars. This shouldn't be too annoying though, as we'lll no longer have to be entering the encryption
password, which is the only reason we'd need numlock in initramfs anyway.)
Additionally, with systemd initramfs, you shouldn't be specifying `root` nor `cryptdevice` kernel arguments, as systemd
can actually pick those up automatically (they'll be discovered by
[systemd-cryptsetup-generator](https://wiki.archlinux.org/title/Dm-crypt/System_configuration#Using_systemd-cryptsetup-generator)
and auto-mounted from initramfs via
[systemd-gpt-auto-generator](https://wiki.archlinux.org/title/Systemd#GPT_partition_automounting)). We will however
still need the `rootflags` argument for selecting the btrfs subvolume (unless your default subvolume is the root
partition subvolume).
So, let's edit our kernel parameters:
```bash
echo "rw loglevel=3" > /etc/kernel/cmdline # overwrite the existing cmdline
echo "rootflags=subvol=/@" >> /etc/kernel/cmdline
```
You'll also need to modify the `/etc/fstab`, as systemd will not use the `/dev/mapper/cryptroot` name, but rather
you'll have a `/dev/gpt-auto-root` (there'll also be `/dev/gpt-auto-root-luks`, which is the encrypted partition). If
you absolutely insist on using a mapper device, you can also use `/dev/mapper/root` though, which is what systemd
will actually call it.
```bash
vim /etc/fstab
```
We can now regenerate the initramfs with: `pacman -S linux` (we could also do `mkinitcpio -P`, however that won't
trigger the pacman hook which auto-signs our final UKI images, so we'd have to re-sign them with `sbctl` manually)
and reboot to check if it worked.
### Choosing PCRs
PCR stands for Platform Configuration Register, and all TPM v2 modules have a bunch of these registers, which hold
hashes about the system's state. These registers are read-only, and their value is set by the TPM module itself.
The data held by the TPM module (our LUKS encryption key) can then only be accessed when all of the selected PCR
registers contain the expected values. You can find a list of the PCR registers on [Arch
Wiki](https://wiki.archlinux.org/title/Trusted_Platform_Module#Accessing_PCR_registers).
You can look at the current values of these registers with this command:
```bash
systemd-analyze pcrs
```
For our purposes, we will choose these:
- **PCR0**: Hash of the UEFI firmware executable code (may change if you update UEFI)
- **PCR7**: Secure boot state - contains the certificates used to validate each boot application
- **PCR12**: Overridden kernel command line, credentials
> [!IMPORTANT]
> If you're using systemd-boot (instead of booting directly from the UKI images), it is very important that we choose
> all 3, including PCR12, as many tutorials only recommend 0 and 7, which would however lead to a security hole, where
> an attacker would be able to remove the drive with the (unencrypted) EFI partition, and modify the systemd-boot
> loader config (`loaders/loader.conf`), adding `editor=yes`, and the put the drive back in.
>
> This wouldn't violate secure boot, as the `.efi` image files were unchanged, and are still signed, so the attacker
> would be able to boot into the systemd-boot menu, from where they could edit the boot entry for our UKI and modify
> the kernel parameters (yes, even though UKIs contain the kernel command line inside of them, systemd-boot can still
> edit those arguments if `editor=yes`).
>
> From there, the attacker could simply add a kernel argument like `init=/bin/bash`, which would bypass systemd as the
> init system and instead make the kernel run bash executable as the PID=1 (init) program. This would mean you would
> get directly into bash console that is running as root, without any need to enter a password.
>
> However, with PCR12, this is prevented, as it detects that the kernel cmdline was overridden, and so the TPM module
> wouldn't release the key.
The nice thing about also selecting PCR12 is that it will even allow us to securely keep `editor=yes` in our
`loader.conf`, for easy debugging, as all that will happen if we do edit the kernel command line will be that the TPM
module will not release the credentials, and so the initramfs will just ask us to enter the password manually.
### Generate recovery key
The following command will generate a new LUKS key and automatically add it to the encrypted root. You will be prompted
for a LUKS password to this device.
This step is optional, as all it does is adding another LUKS keyslot with a generated recovery key, so that in case TPM
wouldn't unlock the drive, you can use this key instead.
You're expected to delete your own key, which is assumed to be less secure than
what this will generate. We will do this after the next step.
If you instead wish to keep your own key working, feel free to skip this step, and the key removal step later.
```bash
systemd-cryptenroll /dev/gpt-auto-root-luks --recovery-key
```
### Enroll the key into TPM
The following command will enroll a new key into the TPM module and add it as a new keyslot of the specified LUKS2 encrypted device.
We also specify `--tpm2-pcrs=0+7+12`, which selects the PCR registers that we decided on above.
Note: If you already had something in the tpm2 moudle, you will want to add `--wipe-slot=tpm2` too.
You will be prompted for a LUKS password to this device (you can still enter your original key, you don't need to use
the recovery one, as we haven't deleted the original one yet).
```bash
systemd-cryptenroll --tpm2-device=auto --tpm2-pcrs=0+7+12 /dev/gpt-auto-root-luks
```
This will enroll the TPM2 token token as a key slot 2 for the encrypted drive.
If you're extra paranoid, you can also provide `--tpm2-with-pin=yes`, to prompt for a PIN code on each boot.
To check that it worked, you can use:
```bash
cryptsetup luksDump /dev/gpt-auto-root-luks
```
Make sure that there is an additional LUKS key slot.
### Remove original key
This is an optional step, only follow it if you have generated and properly stored a recovery key.
**Warning:** Make absolutely certain that the recovery key does in fact work before doing this, otherwise, you may get
locked out! You can test your recovery key with:
```bash
cryptsetup luksOpen /dev/gpt-auto-root-luks crypttemp # enter the recovery key
cryptsetup luksClose crypttemp
```
If this worked, proceed to:
```bash
cryptsetup luksRemoveKey /dev/disk/by-label/ARCH_LUKS # Enter your key to be deleted
```
### Reboot
After a reboot, the system should now get unlocked automatically without prompting for the password.
### Remove key from TPM
In case you'd ever want to remove the LUKS key from TPM, you can do so simply with:
```bash
csystemd-cryptenroll --wipe-slot=tpm2
```
This will actually also remove the LUKS key from the `/dev/gpt-auto-root-luks` device.