COMP 3150Operating Systems

01 Introduction

The Linux kernel's security is a layered design: the identity's model, the permission's mechanisms, the security's modules, and the audit's subsystem are the layers, and each layer builds on the one below it. The design's central mechanism is the reference monitor (Lesson 12.1): the kernel's code mediates every access, checks the requester's credentials against the resource's permissions, and grants or denies the access. The mechanism's properties — the tamper-proofness, the always-invoked's mediation, and the small enough to verify — are the authorization's design's requirements, and the Linux kernel's implementation is one of the classical examples.

The Linux security's identity's model is the Unix's inheritance: the users (the accounts with the UIDs), the groups (the accounts' collections with the GIDs), and the credentials (the process's identity's attributes: the real UID and GID, the effective UID and GID, the saved-set UID and GID, and the supplementary groups). The credentials are the process's security's context: the kernel's reference monitor uses them to determine the process's permissions, and the process's capabilities (Lesson 12.3) and the security modules' checks build on them.

The Linux security's permission's mechanisms are the classical's and the modern's:

  • The mode's bits (the classical Unix: the owner's, the group's, and the others' read, the write, and the execute's permissions) and the special's bits (the setuid, the setgid, and the sticky bits).
  • The POSIX ACLs (the finer's granularity: the per-user's and the per-group's permissions beyond the mode's categories).
  • The capabilities (the finer's privileges: the root's all-or-nothing's privileges split into the separate's units).
  • The file attributes (the chattr's flags: the immutable, the append-only, and the other's attributes).

The Linux security's security's modules are the Linux Security Modules (the LSM) framework's implementations: the kernel's hooks that the security modules use to enforce their policies. The two principal implementations are the SELinux (the type enforcement's mandatory access control) and the AppArmor (the path's confinement's mandatory access control). The two systems implement the formal models' concepts (Lesson 12.4): the SELinux's types are the Bell-LaPadula's and the Biba's labels, and the AppArmor's profiles are the per-program's path's restrictions.

The Linux security's authentication's stack is the PAM's (the Pluggable Authentication Modules) and the NSS's (the Name Service Switch) framework: the programs call the PAM's library, and the library's modules perform the authentication's steps; the NSS determines the identity's sources (the local's files, the directory's services). The audit's subsystem (the auditd and the kernel's audit's framework) records the security-relevant events, and it is the AAA model's third pillar's implementation.

This lesson presents the Linux security's implementation. It presents the identity's model (the users, the groups, the credentials, and the /etc/passwd, the /etc/shadow, and the /etc/group). It presents the permission's mechanisms (the mode's bits, the special's bits, the ACLs, the capabilities, and the file attributes). It presents the security's modules' framework (the LSM) and its two principal implementations (the SELinux and the AppArmor). It presents the authentication's stack (the PAM and the NSS), the audit's subsystem, the sudo and su mechanisms, the kernel's security's parameters (the sysctl's settings), and the hardening's practices. It closes with the Linux security's design's review and the lesson's synthesis.

Prerequisites

This lesson builds on Lessons 12.1 through 12.4. The security's goals (the CIA triad), the AAA model, the reference monitor, and the Saltzer and Schroeder principles are assumed (Lesson 12.1). The authentication's mechanisms (the passwords, the PAM, the SSH keys) are assumed (Lesson 12.2). The authorization's concepts (the subjects, the objects, the permissions), the access control matrix, and the four models (the DAC, the MAC, the RBAC, the ABAC) are assumed (Lesson 12.3). The formal models (the Bell-LaPadula, the Biba, the Clark-Wilson, the RBAC's formalization, the ABAC's framework) are assumed (Lesson 12.4). The lesson is the implementation's presentation, and it uses the Linux's tools and interfaces throughout. The file system's permissions (Lesson 10.2) and the process's credentials (Lesson 3.1) are the context for the identity's model's discussion. Familiarity with the Linux command line from Lesson 2.2 is essential, since the interactive activity uses the id, chmod, chown, setfacl, getfacl, getcap, setcap, chattr, lsattr, getenforce, sestatus, aa-status, auditctl, ausearch, and sudo commands.

02 Learning objectives

By the end of this lesson you will be able to

  • Describe the Linux identity's model: the users, the groups, the credentials (the real and effective UIDs and GIDs, the saved-set UIDs and GIDs, and the supplementary groups), and the identity's files (/etc/passwd, /etc/shadow, and /etc/group).
  • Describe the permission's mechanisms: the mode's bits, the special's bits (setuid, setgid, and sticky), and the POSIX ACLs.
  • Describe the Linux capabilities and the file attributes, and explain how each implements the least privilege's principle.
  • Describe the Linux Security Modules (LSM) framework and its two principal implementations (the SELinux and the AppArmor), and explain how each implements the mandatory access control.
  • Describe the authentication's stack (the PAM and the NSS), the audit's subsystem, and the sudo and su mechanisms.
  • Explain the kernel's security's parameters (the sysctl's settings) and the hardening's practices, and evaluate a system's security's configuration.

This lesson contributes to U12.5 and U12.6, and to course learning outcomes CLO1, CLO7, and CLO8.

03 Required reading

  • Operating System Concepts — Chapter 16, Security, and Chapter 17, Protection. The standard treatment of the protection's mechanisms and the operating system's security's implementation.
  • OSTEP — the Security chapters. OSTEP's treatment of the access control's mechanisms and the kernel's security's implementation is the clearest available account, and it is the basis for the worked example in this lesson.
  • Tanenbaum & Bos — Modern Operating Systems, Chapter 9, Security. A complementary treatment that develops the operating system's security's mechanisms from first principles.
  • Kerrisk, M. — The Linux Programming Interface. No Starch Press, 2010. Chapter 8, Users and Groups, and Chapter 9, Process Credentials. The definitive reference for the Linux identity's model and the process's credentials.
  • Bovet, D. P., & Cesati, M. — Understanding the Linux Kernel, 3rd ed. O'Reilly, 2005. Chapter 20, Process Scheduling (the credentials), and the chapters on the access control and the LSM framework.
  • Love, R. — Linux Kernel Development, 3rd ed., Chapters 5, 6, and the chapters on the security's modules.
  • Smalley, S., Vance, C., & Salamon, W. — Implementing SELinux as a Linux Security Module. NAI Labs Technical Report, 2001. The paper that describes the SELinux's implementation as the LSM's first module.
  • Wright, C., Cowan, C., Smalley, S., Morris, J., & Kroah-Hartman, G. — Linux Security Modules: General Security Support for the Linux Kernel. USENIX Annual Technical Conference, 2002. The paper that introduced the LSM framework.
  • Bauer, M. — Paranoid Penguin: A Step-by-Step Guide to Building a Secure Linux Server. No Starch Press, 2005. The hardening's comprehensive reference.
  • Linux man pages: man 1 id, man 1 whoami, man 1 groups, man 5 passwd, man 5 shadow, man 5 group, man 1 chmod, man 1 chown, man 1 chgrp, man 1 umask, man 1 setfacl, man 1 getfacl, man 5 acl, man 7 capabilities, man 8 setcap, man 1 getcap, man 1 lsattr, man 1 chattr, man 5 pam.conf, man 5 pam.d, man 5 nsswitch.conf, man 8 auditctl, man 8 ausearch, man 8 aureport, man 8 auditd, man 5 sudoers, man 8 sudo, man 8 su, man 8 getenforce (or man 1 getenforce), man 8 sestatus, man 8 semanage, man 8 chcon, man 8 setsebool, man 8 restorecon, man 8 aa-status, man 5 apparmor.d, man 8 apparmor_parser, man 8 sysctl, man 5 sysctl.conf, man 5 proc.

Reading strategy

Read the Kerrisk chapters first. They are the definitive reference for the Linux identity's model and the process's credentials, and they explain the real, the effective, and the saved-set UIDs and GIDs (the credentials that the kernel's access checks use) with the clarity that the lesson's discussion requires. Then read the Silberschatz chapter for the protection's mechanisms' formal treatment, and the OSTEP and the Tanenbaum chapters for the complementary views. The LSM's papers (the Wright et al. and the Smalley et al.) are the framework's and the SELinux's primary sources, and they are worth reading for the framework's design's rationale and the SELinux's implementation's details. Finally, the Linux man pages are the practical tools: id shows the current user's identity and the credentials, chmod and chown set the mode's bits and the ownership, setfacl and getfacl manage the ACLs, setcap and getcap manage the capabilities, lsattr and chattr manage the file attributes, getenforce and sestatus show the SELinux's status, aa-status shows the AppArmor's status, and ausearch and aureport examine the audit's logs. Pay particular attention to the distinction between the real and the effective UIDs and GIDs: the real's values are the user's identity (the login's identity), and the effective's values are the identity that the kernel's access checks use (the identity that the process runs as). The distinction is the source of the setuid mechanism's design: a setuid program's process runs with the file's owner's effective UID while the real UID remains the caller's, so the program can perform the privileged operations and then drop the privileges (the privilege's bracketing).

04 Core content

4.1 The Linux security architecture

The Linux security's architecture is the layered design that the kernel and the user-space's tools implement. The layers, from the foundation to the top:

  • The hardware's protection's mechanisms. The processor's privilege's levels (the kernel's mode and the user's mode), the memory's management's unit (the MMU), and the other hardware's features that the kernel uses to enforce the isolation.
  • The kernel's core. The reference monitor's implementation: the system calls' mediation, the process's credentials, the file system's permissions, the signal's delivery, and the other resources' checks.
  • The Linux Security Modules (LSM) framework. The kernel's hooks that the security modules use to enforce their policies. The framework's design is the kernel's accommodation of the multiple access control's models (the MAC's implementations: the SELinux, the AppArmor, the Smack, the TOMOYO, and the others).
  • The user-space's security's services. The authentication's stack (the PAM, the NSS), the identity's services (the sssd, the nscd), and the audit's subsystem (the auditd).
  • The applications' security. The applications' own's access control's mechanisms: the Web servers' authentication, the databases' privileges, the applications' session's management. The applications' security builds on the kernel's and the user-space's services' layers, and it is the application's developers' responsibility.

The architecture's central mechanism is the reference monitor: the kernel's code that mediates the every access. The reference monitor's properties — the tamper-proofness (the user-space's programs cannot modify the kernel's code or its data), the always-invoked's mediation (the every access is checked), and the small enough to verify (the kernel's code is the audit's subject) — are the Linux kernel's security's foundation. The LSM's framework extends the reference monitor's mediation: the hooks are the additional's checks that the security modules perform, and the modules' policies are the additional's constraints that the kernel enforces.

4.2 Users, groups, and the identity's files

The Linux identity's model is the Unix's inheritance: the users (the accounts with the UIDs), the groups (the accounts' collections with the GIDs), and the credentials (the process's identity's attributes). The identity's files are:

/etc/passwd (the user's database)
The world-readable file that holds the users' accounts, one line per user, with the fields: the username, the password's placeholder (the x in the modern systems, because the hashes are in the /etc/shadow), the UID, the GID (the user's primary group), the GECOS field (the full name and the other information), the home's directory, and the login's shell. The file's world-readable's design is the Unix's legacy: the programs (the ls, the ps) need the users' information to display the names instead of the numbers.
/etc/shadow (the passwords' database)
The root-readable-only file that holds the passwords' hashes and the passwords' aging's information, one line per user, with the fields: the username, the password's hash, the last change's date, the minimum's age, the maximum's age, the warning's period, the inactivity's period, the expiry's date, and the reserved field. The file's restrictive permissions (the 000 or the 640, owned by the root) are the security's design: the hashes are the sensitive's data, and the unprivileged's users must not read them.
/etc/group (the groups' database)
The world-readable file that holds the groups, one line per group, with the fields: the group's name, the password's placeholder, the GID, and the members' list. The members' list is the supplementary's groups' definition: a user who is not the group's primary's member can be a supplementary's member, and the user's process acquires the group's permissions when the group's access is checked.
/etc/gshadow (the groups' passwords)
The root-readable-only file that holds the groups' passwords (the rare's feature) and the groups' administrative's information. The file's design is the /etc/shadow's counterpart, and its use is the rare.

The UID (the user's ID) and the GID (the group's ID) are the kernel's numeric's identifiers. The kernel's reference monitor uses the numeric's IDs (not the names), and the user-space's tools translate between the names and the numbers. The convention: the UID 0 is the root (the superuser with the all-or-nothing's privileges, in the classical's model), the UIDs 1–999 are the system's accounts (the daemons' accounts: the daemon, the bin, the www-data, the sshd), and the UIDs 1000 and above are the regular's users' accounts.

The credentials are the process's identity's attributes, and the kernel's access checks use the credentials (not the user's database's entries directly). The credentials' attributes:

  • The real UID and GID (the RUID, the RGID). The identity of the user who started the process (the login's identity). The real's values are the user's identity's record, and they do not change (except by the privileged's operations).
  • The effective UID and GID (the EUID, the EGID). The identity that the kernel's access checks use: the process's permissions are the effective's values' permissions. The effective's values are usually equal to the real's values, but they differ in the setuid and the setgid programs (the process's effective's values are the file's owner's values while the real's values remain the caller's).
  • The saved-set UID and GID (the SUID, the SGID). The saved's values are the effective's values' copy at the execve's time, and they let the process restore the previous effective's values after the privileged's operations (the privilege's dropping). The saved's values are the classical setuid's mechanism's key: the process can switch between the real's and the saved-set's effective's values, so the privileged's program can do its privileged's work and then drop the privileges.
  • The supplementary groups (the supplementary_group_list). The additional's GIDs that the process holds: the groups the user is a member of (beyond the primary's group). The kernel's access checks the supplementary's groups when the file's group's permission is checked: the process's effective's GID and the supplementary's GIDs are compared with the file's group's GID, and the match grants the group's permissions.
  • The capabilities (the cap_effective, cap_permitted, cap_inheritable, cap_bounding, cap_ambient). The process's fine-grained's privileges (the capabilities' sets). The effective set is the capabilities the process can use; the permitted set is the capabilities the process can raise to the effective's set; the inheritable set is the capabilities the process can pass to the executed programs; the bounding set is the capabilities the process can ever acquire; and the ambient set is the capabilities the process passes to the executed programs (the modern's addition).

The credentials' changes are the privileged's operations: the setuid and the setgid system calls change the real or the effective's values, the setresuid and the setresgid change all three (the real, the effective, the saved-set) with the privileges' controls, and the setgroups changes the supplementary's groups. The changes' rules are the kernel's security's design's central's part: the unprivileged's process can change its effective's values to the real's or the saved-set's values (the classical setuid's mechanism), and the privileged's process (the CAP_SETUID, the CAP_SETGID) can change the values arbitrarily.

4.3 The permissions' bits and the special's bits

The permissions' bits (the mode's bits) are the classical Unix's access control's mechanism: the nine bits organized into the three categories (the owner's, the group's, and the others') with the three permissions (the read, the write, and the execute) in each category. The mode is usually written in the octal notation: the 644 (the owner's read and write, the group's read, the others' read), the 755 (the owner's read, write, and execute, the group's and the others' read and execute), the 600 (the owner's read and write only), the 640 (the owner's read and write, the group's read).

The mode's bits' semantics differ for the files and the directories:

  • The files: the read's bit permits the file's contents' reading, the write's bit permits the file's contents' modification, and the execute's bit permits the file's execution (the program's running or the script's interpretation).
  • The directories: the read's bit permits the directory's entries' listing (the ls), the write's bit permits the directory's entries' modification (the files' creation, the deletion, the rename), and the execute's bit permits the directory's traversal (the entries' access, the path's resolution). The execute's bit's importance is the classical subtlety: a directory without the execute's bit cannot be traversed, even if the read's bit is set (the entries can be listed, but they cannot be accessed), and a directory without the read's bit cannot be listed, even if the execute's bit is set (the entries cannot be listed, but they can be accessed if their names are known).

The special's bits are the additional's bits beyond the nine:

The setuid's bit (the 4000)
The bit's presence on an executable file causes the process's effective UID to be the file's owner's UID (instead of the caller's UID) when the file is executed. The mechanism's purpose is the privileged's programs' design: the programs that need the privileged's operations (the passwd, the su, the sudo) are the setuid's root's programs, so the ordinary's users can run them and the programs perform the privileged's work on the users' behalf. The mechanism's risk is the security's vulnerability: a setuid's root's program with a bug (the buffer's overflow, the race's condition, the input's validation's absence) can be exploited by the unprivileged's users to obtain the root's access. The observation is the reason the modern's systems minimize the setuid's programs and prefer the capabilities (the fine-grained's privileges) or the sudo (the controlled's escalation).
The setgid's bit (the 2000)
The bit's presence on an executable file causes the process's effective GID to be the file's group's GID (instead of the caller's GID) when the file is executed. The mechanism's purpose is the analogous to the setuid's, but for the group's privileges. The bit's presence on a directory has a different's effect: the files created in the directory inherit the directory's group (instead of the creator's primary's group), which is the mechanism's use for the shared's directories (the projects' directories with the shared's group's access).
The sticky's bit (the 1000)
The bit's presence on a directory restricts the files' deletion: only the file's owner, the directory's owner, or the root can delete or rename the files in the directory. The mechanism's purpose is the shared's directories' protection: the /tmp's sticky bit (the classical's example) lets every user create the temporary's files, but prevents the users from deleting each other's files. The bit's presence on a file is the obsolete's legacy (the swap's space's hint), and the modern's systems ignore it.

The special's bits are set with the chmod's symbolic or octal notation: the chmod u+s file (the setuid), the chmod g+s dir (the setgid), the chmod +t dir (the sticky), or the octal's forms (the 4755, the 2755, the 1755). The bits' display: the ls -l's output shows the setuid and the setgid's bits as the s in the owner's or the group's execute's position (the rwsr-xr-x for the setuid, the rwxr-sr-x for the setgid), and the sticky's bit as the t in the others' execute's position (the rwxrwxrwt).

4.4 The POSIX ACLs

The POSIX ACLs (the Access Control Lists) extend the mode's bits with the finer's granularity: the per-user's and the per-group's entries beyond the mode's three categories. The ACL's entries:

  • The owner's entry (the user::). The file's owner's permissions (the mode's owner's category).
  • The named user's entries (the user:name:). The specific users' permissions (the ACL's extension beyond the mode's categories).
  • The group's entry (the group::). The file's group's permissions (the mode's group's category).
  • The named group's entries (the group:name:). The specific groups' permissions.
  • The mask's entry (the mask::). The maximum's permissions that the named users, the named groups, and the group's entry can have. The mask's role is the compatibility with the mode's bits: the chmod's operations on the group's bits set the mask, and the mask's value limits the effective's permissions of the ACL's entries.
  • The others' entry (the other::). The everyone-else's permissions (the mode's others' category).

The ACLs' management:

  • The getfacl command. Displays the file's ACL: the entries and the effective's permissions. The output's format is the standard: the # file: and the # owner: and the # group: headers, the user:: and the user:name: and the group:: and the group:name: and the mask:: and the other:: entries, and the # effective: comments when the mask limits the entries.
  • The setfacl command. Modifies the file's ACL: the setfacl -m u:name:rw file adds or modifies the named user's entry, the setfacl -m g:name:r file the named group's entry, the setfacl -m m::rw file the mask, the setfacl -x u:name file removes the named user's entry, and the setfacl -b file removes the whole ACL.
  • The default's ACLs. The ACLs on a directory with the default: prefix (setfacl -d -m u:name:rw dir) determine the ACLs of the files and the directories created within the directory. The default's ACLs' purpose is the shared's directories' management: the directory's default's ACLs propagate the permissions to the new files and directories, so the users do not need to set the ACLs on each file.

The ACLs' design's subtleties:

  • The mask's interaction. When a file has an ACL with the named user's or the named group's entries, the mode's group's bits (the ls -l's middle triplet) display the mask (not the group's entry's permissions). The observation is the classical's confusion: the ls -l's group's bits on an ACL'd file show the mask, and the file's real group's permissions are in the ACL's group:: entry (the getfacl shows the effective's permissions). The ls's output on an ACL'd file also shows the + character after the mode, so the administrator knows the file has an ACL.
  • The default's ACLs' inheritance. The default's ACLs are inherited by the files and the directories created within the directory, and the inheritance is the recursive: the subdirectories inherit the default's ACLs and pass them to their own files and directories.
  • The ACLs' compatibility. The ACLs extend the mode's bits, and the two coexist: a file without an ACL has the mode's bits only (the classical's behavior), and a file with an ACL has both the mode's bits (the owner's and the others' entries) and the ACL's entries. The chmod's operations on the mode's bits interact with the ACL's mask, and the interaction's understanding is the ACLs' administration's key.

4.5 The Linux capabilities

The Linux capabilities split the root's all-or-nothing's privileges into the separate's units. The classical's model: the UID 0 (the root) has the every privilege, and the other UIDs have the none; the setuid's mechanism gives the full's root's privileges to the programs that need a single's privileged's operation. The capabilities' model: the privileges are the separate's units (the CAP_NET_BIND_SERVICE, the CAP_NET_ADMIN, the CAP_SYS_ADMIN, the CAP_DAC_OVERRIDE, the CAP_SETUID, the ~40 in total), and the processes can hold the specific's capabilities without the root's whole.

The capabilities' sets (the process's credential's components):

  • The permitted's set (cap_permitted). The capabilities the process may hold: the process's capabilities' upper bound, and the process can raise the permitted's capabilities into the effective's set.
  • The effective's set (cap_effective). The capabilities the process can use: the kernel's checks the effective's set when the process performs a privileged's operation.
  • The inheritable's set (cap_inheritable). The capabilities the process can pass to the programs it executes (the execve's inheritance).
  • The bounding's set (cap_bounding). The capabilities the process can ever acquire: the process cannot add a capability that is not in the bounding's set, even if the process is privileged. The bounding's set's purpose is the security's limit: the administrator can restrict the capabilities a process can acquire, so the compromised process cannot obtain the restricted capabilities.
  • The ambient's set (cap_ambient). The capabilities the process passes to the programs it executes, and the programs retain them even if the programs are not the setuid's or the file's capabilities' programs. The ambient's set's purpose is the unprivileged's programs' privilege's retention: the process can run the programs with the specific's capabilities without the setuid's mechanism.

The capabilities' assignment's mechanisms:

  • The file's capabilities. The setcap's command attaches the capabilities to the executable's file (the file's capability's sets: the permitted, the inheritable, the effective). When the file is executed, the process acquires the file's capabilities (subject to the sets' combination's rules), so the program can perform the privileged's operations without the setuid's root. Example: the ping's program needs the CAP_NET_RAW's capability (the raw's socket's creation), and the modern's systems attach the capability to the ping's file instead of the setuid's root's bit.
  • The process's capabilities. The capset's system call changes the process's capabilities, and the systemd's CapabilityBoundingSet, the AmbientCapabilities, and the NoNewPrivileges directives set the services' capabilities. The capsh's tool is the administrator's shell's capabilities' manipulation.
  • The user's capabilities (the libcap's PAM's module). The pam_cap's module (pam_caps) sets the users' capabilities: the users can be granted the specific's capabilities at the login's time, so the users do not need the root's access for the specific's operations.

The capabilities' design's advantages: the least privilege's principle (the fine-grained's privileges, not the root's whole) and the security's improvement (the setuid's root's programs are the attackers' targets, and the capabilities' programs are the safer's replacements). The capabilities' design's subtleties: the CAP_SYS_ADMIN's capability is the "the new root" (it grants the mount's operations, the namespaces' administration, and the many other operations), so the administrators should avoid it; the capabilities' sets' combinations' rules (the permitted's and the inheritable's and the file's sets' combination) are the understanding's concern.

4.6 The file attributes (chattr)

The file attributes are the additional's flags beyond the mode's bits and the ACLs, and they are managed by the chattr's command and displayed by the lsattr's command. The modern's file systems (the ext4, the XFS, the Btrfs) support the attributes, and their set differs by the file system. The most important:

  • The immutable's attribute (the i). The file cannot be modified, deleted, renamed, or linked, even by the root. The attribute's purpose is the critical's files' protection: the administrator can make the important's configuration's files the immutable, so the attacker (or the accidental's mistake) cannot modify them. The attribute's removal requires the CAP_LINUX_IMMUTABLE's capability.
  • The append-only's attribute (the a). The file can only be written in the append's mode: the existing contents cannot be modified, but the new contents can be added. The attribute's purpose is the log's files' protection: the audit's logs and the system's logs are the append-only, so the attacker cannot truncate them (the cover-the-tracks's attempt).
  • The no-dump's attribute (the d). The file is excluded from the dump's backups.
  • The secure-delete's attribute (the s). The file's blocks are zeroed on the deletion (the secure's erase's behavior).
  • The no-atime's attribute (the A). The file's access's time is not updated (the performance's optimization).
  • The compression's attribute (the c). The file is compressed on the disk (the Btrfs's and the other modern's file systems' support).

The attributes' management: the chattr +i file (the immutable's set), the chattr -i file (the removal), the chattr +a file (the append-only's set), and the lsattr file (the display). The attributes' permissions: the immutable's and the append-only's attributes' modification requires the CAP_LINUX_IMMUTABLE's capability (the root's capability), and the other attributes' modification requires the file's ownership.

4.7 The Linux Security Modules (LSM) framework

The Linux Security Modules (LSM) framework is the kernel's accommodation of the multiple access control's models. The framework's design's motivation: the Linux kernel's traditional's access control is the DAC (the mode's bits, the ACLs, the capabilities), and the kernel needed the mechanism for the MAC's policies (the SELinux, the AppArmor, the Smack, the TOMOYO) without the kernel's core's modification for each policy. The LSM framework solves the problem by the hooks: the kernel's code calls the hooks at the critical's points (the file's open, the process's creation, the socket's connection, the capability's check), and the security modules implement the hooks' policies.

The framework's design's properties:

  • The hooks' mediation. The kernel's code calls the hooks at the every critical's operation's point, so the security's modules' policies are the enforced's additional's constraints. The hooks' design is the reference monitor's extension: the kernel's traditional's checks and the modules' checks together determine the access's decision.
  • The modules' registration. The security modules register with the LSM's framework at the boot's time, and the framework's design supports the multiple's modules (the stacked's order: the modules' hooks are called in the registration's order). The modern's systems enable the SELinux or the AppArmor (not the both, in the standard's configurations).
  • The kernel's build's option. The LSM framework is the kernel's build's option (CONFIG_SECURITY), and the specific modules are the separate's options (CONFIG_SECURITY_SELINUX, CONFIG_SECURITY_APPARMOR, CONFIG_SECURITY_SMACK, CONFIG_SECURITY_TOMOYO, CONFIG_SECURITY_YAMA). The kernel's command line's security= parameter selects the active's module.
  • The /sys/kernel/security/ interface. The securityfs's file system exposes the modules' state and their configuration: the /sys/kernel/security/lsm lists the active's modules, and the module-specific's directories (the /sys/fs/selinux/, the /sys/kernel/security/apparmor/) expose the modules' details.

The framework's central's modules are the SELinux (the NSA's mandatory access control: the type enforcement and the MLS) and the AppArmor (the Novell's/SUSE's mandatory access control: the path's confinement). The two modules implement the MAC's policies (Lesson 12.4's Bell-LaPadula and Biba's concepts), and their designs differ: the SELinux's labels are the types (the labels on the subjects and the objects), and the AppArmor's labels are the programs' paths (the profiles attached to the executable's paths).

4.8 SELinux

The SELinux (the Security-Enhanced Linux) is the NSA's mandatory access control's implementation. Its design's foundation: the type enforcement, the role-based access control, and the multi-level security (the MLS). The system's components:

  • The labels (the security's contexts). The every's subject (the process) and the every's object (the file, the socket, the device) has a label: the security's context with the four fields (the user, the role, the type, the sensitivity's level). The context's format: user:role:type:level (for example, system_u:object_r:httpd_sys_content_t:s0). The type is the central's field: the type enforcement's policy's rules are the types' relationships.
  • The policy. The SELinux's policy is the compiled's rules' set: the allow's rules (the source's type, the target's type, the class, the permissions), the type_transition's rules (the default's types for the new objects), the role's assignments, and the boolean's tunables. The policy's sources are the distribution's policy's packages, and the compiled's binary is in the /etc/selinux/<policy>/policy/.
  • The modes. The SELinux's three modes: the enforcing (the policy's rules are the enforced: the violations are the denied), the permissive (the violations are the allowed but the audit's messages are the logged: the debugging's mode), and the disabled (the SELinux is the off).
  • The booleans. The policy's tunable's switches: the named's parameters (the httpd_can_network_connect, the ftpd_anon_write) that the administrator can toggle at the runtime. The booleans' purpose is the policy's flexibility: the administrator can enable the specific's permissions without the policy's recompilation.
  • The tools. The getenforce and the sestatus (the status), the semanage (the policy's administration), the chcon and the restorecon (the labels' modification), the setsebool (the booleans' toggling), the sesearch (the policy's rules' query), the seinfo (the policy's components' listing), and the ausearch with the -m AVC (the audit's denials).

The SELinux's design's advantages: the MAC's enforcement (the type enforcement's rules are the system's policy, and the individual's subjects cannot override them) and the damage's limitation (a compromised's process can access only the resources its type's policy permits). The SELinux's design's disadvantages: the complexity (the policy's language, the labels' administration, the audit's messages' interpretation) and the rigidity (the policy's exceptions' design is the burdensome).

4.9 AppArmor

The AppArmor is the alternative's mandatory access control's implementation (the SUSE's and the Ubuntu's default). Its design's foundation: the path's confinement: the every's program has a profile that specifies the resources the program can access (the files' paths, the capabilities, the network's operations), and the kernel's AppArmor's module enforces the profile's rules. The system's components:

  • The profiles. The text's files in the /etc/apparmor.d/'s directory, one file per program (the usr.bin.firefox, the usr.sbin.cupsd). The profile's contents: the program's path (the /usr/bin/firefox), the included's abstractions (the #include <abstractions/base>), the permitted's resources (the /etc/firefox/** r,, the /tmp/** rw,, the /home/*/.mozilla/** rw,), and the capabilities (the capability net_bind_service,).
  • The modes. The AppArmor's modes: the enforce (the profile's rules are the enforced), the complain (the violations are the allowed but the logged: the profile's development's mode), and the disabled (the profile is not the loaded).
  • The tools. The aa-status (the status), the aa-enforce and the aa-complain (the modes' setting), the aa-genprof and the aa-logprof (the profiles' generation), the apparmor_parser (the profiles' loading), and the dmesg and the audit's logs (the violations' messages).

The AppArmor's design's advantages: the simplicity (the path's confinement is the intuitive: the profile's rules are the paths and the permissions) and the ease of the administration (the profiles' generation and the logs' interpretation are the simpler than the SELinux's). The AppArmor's design's disadvantages: the path's dependence (the profiles are the bound to the paths, so the programs' movements or the hard links can bypass them: the SELinux's labels are the bound to the objects, so the movements do not affect them) and the scope (the AppArmor's confinement is the per-program, and it does not provide the SELinux's system-wide's policy).

The Linux security's layers and the LSM framework The diagram has two parts. The top part shows the Linux security's layers: the hardware's protection's mechanisms, the kernel's core (the reference monitor), the Linux Security Modules (LSM) framework with its hooks, the user-space's services (the PAM, the NSS, the auditd), and the applications' security. The bottom part compares the two principal LSM's implementations: the SELinux (the type enforcement, the labels, the policy) and the AppArmor (the path's confinement, the profiles). THE LINUX SECURITY'S LAYERS Applications' security the web servers' authentication, the databases' privileges, the sessions User-space's services the PAM (the authentication), the NSS (the identity), the auditd (the accounting) The Linux Security Modules (LSM) framework the kernel's hooks at the critical's points (the file's open, the process's creation, the socket's connection) the modules' implementations: the SELinux, the AppArmor, the Smack, the TOMOYO, the Yama The kernel's core (the reference monitor) the system calls' mediation, the credentials, the permissions' checks, the capabilities The hardware's protection's mechanisms the processor's privilege's levels, the MMU, the memory's protection THE TWO PRINCIPAL LSM's MODULES SELinux (the NSA) the type enforcement's MAC The labels (the security's contexts): user:role:type:level the type is the central's field The policy: the allow's rules (the source's type, the target's type, the class, the perms) the booleans (the tunable's switches) The modes: enforcing, permissive, disabled The tools: getenforce, sestatus, semanage, chcon, setsebool, sesearch ausearch -m AVC AppArmor (the SUSE/Ubuntu) the path's confinement's MAC The profiles: the text's files in /etc/apparmor.d/ the permitted's paths and the capabilities The rules' example: /usr/bin/firefox { /etc/firefox/** r, /tmp/** rw, capability net_bind_service, } The modes: enforce, complain, disabled The tools: aa-status, aa-enforce, aa-complain, aa-genprof
Figure 12.5 — The Linux security's layers and the LSM framework. The top diagram shows the security's layers: the hardware's protection's mechanisms, the kernel's core (the reference monitor), the LSM's framework (the kernel's hooks and the security modules), the user-space's services (the PAM, the NSS, the auditd), and the applications' security. The bottom diagram compares the two principal LSM's implementations: the SELinux (the type enforcement's MAC: the labels, the policy, the booleans) and the AppArmor (the path's confinement's MAC: the profiles, the paths, the capabilities). The two modules implement the MAC's policies (Lesson 12.4's Bell-LaPadula and Biba's concepts), and their designs differ: the SELinux's labels are the types (the objects' and the subjects'), and the AppArmor's labels are the programs' paths (the executable's profiles).

4.10 The authentication's stack: PAM and NSS

The Linux authentication's stack was introduced in Lesson 12.2, and this section reviews its role in the security's architecture:

  • The PAM (the Pluggable Authentication Modules). The framework that the programs (the login, the su, the sudo, the sshd, the passwd) call for the authentication, the account's management, the session's management, and the password's management. The PAM's configuration is in the /etc/pam.conf and the /etc/pam.d/'s directory, and the modules (the pam_unix, the pam_pwquality, the pam_faillock, the pam_limits, the pam_env, the pam_selinux, the pam_cap, the pam_google_authenticator) are the mechanisms.
  • The NSS (the Name Service Switch). The framework for the identity's sources: the /etc/nsswitch.conf's file specifies the sources' order for the passwd, the group, the shadow, the hosts, and the other's databases. The sources: the files (the local's files), the systemd (the systemd's accounts), the ldap (the directory's services), the sss (the System Security Services Daemon), the winbind (the Active Directory's integration), and the nis (the legacy's Network Information Service).
  • The sssd (the System Security Services Daemon). The modern's identity's service: the daemon caches the identities and the credentials from the remote's sources (the LDAP, the Kerberos, the Active Directory), so the local's logins and the PAM's checks can use the remote's identities. The sssd's design is the enterprise's Linux integration's standard.

4.11 The audit's subsystem

The audit's subsystem is the AAA model's third pillar's (the accounting's) implementation. The subsystem's components:

  • The kernel's audit's framework. The kernel's code that generates the audit's events (the system calls, the file's accesses, the authentication's events, the SELinux's denials) and the rules that determine which events to record. The auditctl's command manages the rules, and the /etc/audit/audit.rules's file (or the /etc/audit/rules.d/'s directory) holds the rules' persistent's configuration.
  • The auditd's daemon. The user-space's daemon that receives the kernel's audit's messages and writes them to the log's files (the /var/log/audit/audit.log). The daemon's configuration is the /etc/audit/auditd.conf's file (the log's file's path, the rotation's policy, the space's limits).
  • The audit's tools. The ausearch (the log's query by the criteria: the time, the user, the event's type, the success or the failure), the aureport (the log's summary's reports: the authentication's events, the file's accesses, the anomalies), the auparse (the events' parsing), and the auditctl (the rules' management).

The audit's subsystem's design's concerns:

  • The rules' design. The rules determine which events to record: the -w /etc/passwd -p wa -k passwd_changes (the watch on the /etc/passwd's write's and attribute's changes, with the passwd_changes's key), the -a always,exit -F arch=b64 -S execve -k exec (the every's program's execution), the -a always,exit -F arch=b64 -S open -F exit=-EACCES -k access_denied (the every's permission's denial). The rules' design's trade-off: the more rules, the more events, the more storage, and the more the performance's impact.
  • The logs' protection. The audit's logs are the security's evidence, and their protection is the security's requirement: the logs should be the append-only (the chattr +a), the rotation's policy should preserve the evidence, and the logs' integrity should be verified (the cryptographic's signing with the auditd's log_format = RAW's option and the audisp-remote's or the syslog's remote's delivery).
  • The logs' monitoring. The audit's logs' value is the monitoring: the SIEM's systems (the Splunk, the ELK's stack) or the simple's tools (the aureport's reports, the ausearch's queries) can detect the anomalies (the failed's logins, the privilege's escalations, the permission's denials), and the detection is the security's operations's central's activity.

4.12 sudo and su

The sudo and the su are the privilege's escalation's mechanisms:

su (the substitute user)
The command that switches the user's identity: the su - alice starts the shell with the alice's identity (the user must know the alice's password, or the user must be the root). The su's design's properties: the target's password's requirement (the target's credential's verification), the environment's setup (the -'s option loads the target's login's environment), and the audit's record (the su's events in the logs). The su's design's disadvantage: the target's password's sharing (the multiple users' knowing the root's password is the security's weakness: the accountability's loss).
sudo (the superuser do)
The command that executes the specific commands with the target's privileges: the sudo command runs the command with the root's privileges (or the other user's privileges), and the sudoers's file (the /etc/sudoers, edited with the visudo) determines which users can run which commands. The sudo's design's advantages: the least privilege's granularity (the specific's commands, not the whole's root's shell), the accountability (the users authenticate as themselves, and the sudo's log records the commands), and the configuration's centralization (the sudoers's rules). The sudo's design's subtleties: the rules' syntax (the user host = (the runas) the commands), the NOPASSWD's tag (the password's absence: the risky's convenience), the Defaults's directives (the requiretty, the env_reset, the secure_path), and the sudo's timestamp's caching (the password's re-entry's interval).

The two mechanisms' design's comparison: the su is the identity's switch (the whole's shell), and the sudo is the command's execution (the specific's commands). The sudo's design is the least privilege's principle's application (the minimum's privileges), and its accountability's advantage is the security's operations's requirement (the who-did-what's records). The modern's systems prefer the sudo, and the su's use is the decreasing (the su - on the Ubuntu's systems requires the root's password's setting, the sudo -i's alternative is the standard).

4.13 The kernel's security's parameters (sysctl)

The sysctl is the Linux kernel's runtime's parameters' interface: the /proc/sys/'s file system (and its /sys/'s counterpart) exposes the kernel's parameters, and the sysctl's command (or the direct's writes to the files) modifies them. The security-relevant parameters:

  • The network's parameters (the net.ipv4, the net.ipv6). The net.ipv4.tcp_syncookies (the SYN's flood's protection), the net.ipv4.conf.all.rp_filter (the reverse's path's filtering: the spoofed's packets' rejection), the net.ipv4.conf.all.accept_redirects (the ICMP's redirects' rejection), the net.ipv4.conf.all.accept_source_route (the source's routing's rejection), the net.ipv4.icmp_echo_ignore_broadcasts (the broadcast's ping's rejection), the net.ipv4.conf.all.log_martians (the impossible's addresses' logging), and the net.ipv6.conf.all.disable_ipv6 (the IPv6's disabling when unused).
  • The kernel's parameters (the kernel). The kernel.randomize_va_space (the ASLR: the address's space's layout's randomization, the value 2 for the full's randomization), the kernel.dmesg_restrict (the kernel's log's restriction to the root), the kernel.kptr_restrict (the kernel's pointers' restriction in the /proc's interfaces), the kernel.yama.ptrace_scope (the ptrace's scope: the processes' debugging's restriction), the kernel.sysrq (the SysRq's key's functions: the disabling in the production), the kernel.core_pattern (the core's dumps' destination: the pipes to the systemd-coredump or the apport, or the disabling), and the kernel.modules_disabled (the kernel's modules' loading's disabling: the one-way's switch).
  • The file system's parameters (the fs). The fs.protected_hardlinks and the fs.protected_symlinks (the hard and the symbolic links' protection: the /tmp's attacks' prevention), the fs.suid_dumpable (the setuid's programs' core's dumps: the value 0 for the no's dumps), and the fs.protected_fifos and the fs.protected_regular (the FIFO's and the regular's files' protection: the named pipes' and the files' attacks' prevention).
  • The virtual memory's parameters (the vm). The vm.mmap_min_addr (the minimum's address for the mmap: the low addresses' mapping's prevention, the NULL's pointer's dereference's attacks' mitigation), the vm.swappiness (the swap's aggressiveness), and the vm.dirty_ratio and the vm.dirty_background_ratio (the dirty's pages' thresholds).

The sysctl's parameters' management: the /etc/sysctl.conf's file and the /etc/sysctl.d/'s directory hold the persistent's settings, the sysctl -w parameter=value's command sets the runtime's values, and the sysctl -a's command displays the current's values. The sysctl --system's command reloads the configuration. The parameters' hardening's settings are the distributions' and the security's guides' (the CIS's benchmarks, the STIG's guides, the NIST's guides) standard's recommendations.

4.14 The hardening's practices

The hardening is the system's security's configuration's process: the reduction of the attack's surface and the strengthening of the defenses. The practice's components:

  • The attack's surface's reduction. The unnecessary services' removal (the systemctl's disable, the packages' uninstallation), the open ports' closing (the firewalls: the iptables, the nftables, the firewalld, the ufw), the unused's accounts' removal (the old's users, the default's accounts), the unnecessary's capabilities' removal (the setuid's programs' review, the capabilities' minimization), and the kernel's modules' minimization (the unnecessary's drivers' blacklisting).
  • The identities' and the authentication's hardening. The strong's passwords (the length, the passphrase), the password's policies (the pwquality's rules, the faillock's lockout), the SSH's hardening (the key-based's authentication, the root's login's disabling, the non-standard's port, the AllowUsers/AllowGroups's restrictions), the sudo's hardening (the specific's rules, the NOPASSWD's avoidance, the requiretty's setting), and the MFA's deployment (the TOTP, the FIDO2's keys).
  • The kernel's hardening. The sysctl's security's settings (the section 4.13's parameters), the ASLR's enabling, the SELinux's or the AppArmor's enabling, the kernel's modules' signing's enforcement, and the kernel's updates' application.
  • The file systems' hardening. The permissions' review (the world-writable's files' search, the setuid's programs' review), the ACLs' design (the shared's directories), the attributes' use (the immutable's and the append-only's attributes), the mount's options (the noexec, the nosuid, the nodev on the /tmp and the /home), and the disk's encryption (the LUKS).
  • The logging's and the monitoring's hardening. The auditd's rules and the logs' protection, the log's rotation and the retention, the logs' remote's delivery, the file's integrity's monitoring (the AIDE, the Tripwire), and the intrusions' detection (the OSSEC, the Wazuh, the Suricata).
  • The updates' management. The security's patches' application (the unattended-upgrades, the dnf-automatic), the packages' sources' verification (the GPG's signatures), the vulnerabilities' scanning (the OpenVAS, the Nessus, the Trivy), and the configuration's management (the Ansible, the Puppet, the Chef).

The hardening's practice's central's tension: the security and the functionality's trade-off. The more restrictive's configuration is the more secure and the less convenient (the services' disabling, the permissions' restriction, the features' removal), and the more convenient's configuration is the less secure. The hardening's design's goal is the balance: the strongest security the functionality permits, and the functionality the security requires. The observation is the reason the hardening is the iterative's process: the configuration is the assessed, the risks are the identified, the controls are the applied, and the assessment is the repeated.

4.15 Common misconceptions

"The root is the only privileged user."

The root (the UID 0) is the classical superuser, but the modern's Linux systems have the finer-grained's privileges: the capabilities (the CAP_NET_ADMIN, the CAP_SYS_ADMIN, the CAP_DAC_OVERRIDE, the CAP_SETUID), and the setuid's and the setgid's programs. The capabilities' model splits the root's all-or-nothing's privileges, and the observation is the least privilege's principle's application: the services run with the specific's capabilities, not the root's whole.

"The mode's bits are the only access control's mechanism."

The mode's bits are the classical's mechanism, and the modern's Linux adds the ACLs (the per-user's and the per-group's permissions), the capabilities (the fine-grained's privileges), the attributes (the immutable and the append-only), and the LSM's modules (the SELinux, the AppArmor). The mechanisms are the layered: the kernel's checks combine the mode's bits, the ACLs, the capabilities, and the LSM's policies, and the access's decision is the combination's result.

"The setuid's programs are the convenient's mechanism."

The setuid's programs are the security's risk: a setuid's root's program with a bug (the buffer's overflow, the race's condition, the input's validation's absence) can be exploited by the unprivileged's users to obtain the root's access. The modern's systems minimize the setuid's programs (the find / -perm -4000's review) and prefer the capabilities (the specific's privileges) or the sudo (the controlled's escalation).

"The SELinux is the same as the AppArmor."

The SELinux and the AppArmor are the different MAC's implementations. The SELinux's labels are the types (the labels on the subjects and the objects, and the policy's rules are the types' relationships), and the SELinux provides the system-wide's policy, the MLS (the multi-level security), and the RBAC's roles. The AppArmor's labels are the programs' paths (the profiles attached to the executable's paths), and the AppArmor's confinement is the per-program's path's restrictions. The SELinux is the more rigorous and the more complex; the AppArmor is the simpler and the path-dependent.

"The capabilities replace the root."

The capabilities split the root's privileges, but they do not eliminate the root: the CAP_SYS_ADMIN's capability is the "the new root" (it grants the mount's operations, the namespaces' administration, and the many other operations), and the process with the CAP_SYS_ADMIN's capability is effectively the root. The capabilities' design's goal is the least privilege (the specific's capabilities, not the whole), but the CAP_SYS_ADMIN's breadth is the model's practical's limitation.

"The audit's logs are the security's panacea."

The audit's logs are the security's evidence, and their value depends on the design: the rules' coverage (the events the rules record), the logs' protection (the append-only's attribute, the remote's delivery), the logs' retention (the rotation's policy), and the logs' monitoring (the analysis's tools and the administrators' attention). The logs without the monitoring are the storage's waste, and the logs without the protection are the attackers' first target (the cover-the-tracks's attempt).

"The hardening is a one-time's configuration."

The hardening is the ongoing's process: the workload changes, the threats evolve, the software updates, and the configuration drifts. The process's components: the regular's assessments (the vulnerability's scanning, the configuration's review), the updates' application (the security's patches), the logs' monitoring (the anomalies' detection), and the incidents' response (the investigation, the remediation). The observation is the reason the security's operations (the SecOps) is the security's central's activity, not the one-time's configuration.

"The Linux is the secure by default."

The Linux is the secure by design (the reference monitor, the users' separation, the permissions' model), but its default's configuration is the distributions' choice, and the distributions' defaults favour the convenience and the compatibility over the security: the open ports, the default's accounts, the permissive's settings. The hardening's practice is the default's configuration's review and the security's settings' application. The observation is the reason the distributions provide the security's guides (the CIS's benchmarks, the Ubuntu's security's guide, the RHEL's security's guide) and the tools (the usg, the oscap) for the hardening's automation.

05 Worked example

The following example traces a file access through the Linux security's layers, computes the permission's check with the credentials, and demonstrates the capabilities' and the LSM's mediation.

Tracing a file access through the Linux security's layers

Consider the user alice (the UID 1000, the primary GID 1000, the supplementary group developers with the GID 2000) who runs the cat command on the file /projects/report.txt. The file's owner is bob (the UID 1001), its group is developers (the GID 2000), its mode is 0640 (rw-r-----), and it has an ACL that grants alice the read (the entry user:alice:r--). The SELinux is the enforcing, and the file's label is system_u:object_r:projects_t:s0, and the cat's process has the label unconfined_u:unconfined_r:unconfined_t:s0.

  1. The process's credentials. The cat process runs with the credentials: the real UID 1000, the effective UID 1000, the saved-set UID 1000, the real GID 1000, the effective GID 1000, the saved-set GID 1000, and the supplementary groups (the GID 1000 and the GID 2000).
  2. The kernel's VFS layer's check. The cat's open call reaches the VFS layer, which performs the permissions' checks in the order:
    • The mode's categories. The owner's category: the process's effective UID (1000) is compared with the file's owner's UID (1001): no match. The group's category: the process's effective GID (1000) and the supplementary GIDs (2000) are compared with the file's group's GID (2000): the match (the supplementary GID 2000). The group's permissions (r--) apply: the read is granted. The others' category is not checked (the group's category matched).
    • The ACLs. The VFS layer checks the file's ACLs: the entry user:alice:r-- matches the process's effective UID (1000 corresponds to alice), and the mask's value includes the read's permission. The ACL's decision (the read's grant) agrees with the mode's check.
  3. The capability's check. The VFS layer checks the process's capabilities: the process has the CAP_DAC_OVERRIDE's capability in its effective's set? (The answer is no, because the process is the unprivileged's alice.) The capability's check does not apply, and the access proceeds to the LSM's hooks.
  4. The LSM's hooks. The kernel calls the SELinux's hooks: the SELinux's policy checks the source's type (unconfined_t) and the target's type (projects_t) against the policy's rules. If the policy has the allow unconfined_t projects_t:file read's rule, the SELinux's check passes; if the policy denies the read, the SELinux's check fails (the access is denied, and the avc: denied's message is recorded in the audit's log).
  5. The access's decision. The kernel's checks (the mode's, the ACLs', the capabilities', the LSM's) combine into the decision: the read is granted if the every's check passes, and it is denied if the any's check fails. In this case, the mode's check (the group's read) and the ACL's check (the alice's read) pass, the capability's check does not apply, and the SELinux's check (assuming the allow unconfined_t projects_t:file read's rule) passes: the access is granted, and the cat reads the file.
  6. The audit's record. The kernel's audit's subsystem records the access's event (if the audit's rules require it): the process's PID, the user's UID, the file's path, the operation, and the decision (the success or the failure). The SELinux's checks record the avc's messages (the granted's and the denied's decisions).

The trace shows the Linux security's layers' operation: the kernel's checks combine the traditional's (the mode's bits, the ACLs, the capabilities) and the modern's (the LSM's modules), and the access's decision is the combination's result. The observation is the reason the Linux security is the layered's design: the layers provide the multiple's checks, and the LSM's modules' policies are the additional's constraints that the kernel enforces.

The credential's changes and the setuid's mechanism

Consider the passwd command's execution: the user alice runs the passwd command to change her password. The passwd's file is the setuid's root's program: its owner is the root (the UID 0), and its setuid's bit is set (the mode 4755).

  1. The execution's start. alice (the UID 1000) runs the passwd's program. The kernel's execve loads the program, and the kernel's credentials' handling checks the file's setuid's bit.
  2. The credentials' change. The file's setuid's bit is set and the file's owner is the root (the UID 0): the kernel sets the process's effective UID (the EUID) to 0 (the file's owner's UID), while the real UID (the RUID) remains 1000 (the caller's UID). The saved-set UID (the SUID) is set to the effective's value (0).
  3. The program's privileged's operations. The passwd's program now runs with the effective UID 0, so it can read and write the /etc/shadow's file (the root-readable-only file with the passwords' hashes).
  4. The user's interaction. The program prompts alice for the current's password and the new's password, and it verifies the current's password against the /etc/shadow's hash (using the pam_unix's module). The program's privileged's access to the /etc/shadow's file is the setuid's mechanism's purpose: the ordinary's user's password's change requires the privileged's access, and the setuid's mechanism grants the access without the user's knowing the root's password.
  5. The program's privilege's drop. The passwd's program performs the password's change and then drops the privileges (the setuid(getuid())'s call restores the effective's UID to the real's value 1000). The program's subsequent's operations run with alice's privileges, so the program's later's bugs cannot be exploited to obtain the root's access (the privilege's bracketing's design).

The trace shows the setuid's mechanism's design: the program runs with the file's owner's effective UID (the root's), so it can perform the privileged's operations, and it drops the privileges after the operations, so the program's later's parts run with the caller's privileges. The mechanism's subtleties: the program's every's operation must be audited (the privileged's operations' design's care), the program's environment's variables must be sanitized (the LD_PRELOAD's and the PATH's attacks' prevention), and the program's input must be validated (the buffer's overflow's and the injection's attacks' prevention). The observation is the reason the setuid's programs are the security's risk: the program's design's every's detail matters, and the modern's systems prefer the capabilities (the specific's privileges) or the sudo (the controlled's escalation).

The capabilities' model's demonstration

The capabilities' model's demonstration: the ping's program's evolution.

Era The mechanism The permissions' result
The classical's Unix (the 1980s) The ping's program is the setuid's root (the mode 4755, the owner the root) The process runs with the root's whole's privileges while the program executes, so a bug in the program can give the attacker the root's access
The modern's Linux (the 2000s) The ping's program is the capabilities' program (the setcap cap_net_raw+ep /bin/ping) The process holds only the CAP_NET_RAW's capability (the raw's socket's creation), so a bug in the program gives the attacker only the raw's socket's privilege, not the root's whole

The table shows the capabilities' model's advantage: the least privilege's principle's application. The setuid's mechanism gives the program the root's whole's privileges, and the capability's mechanism gives the program only the specific's privilege. The observation is the reason the modern's distributions replaced the setuid's ping with the capabilities' version, and the change is the least privilege's principle's practical's demonstration.

Observing the Linux security on a live system

The Linux tools let an administrator inspect the system's security's state: the identity's model, the permissions' mechanisms, the capabilities, the attributes, the LSM's modules, and the audit's subsystem.

# Show the current user's identity and the credentials
id
cat /proc/self/status | grep -E 'Uid|Gid|Cap'

# Show the files' permissions and the special's bits
ls -la /etc/passwd /etc/shadow
find / -perm -4000 -type f 2>/dev/null | head -20
find / -perm -2000 -type f 2>/dev/null | head -10
ls -la /tmp/ | head -5

# Show the files' ACLs
getfacl /etc/passwd /home/ 2>/dev/null

# Show the files' capabilities
getcap -r / 2>/dev/null

# Show the files' attributes
lsattr /etc/passwd /var/log/ 2>/dev/null | head -10

# Show the SELinux's status and the labels
getenforce
sestatus
ls -Z /etc/passwd /var/www/html/ 2>/dev/null | head -5

# Show the AppArmor's status
sudo aa-status 2>/dev/null | head -10

# Show the kernel's security's parameters
sysctl -a 2>/dev/null | grep -E 'randomize_va_space|dmesg_restrict|kptr_restrict|yama.ptrace|ipv4.tcp_syncookies|ipv4.conf.all.rp_filter|fs.protected' | head -20

# Show the audit's status and the recent's events
sudo auditctl -s 2>/dev/null
sudo ausearch -ts recent 2>/dev/null | head -20
sudo aureport --auth 2>/dev/null | head -10

# Show the sudo's configuration
sudo cat /etc/sudoers | grep -vE '^#|^$'
sudo -l

# Show the PAM's configuration
cat /etc/pam.d/sshd /etc/pam.d/login 2>/dev/null | head -30

# Show the NSS's configuration
grep -E 'passwd|group|shadow' /etc/nsswitch.conf

The commands' outputs show the Linux security's state: the current user's identity and the credentials, the files' permissions and the special's bits, the ACLs, the capabilities, the attributes, the SELinux's or the AppArmor's status, the kernel's security's parameters, the audit's events, the sudo's configuration, the PAM's stack, and the NSS's sources. The inspection is the administrator's first step in the security's assessment, and it is the basis for the hardening's decisions.

06 Interactive activity

Activity · explore the Linux security on a live system

The goal of this activity is to use the Linux command line to inspect and experiment with the system's security's mechanisms: the identity's model, the permissions' mechanisms, the capabilities, the LSM's modules, the audit's subsystem, and the hardening's practices. Work through the steps in your course VM.

  1. Inventory the identity's model. Use id, /etc/passwd, /etc/shadow, and /etc/group to examine the system's identities.
    # Show the current user's identity and the credentials
    id
    cat /proc/self/status | grep -E 'Uid|Gid'
    
    # Show the users' accounts
    cat /etc/passwd | head -20
    sudo cat /etc/shadow | head -10
    
    # Show the groups
    cat /etc/group | head -20
    
    # Count the users and the system's accounts
    grep -c 'nologin\|false' /etc/passwd
    echo "---"
    awk -F: '$3 >= 1000 && $3 < 65534 {print $1, $3}' /etc/passwd
    
    # Show the login's history and the failures
    last | head -10
    sudo lastb | head -10
    How many regular's users and system's accounts are there? What are the current user's credentials (the real and the effective UIDs and GIDs)? What are the passwords' hash's formats? Write down what you find.
  2. Examine the permissions' bits and the special's bits. Use ls, find, and chmod to examine the permissions' mechanisms.
    # Show the key files' permissions
    ls -la /etc/passwd /etc/shadow /etc/sudoers
    
    # Find the setuid and the setgid's programs
    find / -perm -4000 -type f 2>/dev/null
    find / -perm -2000 -type f 2>/dev/null | head -10
    
    # Show the world-writable files
    find / -type f -perm -o+w 2>/dev/null | head -10
    find / -type d -perm -o+w 2>/dev/null | head -10
    
    # Show the sticky's directories
    ls -ld /tmp /var/tmp
    
    # Experiment with the mode's bits
    mkdir /tmp/perm-test
    touch /tmp/perm-test/file.txt
    chmod 777 /tmp/perm-test/file.txt
    ls -la /tmp/perm-test/file.txt
    chmod 600 /tmp/perm-test/file.txt
    ls -la /tmp/perm-test/file.txt
    
    # Clean up
    rm -rf /tmp/perm-test
    How many setuid's programs are there? Which are the most risky? What are the world-writable files and directories? How does the sticky's bit protect the /tmp's directory? Explain the mechanism's design.
  3. Test the POSIX ACLs. Use setfacl and getfacl to experiment with the ACLs.
    # Create a test file
    mkdir /tmp/acl-test
    echo "ACL test" > /tmp/acl-test/file.txt
    chmod 640 /tmp/acl-test/file.txt
    
    # Show the initial's ACL
    getfacl /tmp/acl-test/file.txt
    
    # Add a named user's entry
    setfacl -m u:nobody:r /tmp/acl-test/file.txt
    getfacl /tmp/acl-test/file.txt
    
    # Verify the mode's display
    ls -la /tmp/acl-test/file.txt
    
    # Set the default's ACLs on the directory
    setfacl -d -m u:nobody:rwx /tmp/acl-test/
    getfacl /tmp/acl-test/
    
    # Create a file in the directory and check its ACL
    touch /tmp/acl-test/newfile.txt
    getfacl /tmp/acl-test/newfile.txt
    
    # Remove the ACL
    setfacl -b /tmp/acl-test/file.txt
    setfacl -k /tmp/acl-test/
    
    # Clean up
    rm -rf /tmp/acl-test
    What is the file's ACL after the modification? How does the ls -la's output change (the +'s character)? How do the default's ACLs propagate to the new files? What is the mask's role in the ACL's design?
  4. Examine and test the capabilities. Use getcap, setcap, and getpcaps to examine the capabilities.
    # Show the files' capabilities
    getcap -r / 2>/dev/null
    
    # Show the current process's capabilities
    cat /proc/self/status | grep Cap
    capsh --print 2>/dev/null | head -20
    
    # Show a specific process's capabilities
    sudo getpcaps $(pgrep -f 'sshd|systemd' | head -1) 2>/dev/null
    
    # Test the capabilities' effect
    cp /bin/ping /tmp/ping-test
    sudo setcap cap_net_raw+ep /tmp/ping-test
    getcap /tmp/ping-test
    sudo -u nobody /tmp/ping-test -c 1 localhost 2>&1 | head -2
    
    # Remove the capability
    sudo setcap -r /tmp/ping-test
    getcap /tmp/ping-test
    
    # Clean up
    rm /tmp/ping-test
    Which files have the capabilities? What is the ping's capability (the CAP_NET_RAW)? What happens when the capability is set or removed? How does the capabilities' model implement the least privilege's principle?
  5. Test the file attributes (chattr). Use chattr and lsattr to experiment with the attributes.
    # Create a test file
    touch /tmp/attr-test.txt
    
    # Show the current attributes
    lsattr /tmp/attr-test.txt
    
    # Set the immutable's attribute
    sudo chattr +i /tmp/attr-test.txt
    lsattr /tmp/attr-test.txt
    
    # Try to modify the file (should fail)
    echo "test" >> /tmp/attr-test.txt 2>&1
    sudo rm /tmp/attr-test.txt 2>&1
    
    # Remove the immutable's attribute
    sudo chattr -i /tmp/attr-test.txt
    lsattr /tmp/attr-test.txt
    
    # Set the append-only's attribute
    sudo chattr +a /tmp/attr-test.txt
    echo "test" >> /tmp/attr-test.txt
    echo "overwrite" > /tmp/attr-test.txt 2>&1
    cat /tmp/attr-test.txt
    
    # Clean up
    sudo chattr -a /tmp/attr-test.txt
    rm /tmp/attr-test.txt
    What happens when the immutable's attribute is set? What happens when the append-only's attribute is set? What is the difference between the two attributes' behaviors? How do the attributes' designs implement the critical's files' protection?
  6. Examine the SELinux or the AppArmor. Use the tools to inspect the mandatory access control's implementation.
    # For SELinux:
    getenforce
    sestatus
    ls -Z /etc/passwd /etc/shadow /var/www/html/ 2>/dev/null
    ps -eZ | head -20
    getsebool -a 2>/dev/null | head -20
    sudo semanage user -l 2>/dev/null
    
    # For AppArmor:
    sudo aa-status 2>/dev/null
    ls /etc/apparmor.d/ 2>/dev/null
    sudo cat /etc/apparmor.d/usr.bin.firefox 2>/dev/null | head -20
    
    # Show the current's context (if SELinux is enabled)
    id -Z 2>/dev/null
    Which LSM's module is active (the SELinux, the AppArmor, the both)? What are the files' labels (the types or the profiles)? What are the processes' domains? How does the active's module implement the MAC's policies?
  7. Examine the kernel's security's parameters. Use sysctl to inspect and modify the kernel's security's parameters.
    # Show the security-relevant parameters
    sysctl -a 2>/dev/null | grep -E 'randomize_va_space|dmesg_restrict|kptr_restrict|yama.ptrace|ipv4.tcp_syncookies|ipv4.conf.all.rp_filter|ipv4.conf.all.accept_redirects|fs.protected_hardlinks|fs.protected_symlinks|mmap_min_addr'
    
    # Check the ASLR's status
    cat /proc/sys/kernel/randomize_va_space
    
    # Check the network's hardening's parameters
    cat /proc/sys/net/ipv4/tcp_syncookies
    cat /proc/sys/net/ipv4/conf/all/rp_filter
    
    # Test the parameters' modification (in the VM)
    sudo sysctl -w kernel.dmesg_restrict=1
    cat /proc/sys/kernel/dmesg_restrict
    sudo sysctl -w kernel.dmesg_restrict=0
    
    # Show the persistent's configuration
    cat /etc/sysctl.conf 2>/dev/null | grep -vE '^#|^$'
    ls /etc/sysctl.d/ 2>/dev/null
    What are the current's values of the security's parameters? Is the ASLR enabled (the value 2)? Are the SYN's cookies and the rp_filter enabled? What are the persistent's settings? What would you harden on the system?
  8. Read the man pages. Read the man pages that document the Linux security's mechanisms.
    man 1 id
    man 5 passwd
    man 5 shadow
    man 5 group
    man 1 chmod
    man 1 chown
    man 5 acl
    man 7 capabilities
    man 1 chattr
    man 1 lsattr
    man 5 pam.conf
    man 5 nsswitch.conf
    man 8 auditctl
    man 8 ausearch
    man 5 sudoers
    man 8 getenforce
    man 8 sestatus
    man 8 semanage
    man 5 apparmor.d
    man 8 aa-status
    man 8 sysctl
    man 5 sysctl.conf
    For each, write a sentence describing its main contribution to your understanding of the Linux security. The man 5 passwd and man 5 shadow pages document the identity's files; the man 7 capabilities page documents the capabilities' model; the man 5 sudoers page documents the sudo's configuration; the man 8 sestatus page documents the SELinux's status.

Reflect: the Linux security is the layered's design, and its layers are the accumulated's responses to the decades's threats. The identity's model (the users, the groups, the credentials) is the classical's foundation; the permissions' bits and the special's bits are the classical's mechanisms; the ACLs, the capabilities, and the attributes are the modern's extensions; the LSM's modules (the SELinux, the AppArmor) are the MAC's implementations; the PAM's and the NSS's stack is the authentication's framework; the audit's subsystem is the accounting's implementation; and the sysctl's parameters and the hardening's practices are the configuration's discipline. Which of the mechanisms from this lesson is the most important for the systems you administer? What would you change about the Linux security's design if you could? How would you explain the difference between the mode's bits and the capabilities to someone who has never thought about it? What is the right balance between the security's layers and the administration's burden?

07 Knowledge check

Check your understanding

Question 1

Describe the Linux identity's model: the users, the groups, the credentials (the real and effective UIDs and GIDs, the saved-set UIDs and GIDs, and the supplementary groups), and the identity's files (/etc/passwd, /etc/shadow, and /etc/group). Why do the credentials matter for the access's checks?

Show answer
The Linux identity's model is the Unix's inheritance: the users (the accounts with the UIDs), the groups (the accounts' collections with the GIDs), and the credentials (the process's identity's attributes). The identity's files are the /etc/passwd (the world-readable file that holds the users' accounts: the username, the password's placeholder, the UID, the GID, the GECOS field, the home's directory, and the login's shell), the /etc/shadow (the root-readable-only file that holds the passwords' hashes and the passwords' aging's information), and the /etc/group (the world-readable file that holds the groups: the name, the password's placeholder, the GID, and the members' list). The credentials are the process's identity's attributes, and the kernel's access checks use the credentials (not the identity's files' entries directly). The credentials' attributes: the real UID and GID (the identity of the user who started the process), the effective UID and GID (the identity that the kernel's access checks use: the process's permissions are the effective's values' permissions), the saved-set UID and GID (the effective's values' copy at the execve's time, and the values that let the process restore the previous effective's values after the privileged's operations), and the supplementary groups (the additional's GIDs that the process holds: the groups the user is a member of beyond the primary's group). The credentials matter for the access's checks because the kernel's reference monitor uses them to determine the process's permissions: the file's mode's categories (the owner, the group, the others) are compared with the process's effective UID, the effective GID, and the supplementary GIDs, and the match determines the applicable's category. The real and the effective's distinction is the source of the setuid's mechanism: a setuid's program's process runs with the file's owner's effective UID (the file's owner's identity) while the real UID remains the caller's, so the program can perform the privileged's operations (the effective's identity) and then drop the privileges (the saved-set's mechanism restores the caller's effective's identity). The observation is the reason the credentials are the kernel's security's central's abstraction: the credentials are the process's security's context, and the access's decisions are the credentials' and the resources' permissions' comparison.

Question 2

Describe the Linux permission's mechanisms: the mode's bits, the special's bits (setuid, setgid, and sticky), the POSIX ACLs, and the file attributes. What is each mechanism's purpose, and how does each implement the access control's design?

Show answer
The Linux permission's mechanisms are the layered's design. The mode's bits are the classical Unix's access control: the nine bits organized into the three categories (the owner's, the group's, and the others') with the three permissions (the read, the write, and the execute) in each category. The mode's semantics differ for the files (the read: the contents' reading, the write: the contents' modification, the execute: the program's execution) and the directories (the read: the entries' listing, the write: the entries' modification, the execute: the directory's traversal). The mode's design's advantages are the simplicity and the efficiency; its disadvantage is the coarseness (the three categories only). The special's bits are the additional's bits: the setuid's bit (the 4000: the executable's process runs with the file's owner's effective UID), the setgid's bit (the 2000: the executable's process runs with the file's group's effective GID, or the directory's files inherit the directory's group), and the sticky's bit (the 1000: the directory's files can only be deleted by the file's owner, the directory's owner, or the root). The setuid's and the setgid's bits' design's purpose is the privileged's programs' design (the programs that need the privileged's operations: the passwd, the su, the sudo), and the sticky's bit's purpose is the shared's directories' protection (the /tmp's design). The POSIX ACLs extend the mode's bits with the finer's granularity: the per-user's and the per-group's entries beyond the mode's three categories. The ACL's entries: the owner's (user::), the named user's (user:name:), the group's (group::), the named group's (group:name:), the mask's (mask::: the maximum's permissions for the named users, the named groups, and the group's entry), and the others' (other::). The default's ACLs (the default: prefix) on a directory determine the ACLs of the files and the directories created within the directory. The ACLs' design's purposes are the finer's granularity (the per-user's and the per-group's permissions) and the shared's directories' management (the default's ACLs' propagation). The file attributes (the chattr's flags) are the additional's properties beyond the mode's bits and the ACLs: the immutable (the i: the file cannot be modified, deleted, renamed, or linked, even by the root), the append-only (the a: the file can only be written in the append's mode), the no-dump (the d: the file is excluded from the backups), the secure-delete (the s: the file's blocks are zeroed on the deletion), the no-atime (the A: the access's time is not updated), and the compression (the c: the file is compressed on the disk). The attributes' design's purpose is the critical's files' protection (the immutable's and the append-only's attributes). The four mechanisms implement the access control's design by the layered's checks: the kernel's reference monitor combines the mode's bits, the ACLs, the attributes, and (the following's section) the capabilities and the LSM's modules, and the access's decision is the combination's result.

Question 3

Describe the Linux capabilities. What are the capabilities' sets (the permitted, the effective, the inheritable, the bounding, and the ambient), and how do the capabilities implement the least privilege's principle? What is the CAP_SYS_ADMIN's significance?

Show answer
The Linux capabilities split the root's all-or-nothing's privileges into the separate's units (the ~40 capabilities: the CAP_NET_BIND_SERVICE, the CAP_NET_RAW, the CAP_NET_ADMIN, the CAP_SYS_ADMIN, the CAP_DAC_OVERRIDE, the CAP_SETUID, the CAP_CHOWN, the CAP_KILL, the CAP_LINUX_IMMUTABLE, and the others). The capabilities' sets (the process's credential's components): the permitted set (cap_permitted: the capabilities the process may hold: the process's capabilities' upper bound), the effective set (cap_effective: the capabilities the process can use: the kernel's checks the effective's set when the process performs a privileged's operation), the inheritable set (cap_inheritable: the capabilities the process can pass to the programs it executes), the bounding set (cap_bounding: the capabilities the process can ever acquire: the process cannot add a capability that is not in the bounding's set), and the ambient set (cap_ambient: the capabilities the process passes to the programs it executes, and the programs retain them even if the programs are not the setuid's or the file's capabilities' programs). The capabilities implement the least privilege's principle by the fine-grained's privileges: instead of the setuid's root (the program's process runs with the root's whole's privileges), the capability's program runs with the specific's capabilities (the CAP_NET_RAW for the ping's raw's sockets, the CAP_NET_BIND_SERVICE for the web's server's port 80's binding). The observation is the reason the modern distributions replaced the setuid's ping with the capabilities' version: a bug in the capabilities' program gives the attacker only the specific's privilege, not the root's whole. The CAP_SYS_ADMIN's capability is the "the new root": it grants the mount's operations, the namespaces' administration, the ioctl's operations, the swap's management, and the many other operations. The capability's breadth is the model's practical's limitation: the process with the CAP_SYS_ADMIN's capability is effectively the root, and the capability's design's goal (the least privilege) is defeated by the capability's breadth. The observation is the reason the security's guides recommend the CAP_SYS_ADMIN's avoidance and the more specific's capabilities' use.

Question 4

Describe the Linux Security Modules (LSM) framework and its two principal implementations (the SELinux and the AppArmor). What are each module's design, its mechanisms, and its advantages and disadvantages? When is each appropriate?

Show answer
The Linux Security Modules (LSM) framework is the kernel's accommodation of the multiple access control's models: the kernel's code calls the hooks at the critical's points (the file's open, the process's creation, the socket's connection, the capability's check), and the security modules implement the hooks' policies. The framework's design's properties: the hooks' mediation (the additional's checks that extend the kernel's traditional's checks), the modules' registration (the multiple's modules' support, with the modules' hooks called in the registration's order), the kernel's build's options (the CONFIG_SECURITY and the module-specific's options), and the /sys/kernel/security/'s interface (the modules' state and configuration). The SELinux (the Security-Enhanced Linux) is the NSA's mandatory access control's implementation. The design's foundation: the type enforcement, the role-based access control, and the multi-level security. The components: the labels (the security's contexts: the user:role:type:level format, with the type as the central's field), the policy (the allow's rules, the type_transition's rules, the role's assignments, the boolean's tunables), the modes (the enforcing, the permissive, the disabled), the booleans (the policy's tunable's switches), and the tools (getenforce, sestatus, semanage, chcon, restorecon, setsebool, sesearch, and ausearch -m AVC). The SELinux's advantages: the MAC's enforcement (the system-wide's policy) and the damage's limitation (a compromised's process can access only the resources its type's policy permits). The disadvantages: the complexity (the policy's language, the labels' administration, the audit's messages' interpretation) and the rigidity (the policy's exceptions' design is the burdensome). The AppArmor is the alternative's mandatory access control's implementation (the SUSE's and the Ubuntu's default). The design's foundation: the path's confinement: the every's program has a profile that specifies the resources the program can access. The components: the profiles (the text's files in the /etc/apparmor.d/, with the permitted's paths, the capabilities, and the network's operations), the modes (the enforce, the complain, the disabled), and the tools (aa-status, aa-enforce, aa-complain, aa-genprof, aa-logprof, and apparmor_parser). The AppArmor's advantages: the simplicity (the path's confinement is the intuitive) and the ease of the administration. The disadvantages: the path's dependence (the profiles are the bound to the paths, so the programs' movements or the hard links can bypass them) and the scope (the confinement is the per-program, without the system-wide's policy). The two modules are the appropriate for the different environments: the SELinux for the high-security's systems (the government, the military, the finance) where the system-wide's policy and the MLS are the requirements, and the AppArmor for the general-purpose's systems (the desktops, the servers) where the simplicity and the ease of the administration matter more.

Question 5

Describe the Linux security's supporting mechanisms: the PAM and the NSS, the audit's subsystem, the sudo and su, and the kernel's security's parameters (sysctl). How do the mechanisms together implement the security's architecture, and what are the hardening's practices?

Show answer
The Linux security's supporting mechanisms complete the layered's design. The PAM (the Pluggable Authentication Modules) is the authentication's framework: the programs (the login, the su, the sudo, the sshd, the passwd) call the PAM's library, and the library's modules (the pam_unix, the pam_pwquality, the pam_faillock, the pam_limits, the pam_env, the pam_selinux, the pam_cap, the pam_google_authenticator) perform the authentication's steps. The PAM's advantages are the programs' and the mechanisms' independence and the authentication's policy's centralization. The NSS (the Name Service Switch) is the framework for the identity's sources: the /etc/nsswitch.conf's file specifies the sources' order (the files, the systemd, the ldap, the sss, the winbind). The NSS is what makes the Linux's authentication the enterprise-ready: the same PAM's stack can authenticate the local's users and the directory's users. The audit's subsystem is the AAA model's third pillar's (the accounting's) implementation: the kernel's audit's framework generates the events (the system calls, the file's accesses, the authentication's events, the SELinux's denials), the auditd's daemon writes them to the log's files, and the tools (ausearch, aureport) query and report them. The sudo and the su are the privilege's escalation's mechanisms: the su switches the user's identity (the whole's shell), and the sudo executes the specific commands with the target's privileges (the sudoers's file determines the commands). The sudo's design's advantages are the least privilege's granularity and the accountability. The sysctl's parameters are the kernel's runtime's security's settings: the network's parameters (the tcp_syncookies, the rp_filter, the accept_redirects, the accept_source_route), the kernel's parameters (the randomize_va_space, the dmesg_restrict, the kptr_restrict, the yama.ptrace_scope), the file system's parameters (the protected_hardlinks, the protected_symlinks, the suid_dumpable), and the virtual memory's parameters (the mmap_min_addr). The mechanisms together implement the security's architecture: the PAM's and the NSS's stack is the authentication's layer, the kernel's checks (the mode's bits, the ACLs, the capabilities) and the LSM's modules are the authorization's layer, the audit's subsystem is the accounting's layer, and the sudo and the su are the privilege's escalation's mechanisms. The hardening's practices are the configuration's discipline: the attack's surface's reduction (the unnecessary services' removal, the ports' closing, the setuid's programs' review), the identities' hardening (the strong's passwords, the SSH's keys, the sudo's rules, the MFA), the kernel's hardening (the sysctl's settings, the ASLR, the SELinux or the AppArmor), the file systems' hardening (the permissions' review, the mount's options, the disk's encryption), the logging's and the monitoring's hardening (the auditd's rules, the logs' protection, the integrity's monitoring), and the updates' management (the patches, the scanning). The hardening's central's tension is the security and the functionality's trade-off, and its design's goal is the balance: the strongest security the functionality permits, and the functionality the security requires.

08 Unit discussion

Discussion prompt

The Linux security is the layered's design, and its history is a history of the layers' accumulation. The classical's Unix (the 1970s) provided the identity's model (the users, the groups, the credentials), the permissions' bits, and the setuid's mechanism; the design was the simple and the sufficient for the time's multi-user's systems. The ACLs (the 1990s) added the finer's granularity; the capabilities (the 2000s) split the root's all-or-nothing's privileges; the LSM's framework (the 2000s) enabled the multiple MAC's implementations (the SELinux, the AppArmor); the audit's subsystem (the 2000s) added the accounting; and the namespace's isolation (the 2010s) and the systemd's hardening's directives (the 2010s and the 2020s) added the modern's confinement's mechanisms. Each layer was the response to the previous layers' limitations, and each was shaped by the threats of its time.

The trend is toward the defence in depth and the least privilege. The classical's Unix was the single's mechanism (the permissions' bits) and the coarse's privileges (the root's all-or-nothing); the modern's Linux is the multiple's mechanisms (the permissions' bits, the ACLs, the capabilities, the attributes, the LSM's modules, the systemd's directives, the namespaces) and the fine-grained's privileges (the capabilities' units, the SELinux's types, the AppArmor's profiles, the systemd's CapabilityBoundingSet). The trend's driver is the threats' evolution: the classical's attacks (the local's users' privilege's escalation) were the simple, and the modern's attacks (the remote's code's execution, the supply chain's compromise, the container's escape) are the complex, and the defences must be the layered. The observation is the reason the modern's systems' security is the configuration's discipline: the layers are the many, and the layers' correct's configuration is the security's requirement.

The trend also raises a question about the security and the usability's balance. The more secure's configuration (the SELinux's enforcing, the strict's profiles, the restrictive's sysctl's settings, the minimized's services) is the more complex and the less convenient, and the users' response to the inconvenient's security is the bypasses (the SELinux's disabling, the profiles' complain's mode, the services' re-enabling). The observation is the reason the psychological acceptability's principle (Lesson 12.1's principle 8) is the security's design's central's concern: the security's mechanism must be the usable, or the users will find the ways around it. The modern's approach (the sensible's defaults: the SELinux's targeted's policy, the AppArmor's shipped's profiles, the systemd's hardening's directives' defaults) is the principle's practical's application.

Which of the Linux security's layers is the most important for the modern's systems, and why? Should the security's design prioritize the defence in depth (the many layers) or the simplicity (the fewer layers, the easier configuration)? What is the right balance between the security's strictness and the users' convenience? How should the Linux security's design evolve for the containers, the cloud, and the edge's computing? Post your response to the Unit 12 discussion forum and reply to at least two classmates. Supports CLO1, CLO7, and CLO8.

09 Practice exercise

This ungraded exercise consolidates the lesson and prepares you for Lesson 12.6. Aim to spend 60–90 minutes on it.

  1. Inventory the system's security's state. On your VM, perform a comprehensive security's inventory:
    # The identity's model
    id
    cat /proc/self/status | grep -E 'Uid|Gid|Cap'
    cat /etc/passwd | head -20
    sudo cat /etc/shadow | head -5
    cat /etc/group | head -20
    
    # The permissions' mechanisms
    ls -la /etc/passwd /etc/shadow
    find / -perm -4000 -type f 2>/dev/null
    find / -perm -2000 -type f 2>/dev/null | head -10
    find / -type f -perm -o+w 2>/dev/null | head -10
    getfacl /home/ 2>/dev/null
    
    # The capabilities and the attributes
    getcap -r / 2>/dev/null
    lsattr /etc/passwd /var/log/ 2>/dev/null | head -10
    
    # The LSM's modules
    getenforce 2>/dev/null
    sestatus 2>/dev/null | head -10
    sudo aa-status 2>/dev/null | head -10
    
    # The audit's subsystem
    sudo auditctl -s 2>/dev/null
    sudo auditctl -l 2>/dev/null
    
    # The kernel's parameters
    sysctl -a 2>/dev/null | grep -E 'randomize_va_space|dmesg_restrict|yama.ptrace|ipv4.tcp_syncookies|ipv4.conf.all.rp_filter|fs.protected' | head -15
    
    # The sudo's and the PAM's configuration
    sudo cat /etc/sudoers | grep -vE '^#|^$'
    cat /etc/pam.d/sshd /etc/pam.d/login 2>/dev/null | head -30
    grep -E 'passwd|group|shadow' /etc/nsswitch.conf
    Write a report (500–750 words) that describes the system's security's state, identifies the weaknesses (the unnecessary's setuid's programs, the world-writable's files, the disabled's security's modules, the permissive's sysctl's settings), and recommends the hardening's actions.
  2. Experiment with the credentials and the setuid's mechanism. On your VM, create a setuid's test program and observe the credentials' changes:
    # Create a test program that prints the credentials
    cat > /tmp/creds.c << 'EOF'
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    int main() {
        printf("RUID=%d EUID=%d\n", getuid(), geteuid());
        printf("RGID=%d EGID=%d\n", getgid(), getegid());
        return 0;
    }
    EOF
    gcc -o /tmp/creds /tmp/creds.c
    
    # Run the program normally
    /tmp/creds
    
    # Set the setuid's bit and the owner to the root
    sudo chown root:root /tmp/creds
    sudo chmod 4755 /tmp/creds
    ls -la /tmp/creds
    
    # Run the program as a different user
    sudo -u nobody /tmp/creds
    
    # Compare the outputs. What changed?
    # Clean up
    sudo rm /tmp/creds /tmp/creds.c
    What were the credentials in the two runs? What changed when the setuid's bit was set? Explain the mechanism's design.
  3. Design a capability's policy. A web server (the nginx) is being configured on the system. The server needs to bind to the port 80 (the privileged's port, the CAP_NET_BIND_SERVICE's capability) and to read the web's files. Design the server's capability's policy:
    • Which capabilities does the server need?
    • How would you attach the capabilities to the server's binary (or the systemd's unit)?
    • What would be the difference between the capability's approach and the root's approach?
    • What would be the difference between the capability's approach and the setuid's approach?
    • What would be the systemd's directives (CapabilityBoundingSet, AmbientCapabilities, NoNewPrivileges) in the server's unit?
    Justify your design.
  4. Design a hardening's plan. A small business's Linux server hosts the company's web site, its email, and its file sharing. Design the server's hardening's plan:
    • The attack's surface's reduction (the services, the ports, the accounts).
    • The authentication's hardening (the passwords, the SSH, the MFA, the sudo).
    • The kernel's hardening (the sysctl's settings, the ASLR, the LSM's module).
    • The file systems' hardening (the permissions, the mount's options, the encryption).
    • The logging's and the monitoring's hardening (the auditd's rules, the logs' protection, the integrity's monitoring).
    • The updates' management (the patches, the scanning).
    Justify your design through the security's principles (the least privilege, the fail-safe defaults, the defence in depth) and the lesson's mechanisms.
  5. Compare the SELinux and the AppArmor. Write a short essay (400–500 words) comparing the SELinux and the AppArmor. Your essay should address:
    • Each module's design (the type enforcement versus the path's confinement).
    • Each module's components (the labels, the policy, the booleans versus the profiles, the paths, the capabilities).
    • Each module's advantages and disadvantages.
    • Each module's appropriate environments.
    • The modules' combinations with the other Linux security's mechanisms (the DAC, the capabilities).
    Conclude with a recommendation for a university's server and for a desktop.
  6. Audit a system's security's configuration. Use the CIS's benchmark or the distribution's security's guide to audit your VM's configuration:
    # Install the audit's tool (if available)
    which oscap 2>/dev/null
    which lynis 2>/dev/null
    
    # If the tools are available, run the audit
    sudo lynis audit system 2>/dev/null | head -50
    
    # Or perform the manual's checks
    # The SSH's configuration
    sudo grep -E 'PermitRootLogin|PasswordAuthentication|PubkeyAuthentication|Port' /etc/ssh/sshd_config
    
    # The sysctl's settings
    sysctl -a 2>/dev/null | grep -E 'net.ipv4.tcp_syncookies|net.ipv4.conf.all.rp_filter|kernel.randomize_va_space|kernel.dmesg_restrict'
    
    # The setuid's programs
    find / -perm -4000 -type f 2>/dev/null
    
    # The world-writable's files
    find / -type f -perm -o+w 2>/dev/null | head -10
    
    # The services' state
    systemctl list-units --type=service --state=running 2>/dev/null | head -20
    What are the audit's findings? Which of the CIS's recommendations are the unmet? What are the most important's remediations? Write a report (500–750 words).
  7. Explore the audit's subsystem. On your VM, configure and test the audit's subsystem:
    # Show the current audit's rules
    sudo auditctl -l 2>/dev/null
    
    # Add a rule to audit the /etc/passwd's changes
    sudo auditctl -w /etc/passwd -p wa -k passwd_changes
    
    # Add a rule to audit the failed's logins
    sudo auditctl -a always,exit -F arch=b64 -S execve -k exec_commands 2>/dev/null
    
    # Test the rules
    sudo useradd testaudit
    sudo userdel testaudit
    
    # Search the audit's log
    sudo ausearch -k passwd_changes 2>/dev/null | head -20
    sudo ausearch -k exec_commands 2>/dev/null | tail -20
    
    # Generate the reports
    sudo aureport --auth 2>/dev/null | head -10
    sudo aureport --file 2>/dev/null | head -10
    sudo aureport --summary 2>/dev/null | head -20
    
    # Remove the rules
    sudo auditctl -W /etc/passwd -p wa -k passwd_changes 2>/dev/null
    sudo auditctl -d always,exit -F arch=b64 -S execve -k exec_commands 2>/dev/null
    What did the audit's rules record? What did the ausearch's queries show? What did the aureport's reports summarize? How does the audit's subsystem help the security's operations?
  8. Reflect. In your own words, explain the Linux security's architecture and its layers (the identity's model, the permissions' mechanisms, the capabilities, the LSM's modules, the authentication's stack, the audit's subsystem, and the hardening's practices). Then describe one situation in your own experience — a system you have administered or used — where the Linux security's mechanisms affected the security or the usability. What was the system, and how would a different mechanism or configuration have changed the outcome?

10 Summary

  • The Linux security's architecture is the layered's design: the hardware's protection's mechanisms, the kernel's core (the reference monitor), the LSM's framework, the user-space's services (the PAM, the NSS, the auditd), and the applications' security.
  • The identity's model comprises the users (the UIDs), the groups (the GIDs), and the credentials (the real and effective UIDs and GIDs, the saved-set UIDs and GIDs, and the supplementary groups). The identity's files are the /etc/passwd, the /etc/shadow, and the /etc/group (and the /etc/gshadow).
  • The permission's mechanisms are the mode's bits (the nine bits: the owner's, the group's, and the others' read, write, and execute), the special's bits (the setuid, the setgid, and the sticky), the POSIX ACLs (the per-user's and the per-group's entries, the mask, the default's ACLs), and the file attributes (the immutable, the append-only, the no-dump, the secure-delete, the no-atime, the compression).
  • The Linux capabilities split the root's privileges into the separate's units. The sets: the permitted, the effective, the inheritable, the bounding, and the ambient. The capabilities implement the least privilege's principle, and the CAP_SYS_ADMIN is the "the new root".
  • The Linux Security Modules (LSM) framework is the kernel's accommodation of the multiple access control's models: the hooks at the critical's points, the modules' registration, and the /sys/kernel/security/'s interface. The SELinux (the type enforcement's MAC: the labels, the policy, the booleans, the modes) and the AppArmor (the path's confinement's MAC: the profiles, the paths, the modes) are the two principal's implementations.
  • The authentication's stack is the PAM (the framework: the programs, the modules, the configuration) and the NSS (the identity's sources: the files, the systemd, the ldap, the sssd). The audit's subsystem is the AAA model's third pillar's implementation: the kernel's audit's framework, the auditd's daemon, and the tools (ausearch, aureport).
  • The sudo and the su are the privilege's escalation's mechanisms: the su switches the user's identity (the whole's shell), and the sudo executes the specific's commands with the target's privileges (the sudoers's configuration). The sudo's design implements the least privilege's principle and the accountability.
  • The kernel's security's parameters (the sysctl's settings) are the runtime's hardening's configuration: the network's parameters (the tcp_syncookies, the rp_filter), the kernel's parameters (the randomize_va_space, the dmesg_restrict, the yama.ptrace_scope), the file system's parameters (the protected_hardlinks, the protected_symlinks), and the virtual memory's parameters (the mmap_min_addr).
  • The hardening's practices are the configuration's discipline: the attack's surface's reduction, the identities' and the authentication's hardening, the kernel's hardening, the file systems' hardening, the logging's and the monitoring's hardening, and the updates' management. The hardening's central's tension is the security and the functionality's trade-off.

Looking ahead

This lesson presented the Linux security: the architecture, the identity's model, the permission's mechanisms, the capabilities, the file attributes, the LSM's framework and its two principal implementations, the authentication's stack, the audit's subsystem, the sudo and su, the kernel's security's parameters, and the hardening's practices. It referred several times to the isolation — the mechanisms that confine the processes to the minimum resources — and to the containers and the namespaces. Lesson 12.6 presents sandboxing in detail: the isolation's mechanisms (the namespaces: the mount, the PID, the network, the user, the IPC, the UTS, the cgroup, and the time), the control groups (the cgroups: the resource's limits), the seccomp's filter (the system calls' restrictions), the chroot and the pivot_root (the file system's confinement), the Linux containers (the Docker, the Podman, the LXC), the sandboxing's designs (the browsers' sandboxes: the Chrome's sandbox, the Firefox's content's processes), and the isolation's trade-offs. The lesson is the unit's presentation of the confinement's mechanisms, and it is the bridge to the virtualization and the cloud that Unit 13 presents.

11 References

  • Silberschatz, A., Galvin, P. B., & Gagne, G. Operating System Concepts, 10th ed., Chapters 16 and 17.
  • Arpaci-Dusseau, R. H., & Arpaci-Dusseau, A. C. Operating Systems: Three Easy Pieces, the Security chapters. Available online at ostep.org.
  • Tanenbaum, A. S., & Bos, H. Modern Operating Systems, 4th ed., Chapter 9.
  • Kerrisk, M. The Linux Programming Interface. No Starch Press, 2010. Chapters 8, 9, and 39.
  • Bovet, D. P., & Cesati, M. Understanding the Linux Kernel, 3rd ed. O'Reilly, 2005. Chapters 20 and the security's chapters.
  • Love, R. Linux Kernel Development, 3rd ed. Chapters 5, 6, and the security's modules' chapters.
  • Smalley, S., Vance, C., & Salamon, W. Implementing SELinux as a Linux Security Module. NAI Labs Technical Report, 2001.
  • Wright, C., Cowan, C., Smalley, S., Morris, J., & Kroah-Hartman, G. Linux Security Modules: General Security Support for the Linux Kernel. USENIX Annual Technical Conference, 2002.
  • Bauer, M. Paranoid Penguin: A Step-by-Step Guide to Building a Secure Linux Server. No Starch Press, 2005.
  • Linux man-pages: man 1 id, man 5 passwd, man 5 shadow, man 5 group, man 1 chmod, man 1 chown, man 5 acl, man 7 capabilities, man 1 chattr, man 1 lsattr, man 5 pam.conf, man 5 nsswitch.conf, man 8 auditctl, man 8 ausearch, man 8 aureport, man 5 sudoers, man 8 sudo, man 8 su, man 8 getenforce, man 8 sestatus, man 8 semanage, man 5 apparmor.d, man 8 aa-status, man 8 sysctl, man 5 sysctl.conf.
👤