Security: Difference between revisions

From ArchWiki
(Add link of zh-hans.)
m (wikify link)
 
(385 intermediate revisions by 95 users not shown)
Line 2: Line 2:
[[Category:File systems]]
[[Category:File systems]]
[[Category:Networking]]
[[Category:Networking]]
[[fa:امنیت]]
[[de:Sicherheit]]
[[es:Security]]
[[ja:セキュリティ]]
[[ja:セキュリティ]]
[[pt:Security]]
[[ru:Security]]
[[ru:Security]]
[[zh-hans:Security]]
[[zh-hans:Security]]
Line 9: Line 11:
{{Related|Arch Security Team}}
{{Related|Arch Security Team}}
{{Related|General recommendations}}
{{Related|General recommendations}}
{{Related|PAM}}
{{Related|Identity management}}
{{Related|Capabilities}}
{{Related|Capabilities}}
{{Related|List of Applications/Security}}
{{Related|List of Applications/Security}}
{{Related|Arch package guidelines/Security}}
{{Related articles end}}
{{Related articles end}}
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.
Line 17: Line 20:
== Concepts ==
== Concepts ==


* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.
* It ''is'' possible to tighten security to the point where the system is unusable. Security and convenience must be balanced. The trick is to create a secure ''and'' useful system.
* There are many other things that can be done to heighten the security, but the biggest threat is, and will always be, the user. When you think security, you have to think layers. When one layer is breached, another should stop the attack. But you can never make the system 100% secure unless you unplug the machine from all networks, lock it in a safe and never use it.
* The biggest threat is, and will always be, the user.
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!
* The [[Wikipedia:Principle of least privilege|principle of least privilege]]: Each part of a system should only be able to access what is strictly required, and nothing more.
* The [[Wikipedia:Principle of least privilege|principle of least privilege]]: each part of a system should only be able to access what is required to use it, and nothing more.
* Defense in depth: Security works better in independent layers. When one layer is breached, another should stop the attack.
* Be a little paranoid. And be suspicious. If anything sounds too good to be true, it probably is!
* You can never make a system 100% secure unless you unplug the machine from all networks, turn it off, lock it in a safe, smother it in concrete and never use it.
* Prepare for failure. Create a plan ahead of time to follow when your security is broken.


== Passwords ==
== Passwords ==


Passwords are key to a secure Linux system. They secure your [[Users and groups|user accounts]], [[Disk encryption|encrypted filesystems]], and [[SSH keys|SSH]]/[[GPG]] keys. They are the main way a computer chooses to trust the person using it, so a big part of security is just about picking secure passwords and protecting them.
Passwords are key to a secure system. They secure your [[Users and groups|user accounts]], [[Data-at-rest encryption|encrypted filesystems]], and [[SSH keys|SSH]]/[[GPG]] keys. They are the main way a computer chooses to trust the person using it, so a big part of security is just about picking secure passwords and protecting them.


=== Choosing secure passwords ===
=== Choosing secure passwords ===


When relying on a passphrase, it must be complex enough to not be easily guessed from e.g. personal information, or [[Wikipedia:Password cracking|cracked]] using methods like brute-force attacks. The tenets of strong passphrases are based on ''length'' and ''randomness''. In cryptography the quality of a passphrase is referred to as its [[Wikipedia:Entropic security|entropic security]].  
Passwords must be complex enough to not be easily guessed from e.g. personal information, or [[Wikipedia:Password cracking|cracked]] using methods like social engineering or brute-force attacks. The tenets of strong passwords are based on ''length'' and ''randomness''. In cryptography the quality of a password is often referred to as its [[Wikipedia:Password_strength#Entropy_as_a_measure_of_password_strength|entropy]].  


Insecure passwords include those containing:
Insecure passwords include those containing or those using as a base before substitution/variation:


* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}}), as modern dictionary attacks can easily work with these
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.
* Common phrases or short strings of common dictionary words (e.g. {{ic|photocopyhauntbranchexpose}}) including with character substitution (e.g. {{ic|Ph0toc0pyh4uN7br@nch3xp*se}}) (See Diceware below for when a combination of dictionary words can be secure)
* Any of the [[wikipedia:List_of_the_most_common_passwords|most common passwords]]


The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.
 
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.
The best choice for a password is something long (the longer, the better) and generated from a random source. It is important to use a long password. [https://www.theregister.com/2019/02/14/password_length Weak hash algorithms allow an 8-character password hash to be compromised in just a few hours.]
 
Tools like {{Pkg|pwgen}} or {{AUR|apg}} can generate random passwords. However, these passwords can be difficult to memorize. One memorization technique (for ones often typed) is to generate a long password and memorize a minimally secure number of characters, temporarily writing down the full generated string. Over time, increase the number of characters typed - until the password is ingrained in muscle memory and need not be remembered. This technique is more difficult, but can provide confidence that a password will not turn up in wordlists or "intelligent" brute force attacks that combine words and substitute characters.
 
Apart from password management, {{Pkg|keepassxc}} offers password/passphrase generation. It is possible to customize the generation in a GUI. Dictionary based passphrases are also supported.
 
One technique for memorizing a password is to use a mnemonic phrase, where each word in the phrase reminds you of the next character in the password.
Take for instance “the girl is walking down the rainy street” could be translated to {{ic|t6!WdtR5}} or, less simply, {{ic|t&6!RrlW@dtR,57}}.
Take for instance “the girl is walking down the rainy street” could be translated to {{ic|t6!WdtR5}} or, less simply, {{ic|t&6!RrlW@dtR,57}}.
This approach could make it easier to remember a password, but note that the various letters have very different probabilities of being found at the start of words ([[Wikipedia:Letter frequency#Relative frequencies of the first letters of a word in the English language|Wikipedia:Letter frequency]]). Also consider the [http://world.std.com/~reinhold/diceware.html Diceware Passphrase] method, using a sufficient number of words.
This approach could make it easier to remember a password, but note that the various letters have very different probabilities of being found at the start of words ([[Wikipedia:Letter frequency#Relative frequencies of the first letters of a word in the English language|Wikipedia:Letter frequency]]).  


A better approach is to generate pseudo-random passwords with tools like {{Pkg|pwgen}} or {{AUR|apg}}: for memorizing them, one technique (for ones typed often) is to generate a long password and memorize a minimally secure number of characters, temporarily writing down the full generated string. Over time, increase the number of characters typed - until the password is ingrained in muscle memory and need not be remembered. This technique is more difficult, but can provide confidence that a password will not turn up in wordlists or "intelligent" brute force attacks that combine words and substitute characters.
Another effective technique can be to write randomly generated passwords down and store them in a ''safe'' place, such as in a wallet, purse, or document safe. Most people do a generally good job of protecting their physical valuables from attack, and it is easier for most people to understand physical security best practices compared to digital security practices.


It is also very effective to combine these two techniques by saving long, complex random passwords with a [[password manager]], which will be in turn accessed with a mnemonic password that will have to be used only for that purpose, especially avoiding to ever transmit it over any kind of network. This method of course limits the use of the stored passwords to the terminals where the database is available for reading (which on the other hand could be seen as an added security feature).
It is also very effective to combine the mnemonic and random technique by saving long randomly generated passwords with a [[password manager]], which will be in turn accessed with a memorable "master password"/primary password that must be used only for that purpose. The master password must be memorized and never saved. This requires the password manager to be installed on a system to easily access the password (which could be seen as an inconvenience or a security feature, depending on the situation). Some password managers also have smartphone apps which can be used to display passwords for manual entry on systems without that password manager installed (if that is a common use case, you could still use easily typeable but secure passwords for each service instead of completely random ones, see below). Note that a password manager introduces a single point of failure if you ever forget the master password. 
Some password managers compute the contained passwords based on the master password and the service name where you want to log in instead of encrypting them, making it possible to use it on a new system without syncing any data.


See Bruce Schneier's article [https://www.schneier.com/blog/archives/2014/03/choosing_secure_1.html Choosing Secure Passwords], [https://www.iusmentis.com/security/passphrasefaq/ The passphrase FAQ] or [[Wikipedia:Password strength]] for some additional background.
It can be effective to use a memorable long series of unrelated words as a password. The theory is that if a sufficiently long phrase is used, the gained entropy from the password's length can counter the lost entropy from the use of dictionary words. This [https://xkcd.com/936/ xkcd comic] demonstrates the entropy tradeoff of this method, taking into account the limited set of possible words for each word in the passphrase. If the set of words you choose from is large (multiple thousand words) and you choose 5-7 or even more random words from it, this method provides great entropy, even assuming the attacker knows the set of possible words chosen from and the number of words chosen. The number of possible passphrases after settling on a set of words and number of words is: (number of words in the set of words to select from) to the power of (the number of words chosen for the passphrase). See e.g. [https://www.rempe.us/diceware/ Diceware] for more.
 
See [https://www.iusmentis.com/security/passphrasefaq/ The passphrase FAQ] or [[Wikipedia:Password strength]] for some additional background.


=== Maintaining passwords ===
=== Maintaining passwords ===


Once you pick a strong password, be sure to keep it safe. Watch out for [[Wikipedia:Keylogger|keyloggers]] (software and hardware), [[Wikipedia:Social engineering (security)|social engineering]], [[Wikipedia:Shoulder surfing (computer security)|shoulder surfing]], and avoid reusing passwords so insecure servers cannot leak more information than necessary. [[List of applications/Security#Password managers|Password managers]] can help manage large numbers of complex passwords: if you are copy-pasting the stored passwords from the manager to the applications that need them, make sure to clear the copy buffer every time, and ensure they are not saved in any kind of log (e.g. do not paste them in plain terminal commands, which would store them in files like {{ic|.bash_history}}).
Once you pick a strong password, be sure to keep it safe. Watch out for [[Wikipedia:Keylogger|keyloggers]] (software and hardware), screen loggers, [[Wikipedia:Social engineering (security)|social engineering]], [[Wikipedia:Shoulder surfing (computer security)|shoulder surfing]], and avoid reusing passwords so insecure servers cannot leak more information than necessary. [[List of applications/Security#Password managers|Password managers]] can help manage large numbers of complex passwords: if you are copy-pasting the stored passwords from the manager to the applications that need them, make sure to clear the copy buffer every time, and ensure they are not saved in any kind of log (e.g. do not paste them in plain terminal commands, which would store them in files like {{ic|.bash_history}}). Note that password managers that are implemented as browser extensions may be vulnerable to [https://www.spookjs.com side channel attacks]. These can be mitigated by using password managers that run as separate applications.


As a rule, do not pick insecure passwords just because secure ones are harder to remember. Passwords are a balancing act. It is better to have an encrypted database of secure passwords, guarded behind a key and one strong master password, than it is to have many similar weak passwords. Writing passwords down is perhaps equally effective[https://www.schneier.com/blog/archives/2005/06/write_down_your.html], avoiding potential vulnerabilities in software solutions while requiring physical security.
As a rule, do not pick insecure passwords just because secure ones are harder to remember. Passwords are a balancing act. It is better to have an encrypted database of secure passwords, guarded behind a key and one strong master password, than it is to have many similar weak passwords. Writing passwords down is perhaps equally effective [https://www.schneier.com/blog/archives/2005/06/write_down_your.html], avoiding potential vulnerabilities in software solutions while requiring physical security.


Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.
If you use the same passphrase for disk encryption as you use for your login password (useful e.g. to auto-mount the encrypted partition or folder on login), make sure that {{ic|/etc/shadow}} either also ends up on an encrypted partition, or uses a strong hash algorithm (i.e. sha512/bcrypt, not md5) for the stored password hash (see [[SHA password hashes]] for more info).


If you are backing up your password database, make sure that each copy is not stored behind any other passphrase which in turn is stored in it, e.g. an encrypted drive or an authenticated remote storage service, or you will not be able to access it in case of need; a useful trick is to protect the drives or accounts where the database is backed up using a simple cryptographic hash of the master password. Maintain a list of all the backup locations: if one day you fear that the master passphrase has been compromised you will have to change it immediately on all the database backups and the locations protected with keys derived from the master password. Version-controlling the database in a secure way can be very complicated: if you choose to do it, you must have a way to update the master password of all the database versions. It may not always be immediately clear when the master password is leaked: to reduce the risk of somebody else discovering your password before you realize that it leaked, you may choose to change it on a periodical basis. If you fear that you have lost control over a copy of the database, you will need to change all the passwords contained in it within the time that it may take to brute-force the master password, according to its entropy.
If you use the same passphrase for disk encryption as you use for your login password (useful e.g. to auto-mount the encrypted partition or folder on login), make sure that {{ic|/etc/shadow}} ends up on an encrypted partition or/and uses a strong key derivation function (i.e. yescrypt/argon2 or sha512 with PBKDF2, but not md5 or low iterations in PBKDF2) for the stored password hash (see [[SHA password hashes]] for more information).
 
{{Tip|Arch Linux switched the [https://archlinux.org/news/changes-to-default-password-hashing-algorithm-and-umask-settings/ default hashing] algorithm to yescrypt. If you have not customized the default, executing a password change with {{ic|passwd}} is necessary (and sufficient) to apply the new default.}}
 
If you are backing up your password database, make sure that each copy is not stored behind any other passphrase which in turn is stored in it, e.g. an encrypted drive or an authenticated remote storage service, or you will not be able to access it in case of need; a useful trick is to protect the drives or accounts where the database is backed up using a simple cryptographic hash of the master password. Maintain a list of all the backup locations: if one day you fear that the master passphrase has been compromised you will have to change it immediately on all the database backups and the locations protected with keys derived from the master password.
 
Version-controlling the database in a secure way can be very complicated: if you choose to do it, you must have a way to update the master password of all the database versions. It may not always be immediately clear when the master password is leaked: to reduce the risk of somebody else discovering your password before you realize that it leaked, you may choose to change it on a periodical basis. If you fear that you have lost control over a copy of the database, you will need to change all the passwords contained in it within the time that it may take to brute-force the master password, according to its entropy.


=== Password hashes ===
=== Password hashes ===


{{Expansion|Mention [[Wikipedia:Key derivation function|key derivation functions]], in particular PBKDF2, bcrypt and scrypt, how to use them, advantages and disadvantages, especially regarding custom-hardware-based brute-force attacks.|section=Removal of incorrect warning}}
A hash is a one-way function, i.e. it is designed to make it impossible to deduct the input without computing the hash function with it (example: MD5, SHA).
 
A password-hash function is designed to make deducting a user-input (password) impossible without computing the hash function with it (example: bcrypt). A [[wikipedia:Key derivation function|key derivation function]] (KDF; examples: yescrypt, scrypt, PBKDF2) is a cryptographic algorithm designed to derive secret keys (e.g. an AES key, a password hash) from an input (a master key, a password). Hence, a KDF can serve multiple applications, including those of a password-hash function.


By default, Arch stores the hashed user passwords in the root-only-readable {{ic|/etc/shadow}} file, separated from the other user parameters stored in the world-readable {{ic|/etc/passwd}} file, see [[Users and groups#User database]]. See also [[#Restricting root]].
By default, Arch stores the hashed user passwords in the root-only-readable {{ic|/etc/shadow}} file, separated from the other user parameters stored in the world-readable {{ic|/etc/passwd}} file, see [[Users and groups#User database]]. See also [[#Restricting root]].


Passwords are set with the '''passwd''' command, which [[Wikipedia:Key stretching|stretches]] them with the [[Wikipedia:Crypt (C)|crypt]] function and then saves them in {{ic|/etc/shadow}}. See also [[SHA password hashes]]. The passwords are also [[Wikipedia:Salt (cryptography)|salted]] in order to defend them against [[Wikipedia:Rainbow table|rainbow table]] attacks.
Passwords are set with the '''passwd''' command, which [[Wikipedia:Key stretching|stretches]] them with the system's crypt function and then saves them in {{ic|/etc/shadow}}. The passwords are also [[Wikipedia:Salt (cryptography)|salted]] in order to defend them against [[Wikipedia:Rainbow table|rainbow table]] attacks. See also [https://www.slashroot.in/how-are-passwords-stored-linux-understanding-hashing-shadow-utils How are passwords stored in Linux (Understanding hashing with shadow utils)].
 
Since password hashes follow a defined format, the method and parameter can be configured for subsequent new invocations of the ''passwd'' command. Hence, the individual hashes stored in the {{ic|/etc/shadow}} file can be a heterogeneous mix of the hash functions supported by the system.
 
See {{man|5|crypt}} for more information on the format, hashing methods and parameters.
 
The {{ic|/etc/login.defs}} file configures the [https://archlinux.org/news/changes-to-default-password-hashing-algorithm-and-umask-settings/ default password hashing] method {{ic|ENCRYPT_METHOD YESCRYPT}} and its parameter {{ic|YESCRYPT_COST_FACTOR}}.
 
For example, an increment of the default {{ic|YESCRYPT_COST_FACTOR}} parameter will lead to a logarithmic increase of the compute time required to deduce the hash from a password. This applies, likewise, to a third-party trying to obtain the password secret, and the system to authenticate a user log-in.
 
In contrast, the compute time for the SHA-512 hash function is configured by a parameter with a linear influence. See [[SHA password hashes]] for information on the previous Arch default. Note the yescrypt algorithm internally uses SHA-256, HMAC and PBKDF2 to compute its password-hash. The main reason is to combine positive attributes of these widely used and tested functions for an enhanced resistance to attacks. For example, the usability of SHA for various purposes has resulted in hardware support for the function, i.e. the performance to compute a pure SHA hash has accelerated considerably, making its application as a password-hash function more and more derelict.
 
=== Enforcing strong passwords with pam_pwquality ===


See also [http://www.slashroot.in/how-are-passwords-stored-linux-understanding-hashing-shadow-utils How are passwords stored in Linux (Understanding hashing with shadow utils)].
''pam_pwquality'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system. It is based on ''pam_cracklib'', so it is backwards compatible with its options.


=== Enforcing strong passwords using pam_cracklib ===
[[Install]] the {{Pkg|libpwquality}} package.


''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.
{{Warning|The ''root'' account is not affected by this policy by default.}}


{{Warning|The ''root'' account is not affected by this policy.}}
{{Note|
{{Note|You can use the ''root'' account to set a password for a user that bypasses the desired/configured policy. This is useful when setting temporary passwords.}}
* You can use the ''root'' account to set a password for a user that bypasses the desired/configured policy. This is useful when setting temporary passwords.
* Current security guidelines around passwords, e.g. from NIST, but also from others, do not recommend enforcing special characters, since they often only lead to predictable alterations.
}}


If for example you want to enforce this policy:
If for example you want to enforce this policy:


* prompt 2 times for password in case of an error
* prompt 2 times for password in case of an error (retry option)
* 10 characters minimum length (minlen option)
* 10 characters minimum length (minlen option)
* at least 6 characters should be different from old password when entering a new one (difok option)
* at least 6 characters should be different from old password when entering a new one (difok option)
* at least 1 digit (dcredit option)
* at least 1 digit (dcredit option)
* at least 1 uppercase (ucredit option)
* at least 1 uppercase (ucredit option)
* at least 1 lowercase (lcredit option)
* at least 1 other character (ocredit option)
* at least 1 other character (ocredit option)
* at least 1 lowercase (lcredit option)
* cannot contain the words "myservice" and "mydomain"
* enforce the policy for root


Edit the {{ic|/etc/pam.d/passwd}} file to read as:
Edit the {{ic|/etc/pam.d/passwd}} file to read as:
Line 90: Line 129:
{{bc|1=
{{bc|1=
#%PAM-1.0
#%PAM-1.0
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password required pam_pwquality.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1 [badwords=myservice mydomain] enforce_for_root
password required pam_unix.so use_authtok sha512 shadow
password required pam_unix.so use_authtok sha512 shadow
}}
}}


The {{ic|password required pam_unix.so use_authtok}} instructs the ''pam_unix'' module to not prompt for a password but rather to use the one provided by ''pam_cracklib''.
The {{ic|password required pam_unix.so use_authtok}} instructs the ''pam_unix'' module to not prompt for a password but rather to use the one provided by ''pam_pwquality''.
 
You can refer to the {{man|8|pam_pwquality}} and {{man|8|pam_unix}} man pages for more information.
 
== CPU ==
 
=== Microcode ===
 
See [[microcode]] for information on how to install important security updates for your CPU's microcode.


You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.
=== Hardware vulnerabilities ===
 
Some CPUs contain hardware vulnerabilities. See the [https://docs.kernel.org/admin-guide/hw-vuln/ kernel documentation on hardware vulnerabilities] for a list of these vulnerabilities, as well as mitigation selection guides to help customize the kernel to mitigate these vulnerabilities for specific usage scenarios.
 
To check if you are affected by a known vulnerability, run the following:
 
$ grep -r . /sys/devices/system/cpu/vulnerabilities/
 
In most cases, updating the kernel and microcode will mitigate vulnerabilities.
 
==== Simultaneous multithreading (hyper-threading) ====
 
{{Note|This is something mostly hypervisors benefit from. Enabling it on an ordinary system has very little to no security benefits.}}
 
[[Wikipedia:Simultaneous multithreading|Simultaneous multithreading]] (SMT), also called hyper-threading on Intel CPUs, is a hardware feature that may be a source of [https://docs.kernel.org/admin-guide/hw-vuln/l1tf.html L1 Terminal Fault] and [https://docs.kernel.org/admin-guide/hw-vuln/mds.html Microarchitectural Data Sampling] vulnerabilities. The Linux kernel and microcode updates contain mitigations for known vulnerabilities, but [https://docs.kernel.org/admin-guide/hw-vuln/l1tf.html#virtualization-with-untrusted-guests disabling SMT may still be required on certain CPUs if untrusted virtualization guests are present].
 
SMT can often be disabled in your system's firmware. Consult your motherboard or system documentation for more information. You can also disable SMT in the kernel by adding the following [[kernel parameter]]:
 
mitigations=auto,nosmt
 
== Memory ==
 
=== Hardened malloc ===
 
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened_malloc}}, {{AUR|hardened-malloc-git}}) is a hardened replacement for [[Wikipedia:GNU C Library|glibc]]'s malloc(). The project was originally developed for integration into Android's [[Wikipedia:Bionic (software)|Bionic]] and [[Wikipedia:musl|musl]] by Daniel Micay, of [[Wikipedia:GrapheneOS|GrapheneOS]], but he has also built in support for standard Linux distributions on the x86_64 architecture.
 
While hardened_malloc is not yet integrated into glibc (assistance and pull requests welcome) it can be used easily with LD_PRELOAD. In testing so far, it only causes issues with a handful of applications if enabled globally in {{ic|/etc/ld.so.preload}}. Since hardened_malloc has a performance cost, you may want to decide which implementation to use on a case-by-case basis based on attack surface and performance needs.
 
{{Accuracy|Firefox may require a rebuild for use with hardened-malloc to be effective|section=Use of hardened-malloc with Firefox}}
 
To try it out in a standalone manner, use the hardened-malloc-preload wrapper script, or manually start an application with the proper preload value:
 
LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox
 
Proper usage with [[Firejail]] can be found on its wiki page, and some configurable build options for hardened_malloc can be found on the github repo.


== Storage ==
== Storage ==


=== Disk encryption ===
=== Data-at-rest encryption ===


[[Disk encryption]], preferably full disk encryption with a [[#Passwords|strong passphrase]], is the only way to guard data against physical recovery. This provides complete security when the computer is turned off or the disks in question are unmounted.
[[Data-at-rest encryption]], preferably full-disk encryption with a [[#Passwords|strong passphrase]], is the only way to guard data against physical recovery. This provides data confidentiality when the computer is turned off or the disks in question are unmounted.


Once the computer is powered on and the drive is mounted, however, its data becomes just as vulnerable as an unencrypted drive. It is therefore best practice to unmount data partitions as soon as they are no longer needed.
Once the computer is powered on and the drive is mounted, however, its data becomes just as vulnerable as an unencrypted drive. It is therefore best practice to unmount data partitions as soon as they are no longer needed.


Certain programs, like [[dm-crypt]], allow the user to encrypt a loop file as a virtual volume. This is a reasonable alternative to full disk encryption when only certain parts of the system need be secure.
You may also [[Trusted Platform Module#Data-at-rest encryption with LUKS|encrypt a drive with the key stored in a TPM]], although it has had [https://tpm.fail vulnerabilites in the past] and the key can be extracted by a [https://pulsesecurity.co.nz/articles/TPM-sniffing bus sniffing attack].
 
Certain programs, like [[dm-crypt]], allow the user to encrypt a loop file as a virtual volume. This is a reasonable alternative to full-disk encryption when only certain parts of the system need to be secure.
 
While the block-device or filesystem-based encryption types compared in the [[data-at-rest encryption]] article are useful at protecting data on physical media, most can not be used to protect data on a remote system that you can not control (such as [[Data-at-rest encryption#Cloud-storage optimized|cloud storage]]). In some cases, individual file encryption will be useful.
 
These are some methods to encrypt files:
* Some [[Archiving and compression|archiving and compressing]] tools also provide basic encryption. Some examples are {{Pkg|p7zip}} ({{ic|-p}} flag), {{Pkg|zip}} ({{ic|-e}} flag). The encryption should only be relied on particular care, because the tools may use custom algorithms for cross-platform compatibility.[https://math.ucr.edu/~mike/zipattacks.pdf]
* [[GnuPG]] can be used to [[GnuPG#Encrypt and decrypt|encrypt files]].
* {{Pkg|age}} is a simple and easy to use file encryption tool. It also supports multiple recipients and encryption using SSH keys, which is useful for secure file sharing.


=== File systems ===
=== File systems ===
Line 123: Line 213:
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.
* {{ic|noexec}}: Do not allow direct execution of any  binaries on the mounted file system.
* {{ic|noexec}}: Do not allow direct execution of any  binaries on the mounted file system.
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]], [[Steam]], PyCharm, [[.NET]], etc.
*** Wine does not need the {{ic|exec}} flag for opening Windows binaries. It is only needed when Wine itself is installed in {{ic|/home}}.
*** To keep [[Steam]] working you can mount {{ic|/home/user/.local/share/Steam}} as {{ic|exec}} in [[fstab]] by adding the following: {{bc|/home/user/.local/share/Steam  /home/user/.local/share/Steam  none defaults,bind,user,exec,nofail  0  0}}
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.
{{Note|Wine does not need the {{ic|exec}} flag for opening Windows executables. It is only needed when Wine itself is installed in {{ic|/home}}.}}


File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.
Line 137: Line 227:
* {{ic|/tmp}}
* {{ic|/tmp}}
* {{ic|/boot}}
* {{ic|/boot}}
{{Tip|When using [[Systemd#GPT partition automounting|GPT partition automounting]], the ESP and XBOOTLDR partitions are [https://github.com/systemd/systemd-stable/commit/49804cfb71d3a79f433096e4cfb5616980171336 always hardened] with {{ic|noexec,nosuid,nodev}}.}}


=== File access permissions ===
=== File access permissions ===


The default [[file permissions]] allow read access to almost everything and changing the permissions can hide valuable information from an attacker who gains access to a non-root account such as the {{ic|http}} or {{ic|nobody}} users.
{{Accuracy|{{ic|chmod go-r}} does not "take away all permissions", it only removes the read permission.}}


For example:
The default [[file permissions]] allow read access to almost everything and changing the permissions can hide valuable information from an attacker who gains access to a non-root account such as the {{ic|http}} or {{ic|nobody}} users. You can use [[chmod]] to take away all permissions from the group and others:


  # chmod 700 /boot /etc/{iptables,arptables}
  # chmod go-r ''path_to_hide''


The default [[Umask]] {{ic|0022}} can be changed to improve security for newly created files. The [https://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf NSA RHEL5 Security Guide] suggests a umask of {{ic|0077}} for maximum security, which makes new files not readable by users other than the owner. To change this, see [[Umask#Set the mask value]].
{{Warning|Do not apply this broadly. Try this for one config at a time, ensuring that it is worth hiding, and that it will not break program functionality. You may need to remove the {{ic|g}} from the command (or re-add the permission with {{ic|chmod g+r ''path''}} if already ran) if the group is relied on.}}
 
Some paths to consider are:
 
* {{ic|/boot}}: The [[Partitioning#/boot|boot directory]], which includes the [[vmlinuz]] and [[initramfs]] images.
* {{ic|/etc/nftables.conf}}: The [[nftables]] configuration, applicable to {{Pkg|nftables}} and {{Pkg|iptables-nft}}.
* {{ic|/etc/iptables}}: The legacy [[iptables]] configuration, applicable to {{Pkg|iptables}}.
 
The default [[umask]] {{ic|0022}} can be changed to improve security for newly created files. The [https://apps.nsa.gov/iaarchive/library/ia-guidance/security-configuration/operating-systems/guide-to-the-secure-configuration-of-red-hat-enterprise.cfm NSA RHEL5 Security Guide] suggests a umask of {{ic|0077}} for maximum security, which makes new files not readable by users other than the owner. To change this, see [[Umask#Set the mask value]]. If you use [[sudo]], consider configuring it to use the [[Sudo#Permissive umask|default root umask]].
 
=== SUID and SGID files ===
 
It is important to be aware of any files with the [[Wikipedia:Setuid|Setuid]] or Setgid bit. Examples of relevant files in {{ic|/usr/bin}} with the SUID bit set and owned by root:
 
* gpasswd
* pkexec
* [[sudo]]
* [[su]]
* [[passwd]]
* [[firejail]]
 
The prominent risks of such executable files include privilege escalation vulnerabilities, see e.g [[Wikipedia:Setuid#Security impact]].[https://www.cvedetails.com/vulnerability-list/vendor_id-16224/product_id-36412/Calibre-ebook-Calibre.html][https://www.cvedetails.com/product/32625/Sudo-Project-Sudo.html?vendor_id=15714][https://www.cvedetails.com/vulnerability-list/vendor_id-16191/Firejail-Project.html]
 
Files with the SUID bit set and not owned by root, or files with the SGID bit set ''typically'' have less potential impact but can theoretically still do decent damage if vulnerable. It is usually possible to avoid using Setuid or Setgid by assigning [[Capabilities]] instead.
 
{{Tip|It is vital to be vigilant in keeping packages which provide SUID/SGID executables up to date in order to prevent having a vulnerable system.}}
 
To search {{ic|/usr/bin}} for files with either the SUID or SGID bit:
 
$ find /usr/bin -perm "/u=s,g=s"
 
=== Backups ===
 
{{Merge|System backup|There is a dedicated page for system backups.}}
 
Regularly create backups of important data. Regularly test the integrity of the backups. Regularly test that the backups can be restored.
 
Make sure that at least one copy of the data is stored offline, i.e. not connected to the system under threat in any way. [[Wikipedia:Ransomware|Ransomware]] and other destructive attacks may also attack any connected backup systems.
 
=== SATA SSD frozen mode ===
 
See [[Solid state drive#Setting the SSD state to frozen mode after waking up from sleep]].


== User setup ==
== User setup ==


After installation make a normal user for daily use. Do not use the root user for daily use.
=== Do not use the root account for daily use ===
 
Following the principle of least privilege, do not use the root user for daily use. Create a non-privileged user account for each person using the system. Use [[sudo]] as necessary for temporary privileged access.


=== Enforce a delay after a failed login attempt ===
=== Enforce a delay after a failed login attempt ===
Line 156: Line 291:
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:


{{hc|/etc/pam.d/system-login|
{{hc|/etc/pam.d/system-login|2=
2=auth optional pam_faildelay.so delay=4000000
auth optional pam_faildelay.so delay=4000000
}}
}}


{{ic|4000000}} is the time in microseconds to delay.
{{ic|4000000}} is the time in microseconds to delay.


=== Lockout user after three failed login attempts ===
=== Lock out user after three failed login attempts ===
 
As of {{Pkg|pambase}} 20200721.1-2, {{ic|pam_faillock.so}} is enabled by default to lock out users for 10 minutes after 3 failed login attempts in a 15 minute period (see {{Bug|67644}}). The lockout only applies to password authentication (e.g. login and ''sudo''), public key authentication over SSH is still accepted. To prevent complete denial-of-service, this lockout is disabled for the root user by default.


To further heighten the security it is possible to lockout a user after a specified number of failed login attempts. The user account can either be locked until the root user unlocks it, or automatically be unlocked after a set time.
To unlock a user, do:


To lockout a user for ten minutes after three failed login attempts you have to modify {{ic|/etc/pam.d/system-login}} to read as:
$ faillock --user ''username'' --reset


{{hc|/etc/pam.d/system-login|
By default, the lock mechanism is a file per-user located at {{ic|/run/faillock/}}. Deleting or emptying the file unlocks that user—the directory is owned by root, but the file is owned by the user, so the {{ic|faillock}} command only empties the file, therefore does not require root.
2=#%PAM-1.0


auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed
The module {{ic|pam_faillock.so}} can be configured with the file {{ic|1=/etc/security/faillock.conf}}. The lockout parameters:
account required pam_tally2.so
}}


pam_tally is deprecated and superseded by pam_tally2, so you will want to comment out the pam_tally line:
* {{ic|unlock_time}} — the lockout time (in seconds, default 10 minutes).
* {{ic|fail_interval}} — the time in which failed logins can cause a lockout (in seconds, default 15 minutes).
* {{ic|deny}} — the number of failed logins before lockout (default 3).


#auth required pam_tally.so onerr=succeed file=/var/log/faillog
{{Tip|The primary purpose for the lockout is to slow down brute-force attacks so that they become infeasible. Hence, if lockouts due to mistyping of passwords become too frequent, relaxing the number of attempts may be preferred to reducing the lockout time.}}


That is all there is to it. If you feel adventurous, make three failed login attempts. Then you can see for yourself what happens. To unlock a user manually do:
{{Note|{{ic|1=deny = 0}} will disable the lockout mechanism entirely.}}


# pam_tally2 --reset --user ''username''
By default, all user locks are lost after reboot. If your attacker can reboot the machine, it is more secure if locks persist. To make locks persist, change the {{ic|dir}} parameter in {{ic|1=/etc/security/faillock.conf}} to {{ic|/var/lib/faillock}}.


{{ic|unlock_time}} is specified in seconds. If you want to permanently lockout a user after 3 failed login attempts remove the {{ic|unlock_time}} part of the line. The user is then unable to login until root unlocks the account.
No restart is required for changes to take effect. See {{man|5|faillock.conf}} for further configuration options, such as enabling lockout for the root account, disabling for centralized login (e.g. LDAP), etc.


=== Limit amount of processes ===
=== Limit amount of processes ===


On systems with many, or untrusted users, it is important to limit the number of processes each can run at once, therefore preventing [[Wikipedia:Fork bomb|fork bombs]] and other denial of service attacks. {{ic|/etc/security/limits.conf}} determines how many processes each user, or group can have open, and is empty (except for useful comments) by default. adding the following lines to this file will limit all users to 100 active processes, unless they use the {{ic|prlimit}} command to explicitly raise their maximum to 200 for that session. These values can be changed according to the appropriate number of processes a user should have running, or the hardware of the box you are administrating.  
On systems with many, or untrusted users, it is important to limit the number of processes each can run at once, therefore preventing [[Wikipedia:Fork bomb|fork bombs]] and other denial of service attacks. {{ic|/etc/security/limits.conf}} determines how many processes each user, or group can have open, and is empty (except for useful comments) by default. Adding the following lines to this file will limit all users to 100 active processes, unless they use the {{ic|prlimit}} command to explicitly raise their maximum to 200 for that session. These values can be changed according to the appropriate number of processes a user should have running, or the hardware of the box you are administrating.  


  * soft nproc 100
  * soft nproc 100
  * hard nproc 200
  * hard nproc 200


The current number of threads for each user can be found with {{ic|ps --no-headers -Leo user {{!}} sort {{!}} uniq -c}}. This may help with determining appropriate values for the limits.
The current number of threads for each user can be found with {{ic|ps --no-headers -Leo user {{!}} sort {{!}} uniq --count}}. This may help with determining appropriate values for the limits.


=== Run Xorg rootless ===
=== Use Wayland ===


[[Xorg]] is commonly [https://security.stackexchange.com/questions/4641/why-are-people-saying-that-the-x-window-system-is-not-secure/4646#4646 considered insecure] because of its architecture and dated design. Thus it is recommended to avoid running it as root.
Prefer using [[Wayland]] over [[Xorg]]. Xorg's design predates modern security practices and is [https://security.stackexchange.com/questions/4641/why-are-people-saying-that-the-x-window-system-is-not-secure/4646#4646 considered insecure] by many. For example, Xorg applications may record keystrokes while inactive.


See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.
If you must run Xorg, it is recommended to [[Xorg#Rootless Xorg|avoid running it as root]]. Within Wayland, the Xwayland compatibility layer will automatically use rootless Xorg.


== Restricting root ==
== Restricting root ==


The root user is, by definition, the most powerful user on a system. Because of this, there are a number of ways to keep the power of the root user while limiting its ability to cause harm, or at least to make root user actions more traceable.
The root user is, by definition, the most powerful user on a system. It is also difficult to audit the root user account. It is therefore important to restrict usage of the root user account as much as possible. There are a number of ways to keep the power of the root user while limiting its ability to cause harm.


=== Use sudo instead of su ===
=== Use sudo instead of su ===


{{Merge|sudo|There's a dedicated article.}}
{{Merge|sudo|There is a dedicated article.}}


Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].
Using [[sudo]] for privileged access is preferable to [[su]] for a number of reasons.


* It keeps a log of which normal privilege user has run each privileged command.
* It keeps a log of which normal privilege user has run each privileged command.
Line 217: Line 353:
  # visudo
  # visudo


{{hc|/etc/sudoers|
{{hc|/etc/sudoers|2=
alice ALL = NOPASSWD: /path/to/program
alice ALL = NOPASSWD: /path/to/program
}}
}}


Line 227: Line 363:
This allows all users who are members of the group users to run the commands {{ic|/sbin/mount.cifs}} and {{ic|/sbin/umount.cifs}} from any machine (ALL).
This allows all users who are members of the group users to run the commands {{ic|/sbin/mount.cifs}} and {{ic|/sbin/umount.cifs}} from any machine (ALL).


{{Tip|
{{Tip|To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},


{{hc|/etc/sudoers|
{{hc|/etc/sudoers|2=
2=Defaults editor=/usr/bin/rnano
Defaults editor=/usr/bin/rnano
}}
}}


Exporting {{ic|1=# EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.
Exporting {{ic|1=EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.
}}
}}


==== Editing files using sudo ====
==== Editing files using sudo ====


Running a text editor as root can be a security vulnerability as many editors can run arbitrary shell commands or affect files other than the one you intend to edit. To avoid this, use {{ic|sudoedit filename}} (equivalently, {{ic|sudo -e filename}}) to edit files. This edits a copy of the file using your normal user privileges and then overwrites the original using sudo only after the editor is closed. You can change the editor this uses by setting the {{ic|SUDO_EDITOR}} environment variable:
See [[Sudo#Editing files]]. Alternatively, you can use an editor like {{ic|rvim}} or {{ic|rnano}} which has restricted capabilities in order to be safe to run as root.


$ export SUDO_EDITOR=vim
=== Restricting root login ===


Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.
Once [[sudo]] is properly configured, full root access can be heavily restricted or denied without losing much usability. To disable root, but still allowing to use [[sudo]], you can use {{ic|passwd --lock root}}.


=== Restricting root login ===
==== Allow only certain users ====
 
The [[PAM]] {{ic|pam_wheel.so}} lets you allow only users in the group {{ic|wheel}} to login using [[su]]. See [[su#su and wheel]].
 
==== Denying SSH login ====


Once [[sudo]] is properly configured, full root access can be heavily restricted or denied without losing much usability. To disable root, but still allowing to use [[sudo]], you can use {{ic|passwd -l root}}.
Even if you do not wish to deny root login for local users, it is always good practice to [[OpenSSH#Deny|deny root login via SSH]]. The purpose of this is to add an additional layer of security before a user can completely compromise your system remotely.


==== Allow only certain users ====
==== Specify acceptable login combinations with access.conf ====


The [[PAM]] {{ic|pam_wheel.so}} lets you allow only users in the group {{ic|wheel}} to login using {{ic|su}}. Edit both {{ic|/etc/pam.d/su}} and {{ic|/etc/pam.d/su-l}}, then uncomment the line:
When someone attempts to log in with [[PAM]], {{ic|/etc/security/access.conf}} is checked for the first combination that matches their login properties. Their attempt then fails or succeeds based on the rule for that combination.


{{bc|<nowiki>
+:root:LOCAL
# Uncomment the following line to require a user to be in the "wheel" group.
-:root:ALL
auth required pam_wheel.so use_uid
</nowiki>}}


This means only users who are already able to run privileged commands may login as root.
Rules can be set for specific groups and users. In this example, the user archie is allowed to login locally, as are all users in the wheel and adm groups. All other logins are rejected:


==== Denying SSH login ====
+:archie:LOCAL
+:(wheel):LOCAL
+:(adm):LOCAL
-:ALL:ALL


Even if you do not wish to deny root login for local users, it is always good practice to [[OpenSSH#Deny|deny root login via SSH]]. The purpose of this is to add an additional layer of security before a user can completely compromise your system remotely.
Read more at {{man|5|access.conf}}


== Mandatory access control ==
== Mandatory access control ==
Line 270: Line 410:
=== Pathname MAC ===
=== Pathname MAC ===


Pathname-based access control is a simple form of access control that offers permissions based on the path of a given file. The downside to this style of access control is that permissions are not carried with files if they are moved about the system. On the positive side, pathname-based MAC can be implemented on a much wider range of filesystems, unlike labels-based alternatives.
Pathname-based access control is a simple form of access control that offers permissions based on the path of a given file. The downside to this style of access control is that permissions are not carried with files if they are moved around the system. On the positive side, pathname-based MAC can be implemented on a much wider range of filesystems, unlike labels-based alternatives.


* [[AppArmor]] is a [[Wikipedia:Canonical|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.
* [[AppArmor]] is a [[Wikipedia:Canonical (company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.
* [[Tomoyo]] is another simple, easy-to-use system offering mandatory access control. It is designed to be both simple in usage and in implementation, requiring very few dependencies.
* [[TOMOYO]] is another simple, easy-to-use system offering mandatory access control. It is designed to be both simple in usage and in implementation, requiring very few dependencies.


=== Labels MAC ===
=== Labels MAC ===
Line 279: Line 419:
Labels-based access control means the extended attributes of a file are used to govern its security permissions. While this system is arguably more flexible in its security offerings than pathname-based MAC, it only works on filesystems that support these extended attributes.
Labels-based access control means the extended attributes of a file are used to govern its security permissions. While this system is arguably more flexible in its security offerings than pathname-based MAC, it only works on filesystems that support these extended attributes.


* [[SELinux]], based on a [[Wikipedia:NSA|NSA]] project to improve Linux security, implements MAC completely separate from system users and roles. It offers an extremely robust multi-level MAC policy implementation that can easily maintain control of a system that grows and changes past its original configuration.
* [[SELinux]], based on an [[Wikipedia:NSA|NSA]] project to improve Linux security, implements MAC completely separate from system users and roles. It offers an extremely robust multi-level MAC policy implementation that can easily maintain control of a system that grows and changes past its original configuration.


=== Access Control Lists ===
=== Access Control Lists ===
Line 290: Line 430:


The {{pkg|linux-hardened}} package uses a [https://github.com/anthraxx/linux-hardened basic kernel hardening patch set] and more security-focused compile-time configuration options than the {{pkg|linux}} package. A custom build can be made to choose a different compromise between security and performance than the security-leaning defaults.
The {{pkg|linux-hardened}} package uses a [https://github.com/anthraxx/linux-hardened basic kernel hardening patch set] and more security-focused compile-time configuration options than the {{pkg|linux}} package. A custom build can be made to choose a different compromise between security and performance than the security-leaning defaults.
However, it should be noted that several packages will not work when using this kernel. For example {{pkg|throttled}}.


If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.
Line 299: Line 441:
===== 64-bit processes =====
===== 64-bit processes =====


{{hc|linux-hardened|
{{hc|linux-hardened 5.4.21.a-1-hardened|
Anonymous mapping randomization test    : 32 quality bits (guessed)
Anonymous mapping randomization test    : 32 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 26 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 40 quality bits (guessed)
Heap randomization test (PIE)            : 40 quality bits (guessed)
Heap randomization test (PIE)            : 40 quality bits (guessed)
Main executable randomization (ET_EXEC)  : No randomization
Main executable randomization (ET_EXEC)  : 32 quality bits (guessed)
Main executable randomization (PIE)      : 32 quality bits (guessed)
Main executable randomization (PIE)      : 32 quality bits (guessed)
Shared library randomization test        : 32 quality bits (guessed)
Shared library randomization test        : 32 quality bits (guessed)
Line 311: Line 453:
Arg/env randomization test (SEGMEXEC)    : 44 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 44 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 44 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 44 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 34 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)
Randomization under memory exhaustion @~0: 32 bits (guessed)
Randomization under memory exhaustion @~0: 32 bits (guessed)
Line 317: Line 459:
}}
}}


{{hc|linux|
{{hc|linux 5.5.5-arch1-1|
Anonymous mapping randomization test    : 28 quality bits (guessed)
Anonymous mapping randomization test    : 28 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 13 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 28 quality bits (guessed)
Heap randomization test (PIE)            : 28 quality bits (guessed)
Heap randomization test (PIE)            : 28 quality bits (guessed)
Main executable randomization (ET_EXEC)  : No randomization
Main executable randomization (ET_EXEC)  : 28 quality bits (guessed)
Main executable randomization (PIE)      : 28 quality bits (guessed)
Main executable randomization (PIE)      : 28 quality bits (guessed)
Shared library randomization test        : 28 quality bits (guessed)
Shared library randomization test        : 28 quality bits (guessed)
VDSO randomization test                  : 20 quality bits (guessed)
VDSO randomization test                  : 20 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 30 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 30 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 22 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 22 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)
Randomization under memory exhaustion @~0: 29 bits (guessed)
Randomization under memory exhaustion @0 : 29 bits (guessed)
}}
{{hc|linux-lts 4.19.101-1-lts|
Anonymous mapping randomization test    : 28 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 28 quality bits (guessed)
Heap randomization test (PIE)            : 28 quality bits (guessed)
Main executable randomization (ET_EXEC)  : 28 quality bits (guessed)
Main executable randomization (PIE)      : 28 quality bits (guessed)
Shared library randomization test        : 28 quality bits (guessed)
VDSO randomization test                  : 19 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 30 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 30 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 30 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 30 quality bits (guessed)
Line 373: Line 533:
}}
}}


=== Restricting access to kernel logs ===
=== Restricting access to kernel pointers in the proc filesystem ===


{{Note|This is enabled by default in {{pkg|linux-hardened}}.}}
Setting {{ic|kernel.kptr_restrict}} to 1 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} from regular users without {{ic|CAP_SYSLOG}}, making it more difficult for kernel exploits to resolve addresses/symbols dynamically. This will not help that much on a pre-compiled Arch Linux kernel, since a determined attacker could just download the kernel package and get the symbols manually from there, but if you are compiling your own kernel, this can help mitigating local root exploits. This will break some {{Pkg|perf}} commands when used by non-root users (but many {{Pkg|perf}} features require root access anyway). See {{Bug|34323}} for more information.


The kernel logs contain useful information for an attacker trying to exploit kernel vulnerabilities, such as sensitive memory addresses. The {{ic|kernel.dmesg_restrict}} flag was to forbid access to the logs without the {{ic|CAP_SYS_ADMIN}} capability (which only processes running as root have by default).
Setting  {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.


{{hc|/etc/sysctl.d/50-dmesg-restrict.conf|2=
{{hc|/etc/sysctl.d/51-kptr-restrict.conf|2=
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 1
}}
}}


=== Restricting access to kernel pointers in the proc filesystem ===
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}


{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}
=== BPF hardening ===


Setting {{ic|kernel.kptr_restrict}} to 1 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} from regular users without {{ic|CAP_SYSLOG}}, making it more difficult for kernel exploits to resolve addresses/symbols dynamically. This will not help that much on a pre-compiled Arch Linux kernel, since a determined attacker could just download the kernel package and get the symbols manually from there, but if you are compiling your own kernel, this can help mitigating local root exploits. This will break some {{Pkg|perf}} commands when used by non-root users (but many {{Pkg|perf}} features require root access anyway). See {{Bug|34323}} for more information.
BPF is a system used to load and execute bytecode within the kernel dynamically during runtime. It is used in a number of Linux kernel subsystems such as networking (e.g. XDP, tc), tracing (e.g. kprobes, uprobes, tracepoints) and security (e.g. seccomp). It is also useful for advanced network security, performance profiling and dynamic tracing.


Setting  {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.
BPF was originally an acronym of [[Wikipedia:Berkeley Packet Filter|Berkeley Packet Filter]] since the original classic BPF was used for packet capture tools for BSD. This eventually evolved into Extended BPF (eBPF), which was shortly afterwards renamed to just BPF (not an acronym). BPF should not be confused with packet filtering tools like iptables or netfilter, although BPF can be used to implement packet filtering tools.


{{hc|/etc/sysctl.d/50-kptr-restrict.conf|2=
BPF code may be either interpreted or compiled using a [[Wikipedia:Just-in-time compilation|Just-In-Time (JIT) compiler]]. The Arch kernel is built with {{ic|CONFIG_BPF_JIT_ALWAYS_ON}} which disables the BPF interpreter and forces all BPF to use JIT compilation. This makes it harder for an attacker to use BPF to escalate attacks that exploit SPECTRE-style vulnerabilities. See [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=290af86629b25ffd1ed6232c4e9107da031705cb the kernel patch which introduced CONFIG_BPF_JIT_ALWAYS_ON] for more details.
kernel.kptr_restrict = 1
}}


=== Keep BPF JIT compiler disabled ===
The kernel includes a hardening feature for JIT-compiled BPF which can mitigate some types of JIT spraying attacks at the cost of performance and the ability to trace and debug many BPF programs. It may be enabled by setting {{ic|net.core.bpf_jit_harden}} to {{ic|1}} (to enable hardening of unprivileged code) or {{ic|2}} (to enable hardening of all code).


The Linux kernel includes the ability to compile BPF/Seccomp rule sets to native code as a performance optimization. The {{ic|net.core.bpf_jit_enable}} flag should be set to {{ic|0}} for a maximum level of security.
See the {{ic|net.core.bpf_*}} settings in the [https://docs.kernel.org/admin-guide/sysctl/net.html kernel documentation] for more details.


BPF/Seccomp compilation can be useful in specific domains, such as dynamic servers (e.g. orchestration platforms like Mesos and Kubernetes). It is not usually useful for desktop users or for static servers. A JIT compiler opens up the possibility for an attacker to perform a heap spraying attack, where they fill the kernel's heap with malicious code. This code can then potentially be executed via another exploit, like an incorrect function pointer dereference. The [[Wikipedia:Spectre (security vulnerability)|Spectre]] attacks, published early 2018, are prominent respective exploits.
{{Tip|
* {{Pkg|linux-hardened}} sets {{ic|1=net.core.bpf_jit_harden=2}} by default rather than {{ic|0}}.
* By default, BPF programs can be run even by unprivileged users. To change that behaviour set {{ic|1=kernel.unprivileged_bpf_disabled=1}}[https://access.redhat.com/security/cve/cve-2021-33624].
}}


=== ptrace scope ===
=== ptrace scope ===


Arch enables the Yama LSM by default, providing a {{ic|kernel.yama.ptrace_scope}} flag. This flag is enabled by default and prevents processes from performing a {{ic|ptrace}} call on other processes outside of their scope without {{ic|CAP_SYS_PTRACE}}. While many debugging tools require this for some of their functionality, it is a significant improvement in security. Without this feature, there is essentially no separation between processes running as the same user without applying extra layers like namespaces. The ability to attach a debugger to an existing process is a demonstration of this weakness.
The {{man|2|ptrace}} syscall provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. {{ic|ptrace}} is commonly used by debugging tools including ''gdb'', ''strace'', ''perf'', ''reptyr'' and other debuggers. However, it also provides a means by which a malicious process can read data from and take control of other processes.


==== Examples of broken functionality ====
Arch enables the [https://docs.kernel.org/admin-guide/LSM/Yama.html Yama LSM] by default, which provides a {{ic|kernel.yama.ptrace_scope}} [[kernel parameter]]. This parameter is set to {{ic|1}} (restricted) by default which prevents tracers from performing a {{ic|ptrace}} call on traces outside of a restricted scope unless the tracer is privileged or has the {{ic|CAP_SYS_PTRACE}} [[Capabilities|capability]]. This is a significant improvement in security compared to the classic permissions. Without this module, there is no separation between processes running as the same user (in the absence of additional security layers such as {{man|7|pid_namespaces}}).


{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}
{{Note|By default, you can still use tools which require {{ic|ptrace}} by running them as privileged processes, e.g. using [[sudo]].}}


* {{ic|gdb -p $PID}}
If you do not need to use debugging tools, consider setting {{ic|kernel.yama.ptrace_scope}} to {{ic|2}} (admin-only) or {{ic|3}} (no {{ic|ptrace}} possible) to harden the system.
* {{ic|strace -p $PID}}
* {{ic|perf trace -p $PID}}
* {{ic|reptyr $PID}}


=== hidepid ===
=== hidepid ===
{{Expansion|1=[https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=0fb5ce62c5920b6e0a8a061f2fe80e0403281e10 Linux 5.8 implemented private instances] and new values for {{ic|1=hidepid=}}.}}
{{Accuracy|Enabling {{ic|hidepid}} globally is not a supported way of operation by [[systemd]], nor does it have any practical improvements security-wise when systemd is running as service manager. [https://github.com/systemd/systemd/issues/29893#issuecomment-1798030108]}}


{{Warning|
{{Warning|
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.
* This causes issues with [[D-Bus]], [[Polkit]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.
}}
}}


The kernel has the ability to hide other users' processes, normally accessible via {{ic|/proc}}, from unprivileged users by mounting the {{ic|proc}} filesystem with the {{ic|1=hidepid=}} and {{ic|1=gid=}} options documented [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/proc.txt#n1919 here].  
The kernel has the ability to hide other users' processes, normally accessible via {{ic|/proc}}, from unprivileged users by mounting the {{ic|proc}} filesystem with the {{ic|1=hidepid=}} and {{ic|1=gid=}} options documented in https://docs.kernel.org/filesystems/proc.html.  


This greatly complicates an intruder's task of gathering information about running processes, whether some daemon runs with elevated privileges, whether other user runs some sensitive program, whether other users run any program at all, makes it impossible to learn whether any user runs a specific program (given the program does not reveal itself by its behaviour), and, as an additional bonus, poorly written programs passing sensitive information via program arguments are now protected against local eavesdroppers.
This greatly complicates an intruder's task of gathering information about running processes, whether some daemon runs with elevated privileges, whether other user runs some sensitive program, whether other users run any program at all, makes it impossible to learn whether any user runs a specific program (given the program does not reveal itself by its behaviour), and, as an additional bonus, poorly written programs passing sensitive information via program arguments are now protected against local eavesdroppers.


The {{ic|proc}} [[Users_and_groups#System_groups|group]], provided by the {{Pkg|filesystem}} package, acts as a whitelist of users authorized to learn other users' process information. If users or services need access to {{ic|/proc/<pid>}} directories beyond their own, [[Users_and_groups#Group_management|add them to the group]].
The {{ic|proc}} [[Users and groups#System groups|group]], provided by the {{Pkg|filesystem}} package, acts as a whitelist of users authorized to learn other users' process information. If users or services need access to {{ic|/proc/<pid>}} directories beyond their own, [[Users and groups#Group management|add them to the group]].


For example, to hide process information from other users except those in the {{ic|proc}} group:
For example, to hide process information from other users except those in the {{ic|proc}} group:
Line 439: Line 601:
SupplementaryGroups=proc
SupplementaryGroups=proc
}}
}}
=== Restricting module loading ===
The default Arch kernel has {{ic|CONFIG_MODULE_SIG_ALL}} enabled, which signs all kernel modules built as part of the {{Pkg|linux}} package. This allows the kernel to only load modules signed with a valid key, i.e. out-of-tree modules compiled locally or provided by packages such as {{Pkg|virtualbox-host-modules-arch}} cannot be loaded.
Kernel module loading can be restricted by setting the {{ic|1=module.sig_enforce=1}} [[kernel parameter]]. More information can be found in the [https://docs.kernel.org/admin-guide/module-signing.html kernel documentation].
=== Disable kexec ===
Kexec allows replacing the current running kernel.
{{hc|/etc/sysctl.d/51-kexec-restrict.conf|2=
kernel.kexec_load_disabled = 1
}}
{{Tip|kexec is disabled by default in {{pkg|linux-hardened}}.}}
=== Kernel lockdown mode ===
Since Linux 5.4 the kernel [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=aefcf2f4b58155d27340ba5f9ddbe9513da8286d has gained] an optional [https://mjg59.dreamwidth.org/55105.html lockdown feature], intended to strengthen the boundary between UID 0 (root) and the kernel. When enabled some applications may cease to work which rely on low-level access to either hardware or the kernel.
To use lockdown, its LSM must be initialized and a lockdown mode must be set.
All [[Kernel#Officially supported kernels|officially supported kernels]] initialize the LSM, but none of them enforce any lockdown mode.
{{Tip|Initialized LSMs can be verified by running {{ic|cat /sys/kernel/security/lsm}}.}}
Lockdown has two modes of operation:
* {{ic|integrity}}: kernel features that allow userland to modify the running kernel are disabled (kexec, bpf).
* {{ic|confidentiality}}: kernel features that allow userland to extract confidential information from the kernel are also disabled.
It is recommended to use {{ic|integrity}}, unless your specific threat model dictates otherwise.
To enable kernel lockdown at runtime, run:
# echo ''mode'' > /sys/kernel/security/lockdown
To enable kernel lockdown on boot, use the [[kernel parameter]] {{ic|1=lockdown=''mode''}}.
{{Note|
* Kernel lockdown cannot be disabled at runtime.
* Kernel lockdown disables [[hibernation]].
}}
See also {{man|7|kernel_lockdown}}.
=== Linux Kernel Runtime Guard (LKRG) ===
[https://www.openwall.com/lkrg/ LKRG] ({{AUR|lkrg-dkms}}) is a kernel module which performs integrity checking of the kernel and detection of exploit attempts.
=== Disable emergency shell ===
{{Accuracy|Masking {{ic|emergency.target}} and {{ic|emergency.service}} will have no effect on those units being added to the initramfs and run in early userspace. Even with them in the initramfs, mkinitcpio's systemd hook locks the root account[https://gitlab.archlinux.org/archlinux/packaging/packages/systemd/-/commit/292cdf8a2f7dd7c6c7d91d2b59617391935c837c][https://gitlab.archlinux.org/archlinux/packaging/packages/systemd/-/commit/8835b2f5dfbe8663f1a2fd08edbd35f90bf08691] for "security reasons" (see {{Bug|70408}}). The solution for the issue in the linked article, if even needed, would be to prevent {{ic|rescue.target}}, {{ic|rescue.service}}, {{ic|emergency.target}} and {{ic|emergency.service}} from being added to the initramfs image.}}
The emergency shell is used to interactively troubleshoot the machine during the boot process. However, it is also a gadget that an attacker can use to access secure resources such as the TPM. See [https://pulsesecurity.co.nz/advisories/tpm-luks-bypass this article] for a practical example. The difficulty of attacks can be increased by disabling the emergency shell, at the tradeoff of removing a tool to troubleshoot early boot failures.
To disable the emergency shell, See [[Systemd#Disable emergency mode on remote machine]].


== Sandboxing applications ==
== Sandboxing applications ==
Line 444: Line 664:
See also [[Wikipedia:Sandbox (computer security)]].
See also [[Wikipedia:Sandbox (computer security)]].


{{Note|The user namespace configuration item {{ic|CONFIG_USER_NS}} is currently enabled in {{Pkg|linux}} (v4.14.5 or later), {{Pkg|linux-lts}} (v4.14.15 or later) and {{Pkg|linux-hardened}}. Lack of it may prevent certain sandboxing features from being made available to applications. Unprivileged usage is disabled by default unless the {{ic|kernel.unprivileged_userns_clone}} [[sysctl]] is set to {{ic|1}}, since it greatly increases the attack surface for local privilege escalation.}}
{{Note|The user namespace configuration item {{ic|CONFIG_USER_NS}} is currently enabled in {{Pkg|linux}}, {{Pkg|linux-lts}}, {{Pkg|linux-zen}} and {{Pkg|linux-hardened}}. Lack of it may prevent certain sandboxing features from being made available to applications.}}
 
{{Warning|Unprivileged user namespace usage ({{ic|CONFIG_USER_NS_UNPRIVILEGED}}) is enabled by default in {{Pkg|linux}}, {{Pkg|linux-lts}} and {{Pkg|linux-zen}}, which greatly increases the attack surface for local privilege escalation (see {{Bug|36969}}).}}
 
To mitigate this, either :
* use the {{Pkg|linux-hardened}} kernel which has the safe default, or
* set the {{ic|kernel.unprivileged_userns_clone}} [[sysctl]] to {{ic|0}}.
 
Note that this can break applications such as [[Zoom Meetings|Zoom]]. You will also need to replace {{pkg|bubblewrap}} with {{pkg|bubblewrap-suid}} if it is installed on your system. See [[Bubblewrap#Installation]].


=== Firejail ===
=== Firejail ===


[[Firejail]] is an easy to use and simple tool for sandboxing applications and servers alike. Firejail is suggested for browsers and internet facing applications, as well as any servers you may be running.
[[Firejail]] is an easy to use tool for sandboxing applications and servers alike. It was originally created for browsers and internet facing applications, but supports a large number of applications by now. To establish a sandboxed environment with a variety of features, it is installed as a suid binary and builds a sandboxed runtime environment for the target application based on black and white lists.


=== bubblewrap ===
=== bubblewrap ===


[[bubblewrap]] is a setuid sandbox application developed from [[Wikipedia:Flatpak|Flatpak]] with an even smaller resource footprint than Firejail. While it lacks certain features such as file path whitelisting, bubblewrap does offer bind mounts as well as the creation of user/IPC/PID/network/cgroup namespaces and can support both simple and [https://github.com/projectatomic/bubblewrap/blob/master/demos/bubblewrap-shell.sh complex sandboxes].
[[bubblewrap]] is a sandbox application developed for unprivileged container tools like [[Flatpak]] with a significantly smaller resource footprint and complexity than Firejail. While it lacks certain features such as file path whitelisting, bubblewrap does offer bind mounts as well as the creation of user/IPC/PID/network/cgroup namespaces and can support both simple and complex sandboxes.
 
[[Bubblejail]] sandbox is based on [[bubblewrap]] and provides a resource oriented permission model with a graphical interface to tweak permissions.


=== chroots ===
=== chroots ===


Manual [[chroot]] jails can also be constructed.
Manual [[chroot]] jails can also be constructed to build sandboxed process environments. It is much more limited than other sandboxing technologies; the extent of its sandboxing is file path isolation.


=== Linux containers ===
=== Linux containers ===


[[Linux Containers]] are another good option when you need more separation than the other options (short of KVM and VirtualBox) provide. LXC's run on top of the existing kernel in a pseudo-chroot with their own virtual hardware.
[[Linux Containers]] are another good option when you need more separation than the other options (short of [[#Full virtualization options|full system virtualization]]) provide. LXC is run on top of the existing kernel in a pseudo-chroot with their own virtual hardware.


=== Other virtualization options ===
=== Full virtualization options ===


Using full virtualization options such as [[VirtualBox]], [[KVM]], [[Xen]] or [https://www.qubes-os.org/ Qubes OS] (based on Xen) can also improve isolation and security in the event you plan on running risky applications or browsing dangerous websites.
Using full virtualization options such as [[VirtualBox]], [[KVM]], [[Xen]] or [https://www.qubes-os.org/ Qubes OS] (based on Xen) can also improve isolation and security in the event you plan on running risky applications or browsing dangerous websites.
Line 470: Line 700:
=== Firewalls ===
=== Firewalls ===


While the stock Arch kernel is capable of using [[Wikipedia:Netfilter|Netfilter]]'s [[iptables]] and [[nftables]], they are not enabled by default. It is highly recommended to set up some form of firewall to protect the services running on the system. Many resources (including ArchWiki) do not state explicitly which services are worth protecting, so enabling a firewall is a good precaution.
While the stock Arch kernel is capable of using [[Wikipedia:Netfilter|Netfilter]]'s [[iptables]] and [[nftables]], the services are not [[enable]]d by default. It is highly recommended to set up some form of firewall to protect the services running on the system. Many resources (including ArchWiki) do not state explicitly which services are worth protecting, so enabling a firewall is a good precaution.


* See [[iptables]] and [[nftables]] for general info.
* See [[iptables]] and [[nftables]] for general information.
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.
* See [[:Category:Firewalls]] for other ways of setting up netfilter.
* See [[:Category:Firewalls]] for other ways of setting up netfilter.
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.
* {{Pkg|opensnitch}} is a configurable inbound and outbound firewall with support for configurable rules by application, port, host, etc.
==== Open ports ====
{{Style|"Open ports" is not a good title since it disregards interfaces and addresses that the application may be bound to. From the firewalls' point of view, ports may be "open" even if no application listens on them at the moment.}}
Some services listen for inbound traffic on open network ports. It is important to only bind these services to the addresses and interfaces that are strictly necessary. It may be possible for a remote attacker to [https://samy.pl/slipstream/ exploit flawed network protocols to access exposed services]. This can even happen with [https://nvd.nist.gov/vuln/detail/CVE-2019-13450 processes bound to localhost].
In general, if a service only needs to be accessible to the local system, bind to a Unix domain socket ({{man|7|unix}}) or a loopback address such as {{ic|localhost}} instead of a non-loopback address like {{ic|0.0.0.0/0}}.
If a service needs to be accessible to other systems via the network, control the access with strict [[firewall]] rules and configure authentication, authorization and encryption whenever possible.
You can list all current open ports with {{ic|ss -l}}. To show all '''l'''istening '''p'''rocesses and their '''n'''umeric '''t'''cp and '''u'''dp port numbers:
# ss -lpntu
See {{man|8|ss}} for more options.


=== Kernel parameters ===
=== Kernel parameters ===
Line 483: Line 730:
=== SSH ===
=== SSH ===


To mitigate [[Wikipedia:Brute-force attack|brute-force attacks]] it is recommended to enforce key-based authentication. For OpenSSH, see [[OpenSSH#Force public key authentication]]. Alternatively [[Fail2ban]] or [[Sshguard]] offer lesser forms of protection by monitoring logs and writing [[Iptables|iptables rules]] but open up the potential for a denial of service, since an attacker can spoof packets as if they came from the administrator after identifying their address.
To mitigate [[Wikipedia:Brute-force attack|brute-force attacks]] it is recommended to enforce key-based authentication. For OpenSSH, see [[OpenSSH#Force public key authentication]]. Alternatively [[Fail2ban]] or [[Sshguard]] offer lesser forms of protection by monitoring logs and writing [[firewall]] rules but open up the potential for a denial of service, since an attacker can [[wikipedia:Spoofing_attack#Spoofing_and_TCP/IP|spoof]] packets as if they came from the administrator after identifying their address. Spoofing IP has lines of defense, such as by [[sysctl#Reverse path filtering|reverse path filtering]] and [[sysctl#Disable ICMP redirects|disabling ICMP redirects]].


You may want to harden authentication even more by using two-factor authentication. [[Google Authenticator]] provides a two-step authentication procedure using one-time passcodes (OTP).
You may want to harden authentication even more by using two-factor authentication. [[Google Authenticator]] provides a two-step authentication procedure using one-time passcodes (OTP).


Denying root login is also a good practice, both for tracing intrusions and adding an additional layer of security before root access. For OpenSSH, see [[OpenSSH#Deny]].
Denying root login is also a good practice, both for tracing intrusions and adding an additional layer of security before root access. For OpenSSH, see [[OpenSSH#Deny]].
Mozilla publishes an [https://infosec.mozilla.org/guidelines/openssh.html OpenSSH configuration guide] which configures more verbose audit logging and restricts ciphers.


=== DNS ===
=== DNS ===


{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}
The default domain name resolution (DNS) configuration is highly compatible but has security weaknesses. See [[Domain name resolution#Privacy and security|DNS privacy and security]] for more information.
 
[[DNS]] queries are, by default on most systems, sent and received unencrypted and without checking for authentication of receipt from qualified servers. This could then allow [[Wikipedia:Man-in-the-middle_attack|man-in-the-middle attacks]], whereby an attacker intercepts your DNS queries and modifies the responses to deliver you an IP address leading to a [[Wikipedia:Phishing|phishing]] page to collect your valuable information. Neither you nor the browser/other software would be aware since the DNS protocol takes the legitimacy of query results for granted.
 
[[DNSSEC]] is a set of standards in place that requires DNS servers to provide clients with origin authentication of DNS data, authenticated denial of existence, and data integrity. It, however, is not yet widely used. With DNSSEC enabled, an attacker can not make modifications to your DNS queries and the returning results, but would still be able to read them.
 
[[DNSCrypt]], as well as later alternative protocol developments ''DNS over TLS'' and ''DNS over HTTPS'', use cryptography to secure communications with DNS servers. Usually only one protocol is employed on a system level. See [[Domain name resolution#DNS servers]] for supporting software.
 
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.


=== Proxies ===
=== Proxies ===
Line 507: Line 748:
For example the DNS resolver is implemented in {{Pkg|glibc}}, that is linked with the application (that may be running as root), so a bug in the DNS resolver might lead to a remote code execution. This can be prevented by installing a DNS caching server, such as [[dnsmasq]], which acts as a proxy. [https://googleonlinesecurity.blogspot.it/2016/02/cve-2015-7547-glibc-getaddrinfo-stack.html]
For example the DNS resolver is implemented in {{Pkg|glibc}}, that is linked with the application (that may be running as root), so a bug in the DNS resolver might lead to a remote code execution. This can be prevented by installing a DNS caching server, such as [[dnsmasq]], which acts as a proxy. [https://googleonlinesecurity.blogspot.it/2016/02/cve-2015-7547-glibc-getaddrinfo-stack.html]


=== Managing SSL certificates ===
=== Managing TLS certificates ===


{{Merge|Transport Layer Security|There's a dedicated article.}}
See [[TLS#Trust management]].


See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported.
== Physical security ==


The default internet SSL certificate trustchains are provided by the {{Pkg|ca-certificates}} package and its dependencies. Note that Arch relies on trust-sources (e.g. {{Pkg|ca-certificates-mozilla}}) providing the certificates to be trusted per default by the system.  
Physical access to a computer is root access given enough time and resources. However, a high ''practical'' level of security can be obtained by putting up enough barriers.


There may be occasions when you want to deviate from the default. For example, you may read some [https://www.theregister.co.uk/2016/05/27/blue_coat_ca_certs/ news] and want to distrust a certificate rather than wait until the trust-source providers do. The Arch infrastructure makes such easy:
An attacker can gain full control of your computer on the next boot by simply attaching a malicious IEEE 1394 (FireWire), Thunderbolt or PCI Express device as they are given full memory access by default.[https://web.archive.org/web/20210312083421/http://breaknenter.org/2014/09/inception-metasploit-integration/] For Thunderbolt, you can restrict the direct memory access completely or to known devices, see [[Thunderbolt#User device authorization]]. For Firewire and PCI Express, there is little you can do from preventing this, or modification of the hardware itself - such as flashing malicious firmware onto a drive. However, the vast majority of attackers will not be this knowledgeable and determined.


# Obtain the respective certificate in .crt format (Example: [https://crt.sh/?id=19538258 view], [https://crt.sh/?d=19538258 download]; in case of an existing trusted root certificate authority, you may also find it extracted in the system path),  
[[#Data-at-rest encryption]] will prevent access to your data if the computer is stolen, but malicious firmware can be installed to obtain this data upon your next log in by a resourceful attacker.
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and
# Run ''update-ca-trust'' as root.  


To check the blacklisting works as intended, you may re-open your preferred browser and do so via its GUI, which should show it as '''untrusted''' now.
=== Locking down BIOS ===


== Authenticating packages ==
Adding a password to the BIOS prevents someone from booting into removable media, which is basically the same as having root access to your computer. You should make sure your drive is first in the boot order and disable the other drives from being bootable if you can.


[https://www.cs.arizona.edu/stork/packagemanagersecurity/attacks-on-package-managers.html#overview Attacks on package managers] are possible without proper use of package signing, and can affect even package managers with [https://www.cs.arizona.edu/stork/packagemanagersecurity/faq.html proper signature systems]. Arch uses package signing by default and relies on a web of trust from 5 trusted master keys. See [[Pacman-key]] for details.
=== Boot loaders ===


== Follow vulnerability alerts ==
It is highly important to protect your [[boot loader]]. An unprotected boot loader can bypass any login restrictions, e.g. by setting the {{ic|1=init=/bin/sh}} [[kernel parameter]] to boot directly to a shell.


Subscribe to the Common Vulnerabilities and Exposure (CVE) Security Alert updates, made available by National Vulnerability Database, and found on the [https://nvd.nist.gov/download.cfm NVD Download webpage]. The [https://security.archlinux.org/ Arch Linux Security Tracker] serves as a particularly useful resource in that it combines Arch Linux Security Advisory (ASA), Arch Linux Vulnerability Group (AVG) and CVE data sets in tabular format. See also [[Arch Security Team]].
==== Syslinux ====


{{Warning|Do not be tempted to perform [[partial upgrades]], as they are not supported by Arch Linux and may cause instability: the whole system should be upgraded when upgrading a component. Also note that infrequent system updates can complicate the update process.}}
[[Syslinux]] supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.


== Physical security ==
==== GRUB ====


Physical access to a computer is root access given enough time and resources. However, a high ''practical'' level of security can be obtained by putting up enough barriers.
[[GRUB]] supports bootloader passwords as well. See [[GRUB/Tips and tricks#Password protection of GRUB menu]] for details. It also has support for [[GRUB#Encrypted /boot|encrypted /boot]], which only leaves some parts of the bootloader code unencrypted. GRUB's configuration, [[kernel]] and [[initramfs]] are encrypted.
 
An attacker can gain full control of your computer on the next boot by simply attaching a malicious IEEE 1394 (FireWire), Thunderbolt or PCI Express device as they are given full memory access.[https://www.breaknenter.org/projects/inception/] There is little you can do from preventing this, or modification of the hardware itself - such as flashing malicious firmware onto a drive. However, the vast majority of attackers will not be this knowledgeable and determined.


[[#Disk encryption]] will prevent access to your data if the computer is stolen, but malicious firmware can be installed to obtain this data upon your next log in by a resourceful attacker.
==== systemd-boot ====


=== Locking down BIOS ===
[[systemd-boot]] disables editing of kernel parameters when [[#Secure Boot]] is enabled. Alternatively, see [[systemd-boot#Kernel parameters editor with password protection]] for a more traditional password-based option.


Adding a password to the BIOS prevents someone from booting into removable media, which is basically the same as having root access to your computer. You should make sure your drive is first in the boot order and disable the other drives from being bootable if you can.
=== Secure Boot ===


=== Bootloaders ===
[[Secure Boot]] is a feature of [[UEFI]] that allows authentication of the files your computer boots. This helps preventing some [[Wikipedia:Evil maid attack|evil maid attacks]] such as replacing files inside the boot partition. Normally computers come with keys that are enrolled by vendors (OEM). However these can be removed and allow the computer to enter ''Setup Mode'' which allows the user to enroll and manage their own keys.


It is highly important to protect your bootloader. There is a magic kernel parameter called {{ic|1=init=/bin/sh}}. This makes any user/login restrictions totally useless.
The secure boot page guides you through how to set secure boot up by [[Unified Extensible Firmware Interface/Secure Boot#Using your own keys|using your own keys]].


==== Syslinux ====
=== Trusted Platform Module (TPM) ===


Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.
[[Trusted Platform Module|TPMs]] are hardware microprocessors which have cryptographic keys embedded. This forms the fundamental root of trust of most modern computers and allows end-to-end verification of the boot chain. They can be used as internal smartcards, attest the firmware running on the computer and allow users to insert secrets into a tamper-proof and brute-force resistant store.


==== GRUB ====
=== Boot partition on removable flash drive ===
 
[[GRUB]] supports bootloader passwords as well. See [[GRUB/Tips and tricks#Password protection of GRUB menu]] for details. It also has support for [[GRUB#Encrypted /boot|encrypted /boot]], which only leaves some parts of the bootloader code unencrypted. GRUB's configuration, [[kernel]] and [[initramfs]] are encrypted.


=== Boot partition on removable flash drive ===
One popular idea is to place the boot partition on a flash drive in order to render the system unbootable without it. Proponents of this idea often use [[#Data-at-rest encryption|full-disk encryption]] alongside, and some also use [[Dm-crypt/Specialties#Encrypted system using a detached LUKS header|detached encryption headers]] placed on the boot partition.


One popular idea is to place the boot partition on a flash drive in order to render the system unbootable without it. Proponents of this idea often use [[#Disk encryption|full disk encryption]] alongside, and some also use [[Dm-crypt/Specialties#Encrypted_system_using_a_detached_LUKS_header|detached encryption headers]] placed on the boot partition.  
This method can also be merged with [[Dm-crypt/Specialties#Encrypted /boot and a detached LUKS header on USB|encrypting /boot]].


=== Automatic logout ===
=== Automatic logout ===
Line 583: Line 818:
=== Protect against rogue USB devices ===
=== Protect against rogue USB devices ===


Install [[USBGuard]], which is a software framework that  helps to protect your computer against rogue USB devices (a.k.a. [https://srlabs.de/badusb BadUSB], [https://github.com/samyk/poisontap PoisonTap] or [https://lanturtle.com/ LanTurtle]) by implementing basic whitelisting and blacklisting capabilities based on device attributes.
Install [[USBGuard]], which is a software framework that  helps to protect your computer against rogue USB devices (a.k.a. [https://opensource.srlabs.de/projects/badusb BadUSB], [https://github.com/samyk/poisontap PoisonTap] or [https://lanturtle.com/ LanTurtle]) by implementing basic whitelisting and blacklisting capabilities based on device attributes.
 
=== Volatile data collection ===


== Rebuilding packages ==
A computer that is powered on may be vulnerable to [https://web.archive.org/web/20210420075636/https://fedvte.usalearning.gov/courses/CSI/course/videos/pdf/CSI_D01_S05_T01_STEP.pdf volatile data collection]. It is a best practice to turn a computer completely off at times it is not necessary for it to be on, or if the computer's physical security is temporarily compromised (e.g. when passing through a security checkpoint).
 
== Packages ==
 
=== Authentication ===
 
[https://www2.cs.arizona.edu/stork/packagemanagersecurity/attacks-on-package-managers.html#overview Attacks on package managers] are possible without proper use of package signing, and can affect even package managers with [https://www2.cs.arizona.edu/stork/packagemanagersecurity/faq.html proper signature systems]. Arch uses package signing by default and relies on a web of trust from 5 trusted master keys. See [[Pacman-key]] for details.
 
=== Upgrades ===
 
It is important to regularly [[System maintenance#Upgrading the system|upgrade the system]].
 
=== Follow vulnerability alerts ===
 
Subscribe to the Common Vulnerabilities and Exposure (CVE) Security Alert updates, made available by National Vulnerability Database, and found on the [https://nvd.nist.gov/download.cfm NVD Download webpage]. The [https://security.archlinux.org/ Arch Linux Security Tracker] serves as a particularly useful resource in that it combines Arch Linux Security Advisory (ASA), Arch Linux Vulnerability Group (AVG) and CVE data sets in tabular format. The tool {{Pkg|arch-audit}} can be used to check for vulnerabilities affecting the running system. A graphical system tray, {{Pkg|arch-audit-gtk}}, can also be used. See also [[Arch Security Team]].
 
You should also consider subscribing to the release notifications for software you use, especially if you install software through means other than the main repositories or AUR. Some software have mailing lists you can subscribe to for security notifications. Source code hosting sites often offer RSS feeds for new releases.
 
=== Rebuilding packages ===


Packages can be rebuilt and stripped of undesired functions and features as a means to reduce attack surface. For example, {{Pkg|bzip2}} can be rebuilt without {{ic|bzip2recover}} in an attempt to circumvent [https://security.archlinux.org/CVE-2016-3189 CVE-2016-3189]. Custom hardening flags can also be applied either manually or via a wrapper.
Packages can be rebuilt and stripped of undesired functions and features as a means to reduce attack surface. For example, {{Pkg|bzip2}} can be rebuilt without {{ic|bzip2recover}} in an attempt to circumvent [https://security.archlinux.org/CVE-2016-3189 CVE-2016-3189]. Custom hardening flags can also be applied either manually or via a wrapper.
{{Merge|Arch package guidelines/Security|Security related build flags have their own article.}}
{{Accuracy|Copy-pasted from a 3 years old blog post. The compiler flags are specific to [[GCC]], some are hardly security related (e.g. {{ic|-O2}}, {{ic|-g}}, {{ic|-Wall}}).}}
{| class="wikitable"
! Flag !! Purpose
|-
| -D_FORTIFY_SOURCE=2 || Run-time buffer overflow detection
|-
| -D_GLIBCXX_ASSERTIONS || Run-time bounds checking for C++ strings and containers
|-
| -fasynchronous-unwind-tables || Increased reliability of backtraces
|-
| -fexceptions || Enable table-based thread cancellation
|-
| -fpie -Wl,-pie || Full ASLR for executables
|-
| -fpic -shared || No text relocations for shared libraries
|-
| -fplugin=annobin || Generate data for hardening quality control
|-
| -fstack-clash-protection || Increased reliability of stack overflow detection
|-
| -fstack-protector or -fstack-protector-all || Stack smashing protector
|-
| -fstack-protector-strong || Likewise
|-
| -g || Generate debugging information
|-
| -grecord-gcc-switches || Store compiler flags in debugging information
|-
| -mcet -fcf-protection || Control flow integrity protection
|-
| -O2 || Recommended optimizations
|-
| -pipe || Avoid temporary files, speeding up builds
|-
| -Wall || Recommended compiler warnings
|-
| -Werror=format-security || Reject potentially unsafe format string arguments
|-
| -Werror=implicit-function-declaration || Reject missing function prototypes
|-
| -Wl,-z,defs || Detect and reject underlinking
|-
| -Wl,-z,now || Disable lazy binding
|-
| -Wl,-z,relro || Read-only segments after relocation
|}
* [https://developers.redhat.com/blog/2018/03/21/compiler-and-linker-flags-gcc/ Flags and info source]


== See also ==
== See also ==
Line 593: Line 900:
* [https://security.archlinux.org/ Arch Linux Security Tracker]
* [https://security.archlinux.org/ Arch Linux Security Tracker]
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]
* [https://web.archive.org/web/20210712001756/https://developer.ibm.com/technologies/linux/articles/l-harden-desktop/ Hardening the Linux desktop]
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]
* [https://web.archive.org/web/20190701140035/https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]
* [https://www.privacytools.io/ privacytools.io Privacy Resources]
* [https://www.privacyguides.org/ privacyguides.org Privacy Resources]
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]
* [https://www.debian.org/doc/manuals/securing-debian-manual/index.en.html Securing Debian Manual]
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]

Latest revision as of 10:01, 6 April 2024

This article contains recommendations and best practices for hardening an Arch Linux system.

Concepts

  • It is possible to tighten security to the point where the system is unusable. Security and convenience must be balanced. The trick is to create a secure and useful system.
  • The biggest threat is, and will always be, the user.
  • The principle of least privilege: Each part of a system should only be able to access what is strictly required, and nothing more.
  • Defense in depth: Security works better in independent layers. When one layer is breached, another should stop the attack.
  • Be a little paranoid. And be suspicious. If anything sounds too good to be true, it probably is!
  • You can never make a system 100% secure unless you unplug the machine from all networks, turn it off, lock it in a safe, smother it in concrete and never use it.
  • Prepare for failure. Create a plan ahead of time to follow when your security is broken.

Passwords

Passwords are key to a secure system. They secure your user accounts, encrypted filesystems, and SSH/GPG keys. They are the main way a computer chooses to trust the person using it, so a big part of security is just about picking secure passwords and protecting them.

Choosing secure passwords

Passwords must be complex enough to not be easily guessed from e.g. personal information, or cracked using methods like social engineering or brute-force attacks. The tenets of strong passwords are based on length and randomness. In cryptography the quality of a password is often referred to as its entropy.

Insecure passwords include those containing or those using as a base before substitution/variation:

  • Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)
  • Simple character substitutions on words (e.g., k1araj0hns0n), as modern dictionary attacks can easily work with these
  • Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., DG091101%)
  • Common phrases or short strings of common dictionary words (e.g. photocopyhauntbranchexpose) including with character substitution (e.g. Ph0toc0pyh4uN7br@nch3xp*se) (See Diceware below for when a combination of dictionary words can be secure)
  • Any of the most common passwords


The best choice for a password is something long (the longer, the better) and generated from a random source. It is important to use a long password. Weak hash algorithms allow an 8-character password hash to be compromised in just a few hours.

Tools like pwgen or apgAUR can generate random passwords. However, these passwords can be difficult to memorize. One memorization technique (for ones often typed) is to generate a long password and memorize a minimally secure number of characters, temporarily writing down the full generated string. Over time, increase the number of characters typed - until the password is ingrained in muscle memory and need not be remembered. This technique is more difficult, but can provide confidence that a password will not turn up in wordlists or "intelligent" brute force attacks that combine words and substitute characters.

Apart from password management, keepassxc offers password/passphrase generation. It is possible to customize the generation in a GUI. Dictionary based passphrases are also supported.

One technique for memorizing a password is to use a mnemonic phrase, where each word in the phrase reminds you of the next character in the password. Take for instance “the girl is walking down the rainy street” could be translated to t6!WdtR5 or, less simply, t&6!RrlW@dtR,57. This approach could make it easier to remember a password, but note that the various letters have very different probabilities of being found at the start of words (Wikipedia:Letter frequency).

Another effective technique can be to write randomly generated passwords down and store them in a safe place, such as in a wallet, purse, or document safe. Most people do a generally good job of protecting their physical valuables from attack, and it is easier for most people to understand physical security best practices compared to digital security practices.

It is also very effective to combine the mnemonic and random technique by saving long randomly generated passwords with a password manager, which will be in turn accessed with a memorable "master password"/primary password that must be used only for that purpose. The master password must be memorized and never saved. This requires the password manager to be installed on a system to easily access the password (which could be seen as an inconvenience or a security feature, depending on the situation). Some password managers also have smartphone apps which can be used to display passwords for manual entry on systems without that password manager installed (if that is a common use case, you could still use easily typeable but secure passwords for each service instead of completely random ones, see below). Note that a password manager introduces a single point of failure if you ever forget the master password. Some password managers compute the contained passwords based on the master password and the service name where you want to log in instead of encrypting them, making it possible to use it on a new system without syncing any data.

It can be effective to use a memorable long series of unrelated words as a password. The theory is that if a sufficiently long phrase is used, the gained entropy from the password's length can counter the lost entropy from the use of dictionary words. This xkcd comic demonstrates the entropy tradeoff of this method, taking into account the limited set of possible words for each word in the passphrase. If the set of words you choose from is large (multiple thousand words) and you choose 5-7 or even more random words from it, this method provides great entropy, even assuming the attacker knows the set of possible words chosen from and the number of words chosen. The number of possible passphrases after settling on a set of words and number of words is: (number of words in the set of words to select from) to the power of (the number of words chosen for the passphrase). See e.g. Diceware for more.

See The passphrase FAQ or Wikipedia:Password strength for some additional background.

Maintaining passwords

Once you pick a strong password, be sure to keep it safe. Watch out for keyloggers (software and hardware), screen loggers, social engineering, shoulder surfing, and avoid reusing passwords so insecure servers cannot leak more information than necessary. Password managers can help manage large numbers of complex passwords: if you are copy-pasting the stored passwords from the manager to the applications that need them, make sure to clear the copy buffer every time, and ensure they are not saved in any kind of log (e.g. do not paste them in plain terminal commands, which would store them in files like .bash_history). Note that password managers that are implemented as browser extensions may be vulnerable to side channel attacks. These can be mitigated by using password managers that run as separate applications.

As a rule, do not pick insecure passwords just because secure ones are harder to remember. Passwords are a balancing act. It is better to have an encrypted database of secure passwords, guarded behind a key and one strong master password, than it is to have many similar weak passwords. Writing passwords down is perhaps equally effective [1], avoiding potential vulnerabilities in software solutions while requiring physical security.

Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.

If you use the same passphrase for disk encryption as you use for your login password (useful e.g. to auto-mount the encrypted partition or folder on login), make sure that /etc/shadow ends up on an encrypted partition or/and uses a strong key derivation function (i.e. yescrypt/argon2 or sha512 with PBKDF2, but not md5 or low iterations in PBKDF2) for the stored password hash (see SHA password hashes for more information).

Tip: Arch Linux switched the default hashing algorithm to yescrypt. If you have not customized the default, executing a password change with passwd is necessary (and sufficient) to apply the new default.

If you are backing up your password database, make sure that each copy is not stored behind any other passphrase which in turn is stored in it, e.g. an encrypted drive or an authenticated remote storage service, or you will not be able to access it in case of need; a useful trick is to protect the drives or accounts where the database is backed up using a simple cryptographic hash of the master password. Maintain a list of all the backup locations: if one day you fear that the master passphrase has been compromised you will have to change it immediately on all the database backups and the locations protected with keys derived from the master password.

Version-controlling the database in a secure way can be very complicated: if you choose to do it, you must have a way to update the master password of all the database versions. It may not always be immediately clear when the master password is leaked: to reduce the risk of somebody else discovering your password before you realize that it leaked, you may choose to change it on a periodical basis. If you fear that you have lost control over a copy of the database, you will need to change all the passwords contained in it within the time that it may take to brute-force the master password, according to its entropy.

Password hashes

A hash is a one-way function, i.e. it is designed to make it impossible to deduct the input without computing the hash function with it (example: MD5, SHA).

A password-hash function is designed to make deducting a user-input (password) impossible without computing the hash function with it (example: bcrypt). A key derivation function (KDF; examples: yescrypt, scrypt, PBKDF2) is a cryptographic algorithm designed to derive secret keys (e.g. an AES key, a password hash) from an input (a master key, a password). Hence, a KDF can serve multiple applications, including those of a password-hash function.

By default, Arch stores the hashed user passwords in the root-only-readable /etc/shadow file, separated from the other user parameters stored in the world-readable /etc/passwd file, see Users and groups#User database. See also #Restricting root.

Passwords are set with the passwd command, which stretches them with the system's crypt function and then saves them in /etc/shadow. The passwords are also salted in order to defend them against rainbow table attacks. See also How are passwords stored in Linux (Understanding hashing with shadow utils).

Since password hashes follow a defined format, the method and parameter can be configured for subsequent new invocations of the passwd command. Hence, the individual hashes stored in the /etc/shadow file can be a heterogeneous mix of the hash functions supported by the system.

See crypt(5) for more information on the format, hashing methods and parameters.

The /etc/login.defs file configures the default password hashing method ENCRYPT_METHOD YESCRYPT and its parameter YESCRYPT_COST_FACTOR.

For example, an increment of the default YESCRYPT_COST_FACTOR parameter will lead to a logarithmic increase of the compute time required to deduce the hash from a password. This applies, likewise, to a third-party trying to obtain the password secret, and the system to authenticate a user log-in.

In contrast, the compute time for the SHA-512 hash function is configured by a parameter with a linear influence. See SHA password hashes for information on the previous Arch default. Note the yescrypt algorithm internally uses SHA-256, HMAC and PBKDF2 to compute its password-hash. The main reason is to combine positive attributes of these widely used and tested functions for an enhanced resistance to attacks. For example, the usability of SHA for various purposes has resulted in hardware support for the function, i.e. the performance to compute a pure SHA hash has accelerated considerably, making its application as a password-hash function more and more derelict.

Enforcing strong passwords with pam_pwquality

pam_pwquality provides protection against Dictionary attacks and helps configure a password policy that can be enforced throughout the system. It is based on pam_cracklib, so it is backwards compatible with its options.

Install the libpwquality package.

Warning: The root account is not affected by this policy by default.
Note:
  • You can use the root account to set a password for a user that bypasses the desired/configured policy. This is useful when setting temporary passwords.
  • Current security guidelines around passwords, e.g. from NIST, but also from others, do not recommend enforcing special characters, since they often only lead to predictable alterations.

If for example you want to enforce this policy:

  • prompt 2 times for password in case of an error (retry option)
  • 10 characters minimum length (minlen option)
  • at least 6 characters should be different from old password when entering a new one (difok option)
  • at least 1 digit (dcredit option)
  • at least 1 uppercase (ucredit option)
  • at least 1 lowercase (lcredit option)
  • at least 1 other character (ocredit option)
  • cannot contain the words "myservice" and "mydomain"
  • enforce the policy for root

Edit the /etc/pam.d/passwd file to read as:

#%PAM-1.0
password required pam_pwquality.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1 [badwords=myservice mydomain] enforce_for_root
password required pam_unix.so use_authtok sha512 shadow

The password required pam_unix.so use_authtok instructs the pam_unix module to not prompt for a password but rather to use the one provided by pam_pwquality.

You can refer to the pam_pwquality(8) and pam_unix(8) man pages for more information.

CPU

Microcode

See microcode for information on how to install important security updates for your CPU's microcode.

Hardware vulnerabilities

Some CPUs contain hardware vulnerabilities. See the kernel documentation on hardware vulnerabilities for a list of these vulnerabilities, as well as mitigation selection guides to help customize the kernel to mitigate these vulnerabilities for specific usage scenarios.

To check if you are affected by a known vulnerability, run the following:

$ grep -r . /sys/devices/system/cpu/vulnerabilities/

In most cases, updating the kernel and microcode will mitigate vulnerabilities.

Simultaneous multithreading (hyper-threading)

Note: This is something mostly hypervisors benefit from. Enabling it on an ordinary system has very little to no security benefits.

Simultaneous multithreading (SMT), also called hyper-threading on Intel CPUs, is a hardware feature that may be a source of L1 Terminal Fault and Microarchitectural Data Sampling vulnerabilities. The Linux kernel and microcode updates contain mitigations for known vulnerabilities, but disabling SMT may still be required on certain CPUs if untrusted virtualization guests are present.

SMT can often be disabled in your system's firmware. Consult your motherboard or system documentation for more information. You can also disable SMT in the kernel by adding the following kernel parameter:

mitigations=auto,nosmt

Memory

Hardened malloc

hardened_malloc (hardened_mallocAUR, hardened-malloc-gitAUR) is a hardened replacement for glibc's malloc(). The project was originally developed for integration into Android's Bionic and musl by Daniel Micay, of GrapheneOS, but he has also built in support for standard Linux distributions on the x86_64 architecture.

While hardened_malloc is not yet integrated into glibc (assistance and pull requests welcome) it can be used easily with LD_PRELOAD. In testing so far, it only causes issues with a handful of applications if enabled globally in /etc/ld.so.preload. Since hardened_malloc has a performance cost, you may want to decide which implementation to use on a case-by-case basis based on attack surface and performance needs.

The factual accuracy of this article or section is disputed.

Reason: Firefox may require a rebuild for use with hardened-malloc to be effective (Discuss in Talk:Security#Use of hardened-malloc with Firefox)

To try it out in a standalone manner, use the hardened-malloc-preload wrapper script, or manually start an application with the proper preload value:

LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox

Proper usage with Firejail can be found on its wiki page, and some configurable build options for hardened_malloc can be found on the github repo.

Storage

Data-at-rest encryption

Data-at-rest encryption, preferably full-disk encryption with a strong passphrase, is the only way to guard data against physical recovery. This provides data confidentiality when the computer is turned off or the disks in question are unmounted.

Once the computer is powered on and the drive is mounted, however, its data becomes just as vulnerable as an unencrypted drive. It is therefore best practice to unmount data partitions as soon as they are no longer needed.

You may also encrypt a drive with the key stored in a TPM, although it has had vulnerabilites in the past and the key can be extracted by a bus sniffing attack.

Certain programs, like dm-crypt, allow the user to encrypt a loop file as a virtual volume. This is a reasonable alternative to full-disk encryption when only certain parts of the system need to be secure.

While the block-device or filesystem-based encryption types compared in the data-at-rest encryption article are useful at protecting data on physical media, most can not be used to protect data on a remote system that you can not control (such as cloud storage). In some cases, individual file encryption will be useful.

These are some methods to encrypt files:

  • Some archiving and compressing tools also provide basic encryption. Some examples are p7zip (-p flag), zip (-e flag). The encryption should only be relied on particular care, because the tools may use custom algorithms for cross-platform compatibility.[2]
  • GnuPG can be used to encrypt files.
  • age is a simple and easy to use file encryption tool. It also supports multiple recipients and encryption using SSH keys, which is useful for secure file sharing.

File systems

The kernel now prevents security issues related to hardlinks and symlinks if the fs.protected_hardlinks and fs.protected_symlinks sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.

File systems containing world-writable directories can still be kept separate as a coarse way of limiting the damage from disk space exhaustion. However, filling /var or /tmp is enough to take down services. More flexible mechanisms for dealing with this concern exist (like quotas), and some file systems include related features themselves (Btrfs has quotas on subvolumes).

Mount options

Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).

Relevant mount options are:

  • nodev: Do not interpret character or block special devices on the file system.
  • nosuid: Do not allow set-user-identifier or set-group-identifier bits to take effect.
  • noexec: Do not allow direct execution of any binaries on the mounted file system.
    • Setting noexec on /home disallows executable scripts and breaks Wine, Steam, PyCharm, .NET, etc.
      • Wine does not need the exec flag for opening Windows binaries. It is only needed when Wine itself is installed in /home.
      • To keep Steam working you can mount /home/user/.local/share/Steam as exec in fstab by adding the following:
        /home/user/.local/share/Steam  /home/user/.local/share/Steam  none defaults,bind,user,exec,nofail  0  0
    • Some packages (building nvidia-dkms for example) may require exec on /var.

File systems used for data should always be mounted with nodev, nosuid and noexec.

Potential file system mounts to consider:

  • /var
  • /home
  • /dev/shm
  • /tmp
  • /boot
Tip: When using GPT partition automounting, the ESP and XBOOTLDR partitions are always hardened with noexec,nosuid,nodev.

File access permissions

The factual accuracy of this article or section is disputed.

Reason: chmod go-r does not "take away all permissions", it only removes the read permission. (Discuss in Talk:Security)

The default file permissions allow read access to almost everything and changing the permissions can hide valuable information from an attacker who gains access to a non-root account such as the http or nobody users. You can use chmod to take away all permissions from the group and others:

# chmod go-r path_to_hide
Warning: Do not apply this broadly. Try this for one config at a time, ensuring that it is worth hiding, and that it will not break program functionality. You may need to remove the g from the command (or re-add the permission with chmod g+r path if already ran) if the group is relied on.

Some paths to consider are:

The default umask 0022 can be changed to improve security for newly created files. The NSA RHEL5 Security Guide suggests a umask of 0077 for maximum security, which makes new files not readable by users other than the owner. To change this, see Umask#Set the mask value. If you use sudo, consider configuring it to use the default root umask.

SUID and SGID files

It is important to be aware of any files with the Setuid or Setgid bit. Examples of relevant files in /usr/bin with the SUID bit set and owned by root:

The prominent risks of such executable files include privilege escalation vulnerabilities, see e.g Wikipedia:Setuid#Security impact.[3][4][5]

Files with the SUID bit set and not owned by root, or files with the SGID bit set typically have less potential impact but can theoretically still do decent damage if vulnerable. It is usually possible to avoid using Setuid or Setgid by assigning Capabilities instead.

Tip: It is vital to be vigilant in keeping packages which provide SUID/SGID executables up to date in order to prevent having a vulnerable system.

To search /usr/bin for files with either the SUID or SGID bit:

$ find /usr/bin -perm "/u=s,g=s"

Backups

This article or section is a candidate for merging with System backup.

Notes: There is a dedicated page for system backups. (Discuss in Talk:Security)

Regularly create backups of important data. Regularly test the integrity of the backups. Regularly test that the backups can be restored.

Make sure that at least one copy of the data is stored offline, i.e. not connected to the system under threat in any way. Ransomware and other destructive attacks may also attack any connected backup systems.

SATA SSD frozen mode

See Solid state drive#Setting the SSD state to frozen mode after waking up from sleep.

User setup

Do not use the root account for daily use

Following the principle of least privilege, do not use the root user for daily use. Create a non-privileged user account for each person using the system. Use sudo as necessary for temporary privileged access.

Enforce a delay after a failed login attempt

Add the following line to /etc/pam.d/system-login to add a delay of at least 4 seconds between failed login attempts:

/etc/pam.d/system-login
auth optional pam_faildelay.so delay=4000000

4000000 is the time in microseconds to delay.

Lock out user after three failed login attempts

As of pambase 20200721.1-2, pam_faillock.so is enabled by default to lock out users for 10 minutes after 3 failed login attempts in a 15 minute period (see FS#67644). The lockout only applies to password authentication (e.g. login and sudo), public key authentication over SSH is still accepted. To prevent complete denial-of-service, this lockout is disabled for the root user by default.

To unlock a user, do:

$ faillock --user username --reset

By default, the lock mechanism is a file per-user located at /run/faillock/. Deleting or emptying the file unlocks that user—the directory is owned by root, but the file is owned by the user, so the faillock command only empties the file, therefore does not require root.

The module pam_faillock.so can be configured with the file /etc/security/faillock.conf. The lockout parameters:

  • unlock_time — the lockout time (in seconds, default 10 minutes).
  • fail_interval — the time in which failed logins can cause a lockout (in seconds, default 15 minutes).
  • deny — the number of failed logins before lockout (default 3).
Tip: The primary purpose for the lockout is to slow down brute-force attacks so that they become infeasible. Hence, if lockouts due to mistyping of passwords become too frequent, relaxing the number of attempts may be preferred to reducing the lockout time.
Note: deny = 0 will disable the lockout mechanism entirely.

By default, all user locks are lost after reboot. If your attacker can reboot the machine, it is more secure if locks persist. To make locks persist, change the dir parameter in /etc/security/faillock.conf to /var/lib/faillock.

No restart is required for changes to take effect. See faillock.conf(5) for further configuration options, such as enabling lockout for the root account, disabling for centralized login (e.g. LDAP), etc.

Limit amount of processes

On systems with many, or untrusted users, it is important to limit the number of processes each can run at once, therefore preventing fork bombs and other denial of service attacks. /etc/security/limits.conf determines how many processes each user, or group can have open, and is empty (except for useful comments) by default. Adding the following lines to this file will limit all users to 100 active processes, unless they use the prlimit command to explicitly raise their maximum to 200 for that session. These values can be changed according to the appropriate number of processes a user should have running, or the hardware of the box you are administrating.

* soft nproc 100
* hard nproc 200

The current number of threads for each user can be found with ps --no-headers -Leo user | sort | uniq --count. This may help with determining appropriate values for the limits.

Use Wayland

Prefer using Wayland over Xorg. Xorg's design predates modern security practices and is considered insecure by many. For example, Xorg applications may record keystrokes while inactive.

If you must run Xorg, it is recommended to avoid running it as root. Within Wayland, the Xwayland compatibility layer will automatically use rootless Xorg.

Restricting root

The root user is, by definition, the most powerful user on a system. It is also difficult to audit the root user account. It is therefore important to restrict usage of the root user account as much as possible. There are a number of ways to keep the power of the root user while limiting its ability to cause harm.

Use sudo instead of su

This article or section is a candidate for merging with sudo.

Notes: There is a dedicated article. (Discuss in Talk:Security)

Using sudo for privileged access is preferable to su for a number of reasons.

  • It keeps a log of which normal privilege user has run each privileged command.
  • The root user password need not be given out to each user who requires root access.
  • sudo prevents users from accidentally running commands as root that do not need root access, because a full root terminal is not created. This aligns with the principle of least privilege.
  • Individual programs may be enabled per user, instead of offering complete root access just to run one command. For example, to give the user alice access to a particular program:
# visudo
/etc/sudoers
alice ALL = NOPASSWD: /path/to/program

Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:

%users ALL=/sbin/mount.cifs,/sbin/umount.cifs

This allows all users who are members of the group users to run the commands /sbin/mount.cifs and /sbin/umount.cifs from any machine (ALL).

Tip: To use restricted version of nano instead of vi with visudo,
/etc/sudoers
Defaults editor=/usr/bin/rnano

Exporting EDITOR=nano visudo is regarded as a severe security risk since everything can be used as an EDITOR.

Editing files using sudo

See Sudo#Editing files. Alternatively, you can use an editor like rvim or rnano which has restricted capabilities in order to be safe to run as root.

Restricting root login

Once sudo is properly configured, full root access can be heavily restricted or denied without losing much usability. To disable root, but still allowing to use sudo, you can use passwd --lock root.

Allow only certain users

The PAM pam_wheel.so lets you allow only users in the group wheel to login using su. See su#su and wheel.

Denying SSH login

Even if you do not wish to deny root login for local users, it is always good practice to deny root login via SSH. The purpose of this is to add an additional layer of security before a user can completely compromise your system remotely.

Specify acceptable login combinations with access.conf

When someone attempts to log in with PAM, /etc/security/access.conf is checked for the first combination that matches their login properties. Their attempt then fails or succeeds based on the rule for that combination.

+:root:LOCAL
-:root:ALL

Rules can be set for specific groups and users. In this example, the user archie is allowed to login locally, as are all users in the wheel and adm groups. All other logins are rejected:

+:archie:LOCAL
+:(wheel):LOCAL
+:(adm):LOCAL
-:ALL:ALL

Read more at access.conf(5)

Mandatory access control

Mandatory access control (MAC) is a type of security policy that differs significantly from the discretionary access control (DAC) used by default in Arch and most Linux distributions. MAC essentially means that every action a program could perform that affects the system in any way is checked against a security ruleset. This ruleset, in contrast to DAC methods, cannot be modified by users. Using virtually any mandatory access control system will significantly improve the security of your computer, although there are differences in how it can be implemented.

Pathname MAC

Pathname-based access control is a simple form of access control that offers permissions based on the path of a given file. The downside to this style of access control is that permissions are not carried with files if they are moved around the system. On the positive side, pathname-based MAC can be implemented on a much wider range of filesystems, unlike labels-based alternatives.

  • AppArmor is a Canonical-maintained MAC implementation seen as an "easier" alternative to SELinux.
  • TOMOYO is another simple, easy-to-use system offering mandatory access control. It is designed to be both simple in usage and in implementation, requiring very few dependencies.

Labels MAC

Labels-based access control means the extended attributes of a file are used to govern its security permissions. While this system is arguably more flexible in its security offerings than pathname-based MAC, it only works on filesystems that support these extended attributes.

  • SELinux, based on an NSA project to improve Linux security, implements MAC completely separate from system users and roles. It offers an extremely robust multi-level MAC policy implementation that can easily maintain control of a system that grows and changes past its original configuration.

Access Control Lists

Access Control Lists (ACLs) are an alternative to attaching rules directly to the filesystem in some way. ACLs implement access control by checking program actions against a list of permitted behavior.

Kernel hardening

Kernel self-protection / exploit mitigation

The linux-hardened package uses a basic kernel hardening patch set and more security-focused compile-time configuration options than the linux package. A custom build can be made to choose a different compromise between security and performance than the security-leaning defaults.

However, it should be noted that several packages will not work when using this kernel. For example throttled.

If you use an out-of-tree driver such as NVIDIA, you may need to switch to its DKMS package.

Userspace ASLR comparison

The linux-hardened package provides an improved implementation of Address Space Layout Randomization for userspace processes. The paxtest command can be used to obtain an estimate of the provided entropy:

64-bit processes
linux-hardened 5.4.21.a-1-hardened
Anonymous mapping randomization test     : 32 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 40 quality bits (guessed)
Heap randomization test (PIE)            : 40 quality bits (guessed)
Main executable randomization (ET_EXEC)  : 32 quality bits (guessed)
Main executable randomization (PIE)      : 32 quality bits (guessed)
Shared library randomization test        : 32 quality bits (guessed)
VDSO randomization test                  : 32 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 40 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 40 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 44 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 44 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 34 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)
Randomization under memory exhaustion @~0: 32 bits (guessed)
Randomization under memory exhaustion @0 : 32 bits (guessed)
linux 5.5.5-arch1-1
Anonymous mapping randomization test     : 28 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 28 quality bits (guessed)
Heap randomization test (PIE)            : 28 quality bits (guessed)
Main executable randomization (ET_EXEC)  : 28 quality bits (guessed)
Main executable randomization (PIE)      : 28 quality bits (guessed)
Shared library randomization test        : 28 quality bits (guessed)
VDSO randomization test                  : 20 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 30 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 30 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 22 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 22 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)
Randomization under memory exhaustion @~0: 29 bits (guessed)
Randomization under memory exhaustion @0 : 29 bits (guessed)
linux-lts 4.19.101-1-lts
Anonymous mapping randomization test     : 28 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 28 quality bits (guessed)
Heap randomization test (PIE)            : 28 quality bits (guessed)
Main executable randomization (ET_EXEC)  : 28 quality bits (guessed)
Main executable randomization (PIE)      : 28 quality bits (guessed)
Shared library randomization test        : 28 quality bits (guessed)
VDSO randomization test                  : 19 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 30 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 30 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 22 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 22 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)
Randomization under memory exhaustion @~0: 28 bits (guessed)
Randomization under memory exhaustion @0 : 28 bits (guessed)
32-bit processes (on an x86_64 kernel)
linux-hardened
Anonymous mapping randomization test     : 16 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 22 quality bits (guessed)
Heap randomization test (PIE)            : 27 quality bits (guessed)
Main executable randomization (ET_EXEC)  : No randomization
Main executable randomization (PIE)      : 18 quality bits (guessed)
Shared library randomization test        : 16 quality bits (guessed)
VDSO randomization test                  : 16 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 24 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 24 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 28 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 28 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)
Randomization under memory exhaustion @~0: 18 bits (guessed)
Randomization under memory exhaustion @0 : 18 bits (guessed)
linux
Anonymous mapping randomization test     : 8 quality bits (guessed)
Heap randomization test (ET_EXEC)        : 13 quality bits (guessed)
Heap randomization test (PIE)            : 13 quality bits (guessed)
Main executable randomization (ET_EXEC)  : No randomization
Main executable randomization (PIE)      : 8 quality bits (guessed)
Shared library randomization test        : 8 quality bits (guessed)
VDSO randomization test                  : 8 quality bits (guessed)
Stack randomization test (SEGMEXEC)      : 19 quality bits (guessed)
Stack randomization test (PAGEEXEC)      : 19 quality bits (guessed)
Arg/env randomization test (SEGMEXEC)    : 11 quality bits (guessed)
Arg/env randomization test (PAGEEXEC)    : 11 quality bits (guessed)
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)
Randomization under memory exhaustion @~0: No randomization
Randomization under memory exhaustion @0 : No randomization

Restricting access to kernel pointers in the proc filesystem

Setting kernel.kptr_restrict to 1 will hide kernel symbol addresses in /proc/kallsyms from regular users without CAP_SYSLOG, making it more difficult for kernel exploits to resolve addresses/symbols dynamically. This will not help that much on a pre-compiled Arch Linux kernel, since a determined attacker could just download the kernel package and get the symbols manually from there, but if you are compiling your own kernel, this can help mitigating local root exploits. This will break some perf commands when used by non-root users (but many perf features require root access anyway). See FS#34323 for more information.

Setting kernel.kptr_restrict to 2 will hide kernel symbol addresses in /proc/kallsyms regardless of privileges.

/etc/sysctl.d/51-kptr-restrict.conf
kernel.kptr_restrict = 1
Note: linux-hardened sets kptr_restrict=2 by default rather than 0.

BPF hardening

BPF is a system used to load and execute bytecode within the kernel dynamically during runtime. It is used in a number of Linux kernel subsystems such as networking (e.g. XDP, tc), tracing (e.g. kprobes, uprobes, tracepoints) and security (e.g. seccomp). It is also useful for advanced network security, performance profiling and dynamic tracing.

BPF was originally an acronym of Berkeley Packet Filter since the original classic BPF was used for packet capture tools for BSD. This eventually evolved into Extended BPF (eBPF), which was shortly afterwards renamed to just BPF (not an acronym). BPF should not be confused with packet filtering tools like iptables or netfilter, although BPF can be used to implement packet filtering tools.

BPF code may be either interpreted or compiled using a Just-In-Time (JIT) compiler. The Arch kernel is built with CONFIG_BPF_JIT_ALWAYS_ON which disables the BPF interpreter and forces all BPF to use JIT compilation. This makes it harder for an attacker to use BPF to escalate attacks that exploit SPECTRE-style vulnerabilities. See the kernel patch which introduced CONFIG_BPF_JIT_ALWAYS_ON for more details.

The kernel includes a hardening feature for JIT-compiled BPF which can mitigate some types of JIT spraying attacks at the cost of performance and the ability to trace and debug many BPF programs. It may be enabled by setting net.core.bpf_jit_harden to 1 (to enable hardening of unprivileged code) or 2 (to enable hardening of all code).

See the net.core.bpf_* settings in the kernel documentation for more details.

Tip:
  • linux-hardened sets net.core.bpf_jit_harden=2 by default rather than 0.
  • By default, BPF programs can be run even by unprivileged users. To change that behaviour set kernel.unprivileged_bpf_disabled=1[6].

ptrace scope

The ptrace(2) syscall provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. ptrace is commonly used by debugging tools including gdb, strace, perf, reptyr and other debuggers. However, it also provides a means by which a malicious process can read data from and take control of other processes.

Arch enables the Yama LSM by default, which provides a kernel.yama.ptrace_scope kernel parameter. This parameter is set to 1 (restricted) by default which prevents tracers from performing a ptrace call on traces outside of a restricted scope unless the tracer is privileged or has the CAP_SYS_PTRACE capability. This is a significant improvement in security compared to the classic permissions. Without this module, there is no separation between processes running as the same user (in the absence of additional security layers such as pid_namespaces(7)).

Note: By default, you can still use tools which require ptrace by running them as privileged processes, e.g. using sudo.

If you do not need to use debugging tools, consider setting kernel.yama.ptrace_scope to 2 (admin-only) or 3 (no ptrace possible) to harden the system.

hidepid

This article or section needs expansion.

Reason: Linux 5.8 implemented private instances and new values for hidepid=. (Discuss in Talk:Security)

The factual accuracy of this article or section is disputed.

Reason: Enabling hidepid globally is not a supported way of operation by systemd, nor does it have any practical improvements security-wise when systemd is running as service manager. [7] (Discuss in Talk:Security)
Warning:
  • This may cause issues for certain applications like an application running in a sandbox and Xorg (see workaround).
  • This causes issues with D-Bus, Polkit, PulseAudio and bluetooth when using systemd > 237.64-1.

The kernel has the ability to hide other users' processes, normally accessible via /proc, from unprivileged users by mounting the proc filesystem with the hidepid= and gid= options documented in https://docs.kernel.org/filesystems/proc.html.

This greatly complicates an intruder's task of gathering information about running processes, whether some daemon runs with elevated privileges, whether other user runs some sensitive program, whether other users run any program at all, makes it impossible to learn whether any user runs a specific program (given the program does not reveal itself by its behaviour), and, as an additional bonus, poorly written programs passing sensitive information via program arguments are now protected against local eavesdroppers.

The proc group, provided by the filesystem package, acts as a whitelist of users authorized to learn other users' process information. If users or services need access to /proc/<pid> directories beyond their own, add them to the group.

For example, to hide process information from other users except those in the proc group:

/etc/fstab
proc	/proc	proc	nosuid,nodev,noexec,hidepid=2,gid=proc	0	0

For user sessions to work correctly, an exception needs to be added for systemd-logind:

/etc/systemd/system/systemd-logind.service.d/hidepid.conf
[Service]
SupplementaryGroups=proc

Restricting module loading

The default Arch kernel has CONFIG_MODULE_SIG_ALL enabled, which signs all kernel modules built as part of the linux package. This allows the kernel to only load modules signed with a valid key, i.e. out-of-tree modules compiled locally or provided by packages such as virtualbox-host-modules-arch cannot be loaded.

Kernel module loading can be restricted by setting the module.sig_enforce=1 kernel parameter. More information can be found in the kernel documentation.

Disable kexec

Kexec allows replacing the current running kernel.

/etc/sysctl.d/51-kexec-restrict.conf
kernel.kexec_load_disabled = 1
Tip: kexec is disabled by default in linux-hardened.

Kernel lockdown mode

Since Linux 5.4 the kernel has gained an optional lockdown feature, intended to strengthen the boundary between UID 0 (root) and the kernel. When enabled some applications may cease to work which rely on low-level access to either hardware or the kernel.

To use lockdown, its LSM must be initialized and a lockdown mode must be set.

All officially supported kernels initialize the LSM, but none of them enforce any lockdown mode.

Tip: Initialized LSMs can be verified by running cat /sys/kernel/security/lsm.

Lockdown has two modes of operation:

  • integrity: kernel features that allow userland to modify the running kernel are disabled (kexec, bpf).
  • confidentiality: kernel features that allow userland to extract confidential information from the kernel are also disabled.

It is recommended to use integrity, unless your specific threat model dictates otherwise.

To enable kernel lockdown at runtime, run:

# echo mode > /sys/kernel/security/lockdown

To enable kernel lockdown on boot, use the kernel parameter lockdown=mode.

Note:
  • Kernel lockdown cannot be disabled at runtime.
  • Kernel lockdown disables hibernation.

See also kernel_lockdown(7).

Linux Kernel Runtime Guard (LKRG)

LKRG (lkrg-dkmsAUR) is a kernel module which performs integrity checking of the kernel and detection of exploit attempts.

Disable emergency shell

The factual accuracy of this article or section is disputed.

Reason: Masking emergency.target and emergency.service will have no effect on those units being added to the initramfs and run in early userspace. Even with them in the initramfs, mkinitcpio's systemd hook locks the root account[8][9] for "security reasons" (see FS#70408). The solution for the issue in the linked article, if even needed, would be to prevent rescue.target, rescue.service, emergency.target and emergency.service from being added to the initramfs image. (Discuss in Talk:Security)

The emergency shell is used to interactively troubleshoot the machine during the boot process. However, it is also a gadget that an attacker can use to access secure resources such as the TPM. See this article for a practical example. The difficulty of attacks can be increased by disabling the emergency shell, at the tradeoff of removing a tool to troubleshoot early boot failures.

To disable the emergency shell, See Systemd#Disable emergency mode on remote machine.

Sandboxing applications

See also Wikipedia:Sandbox (computer security).

Note: The user namespace configuration item CONFIG_USER_NS is currently enabled in linux, linux-lts, linux-zen and linux-hardened. Lack of it may prevent certain sandboxing features from being made available to applications.
Warning: Unprivileged user namespace usage (CONFIG_USER_NS_UNPRIVILEGED) is enabled by default in linux, linux-lts and linux-zen, which greatly increases the attack surface for local privilege escalation (see FS#36969).

To mitigate this, either :

  • use the linux-hardened kernel which has the safe default, or
  • set the kernel.unprivileged_userns_clone sysctl to 0.

Note that this can break applications such as Zoom. You will also need to replace bubblewrap with bubblewrap-suid if it is installed on your system. See Bubblewrap#Installation.

Firejail

Firejail is an easy to use tool for sandboxing applications and servers alike. It was originally created for browsers and internet facing applications, but supports a large number of applications by now. To establish a sandboxed environment with a variety of features, it is installed as a suid binary and builds a sandboxed runtime environment for the target application based on black and white lists.

bubblewrap

bubblewrap is a sandbox application developed for unprivileged container tools like Flatpak with a significantly smaller resource footprint and complexity than Firejail. While it lacks certain features such as file path whitelisting, bubblewrap does offer bind mounts as well as the creation of user/IPC/PID/network/cgroup namespaces and can support both simple and complex sandboxes.

Bubblejail sandbox is based on bubblewrap and provides a resource oriented permission model with a graphical interface to tweak permissions.

chroots

Manual chroot jails can also be constructed to build sandboxed process environments. It is much more limited than other sandboxing technologies; the extent of its sandboxing is file path isolation.

Linux containers

Linux Containers are another good option when you need more separation than the other options (short of full system virtualization) provide. LXC is run on top of the existing kernel in a pseudo-chroot with their own virtual hardware.

Full virtualization options

Using full virtualization options such as VirtualBox, KVM, Xen or Qubes OS (based on Xen) can also improve isolation and security in the event you plan on running risky applications or browsing dangerous websites.

Network and firewalls

Firewalls

While the stock Arch kernel is capable of using Netfilter's iptables and nftables, the services are not enabled by default. It is highly recommended to set up some form of firewall to protect the services running on the system. Many resources (including ArchWiki) do not state explicitly which services are worth protecting, so enabling a firewall is a good precaution.

  • See iptables and nftables for general information.
  • See Simple stateful firewall for a guide on setting up an iptables firewall.
  • See Category:Firewalls for other ways of setting up netfilter.
  • See Ipset for blocking lists of ip addresses, such as those from Bluetack.
  • opensnitch is a configurable inbound and outbound firewall with support for configurable rules by application, port, host, etc.

Open ports

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

Reason: "Open ports" is not a good title since it disregards interfaces and addresses that the application may be bound to. From the firewalls' point of view, ports may be "open" even if no application listens on them at the moment. (Discuss in Talk:Security)

Some services listen for inbound traffic on open network ports. It is important to only bind these services to the addresses and interfaces that are strictly necessary. It may be possible for a remote attacker to exploit flawed network protocols to access exposed services. This can even happen with processes bound to localhost.

In general, if a service only needs to be accessible to the local system, bind to a Unix domain socket (unix(7)) or a loopback address such as localhost instead of a non-loopback address like 0.0.0.0/0.

If a service needs to be accessible to other systems via the network, control the access with strict firewall rules and configure authentication, authorization and encryption whenever possible.

You can list all current open ports with ss -l. To show all listening processes and their numeric tcp and udp port numbers:

# ss -lpntu

See ss(8) for more options.

Kernel parameters

Kernel parameters which affect networking can be set using Sysctl. For how to do this, see Sysctl#TCP/IP stack hardening.

SSH

To mitigate brute-force attacks it is recommended to enforce key-based authentication. For OpenSSH, see OpenSSH#Force public key authentication. Alternatively Fail2ban or Sshguard offer lesser forms of protection by monitoring logs and writing firewall rules but open up the potential for a denial of service, since an attacker can spoof packets as if they came from the administrator after identifying their address. Spoofing IP has lines of defense, such as by reverse path filtering and disabling ICMP redirects.

You may want to harden authentication even more by using two-factor authentication. Google Authenticator provides a two-step authentication procedure using one-time passcodes (OTP).

Denying root login is also a good practice, both for tracing intrusions and adding an additional layer of security before root access. For OpenSSH, see OpenSSH#Deny.

Mozilla publishes an OpenSSH configuration guide which configures more verbose audit logging and restricts ciphers.

DNS

The default domain name resolution (DNS) configuration is highly compatible but has security weaknesses. See DNS privacy and security for more information.

Proxies

Proxies are commonly used as an extra layer between applications and the network, sanitizing data from untrusted sources. The attack surface of a small proxy running with lower privileges is significantly smaller than a complex application running with the end user privileges.

For example the DNS resolver is implemented in glibc, that is linked with the application (that may be running as root), so a bug in the DNS resolver might lead to a remote code execution. This can be prevented by installing a DNS caching server, such as dnsmasq, which acts as a proxy. [10]

Managing TLS certificates

See TLS#Trust management.

Physical security

Physical access to a computer is root access given enough time and resources. However, a high practical level of security can be obtained by putting up enough barriers.

An attacker can gain full control of your computer on the next boot by simply attaching a malicious IEEE 1394 (FireWire), Thunderbolt or PCI Express device as they are given full memory access by default.[11] For Thunderbolt, you can restrict the direct memory access completely or to known devices, see Thunderbolt#User device authorization. For Firewire and PCI Express, there is little you can do from preventing this, or modification of the hardware itself - such as flashing malicious firmware onto a drive. However, the vast majority of attackers will not be this knowledgeable and determined.

#Data-at-rest encryption will prevent access to your data if the computer is stolen, but malicious firmware can be installed to obtain this data upon your next log in by a resourceful attacker.

Locking down BIOS

Adding a password to the BIOS prevents someone from booting into removable media, which is basically the same as having root access to your computer. You should make sure your drive is first in the boot order and disable the other drives from being bootable if you can.

Boot loaders

It is highly important to protect your boot loader. An unprotected boot loader can bypass any login restrictions, e.g. by setting the init=/bin/sh kernel parameter to boot directly to a shell.

Syslinux

Syslinux supports password-protecting your bootloader. It allows you to set either a per-menu-item password or a global bootloader password.

GRUB

GRUB supports bootloader passwords as well. See GRUB/Tips and tricks#Password protection of GRUB menu for details. It also has support for encrypted /boot, which only leaves some parts of the bootloader code unencrypted. GRUB's configuration, kernel and initramfs are encrypted.

systemd-boot

systemd-boot disables editing of kernel parameters when #Secure Boot is enabled. Alternatively, see systemd-boot#Kernel parameters editor with password protection for a more traditional password-based option.

Secure Boot

Secure Boot is a feature of UEFI that allows authentication of the files your computer boots. This helps preventing some evil maid attacks such as replacing files inside the boot partition. Normally computers come with keys that are enrolled by vendors (OEM). However these can be removed and allow the computer to enter Setup Mode which allows the user to enroll and manage their own keys.

The secure boot page guides you through how to set secure boot up by using your own keys.

Trusted Platform Module (TPM)

TPMs are hardware microprocessors which have cryptographic keys embedded. This forms the fundamental root of trust of most modern computers and allows end-to-end verification of the boot chain. They can be used as internal smartcards, attest the firmware running on the computer and allow users to insert secrets into a tamper-proof and brute-force resistant store.

Boot partition on removable flash drive

One popular idea is to place the boot partition on a flash drive in order to render the system unbootable without it. Proponents of this idea often use full-disk encryption alongside, and some also use detached encryption headers placed on the boot partition.

This method can also be merged with encrypting /boot.

Automatic logout

If you are using Bash or Zsh, you can set TMOUT for an automatic logout from shells after a timeout.

For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):

/etc/profile.d/shell-timeout.sh
TMOUT="$(( 60*10 ))";
[ -z "$DISPLAY" ] && export TMOUT;
case $( /usr/bin/tty ) in
	/dev/tty[0-9]*) export TMOUT;;
esac

If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:

$ export TMOUT="$(( 60*10 ))";

Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without TMOUT support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.

Protect against rogue USB devices

Install USBGuard, which is a software framework that helps to protect your computer against rogue USB devices (a.k.a. BadUSB, PoisonTap or LanTurtle) by implementing basic whitelisting and blacklisting capabilities based on device attributes.

Volatile data collection

A computer that is powered on may be vulnerable to volatile data collection. It is a best practice to turn a computer completely off at times it is not necessary for it to be on, or if the computer's physical security is temporarily compromised (e.g. when passing through a security checkpoint).

Packages

Authentication

Attacks on package managers are possible without proper use of package signing, and can affect even package managers with proper signature systems. Arch uses package signing by default and relies on a web of trust from 5 trusted master keys. See Pacman-key for details.

Upgrades

It is important to regularly upgrade the system.

Follow vulnerability alerts

Subscribe to the Common Vulnerabilities and Exposure (CVE) Security Alert updates, made available by National Vulnerability Database, and found on the NVD Download webpage. The Arch Linux Security Tracker serves as a particularly useful resource in that it combines Arch Linux Security Advisory (ASA), Arch Linux Vulnerability Group (AVG) and CVE data sets in tabular format. The tool arch-audit can be used to check for vulnerabilities affecting the running system. A graphical system tray, arch-audit-gtk, can also be used. See also Arch Security Team.

You should also consider subscribing to the release notifications for software you use, especially if you install software through means other than the main repositories or AUR. Some software have mailing lists you can subscribe to for security notifications. Source code hosting sites often offer RSS feeds for new releases.

Rebuilding packages

Packages can be rebuilt and stripped of undesired functions and features as a means to reduce attack surface. For example, bzip2 can be rebuilt without bzip2recover in an attempt to circumvent CVE-2016-3189. Custom hardening flags can also be applied either manually or via a wrapper.

This article or section is a candidate for merging with Arch package guidelines/Security.

Notes: Security related build flags have their own article. (Discuss in Talk:Security)

The factual accuracy of this article or section is disputed.

Reason: Copy-pasted from a 3 years old blog post. The compiler flags are specific to GCC, some are hardly security related (e.g. -O2, -g, -Wall). (Discuss in Talk:Security)
Flag Purpose
-D_FORTIFY_SOURCE=2 Run-time buffer overflow detection
-D_GLIBCXX_ASSERTIONS Run-time bounds checking for C++ strings and containers
-fasynchronous-unwind-tables Increased reliability of backtraces
-fexceptions Enable table-based thread cancellation
-fpie -Wl,-pie Full ASLR for executables
-fpic -shared No text relocations for shared libraries
-fplugin=annobin Generate data for hardening quality control
-fstack-clash-protection Increased reliability of stack overflow detection
-fstack-protector or -fstack-protector-all Stack smashing protector
-fstack-protector-strong Likewise
-g Generate debugging information
-grecord-gcc-switches Store compiler flags in debugging information
-mcet -fcf-protection Control flow integrity protection
-O2 Recommended optimizations
-pipe Avoid temporary files, speeding up builds
-Wall Recommended compiler warnings
-Werror=format-security Reject potentially unsafe format string arguments
-Werror=implicit-function-declaration Reject missing function prototypes
-Wl,-z,defs Detect and reject underlinking
-Wl,-z,now Disable lazy binding
-Wl,-z,relro Read-only segments after relocation

See also