37 KiB
title | date | lastmod | tags | author | ||||
---|---|---|---|---|---|---|---|---|
Desktop Linux Hardening | 2022-08-17 | 2022-08-18 |
|
Tommy |
Linux is not a secure operating system. However, there are steps you can take to harden it, reduce its attack surface and improve its privacy.
Before We Start...
This guide is largely based on Madaidan's Linux hardening guide; however, it does take into account usability and ease of maintenance of each recommendation. The goal is to produce a guide that intermediate to advanced Linux users can reasonably follow to set up and maintain the security configurations. It will also not try to be distribution agnostic, and there will be many distribution specific recommendations.
Some of the sections will include mentions of unofficial builds of packages like linux-hardened
, lkrg-akmod
, hardend-malloc
, and so on. These are not endorsements. They are merely there to show you that you have an option to easily obtain and update these packages. Using unofficial builds of packages means adding more parties to trust, and you have to evaluate whether it is worth doing so for the potential privacy or security benefits or not.
During Installation
Drive Encryption
Most Linux distributions have an option within its installer for enabling LUKS full disk encryption. If this option isn’t set at installation time, you will have to backup your data and re-install, as encryption is applied after disk partitioning, but before file systems are formatted.
Encrypted Swap
Consider using encrypted swap or ZRAM instead of unencrypted swap to avoid potential security issues with sensitive data being pushed to swap space. While ZRAM can be set up post-installation, if you want to use encrypted swap, you should set it up while partitioning your drive.
Depending on your distribution, encrypted swap may be automatically set up if you choose to encrypt your drive. Fedora uses ZRAM by default, regardless of whether you enable drive encryption or not.
Privacy Tweaks
MAC Address Randomization
Many desktop Linux distributions (Fedora, openSUSE, etc) will come with NetworkManager, to configure Ethernet and Wi-Fi settings.
It is possible to randomize the MAC address when using NetworkManager. This provides a bit more privacy on Wi-Fi networks as it makes it harder to track specific devices on the network you’re connected to. It does not make you anonymous.
I recommend changing the setting to random instead of stable, as suggested in the article.
If you are using systemd-networkd, you will need to set MACAddressPolicy=random
which will enable RFC 7844 (Anonymity Profiles for DHCP Clients).
There isn’t much point in randomizing the MAC address for Ethernet connections as a system administrator can find you by looking at the port you are using on the network switch. Randomizing Wi-Fi MAC addresses depends on support from the Wi-Fi’s firmware.
Other Identifiers
There are other system identifiers which you may wish to be careful about. You should give this some thought to see if it applies to your threat model:
- Hostnames: Your system's hostname is shared with the networks you connect to. You should avoid including identifying terms like your name or operating system in your hostname, instead sticking to generic terms or random strings.
- Usernames: Similarly, your username is used in a variety of ways across your system. Consider using generic terms like "user" rather than your actual name.
- Machine ID:: During installation a unique machine ID is generated and stored on your device. Consider setting it to a generic ID.
System Counting
Many Linux distributions sends some telemetry data by default to count how many systems are using their software. Consider disabling this depending on your threat model.
The Fedora Project does this by counting how many unique systems access its mirrors by using a countme
variable instead of a unique ID.
This option is currently off by default. However, you could add countme=false
to /etc/dnf/dnf.conf
just in case it is enabled in the future. On systems that use rpm-ostree such as Fedora Silverblue or Kinoite, the countme
option can be disabled by masking the rpm-ostree-countme timer.
openSUSE uses a unique ID to count systems, which can be disabled by deleting the /var/lib/zypp/AnonymousUniqueId
file.
Zorin OS uses the zorin-os-cencus
package, which also uses a unique ID to count systems. You can opt out of this by doing sudo apt purge zorin-os-census
, and optionally hold it with sudo apt-mark hold zorin-os-census
to avoid accidentally installing it in the future.
Snapd assigns a unique ID to your snapd installation and use it for telemetry. While this is generally not a problem, if your threat model calls for anonymity, you should not be using snap packages, and you should remove snapd from your Ubuntu installation. Like with Zorin Census, on Debian based distributions, and especially Ubuntu, consider holding snapd
with sudo apt-mark hold snapd
.
Of course, this is a non-exhaustive list of how different Linux distributions do this. If you are aware of any other tracking mechanisms that different distributions use, feel free to make a pull request or discussion post detailing them!
Keystroke Anonymization
You could be fingerprinted based on soft biometric traits when you use the keyboard. The Kloak package could help you mitigate this threat. It is available as a .deb package from Kicksecure's repository and an AUR package.
With that being said, if your threat model calls for using something like Kloak, you are probably better off just using Whonix.
Application Confinement
Some sandboxing solutions for desktop Linux distributions do exist; however, they are not as strict as those found in macOS or ChromeOS. Applications installed from the package manager (dnf
, apt
, etc.) typically have no sandboxing or confinement whatsoever. Below are a few projects that aim to solve this problem:
Flatpak
{{< youtube id="GkgPIJp8_30">}}
Flatpak aims to be a universal package manager for Linux. One of its main goals is to provide a universal package format which can be used in most Linux distributions. It provides some permission control. With that being said, Flatpak sandboxing is quite weak.
You can restrict applications further by issuing Flatpak overrides. This can be done with the command-line or by using Flatseal. Some sample overrides are provided by me and rusty-snake. Note that this only helps with the lax high level default permissions, but cannot solve the low level issues like /proc
and /sys
access, or an insufficient seccomp blacklist.
Some sensitive permissions you should pay attention to:
- the Network (
--share=network
) socket (internet access) - the PulseAudio socket (
--socket=pulseaudio
) for audio and sound --device=all
access to all devices including the camera--talk-name=org.freedesktop.secrets
dbus (access to secrets stored on your keychain) for applications which do not need it
If an application works natively with Wayland (not running through the XWayland compatibility layer), consider revoking its access to the X11 (--socket=x11
) and inter-process communications (IPC) socket (--share=ipc
) as well.
Many Flatpak apps come with broad filesystem permissions such as --filesystem=home
and --filesystem=host
. Some applications implement the Portal API, which allows a file manager to pass files to the Flatpak application (e.g. VLC) without specific filesystem access privileges. Despite this, many of them, including ones like VLC still use --filesystem=host
.
My strategy to deal with this is to revoke all filesystem access first, then test if an application works without it. If it does, it means the app is already using Portals and I don't need to do anything else. If it doesn't, then I start granting permission to specific directories.
As odd as this may sound, you should not automatically update your Flatpak packages. The problem with Flatpak is that it grants install-time permissions when you update your applications, and you will not be notified of the permission change unless you update them manually via the command line.
Snap
Snap is another universal package manager with some sandboxing support. It is developed by Canonical and heavily pushed on Ubuntu.
Snap packages come in two variants: classic snap with no confinement and strict snap with confinement on systems with AppArmor and Cgroupsv1. If a snap package is classic snap, you are better off using a version provided by your distribution's repository instead, if one is available. If your system does not have AppArmor, then you are better off not using snap at all. Most modern systems outside of Ubuntu and its derivatives only use Cgroupsv2 by default, so you have to set systemd.unified_cgroup_hierarchy=0
in your kernel parameters to get Cgroupsv1 working.
Snap permissions can be managed via the Snap Store or Ubuntu's custom patched GNOME Control Center.
One caveat with Snap packages is that you only have control over the interfaces declared in their manifests. For example, snap has separate interfaces for audio-playback
and audio-record
; however, some packages will only declare the legacy pulseaudio
interface which grants them permission to both play and record audio. Likewise, some applications may work perfectly fine with Wayland, but the package maintainer may only declare the X11 interface in their manifest. For these cases, you need to reach out to the maintainer of the Snap package to update the manifest accordingly.
Firejail
{{< youtube id="N-Mso2bSr3o">}}
Firejail is another method of sandboxing. As it is a large setuid binary, it has a large attack surface which may assist in privilege escalation.
Madaidan provided additional details on how Firejail can worsen the security of your device.
If you do use Firejail, there is a tool called Firetools which can help you quickly manage what an application can have access to and launch them. Note that the configurations by Firetools
are temporary and it does not provide you with an option to save a profile for long term use.
Firejail can also confine X11 windows using Xpra or Xephr, something that Flatpak and Snap cannot do. I highly recommend that you check out their documentation on how to set this up.
One trick to consistently launch applications which have a Firejail profile confined is to use the sudo firecfg
command. This will create a symlink in /usr/local/bin/app_name_here
pointing to Firejail. .desktop
files which do not specifically specify the absolute path of the binaries to use will launch the application through the symlink and have Firejail sandbox them this way. Of course, this is bypassable if you or some other applications launch the application directly from /usr/bin/app_name_here
instead.
Mandatory Access Control
Common Linux Mandatory access control frameworks require policy files in order to force constraints on the system.
The two main control systems are SELinux (used on Android and Fedora based distributions) and AppArmor (Used on Debian based distributions and most openSUSE variants).
Fedora includes SELinux preconfigured with some policies that will confine system daemons (background processes). You should keep it in Enforcing mode.
openSUSE gives the choice of AppArmor or SELinux during the installation process. You should stick to the default for each variant (AppArmor for Tumbleweed and SELinux for MicroOS). openSUSE’s SELinux policies are derived from Fedora.
Arch and Arch-based operating systems often do not come with a mandatory access control system and you must manually install and configure AppArmor for it.
Note that unlike Android, traditional desktop Linux distributions typically do not have full system Mandatory Access Control policies, and only a few system daemons are actually confined.
Making Your Own Policies/Profiles
You can make your own AppArmor profiles, SELinux policies, Bubblewrap profiles, and seccomp blacklist to have better confinement of applications. This is an advanced and sometimes tedious task, so I won’t go into detail about how to do it here, but there are a few projects that you could use as reference.
- Whonix’s AppArmor Everything
- Krathalan’s AppArmor profiles
- noatsecure’s SELinux templates
- Seirdy’s Bubblewrap scripts
Securing Linux Containers
If you’re running a server, you may have heard of Linux Containers. They are more common in server environments where individual services are built to operate independently. However, you may sometimes see them on desktop systems as well, especially for development purposes.
Docker is one of the most common container solutions. It is not a proper sandbox, and this means that there is a large kernel attack surface. You should follow the Docker and OCI Hardening guide to mitigate this problem. In short, there are things you can do like using rootless containers (either through configuration or through using Podman), using a runtime which provides a psuedo-kernel for each container (gVisor), and so on.
Another option is Kata containers, where virtual machines masquerade as containers. Each Kata container has its own Linux kernel and is isolated from the host.
Security Hardening
Umask 077
If you are not using openSUSE, consider changing the default umask for both regular user accounts and root to 077. Changing umask to 077 can break snapper on openSUSE and is not recommended.
The configuration for this varies per distribution, but typically it can be set in /etc/profile
, /etc/bashrc
, or /etc/login.defs
.
Note that unlike on macOS, this will only change the umask for the shell. Files created by running applications will not have their permissions set to 600.
Firewalls
A firewall may be used to secure connections to your system.
Red Hat distributions (such as Fedora) are typically configured through firewalld. Red Hat has plenty of documentation regarding this topic. There is also the Uncomplicated Firewall which can be used as an alternative.
You could also set your default firewall zone to drop packets. If you're on a Red Hat or SUSE based distribution such as Fedora this can be done with the following commands:
firewall-cmd --set-default-zone=drop
firewall-cmd --add-protocol=ipv6-icmp --permanent
firewall-cmd --add-service=dhcpv6-client --permanent
All these firewalls use the Netfilter framework and therefore cannot protect against malicious programs running on the system. A malicious program could insert its own rules.
There are some per-binary outbound firewalls such as OpenSnitch or Portmaster that you could use as well. But just like firewalld and UFW, they are bypassable.
If you are using Flatpak packages, you can revoke their network socket access using Flatseal and prevent those applications from accessing your network. This permission is not bypassable.
If you are using non-classic Snap packages on a system with proper snap confinement support (with both AppArmor and cgroups v1 present), you can use the Snap Store to revoke network permission as well. This is also not bypassable.
Kernel Hardening
There are some additional kernel hardening options such as configuring sysctl keys and kernel command-line parameters which are described in the Madaidan's guide. You should read through them before applying these changes.
Madaidan recommends that you disable unprivileged user namespaces due to it being responsible for various privilege escalation vulnerabilities. However, some software such as Podman and LXD require unprivileged user namespaces to function. If you decide that you want to use these technologies, do not disable kernel.unprivileged_userns_clone
.
If you are using KickSecure or Whonix, most of these hardening have already been done for you thanks to security-misc. If you are using a Debian, you should consider morphing it into KickSecure. On other distributions, you can copy the configurations from the following files to use:
/etc/sysctl.d/30_security-misc.conf
/etc/sysctl.d/30_silent-kernel-printk.conf
/etc/modprobe.d/30_security-misc.conf
Note that these configurations do not disable unprivileged user namespaces. There are also a few things in /etc/modprobe.d/30_security-misc.conf
to keep in mind:
- The
bluetooth
andbtusb
kernel modules are disabled by default. You need to comment outinstall bluetooth /bin/disabled-bluetooth-by-security-misc
andinstall btusb /bin/disabled-bluetooth-by-security-misc
if you want to use Bluetooth. - Apple filesystems are disabled by default. This is generally fine on non-Apple systems; however, if you are using Linux on an Apple product, you must check what filesystem your EFI partition uses. For example, if your EFI filesystem is HFS+, you need to comment out
install hfsplus /bin/disabled-filesys-by-security-misc
, otherwise your computer will not be able to boot into Linux.
Harding Boot Parameters
Read through this section on how to harden your boot parameters:
Kicksecure comes with these boot parameters by default. This section is fairly short, so I'd recommend that you read it through. With that being said, here are all of the parameters that you would need:
slab_nomerge init_on_alloc=1 init_on_free=1 page_alloc.shuffle=1 pti=on vsyscall=none debugfs=off oops=panic module.sig_enforce=1 lockdown=confidentiality mce=0 quiet loglevel=0 spectre_v2=on spec_store_bypass_disable=on tsx=off tsx_async_abort=full,nosmt mds=full,nosmt l1tf=full,force nosmt=force kvm.nx_huge_pages=force
Note that SMT is disabled due to it being the cause of various security vulnerabilities. Also, on rpm-ostree based distributions, you should set the kernel parameters using rpm-ostree kargs
rather than messing with grub configurations directly.
Restricting access to /proc and /sys
You should read these 2 sections in Madaidan's guide to further reduce the attack surface on the kernel:
Disabling access to /sys
without a proper whitelist will lead to various applications breaking. This will unfortunately be an extremely tedious process for most users. Kicksecure, and by extension, Whonix, has the experimental proc-hidepid and hide-hardware-info services which do just this. From my testing, these work perfectly fine on minimal Kicksecure installations and both Qubes-Whonix Workstation and Gateway.
linux-hardened
Some distributions like Arch Linux have the linux-hardened kernel package. It includes hardening patches and more security-conscious defaults. There is an unofficial build of linux-hardened by HardHatOS, though it is not signed with a secure boot key like the official Fedora kernel, unfortunately.
linux-hardened has kernel.unprivileged_userns_clone=0
disabled by default as well. See the note above about how this might impact you.
Linux Kernel Runtime Guard (LKRG)
LKRG is a kernel module that performs runtime integrity check on the kernel to help detect exploits against the kernel. LKRG works in a post-detect fashion, attempting to respond to unauthorized modifications to the running Linux kernel. While it is bypassable by design, it does stop off-the-shelf malware that does not specifically target LKRG itself. This may make exploits harder to develop and execute on vulnerable systems.
If you can get LKRG and maintain module updates, it provides a worthwhile improvement to security. Debian-based distributions can get the LKRG DKMS package from KickSecure's repository and the KickSecure documentation has installation instructions. Once again, if you are using Debian, consider morphing it into KickSecure. It should be noted that KickSecure does not currently install LKRG by default, and you will need to run sudo apt install lkrg-dkms linux-headers-amd64
to obtain it.
On Fedora, fepitre, a QubesOS developer, has a COPR repository where you can install it. Arch based systems can obtain the LKRG DKMS package via an AUR package.
grsecurity
grsecurity is a set of kernel patches that attempt to improve security of the Linux kernel. It requires payment to access the code and is worth using if you have a subscription.
Disabling Simultaneous Multithreading (SMT)
SMT has been the cause of numerous hardware vulnerabilities, and subsequent patches for those vulnerabilities often come with performance penalties that negate a lot of the performance gain given by SMT. If you followed the “Hardening Boot Parameters” section above, some kernel parameters already disable SMT. If the option is available to you, I recommend that you disable it in your firmware as well.
Hardened Memory Allocator
The hardened memory allocator from GrapheneOS can also be used on general Linux distributions. It is available as an AUR package on Arch based distributions, and (though not enabled by default) on Whonix and Kicksecure.
On Fedora, there are currently 2 builds for it:
If you are using Whonix, Kicksecure or have Hardened_Malloc installed somewhere, consider setting up LD_PRELOAD
as described in the Kicksecure Documentation or Arch Wiki.
Mountpoint Hardening
Consider adding the following options nodev
, noexec
, and nosuid
to mountpoints which do not need them. Typically, these could be applied to /boot
, /boot/efi
, and /var
.
These flags could also be applied to /home
and /root
as well, however, noexec
will prevent applications from working that require binary execution in those locations. This includes products such as Flatpak and Snap. It should also be noted that this is not fool proof, as noexec
is bypassable. You can see an example of that here
If you use Toolbox, you should not set any of those options on /var/log/journal
. From my testing, the Toolbox container will fail to start if you have nodev
, nosuid
, or noexec
on said directory. If you are on Arch Linux, you probably would not want to set noexec
on /var/tmp
, as it will make some AUR packages fail to build.
Disabling SUID
SUID allows a user to execute an application as the owner of that application, which in many cases, would be the root
user. Vulnerable SUID executables could lead to privilege escalation vulnerabilities.
It is desirable to remove SUID from as many binaries as possible; however, this takes substantial effort and trial and error on the user's part, as some applications require SUID to function.
Kicksecure, and by extension, Whonix has an experimental permission hardening service and application whitelist to automate SUID removal from most binaries and libraries on the system. From my testing, these work perfectly fine on a minimal Kicksecure installation and both Qubes-Whonix Workstation and Gateway.
If you are using Kicksecure or Whonix, consider enabling the permission-hardening
service.
Securing Time Synchronization
Most Linux distributions by default (especially distributions with systemd-timesyncd
) use NTP for time synchronization which is unencrypted and unauthenticated. There are two ways to easily solve this problem:
- Configure NTS with chronyd
- Use sdwdate on Debian based distributions.
If decide on using NTS with chronyd, consider using multiple different sources to synchronize your time with, and require at least half or more of those providers to actually change the time on your system.
GrapheneOS actually uses a quite nice configuration for this with their infrastructure. I recommend that you replicate their chrony.conf
on your system.
Linux Pluggable Authentication Modules (PAM)
The security of PAM can be hardened to allow secure authentication to your system.
On Red Hat distributions you can use authselect
to configure this e.g.:
sudo authselect select <profile_id, default: sssd> with-faillock without-nullok with-pamaccess
On systems where pam_faillock
is not available, consider using pam_tally2
instead.
If you have a Yubikey, you can also use the pam_u2f
module to require second factor authentication for your login. Follow the Arch Wiki documentation for this. Note that you must set a non-transient hostname before setting this up, as you will not be able to login when your hostname changes.
USB Port Protection
To better protect your USB ports from attacks such as BadUSB, I recommend USBGuard. USBGuard has documentation as does the Arch Wiki.
Another alternative option if you’re using the linux-hardened is the deny_new_usb
sysctl. See Preventing USB Attacks with linux-hardened
.
Secure Boot
Secure Boot can be used to secure the boot process by preventing the loading of unsigned UEFI drivers or boot loaders.
One of the problems with Secure Boot, particularly on Linux is, that only the chainloader (shim), the boot loader (GRUB), and the kernel are verified and that's where verification stops. The initramfs is often left unverified, unencrypted, and open up the window for an evil maid attack. The firmware on most devices is also configured to trust Microsoft's keys for Windows and its partners, leading to a large attacks surface.
To eliminate the need to trust Microsoft's keys, either follow the "Using your own keys" section on the Arch Wiki or use sbctl. The important thing that needs to be done here is to replace the OEM's key with your own Platform Key.
There are several ways to work around the unverified initramfs:
Encrypted /boot
The first way is to encrypt the /boot partition. If you are on Fedora Workstation (not Silverblue), you can follow this guide to convert the existing installation to encrypted /boot
. openSUSE comes with this that by default.
Encrypting /boot
however have its own issues, one being that GRUB only supports LUKS1 and not the newer default LUKS2 scheme. As the bootloader runs in protected mode and the encryption module lacks SSE acceleration so the boot process will take minutes to complete. Another problem with this is that you have to type the encryption password twice, which could be solved by following the openSUSE Wiki.
There are a few options depending on your configuration:
- If you enroll your own keys as described above, and your distribution supports Secure Boot by default, you can add your distribution's EFI Key into the list of trusted keys (db keys). It can then be enrolled into the firmware. Then, you should move all of your keys off your local storage device.
- If you enroll your own keys as described above, and your distribution does not support Secure Boot out of the box (like Arch Linux), you have to leave the keys on the disk and setup automatic signing of the kernel and bootloader. If you are using Grub, you can install it with the
--no-shim-lock
option and remove the need for the chainloader.
Unified Kernel Image
The second option is to creating an Unified Kernel Image that contains the kernel, initramfs, and microcode. This EFI stub can then be signed. I recommend using sbctl to generate such EFI image. This option also requires you to leave the keys on the disk to setup automatic signing, which weakens the security model.
Notes
After setting up Secure Boot it is crucial that you set a “firmware password” (also called a “supervisor password”, “BIOS password” or “UEFI password”), otherwise an adversary can simply disable Secure Boot.
These recommendations can make you a little more resistant to evil maid attacks, but they not good as a proper verified boot process such as that found on Android, ChromeOS or Windows.