Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to strengthen the Security of Linux system

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you about how to strengthen the security of the Linux system. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Choose the right Linux distribution

There are many factors in choosing a good Linux distribution.

Avoid distributing frozen packages because they are usually lagging behind in security updates.

Do not use distributions with the Systemd mechanism. Systemd contains many unnecessary attack surfaces; it tries to do far more than necessary and beyond what the initialization system should do.

Use musl as the default C library. Musl focuses on minimization, which leads to a small attack surface, while other C libraries (such as glibc) are too complex and vulnerable to vulnerabilities. For example, compared with a very small number of vulnerabilities in musl, more than a hundred vulnerabilities in glibc have been publicly disclosed. Although the disclosure of CVE itself is usually inaccurate statistics, sometimes this situation can be used to express excessive problems. Musl also has good vulnerability mitigation measures, especially its new enhanced memory allocator.

It is best to use a distribution of LibreSSL instead of OpenSSL by default. OpenSSL contains a large number of completely unnecessary attack surfaces and follows poor security practices. For example, it still maintains OS / 2 and VMS support for these decades-old operating systems. These obnoxious security practices lead to terrible Heartbleed vulnerabilities. LibreSSL, the OpenSSL branch of the OpenBSD team, adopts excellent programming practices and eliminates many attack surfaces. In its first year of existence, LibreSSL mitigated many vulnerabilities, including some of the most serious ones.

The best distribution to strengthen the foundation of the operating system is Gentoo Linux, because it allows you to configure the system precisely to achieve the desired results, which will be very useful, especially with reference to our use of more secure compilation flags in later chapters.

However, due to the huge usability shortcomings of Gentoo, it may not be easy for many people. In this case, Void Linux's Musl build is a good compromise.

Kernel

The kernel is the core of the operating system and is unfortunately vulnerable. As Brad Spengler once said, it can be thought of as the largest and most vulnerable setuid root binary on the system. Therefore, it is important to enhance the kernel as much as possible.

Stable vs LTS kernel

The Linux kernel is released in two main forms: stability and long-term support (LTS). The stable version is the newer version, while the LTS distribution is the older stable version that has been supported for a long time. Choosing any of these distributions has many consequences.

The Linux kernel does not use CVE to identify security vulnerabilities. This means that fixes for most security vulnerabilities cannot be migrated backwards to the LTS kernel. But the stable version contains all the security fixes made so far.

However, with these fixes, a stable kernel will contain more new features, thus greatly increasing the attack surface of the kernel and introducing a large number of new errors. In contrast, the attack surface of the LTS kernel is smaller because these features are not constantly added.

In addition, a stable kernel includes newer enhancements to mitigate some of the uses that the LTS kernel does not have. Some examples of such functionality are Lockdown LSM and STACKLEAK GCC plug-ins.

All in all, there is a trade-off when choosing a stable or LTS kernel. The LTS kernel has fewer enhancements, and not all common bug fixes at that time have been migrated backwards, but generally it has fewer attack surfaces and is less likely to introduce unknown errors. A stable kernel has more enhanced features and includes all known bug fixes, but it also has more attack surfaces and a better chance of introducing more unknown errors. Finally, it's best to use a newer LTS branch (such as the 4.19 kernel).

Sysctl

Sysctl is a tool that allows users to configure certain kernel settings and enable various security features or disable dangerous features to reduce the attack surface. To change the settings temporarily, you can execute:

Sysctl-w $tunable = $value

To permanently change the sysctls, you can add the changed sysctls to the appropriate file in / etc/sysctl.conf or / etc/sysctl.d, depending on your Linux distribution.

The following are the recommended sysctl settings you should change.

Kernel self-protection

Kernel.kptr_restrict=2

The kernel pointer points to a specific location in kernel memory. These can be useful in leveraging the kernel, but kernel pointers are not hidden by default, for example, they can be easily found by reading the contents of / proc/kallsyms. This setting is designed to reduce kernel pointer leaks. Alternatively, you can set kernel.kptr_restrict = 1 to hide kernel pointers only from processes that do not have CAP_SYSLOG functionality.

Kernel.dmesg_restrict=1

Dmesg is a kernel log that exposes a lot of useful kernel debugging information, but this usually leaks sensitive information, such as kernel pointers. Changing the above sysctl settings will limit kernel logging to the CAP_SYSLOG feature.

Kernel.printk=3 3 3 3

Despite the value of dmesg_restrict, the kernel log will still be displayed in the console during startup. Malware that can record the screen during boot may abuse this malware to gain higher privileges. This option prevents this information from leaking. It must be used in combination with some of the boot parameters described below to be fully effective.

Kernel.unprivileged_bpf_disabled=1 net.core.bpf_jit_harden=2

EBPF exposes a large attack surface, so it needs to be limited. These systems restrict eBPF to CAP_BPF functionality (CAP_SYS_ADMIN on kernel versions prior to 5.8) and enable JIT hardening techniques, such as constant binding.

Dev.tty.ldisc_autoload=0

This restricts the loading of TTY line rules to the CAP_SYS_MODULE function to prevent unprivileged attackers from using TIOCSETD ioctl to load vulnerable line rules, which has previously been abused in many exploits.

Vm.unprivileged_userfaultfd=0

Userfaultfd () system calls are often abused to take advantage of "use-after-free" defects. Therefore, the sysctl is used to restrict this syscall to the CAP_SYS_PTRACE function.

Kernel.kexec_load_disabled=1

Kexec is a system call used to boot another kernel at run time. This feature can be abused to load a malicious kernel and gain arbitrary code execution capabilities in kernel mode, so this sysctl setting will be disabled.

Kernel.sysrq=4

SysRq keys expose many potentially dangerous debugging features to unprivileged users. Contrary to common assumptions, SysRq is not only a physical attack problem, but can also be triggered remotely. The value of the sysctl enables users to use only the SAK key, which is essential for secure access to the root. Alternatively, you can simply set the value to 0 to disable SysRq completely.

Kernel.unprivileged_userns_clone=0

The user namespace is a feature in the kernel designed to improve the sandbox and make it easy for unprivileged users to access, but this feature exposes important kernel attack surfaces for privilege escalation, so the sysctl limits the use of user namespaces to the CAP_SYS_ADMIN feature. For unprivileged sandboxes, it is recommended to use setuid binaries with few attack surfaces to minimize the possibility of privilege escalation. This topic will be discussed further in the sandbox section.

Note that although this sysctl exists only in some Linux distributions, it requires kernel patches. If your kernel does not include this patch, you can completely disable user namespaces (including root users) by setting user.max_user_namespaces = 0.

Kernel.perf_event_paranoid=3

Performance events can add a large number of kernel attack surfaces and lead to a large number of vulnerabilities. This sysctl setting restricts all use of performance events to the CAP_PERFMON feature (the kernel version prior to 5.8is CAP_SYS_ADMIN).

Note that this sysctl setting requires relevant kernel patches in some distributions. Otherwise, this setting is equivalent to kernel.perf_event_paranoid = 2, which limits only a subset of this feature.

The network

Net.ipv4.tcp_syncookies=1

This helps prevent SYN flooding attacks, which are a form of denial of service attacks in which attackers send a large number of fake SYN requests in an attempt to consume enough resources to make the system unresponsive to legitimate traffic.

Net.ipv4.tcp_rfc1337=1

This prevents the time-wait state by dropping RST packets of sockets that are in the waiting state.

Net.ipv4.conf.all.rp_filter=1 net.ipv4.conf.default.rp_filter=1

These enable source authentication to verify packets received from all network interfaces of the computer.

Net.ipv4.conf.all.accept_redirects=0 net.ipv4.conf.default.accept_redirects=0 net.ipv4.conf.all.secure_redirects=0 net.ipv4.conf.default.secure_redirects=0 net.ipv6.conf.all.accept_redirects=0 net.ipv6.conf.default.accept_redirects=0 net.ipv4.conf.all.send_redirects=0 net.ipv4.conf.default.send_redirects=0

These settings disable ICMP redirection to prevent man-in-the-middle attacks and minimize information disclosure.

Net.ipv4.icmp_echo_ignore_all=1

This setting causes your system to ignore all ICMP requests to avoid Smurf attacks, make it more difficult for devices to enumerate on the network, and prevent clock fingerprints from being identified by ICMP timestamps.

Net.ipv4.conf.all.accept_source_route=0 net.ipv4.conf.default.accept_source_route=0 net.ipv6.conf.all.accept_source_route=0 net.ipv6.conf.default.accept_source_route=0

Source routing is a mechanism that allows users to redirect network traffic. Because this can be used to perform man-in-the-middle attacks, in which traffic is redirected for malicious purposes, the above setting disables this feature.

Net.ipv6.conf.all.accept_ra=0 net.ipv6.conf.default.accept_ra=0

Malicious IPv6 routing advertisements can lead to man-in-the-middle attacks and should be disabled.

Net.ipv4.tcp_sack=0 net.ipv4.tcp_dsack=0 net.ipv4.tcp_fack=0

Disable TCP SACK. ACK is usually utilized and is unnecessary in many cases, so if you don't need it, you should disable it.

User space

Kernel.yama.ptrace_scope=2

Ptrace is a system call that allows programs to debug, modify, and check another running process, allowing attackers to easily modify the memory of other running programs. The setting restricts the use of ptrace to processes that only have CAP_SYS_PTRACE capabilities. Alternatively, set sysctl to 3 to disable ptrace completely.

Vm.mmap_rnd_bits=32 vm.mmap_rnd_compat_bits=16

ASLR is a common vulnerability mitigation measure that randomizes the location of critical parts of a process in memory. This may make it more difficult to exploit a variety of vulnerabilities because they require information disclosure in the first place. The above setting increases the number of bits of entropy used for mmap ASLR, thereby improving its effectiveness.

The values of these sysctls must be set according to the CPU architecture. The above values are compatible with x86, but other architectures may be different.

Fs.protected_symlinks=1 fs.protected_hardlinks=1

Symbolic links are allowed to be followed only when the symbolic link matches the owner of the follower or the owner of the directory matches the owner of the symbolic link outside the globally writable sticky directory. This also prevents users who do not have read / write access to the source file from creating hard links. Both prevent many common TOCTOU vulnerabilities (time-of-check-to-time-of-use).

Fs.protected_fifos=2 fs.protected_regular=2

These prevent the creation of files in environments that may be controlled by an attacker (for example, a globally writable directory), making data spoofing attacks more difficult.

Boot parameter

Boot parameters use the boot loader (bootloader) to pass settings to the kernel at boot time. Similar to sysctl, you can use certain settings to improve security. Boot loaders usually differ in the way boot parameters are set. Some examples are listed below, but you should examine the necessary steps to modify parameters for a particular bootloader.

If you use GRUB as the bootstrap, edit / etc / default/grub and add parameters to GRUB_CMDLINE_LINUX_DEFAULT=line.

If you use Syslinux, edit / boot/syslinux/syslinux.cfg and add them to the APPEND line.

If you are using systemd-boot, edit your loader entry and append it to the end of the linux line.

The following settings are recommended to improve security.

Kernel self-protection

Slab_nomerge

This disables slab merging, which greatly increases the difficulty of heap utilization by preventing objects in the merged cache from being overwritten and making it more difficult to affect the layout of the slab cache.

Slub_debug=FZ

These enable sanity check (F) and rezoning (Z). Health checks add various checks to prevent corruption in some slab operations. Repartitioning adds additional areas around the slab to detect when the slab is overwritten beyond its actual size, which helps detect overflows.

Init_on_alloc=1 init_on_free=1

This clears memory to zero during allocation and idle time, which helps mitigate vulnerabilities used after use and clear sensitive information in memory. If your kernel version is less than 5.3, these options do not exist. Instead, append "P" to the above slub_debug option to get slub_debug=FZP and add page_poison=1. Because they are actually a debugging feature and happen to have some security, they provide a weak form of memory erasing when they are released.

Page_alloc.shuffle=1

This option randomizes the free list of page allocators, thereby improving security by reducing the predictability of page allocation, which also improves performance.

Pti=on

This enables kernel page table isolation, which mitigates crashes and prevents some KASLR bypass.

Vsyscall=none

This disables vsyscall because they are obsolete and have been replaced by vDSO. Vsyscall is also on a fixed address in memory, making it a potential target for ROP attacks.

Debugfs=off

This disables debugfs, which exposes a lot of sensitive information about the kernel.

Oops=panic

Sometimes certain kernel exploits can lead to so-called "oops". This parameter will cause the kernel to panic such events, thereby preventing these attacks. However, sometimes the wrong driver can lead to harmless operation, which can cause the system to crash, which means that this boot parameter can only be used on some hardware.

Module.sig_enforce=1

This allows only kernel modules that have been signed with valid keys to be loaded, making it more difficult to load malicious kernel modules.

This prevents all out-of-tree kernel modules (including DKMS modules) from being loaded unless you have signed them, which means that modules such as VirtualBox or Nvidia drivers may not be available, but may not be important depending on your settings.

Lockdown=confidentiality

Kernel locking LSM eliminates many methods of user-space code abuse to escalate to kernel privileges and extract sensitive information. This LSM is necessary to achieve a clear security boundary between user space and the kernel. The above option enables this feature in confidentiality mode (the strictest option). This means that module.sig_enforce=1.

Mce=0

This will cause the kernel to panic errors that cannot be utilized in ECC memory, and these errors may be exploited. This is not necessary for systems that have no ECC memory.

Quiet loglevel=0

These parameters prevent information leakage during boot and must be used in conjunction with the kernel.printk sysctl above.

CPU remission

It is a good idea to enable all CPU mitigation measures that apply to your CPU to ensure that you are not affected by known vulnerabilities. This is a list of all built-in mitigation measures enabled:

Spectre_v2=on spec_store_bypass_disable=on tsx=off tsx_async_abort=full,nosmt mds=full,nosmt l1tfect fullforce nosmt=force kvm.nx_huge_pages=force

You must study the CPU vulnerabilities that affect your system and choose the above mitigation measures accordingly. Keep in mind that you will need to install microcode updates to completely protect yourself from these vulnerabilities. But all of these operations can lead to significant performance degradation.

Result

If all of the above recommendations are followed (excluding specific CPU mitigation measures), you will have:

Slab_nomerge slub_debug=FZ 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

If you use GRUB as the boot loader, you may need to regenerate the GRUB configuration files to apply them.

Hidepid

/ proc is a pseudo file system that contains information about all processes currently running on the system. By default, all users can access this program, which may allow attackers to snoop on other processes. To allow users to see only their own processes and not other users' processes, / proc must be mounted using the hidepid=2,gid=proc mount option. Gid=proc excludes proc groups from this feature, so you can whitelist specific users or processes. One way to add these options is to edit / etc/fstab and add:

Proc / proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0

Systemd-logind still needs to see the progress of other users, so for user sessions to work properly on systemd systems, you must create / etc/systemd/system/systemd-logind.service.d/hidepid.conf and add:

[Service] SupplementaryGroups=proc

Reduce kernel attack surface

It is best to disable any features that are not absolutely necessary to minimize potential kernel attack surfaces. These features don't have to be dangerous, they can just be removed to reduce the attack surface of the benign code. Do not disable random things that you do not know. Here are some examples that may be useful, depending on your settings.

Boot parameter

Boot parameters can usually be used to reduce the attack surface, and one such example is:

Ipv6.disable=1

This disables the entire IPv6 stack, which you may not need if you have not already migrated to it. If you are using an IPv6, do not use this boot parameter.

Blacklist kernel modules

The kernel allows unprivileged users to cause certain modules to be loaded indirectly by automatically loading modules. This allows attackers to automatically load vulnerable modules and then exploit them. One such example is CVE-2017-6074, where an attacker can trigger the loading of a DCCP kernel module by initiating a DCCP connection, and then exploit a vulnerability in that kernel module.

Specific kernel modules can be blacklisted by inserting files into / etc/modprobe.d and blacklisting specified kernel modules.

The Install parameter tells modprobe to run specific commands instead of loading the module as usual. / bin/false is a command that returns only 1, which actually does nothing. Both tell the kernel to run / bin/false instead of loading the module, which will prevent attackers from taking advantage of the module. Here are the kernel modules that are most likely not needed:

Install dccp / bin/false install sctp / bin/false install rds / bin/false install tipc / bin/false install n-hdlc / bin/false install ax25 / bin/false install netrom / bin/false install x25 / bin/false install rose / bin/false install decnet / bin/false install econet / bin/false install af_802154 / bin/false install ipx / bin/false install appletalk / bin/false install psnap / bin/false install p8023 / bin/false install p8022 / bin/ False install can / bin/false install atm / bin/false

In particular, vague network protocols will increase a large number of long-range attack surfaces. This blacklist:

DCCP-Datagram Congestion Control Protocol

SCTP-Stream Control Transmission Protocol

RDS-Reliable Datagram Sockets

TIPC-Transparent Inter-process Communication

HDLC-High-Level Data Link Control

AX25-Amateur X.25

NetRom

X25

ROSE

DECnet

Econet

Af_802154-IEEE 802.15.4

IPX-Internetwork Packet Exchange

AppleTalk

PSNAP-Subnetwork Access Protocol

P8023-Novell raw IEEE 802.3

P8022-IEEE 802.2

CAN-Controller Area Network

ATM

Install cramfs / bin/false install freevxfs / bin/false install jffs2 / bin/false install hfs / bin/false install hfsplus / bin/false install squashfs / bin/false install udf / bin/false

Blacklist a variety of rare file systems.

Install cifs / bin/true install nfs / bin/true install nfsv3 / bin/true install nfsv4 / bin/true install gfs2 / bin/true

If you do not use a network file system, you can also blacklist it.

Install vivid / bin/false

The vivid driver driver is for testing purposes only and is the cause of the privilege escalation vulnerability, so it should be disabled.

Install bluetooth / bin/false install btusb / bin/false

Disable Bluetooth with a history of security issues.

Install uvcvideo / bin/false

This disables the webcam to prevent it from being used to monitor you.

You can also blacklist microphone modules, but this may vary from system to system. To find the name of the module, find it in / proc/asound/modules and blacklist it. For example, one such module is snd_hda_intel.

Note that although sometimes the microphone kernel module is the same as the speaker module. This means that disabling the microphone like this may inadvertently disable any speaker, although the speaker may also become a microphone, so this is not necessarily a negative result.

It is best to physically remove these devices, or at least disable them in BIOS/UEFI. Disabling kernel modules is not always that effective.

Rfkill

Wireless devices can be blacklisted through rfkill to further reduce the long-range attack surface. To blacklist all wireless devices, perform:

Rfkill block all

WiFi can be unlocked in the following ways:

Rfkill unblock wifi

On systems that use systemd, rfkill remains the same in all sessions, but on systems that use other init systems, you may have to create an init script to execute these commands at boot time.

Other kernel pointer leaks

The previous section has prevented some kernel pointer leaks, but there are more leaks.

On the file system, there are kernel images and System.map files in / boot. There is other sensitive kernel information in the / usr/src and / {, usr/} lib/modules directories. You should restrict the file permissions of these directories so that they can only be read by root users. You should also delete System.map files because they are not required except for advanced debugging.

In addition, some logging daemons, such as systemd's journalctl, include kernel logs that can be used to bypass the above dmesg_restrict protection. Removing a user from the adm group is usually sufficient to revoke access to the following logs:

Gpasswd-d $user adm

Restrict access to sysfs

Sysfs is a pseudo file system that provides a great deal of kernel and hardware information. It is usually installed on / sys. Sysfs causes a lot of information leaks, especially kernel pointer leaks. Whonix's security-misc package includes hide-hardware-info scripts that restrict access to this directory and some scripts in / proc in an attempt to hide potential hardware identifiers and prevent kernel pointer leaks. The script is configurable and allows specific applications to be whitelisted based on groups. It is recommended that you apply this method and have it executed using init scripts at startup. Or make a systemd service like this [1].

In order for basic functions to run on systems that use systemd, some system services must be whitelisted. This can be done by creating / etc/systemd/system/user@.service.d/sysfs.conf and adding the following:

[Service] SupplementaryGroups=sysfs}

However, this does not solve all the problems. Many applications may still break, and you need to whitelist them correctly.

Linux strengthening

Some distributions, such as Arch Linux, include enhanced kernel packages. It contains many enhanced patches and more security-focused kernel configurations. If possible, it is recommended to install it.

Grsecurity

Grsecurity is a set of kernel patches that can greatly improve kernel security. These patches used to be available for free, but now they need to be purchased. If available, it is strongly recommended that you get it. Grsecurity provides the latest kernel and user space protection.

Kernel runtime protection

Linux Kernel Runtime Guard (LKRG) is a kernel module that ensures the integrity of the runtime kernel and detects vulnerabilities. It can kill an entire category of kernel vulnerabilities. But this is not a perfect mitigation, because LKRG can be bypassed by design. It only applies to off-the-shelf malware. However, although unlikely, LKRG itself may expose new vulnerabilities like any other kernel module.

Self-compiled kernel

It is recommended that you compile your own kernel while enabling as few kernel modules and as many security features as possible to keep the attack surface of the kernel to an absolute minimum.

In addition, apply kernel hardening patches, such as linux-hardened or grsecurity as described above.

The kernel compiled by the distribution also has a common kernel pointer / symbol, which is very useful for vulnerability exploitation. Compiling your own kernel will provide you with unique kernel symbols, and along with kptr_restrict,dmesg_restrict and other enhancements to kernel pointer leaks, will make it more difficult for attackers to create exploits that rely on kernel pointer knowledge.

You can take inspiration from Whonix's enhanced kernel or use it.

Mandatory access measures

The mandatory access control (MAC) system provides fine-grained control over what the program can access. This means that your browser will not have access to your entire home directory or similar directory.

The most commonly used MAC measures are SELinux and AppArmor. SELinux is more secure than AppArmor because of its finer granularity. For example, it is inode-based rather than path-based, allowing significantly stricter restrictions to be enforced, filtering kernel ioctl, and so on. Unfortunately, this comes at the expense of being difficult to use and difficult to learn, so some people may prefer AppArmor.

To enable AppArmor in the kernel, the following boot parameters must be set:

Apparmor=1 security=apparmor

To enable SELinux, set the following parameters:

Selinux=1 security=selinux

Keep in mind that enabling MAC measures alone does not magically improve security. You must have a strict policy to make full use of it. For example, to create an AppArmor configuration file, execute:

Aa-genprof $path_to_program

Open the program and start using it as usual. AppArmor will detect which files need to be accessed and add them to the configuration file, if you choose. However, this alone is not enough to provide a high-quality configuration file. Please refer to the AppArmor document [2] for more details.

If you want to go further, you can set a complete system MAC policy by implementing the initramfs hook, which restricts each individual user space process, and the hook enforces the MAC policy on the init system. This is how Android uses SELinux and how Whonix will use AppArmor in the future. It is necessary to strengthen a strong security model that implements the principle of least privilege.

Sand box

Apply sandbox

The sandbox allows you to run programs in an isolated environment that has limited or no access to the rest of the system. You can use them to secure your application or to run untrusted programs.

It is recommended that you use the Bubblewrap-to-sandbox program in a separate user account with AppArmor or SELinux. You can also consider using gVisor instead, which has the advantage of providing each guest with its own kernel.

Any of these methods can be used to create a powerful sandbox with minimal attack surface exposure. If you don't want to create your own sandbox, consider using Whonix's sandbox-app-launcher when you're done. You should not use Firejail.

Container solutions such as Docker and LXC are often misled as sandboxie. They are too loose to support a wide variety of applications, so they cannot be considered a powerful application sandbox.

Common sandbox escape

PulseAudio

PulseAudio is a common sound server, but the problem of isolation or sandboxie is not considered when writing it, which makes it a recurrent sandboxie escape vulnerability. To prevent this, it is recommended that you block access to PulseAudio from the sandbox or uninstall it completely from the system.

D-Bus

D-Bus is the most popular form of interprocess communication on desktop Linux, but it is also another common way to sandbox escape because it allows free interaction with services. An example of these vulnerabilities is Firejail. You should block access to D-Bus from the sandbox or mediate with fine-grained rules through MAC.

GUI isolation

Any Xorg window can access another window. This allows trivial keyloggers or screenshots, or even things like root passwords. You can use nested X11 servers, such as Xpra or Xephyr and bubblewrap, to sandbox Xorg windows. By default, Wayland isolates windows from each other, which would be a better choice than Xorg, although Wayland may not be as widely available as Xorg because it is earlier in development.

Ptrace

As mentioned earlier, ptrace is a system call that can be abused to destroy processes running outside the sandbox. To avoid this, you can enable kernel YAMA ptrace restrictions through sysctl, or you can blacklist ptrace syscall in the seccomp filter.

TIOCSTI

TIOCSTI is an ioctl that allows terminal commands to be injected and provides a simple mechanism for attackers to move horizontally between other processes within the same user session. This attack can be mitigated by blacklisting ioctl in the seccomp filter or by using the-new-session parameter of bubblewrap

Systemd sandbox

Although systemd is not recommended, some systems may not be able to switch. These people can at least use sandboxie's service, so they can only access the content they need. This is an example of a sandboxed systemd service:

[Service] CapabilityBoundingSet=CAP_NET_BIND_SERVICE ProtectSystem=strict ProtectHome=true ProtectKernelTunables=true ProtectKernelModules=true ProtectControlGroups=true ProtectKernelLogs=true ProtectHostname=true ProtectClock=true ProtectProc=invisible ProcSubset=pid PrivateTmp=true PrivateUsers=yes PrivateDevices=true MemoryDenyWriteExecute=true NoNewPrivileges=true LockPersonality=true RestrictRealtime=true RestrictSUIDSGID=true RestrictAddressFamilies=AF_INET RestrictNamespaces=yes SystemCallFilter=write read openat close brk fstat lseek mmap mprotect munmap rt_sigaction rt_sigprocmask ioctl nanosleep select access execve getuid arch_prctl set_tid_address set_robust_list prlimit64 pread64 getrandom SystemCallArchitectures=native UMask=0077 IPAddressDeny=any AppArmorProfile=/etc/apparmor.d/usr.bin.example

Description of all options:

CapabilityBoundingSet=- Specifies the capabilities the process is given.

ProtectHome=true- Makes all home directories inaccessible.

ProtectKernelTunables=true- Mounts kernel tunables such as those modified throughsysctlas read-only.

ProtectKernelModules=true- Denies module loading and unloading.

ProtectControlGroups=true- Mounts all control group hierarchies as read-only.

ProtectKernelLogs=true- Prevents accessing the kernel logs.

ProtectHostname=true- Prevents changes to the system hostname.

ProtectClock- Prevents changes to the system clock.

ProtectProc=invisible- Hides all outside processes.

ProcSubset=pid- Permits access to only the pid subset of/proc.

PrivateTmp=true- Mounts an empty tmpfs over/tmpand/var/tmp, therefore hiding their previous contents.

PrivateUsers=true- Sets up an empty user namespace to hide other user accounts on the system.

PrivateDevices=true- Creates a new/devmount with minimal devices present.

MemoryDenyWriteExecute=true- Enforces a memory W ^ X policy.

NoNewPrivileges=true- Prevents escalating privileges.

LockPersonality=true- Locks down thepersonality () syscall to prevent switching execution domains.

RestrictRealtime=true- Prevents attempts to enable realtime scheduling.

RestrictSUIDSGID=true- Prevents executing setuid or setgid binaries.

RestrictAddressFamilies=AF_INET- Restricts the usable socket address families to IPv4 only (AF_INET).

RestrictNamespaces=true- Prevents creating any new namespaces.

SystemCallFilter=...- Restricts the allowed syscalls to the absolute minimum. If you aren't willing to maintain your own custom seccomp filter, then systemd provides many predefined system call sets that you can use.@system-servicewill be suitable for many use cases.

SystemCallArchitectures=native- Prevents executing syscalls from other CPU architectures.

UMask=0077- Sets the umask to a more restrictive value.

IPAddressDeny=any- Blocks all incoming and outgoing traffic to/from any IP address. SetIPAddressAllow=to configure a whitelist. Alternatively, setup a network namespace withPrivateNetwork=true.

AppArmorProfile=...- Runs the process under the specified AppArmor profile.

You cannot just copy this sample configuration to your configuration, the requirements for each service are different, and you must fine-tune the sandbox for each service. For more information about all the options you can set, read the systemd.exec man page [3].

If you are using a system other than systemd but init, you can easily copy all of these options using bubblewrap.

GVisor

The normal sandbox inherently shares the same kernel with the host. You trust that we have assessed as insecure kernels and can correctly restrict these programs. Because the entire attack surface of the host kernel has been fully exposed, the kernel exploiter in sandboxie can bypass any restrictions. Some efforts have been made to limit the attack surface on which seccomp is used, but not enough to completely solve this problem.

GVisor is the solution to this problem. It provides each application with its own kernel, which reimplements most of the system calls in the Linux kernel in a memory-safe language, providing significantly greater isolation.

Virtual machine

Although not the traditional "sandboxie", virtual machines separate processes by virtualizing entirely new systems, thus providing very strong isolation. KVM is a kernel module that allows the kernel to act as a hypervisor, while QEMU is an emulator that leverages KVM. Virt-manager and GNOME Boxs are both good and easy-to-use GUI for managing KVM / QEMU virtual machines. There are many reasons why Virtualbox is not recommended.

Enhanced memory allocator

Hardened_malloc is a hardened memory allocator that provides substantial protection against heap memory corruption vulnerabilities. It is largely based on OpenBSD's malloc design, but has many improvements.

You can use hardened_malloc for each application through the LD_PRELOAD environment variable. For example, assuming that the library you compiled is located in / usr/lib/libhardened_malloc.so, you can execute:

LD_PRELOAD= "/ usr/lib/libhardened_malloc.so" $program

By preloading the library globally, it can also be used system-wide, which is the recommended way to use it. To do this, edit / etc/ld.so.preload and insert:

/ usr/lib/libhardened_malloc.so

Although most applications work properly, hardened_malloc can break some applications. It is recommended that you compile hardened_malloc with the following options to minimize corruption:

CONFIG_SLAB_QUARANTINE_RANDOM_LENGTH=0 CONFIG_SLAB_QUARANTINE_QUEUE_LENGTH=0 CONFIG_GUARD_SLABS_INTERVAL=8

You should also use sysctl to set the following to accommodate the large number of protection pages created by hardened_malloc:

Vm.max_map_count=524240

The Whonix project provides hardened_malloc packages for Debian-based distributions.

Enhanced compilation flag

Compiling your own program can bring many benefits because it enables you to optimize the security of your program. However, it's easy to do the exact opposite and reduce security, and if you're not sure what you're doing, skip this section. This will be the easiest on source-based distributions, such as Gentoo, but it can be done on other distributions as well.

Some compilation options can be used to add additional vulnerability mitigation measures to eliminate common vulnerabilities throughout the category. You may have heard of general protections, such as location-independent executables, stack shredder protectors, immediate binding, read-only relocation, and FORTIFY_SOURCE, but they are not covered in this section because they are widely used. Instead, it will discuss modern vulnerability mitigation measures such as control flow integrity and shadow stacks.

This section deals with native programs written mainly in C or C +. You must use the Clang compiler because these features are not available on GCC. Keep in mind that because these mitigation measures are not widely adopted, some applications may not be able to run after they are enabled.

Control flow Integrity (CFI) is a way to mitigate vulnerabilities designed to prevent code reuse attacks such as ROP or JOP. Because more widely adopted mitigation measures, such as NX, make outdated utilization technologies obsolete, the use of these technologies exploits a large number of vulnerabilities. Clang supports fine-grained frontier CFI, which means it can effectively mitigate JOP attacks. Clang's CFI alone does not ease ROP;. You must also use the separate mechanisms documented below. To enable this feature, the following compilation flags must be applied:

-flto-fvisibility=hidden-fsanitize=cfi

The shadow stack protects the return address of the program by copying the program to another hidden stack. Then compare the return addresses in the main stack and the shadow stack to see if they are different. If so, it indicates that there is an attack and the program will be aborted, thus mitigating the ROP attack. Clang has a feature called ShadowCallStack, which can do this, but is only available on ARM64. To enable this feature, the following compilation flags must be applied:

-fsanitize=shadow-call-stack

If the above ShadowCallStack is not an option, you can choose to use a SafeStack with similar goals. Unfortunately, however, there are many loopholes in this feature, so the effect is not ideal. If you still want to enable this feature, you must apply the following compilation flag:

-fsanitize=safe-stack

One of the most common memory corruption vulnerabilities is uninitialized memory. Clang has an option to automatically initialize variables using zero or a specific mode. It is recommended that you initialize the variable to zero because it is better to find errors by using other modes than by exploiting vulnerability mitigation. To enable this feature, the following compilation flags must be applied:

-ftrivial-auto-var-init=zero-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang

However, the existence of this option is currently under debate [4].

Memory security language

Programs written in memory security languages are automatically protected from a variety of security vulnerabilities, including buffer overflows, uninitialized variables, after-sales use, and so on. Research conducted by security researchers at Microsoft and Google has proved that most of the vulnerabilities that have been discovered are memory security issues. Examples of such memory-safe languages include Rust,Swift and Java, while examples of memory-insecure languages include C and C + +. If possible, replace as many programs as possible with memory-safe alternatives.

Root account

Root can do anything and can access your entire system. Therefore, it should be locked as much as possible so that attackers cannot easily gain access to root users.

/ etc/securetty

The / etc/securetty file specifies the location that allows you to log in as root. The file should be left blank so that no one can do this from the terminal.

Restrict su

Su allows you to switch users from the terminal. By default, it attempts to log in as root. To restrict the use of su to the wheel group, edit / etc/pam.d/su and / etc/pam.d/su-l and add:

Auth required pam_wheel.so use_uid

You should have as few users as possible in the wheel group.

Lock your root account

To lock out the root account to prevent anyone from logging in as root, execute:

Passwd-l root

Before you do this, make sure that you have an alternative way to get the root (for example, boot from the active USB and change to the chroot of the file system) so that you don't inadvertently lock yourself out of the system.

Refuse to log in through SSH's remote root

To prevent someone from logging in as root through SSH, edit / etc/ssh/sshd_config and add:

PermitRootLogin no

Increase the number of hash rounds

You can increase the number of hash rounds used by shadow to crack your password by forcing the attacker to calculate more hash values, thereby improving the security of the hash password. By default, shadow uses 5000 rounds, but you can increase it to any number. Although the more rounds you configure, the slower the login. Edit / etc/pam.d/passwd and add round options.

Password required pam_unix.so sha512 shadow nullok rounds=65536

This causes shadow to perform 65536 hash rounds.

After applying this setting, the password is not automatically re-encrypted, so you need to reset the password using the following methods:

Passwd $username

Restrict Xorg root access

By default, some distributions run Xorg as root, which is a problem because Xorg contains a lot of old and complex code, which adds a huge attack surface and makes it more likely to have a vulnerability exploiter that can gain root privileges. To prevent it from executing as a root user, edit / etc/X11/Xwrapper.config and add:

Needs_root_rights = no

Secure access to root

Malware can use a number of ways to sniff the password of an root account. Therefore, the traditional way of accessing the root account is not secure, and it is best not to access the root at all, but this is actually not feasible. This section details the most secure way to access the root account. These instructions should be applied immediately after installing the operating system to ensure that the software is free of malware.

You should never use a normal user account to access root, as root may have been stolen. You cannot log in directly to the root account either. Create a separate Administrator user account that is used only to access root users and not to other users by doing the following:

Useradd admin

Execute and set a very strong password:

Passwd admin

Only allow this account to use your preferred privilege escalation mechanism. For example, if you use sudo, add a sudoers exception by executing the following command:

Visudo-f / etc/sudoers.d/admin-account

Then enter:

Admin ALL= (ALL) ALL

Make sure that no other account can access sudo (or your preferred mechanism).

Now, to actually log in to the account, restart-for example, to prevent a compromised window manager from performing login spoofing. When you provide a login prompt, activate the security key by pressing the following key combinations on the keyboard:

Alt + SysRq + k

This will kill all applications on the current virtual console, thereby overcoming login spoofing attacks. You can now safely log in to your administrator account and use the root user to perform tasks. When you are finished, log out of the administrator account and log back in to the unprivileged user account.

Firewalls

Firewalls can control incoming and outgoing network traffic and can be used to block or allow certain types of traffic. All incoming traffic should always be blocked unless there is a special reason. It is recommended to set up a strict iptables or nftables firewall. The Firewall must be fine-tuned for your system, and there is not a rule set for all firewalls. It is recommended that you are familiar with creating firewall rules. Arch Wiki and manual page [5] are good resources.

This is an example of a basic iptables configuration that forbids all incoming network traffic:

* filter: INPUT DROP [0:0]: FORWARD DROP [0:0]: OUTPUT ACCEPT [0:0]: TCP-[0:0]: UDP-[0:0]-An INPUT-m conntrack-- ctstate RELATED,ESTABLISHED-j ACCEPT-An INPUT-I lo-j ACCEPT-An INPUT-m conntrack-ctstate INVALID-j DROP-An INPUT-p udp-m conntrack-ctstate NEW-j UDP-An INPUT-p tcp--tcp-flags FIN,SYN RST,ACK SYN-m conntrack-- ctstate NEW-j TCP-An INPUT-p udp-j REJECT-- reject-with icmp-port-unreachable-An INPUT-p tcp- j REJECT-- reject-with tcp-reset-An INPUT-j REJECT-- reject-with icmp-proto-unreachable COMMIT

However, you should not try to use this example on a real system. It applies only to some desktop systems.

Identity identification

To protect privacy, it's best to minimize the amount of information that can be traced back to you.

Hostname and user name

Do not add uniquely identified content to the hostname or user name. Leave them as common names, such as "host" and "user", so that they do not recognize you.

Timezones / Locales / Keymaps

If possible, set your time zone to "UTC" and your locale and keyboard mapping to "US".

Machine ID

A unique machine ID is stored in / var/lib/dbus/machine-id (the systemd system is stored in / etc/machine-id), which should be edited to a common name, such as Whonix ID:

B08dfa6083e7567a1921a715000001fb

MAC address spoofing

The MAC address is a unique identifier assigned to the network interface controller (NIC). Every time you connect to the network (WIFI or Ethernet), your MAC address is exposed. This allows people to use it to track you and uniquely identify you on the local network.

However, you should not completely randomize MAC addresses. Having a completely random MAC address is obvious and can adversely affect your behavior that stands out.

The OUI (Organization unique Identifier) portion of the MAC address identifies the manufacturer of the chipset. Randomizing this part of the MAC address may provide you with an OUI that has never been used before, an OUI that has not been used in decades, or an OUI that is extremely rare in your area, thus making you stand out and clearly indicating that you are spoofing the MAC address.

The end of the MAC address identifies your specific device and can be used to track your device. Randomizing only this part of the MAC address prevents you from being tracked, while still making the MAC address look trusted.

To spoof these addresses, first execute the following command to find out your network interface name:

Ip a

Next, install macchanger and execute:

Macchanger-e $network_interface

To randomly assign MAC addresses at each boot, you should create an initialization script for your specific initialization system. This is an example of systemd:

[Unit] Description=macchanger on eth0 Wants=network-pre.target Before=network-pre.target BindsTo=sys-subsystem-net-devices-eth0.device After=sys-subsystem-net-devices-eth0.device [Service] ExecStart=/usr/bin/macchanger-e eth0 Type=oneshot [Install] WantedBy=multi-user.target

The above example spoofed the MAC address of the eth0 interface at startup. Replace eth0 with your network interface.

Time attack

Almost every system has a different time. This can be used for clock skew fingerprint attacks, and the difference of a few milliseconds is enough to expose the user to identification.

CMP timestamp

The ICMP timestamp leaks the system time in the query reply. The easiest way to stop these attacks is to use a firewall to block incoming connections, or to make the kernel ignore ICMP requests.

TCP timestamp

The TCP timestamp also leaks system time. The kernel tries to solve this problem by using random offsets for each connection, but this is not enough to solve the problem. Therefore, TCP timestamps should be disabled, which can be done by setting the following using sysctl:

Net.ipv4.tcp_timestamps=0

TCP initialization serial number

The TCP initial sequence number (ISN) is another way to disclose system time. To mitigate this, you must install the tirdad kernel module, which generates random ISN for connections.

Time synchronization

Time synchronization is essential for anonymity and security. The wrong system clock may expose you to clock skew fingerprinting attacks, or it can be used to provide you with an outdated HTTPS certificate to bypass certificate expiration or revocation.

The most popular time synchronization method, NTP, is insecure because it is unencrypted and unauthenticated, so attackers can easily intercept and modify requests. NTP also leaks local system time in NTP timestamp format, which can be used for clock skew fingerprint identification, as mentioned earlier.

Therefore, you should uninstall all NTP clients and disable systemd-timesyncd if you are using it. You can connect to a trusted Web site through a secure connection (HTTPS or preferably a Torion service) instead of NTP, and extract the current time from the HTTP header. The tool to do this is sdwdate or my own secure time synchronization tool.

Key fingerprint

People can be identified by entering keys on the keyboard. You can uniquely identify fingerprints by typing speed, pausing between two keystrokes, and the exact time each keystroke is pressed and released. You can use KeyTrac to test online.

Kloak is a tool designed to overcome this tracking method by confusing the time interval between keystrokes and releasing events. When the key is pressed, it introduces a random delay, which is then selected by the application.

File permissions

By default, the permissions of the file are very loose. You should search the entire system for files and directories with inappropriate permissions and restrict them. For example, in some distributions such as Debian, the user's Home directory is globally readable.

This can be limited by doing the following:

Chmod 700 / home/$user

Other examples are / boot,/usr / src and / {, usr /} lib/modules, which contain kernel images, System.map, and various other files, all of which can reveal sensitive information about the kernel.

Chmod 700 / boot / usr/src / lib/modules / usr/lib/modules

In Debian-based distributions, you must use dpkg-statoverride to retain file permissions. Otherwise, they will be overwritten during the update.

The SUID Disabler and Permission Hardener of Whonix automatically apply the steps detailed in this section.

Setuid / setgid

Setuid / SUID allows the user to execute binaries with the privileges of the owner of the binaries. This is typically used to allow unprivileged users to use certain features that are usually reserved only for root users. As a result, many SUID binaries have a history of privileged escalation vulnerabilities. Setgid / SGID is similar, but applies to groups rather than users. To find all binaries on the system using the setuid or setgid bit, execute:

Find /-type f\ (- perm-4000-o-perm-2000\)

You should then remove all unnecessary setuid / setgid bits from programs that are not in use or replace them with features. To delete the setuid bit, execute:

Chmod Umurs $path_to_program

To delete the setgid bit, execute:

Chmod Gmurs $path_to_program

To add functionality to a file, execute:

Setcap $capability+ep $path_to_program

Or, to remove unnecessary features, execute:

Setcap-r $path_to_program

Umask

Umask sets the default file permissions for newly created files. The default umask is 0022, which is not very secure because it provides read access to newly created files for every user on the system. To make the new file unreadable to anyone other than the owner, edit / etc/profile and add:

Umask 0077 core dump

The core dump contains the recorded memory of the program at a specific time (usually when the program crashes). They may contain sensitive information, such as passwords and encryption keys, so they must be disabled.

There are three main ways to disable them: sysctl,systemd and ulimit.

Sysctl

Set the following settings through sysctl:

Kernel.core_pattern= | / bin/false

Systemd

Create / etc/systemd/coredump.conf.d/disable.conf and add the following:

[Coredump] Storage=none

Ulimit

Edit / etc/security/limits.conf and add the following:

* hard core 0

Setuid process

Even after these settings are made, processes running with elevated privileges may still dump their memory.

To prevent them from doing this, set the following through sysctl:

Fs.suid_dumpable=0Swap

Similar to core dumps, swapping or paging copies some memory to disk, which may contain sensitive information. The kernel should be configured to swap sysctl settings only when absolutely necessary:

Vm.swappiness=1PAM

PAM is a framework for user authentication. This is the mechanism you use when you log in. You can make it more secure by requiring a strong password or by forcing delayed authentication after a failed login attempt.

To enforce strong passwords, you can use pam_pwquality. It enforces the configurable policy of the password. For example, if you want your password to contain at least 16 characters (minimum), at least 6 different characters from the old password (difok), at least 3 numbers (dcredit), at least 2 uppercase letters (ucredit), at least 2 characters of lowercase letters (lcredit), and at least 3 other characters (ocredit), then edit / etc/pam.d/passwd and add:

Password required pam_pwquality.so retry=2 minlen=16 difok=6 dcredit=-3 ucredit=-2 lcredit=-2 ocredit=-3 enforce_for_root password required pam_unix.so use_authtok sha512 shadow

To enforce deferred validation, you can use pam_faildelay. To add a delay of at least 4 seconds between two failed login attempts to prevent brute force cracking attempts, edit / etc/pam.d/system-login and add:

Auth optional pam_faildelay.so delay=4000000

4000000 is 4 seconds (in microseconds).

Microcode update

Microcode updates are critical to fixing key CPU vulnerabilities such as Meltdown and Spectre. Most distributions include these distributions in their repositories, such as Arch Linux and Debian.

IPv6 Privacy extension

The IPv6 address is generated from the computer's MAC address, so that your IPv6 address is unique and bound directly to the computer. The privacy extension generates a random IPv6 address to ease this form of tracking. Note that if you turn on MAC address spoofing or disable IPv6, you do not need to perform these steps.

To enable these features, set the following settings through sysctl:

Net.ipv6.conf.all.use_tempaddr=2 net.ipv6.conf.default.use_tempaddr=2

NetworkManager

To enable the privacy extension for NetworkManager, edit / etc/NetworkManager/NetworkManager.conf and add:

[connection] ipv6.ip6-privacy=2

Systemd-networkd

To enable the privacy extension for systemd-networkd, create / etc/systemd/network/ipv6-privacy.conf and add:

[Network] IPv6PrivacyExtensions=kernel

Partition and mount option

The file system should be divided into multiple partitions for fine-grained control of its permissions. You can add different installation options to limit what you can do:

Nodev-prohibit the use of Devic

Nosuid-disable setuid or setgid bits

Noexec-disables the execution of any binaries

These installation options should be set in / etc/fstab whenever possible. If you cannot use a separate partition, create a bind mount. A more secure example of / etc/fstab:

/ / ext4 defaults 1 1 / home / home ext4 defaults,nosuid,noexec,nodev 1 2 / tmp / tmp ext4 defaults,bind,nosuid,noexec,nodev 1 2 / var / var ext4 defaults,bind,nosuid 1 2 / boot / boot ext4 defaults,nosuid,noexec Nodev 1 2

Note that noexec can be bypassed through shell scripts.

Entropy.

Entropy basically reflects the random degree of information collected by the operating system and is essential for things such as encryption. Therefore, it is best to collect as much entropy as possible from various sources by installing other random number generators such as haveged and jitterentropy.

In order for jitterentropy to run correctly, you must load the kernel module as early as possible by creating / usr/lib/modules-load.d/jitterentropy.conf and adding the following:

Jitterentropy_rng

RDRAND

RDRAN is a CPU instruction that provides random numbers. If available, the kernel automatically uses it as an entropy source. However, because it is proprietary and part of CPU itself, its security cannot be audited and verified. You can't even reverse engineer the code. The RNG has been subjected to vulnerabilities before, some of which may be backdoor attacks. You can distrust this feature by setting the following boot parameters:

Random.trust_cpu=off edits files as root

It is recommended that you do not run a normal text editor as root. Most text editors can do more than simply edit text files, but can also be used. For example, open vi as root and enter: sh. Now that you have a root shell that can access the entire system, an attacker can easily take advantage of that shell.

The solution is to use sudoedit. This copies the file to a temporary location, opens a text editor as a normal user, edits the temporary file, and overwrites the original file as root. In this way, the actual editor will not run as root. To use sudoedit, execute:

Sudoedit $path_to_file

By default, it uses vi, but you can switch the default editor through the EDITOR or SUDO_EDITOR environment variables. For example, to use nano, execute:

EDITOR=nano sudoedit $path_to_file

You can set this environment variable globally in / etc/environment.

Security enhancements for specific distributions

HTTP package Manager Image

By default, Linux distributions typically use HTTP or a mix of HTTP and HTTPS images to download packages from their software repositories. This is considered good because the package manager verifies the signature of the package before installation. However, historically, there have been many places to bypass this approach. You should configure the package manager to download specifically from the HTTPS image for defense in depth.

APT seccomp-bpf

Since the package manager Debian Buster, APT has supported optional seccomp-bpf filtering. This limits the system calls that allow APT to be executed, which can severely limit the ability of an attacker to compromise the system when trying to exploit a vulnerability in APT. To enable this feature, create / etc/apt/apt.conf.d/40sandbox and add:

APT::Sandbox::Seccomp "true"; physical security

Full encryption ensures that all data on the drive is encrypted and will not be read by physical attackers. Most distributions support enabling encryption during installation, so make sure that a strong password is set. You can also use dm-crypt to manually encrypt the drive.

Note that full encryption does not include / boot, so you can still modify the kernel, boot loader, and other critical files. To completely prevent tampering, you must also implement a validated boot.

BIOS / UEFI strengthening

If you are still using older versions of BIOS, you should migrate to UEFI to take advantage of newer security features. Most BIOS or UEFI implementations support setting passwords. It's best to enable it and set a very strong password. Although this is weak protection, because it is easy to reset the password. It is usually stored in volatile memory, so attackers only need to be able to remove the CMOS battery for a few seconds, or they can reset it using jumpers on some motherboards.

You should also disable all unused devices and boot options, such as USB boot, to reduce the attack surface.

Don't ignore updates to BIOS or UEFI, be sure to update them. Make it as important as regular operating system updates.

In addition, see the NSA hardware and firmware Security Guide [6].

Bootloader password

The boot loader executes early in the boot process and is responsible for loading the operating system. It is very important to protect it, otherwise it may be tampered with. For example, a local attacker can easily obtain root shell by using init=/bin/bash as a kernel parameter at startup, which tells the kernel to execute / bin/bash instead of a regular init system. You can prevent this by setting a password for the boot loader. Setting the bootstrapper password alone is not enough to fully protect it. You must also follow the instructions below to set up a validated startup.

Grub

To set the password for GRUB, execute:

Grub-mkpasswd-pbkdf2

Enter your password, which will generate a string. It will be similar to "grub.pbkdf2.sha512.10000.C4009...". Create / etc/grub.d/40_password and add:

Set superusers= "$username" password_pbkdf2 $username $password

Replacing "$username" with a string generated by grub-mkpasswd-pbkdf2 will be used for superusers who are allowed to use the GRUB command line, edit menu items, and execute any menu items. For most people, this is just "root".

Regenerate your profile and GRUB will now be password protected.

To restrict editing of boot parameters and access to the GRUB console, while still allowing you to boot, edit / boot/grub/grub.cfg and add the "--unrestricted" parameter next to "menuentry'$OSName'".

Menuentry 'Arch Linux'-- unrestricted

You will need to regenerate the configuration file again to apply this change.

Syslinux

Syslinux can set the master password or menu password. A master password is required to boot any entry, while only a menu password is needed to boot a specific entry.

To set the master password for Syslinux, edit / boot/syslinux/syslinux.cfg and add:

MENU MASTER PASSWD $password

To set the menu password, edit / boot/syslinux/syslinux.cfg and in the label with the item you want to password protect, add:

MENU PASSWD $password

Replace "$password" with the password you want to set.

These passwords can be plain text or can be hashed using MD5,SHA-1,SHA-256 or SHA-512. It is recommended that you first hash the password using a strong hash algorithm, such as SHA-256 or SHA-512, to avoid storing it in clear text.

Systemd-boot

Systemd-boot has an option to prevent kernel parameters from being edited at boot time. In the loader.conf file, add:

Editor no

Systemd-boot does not officially support protecting kernel parameter editor passwords, but you can use systemd-boot-password to do so.

Verify Boot

The verified boot ensures the integrity of the boot chain and the basic system through password authentication. This can be used to ensure that physical attackers cannot modify the software on the device.

Without a validated boot, all of the above precautions can be easily bypassed once physical access is granted. Proven guidance is not just for physical security, as many people think. It can also be used to prevent remote malware persistence-if an attacker manages to break the entire system and gain high privileges, the authenticated boot restores its changes after a reboot and ensures that they cannot be persisted.

The most common verified boot implementation is UEFI secure boot, but it is not a complete implementation by itself, because it only validates the boot loader and kernel, which means that you can:

UEFI security startup alone does not have an immutable trust root, so physical attackers can still flash the firmware of the device. To mitigate this situation, use UEFI secure startup in conjunction with Intel Boot Guard or AMD Secure Boot.

Remote attackers (or physical attackers who do not use encryption) can simply modify any other privileged part of the operating system. For example, if they have the privilege of modifying the kernel, they can also modify / sbin/init to effectively get the same result. Therefore, verifying only the kernel and the boot loader does not have any impact on remote attackers. To mitigate this, you must use dm-verity to validate the basic operating system, although this is difficult and clumsy due to the layout of traditional Linux distributions.

In general, it is difficult to implement a reliable and validated boot implementation on a traditional Linux

USBs

USB devices provide an important attack surface for physical attacks. Examples such as BadUSB and Stuxnet are examples of such attacks. The best practice is to disable all newly connected USB and whitelist only trusted devices, for which USBGuard is very useful.

You can also use nousb as a kernel boot parameter to disable all USB support in the kernel. Kernel.deny_new_usb=1 can be set by sysctl

DMA attack

Direct memory access (DMA) attacks involve full access to all system memory by inserting some physical devices. This can be mitigated by controlling the IOMMU of memory areas accessible to the device or blacklisting kernel modules that are particularly vulnerable.

To enable IOMMU, set the following kernel boot parameters:

Intel_iommu=on amd_iommu=on

You only need to enable this option for a specific CPU manufacturer, but there is no problem enabling both options.

Efi=disable_early_pci_dma

This option fixes the vulnerability in the above IOMMU by disabling the busmaster bit on all PCI bridges during a very early startup.

In addition, Thunderbolt and FireWire are generally vulnerable to DMA attacks. To disable them, blacklist these kernel modules:

Install firewire-core / bin/false install thunderbolt / bin/false

Cold start attack

A cold start attack occurs when an attacker parses the data in the RAM before erasing it. When using modern RAM, cold start attacks are not practical because RAM is usually cleared in seconds or minutes unless it is placed in a coolant such as liquid nitrogen or a freezer. The attacker must pull out the RAM stick from the device and expose it to liquid nitrogen within seconds, and make sure that the user does not notice.

If a cold start attack is part of a threat model, protect your computer for a few minutes after shutdown to ensure that no one can access your RAM memory stick. You can also weld the RAM bar to the motherboard to make it more difficult to get stuck. If you are using a laptop, remove the battery and power it directly with the charging cable. Unplug the cable after shutdown to ensure that the RAM is completely powered off and inaccessible.

In the kernel self-protection startup parameters section, the memory zeroing option when idle will overwrite sensitive data in memory with zeros. In addition, the enhanced memory allocator can clear sensitive data from user space heap memory through the CONFIG_ZERO_ON_FREE configuration option. Nevertheless, some data may remain in memory.

In addition, the modern kernel includes mitigation measures for reset attacks, which commands firmware to erase data on shutdown, although this requires firmware support.

Make sure that the computer is shut down properly so that the above mitigation measures can begin.

If none of the above applies to your threat model, you can implement Tails's memory erase process, which erases most of the memory (except video memory) and has been proven to be effective.

Best practic

Once the system has been hardened as much as possible, good privacy and security practices should be followed:

Disable or remove things you don't need to minimize the attack surface.

Keep up to date. Configure cron tasks or init scripts to update the system on a daily basis.

Don't divulge any information about you or your system, no matter how small it may seem.

Follow general security and privacy recommendations

Despite the enhancements, you must keep in mind that Linux is still a flawed operating system, and there are no enhancements that can completely fix it.

Terminology

You may need to regenerate the GRUB configuration to apply some of the changes made to the boot loader. The steps to do this may sometimes vary from release to release. For example, on a distribution such as Arch Linux, you should regenerate the configuration file by executing the following command:

Grub-mkconfig-o $path_to_grub_config

"$path_to_grub_config" depends on how you set up the system. It's usually / boot/grub/grub.cfg or / boot/EFI/grub/grub.cfg, but make sure it's correct before you execute this command.

In addition, on distributions such as Debian or Ubuntu, you should execute the following command:

Update-grub capability

In the Linux kernel, "root privileges" are divided into different capabilities (capabilities). This is useful when applying the least privilege principle-- they can be granted only a specific subset, rather than the overall root privilege of the process. For example, if the program only needs to set the system time, it only needs all the capabilities of CAP_SYS_TIME, not root. This limits the damage that can be caused, but you must still be careful to grant capabilities, because in any case, many of these capabilities may be abused to gain full root privileges.

The above is the editor for you to share how to strengthen the security of the Linux system, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report