https://wiki.archlinux.org/api.php?action=feedcontributions&user=Teples&feedformat=atomArchWiki - User contributions [en]2024-03-28T17:50:07ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=Audit_framework&diff=649384Audit framework2021-01-21T12:20:27Z<p>Teples: Add example for filtering unwanted messages</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Logging]]<br />
[[ja:Audit フレームワーク]]<br />
The Linux audit framework provides a CAPP-compliant ([[Wikipedia:Controlled Access Protection Profile|Controlled Access Protection Profile]]) auditing system that reliably collects information about any security-relevant (or non-security-relevant) event on a system. It can help you track actions performed on a system.<br />
<br />
Linux audit helps make your system more secure by providing you with means to analyze what is happening on your system in great detail. It does not, however, provide additional security itself—it does not protect your system from code malfunctions or any kind of exploits. Instead, Audit is useful for tracking these issues and helps you take additional security measures to prevent them.<br />
<br />
The audit framework works by listening to the event reported by the kernel and logging them to a log file.<br />
<br />
{{Note|1=Audit framework compatibility with containers was fixed in Linux 3.15, see [https://bugzilla.redhat.com/show_bug.cgi?id=893751], however interpreting audit records may be difficult as support for namespace ID is still work in progress, see [https://github.com/linux-audit/audit-kernel/issues/32].}}<br />
<br />
== Installation ==<br />
<br />
In-kernel audit support is available in {{Pkg|linux}} (since 4.18), {{Pkg|linux-lts}} (since 4.19), {{Pkg|linux-zen}} (since 4.18) and {{Pkg|linux-hardened}}. For custom kernels {{ic|CONFIG_AUDIT}} should be enabled. Audit can be enabled at boot-time by setting {{ic|1=audit=1}} as [[kernel parameter]].<br />
<br />
For userspace support [[install]] {{Pkg|audit}} and [[start/enable]] {{ic|auditd.service}}.<br />
<br />
{{Note|In order to disable audit completely and suppress audit messages from appearing in journal you may set {{ic|1=audit=0}} as [[kernel parameter]] and/or [[mask]] {{ic|systemd-journald-audit.socket}}.}}<br />
<br />
Audit framework is composed of the auditd daemon, responsible for writing the audit messages that were generated through the audit kernel interface and triggered by application and system activity.<br />
<br />
This daemon can be controlled by several commands and files:<br />
<br />
* ''auditctl'' : to control the behavior of the daemon on the fly, adding rules etc.<br />
* {{ic|/etc/audit/audit.rules}} : contains the rules and various parameters of the auditd daemon<br />
* ''aureport'' : generate report of the activity on a system<br />
* ''ausearch'' : search for various events<br />
* ''auditspd'' : the daemon which can be used to relay event notifications to other applications instead of writing them to disk in the audit log<br />
* ''autrace'' : this command can be used to trace a process, in a similar way as strace.<br />
* {{ic|/etc/audit/auditd.conf}} : configuration file related to the logging.<br />
<br />
== Adding rules ==<br />
<br />
Before adding rules, you must know that the audit framework can be very verbose and that each rule must be carefully tested before being effectively deployed. Indeed, just one rule can flood all your logs within a few minutes.<br />
<br />
=== Audit files and directories access ===<br />
<br />
The most basic use of the audit framework is to log the access to the files you want.<br />
To do this, you must use a watch {{ic|-w}} to a file or a directory<br />
The most basic rule to set up is to track accesses to the passwd file :<br />
<br />
# auditctl -w /etc/passwd -p rwxa<br />
<br />
You can track access to a folder with :<br />
<br />
# auditctl -w /etc/security/<br />
<br />
The first rule keeps track of every read {{ic|r}} , write {{ic|w}} , execution {{ic|x}} , attribute change {{ic|a}} to the file {{ic|/etc/passwd}}.<br />
The second one keeps track of any access to the {{ic|/etc/security/}} folder.<br />
<br />
You can list all active rules with :<br />
<br />
# auditctl -l<br />
<br />
You can delete all rules with :<br />
<br />
# auditctl -D<br />
<br />
Once you validate the rules, you can append them to the {{ic|/etc/audit/audit.rules}} file like that : <br />
<br />
-w /etc/audit/audit.rules -p rwxa<br />
-w /etc/security/<br />
<br />
=== Audit syscalls ===<br />
<br />
The audit framework allows you to audit the syscalls performed with the {{ic|-a}} option.<br />
<br />
A security related rule is to track the {{ic|chmod syscall}}, to detect file ownership changes :<br />
<br />
# auditctl -a entry,always -S chmod<br />
<br />
For a list of all syscalls: {{man|2|syscalls}}<br />
<br />
A lot of rules and posibilities are available, see {{man|8|auditctl}} and {{man|7|audit.rules}}.<br />
<br />
=== Filter unwanted messages ===<br />
<br />
In order to prevent noisy audit messages from flooding system logs you may add a rules to exclude some of them:<br />
<br />
{{hc|/etc/audit/rules.d/quiet.rules|2=<br />
-A exclude,always -F msgtype=SERVICE_START<br />
-A exclude,always -F msgtype=SERVICE_STOP<br />
-A exclude,always -F msgtype=BPF<br />
}}<br />
<br />
== Search the logs ==<br />
<br />
The audit framework provides some tools to ease the use and the research of events happening on a system.<br />
<br />
=== Using pid ===<br />
<br />
You can search events related to a particular pid using {{ic|ausearch}}:<br />
<br />
# ausearch -p 1<br />
<br />
This command will show you all the events logged according to your rules related to PID 1 (i.e. systemd).<br />
<br />
=== Using keys===<br />
<br />
One of the great features of the audit framework is its ability to use {{ic|keys}} to manage events, such a usage is recommended.<br />
<br />
You can use the {{ic|-k}} option in your rules to be able to find related events easily :<br />
<br />
# auditctl -w /etc/passwd -p rwxa -k KEY_pwd<br />
<br />
Then, if you search for events with the key {{ic|KEY_pwd}}, ausearch will display only event related to the file {{ic|/etc/passwd}}.<br />
<br />
# ausearch -k KEY_pwd<br />
<br />
=== Look for abnormalities ===<br />
<br />
The {{ic|aureport}} tool can be used to quickly report any abnormal event performed on the system, it includes network interfaces used in promiscous mode, process or thread crashing or exiting with ENOMEM error etc.<br />
<br />
The easiest way to use {{ic|aureport}} is :<br />
<br />
# aureport -n<br />
<br />
aureport can be used to generate custom reports, see {{man|8|aureport}}.<br />
<br />
== Which files or syscalls are worth-auditing? ==<br />
<br />
Keep in mind that each audit rule added will generate logs, so you must be ready to treat this amount of information.<br />
Basically, each security-related event/file must be monitored, like ids, ips, anti-rootkits etc.<br />
On the other side, it's totally useless to track every write syscall, the smallest compilation will fill your logs with this event.<br />
<br />
More complex set of rules can be set up, performing auditing on a very fine-grained base. If you want to do so, see {{man|8|auditctl}}.<br />
<br />
== Gather logs from different hosts ==<br />
<br />
The audit framework has a plugin system which provides the possibility to send local logfiles to a remote auditd.<br />
<br />
=== Send logfiles ===<br />
<br />
To send your logfiles to a remote host you need the {{ic|audisp-remote}} plugin which comes automatically with the {{Pkg|audit}} package.<br />
Activate the plugin:<br />
<br />
{{hc|/etc/audisp/plugins.d/au-remote.conf|output=<br />
active = yes<br />
direction = out<br />
path = /usr/bin/audisp-remote<br />
type = always<br />
format = string<br />
}}<br />
<br />
and set the remote host where the logs should be send to:<br />
<br />
{{hc|/etc/audisp/audisp-remote.conf|output=<br />
remote_server = domain.name.or.ip<br />
port = 60<br />
##local_port = optional<br />
transport = tcp<br />
}}<br />
<br />
=== Receive logfiles ===<br />
<br />
To make audit listen for remote audispds you just need to set the tcp options:<br />
<br />
{{hc|/etc/audit/auditd.conf|output=<br />
tcp_listen_port = 60<br />
tcp_listen_queue = 5<br />
tcp_max_per_addr = 1<br />
##tcp_client_ports = 1024-65535 #optional<br />
tcp_client_max_idle = 0<br />
}}<br />
<br />
Now you can view the logs of '''all''' configured hosts in the logfiles of the receiving auditd.</div>Tepleshttps://wiki.archlinux.org/index.php?title=YubiKey&diff=640470YubiKey2020-11-03T14:16:22Z<p>Teples: /* YubiKey not acting as HID device */ add note about systemd native support for FIDO keys</p>
<hr />
<div>[[Category:Universal 2nd Factor]]<br />
[[ja:Yubikey]]<br />
{{Related articles start}}<br />
{{Related|Universal 2nd Factor}}<br />
{{Related|dm-crypt/Encrypting an entire system}}<br />
{{Related|PAM}}<br />
{{Related|GnuPG}}<br />
{{Related|KeePass}}<br />
{{Related articles end}}<br />
{{Accuracy|The article lacks sources, is interspersed with TODOs and probably out of date.}}<br />
The [https://www.yubico.com YubiKey] is a small [[Wikipedia:Security token|USB Security token]]. Depending on the model, it can:<br />
<br />
* Act as a smartcard (using the [[Wikipedia:CCID (protocol)|CCID protocol]]) - allowing storage of both [https://developers.yubico.com/PGP/ PGP] and [https://developers.yubico.com/PIV/ PIV] secret keys.<br />
* Handle [[Wikipedia:Universal_2nd_Factor|Universal 2nd Factor]] (U2F) requests.<br />
* Store and query approximately 30 [[Wikipedia:Initiative_for_Open_Authentication|OATH]] credentials. <br />
* Handle [[Wikipedia:Challenge–response authentication|challenge-response requests]], in either the Yubico OTP mode or the HMAC-SHA1 mode.<br />
* Generate [[Wikipedia:One-time password|One-time passwords]] (OTP) - [https://developers.yubico.com/OTP/ Yubico's AES based standard].<br />
* "Type" a static password up to 63 characters.<br />
<br />
While offering many features, newer versions of the YubiKey are [https://www.yubico.com/2016/05/secure-hardware-vs-open-source/ not released as open source]. An alternative is the [[Solo]].<br />
<br />
== Installation ==<br />
<br />
=== Management tools ===<br />
<br />
* {{App|YubiKey Manager|Python library and command-line tool ({{ic|ykman}}) for configuring and querying a YubiKey over USB. Has optional GUI.|https://developers.yubico.com/yubikey-manager/|{{Pkg|yubikey-manager}}, {{Pkg|yubikey-manager-qt}}}}<br />
::{{Note|After installation, enable {{ic|pcscd.service}}}}<br />
* {{App|YubiKey Personalization|Library and tool for configuring and querying a YubiKey over the OTP USB connection. More powerful than ykman, but harder to use. Has optional GUI. |https://developers.yubico.com/yubikey-personalization/|{{Pkg|yubikey-personalization}}, {{Pkg|yubikey-personalization-gui}}}}<br />
<br />
=== Authentication tools ===<br />
<br />
* {{App|Yubico PAM|[[PAM]] user authentication with either Yubico OTP or challenge-response.|https://developers.yubico.com/yubico-pam/|{{Pkg|yubico-pam}}}}<br />
* {{App|Yubico PAM-U2F|[[PAM]] user authentication with [[U2F]].|https://developers.yubico.com/pam-u2f/|{{Pkg|pam-u2f}}}}<br />
* {{App|Yubico Authenticator for Desktop| GUI to read OATH codes from your YubiKey over USB. Support the newer OATH implementation (YubiKey NEO and 4) as well as the older slot-based implementation (YubiKey Standard and Edge).|https://developers.yubico.com/OATH/YubiKey_OATH_software.html|{{Pkg|yubioath-desktop}}}}<br />
* {{App|libfido2|Client-side U2F support. Enables web browsers to use the U2F protocol for authentication with your YubiKey.|https://developers.yubico.com/libfido2/|{{Pkg|libfido2}}}}<br />
* {{App|YubiKey Full Disk Encryption|Use challenge-response mode to create strong LUKS passphrases. Supports full disk encryption.|https://github.com/agherzan/yubikey-full-disk-encryption|{{pkg|yubikey-full-disk-encryption}}}}<br />
<br />
== Inputs ==<br />
<br />
The YubiKey takes inputs in the form of API calls over USB and button presses.<br />
<br />
The button is very sensitive. Depending on the context, touching it does one of these things:<br />
<br />
* Trigger a static password or one-time password (OTP) (Short press for slot 1, long press for slot 2). This is the default behavior, and easy to trigger inadvertently.<br />
* Confirm / allow a function or access. The LED will illuminate to prompt the user.<br />
* Insert / eject the smartcard<br />
<br />
== Outputs ==<br />
<br />
The YubiKey transforms these inputs into outputs:<br />
<br />
* Keystrokes (emulating a USB keyboard), used to type static passwords and OTPs. (Note that static passwords are vulnerable to keyloggers.)<br />
* The built-in LED:<br />
** Blinks once when plugged in, useful for troubleshooting.<br />
** Blinks steadily when a button press is required to permit an API response.<br />
* API responses over USB. This is used for:<br />
** Challenge-Response requests (calculated using either Yubico OTP mode or HMAC-SHA1 mode)<br />
** U2F Challenge-Response requests<br />
** CCID Smartcard related requests<br />
<br />
== USB connection modes ==<br />
<br />
Depending on the YubiKey model, the device provides up to three different USB interfaces. Two of the interfaces implement the USB HID (Human Interface Device) device class; the third is a smart card interface (CCID). All three can be enabled or disabled independently, allowing control of their associated protocols.<br />
<br />
The following table shows which protocols use which interfaces:<br />
<br />
{| class="wikitable"<br />
! Protocol !! Interface<br />
|-<br />
|OTP || Keyboard HID<br />
|-<br />
|FIDO || Other HID<br />
|-<br />
|PIV || CCID<br />
|-<br />
|OpenPGP || CCID<br />
|-<br />
|OATH || CCID<br />
|}<br />
<br />
{{ic|ykman}} uses the term "modes", named OTP, FIDO, and CCID. <br />
<br />
{{Note|ykman renamed "U2F" to "FIDO" in release 0.6.1 (2018-04-16). https://developers.yubico.com/yubikey-manager/Release_Notes.html}}<br />
<br />
=== Get enabled modes ===<br />
<br />
{{hc|$ ykman mode|<br />
Current connection mode is: OTP+FIDO+CCID<br />
}}<br />
<br />
=== Set modes ===<br />
<br />
All modes are enabled from the factory. To change them:<br />
<br />
{{ic|$ ykman mode [OPTIONS] <MODE>}}<br />
* {{ic|<MODE>}} can be a string, such as {{ic|OTP+FIDO+CCID}}, or a shortened form {{ic|o+f+c}}.<br />
* {{ic|<MODE>}} can be a mode-number, which encodes several enabled modes.<br />
<br />
Here is a table of mode-numbers, if you care to use them:<br />
<br />
{| class="wikitable"<br />
|0||OTP device only.<br />
|-<br />
|1||CCID device only.<br />
|-<br />
|2||OTP/CCID composite device.<br />
|-<br />
|3||U2F device only.<br />
|-<br />
|4||OTP/U2F composite device.<br />
|-<br />
|5||U2F/CCID composite device.<br />
|-<br />
|6||OTP/U2F/CCID composite device. <br />
|-<br />
|81||CCID device only, with touch-eject.<br />
|}<br />
<br />
{{Note| Some examples use mode number 86, which is [https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 invalid]. The 80 will be ignored, and it will behave like 6.}}<br />
<br />
Options:<br />
* {{ic|--touch-eject}} - The button will insert and eject the smart card. This only works if the mode is CCID only; FIDO and OTP must be disabled.<br />
* {{ic|--autoeject-timeout <SECONDS>}} - Automatically eject the smart card after some time. Same restrictions as {{ic|--touch-eject}}.<br />
* {{ic|--chalresp-timeout <SECONDS>}} - Set the challenge-response timeout.<br />
<br />
For more information, see {{ic|$ ykman mode --help}}<br />
<br />
== One-time password ==<br />
<br />
This feature has a somewhat misleading name, because it also encompasses the static password and challenge-response functions. <br />
<br />
2 slots are provided for this feature, accessible by short and long button presses respectively. Each can be configured with '''one''' of the following:<br />
* Yubico OTP<br />
* OATH-HOTP<br />
* OATH-TOTP<br />
* Challenge-response<br />
* Static Password<br />
<br />
Each function has several configuration options provided at the time of creation, but once set they cannot be read back. It is possible to swap slots 1 and 2, with {{ic|$ ykman otp swap }}.<br />
<br />
=== Factory configuration ===<br />
<br />
On a new YubiKey, Yubico OTP is preconfigured on slot 1. This initial AES symmetric key is stored in the YubiKey on the Yubico Authentication server. This allows validating against YubiCloud, allowing the use of Yubico OTP in combination with the Yubico Forum website for instance or on https://demo.yubico.com).<br />
<br />
{{Warning|If you ever overwrite the factory key in slot 1, you cannot create a new key of the same<br />
trust level. Factory generated Yubico OTP credentials begin with a {{ic|CC}} prefix, while user generated credentials begin with {{ic|VV}}. There is no fundamental difference in security or functionality, though some services only trust {{ic|CC}} credentials. More information can be found in this [https://forum.yubico.com/viewtopic12ca.html?f%3D16&t%3D1960 forum thread].}}<br />
<br />
=== Yubico OTP ===<br />
<br />
The [https://developers.yubico.com/OTP/ Yubico OTP] is based on [[Wikipedia:Symmetric_cryptography|symmetric cryptography]]. More specifically, each YubiKey contains a 128-bit [[Wikipedia:Advanced_Encryption_Standard|AES]] key unique to that device, which is also stored on a validation server. When asked for a password, the YubiKey will create a token by concatenating different fields such as the ID of the key, a counter, and a random number, and encrypting the result.<br />
<br />
This OTP is sent to the target system, which passes it to a validation server. The validation server (also in posession of the secret key) decrypts it and verifies the information inside. The result is returned to the target system, which can then decide whether to grant access.<br />
<br />
==== YubiCloud and validation servers ====<br />
<br />
Yubico provides a validation server with free unlimited access, called YubiCloud. YubiCloud knows the factory configuration of all YubiKeys, and is the "default" validation service used by (for example) {{pkg|yubico-pam}}. Yubico also offers [https://developers.yubico.com/Software_Projects/Yubico_OTP/YubiCloud_Validation_Servers/ open-source implementations] of the server.<br />
<br />
{{Note|To authenticate the Yubico validation server, you can use:<br />
* '''HMAC''': use https://upgrade.yubico.com/getapikey/ to get an HMAC key and ID<br />
* '''HTTPS''': the validation server's certificate is signed by GoDaddy, and is thus trusted by default in Arch installs (at least if you have {{pkg|ca-certificates}} installed)}}<br />
<br />
==== Configuration and usage ====<br />
<br />
Generate a new key in slot 2, and upload it to YubiCloud (opens in a browser):<br />
<br />
$ ykman otp yubiotp --generate-key --upload 2<br />
<br />
For more information, see {{ic|$ ykman otp yubiotp --help}}<br />
<br />
==== Security risks ====<br />
<br />
===== AES key compromise =====<br />
<br />
As you can imagine, the AES key should be kept secret. It cannot be retrieved from the YubiKey itself (or it should not, at least not with software). It is also present in the validation server, so the security of this server is very important.<br />
<br />
===== Validation requests/responses tampering =====<br />
<br />
Since the target system relies on a validation server, a possible attack would be to impersonate it. To prevent this, the target system needs to authenticate the validation server, either using HMAC or HTTPS.<br />
<br />
=== Challenge-response ===<br />
<br />
A challenge is sent to the YubiKey, which calculates a response based on some secret. The same challenge always results in the same response. Without the secret this calculation is not feasible, even with many challenge-response pairs.<br />
<br />
This can be used for<br />
* True 2-factor authentication: The user is provided a challenge, they must provide the correct response in addition to a password. Both parties must have the secret key. <br />
* "Semi" 2-factor authentication: the challenge acts as a password, and the server stores the correct response. This is not an OTP, and if anyone can obtain the response they will gain access, but it is simpler as the server does not need the secret key.<br />
<br />
There are two Challenge-Response algorithms:<br />
* HMAC-SHA1<br />
* Yubico OTP<br />
<br />
You can set them up with a GUI using the {{pkg|yubikey-personalization-gui}}, or with the following instructions:<br />
<br />
==== HMAC-SHA1 algorithm ====<br />
<br />
Set up slot 2 in challenge response mode with a generated key:<br />
<br />
$ ykman otp chalresp --generate 2<br />
<br />
You can omit the {{ic|--generate}} flag in order to provide a key. For more information, see {{ic|$ ykman otp chalresp --help}}<br />
<br />
==== Yubico OTP algorithm ====<br />
<br />
{{ic|ykman}} Does not appear to support setting the chal-yubico algorithm, but you can use {{ic|ykpersonalize}}. Generate a random key in slot 2:<br />
<br />
$ ykpersonalize -2 -ochal-resp -ochal-yubico<br />
<br />
For more information, see {{man|1|ykpersonalize}}.<br />
<br />
==== Sending a challenge ====<br />
<br />
To send a challenge and get a response:<br />
<br />
{{bc|ykchalresp -<SLOT NUMBER> <CHALLENGE>}}<br />
<br />
=== OATH ===<br />
<br />
The older OATH method uses the OTP slots, but if your key supports the newer API you likely want to use it instead. See the [[#OATH]] section for details.<br />
<br />
=== Static password ===<br />
<br />
You can either generate a static password:<br />
<br />
ykman otp static --generate <SLOT NUMBER><br />
<br />
or provide one:<br />
<br />
ykman otp static <SLOT NUMBER> <PASSWORD><br />
<br />
You have several options; you can set the length and character set of the generated password, and whether or not to send an Enter keystroke. See {{ic|ykman otp static --help}} for more.<br />
<br />
=== Emulated USB keyboard limitations, or "Why does my password look so weak?" ===<br />
<br />
In order for the YubiKey to work with most keyboard layouts, passwords are by default limited to the ModHex alphabet ({{ic|cbdefghijklnrtuv}}), digits {{ic|0-9}}, and {{ic|!}}. These characters use the same scan codes across a very large number of keyboard layouts, ensuring compatibility with most computers.<br />
<br />
Yubico has provided a [https://www.yubico.com/wp-content/uploads/2015/11/Yubico_WhitePaper_Static_Password_Function.pdf whitepaper] on the subject.<br />
<br />
== OATH ==<br />
<br />
[[Wikipedia:Initiative_for_Open_authentication|OATH]] comes in 2 flavors, both based on a shared secret: <br />
; HOTP: HMAC (Hash-based message authentication code) based one-time-password ([[Wikipedia:HMAC-based_One-time_Password_algorithm|HOTP]]). Every time a key is generated, the YubiKey increments a counter. It concatenates a secret key and this counter, and hashes this result. The server increments a counter every time a key is successfully authenticated. To handle desynchronization, the server can also check several (30-100) additional values beyond its current counter state.<br />
; TOTP: Time-based one-time-password ([[Wikipedia:Time-based_One-time_Password_algorithm|TOTP]]), which works much like HOTP except it uses the current time instead of a counter. Since the YubiKey does not have an internal clock, it must be provided with the current time (handled automatically by most tools). This is the same algorithm that Google Authenticator and other common mobile-based 2-factor applications use.<br />
<br />
Both use a base32-encoded key of arbitrary length. To generate one, you can use something like the following:<br />
<br />
$ head -c 16 /dev/urandom | base32 --wrap 0<br />
<br />
To use a provided key, you first need to acquire the base32 shared secret. One way to do this is to decode the provided QR code, which can be accomplished with the {{ic|zbarimg}} tool from {{Pkg|zbar}}. This is what you are looking for:<br />
<br />
otpauth://totp/label%3Ausername?secret=ABCD1234AAAAAAAA&issuer=issuer<br />
^^^^^^^^^^^^^^^^<br />
<br />
The YubiKey offers 2 implementations:<br />
; OATH API: Newer method, can store approximately 30 credentials depending on the model. (YubiKey 4, NEO, and newer)<br />
; OTP slot: Older method, both OTP slots can store a single credential. (All models which support challenge-response)<br />
<br />
=== OATH API ===<br />
<br />
If you prefer a GUI, you can use {{Pkg|yubioath-desktop}}.<br />
<br />
{{ic|ykman}} can add codes in the URI format with {{ic|ykman oath uri}}. Here is a one-liner that will add a credential from an image of a QR code:<br />
<br />
$ zbarimg qr_code.png --quiet --raw | xargs ykman oath uri<br />
<br />
You can also do things manually. Program a TOTP key, requiring a button touch to generate a code:<br />
<br />
$ ykman oath add --touch (name) (secret)<br />
<br />
Program an HOTP key:<br />
<br />
$ ykman oath add --oath-type HOTP (name) (secret)<br />
<br />
List credentials:<br />
<br />
$ ykman oath list<br />
<br />
Generate codes:<br />
<br />
$ ykman oath code (query)<br />
<br />
To see all available subcommands see {{ic|ykman oath --help}}. To see information about each, use {{ic|ykman oath (subcommand) --help}}.<br />
<br />
=== OTP slot implementation ===<br />
<br />
Program an HOTP in slot 2:<br />
<br />
$ ykman otp hotp 2 (key)<br />
<br />
Program a TOTP:<br />
<br />
$ ykman otp chalresp --totp (slot number) (key)<br />
<br />
Generate an HOTP:<br />
<br />
$ ykman otp calculate (slot number)<br />
<br />
Generate a TOTP:<br />
<br />
$ ykman otp calculate --totp (slot number)<br />
<br />
See also: {{ic|ykman otp --help}}, and https://developers.yubico.com/OATH/<br />
<br />
== U2F ==<br />
<br />
[[Universal_2nd_Factor|Universal 2nd Factor]] (U2F) with a YubiKey is very simple, requiring no configuration for the key itself. Note that this mode is also referred to as 'FIDO' in some documentation and utilities. You have a few limited management options through the {{ic|ykman}} utility: <br />
* Set a PIN: {{ic|$ ykman fido set-pin}}<br />
* delete individual credentials: {{ic|$ ykman fido delete <QUERY>}}<br />
* Reset all credentials and PIN: {{ic|$ ykman fido reset}}<br />
<br />
To use U2F for authentication, see the instructions in [[Universal_2nd_Factor|U2F]].<br />
<br />
== CCID smartcard ==<br />
<br />
CCID (Chip Card Interface Device) is a USB standard device class for use by USB devices that act as smart card readers or with security tokens that connect directly via USB, like the YubiKey. HID (Human Interface Device) and CCID are both USB device classes, i.e. they are in the same category of USB specifications. HID is a specification for computer peripherals, like keyboards. The YubiKey works like a USB (HID) keyboard when used in the OTP and FIDO modes, but switches to the CCID protocol when using the PIV application, or as an OpenPGP device.<br />
<br />
CCID mode should be enabled by default on all YubiKeys shipped since November 2015 [https://www.yubico.com/support/knowledge-base/categories/articles/use-yubikey-yubikey-windows-hello-app/]. Enable at least the CCID mode. Please see [[#Set the enabled modes]].<br />
<br />
=== PIV ===<br />
<br />
Starting with the YubiKey NEO, the YubiKeys contain a PIV (Personal Identity Verification) application on the chip. PIV is a US government standard (FIPS 201) that specifies how a token using RSA or ECC (Elliptic Curve Cryptography) is used for personal electronic identification. The YubiKey NEO only supports RSA encryption, later models (YubiKey 4 and 5) support both RSA and ECC. The distinguishing characteristic of a PIV token is that it is built to protect private keys and operate on-chip. A private key never leaves the token after it has been installed on it. Optionally, the private key can even be generated on-chip with the aid of an on-chip random number generator. If generated on-chip, the private key is never handled outside of the chip, and there is no way to recover it from the token. When using the PIV mechanism, the YubiKey functions as a CCID device.<br />
<br />
=== OpenPGP smartcards ===<br />
<br />
The YubiKey can act as a standard GPG smartcard; see the [[GnuPG#Smartcards|GPG Smartcard]] section for instructions on how to set up and use it. Yubico also provides some documentation [https://developers.yubico.com/PGP/ here].<br />
<br />
If you do not want to use the other features (U2F and OTP), the button can be configured to insert and eject it, and an auto-eject timeout can be set as well. See [[#USB connection modes]] for more.<br />
<br />
The default user pin is {{ic|123456}} and the default admin pin is {{ic|12345678}}.<br />
<br />
== Use cases ==<br />
<br />
This section details how to use your YubiKey for various authentication purposes. It is by no means an exhaustive list.<br />
<br />
=== Full disk encryption with LUKS ===<br />
<br />
You have several options:<br />
<br />
* '''Challenge-Response:''' the [[#Challenge-response|response]] to some challenge is used as a LUKS key. The challenge can act as a password for true 2-factor authentication, or stored in plain-text for one-factor authentication.<br />
* '''GnuPG:''' Uses the yubikey's [[#CCID_Smartcard|PGP smartcard]] functionality. Offers strong 2-factor authentication without needing a huge passphrase.<br />
* '''FIDO HMAC Secret:''' If your YubiKey supports [[U2F]], it can be configured to return a symmetric secret when given some passphrase.<br />
<br />
{{Note|A disk's encryption is only as strong as its weakest key. Once you configure one of these tools, consider removing the initial passphrase, or replacing it with a very long one.}}<br />
<br />
==== Common prerequisites ==== <br />
<br />
* A bootable [[dm-crypt/Encrypting_an_entire_system|LUKS encrypted]] system, using the {{ic|encrypt}} [[mkinitcpio]] hook, with at least one free keyslot. <br />
** The {{ic|sd-encrypt}} hook is not supported by any of these tools.<br />
* Backed up LUKS header (Optional, though advisable)<br />
<br />
==== Challenge-response ====<br />
<br />
See {{Pkg|yubikey-full-disk-encryption}}'s [https://github.com/agherzan/yubikey-full-disk-encryption#usage official documentation] for complete instructions. Broadly:<br />
<br />
# Install {{Pkg|yubikey-full-disk-encryption}}<br />
# Configure {{ic|/etc/ykfde.conf}}<br />
# Enroll the disk: {{ic|# ykfde-enroll -d /dev/<DISK> -s <LUKS_SLOT>}}<br />
# Add the {{ic|ykfde}} [[mkinitcpio#HOOKS|mkinitcpio hook]] before the {{ic|encrypt}} hook. <br />
# Regenerate the initramfs: {{ic| # mkinitcpio -P}}<br />
<br />
:{{Note|Plymouth Users: Replace the {{ic|plymouth-encrypt}} hook with the {{ic|ykfde}} hook.}}<br />
<br />
There are a few variations available:<br />
<br />
* 2FA: default behavior. You must provide the challenge as a password when enrolling the device, and upon boot.<br />
* 1FA: Set {{ic|YKFDE_CHALLENGE}} in {{ic|ykfde.conf}}. Note that this is stored in plaintext. Consider disabling non-root read permissions to this file.<br />
* [https://github.com/agherzan/yubikey-full-disk-encryption#enable-nfc-support-in-ykfde-initramfs-hook-experimental NFC support] (Experimental)<br />
* [https://github.com/agherzan/yubikey-full-disk-encryption#enable-ykfde-suspend-service-experimental Suspend & Resume support] (Experimental) Automatically lock encrypted volumes on suspend, unlock them on resume.<br />
<br />
You must regenerate the initramfs for any configuration changes to take effect.<br />
<br />
==== GnuPG encrypted keyfile ====<br />
<br />
One tool to accomplish this is [https://github.com/fuhry/initramfs-scencrypt initramfs-scencrypt]; see its docs for complete instructions. Note that as of October 2020 this package is not in the AUR and is not thoroughly tested, though the GitHub repo offers a PKGBUILD.<br />
<br />
The [[Dm-crypt/Specialties#Using_GPG,_LUKS,_or_OpenSSL_Encrypted_Keyfiles|dm-crypt pages]] offer a few alternatives, though they are mostly links to old forum posts.<br />
<br />
==== HMAC secret extension of FIDO2 protocol ====<br />
<br />
Yet another way of using YubiKey for full disk encryption is to utilize [https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#sctn-hmac-secret-extension HMAC Secret Extension] to retrieve the LUKS password from YubiKey which is protected by passphrase supplied by user. This functionality requires at least [https://support.yubico.com/support/solutions/articles/15000027138-yubikey-5-2-3-enhancements-to-fido-2-support YubiKey 5 with firmware 5.2.3+].<br />
<br />
In order to use this install {{AUR|fido2-hmac-secret}} and follow instructions available in [https://github.com/mjec/fido2-hmac-secret/wiki/Arch-Linux-LUKS-configuration project documentation].<br />
<br />
=== KeePass ===<br />
<br />
[[KeePass]] can be configured for YubiKey support; see the [[KeePass#Yubikey|YubiKey section]] for instructions.<br />
<br />
=== SSH keys ===<br />
<br />
If your yubikey supports CCID smartcards, you can use it as a hardware-backed [[SSH key]], either based on GPG or PIV keys. Yubico offers good documentation:<br />
* An [https://developers.yubico.com/PIV/Guides/Securing_SSH_with_OpenPGP_or_PIV.html overview of both] possibilities, giving their advantages and disadvantages<br />
* Instructions for [https://developers.yubico.com/PGP/SSH_authentication/index.html PGP authentication]<br />
* Instructions for [https://developers.yubico.com/PIV/Guides/SSH_user_certificates.html PIV authentication through user certificates]<br />
* Instructions for [https://developers.yubico.com/PIV/Guides/SSH_with_PIV_and_PKCS11.html PIV authentication through #PKCS11]<br />
<br />
:{{Note|The default PIN code of the PIV application on the YubiKey is {{ic|123456}}; you may want to change it, as well as the default management key. See the [https://developers.yubico.com/PIV/Guides/Device_setup.html device setup instructions] for more.}}<br />
<br />
=== Linux user authentication with PAM ===<br />
<br />
[[PAM]], and therefore anything which uses PAM for user authentication, can be configured to use a YubiKey as a factor of its user authentication process. This includes sudo, su, ssh, screen lockers, display managers, and nearly every other instance where a Linux system needs to authenticate a user. Its flexible configuration allows you to set whichever authentication requirements fit your needs, for the entire system, a specific application, or for groups of applications. For example, you could accept the YubiKey as an alternative to a password for local sessions, while requiring both for remote sessions. In addition to the Arch Wiki, You are encouraged to read {{man|8|pam}} and {{man|5|pam.conf}} to understand how it works and how to configure it.<br />
<br />
There are several modules available which integrate YubiKey-supported protocols into PAM:<br />
* {{Pkg|pam-u2f}} - Supports [[#U2F]] via the FIDO2 standard. If you are not sure which method to use, this one is a good choice.<br />
** [[Universal_2nd_Factor#Authentication_for_Arch_Linux|Arch Wiki Instructions]]<br />
** [https://developers.yubico.com/pam-u2f/ Yubico's official docs], including a list of supported module parameters.<br />
** Man Pages: {{Man|8|pam_u2f}}, {{Man|1|pamu2fcfg}}<br />
* {{Pkg|oath-toolkit}} - Supports [[#OATH]] one-time passwords (either HOTP or TOTP) <br />
** [[pam_oath]]<br />
* {{Pkg|yubico-pam}} - Supports [[#Yubico OTP]] and challenge-response OTPs. Note that Yubico OTP mode requires a network connection to a validation server, while challenge-response mode does not.<br />
** [https://developers.yubico.com/yubico-pam/ Yubico's official docs]<br />
** {{Man|8|pam_yubico}} - Take note of the {{ic|mode}} parameter, used to set challenge-response mode.<br />
<br />
{{Warning|Exercise caution when modifying PAM configuration files. Mistakes can render a system completely insecure, or so secure that no authentication is possible.}}<br />
<br />
PAM configuration is beyond the scope of this article, but for a brief overview:<br />
* Create file(s) containing authorized keys, either in users' home directories or centrally.<br />
* Add a line in the appropriate place in the appropriate PAM configuration file which follows this format:<br />
auth [required|sufficient] [module_name].so [module arguments]<br />
* {{ic|auth required}} for multifactor, {{ic|auth sufficient}} for single factor.<br />
* {{ic|module_name}} - Example: {{ic|pam_u2f.so}}. See a list of installed modules: {{ic| $ ls /usr/lib/security }}<br />
* Module configuration arguments are for things like the location of the keyfile, or which method the module should use for authentication.<br />
<br />
==== SSH notes ====<br />
<br />
* Yubico has provided [https://developers.yubico.com/yubico-pam/Yubikey_and_SSH_via_PAM.html additional guidance]. It's written for an old version of Ubuntu, but much of it still applies to an updated Arch system.<br />
* If you are configuring a distant server to use YubiKey, you should open at least one additional, rescue SSH session, so that you are not locked out if the configuration fails.<br />
* Check that {{ic|/etc/ssh/sshd_config}} contains the following settings. The {{ic|sshd_config}} shipped with {{pkg|openssh}} has these set correctly by default.<br />
ChallengeResponseAuthentication no<br />
UsePAM yes<br />
<br />
=== Browser/web integration ===<br />
<br />
Many web services are beginning to support FIDO hardware tokens. See the [[U2F]] page for more information, but usually the only thing you need to do is to install {{Pkg|libfido2}} and [https://demo.yubico.com/webauthn-technical/registration try it].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Executing actions on insertion/removal of YubiKey device ===<br />
<br />
For example, you want to perform an action when you pull your YubiKey out of the USB slot, create {{ic|/etc/udev/rules.d/80-yubikey-actions.rules}} and add the following contents:<br />
ACTION=="remove", ENV{ID_VENDOR}=="Yubico", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0010|0111|0112|0113|0114|0115|0116|0401|0402|0403|0404|0405|0406|0407|0410", RUN+="/usr/local/bin/script args"<br />
<br />
Please note, most keys are covered within this example but it may not work for all versions of YubiKey. You will have to look at the output of lsusb to get the vendor and model ID's, along with the description of the device or you could use udevadm to get information. Of course, to execute a script on insertion, you would change the action to 'add' instead of remove.<br />
<br />
== Maintenance / upgrades ==<br />
<br />
=== Installing the OATH Applet for a YubiKey NEO ===<br />
<br />
These steps will allow you to install the OATH applet onto your YubiKey NEO. This allows the use of Yubico Authenticator in the Google Play Store.<br />
{{Note|1=These steps are only for NEOs with a firmware version <= 3.1.2. The current generation NEOs (with U2F) come with the OpenPGP applet already installed)}}<br />
<br />
==== Configure the NEO as a CCID device ====<br />
<br />
# Install {{pkg|yubikey-personalization-gui}} ({{AUR|yubikey-personalization-gui-git}}).<br />
# Add the udev rules and reboot so you can manage the YubiKey without needing to be root<br />
# Run {{ic|ykpersonalize -m82}}, enter {{ic|y}}, and hit enter.<br />
<br />
==== Install the applet ====<br />
<br />
# Install {{AUR|gpshell}}, {{AUR|gppcscconnectionplugin}}, {{AUR|globalplatform}}, and {{Pkg|pcsclite}}.<br />
# [[Start]] {{ic|pcscd.service}}.<br />
# Download the most recent CAP file from the [http://opensource.yubico.com/ykneo-oath/releases.html ykneo-oath] site.<br />
# Download {{ic|gpinstall.txt}} from [https://github.com/Yubico/ykneo-oath/blob/master/gpinstall.txt GitHub].<br />
# Edit the line in gpinstall.txt beginning with {{ic|install -file}} to reflect the path where the CAP file is located.<br />
# Open a terminal and run {{ic| gpshell <location of gpinstall.txt>}}<br />
# Ideally, a bunch of text will scroll by and it ends saying something like<br />
{{ bc | Command --> 80E88013D7C000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A100<br />
Wrapped command --> 84E88013DFC000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A15D848CB77<br />
27D0EDA00<br />
Response <-- 009000<br />
Command --> 80E60C002107A000000527210108A00000052721010108A000000527210101010003C901000000<br />
Wrapped command --> 84E60C002907A000000527210108A00000052721010108A000000527210101010003C9010000B4648127914A4C7C00<br />
Response <-- 009000<br />
card_disconnect<br />
release_context}}<br />
# Unplug the NEO and try it with the Yubico Authenticator app<br />
<br />
==== (Optional) Install the Yubico Authenticator desktop client ====<br />
<br />
You can get the desktop version of the Yubico Authenticator by installing {{Pkg|yubioath-desktop}}.<br />
<br />
While {{ic|pcscd.service}} is running, run {{ic|yubioath-desktop}} and insert your YubiKey when prompted.<br />
<br />
== Troubleshooting ==<br />
<br />
Restart, especially if you have completed updates since your YubiKey last worked. Do this even if some functions appear to be functioning.<br />
<br />
=== YubiKey not acting as HID device ===<br />
{{Note|1=These steps are no longer necessary after [https://github.com/systemd/systemd/commit/d45ee2f31a8358db0accde2e7c81777cedadc3c2 systemd since v244] added native support for this functionality.}}<br />
<br />
Add udev rule as described in [https://michaelheap.com/yubikey-on-arch/ this article]:<br />
<br />
{{hc|/etc/udev/rules.d/10-security-key.rules|2=<br />
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="users", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0"<br />
}}<br />
<br />
Run {{ic|udevadm trigger}} afterwards.<br />
<br />
You may also need to [[install]] the package {{pkg|libu2f-host}} if you want support in chrome.<br />
<br />
=== ykman fails to connect to the YubiKey ===<br />
<br />
If the manager fails to connect to the YubiKey, make sure you have started {{ic|pcscd.service}} or {{ic|pcscd.socket}}.<br />
<br />
=== Error: Failed connecting to YubiKey 5 [OTP+FIDO+CCID]. Make sure the application have the required permissions. ===<br />
<br />
This can occur when using {{ic|ykman}} to access the oath credentials on the device if {{ic|scdaemon}} has already taken exclusive control of the device. [https://github.com/Yubico/yubikey-manager/issues/35]<br />
<br />
To fix this you can set the {{ic|reader-port}} option with the correct value for your device in {{ic|~/.gnupg/scdaemon.conf}}. [https://support.yubico.com/support/solutions/articles/15000014892-troubleshooting-gpg-no-such-device-]<br />
<br />
{{Note|This will cause the gpgagent to re-prompt you to unlock the YubiKey after each time you access the YubiKey through ykman.}}<br />
<br />
For YubiKey NEO and YubiKey 4:<br />
reader-port Yubico Yubikey<br />
or for YubiKey 5<br />
reader-port Yubico Yubi<br />
<br />
=== YubiKey fails to bind within a guest VM ===<br />
<br />
Assuming the YubiKey is available to the guest, the issue results from a driver binding to the device on the host. To unbind the device, the bus and port information is needed from {{ic|dmesg}} on the host:<br />
<br />
$ dmesg | grep -B1 Yubico | tail -n 2 | head -n 1 | sed -E 's/^\<nowiki>[[^]]</nowiki>+\] usb (<nowiki>[^:]</nowiki>*):.*/\1/'<br />
<br />
The resulting USB id should be of the form {{ic|X-Y.Z}} or {{ic|X-Y}}. Then, on the host, use {{ic|find}} to search {{ic|/sys/bus/usb/drivers}} for which driver the YubiKey is binded to (e.g. {{ic|usbhid}} or {{ic|usbfs}}).<br />
<br />
$ find /sys/bus/usb/drivers -name "*X-Y.Z*"<br />
<br />
To unbind the device, use the result from the previous command (i.e. {{ic|/sys/bus/usb/drivers/<DRIVER>/X-Y.Z:1.0}}):<br />
<br />
# echo 'X-Y.Z:1.0' > /sys/bus/usb/drivers/<DRIVER>/unbind<br />
<br />
=== Error: [key] could not be locally signed or gpg: No default secret key: No public key ===<br />
<br />
Occurs when attempting to sign keys on a non-standard keyring while a YubiKey is plugged in, e.g. as [[Pacman/Package_signing|Pacman]] does in {{ic|pacman-key --populate archlinux}}. The solution is to remove the offending YubiKey and start over.<br />
<br />
=== YubiKey disappears and reappears in Yubico Authenticator ===<br />
<br />
This happens when the CCID driver is not installed. You may need to [[install]] the {{pkg|ccid}} package.<br />
<br />
=== YubiKey core error: timeout ===<br />
<br />
You are probably using the wrong slot. Try the other one.</div>Tepleshttps://wiki.archlinux.org/index.php?title=Go_package_guidelines&diff=614705Go package guidelines2020-05-21T12:16:51Z<p>Teples: /* Sample PKGBUILD */ Fix buildflags order in template similar as below</p>
<hr />
<div>[[Category:Arch package guidelines]]<br />
[[ja:Go パッケージガイドライン]]<br />
[[pt:Go package guidelines]]<br />
[[zh-hans:Go package guidelines]]<br />
{{Package guidelines}}<br />
<br />
This document covers standards and guidelines on writing [[PKGBUILD]]s for [[Go]].<br />
<br />
== General guidelines ==<br />
<br />
=== Package naming ===<br />
<br />
For [[Go]] library modules, use {{ic|golang-''modulename''}}. Also use the prefix if the package provides a program that is strongly coupled to the Go ecosystem. For other applications, use only the program name.<br />
<br />
{{Note|The package name should be entirely lowercase.}}<br />
<br />
== Building ==<br />
<br />
=== Dependencies ===<br />
<br />
Go 1.11 introduced the initial support for [https://github.com/golang/go/wiki/Modules go modules]. This allows Go upstream code to declare dependencies and pin them to the given project version. Currently our packaging efforts utilizes this to vendor dependencies.<br />
<br />
=== Flags and build options ===<br />
<br />
Most Makefiles written for go applications do not respect the build flags provided by build systems along with overwriting {{ic|GOFLAGS}}, this causes Go binaries to not be compiled with [https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro RELRO] as we need {{ic|CGO_CFLAGS}} and {{ic|CGO_LDFLAGS}} to be set for the compiler. This needs to be patched into the Makefile, or the Makefile should be omitted.<br />
<br />
{{bc|<nowiki><br />
export CGO_CPPFLAGS="${CPPFLAGS}"<br />
export CGO_CFLAGS="${CFLAGS}"<br />
export CGO_CXXFLAGS="${CXXFLAGS}"<br />
export CGO_LDFLAGS="${LDFLAGS}"<br />
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"<br />
<br />
<br />
# or alternatively you can define some of these flags from the CLI options<br />
go build \<br />
-trimpath \<br />
-buildmode=pie \<br />
-mod=readonly \<br />
-modcacherw \<br />
-ldflags "-extldflags ${LDFLAGS}" \<br />
.<br />
</nowiki>}}<br />
<br />
===== Flag Meaning: =====<br />
* {{ic|<nowiki>-buildmode=pie</nowiki>}} enables [https://en.wikipedia.org/wiki/Position-independent_code PIE compilation] for binary harderning.<br />
* {{ic|-trimpath}} important for [https://reproducible-builds.org/ reproducible builds] so full build paths and module paths are not embedded.<br />
* {{ic|<nowiki>-mod=readonly</nowiki>}} ensure the module files are not updated in any go actions.<br />
* {{ic|-modcacherw}} is not important, but it ensures that go modules creates a write-able path. Default is read-only.<br />
<br />
{{Warning|It's up to the packager to verify the build flags are passed correctly to the compiler. Read the {{ic|Makefile}} if there is one}}<br />
<br />
=== Output directory ===<br />
<br />
There are currently a few ways to build all go binaries in a project.<br />
{{bc|<nowiki><br />
build(){<br />
cd "$pkgname-$pkgver"<br />
go build -o output-binary .<br />
}<br />
</nowiki>}}<br />
<br />
{{ic|...}} is a shorthand for the compiler to recursively descend into the directory and find all binaries. It can be used in conjunction with a output directory to build everything.<br />
<br />
{{bc|<nowiki><br />
prepare(){<br />
cd "$pkgname-$pkgver"<br />
mkdir -p build<br />
}<br />
<br />
build(){<br />
cd "$pkgname-$pkgver"<br />
go build -o build ./cmd/...<br />
}<br />
</nowiki>}}<br />
<br />
== Sample PKGBUILD ==<br />
<br />
{{bc|<nowiki><br />
pkgname=foo<br />
pkgver=0.0.1<br />
pkgrel=1<br />
pkgdesc='Go PKGBUILD Example'<br />
arch=('x86_64')<br />
url="https://example.org/$pkgname"<br />
license=('GPL')<br />
makedepends=('go')<br />
source=("$url/$pkgname-$pkgver.tar.gz")<br />
sha256sums=('1337deadbeef')<br />
<br />
prepare(){<br />
cd "$pkgname-$pkgver"<br />
mkdir -p build/<br />
}<br />
<br />
build() {<br />
cd "$pkgname-$pkgver"<br />
export CGO_CPPFLAGS="${CPPFLAGS}"<br />
export CGO_CFLAGS="${CFLAGS}"<br />
export CGO_CXXFLAGS="${CXXFLAGS}"<br />
export CGO_LDFLAGS="${LDFLAGS}"<br />
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"<br />
go build -o build ./cmd/...<br />
}<br />
<br />
check() {<br />
cd "$pkgname-$pkgver"<br />
go test ./...<br />
}<br />
<br />
package() {<br />
cd "$pkgname-$pkgver"<br />
install -Dm755 build/$pkgname "$pkgdir"/usr/bin/$pkgname<br />
}<br />
</nowiki>}}<br />
<br />
== Example packages ==<br />
<br />
* {{Pkg|podman}}<br />
* {{Pkg|k9s}}<br />
* {{Pkg|helm}}</div>Tepleshttps://wiki.archlinux.org/index.php?title=Go_package_guidelines&diff=614384Go package guidelines2020-05-19T12:25:33Z<p>Teples: /* Flags and build options */ make flag order more logical same as it's set in Compiler and Linker Flags in makepkg.conf</p>
<hr />
<div>[[Category:Arch package guidelines]]<br />
[[ja:Go パッケージガイドライン]]<br />
[[pt:Go package guidelines]]<br />
[[zh-hans:Go package guidelines]]<br />
{{Package guidelines}}<br />
<br />
This document covers standards and guidelines on writing [[PKGBUILD]]s for [[Go]].<br />
<br />
== General guidelines ==<br />
<br />
=== Package naming ===<br />
<br />
For [[Go]] library modules, use {{ic|golang-''modulename''}}. Also use the prefix if the package provides a program that is strongly coupled to the Go ecosystem. For other applications, use only the program name.<br />
<br />
{{Note|The package name should be entirely lowercase.}}<br />
<br />
== Building ==<br />
<br />
=== Dependencies ===<br />
<br />
Go 1.11 introduced the initial support for [https://github.com/golang/go/wiki/Modules go modules]. This allows Go upstream code to declare dependencies and pin them to the given project version. Currently our packaging efforts utilizes this to vendor dependencies.<br />
<br />
=== Flags and build options ===<br />
<br />
Most Makefiles written for go applications do not respect the build flags provided by build systems along with overwriting {{ic|GOFLAGS}}, this causes Go binaries to not be compiled with [https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro RELRO] as we need {{ic|CGO_CFLAGS}} and {{ic|CGO_LDFLAGS}} to be set for the compiler. This needs to be patched into the Makefile, or the Makefile should be omitted.<br />
<br />
{{bc|<nowiki><br />
export CGO_CPPFLAGS="${CPPFLAGS}"<br />
export CGO_CFLAGS="${CFLAGS}"<br />
export CGO_CXXFLAGS="${CXXFLAGS}"<br />
export CGO_LDFLAGS="${LDFLAGS}"<br />
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"<br />
<br />
<br />
# or alternatively you can define some of these flags from the CLI options<br />
go build \<br />
-trimpath \<br />
-buildmode=pie \<br />
-mod=readonly \<br />
-modcacherw \<br />
-ldflags "-extldflags ${LDFLAGS}" \<br />
.<br />
</nowiki>}}<br />
<br />
===== Flag Meaning: =====<br />
* {{ic|<nowiki>-buildmode=pie</nowiki>}} enables [https://en.wikipedia.org/wiki/Position-independent_code PIE compilation] for binary harderning.<br />
* {{ic|-trimpath}} important for [https://reproducible-builds.org/ reproducible builds] so full build paths and module paths are not embedded.<br />
* {{ic|<nowiki>-mod=readonly</nowiki>}} ensure the module files are not updated in any go actions.<br />
* {{ic|-modcacherw}} is not important, but it ensures that go modules creates a write-able path. Default is read-only.<br />
<br />
{{Warning|It's up to the packager to verify the build flags are passed correctly to the compiler. Read the {{ic|Makefile}} if there is one}}<br />
<br />
=== Output directory ===<br />
<br />
There are currently a few ways to build all go binaries in a project.<br />
{{bc|<nowiki><br />
build(){<br />
cd "$pkgname-$pkgver"<br />
go build -o output-binary .<br />
}<br />
</nowiki>}}<br />
<br />
{{ic|...}} is a shorthand for the compiler to recursively descend into the directory and find all binaries. It can be used in conjunction with a output directory to build everything.<br />
<br />
{{bc|<nowiki><br />
prepare(){<br />
cd "$pkgname-$pkgver"<br />
mkdir -p build<br />
}<br />
<br />
build(){<br />
cd "$pkgname-$pkgver"<br />
go build -o build ./cmd/...<br />
}<br />
</nowiki>}}<br />
<br />
== Sample PKGBUILD ==<br />
<br />
{{bc|<nowiki><br />
pkgname=foo<br />
pkgver=0.0.1<br />
pkgrel=1<br />
pkgdesc='Go PKGBUILD Example'<br />
arch=('x86_64')<br />
url="https://example.org/$pkgname"<br />
license=('GPL')<br />
makedepends=('go')<br />
source=("$url/$pkgname-$pkgver.tar.gz")<br />
sha256sums=('1337deadbeef')<br />
<br />
prepare(){<br />
cd "$pkgname-$pkgver"<br />
mkdir -p build/<br />
}<br />
<br />
build() {<br />
cd "$pkgname-$pkgver"<br />
export CGO_LDFLAGS="${LDFLAGS}"<br />
export CGO_CFLAGS="${CFLAGS}"<br />
export CGO_CPPFLAGS="${CPPFLAGS}"<br />
export CGO_CXXFLAGS="${CXXFLAGS}"<br />
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"<br />
go build -o build ./cmd/...<br />
}<br />
<br />
check() {<br />
cd "$pkgname-$pkgver"<br />
go test ./...<br />
}<br />
<br />
package() {<br />
cd "$pkgname-$pkgver"<br />
install -Dm755 build/$pkgname "$pkgdir"/usr/bin/$pkgname<br />
}<br />
</nowiki>}}<br />
<br />
== Example packages ==<br />
<br />
* {{Pkg|podman}}<br />
* {{Pkg|k9s}}<br />
* {{Pkg|helm}}</div>Tepleshttps://wiki.archlinux.org/index.php?title=YubiKey&diff=596912YubiKey2020-02-06T20:15:12Z<p>Teples: /* Challenge-Response mode for LUKS passphrase (systemd/sd-encrypt) */ clarify project info</p>
<hr />
<div>[[Category:Authentication]]<br />
[[ja:Yubikey]]<br />
{{Accuracy|The article lacks sources, is interspersed with TODOs and probably out of date.}}<br />
{{Style|ykman-specifics should be grouped together.}}<br />
This article describes how [https://yubico.com Yubico]'s [[Wikipedia:YubiKey|YubiKey]] works and how you can use it.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the warning under [[#Initial configuration]].}}<br />
<br />
== Introduction ==<br />
<br />
The YubiKey is a small [[Wikipedia:Security token|USB Security token]] that supports:<br />
<br />
* generating [[Wikipedia:One-time password|one-time passwords]] (OTP) - using either AES based Yubico OTP algorithm or OATH-HOTP following RFC 4226<br />
* outputting a up to 63 char long static password<br />
* handling [[Wikipedia:Challenge–response authentication|challenge-response requests]], using either Yubico OTP mode or HMAC-SHA1 mode<br />
* handling [[Wikipedia:Universal_2nd_Factor|Universal 2nd Factor]] (U2F) requests (YubiKey 4 and YubiKey NEO)<br />
* acting as smartcard (using the [[Wikipedia:CCID (protocol)|CCID protocol]]) (YubiKey 4 and YubiKey NEO) - allowing storage of signing, encrypting, authenticating (RSA) keys to be used for instance for SSH login (authentication), Email signature/encryption, git commit signature, etc.<br />
<br />
It is manufactured by [http://www.yubico.com/ Yubico].<br />
<br />
One of its strengths is that it emulates a USB keyboard to send the OTP as text, and thus requires only USB HID drivers found on practically all desktop computers.<br />
<br />
While offering a lot of features, newer versions of the YubiKey are [https://www.yubico.com/2016/05/secure-hardware-vs-open-source/ not released as open source]. An alternative is the [[Solo]].<br />
<br />
=== Installation ===<br />
<br />
There are several packages available:<br />
<br />
* {{App|Yubico PAM|Module to integrate the YubiKey into [[PAM]].|https://developers.yubico.com/yubico-pam/|{{Pkg|yubico-pam}}}}<br />
* {{App|YubiKey Manager|Python library and command-line tool ({{ic|ykman}}) for configuring a YubiKey over all USB connections. Has optional GUI.|https://developers.yubico.com/yubikey-manager/|{{Pkg|yubikey-manager}}, {{Pkg|yubikey-manager-qt}}}}<br />
{{Note|After you install the yubikey-manager (which can be called by ykman in CLI), you need to enable {{ic|pcscd.service}} to get it running}}<br />
* {{App|Yubikey Personalization|Library and tool to configure slot features over the OTP USB connection. Has optional GUI.|https://developers.yubico.com/yubikey-personalization/|{{Pkg|yubikey-personalization}}, {{Pkg|yubikey-personalization-gui}}}}<br />
* {{App|Yubico Authenticator for Desktop|Lets you read OATH codes from your YubiKey over USB. Support the newer OATH implementation (YubiKey NEO and 4) as well as the older slot-based implementation (YubiKey Standard and Edge).|https://developers.yubico.com/OATH/YubiKey_OATH_software.html|{{Pkg|yubioath-desktop}}}}<br />
<br />
=== Understanding the YubiKey ===<br />
<br />
The YubiKey is a small USB dongle with one button and an LED to communicate with you.<br />
<br />
One of its strengths is that it can emulate a USB keyboard to send a password (OTP or static password) as text, and thus requires only USB HID drivers found on practically all computers (desktop, mobile, tablet, etc.).<br />
<br />
This also makes it vulnerable to keyloggers if the {{ic|static password}} functionality is used, which is why if possible one should avoid it and try to only use the one-time password (OTP), Challenge-Response and CCID Smartcard functionality.<br />
<br />
==== Inputs ====<br />
<br />
The YubiKey takes inputs in the form of:<br />
<br />
* API calls sent to it via the USB interface.<br />
* short button press<br />
* long button press<br />
<br />
==== Outputs ====<br />
<br />
The YubiKey transforms these inputs into outputs in the form of:<br />
<br />
* Sending keystroke keycodes (emulating a USB keyboard and typing for you) <br> This is used to:<br />
** type the static password<br />
** type the OTP<br />
<br />
* Sending back a Response via the API (over the USB interface). <br> This is used to send back:<br />
** the response of a Challenge-Response request (calculated using either Yubico OTP mode or HMAC-SHA1 mode)<br />
** the response of a U2F Challenge-Response request<br />
** the response of a CCID Smartcard related request<br />
<br />
=== The button ===<br />
<br />
The button activates by slightly touching it. Sometimes it even reacts when you are very close but are not touching it yet.<br />
<br />
Depending on the context, touching the button does one of these things:<br />
<br />
* triggering a function (like triggering the output of a static password or of a one-time password (OTP))<br />
* confirming / allowing a function or access<br />
* inserting / ejecting the smartcard<br />
<br />
In the OTP mode a short press yields slot 1 and a long press yields slot 2.<br />
<br />
=== USB connection modes ===<br />
<br />
Depending on the YubiKey model, the device provides up to three<br />
different USB interfaces with their associated protocols. Two of the<br />
interfaces implement the USB HID (Human Interface Device) device<br />
class; the third is a smart card interface (CCID). The YubiKey is a<br />
multi-function USB device, just like a USB printer that can also<br />
function as a scanner.<br />
<br />
The following table shows which interfaces the different applications<br />
use:<br />
<br />
{| class="wikitable"<br />
! Application !! USB Interface<br />
|-<br />
|OTP || Keyboard HID<br />
|-<br />
|FIDO || Other HID<br />
|-<br />
|PIV || CCID<br />
|-<br />
|OpenPGP || CCID<br />
|-<br />
|OATH || CCID<br />
|}<br />
<br />
All three interfaces can be independently enabled or disabled.<br />
The ykman program uses the term "manage connection modes" and uses<br />
OTP, FIDO, and CCID as selectors for which modes should be enabled.<br />
<br />
{{Note|The old U2F mode has been renamed and is now called FIDO in ykman 0.6.1 and later (released<br />
2018-04-16) https://developers.yubico.com/yubikey-manager/Release_Notes.html}}<br />
<br />
The set of enabled USB interfaces affects which applications on the<br />
key can be accessed. As an example, if only the HID interfaces are<br />
enabled, the applications dependent on the CCID interface are<br />
unavailable.<br />
<br />
Which application on the key is chosen is determined by the host<br />
application and is a combination of USB interface and an application<br />
selection mechanism. For example, if the host application wants to<br />
communicate with the PIV application on the key, it accesses the key<br />
using the CCID interface and using the protocols defined by CCID sends<br />
a 'select application' command to the key selecting the PIV application.<br />
<br />
==== Get enabled modes ====<br />
<br />
{{ic|ykman mode}} will tell you what modes are currently activated/enabled/available.<br />
This could output something like<br />
{{bc|Current connection mode is: OTP+U2F+CCID}}<br />
Meaning that currently the OTP, U2F and CCID subsystem of the key are enabled.<br />
<br />
==== Set the enabled modes ====<br />
<br />
{{ic|ykman mode <MODE>}} will allow you to define which modes should be activated/enabled/available. <br />
* {{ic|<MODE>}} can be a string, such as {{ic|OTP+U2F+CCID}}, or a shortened form {{ic|o+u+c}}.<br>With "+" you can combine multiple modes that you wish to be enabled.<br />
* {{ic|<MODE>}} can be a mode-number, which is one number that encodes several enabled modes (like flags) into one value.<br>The only valid modes when using numbers is 0 - 6 ([https://github.com/Yubico/yubikey-manager/blob/master/ykman/util.py#L94 see here]). The extra flags are not part of the mode in that sense, they just need to be set at the same time as the mode is set.<br />
<br />
Usually what you want is to make all functionality available (you will still need to potentially configure stuff, see functionality sections below for more details).<br />
In order to do so you can use:<br />
<br />
{{ic|ykman mode c+u+o}} or {{ic|ykman mode 6}}<br />
<br />
{{Note|Using the "80" mode-number or the corresponding {{ic|--touch-eject}} parameter of {{ic|ykman mode}} can only be used when the device is ''only'' in CCID mode (by running {{ic|ykman mode ccid --touch-eject}} for instance).<br />
<br />
Once the {{ic|--touch-eject}} flag is set, you should be able to eject/insert the smartcard by pressing the button. The LED should indicate if the card is inserted or not as well.<br />
}}<br />
<br />
{{Warning|But using the 80 mode-number or the corresponding {{ic|--touch-eject}} is not recommend as it would prevent you from using the U2F and OTP features of the YubiKey.}}<br />
<br />
{{Note|The often seen:<br />
<br />
{{ic|ykman mode c+u+o --touch-eject}} or {{ic|ykman mode 86}}<br />
<br />
will ignore the {{ic|--touch-eject}} and be identical to the above recommended {{ic|ykman mode 6}}.<br />
<br />
86 is not a valid mode. It might be a bug that the tool accepts higher values ([https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 see here]).}}<br />
<br />
=== Two Slots ===<br />
<br />
Only if the OTP mode is activated (see Modes of the YubiKey below), the Yubikey provides 2 slots.<br />
<br />
If the transport mode OTP is enabled, the two YubiKey Slots, long press and short press, can be configured and used.<br />
<br />
==== Configuration of the slots ====<br />
<br />
These slots can have one of the following credentials configured: a [https://developers.yubico.com/OTP/ Yubico OTP] (which is what comes preconfigured in the short press slot on a new key), a static password, a challenge-response credential, an OATH-HOTP credential. All this functionality is found in the {{ic|ykman otp}} commands.<br />
<br />
{{Note|A slot has either a Yubico OTP or a challenge-response credential configured. More general: One, and only one, type of the above listed possible credential per slot.}}<br />
<br />
There are several flags that can be set during the configuration of the slots.<br />
These flags /cannot/ be read from the device once written. However, the behaviour of the device should change when the flags are set ;)<br />
<br />
{{Note|Actually most of (all of??) the parameters and details you use during configuration of the slots, cannot be read back, once written to the YubiKey.}}<br />
<br />
=== The LED ===<br />
<br />
The YubiKey has a small green LED able to communicate with you.<br />
Its message to you actually depends on the currently used [[#USB connection modes]] of your YubiKey.<br />
<br />
The possible messages are:<br />
* *steady on*: Press now, to allow access. (typically (TODO exclusively?) U2F mode)<br />
* *slow blinking*: Power/setting up/ready for use (TODO explain)<br />
* *rapid blinking*: Error, configuring driver (TODO explain)<br />
<br />
{{Note|If the CCID mode is turned on, then the LED of the key is always shortly flashing every two-three seconds once inserted.<br>You can turn the blinking off by disabling the CCID mode. This slow blinking just shows that the device has power, alternatively it shows a need for a button press. On Windows this behavior will typically stop once drivers are installed and it is ready for use. Mac and Linux systems will keep blinking; here [https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 the best current workaround] to get the LED to blink less is to disable CCID.}}<br />
<br />
=== Initial configuration ===<br />
<br />
On a new YubiKey the Yubico OTP is preconfigured on slot 1. <br />
<br />
{{Warning|Before you overwrite your slot 1, please be aware that one is not able to reconfigure the same trust level [https://forum.yubico.com/viewtopic12ca.html?f%3D16&t%3D1960 see here]. Meaning:<br />
<br />
One could think that it is a good idea to reset configuration slot 1 to a new OTP. But then a "VV" prefix in your credentials must be used. Whereas the factory credentials on your Yubikey use a "CC" prefix. You can upload a "VV" credential using the Yubico personalization tool GUI or manually upload the new AES key to the [https://upload.yubico.com/ yubico.com website] in order to regain the same functionality than with the original factory configuration. VV credentials are not less secure than CC. However some services may only trust CC credentials as they believe that the user process is more prone to security vulnerabilities. This is because you could have malware on your machine or someone intercepting your key when sending it to the YubiCloud.<br />
}}<br />
<br />
=== Limitations of the passwords typed by YubiKey via USB-keyboard -- or "Why do my password look so weak ?" ===<br />
<br />
The YubiKey can type passwords (OTP or Static Password) for you by acting as USB keyboard and sending scan-codes like if you would type.<br />
<br />
A limitation of the YubiKey, however, prevents you from choosing characters that require a modifier key other than Shift.<br />
And in order for the YubiKey to work with all possible keyboard layouts (e.g. the {{ic|Z}} on a German keyboard has a different scan-code than the {{ic|Z}} on a US keyboard) it is necessary to limit the characters used by YubiKey passwords to the ModHex alphabet + Digits (0-9) (+ optionally "!" as the only available Symbol in static passwords).<br />
<br />
The 16 characters used in the ModHex alphabet are: {{ic|c,b,d,e,f,g,h,i,j,k,l,n,r,t,u,v}}. These characters share a property that makes them very valuable to a YubiKey: They use the same scan codes across a very large number of keyboard layouts. In other words, the scan code 0x06 maps to the character c for English, Swedish, German, French, and many others.<br />
<br />
[https://www.yubico.com/wp-content/uploads/2015/11/Yubico_WhitePaper_Static_Password_Function.pdf See here for full info]<br />
<br />
== One-time password ==<br />
<br />
=== Yubico OTP mode ===<br />
<br />
The Yubico OTP mode is AES symmetric key based. On a new YubiKey the Yubico OTP is preconfigured on slot 1. This initial AES symmetric key is stored in the YubiKey and the same AES key is already stored on the Yubico Authentication server. This allows validating against YubiCloud, meaning the use of Yubico OTP in combination with the Yubico Forum website for instance or on https://demo.yubico.com).<br />
<br />
The initial configuration and AES key stored in slot 1 can of course be overwritten.<br />
<br />
{{Warning|Please read [[#Initial configuration]] before you overwrite the intial configuration of slot 1 that your YubiKey comes shipped with.}}<br />
<br />
==== How does it work ====<br />
<br />
Yubikey's authentication protocol is based on [[Wikipedia:Symmetric_cryptography|symmetric cryptography]].<br />
More specifically, each YubiKey contains a 128-bit [[Wikipedia:Advanced_Encryption_Standard|AES]] key unique to that device.<br />
It is used to encrypt a token made of different fields such as the ID of the key, a counter, a random number, etc.<br />
The OTP is made from concatenating the ID of the key with this encrypted token.<br />
<br />
This OTP is sent to the target system to which we want to authenticate.<br />
This target system asks a validation server if the OTP is good.<br />
The validation server has a mapping of YubiKey IDs -> AES key.<br />
Using the key ID in the OTP, it can thus retrieve the AES key and decrypt the other part of the OTP.<br />
If it looks OK (plain-text ID and encrypted ID are the same, the counter is bigger than the last seen one to prevent [[wikipedia:Replay_attack|replay attacks]], then authentication is successful.<br />
<br />
The validation server sends that authentication status back to the target system, which grants access or not based on that response.<br />
<br />
==== Security risks ====<br />
<br />
===== AES key compromise =====<br />
<br />
As you can imagine, the AES key should be kept secret.<br />
It cannot be retrieved from the YubiKey itself (or it should not, at least not with software).<br />
It is present in the validation server though, so the security of this server is very important.<br />
<br />
===== Validation requests/responses tampering =====<br />
<br />
Since the target system relies on the ruling of the validation server, a trivial attack would be to impersonate the validation server.<br />
The target system thus needs to authenticate the validation server.<br />
2 methods are available :<br />
* '''HMAC''': This is also symmetric cryptography, the target server and validation server share a key that is used to sign requests and responses.<br />
* '''TLS''': Requests and responses travel via HTTP, so TLS (HTTPS) can be used to authenticate and encrypt the connection.<br />
<br />
==== YubiCloud and validation servers ====<br />
<br />
When you buy a YubiKey, it is preloaded with an AES key that is known only to Yubico.<br />
They will not even communicate it to you.<br />
Yubico provides a validation server with free unlimited access (YubiCloud).<br />
It also offers open-source implementations of the server.<br />
<br />
So you can either:<br />
* choose to use your YubiKey with its preloaded AES key and validate against Yubico's validation server ;<br />
* or load a new AES key in your YubiKey and run your own validation server.<br />
<br />
{{Note|To authenticate the Yubico validation server, you can:<br />
* '''with HMAC''': use https://upgrade.yubico.com/getapikey/ to get an HMAC key and ID<br />
* '''with HTTPS''': the validation server's certificate is signed by GoDaddy, and is thus trusted by default in Arch installs (at least if you have package ca-certificates)}}<br />
<br />
=== OATH-HOTP mode (RFC 4226) ===<br />
<br />
{{Expansion|Empty section.}}<br />
<br />
== Challenge-Response ==<br />
<br />
=== Function and Application of Challenge-Response ===<br />
This technique can be used to authenticate.<br />
<br />
A challenge is sent to the YubiKey and a response is (auto-magically) calculated and send back.<br />
This calculation needs a secret (e.g. an AES key in case of the Yubico OTP mode)<br />
The same challenge always results in the same response.<br />
Without the secret this calculation is not meant to be feasable. Even if in the possession of many challenge-response pairs.<br />
<br />
This can be used for:<br />
* true 2-factor (possession and knowledge) authentication:<br>If you combine the response (possession factor) with a password (knowledge factor) and to authenticate you need to present the triple (challenge,response, password) to 3rd party. In which case the challenge and the corresponding response can be (publicly) send to a 3rd party to authenticate the possession factor, by redoing basically the same (auto-magical) calculation. The needed secret needs to be shared with 3rd party to allow an authentication.<br />
<br />
* semi 2-factor (possession and knowledge) authentication:<br>The challenge can be public. Only with the possession of the YubiKey hardware the response can be generated. This can be used to create a "sort-of" 2-factor authentication (possession and knowledge): If you combine the response (possession factor) with a password (knowledge factor) and use the result for instance as passphrase for cryptsetup.<br />
<br />
This functionality will consume one slot. And it is used via API calls to the YubiKey. So you usually use some tool to communicate the challenge to your YubiKey and get back the response.<br />
<br />
There are two Challenge-Response modes:<br />
* Yubico OTP mode <br />
* HMAC-SHA1 mode<br />
<br />
=== Setup the slot ===<br />
<br />
One way to setup slot {{ic|2}} in challenge-response mode ({{ic|-ochal-resp}}) is with {{ic|ykpersonalize}}:<br />
<br />
{{bc|ykpersonalize -v -2 -ochal-resp -ochal-hmac -ohmac-lt64 -oserial-api-visible -ochal-btn-trig}}<br />
<br />
Check with {{man|1|ykpersonalize}} to make sure that the options used above are right for you. You may also enable challenge-response mode using graphical interface through {{pkg|yubikey-personalization-gui}}.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the '''Warning''' under [[#Initial configuration]].}}<br />
<br />
=== Use the slot - get a response for a challenge ===<br />
<br />
To use a Challenge-Response slot (no matter which mode):<br />
<br />
{{bc|ykchalresp -2 <CHALLENGE>}}<br />
<br />
== U2F ==<br />
<br />
{{Expansion}}<br />
<br />
=== Enabling U2F in the browser ===<br />
<br />
==== Chromium/Chrome ====<br />
<br />
[[Chromium/Tips and tricks#U2F authentication]]<br />
<br />
==== Firefox ====<br />
<br />
[[Firefox/Tweaks#Fido U2F authentication]]<br />
<br />
== CCID Smartcard ==<br />
<br />
CCID (Chip Card Interface Device) is a USB standard device class for use by USB devices that act as smart card readers or with security tokens that connect directly via USB, like the Yubikey. HID (Human Interface Device) and CCID are both USB device classes, i.e. they are in the same category of USB specifications. HID is a specification for computer peripherals, like keyboards. The Yubikey works like a USB (HID) keyboard when used in the OTP and U2F modes, but switches to the CCID protocol when using the PIV application, or as an OpenPGP device.<br />
<br />
CCID mode should be enabled by default on all YubiKeys shipped since November 2015 [https://www.yubico.com/support/knowledge-base/categories/articles/use-yubikey-yubikey-windows-hello-app/]. Enable at least the CCID mode. Please see [[#Set the enabled modes]].<br />
<br />
=== PIV ===<br />
<br />
Starting with the YubiKey NEO, the Yubikeys contain a PIV (Personal Identity Verification) application on the chip. PIV is a US government standard (FIPS 201) that specifies how a token using RSA or ECC (Elliptic Curve Cryptography) is used for personal electronic identification. The YubiKey NEO only supports RSA encryption, later models (YubiKey 4 and 5) support both RSA and ECC. The distinguishing characteristic of a PIV token is that it is built to protect private keys and operate on them on-chip. A private key never leaves the token after it has been installed on it. Optionally, the private key can even be generated on-chip with the aid of an on-chip random number generator. If generated on-chip, the private key is never handled outside of the chip, and there is no way to recover it from the token. When using the PIV mechanism, the Yubikey functions as a CCID device.<br />
<br />
=== Use OpenPGP smartcard mode ===<br />
<br />
See [[GnuPG#Smartcards]]<br />
<br />
=== Using a YubiKey with SSH ===<br />
<br />
The following example describes how to use a YubiKey for [[SSH keys]]. A YubiKey with the PIV (Personal Identification Verification) application is required; this means you need a YubiKey NEO or YubiKey 4 or later.<br />
<br />
==== Generating a key pair on the YubiKey ====<br />
<br />
A private key and associated certificate need to be either generated on the YubiKey or imported to it. Install the {{Pkg|yubikey-manager}}<br />
package. Insert the YubiKey in a USB port and check that it is recognized:<br />
<br />
$ ykman list<br />
YubiKey 4 [OTP+FIDO+CCID] Serial: 1234567<br />
<br />
The following two commands ({{ic|generate-key}} and {{ic|generate-certificate}}) require providing the PIV application's 24-byte management key, if it has been changed from its default value (recommended). The examples below assume the shell variable {{ic|MK}} has been set in advance to the 48 character hex string representation of the management key. For example:<br />
<br />
$ MK=AB019982CA48BDC6776B1F9A0A3E129FDE0705D219AF0037<br />
<br />
Generate a 2048-bit RSA key pair on the YubiKey. The private key will be stored in key slot 9a on the YubiKey, and the public key will be<br />
written to the file {{ic|pubkey.pem}}.<br />
<br />
$ ykman piv generate-key -m $MK -a RSA2048 9a pubkey.pem<br />
<br />
Next, use the YubiKey to generate a self-signed certificate for the public key:<br />
<br />
$ ykman piv generate-certificate -m $MK -d 1826 -s "SSH Key" 9a pubkey.pem<br />
<br />
The Subject field in the certificate will be set to "SSH Key" with the {{ic|-s}} option. This field will be included in the prompt for PIN to help identify which key is used for authentication. The example command also specifies the {{ic|-d}} option to set the number of days until the certificate expires. If the {{ic|-d}} option is omitted, a default value of 365 days is used.<br />
<br />
Note that the last parameter in the {{ic|generate-key}} command is the file name where the public key is written to, whereas the last parameter in the {{ic|generate-certificate}} command specifies where the public key is read from. The certificate is constructed and signed on the YubiKey and stored alongside the private key; the command does not output the certificate.<br />
<br />
At this point the YubiKey is ready for authenticating to a SSH server. For this to happen, some additional configuration on both the client and the server is required.<br />
<br />
==== Client configuration ====<br />
<br />
The standard API used to communicate with cryptographic tokens is defined by [[wikipedia:PKCS_11|PKCS#11]].<br />
Install the {{Pkg|opensc}} package which provides this API in the form of the shared library {{ic|/usr/lib/opensc-pkcs11.so}}. The ssh client should be configured to use this library with the directive PKCS11Provider in {{ic|~/.ssh/config}}:<br />
<br />
{{hc|~/.ssh/config|PKCS11Provider /usr/lib/opensc-pkcs11.so}}<br />
<br />
==== Public key conversion ====<br />
<br />
The {{ic|pubkey.pem}} file contains the public key in PEM (Privacy Enhanced Mail) format. OpenSSH uses a different format defined in RFC 4253,<br />
section 6.6, so the PEM formatted key should be converted to the format OpenSSH understands. This can be done using {{ic|ssh-keygen}}:<br />
<br />
$ ssh-keygen -i -m PKCS8 -f pubkey.pem > pubkey.txt<br />
<br />
This command uses the import ({{ic|-i}}) function of the {{ic|ssh-keygen}}, specifies PKCS8 as the input file format ({{ic|-m}}), and reads the input from the ({{ic|-f}}) file {{ic|pubkey.pem}}. The converted key is written on standard output, which is the example is redirected to the file {{ic|pubkey.txt}}.<br />
<br />
The converted public key should now be copied to the remote server as described in [[SSH keys#Copying the public key to the remote server]].<br />
<br />
==== Initiating an SSH session with the YubiKey ====<br />
<br />
To authenticate a SSH connection using the YubiKey, just use ''ssh'' normally. You will be prompted for the PIN instead of a password:<br />
<br />
$ ssh remote<br />
Enter PIN for 'SSH Key' <br />
[user@remote ~]$ <br />
<br />
==== Using ssh-agent to cache the PIN ====<br />
<br />
ssh-agent (see [[SSH keys#SSH agents]]) can also be used with the PKCS#11 library; in this case the PIN code is cached instead of the private key.<br />
<br />
$ ssh-add -s /usr/lib/opensc-pkcs11.so<br />
<br />
As long as the PIN is cached in by the agent, the cached value is used and the user is not prompted for it.<br />
<br />
==== Further reading ====<br />
<br />
The default PIN code of the PIV application on the YubiKey is {{ic|123456}}; you may want to change it. The YubiKey also requires a 24-byte management key for administrative functions like key generation. If the management key has been changed from its default value, the new value needs to be specified using the {{ic|-m}} option on the command line for certain commands. See [https://developers.yubico.com/PIV/ What is PIV?]<br />
<br />
== Tips and tricks ==<br />
<br />
=== YubiKey and LUKS encrypted partition/disk ===<br />
<br />
YubiKey can be used to strengthen the security of your [[LUKS]] encrypted partition/disk. There are multiple ways to achieve it. But before enabling Yubikey as a 2FA device it is recommended to setup plain LUKS encryption first and make sure it works correctly.<br />
<br />
==== Challenge-Response mode for LUKS passphrase (udev/encrypt) ====<br />
<br />
One way to do it is to use a Challenge-Response mode for creating strong LUKS passphrases. First, install {{Pkg|yubikey-full-disk-encryption}} package. Using this tool you can add/modify/remove Yubikey-protected passphrases.<br />
<br />
Make changes to {{ic|/etc/ykfde.conf}} configuration file as as:<br />
* choose Yubikey slot to use for LUKS ({{ic|YKFDE_CHALLENGE_SLOT}})<br />
* whether you want to type a password at boot ({{ic|YKFDE_CHALLENGE_PASSWORD_NEEDED}}) or use predefined password ({{ic|YKFDE_CHALLENGE}}) which essentially means you check for Yubikey hardware presence only.<br />
<br />
LUKS supports multiple password so you need to select a slot that is going to store Yubikey-protected passphrase. Inspect existing slots using command:<br />
<br />
# cryptsetup luksDump /dev/<DISK><br />
<br />
Check entries under {{ic|Keyslots:}} section. And then pick an unused slot.<br />
<br />
Enroll your new passphrase:<br />
<br />
# ykfde-enroll -d /dev/<DISK> -s <LUKS_SLOT><br />
<br />
It will require the new and existing passphrases.<br />
<br />
And the last step is to add {{ic|ykfde}} hook to {{ic|/etc/mkinitcpio.conf}} file before or instead of {{ic|encrypt}} hook. Then regenerate initramfs with {{ic|mkinitcpio -P}}.<br />
<br />
{{Warning|As of December 2019 `sd-encrypt` enabled boot is [https://github.com/agherzan/yubikey-full-disk-encryption/issues/14 not supported] by {{Pkg|yubikey-full-disk-encryption}}.}}<br />
<br />
==== Challenge-Response mode for LUKS passphrase (systemd/sd-encrypt) ====<br />
<br />
On systems which use {{ic|systemd}} instead of {{ic|udev}} hook in initramfs, full disk encryption can be served by the {{aur|mkinitcpio-ykfde}} package. Using this tool you can add Yubikey-protected luks slots. Note that this is similar but different project than one mentioned in paragraph above and they aren't compatible with each other.<br />
<br />
Make changes to {{ic|/etc/ykfde.conf}} configuration file as as:<br />
* general/device name: devicename (rd.luks.name) defined in {{ic|/etc/default/grub}}<br />
* key specific sections: map individual YubiKeys / slots to luks slots.<br />
<br />
Add ykfde challenges file to grub initrd {{ic|/etc/default/grub}}:<br />
<br />
GRUB_EARLY_INITRD_LINUX_CUSTOM="ykfde-challenges.img"<br />
<br />
Add {{ic|ykfde}} hook to {{ic|/etc/mkinitcpio.conf}} file before {{ic|sd-encrypt}} hook.<br />
<br />
Enroll new luks slot:<br />
<br />
# ykfde --ask-2nd-factor<br />
<br />
Push challenges to /boot partition:<br />
<br />
# ykfde-cpio<br />
<br />
Rebuild initrd and update grub config:<br />
<br />
# mkinitcpio -P<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
If you want to unlock one single luks slot using multiple YubiKeys sharing the same challenge response configuration you have to enure ykfde uses the same challenge (stored in {{ic|/etc/ykfde.d/}}).<br />
<br />
For further details please see the [https://github.com/eworm-de/mkinitcpio-ykfde/blob/master/README-mkinitcpio.md project documentation].<br />
<br />
==== OpenPGP applet ====<br />
<br />
Another way of using YubiKey for full disk encryption is to utilize its OpenPGP applet to decrypt the LUKS keyfile during boot. [https://github.com/fuhry/initramfs-scencrypt initramfs-scencrypt] is a set of hooks for initramfs that automate this process.<br />
<br />
==== HMAC Secret Extension of FIDO2 protocol ====<br />
<br />
Yet another way of using YubiKey for full disk encryption is to utilize [https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#sctn-hmac-secret-extension HMAC Secret Extension] to retrieve the LUKS password from YubiKey which is protected by passphrase supplied by user. This functionality requires at least [https://support.yubico.com/support/solutions/articles/15000027138-yubikey-5-2-3-enhancements-to-fido-2-support YubiKey 5 with firmware 5.2.3+].<br />
<br />
In order to use this install {{AUR|fido2-hmac-secret}} and follow instructions available in [https://github.com/mjec/fido2-hmac-secret/wiki/Arch-Linux-LUKS-configuration project documentation].<br />
<br />
=== Yubikey and KeePass ===<br />
<br />
{{Style|Duplicates [[KeePass]].}}<br />
<br />
Yubikey can be integrated with [[KeePass]] using [[KeePass#Yubikey|plugins]].<br />
<br />
For a native open-source implementation of KeePass have a look at:<br />
<br />
==== keepassx2 ====<br />
<br />
{{AUR|keepassx2}} ([https://keepassx.org/ see keepassx.org]) a keepass QT FOSS reimplementation, extremely stable and available for Windows, MacOSX and Linux.<br />
<br />
==== KeePassXC ====<br />
<br />
{{Pkg|keepassxc}} ([https://keepassxc.org/ see keepassxc.org]) a KeePassX fork that integrated YubiKey into KeePassX v2.<br>The integration covers Challenge-Response as security factor to open the database, but also the generation of OTP using the YubiKey.<br />
<br />
In order to have a KeePassXC database work on Android (using the [https://play.google.com/store/apps/details?id=keepass2android.keepass2android Keepass2Android app]), you need to use version 1.06 of the app. You also need to save the database file in the KDBX 4 format, since Keepass2Android do not support the KDBX 3 format.<br />
<br />
YubiKey support in Keepass2Android (which is compatible with KeePassXC) is tracked [https://github.com/PhilippC/keepass2android/issues/4 on GitHub].<br />
<br />
=== Two-factor authentication with SSH ===<br />
<br />
{{Note|See also: https://developers.yubico.com/yubico-pam/Yubikey_and_SSH_via_PAM.html}}<br />
<br />
This details how to use a Yubikey to have [[wikipedia:Two-factor_authentication|two-factor authentication]] with SSH, that is, to use both a password and a YubiKey OTP.<br />
<br />
==== Prerequisites ====<br />
<br />
Install {{Pkg|yubico-pam}}.<br />
<br />
{{Note|If you are configuring a distant server to use YubiKey, you should open at least one additional, rescue SSH session, so that you are not locked out of your server if the configuration does not work and you exit your main session inadvertently}}<br />
<br />
{{Note|The following assumes you are using the default Yubico servers. See the [https://github.com/Yubico/yubico-pam yubico-pam documentation] for options relevant to using your own server.}}<br />
<br />
==== Configuration ====<br />
<br />
===== Authorization Mapping Files =====<br />
<br />
A mapping must be made between the YubiKey token ID and the user ID it is<br />
attached to. There are two ways to do this, either centrally in one file, or<br />
individually, where users can create the mapping in their home directories.<br />
If the central authorization mapping file is being used, user home directory<br />
mappings will not be used and vice versa.<br />
<br />
====== Central authorization mapping ======<br />
<br />
Create a file {{ic|/etc/yubico/authorized_yubikeys}}, the file must contain a user name and the<br />
YubiKey token ID separated by colons (same format as the passwd file) for<br />
each user you want to allow onto the system using a YubiKey.<br />
<br />
The mappings should look like this, one per line:<br />
<br />
<first user name>:<Yubikey token ID1>:<Yubikey token ID2>:...<br />
<second user name>:<Yubikey token ID3>:<Yubikey token ID4>:...<br />
<br />
You can specify multiple key tokens to correspond to one user, but only one is required.<br />
<br />
====== Per-user authorization mapping ======<br />
<br />
Each user creates a {{ic|~/.yubico/authorized_yubikeys}} file inside of their home<br />
directory and places the mapping in that file, the file must have only one<br />
line:<br />
<br />
<user name>:<Yubikey token ID1>:<Yubikey token ID2><br />
<br />
This is much the same concept as the SSH {{ic|authorized_keys}} file.<br />
<br />
Note that this file must be readable by the {{ic|pam_yubico}} module when the user is authenticated, otherwise login will fail. If this is not possible or desired, use the global mapping file instead.<br />
<br />
====== Obtaining the YubiKey token ID (a.k.a. public ID) ======<br />
<br />
You can obtain the YubiKey token ID in several ways. One is by<br />
removing the last 32 characters of any OTP (One Time Password)<br />
generated with your YubiKey. Another is by using the<br />
[http://demo.yubico.com/php-yubico/Modhex_Calculator.php modhex calculator].<br />
<br />
Enter your YubiKey OTP and convert it, your Yubikey token ID is 12<br />
characters and listed as:<br />
<br />
Modhex encoded: XXXXXXX<br />
<br />
===== PAM configuration =====<br />
<br />
Having set up the {{ic|pam_yubico}} module, you next need to tell PAM to use it when logging in via SSH. There are several ways of doing this.<br />
<br />
====== The default way ======<br />
<br />
Obtain HMAC credentials from Yubico as described in [[#YubiCloud and validation servers]]. You will receive a Client ID and a secret key.<br />
<br />
Add one of the two following lines to the beginnning of {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID authfile=/etc/yubico/authorized_yubikeys<br />
<br />
if you are using a central authorization mapping file, or<br />
<br />
auth required pam_yubico.so id=CLIENTID<br />
<br />
if you are using per-user authorization mapping, where {{ic|CLIENTID}} is your Client ID. This method utilizes your ID and the server's certificate to authenticate the connection.<br />
<br />
{{Note|This will authenticate via Yubico's free YubiCloud servers. If you want to use a different server, add it via the {{ic|urllist}} parameter.}}<br />
<br />
====== Using pure HMAC to authenticate the validation server ======<br />
<br />
Add {{ic|key}} to the above lines in {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID key=SECRETKEY ...<br />
<br />
where {{ic|CLIENTID}} and {{ic|SECRETKEY}} are your HMAC ID and key.<br />
<br />
You should also disallow unprivileged users to read the file to prevent them from seeing the HMAC credentials:<br />
# chmod o-r /etc/pam.d/sshd<br />
<br />
{{Note|HMAC credentials should be unique to a single target server. That way, if an attacker finds them, he will not be able to craft responses to authenticate to other target servers you own}}<br />
<br />
====== Using pure HTTPS to authenticate the validation server ======<br />
<br />
{{Warning|While this "old" method of using a dummy id still works, it is unknown how secure and/or future-proof it is, as Yubico no longer describes it in their documentation. Proceed at your own risk. At the very least you should ensure that only HTTPS servers with valid certificates are used for authentication.}}<br />
<br />
If you do not want to use HMAC credentials from Yubico, it is still possible to authenticate via the Yubico server by setting {{ic|1=CLIENTID=1}} instead of your own ID. Although {{ic|pam_yubico}}'s default server uses HTTPS already, for security reasons you should specify it manually via the {{ic|urllist}} parameter, as the servers certificate is the only way in which the connection is authenticated. You can find the keyserver URL by adding the {{ic|debug}} parameter to the {{ic|auth}} line.<br />
<br />
===== SSHD configuration =====<br />
<br />
You should check that {{ic|/etc/ssh/sshd_config}} contains these lines and that they are not commented. The {{ic|sshd_config}} shipped with {{pkg|openssh}} has these set correctly by default.<br />
ChallengeResponseAuthentication no<br />
UsePAM yes<br />
<br />
==== That is it! ====<br />
<br />
You should not need to restart anything if you did not change the SSHD config file.<br />
<br />
To log in, at the {{ic|Password:}} prompt of SSH, you have to type your password '''without pressing enter''' and touch the YubiKey's button.<br />
The YubiKey should send a return at the end of the OTP so you do not need to touch the enter key at all.<br />
<br />
You can display information about the login data generated by {{ic|pam_yubico}} by adding the {{ic|debug}} option to the auth line in{{ic|/etc/pam.d/sshd}}. However, if you are using a central authorization file, you should remove that option once finished testing, as it causes {{ic|pam_yubico}} to display the entire content of the central file to every user who logs in using a YubiKey.<br />
<br />
==== Explanation ====<br />
<br />
This works because the prompt is {{ic|pam_yubico.so}}'s one, since this module is before {{ic|pam_unix.so}}, which normally does basic password authentication.<br />
So, you are giving a string that is the concatenation of your password and the OTP to {{ic|pam_yubico.so}}.<br />
Since the OTPs have a fixed length (let us call this size N), it just has to get the last N characters to retrieve the OTP, and it assumes that the other characters at the start are the password.<br />
It tries to validate the OTP, and in case of success, sends the password to the next PAM module. In Archlinux' default PAM stack, the authenticator {{ic|pam_unix.so}} is instructed to try receiving a password from the previous module with {{ic|try_first_pass}}, so it automatically uses the password sent by {{ic|pam_yubico.so}}.<br />
<br />
=== Executing actions on insertion/removal of YubiKey device ===<br />
<br />
For example, you want to perform an action when you pull your YubiKey out of the USB slot, create {{ic|/etc/udev/rules.d/80-yubikey-actions.rules}} and add the following contents:<br />
ACTION=="remove", ENV{ID_MODEL}=="Yubikey_4_OTP+U2F+CCID", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0407", RUN+="/usr/local/bin/script args"<br />
<br />
Please note, that this example is for the YubiKey 4, and you will have to look at the output of {{ic|lsusb}} to get the vendor and model ID's, along with the description of the device. Of course, to execute a script on insertion, you would change the action to 'add' instead of remove.<br />
<br />
== Maintenance / Upgrades ==<br />
<br />
=== Installing the OATH Applet for a YubiKey NEO ===<br />
<br />
These steps will allow you to install the OATH applet onto your YubiKey NEO. This allows the use of Yubico Authenticator in the Google Play Store.<br />
{{Note|1=These steps are only for NEOs with a firmware version <= 3.1.2. The current generation NEOs (with U2F) come with the OpenPGP applet already installed)}}<br />
<br />
==== Configure the NEO as a CCID Device ====<br />
<br />
# Install {{pkg|yubikey-personalization-gui}} ({{AUR|yubikey-personalization-gui-git}}).<br />
# Add the udev rules and reboot so you can manage the YubiKey without needing to be root<br />
# Run {{ic|ykpersonalize -m82}}, enter {{ic|y}}, and hit enter.<br />
<br />
==== Install the Applet ====<br />
<br />
# Install {{AUR|gpshell}}, {{AUR|gppcscconnectionplugin}}, {{AUR|globalplatform}}, and {{Pkg|pcsclite}}.<br />
# [[Start]] {{ic|pcscd.service}}.<br />
# Download the most recent CAP file from the [http://opensource.yubico.com/ykneo-oath/releases.html ykneo-oath] site.<br />
# Download {{ic|gpinstall.txt}} from [https://github.com/Yubico/ykneo-oath/blob/master/gpinstall.txt GitHub].<br />
# Edit the line in gpinstall.txt beginning with {{ic|install -file}} to reflect the path where the CAP file is located.<br />
# Open a terminal and run {{ic| gpshell <location of gpinstall.txt>}}<br />
# Ideally, a bunch of text will scroll by and it ends saying something like<br />
{{ bc | Command --> 80E88013D7C000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A100<br />
Wrapped command --> 84E88013DFC000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A15D848CB77<br />
27D0EDA00<br />
Response <-- 009000<br />
Command --> 80E60C002107A000000527210108A00000052721010108A000000527210101010003C901000000<br />
Wrapped command --> 84E60C002907A000000527210108A00000052721010108A000000527210101010003C9010000B4648127914A4C7C00<br />
Response <-- 009000<br />
card_disconnect<br />
release_context}}<br />
# Unplug the NEO and try it with the Yubico Authenticator app<br />
<br />
==== (Optional) Install the Yubico Authenticator Desktop client ====<br />
<br />
You can get the desktop version of the Yubico Authenticator by installing {{Pkg|yubioath-desktop}}.<br />
<br />
While {{ic|pcscd.service}} is running, run {{ic|yubioath-gui}} and insert your Yubikey when prompted.<br />
<br />
== Troubleshooting ==<br />
<br />
Restart, especially if you have completed updates since your YubiKey last worked. Do this even if some functions appear to be functioning.<br />
<br />
=== YubiKey not acting as HID device ===<br />
Add udev rule as described in [https://michaelheap.com/yubikey-on-arch/ this article]:<br />
<br />
{{hc|/etc/udev/rules.d/10-security-key.rules|2=<br />
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="users", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0"<br />
}}<br />
<br />
Run {{ic|udevadm trigger}} afterwards.<br />
<br />
You may also need to [[install]] the package {{pkg|libu2f-host}} if you want support in chrome.<br />
<br />
=== ykman fails to connect to the YubiKey ===<br />
<br />
If the manager fails to connect to the YubiKey, make sure you have started {{ic|pcscd.service}} or {{ic|pcscd.socket}}.<br />
<br />
=== YubiKey fails to bind within a guest VM ===<br />
<br />
Assuming the YubiKey is available to the guest, the issue results from a driver binding to the device on the host. To unbind the device, the bus and port information is needed from {{ic|dmesg}} on the host:<br />
<br />
$ dmesg | grep -B1 Yubico | tail -n 2 | head -n 1 | sed -E 's/^\<nowiki>[[^]]</nowiki>+\] usb (<nowiki>[^:]</nowiki>*):.*/\1/'<br />
<br />
The resulting USB id should be of the form {{ic|X-Y.Z}} or {{ic|X-Y}}. Then, on the host, use {{ic|find}} to search {{ic|/sys/bus/usb/drivers}} for which driver the YubiKey is binded to (e.g. {{ic|usbhid}} or {{ic|usbfs}}).<br />
<br />
$ find /sys/bus/usb/drivers -name "*X-Y.Z*"<br />
<br />
To unbind the device, use the result from the previous command (i.e. {{ic|/sys/bus/usb/drivers/<DRIVER>/X-Y.Z:1.0}}):<br />
<br />
# echo 'X-Y.Z:1.0' > /sys/bus/usb/drivers/<DRIVER>/unbind<br />
<br />
=== Error: [key] could not be locally signed or gpg: No default secret key: No public key ===<br />
<br />
Occurs when attempting to sign keys on a non-standard keyring while a YubiKey is plugged in, e.g. as [[Pacman/Package_signing|Pacman]] does in {{ic|pacman-key --populate archlinux}}. The solution is to remove the offending YubiKey and start over.</div>Tepleshttps://wiki.archlinux.org/index.php?title=YubiKey&diff=595016YubiKey2020-01-14T14:59:14Z<p>Teples: /* Tips and tricks */ Add info about using HMAC Secret Extension for LUKS</p>
<hr />
<div>[[Category:Authentication]]<br />
[[ja:Yubikey]]<br />
{{Accuracy|The article lacks sources, is interspersed with TODOs and probably out of date.}}<br />
{{Style|ykman-specifics should be grouped together.}}<br />
This article describes how [https://yubico.com Yubico]'s [[Wikipedia:YubiKey|YubiKey]] works and how you can use it.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the warning under [[#Initial configuration]].}}<br />
<br />
== Introduction ==<br />
<br />
The YubiKey is a small [[Wikipedia:Security token|USB Security token]] that supports:<br />
<br />
* generating [[Wikipedia:One-time password|one-time passwords]] (OTP) - using either AES based Yubico OTP algorithm or OATH-HOTP following RFC 4226<br />
* outputting a up to 63 char long static password<br />
* handling [[Wikipedia:Challenge–response authentication|challenge-response requests]], using either Yubico OTP mode or HMAC-SHA1 mode<br />
* handling [[Wikipedia:Universal_2nd_Factor|Universal 2nd Factor]] (U2F) requests (YubiKey 4 and YubiKey NEO)<br />
* acting as smartcard (using the [[Wikipedia:CCID (protocol)|CCID protocol]]) (YubiKey 4 and YubiKey NEO) - allowing storage of signing, encrypting, authenticating (RSA) keys to be used for instance for SSH login (authentication), Email signature/encryption, git commit signature, etc.<br />
<br />
It is manufactured by [http://www.yubico.com/ Yubico].<br />
<br />
One of its strengths is that it emulates a USB keyboard to send the OTP as text, and thus requires only USB HID drivers found on practically all desktop computers.<br />
<br />
While offering a lot of features, newer versions of the YubiKey are [https://www.yubico.com/2016/05/secure-hardware-vs-open-source/ not released as open source]. An alternative is the [[Solo]].<br />
<br />
=== Installation ===<br />
<br />
There are several packages available:<br />
<br />
* {{App|Yubico PAM|Module to integrate the YubiKey into [[PAM]].|https://developers.yubico.com/yubico-pam/|{{Pkg|yubico-pam}}}}<br />
* {{App|YubiKey Manager|Python library and command-line tool ({{ic|ykman}}) for configuring a YubiKey over all USB connections. Has optional GUI.|https://developers.yubico.com/yubikey-manager/|{{Pkg|yubikey-manager}}, {{Pkg|yubikey-manager-qt}}}}<br />
{{Note|After you install the yubikey-manager (which can be called by ykman in CLI), you need to enable {{ic|pcscd.service}} to get it running}}<br />
* {{App|Yubikey Personalization|Library and tool to configure slot features over the OTP USB connection. Has optional GUI.|https://developers.yubico.com/yubikey-personalization/|{{Pkg|yubikey-personalization}}, {{Pkg|yubikey-personalization-gui}}}}<br />
* {{App|Yubico Authenticator for Desktop|Lets you read OATH codes from your YubiKey over USB. Support the newer OATH implementation (YubiKey NEO and 4) as well as the older slot-based implementation (YubiKey Standard and Edge).|https://developers.yubico.com/OATH/YubiKey_OATH_software.html|{{Pkg|yubioath-desktop}}}}<br />
<br />
=== Understanding the YubiKey ===<br />
<br />
The YubiKey is a small USB dongle with one button and an LED to communicate with you.<br />
<br />
One of its strengths is that it can emulate a USB keyboard to send a password (OTP or static password) as text, and thus requires only USB HID drivers found on practically all computers (desktop, mobile, tablet, etc.).<br />
<br />
This also makes it vulnerable to keyloggers if the {{ic|static password}} functionality is used, which is why if possible one should avoid it and try to only use the one-time password (OTP), Challenge-Response and CCID Smartcard functionality.<br />
<br />
==== Inputs ====<br />
<br />
The YubiKey takes inputs in the form of:<br />
<br />
* API calls sent to it via the USB interface.<br />
* short button press<br />
* long button press<br />
<br />
==== Outputs ====<br />
<br />
The YubiKey transforms these inputs into outputs in the form of:<br />
<br />
* Sending keystroke keycodes (emulating a USB keyboard and typing for you) <br> This is used to:<br />
** type the static password<br />
** type the OTP<br />
<br />
* Sending back a Response via the API (over the USB interface). <br> This is used to send back:<br />
** the response of a Challenge-Response request (calculated using either Yubico OTP mode or HMAC-SHA1 mode)<br />
** the response of a U2F Challenge-Response request<br />
** the response of a CCID Smartcard related request<br />
<br />
=== The button ===<br />
<br />
The button activates by slightly touching it. Sometimes it even reacts when you are very close but are not touching it yet.<br />
<br />
Depending on the context, touching the button does one of these things:<br />
<br />
* triggering a function (like triggering the output of a static password or of a one-time password (OTP))<br />
* confirming / allowing a function or access<br />
* inserting / ejecting the smartcard<br />
<br />
In the OTP mode a short press yields slot 1 and a long press yields slot 2.<br />
<br />
=== USB connection modes ===<br />
<br />
Depending on the YubiKey model, the device provides up to three<br />
different USB interfaces with their associated protocols. Two of the<br />
interfaces implement the USB HID (Human Interface Device) device<br />
class; the third is a smart card interface (CCID). The YubiKey is a<br />
multi-function USB device, just like a USB printer that can also<br />
function as a scanner.<br />
<br />
The following table shows which interfaces the different applications<br />
use:<br />
<br />
{| class="wikitable"<br />
! Application !! USB Interface<br />
|-<br />
|OTP || Keyboard HID<br />
|-<br />
|FIDO || Other HID<br />
|-<br />
|PIV || CCID<br />
|-<br />
|OpenPGP || CCID<br />
|-<br />
|OATH || CCID<br />
|}<br />
<br />
All three interfaces can be independently enabled or disabled.<br />
The ykman program uses the term "manage connection modes" and uses<br />
OTP, FIDO, and CCID as selectors for which modes should be enabled.<br />
<br />
{{Note|The old U2F mode has been renamed and is now called FIDO in ykman 0.6.1 and later (released<br />
2018-04-16) https://developers.yubico.com/yubikey-manager/Release_Notes.html}}<br />
<br />
The set of enabled USB interfaces affects which applications on the<br />
key can be accessed. As an example, if only the HID interfaces are<br />
enabled, the applications dependent on the CCID interface are<br />
unavailable.<br />
<br />
Which application on the key is chosen is determined by the host<br />
application and is a combination of USB interface and an application<br />
selection mechanism. For example, if the host application wants to<br />
communicate with the PIV application on the key, it accesses the key<br />
using the CCID interface and using the protocols defined by CCID sends<br />
a 'select application' command to the key selecting the PIV application.<br />
<br />
==== Get enabled modes ====<br />
<br />
{{ic|ykman mode}} will tell you what modes are currently activated/enabled/available.<br />
This could output something like<br />
{{bc|Current connection mode is: OTP+U2F+CCID}}<br />
Meaning that currently the OTP, U2F and CCID subsystem of the key are enabled.<br />
<br />
==== Set the enabled modes ====<br />
<br />
{{ic|ykman mode <MODE>}} will allow you to define which modes should be activated/enabled/available. <br />
* {{ic|<MODE>}} can be a string, such as {{ic|OTP+U2F+CCID}}, or a shortened form {{ic|o+u+c}}.<br>With "+" you can combine multiple modes that you wish to be enabled.<br />
* {{ic|<MODE>}} can be a mode-number, which is one number that encodes several enabled modes (like flags) into one value.<br>The only valid modes when using numbers is 0 - 6 ([https://github.com/Yubico/yubikey-manager/blob/master/ykman/util.py#L94 see here]). The extra flags are not part of the mode in that sense, they just need to be set at the same time as the mode is set.<br />
<br />
Usually what you want is to make all functionality available (you will still need to potentially configure stuff, see functionality sections below for more details).<br />
In order to do so you can use:<br />
<br />
{{ic|ykman mode c+u+o}} or {{ic|ykman mode 6}}<br />
<br />
{{Note|Using the "80" mode-number or the corresponding {{ic|--touch-eject}} parameter of {{ic|ykman mode}} can only be used when the device is ''only'' in CCID mode (by running {{ic|ykman mode ccid --touch-eject}} for instance).<br />
<br />
Once the {{ic|--touch-eject}} flag is set, you should be able to eject/insert the smartcard by pressing the button. The LED should indicate if the card is inserted or not as well.<br />
}}<br />
<br />
{{Warning|But using the 80 mode-number or the corresponding {{ic|--touch-eject}} is not recommend as it would prevent you from using the U2F and OTP features of the YubiKey.}}<br />
<br />
{{Note|The often seen:<br />
<br />
{{ic|ykman mode c+u+o --touch-eject}} or {{ic|ykman mode 86}}<br />
<br />
will ignore the {{ic|--touch-eject}} and be identical to the above recommended {{ic|ykman mode 6}}.<br />
<br />
86 is not a valid mode. It might be a bug that the tool accepts higher values ([https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 see here]).}}<br />
<br />
=== Two Slots ===<br />
<br />
Only if the OTP mode is activated (see Modes of the YubiKey below), the Yubikey provides 2 slots.<br />
<br />
If the transport mode OTP is enabled, the two YubiKey Slots, long press and short press, can be configured and used.<br />
<br />
==== Configuration of the slots ====<br />
<br />
These slots can have one of the following credentials configured: a [https://developers.yubico.com/OTP/ Yubico OTP] (which is what comes preconfigured in the short press slot on a new key), a static password, a challenge-response credential, an OATH-HOTP credential. All this functionality is found in the {{ic|ykman otp}} commands.<br />
<br />
{{Note|A slot has either a Yubico OTP or a challenge-response credential configured. More general: One, and only one, type of the above listed possible credential per slot.}}<br />
<br />
There are several flags that can be set during the configuration of the slots.<br />
These flags /cannot/ be read from the device once written. However, the behaviour of the device should change when the flags are set ;)<br />
<br />
{{Note|Actually most of (all of??) the parameters and details you use during configuration of the slots, cannot be read back, once written to the YubiKey.}}<br />
<br />
=== The LED ===<br />
<br />
The YubiKey has a small green LED able to communicate with you.<br />
Its message to you actually depends on the currently used [[#USB connection modes]] of your YubiKey.<br />
<br />
The possible messages are:<br />
* *steady on*: Press now, to allow access. (typically (TODO exclusively?) U2F mode)<br />
* *slow blinking*: Power/setting up/ready for use (TODO explain)<br />
* *rapid blinking*: Error, configuring driver (TODO explain)<br />
<br />
{{Note|If the CCID mode is turned on, then the LED of the key is always shortly flashing every two-three seconds once inserted.<br>You can turn the blinking off by disabling the CCID mode. This slow blinking just shows that the device has power, alternatively it shows a need for a button press. On Windows this behavior will typically stop once drivers are installed and it is ready for use. Mac and Linux systems will keep blinking; here [https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 the best current workaround] to get the LED to blink less is to disable CCID.}}<br />
<br />
=== Initial configuration ===<br />
<br />
On a new YubiKey the Yubico OTP is preconfigured on slot 1. <br />
<br />
{{Warning|Before you overwrite your slot 1, please be aware that one is not able to reconfigure the same trust level [https://forum.yubico.com/viewtopic12ca.html?f%3D16&t%3D1960 see here]. Meaning:<br />
<br />
One could think that it is a good idea to reset configuration slot 1 to a new OTP. But then a "VV" prefix in your credentials must be used. Whereas the factory credentials on your Yubikey use a "CC" prefix. You can upload a "VV" credential using the Yubico personalization tool GUI or manually upload the new AES key to the [https://upload.yubico.com/ yubico.com website] in order to regain the same functionality than with the original factory configuration. VV credentials are not less secure than CC. However some services may only trust CC credentials as they believe that the user process is more prone to security vulnerabilities. This is because you could have malware on your machine or someone intercepting your key when sending it to the YubiCloud.<br />
}}<br />
<br />
=== Limitations of the passwords typed by YubiKey via USB-keyboard -- or "Why do my password look so weak ?" ===<br />
<br />
The YubiKey can type passwords (OTP or Static Password) for you by acting as USB keyboard and sending scan-codes like if you would type.<br />
<br />
A limitation of the YubiKey, however, prevents you from choosing characters that require a modifier key other than Shift.<br />
And in order for the YubiKey to work with all possible keyboard layouts (e.g. the {{ic|Z}} on a German keyboard has a different scan-code than the {{ic|Z}} on a US keyboard) it is necessary to limit the characters used by YubiKey passwords to the ModHex alphabet + Digits (0-9) (+ optionally "!" as the only available Symbol in static passwords).<br />
<br />
The 16 characters used in the ModHex alphabet are: {{ic|c,b,d,e,f,g,h,i,j,k,l,n,r,t,u,v}}. These characters share a property that makes them very valuable to a YubiKey: They use the same scan codes across a very large number of keyboard layouts. In other words, the scan code 0x06 maps to the character c for English, Swedish, German, French, and many others.<br />
<br />
[https://www.yubico.com/wp-content/uploads/2015/11/Yubico_WhitePaper_Static_Password_Function.pdf See here for full info]<br />
<br />
== One-time password ==<br />
<br />
=== Yubico OTP mode ===<br />
<br />
The Yubico OTP mode is AES symmetric key based. On a new YubiKey the Yubico OTP is preconfigured on slot 1. This initial AES symmetric key is stored in the YubiKey and the same AES key is already stored on the Yubico Authentication server. This allows validating against YubiCloud, meaning the use of Yubico OTP in combination with the Yubico Forum website for instance or on https://demo.yubico.com).<br />
<br />
The initial configuration and AES key stored in slot 1 can of course be overwritten.<br />
<br />
{{Warning|Please read [[#Initial configuration]] before you overwrite the intial configuration of slot 1 that your YubiKey comes shipped with.}}<br />
<br />
==== How does it work ====<br />
<br />
Yubikey's authentication protocol is based on [[Wikipedia:Symmetric_cryptography|symmetric cryptography]].<br />
More specifically, each YubiKey contains a 128-bit [[Wikipedia:Advanced_Encryption_Standard|AES]] key unique to that device.<br />
It is used to encrypt a token made of different fields such as the ID of the key, a counter, a random number, etc.<br />
The OTP is made from concatenating the ID of the key with this encrypted token.<br />
<br />
This OTP is sent to the target system to which we want to authenticate.<br />
This target system asks a validation server if the OTP is good.<br />
The validation server has a mapping of YubiKey IDs -> AES key.<br />
Using the key ID in the OTP, it can thus retrieve the AES key and decrypt the other part of the OTP.<br />
If it looks OK (plain-text ID and encrypted ID are the same, the counter is bigger than the last seen one to prevent [[wikipedia:Replay_attack|replay attacks]], then authentication is successful.<br />
<br />
The validation server sends that authentication status back to the target system, which grants access or not based on that response.<br />
<br />
==== Security risks ====<br />
<br />
===== AES key compromise =====<br />
<br />
As you can imagine, the AES key should be kept secret.<br />
It cannot be retrieved from the YubiKey itself (or it should not, at least not with software).<br />
It is present in the validation server though, so the security of this server is very important.<br />
<br />
===== Validation requests/responses tampering =====<br />
<br />
Since the target system relies on the ruling of the validation server, a trivial attack would be to impersonate the validation server.<br />
The target system thus needs to authenticate the validation server.<br />
2 methods are available :<br />
* '''HMAC''': This is also symmetric cryptography, the target server and validation server share a key that is used to sign requests and responses.<br />
* '''TLS''': Requests and responses travel via HTTP, so TLS (HTTPS) can be used to authenticate and encrypt the connection.<br />
<br />
==== YubiCloud and validation servers ====<br />
<br />
When you buy a YubiKey, it is preloaded with an AES key that is known only to Yubico.<br />
They will not even communicate it to you.<br />
Yubico provides a validation server with free unlimited access (YubiCloud).<br />
It also offers open-source implementations of the server.<br />
<br />
So you can either:<br />
* choose to use your YubiKey with its preloaded AES key and validate against Yubico's validation server ;<br />
* or load a new AES key in your YubiKey and run your own validation server.<br />
<br />
{{Note|To authenticate the Yubico validation server, you can:<br />
* '''with HMAC''': use https://upgrade.yubico.com/getapikey/ to get an HMAC key and ID<br />
* '''with HTTPS''': the validation server's certificate is signed by GoDaddy, and is thus trusted by default in Arch installs (at least if you have package ca-certificates)}}<br />
<br />
=== OATH-HOTP mode (RFC 4226) ===<br />
<br />
{{Expansion|Empty section.}}<br />
<br />
== Challenge-Response ==<br />
<br />
=== Function and Application of Challenge-Response ===<br />
This technique can be used to authenticate.<br />
<br />
A challenge is sent to the YubiKey and a response is (auto-magically) calculated and send back.<br />
This calculation needs a secret (e.g. an AES key in case of the Yubico OTP mode)<br />
The same challenge always results in the same response.<br />
Without the secret this calculation is not meant to be feasable. Even if in the possession of many challenge-response pairs.<br />
<br />
This can be used for:<br />
* true 2-factor (possession and knowledge) authentication:<br>If you combine the response (possession factor) with a password (knowledge factor) and to authenticate you need to present the triple (challenge,response, password) to 3rd party. In which case the challenge and the corresponding response can be (publicly) send to a 3rd party to authenticate the possession factor, by redoing basically the same (auto-magical) calculation. The needed secret needs to be shared with 3rd party to allow an authentication.<br />
<br />
* semi 2-factor (possession and knowledge) authentication:<br>The challenge can be public. Only with the possession of the YubiKey hardware the response can be generated. This can be used to create a "sort-of" 2-factor authentication (possession and knowledge): If you combine the response (possession factor) with a password (knowledge factor) and use the result for instance as passphrase for cryptsetup.<br />
<br />
This functionality will consume one slot. And it is used via API calls to the YubiKey. So you usually use some tool to communicate the challenge to your YubiKey and get back the response.<br />
<br />
There are two Challenge-Response modes:<br />
* Yubico OTP mode <br />
* HMAC-SHA1 mode<br />
<br />
=== Setup the slot ===<br />
<br />
One way to setup slot {{ic|2}} in challenge-response mode ({{ic|-ochal-resp}}) is with {{ic|ykpersonalize}}:<br />
<br />
{{bc|ykpersonalize -v -2 -ochal-resp -ochal-hmac -ohmac-lt64 -oserial-api-visible -ochal-btn-trig}}<br />
<br />
Check with {{man|1|ykpersonalize}} to make sure that the options used above are right for you. You may also enable challenge-response mode using graphical interface through {{pkg|yubikey-personalization-gui}}.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the '''Warning''' under [[#Initial configuration]].}}<br />
<br />
=== Use the slot - get a response for a challenge ===<br />
<br />
To use a Challenge-Response slot (no matter which mode):<br />
<br />
{{bc|ykchalresp -2 <CHALLENGE>}}<br />
<br />
== U2F ==<br />
<br />
{{Expansion}}<br />
<br />
=== Enabling U2F in the browser ===<br />
<br />
==== Chromium/Chrome ====<br />
<br />
[[Chromium/Tips and tricks#U2F authentication]]<br />
<br />
==== Firefox ====<br />
<br />
[[Firefox/Tweaks#Fido U2F authentication]]<br />
<br />
== CCID Smartcard ==<br />
<br />
CCID (Chip Card Interface Device) is a USB standard device class for use by USB devices that act as smart card readers or with security tokens that connect directly via USB, like the Yubikey. HID (Human Interface Device) and CCID are both USB device classes, i.e. they are in the same category of USB specifications. HID is a specification for computer peripherals, like keyboards. The Yubikey works like a USB (HID) keyboard when used in the OTP and U2F modes, but switches to the CCID protocol when using the PIV application, or as an OpenPGP device.<br />
<br />
CCID mode should be enabled by default on all YubiKeys shipped since November 2015 [https://www.yubico.com/support/knowledge-base/categories/articles/use-yubikey-yubikey-windows-hello-app/]. Enable at least the CCID mode. Please see [[#Set the enabled modes]].<br />
<br />
=== PIV ===<br />
<br />
Starting from the fourth generation devices, the Yubikeys contain a PIV (Personal Identity Verification) application on the chip. PIV is a US government standard (FIPS 201) that specifies how a token using RSA or ECC (Elliptic Curve Cryptography) is used for personal electronic identification. The distinguishing characteristic of a PIV token is that it is built to protect private keys and operate on them on-chip. A private key never leaves the token after it has been installed on it. Optionally, the private key can even be generated on-chip with the aid of an on-chip random number generator. If generated on-chip, the private key is never handled outside of the chip, and there is no way to recover it from the token. When using the PIV mechanism, the Yubikey functions as a CCID device.<br />
<br />
=== Use OpenPGP smartcard mode ===<br />
<br />
See [[GnuPG#Smartcards]]<br />
<br />
=== Using a YubiKey with SSH ===<br />
<br />
The following example describes how to use a YubiKey for [[SSH keys]]. A YubiKey with the PIV (Personal Identification Verification) application is required; this means you need a YubiKey NEO or YubiKey 4 or later.<br />
<br />
==== Generating a key pair on the YubiKey ====<br />
<br />
A private key and associated certificate need to be either generated on the YubiKey or imported to it. Install the {{Pkg|yubikey-manager}}<br />
package. Insert the YubiKey in a USB port and check that it is recognized:<br />
<br />
$ ykman list<br />
YubiKey 4 [OTP+FIDO+CCID] Serial: 1234567<br />
<br />
The following two commands ({{ic|generate-key}} and {{ic|generate-certificate}}) require providing the PIV application's 24-byte management key, if it has been changed from its default value (recommended). The examples below assume the shell variable {{ic|MK}} has been set in advance to the 48 character hex string representation of the management key. For example:<br />
<br />
$ MK=AB019982CA48BDC6776B1F9A0A3E129FDE0705D219AF0037<br />
<br />
Generate a 2048-bit RSA key pair on the YubiKey. The private key will be stored in key slot 9a on the YubiKey, and the public key will be<br />
written to the file {{ic|pubkey.pem}}.<br />
<br />
$ ykman piv generate-key -m $MK -a RSA2048 9a pubkey.pem<br />
<br />
Next, use the YubiKey to generate a self-signed certificate for the public key:<br />
<br />
$ ykman piv generate-certificate -m $MK -d 1826 -s "SSH Key" 9a pubkey.pem<br />
<br />
The Subject field in the certificate will be set to "SSH Key" with the {{ic|-s}} option. This field will be included in the prompt for PIN to help identify which key is used for authentication. The example command also specifies the {{ic|-d}} option to set the number of days until the certificate expires. If the {{ic|-d}} option is omitted, a default value of 365 days is used.<br />
<br />
Note that the last parameter in the {{ic|generate-key}} command is the file name where the public key is written to, whereas the last parameter in the {{ic|generate-certificate}} command specifies where the public key is read from. The certificate is constructed and signed on the YubiKey and stored alongside the private key; the command does not output the certificate.<br />
<br />
At this point the YubiKey is ready for authenticating to a SSH server. For this to happen, some additional configuration on both the client and the server is required.<br />
<br />
==== Client configuration ====<br />
<br />
The standard API used to communicate with cryptographic tokens is defined by [[wikipedia:PKCS_11|PKCS#11]].<br />
Install the {{Pkg|opensc}} package which provides this API in the form of the shared library {{ic|/usr/lib/opensc-pkcs11.so}}. The ssh client should be configured to use this library with the directive PKCS11Provider in {{ic|~/.ssh/config}}:<br />
<br />
{{hc|~/.ssh/config|PKCS11Provider /usr/lib/opensc-pkcs11.so}}<br />
<br />
==== Public key conversion ====<br />
<br />
The {{ic|pubkey.pem}} file contains the public key in PEM (Privacy Enhanced Mail) format. OpenSSH uses a different format defined in RFC 4253,<br />
section 6.6, so the PEM formatted key should be converted to the format OpenSSH understands. This can be done using {{ic|ssh-keygen}}:<br />
<br />
$ ssh-keygen -i -m PKCS8 -f pubkey.pem > pubkey.txt<br />
<br />
This command uses the import ({{ic|-i}}) function of the {{ic|ssh-keygen}}, specifies PKCS8 as the input file format ({{ic|-m}}), and reads the input from the ({{ic|-f}}) file {{ic|pubkey.pem}}. The converted key is written on standard output, which is the example is redirected to the file {{ic|pubkey.txt}}.<br />
<br />
The converted public key should now be copied to the remote server as described in [[SSH keys#Copying the public key to the remote server]].<br />
<br />
==== Initiating an SSH session with the YubiKey ====<br />
<br />
To authenticate a SSH connection using the YubiKey, just use ''ssh'' normally. You will be prompted for the PIN instead of a password:<br />
<br />
$ ssh remote<br />
Enter PIN for 'SSH Key' <br />
[user@remote ~]$ <br />
<br />
==== Using ssh-agent to cache the PIN ====<br />
<br />
ssh-agent (see [[SSH keys#SSH agents]]) can also be used with the PKCS#11 library; in this case the PIN code is cached instead of the private key.<br />
<br />
$ ssh-add -s /usr/lib/pkcs11/opensc-pkcs11.so<br />
<br />
As long as the PIN is cached in by the agent, the cached value is used and the user is not prompted for it.<br />
<br />
==== Further reading ====<br />
<br />
The default PIN code of the PIV application on the YubiKey is {{ic|123456}}; you may want to change it. The YubiKey also requires a 24-byte management key for administrative functions like key generation. If the management key has been changed from its default value, the new value needs to be specified using the {{ic|-m}} option on the command line for certain commands. See [https://developers.yubico.com/PIV/ What is PIV?]<br />
<br />
== Tips and tricks ==<br />
<br />
=== YubiKey and LUKS encrypted partition/disk ===<br />
<br />
YubiKey can be used to strengthen the security of your [[LUKS]] encrypted partition/disk. There are multiple ways to achieve it. But before enabling Yubikey as a 2FA device it is recommended to setup plain LUKS encryption first and make sure it works correctly.<br />
<br />
==== Challenge-Response mode for LUKS passphrase ====<br />
<br />
One way to do it is to use a Challenge-Response mode for creating strong LUKS passphrases. First, install {{Pkg|yubikey-full-disk-encryption}} package. Using this tool you can add/modify/remove Yubikey-protected passphrases.<br />
<br />
Make changes to {{ic|/etc/ykfde.conf}} configuration file as as:<br />
* choose Yubikey slot to use for LUKS ({{ic|YKFDE_CHALLENGE_SLOT}})<br />
* whether you want to type a password at boot ({{ic|YKFDE_CHALLENGE_PASSWORD_NEEDED}}) or use predefined password ({{ic|YKFDE_CHALLENGE}}) which essentially means you check for Yubikey hardware presence only.<br />
<br />
LUKS supports multiple password so you need to select a slot that is going to store Yubikey-protected passphrase. Inspect existing slots using command:<br />
<br />
# cryptsetup luksDump /dev/<DISK><br />
<br />
Check entries under {{ic|Keyslots:}} section. And then pick an unused slot.<br />
<br />
Enroll your new passphrase:<br />
<br />
# ykfde-enroll -d /dev/<DISK> -s <LUKS_SLOT><br />
<br />
It will require the new and existing passphrases.<br />
<br />
And the last step is to add {{ic|ykfde}} hook to {{ic|/etc/mkinitcpio.conf}} file before or instead of {{ic|encrypt}} hook. Then regenerate initramfs with {{ic|mkinitcpio -P}}.<br />
<br />
{{Warning|As of December 2019 `sd-encrypt` enabled boot is [https://github.com/agherzan/yubikey-full-disk-encryption/issues/14 not supported] by {{Pkg|yubikey-full-disk-encryption}}.}}<br />
<br />
==== OpenPGP applet ====<br />
<br />
Another way of using YubiKey for full disk encryption is to utilize its OpenPGP applet to decrypt the LUKS keyfile during boot. [https://github.com/fuhry/initramfs-scencrypt initramfs-scencrypt] is a set of hooks for initramfs that automate this process.<br />
<br />
==== HMAC Secret Extension of FIDO2 protocol ====<br />
<br />
Yet another way of using YubiKey for full disk encryption is to utilize [https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#sctn-hmac-secret-extension HMAC Secret Extension] to retrieve the LUKS password from YubiKey which is protected by passphrase supplied by user. This functionality requires at least [https://support.yubico.com/support/solutions/articles/15000027138-yubikey-5-2-3-enhancements-to-fido-2-support YubiKey 5 with firmware 5.2.3+].<br />
<br />
In order to use this install {{AUR|fido2-hmac-secret}} and follow instructions available in [https://github.com/mjec/fido2-hmac-secret/wiki/Arch-Linux-LUKS-configuration project documentation].<br />
<br />
=== Yubikey and KeePass ===<br />
<br />
{{Style|Duplicates [[KeePass]].}}<br />
<br />
Yubikey can be integrated with [[KeePass]] using [[KeePass#Yubikey|plugins]].<br />
<br />
For a native open-source implementation of KeePass have a look at:<br />
<br />
==== keepassx2 ====<br />
<br />
{{AUR|keepassx2}} ([https://keepassx.org/ see keepassx.org]) a keepass QT FOSS reimplementation, extremely stable and available for Windows, MacOSX and Linux.<br />
<br />
==== KeePassXC ====<br />
<br />
{{Pkg|keepassxc}} ([https://keepassxc.org/ see keepassxc.org]) a KeePassX fork that integrated YubiKey into KeePassX v2.<br>The integration covers Challenge-Response as security factor to open the database, but also the generation of OTP using the YubiKey.<br />
<br />
In order to have a KeePassXC database work on Android (using the [https://play.google.com/store/apps/details?id=keepass2android.keepass2android Keepass2Android app]), you need to use version 1.06 of the app. You also need to save the database file in the KDBX 4 format, since Keepass2Android do not support the KDBX 3 format.<br />
<br />
YubiKey support in Keepass2Android (which is compatible with KeePassXC) is tracked [https://github.com/PhilippC/keepass2android/issues/4 on GitHub].<br />
<br />
=== Two-factor authentication with SSH ===<br />
<br />
{{Note|See also: https://developers.yubico.com/yubico-pam/Yubikey_and_SSH_via_PAM.html}}<br />
<br />
This details how to use a Yubikey to have [[wikipedia:Two-factor_authentication|two-factor authentication]] with SSH, that is, to use both a password and a YubiKey OTP.<br />
<br />
==== Prerequisites ====<br />
<br />
Install {{Pkg|yubico-pam}}.<br />
<br />
{{Note|If you are configuring a distant server to use YubiKey, you should open at least one additional, rescue SSH session, so that you are not locked out of your server if the configuration does not work and you exit your main session inadvertently}}<br />
<br />
{{Note|The following assumes you are using the default Yubico servers. See the [https://github.com/Yubico/yubico-pam yubico-pam documentation] for options relevant to using your own server.}}<br />
<br />
==== Configuration ====<br />
<br />
===== Authorization Mapping Files =====<br />
<br />
A mapping must be made between the YubiKey token ID and the user ID it is<br />
attached to. There are two ways to do this, either centrally in one file, or<br />
individually, where users can create the mapping in their home directories.<br />
If the central authorization mapping file is being used, user home directory<br />
mappings will not be used and vice versa.<br />
<br />
====== Central authorization mapping ======<br />
<br />
Create a file {{ic|/etc/yubico/authorized_yubikeys}}, the file must contain a user name and the<br />
YubiKey token ID separated by colons (same format as the passwd file) for<br />
each user you want to allow onto the system using a YubiKey.<br />
<br />
The mappings should look like this, one per line:<br />
<br />
<first user name>:<Yubikey token ID1>:<Yubikey token ID2>:...<br />
<second user name>:<Yubikey token ID3>:<Yubikey token ID4>:...<br />
<br />
You can specify multiple key tokens to correspond to one user, but only one is required.<br />
<br />
====== Per-user authorization mapping ======<br />
<br />
Each user creates a {{ic|~/.yubico/authorized_yubikeys}} file inside of their home<br />
directory and places the mapping in that file, the file must have only one<br />
line:<br />
<br />
<user name>:<Yubikey token ID1>:<Yubikey token ID2><br />
<br />
This is much the same concept as the SSH {{ic|authorized_keys}} file.<br />
<br />
Note that this file must be readable by the {{ic|pam_yubico}} module when the user is authenticated, otherwise login will fail. If this is not possible or desired, use the global mapping file instead.<br />
<br />
====== Obtaining the YubiKey token ID (a.k.a. public ID) ======<br />
<br />
You can obtain the YubiKey token ID in several ways. One is by<br />
removing the last 32 characters of any OTP (One Time Password)<br />
generated with your YubiKey. Another is by using the<br />
[http://demo.yubico.com/php-yubico/Modhex_Calculator.php modhex calculator].<br />
<br />
Enter your YubiKey OTP and convert it, your Yubikey token ID is 12<br />
characters and listed as:<br />
<br />
Modhex encoded: XXXXXXX<br />
<br />
===== PAM configuration =====<br />
<br />
Having set up the {{ic|pam_yubico}} module, you next need to tell PAM to use it when logging in via SSH. There are several ways of doing this.<br />
<br />
====== The default way ======<br />
<br />
Obtain HMAC credentials from Yubico as described in [[#YubiCloud and validation servers]]. You will receive a Client ID and a secret key.<br />
<br />
Add one of the two following lines to the beginnning of {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID authfile=/etc/yubico/authorized_yubikeys<br />
<br />
if you are using a central authorization mapping file, or<br />
<br />
auth required pam_yubico.so id=CLIENTID<br />
<br />
if you are using per-user authorization mapping, where {{ic|CLIENTID}} is your Client ID. This method utilizes your ID and the server's certificate to authenticate the connection.<br />
<br />
{{Note|This will authenticate via Yubico's free YubiCloud servers. If you want to use a different server, add it via the {{ic|urllist}} parameter.}}<br />
<br />
====== Using pure HMAC to authenticate the validation server ======<br />
<br />
Add {{ic|key}} to the above lines in {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID key=SECRETKEY ...<br />
<br />
where {{ic|CLIENTID}} and {{ic|SECRETKEY}} are your HMAC ID and key.<br />
<br />
You should also disallow unprivileged users to read the file to prevent them from seeing the HMAC credentials:<br />
# chmod o-r /etc/pam.d/sshd<br />
<br />
{{Note|HMAC credentials should be unique to a single target server. That way, if an attacker finds them, he will not be able to craft responses to authenticate to other target servers you own}}<br />
<br />
====== Using pure HTTPS to authenticate the validation server ======<br />
<br />
{{Warning|While this "old" method of using a dummy id still works, it is unknown how secure and/or future-proof it is, as Yubico no longer describes it in their documentation. Proceed at your own risk. At the very least you should ensure that only HTTPS servers with valid certificates are used for authentication.}}<br />
<br />
If you do not want to use HMAC credentials from Yubico, it is still possible to authenticate via the Yubico server by setting {{ic|1=CLIENTID=1}} instead of your own ID. Although {{ic|pam_yubico}}'s default server uses HTTPS already, for security reasons you should specify it manually via the {{ic|urllist}} parameter, as the servers certificate is the only way in which the connection is authenticated. You can find the keyserver URL by adding the {{ic|debug}} parameter to the {{ic|auth}} line.<br />
<br />
===== SSHD configuration =====<br />
<br />
You should check that {{ic|/etc/ssh/sshd_config}} contains these lines and that they are not commented. The {{ic|sshd_config}} shipped with {{pkg|openssh}} has these set correctly by default.<br />
ChallengeResponseAuthentication no<br />
UsePAM yes<br />
<br />
==== That is it! ====<br />
<br />
You should not need to restart anything if you did not change the SSHD config file.<br />
<br />
To log in, at the {{ic|Password:}} prompt of SSH, you have to type your password '''without pressing enter''' and touch the YubiKey's button.<br />
The YubiKey should send a return at the end of the OTP so you do not need to touch the enter key at all.<br />
<br />
You can display information about the login data generated by {{ic|pam_yubico}} by adding the {{ic|debug}} option to the auth line in{{ic|/etc/pam.d/sshd}}. However, if you are using a central authorization file, you should remove that option once finished testing, as it causes {{ic|pam_yubico}} to display the entire content of the central file to every user who logs in using a YubiKey.<br />
<br />
==== Explanation ====<br />
<br />
This works because the prompt is {{ic|pam_yubico.so}}'s one, since this module is before {{ic|pam_unix.so}}, which normally does basic password authentication.<br />
So, you are giving a string that is the concatenation of your password and the OTP to {{ic|pam_yubico.so}}.<br />
Since the OTPs have a fixed length (let us call this size N), it just has to get the last N characters to retrieve the OTP, and it assumes that the other characters at the start are the password.<br />
It tries to validate the OTP, and in case of success, sends the password to the next PAM module. In Archlinux' default PAM stack, the authenticator {{ic|pam_unix.so}} is instructed to try receiving a password from the previous module with {{ic|try_first_pass}}, so it automatically uses the password sent by {{ic|pam_yubico.so}}.<br />
<br />
=== Executing actions on insertion/removal of YubiKey device ===<br />
<br />
For example, you want to perform an action when you pull your YubiKey out of the USB slot, create {{ic|/etc/udev/rules.d/80-yubikey-actions.rules}} and add the following contents:<br />
ACTION=="remove", ENV{ID_MODEL}=="Yubikey_4_OTP+U2F+CCID", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0407", RUN+="/usr/local/bin/script args"<br />
<br />
Please note, that this example is for the YubiKey 4, and you will have to look at the output of {{ic|lsusb}} to get the vendor and model ID's, along with the description of the device. Of course, to execute a script on insertion, you would change the action to 'add' instead of remove.<br />
<br />
== Maintenance / Upgrades ==<br />
<br />
=== Installing the OATH Applet for a YubiKey NEO ===<br />
<br />
These steps will allow you to install the OATH applet onto your YubiKey NEO. This allows the use of Yubico Authenticator in the Google Play Store.<br />
{{Note|1=These steps are only for NEOs with a firmware version <= 3.1.2. The current generation NEOs (with U2F) come with the OpenPGP applet already installed)}}<br />
<br />
==== Configure the NEO as a CCID Device ====<br />
<br />
# Install {{pkg|yubikey-personalization-gui}} ({{AUR|yubikey-personalization-gui-git}}).<br />
# Add the udev rules and reboot so you can manage the YubiKey without needing to be root<br />
# Run {{ic|ykpersonalize -m82}}, enter {{ic|y}}, and hit enter.<br />
<br />
==== Install the Applet ====<br />
<br />
# Install {{AUR|gpshell}}, {{AUR|gppcscconnectionplugin}}, {{AUR|globalplatform}}, and {{Pkg|pcsclite}}.<br />
# [[Start]] {{ic|pcscd.service}}.<br />
# Download the most recent CAP file from the [http://opensource.yubico.com/ykneo-oath/releases.html ykneo-oath] site.<br />
# Download {{ic|gpinstall.txt}} from [https://github.com/Yubico/ykneo-oath/blob/master/gpinstall.txt GitHub].<br />
# Edit the line in gpinstall.txt beginning with {{ic|install -file}} to reflect the path where the CAP file is located.<br />
# Open a terminal and run {{ic| gpshell <location of gpinstall.txt>}}<br />
# Ideally, a bunch of text will scroll by and it ends saying something like<br />
{{ bc | Command --> 80E88013D7C000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A100<br />
Wrapped command --> 84E88013DFC000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A15D848CB77<br />
27D0EDA00<br />
Response <-- 009000<br />
Command --> 80E60C002107A000000527210108A00000052721010108A000000527210101010003C901000000<br />
Wrapped command --> 84E60C002907A000000527210108A00000052721010108A000000527210101010003C9010000B4648127914A4C7C00<br />
Response <-- 009000<br />
card_disconnect<br />
release_context}}<br />
# Unplug the NEO and try it with the Yubico Authenticator app<br />
<br />
==== (Optional) Install the Yubico Authenticator Desktop client ====<br />
<br />
You can get the desktop version of the Yubico Authenticator by installing {{Pkg|yubico-yubioath-desktop}}{{Broken package link|package not found}}.<br />
<br />
While {{ic|pcscd.service}} is running, run {{ic|yubioath-gui}} and insert your Yubikey when prompted.<br />
<br />
== Troubleshooting ==<br />
<br />
Restart, especially if you have completed updates since your YubiKey last worked. Do this even if some functions appear to be functioning.<br />
<br />
=== YubiKey not acting as HID device ===<br />
Add udev rule as described in [https://michaelheap.com/yubikey-on-arch/ this article]:<br />
<br />
{{hc|/etc/udev/rules.d/10-security-key.rules|2=<br />
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="users", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0"<br />
}}<br />
<br />
Run {{ic|udevadm trigger}} afterwards.<br />
<br />
You may also need to [[install]] the package {{pkg|libu2f-host}} if you want support in chrome.<br />
<br />
=== ykman fails to connect to the YubiKey ===<br />
<br />
If the manager fails to connect to the YubiKey, make sure you have started {{ic|pcscd.service}} or {{ic|pcscd.socket}}.<br />
<br />
=== YubiKey fails to bind within a guest VM ===<br />
<br />
Assuming the YubiKey is available to the guest, the issue results from a driver binding to the device on the host. To unbind the device, the bus and port information is needed from {{ic|dmesg}} on the host:<br />
<br />
$ dmesg | grep -B1 Yubico | tail -n 2 | head -n 1 | sed -E 's/^\<nowiki>[[^]]</nowiki>+\] usb (<nowiki>[^:]</nowiki>*):.*/\1/'<br />
<br />
The resulting USB id should be of the form {{ic|X-Y.Z}} or {{ic|X-Y}}. Then, on the host, use {{ic|find}} to search {{ic|/sys/bus/usb/drivers}} for which driver the YubiKey is binded to (e.g. {{ic|usbhid}} or {{ic|usbfs}}).<br />
<br />
$ find /sys/bus/usb/drivers -name "*X-Y.Z*"<br />
<br />
To unbind the device, use the result from the previous command (i.e. {{ic|/sys/bus/usb/drivers/<DRIVER>/X-Y.Z:1.0}}):<br />
<br />
# echo 'X-Y.Z:1.0' > /sys/bus/usb/drivers/<DRIVER>/unbind<br />
<br />
=== Error: [key] could not be locally signed or gpg: No default secret key: No public key ===<br />
<br />
Occurs when attempting to sign keys on a non-standard keyring while a YubiKey is plugged in, e.g. as [[Pacman/Package_signing|Pacman]] does in {{ic|pacman-key --populate archlinux}}. The solution is to remove the offending YubiKey and start over.</div>Tepleshttps://wiki.archlinux.org/index.php?title=YubiKey&diff=595011YubiKey2020-01-14T14:37:18Z<p>Teples: /* Tips and tricks */ Move warning to relevant section it relates to instead of introductory paragraph</p>
<hr />
<div>[[Category:Authentication]]<br />
[[ja:Yubikey]]<br />
{{Accuracy|The article lacks sources, is interspersed with TODOs and probably out of date.}}<br />
{{Style|ykman-specifics should be grouped together.}}<br />
This article describes how [https://yubico.com Yubico]'s [[Wikipedia:YubiKey|YubiKey]] works and how you can use it.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the warning under [[#Initial configuration]].}}<br />
<br />
== Introduction ==<br />
<br />
The YubiKey is a small [[Wikipedia:Security token|USB Security token]] that supports:<br />
<br />
* generating [[Wikipedia:One-time password|one-time passwords]] (OTP) - using either AES based Yubico OTP algorithm or OATH-HOTP following RFC 4226<br />
* outputting a up to 63 char long static password<br />
* handling [[Wikipedia:Challenge–response authentication|challenge-response requests]], using either Yubico OTP mode or HMAC-SHA1 mode<br />
* handling [[Wikipedia:Universal_2nd_Factor|Universal 2nd Factor]] (U2F) requests (YubiKey 4 and YubiKey NEO)<br />
* acting as smartcard (using the [[Wikipedia:CCID (protocol)|CCID protocol]]) (YubiKey 4 and YubiKey NEO) - allowing storage of signing, encrypting, authenticating (RSA) keys to be used for instance for SSH login (authentication), Email signature/encryption, git commit signature, etc.<br />
<br />
It is manufactured by [http://www.yubico.com/ Yubico].<br />
<br />
One of its strengths is that it emulates a USB keyboard to send the OTP as text, and thus requires only USB HID drivers found on practically all desktop computers.<br />
<br />
While offering a lot of features, newer versions of the YubiKey are [https://www.yubico.com/2016/05/secure-hardware-vs-open-source/ not released as open source]. An alternative is the [[Solo]].<br />
<br />
=== Installation ===<br />
<br />
There are several packages available:<br />
<br />
* {{App|Yubico PAM|Module to integrate the YubiKey into [[PAM]].|https://developers.yubico.com/yubico-pam/|{{Pkg|yubico-pam}}}}<br />
* {{App|YubiKey Manager|Python library and command-line tool ({{ic|ykman}}) for configuring a YubiKey over all USB connections. Has optional GUI.|https://developers.yubico.com/yubikey-manager/|{{Pkg|yubikey-manager}}, {{Pkg|yubikey-manager-qt}}}}<br />
{{Note|After you install the yubikey-manager (which can be called by ykman in CLI), you need to enable {{ic|pcscd.service}} to get it running}}<br />
* {{App|Yubikey Personalization|Library and tool to configure slot features over the OTP USB connection. Has optional GUI.|https://developers.yubico.com/yubikey-personalization/|{{Pkg|yubikey-personalization}}, {{Pkg|yubikey-personalization-gui}}}}<br />
* {{App|Yubico Authenticator for Desktop|Lets you read OATH codes from your YubiKey over USB. Support the newer OATH implementation (YubiKey NEO and 4) as well as the older slot-based implementation (YubiKey Standard and Edge).|https://developers.yubico.com/OATH/YubiKey_OATH_software.html|{{Pkg|yubioath-desktop}}}}<br />
<br />
=== Understanding the YubiKey ===<br />
<br />
The YubiKey is a small USB dongle with one button and an LED to communicate with you.<br />
<br />
One of its strengths is that it can emulate a USB keyboard to send a password (OTP or static password) as text, and thus requires only USB HID drivers found on practically all computers (desktop, mobile, tablet, etc.).<br />
<br />
This also makes it vulnerable to keyloggers if the {{ic|static password}} functionality is used, which is why if possible one should avoid it and try to only use the one-time password (OTP), Challenge-Response and CCID Smartcard functionality.<br />
<br />
==== Inputs ====<br />
<br />
The YubiKey takes inputs in the form of:<br />
<br />
* API calls sent to it via the USB interface.<br />
* short button press<br />
* long button press<br />
<br />
==== Outputs ====<br />
<br />
The YubiKey transforms these inputs into outputs in the form of:<br />
<br />
* Sending keystroke keycodes (emulating a USB keyboard and typing for you) <br> This is used to:<br />
** type the static password<br />
** type the OTP<br />
<br />
* Sending back a Response via the API (over the USB interface). <br> This is used to send back:<br />
** the response of a Challenge-Response request (calculated using either Yubico OTP mode or HMAC-SHA1 mode)<br />
** the response of a U2F Challenge-Response request<br />
** the response of a CCID Smartcard related request<br />
<br />
=== The button ===<br />
<br />
The button activates by slightly touching it. Sometimes it even reacts when you are very close but are not touching it yet.<br />
<br />
Depending on the context, touching the button does one of these things:<br />
<br />
* triggering a function (like triggering the output of a static password or of a one-time password (OTP))<br />
* confirming / allowing a function or access<br />
* inserting / ejecting the smartcard<br />
<br />
In the OTP mode a short press yields slot 1 and a long press yields slot 2.<br />
<br />
=== USB connection modes ===<br />
<br />
Depending on the YubiKey model, the device provides up to three<br />
different USB interfaces with their associated protocols. Two of the<br />
interfaces implement the USB HID (Human Interface Device) device<br />
class; the third is a smart card interface (CCID). The YubiKey is a<br />
multi-function USB device, just like a USB printer that can also<br />
function as a scanner.<br />
<br />
The following table shows which interfaces the different applications<br />
use:<br />
<br />
{| class="wikitable"<br />
! Application !! USB Interface<br />
|-<br />
|OTP || Keyboard HID<br />
|-<br />
|FIDO || Other HID<br />
|-<br />
|PIV || CCID<br />
|-<br />
|OpenPGP || CCID<br />
|-<br />
|OATH || CCID<br />
|}<br />
<br />
All three interfaces can be independently enabled or disabled.<br />
The ykman program uses the term "manage connection modes" and uses<br />
OTP, FIDO, and CCID as selectors for which modes should be enabled.<br />
<br />
{{Note|The old U2F mode has been renamed and is now called FIDO in ykman 0.6.1 and later (released<br />
2018-04-16) https://developers.yubico.com/yubikey-manager/Release_Notes.html}}<br />
<br />
The set of enabled USB interfaces affects which applications on the<br />
key can be accessed. As an example, if only the HID interfaces are<br />
enabled, the applications dependent on the CCID interface are<br />
unavailable.<br />
<br />
Which application on the key is chosen is determined by the host<br />
application and is a combination of USB interface and an application<br />
selection mechanism. For example, if the host application wants to<br />
communicate with the PIV application on the key, it accesses the key<br />
using the CCID interface and using the protocols defined by CCID sends<br />
a 'select application' command to the key selecting the PIV application.<br />
<br />
==== Get enabled modes ====<br />
<br />
{{ic|ykman mode}} will tell you what modes are currently activated/enabled/available.<br />
This could output something like<br />
{{bc|Current connection mode is: OTP+U2F+CCID}}<br />
Meaning that currently the OTP, U2F and CCID subsystem of the key are enabled.<br />
<br />
==== Set the enabled modes ====<br />
<br />
{{ic|ykman mode <MODE>}} will allow you to define which modes should be activated/enabled/available. <br />
* {{ic|<MODE>}} can be a string, such as {{ic|OTP+U2F+CCID}}, or a shortened form {{ic|o+u+c}}.<br>With "+" you can combine multiple modes that you wish to be enabled.<br />
* {{ic|<MODE>}} can be a mode-number, which is one number that encodes several enabled modes (like flags) into one value.<br>The only valid modes when using numbers is 0 - 6 ([https://github.com/Yubico/yubikey-manager/blob/master/ykman/util.py#L94 see here]). The extra flags are not part of the mode in that sense, they just need to be set at the same time as the mode is set.<br />
<br />
Usually what you want is to make all functionality available (you will still need to potentially configure stuff, see functionality sections below for more details).<br />
In order to do so you can use:<br />
<br />
{{ic|ykman mode c+u+o}} or {{ic|ykman mode 6}}<br />
<br />
{{Note|Using the "80" mode-number or the corresponding {{ic|--touch-eject}} parameter of {{ic|ykman mode}} can only be used when the device is ''only'' in CCID mode (by running {{ic|ykman mode ccid --touch-eject}} for instance).<br />
<br />
Once the {{ic|--touch-eject}} flag is set, you should be able to eject/insert the smartcard by pressing the button. The LED should indicate if the card is inserted or not as well.<br />
}}<br />
<br />
{{Warning|But using the 80 mode-number or the corresponding {{ic|--touch-eject}} is not recommend as it would prevent you from using the U2F and OTP features of the YubiKey.}}<br />
<br />
{{Note|The often seen:<br />
<br />
{{ic|ykman mode c+u+o --touch-eject}} or {{ic|ykman mode 86}}<br />
<br />
will ignore the {{ic|--touch-eject}} and be identical to the above recommended {{ic|ykman mode 6}}.<br />
<br />
86 is not a valid mode. It might be a bug that the tool accepts higher values ([https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 see here]).}}<br />
<br />
=== Two Slots ===<br />
<br />
Only if the OTP mode is activated (see Modes of the YubiKey below), the Yubikey provides 2 slots.<br />
<br />
If the transport mode OTP is enabled, the two YubiKey Slots, long press and short press, can be configured and used.<br />
<br />
==== Configuration of the slots ====<br />
<br />
These slots can have one of the following credentials configured: a [https://developers.yubico.com/OTP/ Yubico OTP] (which is what comes preconfigured in the short press slot on a new key), a static password, a challenge-response credential, an OATH-HOTP credential. All this functionality is found in the {{ic|ykman otp}} commands.<br />
<br />
{{Note|A slot has either a Yubico OTP or a challenge-response credential configured. More general: One, and only one, type of the above listed possible credential per slot.}}<br />
<br />
There are several flags that can be set during the configuration of the slots.<br />
These flags /cannot/ be read from the device once written. However, the behaviour of the device should change when the flags are set ;)<br />
<br />
{{Note|Actually most of (all of??) the parameters and details you use during configuration of the slots, cannot be read back, once written to the YubiKey.}}<br />
<br />
=== The LED ===<br />
<br />
The YubiKey has a small green LED able to communicate with you.<br />
Its message to you actually depends on the currently used [[#USB connection modes]] of your YubiKey.<br />
<br />
The possible messages are:<br />
* *steady on*: Press now, to allow access. (typically (TODO exclusively?) U2F mode)<br />
* *slow blinking*: Power/setting up/ready for use (TODO explain)<br />
* *rapid blinking*: Error, configuring driver (TODO explain)<br />
<br />
{{Note|If the CCID mode is turned on, then the LED of the key is always shortly flashing every two-three seconds once inserted.<br>You can turn the blinking off by disabling the CCID mode. This slow blinking just shows that the device has power, alternatively it shows a need for a button press. On Windows this behavior will typically stop once drivers are installed and it is ready for use. Mac and Linux systems will keep blinking; here [https://github.com/Yubico/yubikey-manager/issues/20#issuecomment-326496204 the best current workaround] to get the LED to blink less is to disable CCID.}}<br />
<br />
=== Initial configuration ===<br />
<br />
On a new YubiKey the Yubico OTP is preconfigured on slot 1. <br />
<br />
{{Warning|Before you overwrite your slot 1, please be aware that one is not able to reconfigure the same trust level [https://forum.yubico.com/viewtopic12ca.html?f%3D16&t%3D1960 see here]. Meaning:<br />
<br />
One could think that it is a good idea to reset configuration slot 1 to a new OTP. But then a "VV" prefix in your credentials must be used. Whereas the factory credentials on your Yubikey use a "CC" prefix. You can upload a "VV" credential using the Yubico personalization tool GUI or manually upload the new AES key to the [https://upload.yubico.com/ yubico.com website] in order to regain the same functionality than with the original factory configuration. VV credentials are not less secure than CC. However some services may only trust CC credentials as they believe that the user process is more prone to security vulnerabilities. This is because you could have malware on your machine or someone intercepting your key when sending it to the YubiCloud.<br />
}}<br />
<br />
=== Limitations of the passwords typed by YubiKey via USB-keyboard -- or "Why do my password look so weak ?" ===<br />
<br />
The YubiKey can type passwords (OTP or Static Password) for you by acting as USB keyboard and sending scan-codes like if you would type.<br />
<br />
A limitation of the YubiKey, however, prevents you from choosing characters that require a modifier key other than Shift.<br />
And in order for the YubiKey to work with all possible keyboard layouts (e.g. the {{ic|Z}} on a German keyboard has a different scan-code than the {{ic|Z}} on a US keyboard) it is necessary to limit the characters used by YubiKey passwords to the ModHex alphabet + Digits (0-9) (+ optionally "!" as the only available Symbol in static passwords).<br />
<br />
The 16 characters used in the ModHex alphabet are: {{ic|c,b,d,e,f,g,h,i,j,k,l,n,r,t,u,v}}. These characters share a property that makes them very valuable to a YubiKey: They use the same scan codes across a very large number of keyboard layouts. In other words, the scan code 0x06 maps to the character c for English, Swedish, German, French, and many others.<br />
<br />
[https://www.yubico.com/wp-content/uploads/2015/11/Yubico_WhitePaper_Static_Password_Function.pdf See here for full info]<br />
<br />
== One-time password ==<br />
<br />
=== Yubico OTP mode ===<br />
<br />
The Yubico OTP mode is AES symmetric key based. On a new YubiKey the Yubico OTP is preconfigured on slot 1. This initial AES symmetric key is stored in the YubiKey and the same AES key is already stored on the Yubico Authentication server. This allows validating against YubiCloud, meaning the use of Yubico OTP in combination with the Yubico Forum website for instance or on https://demo.yubico.com).<br />
<br />
The initial configuration and AES key stored in slot 1 can of course be overwritten.<br />
<br />
{{Warning|Please read [[#Initial configuration]] before you overwrite the intial configuration of slot 1 that your YubiKey comes shipped with.}}<br />
<br />
==== How does it work ====<br />
<br />
Yubikey's authentication protocol is based on [[Wikipedia:Symmetric_cryptography|symmetric cryptography]].<br />
More specifically, each YubiKey contains a 128-bit [[Wikipedia:Advanced_Encryption_Standard|AES]] key unique to that device.<br />
It is used to encrypt a token made of different fields such as the ID of the key, a counter, a random number, etc.<br />
The OTP is made from concatenating the ID of the key with this encrypted token.<br />
<br />
This OTP is sent to the target system to which we want to authenticate.<br />
This target system asks a validation server if the OTP is good.<br />
The validation server has a mapping of YubiKey IDs -> AES key.<br />
Using the key ID in the OTP, it can thus retrieve the AES key and decrypt the other part of the OTP.<br />
If it looks OK (plain-text ID and encrypted ID are the same, the counter is bigger than the last seen one to prevent [[wikipedia:Replay_attack|replay attacks]], then authentication is successful.<br />
<br />
The validation server sends that authentication status back to the target system, which grants access or not based on that response.<br />
<br />
==== Security risks ====<br />
<br />
===== AES key compromise =====<br />
<br />
As you can imagine, the AES key should be kept secret.<br />
It cannot be retrieved from the YubiKey itself (or it should not, at least not with software).<br />
It is present in the validation server though, so the security of this server is very important.<br />
<br />
===== Validation requests/responses tampering =====<br />
<br />
Since the target system relies on the ruling of the validation server, a trivial attack would be to impersonate the validation server.<br />
The target system thus needs to authenticate the validation server.<br />
2 methods are available :<br />
* '''HMAC''': This is also symmetric cryptography, the target server and validation server share a key that is used to sign requests and responses.<br />
* '''TLS''': Requests and responses travel via HTTP, so TLS (HTTPS) can be used to authenticate and encrypt the connection.<br />
<br />
==== YubiCloud and validation servers ====<br />
<br />
When you buy a YubiKey, it is preloaded with an AES key that is known only to Yubico.<br />
They will not even communicate it to you.<br />
Yubico provides a validation server with free unlimited access (YubiCloud).<br />
It also offers open-source implementations of the server.<br />
<br />
So you can either:<br />
* choose to use your YubiKey with its preloaded AES key and validate against Yubico's validation server ;<br />
* or load a new AES key in your YubiKey and run your own validation server.<br />
<br />
{{Note|To authenticate the Yubico validation server, you can:<br />
* '''with HMAC''': use https://upgrade.yubico.com/getapikey/ to get an HMAC key and ID<br />
* '''with HTTPS''': the validation server's certificate is signed by GoDaddy, and is thus trusted by default in Arch installs (at least if you have package ca-certificates)}}<br />
<br />
=== OATH-HOTP mode (RFC 4226) ===<br />
<br />
{{Expansion|Empty section.}}<br />
<br />
== Challenge-Response ==<br />
<br />
=== Function and Application of Challenge-Response ===<br />
This technique can be used to authenticate.<br />
<br />
A challenge is sent to the YubiKey and a response is (auto-magically) calculated and send back.<br />
This calculation needs a secret (e.g. an AES key in case of the Yubico OTP mode)<br />
The same challenge always results in the same response.<br />
Without the secret this calculation is not meant to be feasable. Even if in the possession of many challenge-response pairs.<br />
<br />
This can be used for:<br />
* true 2-factor (possession and knowledge) authentication:<br>If you combine the response (possession factor) with a password (knowledge factor) and to authenticate you need to present the triple (challenge,response, password) to 3rd party. In which case the challenge and the corresponding response can be (publicly) send to a 3rd party to authenticate the possession factor, by redoing basically the same (auto-magical) calculation. The needed secret needs to be shared with 3rd party to allow an authentication.<br />
<br />
* semi 2-factor (possession and knowledge) authentication:<br>The challenge can be public. Only with the possession of the YubiKey hardware the response can be generated. This can be used to create a "sort-of" 2-factor authentication (possession and knowledge): If you combine the response (possession factor) with a password (knowledge factor) and use the result for instance as passphrase for cryptsetup.<br />
<br />
This functionality will consume one slot. And it is used via API calls to the YubiKey. So you usually use some tool to communicate the challenge to your YubiKey and get back the response.<br />
<br />
There are two Challenge-Response modes:<br />
* Yubico OTP mode <br />
* HMAC-SHA1 mode<br />
<br />
=== Setup the slot ===<br />
<br />
One way to setup slot {{ic|2}} in challenge-response mode ({{ic|-ochal-resp}}) is with {{ic|ykpersonalize}}:<br />
<br />
{{bc|ykpersonalize -v -2 -ochal-resp -ochal-hmac -ohmac-lt64 -oserial-api-visible -ochal-btn-trig}}<br />
<br />
Check with {{man|1|ykpersonalize}} to make sure that the options used above are right for you. You may also enable challenge-response mode using graphical interface through {{pkg|yubikey-personalization-gui}}.<br />
<br />
{{Note|Before you overwrite the initial configuration of slot 1, please be aware of the '''Warning''' under [[#Initial configuration]].}}<br />
<br />
=== Use the slot - get a response for a challenge ===<br />
<br />
To use a Challenge-Response slot (no matter which mode):<br />
<br />
{{bc|ykchalresp -2 <CHALLENGE>}}<br />
<br />
== U2F ==<br />
<br />
{{Expansion}}<br />
<br />
=== Enabling U2F in the browser ===<br />
<br />
==== Chromium/Chrome ====<br />
<br />
[[Chromium/Tips and tricks#U2F authentication]]<br />
<br />
==== Firefox ====<br />
<br />
[[Firefox/Tweaks#Fido U2F authentication]]<br />
<br />
== CCID Smartcard ==<br />
<br />
CCID (Chip Card Interface Device) is a USB standard device class for use by USB devices that act as smart card readers or with security tokens that connect directly via USB, like the Yubikey. HID (Human Interface Device) and CCID are both USB device classes, i.e. they are in the same category of USB specifications. HID is a specification for computer peripherals, like keyboards. The Yubikey works like a USB (HID) keyboard when used in the OTP and U2F modes, but switches to the CCID protocol when using the PIV application, or as an OpenPGP device.<br />
<br />
CCID mode should be enabled by default on all YubiKeys shipped since November 2015 [https://www.yubico.com/support/knowledge-base/categories/articles/use-yubikey-yubikey-windows-hello-app/]. Enable at least the CCID mode. Please see [[#Set the enabled modes]].<br />
<br />
=== PIV ===<br />
<br />
Starting from the fourth generation devices, the Yubikeys contain a PIV (Personal Identity Verification) application on the chip. PIV is a US government standard (FIPS 201) that specifies how a token using RSA or ECC (Elliptic Curve Cryptography) is used for personal electronic identification. The distinguishing characteristic of a PIV token is that it is built to protect private keys and operate on them on-chip. A private key never leaves the token after it has been installed on it. Optionally, the private key can even be generated on-chip with the aid of an on-chip random number generator. If generated on-chip, the private key is never handled outside of the chip, and there is no way to recover it from the token. When using the PIV mechanism, the Yubikey functions as a CCID device.<br />
<br />
=== Use OpenPGP smartcard mode ===<br />
<br />
See [[GnuPG#Smartcards]]<br />
<br />
=== Using a YubiKey with SSH ===<br />
<br />
The following example describes how to use a YubiKey for [[SSH keys]]. A YubiKey with the PIV (Personal Identification Verification) application is required; this means you need a YubiKey NEO or YubiKey 4 or later.<br />
<br />
==== Generating a key pair on the YubiKey ====<br />
<br />
A private key and associated certificate need to be either generated on the YubiKey or imported to it. Install the {{Pkg|yubikey-manager}}<br />
package. Insert the YubiKey in a USB port and check that it is recognized:<br />
<br />
$ ykman list<br />
YubiKey 4 [OTP+FIDO+CCID] Serial: 1234567<br />
<br />
The following two commands ({{ic|generate-key}} and {{ic|generate-certificate}}) require providing the PIV application's 24-byte management key, if it has been changed from its default value (recommended). The examples below assume the shell variable {{ic|MK}} has been set in advance to the 48 character hex string representation of the management key. For example:<br />
<br />
$ MK=AB019982CA48BDC6776B1F9A0A3E129FDE0705D219AF0037<br />
<br />
Generate a 2048-bit RSA key pair on the YubiKey. The private key will be stored in key slot 9a on the YubiKey, and the public key will be<br />
written to the file {{ic|pubkey.pem}}.<br />
<br />
$ ykman piv generate-key -m $MK -a RSA2048 9a pubkey.pem<br />
<br />
Next, use the YubiKey to generate a self-signed certificate for the public key:<br />
<br />
$ ykman piv generate-certificate -m $MK -d 1826 -s "SSH Key" 9a pubkey.pem<br />
<br />
The Subject field in the certificate will be set to "SSH Key" with the {{ic|-s}} option. This field will be included in the prompt for PIN to help identify which key is used for authentication. The example command also specifies the {{ic|-d}} option to set the number of days until the certificate expires. If the {{ic|-d}} option is omitted, a default value of 365 days is used.<br />
<br />
Note that the last parameter in the {{ic|generate-key}} command is the file name where the public key is written to, whereas the last parameter in the {{ic|generate-certificate}} command specifies where the public key is read from. The certificate is constructed and signed on the YubiKey and stored alongside the private key; the command does not output the certificate.<br />
<br />
At this point the YubiKey is ready for authenticating to a SSH server. For this to happen, some additional configuration on both the client and the server is required.<br />
<br />
==== Client configuration ====<br />
<br />
The standard API used to communicate with cryptographic tokens is defined by [[wikipedia:PKCS_11|PKCS#11]].<br />
Install the {{Pkg|opensc}} package which provides this API in the form of the shared library {{ic|/usr/lib/opensc-pkcs11.so}}. The ssh client should be configured to use this library with the directive PKCS11Provider in {{ic|~/.ssh/config}}:<br />
<br />
{{hc|~/.ssh/config|PKCS11Provider /usr/lib/opensc-pkcs11.so}}<br />
<br />
==== Public key conversion ====<br />
<br />
The {{ic|pubkey.pem}} file contains the public key in PEM (Privacy Enhanced Mail) format. OpenSSH uses a different format defined in RFC 4253,<br />
section 6.6, so the PEM formatted key should be converted to the format OpenSSH understands. This can be done using {{ic|ssh-keygen}}:<br />
<br />
$ ssh-keygen -i -m PKCS8 -f pubkey.pem > pubkey.txt<br />
<br />
This command uses the import ({{ic|-i}}) function of the {{ic|ssh-keygen}}, specifies PKCS8 as the input file format ({{ic|-m}}), and reads the input from the ({{ic|-f}}) file {{ic|pubkey.pem}}. The converted key is written on standard output, which is the example is redirected to the file {{ic|pubkey.txt}}.<br />
<br />
The converted public key should now be copied to the remote server as described in [[SSH keys#Copying the public key to the remote server]].<br />
<br />
==== Initiating an SSH session with the YubiKey ====<br />
<br />
To authenticate a SSH connection using the YubiKey, just use ''ssh'' normally. You will be prompted for the PIN instead of a password:<br />
<br />
$ ssh remote<br />
Enter PIN for 'SSH Key' <br />
[user@remote ~]$ <br />
<br />
==== Using ssh-agent to cache the PIN ====<br />
<br />
ssh-agent (see [[SSH keys#SSH agents]]) can also be used with the PKCS#11 library; in this case the PIN code is cached instead of the private key.<br />
<br />
$ ssh-add -s /usr/lib/pkcs11/opensc-pkcs11.so<br />
<br />
As long as the PIN is cached in by the agent, the cached value is used and the user is not prompted for it.<br />
<br />
==== Further reading ====<br />
<br />
The default PIN code of the PIV application on the YubiKey is {{ic|123456}}; you may want to change it. The YubiKey also requires a 24-byte management key for administrative functions like key generation. If the management key has been changed from its default value, the new value needs to be specified using the {{ic|-m}} option on the command line for certain commands. See [https://developers.yubico.com/PIV/ What is PIV?]<br />
<br />
== Tips and tricks ==<br />
<br />
=== YubiKey and LUKS encrypted partition/disk ===<br />
<br />
YubiKey can be used to strengthen the security of your [[LUKS]] encrypted partition/disk. There are multiple ways to achieve it. But before enabling Yubikey as a 2FA device it is recommended to setup plain LUKS encryption first and make sure it works correctly.<br />
<br />
==== Challenge-Response mode for LUKS passphrase ====<br />
<br />
One way to do it is to use a Challenge-Response mode for creating strong LUKS passphrases. First, install {{Pkg|yubikey-full-disk-encryption}} package. Using this tool you can add/modify/remove Yubikey-protected passphrases.<br />
<br />
Make changes to {{ic|/etc/ykfde.conf}} configuration file as as:<br />
* choose Yubikey slot to use for LUKS ({{ic|YKFDE_CHALLENGE_SLOT}})<br />
* whether you want to type a password at boot ({{ic|YKFDE_CHALLENGE_PASSWORD_NEEDED}}) or use predefined password ({{ic|YKFDE_CHALLENGE}}) which essentially means you check for Yubikey hardware presence only.<br />
<br />
LUKS supports multiple password so you need to select a slot that is going to store Yubikey-protected passphrase. Inspect existing slots using command:<br />
<br />
# cryptsetup luksDump /dev/<DISK><br />
<br />
Check entries under {{ic|Keyslots:}} section. And then pick an unused slot.<br />
<br />
Enroll your new passphrase:<br />
<br />
# ykfde-enroll -d /dev/<DISK> -s <LUKS_SLOT><br />
<br />
It will require the new and existing passphrases.<br />
<br />
And the last step is to add {{ic|ykfde}} hook to {{ic|/etc/mkinitcpio.conf}} file before or instead of {{ic|encrypt}} hook. Then regenerate initramfs with {{ic|mkinitcpio -P}}.<br />
<br />
{{Warning|As of December 2019 `sd-encrypt` enabled boot is [https://github.com/agherzan/yubikey-full-disk-encryption/issues/14 not supported] by {{Pkg|yubikey-full-disk-encryption}}.}}<br />
<br />
==== OpenPGP applet ====<br />
<br />
Another way of using YubiKey for full disk encryption is to utilize its OpenPGP applet to decrypt the LUKS keyfile during boot. [https://github.com/fuhry/initramfs-scencrypt initramfs-scencrypt] is a set of hooks for initramfs that automate this process.<br />
<br />
=== Yubikey and KeePass ===<br />
<br />
{{Style|Duplicates [[KeePass]].}}<br />
<br />
Yubikey can be integrated with [[KeePass]] using [[KeePass#Yubikey|plugins]].<br />
<br />
For a native open-source implementation of KeePass have a look at:<br />
<br />
==== keepassx2 ====<br />
<br />
{{AUR|keepassx2}} ([https://keepassx.org/ see keepassx.org]) a keepass QT FOSS reimplementation, extremely stable and available for Windows, MacOSX and Linux.<br />
<br />
==== KeePassXC ====<br />
<br />
{{Pkg|keepassxc}} ([https://keepassxc.org/ see keepassxc.org]) a KeePassX fork that integrated YubiKey into KeePassX v2.<br>The integration covers Challenge-Response as security factor to open the database, but also the generation of OTP using the YubiKey.<br />
<br />
In order to have a KeePassXC database work on Android (using the [https://play.google.com/store/apps/details?id=keepass2android.keepass2android Keepass2Android app]), you need to use version 1.06 of the app. You also need to save the database file in the KDBX 4 format, since Keepass2Android do not support the KDBX 3 format.<br />
<br />
YubiKey support in Keepass2Android (which is compatible with KeePassXC) is tracked [https://github.com/PhilippC/keepass2android/issues/4 on GitHub].<br />
<br />
=== Two-factor authentication with SSH ===<br />
<br />
{{Note|See also: https://developers.yubico.com/yubico-pam/Yubikey_and_SSH_via_PAM.html}}<br />
<br />
This details how to use a Yubikey to have [[wikipedia:Two-factor_authentication|two-factor authentication]] with SSH, that is, to use both a password and a YubiKey OTP.<br />
<br />
==== Prerequisites ====<br />
<br />
Install {{Pkg|yubico-pam}}.<br />
<br />
{{Note|If you are configuring a distant server to use YubiKey, you should open at least one additional, rescue SSH session, so that you are not locked out of your server if the configuration does not work and you exit your main session inadvertently}}<br />
<br />
{{Note|The following assumes you are using the default Yubico servers. See the [https://github.com/Yubico/yubico-pam yubico-pam documentation] for options relevant to using your own server.}}<br />
<br />
==== Configuration ====<br />
<br />
===== Authorization Mapping Files =====<br />
<br />
A mapping must be made between the YubiKey token ID and the user ID it is<br />
attached to. There are two ways to do this, either centrally in one file, or<br />
individually, where users can create the mapping in their home directories.<br />
If the central authorization mapping file is being used, user home directory<br />
mappings will not be used and vice versa.<br />
<br />
====== Central authorization mapping ======<br />
<br />
Create a file {{ic|/etc/yubico/authorized_yubikeys}}, the file must contain a user name and the<br />
YubiKey token ID separated by colons (same format as the passwd file) for<br />
each user you want to allow onto the system using a YubiKey.<br />
<br />
The mappings should look like this, one per line:<br />
<br />
<first user name>:<Yubikey token ID1>:<Yubikey token ID2>:...<br />
<second user name>:<Yubikey token ID3>:<Yubikey token ID4>:...<br />
<br />
You can specify multiple key tokens to correspond to one user, but only one is required.<br />
<br />
====== Per-user authorization mapping ======<br />
<br />
Each user creates a {{ic|~/.yubico/authorized_yubikeys}} file inside of their home<br />
directory and places the mapping in that file, the file must have only one<br />
line:<br />
<br />
<user name>:<Yubikey token ID1>:<Yubikey token ID2><br />
<br />
This is much the same concept as the SSH {{ic|authorized_keys}} file.<br />
<br />
Note that this file must be readable by the {{ic|pam_yubico}} module when the user is authenticated, otherwise login will fail. If this is not possible or desired, use the global mapping file instead.<br />
<br />
====== Obtaining the YubiKey token ID (a.k.a. public ID) ======<br />
<br />
You can obtain the YubiKey token ID in several ways. One is by<br />
removing the last 32 characters of any OTP (One Time Password)<br />
generated with your YubiKey. Another is by using the<br />
[http://demo.yubico.com/php-yubico/Modhex_Calculator.php modhex calculator].<br />
<br />
Enter your YubiKey OTP and convert it, your Yubikey token ID is 12<br />
characters and listed as:<br />
<br />
Modhex encoded: XXXXXXX<br />
<br />
===== PAM configuration =====<br />
<br />
Having set up the {{ic|pam_yubico}} module, you next need to tell PAM to use it when logging in via SSH. There are several ways of doing this.<br />
<br />
====== The default way ======<br />
<br />
Obtain HMAC credentials from Yubico as described in [[#YubiCloud and validation servers]]. You will receive a Client ID and a secret key.<br />
<br />
Add one of the two following lines to the beginnning of {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID authfile=/etc/yubico/authorized_yubikeys<br />
<br />
if you are using a central authorization mapping file, or<br />
<br />
auth required pam_yubico.so id=CLIENTID<br />
<br />
if you are using per-user authorization mapping, where {{ic|CLIENTID}} is your Client ID. This method utilizes your ID and the server's certificate to authenticate the connection.<br />
<br />
{{Note|This will authenticate via Yubico's free YubiCloud servers. If you want to use a different server, add it via the {{ic|urllist}} parameter.}}<br />
<br />
====== Using pure HMAC to authenticate the validation server ======<br />
<br />
Add {{ic|key}} to the above lines in {{ic|/etc/pam.d/sshd}}:<br />
<br />
auth required pam_yubico.so id=CLIENTID key=SECRETKEY ...<br />
<br />
where {{ic|CLIENTID}} and {{ic|SECRETKEY}} are your HMAC ID and key.<br />
<br />
You should also disallow unprivileged users to read the file to prevent them from seeing the HMAC credentials:<br />
# chmod o-r /etc/pam.d/sshd<br />
<br />
{{Note|HMAC credentials should be unique to a single target server. That way, if an attacker finds them, he will not be able to craft responses to authenticate to other target servers you own}}<br />
<br />
====== Using pure HTTPS to authenticate the validation server ======<br />
<br />
{{Warning|While this "old" method of using a dummy id still works, it is unknown how secure and/or future-proof it is, as Yubico no longer describes it in their documentation. Proceed at your own risk. At the very least you should ensure that only HTTPS servers with valid certificates are used for authentication.}}<br />
<br />
If you do not want to use HMAC credentials from Yubico, it is still possible to authenticate via the Yubico server by setting {{ic|1=CLIENTID=1}} instead of your own ID. Although {{ic|pam_yubico}}'s default server uses HTTPS already, for security reasons you should specify it manually via the {{ic|urllist}} parameter, as the servers certificate is the only way in which the connection is authenticated. You can find the keyserver URL by adding the {{ic|debug}} parameter to the {{ic|auth}} line.<br />
<br />
===== SSHD configuration =====<br />
<br />
You should check that {{ic|/etc/ssh/sshd_config}} contains these lines and that they are not commented. The {{ic|sshd_config}} shipped with {{pkg|openssh}} has these set correctly by default.<br />
ChallengeResponseAuthentication no<br />
UsePAM yes<br />
<br />
==== That is it! ====<br />
<br />
You should not need to restart anything if you did not change the SSHD config file.<br />
<br />
To log in, at the {{ic|Password:}} prompt of SSH, you have to type your password '''without pressing enter''' and touch the YubiKey's button.<br />
The YubiKey should send a return at the end of the OTP so you do not need to touch the enter key at all.<br />
<br />
You can display information about the login data generated by {{ic|pam_yubico}} by adding the {{ic|debug}} option to the auth line in{{ic|/etc/pam.d/sshd}}. However, if you are using a central authorization file, you should remove that option once finished testing, as it causes {{ic|pam_yubico}} to display the entire content of the central file to every user who logs in using a YubiKey.<br />
<br />
==== Explanation ====<br />
<br />
This works because the prompt is {{ic|pam_yubico.so}}'s one, since this module is before {{ic|pam_unix.so}}, which normally does basic password authentication.<br />
So, you are giving a string that is the concatenation of your password and the OTP to {{ic|pam_yubico.so}}.<br />
Since the OTPs have a fixed length (let us call this size N), it just has to get the last N characters to retrieve the OTP, and it assumes that the other characters at the start are the password.<br />
It tries to validate the OTP, and in case of success, sends the password to the next PAM module. In Archlinux' default PAM stack, the authenticator {{ic|pam_unix.so}} is instructed to try receiving a password from the previous module with {{ic|try_first_pass}}, so it automatically uses the password sent by {{ic|pam_yubico.so}}.<br />
<br />
=== Executing actions on insertion/removal of YubiKey device ===<br />
<br />
For example, you want to perform an action when you pull your YubiKey out of the USB slot, create {{ic|/etc/udev/rules.d/80-yubikey-actions.rules}} and add the following contents:<br />
ACTION=="remove", ENV{ID_MODEL}=="Yubikey_4_OTP+U2F+CCID", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0407", RUN+="/usr/local/bin/script args"<br />
<br />
Please note, that this example is for the YubiKey 4, and you will have to look at the output of {{ic|lsusb}} to get the vendor and model ID's, along with the description of the device. Of course, to execute a script on insertion, you would change the action to 'add' instead of remove.<br />
<br />
== Maintenance / Upgrades ==<br />
<br />
=== Installing the OATH Applet for a YubiKey NEO ===<br />
<br />
These steps will allow you to install the OATH applet onto your YubiKey NEO. This allows the use of Yubico Authenticator in the Google Play Store.<br />
{{Note|1=These steps are only for NEOs with a firmware version <= 3.1.2. The current generation NEOs (with U2F) come with the OpenPGP applet already installed)}}<br />
<br />
==== Configure the NEO as a CCID Device ====<br />
<br />
# Install {{pkg|yubikey-personalization-gui}} ({{AUR|yubikey-personalization-gui-git}}).<br />
# Add the udev rules and reboot so you can manage the YubiKey without needing to be root<br />
# Run {{ic|ykpersonalize -m82}}, enter {{ic|y}}, and hit enter.<br />
<br />
==== Install the Applet ====<br />
<br />
# Install {{AUR|gpshell}}, {{AUR|gppcscconnectionplugin}}, {{AUR|globalplatform}}, and {{Pkg|pcsclite}}.<br />
# [[Start]] {{ic|pcscd.service}}.<br />
# Download the most recent CAP file from the [http://opensource.yubico.com/ykneo-oath/releases.html ykneo-oath] site.<br />
# Download {{ic|gpinstall.txt}} from [https://github.com/Yubico/ykneo-oath/blob/master/gpinstall.txt GitHub].<br />
# Edit the line in gpinstall.txt beginning with {{ic|install -file}} to reflect the path where the CAP file is located.<br />
# Open a terminal and run {{ic| gpshell <location of gpinstall.txt>}}<br />
# Ideally, a bunch of text will scroll by and it ends saying something like<br />
{{ bc | Command --> 80E88013D7C000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A100<br />
Wrapped command --> 84E88013DFC000C400BE00C700CA00CA00B400BE00CE00D200D500D700B000DB00C700DF00BEFFFF00BE00E400AC00AE00AE00DB00E700A<br />
A00EA00ED00ED00ED00BE00EF00F100F400F100F700FA00FF00BE00F700AA01010103010700CA00C400B400AA00F700B400AA00B600C7010C<br />
010C00AA0140012001B0056810B0013005600000056810E0011006B4B44304B44404B44106B44B4405B443400343B002410636810E06B4B44<br />
407326810B004B43103441003334002B102B404B3B403BB4003B440076820A4100221024405B4341008B44600000231066820A15D848CB77<br />
27D0EDA00<br />
Response <-- 009000<br />
Command --> 80E60C002107A000000527210108A00000052721010108A000000527210101010003C901000000<br />
Wrapped command --> 84E60C002907A000000527210108A00000052721010108A000000527210101010003C9010000B4648127914A4C7C00<br />
Response <-- 009000<br />
card_disconnect<br />
release_context}}<br />
# Unplug the NEO and try it with the Yubico Authenticator app<br />
<br />
==== (Optional) Install the Yubico Authenticator Desktop client ====<br />
<br />
You can get the desktop version of the Yubico Authenticator by installing {{Pkg|yubico-yubioath-desktop}}{{Broken package link|package not found}}.<br />
<br />
While {{ic|pcscd.service}} is running, run {{ic|yubioath-gui}} and insert your Yubikey when prompted.<br />
<br />
== Troubleshooting ==<br />
<br />
Restart, especially if you have completed updates since your YubiKey last worked. Do this even if some functions appear to be functioning.<br />
<br />
=== YubiKey not acting as HID device ===<br />
Add udev rule as described in [https://michaelheap.com/yubikey-on-arch/ this article]:<br />
<br />
{{hc|/etc/udev/rules.d/10-security-key.rules|2=<br />
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="users", ATTRS{idVendor}=="2581", ATTRS{idProduct}=="f1d0"<br />
}}<br />
<br />
Run {{ic|udevadm trigger}} afterwards.<br />
<br />
You may also need to [[install]] the package {{pkg|libu2f-host}} if you want support in chrome.<br />
<br />
=== ykman fails to connect to the YubiKey ===<br />
<br />
If the manager fails to connect to the YubiKey, make sure you have started {{ic|pcscd.service}} or {{ic|pcscd.socket}}.<br />
<br />
=== YubiKey fails to bind within a guest VM ===<br />
<br />
Assuming the YubiKey is available to the guest, the issue results from a driver binding to the device on the host. To unbind the device, the bus and port information is needed from {{ic|dmesg}} on the host:<br />
<br />
$ dmesg | grep -B1 Yubico | tail -n 2 | head -n 1 | sed -E 's/^\<nowiki>[[^]]</nowiki>+\] usb (<nowiki>[^:]</nowiki>*):.*/\1/'<br />
<br />
The resulting USB id should be of the form {{ic|X-Y.Z}} or {{ic|X-Y}}. Then, on the host, use {{ic|find}} to search {{ic|/sys/bus/usb/drivers}} for which driver the YubiKey is binded to (e.g. {{ic|usbhid}} or {{ic|usbfs}}).<br />
<br />
$ find /sys/bus/usb/drivers -name "*X-Y.Z*"<br />
<br />
To unbind the device, use the result from the previous command (i.e. {{ic|/sys/bus/usb/drivers/<DRIVER>/X-Y.Z:1.0}}):<br />
<br />
# echo 'X-Y.Z:1.0' > /sys/bus/usb/drivers/<DRIVER>/unbind<br />
<br />
=== Error: [key] could not be locally signed or gpg: No default secret key: No public key ===<br />
<br />
Occurs when attempting to sign keys on a non-standard keyring while a YubiKey is plugged in, e.g. as [[Pacman/Package_signing|Pacman]] does in {{ic|pacman-key --populate archlinux}}. The solution is to remove the offending YubiKey and start over.</div>Tepleshttps://wiki.archlinux.org/index.php?title=Firejail&diff=584161Firejail2019-09-29T20:35:46Z<p>Teples: /* Use With hardened_malloc */ link to stable version, fix typo</p>
<hr />
<div>[[Category:Sandboxing]]<br />
[[ja:Firejail]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related articles end}}<br />
[https://firejail.wordpress.com/ Firejail] is an easy to use SUID sandbox program that reduces the risk of security breaches by restricting the running environment of untrusted applications using Linux namespaces, seccomp-bpf and Linux capabilities.<br />
<br />
== Installation ==<br />
<br />
[[Install]] either {{Pkg|firejail}}, or the {{aur|firejail-git}} package. A GUI application for use with Firejail is also available, {{aur|firetools}}.<br />
<br />
{{Note|For information about {{man|7|user_namespaces}} support in Arch Linux kernels see [[Security#Sandboxing applications]]. [https://github.com/netblue30/firejail/issues/1842#issuecomment-376642039 Firejail can use it even if it is disabled].}}<br />
{{Warning|While upstream is gradually adopting whitelists, (cf {{ic|/etc/firejail/firefox.profile}},) most of the supplied profiles still rely heavily on blacklists. This means that anything not explicitly forbidden by the profile will be accessible to the application. For example, if you have btrfs snapshots available in {{ic|/mnt/btrfs}}, a jailed program may be forbidden from accessing {{ic|$HOME/.ssh}}, but would still be able to access {{ic|/mnt/btrfs/@some-snapshot/$HOME/.ssh}}. Make sure to audit your profiles, see [[#Testing profiles]]}}<br />
<br />
=== Apparmor integration ===<br />
<br />
Since 0.9.60-1, {{Pkg|firejail}}, has supported more direct integration with Apparmor through a generic apparmor profile. During installation, the profile, {{ic|firejail-default}}, is placed in {{ic|/etc/apparmor.d}} directory, and needs to be loaded into the kernel by running the following command as root:<br />
<br />
# apparmor_parser -r /etc/apparmor.d/firejail-default<br />
<br />
To quote the manual: <br />
<br />
:''The installed profile is supplemental for main firejail functions and among other things does the following:''<br />
<br />
::''- Disable ptrace. With ptrace it is possible to inspect and hijack running programs. Usually this is needed only for debugging.''<br />
<br />
::''- Whitelist write access to several files under /run, /proc and /sys.''<br />
<br />
::''- Allow running programs only from well-known system paths, such as /bin, /sbin, /usr/bin etc. Those paths are available as read-only. Running programs and scripts from user home or other directories writable by the user is not allowed.''<br />
<br />
::''- Prevent using non-standard network sockets. Only unix, inet, inet6, netlink, raw and packet are allowed.''<br />
<br />
::''- Deny access to known sensitive paths like .snapshots.''<br />
<br />
Local customizations of the apparmor profile are supported by editing the file {{ic|/etc/apparmor.d/local/firejail-local}}<br />
<br />
== Configuration ==<br />
<br />
Most users will not require any custom configuration and can proceed to [[#Usage]].<br />
<br />
Firejail uses profiles to set the security protections for each of the applications executed inside of it - you can find the default profiles in {{ic|/etc/firejail/''application''.profile}}. Should you require custom profiles for applications not included, or wish to modify the defaults, you may place new rules or copies of the defaults in the {{ic|~/.config/firejail/}} directory. You may have multiple custom profile files for a single application, and you may share the same profile file among several applications.<br />
<br />
If firejail does not have a profile for a particular application, it uses its restrictive system-wide default profile. This can result in the application not functioning as desired, without first creating a custom, and less restrictive profile.<br />
<br />
Refer to {{man|5|firejail-profile}}.<br />
<br />
== Usage ==<br />
<br />
To execute an application using firejail's default protections for that application (the default profile), execute the following:<br />
<br />
$ firejail <program name><br />
<br />
One-time additions to the default profile can be added as command line options (see the man page). For example, to execute ''okular'' with seccomp protection, execute the following:<br />
<br />
$ firejail --seccomp okular<br />
<br />
You may define multiple non-default profiles for a single program. Once you create your profile file, you can use it by executing:<br />
<br />
$ firejail --profile=/absolute/path/to/profile <program name><br />
<br />
=== Using Firejail by default ===<br />
<br />
To use Firejail by default for all applications for which it has profiles, run the ''firecfg'' tool as root.<br />
<br />
# firecfg<br />
<br />
This creates symbolic links in {{ic|/usr/local/bin}} pointing to {{ic|/usr/bin/firejail}}, for all programs for which firejail has default profiles.<br />
<br />
{{Tip|A [[pacman hook]] can be used to automatically run {{ic|firecfg}} on [[pacman]] operations:<br />
{{hc|/etc/pacman.d/hooks/firejail.hook|2=<br />
[Trigger]<br />
Type = File<br />
Operation = Install<br />
Operation = Upgrade<br />
Operation = Remove<br />
Target = usr/bin/*<br />
Target = usr/local/bin/*<br />
Target = usr/share/applications/*.desktop<br />
<br />
[Action]<br />
Description = Configure symlinks in /usr/local/bin based on firecfg.config...<br />
When = PostTransaction<br />
Depends = firejail<br />
Exec = /bin/sh -c 'firecfg &>/dev/null'}}}}<br />
<br />
To manually map individual applications execute:<br />
<br />
# ln -s /usr/bin/firejail /usr/local/bin/<application><br />
<br />
{{Note|1=<nowiki></nowiki><br />
* {{ic|/usr/local/bin}} should be set before {{ic|/usr/bin}} in the {{ic|PATH}} [[environment variable]].<br />
* To run a symbolic program with custom Firejail setting, simple prefix ''firejail'' as seen in [[#Usage]].<br />
* For a daemon, you will need to overwrite the systemd unit file for that daemon to call firejail, see [[systemd#Editing provided units]].<br />
* {{ic|firecfg}} doesn't work with some cli shells such as: {{ic|tar}}, {{ic|curl}}, {{ic|wget}}, and {{ic|git}} which need to be symlinked manually.<br />
* Symbolic links to {{ic|gzip}} and {{ic|xz}} interfere with {{ic|makepkg}}'s ability to preload {{ic|libfakeroot.so}}. See [https://bbs.archlinux.org/viewtopic.php?id=230913 BBS#230913].}}<br />
<br />
{{Warning|Upstream provides profiles for {{ic|gpg}} and {{ic|gpg-agent}}. If gpg is symlinked with the supplied profile, pacman will be unable to update {{pkg|archlinux-keyring}}.}}<br />
<br />
=== Use With hardened_malloc ===<br />
{{AUR|hardened_malloc}} is a hardened implementation of glibc's malloc() allocator, originally written for Android but extended for use on the desktop. While not integrated into glibc yet, it can be used selectively with LD_PRELOAD. The proper way to launch an application within firejail using hardened_malloc is demonstrated below. To make it permanent, you'd need to create your own entry in /usr/local/bin for the desired application.''<br />
<br />
{{bc|1=firejail --env=LD_PRELOAD='/usr/lib/libhardened_malloc.so' /usr/bin/firefox}}<br />
<br />
The various environment variables and settings that can be used to tune hardened_malloc can be found on it's [https://github.com/GrapheneOS/hardened_malloc github page].<br />
<br />
=== Enable AppArmor support ===<br />
There are a number of ways to enable [[AppArmor]] confinement on top of a Firejail security profile:<br />
<br />
* Pass the {{ic|--apparmor}} flag to Firejail in the command line, e.g. {{ic|$ firejail --apparmor firefox}}<br />
* Use a custom profile.<br />
* Enable Apparmor globally in {{ic|/etc/firejail/globals.local}} and disable as needed through the use of {{ic|ignore apparmor}} in {{ic|/etc/firejail/<ProgramName>.local}}.<br />
<br />
=== Verifying Firejail is being used ===<br />
<br />
$ firejail --list<br />
<br />
== Creating custom profiles ==<br />
<br />
=== Whitelists and Blacklists ===<br />
<br />
Blacklists are permissive:<br />
<br />
* Permit everything not explicitly forbidden: {{ic|blacklist <location/file>}}<br />
* Permit file or location in any later blacklist: {{ic|noblacklist <location/file>}} <br />
<br />
Whitelists are restrictive: <br />
<br />
* Forbid everything not explicitly permitted: {{ic|whitelist <location/file>}}<br />
* Forbid file or location in any later whitelist: {{ic|nowhitelist <location/file>}}<br />
<br />
=== Profile writing ===<br />
<br />
The basic process is:<br />
<br />
# Copy the default profile (which uses blacklists) to your work folder and give it a unique name<br />
# Change the line {{ic|include /etc/firejail/default.local}} to {{ic|include /etc/firejail/ProfileName.local}}<br />
# Gradually comment/uncomment the various options while checking at each stage that the application runs inside the new sandbox<br />
# Desirable options not available in the copied default profile can be found by consulting the manual<br />
# [https://firejail.wordpress.com/documentation-2/building-whitelisted-profiles/ Build a whitelist] of permitted locations. For portability, it may be advisable to place at least some of this list it in a {{ic|.local}} file<br />
# Test the profile for security holes, see [[#Testing profiles]]<br />
# Once satisfied, copy your new profile to either {{ic|/etc/firejail/}} or {{ic|~/.config/firejail/}}<br />
<br />
You may find the following to be useful:<br />
<br />
# {{ic|firejail --debug $OtherOptions $PathToProfile $Program > $PathToOutputFile}} Gives a detailed breakdown of the sandbox<br />
# {{ic|firejail --debug-caps}} gives a list of caps supported by the current Firejail software build. This is useful when building a [https://l3net.wordpress.com/2015/03/16/firejail-linux-capabilities-guide/ caps whitelist].<br />
# {{ic|firejail --help}} for a full list of {{ic|--debug}} options<br />
# {{ic|firemon PID}} monitors the running process. See {{ic|firemon --help}} for details<br />
# {{Pkg|checksec}} may also be useful in testing which standard security features are being used<br />
<br />
{{Note|<nowiki></nowiki><br />
* The idea is to be as restrictive as possible, while still maintaining usability. This may involve sacrificing potentially dangerous functionality and a change in cavalier work habits.<br />
* By default, seccomp filters work on a blacklist (which can be found in the manual). It is possible to use {{ic|seccomp.keep}} to build a custom whitelist of filters for an application. [https://firejail.wordpress.com/documentation-2/seccomp-guide/].<br />
* The list of possible options for a firejail profile is extensive, and users should consult the firejail-profile(5) man page.<br />
}}<br />
<br />
==== Persistent local customisation ====<br />
<br />
The standard profile layout now includes the capability to make persistent local customisations through the inclusion of {{ic|.local}} files. Basically, each officially supported profile contains the lines {{ic|include /etc/firejail/ProgramName.local}} and {{ic|include /etc/firejail/globals.local}}. Since the order of precedence is determined by which is read first, this makes for a very powerful way of making local customisations.<br />
For example, with reference [https://github.com/netblue30/firejail/issues/1510#issuecomment-326443650 this firejail question], to globally enable Apparmor and disable Internet connectivity, one could simply create/edit {{ic|/etc/firejail/globals.local}} to include the lines<br />
<br />
# enable Apparmor and disable Internet globally<br />
net none<br />
apparmor<br />
<br />
Then, to allow, for example, "curl" to connect to the internet, yet still maintain its apparmor confinement, one would create/edit {{ic|/etc/firejail/curl.local}} to include the lines.<br />
<br />
# enable internet for curl<br />
ignore net<br />
<br />
Since {{ic|curl.local}} is read before {{ic|globals.local}}, {{ic|ignore net}} overrides {{ic|net none}}, and, as a bonus, the above changes would be persistent across future updates.<br />
<br />
=== Testing profiles ===<br />
<br />
Firejail's built in audit feature allows the user to find gaps in a security profile by replacing the program to be sandboxed with a test program. By default, firejail uses the {{ic|faudit}} program distributed with Firejail. (Note: A custom test program supplied by the user can also be used.) <br />
Examples:<br />
<br />
# Run the default audit program: {{ic|$ firejail --audit transmission-gtk}}<br />
# Run a custom audit program: {{ic|1=$ firejail --audit=~/sandbox-test transmission-gtk}} <br />
<br />
In the examples above, the sandbox configures the transmission-gtk profile and starts the test program. The real program, transmission-gtk, will not be started.<br />
<br />
{{Note|The audit feature is not implemented for --x11 commands.}}<br />
<br />
== Firejail with Xephyr ==<br />
<br />
[[Xephyr]] will allow you to sandbox [[Xorg]]. If you want to be able to resize windows, install a window manager such as [[Openbox]].<br />
<br />
{{ic|xephyr-screen ''Width''x''Height''}} can be set in {{ic|/etc/firejail/firejail.config}} where {{ic|''Width''}} and {{ic|''Height''}} are in pixels and based on your screen resolution.<br />
<br />
To open the sandbox:<br />
<br />
$ firejail --x11 --net=''device'' openbox<br />
<br />
{{ic|''device''}} is your active [[network interface]]. Then right click and select your applications to run.<br />
<br />
{{Note|If you use [[Unbound]], [[dnsmasq]], [[Pdnsd]] or any other local cache as your resolver on 127.0.0.1 for example, you would leave {{ic|1=--net=''device''}} out of the command as your network should work automatically.}}<br />
<br />
A great guide can be found on the [https://firejail.wordpress.com/documentation-2/x11-guide/#configurexephyr Firejail Wordpress].<br />
<br />
According to the guide:<br />
<br />
:The sandbox replaces the regular X11 server with Xpra or Xephyr server. This prevents X11 keyboard loggers and screenshot utilities from accessing the main X11 server.<br />
<br />
Note that the statement:<br />
<br />
:The only way to disable the abstract socket {{ic|@/tmp/.X11-unix/X0}} is by using a network namespace. If for any reasons you cannot use a network namespace, the abstract socket will still be visible inside the sandbox. Hackers can attach keylogger and screenshot programs to this socket.<br />
<br />
is incorrect, [[Xinit#xserverrc|xserverrc]] can be edited to {{ic|-nolisten local}} which disables the abstract sockets of X11 and helps isolate it.<br />
<br />
=== Sandboxing a browser ===<br />
<br />
[[Openbox]] can be configured to start a certain browser at startup. {{ic|''program''.profile}} is the respective profile contained in {{ic|/etc/firejail}}, and {{ic|--startup "''command''"}} is the command line used to start the program. For example, to start Chromium in the sandbox:<br />
<br />
$ firejail --x11 --profile=/etc/firejail/chromium.profile openbox --startup "chromium"<br />
<br />
==Tips and tricks==<br />
<br />
=== Paths containing spaces ===<br />
<br />
If you need to reference, whitelist, or blacklist a directory within a custom profile, such as with {{aur|palemoon}}, you must do so using the absolute path, without encapsulation or escapes:<br />
/home/user/.moonchild productions<br />
<br />
===Private mode===<br />
<br />
Firejail also includes a one time private mode, in which no mounts are made in the chroots to your home directory. In doing this, you can execute applications without performing any changes to disk. For example, to execute okular in private mode, do the following:<br />
<br />
$ firejail --seccomp --private okular<br />
<br />
== Troubleshooting ==<br />
<br />
Some applications do not work properly with Firejail, and others simply require special configuration. In the instance any directories are disallowed or blacklisted for any given application, you may have to further edit the profile to enable nonstandard directories that said application needs to access. One example is wine; wine will not work with seccomp in most cases.<br />
<br />
Other configurations exist; it is suggested you check out the man page for firejail to see them all, as firejail is in rapid development.<br />
<br />
=== Remove Firejail symbolic links ===<br />
<br />
To remove Firejail created symbolic links (e.g. reset to default):<br />
<br />
# firecfg --clean<br />
<br />
Verify if any leftovers of [[Desktop entries]] are still overruled by Firejail.<br />
<br />
=== Desktop files ===<br />
<br />
Some GUI application launchers ({{ic|.desktop}} files) are coded using absolute paths to an executable, which circumvents firejail's symlink method of ensuring that it is being used. The ''firecfg'' tool includes an option to over-ride this on a per-user basis by copying the {{ic|.desktop}} files from {{ic|/usr/share/applications/*.desktop}} to {{ic|~/.local/share/applications/}} and replacing the absolute paths with simple file names.<br />
<br />
$ firecfg --fix<br />
<br />
There may be cases for which you need to manually modify the EXEC line of the {{ic|.desktop}} file in {{ic|~/.local/share/applications/}} to explicitly call Firejail.<br />
<br />
=== PulseAudio ===<br />
{{Note|Using PulseAudio version 9.0 or later should fix this issue.}}<br />
<br />
If Firejail causes [[PulseAudio]] issues with sandboxed applications [https://firejail.wordpress.com/support/known-problems/#pulseaudio], the following command may be used:<br />
<br />
$ firecfg --fix-sound<br />
<br />
This commands creates a custom {{ic|~/.config/pulse/client.conf}} file for the ''current'' user with {{ic|1=enable-shm = no}} and possible other workarounds.<br />
<br />
=== Hidepid ===<br />
<br />
If you have [[hidepid]] installed, Firemon can only be run as root. This, among other things, will cause problems with the Firetools GUI incorrectly reporting "Capabilities", "Protocols" and the status of "Seccomp". See [https://github.com/netblue30/firejail/issues/1564]<br />
<br />
=== Proprietary Nvidia drivers ===<br />
<br />
Some users report problems when using Firejail and proprietary graphic drivers from [[NVIDIA]] (e.g. [https://github.com/netblue30/firejail/issues/1753], [https://github.com/netblue30/firejail/issues/879] or [https://github.com/netblue30/firejail/issues/841]). This can often be solved by disabling the {{ic|noroot}} Firejail option in the application's profile file.<br />
<br />
=== --net options and Linux kernel >=4.20.0 ===<br />
<br />
There is a bug on firejail 0.5.96 with linux >= 4.20.0, see [https://github.com/netblue30/firejail/issues/2314] and [https://github.com/netblue30/firejail/pull/2327]<br />
<br />
Example error message:<br />
<br />
$ firejail --noprofile --net=eth0 ls<br />
Parent pid 8521, child pid 8522<br />
Error send: arp.c:182 arp_check: Invalid argument<br />
Error: proc 8521 cannot sync with peer: unexpected EOF<br />
Peer 8522 unexpectedly exited with status 1<br />
<br />
==See also==<br />
* [https://github.com/netblue30/firejail Firejail GitHub project page]<br />
* [[bubblewrap]], a minimal alternative to Firejail</div>Tepleshttps://wiki.archlinux.org/index.php?title=Security&diff=584160Security2019-09-29T20:33:56Z<p>Teples: /* Hardened Malloc */ link to stable version</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:File systems]]<br />
[[Category:Networking]]<br />
[[fa:امنیت]]<br />
[[ja:セキュリティ]]<br />
[[ru:Security]]<br />
[[zh-hans:Security]]<br />
{{Related articles start}}<br />
{{Related|Arch Security Team}}<br />
{{Related|General recommendations}}<br />
{{Related|PAM}}<br />
{{Related|Capabilities}}<br />
{{Related|List of Applications/Security}}<br />
{{Related articles end}}<br />
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.<br />
<br />
== Concepts ==<br />
<br />
* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.<br />
* 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.<br />
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!<br />
* 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.<br />
<br />
== Passwords ==<br />
<br />
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.<br />
<br />
=== Choosing secure passwords ===<br />
<br />
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]]. <br />
<br />
Insecure passwords include those containing:<br />
<br />
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)<br />
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})<br />
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})<br />
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.<br />
<br />
The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.<br />
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.<br />
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}}.<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
=== Maintaining passwords ===<br />
<br />
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}}).<br />
<br />
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.<br />
<br />
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.<br />
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).<br />
<br />
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.<br />
<br />
=== Password hashes ===<br />
<br />
{{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}}<br />
<br />
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]].<br />
<br />
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.<br />
<br />
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)].<br />
<br />
=== Enforcing strong passwords using pam_cracklib ===<br />
<br />
''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.<br />
<br />
{{Warning|The ''root'' account is not affected by this policy.}}<br />
<br />
{{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.}}<br />
<br />
If for example you want to enforce this policy:<br />
<br />
* prompt 2 times for password in case of an error<br />
* 10 characters minimum length (minlen option)<br />
* at least 6 characters should be different from old password when entering a new one (difok option)<br />
* at least 1 digit (dcredit option)<br />
* at least 1 uppercase (ucredit option)<br />
* at least 1 other character (ocredit option)<br />
* at least 1 lowercase (lcredit option)<br />
<br />
Edit the {{ic|/etc/pam.d/passwd}} file to read as:<br />
<br />
{{bc|1=<br />
#%PAM-1.0<br />
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1<br />
password required pam_unix.so use_authtok sha512 shadow<br />
}}<br />
<br />
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''.<br />
<br />
You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.<br />
<br />
== Memory ==<br />
<br />
=== Hardened Malloc ===<br />
<br />
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened_malloc}}) 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.<br />
<br />
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. For example, man fails to work properly unless its seccomp environment flag is disabled due to not having {{ic|getrandom}} in the standard whitelist, although this can be easily fixed by rebuilding it with the system call added. 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.<br />
<br />
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:<br />
<br />
LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox<br />
<br />
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.<br />
<br />
== Storage ==<br />
<br />
=== Disk encryption ===<br />
<br />
[[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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== File systems ===<br />
<br />
The kernel now prevents security issues related to hardlinks and symlinks if the {{ic|fs.protected_hardlinks}} and {{ic|fs.protected_symlinks}} sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.<br />
<br />
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 {{ic|/var}} or {{ic|/tmp}} is enough to take down services. More flexible mechanisms for dealing with this concern exist (like [[Disk quota|quotas]]), and some [[file systems]] include related features themselves (Btrfs has quotas on subvolumes).<br />
<br />
==== Mount options ====<br />
<br />
Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).<br />
<br />
Relevant mount options are:<br />
<br />
* {{ic|nodev}}: Do not interpret character or block special devices on the file system.<br />
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.<br />
* {{ic|noexec}}: Do not allow direct execution of any binaries on the mounted file system.<br />
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].<br />
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.<br />
<br />
{{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}}.}}<br />
<br />
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.<br />
<br />
Potential file system mounts to consider:<br />
<br />
* {{ic|/var}}<br />
* {{ic|/home}}<br />
* {{ic|/dev/shm}}<br />
* {{ic|/tmp}}<br />
* {{ic|/boot}}<br />
<br />
=== File access permissions ===<br />
<br />
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.<br />
<br />
For example:<br />
<br />
# chmod 700 /boot /etc/{iptables,arptables}<br />
<br />
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]].<br />
<br />
== User setup ==<br />
<br />
After installation make a normal user for daily use. Do not use the root user for daily use.<br />
<br />
=== Enforce a delay after a failed login attempt ===<br />
<br />
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:<br />
<br />
{{hc|/etc/pam.d/system-login|2=<br />
auth optional pam_faildelay.so delay=4000000<br />
}}<br />
<br />
{{ic|4000000}} is the time in microseconds to delay.<br />
<br />
=== Lockout user after three failed login attempts ===<br />
<br />
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.<br />
<br />
To lockout a user for ten minutes {{ic|1=unlock_time=600}} after three failed login attempts {{ic|1=deny=3}}, add the parameters to the PAM configuration as follows:<br />
<br />
{{hc|/etc/pam.d/system-login|2=<br />
auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog<br />
}}<br />
<br />
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:<br />
<br />
# pam_tally2 --reset --user ''username''<br />
<br />
{{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.<br />
<br />
=== Limit amount of processes ===<br />
<br />
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. <br />
<br />
* soft nproc 100<br />
* hard nproc 200<br />
<br />
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.<br />
<br />
=== Run Xorg rootless ===<br />
<br />
[[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.<br />
<br />
See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.<br />
<br />
== Restricting root ==<br />
<br />
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.<br />
<br />
=== Use sudo instead of su ===<br />
<br />
{{Merge|sudo|There's a dedicated article.}}<br />
<br />
Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].<br />
<br />
* It keeps a log of which normal privilege user has run each privileged command.<br />
* The root user password need not be given out to each user who requires root access.<br />
* {{ic|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 [[Wikipedia:Principle of least privilege|principle of least privilege]].<br />
* 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:<br />
<br />
# visudo<br />
<br />
{{hc|/etc/sudoers|2=<br />
alice ALL = NOPASSWD: /path/to/program<br />
}}<br />
<br />
Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:<br />
<br />
%users ALL=/sbin/mount.cifs,/sbin/umount.cifs<br />
<br />
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).<br />
<br />
{{Tip|<br />
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},<br />
<br />
{{hc|/etc/sudoers|2=<br />
Defaults editor=/usr/bin/rnano<br />
}}<br />
<br />
Exporting {{ic|1=EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.<br />
}}<br />
<br />
==== Editing files using sudo ====<br />
<br />
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 --edit 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:<br />
<br />
$ export SUDO_EDITOR=vim<br />
<br />
Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.<br />
<br />
=== Restricting root login ===<br />
<br />
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}}.<br />
<br />
==== Allow only certain users ====<br />
<br />
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]].<br />
<br />
==== Denying SSH login ====<br />
<br />
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.<br />
<br />
==== Specify acceptable login combinations with access.conf ====<br />
<br />
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. <br />
<br />
+:root:LOCAL<br />
-:root:ALL<br />
<br />
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:<br />
<br />
+:archie:LOCAL<br />
+:(wheel):LOCAL<br />
+:(adm):LOCAL<br />
-:ALL:ALL<br />
<br />
Read more at {{man|5|access.conf}}<br />
<br />
== Mandatory access control ==<br />
<br />
[[Wikipedia:Mandatory Access Control|Mandatory access control]] (MAC) is a type of security policy that differs significantly from the [[Wikipedia:Discretionary Access Control|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.<br />
<br />
=== Pathname MAC ===<br />
<br />
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.<br />
<br />
* [[AppArmor]] is a [[Wikipedia:Canonical_(company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.<br />
* [[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.<br />
<br />
=== Labels MAC ===<br />
<br />
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.<br />
<br />
* [[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.<br />
<br />
=== Access Control Lists ===<br />
<br />
[[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.<br />
<br />
== Kernel hardening ==<br />
<br />
=== Kernel self-protection / exploit mitigation ===<br />
<br />
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.<br />
<br />
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.<br />
<br />
==== Userspace ASLR comparison ====<br />
<br />
The {{pkg|linux-hardened}} package provides an improved implementation of Address Space Layout Randomization for userspace processes. The {{pkg|paxtest}} command can be used to obtain an estimate of the provided entropy:<br />
<br />
===== 64-bit processes =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 32 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 26 quality bits (guessed)<br />
Heap randomization test (PIE) : 40 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 32 quality bits (guessed)<br />
Shared library randomization test : 32 quality bits (guessed)<br />
VDSO randomization test : 32 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 40 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 40 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 44 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 44 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 32 bits (guessed)<br />
Randomization under memory exhaustion @0 : 32 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 28 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 28 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 28 quality bits (guessed)<br />
Shared library randomization test : 28 quality bits (guessed)<br />
VDSO randomization test : 20 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 30 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 30 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 22 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 22 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 28 bits (guessed)<br />
Randomization under memory exhaustion @0 : 28 bits (guessed)<br />
}}<br />
<br />
===== 32-bit processes (on an x86_64 kernel) =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 16 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 22 quality bits (guessed)<br />
Heap randomization test (PIE) : 27 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 18 quality bits (guessed)<br />
Shared library randomization test : 16 quality bits (guessed)<br />
VDSO randomization test : 16 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 24 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 24 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 28 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 28 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 18 bits (guessed)<br />
Randomization under memory exhaustion @0 : 18 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 8 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 13 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 8 quality bits (guessed)<br />
Shared library randomization test : 8 quality bits (guessed)<br />
VDSO randomization test : 8 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 19 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 19 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 11 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 11 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: No randomization<br />
Randomization under memory exhaustion @0 : No randomization<br />
}}<br />
<br />
=== Restricting access to kernel logs ===<br />
<br />
{{Tip|This is enabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
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).<br />
<br />
{{hc|/etc/sysctl.d/51-dmesg-restrict.conf|2=<br />
kernel.dmesg_restrict = 1<br />
}}<br />
<br />
=== Restricting access to kernel pointers in the proc filesystem ===<br />
<br />
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}<br />
<br />
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.<br />
<br />
Setting {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.<br />
<br />
{{hc|/etc/sysctl.d/51-kptr-restrict.conf|2=<br />
kernel.kptr_restrict = 1<br />
}}<br />
<br />
=== Keep BPF JIT compiler disabled ===<br />
<br />
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.<br />
<br />
{{Note|Arch Linux kernels are built with [https://cateee.net/lkddb/web-lkddb/BPF_JIT_ALWAYS_ON.html CONFIG_BPF_JIT_ALWAYS_ON] option which cannot be overridden by the above. You may set {{ic|net.core.bpf_jit_harden}} flag to {{ic|2}} instead.}}<br />
<br />
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.<br />
<br />
=== ptrace scope ===<br />
<br />
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.<br />
<br />
==== Examples of broken functionality ====<br />
<br />
{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}<br />
<br />
* {{ic|gdb -p $PID}}<br />
* {{ic|strace -p $PID}}<br />
* {{ic|perf trace -p $PID}}<br />
* {{ic|reptyr $PID}}<br />
<br />
=== hidepid ===<br />
<br />
{{Warning|<br />
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).<br />
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.<br />
}}<br />
<br />
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]. <br />
<br />
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.<br />
<br />
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]].<br />
<br />
For example, to hide process information from other users except those in the {{ic|proc}} group:<br />
<br />
{{hc|/etc/fstab|2=<br />
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0<br />
}}<br />
<br />
For user sessions to work correctly, an exception needs to be added for ''systemd-logind'':<br />
<br />
{{hc|/etc/systemd/system/systemd-logind.service.d/hidepid.conf|2=<br />
[Service]<br />
SupplementaryGroups=proc<br />
}}<br />
<br />
=== Restricting module loading ===<br />
<br />
The default Arch kernel has {{ic|CONFIG_MODULE_SIG_ALL}} enabled which signs all kernel modules build as part of the {{Pkg|linux}} package. This allows the kernel to restrict modules to be only loaded when they are signed with a valid key, in practical terms this means that all out of tree modules compiled locally or provides by packages such as {{Pkg|wireguard-arch}} cannot be loaded. Restricting loading kernel modules can be done by adding {{ic|1=module.sig_enforce=1}} to the kernel command line, further documentation can be found [https://www.kernel.org/doc/html/v5.2-rc3/admin-guide/module-signing.html here].<br />
<br />
=== Disable kexec ===<br />
<br />
{{Tip|kexec is disabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
Kexec allows replacing the current running kernel.<br />
<br />
{{hc|/etc/sysctl.d/51-kexec-restrict.conf|2=<br />
kernel.kexec_loaded_disabled = 1<br />
}}<br />
<br />
== Sandboxing applications ==<br />
<br />
See also [[Wikipedia:Sandbox (computer security)]].<br />
<br />
{{Note|The user namespace configuration item {{ic|CONFIG_USER_NS}} is currently enabled in {{Pkg|linux}} (4.14.5 or later), {{Pkg|linux-lts}} (4.14.15 or later) and {{Pkg|linux-hardened}}. Lack of it may prevent certain sandboxing features from being made available to applications.}}<br />
<br />
{{Warning|Unprivileged user namespace usage ({{ic|CONFIG_USER_NS_UNPRIVILEGED}}) is enabled by default in {{Pkg|linux}} (5.1.8 or later), {{Pkg|linux-lts}} (4.19.55-2 or later) and {{Pkg|linux-zen}} (5.1.14.zen1-2 or later) unless the {{ic|kernel.unprivileged_userns_clone}} [[sysctl]] is set to {{ic|0}}. Since this greatly increases the attack surface for local privilege escalation, it is advised to disable this manually, or use the {{Pkg|linux-hardened}} kernel. For more information see {{Bug|36969}}.}}<br />
<br />
=== Firejail ===<br />
<br />
[[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.<br />
<br />
=== bubblewrap ===<br />
<br />
[[bubblewrap]] is a 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].<br />
<br />
=== chroots ===<br />
<br />
Manual [[chroot]] jails can also be constructed.<br />
<br />
=== Linux containers ===<br />
<br />
[[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.<br />
<br />
=== Other virtualization options ===<br />
<br />
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.<br />
<br />
== Network and firewalls ==<br />
<br />
=== Firewalls ===<br />
<br />
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.<br />
<br />
* See [[iptables]] and [[nftables]] for general info.<br />
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.<br />
* See [[:Category:Firewalls]] for other ways of setting up netfilter.<br />
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.<br />
<br />
=== Kernel parameters ===<br />
<br />
Kernel parameters which affect networking can be set using [[Sysctl]]. For how to do this, see [[Sysctl#TCP/IP stack hardening]].<br />
<br />
=== SSH ===<br />
<br />
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.<br />
<br />
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).<br />
<br />
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]].<br />
<br />
=== DNS ===<br />
<br />
{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.<br />
<br />
=== Proxies ===<br />
<br />
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.<br />
<br />
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]<br />
<br />
=== Managing SSL certificates ===<br />
<br />
{{Merge|Transport Layer Security|There's a dedicated article.}}<br />
<br />
See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported. <br />
<br />
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. <br />
<br />
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:<br />
<br />
# 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), <br />
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and <br />
# Run ''update-ca-trust'' as root. <br />
<br />
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.<br />
<br />
== Authenticating packages ==<br />
<br />
[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.<br />
<br />
== Follow vulnerability alerts ==<br />
<br />
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]].<br />
<br />
{{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.}}<br />
<br />
== Physical security ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
[[#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.<br />
<br />
=== Locking down BIOS ===<br />
<br />
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.<br />
<br />
=== Bootloaders ===<br />
<br />
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.<br />
<br />
==== Syslinux ====<br />
<br />
Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.<br />
<br />
==== GRUB ====<br />
<br />
[[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.<br />
<br />
=== Boot partition on removable flash drive ===<br />
<br />
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. <br />
<br />
=== Automatic logout ===<br />
<br />
If you are using [[Bash]] or [[Zsh]], you can set {{ic|TMOUT}} for an automatic logout from shells after a timeout.<br />
<br />
For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):<br />
<br />
{{hc|/etc/profile.d/shell-timeout.sh|<nowiki><br />
TMOUT="$(( 60*10 ))";<br />
[ -z "$DISPLAY" ] && export TMOUT;<br />
case $( /usr/bin/tty ) in<br />
/dev/tty[0-9]*) export TMOUT;;<br />
esac<br />
</nowiki>}}<br />
<br />
If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:<br />
<br />
$ export TMOUT="$(( 60*10 ))";<br />
<br />
Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without {{ic|TMOUT}} support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.<br />
<br />
=== Protect against rogue USB devices ===<br />
<br />
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.<br />
<br />
== Rebuilding packages ==<br />
<br />
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.<br />
<br />
== See also ==<br />
<br />
* [https://security.archlinux.org/ Arch Linux Security Tracker]<br />
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]<br />
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]<br />
* [https://www.privacytools.io/ privacytools.io Privacy Resources]<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]<br />
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]<br />
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Snap&diff=583725Snap2019-09-23T12:52:10Z<p>Teples: /* Graphical management */ Unfortunately gsc snap support was dropped from aur prematurely</p>
<hr />
<div>[[Category:Development]]<br />
[[es:Snap]]<br />
[[ja:Snap]]<br />
[[pl:Snap]]<br />
[[ru:Snap]]<br />
{{Related articles start}}<br />
{{Related|Flatpak}}<br />
{{Related|AppArmor}}<br />
{{Related articles end}}<br />
<br />
[https://snapcraft.io/ Snap] is a software deployment and package management system. The packages are called 'snaps' and the tool for using them is 'snapd', which works across a range of Linux distributions and allows, therefore, distro-agnostic upstream software deployment. Snap was originally designed and built by Canonical.<br />
<br />
[https://github.com/snapcore/snapd snapd] is a REST API daemon for managing snap packages. Users can interact with it by using the ''snap'' client, which is part of the same package. <br />
<br />
Snaps can be confined using [[AppArmor]] which is now enabled in the default kernel. Consult relevant wiki pages to find steps for enabling [[AppArmor]] in your system.<br />
<br />
==Installation==<br />
<br />
[[Install]] the {{AUR|snapd}} or the {{AUR|snapd-git}} package.<br />
<br />
{{tip|{{ic|snapd}} installs a script in {{ic|/etc/profile.d/snapd.sh}} to export the paths of binaries installed with the snapd package and desktop entries. Reboot once to make this change take effect.}}<br />
<br />
Since version 2.36, {{ic|snapd}} enabled AppArmor support for Arch Linux. In order to use it, you have to enable AppArmor in your system, see [[AppArmor#Installation]].<br />
<br />
{{Note|If AppArmor isn't enabled in your system then all snaps will run in {{ic|devel}} mode which mean they will have same, unrestricted access to your system as apps installed from Arch Linux repositories.}}<br />
<br />
If you are using [[AppArmor]]:<br />
<br />
$ systemctl enable --now apparmor.service<br />
$ systemctl enable --now snapd.apparmor.service<br />
<br />
== Configuration ==<br />
<br />
To launch the {{ic|snapd}} daemon when ''snap'' tries to use it, [[start]] and/or [[enable]] the {{ic|snapd.socket}}.<br />
<br />
== Usage == <br />
The ''snap'' tool is used to manage the snaps.<br />
<br />
=== Finding ===<br />
To find snaps to install, you can query the Ubuntu Store with:<br />
<br />
$ snap find ''searchterm''<br />
<br />
=== Installing ===<br />
Once you found the snap you are looking for you can install it with:<br />
# snap install ''snapname''<br />
This requires root privileges. Per user installation of snaps is not possible, yet. This will download the snap into {{ic|/var/lib/snapd/snaps}} and mount it to {{ic|/var/lib/snapd/snap/''snapname''}} to make it available to the system.<br />
<br />
It will also create mount units for each snap and add them to {{ic| /etc/systemd/system/multi-user.target.wants/}} as symlinks to make all snaps available when the system is booted.<br />
Once that is done you should find it in the list of installed snaps together with its version number, revision and developer using:<br />
$ snap list<br />
<br />
You can also sideload snaps from your local hard drive with:<br />
# snap install --dangerous ''/path/to/snap''<br />
<br />
=== Updating ===<br />
To update your snaps manually use:<br />
# snap refresh<br />
<br />
Snaps are refreshed automatically according to snap {{ic|refresh.timer}} setting.<br />
<br />
To view the next/last refresh times use:<br />
# snap refresh --time<br />
<br />
To set a different refresh time, eg. twice a day:<br />
# snap set core refresh.timer=0:00~24:00/2<br />
<br />
See [https://forum.snapcraft.io/t/system-options/87 system options documentation page] for details on customizing the refresh time.<br />
<br />
=== Removing ===<br />
Snaps can be removed by executing:<br />
# snap remove ''snapname''<br />
<br />
== Tips and tricks ==<br />
=== Classic snaps ===<br />
Some snaps (e.g. Skype and Pycharm) use classic confinement. However, classic confinement requires the {{ic|/snap}} directory, which is not FHS-compliant. Therefore, the snapd package doesn't ship this directory. However, if the user wants to, they can manually create a symlink from {{ic|/snap}} to {{ic|/var/lib/snapd/snap}}, to allow the installation of classic snaps:<br />
<br />
# ln -s /var/lib/snapd/snap /snap<br />
<br />
=== Confinement ===<br />
<br />
When using [[AppArmor]], snapd (2.36+) will generate the same profiles for snaps as on Ubuntu. The [[AppArmor]] parser is smart enough to drop the rules that are not yet supported by the mainline kernel.<br />
<br />
To verify that basic confinement is working, install ''hello-world'' snap. Then run the following:<br />
<br />
$ hello-world.evil<br />
Hello Evil World!<br />
This example demonstrates the app confinement<br />
You should see a permission denied error next<br />
/snap/hello-world/27/bin/evil: 9: /snap/hello-world/27/bin/evil: cannot create /var/tmp/myevil.txt: Permission denied<br />
<br />
The denial was caused by AppArmor and should have been logged:<br />
<br />
$ dmesg<br />
...<br />
[ +0.000003] audit: type=1327 audit(1540469583.966:257): proctitle=2F62696E2F7368002F736E61702F68656C6C6F2D776F726C642F32372F62696E2F6576696C<br />
[ +12.268939] audit: type=1400 audit(1540469596.236:258): apparmor="DENIED" operation="open" profile="snap.hello-world.evil" name="/var/tmp/myevil.txt" pid=10835 comm="evil" requested_mask="wc" denied_mask="wc" fsuid=1000 ouid=1000<br />
[ +0.000006] audit: type=1300 audit(1540469596.236:258): arch=c000003e syscall=2 success=no exit=-13 a0=55d991ba6bc8 a1=241 a2=1b6 a3=55d991ba6be0 items=0 ppid=31349 pid=10835 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts2 ses=3 comm="evil" exe="/bin/dash" subj==snap.hello-world.evil (enforce)<br />
...<br />
<br />
If you do not see the denial, verify that the profiles were loaded:<br />
<br />
$ sudo aa-status |grep snap.hello-world<br />
snap.hello-world.env<br />
snap.hello-world.evil<br />
snap.hello-world.hello-world<br />
snap.hello-world.sh<br />
<br />
Also, you can check what sandbox features are available in the system according to snapd:<br />
<br />
$ snap debug sandbox-features<br />
apparmor: kernel:caps kernel:domain kernel:file kernel:mount kernel:namespaces kernel:network_v8 kernel:policy kernel:ptrace kernel:query kernel:rlimit kernel:signal parser:unsafe policy:default support-level:partial<br />
confinement-options: devmode<br />
dbus: mediated-bus-access<br />
kmod: mediated-modprobe<br />
mount: freezer-cgroup-v1 layouts mount-namespace per-snap-persistency per-snap-profiles per-snap-updates per-snap-user-profiles stale-base-invalidation<br />
seccomp: bpf-argument-filtering kernel:allow kernel:errno kernel:kill_process kernel:kill_thread kernel:log kernel:trace kernel:trap<br />
<br />
== Graphical management ==<br />
Both Gnome Software Center and KDE Discover can provide native snap support. For KDE Discover install {{AUR|discover-snap}} package.<br />
<br />
== Support ==<br />
Arch Linux related mailing lists and other official Arch Linux support channels aren't an appropriate place to request help with snaps on Arch Linux. An appropriate place to ask for support is the [https://forum.snapcraft.io Snapcraft forum].<br />
<br />
== See also == <br />
* [https://snapcraft.io/ Official site]<br />
* [https://github.com/snapcore/snapd GitHub repository]<br />
* [http://arstechnica.com/information-technology/2016/06/goodbye-apt-and-yum-ubuntus-snap-apps-are-coming-to-distros-everywhere/ arstechnica article] (06/16) about Ubuntu snaps becoming available for Arch and other distros</div>Tepleshttps://wiki.archlinux.org/index.php?title=Snap&diff=583722Snap2019-09-23T12:46:27Z<p>Teples: Undo revision 577833 by Thisischrys (talk) They didn't. MR for removal was rejected: https://gitlab.gnome.org/GNOME/gnome-software/merge_requests/253</p>
<hr />
<div>[[Category:Development]]<br />
[[es:Snap]]<br />
[[ja:Snap]]<br />
[[pl:Snap]]<br />
[[ru:Snap]]<br />
{{Related articles start}}<br />
{{Related|Flatpak}}<br />
{{Related|AppArmor}}<br />
{{Related articles end}}<br />
<br />
[https://snapcraft.io/ Snap] is a software deployment and package management system. The packages are called 'snaps' and the tool for using them is 'snapd', which works across a range of Linux distributions and allows, therefore, distro-agnostic upstream software deployment. Snap was originally designed and built by Canonical.<br />
<br />
[https://github.com/snapcore/snapd snapd] is a REST API daemon for managing snap packages. Users can interact with it by using the ''snap'' client, which is part of the same package. <br />
<br />
Snaps can be confined using [[AppArmor]] which is now enabled in the default kernel. Consult relevant wiki pages to find steps for enabling [[AppArmor]] in your system.<br />
<br />
==Installation==<br />
<br />
[[Install]] the {{AUR|snapd}} or the {{AUR|snapd-git}} package.<br />
<br />
{{tip|{{ic|snapd}} installs a script in {{ic|/etc/profile.d/snapd.sh}} to export the paths of binaries installed with the snapd package and desktop entries. Reboot once to make this change take effect.}}<br />
<br />
Since version 2.36, {{ic|snapd}} enabled AppArmor support for Arch Linux. In order to use it, you have to enable AppArmor in your system, see [[AppArmor#Installation]].<br />
<br />
{{Note|If AppArmor isn't enabled in your system then all snaps will run in {{ic|devel}} mode which mean they will have same, unrestricted access to your system as apps installed from Arch Linux repositories.}}<br />
<br />
If you are using [[AppArmor]]:<br />
<br />
$ systemctl enable --now apparmor.service<br />
$ systemctl enable --now snapd.apparmor.service<br />
<br />
== Configuration ==<br />
<br />
To launch the {{ic|snapd}} daemon when ''snap'' tries to use it, [[start]] and/or [[enable]] the {{ic|snapd.socket}}.<br />
<br />
== Usage == <br />
The ''snap'' tool is used to manage the snaps.<br />
<br />
=== Finding ===<br />
To find snaps to install, you can query the Ubuntu Store with:<br />
<br />
$ snap find ''searchterm''<br />
<br />
=== Installing ===<br />
Once you found the snap you are looking for you can install it with:<br />
# snap install ''snapname''<br />
This requires root privileges. Per user installation of snaps is not possible, yet. This will download the snap into {{ic|/var/lib/snapd/snaps}} and mount it to {{ic|/var/lib/snapd/snap/''snapname''}} to make it available to the system.<br />
<br />
It will also create mount units for each snap and add them to {{ic| /etc/systemd/system/multi-user.target.wants/}} as symlinks to make all snaps available when the system is booted.<br />
Once that is done you should find it in the list of installed snaps together with its version number, revision and developer using:<br />
$ snap list<br />
<br />
You can also sideload snaps from your local hard drive with:<br />
# snap install --dangerous ''/path/to/snap''<br />
<br />
=== Updating ===<br />
To update your snaps manually use:<br />
# snap refresh<br />
<br />
Snaps are refreshed automatically according to snap {{ic|refresh.timer}} setting.<br />
<br />
To view the next/last refresh times use:<br />
# snap refresh --time<br />
<br />
To set a different refresh time, eg. twice a day:<br />
# snap set core refresh.timer=0:00~24:00/2<br />
<br />
See [https://forum.snapcraft.io/t/system-options/87 system options documentation page] for details on customizing the refresh time.<br />
<br />
=== Removing ===<br />
Snaps can be removed by executing:<br />
# snap remove ''snapname''<br />
<br />
== Tips and tricks ==<br />
=== Classic snaps ===<br />
Some snaps (e.g. Skype and Pycharm) use classic confinement. However, classic confinement requires the {{ic|/snap}} directory, which is not FHS-compliant. Therefore, the snapd package doesn't ship this directory. However, if the user wants to, they can manually create a symlink from {{ic|/snap}} to {{ic|/var/lib/snapd/snap}}, to allow the installation of classic snaps:<br />
<br />
# ln -s /var/lib/snapd/snap /snap<br />
<br />
=== Confinement ===<br />
<br />
When using [[AppArmor]], snapd (2.36+) will generate the same profiles for snaps as on Ubuntu. The [[AppArmor]] parser is smart enough to drop the rules that are not yet supported by the mainline kernel.<br />
<br />
To verify that basic confinement is working, install ''hello-world'' snap. Then run the following:<br />
<br />
$ hello-world.evil<br />
Hello Evil World!<br />
This example demonstrates the app confinement<br />
You should see a permission denied error next<br />
/snap/hello-world/27/bin/evil: 9: /snap/hello-world/27/bin/evil: cannot create /var/tmp/myevil.txt: Permission denied<br />
<br />
The denial was caused by AppArmor and should have been logged:<br />
<br />
$ dmesg<br />
...<br />
[ +0.000003] audit: type=1327 audit(1540469583.966:257): proctitle=2F62696E2F7368002F736E61702F68656C6C6F2D776F726C642F32372F62696E2F6576696C<br />
[ +12.268939] audit: type=1400 audit(1540469596.236:258): apparmor="DENIED" operation="open" profile="snap.hello-world.evil" name="/var/tmp/myevil.txt" pid=10835 comm="evil" requested_mask="wc" denied_mask="wc" fsuid=1000 ouid=1000<br />
[ +0.000006] audit: type=1300 audit(1540469596.236:258): arch=c000003e syscall=2 success=no exit=-13 a0=55d991ba6bc8 a1=241 a2=1b6 a3=55d991ba6be0 items=0 ppid=31349 pid=10835 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts2 ses=3 comm="evil" exe="/bin/dash" subj==snap.hello-world.evil (enforce)<br />
...<br />
<br />
If you do not see the denial, verify that the profiles were loaded:<br />
<br />
$ sudo aa-status |grep snap.hello-world<br />
snap.hello-world.env<br />
snap.hello-world.evil<br />
snap.hello-world.hello-world<br />
snap.hello-world.sh<br />
<br />
Also, you can check what sandbox features are available in the system according to snapd:<br />
<br />
$ snap debug sandbox-features<br />
apparmor: kernel:caps kernel:domain kernel:file kernel:mount kernel:namespaces kernel:network_v8 kernel:policy kernel:ptrace kernel:query kernel:rlimit kernel:signal parser:unsafe policy:default support-level:partial<br />
confinement-options: devmode<br />
dbus: mediated-bus-access<br />
kmod: mediated-modprobe<br />
mount: freezer-cgroup-v1 layouts mount-namespace per-snap-persistency per-snap-profiles per-snap-updates per-snap-user-profiles stale-base-invalidation<br />
seccomp: bpf-argument-filtering kernel:allow kernel:errno kernel:kill_process kernel:kill_thread kernel:log kernel:trace kernel:trap<br />
<br />
== Graphical management ==<br />
Both Gnome Software Center and KDE Discover can provide native snap support with the {{AUR|gnome-software-snap}} or {{AUR|discover-snap}} packages.<br />
<br />
== Support ==<br />
Arch Linux related mailing lists and other official Arch Linux support channels aren't an appropriate place to request help with snaps on Arch Linux. An appropriate place to ask for support is the [https://forum.snapcraft.io Snapcraft forum].<br />
<br />
== See also == <br />
* [https://snapcraft.io/ Official site]<br />
* [https://github.com/snapcore/snapd GitHub repository]<br />
* [http://arstechnica.com/information-technology/2016/06/goodbye-apt-and-yum-ubuntus-snap-apps-are-coming-to-distros-everywhere/ arstechnica article] (06/16) about Ubuntu snaps becoming available for Arch and other distros</div>Tepleshttps://wiki.archlinux.org/index.php?title=Security&diff=578430Security2019-07-30T20:56:29Z<p>Teples: /* Disable kexec */ Other references to linux-hardened use Note so keep it consistent</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:File systems]]<br />
[[Category:Networking]]<br />
[[fa:امنیت]]<br />
[[ja:セキュリティ]]<br />
[[ru:Security]]<br />
[[zh-hans:Security]]<br />
{{Related articles start}}<br />
{{Related|Arch Security Team}}<br />
{{Related|General recommendations}}<br />
{{Related|PAM}}<br />
{{Related|Capabilities}}<br />
{{Related|List of Applications/Security}}<br />
{{Related articles end}}<br />
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.<br />
<br />
== Concepts ==<br />
<br />
* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.<br />
* 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.<br />
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!<br />
* 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.<br />
<br />
== Passwords ==<br />
<br />
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.<br />
<br />
=== Choosing secure passwords ===<br />
<br />
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]]. <br />
<br />
Insecure passwords include those containing:<br />
<br />
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)<br />
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})<br />
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})<br />
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.<br />
<br />
The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.<br />
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.<br />
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}}.<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
=== Maintaining passwords ===<br />
<br />
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}}).<br />
<br />
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.<br />
<br />
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.<br />
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).<br />
<br />
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.<br />
<br />
=== Password hashes ===<br />
<br />
{{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}}<br />
<br />
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]].<br />
<br />
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.<br />
<br />
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)].<br />
<br />
=== Enforcing strong passwords using pam_cracklib ===<br />
<br />
''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.<br />
<br />
{{Warning|The ''root'' account is not affected by this policy.}}<br />
{{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.}}<br />
<br />
If for example you want to enforce this policy:<br />
<br />
* prompt 2 times for password in case of an error<br />
* 10 characters minimum length (minlen option)<br />
* at least 6 characters should be different from old password when entering a new one (difok option)<br />
* at least 1 digit (dcredit option)<br />
* at least 1 uppercase (ucredit option)<br />
* at least 1 other character (ocredit option)<br />
* at least 1 lowercase (lcredit option)<br />
<br />
Edit the {{ic|/etc/pam.d/passwd}} file to read as:<br />
<br />
{{bc|1=<br />
#%PAM-1.0<br />
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1<br />
password required pam_unix.so use_authtok sha512 shadow<br />
}}<br />
<br />
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''.<br />
<br />
You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.<br />
<br />
== Memory ==<br />
<br />
=== Hardened Malloc ===<br />
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened-malloc-git}}) 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.<br />
<br />
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. For example, man fails to work properly unless its seccomp environment flag is disabled due to not having {{ic|getrandom}} in the standard whitelist, although this can be easily fixed by rebuilding it with the system call added. 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.<br />
<br />
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:<br />
<br />
{{bc|1=LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox}}<br />
<br />
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.<br />
<br />
== Storage ==<br />
<br />
=== Disk encryption ===<br />
<br />
[[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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== File systems ===<br />
<br />
The kernel now prevents security issues related to hardlinks and symlinks if the {{ic|fs.protected_hardlinks}} and {{ic|fs.protected_symlinks}} sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.<br />
<br />
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 {{ic|/var}} or {{ic|/tmp}} is enough to take down services. More flexible mechanisms for dealing with this concern exist (like [[Disk quota|quotas]]), and some [[file systems]] include related features themselves (Btrfs has quotas on subvolumes).<br />
<br />
==== Mount options ====<br />
<br />
Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).<br />
<br />
Relevant mount options are:<br />
<br />
* {{ic|nodev}}: Do not interpret character or block special devices on the file system.<br />
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.<br />
* {{ic|noexec}}: Do not allow direct execution of any binaries on the mounted file system.<br />
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].<br />
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.<br />
<br />
{{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}}.}}<br />
<br />
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.<br />
<br />
Potential file system mounts to consider:<br />
<br />
* {{ic|/var}}<br />
* {{ic|/home}}<br />
* {{ic|/dev/shm}}<br />
* {{ic|/tmp}}<br />
* {{ic|/boot}}<br />
<br />
=== File access permissions ===<br />
<br />
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.<br />
<br />
For example:<br />
<br />
# chmod 700 /boot /etc/{iptables,arptables}<br />
<br />
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]].<br />
<br />
== User setup ==<br />
<br />
After installation make a normal user for daily use. Do not use the root user for daily use.<br />
<br />
=== Enforce a delay after a failed login attempt ===<br />
<br />
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:<br />
<br />
{{hc|/etc/pam.d/system-login|<br />
2=auth optional pam_faildelay.so delay=4000000<br />
}}<br />
<br />
{{ic|4000000}} is the time in microseconds to delay.<br />
<br />
=== Lockout user after three failed login attempts ===<br />
<br />
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.<br />
<br />
To lockout a user for ten minutes {{ic|1=unlock_time=600}} after three failed login attempts {{ic|1=deny=3}}, add the parameters to the PAM configuration as follows:<br />
<br />
{{hc|/etc/pam.d/system-login|2=auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog<br />
}}<br />
<br />
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:<br />
<br />
# pam_tally2 --reset --user ''username''<br />
<br />
{{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.<br />
<br />
=== Limit amount of processes ===<br />
<br />
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. <br />
<br />
* soft nproc 100<br />
* hard nproc 200<br />
<br />
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.<br />
<br />
=== Run Xorg rootless ===<br />
<br />
[[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.<br />
<br />
See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.<br />
<br />
== Restricting root ==<br />
<br />
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.<br />
<br />
=== Use sudo instead of su ===<br />
<br />
{{Merge|sudo|There's a dedicated article.}}<br />
<br />
Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].<br />
<br />
* It keeps a log of which normal privilege user has run each privileged command.<br />
* The root user password need not be given out to each user who requires root access.<br />
* {{ic|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 [[Wikipedia:Principle of least privilege|principle of least privilege]].<br />
* 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:<br />
<br />
# visudo<br />
<br />
{{hc|/etc/sudoers|<br />
alice ALL &#61; NOPASSWD: /path/to/program<br />
}}<br />
<br />
Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:<br />
<br />
%users ALL=/sbin/mount.cifs,/sbin/umount.cifs<br />
<br />
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).<br />
<br />
{{Tip|<br />
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},<br />
<br />
{{hc|/etc/sudoers|<br />
2=Defaults editor=/usr/bin/rnano<br />
}}<br />
<br />
Exporting {{ic|1=# EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.<br />
}}<br />
<br />
==== Editing files using sudo ====<br />
<br />
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 --edit 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:<br />
<br />
$ export SUDO_EDITOR=vim<br />
<br />
Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.<br />
<br />
=== Restricting root login ===<br />
<br />
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}}.<br />
<br />
==== Allow only certain users ====<br />
<br />
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:<br />
<br />
{{bc|<nowiki><br />
# Uncomment the following line to require a user to be in the "wheel" group.<br />
auth required pam_wheel.so use_uid<br />
</nowiki>}}<br />
<br />
This means only users who are already able to run privileged commands may login as root.<br />
<br />
==== Denying SSH login ====<br />
<br />
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.<br />
<br />
==== Specify acceptable login combinations with access.conf ====<br />
<br />
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. <br />
<br />
+:root:LOCAL<br />
-:root:ALL<br />
<br />
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:<br />
<br />
+:archie:LOCAL<br />
+:(wheel):LOCAL<br />
+:(adm):LOCAL<br />
-:ALL:ALL<br />
<br />
Read more at {{man|5|access.conf}}<br />
<br />
== Mandatory access control ==<br />
<br />
[[Wikipedia:Mandatory Access Control|Mandatory access control]] (MAC) is a type of security policy that differs significantly from the [[Wikipedia:Discretionary Access Control|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.<br />
<br />
=== Pathname MAC ===<br />
<br />
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.<br />
<br />
* [[AppArmor]] is a [[Wikipedia:Canonical_(company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.<br />
* [[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.<br />
<br />
=== Labels MAC ===<br />
<br />
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.<br />
<br />
* [[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.<br />
<br />
=== Access Control Lists ===<br />
<br />
[[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.<br />
<br />
== Kernel hardening ==<br />
<br />
=== Kernel self-protection / exploit mitigation ===<br />
<br />
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.<br />
<br />
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.<br />
<br />
==== Userspace ASLR comparison ====<br />
<br />
The {{pkg|linux-hardened}} package provides an improved implementation of Address Space Layout Randomization for userspace processes. The {{pkg|paxtest}} command can be used to obtain an estimate of the provided entropy:<br />
<br />
===== 64-bit processes =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 32 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 26 quality bits (guessed)<br />
Heap randomization test (PIE) : 40 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 32 quality bits (guessed)<br />
Shared library randomization test : 32 quality bits (guessed)<br />
VDSO randomization test : 32 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 40 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 40 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 44 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 44 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 32 bits (guessed)<br />
Randomization under memory exhaustion @0 : 32 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 28 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 28 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 28 quality bits (guessed)<br />
Shared library randomization test : 28 quality bits (guessed)<br />
VDSO randomization test : 20 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 30 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 30 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 22 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 22 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 28 bits (guessed)<br />
Randomization under memory exhaustion @0 : 28 bits (guessed)<br />
}}<br />
<br />
===== 32-bit processes (on an x86_64 kernel) =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 16 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 22 quality bits (guessed)<br />
Heap randomization test (PIE) : 27 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 18 quality bits (guessed)<br />
Shared library randomization test : 16 quality bits (guessed)<br />
VDSO randomization test : 16 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 24 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 24 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 28 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 28 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 18 bits (guessed)<br />
Randomization under memory exhaustion @0 : 18 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 8 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 13 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 8 quality bits (guessed)<br />
Shared library randomization test : 8 quality bits (guessed)<br />
VDSO randomization test : 8 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 19 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 19 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 11 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 11 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: No randomization<br />
Randomization under memory exhaustion @0 : No randomization<br />
}}<br />
<br />
=== Restricting access to kernel logs ===<br />
<br />
{{Note|This is enabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
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).<br />
<br />
{{hc|/etc/sysctl.d/50-dmesg-restrict.conf|2=<br />
kernel.dmesg_restrict = 1<br />
}}<br />
<br />
=== Restricting access to kernel pointers in the proc filesystem ===<br />
<br />
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}<br />
<br />
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.<br />
<br />
Setting {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.<br />
<br />
{{hc|/etc/sysctl.d/50-kptr-restrict.conf|2=<br />
kernel.kptr_restrict = 1<br />
}}<br />
<br />
=== Keep BPF JIT compiler disabled ===<br />
<br />
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.<br />
<br />
{{Note|Arch Linux kernels are built with [https://cateee.net/lkddb/web-lkddb/BPF_JIT_ALWAYS_ON.html CONFIG_BPF_JIT_ALWAYS_ON] option which can't be overridden by the above. You may set {{ic|net.core.bpf_jit_harden}} flag to {{ic|2}} instead.}}<br />
<br />
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.<br />
<br />
=== ptrace scope ===<br />
<br />
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.<br />
<br />
==== Examples of broken functionality ====<br />
<br />
{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}<br />
<br />
* {{ic|gdb -p $PID}}<br />
* {{ic|strace -p $PID}}<br />
* {{ic|perf trace -p $PID}}<br />
* {{ic|reptyr $PID}}<br />
<br />
=== hidepid ===<br />
<br />
{{Warning|<br />
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).<br />
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.<br />
}}<br />
<br />
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]. <br />
<br />
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.<br />
<br />
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]].<br />
<br />
For example, to hide process information from other users except those in the {{ic|proc}} group:<br />
<br />
{{hc|/etc/fstab|2=<br />
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0<br />
}}<br />
<br />
For user sessions to work correctly, an exception needs to be added for ''systemd-logind'':<br />
<br />
{{hc|/etc/systemd/system/systemd-logind.service.d/hidepid.conf|2=<br />
[Service]<br />
SupplementaryGroups=proc<br />
}}<br />
<br />
=== Restricting module loading ===<br />
The default Arch kernel has {{ic|CONFIG_MODULE_SIG_ALL}} enabled which signs all kernel modules build as part of the {{Pkg|linux}} package. This allows the kernel to restrict modules to be only loaded when they are signed with a valid key, in practical terms this means that all out of tree modules compiled locally or provides by packages such as {{Pkg|wireguard-arch}} cannot be loaded. Restricting loading kernel modules can be done by adding {{ic|1=module.sig_enforce=1}} to the kernel command line, further documentation can be found [https://www.kernel.org/doc/html/v5.2-rc3/admin-guide/module-signing.html here].<br />
<br />
=== Disable kexec ===<br />
<br />
{{Note|kexec is disabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
Kexec allows replacing the current running kernel.<br />
<br />
{{hc|/etc/sysctl.d/50-kexec-restrict.conf|2=<br />
kernel.kexec_loaded_disabled = 1<br />
}}<br />
<br />
== Sandboxing applications ==<br />
<br />
See also [[Wikipedia:Sandbox (computer security)]].<br />
<br />
{{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 enabled by default starting with v5.1.8 unless the {{ic|kernel.unprivileged_userns_clone}} [[sysctl]] is set to {{ic|0}}. Since this greatly increases the attack surface for local privilege escalation, it is advised to disable this manually, or use the {{Pkg|linux-hardened}} kernel.}}<br />
<br />
=== Firejail ===<br />
<br />
[[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.<br />
<br />
=== bubblewrap ===<br />
<br />
[[bubblewrap]] is a 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].<br />
<br />
=== chroots ===<br />
<br />
Manual [[chroot]] jails can also be constructed.<br />
<br />
=== Linux containers ===<br />
<br />
[[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.<br />
<br />
=== Other virtualization options ===<br />
<br />
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.<br />
<br />
== Network and firewalls ==<br />
<br />
=== Firewalls ===<br />
<br />
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.<br />
<br />
* See [[iptables]] and [[nftables]] for general info.<br />
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.<br />
* See [[:Category:Firewalls]] for other ways of setting up netfilter.<br />
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.<br />
<br />
=== Kernel parameters ===<br />
<br />
Kernel parameters which affect networking can be set using [[Sysctl]]. For how to do this, see [[Sysctl#TCP/IP stack hardening]].<br />
<br />
=== SSH ===<br />
<br />
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.<br />
<br />
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).<br />
<br />
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]].<br />
<br />
=== DNS ===<br />
<br />
{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.<br />
<br />
=== Proxies ===<br />
<br />
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.<br />
<br />
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]<br />
<br />
=== Managing SSL certificates ===<br />
<br />
{{Merge|Transport Layer Security|There's a dedicated article.}}<br />
<br />
See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported. <br />
<br />
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. <br />
<br />
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:<br />
<br />
# 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), <br />
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and <br />
# Run ''update-ca-trust'' as root. <br />
<br />
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.<br />
<br />
== Authenticating packages ==<br />
<br />
[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.<br />
<br />
== Follow vulnerability alerts ==<br />
<br />
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]].<br />
<br />
{{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.}}<br />
<br />
== Physical security ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
[[#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.<br />
<br />
=== Locking down BIOS ===<br />
<br />
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.<br />
<br />
=== Bootloaders ===<br />
<br />
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.<br />
<br />
==== Syslinux ====<br />
<br />
Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.<br />
<br />
==== GRUB ====<br />
<br />
[[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.<br />
<br />
=== Boot partition on removable flash drive ===<br />
<br />
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. <br />
<br />
=== Automatic logout ===<br />
<br />
If you are using [[Bash]] or [[Zsh]], you can set {{ic|TMOUT}} for an automatic logout from shells after a timeout.<br />
<br />
For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):<br />
<br />
{{hc|/etc/profile.d/shell-timeout.sh|<nowiki><br />
TMOUT="$(( 60*10 ))";<br />
[ -z "$DISPLAY" ] && export TMOUT;<br />
case $( /usr/bin/tty ) in<br />
/dev/tty[0-9]*) export TMOUT;;<br />
esac<br />
</nowiki>}}<br />
<br />
If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:<br />
<br />
$ export TMOUT="$(( 60*10 ))";<br />
<br />
Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without {{ic|TMOUT}} support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.<br />
<br />
=== Protect against rogue USB devices ===<br />
<br />
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.<br />
<br />
== Rebuilding packages ==<br />
<br />
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.<br />
<br />
== See also ==<br />
<br />
* [https://security.archlinux.org/ Arch Linux Security Tracker]<br />
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]<br />
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]<br />
* [https://www.privacytools.io/ privacytools.io Privacy Resources]<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]<br />
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]<br />
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Kernel&diff=577818Kernel2019-07-23T20:29:04Z<p>Teples: /* Officially supported kernels */ AppArmor and SELinux status is the same in hardened as in vanilla</p>
<hr />
<div>[[Category:Kernel]]<br />
[[Category:Lists of software]]<br />
[[cs:Kernel Compilation]]<br />
[[es:Kernel]]<br />
[[fr:Noyaux Linux]]<br />
[[it:Kernels]]<br />
[[ja:カーネル]]<br />
[[ru:Kernel]]<br />
[[zh-hans:Kernels]]<br />
{{Related articles start}}<br />
{{Related|Kernel modules}}<br />
{{Related|Compile kernel module}}<br />
{{Related|Kernel Panics}}<br />
{{Related|sysctl}}<br />
{{Related articles end}}<br />
<br />
According to [[Wikipedia:Linux kernel|Wikipedia]]:<br />
:The '''Linux kernel''' is an open-source monolithic Unix-like computer [[Wikipedia:Kernel (operating system)|operating system kernel]].<br />
<br />
[[Arch Linux]] is based on the Linux kernel. There are various alternative Linux kernels available for Arch Linux in addition to the stable [[Wikipedia:Linux kernel|Linux kernel]]. This article lists some of the options available in the repositories with a brief description of each. There is also a description of patches that can be applied to the system's kernel. The article ends with an overview of custom kernel compilation with links to various methods.<br />
<br />
Kernel packages are [[install]]ed onto the file system under {{ic|/boot/}}. To be able to boot into kernels, the [[boot loader]] has to be configured appropriately.<br />
<br />
== Officially supported kernels ==<br />
<br />
* {{App|Stable|Vanilla Linux kernel and modules, with a few patches applied.|https://www.kernel.org/|{{Pkg|linux}}}}<br />
* {{App|Hardened|A security-focused Linux kernel applying a set of hardening patches to mitigate kernel and userspace exploits. It also enables more upstream kernel hardening features than {{Pkg|linux}}.|https://github.com/anthraxx/linux-hardened|{{Pkg|linux-hardened}}}}<br />
* {{App|Longterm|Long-term support (LTS) Linux kernel and modules.|https://www.kernel.org/|{{Pkg|linux-lts}}}}<br />
* {{App|ZEN Kernel|Result of a collaborative effort of kernel hackers to provide the best Linux kernel possible for everyday systems. Some more details can be found on https://liquorix.net (which provides kernel binaries based on ZEN for Debian).|https://github.com/zen-kernel/zen-kernel|{{Pkg|linux-zen}}}}<br />
<br />
== Compilation ==<br />
<br />
Arch Linux provides two methods to compile your own kernel.<br />
<br />
; [[/Arch Build System]]: Takes advantage of the high quality of existing {{Pkg|linux}} [[PKGBUILD]] and the benefits of [[Wikipedia:Package management system|package management]].<br />
; [[/Traditional compilation]]: Involves manually downloading a source tarball, and compiling in your home directory as a normal user.<br />
<br />
== kernel.org kernels ==<br />
<br />
* {{App|Git|Linux kernel and modules built using sources from Linus Torvalds' Git repository|https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git|{{AUR|linux-git}}}}<br />
* {{App|Mainline|Kernels where all new features are introduced, released every 2-3 months.|https://www.kernel.org/|{{AUR|linux-mainline}}}}<br />
* {{App|Next|Bleeding edge kernels with features pending to be merged into next mainline release.|https://www.kernel.org/doc/man-pages/linux-next.html|{{AUR|linux-next-git}}}}<br />
* {{App|Longterm 3.16|Long-term support (LTS) Linux 3.16 kernel and modules.|https://www.kernel.org/|{{AUR|linux-lts316}}}}<br />
* {{App|Longterm 4.4|Long-term support (LTS) Linux 4.4 kernel and modules.|https://www.kernel.org/|{{AUR|linux-lts44}}}}<br />
* {{App|Longterm 4.9|Long-term support (LTS) Linux 4.9 kernel and modules.|https://www.kernel.org/|{{AUR|linux-lts49}}}}<br />
* {{App|Longterm 4.14|Long-term support (LTS) Linux 4.14 kernel and modules.|https://www.kernel.org/|{{AUR|linux-lts414}}}}<br />
<br />
== Patches and patchsets ==<br />
<br />
There are lots of reasons to patch your kernel, the major ones are for performance or support for non-mainline features such as [[reiser4]] file system support. Other reasons might include fun and to see how it is done and what the improvements are.<br />
<br />
However, it is important to note that the best way to increase the speed of your system is to first tailor your kernel to your system, especially the architecture and processor type. For this reason using pre-packaged versions of custom kernels with generic architecture settings is not recommended or really worth it. A further benefit is that you can reduce the size of your kernel (and therefore build time) by not including support for things you do not have or use. For example, you might start with the stock kernel config when a new kernel version is released and remove support for things like bluetooth, video4linux, 1000Mbit ethernet, etc.; functionality you know you will not require for your specific machine. Although this page is not about customizing your kernel config, it is recommended as a first step--before moving on to using a patchset once you have grasped the fundamentals involved.<br />
<br />
The config files for the Arch kernel packages can be used as a starting point. They are in the Arch package source files, for example [https://projects.archlinux.org/svntogit/packages.git/tree/trunk?h=packages/linux] linked from {{Pkg|linux}}. The config file of your currently running kernel may also be available in your file system at {{ic|/proc/config.gz}} if the {{ic|CONFIG_IKCONFIG_PROC}} kernel option is enabled.<br />
<br />
If you have not actually patched or customized a kernel before it is not that hard and there are many PKGBUILDs on the forum for individual patchsets. However, you are advised to start from scratch with a bit of research on the benefits of each patchset, rather than just arbitrarily picking one. This way you will learn much more about what you are doing rather than just choosing a kernel at startup and then be left wondering what it actually does.<br />
<br />
{{Warning|Patchsets are developed by a variety of people. Some of these people are actually involved in the production of the linux kernel and others are hobbyists, which may reflect its level of reliability and stability.}}<br />
<br />
=== Major patchsets ===<br />
<br />
* {{App|[[Linux-ck]]|Contains patches by Con Kolivas designed to improve system responsiveness with specific emphasis on the desktop, but suitable to any workload.|http://ck.kolivas.org/|{{AUR|linux-ck}}}}<br />
* {{App|pf-kernel|Provides you with a handful of awesome features not merged into mainline. It is based on neither existing Linux fork nor patchset, although some unofficial ports may be used if required patches have not been released officially. The most prominent patches of linux-pf are PDS CPU scheduler and UKSM.|https://gitlab.com/post-factum/pf-kernel/wikis/README|Packages:}}<br />
:* [[Unofficial_user_repositories#post-factum_kernels|Repository]] by pf-kernel developer, [https://aur.archlinux.org/account/post-factum post-factum]<br />
:* [[Unofficial_user_repositories#home-thaodan|Repository]], {{AUR|linux-pf}}, {{AUR|linux-pf-preset-default}}, {{AUR|linux-pf-lts}} by pf-kernel fork developer, [https://aur.archlinux.org/account/Thaodan Thaodan]<br />
* {{App|[[Realtime kernel]]|Maintained by a small group of core developers, led by Ingo Molnar. This patch allows nearly all of the kernel to be preempted, with the exception of a few very small regions of code ("raw_spinlock critical regions"). This is done by replacing most kernel spinlocks with mutexes that support priority inheritance, as well as moving all interrupt and software interrupts to kernel threads.|https://wiki.linuxfoundation.org/realtime/start|{{AUR|linux-rt}}, {{AUR|linux-rt-lts}}}}<br />
<br />
=== Other patchsets ===<br />
<br />
Some of the listed packages may also be available as binary packages via [[Unofficial user repositories]].<br />
<br />
* {{App|[[AppArmor]]|The [[Wikipedia:Mandatory_access_control|Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM). While {{Pkg|linux}} supports apparmor this kernel has the required [[kernel parameters]] enabled by default. |https://gitlab.com/apparmor/apparmor/wikis/About|{{AUR|linux-apparmor}}}}<br />
* {{App|Aufs|The aufs-compatible linux kernel and modules, useful when using [[docker]].|http://aufs.sourceforge.net/|}}<br />
* {{App|BLD|Provides alternate CPU load distribution technique for task scheduler.|https://github.com/rmullick/bld-patches/wiki|{{AUR|linux-bld}}}}<br />
* {{App|Clear|Patches from Intel's Clear Linux project. Provides performance and security optimizations; [[WireGuard]] module. |https://github.com/clearlinux-pkgs/linux|{{AUR|linux-clear}}}}<br />
* {{App|Libre|The Linux Kernels without "binary blobs".|https://www.fsfla.org/ikiwiki/selibre/linux-libre/|{{AUR|linux-libre}}}}<br />
* {{App|Liquorix|Kernel replacement built using Debian-targeted configuration and the ZEN kernel sources. Designed for desktop, multimedia, and gaming workloads, it is often used as a Debian Linux performance replacement kernel. Damentz, the maintainer of the Liquorix patchset, is a developer for the ZEN patchset as well.|https://liquorix.net|{{AUR|linux-lqx}}}}<br />
* {{App|MultiPath TCP|The Linux Kernel and modules with Multipath TCP support.|https://multipath-tcp.org/|{{AUR|linux-mptcp}}}}<br />
* {{App|[[Reiser4]]|Successor filesystem for ReiserFS, developed from scratch by Namesys and Hans Reiser.|https://sourceforge.net/projects/reiser4/files/|}}<br />
* {{App|VFIO|The Linux kernel and a few patches written by Alex Williamson (acs override and i915) to enable the ability to do PCI Passthrough with KVM on some machines.|https://lwn.net/Articles/499240/|{{AUR|linux-vfio}}, {{AUR|linux-vfio-lts}}}}<br />
<br />
== See also ==<br />
<br />
* [http://www.kroah.com/lkn/ O'Reilly - Linux Kernel in a Nutshell] (free ebook)<br />
* [http://kroah.com/log/blog/2018/08/24/what-stable-kernel-should-i-use/ What stable kernel should I use?] by Greg Kroah-Hartman</div>Tepleshttps://wiki.archlinux.org/index.php?title=Security&diff=577817Security2019-07-23T20:14:04Z<p>Teples: /* Keep BPF JIT compiler disabled */ Clarify that this option can't be used for Arch kernels</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:File systems]]<br />
[[Category:Networking]]<br />
[[fa:امنیت]]<br />
[[ja:セキュリティ]]<br />
[[ru:Security]]<br />
[[zh-hans:Security]]<br />
{{Related articles start}}<br />
{{Related|Arch Security Team}}<br />
{{Related|General recommendations}}<br />
{{Related|PAM}}<br />
{{Related|Capabilities}}<br />
{{Related|List of Applications/Security}}<br />
{{Related articles end}}<br />
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.<br />
<br />
== Concepts ==<br />
<br />
* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.<br />
* 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.<br />
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!<br />
* 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.<br />
<br />
== Passwords ==<br />
<br />
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.<br />
<br />
=== Choosing secure passwords ===<br />
<br />
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]]. <br />
<br />
Insecure passwords include those containing:<br />
<br />
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)<br />
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})<br />
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})<br />
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.<br />
<br />
The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.<br />
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.<br />
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}}.<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
=== Maintaining passwords ===<br />
<br />
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}}).<br />
<br />
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.<br />
<br />
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.<br />
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).<br />
<br />
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.<br />
<br />
=== Password hashes ===<br />
<br />
{{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}}<br />
<br />
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]].<br />
<br />
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.<br />
<br />
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)].<br />
<br />
=== Enforcing strong passwords using pam_cracklib ===<br />
<br />
''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.<br />
<br />
{{Warning|The ''root'' account is not affected by this policy.}}<br />
{{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.}}<br />
<br />
If for example you want to enforce this policy:<br />
<br />
* prompt 2 times for password in case of an error<br />
* 10 characters minimum length (minlen option)<br />
* at least 6 characters should be different from old password when entering a new one (difok option)<br />
* at least 1 digit (dcredit option)<br />
* at least 1 uppercase (ucredit option)<br />
* at least 1 other character (ocredit option)<br />
* at least 1 lowercase (lcredit option)<br />
<br />
Edit the {{ic|/etc/pam.d/passwd}} file to read as:<br />
<br />
{{bc|1=<br />
#%PAM-1.0<br />
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1<br />
password required pam_unix.so use_authtok sha512 shadow<br />
}}<br />
<br />
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''.<br />
<br />
You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.<br />
<br />
== Memory ==<br />
<br />
=== Hardened Malloc ===<br />
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened-malloc-git}}) 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.<br />
<br />
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. For example, man fails to work properly unless its seccomp environment flag is disabled due to not having {{ic|getrandom}} in the standard whitelist, although this can be easily fixed by rebuilding it with the system call added. 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.<br />
<br />
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:<br />
<br />
{{bc|1=LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox}}<br />
<br />
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.<br />
<br />
== Storage ==<br />
<br />
=== Disk encryption ===<br />
<br />
[[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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== File systems ===<br />
<br />
The kernel now prevents security issues related to hardlinks and symlinks if the {{ic|fs.protected_hardlinks}} and {{ic|fs.protected_symlinks}} sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.<br />
<br />
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 {{ic|/var}} or {{ic|/tmp}} is enough to take down services. More flexible mechanisms for dealing with this concern exist (like [[Disk quota|quotas]]), and some [[file systems]] include related features themselves (Btrfs has quotas on subvolumes).<br />
<br />
==== Mount options ====<br />
<br />
Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).<br />
<br />
Relevant mount options are:<br />
<br />
* {{ic|nodev}}: Do not interpret character or block special devices on the file system.<br />
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.<br />
* {{ic|noexec}}: Do not allow direct execution of any binaries on the mounted file system.<br />
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].<br />
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.<br />
<br />
{{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}}.}}<br />
<br />
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.<br />
<br />
Potential file system mounts to consider:<br />
<br />
* {{ic|/var}}<br />
* {{ic|/home}}<br />
* {{ic|/dev/shm}}<br />
* {{ic|/tmp}}<br />
* {{ic|/boot}}<br />
<br />
=== File access permissions ===<br />
<br />
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.<br />
<br />
For example:<br />
<br />
# chmod 700 /boot /etc/{iptables,arptables}<br />
<br />
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]].<br />
<br />
== User setup ==<br />
<br />
After installation make a normal user for daily use. Do not use the root user for daily use.<br />
<br />
=== Enforce a delay after a failed login attempt ===<br />
<br />
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:<br />
<br />
{{hc|/etc/pam.d/system-login|<br />
2=auth optional pam_faildelay.so delay=4000000<br />
}}<br />
<br />
{{ic|4000000}} is the time in microseconds to delay.<br />
<br />
=== Lockout user after three failed login attempts ===<br />
<br />
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.<br />
<br />
To lockout a user for ten minutes {{ic|1=unlock_time=600}} after three failed login attempts {{ic|1=deny=3}}, add the parameters to the PAM configuration as follows:<br />
<br />
{{hc|/etc/pam.d/system-login|2=auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog<br />
}}<br />
<br />
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:<br />
<br />
# pam_tally2 --reset --user ''username''<br />
<br />
{{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.<br />
<br />
=== Limit amount of processes ===<br />
<br />
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. <br />
<br />
* soft nproc 100<br />
* hard nproc 200<br />
<br />
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.<br />
<br />
=== Run Xorg rootless ===<br />
<br />
[[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.<br />
<br />
See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.<br />
<br />
== Restricting root ==<br />
<br />
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.<br />
<br />
=== Use sudo instead of su ===<br />
<br />
{{Merge|sudo|There's a dedicated article.}}<br />
<br />
Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].<br />
<br />
* It keeps a log of which normal privilege user has run each privileged command.<br />
* The root user password need not be given out to each user who requires root access.<br />
* {{ic|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 [[Wikipedia:Principle of least privilege|principle of least privilege]].<br />
* 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:<br />
<br />
# visudo<br />
<br />
{{hc|/etc/sudoers|<br />
alice ALL &#61; NOPASSWD: /path/to/program<br />
}}<br />
<br />
Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:<br />
<br />
%users ALL=/sbin/mount.cifs,/sbin/umount.cifs<br />
<br />
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).<br />
<br />
{{Tip|<br />
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},<br />
<br />
{{hc|/etc/sudoers|<br />
2=Defaults editor=/usr/bin/rnano<br />
}}<br />
<br />
Exporting {{ic|1=# EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.<br />
}}<br />
<br />
==== Editing files using sudo ====<br />
<br />
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 --edit 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:<br />
<br />
$ export SUDO_EDITOR=vim<br />
<br />
Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.<br />
<br />
=== Restricting root login ===<br />
<br />
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}}.<br />
<br />
==== Allow only certain users ====<br />
<br />
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:<br />
<br />
{{bc|<nowiki><br />
# Uncomment the following line to require a user to be in the "wheel" group.<br />
auth required pam_wheel.so use_uid<br />
</nowiki>}}<br />
<br />
This means only users who are already able to run privileged commands may login as root.<br />
<br />
==== Denying SSH login ====<br />
<br />
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.<br />
<br />
==== Specify acceptable login combinations with access.conf ====<br />
<br />
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. <br />
<br />
+:root:LOCAL<br />
-:root:ALL<br />
<br />
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:<br />
<br />
+:archie:LOCAL<br />
+:(wheel):LOCAL<br />
+:(adm):LOCAL<br />
-:ALL:ALL<br />
<br />
Read more at {{man|5|access.conf}}<br />
<br />
== Mandatory access control ==<br />
<br />
[[Wikipedia:Mandatory Access Control|Mandatory access control]] (MAC) is a type of security policy that differs significantly from the [[Wikipedia:Discretionary Access Control|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.<br />
<br />
=== Pathname MAC ===<br />
<br />
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.<br />
<br />
* [[AppArmor]] is a [[Wikipedia:Canonical_(company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.<br />
* [[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.<br />
<br />
=== Labels MAC ===<br />
<br />
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.<br />
<br />
* [[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.<br />
<br />
=== Access Control Lists ===<br />
<br />
[[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.<br />
<br />
== Kernel hardening ==<br />
<br />
=== Kernel self-protection / exploit mitigation ===<br />
<br />
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.<br />
<br />
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.<br />
<br />
==== Userspace ASLR comparison ====<br />
<br />
The {{pkg|linux-hardened}} package provides an improved implementation of Address Space Layout Randomization for userspace processes. The {{pkg|paxtest}} command can be used to obtain an estimate of the provided entropy:<br />
<br />
===== 64-bit processes =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 32 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 26 quality bits (guessed)<br />
Heap randomization test (PIE) : 40 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 32 quality bits (guessed)<br />
Shared library randomization test : 32 quality bits (guessed)<br />
VDSO randomization test : 32 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 40 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 40 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 44 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 44 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 32 bits (guessed)<br />
Randomization under memory exhaustion @0 : 32 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 28 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 28 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 28 quality bits (guessed)<br />
Shared library randomization test : 28 quality bits (guessed)<br />
VDSO randomization test : 20 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 30 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 30 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 22 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 22 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 28 bits (guessed)<br />
Randomization under memory exhaustion @0 : 28 bits (guessed)<br />
}}<br />
<br />
===== 32-bit processes (on an x86_64 kernel) =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 16 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 22 quality bits (guessed)<br />
Heap randomization test (PIE) : 27 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 18 quality bits (guessed)<br />
Shared library randomization test : 16 quality bits (guessed)<br />
VDSO randomization test : 16 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 24 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 24 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 28 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 28 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 18 bits (guessed)<br />
Randomization under memory exhaustion @0 : 18 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 8 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 13 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 8 quality bits (guessed)<br />
Shared library randomization test : 8 quality bits (guessed)<br />
VDSO randomization test : 8 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 19 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 19 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 11 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 11 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: No randomization<br />
Randomization under memory exhaustion @0 : No randomization<br />
}}<br />
<br />
=== Restricting access to kernel logs ===<br />
<br />
{{Note|This is enabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
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).<br />
<br />
{{hc|/etc/sysctl.d/50-dmesg-restrict.conf|2=<br />
kernel.dmesg_restrict = 1<br />
}}<br />
<br />
=== Restricting access to kernel pointers in the proc filesystem ===<br />
<br />
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}<br />
<br />
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.<br />
<br />
Setting {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.<br />
<br />
{{hc|/etc/sysctl.d/50-kptr-restrict.conf|2=<br />
kernel.kptr_restrict = 1<br />
}}<br />
<br />
=== Keep BPF JIT compiler disabled ===<br />
<br />
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.<br />
<br />
{{Note|Arch Linux kernels are built with [https://cateee.net/lkddb/web-lkddb/BPF_JIT_ALWAYS_ON.html CONFIG_BPF_JIT_ALWAYS_ON] option which can't be overridden by the above. You may set {{ic|net.core.bpf_jit_harden}} flag to {{ic|2}} instead.}}<br />
<br />
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.<br />
<br />
=== ptrace scope ===<br />
<br />
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.<br />
<br />
==== Examples of broken functionality ====<br />
<br />
{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}<br />
<br />
* {{ic|gdb -p $PID}}<br />
* {{ic|strace -p $PID}}<br />
* {{ic|perf trace -p $PID}}<br />
* {{ic|reptyr $PID}}<br />
<br />
=== hidepid ===<br />
<br />
{{Warning|<br />
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).<br />
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.<br />
}}<br />
<br />
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]. <br />
<br />
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.<br />
<br />
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]].<br />
<br />
For example, to hide process information from other users except those in the {{ic|proc}} group:<br />
<br />
{{hc|/etc/fstab|2=<br />
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0<br />
}}<br />
<br />
For user sessions to work correctly, an exception needs to be added for ''systemd-logind'':<br />
<br />
{{hc|/etc/systemd/system/systemd-logind.service.d/hidepid.conf|2=<br />
[Service]<br />
SupplementaryGroups=proc<br />
}}<br />
<br />
=== Restricting module loading ===<br />
The default Arch kernel has {{ic|CONFIG_MODULE_SIG_ALL}} enabled which signs all kernel modules build as part of the {{Pkg|linux}} package. This allows the kernel to restrict modules to be only loaded when they are signed with a valid key, in practical terms this means that all out of tree modules compiled locally or provides by packages such as {{Pkg|wireguard-arch}} cannot be loaded. Restricting loading kernel modules can be done by adding {{ic|1=module.sig_enforce=1}} to the kernel command line, further documentation can be found [https://www.kernel.org/doc/html/v5.2-rc3/admin-guide/module-signing.html here].<br />
<br />
== Sandboxing applications ==<br />
<br />
See also [[Wikipedia:Sandbox (computer security)]].<br />
<br />
{{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 enabled by default starting with v5.1.8 unless the {{ic|kernel.unprivileged_userns_clone}} [[sysctl]] is set to {{ic|0}}. Since this greatly increases the attack surface for local privilege escalation, it is advised to disable this manually, or use the {{Pkg|linux-hardened}} kernel.}}<br />
<br />
=== Firejail ===<br />
<br />
[[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.<br />
<br />
=== bubblewrap ===<br />
<br />
[[bubblewrap]] is a 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].<br />
<br />
=== chroots ===<br />
<br />
Manual [[chroot]] jails can also be constructed.<br />
<br />
=== Linux containers ===<br />
<br />
[[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.<br />
<br />
=== Other virtualization options ===<br />
<br />
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.<br />
<br />
== Network and firewalls ==<br />
<br />
=== Firewalls ===<br />
<br />
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.<br />
<br />
* See [[iptables]] and [[nftables]] for general info.<br />
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.<br />
* See [[:Category:Firewalls]] for other ways of setting up netfilter.<br />
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.<br />
<br />
=== Kernel parameters ===<br />
<br />
Kernel parameters which affect networking can be set using [[Sysctl]]. For how to do this, see [[Sysctl#TCP/IP stack hardening]].<br />
<br />
=== SSH ===<br />
<br />
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.<br />
<br />
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).<br />
<br />
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]].<br />
<br />
=== DNS ===<br />
<br />
{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.<br />
<br />
=== Proxies ===<br />
<br />
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.<br />
<br />
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]<br />
<br />
=== Managing SSL certificates ===<br />
<br />
{{Merge|Transport Layer Security|There's a dedicated article.}}<br />
<br />
See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported. <br />
<br />
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. <br />
<br />
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:<br />
<br />
# 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), <br />
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and <br />
# Run ''update-ca-trust'' as root. <br />
<br />
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.<br />
<br />
== Authenticating packages ==<br />
<br />
[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.<br />
<br />
== Follow vulnerability alerts ==<br />
<br />
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]].<br />
<br />
{{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.}}<br />
<br />
== Physical security ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
[[#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.<br />
<br />
=== Locking down BIOS ===<br />
<br />
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.<br />
<br />
=== Bootloaders ===<br />
<br />
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.<br />
<br />
==== Syslinux ====<br />
<br />
Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.<br />
<br />
==== GRUB ====<br />
<br />
[[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.<br />
<br />
=== Boot partition on removable flash drive ===<br />
<br />
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. <br />
<br />
=== Automatic logout ===<br />
<br />
If you are using [[Bash]] or [[Zsh]], you can set {{ic|TMOUT}} for an automatic logout from shells after a timeout.<br />
<br />
For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):<br />
<br />
{{hc|/etc/profile.d/shell-timeout.sh|<nowiki><br />
TMOUT="$(( 60*10 ))";<br />
[ -z "$DISPLAY" ] && export TMOUT;<br />
case $( /usr/bin/tty ) in<br />
/dev/tty[0-9]*) export TMOUT;;<br />
esac<br />
</nowiki>}}<br />
<br />
If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:<br />
<br />
$ export TMOUT="$(( 60*10 ))";<br />
<br />
Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without {{ic|TMOUT}} support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.<br />
<br />
=== Protect against rogue USB devices ===<br />
<br />
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.<br />
<br />
== Rebuilding packages ==<br />
<br />
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.<br />
<br />
== See also ==<br />
<br />
* [https://security.archlinux.org/ Arch Linux Security Tracker]<br />
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]<br />
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]<br />
* [https://www.privacytools.io/ privacytools.io Privacy Resources]<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]<br />
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]<br />
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=LXD&diff=576706LXD2019-07-01T14:52:01Z<p>Teples: /* Accessing LXD as a unprivileged user */ add warning about lxd group membership similar to one in docker page</p>
<hr />
<div>[[Category:Virtualization]]<br />
[[es:LXD]]<br />
[[ja:LXD]]<br />
'''[https://linuxcontainers.org/lxd/ LXD]''' is a container "hypervisor" and a new user experience for [[Linux Containers]].<br />
<br />
{{Related articles start}}<br />
{{Related|Linux Containers}}<br />
{{Related articles end}}<br />
<br />
== Setup ==<br />
=== Required software ===<br />
Install [[LXC]] and the {{AUR|lxd}} package, then [[start]] {{ic|lxd.service}}.<br />
<br />
See [[Linux Containers#Enable support to run unprivileged containers (optional)]] if you want to run ''unprivileged'' containers. Otherwise see [[#Launching container without CONFIG_USER_NS]].<br />
<br />
=== Alternative installation method ===<br />
<br />
An alternative method of installation is via [[snapd]], by installing the {{AUR|snapd}} package and running:<br />
<br />
# snap install lxd<br />
<br />
=== Configure LXD ===<br />
LXD needs to configure a storage pool, and (if you want internet access) network configuration. To do so, run the following as root:<br />
# lxd init<br />
<br />
=== Accessing LXD as a unprivileged user ===<br />
<br />
By default the LXD daemon allows users in the {{ic|lxd}} group access, so add your user to the group:<br />
<br />
# usermod -a -G lxd <user><br />
<br />
{{Warning|Anyone added to the {{ic|lxd}} group is root equivalent. More information [https://github.com/lxc/lxd#security here] and [https://bugs.launchpad.net/ubuntu/+source/lxd/+bug/1829071 here].}}<br />
<br />
== Basic usage ==<br />
=== Create container ===<br />
<br />
LXD has two parts, the daemon (the lxd binary), and the client (the lxc binary). Now that the daemon is all configured and running, you can create a container:<br />
<br />
$ lxc launch ubuntu:16.04<br />
<br />
Alternatively, you can also use a remote LXD host as a source of images. One comes pre-configured in LXD, called "images" (images.linuxcontainers.org)<br />
<br />
$ lxc launch images:centos/7/amd64 centos<br />
<br />
To create an amd64 Arch container:<br />
<br />
$ lxc launch images:archlinux/current/amd64 arch<br />
<br />
== Advanced usage ==<br />
=== LXD Networking ===<br />
<br />
LXD uses LXC's networking capabilities. By default it connects containers to the {{ic|lxcbr0}} network device. Refer to the LXC documentation on [[Linux Containers#Host network configuration|network configuration]] to set up a bridge for your containers.<br />
<br />
If you want to use a different interface than {{ic|lxcbr0}} edit the default using the lxc command line tool:<br />
<br />
$ lxc profile edit default<br />
<br />
An editor will open with a config file that by default contains:<br />
<br />
name: default<br />
config: {}<br />
devices:<br />
eth0:<br />
name: eth0<br />
nictype: bridged<br />
parent: lxcbr0<br />
type: nic<br />
<br />
You can set the {{ic|parent}} parameter to whichever bridge you want LXD to attach the containers to by default.<br />
<br />
==== Example network configuration ====<br />
<br />
Thanks to @jpic, the LXD package now provides some example networking configuration in {{ic|/usr/share/lxd/}}. To use this configuration run the following commands:<br />
<br />
$ ln -s /usr/share/lxd/dnsmasq-lxd.conf /etc/dnsmasq-lxd.conf<br />
$ ln -s /usr/share/lxd/systemd/system/dnsmasq@lxd.service /etc/systemd/system/dnsmasq@lxd.service <br />
$ ln -s /usr/share/lxd/netctl/lxd /etc/netctl/lxd<br />
$ ln -s /usr/share/lxd/dbus-1/system.d/dnsmasq-lxd.conf /etc/dbus-1/system.d/dnsmasq-lxd.conf<br />
<br />
If you use [[NetworkManager]], also symlink the following file:<br />
<br />
$ ln -s /usr/share/lxd/NetworkManager/dnsmasq.d/lxd.conf /etc/NetworkManager/dnsmasq.d/lxd.conf<br />
<br />
Change {{ic|parent: lxcbr0}} to {{ic|parent: lxd}}:<br />
<br />
$ lxc profile edit default<br />
<br />
Finally, [[enable]] and [[start]] {{ic|dnsmasq@lxd.service}} and {{ic|netctl@lxd.service}}.<br />
<br />
If you encounter issue with the provided example configuration, or have suggestions to improve it, please leave a comment on the {{AUR|lxd}} page.<br />
<br />
=== Modify processes and files limit ===<br />
<br />
You may want to increase file descriptor limit or max user processes limit, since default file descriptor limit is 1024 on Arch Linux.<br />
<br />
[[Edit]] the {{ic|lxd.service}}:<br />
<br />
{{hc|# systemctl edit lxd.service|2=<br />
[Service]<br />
LimitNOFILE=infinity<br />
LimitNPROC=infinity<br />
TasksMax=infinity<br />
}}<br />
<br />
== Troubleshooting ==<br />
=== Check kernel config ===<br />
By default Arch Linux kernel is compiled correctly for Linux Containers and its frontend LXD. However, if you're using a custom kernel, or changed kernel options the kernel might be configured incorrectly. Verify that the running kernel is properly configured to run a container:<br />
$ lxc-checkconfig<br />
<br />
=== Launching container without CONFIG_USER_NS ===<br />
For launching images you must provide {{ic|1=security.privileged=true}} during image creation:<br />
<br />
$ lxc launch ubuntu:16.04 ubuntu -c security.privileged=true<br />
<br />
Or for already existed image you may edit config:<br />
<br />
{{hc|$ lxc config edit ubuntu|<br />
name: ubuntu<br />
profiles:<br />
- default<br />
config:<br />
...<br />
security.privileged: "true"<br />
...<br />
devices:<br />
root:<br />
path: /<br />
type: disk<br />
ephemeral: false<br />
}}<br />
<br />
Or to enable {{ic|1=security.privileged=true}} for new containers, edit the config for the default profile:<br />
<br />
$ lxc profile edit default<br />
<br />
=== No ipv4 on unprivileged Arch container ===<br />
<br />
{{Remove|As of systemd v239, this issue has been [https://github.com/lxc/lxd/issues/4071#issuecomment-405868612 fixed]. Updating {{pkg|systemd}} should fix this issue without the workaround below.}}<br />
<br />
This was tested and validated on LXD v.2.20. The container can not start the {{ic|1=systemd-networkd}} service so does not get a valid ipv4 address. A work-around was suggested by Stéphane Graber ([https://github.com/lxc/lxd/issues/4071 Github Issue]), execute on the host and restart the container:<br />
<br />
$ lxc profile set default security.syscalls.blacklist "keyctl errno 38"<br />
<br />
:stgraber: "The reason is that the networkd systemd unit somehow makes use of the kernel keyring, which doesn't work inside unprivileged containers right now. The line above makes that system call return not-implemented which is enough of a workaround to get things going again."<br />
<br />
=== Resource limits are not applied when viewed from inside a container ===<br />
<br />
The service lxcfs (found in the Community repository) needs to be installed and started :<br />
<br />
$ systemctl start lxcfs<br />
<br />
lxd will need to be restarted. Enable lxcfs for the service to be started at boot time. <br />
<br />
== Uninstall ==<br />
[[Stop]] and disable {{ic|lxd.service}} and {{ic|lxd.socket}}:<br />
<br />
Then uninstall the package via pacman:<br />
# pacman -R lxd<br />
<br />
If you uninstalled the package without disabling the service, you might have a lingering broken symlink at {{ic|/etc/systemd/system/multi-user.wants/lxd.service}}.<br />
<br />
If you want to remove all data:<br />
# rm -r /var/lib/lxd<br />
<br />
If you used any of the example networking configs, you should remove those as well.<br />
<br />
== See also ==<br />
<br />
* [https://lxd.readthedocs.io Official documentation]<br />
* [https://linuxcontainers.org/lxd/ The official LXD homepage]<br />
* [https://github.com/lxc/lxd The LXD GitHub page]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Linux_Containers&diff=576705Linux Containers2019-07-01T14:46:19Z<p>Teples: /* Enable support to run unprivileged containers (optional) */ update info about usrns support in arch kernels</p>
<hr />
<div>[[Category:Virtualization]]<br />
[[Category:Sandboxing]]<br />
[[ja:Linux Containers]]<br />
[[pt:Linux Containers]]<br />
{{Related articles start}}<br />
{{Related|ABS}}<br />
{{Related|Cgroups}}<br />
{{Related|Docker}}<br />
{{Related|LXD}}<br />
{{Related|OpenVPN}}<br />
{{Related|OpenVPN (client) in Linux containers}}<br />
{{Related|OpenVPN (server) in Linux containers}}<br />
{{Related|PeerGuardian Linux}}<br />
{{Related|systemd-nspawn}}<br />
{{Related articles end}}<br />
<br />
[https://linuxcontainers.org/ Linux Containers] (LXC) is an operating-system-level virtualization method for running multiple isolated Linux systems (containers) on a single control host (LXC host). It does not provide a virtual machine, but rather provides a virtual environment that has its own CPU, memory, block I/O, network, etc. space and the resource control mechanism. This is provided by [[Wikipedia:Linux namespaces|namespaces]] and [[cgroups]] features in Linux kernel on LXC host. It is similar to a chroot, but offers much more isolation.<br />
<br />
Alternatives for using containers are [[systemd-nspawn]], [[docker]] or {{Pkg|rkt}}.<br />
<br />
== Privileged containers or unprivileged containers ==<br />
LXCs can be setup to run in either ''privileged'' or ''unprivileged'' configurations.<br />
<br />
In general, running an ''unprivileged'' container is [https://www.stgraber.org/2014/01/17/lxc-1-0-unprivileged-containers considered safer] than running a ''privileged'' container since ''unprivileged'' containers have an increased degree of isolation by virtue of their design. Key to this is the mapping of the root UID in the container to a non-root UID on the host which makes it more difficult for a hack within the container to lead to consequences on host system. In other words, if an attacker manages to escape the container, he or she should find themselves with no rights on the host.<br />
<br />
The Arch {{pkg|linux}}, {{pkg|linux-lts}} and {{pkg|linux-zen}} packages currently provide out-of-the-box support for ''unprivileged'' containers. In {{pkg|linux-hardened}} ''unprivileged'' containers are only available for the system administrator with additional kernel configuration as user namespaces are disabled by default for normal users there. This article contains information for users to run either type of container, but additional setup may required to use ''unprivileged'' containers.<br />
<br />
=== An example to illustrate unprivileged containers ===<br />
<br />
To illustrate the power of UID mapping, consider the output below from a running, ''unprivileged'' container. Therein, we see the containerized processes owned by the containerized root user in the output of {{ic|ps}}:<br />
<br />
[root@unprivileged_container /]# ps -ef | head -n 5<br />
UID PID PPID C STIME TTY TIME CMD<br />
root 1 0 0 17:49 ? 00:00:00 /sbin/init<br />
root 14 1 0 17:49 ? 00:00:00 /usr/lib/systemd/systemd-journald<br />
dbus 25 1 0 17:49 ? 00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation<br />
systemd+ 26 1 0 17:49 ? 00:00:00 /usr/lib/systemd/systemd-networkd<br />
<br />
On the host however, those containerized root processes are running as the mapped user (ID>100000) on the host, not as the root user on the host:<br />
[root@host /]# lxc-info -Ssip --name sandbox<br />
State: RUNNING<br />
PID: 26204<br />
CPU use: 10.51 seconds<br />
BlkIO use: 244.00 KiB<br />
Memory use: 13.09 MiB<br />
KMem use: 7.21 MiB<br />
<br />
[root@host /]# ps -ef | grep 26204 | head -n 5<br />
UID PID PPID C STIME TTY TIME CMD<br />
100000 26204 26200 0 12:49 ? 00:00:00 /sbin/init<br />
100000 26256 26204 0 12:49 ? 00:00:00 /usr/lib/systemd/systemd-journald<br />
100081 26282 26204 0 12:49 ? 00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation<br />
100000 26284 26204 0 12:49 ? 00:00:00 /usr/lib/systemd/systemd-logind<br />
<br />
== Setup ==<br />
=== Required software ===<br />
Installing {{Pkg|lxc}} and {{Pkg|arch-install-scripts}} will allow the host system to run privileged lxcs.<br />
<br />
==== Enable support to run unprivileged containers (optional) ====<br />
Users wishing to run ''unprivileged'' containers on {{pkg|linux-hardened}} or their custom kernel need to complete several additional setup steps.<br />
<br />
Firstly, a kernel is required that has support for '''User Namespaces''' (a kernel with {{ic|CONFIG_USER_NS}}). All Arch Linux kernels have support for {{ic|CONFIG_USER_NS}}. However, due to more general security concerns, the {{pkg|linux-hardened}} kernel does ship with User Namespaces enabled only for the ''root'' user. You have two options to create ''unprivileged'' containers there:<br />
<br />
* Start your unprivileged containers only as ''root''.<br />
* Enable the ''sysctl'' setting {{ic|kernel.unprivileged_userns_clone}} to allow normal users to run unprivileged containers. This can be done for the current session with {{ic|1=sysctl kernel.unprivileged_userns_clone=1}} and can be made permanent with {{man|5|sysctl.d}}.<br />
<br />
Enable the [[control groups]] [[PAM]] module by modifying {{ic|/etc/pam.d/system-login}} to '''additionally''' contain the following line:<br />
session optional pam_cgfs.so -c freezer,memory,name=systemd,unified<br />
<br />
Secondly, modify {{ic|/etc/lxc/default.conf}} to contain the following lines:<br />
lxc.idmap = u 0 100000 65536<br />
lxc.idmap = g 0 100000 65536<br />
<br />
Finally, create both {{ic|/etc/subuid}} and {{ic|/etc/subgid}} to contain the mapping to the containerized uid/gid pairs for each user who shall be able to run the containers. The example below is simply for the root user (and systemd system unit):<br />
<br />
{{hc|/etc/subuid|<br />
root:100000:65536<br />
}}<br />
<br />
{{hc|/etc/subgid|<br />
root:100000:65536<br />
}}<br />
<br />
=== Host network configuration ===<br />
LXCs support different virtual network types and devices (see {{man|5|lxc.container.conf}}). A bridge device on the host is required for most types of virtual networking.<br />
<br />
LXC comes with its own NAT bridge (lxcbr0).<br />
{{Note|A NAT bridge is a standalone bridge with a private network that is not bridged to the host eth0 or a physical network. It exists as a private subnet in the host.}}<br />
{{Tip|This is quite useful when Wi-Fi is the only option. There have been various attempts of creating bridges on Wi-Fi, but without much success.}}<br />
<br />
To use LXC's NAT bridge you need to create its configuration file:<br />
<br />
{{hc|/etc/default/lxc-net|<br />
2=# Leave USE_LXC_BRIDGE as "true" if you want to use lxcbr0 for your<br />
# containers. Set to "false" if you'll use virbr0 or another existing<br />
# bridge, or mavlan to your host's NIC.<br />
USE_LXC_BRIDGE="true"<br />
<br />
# If you change the LXC_BRIDGE to something other than lxcbr0, then<br />
# you will also need to update your /etc/lxc/default.conf as well as the<br />
# configuration (/var/lib/lxc/<container>/config) for any containers<br />
# already created using the default config to reflect the new bridge<br />
# name.<br />
# If you have the dnsmasq daemon installed, you'll also have to update<br />
# /etc/dnsmasq.d/lxc and restart the system wide dnsmasq daemon.<br />
LXC_BRIDGE="lxcbr0"<br />
LXC_ADDR="10.0.3.1"<br />
LXC_NETMASK="255.255.255.0"<br />
LXC_NETWORK="10.0.3.0/24"<br />
LXC_DHCP_RANGE="10.0.3.2,10.0.3.254"<br />
LXC_DHCP_MAX="253"<br />
# Uncomment the next line if you'd like to use a conf-file for the lxcbr0<br />
# dnsmasq. For instance, you can use 'dhcp-host=mail1,10.0.3.100' to have<br />
# container 'mail1' always get ip address 10.0.3.100.<br />
#LXC_DHCP_CONFILE=/etc/lxc/dnsmasq.conf<br />
<br />
# Uncomment the next line if you want lxcbr0's dnsmasq to resolve the .lxc<br />
# domain. You can then add "server=/lxc/10.0.3.1' (or your actual $LXC_ADDR)<br />
# to your system dnsmasq configuration file (normally /etc/dnsmasq.conf,<br />
# or /etc/NetworkManager/dnsmasq.d/lxc.conf on systems that use NetworkManager).<br />
# Once these changes are made, restart the lxc-net and network-manager services.<br />
# 'container1.lxc' will then resolve on your host.<br />
#LXC_DOMAIN="lxc"<br />
}}<br />
<br />
{{Tip| Make sure the bridge's IP range does not interfere with your local network.}}<br />
<br />
Then we need to modify the LXC container template so our containers use our bridge:<br />
<br />
{{hc|/etc/lxc/default.conf|<br />
2=lxc.net.0.type = veth<br />
lxc.net.0.link = lxcbr0<br />
lxc.net.0.flags = up<br />
lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx<br />
}}<br />
<br />
You also need to [[install]] {{pkg|dnsmasq}} which is a dependency for lxcbr0.<br />
<br />
[[Enable]] and/or [[start]] {{ic|lxc-net.service}} to use the bridge:<br />
<br />
See [[Network bridge]] for more information.<br />
<br />
=== Alternate Network - Bridge on same network as host ===<br />
<br />
{{Remove|Duplicates [[Bridge with netctl]].}}<br />
<br />
If you would like the containers to be on the same network as your host machine and not utilize NAT and firewall forwarding rules you can do the following.<br />
<br />
You will setup a manual bridge using netctl that includes the hosts ethernet adapter. You set your ethernet to not have an ip address and instead assign an ip address to the bridge that it is binded to. <br />
<br />
In this scenario you will not be using the lxc-net service stop it if you enabled it.<br />
<br />
# systemctl stop lxc-net<br />
# systemctl disable lxc-net<br />
<br />
{{hc|/etc/netctl/ethernet|<br />
2=Description="Manual Ethernet setup for bridge"<br />
Interface=eno1 # your interface<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
{{hc|/etc/netctl/bridge|<br />
2=Description="Bridge Interface"<br />
Interface=br0<br />
Connection=bridge<br />
BindsToInterfaces=(eno1)<br />
IP=dhcp<br />
}}<br />
<br />
Make sure to first shutdown your current ethernet connections prior to bringing these up.<br />
<br />
# netctl stop-all<br />
# netctl start ethernet<br />
# netctl start bridge<br />
# netctl enable ethernet<br />
# netctl enable bridge<br />
<br />
Now change the default config for your containers.<br />
<br />
{{hc|/etc/lxc/default.conf|<br />
2=lxc.idmap = u 0 100000 65536<br />
lxc.idmap = g 0 100000 65536<br />
<br />
lxc.net.0.type = veth<br />
lxc.net.0.link = br0<br />
lxc.net.0.flags = up<br />
}}<br />
<br />
Now when you create a new container and start it, it should get an DHCP ip from the same network as the host.<br />
<br />
=== Container creation ===<br />
Containers are built using {{ic|lxc-create}}. With the release of lxc-3.0.0-1, upstream has deprecated locally stored templates.<br />
<br />
To build an Arch container, invoke like this:<br />
# lxc-create -n playtime -t download -- --dist archlinux --release current --arch amd64<br />
<br />
For other distros, invoke like this and select options from the supported distros displayed in the list:<br />
# lxc-create -n playtime -t download<br />
<br />
{{Tip|Users may optionally install {{Pkg|haveged}} and [[start]] {{ic|haveged.service}} to avoid a perceived hang during the setup process while waiting for system entropy to be seeded. Without it, the generation of private/GPG keys can add a lengthy wait to the process.}}<br />
<br />
{{Tip|Users of [[Btrfs]] can append {{ic|-B btrfs}} to create a Btrfs subvolume for storing containerized rootfs. This comes in handy if cloning containers with the help of {{ic|lxc-clone}} command. [[ZFS]] users may use {{ic|-B zfs}}, correspondingly.}}<br />
<br />
{{Note|Users wanting the legacy templates can find them in {{AUR|lxc-templates}} or alternatively, users can build their own templates with {{AUR|distrobuilder}}.}}<br />
<br />
=== Container configuration ===<br />
The examples below can be used with ''privileged'' and ''unprivileged'' containers alike. Note that for unprivileged containers, additional lines will be present by default which are not shown in the examples, including the {{ic|1=lxc.idmap = u 0 100000 65536}} and the {{ic|1=lxc.idmap = g 0 100000 65536}} values optionally defined in the [[#Enable support to run unprivileged containers (optional)]] section.<br />
<br />
==== Basic config with networking ====<br />
{{Note|With the release of lxc-1:2.1.0-1, many of the configuration options have changed. Existing containers need to be updated; users are directed to the table of these changes in the [https://discuss.linuxcontainers.org/t/lxc-2-1-has-been-released/487 v2.1 release notes].}}<br />
<br />
System resources to be virtualized/isolated when a process is using the container are defined in {{ic|/var/lib/lxc/CONTAINER_NAME/config}}. By default, the creation process will make a minimum setup without networking support. Below is an example config with networking:<br />
<br />
{{hc|/var/lib/lxc/playtime/config|<nowiki><br />
# Template used to create this container: /usr/share/lxc/templates/lxc-archlinux<br />
# Parameters passed to the template:<br />
# For additional config options, please look at lxc.container.conf(5)<br />
<br />
## default values<br />
lxc.rootfs.path = /var/lib/lxc/playtime/rootfs<br />
lxc.uts.name = playtime<br />
lxc.arch = x86_64<br />
lxc.include = /usr/share/lxc/config/common.conf<br />
<br />
## network<br />
lxc.net.0.type = veth<br />
lxc.net.0.link = br0<br />
lxc.net.0.flags = up<br />
lxc.net.0.name = eth0<br />
lxc.net.0.hwaddr = ee:ec:fa:e9:56:7d<br />
# uncomment the next two lines if static IP addresses are needed<br />
# leaving these commented will imply DHCP networking<br />
#<br />
#lxc.net.0.ipv4.address = 192.168.0.3/24<br />
#lxc.net.0.ipv4.gateway = 192.168.0.1<br />
</nowiki>}}<br />
<br />
{{Note|The lxc.network.hwaddr entry is optional and if skipped, a random MAC address will be created automatically. It can be advantageous to define a MAC address for the container to allow the DHCP server to always assign the same IP to the container's NIC (beyond the scope of this article but worth mentioning).}}<br />
<br />
==== Mounts within the container ====<br />
For ''privileged'' containers, one can select directories on the host to bind mount to the container. This can be advantageous for example if the same architecture is being containerize and one wants to share pacman packages between the host and container. Another example could be shared directories. The syntax is simple:<br />
<br />
lxc.mount.entry = /var/cache/pacman/pkg var/cache/pacman/pkg none bind 0 0<br />
<br />
{{Note|This will not work without filesystem permission modifications on the host if using ''unprivileged'' containers.}}<br />
==== Xorg program considerations (optional) ====<br />
In order to run programs on the host's display, some bind mounts need to be defined so that the containerized programs can access the host's resources. Add the following section to {{ic|/var/lib/lxc/playtime/config}}:<br />
## for xorg<br />
lxc.mount.entry = /dev/dri dev/dri none bind,optional,create=dir<br />
lxc.mount.entry = /dev/snd dev/snd none bind,optional,create=dir<br />
lxc.mount.entry = /tmp/.X11-unix tmp/.X11-unix none bind,optional,create=dir,ro<br />
lxc.mount.entry = /dev/video0 dev/video0 none bind,optional,create=file<br />
<br />
If you still get a permission denied error in your LXC guest, then you may need to call {{ic|xhost +}} in your host to allow the guest to connect to the host's display server. Take note of the security concerns of opening up your display server by doing this.<br />
In addition you might need to add the following line '''before''' the above bind mount lines.<br />
lxc.mount.entry = tmpfs tmp tmpfs defaults<br />
<br />
{{Note|This will not work if using ''unprivileged'' containers.}}<br />
<br />
==== OpenVPN considerations ====<br />
<br />
Users wishing to run [[OpenVPN]] within the container are requested to direct to either [[OpenVPN (client) in Linux containers]] and/or [[OpenVPN (server) in Linux containers]].<br />
<br />
== Managing containers ==<br />
=== Basic usage ===<br />
To list all installed LXC containers:<br />
# lxc-ls -f<br />
<br />
Systemd can be used to [[start]] and to [[stop]] LXCs via {{ic|lxc@CONTAINER_NAME.service}}. [[Enable]] {{ic|lxc@CONTAINER_NAME.service}} to have it start when the host system boots.<br />
<br />
{{Warning|See {{Bug|61078}} wherein this service unit is currently broken as shipped and will require a [[Systemd#Drop-in files]] modification to work properly.}}<br />
<br />
Users can also start/stop LXCs without systemd.<br />
Start a container:<br />
# lxc-start -n CONTAINER_NAME<br />
<br />
Stop a container:<br />
# lxc-stop -n CONTAINER_NAME<br />
<br />
To login into a container:<br />
# lxc-console -n CONTAINER_NAME<br />
<br />
If when login you get pts/0 and lxc/tty1 use:<br />
# lxc-console -n CONTAINER_NAME -t 0<br />
<br />
Once logged, treat the container like any other linux system, set the root password, create users, install packages, etc.<br />
<br />
To attach to a container:<br />
# lxc-attach -n CONTAINER_NAME --clear-env<br />
<br />
It works nearly the same as lxc-console, but you are automatically accessing root prompt inside the container, bypassing login. Without the {{ic| --clear-env}} flag, the host will pass its own environment variables into the container (including {{ic|$PATH}}, so some commands will not work when the containers are based on another distribution).<br />
<br />
=== Advanced usage ===<br />
<br />
==== LXC clones ====<br />
Users with a need to run multiple containers can simplify administrative overhead (user management, system updates, etc.) by using snapshots. The strategy is to setup and keep up-to-date a single base container, then, as needed, clone (snapshot) it. The power in this strategy is that the disk space and system overhead are truly minimized since the snapshots use an overlayfs mount to only write out to disk, only the differences in data. The base system is read-only but changes to it in the snapshots are allowed via the overlayfs.<br />
<br />
{{Expansion|The note needs a reference.}}<br />
<br />
{{Note|overlayfs for unprivileged containers is not supported in the current mainline Arch Linux kernel due to security considerations.}}<br />
<br />
For example, setup a container as outlined above. We will call it "base" for the purposes of this guide. Now create 2 snapshots of "base" which we will call "snap1" and "snap2" with these commands:<br />
# lxc-copy -n base -N snap1 -B overlayfs -s<br />
# lxc-copy -n base -N snap2 -B overlayfs -s<br />
<br />
{{Note|If a static IP was defined for the "base" lxc, that will need to manually changed in the config for "snap1" and for "snap2" before starting them. If the process is to be automated, a script using sed can do this automatically although this is beyond the scope of this wiki section.}}<br />
<br />
The snapshots can be started/stopped like any other container. Users can optionally destroy the snapshots and all new data therein with the following command. Note that the underlying "base" lxc is untouched:<br />
# lxc-destroy -n snap1 -f<br />
<br />
Systemd units and wrapper scripts to manage snapshots for [[pi-hole]] and [[OpenVPN]] are available to automate the process in [https://github.com/graysky2/lxc-snapshots lxc-snapshots].<br />
<br />
=== Converting a privileged container to an unprivileged container ===<br />
Once the system has been configured to use unprivileged containers (see, [[#Enable support to run unprivileged containers (optional)]]), {{AUR|nsexec-bzr}} contains a utility called {{ic|uidmapshift}} which is able to convert an existing ''privileged'' container to an ''unprivileged'' container to avoid a total rebuild of the image.<br />
<br />
{{Warning|<br />
* It is recommended to backup the existing image before using this utility!<br />
* This utility will not shift UIDs and GIDs in [[ACL]], you will need to shift them on your own.<br />
}}<br />
<br />
Invoke the utility to convert over like so:<br />
# uidmapshift -b /var/lib/lxc/foo 0 100000 65536<br />
<br />
Additional options are available simply by calling {{ic|uidmapshift}} without any arguments.<br />
<br />
== Running Xorg programs ==<br />
Either attach to or [[SSH]] into the target container and prefix the call to the program with the DISPLAY ID of the host's X session. For most simple setups, the display is always 0.<br />
<br />
An example of running Firefox from the container in the host's display:<br />
$ DISPLAY=:0 firefox<br />
<br />
Alternatively, to avoid directly attaching to or connecting to the container, the following can be used on the host to automate the process:<br />
# lxc-attach -n playtime --clear-env -- sudo -u YOURUSER env DISPLAY=:0 firefox<br />
<br />
== Troubleshooting ==<br />
<br />
=== Root login fails ===<br />
<br />
If you get the following error when you try to login using lxc-console:<br />
<br />
login: root<br />
Login incorrect<br />
<br />
And the container's {{ic|journalctl}} shows:<br />
<br />
pam_securetty(login:auth): access denied: tty 'pts/0' is not secure !<br />
<br />
Add {{ic|pts/0}} to the list of terminal names in {{ic|/etc/securetty}} on the '''container''' filesystem, see [http://unix.stackexchange.com/questions/41840/effect-of-entries-in-etc-securetty/41939#41939]. You can also opt to delete {{ic|/etc/securetty}} on the '''container''' to allow always root to login, see [https://github.com/systemd/systemd/issues/852].<br />
<br />
Alternatively, create a new user in lxc-attach and use it for logging in to the system, then switch to root.<br />
<br />
# lxc-attach -n playtime<br />
[root@playtime]# useradd -m -Gwheel newuser<br />
[root@playtime]# passwd newuser<br />
[root@playtime]# passwd root<br />
[root@playtime]# exit<br />
# lxc-console -n playtime<br />
[newuser@playtime]$ su<br />
<br />
=== No network-connection with veth in container config===<br />
<br />
If you cannot access your LAN or WAN with a networking interface configured as '''veth''' and setup through {{ic|/etc/lxc/''containername''/config}}.<br />
If the virtual interface gets the ip assigned and should be connected to the network correctly.<br />
ip addr show veth0 <br />
inet 192.168.1.111/24<br />
You may disable all the relevant static ip formulas and try setting the ip through the booted container-os like you would normaly do.<br />
<br />
Example {{ic|''container''/config}}<br />
<br />
...<br />
lxc.net.0.type = veth<br />
lxc.net.0.name = veth0<br />
lxc.net.0.flags = up<br />
lxc.net.0.link = {{ic|bridge}}<br />
...<br />
<br />
And then assign your IP through your preferred method '''inside''' the container, see also [[Network configuration#Network management]].<br />
<br />
=== Error: unknown command ===<br />
<br />
The error may happen when you type a basic command (''ls'', ''cat'', etc.) on an attached container that have different Linux distribution from the host system (e.g. Debian container in Arch Linux host system). When you attach, use the argument {{ic|--clear-env}}: <br />
<br />
# lxc-attach -n ''container_name'' --clear-env<br />
<br />
=== Error: Failed at step KEYRING spawning... ===<br />
<br />
Services in an unprivileged container may fail with the following message<br />
<br />
some.service: Failed to change ownership of session keyring: Permission denied<br />
some.service: Failed to set up kernel keyring: Permission denied<br />
some.service: Failed at step KEYRING spawning ....: Permission denied<br />
<br />
Create a file {{ic|/etc/lxc/unpriv.seccomp}} containing<br />
<br />
{{hc|/etc/lxc/unpriv.seccomp|<br />
2<br />
blacklist<br />
[all]<br />
keyctl errno 38}}<br />
<br />
Then add the following line to the container configuration '''after''' lxc.idmap<br />
<br />
lxc.seccomp.profile = /etc/lxc/unpriv.seccomp<br />
<br />
== See also ==<br />
<br />
* [https://www.stgraber.org/2013/12/20/lxc-1-0-blog-post-series/ LXC 1.0 Blog Post Series]<br />
* [https://stgraber.org/2016/03/11/lxd-2-0-blog-post-series-012/ LXD 2.0: Blog post series]<br />
* [http://www.ibm.com/developerworks/linux/library/l-lxc-containers/ LXC@developerWorks]<br />
* [http://l3net.wordpress.com/tag/lxc/ LXC articles on l3net]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Linux_Containers&diff=576704Linux Containers2019-07-01T14:42:11Z<p>Teples: /* Privileged containers or unprivileged containers */ update info about userns support in arch kernels</p>
<hr />
<div>[[Category:Virtualization]]<br />
[[Category:Sandboxing]]<br />
[[ja:Linux Containers]]<br />
[[pt:Linux Containers]]<br />
{{Related articles start}}<br />
{{Related|ABS}}<br />
{{Related|Cgroups}}<br />
{{Related|Docker}}<br />
{{Related|LXD}}<br />
{{Related|OpenVPN}}<br />
{{Related|OpenVPN (client) in Linux containers}}<br />
{{Related|OpenVPN (server) in Linux containers}}<br />
{{Related|PeerGuardian Linux}}<br />
{{Related|systemd-nspawn}}<br />
{{Related articles end}}<br />
<br />
[https://linuxcontainers.org/ Linux Containers] (LXC) is an operating-system-level virtualization method for running multiple isolated Linux systems (containers) on a single control host (LXC host). It does not provide a virtual machine, but rather provides a virtual environment that has its own CPU, memory, block I/O, network, etc. space and the resource control mechanism. This is provided by [[Wikipedia:Linux namespaces|namespaces]] and [[cgroups]] features in Linux kernel on LXC host. It is similar to a chroot, but offers much more isolation.<br />
<br />
Alternatives for using containers are [[systemd-nspawn]], [[docker]] or {{Pkg|rkt}}.<br />
<br />
== Privileged containers or unprivileged containers ==<br />
LXCs can be setup to run in either ''privileged'' or ''unprivileged'' configurations.<br />
<br />
In general, running an ''unprivileged'' container is [https://www.stgraber.org/2014/01/17/lxc-1-0-unprivileged-containers considered safer] than running a ''privileged'' container since ''unprivileged'' containers have an increased degree of isolation by virtue of their design. Key to this is the mapping of the root UID in the container to a non-root UID on the host which makes it more difficult for a hack within the container to lead to consequences on host system. In other words, if an attacker manages to escape the container, he or she should find themselves with no rights on the host.<br />
<br />
The Arch {{pkg|linux}}, {{pkg|linux-lts}} and {{pkg|linux-zen}} packages currently provide out-of-the-box support for ''unprivileged'' containers. In {{pkg|linux-hardened}} ''unprivileged'' containers are only available for the system administrator with additional kernel configuration as user namespaces are disabled by default for normal users there. This article contains information for users to run either type of container, but additional setup may required to use ''unprivileged'' containers.<br />
<br />
=== An example to illustrate unprivileged containers ===<br />
<br />
To illustrate the power of UID mapping, consider the output below from a running, ''unprivileged'' container. Therein, we see the containerized processes owned by the containerized root user in the output of {{ic|ps}}:<br />
<br />
[root@unprivileged_container /]# ps -ef | head -n 5<br />
UID PID PPID C STIME TTY TIME CMD<br />
root 1 0 0 17:49 ? 00:00:00 /sbin/init<br />
root 14 1 0 17:49 ? 00:00:00 /usr/lib/systemd/systemd-journald<br />
dbus 25 1 0 17:49 ? 00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation<br />
systemd+ 26 1 0 17:49 ? 00:00:00 /usr/lib/systemd/systemd-networkd<br />
<br />
On the host however, those containerized root processes are running as the mapped user (ID>100000) on the host, not as the root user on the host:<br />
[root@host /]# lxc-info -Ssip --name sandbox<br />
State: RUNNING<br />
PID: 26204<br />
CPU use: 10.51 seconds<br />
BlkIO use: 244.00 KiB<br />
Memory use: 13.09 MiB<br />
KMem use: 7.21 MiB<br />
<br />
[root@host /]# ps -ef | grep 26204 | head -n 5<br />
UID PID PPID C STIME TTY TIME CMD<br />
100000 26204 26200 0 12:49 ? 00:00:00 /sbin/init<br />
100000 26256 26204 0 12:49 ? 00:00:00 /usr/lib/systemd/systemd-journald<br />
100081 26282 26204 0 12:49 ? 00:00:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation<br />
100000 26284 26204 0 12:49 ? 00:00:00 /usr/lib/systemd/systemd-logind<br />
<br />
== Setup ==<br />
=== Required software ===<br />
Installing {{Pkg|lxc}} and {{Pkg|arch-install-scripts}} will allow the host system to run privileged lxcs.<br />
<br />
==== Enable support to run unprivileged containers (optional) ====<br />
Users wishing to run ''unprivileged'' containers need to complete several additional setup steps.<br />
<br />
Firstly, a kernel is required that has support for '''User Namespaces''' (a kernel with {{ic|CONFIG_USER_NS}}). All Arch Linux kernels have support for {{ic|CONFIG_USER_NS}}. However, due to more general security concerns, the default Arch kernel does ship with User Namespaces enabled only for the ''root'' user. You have two options to create ''unprivileged'' containers:<br />
<br />
* Start your unprivileged containers only as ''root''.<br />
* Enable the ''sysctl'' setting {{ic|kernel.unprivileged_userns_clone}} to allow normal users to run unprivileged containers. This can be done for the current session with {{ic|1=sysctl kernel.unprivileged_userns_clone=1}} and can be made permanent with {{man|5|sysctl.d}}.<br />
<br />
Enable the [[control groups]] [[PAM]] module by modifying {{ic|/etc/pam.d/system-login}} to '''additionally''' contain the following line:<br />
session optional pam_cgfs.so -c freezer,memory,name=systemd,unified<br />
<br />
Secondly, modify {{ic|/etc/lxc/default.conf}} to contain the following lines:<br />
lxc.idmap = u 0 100000 65536<br />
lxc.idmap = g 0 100000 65536<br />
<br />
Finally, create both {{ic|/etc/subuid}} and {{ic|/etc/subgid}} to contain the mapping to the containerized uid/gid pairs for each user who shall be able to run the containers. The example below is simply for the root user (and systemd system unit):<br />
<br />
{{hc|/etc/subuid|<br />
root:100000:65536<br />
}}<br />
<br />
{{hc|/etc/subgid|<br />
root:100000:65536<br />
}}<br />
<br />
=== Host network configuration ===<br />
LXCs support different virtual network types and devices (see {{man|5|lxc.container.conf}}). A bridge device on the host is required for most types of virtual networking.<br />
<br />
LXC comes with its own NAT bridge (lxcbr0).<br />
{{Note|A NAT bridge is a standalone bridge with a private network that is not bridged to the host eth0 or a physical network. It exists as a private subnet in the host.}}<br />
{{Tip|This is quite useful when Wi-Fi is the only option. There have been various attempts of creating bridges on Wi-Fi, but without much success.}}<br />
<br />
To use LXC's NAT bridge you need to create its configuration file:<br />
<br />
{{hc|/etc/default/lxc-net|<br />
2=# Leave USE_LXC_BRIDGE as "true" if you want to use lxcbr0 for your<br />
# containers. Set to "false" if you'll use virbr0 or another existing<br />
# bridge, or mavlan to your host's NIC.<br />
USE_LXC_BRIDGE="true"<br />
<br />
# If you change the LXC_BRIDGE to something other than lxcbr0, then<br />
# you will also need to update your /etc/lxc/default.conf as well as the<br />
# configuration (/var/lib/lxc/<container>/config) for any containers<br />
# already created using the default config to reflect the new bridge<br />
# name.<br />
# If you have the dnsmasq daemon installed, you'll also have to update<br />
# /etc/dnsmasq.d/lxc and restart the system wide dnsmasq daemon.<br />
LXC_BRIDGE="lxcbr0"<br />
LXC_ADDR="10.0.3.1"<br />
LXC_NETMASK="255.255.255.0"<br />
LXC_NETWORK="10.0.3.0/24"<br />
LXC_DHCP_RANGE="10.0.3.2,10.0.3.254"<br />
LXC_DHCP_MAX="253"<br />
# Uncomment the next line if you'd like to use a conf-file for the lxcbr0<br />
# dnsmasq. For instance, you can use 'dhcp-host=mail1,10.0.3.100' to have<br />
# container 'mail1' always get ip address 10.0.3.100.<br />
#LXC_DHCP_CONFILE=/etc/lxc/dnsmasq.conf<br />
<br />
# Uncomment the next line if you want lxcbr0's dnsmasq to resolve the .lxc<br />
# domain. You can then add "server=/lxc/10.0.3.1' (or your actual $LXC_ADDR)<br />
# to your system dnsmasq configuration file (normally /etc/dnsmasq.conf,<br />
# or /etc/NetworkManager/dnsmasq.d/lxc.conf on systems that use NetworkManager).<br />
# Once these changes are made, restart the lxc-net and network-manager services.<br />
# 'container1.lxc' will then resolve on your host.<br />
#LXC_DOMAIN="lxc"<br />
}}<br />
<br />
{{Tip| Make sure the bridge's IP range does not interfere with your local network.}}<br />
<br />
Then we need to modify the LXC container template so our containers use our bridge:<br />
<br />
{{hc|/etc/lxc/default.conf|<br />
2=lxc.net.0.type = veth<br />
lxc.net.0.link = lxcbr0<br />
lxc.net.0.flags = up<br />
lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx<br />
}}<br />
<br />
You also need to [[install]] {{pkg|dnsmasq}} which is a dependency for lxcbr0.<br />
<br />
[[Enable]] and/or [[start]] {{ic|lxc-net.service}} to use the bridge:<br />
<br />
See [[Network bridge]] for more information.<br />
<br />
=== Alternate Network - Bridge on same network as host ===<br />
<br />
{{Remove|Duplicates [[Bridge with netctl]].}}<br />
<br />
If you would like the containers to be on the same network as your host machine and not utilize NAT and firewall forwarding rules you can do the following.<br />
<br />
You will setup a manual bridge using netctl that includes the hosts ethernet adapter. You set your ethernet to not have an ip address and instead assign an ip address to the bridge that it is binded to. <br />
<br />
In this scenario you will not be using the lxc-net service stop it if you enabled it.<br />
<br />
# systemctl stop lxc-net<br />
# systemctl disable lxc-net<br />
<br />
{{hc|/etc/netctl/ethernet|<br />
2=Description="Manual Ethernet setup for bridge"<br />
Interface=eno1 # your interface<br />
Connection=ethernet<br />
IP=no<br />
}}<br />
<br />
{{hc|/etc/netctl/bridge|<br />
2=Description="Bridge Interface"<br />
Interface=br0<br />
Connection=bridge<br />
BindsToInterfaces=(eno1)<br />
IP=dhcp<br />
}}<br />
<br />
Make sure to first shutdown your current ethernet connections prior to bringing these up.<br />
<br />
# netctl stop-all<br />
# netctl start ethernet<br />
# netctl start bridge<br />
# netctl enable ethernet<br />
# netctl enable bridge<br />
<br />
Now change the default config for your containers.<br />
<br />
{{hc|/etc/lxc/default.conf|<br />
2=lxc.idmap = u 0 100000 65536<br />
lxc.idmap = g 0 100000 65536<br />
<br />
lxc.net.0.type = veth<br />
lxc.net.0.link = br0<br />
lxc.net.0.flags = up<br />
}}<br />
<br />
Now when you create a new container and start it, it should get an DHCP ip from the same network as the host.<br />
<br />
=== Container creation ===<br />
Containers are built using {{ic|lxc-create}}. With the release of lxc-3.0.0-1, upstream has deprecated locally stored templates.<br />
<br />
To build an Arch container, invoke like this:<br />
# lxc-create -n playtime -t download -- --dist archlinux --release current --arch amd64<br />
<br />
For other distros, invoke like this and select options from the supported distros displayed in the list:<br />
# lxc-create -n playtime -t download<br />
<br />
{{Tip|Users may optionally install {{Pkg|haveged}} and [[start]] {{ic|haveged.service}} to avoid a perceived hang during the setup process while waiting for system entropy to be seeded. Without it, the generation of private/GPG keys can add a lengthy wait to the process.}}<br />
<br />
{{Tip|Users of [[Btrfs]] can append {{ic|-B btrfs}} to create a Btrfs subvolume for storing containerized rootfs. This comes in handy if cloning containers with the help of {{ic|lxc-clone}} command. [[ZFS]] users may use {{ic|-B zfs}}, correspondingly.}}<br />
<br />
{{Note|Users wanting the legacy templates can find them in {{AUR|lxc-templates}} or alternatively, users can build their own templates with {{AUR|distrobuilder}}.}}<br />
<br />
=== Container configuration ===<br />
The examples below can be used with ''privileged'' and ''unprivileged'' containers alike. Note that for unprivileged containers, additional lines will be present by default which are not shown in the examples, including the {{ic|1=lxc.idmap = u 0 100000 65536}} and the {{ic|1=lxc.idmap = g 0 100000 65536}} values optionally defined in the [[#Enable support to run unprivileged containers (optional)]] section.<br />
<br />
==== Basic config with networking ====<br />
{{Note|With the release of lxc-1:2.1.0-1, many of the configuration options have changed. Existing containers need to be updated; users are directed to the table of these changes in the [https://discuss.linuxcontainers.org/t/lxc-2-1-has-been-released/487 v2.1 release notes].}}<br />
<br />
System resources to be virtualized/isolated when a process is using the container are defined in {{ic|/var/lib/lxc/CONTAINER_NAME/config}}. By default, the creation process will make a minimum setup without networking support. Below is an example config with networking:<br />
<br />
{{hc|/var/lib/lxc/playtime/config|<nowiki><br />
# Template used to create this container: /usr/share/lxc/templates/lxc-archlinux<br />
# Parameters passed to the template:<br />
# For additional config options, please look at lxc.container.conf(5)<br />
<br />
## default values<br />
lxc.rootfs.path = /var/lib/lxc/playtime/rootfs<br />
lxc.uts.name = playtime<br />
lxc.arch = x86_64<br />
lxc.include = /usr/share/lxc/config/common.conf<br />
<br />
## network<br />
lxc.net.0.type = veth<br />
lxc.net.0.link = br0<br />
lxc.net.0.flags = up<br />
lxc.net.0.name = eth0<br />
lxc.net.0.hwaddr = ee:ec:fa:e9:56:7d<br />
# uncomment the next two lines if static IP addresses are needed<br />
# leaving these commented will imply DHCP networking<br />
#<br />
#lxc.net.0.ipv4.address = 192.168.0.3/24<br />
#lxc.net.0.ipv4.gateway = 192.168.0.1<br />
</nowiki>}}<br />
<br />
{{Note|The lxc.network.hwaddr entry is optional and if skipped, a random MAC address will be created automatically. It can be advantageous to define a MAC address for the container to allow the DHCP server to always assign the same IP to the container's NIC (beyond the scope of this article but worth mentioning).}}<br />
<br />
==== Mounts within the container ====<br />
For ''privileged'' containers, one can select directories on the host to bind mount to the container. This can be advantageous for example if the same architecture is being containerize and one wants to share pacman packages between the host and container. Another example could be shared directories. The syntax is simple:<br />
<br />
lxc.mount.entry = /var/cache/pacman/pkg var/cache/pacman/pkg none bind 0 0<br />
<br />
{{Note|This will not work without filesystem permission modifications on the host if using ''unprivileged'' containers.}}<br />
==== Xorg program considerations (optional) ====<br />
In order to run programs on the host's display, some bind mounts need to be defined so that the containerized programs can access the host's resources. Add the following section to {{ic|/var/lib/lxc/playtime/config}}:<br />
## for xorg<br />
lxc.mount.entry = /dev/dri dev/dri none bind,optional,create=dir<br />
lxc.mount.entry = /dev/snd dev/snd none bind,optional,create=dir<br />
lxc.mount.entry = /tmp/.X11-unix tmp/.X11-unix none bind,optional,create=dir,ro<br />
lxc.mount.entry = /dev/video0 dev/video0 none bind,optional,create=file<br />
<br />
If you still get a permission denied error in your LXC guest, then you may need to call {{ic|xhost +}} in your host to allow the guest to connect to the host's display server. Take note of the security concerns of opening up your display server by doing this.<br />
In addition you might need to add the following line '''before''' the above bind mount lines.<br />
lxc.mount.entry = tmpfs tmp tmpfs defaults<br />
<br />
{{Note|This will not work if using ''unprivileged'' containers.}}<br />
<br />
==== OpenVPN considerations ====<br />
<br />
Users wishing to run [[OpenVPN]] within the container are requested to direct to either [[OpenVPN (client) in Linux containers]] and/or [[OpenVPN (server) in Linux containers]].<br />
<br />
== Managing containers ==<br />
=== Basic usage ===<br />
To list all installed LXC containers:<br />
# lxc-ls -f<br />
<br />
Systemd can be used to [[start]] and to [[stop]] LXCs via {{ic|lxc@CONTAINER_NAME.service}}. [[Enable]] {{ic|lxc@CONTAINER_NAME.service}} to have it start when the host system boots.<br />
<br />
{{Warning|See {{Bug|61078}} wherein this service unit is currently broken as shipped and will require a [[Systemd#Drop-in files]] modification to work properly.}}<br />
<br />
Users can also start/stop LXCs without systemd.<br />
Start a container:<br />
# lxc-start -n CONTAINER_NAME<br />
<br />
Stop a container:<br />
# lxc-stop -n CONTAINER_NAME<br />
<br />
To login into a container:<br />
# lxc-console -n CONTAINER_NAME<br />
<br />
If when login you get pts/0 and lxc/tty1 use:<br />
# lxc-console -n CONTAINER_NAME -t 0<br />
<br />
Once logged, treat the container like any other linux system, set the root password, create users, install packages, etc.<br />
<br />
To attach to a container:<br />
# lxc-attach -n CONTAINER_NAME --clear-env<br />
<br />
It works nearly the same as lxc-console, but you are automatically accessing root prompt inside the container, bypassing login. Without the {{ic| --clear-env}} flag, the host will pass its own environment variables into the container (including {{ic|$PATH}}, so some commands will not work when the containers are based on another distribution).<br />
<br />
=== Advanced usage ===<br />
<br />
==== LXC clones ====<br />
Users with a need to run multiple containers can simplify administrative overhead (user management, system updates, etc.) by using snapshots. The strategy is to setup and keep up-to-date a single base container, then, as needed, clone (snapshot) it. The power in this strategy is that the disk space and system overhead are truly minimized since the snapshots use an overlayfs mount to only write out to disk, only the differences in data. The base system is read-only but changes to it in the snapshots are allowed via the overlayfs.<br />
<br />
{{Expansion|The note needs a reference.}}<br />
<br />
{{Note|overlayfs for unprivileged containers is not supported in the current mainline Arch Linux kernel due to security considerations.}}<br />
<br />
For example, setup a container as outlined above. We will call it "base" for the purposes of this guide. Now create 2 snapshots of "base" which we will call "snap1" and "snap2" with these commands:<br />
# lxc-copy -n base -N snap1 -B overlayfs -s<br />
# lxc-copy -n base -N snap2 -B overlayfs -s<br />
<br />
{{Note|If a static IP was defined for the "base" lxc, that will need to manually changed in the config for "snap1" and for "snap2" before starting them. If the process is to be automated, a script using sed can do this automatically although this is beyond the scope of this wiki section.}}<br />
<br />
The snapshots can be started/stopped like any other container. Users can optionally destroy the snapshots and all new data therein with the following command. Note that the underlying "base" lxc is untouched:<br />
# lxc-destroy -n snap1 -f<br />
<br />
Systemd units and wrapper scripts to manage snapshots for [[pi-hole]] and [[OpenVPN]] are available to automate the process in [https://github.com/graysky2/lxc-snapshots lxc-snapshots].<br />
<br />
=== Converting a privileged container to an unprivileged container ===<br />
Once the system has been configured to use unprivileged containers (see, [[#Enable support to run unprivileged containers (optional)]]), {{AUR|nsexec-bzr}} contains a utility called {{ic|uidmapshift}} which is able to convert an existing ''privileged'' container to an ''unprivileged'' container to avoid a total rebuild of the image.<br />
<br />
{{Warning|<br />
* It is recommended to backup the existing image before using this utility!<br />
* This utility will not shift UIDs and GIDs in [[ACL]], you will need to shift them on your own.<br />
}}<br />
<br />
Invoke the utility to convert over like so:<br />
# uidmapshift -b /var/lib/lxc/foo 0 100000 65536<br />
<br />
Additional options are available simply by calling {{ic|uidmapshift}} without any arguments.<br />
<br />
== Running Xorg programs ==<br />
Either attach to or [[SSH]] into the target container and prefix the call to the program with the DISPLAY ID of the host's X session. For most simple setups, the display is always 0.<br />
<br />
An example of running Firefox from the container in the host's display:<br />
$ DISPLAY=:0 firefox<br />
<br />
Alternatively, to avoid directly attaching to or connecting to the container, the following can be used on the host to automate the process:<br />
# lxc-attach -n playtime --clear-env -- sudo -u YOURUSER env DISPLAY=:0 firefox<br />
<br />
== Troubleshooting ==<br />
<br />
=== Root login fails ===<br />
<br />
If you get the following error when you try to login using lxc-console:<br />
<br />
login: root<br />
Login incorrect<br />
<br />
And the container's {{ic|journalctl}} shows:<br />
<br />
pam_securetty(login:auth): access denied: tty 'pts/0' is not secure !<br />
<br />
Add {{ic|pts/0}} to the list of terminal names in {{ic|/etc/securetty}} on the '''container''' filesystem, see [http://unix.stackexchange.com/questions/41840/effect-of-entries-in-etc-securetty/41939#41939]. You can also opt to delete {{ic|/etc/securetty}} on the '''container''' to allow always root to login, see [https://github.com/systemd/systemd/issues/852].<br />
<br />
Alternatively, create a new user in lxc-attach and use it for logging in to the system, then switch to root.<br />
<br />
# lxc-attach -n playtime<br />
[root@playtime]# useradd -m -Gwheel newuser<br />
[root@playtime]# passwd newuser<br />
[root@playtime]# passwd root<br />
[root@playtime]# exit<br />
# lxc-console -n playtime<br />
[newuser@playtime]$ su<br />
<br />
=== No network-connection with veth in container config===<br />
<br />
If you cannot access your LAN or WAN with a networking interface configured as '''veth''' and setup through {{ic|/etc/lxc/''containername''/config}}.<br />
If the virtual interface gets the ip assigned and should be connected to the network correctly.<br />
ip addr show veth0 <br />
inet 192.168.1.111/24<br />
You may disable all the relevant static ip formulas and try setting the ip through the booted container-os like you would normaly do.<br />
<br />
Example {{ic|''container''/config}}<br />
<br />
...<br />
lxc.net.0.type = veth<br />
lxc.net.0.name = veth0<br />
lxc.net.0.flags = up<br />
lxc.net.0.link = {{ic|bridge}}<br />
...<br />
<br />
And then assign your IP through your preferred method '''inside''' the container, see also [[Network configuration#Network management]].<br />
<br />
=== Error: unknown command ===<br />
<br />
The error may happen when you type a basic command (''ls'', ''cat'', etc.) on an attached container that have different Linux distribution from the host system (e.g. Debian container in Arch Linux host system). When you attach, use the argument {{ic|--clear-env}}: <br />
<br />
# lxc-attach -n ''container_name'' --clear-env<br />
<br />
=== Error: Failed at step KEYRING spawning... ===<br />
<br />
Services in an unprivileged container may fail with the following message<br />
<br />
some.service: Failed to change ownership of session keyring: Permission denied<br />
some.service: Failed to set up kernel keyring: Permission denied<br />
some.service: Failed at step KEYRING spawning ....: Permission denied<br />
<br />
Create a file {{ic|/etc/lxc/unpriv.seccomp}} containing<br />
<br />
{{hc|/etc/lxc/unpriv.seccomp|<br />
2<br />
blacklist<br />
[all]<br />
keyctl errno 38}}<br />
<br />
Then add the following line to the container configuration '''after''' lxc.idmap<br />
<br />
lxc.seccomp.profile = /etc/lxc/unpriv.seccomp<br />
<br />
== See also ==<br />
<br />
* [https://www.stgraber.org/2013/12/20/lxc-1-0-blog-post-series/ LXC 1.0 Blog Post Series]<br />
* [https://stgraber.org/2016/03/11/lxd-2-0-blog-post-series-012/ LXD 2.0: Blog post series]<br />
* [http://www.ibm.com/developerworks/linux/library/l-lxc-containers/ LXC@developerWorks]<br />
* [http://l3net.wordpress.com/tag/lxc/ LXC articles on l3net]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Security&diff=574771Security2019-06-07T10:41:42Z<p>Teples: /* Restricting module loading */ Prettify formatting as done elsewhere</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:File systems]]<br />
[[Category:Networking]]<br />
[[fa:امنیت]]<br />
[[ja:セキュリティ]]<br />
[[ru:Security]]<br />
[[zh-hans:Security]]<br />
{{Related articles start}}<br />
{{Related|Arch Security Team}}<br />
{{Related|General recommendations}}<br />
{{Related|PAM}}<br />
{{Related|Capabilities}}<br />
{{Related|List of Applications/Security}}<br />
{{Related articles end}}<br />
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.<br />
<br />
== Concepts ==<br />
<br />
* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.<br />
* 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.<br />
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!<br />
* 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.<br />
<br />
== Passwords ==<br />
<br />
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.<br />
<br />
=== Choosing secure passwords ===<br />
<br />
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]]. <br />
<br />
Insecure passwords include those containing:<br />
<br />
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)<br />
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})<br />
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})<br />
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.<br />
<br />
The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.<br />
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.<br />
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}}.<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
=== Maintaining passwords ===<br />
<br />
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}}).<br />
<br />
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.<br />
<br />
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.<br />
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).<br />
<br />
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.<br />
<br />
=== Password hashes ===<br />
<br />
{{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}}<br />
<br />
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]].<br />
<br />
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.<br />
<br />
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)].<br />
<br />
=== Enforcing strong passwords using pam_cracklib ===<br />
<br />
''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.<br />
<br />
{{Warning|The ''root'' account is not affected by this policy.}}<br />
{{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.}}<br />
<br />
If for example you want to enforce this policy:<br />
<br />
* prompt 2 times for password in case of an error<br />
* 10 characters minimum length (minlen option)<br />
* at least 6 characters should be different from old password when entering a new one (difok option)<br />
* at least 1 digit (dcredit option)<br />
* at least 1 uppercase (ucredit option)<br />
* at least 1 other character (ocredit option)<br />
* at least 1 lowercase (lcredit option)<br />
<br />
Edit the {{ic|/etc/pam.d/passwd}} file to read as:<br />
<br />
{{bc|1=<br />
#%PAM-1.0<br />
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1<br />
password required pam_unix.so use_authtok sha512 shadow<br />
}}<br />
<br />
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''.<br />
<br />
You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.<br />
<br />
== Memory ==<br />
<br />
=== Hardened Malloc ===<br />
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened-malloc-git}}) 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.<br />
<br />
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 - Xorg fails to start, and man fails to work properly unless its seccomp environment flag is disabled. Between these, and because hardened_malloc is arguably less efficient and more complex than the standard malloc, it is suggested that one use it for more at risk applications, such as those that face the internet. It can also be used as a complement to sandboxed applications inside [[Firejail]]. <br />
<br />
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:<br />
<br />
{{bc|1=LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox}}<br />
<br />
Proper usage with Firejail can be found on its wiki page, and some configurable environment variables available for hardened_malloc can be found on the github repo.<br />
<br />
== Storage ==<br />
<br />
=== Disk encryption ===<br />
<br />
[[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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== File systems ===<br />
<br />
The kernel now prevents security issues related to hardlinks and symlinks if the {{ic|fs.protected_hardlinks}} and {{ic|fs.protected_symlinks}} sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.<br />
<br />
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 {{ic|/var}} or {{ic|/tmp}} is enough to take down services. More flexible mechanisms for dealing with this concern exist (like [[Disk quota|quotas]]), and some [[file systems]] include related features themselves (Btrfs has quotas on subvolumes).<br />
<br />
==== Mount options ====<br />
<br />
Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).<br />
<br />
Relevant mount options are:<br />
<br />
* {{ic|nodev}}: Do not interpret character or block special devices on the file system.<br />
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.<br />
* {{ic|noexec}}: Do not allow direct execution of any binaries on the mounted file system.<br />
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].<br />
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.<br />
<br />
{{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}}.}}<br />
<br />
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.<br />
<br />
Potential file system mounts to consider:<br />
<br />
* {{ic|/var}}<br />
* {{ic|/home}}<br />
* {{ic|/dev/shm}}<br />
* {{ic|/tmp}}<br />
* {{ic|/boot}}<br />
<br />
=== File access permissions ===<br />
<br />
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.<br />
<br />
For example:<br />
<br />
# chmod 700 /boot /etc/{iptables,arptables}<br />
<br />
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]].<br />
<br />
== User setup ==<br />
<br />
After installation make a normal user for daily use. Do not use the root user for daily use.<br />
<br />
=== Enforce a delay after a failed login attempt ===<br />
<br />
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:<br />
<br />
{{hc|/etc/pam.d/system-login|<br />
2=auth optional pam_faildelay.so delay=4000000<br />
}}<br />
<br />
{{ic|4000000}} is the time in microseconds to delay.<br />
<br />
=== Lockout user after three failed login attempts ===<br />
<br />
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.<br />
<br />
To lockout a user for ten minutes {{ic|1=unlock_time=600}} after three failed login attempts {{ic|1=deny=3}}, add the parameters to the PAM configuration as follows:<br />
<br />
{{hc|/etc/pam.d/system-login|2=auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog<br />
}}<br />
<br />
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:<br />
<br />
# pam_tally2 --reset --user ''username''<br />
<br />
{{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.<br />
<br />
=== Limit amount of processes ===<br />
<br />
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. <br />
<br />
* soft nproc 100<br />
* hard nproc 200<br />
<br />
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.<br />
<br />
=== Run Xorg rootless ===<br />
<br />
[[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.<br />
<br />
See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.<br />
<br />
== Restricting root ==<br />
<br />
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.<br />
<br />
=== Use sudo instead of su ===<br />
<br />
{{Merge|sudo|There's a dedicated article.}}<br />
<br />
Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].<br />
<br />
* It keeps a log of which normal privilege user has run each privileged command.<br />
* The root user password need not be given out to each user who requires root access.<br />
* {{ic|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 [[Wikipedia:Principle of least privilege|principle of least privilege]].<br />
* 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:<br />
<br />
# visudo<br />
<br />
{{hc|/etc/sudoers|<br />
alice ALL &#61; NOPASSWD: /path/to/program<br />
}}<br />
<br />
Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:<br />
<br />
%users ALL=/sbin/mount.cifs,/sbin/umount.cifs<br />
<br />
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).<br />
<br />
{{Tip|<br />
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},<br />
<br />
{{hc|/etc/sudoers|<br />
2=Defaults editor=/usr/bin/rnano<br />
}}<br />
<br />
Exporting {{ic|1=# EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.<br />
}}<br />
<br />
==== Editing files using sudo ====<br />
<br />
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 --edit 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:<br />
<br />
$ export SUDO_EDITOR=vim<br />
<br />
Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.<br />
<br />
=== Restricting root login ===<br />
<br />
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}}.<br />
<br />
==== Allow only certain users ====<br />
<br />
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:<br />
<br />
{{bc|<nowiki><br />
# Uncomment the following line to require a user to be in the "wheel" group.<br />
auth required pam_wheel.so use_uid<br />
</nowiki>}}<br />
<br />
This means only users who are already able to run privileged commands may login as root.<br />
<br />
==== Denying SSH login ====<br />
<br />
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.<br />
<br />
== Mandatory access control ==<br />
<br />
[[Wikipedia:Mandatory Access Control|Mandatory access control]] (MAC) is a type of security policy that differs significantly from the [[Wikipedia:Discretionary Access Control|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.<br />
<br />
=== Pathname MAC ===<br />
<br />
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.<br />
<br />
* [[AppArmor]] is a [[Wikipedia:Canonical_(company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.<br />
* [[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.<br />
<br />
=== Labels MAC ===<br />
<br />
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.<br />
<br />
* [[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.<br />
<br />
=== Access Control Lists ===<br />
<br />
[[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.<br />
<br />
== Kernel hardening ==<br />
<br />
=== Kernel self-protection / exploit mitigation ===<br />
<br />
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.<br />
<br />
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.<br />
<br />
==== Userspace ASLR comparison ====<br />
<br />
The {{pkg|linux-hardened}} package provides an improved implementation of Address Space Layout Randomization for userspace processes. The {{pkg|paxtest}} command can be used to obtain an estimate of the provided entropy:<br />
<br />
===== 64-bit processes =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 32 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 26 quality bits (guessed)<br />
Heap randomization test (PIE) : 40 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 32 quality bits (guessed)<br />
Shared library randomization test : 32 quality bits (guessed)<br />
VDSO randomization test : 32 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 40 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 40 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 44 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 44 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 32 bits (guessed)<br />
Randomization under memory exhaustion @0 : 32 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 28 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 28 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 28 quality bits (guessed)<br />
Shared library randomization test : 28 quality bits (guessed)<br />
VDSO randomization test : 20 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 30 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 30 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 22 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 22 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 28 bits (guessed)<br />
Randomization under memory exhaustion @0 : 28 bits (guessed)<br />
}}<br />
<br />
===== 32-bit processes (on an x86_64 kernel) =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 16 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 22 quality bits (guessed)<br />
Heap randomization test (PIE) : 27 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 18 quality bits (guessed)<br />
Shared library randomization test : 16 quality bits (guessed)<br />
VDSO randomization test : 16 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 24 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 24 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 28 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 28 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 18 bits (guessed)<br />
Randomization under memory exhaustion @0 : 18 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 8 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 13 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 8 quality bits (guessed)<br />
Shared library randomization test : 8 quality bits (guessed)<br />
VDSO randomization test : 8 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 19 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 19 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 11 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 11 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: No randomization<br />
Randomization under memory exhaustion @0 : No randomization<br />
}}<br />
<br />
=== Restricting access to kernel logs ===<br />
<br />
{{Note|This is enabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
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).<br />
<br />
{{hc|/etc/sysctl.d/50-dmesg-restrict.conf|2=<br />
kernel.dmesg_restrict = 1<br />
}}<br />
<br />
=== Restricting access to kernel pointers in the proc filesystem ===<br />
<br />
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}<br />
<br />
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.<br />
<br />
Setting {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.<br />
<br />
{{hc|/etc/sysctl.d/50-kptr-restrict.conf|2=<br />
kernel.kptr_restrict = 1<br />
}}<br />
<br />
=== Keep BPF JIT compiler disabled ===<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== ptrace scope ===<br />
<br />
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.<br />
<br />
==== Examples of broken functionality ====<br />
<br />
{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}<br />
<br />
* {{ic|gdb -p $PID}}<br />
* {{ic|strace -p $PID}}<br />
* {{ic|perf trace -p $PID}}<br />
* {{ic|reptyr $PID}}<br />
<br />
=== hidepid ===<br />
<br />
{{Warning|<br />
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).<br />
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.<br />
}}<br />
<br />
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]. <br />
<br />
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.<br />
<br />
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]].<br />
<br />
For example, to hide process information from other users except those in the {{ic|proc}} group:<br />
<br />
{{hc|/etc/fstab|2=<br />
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0<br />
}}<br />
<br />
For user sessions to work correctly, an exception needs to be added for ''systemd-logind'':<br />
<br />
{{hc|/etc/systemd/system/systemd-logind.service.d/hidepid.conf|2=<br />
[Service]<br />
SupplementaryGroups=proc<br />
}}<br />
<br />
=== Restricting module loading ===<br />
The default Arch kernel has {{ic|CONFIG_MODULE_SIG_ALL}} enabled which signs all kernel modules build as part of the {{Pkg|Linux}} package. This allows the kernel to restrict modules to be only loaded when they are signed with a valid key, in practical terms this means that all out of tree modules compiled locally or provides by packages such as {{Pkg|wireguard-arch}} cannot be loaded. Restricting loading kernel modules can be done by adding {{ic|1=module.sig_enforce=1}} to the kernel command line, further documentation can be found [https://www.kernel.org/doc/html/v5.2-rc3/admin-guide/module-signing.html here].<br />
<br />
== Sandboxing applications ==<br />
<br />
See also [[Wikipedia:Sandbox (computer security)]].<br />
<br />
{{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.}}<br />
<br />
=== Firejail ===<br />
<br />
[[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.<br />
<br />
=== bubblewrap ===<br />
<br />
[[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].<br />
<br />
=== chroots ===<br />
<br />
Manual [[chroot]] jails can also be constructed.<br />
<br />
=== Linux containers ===<br />
<br />
[[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.<br />
<br />
=== Other virtualization options ===<br />
<br />
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.<br />
<br />
== Network and firewalls ==<br />
<br />
=== Firewalls ===<br />
<br />
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.<br />
<br />
* See [[iptables]] and [[nftables]] for general info.<br />
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.<br />
* See [[:Category:Firewalls]] for other ways of setting up netfilter.<br />
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.<br />
<br />
=== Kernel parameters ===<br />
<br />
Kernel parameters which affect networking can be set using [[Sysctl]]. For how to do this, see [[Sysctl#TCP/IP stack hardening]].<br />
<br />
=== SSH ===<br />
<br />
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.<br />
<br />
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).<br />
<br />
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]].<br />
<br />
=== DNS ===<br />
<br />
{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.<br />
<br />
=== Proxies ===<br />
<br />
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.<br />
<br />
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]<br />
<br />
=== Managing SSL certificates ===<br />
<br />
{{Merge|Transport Layer Security|There's a dedicated article.}}<br />
<br />
See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported. <br />
<br />
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. <br />
<br />
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:<br />
<br />
# 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), <br />
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and <br />
# Run ''update-ca-trust'' as root. <br />
<br />
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.<br />
<br />
== Authenticating packages ==<br />
<br />
[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.<br />
<br />
== Follow vulnerability alerts ==<br />
<br />
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]].<br />
<br />
{{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.}}<br />
<br />
== Physical security ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
[[#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.<br />
<br />
=== Locking down BIOS ===<br />
<br />
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.<br />
<br />
=== Bootloaders ===<br />
<br />
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.<br />
<br />
==== Syslinux ====<br />
<br />
Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.<br />
<br />
==== GRUB ====<br />
<br />
[[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.<br />
<br />
=== Boot partition on removable flash drive ===<br />
<br />
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. <br />
<br />
=== Automatic logout ===<br />
<br />
If you are using [[Bash]] or [[Zsh]], you can set {{ic|TMOUT}} for an automatic logout from shells after a timeout.<br />
<br />
For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):<br />
<br />
{{hc|/etc/profile.d/shell-timeout.sh|<nowiki><br />
TMOUT="$(( 60*10 ))";<br />
[ -z "$DISPLAY" ] && export TMOUT;<br />
case $( /usr/bin/tty ) in<br />
/dev/tty[0-9]*) export TMOUT;;<br />
esac<br />
</nowiki>}}<br />
<br />
If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:<br />
<br />
$ export TMOUT="$(( 60*10 ))";<br />
<br />
Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without {{ic|TMOUT}} support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.<br />
<br />
=== Protect against rogue USB devices ===<br />
<br />
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.<br />
<br />
== Rebuilding packages ==<br />
<br />
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.<br />
<br />
== See also ==<br />
<br />
* [https://security.archlinux.org/ Arch Linux Security Tracker]<br />
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]<br />
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]<br />
* [https://www.privacytools.io/ privacytools.io Privacy Resources]<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]<br />
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]<br />
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Security&diff=574770Security2019-06-07T10:38:47Z<p>Teples: /* Restricting module loading */ Fix formatting. This is no github :)</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:File systems]]<br />
[[Category:Networking]]<br />
[[fa:امنیت]]<br />
[[ja:セキュリティ]]<br />
[[ru:Security]]<br />
[[zh-hans:Security]]<br />
{{Related articles start}}<br />
{{Related|Arch Security Team}}<br />
{{Related|General recommendations}}<br />
{{Related|PAM}}<br />
{{Related|Capabilities}}<br />
{{Related|List of Applications/Security}}<br />
{{Related articles end}}<br />
This article contains recommendations and best practices for [[Wikipedia:Hardening (computing)|hardening]] an Arch Linux system.<br />
<br />
== Concepts ==<br />
<br />
* It ''is'' possible to tighten the security so much as to make your system unusable. The trick is to secure it without overdoing it.<br />
* 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.<br />
* Be a little paranoid. It helps. And be suspicious. If anything sounds too good to be true, it probably is!<br />
* 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.<br />
<br />
== Passwords ==<br />
<br />
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.<br />
<br />
=== Choosing secure passwords ===<br />
<br />
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]]. <br />
<br />
Insecure passwords include those containing:<br />
<br />
* Personally identifiable information (e.g., your dog's name, date of birth, area code, favorite video game)<br />
* Simple character substitutions on words (e.g., {{ic|k1araj0hns0n}})<br />
* Root "words" or common strings followed or preceded by added numbers, symbols, or characters (e.g., {{ic|DG091101%}})<br />
* Common phrases or short phrases of grammatically related words (e.g. {{ic|all of the lights}}), and even with character substitution.<br />
<br />
The right choice for a password is something long (8-20 characters, depending on importance) and seemingly completely random.<br />
A good technique for building secure, seemingly random passwords is to base them on characters from every word in a sentence.<br />
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}}.<br />
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.<br />
<br />
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.<br />
<br />
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).<br />
<br />
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.<br />
<br />
=== Maintaining passwords ===<br />
<br />
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}}).<br />
<br />
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.<br />
<br />
Another aspect of the strength of the passphrase is that it must not be easily recoverable from other places.<br />
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).<br />
<br />
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.<br />
<br />
=== Password hashes ===<br />
<br />
{{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}}<br />
<br />
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]].<br />
<br />
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.<br />
<br />
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)].<br />
<br />
=== Enforcing strong passwords using pam_cracklib ===<br />
<br />
''pam_cracklib'' provides protection against [[Wikipedia:Dictionary attack|Dictionary attacks]] and helps configure a password policy that can be enforced throughout the system.<br />
<br />
{{Warning|The ''root'' account is not affected by this policy.}}<br />
{{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.}}<br />
<br />
If for example you want to enforce this policy:<br />
<br />
* prompt 2 times for password in case of an error<br />
* 10 characters minimum length (minlen option)<br />
* at least 6 characters should be different from old password when entering a new one (difok option)<br />
* at least 1 digit (dcredit option)<br />
* at least 1 uppercase (ucredit option)<br />
* at least 1 other character (ocredit option)<br />
* at least 1 lowercase (lcredit option)<br />
<br />
Edit the {{ic|/etc/pam.d/passwd}} file to read as:<br />
<br />
{{bc|1=<br />
#%PAM-1.0<br />
password required pam_cracklib.so retry=2 minlen=10 difok=6 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1<br />
password required pam_unix.so use_authtok sha512 shadow<br />
}}<br />
<br />
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''.<br />
<br />
You can refer to the {{man|8|pam_cracklib}} and {{man|8|pam_unix}} man pages for more information.<br />
<br />
== Memory ==<br />
<br />
=== Hardened Malloc ===<br />
[https://github.com/GrapheneOS/hardened_malloc hardened_malloc] ({{AUR|hardened-malloc-git}}) 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.<br />
<br />
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 - Xorg fails to start, and man fails to work properly unless its seccomp environment flag is disabled. Between these, and because hardened_malloc is arguably less efficient and more complex than the standard malloc, it is suggested that one use it for more at risk applications, such as those that face the internet. It can also be used as a complement to sandboxed applications inside [[Firejail]]. <br />
<br />
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:<br />
<br />
{{bc|1=LD_PRELOAD="/usr/lib/libhardened_malloc.so" /usr/bin/firefox}}<br />
<br />
Proper usage with Firejail can be found on its wiki page, and some configurable environment variables available for hardened_malloc can be found on the github repo.<br />
<br />
== Storage ==<br />
<br />
=== Disk encryption ===<br />
<br />
[[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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== File systems ===<br />
<br />
The kernel now prevents security issues related to hardlinks and symlinks if the {{ic|fs.protected_hardlinks}} and {{ic|fs.protected_symlinks}} sysctl switches are enabled, so there is no longer a major security benefit from separating out world-writable directories.<br />
<br />
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 {{ic|/var}} or {{ic|/tmp}} is enough to take down services. More flexible mechanisms for dealing with this concern exist (like [[Disk quota|quotas]]), and some [[file systems]] include related features themselves (Btrfs has quotas on subvolumes).<br />
<br />
==== Mount options ====<br />
<br />
Following the principle of least privilege, file systems should be mounted with the most restrictive mount options possible (without losing functionality).<br />
<br />
Relevant mount options are:<br />
<br />
* {{ic|nodev}}: Do not interpret character or block special devices on the file system.<br />
* {{ic|nosuid}}: Do not allow set-user-identifier or set-group-identifier bits to take effect.<br />
* {{ic|noexec}}: Do not allow direct execution of any binaries on the mounted file system.<br />
** Setting {{ic|noexec}} on {{ic|/home}} disallows executable scripts and breaks [[Wine]]* and [[Steam]].<br />
** Some packages (building {{Pkg|nvidia-dkms}} for example) may require {{ic|exec}} on {{ic|/var}}.<br />
<br />
{{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}}.}}<br />
<br />
File systems used for data should always be mounted with {{ic|nodev}}, {{ic|nosuid}} and {{ic|noexec}}.<br />
<br />
Potential file system mounts to consider:<br />
<br />
* {{ic|/var}}<br />
* {{ic|/home}}<br />
* {{ic|/dev/shm}}<br />
* {{ic|/tmp}}<br />
* {{ic|/boot}}<br />
<br />
=== File access permissions ===<br />
<br />
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.<br />
<br />
For example:<br />
<br />
# chmod 700 /boot /etc/{iptables,arptables}<br />
<br />
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]].<br />
<br />
== User setup ==<br />
<br />
After installation make a normal user for daily use. Do not use the root user for daily use.<br />
<br />
=== Enforce a delay after a failed login attempt ===<br />
<br />
Add the following line to {{ic|/etc/pam.d/system-login}} to add a delay of at least 4 seconds between failed login attempts:<br />
<br />
{{hc|/etc/pam.d/system-login|<br />
2=auth optional pam_faildelay.so delay=4000000<br />
}}<br />
<br />
{{ic|4000000}} is the time in microseconds to delay.<br />
<br />
=== Lockout user after three failed login attempts ===<br />
<br />
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.<br />
<br />
To lockout a user for ten minutes {{ic|1=unlock_time=600}} after three failed login attempts {{ic|1=deny=3}}, add the parameters to the PAM configuration as follows:<br />
<br />
{{hc|/etc/pam.d/system-login|2=auth required pam_tally2.so deny=3 unlock_time=600 onerr=succeed file=/var/log/tallylog<br />
}}<br />
<br />
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:<br />
<br />
# pam_tally2 --reset --user ''username''<br />
<br />
{{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.<br />
<br />
=== Limit amount of processes ===<br />
<br />
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. <br />
<br />
* soft nproc 100<br />
* hard nproc 200<br />
<br />
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.<br />
<br />
=== Run Xorg rootless ===<br />
<br />
[[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.<br />
<br />
See [[Xorg#Rootless Xorg]] for more details how to run it without root privileges.<br />
<br />
== Restricting root ==<br />
<br />
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.<br />
<br />
=== Use sudo instead of su ===<br />
<br />
{{Merge|sudo|There's a dedicated article.}}<br />
<br />
Using [[sudo]] for privileged access is preferable to [[su]] for [[Su#Sudo, an alternative|a number of reasons]].<br />
<br />
* It keeps a log of which normal privilege user has run each privileged command.<br />
* The root user password need not be given out to each user who requires root access.<br />
* {{ic|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 [[Wikipedia:Principle of least privilege|principle of least privilege]].<br />
* 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:<br />
<br />
# visudo<br />
<br />
{{hc|/etc/sudoers|<br />
alice ALL &#61; NOPASSWD: /path/to/program<br />
}}<br />
<br />
Or, individual commands can be allowed for all users. To mount Samba shares from a server as a regular user:<br />
<br />
%users ALL=/sbin/mount.cifs,/sbin/umount.cifs<br />
<br />
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).<br />
<br />
{{Tip|<br />
To use restricted version of {{ic|nano}} instead of {{ic|vi}} with {{ic|visudo}},<br />
<br />
{{hc|/etc/sudoers|<br />
2=Defaults editor=/usr/bin/rnano<br />
}}<br />
<br />
Exporting {{ic|1=# EDITOR=nano visudo}} is regarded as a severe security risk since everything can be used as an {{ic|EDITOR}}.<br />
}}<br />
<br />
==== Editing files using sudo ====<br />
<br />
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 --edit 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:<br />
<br />
$ export SUDO_EDITOR=vim<br />
<br />
Alternatively, use an editor like {{ic|rvim}} which has restricted capabilities in order to be safe to run as root.<br />
<br />
=== Restricting root login ===<br />
<br />
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}}.<br />
<br />
==== Allow only certain users ====<br />
<br />
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:<br />
<br />
{{bc|<nowiki><br />
# Uncomment the following line to require a user to be in the "wheel" group.<br />
auth required pam_wheel.so use_uid<br />
</nowiki>}}<br />
<br />
This means only users who are already able to run privileged commands may login as root.<br />
<br />
==== Denying SSH login ====<br />
<br />
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.<br />
<br />
== Mandatory access control ==<br />
<br />
[[Wikipedia:Mandatory Access Control|Mandatory access control]] (MAC) is a type of security policy that differs significantly from the [[Wikipedia:Discretionary Access Control|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.<br />
<br />
=== Pathname MAC ===<br />
<br />
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.<br />
<br />
* [[AppArmor]] is a [[Wikipedia:Canonical_(company)|Canonical]]-maintained MAC implementation seen as an "easier" alternative to SELinux.<br />
* [[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.<br />
<br />
=== Labels MAC ===<br />
<br />
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.<br />
<br />
* [[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.<br />
<br />
=== Access Control Lists ===<br />
<br />
[[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.<br />
<br />
== Kernel hardening ==<br />
<br />
=== Kernel self-protection / exploit mitigation ===<br />
<br />
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.<br />
<br />
If you use an out-of-tree driver such as [[NVIDIA]], you may need to switch to its [[DKMS]] package.<br />
<br />
==== Userspace ASLR comparison ====<br />
<br />
The {{pkg|linux-hardened}} package provides an improved implementation of Address Space Layout Randomization for userspace processes. The {{pkg|paxtest}} command can be used to obtain an estimate of the provided entropy:<br />
<br />
===== 64-bit processes =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 32 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 26 quality bits (guessed)<br />
Heap randomization test (PIE) : 40 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 32 quality bits (guessed)<br />
Shared library randomization test : 32 quality bits (guessed)<br />
VDSO randomization test : 32 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 40 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 40 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 44 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 44 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 32 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 34 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 32 bits (guessed)<br />
Randomization under memory exhaustion @0 : 32 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 28 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 28 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 28 quality bits (guessed)<br />
Shared library randomization test : 28 quality bits (guessed)<br />
VDSO randomization test : 20 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 30 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 30 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 22 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 22 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 28 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 28 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 28 bits (guessed)<br />
Randomization under memory exhaustion @0 : 28 bits (guessed)<br />
}}<br />
<br />
===== 32-bit processes (on an x86_64 kernel) =====<br />
<br />
{{hc|linux-hardened|<br />
Anonymous mapping randomization test : 16 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 22 quality bits (guessed)<br />
Heap randomization test (PIE) : 27 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 18 quality bits (guessed)<br />
Shared library randomization test : 16 quality bits (guessed)<br />
VDSO randomization test : 16 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 24 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 24 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 28 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 28 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 18 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 16 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: 18 bits (guessed)<br />
Randomization under memory exhaustion @0 : 18 bits (guessed)<br />
}}<br />
<br />
{{hc|linux|<br />
Anonymous mapping randomization test : 8 quality bits (guessed)<br />
Heap randomization test (ET_EXEC) : 13 quality bits (guessed)<br />
Heap randomization test (PIE) : 13 quality bits (guessed)<br />
Main executable randomization (ET_EXEC) : No randomization<br />
Main executable randomization (PIE) : 8 quality bits (guessed)<br />
Shared library randomization test : 8 quality bits (guessed)<br />
VDSO randomization test : 8 quality bits (guessed)<br />
Stack randomization test (SEGMEXEC) : 19 quality bits (guessed)<br />
Stack randomization test (PAGEEXEC) : 19 quality bits (guessed)<br />
Arg/env randomization test (SEGMEXEC) : 11 quality bits (guessed)<br />
Arg/env randomization test (PAGEEXEC) : 11 quality bits (guessed)<br />
Offset to library randomisation (ET_EXEC): 8 quality bits (guessed)<br />
Offset to library randomisation (ET_DYN) : 13 quality bits (guessed)<br />
Randomization under memory exhaustion @~0: No randomization<br />
Randomization under memory exhaustion @0 : No randomization<br />
}}<br />
<br />
=== Restricting access to kernel logs ===<br />
<br />
{{Note|This is enabled by default in {{pkg|linux-hardened}}.}}<br />
<br />
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).<br />
<br />
{{hc|/etc/sysctl.d/50-dmesg-restrict.conf|2=<br />
kernel.dmesg_restrict = 1<br />
}}<br />
<br />
=== Restricting access to kernel pointers in the proc filesystem ===<br />
<br />
{{Note|{{pkg|linux-hardened}} sets {{ic|1=kptr_restrict=2}} by default rather than {{ic|0}}.}}<br />
<br />
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.<br />
<br />
Setting {{ic|kernel.kptr_restrict}} to 2 will hide kernel symbol addresses in {{ic|/proc/kallsyms}} regardless of privileges.<br />
<br />
{{hc|/etc/sysctl.d/50-kptr-restrict.conf|2=<br />
kernel.kptr_restrict = 1<br />
}}<br />
<br />
=== Keep BPF JIT compiler disabled ===<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== ptrace scope ===<br />
<br />
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.<br />
<br />
==== Examples of broken functionality ====<br />
<br />
{{Note|You can still execute these commands as root (such as allowing them through [[sudo]] for certain users, with or without a password).}}<br />
<br />
* {{ic|gdb -p $PID}}<br />
* {{ic|strace -p $PID}}<br />
* {{ic|perf trace -p $PID}}<br />
* {{ic|reptyr $PID}}<br />
<br />
=== hidepid ===<br />
<br />
{{Warning|<br />
* This may cause issues for certain applications like an application running in a sandbox and [[Xorg]] (see workaround).<br />
* This causes issues with [[D-Bus]], [[PulseAudio]] and [[bluetooth]] when using {{Pkg|systemd}} > 237.64-1.<br />
}}<br />
<br />
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]. <br />
<br />
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.<br />
<br />
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]].<br />
<br />
For example, to hide process information from other users except those in the {{ic|proc}} group:<br />
<br />
{{hc|/etc/fstab|2=<br />
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0<br />
}}<br />
<br />
For user sessions to work correctly, an exception needs to be added for ''systemd-logind'':<br />
<br />
{{hc|/etc/systemd/system/systemd-logind.service.d/hidepid.conf|2=<br />
[Service]<br />
SupplementaryGroups=proc<br />
}}<br />
<br />
=== Restricting module loading ===<br />
The default Arch kernel has CONFIG_MODULE_SIG_ALL enabled which signs all kernel modules build as part of the {{Pkg|Linux}} package. This allows the kernel to restrict modules to be only loaded when they are signed with a valid key, in practical terms this means that all out of tree modules compiled locally or provides by packages such as {{Pkg|wireguard-arch}} cannot be loaded. Restricting loading kernel modules can be done by adding {{ic|1=module.sig_enforce=1}} to the kernel command line, further documentation can be found [https://www.kernel.org/doc/html/v5.2-rc3/admin-guide/module-signing.html here].<br />
<br />
== Sandboxing applications ==<br />
<br />
See also [[Wikipedia:Sandbox (computer security)]].<br />
<br />
{{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.}}<br />
<br />
=== Firejail ===<br />
<br />
[[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.<br />
<br />
=== bubblewrap ===<br />
<br />
[[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].<br />
<br />
=== chroots ===<br />
<br />
Manual [[chroot]] jails can also be constructed.<br />
<br />
=== Linux containers ===<br />
<br />
[[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.<br />
<br />
=== Other virtualization options ===<br />
<br />
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.<br />
<br />
== Network and firewalls ==<br />
<br />
=== Firewalls ===<br />
<br />
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.<br />
<br />
* See [[iptables]] and [[nftables]] for general info.<br />
* See [[Simple stateful firewall]] for a guide on setting up an iptables firewall.<br />
* See [[:Category:Firewalls]] for other ways of setting up netfilter.<br />
* See [[Ipset]] for blocking lists of ip addresses, such as those from Bluetack.<br />
<br />
=== Kernel parameters ===<br />
<br />
Kernel parameters which affect networking can be set using [[Sysctl]]. For how to do this, see [[Sysctl#TCP/IP stack hardening]].<br />
<br />
=== SSH ===<br />
<br />
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.<br />
<br />
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).<br />
<br />
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]].<br />
<br />
=== DNS ===<br />
<br />
{{Accuracy|Your browser might notice DNS spoofing with [[HSTS]].}}<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
[[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.<br />
<br />
If you have a domain name, set a [[Sender Policy Framework]] policy to combat email spoofing.<br />
<br />
=== Proxies ===<br />
<br />
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.<br />
<br />
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]<br />
<br />
=== Managing SSL certificates ===<br />
<br />
{{Merge|Transport Layer Security|There's a dedicated article.}}<br />
<br />
See [[OpenSSL]] and [[Network Security Services]] (NSS) for managing custom server-side SSL certificates. Notably, the related [[Let’s Encrypt]] project is also supported. <br />
<br />
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. <br />
<br />
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:<br />
<br />
# 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), <br />
# Copy it to {{ic|/etc/ca-certificates/trust-source/blacklist/}} and <br />
# Run ''update-ca-trust'' as root. <br />
<br />
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.<br />
<br />
== Authenticating packages ==<br />
<br />
[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.<br />
<br />
== Follow vulnerability alerts ==<br />
<br />
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]].<br />
<br />
{{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.}}<br />
<br />
== Physical security ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
[[#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.<br />
<br />
=== Locking down BIOS ===<br />
<br />
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.<br />
<br />
=== Bootloaders ===<br />
<br />
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.<br />
<br />
==== Syslinux ====<br />
<br />
Syslinux supports [[Syslinux#Security|password-protecting your bootloader]]. It allows you to set either a per-menu-item password or a global bootloader password.<br />
<br />
==== GRUB ====<br />
<br />
[[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.<br />
<br />
=== Boot partition on removable flash drive ===<br />
<br />
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. <br />
<br />
=== Automatic logout ===<br />
<br />
If you are using [[Bash]] or [[Zsh]], you can set {{ic|TMOUT}} for an automatic logout from shells after a timeout.<br />
<br />
For example, the following will automatically log out from virtual consoles (but not terminal emulators in X11):<br />
<br />
{{hc|/etc/profile.d/shell-timeout.sh|<nowiki><br />
TMOUT="$(( 60*10 ))";<br />
[ -z "$DISPLAY" ] && export TMOUT;<br />
case $( /usr/bin/tty ) in<br />
/dev/tty[0-9]*) export TMOUT;;<br />
esac<br />
</nowiki>}}<br />
<br />
If you really want EVERY Bash/Zsh prompt (even within X) to timeout, use:<br />
<br />
$ export TMOUT="$(( 60*10 ))";<br />
<br />
Note that this will not work if there is some command running in the shell (eg.: an SSH session or other shell without {{ic|TMOUT}} support). But if you are using VC mostly for restarting frozen GDM/Xorg as root, then this is very useful.<br />
<br />
=== Protect against rogue USB devices ===<br />
<br />
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.<br />
<br />
== Rebuilding packages ==<br />
<br />
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.<br />
<br />
== See also ==<br />
<br />
* [https://security.archlinux.org/ Arch Linux Security Tracker]<br />
* [https://wiki.centos.org/HowTos/OS_Protection CentOS Wiki: OS Protection]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-desktop/index.html Hardening the Linux desktop]<br />
* [https://www.ibm.com/developerworks/linux/tutorials/l-harden-server/index.html Hardening the Linux server]<br />
* [https://github.com/lfit/itpol/blob/master/linux-workstation-security.md Linux Foundation: Linux workstation security checklist]<br />
* [https://www.privacytools.io/ privacytools.io Privacy Resources]<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/ Red Hat Enterprise Linux 7 Security Guide]<br />
* [https://www.debian.org/doc/manuals/securing-debian-howto/securing-debian-howto.en.pdf Securing Debian Manual (PDF)]<br />
* [https://web.archive.org/web/20140220055801/http://crunchbang.org:80/forums/viewtopic.php?id=24722 The paranoid #! Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Improving_performance&diff=570960Improving performance2019-04-12T23:21:17Z<p>Teples: /* Kernel's I/O schedulers */ Update info about multi/single queue schedulers status</p>
<hr />
<div>[[Category:Hardware]]<br />
[[Category:System administration]]<br />
[[ar:Improving performance]]<br />
[[es:Improving performance]]<br />
[[ja:パフォーマンスの最大化]]<br />
[[ru:Improving performance]]<br />
[[zh-hans:Improving performance]]<br />
{{Related articles start}}<br />
{{Related|Improving performance/Boot process}}<br />
{{Related|Pacman/Tips and tricks#Performance}}<br />
{{Related|OpenSSH#Speeding up SSH}}<br />
{{Related|Openoffice#Speed up OpenOffice}}<br />
{{Related|Laptop}}<br />
{{Related|Preload}}<br />
{{Related articles end}}<br />
This article provides information on basic system diagnostics relating to performance as well as steps that may be taken to reduce resource consumption or to otherwise optimize the system with the end-goal being either perceived or documented improvements to a system's performance.<br />
<br />
== The basics ==<br />
<br />
=== Know your system ===<br />
<br />
The best way to tune a system is to target bottlenecks, or subsystems which limit overall speed. The system specifications can help identify them.<br />
<br />
* If the computer becomes slow when large applications (such as LibreOffice and Firefox) run at the same time, check if the amount of RAM is sufficient. Use the following command, and check the "available" column:<br />
<br />
$ free -h<br />
<br />
* If boot time is slow, and applications take a long time to load at first launch (only), then the hard drive is likely to blame. The speed of a hard drive can be measured with the {{ic|hdparm}} command:<br />
{{Note|{{Pkg|hdparm}} indicates only the pure read speed of a hard drive, and is not a valid benchmark. A value higher than 40MB/s (while idle) is however acceptable on an average system.}}<br />
<br />
# hdparm -t /dev/sdX<br />
<br />
* If CPU load is consistently high even with enough RAM available, then try to lower CPU usage by disabling running [[daemons]] and/or processes. This can be monitored in several ways, for example with {{Pkg|htop}}, {{ic|pstree}} or any other [[List_of_applications#System monitors|system monitoring]] tool:<br />
<br />
$ htop<br />
<br />
* If applications using direct rendering are slow (i.e those which use the GPU, such as video players, games, or even a [[window manager]]), then improving GPU performance should help. The first step is to verify if direct rendering is actually enabled. This is indicated by the {{ic|glxinfo}} command, part of the {{Pkg|mesa-demos}} package:<br />
{{hc|<nowiki>$ glxinfo | grep direct</nowiki>|<br />
direct rendering: Yes<br />
}}<br />
<br />
* When running a [[desktop environment]], disabling (unused) visual desktop effects may reduce GPU usage. Use a more lightweight environment or create a [[Desktop_environment#Custom_environments|custom environment]] if the current does not meet the hardware and/or personal requirements.<br />
<br />
=== Benchmarking ===<br />
<br />
The effects of optimization are often difficult to judge. They can however be measured by [[benchmarking]] tools.<br />
<br />
== Storage devices ==<br />
<br />
=== Multiple hardware paths ===<br />
<br />
{{Style|Subjective writing}}<br />
<br />
An internal hardware path is how the storage device is connected to your motherboard. There are different ways to connect to the motherboard such as TCP/IP through a NIC, plugged in directly using PCIe/PCI, Firewire, Raid Card, USB, etc. By spreading your storage devices across these multiple connection points you maximize the capabilities of your motherboard, for example 6 hard-drives connected via USB would be much much slower than 3 over USB and 3 over Firewire. The reason is that each entry path into the motherboard is like a pipe, and there is a set limit to how much can go through that pipe at any one time. The good news is that the motherboard usually has several pipes.<br />
<br />
More Examples<br />
<br />
# Directly to the motherboard using pci/PCIe/ata<br />
# Using an external enclosure to house the disk over USB/Firewire<br />
# Turn the device into a network storage device by connecting over tcp/ip<br />
<br />
Note also that if you have a 2 USB ports on the front of your machine, and 4 USB ports on the back, and you have 4 disks, it would probably be fastest to put 2 on front/2 on back or 3 on back/1 on front. This is because internally the front ports are likely a separate Root Hub than the back, meaning you can send twice as much data by using both than just 1. Use the following commands to determine the various paths on your machine.<br />
<br />
{{hc|USB Device Tree|$ lsusb -tv}}<br />
<br />
{{hc|PCI Device Tree|$ lspci -tv}}<br />
<br />
=== Partitioning ===<br />
<br />
Make sure that your partitions are [[Partitioning#Partition_alignment|properly aligned]].<br />
<br />
==== Multiple drives ====<br />
<br />
If you have multiple disks available, you can set them up as a software [[RAID]] for serious speed improvements.<br />
<br />
Creating [[swap]] on a separate disk can also help quite a bit, especially if your machine swaps frequently.<br />
<br />
==== Layout on HDDs ====<br />
<br />
If using a traditional spinning HDD, your partition layout can influence the system's performance. Sectors at the beginning of the drive (closer to the outside of the disk) are faster than those at the end. Also, a smaller partition requires less movements from the drive's head, and so speed up disk operations. Therefore, it is advised to create a small partition (10GB, more or less depending on your needs) only for your system, as near to the beginning of the drive as possible. Other data (pictures, videos) should be kept on a separate partition, and this is usually achieved by separating the home directory ({{ic|/home/''user''}}) from the system ({{ic|/}}).<br />
<br />
=== Choosing and tuning your filesystem ===<br />
<br />
Choosing the best filesystem for a specific system is very important because each has its own strengths. The [[File systems]] article provides a short summary of the most popular ones. You can also find relevant articles in [[:Category:File systems]].<br />
<br />
==== Mount options ====<br />
<br />
The [[fstab#atime options|noatime]] option is known to improve performance of the filesystem.<br />
<br />
Other mount options are filesystem specific, therefore see the relevant articles for the filesystems:<br />
<br />
* [[Ext3]]<br />
* [[Ext4#Improving performance]]<br />
* [[JFS Filesystem#Optimizations]]<br />
* [[XFS#Performance]]<br />
* [[Btrfs#Defragmentation]], [[Btrfs#Compression]], and {{man|5|btrfs}}<br />
* [[ZFS#Tuning]]<br />
<br />
===== Reiserfs =====<br />
<br />
The {{Ic|1=data=writeback}} mount option improves speed, but may corrupt data during power loss. The {{Ic|notail}} mount option increases the space used by the filesystem by about 5%, but also improves overall speed. You can also reduce disk load by putting the journal and data on separate drives. This is done when creating the filesystem: <br />
<br />
# mkreiserfs –j /dev/sd'''a1''' /dev/sd'''b1'''<br />
<br />
Replace {{ic|/dev/sd'''a1'''}} with the partition reserved for the journal, and {{ic|/dev/sd'''b1'''}} with the partition for data. You can learn more about reiserfs with this [http://www.funtoo.org/Funtoo_Filesystem_Guide,_Part_2 article].<br />
<br />
=== Tuning kernel parameters ===<br />
<br />
There are several key tunables affecting the performance of block devices, see [[sysctl#Virtual memory]] for more information.<br />
<br />
=== Input/output schedulers ===<br />
==== Background information ====<br />
The input/output ''(I/O)'' scheduler is the kernel component that decides in which order the block I/O operations are submitted to storage devices. It is useful to remind here some specifications of two main drive types because the goal of the I/O scheduler is to optimize the way these are able to deal with read requests:<br />
<br />
* An HDD has spinning disks and a head that moves physically to the required location. Therefore, random latency is quite high ranging between 3 and 12ms (whether it is a high end server drive or a laptop drive and bypassing the disk controller write buffer) while sequential access provides much higher throughput. The typical HDD throughput is about 200 I/O operations per second ''(IOPS)''.<br />
<br />
* An SSD does not have moving parts, random access is as fast as sequential one, typically under 0.1ms, and it can handle multiple concurrent requests. The typical SSD throughput is greater than 10,000 IOPS, which is more than needed in common workload situations.<br />
<br />
If there are many processes making I/O requests to different storage parts, thousands of IOPS can be generated while a typical HDD can handle only about 200 IOPS. There is a queue of requests that have to wait for access to the storage. This is where the I/O schedulers plays an optimization role.<br />
<br />
==== The scheduling algorithms ====<br />
<br />
One way to improve throughput is to linearize access: by ordering waiting requests by their logical address and grouping the closest ones. Historically this was the first Linux I/O scheduler called [[w:Elevator_algorithm|elevator]].<br />
<br />
One issue with the elevator algorithm is that it is not optimal for a process doing sequential access: reading a block of data, processing it for several microseconds then reading next block and so on. The elevator scheduler does not know that the process is about to read another block nearby and, thus, moves to another request by another process at some other location. The [[w:Anticipatory_scheduling|anticipatory]] I/O scheduler overcomes the problem: it pauses for a few milliseconds in anticipation of another close-by read operation before dealing with another request.<br />
<br />
While these schedulers try to improve total throughput, they might leave some unlucky requests waiting for a very long time. As an example, imagine the majority of processes make requests at the beginning of the storage space while an unlucky process makes a request at the other end of storage. This potentially infinite postponement of the process is called starvation. To improve fairness, the [[w:Deadline_scheduler|deadline]] algorithm was developed. It has a queue ordered by address, similar to the elevator, but if some request sits in this queue for too long then it moves to an "expired" queue ordered by expire time. The scheduler checks the expire queue first and processes requests from there and only then moves to the elevator queue. Note that this fairness has a negative impact on overall throughput.<br />
<br />
The [[w:CFQ|Completely Fair Queuing ''(CFQ)'']] approaches the problem differently by allocating a timeslice and a number of allowed requests by queue depending on the priority of the process submitting them. It supports [[cgroup]] that allows to reserve some amount of I/O to a specific collection of processes. It is in particular useful for shared and cloud hosting: users who paid for some IOPS want to get their share whenever needed. Also, it idles at the end of synchronous I/O waiting for other nearby operations, taking over this feature from the ''anticipatory'' scheduler and bringing some enhancements. Both the ''anticipatory'' and the ''elevator'' schedulers were decommissioned from the Linux kernel replaced by the more advanced alternatives presented above.<br />
<br />
The [https://algo.ing.unimo.it/people/paolo/disk_sched/ Budget Fair Queuing ''(BFQ)''] is based on CFQ code and brings some enhancements. It does not grant the disk to each process for a fixed time-slice but assigns a "budget" measured in number of sectors to the process and uses heuristics. It is a relatively complex scheduler, it may be more adapted to rotational drives and slow SSDs because its high per-operation overhead, especially if associated with a slow CPU, can slow down fast devices. The objective of BFQ on personal systems is that for interactive tasks, the storage device is virtually as responsive as if it was idle. In its default configuration it focuses on delivering the lowest latency rather than achieving the maximum throughput.<br />
<br />
[https://lwn.net/Articles/720675/ Kyber] is a recent scheduler inspired by active queue management techniques used for network routing. The implementation is based on "tokens" that serve as a mechanism for limiting requests. A queuing token is required to allocate a request, this is used to prevent starvation of requests. A dispatch token is also needed and limits the operations of a certain priority on a given device. Finally, a target read latency is defined and the scheduler tunes itself to reach this latency goal. The implementation of the algorithm is relatively simple and it is deemed efficient for fast devices.<br />
<br />
==== Kernel's I/O schedulers ====<br />
While some of the early algorithms have now been decommissioned, the official Linux kernel supports a number of I/O schedulers which can be split into two categories:<br />
<br />
*The '''multi-queue schedulers''' are available by default with the kernel. The [https://www.thomas-krenn.com/en/wiki/Linux_Multi-Queue_Block_IO_Queueing_Mechanism_(blk-mq) Multi-Queue Block I/O Queuing Mechanism ''(blk-mq)''] maps I/O queries to multiple queues, the tasks are distributed across threads and therefore CPU cores. Within this framework the following schedulers are available:<br />
**''None'', no queuing algorithm is applied.<br />
**''mq-deadline'' is the adaptation of the deadline scheduler to multi-threading.<br />
**''Kyber''<br />
**''BFQ''<br />
<br />
*The '''single-queue schedulers''' are legacy schedulers, they can be activated at boot time as described in [[#Changing I/O scheduler]]:<br />
**[[w:NOOP_scheduler|NOOP]] is the simplest scheduler, it inserts all incoming I/O requests into a simple FIFO queue and implements request merging. In this algorithm, there is no re-ordering of the request based on the sector number. Therefore it can be used if the ordering is dealt with at another layer, at the device level for example, or if it does not matter, for SSDs for instance.<br />
**''Deadline''<br />
**''CFQ''<br />
:{{Note|1=Single-queue schedulers [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f382fb0bcef4c37dc049e9f6963e3baf204d815c were removed from kernel since Linux 5.0].}}<br />
<br />
==== Changing I/O scheduler ====<br />
{{Note|<br />
* The block multi-queue ''(blk-mq)'' mode must be disabled at boot time to be able to access the legacy ''CFQ'' and ''Deadline'' schedulers. This is done by adding {{ic|1=scsi_mod.use_blk_mq=0}} to the [[kernel parameters]]. The multi-queue schedulers are no longer available once in this mode.<br />
* The best choice of scheduler depends on both the device and the exact nature of the workload. Also, the throughput in MB/s is not the only measure of performance: deadline or fairness deteriorate the overall throughput but may improve system responsiveness. [[Benchmarking]] may be useful to indicate each I/O scheduler performance.}}<br />
<br />
To list the available schedulers for a device and the active scheduler (in brackets):<br />
{{hc|$ cat /sys/block/'''''sda'''''/queue/scheduler|<br />
mq-deadline kyber [bfq] none}}<br />
<br />
To list the available schedulers for all devices:<br />
{{hc|$ cat /sys/block/'''*'''/queue/scheduler|<br />
none<br />
[mq-deadline] kyber bfq none<br />
mq-deadline kyber [bfq] none}}<br />
<br />
To change the active I/O scheduler to ''bfq'' for device ''sda'', use:<br />
<br />
# echo '''''bfq''''' > /sys/block/'''''sda'''''/queue/scheduler<br />
<br />
The process to change I/O scheduler, depending on whether the disk is rotating or not can be automated and persist across reboots. For example the [[udev]] rule below sets the scheduler to ''none'' for [[NVMe]], ''mq-deadline'' for [[SSD]]/eMMC, and ''bfq'' for rotational drives:<br />
<br />
{{hc|/etc/udev/rules.d/60-ioschedulers.rules|2=<br />
# set scheduler for NVMe<br />
ACTION=="add{{!}}change", KERNEL=="nvme[0-9]*", ATTR{queue/scheduler}="none"<br />
# set scheduler for SSD and eMMC<br />
ACTION=="add{{!}}change", KERNEL=="sd[a-z]{{!}}mmcblk[0-9]*", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="mq-deadline"<br />
# set scheduler for rotating disks<br />
ACTION=="add{{!}}change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="bfq"<br />
}}<br />
<br />
Reboot or force [[udev#Loading new rules]].<br />
<br />
==== Tuning I/O scheduler ====<br />
<br />
Each of the kernel's I/O scheduler has its own tunables, such as the latency time, the expiry time or the FIFO parameters. They are helpful in adjusting the algorithm to a particular combination of device and workload. This is typically to achieve a higher throughput or a lower latency for a given utilization.<br />
The tunables and their description can be found within the [https://www.kernel.org/doc/Documentation/block/ kernel documentation files].<br />
<br />
To list the available tunables for a device, in the example below ''sdb'' which is using ''deadline'', use:<br />
{{hc|$ ls /sys/block/'''''sdb'''''/queue/iosched|<br />
fifo_batch front_merges read_expire write_expire writes_starved}}<br />
<br />
To improve ''deadline'''s throughput at the cost of latency, one can increase {{ic|fifo_batch}} with the command:<br />
<br />
{{bc|# echo ''32'' > /sys/block/'''''sdb'''''/queue/iosched/'''fifo_batch'''}}<br />
<br />
=== Power management configuration ===<br />
When dealing with traditional rotational disks (HDD's) you may want to [[Hdparm#Power_management_configuration|lower or disable power saving features]] completely.<br />
<br />
=== Reduce disk reads/writes ===<br />
<br />
Avoiding unnecessary access to slow storage drives is good for performance and also increasing lifetime of the devices, although on modern hardware the difference in life expectancy is usually negligible.<br />
<br />
{{Note|A 32GB SSD with a mediocre 10x write amplification factor, a standard 10000 write/erase cycle, and '''10GB of data written per day''', would get an '''8 years life expectancy'''. It gets better with bigger SSDs and modern controllers with less write amplification. Also compare [http://techreport.com/review/25889/the-ssd-endurance-experiment-500tb-update] when considering whether any particular strategy to limit disk writes is actually needed.}}<br />
<br />
==== Show disk writes ====<br />
<br />
The {{Pkg|iotop}} package can sort by disk writes, and show how much and how frequently programs are writing to the disk. See {{man|8|iotop}} for details.<br />
<br />
==== Relocate files to tmpfs ====<br />
<br />
Relocate files, such as your browser profile, to a [[tmpfs]] file system, for improvements in application response as all the files are now stored in RAM:<br />
<br />
* Refer to [[Profile-sync-daemon]] for syncing browser profiles. Certain browsers might need special attention, see e.g. [[Firefox on RAM]].<br />
* Refer to [[Anything-sync-daemon]] for syncing any specified folder.<br />
* Refer to [[Makepkg#Improving compile times]] for improving compile times when building packages.<br />
<br />
==== Compiling in tmpfs ====<br />
<br />
See [[Makepkg#Building from files in memory]].<br />
<br />
==== Optimize the filesystem ====<br />
<br />
[[Filesystems]] may provide performance improvements instructions for each filesystem, e.g. [[Ext4#Improving performance]].<br />
<br />
==== Swap space ====<br />
<br />
See [[Swap#Performance]].<br />
<br />
=== Storage I/O scheduling with ionice ===<br />
<br />
Many tasks such as backups do not rely on a short storage I/O delay or high storage I/O bandwidth to fulfil their task, they can be classified as background tasks.<br />
On the other hand quick I/O is necessary for good UI responsiveness on the desktop.<br />
Therefore it is beneficial to reduce the amount of storage bandwidth available to background tasks, whilst other tasks are in need of storage I/O. This can be achieved by making use of the linux I/O scheduler CFQ, which allows setting different priorities for processes.<br />
<br />
The I/O priority of a background process can be reduced to the "Idle" level by starting it with<br />
<br />
# ionice -c 3 command<br />
<br />
See {{man|1|ionice}} and [https://www.cyberciti.biz/tips/linux-set-io-scheduling-class-priority.html] for more information.<br />
<br />
== CPU ==<br />
<br />
=== Overclocking ===<br />
<br />
[[w:Overclocking|Overclocking]] improves the computational performance of the CPU by increasing its peak clock frequency. The ability to overclock depends on the combination of CPU model and motherboard model. It is most frequently done through the BIOS. Overclocking also has disadvantages and risks. It is neither recommended nor discouraged here.<br />
<br />
Many Intel chips will not correctly report their clock frequency to acpi_cpufreq and most other utilities. This will result in excessive messages in dmesg, which can be avoided by unloading and blacklisting the kernel module {{ic|acpi_cpufreq}}.<br />
To read their clock speed use ''i7z'' from the {{Pkg|i7z}} package. To check for correct operation of an overclocked CPU, it is recommended to do [[stress testing]].<br />
<br />
=== Frequency scaling ===<br />
<br />
See [[CPU frequency scaling]].<br />
<br />
=== Alternative CPU scheduler ===<br />
<br />
{{Expansion|MuQSS is not the only alternative scheduler.}}<br />
<br />
The default CPU scheduler in the mainline Linux kernel is [[w:Completely_Fair_Scheduler|CFS]].<br />
<br />
An alternative scheduler designed to be used on desktop computers is MuQSS, developed by [http://users.tpg.com.au/ckolivas/kernel/ Con Kolivas], which is focused on desktop interactivity and responsiveness. MuQSS is available either as a stand-alone patch or as part of a wider patchset, the '''-ck''' patchset. See [[Linux-ck]] and [[Linux-pf]] for more information on the patchset.<br />
<br />
=== Real-time kernel ===<br />
<br />
Some applications such as running a TV tuner card at full HD resolution (1080p) may benefit from using a [[realtime kernel]].<br />
<br />
=== Adjusting priorities of processes ===<br />
<br />
See also {{man|1|nice}} and {{man|1|renice}}.<br />
<br />
==== Ananicy ====<br />
<br />
[https://github.com/Nefelim4ag/Ananicy Ananicy] is a daemon, available in the {{AUR|ananicy-git}} package, for auto adjusting the nice levels of executables. The nice level represents the priority of the executable when allocating CPU resources.<br />
<br />
==== cgroups ====<br />
<br />
See [[cgroups]].<br />
<br />
==== Cpulimit ====<br />
<br />
[https://github.com/opsengine/cpulimit Cpulimit] is a program to limit the CPU usage percentage of a specific process. After installing {{Pkg|cpulimit}}, you may limit the CPU usage of a processes' PID using a scale of 0 to 100 times the number of CPU cores that the computer has. For example, with eight CPU cores the precentage range will be 0 to 800. Usage:<br />
<br />
$ cpulimit -l 50 -p 5081<br />
<br />
=== irqbalance ===<br />
<br />
The purpose of {{Pkg|irqbalance}} is distribute hardware interrupts across processors on a multiprocessor system in order to increase performance. It can be [[systemd#Using units|controlled]] by the provided {{ic|irqbalance.service}}.<br />
<br />
== Graphics ==<br />
<br />
=== Xorg configuration ===<br />
<br />
Graphics performance may depend on the settings in {{man|5|xorg.conf}}; see the [[NVIDIA]], [[ATI]] and [[Intel]] articles. Improper settings may stop Xorg from working, so caution is advised.<br />
<br />
=== Mesa configuration ===<br />
<br />
The performance of the Mesa drivers can be configured via [https://dri.freedesktop.org/wiki/ConfigurationInfrastructure/ drirc]. GUI configuration tools are available:<br />
* {{App|adriconf (Advanced DRI Configurator)|GUI tool to configure Mesa drivers by setting options and writing them to the standard drirc file.|https://github.com/jlHertel/adriconf/|{{Pkg|adriconf}}}}<br />
* {{App|DRIconf|Configuration applet for the Direct Rendering Infrastructure. It allows customizing performance and visual quality settings of OpenGL drivers on a per-driver, per-screen and/or per-application level.|https://dri.freedesktop.org/wiki/DriConf/|{{AUR|driconf}}}}<br />
<br />
=== Overclocking ===<br />
<br />
As with CPUs, overclocking can directly improve performance, but is generally recommended against. There are several packages in the [[AUR]], such as {{AUR|amdoverdrivectrl}} (ATI) and {{AUR|nvclock}} (NVIDIA).<br />
<br />
See [[AMDGPU#Overclocking]] or [[NVIDIA/Tips and tricks#Enabling overclocking]].<br />
<br />
== RAM and swap ==<br />
<br />
=== Clock frequency and timings ===<br />
<br />
RAM can run at different clock frequencies and timings, which can be configured in the BIOS. Memory performance depends on both values. Selecting the highest preset presented by the BIOS usually improves the performance over the default setting. Note that increasing the frequency to values not supported by both motherboard and RAM vendor is overclocking, and similar risks and disadvantages apply, see [[#Overclocking]].<br />
<br />
=== Root on RAM overlay ===<br />
<br />
If running off a slow writing medium (USB, spinning HDDs) and storage requirements are low, the root may be run on a RAM overlay ontop of read only root (on disk). This can vastly improve performance at the cost of a limited writable space to root. See {{AUR|liveroot}}.<br />
<br />
=== Zram or zswap ===<br />
<br />
The [https://www.kernel.org/doc/Documentation/blockdev/zram.txt zram] kernel module (previously called '''compcache''') provides a compressed block device in RAM. If you use it as swap device, the RAM can hold much more information but uses more CPU. Still, it is much quicker than swapping to a hard drive. If a system often falls back to swap, this could improve responsiveness. Using zram is also a good way to reduce disk read/write cycles due to swap on SSDs.<br />
<br />
Similar benefits (at similar costs) can be achieved using [[zswap]] rather than zram. The two are generally similar in intent although not operation: zswap operates as a compressed RAM cache and neither requires (nor permits) extensive userspace configuration.<br />
<br />
Example: To set up one lz4 compressed zram device with 32GiB capacity and a higher-than-normal priority (only for the current session):<br />
<br />
# modprobe zram<br />
# echo lz4 > /sys/block/zram0/comp_algorithm<br />
# echo 32G > /sys/block/zram0/disksize<br />
# mkswap --label zram0 /dev/zram0<br />
# swapon --priority 100 /dev/zram0<br />
<br />
To disable it again, either reboot or run<br />
<br />
# swapoff /dev/zram0<br />
# rmmod zram<br />
<br />
A detailed explanation of all steps, options and potential problems is provided in the official documentation of the module [https://www.kernel.org/doc/Documentation/blockdev/zram.txt here].<br />
<br />
The {{Pkg|systemd-swap}} package provides a {{ic|systemd-swap.service}} unit to automatically initialize zram devices. Configuration is possible in {{ic|/etc/systemd/swap.conf}}.<br />
<br />
The package {{AUR|zramswap}} provides an automated script for setting up such swap devices with optimal settings for your system (such as RAM size and CPU core number). The script creates one zram device per CPU core with a total space equivalent to the RAM available, so you will have a compressed swap with higher priority than regular swap, which will utilize multiple CPU cores for compressing data. To do this automatically on every boot, [[enable]] {{ic|zramswap.service}}.<br />
<br />
==== Swap on zRAM using a udev rule ====<br />
<br />
The example below describes how to set up swap on zRAM automatically at boot with a single udev rule. No extra package should be needed to make this work.<br />
<br />
First, enable the module:<br />
<br />
{{hc|/etc/modules-load.d/zram.conf|<nowiki><br />
zram<br />
</nowiki>}}<br />
<br />
Configure the number of /dev/zram nodes you need.<br />
<br />
{{hc|/etc/modprobe.d/zram.conf|<nowiki><br />
options zram num_devices=2<br />
</nowiki>}}<br />
<br />
Create the udev rule as shown in the example.<br />
<br />
{{hc|/etc/udev/rules.d/99-zram.rules|<nowiki><br />
KERNEL=="zram0", ATTR{disksize}="512M" RUN="/usr/bin/mkswap /dev/zram0", TAG+="systemd"<br />
KERNEL=="zram1", ATTR{disksize}="512M" RUN="/usr/bin/mkswap /dev/zram1", TAG+="systemd"<br />
</nowiki>}}<br />
<br />
Add /dev/zram to your fstab.<br />
<br />
{{hc|/etc/fstab|<nowiki><br />
/dev/zram0 none swap defaults 0 0<br />
/dev/zram1 none swap defaults 0 0<br />
</nowiki>}}<br />
<br />
=== Using the graphic card's RAM ===<br />
<br />
In the unlikely case that you have very little RAM and a surplus of video RAM, you can use the latter as swap. See [[Swap on video RAM]].<br />
<br />
== Network ==<br />
<br />
* Kernel networking: see [[Sysctl#Improving performance]]<br />
* NIC: see [[Network configuration#Set device MTU and queue length]]<br />
* DNS: consider using a caching DNS resolver, see [[Domain name resolution#Resolvers]]{{Broken section link}}<br />
* Samba: see [[Samba#Improve throughput]]<br />
<br />
== Watchdogs ==<br />
According to [[wikipedia:Watchdog_timer]]:<br />
:A watchdog timer [...] is an electronic timer that is used to detect and recover from computer malfunctions. During normal operation, the computer regularly resets the watchdog timer [...]. If, [...], the computer fails to reset the watchdog, the timer will elapse and generate a timeout signal [...] used to initiate corrective [...] actions [...] typically include placing the computer system in a safe state and restoring normal system operation.<br />
<br />
Many users need this feature due to their system's mission-critical role (i.e. servers), or because of the lack of power reset (i.e. embedded devices). Thus, this feature is required for a good operation in some situations. On the other hand, normal users (i.e. desktop and laptop) do not need this feature and can disable it.<br />
<br />
To disable watchdog timers (both software and hardware), append {{ic|nowatchdog}} to your boot parameters.<br />
<br />
To check the new configuration do:<br />
# cat /proc/sys/kernel/watchdog<br />
or use:<br />
# wdctl<br />
<br />
After you disabled watchdogs, you can ''optionally'' avoid the loading of the module responsible of the hardware watchdog, too. Do it by [[blacklisting]] the related module, e.g. {{ic|iTCO_wdt}}.<br />
<br />
{{Note|1=Some users [https://bbs.archlinux.org/viewtopic.php?id=221239 reported] the {{ic|nowatchdog}} parameter does not work as expected but they have successfully disabled the watchdog (at least the hardware one) by blacklisting the above-mentioned module.}}<br />
<br />
Either action will speed up your boot and shutdown, because one less module is loaded. Additionally disabling watchdog timers increases performance and [[Power_management#Disabling_NMI_watchdog|lowers power consumption]].<br />
<br />
See [https://bbs.archlinux.org/viewtopic.php?id=163768], [https://bbs.archlinux.org/viewtopic.php?id=165834], [http://0pointer.de/blog/projects/watchdog.html], and [https://www.kernel.org/doc/Documentation/watchdog/watchdog-parameters.txt] for more information.<br />
<br />
== See also ==<br />
<br />
* [https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Performance_Tuning_Guide/index.html Red Hat Performance Tuning Guide]<br />
* [https://www.thomas-krenn.com/en/wiki/Linux_Performance_Measurements_using_vmstat Linux Performance Measurements using vmstat]</div>Tepleshttps://wiki.archlinux.org/index.php?title=SELinux&diff=567827SELinux2019-03-03T13:32:45Z<p>Teples: SELinux userspace tools moved to SELinuxProject</p>
<hr />
<div>[[Category:Access control]]<br />
[[Category:Kernel]]<br />
[[Category:Red Hat]]<br />
[[ja:SELinux]]<br />
[[ru:SELinux]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|AppArmor}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
<br />
Security-Enhanced Linux (SELinux) is a Linux feature that provides a variety of security policies, including U.S. Department of Defense style [[Mandatory Access Control]] (MAC), through the use of Linux Security Modules (LSM) in the Linux kernel. It is not a Linux distribution, but rather a set of modifications that can be applied to Unix-like operating systems, such as Linux and BSD.<br />
<br />
Running SELinux under a Linux distribution requires three things: An SELinux enabled kernel, SELinux Userspace tools and libraries, and SELinux Policies (mostly based on the Reference Policy). Some common Linux programs will also need to be patched/compiled with SELinux features.<br />
<br />
==Current status in Arch Linux==<br />
<br />
SELinux is not officially supported (see [https://lists.archlinux.org/pipermail/arch-general/2013-October/034352.html][https://lists.archlinux.org/pipermail/arch-general/2017-February/043149.html]). The status of unofficial support is:<br />
<br />
{| class="wikitable"<br />
! Name !! Status !! Available at<br />
|-<br />
| SELinux enabled kernel || Implemented for {{pkg|linux}}, {{pkg|linux-zen}} and {{pkg|linux-hardened}} || Available in official repositories since [https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc 4.18.8].<br />
|-<br />
| SELinux Userspace tools and libraries || Implemented in AUR: https://aur.archlinux.org/packages/?O=0&K=selinux || Work is done at https://github.com/archlinuxhardened/selinux<br />
|-<br />
| SELinux Policy || Work in progress, using [https://github.com/SELinuxProject/refpolicy Reference Policy] as upstream || Upstream: https://github.com/SELinuxProject/refpolicy (since release 20170805 the policy has integrated support for systemd and single-/usr/bin directory)<br />
|}<br />
<br />
Summary of changes in AUR as compared to official core packages:<br />
<br />
{| class="wikitable"<br />
! Name !! Status and comments<br />
|-<br />
| linux || Need following [[kernel parameters]] at boot: {{ic|1=selinux=1 security=selinux}}<br />
|-<br />
| linux-hardened || Need following [[kernel parameters]] at boot: {{ic|1=selinux=1 security=selinux}}<br />
|-<br />
| coreutils || Need a rebuild with {{ic|--with-selinux}} flag to link with libselinux<br />
|-<br />
| cronie || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| dbus || Need a rebuild with {{ic|--enable-libaudit}} and {{ic|--enable-selinux}} flags<br />
|-<br />
| findutils || Need a rebuild with libselinux installed to enable SELinux-specific options<br />
|-<br />
| iproute2 || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| logrotate || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| openssh || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| pam || Need a rebuild with {{ic|--enable-selinux}} flag for Linux-PAM ; Need a patch for pam_unix2, which only removes a function already implemented in a recent versions of libselinux<br />
|-<br />
| pambase || Configuration changes to add pam_selinux.so to {{ic|/etc/pam.d/system-login}}<br />
|-<br />
| psmisc || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| shadow || Need a rebuild with {{ic|--with-selinux}} flags<br />
|-<br />
| sudo || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| systemd || Need a rebuild with {{ic|--enable-audit}} and {{ic|--enable-selinux}} flags<br />
|-<br />
| util-linux || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
|}<br />
<br />
All of the other SELinux-related packages may be included without changes nor risks.<br />
<br />
==Concepts: Mandatory Access Controls==<br />
<br />
{{Note|This section is meant for beginners. If you know what SELinux does and how it works, feel free to skip ahead to the installation.}}<br />
<br />
Before you enable SELinux, it is worth understanding what it does. Simply and succinctly, SELinux enforces ''Mandatory Access Controls (MACs)'' on Linux. In contrast to SELinux, the traditional user/group/rwx permissions are a form of ''Discretionary Access Control (DAC)''. MACs are different from DACs because security policy and its execution are completely separated.<br />
<br />
An example would be the use of the ''sudo'' command. When DACs are enforced, sudo allows temporary privilege escalation to root, giving the process so spawned unrestricted systemwide access. However, when using MACs, if the security administrator deems the process to have access only to a certain set of files, then no matter what the kind of privilege escalation used, unless the security policy itself is changed, the process will remain constrained to simply that set of files. So if ''sudo'' is tried on a machine with SELinux running in order for a process to gain access to files its policy does not allow, it will fail.<br />
<br />
Another set of examples are the traditional (-rwxr-xr-x) type permissions given to files. When under DAC, these are user-modifiable. However, under MAC, a security administrator can choose to freeze the permissions of a certain file by which it would become impossible for any user to change these permissions until the policy regarding that file is changed.<br />
<br />
As you may imagine, this is particularly useful for processes which have the potential to be compromised, i.e. web servers and the like. If DACs are used, then there is a particularly good chance of havoc being wreaked by a compromised program which has access to privilege escalation.<br />
<br />
For further information, visit [[wikipedia:Mandatory access control]].<br />
<br />
==Installing SELinux==<br />
<br />
===Package description===<br />
<br />
All SELinux related packages belong to the ''selinux'' group in the AUR.<br />
<br />
====SELinux aware system utilities====<br />
<br />
;{{AUR|coreutils-selinux}}<br />
:Modified coreutils package compiled with SELinux support enabled. It replaces the {{pkg|coreutils}} package<br />
<br />
;{{AUR|cronie-selinux}}<br />
:Fedora fork of Vixie cron with SELinux enabled. It replaces the {{pkg|cronie}} package.<br />
<br />
;{{AUR|dbus-selinux}}<br />
:An SELinux aware version of [[D-Bus]]. It replaces the {{pkg|dbus}} package.<br />
<br />
;{{AUR|findutils-selinux}}<br />
:Patched findutils package compiled with SELinux support to make searching of files with specified security context possible. It replaces the {{pkg|findutils}} package.<br />
<br />
;{{AUR|iproute2-selinux}}<br />
:iproute2 package compiled with SELinux support; for example, it adds the {{ic|-Z}} option to {{ic|ss}}. It replaces the {{pkg|iproute2}} package.<br />
<br />
;{{AUR|logrotate-selinux}}<br />
:Logrotate package compiled with SELinux support. It replaces the {{pkg|logrotate}} package.<br />
<br />
;{{AUR|openssh-selinux}}<br />
:[[OpenSSH]] package compiled with SELinux support to set security context for user sessions. It replaces the {{pkg|openssh}} package.<br />
<br />
;{{AUR|pam-selinux}} and {{AUR|pambase-selinux}}<br />
:PAM package with pam_selinux.so. and the underlying base package. They replace the {{pkg|pam}} and {{pkg|pambase}} packages respectively.<br />
<br />
;{{AUR|psmisc-selinux}}<br />
:Psmisc package compiled with SELinux support; for example, it adds the {{ic|-Z}} option to {{ic|killall}}. It replaces the {{pkg|psmisc}} package.<br />
<br />
;{{AUR|shadow-selinux}}<br />
:Shadow package compiled with SELinux support; contains a modified {{ic|/etc/pam.d/login}} file to set correct security context for user after login. It replaces the {{pkg|shadow}} package.<br />
<br />
;{{AUR|sudo-selinux}}<br />
:Modified [[sudo]] package compiled with SELinux support which sets the security context correctly. It replaces the {{pkg|sudo}} package.<br />
<br />
;{{AUR|systemd-selinux}}<br />
:An SELinux aware version of [[Systemd]]. It replaces the {{pkg|systemd}} package.<br />
<br />
;{{AUR|util-linux-selinux}}<br />
:Modified util-linux package compiled with SELinux support enabled. It replaces the {{pkg|util-linux}} package.<br />
<br />
====SELinux userspace utilities====<br />
;{{AUR|checkpolicy}}<br />
:Tools to build SELinux policy<br />
<br />
;{{AUR|mcstrans}}<br />
:Daemon which is used by libselinux to translate MCS labels<br />
<br />
;{{AUR|libselinux}}<br />
:Library for security-aware applications. Python bindings needed for ''semanage'' and ''setools'' now included.<br />
<br />
;{{AUR|libsemanage}}<br />
:Library for policy management. Python bindings needed for ''semanage'' and ''setools'' now included.<br />
<br />
;{{AUR|libsepol}}<br />
:Library for binary policy manipulation.<br />
<br />
;{{AUR|policycoreutils}}<br />
:SELinux core utils such as newrole, setfiles, etc.<br />
<br />
;{{AUR|restorecond}}<br />
:Daemon which maintains the label of some files<br />
<br />
;{{AUR|secilc}}<br />
:Compiler for SELinux policies written in CIL (Common Intermediate Language)<br />
<br />
;{{AUR|selinux-dbus-config}}<br />
:DBus service which allows managing SELinux configuration<br />
<br />
;{{AUR|selinux-gui}}<br />
:SELinux GUI tools (system-config-selinux)<br />
<br />
;{{AUR|selinux-python}} and {{AUR|selinux-python2}}<br />
:SELinux python tools and libraries (semanage, sepolgen, sepolicy, etc.)<br />
<br />
;{{AUR|selinux-sandbox}}<br />
:Sandboxing tool for SELinux<br />
<br />
;{{AUR|semodule-utils}}<br />
:Tools to handle SELinux modules when building a policy<br />
<br />
====SELinux policy packages====<br />
<br />
;{{AUR|selinux-refpolicy-src}}<br />
:Reference policy sources<br />
<br />
;{{AUR|selinux-refpolicy-git}}<br />
:Reference policy git master (https://github.com/SELinuxProject/refpolicy) built with configuration specific for Arch Linux<br />
<br />
;{{AUR|selinux-refpolicy-arch}}<br />
:Precompiled modular Reference policy with headers and documentation but without sources. Development Arch Linux Refpolicy patches included, which fixes issues related to path labeling and systemd support. These patches are also sent to Reference Policy maintainers and their inclusion in {{AUR|selinux-refpolicy-arch}} is mainly a way to perform updates between Refpolicy releases.<br />
<br />
====Other SELinux tools====<br />
<br />
;{{AUR|setools}}<br />
:CLI and GUI tools to manage SELinux<br />
<br />
;{{AUR|selinux-alpm-hook}}<br />
:pacman hook to label files accordingly to SELinux policy when installing and updating packages<br />
<br />
=== Installation ===<br />
<br />
There are two methods to install the requisite SELinux packages.<br />
<br />
==== Via AUR ====<br />
<br />
* First, install SELinux userspace tools and libraries, in this order (because of the dependencies): {{AUR|libsepol}}, {{AUR|libselinux}}, {{AUR|secilc}}, {{AUR|checkpolicy}}, {{AUR|setools}}, {{AUR|libsemanage}}, {{AUR|semodule-utils}}, {{AUR|policycoreutils}}, {{AUR|selinux-python}} (which depends on {{AUR|python-ipy}}), {{AUR|mcstrans}} and {{AUR|restorecond}}.<br />
* Then install {{AUR|pambase-selinux}} and {{AUR|pam-selinux}} and make sure you can login again after the installation completed, because files in {{ic|/etc/pam.d/}} got removed and created when {{pkg|pambase}} got replaced with {{AUR|pambase-selinux}}.<br />
* Next you can recompile some core packages by installing: {{AUR|coreutils-selinux}}, {{AUR|findutils-selinux}}, {{AUR|iproute2-selinux}}, {{AUR|logrotate-selinux}}, {{AUR|openssh-selinux}}, {{AUR|psmisc-selinux}}, {{AUR|shadow-selinux}}, {{AUR|cronie-selinux}}<br />
* Next, backup your {{ic|/etc/sudoers}} file. Install {{AUR|sudo-selinux}} and restore your {{ic|/etc/sudoers}} (it is overridden when this package is installed as a replacement of {{pkg|sudo}}).<br />
* Next come util-linux and systemd. Because of a cyclic makedepends between these two packages which will not be fixed ({{bug|39767}}), you need to build the source package {{AUR|systemd-selinux}}, install {{AUR|libsystemd-selinux}}{{Broken package link|package not found}}, build and install {{AUR|util-linux-selinux}} (with {{AUR|libutil-linux-selinux}}) and rebuild and install {{AUR|systemd-selinux}}.<br />
* Next, install {{AUR|dbus-selinux}}.<br />
* Next, install {{AUR|selinux-alpm-hook}} in order to run restorecon every time pacman installs a package.<br />
<br />
After all these steps, you can install a SELinux kernel (like {{AUR|linux-selinux}}) and a policy (like {{AUR|selinux-refpolicy-arch}} or {{AUR|selinux-refpolicy-git}}).<br />
<br />
==== Using the GitHub repository ====<br />
<br />
All packages are maintained at https://github.com/archlinuxhardened/selinux . This repository also contains a script named {{ic|build_and_install_all.sh}} which builds and installs (or updates) all packages in the needed order. Here is an example of a way this script can be used in a user shell to install all packages (with downloading the GPG keys which are used to verify the source tarballs of the package):<br />
<br />
git clone https://github.com/archlinuxhardened/selinux<br />
cd selinux<br />
./recv_gpg_keys.sh<br />
./build_and_install_all.sh<br />
<br />
Of course, it is possible to modify the content of {{ic|build_and_install_all.sh}} before running it, for example if you already have SELinux support in your kernel.<br />
<br />
===Changing boot loader configuration===<br />
<br />
If you have installed a new kernel, make sure that you update your bootloader accordingly to boot on it. Moreover you may need to add {{ic|<nowiki>security=selinux selinux=1</nowiki>}} to the kernel command line. More precisely, if the kernel configuration does not set {{ic|CONFIG_DEFAULT_SECURITY_SELINUX}}, {{ic|<nowiki>security=selinux</nowiki>}} is needed, and if it contains {{ic|<nowiki>CONFIG_SECURITY_SELINUX_BOOTPARAM=y</nowiki>}} {{ic|<nowiki>CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE=0</nowiki>}}, {{ic|<nowiki>selinux=1</nowiki>}} is needed.<br />
<br />
====GRUB====<br />
<br />
Add {{ic|<nowiki>security=selinux selinux=1</nowiki>}} to {{ic|GRUB_CMDLINE_LINUX_DEFAULT}} variable in {{ic|/etc/default/grub}}<br />
Run the following command:<br />
<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
====Syslinux====<br />
<br />
Change your syslinux.cfg file by adding:<br />
<br />
{{hc|/boot/syslinux/syslinux.cfg|<nowiki>LABEL arch-selinux<br />
LINUX ../vmlinuz-linux-selinux<br />
APPEND root=/dev/sda2 ro security=selinux selinux=1<br />
INITRD ../initramfs-linux-selinux.img</nowiki>}}<br />
<br />
at the end. Change "linux-selinux" to whatever kernel you are using.<br />
<br />
====systemd-boot====<br />
<br />
Create a new loader entry, for example in {{ic|/boot/loader/entries/arch-selinux.conf}}:<br />
<br />
{{hc|/boot/loader/entries/arch-selinux.conf|2=<br />
title Arch Linux SELinux<br />
linux /vmlinuz-linux-selinux<br />
initrd /initramfs-linux-selinux.img<br />
options root=/dev/sda2 ro selinux=1 security=selinux<br />
}}<br />
<br />
===Checking PAM===<br />
<br />
A correctly set-up [[PAM]] is important to get the proper security context after login. Check for the presence of the following lines in {{ic|/etc/pam.d/system-login}}:<br />
<br />
{{bc|# pam_selinux.so close should be the first session rule<br />
session required pam_selinux.so close}}<br />
<br />
{{bc|# pam_selinux.so open should only be followed by sessions to be executed in the user context<br />
session required pam_selinux.so open}}<br />
<br />
===Installing a policy===<br />
<br />
{{Warning|The reference policy as given by [https://github.com/SELinuxProject/refpolicy/wiki SELinuxProject] is not very good for Arch Linux, as before release 20170805 almost no file were labelled correctly. The major problems were:<br />
<br />
* {{ic|/lib}} and {{ic|/usr/lib}} were considered different (and also {{ic|/bin}}, {{ic|/sbin}}, {{ic|/usr/bin}} and {{ic|/usr/sbin}}). This introduced some instability when applying labels to the whole system, as files in these folders might be seen with 2 (or 4) different labels. <br />
* systemd was not yet supported (C. PeBenito, main developer of the refpolicy, announced its willingness to work on it in its github repository in October 2014, http://oss.tresys.com/pipermail/refpolicy/2014-October/007430.html)<br />
<br />
Since refpolicy release 20170805 these two points have been addressed, but most people submitting patches to improve the policy use an other distribution (Debian, Gentoo, RHEL, etc.). Therefore the compatibility with Arch Linux packages is not perfect (for example the policy may not support the most recent features of a program). }}<br />
<br />
Policies are the mainstay of SELinux. They are what govern its behaviour. The only policy currently available in the AUR is the Reference Policy. In order to install it, you should use the source files, which may be got from the package {{AUR|selinux-refpolicy-src}} or by downloading the latest release on https://github.com/SELinuxProject/refpolicy/wiki/DownloadRelease#current-release. When using the AUR package, navigate to {{ic|/etc/selinux/refpolicy/src/policy}} and run the following commands:<br />
<br />
{{bc|# make bare<br />
# make conf<br />
# make install}}<br />
<br />
to install the reference policy as it is. Those who know how to write SELinux policies can tweak them to their heart's content before running the commands written above. The command takes a while to do its job and taxes one core of your system completely, so do not worry. Just sit back and let the command run for as long as it takes.<br />
<br />
To load the reference policy run:<br />
{{bc|# make load}}<br />
<br />
Then, make the file {{ic|/etc/selinux/config}} with the following contents (Only works if you used the defaults as mentioned above. If you decided to change the name of the policy, you need to tweak the file):<br />
<br />
{{hc|/etc/selinux/config|<nowiki># This file controls the state of SELinux on the system.<br />
# SELINUX= can take one of these three values:<br />
# enforcing - SELinux security policy is enforced.<br />
# Set this value once you know for sure that SELinux is configured the way you like it and that your system is ready for deployment<br />
# permissive - SELinux prints warnings instead of enforcing.<br />
# Use this to customise your SELinux policies and booleans prior to deployment. Recommended during policy development.<br />
# disabled - No SELinux policy is loaded.<br />
# This is not a recommended setting, for it may cause problems with file labelling<br />
SELINUX=permissive<br />
# SELINUXTYPE= takes the name of SELinux policy to<br />
# be used. Current options are:<br />
# refpolicy (vanilla reference policy)<br />
# <custompolicy> - Substitute <custompolicy> with the name of any custom policy you choose to load<br />
SELINUXTYPE=refpolicy</nowiki>}}<br />
<br />
Now, you may reboot. After rebooting, run:<br />
<br />
# restorecon -r /<br />
<br />
to label your filesystem.<br />
<br />
Now, make a file {{ic|requiredmod.te}} with the contents:<br />
<br />
{{hc|requiredmod.te|<nowiki>module requiredmod 1.0;<br />
<br />
require {<br />
type devpts_t;<br />
type kernel_t;<br />
type device_t;<br />
type var_run_t;<br />
type udev_t;<br />
type hugetlbfs_t;<br />
type udev_tbl_t;<br />
type tmpfs_t;<br />
class sock_file write;<br />
class unix_stream_socket { read write ioctl };<br />
class capability2 block_suspend;<br />
class dir { write add_name };<br />
class filesystem associate;<br />
}<br />
<br />
#============= devpts_t ==============<br />
allow devpts_t device_t:filesystem associate;<br />
<br />
#============= hugetlbfs_t ==============<br />
allow hugetlbfs_t device_t:filesystem associate;<br />
<br />
#============= kernel_t ==============<br />
allow kernel_t self:capability2 block_suspend;<br />
<br />
#============= tmpfs_t ==============<br />
allow tmpfs_t device_t:filesystem associate;<br />
<br />
#============= udev_t ==============<br />
allow udev_t kernel_t:unix_stream_socket { read write ioctl };<br />
allow udev_t udev_tbl_t:dir { write add_name };<br />
allow udev_t var_run_t:sock_file write;</nowiki>}}<br />
<br />
and run the following commands:<br />
<br />
{{bc|<nowiki># checkmodule -m -o requiredmod.mod requiredmod.te<br />
# semodule_package -o requiredmod.pp -m requiredmod.mod<br />
# semodule -i requiredmod.pp</nowiki>}}<br />
<br />
This is required to remove a few messages from {{ic|/var/log/audit/audit.log}} which are a nuisance to deal with in the reference policy. This is an ugly hack and it should be made very clear that the policy so installed simply patches the reference policy in order to hide the effects of incorrect labelling.<br />
<br />
===Testing in a Vagrant virtual machine===<br />
<br />
It is possible to use [[Vagrant]] to provision a virtual Arch Linux machine with SELinux configured. This is a convenient way to test an Arch Linux system running SELinux without modifying a current system. Here are commands which can be used to achieve this:<br />
<br />
git clone https://github.com/archlinuxhardened/selinux<br />
cd selinux/_vagrant<br />
vagrant up<br />
vagrant ssh<br />
<br />
==Post-installation steps==<br />
<br />
You can check that SELinux is working with {{ic|sestatus}}. You should get something like:<br />
<br />
{{bc|<nowiki>SELinux status: enabled<br />
SELinuxfs mount: /sys/fs/selinux<br />
SELinux root directory: /etc/selinux<br />
Loaded policy name: refpolicy<br />
Current mode: permissive<br />
Mode from config file: permissive<br />
Policy MLS status: disabled<br />
Policy deny_unknown status: allowed<br />
Max kernel policy version: 28</nowiki>}}<br />
<br />
To maintain correct context, you can use ''restorecond'':<br />
<br />
# systemctl enable restorecond<br />
<br />
To switch to enforcing mode without rebooting, you can use:<br />
<br />
# echo 1 > /sys/fs/selinux/enforce<br />
<br />
===Swapfiles===<br />
<br />
If you have a swap file instead of a swap partition, issue the following commands in order to set the appropriate security context:<br />
<br />
{{bc|# semanage fcontext -a -t swapfile_t "/path/to/swapfile"<br />
# restorecon /path/to/swapfile}}<br />
<br />
==Working with SELinux==<br />
<br />
SELinux defines security using a different mechanism than traditional Unix access controls. The best way to understand it is by example. For example, the SELinux security context of the apache homepage looks like the following:<br />
<br />
$ls -lZ /var/www/html/index.html<br />
-rw-r--r-- username username system_u:object_r:httpd_sys_content_t /var/www/html/index.html<br />
<br />
The first three and the last columns should be familiar to any (Arch) Linux user. The fourth column is new and has the format:<br />
<br />
user:role:type[:level]<br />
<br />
To explain:<br />
#'''User:''' The SELinux user identity. This can be associated to one or more roles that the SELinux user is allowed to use.<br />
#'''Role:''' The SELinux role. This can be associated to one or more types the SELinux user is allowed to access.<br />
#'''Type:''' When a type is associated with a process, it defines what processes (or domains) the SELinux user (the subject) can access. When a type is associated with an object, it defines what access permissions the SELinux user has to that object.<br />
#'''Level:''' This optional field can also be know as a range and is only present if the policy supports MCS or MLS.<br />
<br />
This is important in case you wish to understand how to build your own policies, for these are the basic building blocks of SELinux. However, for most purposes, there is no need to, for the reference policy is sufficiently mature. However, if you are a power user or someone with very specific needs, then it might be ideal for you to learn how to make your own SELinux policies.<br />
<br />
[http://www.fosteringlinux.com/tag/selinux/ This] is a great series of articles for someone seeking to understand how to work with SELinux.<br />
<br />
==Troubleshooting==<br />
<br />
The place to look for SELinux errors is the [[systemd journal]]. In order to see SELinux messages related to the label {{ic|system_u:system_r:policykit_t:s0}} (for example), you would need to run:<br />
<br />
# journalctl _SELINUX_CONTEXT=system_u:system_r:policykit_t:s0<br />
<br />
===Useful tools===<br />
<br />
There are some tools/commands that can greatly help with SELinux. <br />
<br />
;restorecon: Restores the context of a file/directory (or recursively with {{ic|-R}}) based on any policy rules <br />
;chcon: Change the context on a specific file<br />
<br />
===Reporting issues===<br />
<br />
Please report issues on GitHub: https://github.com/archlinuxhardened/selinux/issues<br />
<br />
==See also==<br />
* [[wikipedia:Security-Enhanced_Linux|Security Enhanced Linux]]<br />
* [https://wiki.gentoo.org/wiki/SELinux Gentoo SELinux Handbook]<br />
* [https://fedoraproject.org/wiki/SELinux Fedora Project's SELinux Wiki]<br />
* [https://www.nsa.gov/what-we-do/research/selinux/ NSA's Official SELinux Homepage]<br />
* [https://github.com/SELinuxProject SELinux Project Homepage]<br />
** [https://github.com/SELinuxProject/refpolicy/wiki Reference Policy Homepage]<br />
** [https://github.com/SELinuxProject/setools/wiki SETools Homepage]<br />
* [https://web.archive.org/web/20140816115906/http://jamesthebard.net/archlinux-selinux-and-you-a-trip-down-the-rabbit-hole/ ArchLinux, SELinux and You (archived)]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Makepkg&diff=566438Makepkg2019-02-12T12:06:08Z<p>Teples: /* CFLAGS/CXXFLAGS in makepkg.conf do not work for QMAKE based packages */ Add also LDFLAGS accordingly</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Package development]]<br />
[[Category:About Arch]]<br />
[[Category:Commands]]<br />
[[ar:Makepkg]]<br />
[[el:Makepkg]]<br />
[[es:Makepkg]]<br />
[[fa:Makepkg]]<br />
[[fr:makepkg]]<br />
[[it:Makepkg]]<br />
[[ja:Makepkg]]<br />
[[nl:Makepkg]]<br />
[[pt:Makepkg]]<br />
[[ru:Makepkg]]<br />
[[sr:Makepkg]]<br />
[[zh-hans:Makepkg]]<br />
{{Related articles start}}<br />
{{Related|Creating packages}}<br />
{{Related|PKGBUILD}}<br />
{{Related|.SRCINFO}}<br />
{{Related|Arch User Repository}}<br />
{{Related|pacman}}<br />
{{Related|Official repositories}}<br />
{{Related|Arch Build System}}<br />
{{Related articles end}}<br />
<br />
[https://projects.archlinux.org/pacman.git/tree/scripts/makepkg.sh.in makepkg] is a script to automate the building of packages. The requirements for using the script are a build-capable Unix platform and a [[PKGBUILD]].<br />
<br />
''makepkg'' is provided by the {{Pkg|pacman}} package.<br />
<br />
== Configuration ==<br />
<br />
See {{man|5|makepkg.conf}} for details on configuration options for ''makepkg''.<br />
<br />
The system configuration is available in {{ic|/etc/makepkg.conf}}, but user-specific changes can be made in {{ic|$XDG_CONFIG_HOME/pacman/makepkg.conf}} or {{ic|~/.makepkg.conf}}. It is recommended to review the configuration prior to building packages.<br />
<br />
=== Packager information ===<br />
<br />
Each package is tagged with metadata identifying amongst others also the ''packager''. By default, user-compiled packages are marked with {{ic|Unknown Packager}}. If multiple users will be compiling packages on a system, or you are otherwise distributing your packages to other users, it is convenient to provide real contact. This can be done by setting the {{ic|PACKAGER}} variable in {{ic|makepkg.conf}}.<br />
<br />
To check this on an installed package:<br />
<br />
{{hc|$ pacman -Qi ''package''|<nowiki><br />
...<br />
Packager : John Doe <john@doe.com><br />
...<br />
</nowiki>}}<br />
<br />
To automatically produce signed packages, also set the {{ic|GPGKEY}} variable in {{ic|makepkg.conf}}.<br />
<br />
=== Package output ===<br />
<br />
By default, ''makepkg'' creates the package tarballs in the working directory and downloads source data directly to the {{ic|src/}} directory. Custom paths can be configured, for example to keep all built packages in {{ic|~/build/packages/}} and all sources in {{ic|~/build/sources/}}.<br />
<br />
Configure the following {{ic|makepkg.conf}} variables if needed:<br />
<br />
* {{ic|PKGDEST}} &mdash; directory for storing resulting packages<br />
* {{ic|SRCDEST}} &mdash; directory for storing [[PKGBUILD#source|source]] data (symbolic links will be placed to {{ic|src/}} if it points elsewhere)<br />
* {{ic|SRCPKGDEST}} &mdash; directory for storing resulting source packages (built with {{ic|makepkg -S}})<br />
<br />
{{Tip|The {{ic|PKGDEST}} directory can be cleaned up with e.g. {{ic|paccache -c ~/build/packages/}} as described in [[pacman#Cleaning the package cache]].}}<br />
<br />
=== Signature checking ===<br />
<br />
{{Note|The signature checking implemented in ''makepkg'' does not use pacman's keyring, instead relying on the user's keyring.[http://allanmcrae.com/2015/01/two-pgp-keyrings-for-package-management-in-arch-linux/]}}<br />
<br />
If a signature file in the form of ''.sig'' or ''.asc'' is part of the [[PKGBUILD]] source array, ''makepkg'' automatically attempts to [[GnuPG#Verify a signature|verify]] it. In case the user's keyring does not contain the needed public key for signature verification, ''makepkg'' will abort the installation with a message that the PGP key could not be verified. <br />
<br />
If a needed public key for a package is missing, the [[PKGBUILD]] will most likely contain a [[PKGBUILD#validpgpkeys|validpgpkeys]] entry with the required key IDs. You can [[GnuPG#Import_a_public_key|import]] it manually, or you can find it [[GnuPG#Use_a_keyserver|on a keyserver]] and import it from there.<br />
<br />
== Usage ==<br />
Before continuing, [[install]] the {{Grp|base-devel}} group. Packages belonging to this group are '''not''' required to be listed as build-time dependencies (''makedepends'') in [[PKGBUILD]] files. In addition, the {{Grp|base}} group is assumed to be installed on '''all''' Arch systems.<br />
<br />
{{Note|<br />
* Make sure [[sudo]] is configured properly for commands passed to [[pacman]].<br />
* Running ''makepkg'' itself as root is [https://lists.archlinux.org/pipermail/pacman-dev/2014-March/018911.html disallowed].[https://projects.archlinux.org/pacman.git/tree/NEWS] Besides how a {{ic|PKGBUILD}} may contain arbitrary commands, building as root is generally considered unsafe.[https://bbs.archlinux.org/viewtopic.php?id&#61;67561] Users who have no access to a regular user account should run makepkg as the [http://allanmcrae.com/2015/01/replacing-makepkg-asroot/ nobody user].<br />
}}<br />
<br />
To build a package, one must first create a [[PKGBUILD]], or build script, as described in [[Creating packages]]. Existing scripts are available from the [[Arch Build System]] ''(ABS)'' tree or the [[AUR]]. Once in possession of a {{ic|PKGBUILD}}, change to the directory where it is saved and run the following command to build the package:<br />
<br />
$ makepkg<br />
<br />
If required dependencies are missing, ''makepkg'' will issue a warning before failing. To build the package and install needed dependencies, add the flag {{ic|-s}}/{{ic|--syncdeps}}:<br />
<br />
$ makepkg --syncdeps<br />
<br />
Adding the {{ic|-r}}/{{ic|--rmdeps}} flag causes ''makepkg'' to remove the make dependencies later, which are no longer needed. If constantly building packages, consider using [[Pacman/Tips and tricks#Removing unused packages (orphans)]] once in a while instead.<br />
<br />
{{Note|<br />
* These dependencies must be available in the configured repositories; see [[pacman#Repositories and mirrors]] for details. Alternatively, one can manually install dependencies prior to building ({{ic|pacman -S --asdeps ''dep1'' ''dep2''}}).<br />
* Only global values are used when installing dependencies, i.e any override done in a split package's packaging function will not be used. [https://patchwork.archlinux.org/patch/2271/]}}<br />
<br />
Once all dependencies are satisfied and the package builds successfully, a package file ({{ic|''pkgname''-''pkgver''.pkg.tar.xz}}) will be created in the working directory. To install, use {{ic|-i}}/{{ic|--install}} (same as {{ic|pacman -U ''pkgname''-''pkgver''.pkg.tar.xz}}):<br />
<br />
$ makepkg --install<br />
<br />
To clean up leftover files and folders, such as files extracted to the {{ic|$srcdir}}, add the option {{ic|-c}}/{{ic|--clean}}. This is useful for multiple builds of the same package or updating the package version, while using the same build folder. It prevents obsolete and remnant files from carrying over to the new builds:<br />
<br />
$ makepkg --clean<br />
<br />
For more, see [https://www.archlinux.org/pacman/makepkg.8.html makepkg(8)].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Building optimized binaries ===<br />
<br />
A performance improvement of the packaged software can be achieved by enabling compiler optimizations for the host machine. The downside is that binaries compiled for a specific processor architecture will not run correctly on other machines. On x86_64 machines, there are rarely significant enough real world performance gains that would warrant investing the time to rebuild official packages.<br />
<br />
However, it is very easy to reduce performance by using "nonstandard" compiler flags. Many compiler optimizations are only useful in certain situations and should not be indiscriminately applied to every package. Unless you can verify/benchmark that something is faster, there is a very good chance it is not! The Gentoo [http://www.gentoo.org/doc/en/gcc-optimization.xml Compilation Optimization Guide] and [http://wiki.gentoo.org/wiki/Safe_CFLAGS Safe CFLAGS] wiki article provide more in-depth information about compiler optimization.<br />
<br />
The options passed to a C/C++ compiler (e.g. {{Pkg|gcc}} or {{Pkg|clang}}) are controlled by the {{ic|CFLAGS}}, {{ic|CXXFLAGS}}, and {{ic|CPPFLAGS}} environment variables. For use in the Arch build system, ''makepkg'' exposes these environment variables as configuration options in {{ic|makepkg.conf}}. The default values are configured to produce generic binaries that can be installed on a wide range of machines.<br />
<br />
{{Note|<br />
* Keep in mind that not all build systems use the variables configured in {{ic|makepkg.conf}}. For example, ''cmake'' disregards the preprocessor options environment variable, {{ic|CPPFLAGS}}. Consequently, many [[PKGBUILD]]s contain workarounds with options specific to the build system used by the packaged software.<br />
* The configuration provided with the source code in the {{ic|Makefile}} or a specific argument in the compilation command line takes precedence and can potentially override the one in {{ic|makepkg.conf}}.<br />
}}<br />
<br />
GCC can automatically detect and enable safe architecture-specific optimizations. To use this feature, first remove any {{ic|-march}} and {{ic|-mtune}} flags, then add {{ic|1=-march=native}}. For example:<br />
{{hc|/etc/makepkg.conf|2=<br />
CFLAGS="'''-march=native''' -O2 -pipe -fstack-protector-strong -fno-plt"<br />
CXXFLAGS="${CFLAGS}"}}<br />
To see what flags this enables on your machine, run:<br />
<br />
$ gcc -march=native -v -Q --help=target<br />
<br />
{{Note|1=If you specify different value than {{ic|1=-march=native}}, then {{ic|1=-Q --help=target}} '''will not''' work as expected.[https://bbs.archlinux.org/viewtopic.php?pid=1616694#p1616694] You need to go through a compilation phase to find out which options are really enabled. See [https://wiki.gentoo.org/wiki/Safe_CFLAGS#Find_CPU-specific_options Find CPU-specific options] on Gentoo wiki for instructions.<br />
}}<br />
<br />
=== Improving compile times ===<br />
==== Parallel compilation ====<br />
<br />
The {{Pkg|make}} build system uses the {{ic|MAKEFLAGS}} [[environment variable]] to specify additional options for ''make''. The variable can also be set in the {{ic|makepkg.conf}} file.<br />
<br />
Users with multi-core/multi-processor systems can specify the number of jobs to run simultaneously. This can be accomplished with the use of ''nproc'' to determine the number of available processors, e.g. {{ic|1=MAKEFLAGS="-j$(nproc)"}}. Some [[PKGBUILD]]s specifically override this with {{ic|-j1}}, because of race conditions in certain versions or simply because it is not supported in the first place. Packages that fail to build because of this should be [[Reporting bug guidelines|reported]] on the bug tracker (or in the case of [[AUR]] packages, to the package maintainer) after making sure that the error is indeed being caused by your {{ic|MAKEFLAGS}}.<br />
<br />
See {{man|1|make}} for a complete list of available options.<br />
<br />
==== Building from files in memory ====<br />
<br />
As compiling requires many I/O operations and handling of small files, moving the working directory to a [[tmpfs]] may bring improvements in build times. <br />
<br />
The {{ic|BUILDDIR}} variable can be temporarily exported to ''makepkg'' to set the build directory to an existing tmpfs. For example:<br />
<br />
$ BUILDDIR=/tmp/makepkg makepkg<br />
<br />
Persistent configuration can be done in {{ic|makepkg.conf}} by uncommenting the {{ic|BUILDDIR}} option, which is found at the end of the {{ic|BUILD ENVIRONMENT}} section in the default {{ic|/etc/makepkg.conf}} file. Setting its value to e.g. {{ic|1=BUILDDIR=/tmp/makepkg}} will make use of the Arch's default {{ic|/tmp}} temporary file system.<br />
<br />
{{Note|<br />
* Avoid compiling larger packages in tmpfs to prevent running out of memory.<br />
* The tmpfs folder must be mounted without the {{ic|noexec}} option, otherwise it will prevent built binaries from being executed.<br />
* Keep in mind that packages compiled in tmpfs will not persist across reboot. Consider setting the [[#Package output|PKGDEST]] option appropriately to move the built package automatically to a persistent directory.<br />
}}<br />
<br />
==== Using a compilation cache ====<br />
<br />
The use of [[ccache]] can improve build times by caching the results of compilations for successive use.<br />
<br />
=== Generate new checksums ===<br />
Install {{Pkg|pacman-contrib}} and run the following command in the same directory as the PKGBUILD file to generate new checksums:<br />
$ updpkgsums<br />
<br />
The checksums can also be obtained with e.g {{ic|sha256sum}} and added to the {{ic|sha256sums}} array by hand.<br />
<br />
=== Use other compression algorithms ===<br />
<br />
To speed up both packaging and installation, with the tradeoff of having larger package archives, you can change {{ic|PKGEXT}}. For example, the following makes the package archive uncompressed for only one invocation:<br />
<br />
$ PKGEXT='.pkg.tar' makepkg<br />
<br />
As another example, the following uses the lzop algorithm, with the {{pkg|lzop}} package required:<br />
<br />
$ PKGEXT='.pkg.tar.lzo' makepkg<br />
<br />
To make one of these settings permanent, set {{ic|PKGEXT}} in {{ic|/etc/makepkg.conf}}.<br />
<br />
=== Utilizing multiple cores on compression ===<br />
{{pkg|xz}} supports [[Wikipedia:Symmetric multiprocessing|symmetric multiprocessing (SMP)]] via the {{ic|--threads}} flag to speed up compression. For example, to let makepkg use as many CPU cores as possible to compress packages, edit {{ic|COMPRESSXZ}} array in {{ic|/etc/makepkg.conf}}:<br />
<br />
COMPRESSXZ=(xz -c -z - '''--threads=0''')<br />
<br />
{{pkg|pigz}} is a drop-in, parallel implementation for {{pkg|gzip}} which by default uses all available CPU cores (the {{ic|-p/--processes}} flag can be used to employ less cores):<br />
<br />
COMPRESSGZ=('''pigz''' -c -f -n)<br />
<br />
=== Show packages with specific packager ===<br />
<br />
This shows all packages installed on the system with the packager named ''packagername'':<br />
<br />
$ expac "%n %p" | grep "''packagername''" | column -t<br />
<br />
This shows all packages installed on the system with the packager set in the {{ic|/etc/makepkg}} variable {{ic|PACKAGER}}. This shows only packages that are in a repository defined in {{ic|/etc/pacman.conf}}.<br />
<br />
$ . /etc/makepkg.conf; grep -xvFf <(pacman -Qqm) <(expac "%n\t%p" | grep "$PACKAGER$" | cut -f1)<br />
<br />
=== Build 32-bit packages on a 64-bit system ===<br />
{{merge|Building 32-bit packages on a 64-bit system}}<br />
{{out of date|The [[Install bundled 32-bit system in 64-bit system]] article has been archived}}<br />
{{Warning|Errors have been reported when using this method to build the {{Pkg|linux}} package. The [[Install bundled 32-bit system in 64-bit system|chroot method]] is preferred and has been verified to work for building the kernel packages.}}<br />
<br />
First, enable the [[multilib]] repository and [[install]] {{Grp|multilib-devel}}.<br />
<br />
Then create a 32-bit configuration file<br />
<br />
{{hc|~/.makepkg.i686.conf|<nowiki><br />
CARCH="i686"<br />
CHOST="i686-unknown-linux-gnu"<br />
CFLAGS="-m32 -march=i686 -mtune=generic -O2 -pipe -fstack-protector-strong"<br />
CXXFLAGS="${CFLAGS}"<br />
LDFLAGS="-m32 -Wl,-O1,--sort-common,--as-needed,-z,relro"</nowiki>}}<br />
<br />
and invoke makepkg as such<br />
$ linux32 makepkg --config ~/.makepkg.i686.conf<br />
<br />
== Troubleshooting ==<br />
<br />
=== Makepkg sometimes fails to sign a package without asking for signature passphrase ===<br />
<br />
With [https://www.gnupg.org/faq/whats-new-in-2.1.html gnupg 2.1], gpg-agent is now started 'on-the-fly' by gpg. The problem arises in the package stage of {{ic|makepkg --sign}}. To allow for the correct privileges, {{pkg|fakeroot}} runs the {{ic|package()}} function thereby starting gpg-agent within the same fakeroot environment. On exit, the fakeroot cleanups semaphores causing the 'write' end of the pipe to close for that instance of gpg-agent which will result in a broken pipe error. If the same gpg-agent is running when {{ic|makepkg --sign}} is next executed, then gpg-agent returns exit code 2; so the following output occurs:<br />
<br />
==> Signing package...<br />
==> WARNING: Failed to sign package file.<br />
<br />
This bug is currently being tracked: {{Bug|49946}}. A temporary workaround for this issue is to run {{ic|killall gpg-agent && makepkg --sign}} instead. This issue is resolved within {{aur|pacman-git}}, specifically at commit hash {{ic|c6b04c04653ba9933fe978829148312e412a9ea7}}<br />
<br />
=== CFLAGS/CXXFLAGS/LDFLAGS in makepkg.conf do not work for CMake based packages ===<br />
<br />
In order to let CMake use the variables defined in {{ic|makepkg.conf}}, simply do not specify the {{ic|-DCMAKE_BUILD_TYPE}} flag when configuring a cmake project. [https://lists.archlinux.org/pipermail/arch-dev-public/2018-March/029181.html]<br />
<br />
This will cause cmake to use a build type of {{ic|None}} which then uses the environmental variables such as {{ic|CFLAGS}}, {{ic|CPPFLAGS}}, etc.<br />
<br />
=== CFLAGS/CXXFLAGS/LDFLAGS in makepkg.conf do not work for QMAKE based packages ===<br />
Qmake automatically sets the variable {{ic|CFLAGS}}, {{ic|CXXFLAGS}} and {{ic|LDFLAGS}} according to what it thinks should be the right configuration. In order to let qmake use the variables defined in the makepkg configuration file, you must edit the PKGBUILD and pass the variables [https://doc.qt.io/qt-5/qmake-variable-reference.html#qmake-cflags QMAKE_CFLAGS], [https://doc.qt.io/qt-5/qmake-variable-reference.html#qmake-cxxflags QMAKE_CXXFLAGS] AND [https://doc.qt.io/qt-5/qmake-variable-reference.html#qmake-lflags QMAKE_LFLAGS]to qmake. For example:<br />
<br />
{{hc|PKGBUILD|<nowiki><br />
...<br />
<br />
build() {<br />
cd "$srcdir/$_pkgname-$pkgver-src"<br />
qmake-qt5 "$srcdir/$_pkgname-$pkgver-src/$_pkgname.pro" \<br />
PREFIX=/usr \<br />
QMAKE_CFLAGS="${CFLAGS}" \<br />
QMAKE_CXXFLAGS="${CXXFLAGS}" \<br />
QMAKE_LFLAGS="${LDFLAGS}"<br />
<br />
make<br />
}<br />
<br />
...<br />
</nowiki>}}<br />
<br />
Alternatively, for a system wide configuration, you can create your own {{ic|qmake.conf}} and set the [https://doc.qt.io/qt-5/qmake-environment-reference.html#qmakespec QMAKESPEC] environment variable.<br />
<br />
=== Specifying install directory for QMAKE based packages ===<br />
The makefile generated by qmake uses the environment variable INSTALL_ROOT to specify where the program should be installed. Thus this package function should work:<br />
<br />
{{hc|PKGBUILD|<nowiki><br />
...<br />
<br />
package() {<br />
cd "$srcdir/${pkgname%-git}"<br />
make INSTALL_ROOT="$pkgdir" install<br />
}<br />
<br />
...<br />
</nowiki>}}<br />
<br />
Note, that qmake also has to be configured appropriately. For example put this in your .pro file:<br />
<br />
{{hc|YourProject.pro|<nowiki><br />
...<br />
<br />
target.path = /usr/local/bin<br />
INSTALLS += target<br />
<br />
...<br />
</nowiki>}}<br />
<br />
=== WARNING: Package contains reference to $srcdir ===<br />
<br />
Somehow, the literal strings {{ic|$srcdir}} or {{ic|$pkgdir}} ended up in one of the installed files in your package.<br />
<br />
To identify which files, run the following from the ''makepkg'' build directory:<br />
$ grep -R "$(pwd)/src" pkg/<br />
<br />
=== Makepkg fails to download dependencies when behind proxy ===<br />
<br />
When ''makepkg'' calls dependencies, it calls pacman to install the packages, which requires administrative privileges via ''sudo''. However, ''sudo'' does not pass any [[environment variables]] to the privileged environment, and includes the proxy-related variables {{ic|ftp_proxy}}, {{ic|http_proxy}}, {{ic|https_proxy}}, and {{ic|no_proxy}}.<br />
<br />
In order to have ''makepkg'' working behind a proxy you have to do one of the following methods.<br />
<br />
==== Enable proxy by setting its URL in XferCommand ====<br />
<br />
The XferCommand can be set to use the desired proxy URL in {{ic|/etc/pacman.conf}}. Add or uncomment the following line in your {{ic|pacman.conf}}[http://www.mail-archive.com/arch-general@archlinux.org/msg15561.html]:<br />
<br />
{{hc|/etc/pacman.conf|<nowiki><br />
...<br />
XferCommand = /usr/bin/curl -x http://username:password@proxy.proxyhost.com:80 -L -C - -f -o %o %u<br />
...<br />
</nowiki>}}<br />
<br />
==== Enable proxy via sudoer's env_keep ====<br />
<br />
Alternatively, one may want to use sudoer's {{ic|env_keep}} option, which enables preserving given variables the privileged environment. See [[Sudo#Environment variables]] for more information.<br />
<br />
=== Makepkg fails, but make succeeds ===<br />
<br />
If something manually compiles using ''make'', but fails through ''makepkg'', it's almost certainly because {{ic|/etc/makepkg.conf}} sets a compilation variable to something reasonable that usually works, but that what you're compiling is incompatible with. Try adding these flags to the PKGBUILD {{ic|options}} array:<br />
<br />
{{ic|!buildflags}}, to prevent its default {{ic|CPPFLAGS}}, {{ic|CFLAGS}}, {{ic|CXXFLAGS}}, and {{ic|LDFLAGS}}.<br />
<br />
{{ic|!makeflags}}, to prevent its default {{ic|MAKEFLAGS}}, in case you've edited {{ic|/etc/makepkg.conf}} to enable parallel builds.<br />
<br />
{{ic|!debug}}, to prevent its default {{ic|DEBUG_CFLAGS}}, and {{ic|DEBUG_CXXFLAGS}}, in case your package is a debug build.<br />
<br />
If any of these fix the problem, this could indicate you can report a bug upstream, if you isolate exactly which flag is causing the problem.<br />
<br />
== See also ==<br />
<br />
* [https://www.archlinux.org/pacman/makepkg.8.html makepkg(8) Manual Page]<br />
* [https://www.archlinux.org/pacman/makepkg.conf.5.html makepkg.conf(5) Manual Page]<br />
* [https://gist.github.com/Earnestly/bebad057f40a662b5cc3 A Brief Tour of the Makepkg Process]<br />
* [https://projects.archlinux.org/pacman.git/tree/scripts/makepkg.sh.in makepkg source code]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Systemd-nspawn&diff=555151Systemd-nspawn2018-11-14T09:03:31Z<p>Teples: /* Use an X environment */ Clarify that mounting /tmp/.X11-unix read-only isn't a bug but feature</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Virtualization]]<br />
[[Category:Sandboxing]]<br />
[[es:Systemd-nspawn]]<br />
[[ja:Systemd-nspawn]]<br />
[[ru:Systemd-nspawn]]<br />
{{Related articles start}}<br />
{{Related|systemd}}<br />
{{Related|Linux Containers}}<br />
{{Related|systemd-networkd}}<br />
{{Related|Docker}}<br />
{{Related|Lxc-systemd}}<br />
{{Related articles end}}<br />
<br />
''systemd-nspawn'' is like the [[chroot]] command, but it is a ''chroot on steroids''.<br />
<br />
''systemd-nspawn'' may be used to run a command or OS in a light-weight namespace container. It is more powerful than [[chroot]] since it fully virtualizes the file system hierarchy, as well as the process tree, the various IPC subsystems and the host and domain name.<br />
<br />
''systemd-nspawn'' limits access to various kernel interfaces in the container to read-only, such as {{ic|/sys}}, {{ic|/proc/sys}} or {{ic|/sys/fs/selinux}}. Network interfaces and the system clock may not be changed from within the container. Device nodes may not be created. The host system cannot be rebooted and kernel modules may not be loaded from within the container.<br />
<br />
This mechanism differs from [[Lxc-systemd]] or [[Libvirt]]-lxc, as it is a much simpler tool to configure.<br />
<br />
== Installation ==<br />
<br />
''systemd-nspawn'' is part of and packaged with {{Pkg|systemd}}. <br />
<br />
== Examples ==<br />
<br />
=== Create and boot a minimal Arch Linux distribution in a container ===<br />
<br />
First install {{Pkg|arch-install-scripts}}.<br />
<br />
Next, create a directory to hold the container. In this example we will use {{ic|~/MyContainer}}. <br />
<br />
Next, we use pacstrap to install a basic arch-system into the container. At minimum we need to install the {{Grp|base}} group. <br />
<br />
# pacstrap -i -c ~/MyContainer base [additional pkgs/groups]<br />
<br />
{{Tip|The {{ic|-i}} option will '''avoid''' auto-confirmation of package selection. As you do not need to install the Linux kernel in the container, you can remove it from the package list selection to save space. See [[Pacman#Usage]].}}<br />
<br />
{{Note|The package {{Pkg|linux-firmware}} required by {{Pkg|linux}}, which is included in the {{Grp|base}} group and isn't necessary to run the container, causes some issues to {{ic|systemd-tmpfiles-setup.service}} during the booting process with {{ic|systemd-nspawn}}. It's possible to install the {{Grp|base}} group but excluding the {{Pkg|linux}} package and its dependencies when building the container with {{ic|# pacstrap -i -c ~/MyContainer base --ignore linux [additional pkgs/groups]}}. The {{ic|--ignore}} flag will be simply passed to {{Pkg|pacman}}. See {{Bug|46591}} for more information.}}<br />
<br />
Once your installation is finished, boot into the container:<br />
<br />
# systemd-nspawn -b -D ~/MyContainer<br />
<br />
The {{ic|-b}} option will boot the container (i.e. run {{ic|systemd}} as PID=1), instead of just running a shell, and {{ic|-D}} specifies the directory that becomes the container's root directory.<br />
<br />
After the container starts, log in as "root" with no password.<br />
<br />
The container can be powered off by running {{ic|poweroff}} from within the container. From the host, containers can be controlled by the [[#machinectl|machinectl]] tool.<br />
<br />
{{Note|To terminate the ''session'' from within the container, hold {{ic|Ctrl}} and rapidly press {{ic|]}} three times. Non-US keyboard users should use {{ic|%}} instead of {{ic|]}}.}}<br />
<br />
=== Create a Debian or Ubuntu environment ===<br />
<br />
Install {{Pkg|debootstrap}}, and one or both of {{Pkg|debian-archive-keyring}} and {{Pkg|ubuntu-keyring}} (obviously install the keyrings for the distros you want).<br />
<br />
{{Note|''systemd-nspawn'' requires that the operating system in the container has systemd running as PID 1 and ''systemd-nspawn'' is installed in the container. This means Ubuntu before 15.04 will not work out of the box and requires additional configuration to switch from upstart to systemd. Also make sure that the {{ic|systemd-container}} package is installed on the container system.}}<br />
<br />
From there it's rather easy to setup Debian or Ubuntu environments:<br />
<br />
# cd /var/lib/machines<br />
# debootstrap --include=systemd-container <codename> myContainer <repository-url><br />
<br />
For Debian valid code names are either the rolling names like "stable" and "testing" or release names like "stretch" and "sid", for Ubuntu the code name like "xenial" or "zesty" should be used. A complete list of codenames is in {{ic|/usr/share/debootstrap/scripts}}. In case of a Debian image the "repository-url" can be {{ic|http://deb.debian.org/debian/}}. For an Ubuntu image, the "repository-url" can be {{ic|http://archive.ubuntu.com/ubuntu/}}.<br />
<br />
Unlike Arch, Debian and Ubuntu will not let you login without a password on first login. To set the root password login without the '-b' option and set a password:<br />
<br />
# systemd-nspawn -D myContainer<br />
# passwd<br />
# logout<br />
<br />
If the above didn't work. One can start the container and use these commands instead:<br />
# systemd-nspawn -b -D myContainer #Starts the container<br />
# machinectl shell root@myContainer /bin/bash #Get a root bash shell<br />
# passwd<br />
# logout<br />
<br />
=== Creating private users (unprivileged containers) ===<br />
<br />
''systemd-nspawn'' supports unprivileged containers, though the containers need to be booted as root.<br />
<br />
{{Note|This feature requires {{man|7|user_namespaces}}, for further info see [[Linux Containers#Enable support to run unprivileged containers (optional)]]}}<br />
<br />
The easiest way to do this is to let ''systemd-nspawn'' decide everything:<br />
<br />
# systemd-nspawn -UD myContainer<br />
# passwd<br />
# logout<br />
# systemd-nspawn -bUD myContainer<br />
<br />
Here ''systemd-nspawn'' will see if the owner of the directory is being used, if not it will use that as base and 65536 IDs above it. On the other hand if the UID/GID is in use it will randomly pick an unused range of 65536 IDs from 524288 - 1878982656 and use them.<br />
<br />
{{Note|<br />
* The base of the range chosen is always a multiple of 65536.<br />
* {{ic|-U}} and {{ic|1=--private-users=pick}} is the same, if kernel supports user namespaces. {{ic|1=--private-users=pick}} also implies {{ic|1=--private-users-chown}}, see {{man|1|systemd-nspawn}} for details.<br />
}}<br />
<br />
You can also specify the UID/GID of the container manually:<br />
<br />
# systemd-nspawn -D myContainer --private-users=1354956800:65536 --private-users-chown<br />
# passwd<br />
# logout<br />
# systemd-nspawn -bUD myContainer<br />
<br />
While booting the container you could still use {{ic|1=--private-users=1354956800:65536}} with {{ic|--private-users-chown}}, but it is unnecessarily complicated, let {{ic|-U}} handle it after the assigning the IDs.<br />
<br />
=== Enable container on boot ===<br />
<br />
When using a container frequently, you may want to start it on boot.<br />
<br />
First [[enable]] the {{ic|machines.target}} target, then {{ic|systemd-nspawn@''myContainer''.service}}, where {{ic|myContainer}} is an nspawn container in {{ic|/var/lib/machines}}.<br />
<br />
{{Tip|To customize the startup of a container, edit {{ic|/etc/systemd/nspawn/''myContainer''.nspawn}}. See {{man|5|systemd.nspawn}} for all options.}}<br />
<br />
=== Build and test packages ===<br />
<br />
See [[Creating packages for other distributions]] for example uses.<br />
<br />
== Management ==<br />
<br />
=== machinectl ===<br />
<br />
{{Note|The ''machinectl'' tool requires [[systemd]] and {{Pkg|dbus}} to be installed in the container. See [https://github.com/systemd/systemd/issues/685] for detailed discussion.}}<br />
<br />
Managing your containers is essentially done with the {{ic|machinectl}} command. See {{man|1|machinectl}} for details.<br />
<br />
Examples:<br />
<br />
Spawn a new shell inside a running container: <br />
<br />
$ machinectl login ''MyContainer''<br />
<br />
Show detailed information about a container: <br />
<br />
$ machinectl status ''MyContainer''<br />
<br />
Reboot a container:<br />
<br />
$ machinectl reboot ''MyContainer''<br />
<br />
Poweroff a container:<br />
<br />
$ machinectl poweroff ''MyContainer''<br />
<br />
{{Tip|Poweroff and reboot operations can be performed from within a container session using the ''systemctl'' {{ic|poweroff}} or {{ic|reboot}} commands.}}<br />
<br />
Download an image:<br />
<br />
# machinectl pull-tar ''URL'' ''name''<br />
<br />
=== systemd toolchain ===<br />
<br />
Much of the core systemd toolchain has been updated to work with containers. Tools that do usually provide a {{ic|1=-M, --machine=}} option which will take a container name as argument.<br />
<br />
Examples:<br />
<br />
See journal logs for a particular machine:<br />
<br />
$ journalctl -M ''MyContainer''<br />
<br />
Show control group contents:<br />
<br />
$ systemd-cgls -M ''MyContainer''<br />
<br />
See startup time of container:<br />
<br />
$ systemd-analyze -M ''MyContainer''<br />
<br />
For an overview of resource usage:<br />
<br />
$ systemd-cgtop<br />
<br />
== Tips and tricks ==<br />
<br />
=== Use an X environment ===<br />
<br />
See [[Xhost]] and [[Change root#Run graphical applications from chroot]].<br />
<br />
You will need to set the {{ic|DISPLAY}} environment variable inside your container session to connect to the external X server.<br />
<br />
X stores some required files in the {{ic|/tmp}} directory. In order for your container to display anything, it needs access to those files. To do so, append the {{ic|--bind-ro<nowiki>=</nowiki>/tmp/.X11-unix}} option when starting the container.<br />
<br />
{{Note|Since systemd version 235, {{ic|/tmp/.X11-unix}} contents [https://github.com/systemd/systemd/issues/7093 have to be bind-mounted as read-only], otherwise they will disappear from the filesystem. The read-only mount flag does not prevent using {{ic|connect()}} syscall on the socket. If you binded also {{ic|/run/user/1000}} then you might want to explicitly bind {{ic|/run/user/1000/bus}} as read-only to protect the dbus socket from being deleted. }}<br />
<br />
=== Run Firefox ===<br />
<br />
See [[Firefox tweaks#Run Firefox inside an nspawn container|Firefox tweaks]].<br />
<br />
=== Access host filesystem ===<br />
<br />
See {{ic|--bind}} and {{ic|--bind-ro}} in {{man|1|systemd-nspawn}}.<br />
<br />
If both the host and the container are Arch Linux, then one could, for example, share the pacman cache:<br />
<br />
# systemd-nspawn --bind=/var/cache/pacman/pkg<br />
<br />
Or you can specify per-container bind using the file:<br />
<br />
{{hc|/etc/systemd/nspawn/''my-container''.nspawn|<nowiki><br />
[Files]<br />
Bind=/var/cache/pacman/pkg<br />
</nowiki>}}<br />
<br />
See [[#Specify per-container settings]].<br />
<br />
=== Configure networking ===<br />
<br />
{{Style}}<br />
<br />
<br />
For the most simple setup, allowing outgoing connections to the internet, you can use [[systemd-networkd]] for network management and DHCP and {{ic|systemd-resolved}} for DNS.<br />
<br />
# systemctl enable --now systemd-networkd systemd-resolved<br />
# ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf # let systemd-resolved manage /etc/resolv.conf<br />
<br />
This assumes you have started {{ic|systemd-nspawn}} with the {{ic|-n}} switch, creating a virtual Ethernet link to the host.<br />
<br />
Instead of using {{ic|systemd-resolved}} you can also manually [[textedit|edit]] your container's {{ic|/etc/resolv.conf}} by adding your DNS server's IP address.<br />
<br />
Note the canonical [[systemd-networkd]] host and container .network files are from https://github.com/systemd/systemd/tree/master/network .<br />
<br />
See [[systemd-networkd#Usage with containers]] for more complex examples.<br />
<br />
==== nsswitch.conf ====<br />
<br />
{{Merge|systemd-networkd}}<br />
<br />
To make it easier to connect to a container from the host, you can enable local DNS resolution for container names. In {{ic|/etc/nsswitch.conf}}, add {{ic|mymachines}} to the {{ic|hosts:}} section, e.g.<br />
<br />
hosts: files mymachines dns myhostname<br />
<br />
Then, any DNS lookup for hostname {{ic|foo}} on the host will first consult {{ic|/etc/hosts}}, then the names of local containers, then upstream DNS etc.<br />
<br />
==== Use host networking ====<br />
<br />
To disable private networking used by containers started with {{ic|machinectl start MyContainer}} [[edit]] the configuration of {{ic|systemd-nspawn@.service}} with <br />
<br />
# systemctl edit systemd-nspawn@.service<br />
<br />
and set the {{ic|1=ExecStart=}} option without the {{ic|--network-veth}} parameter unlike the original service:<br />
<br />
{{hc|/etc/systemd/system/systemd-nspawn@.service.d/override.conf|<nowiki><br />
[Service]<br />
ExecStart=<br />
ExecStart=/usr/bin/systemd-nspawn --quiet --keep-unit --boot --link-journal=try-guest --machine=%i<br />
</nowiki>}}<br />
<br />
The newly started containers will use the hosts networking.<br />
<br />
==== Virtual Ethernet interfaces ====<br />
<br />
If a container is started with {{ic|systemd-nspawn ... -n}}, systemd will automatically create one virtual Ethernet interface on the host, and one in the container, connected by a virtual Ethernet cable.<br />
<br />
If the name of the container is {{ic|foo}}, the name of the virtual Ethernet interface on the host is {{ic|ve-foo}}. The name of the virtual Ethernet interface in the container is always {{ic|host0}}.<br />
<br />
When examining the interfaces with {{ic|ip link}}, interface names will be shown with a suffix, such as {{ic|ve-foo@if2}} and {{ic|host0@if9}}. The {{ic|@ifN}} is not actually part of the name of the interface; instead, {{ic|ip link}} appends this information to indicate which "slot" the virtual Ethernet cable connects to on the other end.<br />
<br />
For example, a host virtual Ethernet interface shown as {{ic|ve-foo@if2}} will connect to container {{ic|foo}}, and inside the container to the second network interface -- the one shown with index 2 when running {{ic|ip link}} inside the container. Similarly, in the container, the interface named {{ic|host0@if9}} will connect to the 9th slot on the host.<br />
<br />
==== Use a network bridge ====<br />
<br />
If you have configured a network bridge on the host system in order to have an IP address assigned to the container as if it was a physical machine in your local network (see, for example, [[systemd-networkd#DHCP with two distinct IP]] or [[systemd-networkd#Static IP network]]) you can make systemd-nspawn use it by using the option {{ic|1=--network-bridge=''br0''}}.<br />
<br />
=== Run on a non-systemd system ===<br />
<br />
See [[Init#systemd-nspawn]].<br />
<br />
=== Specify per-container settings ===<br />
<br />
To specify per-container settings and not overrides for all (e.g. bind a directory to only one container), the ''.nspawn'' files can be used. See {{man|5|systemd.nspawn}} for details.<br />
<br />
=== Use Btrfs subvolume as container root ===<br />
<br />
To use a [[Btrfs#Subvolumes|Btrfs subvolume]] as a template for the container's root, use the {{ic|--template}} flag. This takes a snapshot of the subvolume and populates the root directory for the container with it.<br />
<br />
{{Note|If the template path specified is not the root of a subvolume, the '''entire''' tree is copied. This will be very time consuming.}}<br />
<br />
For example, to use a snapshot located at {{ic|/.snapshots/403/snapshot}}:<br />
<br />
# systemd-nspawn --template=/.snapshots/403/snapshots -b -D ''my-container''<br />
<br />
where {{ic|''my-container''}} is the name of the directory that will be created for the container. After powering off, the newly created subvolume is retained.<br />
<br />
=== Use temporary Btrfs snapshot of container ===<br />
<br />
One can use the {{ic|--ephemeral}} or {{ic|-x}} flag to create a temporary btrfs snapshot of the container and use it as the container root. Any changes made while booted in the container will be lost. For example:<br />
<br />
# systemd-nspawn -D ''my-container'' -xb<br />
<br />
where ''my-container'' is the directory of an '''existing''' container or system. For example, if {{ic|/}} is a btrfs subvolume one could create an ephemeral container of the currently running host system by doing:<br />
<br />
# systemd-nspawn -D / -xb <br />
<br />
After powering off the container, the btrfs subvolume that was created is immediately removed.<br />
<br />
=== Run docker in systemd-nspawn ===<br />
<br />
[[Docker]] requires {{ic|rw}} permission of {{ic|/sys/fs/cgroup}} to run its containers, which is mounted read-only by {{ic|systemd-nspawn}} by default due to cgroup namespace. However, it is possible to run Docker in a systemd-nspawn container by bind-mounting {{ic|/sys/fs/cgroup}} from host os and enabling necessary capabilities and permissions.<br />
<br />
{{Note|The following steps are essentially sharing the cgroup namespace to the container, giving kernel keyring permissions and making it a privileged container, which is likely to increase the attack surface and decrease security level. You should always evaluate the actual benefits by doing so before following the steps.}}<br />
<br />
First, cgroup namespace should be disabled by {{ic|systemctl edit systemd-nspawn@myContainer}}<br />
<br />
{{hc|systemctl edit systemd-nspawn@myContainer|<nowiki><br />
[Service]<br />
Environment=SYSTEMD_NSPAWN_USE_CGNS=0<br />
</nowiki>}}<br />
<br />
Then, edit {{ic|/etc/systemd/nspawn/myContainer.nspawn}} (create if absent) and add the following configurations.<br />
<br />
{{hc|/etc/systemd/nspawn/myContainer.nspawn|<nowiki><br />
[Exec]<br />
Capability=all<br />
SystemCallFilter=add_key keyctl<br />
<br />
[Files]<br />
Bind=/sys/fs/cgroup<br />
</nowiki>}}<br />
<br />
This grants all capabilities to the container, whitelists two system calls {{ic|add_key}} and {{ic|keyctl}} (related to kernel keyring and required by Docker), and bind-mounts {{ic|/sys/fs/cgroup}} from host to the container. After editing these files, you need to poweroff and restart your container for them to take effect.<br />
<br />
{{Note|You might need to load the {{ic|overlay}} module on the host before starting Docker inside the systemd-nspawn to use the {{ic|overlay2}} storage driver (default storage driver of Docker) properly. Failure to load the driver will cause Docker to choose the inefficient driver {{ic|vfs}} which copies everything for every layer of Docker containers. Consult [[Kernel modules#Automatic module loading with systemd]] on how to load the module automatically.}}<br />
<br />
== Troubleshooting ==<br />
<br />
=== root login fails ===<br />
<br />
If you get the following error when you try to login (i.e. using {{ic|machinectl login <name>}}):<br />
<br />
arch-nspawn login: root<br />
Login incorrect<br />
<br />
And {{ic|journalctl}} shows:<br />
<br />
pam_securetty(login:auth): access denied: tty 'pts/0' is not secure !<br />
<br />
Add {{ic|pts/0}} to the list of terminal names in {{ic|/etc/securetty}} on the '''container''' filesystem, see [http://unix.stackexchange.com/questions/41840/effect-of-entries-in-etc-securetty/41939#41939]. You can also opt to delete {{ic|/etc/securetty}} on the '''container''' to allow root to login to any tty, see [https://github.com/systemd/systemd/issues/852].<br />
<br />
=== Unable to upgrade some packages on the container ===<br />
<br />
It can sometimes be impossible to upgrade some packages on the container, {{Pkg|filesystem}} being a perfect example. The issue is due to {{ic|/sys}} being mounted as Read Only. The workaround is to remount the directory in Read Write when running {{ic|mount -o remount,rw -t sysfs sysfs /sys}}, do the upgrade then reboot the container.<br />
<br />
=== execv(...) failed: Permission denied ===<br />
<br />
When trying to boot the container via {{ic|systemd-nspawn -bD ''/path/to/container''}} (or executing something in the container), and the following error comes up:<br />
<br />
execv(/usr/lib/systemd/systemd, /lib/systemd/systemd, /sbin/init) failed: Permission denied<br />
<br />
even though the permissions of the files in question (i.e. {{ic|/lib/systemd/systemd}}) are correct, this can be the result of having mounted the file system on which the container is stored as non-root user. For example, if you mount your disk manually with an entry in [[fstab]] that has the options {{ic|noauto,user,...}}, ''systemd-nspawn'' will not allow executing the files even if they are owned by root.<br />
<br />
== See also ==<br />
<br />
* [[Getty#Nspawn_console|Automatic console login]]<br />
* [http://www.freedesktop.org/software/systemd/man/machinectl.html machinectl man page]<br />
* [http://www.freedesktop.org/software/systemd/man/systemd-nspawn.html systemd-nspawn man page]<br />
* [http://lwn.net/Articles/572957/ Creating containers with systemd-nspawn]<br />
* [https://www.youtube.com/results?search_query=systemd-nspawn&aq=f Presentation by Lennart Pottering on systemd-nspawn]<br />
* [http://dabase.com/e/12009/ Running Firefox in a systemd-nspawn container]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Snap&diff=550947Snap2018-10-25T12:05:26Z<p>Teples: /* Installation */ Add info about AppArmor support</p>
<hr />
<div>[[Category:Development]]<br />
[[ja:snapd]]<br />
[[pl:Snap]]<br />
[[ru:Snapd]]<br />
{{Related articles start}}<br />
{{Related|Flatpak}}<br />
{{Related articles end}}<br />
<br />
''[https://snapcraft.io/ Snap]'' is a software deployment and package management system. The packages are called 'snaps' and the tool for using them is 'snapd', which works across a range of Linux distributions and allows, therefore, distro-agnostic upstream software deployment. Snap was originally designed and built by Canonical.<br />
<br />
[https://github.com/snapcore/snapd snapd] is a REST API daemon for managing snap packages. Users can interact with it by using the ''snap'' client, which is part of the same package. <br />
<br />
==Installation==<br />
<br />
[[Install]] the {{AUR|snapd}} or the {{AUR|snapd-git}} package.<br />
<br />
{{tip|{{ic|snapd}} installs a script in {{ic|/etc/profile.d/snapd.sh}} to export the paths of binaries installed with the snapd package and desktop entries. Reboot once to make this change take effect.}}<br />
<br />
Since version 2.36, {{ic|snapd}} enabled AppArmor support for Arch Linux. In order to use it, you have to enable AppArmor in your system, see [[AppArmor#Installation]].<br />
<br />
{{Note|If AppArmor isn't enabled in your system then all snaps will run in {{ic|devel}} mode which mean they will have same, unrestricted access to your system as apps installed from Arch Linux repositories.}}<br />
<br />
== Configuration ==<br />
<br />
To launch the {{ic|snapd}} daemon when ''snap'' tries to use it, [[start]] and/or [[enable]] the {{ic|snapd.socket}}.<br />
<br />
== Usage == <br />
The ''snap'' tool is used to manage the snaps.<br />
<br />
=== Finding ===<br />
To find snaps to install, you can query the Ubuntu Store with:<br />
<br />
$ snap find ''searchterm''<br />
<br />
=== Installing ===<br />
Once you found the snap you are looking for you can install it with:<br />
# snap install ''snapname''<br />
This requires root privileges. Per user installation of snaps is not possible, yet. This will download the snap into {{ic|/var/lib/snapd/snaps}} and mount it to {{ic|/var/lib/snapd/snap/''snapname''}} to make it available to the system.<br />
<br />
It will also create mount units for each snap and add them to {{ic| /etc/systemd/system/multi-user.target.wants/}} as symlinks to make all snaps available when the system is booted.<br />
Once that is done you should find it in the list of installed snaps together with its version number, revision and developer using:<br />
$ snap list<br />
<br />
You can also sideload snaps from your local hard drive with:<br />
# snap install --dangerous ''/path/to/snap''<br />
<br />
=== Updating ===<br />
To update your snaps manually use:<br />
# snap refresh<br />
<br />
Snaps are refreshed automatically according to snap {{ic|refresh.timer}} setting.<br />
<br />
To view the next/last refresh times use:<br />
# snap refresh --time<br />
<br />
To set a different refresh time, eg. twice a day:<br />
# snap set core refresh.timer=0:00~24:00/2<br />
<br />
See [https://forum.snapcraft.io/t/system-options/87 system options documentation page] for details on customizing the refresh time.<br />
<br />
=== Removing ===<br />
Snaps can be removed by executing:<br />
# snap remove ''snapname''<br />
<br />
== Tips and tricks ==<br />
=== Classic snaps ===<br />
Some snaps (e.g. Skype and Pycharm) use classic confinement. However, classic confinement requires the {{ic|/snap}} directory, which is not FHS-compliant. Therefore, the snapd package doesn't ship this directory. However, if the user wants to, they can manually create a symlink from {{ic|/snap}} to {{ic|/var/lib/snapd/snap}}, to allow the installation of classic snaps:<br />
<br />
# ln -s /var/lib/snapd/snap /snap<br />
<br />
== Support ==<br />
Arch Linux related mailing lists and other official Arch Linux support channels aren't an appropriate place to request help with snaps on Arch Linux. An appropriate place to ask for support is the [https://forum.snapcraft.io Snapcraft forum].<br />
<br />
== See also == <br />
* [https://snapcraft.io/ Official site]<br />
* [https://github.com/snapcore/snapd GitHub repository]<br />
* [http://arstechnica.com/information-technology/2016/06/goodbye-apt-and-yum-ubuntus-snap-apps-are-coming-to-distros-everywhere/ arstechnica article] (06/16) about Ubuntu snaps becoming available for Arch and other distros</div>Tepleshttps://wiki.archlinux.org/index.php?title=User_talk:Teples&diff=550326User talk:Teples2018-10-23T11:10:07Z<p>Teples: /* AppArmor in linux */ Remove resolved section</p>
<hr />
<div></div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=548435AppArmor2018-10-19T12:11:58Z<p>Teples: /* Speed-up AppArmor start by caching profiles */ Move comment to note for easier readability</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ aa-enabled|<br />
Yes<br />
}}<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof}} and {{man|8|aa-logprof}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
Install and enable [[Audit framework]]. Allow your desktop user to read audit logs in {{ic|/var/log/audit}} by adding it to {{ic|audit}} [[group]]:<br />
<br />
# groupadd -r audit<br />
# gpasswd -a <username> audit<br />
<br />
Add {{ic|audit}} group to {{ic|auditd.conf}}:<br />
{{hc|/etc/audit/auditd.conf|2=<br />
log_group = audit<br />
}}<br />
<br />
{{Tip|You may use other already existing system groups like {{ic|wheel}} or {{ic|adm}}.}}<br />
<br />
Create [[desktop launcher]] with the below content:<br />
<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60 -f /var/log/audit/audit.log<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
Reboot and check if {{ic|aa-notify}} daemon is running:<br />
<br />
$ ps aux | grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
For more information, see {{man|8|aa-notify}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
To enable caching AppArmor profiles, uncomment:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
}}<br />
<br />
To change default cache location add:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
cache-loc=/path/to/location<br />
}}<br />
<br />
{{Note|Since 2.13.1 default cache location is {{ic|/var/cache/apparmor/}}, previously it was {{ic|/etc/apparmor.d/cache.d/}}.}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=547768AppArmor2018-10-15T13:10:28Z<p>Teples: /* Speed-up AppArmor start by caching profiles */ Update default cache location info for 2.13.1</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ aa-enabled|<br />
Yes<br />
}}<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-genprof.8.en.html}} and {{man|8|aa-logprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-logprof.8.en.html}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
Install and enable [[Audit framework]]. Allow your desktop user to read audit logs in {{ic|/var/log/audit}} by adding it to {{ic|audit}} [[group]]:<br />
<br />
# groupadd -r audit<br />
# gpasswd -a <username> audit<br />
<br />
Add {{ic|audit}} group to {{ic|auditd.conf}}:<br />
{{hc|/etc/audit/auditd.conf|2=<br />
log_group = audit<br />
}}<br />
<br />
{{Tip|You may use other already existing system groups like {{ic|wheel}} or {{ic|adm}}.}}<br />
<br />
Create [[desktop launcher]] with the below content:<br />
<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60 -f /var/log/audit/audit.log<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
Reboot and check if {{ic|aa-notify}} daemon is running:<br />
<br />
$ ps aux | grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
To enable caching AppArmor profiles, uncomment:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
}}<br />
<br />
To change default cache location (since 2.13.1 default cache location is {{ic|/var/cache/apparmor/}}, previously it was {{ic|/etc/apparmor.d/cache.d/}} add:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
cache-loc=/path/to/location<br />
}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=User_talk:Teples&diff=547627User talk:Teples2018-10-14T10:48:15Z<p>Teples: /* AppArmor in linux */</p>
<hr />
<div>== <s>AppArmor in linux</s> ==<br />
<br />
Hi Teples,<br />
<br />
It has been reverted: https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux&id=62b80117614b44f4a17921b0d1cb9b9e6d08fa4e<br />
<br />
I have even asked if it could be enabled again, just for apparmor, unfortunately the answer was no (although good alternatives are available, so it's not a big of a deal).<br />
[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 02:18, 29 September 2018 (UTC)<br />
:Hi Francoism<br />
:<br />
:Please look at the date of the commit you linked (2018-09-03), then please look at the date of the commit linked (by me) in wiki (2018-09-15). The sequence of events was this:<br />
:1. AppArmor enabled<br />
:2. AppArmor disabled (commit you linked)<br />
:3. AppArmor enabled again (commit I linked)<br />
:<br />
:It's easy check what's the current status by looking in the config file: https://git.archlinux.org/svntogit/packages.git/tree/trunk/config?h=packages/linux#n9274 which I checked after seeing your revert even as I was sure what's inside as I follow all commits to linux package in real time.<br />
:<br />
:It's nice that you decided to reach me here, unfortunately only after you reverted my change the second time. Please double check before doing the revert.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 10:14, 29 September 2018 (UTC)<br />
::Oops, missed that commit! Sorry for the revert and thanks for letting me now.<br />
::[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 09:55, 30 September 2018 (UTC)<br />
:::Thanks for updating the cache section. Seems the default cache location is {{ic|/etc/apparmor.d/cache}}, should this be changed to {{ic|/var/cache/apparmor}} and/or should the user create the path? If I don't set {{ic|--cache-loc}} it doesn't produce an error - is it using {{ic|/etc/apparmor.d/cache.d}}?<br />
:::[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 11:18, 1 October 2018 (UTC)<br />
::::{{ic|/var/cache/apparmor}} will be the default location in 2.13.1 release which should be available very soon (perhaps this week) thus I thought it's better to choose it now instead of changing it after few days again. See https://gitlab.com/apparmor/apparmor/commit/affc7a9fb4a42dfbfee396c53214b789ad93d42a . If specified in config, it should be created automatically by apparmor parser, no need to create it manually. If not specified then cache will be put under /etc (until 2.13.1 release). You can see if profile caches are created by listing the cache dir with {{ic|sudo ls -al <cache-dir>}}<br />
::::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:22, 1 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545677AppArmor2018-10-02T21:23:51Z<p>Teples: /* Speed-up AppArmor start by caching profiles */ Fix typo</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-genprof.8.en.html}} and {{man|8|aa-logprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-logprof.8.en.html}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
Install and enable [[Audit framework]]. Allow your desktop user to read audit logs in {{ic|/var/log/audit}} by adding it to {{ic|audit}} [[group]]:<br />
<br />
# groupadd -r audit<br />
# gpasswd -a <username> audit<br />
<br />
Add {{ic|audit}} group to {{ic|auditd.conf}}:<br />
{{hc|/etc/audit/auditd.conf|2=<br />
log_group = audit<br />
}}<br />
<br />
{{Tip|You may use other already existing system groups like {{ic|wheel}} or {{ic|adm}}.}}<br />
<br />
Create [[desktop launcher]] with the below content:<br />
<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60 -f /var/log/audit/audit.log<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
Reboot and check if {{ic|aa-notify}} daemon is running:<br />
<br />
$ ps aux | grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
To enable caching AppArmor profiles, uncomment:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
}}<br />
<br />
To change default cache location from {{ic|/etc/apparmor.d/cache.d/}} to {{ic|/var/cache/apparmor/}} add:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
cache-loc=/var/cache/apparmor<br />
}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=545673Talk:AppArmor2018-10-02T18:58:17Z<p>Teples: /* Desktop notifications */ re</p>
<hr />
<div>==<s> re: LTS kernel edits </s>==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)<br />
<br />
== <s>Desktop notifications</s> ==<br />
<br />
Has anyone managed to get [[AppArmor#Get desktop notification on DENIED actions]] to actually work?<br />
<br />
When {{ic|auditd.service}} starts it changes the permissions of {{ic|/var/log/audit/}} and {{ic|/var/log/audit/audit.log}}. Even when I change ACLs so that I can read {{ic|/var/log/audit/audit.log}}, aa-notify still shows {{ic|Cannot read '/var/log/audit/audit.log'}}.<br />
<br />
-- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 10:06, 2 October 2018 (UTC)<br />
:I'm sorry for inconvenience. I proposed different approach, see https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545635&oldid=545631 . I hope this one will work.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:26, 2 October 2018 (UTC)<br />
<br />
::Thanks, now it works for me :) -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 17:14, 2 October 2018 (UTC)<br />
::: AFAIK if auditd.service isn't started then there is nothing logged to /var/log/audit/audit.log so https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545662&oldid=545635 doesn't make sense. I think auditd is the only process which logs there. Did you observe something different?<br />
:::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 17:55, 2 October 2018 (UTC)<br />
<br />
::::No, but this allows to allows to start {{ic|auditd.service}} later, after login. Without {{ic|-f /var/log/audit/audit.log}} aa-notify would try read {{ic|/var/log/kern.log}} and fail. So if {{ic|auditd.service}} is started after login, you would need to re-login for apparmor-notify.desktop to start. -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 18:01, 2 October 2018 (UTC)<br />
<br />
:::::Ok, thx for info.<br />
:::::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 18:58, 2 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=545668Talk:AppArmor2018-10-02T17:57:40Z<p>Teples: /* Desktop notifications */</p>
<hr />
<div>==<s> re: LTS kernel edits </s>==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)<br />
<br />
== <s>Desktop notifications</s> ==<br />
<br />
Has anyone managed to get [[AppArmor#Get desktop notification on DENIED actions]] to actually work?<br />
<br />
When {{ic|auditd.service}} starts it changes the permissions of {{ic|/var/log/audit/}} and {{ic|/var/log/audit/audit.log}}. Even when I change ACLs so that I can read {{ic|/var/log/audit/audit.log}}, aa-notify still shows {{ic|Cannot read '/var/log/audit/audit.log'}}.<br />
<br />
-- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 10:06, 2 October 2018 (UTC)<br />
:I'm sorry for inconvenience. I proposed different approach, see https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545635&oldid=545631 . I hope this one will work.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:26, 2 October 2018 (UTC)<br />
<br />
::Thanks, now it works for me :) -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 17:14, 2 October 2018 (UTC)<br />
::: AFAIK if auditd.service isn't started then there is nothing logged to /var/log/audit/audit.log so https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545662&oldid=545635 doesn't make sense. I think auditd is the only process which logs there. Did you observe something different?<br />
:::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 17:55, 2 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=545667Talk:AppArmor2018-10-02T17:55:31Z<p>Teples: /* Desktop notifications */ signature</p>
<hr />
<div>==<s> re: LTS kernel edits </s>==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)<br />
<br />
== <s>Desktop notifications</s> ==<br />
<br />
Has anyone managed to get [[AppArmor#Get desktop notification on DENIED actions]] to actually work?<br />
<br />
When {{ic|auditd.service}} starts it changes the permissions of {{ic|/var/log/audit/}} and {{ic|/var/log/audit/audit.log}}. Even when I change ACLs so that I can read {{ic|/var/log/audit/audit.log}}, aa-notify still shows {{ic|Cannot read '/var/log/audit/audit.log'}}.<br />
<br />
-- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 10:06, 2 October 2018 (UTC)<br />
:I'm sorry for inconvenience. I proposed different approach, see https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545635&oldid=545631 . I hope this one will work.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:26, 2 October 2018 (UTC)<br />
<br />
::Thanks, now it works for me :) -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 17:14, 2 October 2018 (UTC)<br />
::: AFAIK if auditd.service isn't started then there is nothing logged to /var/log/audit/audit.log so https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545662&oldid=545635 doesn't make sense. Did you observe something different?<br />
:::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 17:55, 2 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=545666Talk:AppArmor2018-10-02T17:55:12Z<p>Teples: /* Desktop notifications */ re</p>
<hr />
<div>==<s> re: LTS kernel edits </s>==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)<br />
<br />
== <s>Desktop notifications</s> ==<br />
<br />
Has anyone managed to get [[AppArmor#Get desktop notification on DENIED actions]] to actually work?<br />
<br />
When {{ic|auditd.service}} starts it changes the permissions of {{ic|/var/log/audit/}} and {{ic|/var/log/audit/audit.log}}. Even when I change ACLs so that I can read {{ic|/var/log/audit/audit.log}}, aa-notify still shows {{ic|Cannot read '/var/log/audit/audit.log'}}.<br />
<br />
-- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 10:06, 2 October 2018 (UTC)<br />
:I'm sorry for inconvenience. I proposed different approach, see https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545635&oldid=545631 . I hope this one will work.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:26, 2 October 2018 (UTC)<br />
<br />
::Thanks, now it works for me :) -- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 17:14, 2 October 2018 (UTC)<br />
::: AFAIK if auditd.service isn't started then there is nothing logged to /var/log/audit/audit.log so https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545662&oldid=545635 doesn't make sense. Did you observe something different?</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=545636Talk:AppArmor2018-10-02T12:26:41Z<p>Teples: /* Desktop notifications */ re</p>
<hr />
<div>==<s> re: LTS kernel edits </s>==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)<br />
<br />
== Desktop notifications ==<br />
<br />
Has anyone managed to get [[AppArmor#Get desktop notification on DENIED actions]] to actually work?<br />
<br />
When {{ic|auditd.service}} starts it changes the permissions of {{ic|/var/log/audit/}} and {{ic|/var/log/audit/audit.log}}. Even when I change ACLs so that I can read {{ic|/var/log/audit/audit.log}}, aa-notify still shows {{ic|Cannot read '/var/log/audit/audit.log'}}.<br />
<br />
-- [[User:nl6720|nl6720]] ([[User talk:nl6720|talk]]) 10:06, 2 October 2018 (UTC)<br />
:I'm sorry for inconvenience. I proposed different approach, see https://wiki.archlinux.org/index.php?title=AppArmor&type=revision&diff=545635&oldid=545631 . I hope this one will work.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:26, 2 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545635AppArmor2018-10-02T12:24:20Z<p>Teples: /* Get desktop notification on DENIED actions */ Use group approach for reading logs permission as ACLs are more tricky</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-genprof.8.en.html}} and {{man|8|aa-logprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-logprof.8.en.html}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
Install and enable [[Audit framework]]. Allow your desktop user to read audit logs in {{ic|/var/log/audit}} by adding it to {{ic|audit}} [[group]]:<br />
<br />
# groupadd -r audit<br />
# gpasswd -a <username> audit<br />
<br />
Add {{ic|audit}} group to {{ic|auditd.conf}}:<br />
{{hc|/etc/audit/auditd.conf|2=<br />
log_group = audit<br />
}}<br />
<br />
{{Note|You may use other already existing system groups like {{ic|wheel}} or {{ic|adm}}.}}<br />
<br />
Create desktop launcher with the below content:<br />
<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
Reboot and check if {{ic|aa-notify}} daemon is running:<br />
<br />
$ ps aux | grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
To enable caching AppAmror profiles uncomment:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
}}<br />
<br />
To change default cache location from {{ic|/etc/apparmor.d/cache.d/}} to {{ic|/var/cache/apparmor/}} add:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
cache-loc=/var/cache/apparmor<br />
}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545631AppArmor2018-10-02T11:02:20Z<p>Teples: /* Get desktop notification on DENIED actions */ Improve ACLs: "-b" flag covers all ACLs including the default, "-d" flag applies only to directories.</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-genprof.8.en.html}} and {{man|8|aa-logprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-logprof.8.en.html}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
Install and enable [[Audit framework]]. Allow your desktop user to read audit logs in {{ic|/var/log/audit}} with [[Access Control Lists]]:<br />
<br />
# setfacl -R -m u:''username'':rX /var/log/audit<br />
# setfacl -d -m u:''username'':r /var/log/audit<br />
<br />
Create desktop launcher with the below content:<br />
<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
Re-login and check if {{ic|aa-notify}} daemon is running:<br />
<br />
$ ps aux | grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
To undo above, run:<br />
<br />
# setfacl -R -b /var/log/audit<br />
$ rm ~/.config/autostart/apparmor-notify.desktop<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
To enable caching AppAmror profiles uncomment:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
}}<br />
<br />
To change default cache location from {{ic|/etc/apparmor.d/cache.d/}} to {{ic|/var/cache/apparmor/}} add:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
cache-loc=/var/cache/apparmor<br />
}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame | grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=Firejail&diff=545488Firejail2018-10-01T19:18:53Z<p>Teples: /* Firejail with Apparmor */ Update info about AppArmor support.</p>
<hr />
<div>[[Category:Security]]<br />
[[ja:Firejail]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related articles end}}<br />
[https://firejail.wordpress.com/ Firejail] is an easy to use SUID sandbox program that reduces the risk of security breaches by restricting the running environment of untrusted applications using Linux namespaces, seccomp-bpf and Linux capabilities.<br />
<br />
== Installation ==<br />
<br />
[[Install]] either {{Pkg|firejail}}, {{aur|firejail-git}} or the {{aur|firejail-apparmor}} package. A GUI application for use with Firejail is also available, {{aur|firetools}}.<br />
<br />
{{Note|For information about {{man|7|user_namespaces}} support in Arch Linux kernels see [[Security#Sandboxing applications]]. [https://github.com/netblue30/firejail/issues/1842#issuecomment-376642039 Firejail can use it even if it is disabled].}}<br />
{{Warning|While upstream is gradually adopting whitelists, (cf {{ic|/etc/firejail/firefox.profile}},) most of the supplied profiles still rely heavily on blacklists. This means that anything not explicitly forbidden by the profile will be accessible to the application. For example, if you have btrfs snapshots available in {{ic|/mnt/btrfs}}, a jailed program may be forbidden from accessing {{ic|$HOME/.ssh}}, but would still be able to access {{ic|/mnt/btrfs/@some-snapshot/$HOME/.ssh}}. Make sure to audit your profiles, see [[#Testing profiles]]}}<br />
<br />
== Configuration ==<br />
<br />
Most users will not require any custom configuration and can proceed to [[#Usage]].<br />
<br />
Firejail uses profiles to set the security protections for each of the applications executed inside of it - you can find the default profiles in {{ic|/etc/firejail/''application''.profile}}. Should you require custom profiles for applications not included, or wish to modify the defaults, you may place new rules or copies of the defaults in the {{ic|~/.config/firejail/}} directory. You may have multiple custom profile files for a single application, and you may share the same profile file among several applications.<br />
<br />
If firejail does not have a profile for a particular application, it uses its restrictive system-wide default profile. This can result in the application not functioning as desired, without first creating a custom, and less restrictive profile.<br />
<br />
Refer to {{man|5|firejail-profile}}.<br />
<br />
== Usage ==<br />
<br />
To execute an application using firejail's default protections for that application (the default profile), execute the following:<br />
<br />
$ firejail <program name><br />
<br />
One-time additions to the default profile can be added as command line options (see the man page). For example, to execute ''okular'' with seccomp protection, execute the following:<br />
<br />
$ firejail --seccomp okular<br />
<br />
You may define multiple non-default profiles for a single program. Once you create your profile file, you can use it by executing:<br />
<br />
$ firejail --profile=/absolute/path/to/profile <program name><br />
<br />
=== Using Firejail by default ===<br />
<br />
To use Firejail by default for all applications for which it has profiles, run the ''firecfg'' tool as root.<br />
<br />
# firecfg<br />
<br />
This creates symbolic links in {{ic|/usr/local/bin}} pointing to {{ic|/usr/bin/firejail}}, for all programs for which firejail has default profiles. Once this is done, you only need to prefix a program with ''firejail'' if you want to run it with some custom security setting.<br />
<br />
Please be aware that in order for this to work, {{ic|/usr/local/bin}} must be before {{ic|/usr/bin/}} in your {{ic|PATH}}.<br />
<br />
You can manually do this for individual applications by executing:<br />
<br />
# ln -s /usr/bin/firejail /usr/local/bin/<program name><br />
<br />
{{Note|1=<nowiki></nowiki><br />
* For a daemon, you will need to overwrite the systemd unit file for that daemon to call firejail, see [[systemd#Editing provided units]].<br />
* {{ic|firecfg}} doesn't work with some cli shells such as: {{ic|tar}}, {{ic|curl}}, {{ic|wget}}, {{ic|git}} and {{ic|ssh}} which need to be symlinked manually.<br />
* Symbolic links to {{ic|gzip}} and {{ic|xz}} interfere with {{ic|makepkg}}'s ability to preload {{ic|libfakeroot.so}}. See [https://bbs.archlinux.org/viewtopic.php?id=230913 BBS#230913].}}<br />
<br />
{{Warning|Upstream provides profiles for {{ic|gpg}} and {{ic|gpg-agent}}. If gpg is symlinked with the supplied profile, pacman will be unable to update {{pkg|archlinux-keyring}}.}}<br />
<br />
=== Verifying Firejail is being used ===<br />
<br />
$ firejail --list<br />
<br />
== Creating custom profiles ==<br />
<br />
=== Whitelists and Blacklists ===<br />
<br />
Blacklists are permissive:<br />
<br />
* Permit everything not explicitly forbidden: {{ic|blacklist <location/file>}}<br />
* Permit file or location in any later blacklist: {{ic|noblacklist <location/file>}} <br />
<br />
Whitelists are restrictive: <br />
<br />
* Forbid everything not explicitly permitted: {{ic|whitelist <location/file>}}<br />
* Forbid file or location in any later whitelist: {{ic|nowhitelist <location/file>}}<br />
<br />
=== Profile writing ===<br />
<br />
The basic process is:<br />
<br />
# Copy the default profile (which uses blacklists) to your work folder and give it a unique name:<br />
# Change the line {{ic|include /etc/firejail/default.local}} to {{ic|include /etc/firejail/ProfileName.local}}<br />
# Gradually comment/uncomment the various options while checking at each stage that the application runs inside the new sandbox<br />
# Desirable options not available in the copied default profile can be found by consulting the manual<br />
# [https://firejail.wordpress.com/documentation-2/building-whitelisted-profiles/ Build a whitelist] of permitted locations. For portability, it may be advisable to place at least some of this list it in a {{ic|.local}} file<br />
# Test the profile for security holes, see [[#Testing profiles]]<br />
# Once satisfied, copy your new profile to either {{ic|/etc/firejail/}} or {{ic|~/.config/firejail/}}<br />
<br />
You may find the following to be useful:<br />
<br />
# {{ic|firejail --debug $OtherOptions $PathToProfile $Program > $PathToOutputFile}} Gives a detailed breakdown of the sandbox<br />
# {{ic|firejail --debug-caps}} gives a list of caps supported by the current Firejail software build. This is useful when building a [https://l3net.wordpress.com/2015/03/16/firejail-linux-capabilities-guide/ caps whitelist].<br />
# {{ic|firejail --help}} for a full list of {{ic|--debug}} options<br />
# {{ic|firemon PID}} monitors the running process. See {{ic|firemon --help}} for details<br />
# {{Pkg|checksec}} may also be useful in testing which standard security features are being used<br />
<br />
{{Note|<nowiki></nowiki><br />
* The idea is to be as restrictive as possible, while still maintaining usability. This may involve sacrificing potentially dangerous functionality and a change in cavalier work habits.<br />
* By default, seccomp filters work on a blacklist (which can be found in the manual). It is possible to use {{ic|seccomp.keep}} to build a custom whitelist of filters for an application. [https://firejail.wordpress.com/documentation-2/seccomp-guide/].<br />
* The list of possible options for a firejail profile is extensive, and users should consult the firejail-profile(5) man page.<br />
}}<br />
<br />
==== Persistent local customisation ====<br />
<br />
The standard profile layout now includes the capability to make persistent local customisations through the inclusion of {{ic|.local}} files. Basically, each officially supported profile contains the lines {{ic|include /etc/firejail/ProgramName.local}} and {{ic|include /etc/firejail/globals.local}}. Since the order of precedence is determined by which is read first, this makes for a very powerful way of making local customisations.<br />
For example, with reference [https://github.com/netblue30/firejail/issues/1510#issuecomment-326443650 this firejail question], to globally enable Apparmor and disable Internet connectivity, one could simply create/edit {{ic|/etc/firejail/globals.local}} to include the lines<br />
<br />
# enable Apparmor and disable Internet globally<br />
net none<br />
apparmor<br />
<br />
Then, to allow, for example, "curl" to connect to the internet, yet still maintain its apparmor confinement, one would create/edit {{ic|/etc/firejail/curl.local}} to include the lines.<br />
<br />
# enable internet for curl<br />
ignore net<br />
<br />
Since {{ic|curl.local}} is read before {{ic|globals.local}}, {{ic|ignore net}} overrides {{ic|net none}}, and, as a bonus, the above changes would be persistent across future updates.<br />
<br />
=== Testing profiles ===<br />
<br />
Firejail's built in audit feature allows the user to find gaps in a security profile by replacing the program to be sandboxed with a test program. By default, firejail uses the {{ic|faudit}} program distributed with Firejail. (Note: A custom test program supplied by the user can also be used.) <br />
Examples:<br />
<br />
# Run the default audit program: {{ic|$ firejail --audit transmission-gtk}}<br />
# Run a custom audit program: {{ic|1=$ firejail --audit=~/sandbox-test transmission-gtk}} <br />
<br />
In the examples above, the sandbox configures the transmission-gtk profile and starts the test program. The real program, transmission-gtk, will not be started.<br />
<br />
{{Note|The audit feature is not implemented for --x11 commands.}}<br />
<br />
== Firejail with Apparmor ==<br />
<br />
Since 0.9.42, {{aur|firejail-apparmor}}, has supported more direct integration with Apparmor through a generic apparmor profile. During installation, the profile, {{ic|firejail-default}}, is placed in {{ic|/etc/apparmor.d}} directory, and needs to be loaded into the kernel by running the following command as root:<br />
<br />
# apparmor_parser -r /etc/apparmor.d/firejail-default<br />
<br />
To quote the manual: <br />
<br />
:''The installed profile is supplemental for main firejail functions and among other things does the following:''<br />
<br />
::''- Disable ptrace. With ptrace it is possible to inspect and hijack running programs. Usually this is needed only for debugging.''<br />
<br />
::''- Whitelist write access to several files under /run, /proc and /sys.''<br />
<br />
::''- Allow running programs only from well-known system paths, such as /bin, /sbin, /usr/bin etc. Those paths are available as read-only. Running programs and scripts from user home or other directories writable by the user is not allowed.''<br />
<br />
::''- Prevent using non-standard network sockets. Only unix, inet, inet6, netlink, raw and packet are allowed.''<br />
<br />
::''- Deny access to known sensitive paths like .snapshots.''<br />
<br />
Local customizations of the apparmor profile are supported by editing the file {{ic|/etc/apparmor.d/local/firejail-local}}<br />
<br />
====Apparmor usage====<br />
There are a number of ways to enable Apparmor confinement on top of a Firejail security profile:<br />
<br />
* Pass the {{ic|--apparmor}} flag to Firejail in the command line, eg {{ic|firejail --apparmor firefox}}<br />
* Use a custom profile.<br />
* Enable Apparmor globally in {{ic|/etc/firejail/globals.local}} and disable as needed through the use of {{ic|ignore apparmor}} in {{ic|/etc/firejail/<ProgramName>.local}}.<br />
<br />
== Firejail with Xephyr ==<br />
<br />
[[Xephyr]] will allow you to sandbox [[Xorg]]. If you want to be able to resize windows, install a window manager such as [[Openbox]].<br />
<br />
{{ic|xephyr-screen ''Width''x''Height''}} can be set in {{ic|/etc/firejail/firejail.config}} where {{ic|''Width''}} and {{ic|''Height''}} are in pixels and based on your screen resolution.<br />
<br />
To open the sandbox:<br />
<br />
$ firejail --x11 --net=''device'' openbox<br />
<br />
{{ic|''device''}} is your active [[network interface]]. Then right click and select your applications to run.<br />
<br />
{{Note|If you use [[Unbound]], [[dnsmasq]], [[Pdnsd]] or any other local cache as your resolver on 127.0.0.1 for example, you would leave {{ic|1=--net=''device''}} out of the command as your network should work automatically.}}<br />
<br />
A great guide can be found on the [https://firejail.wordpress.com/documentation-2/x11-guide/#configurexephyr Firejail Wordpress].<br />
<br />
According to the guide:<br />
<br />
:The sandbox replaces the regular X11 server with Xpra or Xephyr server. This prevents X11 keyboard loggers and screenshot utilities from accessing the main X11 server.<br />
<br />
Note that the statement:<br />
<br />
:The only way to disable the abstract socket {{ic|@/tmp/.X11-unix/X0}} is by using a network namespace. If for any reasons you cannot use a network namespace, the abstract socket will still be visible inside the sandbox. Hackers can attach keylogger and screenshot programs to this socket.<br />
<br />
is incorrect, [[Xinit#xserverrc|xserverrc]] can be edited to {{ic|-nolisten local}} which disables the abstract sockets of X11 and helps isolate it.<br />
<br />
=== Sandboxing a browser ===<br />
<br />
[[Openbox]] can be configured to start a certain browser at startup. {{ic|''program''.profile}} is the respective profile contained in {{ic|/etc/firejail}}, and {{ic|--startup "''command''"}} is the command line used to start the program. For example, to start Chromium in the sandbox:<br />
<br />
$ firejail --x11 --profile=/etc/firejail/chromium.profile openbox --startup "chromium"<br />
<br />
==Tips and tricks==<br />
<br />
=== Paths containing spaces ===<br />
<br />
If you need to reference, whitelist, or blacklist a directory within a custom profile, such as with {{aur|palemoon}}, you must do so using the absolute path, without encapsulation or escapes:<br />
/home/user/.moonchild productions<br />
<br />
===Private mode===<br />
<br />
Firejail also includes a one time private mode, in which no mounts are made in the chroots to your home directory. In doing this, you can execute applications without performing any changes to disk. For example, to execute okular in private mode, do the following:<br />
<br />
$ firejail --seccomp --private okular<br />
<br />
== Troubleshooting ==<br />
<br />
Some applications do not work properly with Firejail, and others simply require special configuration. In the instance any directories are disallowed or blacklisted for any given application, you may have to further edit the profile to enable nonstandard directories that said application needs to access. One example is wine; wine will not work with seccomp in most cases.<br />
<br />
Other configurations exist; it is suggested you check out the man page for firejail to see them all, as firejail is in rapid development.<br />
<br />
=== Remove Firejail symbolic links ===<br />
<br />
To remove Firejail created symbolic links (e.g. reset to default):<br />
<br />
# firecfg --clean<br />
<br />
Verify if any leftovers of [[Desktop entries]] are still overruled by Firejail.<br />
<br />
=== Desktop files ===<br />
<br />
Some GUI application launchers ({{ic|.desktop}} files) are coded using absolute paths to an executable, which circumvents firejail's symlink method of ensuring that it is being used. The ''firecfg'' tool includes an option to over-ride this on a per-user basis by copying the {{ic|.desktop}} files from {{ic|/usr/share/applications/*.desktop}} to {{ic|~/.local/share/applications/}} and replacing the absolute paths with simple file names.<br />
<br />
$ firecfg --fix<br />
<br />
There may cases for which you need to manually modify the EXEC line of the {{ic|.desktop}} file in {{ic|~/.local/share/applications/}} to explicitly call Firejail.<br />
<br />
=== Symbolic links ===<br />
{{Accuracy|Questionable statements, e.g. how does "updatedb" which is only relevant to "locate" matter, otherwise vague or trivial}}<br />
# If used, any location database or hash table will need to be updated/reset.<br />
# Some applications, notably ''Thunar'', run with only one instance. As a result, after symlinking firejail to the application, the profile may not be loaded until the next login.[https://github.com/netblue30/firejail/issues/1311]<br />
<br />
=== PulseAudio ===<br />
{{Note|Using PulseAudio version 9.0 or later should fix this issue.}}<br />
<br />
If Firejail causes [[PulseAudio]] issues with sandboxed applications [https://firejail.wordpress.com/support/known-problems/#pulseaudio], the following command may be used:<br />
<br />
$ firecfg --fix-sound<br />
<br />
This commands creates a custom {{ic|~/.config/pulse/client.conf}} file for the ''current'' user with {{ic|1=enable-shm = no}} and possible other workarounds.<br />
<br />
=== Hidepid ===<br />
<br />
If you have [[hidepid]] installed, Firemon can only be run as root. This, among other things, will cause problems with the Firetools GUI incorrectly reporting "Capabilities", "Protocols" and the status of "Seccomp". See [https://github.com/netblue30/firejail/issues/1564]<br />
<br />
=== Proprietary Nvidia drivers ===<br />
<br />
Some users report problems when using Firejail and proprietary graphic drivers from [[NVIDIA]] (e.g. [https://github.com/netblue30/firejail/issues/1753], [https://github.com/netblue30/firejail/issues/879] or [https://github.com/netblue30/firejail/issues/841]). This can often be solved by disabling the {{ic|noroot}} Firejail option in the application's profile file.<br />
<br />
==See also==<br />
* [https://github.com/netblue30/firejail Firejail GitHub project page]<br />
* [[bubblewrap]], a minimal alternative to Firejail</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545426AppArmor2018-10-01T12:52:14Z<p>Teples: /* Auditing and generating profiles */ Rewrite generating profiles section. Add links to detailed guides at AppArmor wiki.</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
[[Install]] {{Pkg|apparmor}} for userspace tools and libraries to control AppArmor. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
== Usage ==<br />
<br />
=== Display current status ===<br />
<br />
To test if AppArmor has been correctly enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
=== Disabling loading ===<br />
<br />
Disable AppArmor by unloading all profiles for the current session:<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security=apparmor}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
New AppArmor profiles can be created by utilizing {{man|8|aa-genprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-genprof.8.en.html}} and {{man|8|aa-logprof|url=https://manpages.debian.org/unstable/apparmor-utils/aa-logprof.8.en.html}} tools available in {{pkg|apparmor}} package. Detailed guide about using those tools is available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_with_tools AppArmor wiki - Profiling with tools].<br />
<br />
Alternatively profiles may be also created manually, see guide available at [https://gitlab.com/apparmor/apparmor/wikis/Profiling_by_hand AppArmor wiki - Profiling by hand].<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
1. Install and enable [[Audit framework]].<br />
<br />
2. Allow your desktop user to read audit logs with [[Access Control Lists]]:<br />
# setfacl -m u:<user>:rx /var/log/audit # allow <user> to read and navigate below /var/log/audit directory<br />
# setfacl -R -m u:<user>:r /var/log/audit # allow <user> to read all files in /var/log/audit<br />
# setfacl -dm u:<user>:r /var/log/audit # allow <user> to read all new files created inside /var/log/audit<br />
<br />
3. Create desktop launcher with the below content:<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
4. Re-login and check if {{ic|aa-notify}} daemon is running:<br />
$ ps aux |grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
To undo above, run:<br />
# setfacl -R -b /var/log/audit<br />
$ rm ~/.config/autostart/apparmor-notify.desktop<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame |grep apparmor<br />
<br />
To enable caching AppAmror profiles, add two below lines to {{ic|/etc/apparmor/parser.conf}}:<br />
<br />
{{hc|/etc/apparmor/parser.conf|2=<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
cache-loc=/var/cache/apparmor<br />
}}<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame |grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=User_talk:Teples&diff=545423User talk:Teples2018-10-01T12:22:44Z<p>Teples: /* AppArmor in linux */ re</p>
<hr />
<div>== AppArmor in linux ==<br />
<br />
Hi Teples,<br />
<br />
It has been reverted: https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux&id=62b80117614b44f4a17921b0d1cb9b9e6d08fa4e<br />
<br />
I have even asked if it could be enabled again, just for apparmor, unfortunately the answer was no (although good alternatives are available, so it's not a big of a deal).<br />
[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 02:18, 29 September 2018 (UTC)<br />
:Hi Francoism<br />
:<br />
:Please look at the date of the commit you linked (2018-09-03), then please look at the date of the commit linked (by me) in wiki (2018-09-15). The sequence of events was this:<br />
:1. AppArmor enabled<br />
:2. AppArmor disabled (commit you linked)<br />
:3. AppArmor enabled again (commit I linked)<br />
:<br />
:It's easy check what's the current status by looking in the config file: https://git.archlinux.org/svntogit/packages.git/tree/trunk/config?h=packages/linux#n9274 which I checked after seeing your revert even as I was sure what's inside as I follow all commits to linux package in real time.<br />
:<br />
:It's nice that you decided to reach me here, unfortunately only after you reverted my change the second time. Please double check before doing the revert.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 10:14, 29 September 2018 (UTC)<br />
::Oops, missed that commit! Sorry for the revert and thanks for letting me now.<br />
::[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 09:55, 30 September 2018 (UTC)<br />
:::Thanks for updating the cache section. Seems the default cache location is {{ic|/etc/apparmor.d/cache}}, should this be changed to {{ic|/var/cache/apparmor}} and/or should the user create the path? If I don't set {{ic|--cache-loc}} it doesn't produce an error - is it using {{ic|/etc/apparmor.d/cache.d}}?<br />
:::[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 11:18, 1 October 2018 (UTC)<br />
::::{{ic|/var/cache/apparmor}} will be the default location in 2.13.1 release which should be available very soon (perhaps this week) thus I thought it's better to choose it now instead of changing it after few days again. See https://gitlab.com/apparmor/apparmor/commit/affc7a9fb4a42dfbfee396c53214b789ad93d42a . If specified in config, it should be created automatically by apparmor parser, no need to create it manually. If not specified then cache will be put under /etc (until 2.13.1 release). You can see if profile caches are created by listing the cache dir with {{ic|sudo ls -al <cache-dir>}}<br />
::::[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 12:22, 1 October 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545400AppArmor2018-10-01T11:06:17Z<p>Teples: /* Cache profiles */ Rewrite cache section. Add concrete steps to speedup AppArmor loading at boot.</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor by unloading all profiles for the current session, run :<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security="apparmor"}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
1. Install and enable [[Audit framework]].<br />
<br />
2. Allow your desktop user to read audit logs with [[Access Control Lists]]:<br />
# setfacl -m u:<user>:rx /var/log/audit # allow <user> to read and navigate below /var/log/audit directory<br />
# setfacl -R -m u:<user>:r /var/log/audit # allow <user> to read all files in /var/log/audit<br />
# setfacl -dm u:<user>:r /var/log/audit # allow <user> to read all new files created inside /var/log/audit<br />
<br />
3. Create desktop launcher with the below content:<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
4. Re-login and check if {{ic|aa-notify}} daemon is running:<br />
$ ps aux |grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
To undo above, run:<br />
# setfacl -R -b /var/log/audit<br />
$ rm ~/.config/autostart/apparmor-notify.desktop<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Speed-up AppArmor start by caching profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may significantly increase the boot time. You can check current AppArmor startup time with:<br />
<br />
$ systemd-analyze blame |grep apparmor<br />
<br />
To enable caching AppAmror profiles, add two below lines to {{ic|/etc/apparmor/parser.conf}}:<br />
<br />
## Turn creating/updating of the cache on by default<br />
write-cache<br />
cache-loc=/var/cache/apparmor<br />
<br />
Reboot and check AppArmor startup time again to see improvement:<br />
<br />
$ systemd-analyze blame |grep apparmor<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545311AppArmor2018-09-30T16:12:27Z<p>Teples: /* Get desktop notification on DENIED actions */ Add info about checking if aa-notify is running</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor by unloading all profiles for the current session, run :<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security="apparmor"}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
1. Install and enable [[Audit framework]].<br />
<br />
2. Allow your desktop user to read audit logs with [[Access Control Lists]]:<br />
# setfacl -m u:<user>:rx /var/log/audit # allow <user> to read and navigate below /var/log/audit directory<br />
# setfacl -R -m u:<user>:r /var/log/audit # allow <user> to read all files in /var/log/audit<br />
# setfacl -dm u:<user>:r /var/log/audit # allow <user> to read all new files created inside /var/log/audit<br />
<br />
3. Create desktop launcher with the below content:<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
4. Re-login and check if {{ic|aa-notify}} daemon is running:<br />
$ ps aux |grep aa-notify<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
To undo above, run:<br />
# setfacl -R -b /var/log/audit<br />
$ rm ~/.config/autostart/apparmor-notify.desktop<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545310AppArmor2018-09-30T16:08:30Z<p>Teples: /* Get desktop notification on DENIED actions */ Rewrite section. Add concrete step-by-step actions to enable AppArmor desktop notifications.</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[https://gitlab.com/apparmor AppArmor] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor by unloading all profiles for the current session, run :<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security="apparmor"}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} man page and [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notification daemon displays desktop notifications whenever AppArmor denies a program access. To automatically start {{ic|aa-notify}} daemon on login follow below steps:<br />
<br />
1. Install and enable [[Audit framework]].<br />
<br />
2. Allow your desktop user to read audit logs with [[Access Control Lists]]:<br />
# setfacl -m u:<user>:rx /var/log/audit # allow <user> to read and navigate below /var/log/audit directory<br />
# setfacl -R -m u:<user>:r /var/log/audit # allow <user> to read all files in /var/log/audit<br />
# setfacl -dm u:<user>:r /var/log/audit # allow <user> to read all new files created inside /var/log/audit<br />
<br />
3. Create desktop launcher with the below content:<br />
{{hc|~/.config/autostart/apparmor-notify.desktop|2=<br />
[Desktop Entry]<br />
Type=Application<br />
Name=AppArmor Notify<br />
Comment=Receive on screen notifications of AppArmor denials<br />
TryExec=/usr/bin/aa-notify<br />
Exec=/usr/bin/aa-notify -p -s 1 -w 60<br />
StartupNotify=false<br />
NoDisplay=true<br />
}}<br />
<br />
{{Note|Depending on your specific system configuration there could be A LOT of notifications displayed.}}<br />
<br />
To undo above, run:<br />
# setfacl -R -b /var/log/audit<br />
$ rm ~/.config/autostart/apparmor-notify.desktop<br />
<br />
For more information, see {{man|8|aa-notify|url=https://manpages.debian.org/unstable/apparmor-notify/aa-notify.8.en.html}}.<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Failing to start Samba SMB/CIFS server ===<br />
<br />
See [[Samba#Permission issues on AppArmor]].<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:AppArmor]]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545232AppArmor2018-09-30T09:33:38Z<p>Teples: /* See also */ Add link to openSUSE AppArmor security guide which has a lot of info</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[[Wikipedia:AppArmor|AppArmor]] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor by unloading all profiles for the current session, run :<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security="apparmor"}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notify daemon displays desktop notifications whenever AppArmor denies a program access. The script must be started at each boot and needs a few additional parameters:<br />
<br />
# aa-notify -p -f /var/log/audit/audit.log --display $DISPLAY<br />
<br />
The daemon relies on the auditing events being logged to a text file which can be specified using {{ic|-f}}. To circumvent [[systemd]] not logging to a file it is necessary to [[enable]] {{ic|auditd.service}} and pass its log file to {{ic|aa-notify}}. No special auditing rules are necessary for this to work, therefore the overhead is not as significant as it was when [[#Auditing and generating profiles]].<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} — Structure of the AppArmor configuration directory<br />
* {{man|8|apparmor_parser|url=http://manpages.ubuntu.com/manpages/bionic/man8/apparmor_parser.8.html}} — The most fundamental AppArmor utility to load, unload, cache and stat profiles<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [https://wiki.ubuntu.com/ApparmorProfileMigration Apparmor Profile Migration] — Emergence of profiles<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://launchpad.net/apparmor Launchpad Project Page]<br />
* [https://gitlab.com/apparmor AppArmor GitLab project page]<br />
* [https://doc.opensuse.org/documentation/leap/security/single-html/book.security/index.html#part.apparmor AppArmor in openSUSE Security Guide]</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545222AppArmor2018-09-30T09:08:13Z<p>Teples: /* Disabling */ Add proper info about disabling apparmor at runtime, update info about disabling apparmor in kernel</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[[Wikipedia:AppArmor|AppArmor]] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor by unloading all profiles for the current session, run :<br />
<br />
# aa-teardown <br />
<br />
To prevent from loading AppArmor profiles at the next boot [[disable]] {{ic|apparmor.service}}. To prevent the kernel from loading AppArmor, remove {{ic|1=apparmor=1 security="apparmor"}} from the [[kernel parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notify daemon displays desktop notifications whenever AppArmor denies a program access. The script must be started at each boot and needs a few additional parameters:<br />
<br />
# aa-notify -p -f /var/log/audit/audit.log --display $DISPLAY<br />
<br />
The daemon relies on the auditing events being logged to a text file which can be specified using {{ic|-f}}. To circumvent [[systemd]] not logging to a file it is necessary to [[enable]] {{ic|auditd.service}} and pass its log file to {{ic|aa-notify}}. No special auditing rules are necessary for this to work, therefore the overhead is not as significant as it was when [[#Auditing and generating profiles]].<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} — Structure of the AppArmor configuration directory<br />
* {{man|8|apparmor_parser|url=http://manpages.ubuntu.com/manpages/bionic/man8/apparmor_parser.8.html}} — The most fundamental AppArmor utility to load, unload, cache and stat profiles<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [https://wiki.ubuntu.com/ApparmorProfileMigration Apparmor Profile Migration] — Emergence of profiles<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://launchpad.net/apparmor Launchpad Project Page]<br />
* [https://gitlab.com/apparmor AppArmor GitLab project page]<br />
* {{Bug|21406}} — Initial discussion about the introduction of AppArmor</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=545215AppArmor2018-09-30T08:53:00Z<p>Teples: /* Userspace Tools */ apparmor package officially available in Arch Linux community repo</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[[Wikipedia:AppArmor|AppArmor]] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]).<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} package. To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor for the current session, [[stop]] {{ic|apparmor.service}}, or [[disable]] it to prevent it from starting at the next boot.<br />
<br />
Alternatively you may choose to disable the kernel modules required by AppArmor by appending {{ic|1=apparmor=0 security=""}} to the [[kernel parameters|kernel boot parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notify daemon displays desktop notifications whenever AppArmor denies a program access. The script must be started at each boot and needs a few additional parameters:<br />
<br />
# aa-notify -p -f /var/log/audit/audit.log --display $DISPLAY<br />
<br />
The daemon relies on the auditing events being logged to a text file which can be specified using {{ic|-f}}. To circumvent [[systemd]] not logging to a file it is necessary to [[enable]] {{ic|auditd.service}} and pass its log file to {{ic|aa-notify}}. No special auditing rules are necessary for this to work, therefore the overhead is not as significant as it was when [[#Auditing and generating profiles]].<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} — Structure of the AppArmor configuration directory<br />
* {{man|8|apparmor_parser|url=http://manpages.ubuntu.com/manpages/bionic/man8/apparmor_parser.8.html}} — The most fundamental AppArmor utility to load, unload, cache and stat profiles<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [https://wiki.ubuntu.com/ApparmorProfileMigration Apparmor Profile Migration] — Emergence of profiles<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://launchpad.net/apparmor Launchpad Project Page]<br />
* [https://gitlab.com/apparmor AppArmor GitLab project page]<br />
* {{Bug|21406}} — Initial discussion about the introduction of AppArmor</div>Tepleshttps://wiki.archlinux.org/index.php?title=User_talk:Teples&diff=544682User talk:Teples2018-09-29T10:14:44Z<p>Teples: /* AppArmor in linux */</p>
<hr />
<div>== AppArmor in linux ==<br />
<br />
Hi Teples,<br />
<br />
It has been reverted: https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux&id=62b80117614b44f4a17921b0d1cb9b9e6d08fa4e<br />
<br />
I have even asked if it could be enabled again, just for apparmor, unfortunately the answer was no (although good alternatives are available, so it's not a big of a deal).<br />
[[User:Francoism|Francoism]] ([[User talk:Francoism|talk]]) 02:18, 29 September 2018 (UTC)<br />
:Hi Francoism<br />
:<br />
:Please look at the date of the commit you linked (2018-09-03), then please look at the date of the commit linked (by me) in wiki (2018-09-15). The sequence of events was this:<br />
:1. AppArmor enabled<br />
:2. AppArmor disabled (commit you linked)<br />
:3. AppArmor enabled again (commit I linked)<br />
:<br />
:It's easy check what's the current status by looking in the config file: https://git.archlinux.org/svntogit/packages.git/tree/trunk/config?h=packages/linux#n9274 which I checked after seeing your revert even as I was sure what's inside as I follow all commits to linux package in real time.<br />
:<br />
:It's nice that you decided to reach me here, unfortunately only after you reverted my change the second time. Please double check before doing the revert.<br />
:[[User:Teples|Teples]] ([[User talk:Teples|talk]]) 10:14, 29 September 2018 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=AppArmor&diff=544547AppArmor2018-09-28T22:37:18Z<p>Teples: Undo revision 544208 by Francoism (talk) AppArmor is available in 'linux' package (exact commit is even linked).</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:AppArmor]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|SELinux}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
[[Wikipedia:AppArmor|AppArmor]] is a [[Mandatory Access Control]] (MAC) system, implemented upon the [[Wikipedia:Linux_Security_Modules|Linux Security Modules]] (LSM).<br />
<br />
AppArmor, like most other LSMs, supplements rather than replaces the default Discretionary Access Control (DAC). As such it's impossible to grant a process more privileges than it had in the first place. <br />
<br />
Ubuntu, SUSE and a number of other distributions use it by default. RHEL (and its variants) use SELinux which requires good userspace integration to work properly. SELinux attaches labels to all files, processes and objects and is therefore very flexible. However configuring SELinux is considered to be very complicated and requires a supported filesystem. AppArmor on the other hand works using file paths and its configuration can be easily adapted.<br />
<br />
AppArmor proactively protects the operating system and applications from external or internal threats and even zero-day attacks by enforcing a specific rule set on a per application basis. Security policies completely define what system resources individual applications can access, and with what privileges. Access is denied by default if no profile says otherwise. A few default policies are included with AppArmor and using a combination of advanced static analysis and learning-based tools, AppArmor policies for even very complex applications can be deployed successfully in a matter of hours.<br />
<br />
Every breach of policy triggers a message in the system log, and AppArmor can be configured to notify users with real-time violation warnings popping up on the desktop.<br />
<br />
== Installation ==<br />
<br />
=== Kernel ===<br />
<br />
AppArmor is available in {{Pkg|linux}} ([https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc since 4.18.8.arch1-1]), {{Pkg|linux-zen}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-zen&id=3ab708208c8e13d5de08dabebc442d2d0be7a585 since 4.18.8.zen1-1]) and {{Pkg|linux-hardened}} ([https://git.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-hardened&id=14eccc6c604d37fa3001146f5bd4ca32ffa15c4f since 4.17.4.a-1]). Another option is to compile a [[#Custom kernel]].<br />
<br />
To enable AppArmor as default security model on every boot, set the following [[kernel parameters]]:<br />
<br />
apparmor=1 security=apparmor<br />
<br />
==== Custom kernel ====<br />
<br />
When [[Kernels#Compilation|compiling the kernel]], it is required to set at least the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR=y<br />
CONFIG_AUDIT=y<br />
<br />
To use AppArmor as the default Linux security model and omitting the need of setting kernel parameters, also set the following options:<br />
<br />
CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE=1<br />
CONFIG_DEFAULT_SECURITY_APPARMOR=y<br />
<br />
=== Userspace Tools ===<br />
<br />
The userspace tools and libraries to control AppArmor are supplied by {{Pkg|apparmor}} or {{AUR|apparmor}}.<br />
<br />
{{Note|The {{AUR|apparmor}} package will no longer be updated, it will be replaced by the {{Pkg|apparmor}} package that is currently in ''community-testing''. To use it you must enable the [[Official repositories#Testing repositories|testing repositories]].}}<br />
<br />
The {{AUR|apparmor}} package is a split package which consists of following sub-packages:<br />
<br />
* {{AUR|apparmor}} (meta package)<br />
* {{AUR|apparmor-libapparmor}}<br />
* {{AUR|apparmor-utils}}<br />
* {{AUR|apparmor-parser}}<br />
* {{AUR|apparmor-profiles}}<br />
* {{AUR|apparmor-pam}}<br />
* {{AUR|apparmor-vim}}<br />
<br />
To load all AppArmor profiles on startup, [[enable]] {{ic|apparmor.service}}.<br />
<br />
=== Testing ===<br />
<br />
To test if AppArmor has been enabled:<br />
<br />
{{hc|$ cat /sys/module/apparmor/parameters/enabled|<br />
Y<br />
}}<br />
<br />
{{ic|Y}} — enabled, {{ic|N}} — disabled, {{ic|no such file}} — module not in kernel.<br />
<br />
To display the current loaded status use {{ic|apparmor_status}}:<br />
<br />
{{hc|# apparmor_status|<br />
apparmor module is loaded.<br />
44 profiles are loaded.<br />
44 profiles are in enforce mode.<br />
...<br />
0 profiles are in complain mode.<br />
0 processes have profiles defined.<br />
0 processes are in enforce mode.<br />
0 processes are in complain mode.<br />
0 processes are unconfined but have a profile defined.<br />
}}<br />
<br />
== Disabling ==<br />
<br />
To disable AppArmor for the current session, [[stop]] {{ic|apparmor.service}}, or [[disable]] it to prevent it from starting at the next boot.<br />
<br />
Alternatively you may choose to disable the kernel modules required by AppArmor by appending {{ic|1=apparmor=0 security=""}} to the [[kernel parameters|kernel boot parameters]].<br />
<br />
== Configuration ==<br />
<br />
=== Auditing and generating profiles ===<br />
<br />
To create new profiles the [[Audit framework]] should be running. This is because Arch Linux adopted [[systemd]] and doesn't do kernel logging to file by default. AppArmor can grab kernel audit logs from the userspace auditd daemon, allowing you to build a profile.<br />
<br />
To get kernel audit logs, you'll need to have rules in place to monitor the desired application. Most often a basic rule configured with {{man|8|auditctl}} will suffice:<br />
<br />
# auditctl -a exit,always -F arch=b64 -S all -F path=/usr/bin/chromium -F key=MonitorChromium<br />
<br />
Be sure to read [[Audit framework#Adding rules]] if this is unfamiliar to you.<br />
<br />
{{Note|Remember to stop the service afterwards (and maybe clear {{ic|/var/log/audit/audit.log}}) because it may cause overhead depending on your rules.}}<br />
<br />
=== Understanding profiles ===<br />
<br />
Profiles are human readable text files residing under {{ic|/etc/apparmor.d/}} describing how binaries should be treated when executed. A basic profile looks similar to this:<br />
<br />
{{hc|/etc/apparmor.d/usr.bin.test|<br />
#include <tunables/global><br />
<br />
profile test /usr/lib/test/test_binary {<br />
#include <abstractions/base><br />
<br />
# Main libraries and plugins<br />
/usr/share/TEST/** r,<br />
/usr/lib/TEST/** rm,<br />
<br />
# Configuration files and logs<br />
@{HOME}/.config/ r,<br />
@{HOME}/.config/TEST/** rw,<br />
}<br />
}}<br />
<br />
Strings preceded by a {{ic|@}} symbol are variables defined by abstractions ({{ic|/etc/apparmor.d/abstractions/}}), tunables ({{ic|/etc/apparmor.d/tunables/}}) or by the profile itself. {{ic|#include}} includes other profile-files directly. Paths followed by a set of characters are [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#file-access-rules access permissions]. Pattern matching is done using [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#apparmor-globbing-syntax AppArmor's globbing syntax].<br />
<br />
Most common use cases are covered by the following statements:<br />
<br />
* {{ic|r}} — read: read data<br />
* {{ic|w}} — write: create, delete, write to a file and extend it<br />
* {{ic|m}} — memory map executable: memory map a file executable<br />
* {{ic|x}} — execute: execute file; needs to be preceded by a [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference#execute-rules qualifier]<br />
<br />
Remember that those permission do not allow binaries to exceed the permission dictated by the Discretionary Access Control (DAC).<br />
<br />
This is merely a short overview, for a more detailed guide be sure to have a look at the [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference documentation].<br />
<br />
=== Parsing profiles ===<br />
<br />
To load (enforce or complain), unload, reload, cache and stat profiles use {{ic|apparmor_parser}}. The default action ({{ic|-a}}) is to load a new profile in enforce mode, loading it in complain mode is possible using the {{ic|-C}} switch, in order to overwrite an existing profile use the {{ic|-r}} option and to remove a profile use {{ic|-R}}. Each action may also apply to multiple profiles. Refer to {{man|8|apparmor_parser|url=https://man.cx/apparmor_parser(8)}} man page for more information.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Get desktop notification on DENIED actions ===<br />
<br />
The notify daemon displays desktop notifications whenever AppArmor denies a program access. The script must be started at each boot and needs a few additional parameters:<br />
<br />
# aa-notify -p -f /var/log/audit/audit.log --display $DISPLAY<br />
<br />
The daemon relies on the auditing events being logged to a text file which can be specified using {{ic|-f}}. To circumvent [[systemd]] not logging to a file it is necessary to [[enable]] {{ic|auditd.service}} and pass its log file to {{ic|aa-notify}}. No special auditing rules are necessary for this to work, therefore the overhead is not as significant as it was when [[#Auditing and generating profiles]].<br />
<br />
=== Cache profiles ===<br />
<br />
Since AppArmor has to translate the configured profiles into a binary format it may take some time to load them. Besides being bothersome for the user, it may also increases the boot time significantly!<br />
<br />
To circumvent some of those problems AppArmor can cache profiles in {{ic|/etc/apparmor.d/cache/}}. However this behaviour is disabled by default therefore it must be done manually with {{ic|apparmor_parser}}. In order to write to the cache use {{ic|-W}} (overwrite existing profiles with {{ic|-T}}) and reload the profiles using {{ic|-r}}. Refer to [[#Parsing profiles]] for a brief overview of additional arguments.<br />
<br />
== See also ==<br />
<br />
* [https://gitlab.com/apparmor/apparmor/wikis/home AppArmor wiki]<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_Core_Policy_Reference AppArmor Core Policy Reference] — Detailed description of available options in a profile<br />
* [https://ubuntuforums.org/showthread.php?t=1008906 Ubuntu Tutorial] — General overview of available utilities and profile creation<br />
* [https://help.ubuntu.com/community/AppArmor Ubuntu Wiki] — Basic command overview<br />
* [https://gitlab.com/apparmor/apparmor/wikis/AppArmor_versions AppArmor Versions] — Version overview and links to the respective release notes<br />
* {{man|5|apparmor.d|url=http://manpages.ubuntu.com/manpages/bionic/man5/apparmor.d.5.html}} — Structure of the AppArmor configuration directory<br />
* {{man|8|apparmor_parser|url=http://manpages.ubuntu.com/manpages/bionic/man8/apparmor_parser.8.html}} — The most fundamental AppArmor utility to load, unload, cache and stat profiles<br />
* [https://gitlab.com/apparmor/apparmor/wikis/Kernel_interfaces Kernel Interfaces] — Low level interfaces to the AppArmor kernel module<br />
* [https://wiki.ubuntu.com/ApparmorProfileMigration Apparmor Profile Migration] — Emergence of profiles<br />
* [[wikipedia:Linux Security Modules]] — Linux kernel module on which basis AppArmor is build upon<br />
* [https://launchpad.net/apparmor Launchpad Project Page]<br />
* [https://gitlab.com/apparmor AppArmor GitLab project page]<br />
* {{Bug|21406}} — Initial discussion about the introduction of AppArmor</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=541872Talk:AppArmor2018-09-17T20:41:37Z<p>Teples: /* blog about arch apparmor */ Link no longer exist, severly outdated info</p>
<hr />
<div>== <s>blog about arch apparmor</s> ==<br />
This blogger has recently tested Apparmor, but he does say it needs patching and mods to the PKGBUILD to work. Check it out: - http://c0debreak.blogspot.com/2012/06/enabling-apparmor-in-arch-linux.html [[User:Iruel|Iruel]] ([[User talk:Iruel|talk]])<br />
<br />
To install it I needed to install bison27 from aur as with bison from base-devel I wasn't able to compile. Should I add this infomation in the "AppArmor Packages" section? <br />
<br />
[[User:Valo|Valo]] ([[User talk:Valo|talk]]) 08:46, 7 September 2013 (UTC)<br />
<br />
== <s>core/linux 3.14 Removed Apparmor Support</s>==<br />
<br />
Just when 3.13 came around and had working apparmor in the stock kernel, it got removed from mainline in 3.14. So this article is going to require deep rewrites, and someone will need to bring linux-apparmor up to date and maintain that.<br />
{{unsigned|10 April 2014 3:40|Zanny}}<br />
<br />
Can anyone provide informations about why the apparmor support has been dropped? [[User:Marcus039|Marcus039]] ([[User talk:Marcus039|talk]]) 01:25, 21 February 2016 (UTC)<br />
<br />
:One main point was that it was enabled in the kernel, although the required userspace tools were not supported in the official repos. See [http://archlinux.2023198.n4.nabble.com/Trimming-down-our-default-kernel-configuration-td4696628.html] for the discussion. --[[User:Indigo|Indigo]] ([[User talk:Indigo|talk]]) 09:03, 21 February 2016 (UTC)<br />
<br />
== re: LTS kernel edits ==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=Talk:AppArmor&diff=541871Talk:AppArmor2018-09-17T20:39:40Z<p>Teples: /* core/linux 3.14 Removed Apparmor Support */ No longer true after https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc</p>
<hr />
<div>== blog about arch apparmor ==<br />
This blogger has recently tested Apparmor, but he does say it needs patching and mods to the PKGBUILD to work. Check it out: - http://c0debreak.blogspot.com/2012/06/enabling-apparmor-in-arch-linux.html [[User:Iruel|Iruel]] ([[User talk:Iruel|talk]])<br />
<br />
To install it I needed to install bison27 from aur as with bison from base-devel I wasn't able to compile. Should I add this infomation in the "AppArmor Packages" section? <br />
<br />
[[User:Valo|Valo]] ([[User talk:Valo|talk]]) 08:46, 7 September 2013 (UTC)<br />
<br />
== <s>core/linux 3.14 Removed Apparmor Support</s>==<br />
<br />
Just when 3.13 came around and had working apparmor in the stock kernel, it got removed from mainline in 3.14. So this article is going to require deep rewrites, and someone will need to bring linux-apparmor up to date and maintain that.<br />
{{unsigned|10 April 2014 3:40|Zanny}}<br />
<br />
Can anyone provide informations about why the apparmor support has been dropped? [[User:Marcus039|Marcus039]] ([[User talk:Marcus039|talk]]) 01:25, 21 February 2016 (UTC)<br />
<br />
:One main point was that it was enabled in the kernel, although the required userspace tools were not supported in the official repos. See [http://archlinux.2023198.n4.nabble.com/Trimming-down-our-default-kernel-configuration-td4696628.html] for the discussion. --[[User:Indigo|Indigo]] ([[User talk:Indigo|talk]]) 09:03, 21 February 2016 (UTC)<br />
<br />
== re: LTS kernel edits ==<br />
<br />
The {{pkg|linux-lts}} package [https://projects.archlinux.org/svntogit/packages.git/commit/trunk?h=packages/linux-lts&id=ff72f001939615403dd11b4975a7dbb3b2dcfdf2 has dropped support for AppArmor] so using that isn't a solution. -- [[User:Thestinger|thestinger]] ([[User talk:Thestinger|talk]]) 12:35, 5 July 2014 (UTC)</div>Tepleshttps://wiki.archlinux.org/index.php?title=SELinux&diff=541849SELinux2018-09-17T19:09:14Z<p>Teples: /* Preparing the Kernel */ Remove obsolete section</p>
<hr />
<div>[[Category:Security]]<br />
[[Category:Kernel]]<br />
[[ja:SELinux]]<br />
[[ru:SELinux]]<br />
{{Related articles start}}<br />
{{Related|Security}}<br />
{{Related|AppArmor}}<br />
{{Related|TOMOYO Linux}}<br />
{{Related articles end}}<br />
<br />
Security-Enhanced Linux (SELinux) is a Linux feature that provides a variety of security policies, including U.S. Department of Defense style [[Mandatory Access Control]] (MAC), through the use of Linux Security Modules (LSM) in the Linux kernel. It is not a Linux distribution, but rather a set of modifications that can be applied to Unix-like operating systems, such as Linux and BSD.<br />
<br />
Running SELinux under a Linux distribution requires three things: An SELinux enabled kernel, SELinux Userspace tools and libraries, and SELinux Policies (mostly based on the Reference Policy). Some common Linux programs will also need to be patched/compiled with SELinux features.<br />
<br />
==Current status in Arch Linux==<br />
<br />
SELinux is not officially supported (see [https://lists.archlinux.org/pipermail/arch-general/2013-October/034352.html][https://lists.archlinux.org/pipermail/arch-general/2017-February/043149.html]). The status of unofficial support is:<br />
<br />
{| class="wikitable"<br />
! Name !! Status !! Available at<br />
|-<br />
| SELinux enabled kernel || Implemented for {{pkg|linux}}, {{pkg|linux-zen}} and {{pkg|linux-hardened}} || Available in official repositories since [https://git.archlinux.org/svntogit/packages.git/commit/?id=c46609a4b0325c363455264844091b71de01eddc 4.18.8].<br />
|-<br />
| SELinux Userspace tools and libraries || Implemented in AUR: https://aur.archlinux.org/packages/?O=0&K=selinux || Work is done at https://github.com/archlinuxhardened/selinux<br />
|-<br />
| SELinux Policy || Work in progress, using [https://github.com/TresysTechnology/refpolicy Reference Policy] as upstream || Upstream: https://github.com/TresysTechnology/refpolicy (since release 20170805 the policy has integrated support for systemd and single-/usr/bin directory)<br />
|}<br />
<br />
Summary of changes in AUR as compared to official core packages:<br />
<br />
{| class="wikitable"<br />
! Name !! Status and comments<br />
|-<br />
| linux || Need following [[kernel_parameters]] at boot: {{ic|1=selinux=1 security=selinux}}<br />
|-<br />
| linux-hardened || Need following [[kernel_parameters]] at boot: {{ic|1=selinux=1 security=selinux}}<br />
|-<br />
| coreutils || Need a rebuild with {{ic|--with-selinux}} flag to link with libselinux<br />
|-<br />
| cronie || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| dbus || Need a rebuild with {{ic|--enable-libaudit}} and {{ic|--enable-selinux}} flags<br />
|-<br />
| findutils || Need a rebuild with libselinux installed to enable SELinux-specific options<br />
|-<br />
| iproute2 || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| logrotate || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| openssh || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| pam || Need a rebuild with {{ic|--enable-selinux}} flag for Linux-PAM ; Need a patch for pam_unix2, which only removes a function already implemented in a recent versions of libselinux<br />
|-<br />
| pambase || Configuration changes to add pam_selinux.so to {{ic|/etc/pam.d/system-login}}<br />
|-<br />
| psmisc || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| shadow || Need a rebuild with {{ic|--with-selinux}} flags<br />
|-<br />
| sudo || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
| systemd || Need a rebuild with {{ic|--enable-audit}} and {{ic|--enable-selinux}} flags<br />
|-<br />
| util-linux || Need a rebuild with {{ic|--with-selinux}} flag<br />
|-<br />
|}<br />
<br />
All of the other SELinux-related packages may be included without changes nor risks.<br />
<br />
==Concepts: Mandatory Access Controls==<br />
<br />
{{Note|This section is meant for beginners. If you know what SELinux does and how it works, feel free to skip ahead to the installation.}}<br />
<br />
Before you enable SELinux, it is worth understanding what it does. Simply and succinctly, SELinux enforces ''Mandatory Access Controls (MACs)'' on Linux. In contrast to SELinux, the traditional user/group/rwx permissions are a form of ''Discretionary Access Control (DAC)''. MACs are different from DACs because security policy and its execution are completely separated.<br />
<br />
An example would be the use of the ''sudo'' command. When DACs are enforced, sudo allows temporary privilege escalation to root, giving the process so spawned unrestricted systemwide access. However, when using MACs, if the security administrator deems the process to have access only to a certain set of files, then no matter what the kind of privilege escalation used, unless the security policy itself is changed, the process will remain constrained to simply that set of files. So if ''sudo'' is tried on a machine with SELinux running in order for a process to gain access to files its policy does not allow, it will fail.<br />
<br />
Another set of examples are the traditional (-rwxr-xr-x) type permissions given to files. When under DAC, these are user-modifiable. However, under MAC, a security administrator can choose to freeze the permissions of a certain file by which it would become impossible for any user to change these permissions until the policy regarding that file is changed.<br />
<br />
As you may imagine, this is particularly useful for processes which have the potential to be compromised, i.e. web servers and the like. If DACs are used, then there is a particularly good chance of havoc being wreaked by a compromised program which has access to privilege escalation.<br />
<br />
For further information, visit [[wikipedia:Mandatory access control]].<br />
<br />
==Installing SELinux==<br />
<br />
===Package description===<br />
<br />
All SELinux related packages belong to the ''selinux'' group in the AUR.<br />
<br />
====SELinux aware system utilities====<br />
<br />
;{{AUR|coreutils-selinux}}<br />
:Modified coreutils package compiled with SELinux support enabled. It replaces the {{pkg|coreutils}} package<br />
<br />
;{{AUR|cronie-selinux}}<br />
:Fedora fork of Vixie cron with SELinux enabled. It replaces the {{pkg|cronie}} package.<br />
<br />
;{{AUR|dbus-selinux}}<br />
:An SELinux aware version of [[D-Bus]]. It replaces the {{pkg|dbus}} package.<br />
<br />
;{{AUR|findutils-selinux}}<br />
:Patched findutils package compiled with SELinux support to make searching of files with specified security context possible. It replaces the {{pkg|findutils}} package.<br />
<br />
;{{AUR|iproute2-selinux}}<br />
:iproute2 package compiled with SELinux support; for example, it adds the {{ic|-Z}} option to {{ic|ss}}. It replaces the {{pkg|iproute2}} package.<br />
<br />
;{{AUR|logrotate-selinux}}<br />
:Logrotate package compiled with SELinux support. It replaces the {{pkg|logrotate}} package.<br />
<br />
;{{AUR|openssh-selinux}}<br />
:[[OpenSSH]] package compiled with SELinux support to set security context for user sessions. It replaces the {{pkg|openssh}} package.<br />
<br />
;{{AUR|pam-selinux}} and {{AUR|pambase-selinux}}<br />
:PAM package with pam_selinux.so. and the underlying base package. They replace the {{pkg|pam}} and {{pkg|pambase}} packages respectively.<br />
<br />
;{{AUR|psmisc-selinux}}<br />
:Psmisc package compiled with SELinux support; for example, it adds the {{ic|-Z}} option to {{ic|killall}}. It replaces the {{pkg|psmisc}} package.<br />
<br />
;{{AUR|shadow-selinux}}<br />
:Shadow package compiled with SELinux support; contains a modified {{ic|/etc/pam.d/login}} file to set correct security context for user after login. It replaces the {{pkg|shadow}} package.<br />
<br />
;{{AUR|sudo-selinux}}<br />
:Modified [[sudo]] package compiled with SELinux support which sets the security context correctly. It replaces the {{pkg|sudo}} package.<br />
<br />
;{{AUR|systemd-selinux}}<br />
:An SELinux aware version of [[Systemd]]. It replaces the {{pkg|systemd}} package.<br />
<br />
;{{AUR|util-linux-selinux}}<br />
:Modified util-linux package compiled with SELinux support enabled. It replaces the {{pkg|util-linux}} package.<br />
<br />
====SELinux userspace utilities====<br />
;{{AUR|checkpolicy}}<br />
:Tools to build SELinux policy<br />
<br />
;{{AUR|mcstrans}}<br />
:Daemon which is used by libselinux to translate MCS labels<br />
<br />
;{{AUR|libselinux}}<br />
:Library for security-aware applications. Python bindings needed for ''semanage'' and ''setools'' now included.<br />
<br />
;{{AUR|libsemanage}}<br />
:Library for policy management. Python bindings needed for ''semanage'' and ''setools'' now included.<br />
<br />
;{{AUR|libsepol}}<br />
:Library for binary policy manipulation.<br />
<br />
;{{AUR|policycoreutils}}<br />
:SELinux core utils such as newrole, setfiles, etc.<br />
<br />
;{{AUR|restorecond}}<br />
:Daemon which maintains the label of some files<br />
<br />
;{{AUR|secilc}}<br />
:Compiler for SELinux policies written in CIL (Common Intermediate Language)<br />
<br />
;{{AUR|selinux-dbus-config}}<br />
:DBus service which allows managing SELinux configuration<br />
<br />
;{{AUR|selinux-gui}}<br />
:SELinux GUI tools (system-config-selinux)<br />
<br />
;{{AUR|selinux-python}} and {{AUR|selinux-python2}}<br />
:SELinux python tools and libraries (semanage, sepolgen, sepolicy, etc.)<br />
<br />
;{{AUR|selinux-sandbox}}<br />
:Sandboxing tool for SELinux<br />
<br />
;{{AUR|semodule-utils}}<br />
:Tools to handle SELinux modules when building a policy<br />
<br />
====SELinux policy packages====<br />
<br />
;{{AUR|selinux-refpolicy-src}}<br />
:Reference policy sources<br />
<br />
;{{AUR|selinux-refpolicy-git}}<br />
:Reference policy git master (https://github.com/TresysTechnology/refpolicy) built with configuration specific for Arch Linux<br />
<br />
;{{AUR|selinux-refpolicy-arch}}<br />
:Precompiled modular Reference policy with headers and documentation but without sources. Development Arch Linux Refpolicy patches included, which fixes issues related to path labeling and systemd support. These patches are also sent to Reference Policy maintainers and their inclusion in {{AUR|selinux-refpolicy-arch}} is mainly a way to perform updates between Refpolicy releases.<br />
<br />
====Other SELinux tools====<br />
<br />
;{{AUR|setools}}<br />
:CLI and GUI tools to manage SELinux<br />
<br />
;{{AUR|selinux-alpm-hook}}<br />
:pacman hook to label files accordingly to SELinux policy when installing and updating packages<br />
<br />
=== Installation ===<br />
<br />
There are two methods to install the requisite SELinux packages.<br />
<br />
==== Via AUR ====<br />
<br />
* First, install SELinux userspace tools and libraries, in this order (because of the dependencies): {{AUR|libsepol}}, {{AUR|libselinux}}, {{AUR|secilc}}, {{AUR|checkpolicy}}, {{AUR|setools}}, {{AUR|libsemanage}}, {{AUR|semodule-utils}}, {{AUR|policycoreutils}}, {{AUR|selinux-python}} (which depends on {{AUR|python-ipy}}), {{AUR|mcstrans}} and {{AUR|restorecond}}.<br />
* Then install {{AUR|pambase-selinux}} and {{AUR|pam-selinux}} and make sure you can login again after the installation completed, because files in {{ic|/etc/pam.d/}} got removed and created when {{pkg|pambase}} got replaced with {{AUR|pambase-selinux}}.<br />
* Next you can recompile some core packages by installing: {{AUR|coreutils-selinux}}, {{AUR|findutils-selinux}}, {{AUR|iproute2-selinux}}, {{AUR|logrotate-selinux}}, {{AUR|openssh-selinux}}, {{AUR|psmisc-selinux}}, {{AUR|shadow-selinux}}, {{AUR|cronie-selinux}}<br />
* Next, backup your {{ic|/etc/sudoers}} file. Install {{AUR|sudo-selinux}} and restore your {{ic|/etc/sudoers}} (it is overridden when this package is installed as a replacement of {{pkg|sudo}}).<br />
* Next come util-linux and systemd. Because of a cyclic makedepends between these two packages which will not be fixed ({{bug|39767}}), you need to build the source package {{AUR|systemd-selinux}}, install {{AUR|libsystemd-selinux}}, build and install {{AUR|util-linux-selinux}} (with {{AUR|libutil-linux-selinux}}) and rebuild and install {{AUR|systemd-selinux}}.<br />
* Next, install {{AUR|dbus-selinux}}.<br />
* Next, install {{AUR|selinux-alpm-hook}} in order to run restorecon every time pacman installs a package.<br />
<br />
After all these steps, you can install a SELinux kernel (like {{AUR|linux-selinux}}) and a policy (like {{AUR|selinux-refpolicy-arch}} or {{AUR|selinux-refpolicy-git}}).<br />
<br />
==== Using the GitHub repository ====<br />
<br />
All packages are maintained at https://github.com/archlinuxhardened/selinux . This repository also contains a script named {{ic|build_and_install_all.sh}} which builds and installs (or updates) all packages in the needed order. Here is an example of a way this script can be used in a user shell to install all packages (with downloading the GPG keys which are used to verify the source tarballs of the package):<br />
<br />
git clone https://github.com/archlinuxhardened/selinux<br />
cd selinux<br />
./recv_gpg_keys.sh<br />
./build_and_install_all.sh<br />
<br />
Of course, it is possible to modify the content of {{ic|build_and_install_all.sh}} before running it, for example if you already have SELinux support in your kernel.<br />
<br />
===Changing boot loader configuration===<br />
<br />
If you have installed a new kernel, make sure that you update your bootloader accordingly to boot on it. Moreover you may need to add {{ic|<nowiki>security=selinux selinux=1</nowiki>}} to the kernel command line. More precisely, if the kernel configuration does not set {{ic|CONFIG_DEFAULT_SECURITY_SELINUX}}, {{ic|<nowiki>security=selinux</nowiki>}} is needed, and if it contains {{ic|<nowiki>CONFIG_SECURITY_SELINUX_BOOTPARAM=y</nowiki>}} {{ic|<nowiki>CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE=0</nowiki>}}, {{ic|<nowiki>selinux=1</nowiki>}} is needed.<br />
<br />
====GRUB====<br />
<br />
Add {{ic|<nowiki>security=selinux selinux=1</nowiki>}} to {{ic|GRUB_CMDLINE_LINUX_DEFAULT}} variable in {{ic|/etc/default/grub}}<br />
Run the following command:<br />
<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
====Syslinux====<br />
<br />
Change your syslinux.cfg file by adding:<br />
<br />
{{hc|/boot/syslinux/syslinux.cfg|<nowiki>LABEL arch-selinux<br />
LINUX ../vmlinuz-linux-selinux<br />
APPEND root=/dev/sda2 ro security=selinux selinux=1<br />
INITRD ../initramfs-linux-selinux.img</nowiki>}}<br />
<br />
at the end. Change "linux-selinux" to whatever kernel you are using.<br />
<br />
====systemd-boot====<br />
<br />
Create a new loader entry, for example in {{ic|/boot/loader/entries/arch-selinux.conf}}:<br />
<br />
{{hc|/boot/loader/entries/arch-selinux.conf|2=<br />
title Arch Linux SELinux<br />
linux /vmlinuz-linux-selinux<br />
initrd /initramfs-linux-selinux.img<br />
options root=/dev/sda2 ro selinux=1 security=selinux<br />
}}<br />
<br />
===Checking PAM===<br />
<br />
A correctly set-up [[PAM]] is important to get the proper security context after login. Check for the presence of the following lines in {{ic|/etc/pam.d/system-login}}:<br />
<br />
{{bc|# pam_selinux.so close should be the first session rule<br />
session required pam_selinux.so close}}<br />
<br />
{{bc|# pam_selinux.so open should only be followed by sessions to be executed in the user context<br />
session required pam_selinux.so open}}<br />
<br />
===Installing a policy===<br />
<br />
{{Warning|The reference policy as given by [https://github.com/TresysTechnology/refpolicy/wiki Tresys] is not very good for Arch Linux, as before release 20170805 almost no file were labelled correctly. The major problems were:<br />
<br />
* {{ic|/lib}} and {{ic|/usr/lib}} were considered different (and also {{ic|/bin}}, {{ic|/sbin}}, {{ic|/usr/bin}} and {{ic|/usr/sbin}}). This introduced some instability when applying labels to the whole system, as files in these folders might be seen with 2 (or 4) different labels. <br />
* systemd was not yet supported (C. PeBenito, main developer of the refpolicy, announced its willingness to work on it in its github repository in October 2014, http://oss.tresys.com/pipermail/refpolicy/2014-October/007430.html)<br />
<br />
Since refpolicy release 20170805 these two points have been addressed, but most people submitting patches to improve the policy use an other distribution (Debian, Gentoo, RHEL, etc.). Therefore the compatibility with Arch Linux packages is not perfect (for example the policy may not support the most recent features of a program). }}<br />
<br />
Policies are the mainstay of SELinux. They are what govern its behaviour. The only policy currently available in the AUR is the Reference Policy. In order to install it, you should use the source files, which may be got from the package {{AUR|selinux-refpolicy-src}} or by downloading the latest release on https://github.com/TresysTechnology/refpolicy/wiki/DownloadRelease#current-release. When using the AUR package, navigate to {{ic|/etc/selinux/refpolicy/src/policy}} and run the following commands:<br />
<br />
{{bc|# make bare<br />
# make conf<br />
# make install}}<br />
<br />
to install the reference policy as it is. Those who know how to write SELinux policies can tweak them to their heart's content before running the commands written above. The command takes a while to do its job and taxes one core of your system completely, so do not worry. Just sit back and let the command run for as long as it takes.<br />
<br />
To load the reference policy run:<br />
{{bc|# make load}}<br />
<br />
Then, make the file {{ic|/etc/selinux/config}} with the following contents (Only works if you used the defaults as mentioned above. If you decided to change the name of the policy, you need to tweak the file):<br />
<br />
{{hc|/etc/selinux/config|<nowiki># This file controls the state of SELinux on the system.<br />
# SELINUX= can take one of these three values:<br />
# enforcing - SELinux security policy is enforced.<br />
# Set this value once you know for sure that SELinux is configured the way you like it and that your system is ready for deployment<br />
# permissive - SELinux prints warnings instead of enforcing.<br />
# Use this to customise your SELinux policies and booleans prior to deployment. Recommended during policy development.<br />
# disabled - No SELinux policy is loaded.<br />
# This is not a recommended setting, for it may cause problems with file labelling<br />
SELINUX=permissive<br />
# SELINUXTYPE= takes the name of SELinux policy to<br />
# be used. Current options are:<br />
# refpolicy (vanilla reference policy)<br />
# <custompolicy> - Substitute <custompolicy> with the name of any custom policy you choose to load<br />
SELINUXTYPE=refpolicy</nowiki>}}<br />
<br />
Now, you may reboot. After rebooting, run:<br />
<br />
# restorecon -r /<br />
<br />
to label your filesystem.<br />
<br />
Now, make a file {{ic|requiredmod.te}} with the contents:<br />
<br />
{{hc|requiredmod.te|<nowiki>module requiredmod 1.0;<br />
<br />
require {<br />
type devpts_t;<br />
type kernel_t;<br />
type device_t;<br />
type var_run_t;<br />
type udev_t;<br />
type hugetlbfs_t;<br />
type udev_tbl_t;<br />
type tmpfs_t;<br />
class sock_file write;<br />
class unix_stream_socket { read write ioctl };<br />
class capability2 block_suspend;<br />
class dir { write add_name };<br />
class filesystem associate;<br />
}<br />
<br />
#============= devpts_t ==============<br />
allow devpts_t device_t:filesystem associate;<br />
<br />
#============= hugetlbfs_t ==============<br />
allow hugetlbfs_t device_t:filesystem associate;<br />
<br />
#============= kernel_t ==============<br />
allow kernel_t self:capability2 block_suspend;<br />
<br />
#============= tmpfs_t ==============<br />
allow tmpfs_t device_t:filesystem associate;<br />
<br />
#============= udev_t ==============<br />
allow udev_t kernel_t:unix_stream_socket { read write ioctl };<br />
allow udev_t udev_tbl_t:dir { write add_name };<br />
allow udev_t var_run_t:sock_file write;</nowiki>}}<br />
<br />
and run the following commands:<br />
<br />
{{bc|<nowiki># checkmodule -m -o requiredmod.mod requiredmod.te<br />
# semodule_package -o requiredmod.pp -m requiredmod.mod<br />
# semodule -i requiredmod.pp</nowiki>}}<br />
<br />
This is required to remove a few messages from {{ic|/var/log/audit/audit.log}} which are a nuisance to deal with in the reference policy. This is an ugly hack and it should be made very clear that the policy so installed simply patches the reference policy in order to hide the effects of incorrect labelling.<br />
<br />
===Testing in a Vagrant virtual machine===<br />
<br />
It is possible to use [[Vagrant]] to provision a virtual Arch Linux machine with SELinux configured. This is a convenient way to test an Arch Linux system running SELinux without modifying a current system. Here are commands which can be used to achieve this:<br />
<br />
git clone https://github.com/archlinuxhardened/selinux<br />
cd selinux/_vagrant<br />
vagrant up<br />
vagrant ssh<br />
<br />
==Post-installation steps==<br />
<br />
You can check that SELinux is working with {{ic|sestatus}}. You should get something like:<br />
<br />
{{bc|<nowiki>SELinux status: enabled<br />
SELinuxfs mount: /sys/fs/selinux<br />
SELinux root directory: /etc/selinux<br />
Loaded policy name: refpolicy<br />
Current mode: permissive<br />
Mode from config file: permissive<br />
Policy MLS status: disabled<br />
Policy deny_unknown status: allowed<br />
Max kernel policy version: 28</nowiki>}}<br />
<br />
To maintain correct context, you can use ''restorecond'':<br />
<br />
# systemctl enable restorecond<br />
<br />
To switch to enforcing mode without rebooting, you can use:<br />
<br />
# echo 1 > /sys/fs/selinux/enforce<br />
<br />
===Swapfiles===<br />
<br />
If you have a swap file instead of a swap partition, issue the following commands in order to set the appropriate security context:<br />
<br />
{{bc|# semanage fcontext -a -t swapfile_t "/path/to/swapfile"<br />
# restorecon /path/to/swapfile}}<br />
<br />
==Working with SELinux==<br />
<br />
SELinux defines security using a different mechanism than traditional Unix access controls. The best way to understand it is by example. For example, the SELinux security context of the apache homepage looks like the following:<br />
<br />
$ls -lZ /var/www/html/index.html<br />
-rw-r--r-- username username system_u:object_r:httpd_sys_content_t /var/www/html/index.html<br />
<br />
The first three and the last columns should be familiar to any (Arch) Linux user. The fourth column is new and has the format:<br />
<br />
user:role:type[:level]<br />
<br />
To explain:<br />
#'''User:''' The SELinux user identity. This can be associated to one or more roles that the SELinux user is allowed to use.<br />
#'''Role:''' The SELinux role. This can be associated to one or more types the SELinux user is allowed to access.<br />
#'''Type:''' When a type is associated with a process, it defines what processes (or domains) the SELinux user (the subject) can access. When a type is associated with an object, it defines what access permissions the SELinux user has to that object.<br />
#'''Level:''' This optional field can also be know as a range and is only present if the policy supports MCS or MLS.<br />
<br />
This is important in case you wish to understand how to build your own policies, for these are the basic building blocks of SELinux. However, for most purposes, there is no need to, for the reference policy is sufficiently mature. However, if you are a power user or someone with very specific needs, then it might be ideal for you to learn how to make your own SELinux policies.<br />
<br />
[http://www.fosteringlinux.com/tag/selinux/ This] is a great series of articles for someone seeking to understand how to work with SELinux.<br />
<br />
==Troubleshooting==<br />
<br />
The place to look for SELinux errors is the systemd journal. In order to see SELinux messages related to the label {{ic|system_u:system_r:policykit_t:s0}} (for example), you would need to run:<br />
<br />
# journalctl _SELINUX_CONTEXT=system_u:system_r:policykit_t:s0<br />
<br />
===Useful tools===<br />
<br />
There are some tools/commands that can greatly help with SELinux. <br />
<br />
;restorecon: Restores the context of a file/directory (or recursively with {{ic|-R}}) based on any policy rules <br />
;chcon: Change the context on a specific file<br />
<br />
===Reporting issues===<br />
<br />
Please report issues on GitHub: https://github.com/archlinuxhardened/selinux/issues<br />
<br />
==See also==<br />
* [[wikipedia:Security-Enhanced_Linux|Security Enhanced Linux]]<br />
* [https://wiki.gentoo.org/wiki/SELinux Gentoo SELinux Handbook]<br />
* [https://fedoraproject.org/wiki/SELinux Fedora Project's SELinux Wiki]<br />
* [https://www.nsa.gov/what-we-do/research/selinux/ NSA's Official SELinux Homepage]<br />
* [http://userspace.selinuxproject.org/ SELinux Userspace Homepage]<br />
** [http://oss.tresys.com/projects/refpolicy Reference Policy Homepage]<br />
** [http://oss.tresys.com/projects/setools SETools Homepage]<br />
* [https://web.archive.org/web/20140816115906/http://jamesthebard.net/archlinux-selinux-and-you-a-trip-down-the-rabbit-hole/ ArchLinux, SELinux and You (archived)]</div>Teples