Landlock audit support
Subsystems (6)
Mickaël Salaün
maintainerv6 cover Landlock audit support
Hi,
This patch series adds audit support to Landlock.
Logging denied requests is useful for different use cases:
- sysadmins: to look for users' issues,
- security experts: to detect attack attempts,
- power users: to understand denials,
- developers: to ease sandboxing support and get feedback from users.
Because of its unprivileged nature, Landlock can compose standalone security policies (i.e. domains). To make logs useful, they need to contain the most relevant Landlock domain that denied an action, and the reason of such denial. This translates to the latest nested domain and the related blockers: missing access rights or other kind of restrictions.
# Main changes from previous version
Renamed the landlock_restrict_self(2) flags to improve clarity and consistency, and slightly change the semantic of the first one:
- LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF: do not log denied access caused by a task with the same executable (i.e. before any new execve(2));
- LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC_ON: log denied access for processes resulting from an execve(2), which is not the case by default.
- LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF: do not log denied access from future nested domains.
These new LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF and LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC_ON are not incompatible anymore.
Make it possible to set LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF without ruleset/domain. This bit is now stored directly in the Landlock credentials, not a potential related domain.
Moved audit data declarations to not impact allowed requests.
Added new tests and improved previous ones. I'm still working on new tests but the kernel code should not change much with the next versions. I'd still like to align as much as possible with other LSM logs regarding the logged objects: e.g. in a link action, should we log the dir's path or the file's dentry?
# Design
Log records are created for any denied actions caused by a Landlock policy, which means that a well-sandboxed applications should not log anything except for unattended access requests that might be the result of attacks or bugs.
However, sandbox tools creating restricted environments could lead to abundant log entries because the sandboxed processes may not be aware of the related restrictions. To avoid log spam, the landlock_restrict_self(2) syscall gets new flags to not log denials related to this specific domain. Except for well-understood exceptions, these flags should not be set. Indeed, applications sandboxing themselves should only try to bypass their own sandbox if they are compromised, which should ring a bell thanks to log events.
When an action is denied, the related Landlock domain ID is specified. If this domain was not previously described in a log record, one is created. This record contains the domain ID, its creation time, and informations about the process that enforced the restriction (at the time of the call to landlock_restrict_self): PID, UID, executable path, and name (comm).
This new approach also brings building blocks for an upcoming unprivileged introspection interface. The unique Landlock IDs will be useful to tie audit log entries to running processes, and to get properties of the related Landlock domains. This will replace the previously logged ruleset properties.
# Samples
Here are two examples of log events (see serial numbers):
$ LL_FS_RO=/ LL_FS_RW=/ LL_SCOPED=s LL_FORCE_LOG=1 ./sandboxer kill 1
type=LANDLOCK_ACCESS msg=audit(1729738800.268:30): domain=1a6fdc66f blockers=scope.signal opid=1 ocomm="systemd" type=LANDLOCK_DOMAIN msg=audit(1729738800.268:30): domain=1a6fdc66f status=allocated mode=enforcing pid=286 uid=0 exe="/root/sandboxer" comm="sandboxer" type=SYSCALL msg=audit(1729738800.268:30): arch=c000003e syscall=62 success=no exit=-1 [..] ppid=272 pid=286 auid=0 uid=0 gid=0 [...] comm="kill" [...] type=PROCTITLE msg=audit(1729738800.268:30): proctitle=6B696C6C0031
type=LANDLOCK_DOMAIN msg=audit(1729738800.324:31): domain=1a6fdc66f status=deallocated denials=1
$ LL_FS_RO=/ LL_FS_RW=/tmp LL_FORCE_LOG=1 ./sandboxer sh -c "echo > /etc/passwd"
type=LANDLOCK_ACCESS msg=audit(1729738800.221:33): domain=1a6fdc679 blockers=fs.write_file path="/dev/tty" dev="devtmpfs" ino=9 type=LANDLOCK_DOMAIN msg=audit(1729738800.221:33): domain=1a6fdc679 status=allocated mode=enforcing pid=289 uid=0 exe="/root/sandboxer" comm="sandboxer" type=SYSCALL msg=audit(1729738800.221:33): arch=c000003e syscall=257 success=no exit=-13 [...] ppid=272 pid=289 auid=0 uid=0 gid=0 [...] comm="sh" [...] type=PROCTITLE msg=audit(1729738800.221:33): proctitle=7368002D63006563686F203E202F6574632F706173737764
type=LANDLOCK_ACCESS msg=audit(1729738800.221:34): domain=1a6fdc679 blockers=fs.write_file path="/etc/passwd" dev="vda2" ino=143821 type=SYSCALL msg=audit(1729738800.221:34): arch=c000003e syscall=257 success=no exit=-13 [...] ppid=272 pid=289 auid=0 uid=0 gid=0 [...] comm="sh" [...] type=PROCTITLE msg=audit(1729738800.221:34): proctitle=7368002D63006563686F203E202F6574632F706173737764
type=LANDLOCK_DOMAIN msg=audit(1729738800.261:35): domain=1a6fdc679 status=deallocated denials=2
# Previous versions
v5: https://lore.kernel.org/r/[email protected]
v4: https://lore.kernel.org/r/[email protected]
v3: https://lore.kernel.org/r/[email protected]
v2: https://lore.kernel.org/r/[email protected]
v1: https://lore.kernel.org/r/[email protected]
Regards,
Mickaël Salaün (26):
lsm: Add audit_log_lsm_data() helper
landlock: Add unique ID generator
landlock: Move domain hierarchy management
landlock: Prepare to use credential instead of domain for filesystem
landlock: Prepare to use credential instead of domain for network
landlock: Prepare to use credential instead of domain for scope
landlock: Prepare to use credential instead of domain for fowner
landlock: Identify domain execution crossing
landlock: Add AUDIT_LANDLOCK_ACCESS and log ptrace denials
landlock: Add AUDIT_LANDLOCK_DOMAIN and log domain status
landlock: Log mount-related denials
landlock: Log file-related denials
landlock: Log truncate and IOCTL denials
landlock: Log TCP bind and connect denials
landlock: Log scoped denials
landlock: Add LANDLOCK_RESTRICT_SELF_LOG_*_EXEC_* flags
landlock: Add LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF samples/landlock: Enable users to log sandbox denials selftests/landlock: Add test for invalid ruleset file descriptor selftests/landlock: Extend tests for landlock_restrict_self(2)'s flags selftests/landlock: Add tests for audit flags and domain IDs selftests/landlock: Test audit with restrict flags selftests/landlock: Add audit tests for ptrace selftests/landlock: Add audit tests for abstract unix socket scoping selftests/landlock: Add audit tests for filesystem
landlock: Add audit documentation
Documentation/admin-guide/LSM/index.rst | 1 + Documentation/admin-guide/LSM/landlock.rst | 158 ++++++ Documentation/security/landlock.rst | 13 +- Documentation/userspace-api/landlock.rst | 9 +- MAINTAINERS | 1 + include/linux/lsm_audit.h | 8 + include/uapi/linux/audit.h | 4 +- include/uapi/linux/landlock.h | 33 ++ samples/landlock/sandboxer.c | 37 +- security/landlock/.kunitconfig | 2 + security/landlock/Makefile | 5 + security/landlock/access.h | 23 + security/landlock/audit.c | 519 ++++++++++++++++++ security/landlock/audit.h | 77 +++ security/landlock/cred.c | 26 +- security/landlock/cred.h | 89 ++- security/landlock/domain.c | 264 +++++++++ security/landlock/domain.h | 157 ++++++ security/landlock/fs.c | 275 ++++++++-- security/landlock/fs.h | 35 +- security/landlock/id.c | 251 +++++++++ security/landlock/id.h | 25 + security/landlock/limits.h | 4 + security/landlock/net.c | 74 ++- security/landlock/ruleset.c | 33 +- security/landlock/ruleset.h | 47 +- security/landlock/setup.c | 2 + security/landlock/syscalls.c | 72 ++- security/landlock/task.c | 239 +++++--- security/lsm_audit.c | 27 +- tools/testing/kunit/configs/all_tests.config | 2 + tools/testing/selftests/landlock/Makefile | 6 +- tools/testing/selftests/landlock/audit.h | 425 ++++++++++++++ tools/testing/selftests/landlock/audit_test.c | 460 ++++++++++++++++ tools/testing/selftests/landlock/base_test.c | 84 ++- tools/testing/selftests/landlock/common.h | 19 + tools/testing/selftests/landlock/config | 1 + tools/testing/selftests/landlock/fs_test.c | 455 +++++++++++++++ .../testing/selftests/landlock/ptrace_test.c | 140 +++++ .../landlock/scoped_abstract_unix_test.c | 121 ++++ .../selftests/landlock/wait-pipe-sandbox.c | 131 +++++ 41 files changed, 4123 insertions(+), 231 deletions(-) create mode 100644 Documentation/admin-guide/LSM/landlock.rst create mode 100644 security/landlock/audit.c create mode 100644 security/landlock/audit.h create mode 100644 security/landlock/domain.c create mode 100644 security/landlock/domain.h create mode 100644 security/landlock/id.c create mode 100644 security/landlock/id.h create mode 100644 tools/testing/selftests/landlock/audit.h create mode 100644 tools/testing/selftests/landlock/audit_test.c create mode 100644 tools/testing/selftests/landlock/wait-pipe-sandbox.c
base-commit: 7eb172143d5508b4da468ed59ee857c6e5e01da6
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 1/26 lsm: Add audit_log_lsm_data() helper
Extract code from dump_common_audit_data() into the audit_log_lsm_data() helper. This helps reuse common LSM audit data while not abusing AUDIT_AVC records because of the common_lsm_audit() helper.
Depends-on: 7ccbe076d987 ("lsm: Only build lsm_audit.c if CONFIG_SECURITY and CONFIG_AUDIT are set")
---
Changes since v4:
- Add Depends-on tag.
Changes since v3:
- Rebase on top of the v6.13's get_task_comm() fix.
- Add Acked-by Paul.
Changes since v1:
- Fix commit message (spotted by Paul).
- Constify dump_common_audit_data()'s and audit_log_lsm_data()'s "a" argument.
- Fix build without CONFIG_NET: see previous patch.
--- include/linux/lsm_audit.h | 8 ++++++++ security/lsm_audit.c | 27 ++++++++++++++++++--------- 2 files changed, 26 insertions(+), 9 deletions(-)
include/linux/lsm_audit.h +8 -0
@@ -132,6 +132,9 @@ void common_lsm_audit(struct common_audit_data *a,void (*pre_audit)(struct audit_buffer *,void *), void (*post_audit)(struct audit_buffer *, void *)); +void audit_log_lsm_data (struct audit_buffer *ab, +const struct common_audit_data *a); +#else /* CONFIG_AUDIT */ static inline void common_lsm_audit(struct common_audit_data *a,
@@ -140,6 +143,11 @@ static inline void common_lsm_audit(struct common_audit_data *a, { } +static inline void audit_log_lsm_data (struct audit_buffer *ab, +const struct common_audit_data *a) +{ +} +#endif /* CONFIG_AUDIT */ #endif
security/lsm_audit.c +18 -9
@@ -189,16 +189,13 @@ static inline void print_ipv4_addr(struct audit_buffer *ab, __be32 addr, }/** -* dump_common_audit_data - helper to dump common audit data +* audit_log_lsm_data - helper to log common LSM audit data * @ab : the audit buffer * @a : common audit data -* */ -static void dump_common_audit_data (struct audit_buffer *ab, -struct common_audit_data *a) +void audit_log_lsm_data (struct audit_buffer *ab, +const struct common_audit_data *a) { -char comm[sizeof (current->comm)]; -/* * To keep stack sizes in check force programmers to notice if they * start making this union too large! See struct lsm_network_audit
@@ -206,9 +203,6 @@ static void dump_common_audit_data(struct audit_buffer *ab,*/ BUILD_BUG_ON (sizeof (a->u) >sizeof (void *)*2 ); -audit_log_format (ab," pid=%d comm=" ,task_tgid_nr (current)); -audit_log_untrustedstring (ab,get_task_comm (comm, current)); -switch (a->type) {case LSM_AUDIT_DATA_NONE :return ;
@@ -431,6 +425,21 @@ static void dump_common_audit_data(struct audit_buffer *ab, }/* switch (a->type) */ } +/** +* dump_common_audit_data - helper to dump common audit data +* @ab : the audit buffer +* @a : common audit data +*/ +static void dump_common_audit_data (struct audit_buffer *ab, +const struct common_audit_data *a) +{ +char comm[sizeof (current->comm)]; + +audit_log_format (ab," pid=%d comm=" ,task_tgid_nr (current)); +audit_log_untrustedstring (ab,get_task_comm (comm, current)); +audit_log_lsm_data (ab, a); +} +/** * common_lsm_audit - generic LSM auditing function * @a: auxiliary audit data
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 2/26 landlock: Add unique ID generator
In reply to Mickaël SalaünLandlock IDs can be generated to uniquely identify Landlock objects. For now, only Landlock domains get an ID at creation time. These IDs map to immutable domain hierarchies.
Landlock IDs have important properties:
- They are unique during the lifetime of the running system thanks to the 64-bit values: at worse, 2^60 - 2*2^32 useful IDs.
- They are always greater than 2^32 and must then be stored in 64-bit integer types.
- The initial ID (at boot time) is randomly picked between 2^32 and 2^33, which limits collisions in logs across different boots.
- IDs are sequential, which enables users to order them.
- IDs may not be consecutive but increase with a random 2^4 step, which limits side channels.
Such IDs can be exposed to unprivileged processes, even if it is not the case with this audit patch series. The domain IDs will be useful for user space to identify sandboxes and get their properties.
These Landlock IDs are more secure that other absolute kernel IDs such as pipe's inodes which rely on a shared global counter.
For checkpoint/restore features (i.e. CRIU), we could easily implement a privileged interface (e.g. sysfs) to set the next ID counter.
IDR/IDA are not used because we only need a bijection from Landlock objects to Landlock IDs, and we must not recycle IDs. This enables us to identify all Landlock objects during the lifetime of the system (e.g. in logs), but not to access an object from an ID nor know if an ID is
assigned. Using a counter is simpler, it scales (i.e. avoids growing
memory footprint), and it does not require locking. We'll use proper file descriptors (with IDs used as inode numbers) to access Landlock objects.
---
Changes since v5:
- Add KUnit error message, suggested by Günther.
Changes since v3:
- Rename landlock_get_id_range() helper to reflect the "range" of IDs.
- Add docstring for landlock_get_id_range().
Changes since v2:
- Extend commit message.
- Rename global_counter to next_id.
- Fix KUnit's test __init types, spotted by kernel test robot.
Changes since v1:
- New patch.
--- security/landlock/.kunitconfig | 2 + security/landlock/Makefile | 2 + security/landlock/id.c | 251 +++++++++++++++++++ security/landlock/id.h | 25 ++ security/landlock/setup.c | 2 + tools/testing/kunit/configs/all_tests.config | 2 + 6 files changed, 284 insertions(+) create mode 100644 security/landlock/id.c create mode 100644 security/landlock/id.h
security/landlock/.kunitconfig +2 -0
@@ -1,4 +1,6 @@ +CONFIG_AUDIT=y CONFIG_KUNIT=y +CONFIG_NET=y CONFIG_SECURITY=y CONFIG_SECURITY_LANDLOCK=y CONFIG_SECURITY_LANDLOCK_KUNIT_TEST=y
security/landlock/Makefile +2 -0
@@ -4,3 +4,5 @@ landlock-y := setup.o syscalls.o object.o ruleset.o \ cred.o task.o fs.o landlock-$(CONFIG_INET) += net.o + +landlock-$(CONFIG_AUDIT) += id.o
security/landlock/id.c new file +251 -0
251 lines not on this page · raw message
security/landlock/id.h new file +25 -0
@@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - Unique identification number generator +* +* Copyright © 2024-2025 Microsoft Corporation +*/ + +#ifndef _SECURITY_LANDLOCK_ID_H +#define _SECURITY_LANDLOCK_ID_H + +#ifdef CONFIG_AUDIT + +void __init landlock_init_id (void ); + +u64 landlock_get_id_range (size_t number_of_ids); + +#else /* CONFIG_AUDIT */ + +static inline void __init landlock_init_id (void ) +{ +} + +#endif /* CONFIG_AUDIT */ + +#endif /* _SECURITY_LANDLOCK_ID_H */
security/landlock/setup.c +2 -0
@@ -13,6 +13,7 @@#include "common.h" #include "cred.h" #include "fs.h" +#include "id.h" #include "net.h" #include "setup.h" #include "task.h"
@@ -33,6 +34,7 @@ const struct lsm_id landlock_lsmid = {static int __init landlock_init (void ) { +landlock_init_id ();landlock_add_cred_hooks ();landlock_add_task_hooks ();landlock_add_fs_hooks ();
tools/testing/kunit/configs/all_tests.config +2 -0
@@ -41,6 +41,8 @@ CONFIG_DAMON_PADDR=y CONFIG_REGMAP_BUILD=y +CONFIG_AUDIT=y + CONFIG_SECURITY=y CONFIG_SECURITY_APPARMOR=y CONFIG_SECURITY_LANDLOCK=y
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 3/26 landlock: Move domain hierarchy management
In reply to Mickaël SalaünCreate a new domain.h file containing the struct landlock_hierarchy definition and helpers. This type will grow with audit support. This also prepares for a new domain type.
---
Changes since v4:
- Revert v3 changes because of the new audit rule patch removal.
Changes since v3:
- Export landlock_get_hierarchy() and landlock_put_hierarchy().
- Clean up Makefile entries.
Changes since v1:
- New patch.
--- security/landlock/domain.h | 48 +++++++++++++++++++++++++++++++++++++ security/landlock/ruleset.c | 21 +++------------- security/landlock/ruleset.h | 17 +------------ security/landlock/task.c | 1 + 4 files changed, 53 insertions(+), 34 deletions(-) create mode 100644 security/landlock/domain.h
security/landlock/domain.h new file +48 -0
@@ -0,0 +1,48 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - Domain management +* +* Copyright © 2016-2020 Mickaël Salaün <[email protected]> +* Copyright © 2018-2020 ANSSI +*/ + +#ifndef _SECURITY_LANDLOCK_DOMAIN_H +#define _SECURITY_LANDLOCK_DOMAIN_H + +#include <linux/mm.h> +#include <linux/refcount.h> + +/** +* struct landlock_hierarchy - Node in a domain hierarchy +*/ +struct landlock_hierarchy { +/** +* @parent: Pointer to the parent node, or NULL if it is a root +* Landlock domain. +*/ +struct landlock_hierarchy *parent; +/** +* @usage: Number of potential children domains plus their parent +* domain. +*/ +refcount_t usage; +}; + +static inline void +landlock_get_hierarchy (struct landlock_hierarchy *const hierarchy) +{ +if (hierarchy) +refcount_inc (&hierarchy->usage); +} + +static inline void landlock_put_hierarchy (struct landlock_hierarchy *hierarchy) +{ +while (hierarchy &&refcount_dec_and_test (&hierarchy->usage)) { +const struct landlock_hierarchy *const freeme = hierarchy; + + hierarchy = hierarchy->parent; +kfree (freeme); + } +} + +#endif /* _SECURITY_LANDLOCK_DOMAIN_H */
security/landlock/ruleset.c +3 -18
@@ -23,6 +23,7 @@#include <linux/workqueue.h> #include "access.h" +#include "domain.h" #include "limits.h" #include "object.h" #include "ruleset.h"
@@ -307,22 +308,6 @@ int landlock_insert_rule(struct landlock_ruleset *const ruleset,return insert_rule (ruleset, id, &layers,ARRAY_SIZE (layers)); } -static void get_hierarchy (struct landlock_hierarchy *const hierarchy) -{ -if (hierarchy) -refcount_inc (&hierarchy->usage); -} - -static void put_hierarchy (struct landlock_hierarchy *hierarchy) -{ -while (hierarchy &&refcount_dec_and_test (&hierarchy->usage)) { -const struct landlock_hierarchy *const freeme = hierarchy; - - hierarchy = hierarchy->parent; -kfree (freeme); - } -} -static int merge_tree (struct landlock_ruleset *const dst,struct landlock_ruleset *const src,const enum landlock_key_type key_type)
@@ -477,7 +462,7 @@ static int inherit_ruleset(struct landlock_ruleset *const parent, err = -EINVAL ; goto out_unlock; } -get_hierarchy (parent->hierarchy); +landlock_get_hierarchy (parent->hierarchy); child->hierarchy->parent = parent->hierarchy; out_unlock:
@@ -501,7 +486,7 @@ static void free_ruleset(struct landlock_ruleset *const ruleset)free_rule (freeme,LANDLOCK_KEY_NET_PORT );#endif /* IS_ENABLED(CONFIG_INET) */ -put_hierarchy (ruleset->hierarchy); +landlock_put_hierarchy (ruleset->hierarchy);kfree (ruleset); }
security/landlock/ruleset.h +1 -16
@@ -17,6 +17,7 @@#include <linux/workqueue.h> #include "access.h" +#include "domain.h" #include "limits.h" #include "object.h"
@@ -108,22 +109,6 @@ struct landlock_rule { struct landlock_layer layers[] __counted_by(num_layers); }; -/** -* struct landlock_hierarchy - Node in a ruleset hierarchy -*/ -struct landlock_hierarchy { -/** -* @parent: Pointer to the parent node, or NULL if it is a root -* Landlock domain. -*/ -struct landlock_hierarchy *parent; -/** -* @usage: Number of potential children domains plus their parent -* domain. -*/ -refcount_t usage; -}; -/** * struct landlock_ruleset - Landlock ruleset *
security/landlock/task.c +1 -0
@@ -18,6 +18,7 @@#include "common.h" #include "cred.h" +#include "domain.h" #include "fs.h" #include "ruleset.h" #include "setup.h"
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 4/26 landlock: Prepare to use credential instead of domain for filesystem
In reply to Mickaël SalaünThis cosmetic change is needed for audit support, specifically to be able to filter according to cross-execution boundaries.
Add landlock_get_applicable_subject(), mainly a copy of landlock_get_applicable_domain(), which will fully replace it in a following commit.
Optimize current_check_access_path() to only handle the access request.
Partially replace get_current_fs_domain() with explicit calls to landlock_get_applicable_subject(). The remaining ones will follow with more changes.
Remove explicit domain->num_layers check which is now part of the landlock_get_applicable_subject() call.
---
Changes since v4:
- New patch to avoid duplicated computation of the layer level that denied an access.
--- security/landlock/cred.h | 50 +++++++++++++++++++++++++++++++ security/landlock/fs.c | 65 +++++++++++++++++++++++----------------- 2 files changed, 88 insertions(+), 27 deletions(-)
security/landlock/cred.h +50 -0
@@ -13,6 +13,7 @@#include <linux/init.h> #include <linux/rcupdate.h> +#include "access.h" #include "ruleset.h" #include "setup.h"
@@ -53,6 +54,55 @@ static inline bool landlocked(const struct task_struct *const task) return has_dom; } +/** +* landlock_get_applicable_subject - Return the subject's Landlock credential +* if its enforced domain applies to (i.e. +* handles) at least one of the access rights +* specified in @masks +* +* @cred: credential +* @masks: access masks +* @handle_layer: returned youngest layer handling a subset of @masks. Not set +* if the function returns NULL. +* +* Returns: landlock_cred(@cred) if any access rights specified in @masks is +* handled, or NULL otherwise. +*/ +static inline const struct landlock_cred_security * +landlock_get_applicable_subject (const struct cred *const cred, +const struct access_masks masks, +size_t *const handle_layer) +{ +const union access_masks_all masks_all = { + .masks = masks, + }; +const struct landlock_ruleset *domain; +ssize_t layer_level; + +if (!cred) +return NULL ; + + domain =landlock_cred (cred)->domain; +if (!domain) +return NULL ; + +for (layer_level = domain->num_layers -1 ; layer_level >=0 ; + layer_level--) { +union access_masks_all layer = { + .masks = domain->access_masks[layer_level], + }; + +if (layer.all & masks_all.all) { +if (handle_layer) + *handle_layer = layer_level; + +return landlock_cred (cred); + } + } + +return NULL ; +} +__init void landlock_add_cred_hooks (void );#endif /* _SECURITY_LANDLOCK_CRED_H */
security/landlock/fs.c +38 -27
131 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 5/26 landlock: Prepare to use credential instead of domain for network
In reply to Mickaël SalaünThis cosmetic change that is needed for audit support, specifically to be able to filter according to cross-execution boundaries.
Optimize current_check_access_socket() to only handle the access request.
Remove explicit domain->num_layers check which is now part of the landlock_get_applicable_subject() call.
---
Changes since v4:
- New patch.
--- security/landlock/net.c | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-)
security/landlock/net.c +10 -13
@@ -39,10 +39,6 @@ int landlock_append_net_rule(struct landlock_ruleset *const ruleset,return err; } -static const struct access_masks any_net = { - .net = ~0 , -}; - static int current_check_access_socket(struct socket *const sock, struct sockaddr *const address, const int addrlen,
@@ -54,14 +50,14 @@ static int current_check_access_socket(struct socket *const sock,struct landlock_id id = { .type =LANDLOCK_KEY_NET_PORT , }; -const struct landlock_ruleset *const dom = -landlock_get_applicable_domain (landlock_get_current_domain (), - any_net); +const struct access_masks masks = { + .net = access_request, + }; +const struct landlock_cred_security *const subject = +landlock_get_applicable_subject (current_cred (), masks,NULL ); -if (!dom) +if (!subject)return 0 ; -if (WARN_ON_ONCE (dom->num_layers <1 )) -return -EACCES ;if (!sk_is_tcp (sock->sk))return 0 ;
@@ -145,9 +141,10 @@ static int current_check_access_socket(struct socket *const sock, id.key.data = (__force uintptr_t )port;BUILD_BUG_ON (sizeof (port) >sizeof (id.key.data)); - rule =landlock_find_rule (dom, id); - access_request =landlock_init_layer_masks ( - dom, access_request, &layer_masks,LANDLOCK_KEY_NET_PORT ); + rule =landlock_find_rule (subject->domain, id); + access_request =landlock_init_layer_masks (subject->domain, + access_request, &layer_masks, +LANDLOCK_KEY_NET_PORT );if (landlock_unmask_layers (rule, access_request, &layer_masks,ARRAY_SIZE (layer_masks)))return 0 ;
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 6/26 landlock: Prepare to use credential instead of domain for scope
In reply to Mickaël SalaünThis cosmetic change that is needed for audit support, specifically to be able to filter according to cross-execution boundaries.
Replace hardcoded LANDLOCK_SCOPE_SIGNAL with the signal_scope.scope variable.
Use scoped guards for RCU read-side critical sections.
---
Changes since v4:
- New patch.
--- security/landlock/task.c | 50 +++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 24 deletions(-)
security/landlock/task.c +26 -24
@@ -7,6 +7,7 @@*/ #include <asm/current.h> +#include <linux/cleanup.h> #include <linux/cred.h> #include <linux/errno.h> #include <linux/kernel.h>
@@ -213,15 +214,15 @@ static int hook_unix_stream_connect(struct sock *const sock,struct sock *const other, struct sock *const newsk) { - const struct landlock_ruleset *const dom = -landlock_get_applicable_domain (landlock_get_current_domain (), - unix_scope); + const struct landlock_cred_security *const subject = +landlock_get_applicable_subject (current_cred (), unix_scope, +NULL );/* Quick return for non-landlocked tasks. */ -if (!dom) +if (!subject)return 0 ; -if (is_abstract_socket (other) &&sock_is_scoped (other, dom)) +if (is_abstract_socket (other) &&sock_is_scoped (other, subject->domain))return -EPERM ;return 0 ;
@@ -230,11 +231,11 @@ static int hook_unix_stream_connect(struct sock *const sock,static int hook_unix_may_send (struct socket *const sock,struct socket *const other) { -const struct landlock_ruleset *const dom = -landlock_get_applicable_domain (landlock_get_current_domain (), - unix_scope); +const struct landlock_cred_security *const subject = +landlock_get_applicable_subject (current_cred (), unix_scope, +NULL ); -if (!dom) +if (!subject)return 0 ;/*
@@ -244,7 +245,8 @@ static int hook_unix_may_send(struct socket *const sock,if (unix_peer (sock->sk) == other->sk)return 0 ; -if (is_abstract_socket (other->sk) &&sock_is_scoped (other->sk, dom)) +if (is_abstract_socket (other->sk) && +sock_is_scoped (other->sk, subject->domain))return -EPERM ;return 0 ;
@@ -256,27 +258,27 @@ static const struct access_masks signal_scope = {static int hook_task_kill (struct task_struct *const p,struct kernel_siginfo *const info,const int sig, -const struct cred *const cred) +const struct cred *cred) {bool is_scoped; -const struct landlock_ruleset *dom; +const struct landlock_cred_security *subject; -if (cred) { -/* Dealing with USB IO. */ - dom =landlock_cred (cred)->domain; - }else { - dom =landlock_get_current_domain (); - } - dom =landlock_get_applicable_domain (dom, signal_scope); +if (!cred) +/* Not dealing with USB IO. */ + cred =current_cred (); + + subject =landlock_get_applicable_subject (cred, signal_scope,NULL );/* Quick return for non-landlocked tasks. */ -if (!dom) +if (!subject)return 0 ; -rcu_read_lock (); - is_scoped =domain_is_scoped (dom,landlock_get_task_domain (p), -LANDLOCK_SCOPE_SIGNAL ); -rcu_read_unlock (); +scoped_guard (rcu) + { + is_scoped =domain_is_scoped (subject->domain, +landlock_get_task_domain (p), + signal_scope.scope); + }if (is_scoped)return -EPERM ;
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 7/26 landlock: Prepare to use credential instead of domain for fowner
In reply to Mickaël SalaünThis cosmetic change that is needed for audit support, specifically to be able to filter according to cross-execution boundaries.
struct landlock_file_security's size stay the same for now but it will increase with struct landlock_cred_security's size.
Only save Landlock domain in hook_file_set_fowner() if the current domain has LANDLOCK_SCOPE_SIGNAL, which was previously done for each hook_file_send_sigiotask() calls. This should improve a bit performances.
Replace hardcoded LANDLOCK_SCOPE_SIGNAL with the signal_scope.scope variable.
Use scoped guards for RCU read-side critical sections.
---
Changes since v5:
- Only call landlock_get_ruleset() when needed in
hook_file_set_fowner().
Changes since v4:
- New patch.
--- security/landlock/fs.c | 26 ++++++++++++++++++++------ security/landlock/fs.h | 12 +++++++----- security/landlock/task.c | 25 ++++++++++++++++--------- 3 files changed, 43 insertions(+), 20 deletions(-)
security/landlock/fs.c +20 -6
@@ -1641,17 +1641,31 @@ static int hook_file_ioctl_compat(struct file *file, unsigned int cmd,static void hook_file_set_fowner (struct file *file) { -struct landlock_ruleset *new_dom, *prev_dom; +static const struct access_masks signal_scope = { + .scope =LANDLOCK_SCOPE_SIGNAL , + }; +const struct landlock_cred_security *new_subject; +struct landlock_cred_security *fown_subject; +struct landlock_ruleset *prev_dom;/* * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix * file_set_fowner LSM hook inconsistencies"). */ lockdep_assert_held (&file_f_owner (file)->lock); - new_dom =landlock_get_current_domain (); -landlock_get_ruleset (new_dom); - prev_dom =landlock_file (file)->fown_domain; -landlock_file (file)->fown_domain = new_dom; + + fown_subject = &landlock_file (file)->fown_subject; + prev_dom = fown_subject->domain; + new_subject =landlock_get_applicable_subject (current_cred (), + signal_scope,NULL ); +if (new_subject) { +landlock_get_ruleset (new_subject->domain); + *fown_subject = *new_subject; + }else { +static const struct landlock_cred_security empty = {}; + + *fown_subject = empty; + }/* Called in an RCU read-side critical section. */ landlock_put_ruleset_deferred (prev_dom);
@@ -1659,7 +1673,7 @@ static void hook_file_set_fowner(struct file *file)static void hook_file_free_security (struct file *file) { -landlock_put_ruleset_deferred (landlock_file (file)->fown_domain); +landlock_put_ruleset_deferred (landlock_file (file)->fown_subject.domain); }static struct security_hook_list landlock_hooks[]__ro_after_init = {
security/landlock/fs.h +7 -5
@@ -14,6 +14,7 @@#include <linux/rcupdate.h> #include "access.h" +#include "cred.h" #include "ruleset.h" #include "setup.h"
@@ -54,12 +55,13 @@ struct landlock_file_security {*/ access_mask_t allowed_access;/** -* @fown_domain: Domain of the task that set the PID that may receive a -* signal e.g., SIGURG when writing MSG_OOB to the related socket. -* This pointer is protected by the related file->f_owner->lock, as for -* fown_struct's members: pid, uid, and euid. +* @fown_subject: Landlock credential of the task that set the PID that +* may receive a signal e.g., SIGURG when writing MSG_OOB to the +* related socket. This pointer is protected by the related +* file->f_owner->lock, as for fown_struct's members: pid, uid, and +* euid. */ -struct landlock_ruleset *fown_domain; +struct landlock_cred_security fown_subject; };/**
security/landlock/task.c +16 -9
@@ -288,22 +288,29 @@ static int hook_task_kill(struct task_struct *const p,static int hook_file_send_sigiotask (struct task_struct *tsk,struct fown_struct *fown,int signum) { -const struct landlock_ruleset *dom; +const struct landlock_cred_security *subject;bool is_scoped = false;/* Lock already held by send_sigio() and send_sigurg(). */ lockdep_assert_held (&fown->lock); - dom =landlock_get_applicable_domain ( -landlock_file (fown->file)->fown_domain, signal_scope); + subject = &landlock_file (fown->file)->fown_subject; -/* Quick return for unowned socket. */ -if (!dom) +/* +* Quick return for unowned socket. +* +* subject->domain has already been filtered when saved by +* hook_file_set_fowner(), so there is no need to call +* landlock_get_applicable_subject() here. +*/ +if (!subject->domain)return 0 ; -rcu_read_lock (); - is_scoped =domain_is_scoped (dom,landlock_get_task_domain (tsk), -LANDLOCK_SCOPE_SIGNAL ); -rcu_read_unlock (); +scoped_guard (rcu) + { + is_scoped =domain_is_scoped (subject->domain, +landlock_get_task_domain (tsk), + signal_scope.scope); + }if (is_scoped)return -EPERM ;
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 8/26 landlock: Identify domain execution crossing
In reply to Mickaël SalaünExtend struct landlock_cred_security with a domain_exec bitmask to identify which Landlock domain were created by the current task's bprm. This is reset on each execve(2) call.
---
Changes since v5:
- Add documentation and pack struct landlock_cred_security to minimize struct landlock_file_security.
Changes since v4:
- New patch.
--- security/landlock/cred.c | 26 ++++++++++++++++++++++---- security/landlock/cred.h | 32 +++++++++++++++++++++++++++++++- security/landlock/syscalls.c | 5 +++++ 3 files changed, 58 insertions(+), 5 deletions(-)
security/landlock/cred.c +22 -4
@@ -4,8 +4,10 @@* * Copyright © 2017-2020 Mickaël Salaün <[email protected]> * Copyright © 2018-2020 ANSSI +* Copyright © 2025 Microsoft Corporation */ +#include <linux/binfmts.h> #include <linux/cred.h> #include <linux/lsm_hooks.h>
@@ -17,11 +19,12 @@static void hook_cred_transfer (struct cred *const new,const struct cred *const old) { -struct landlock_ruleset *const old_dom =landlock_cred (old)->domain; +const struct landlock_cred_security *const old_llcred = +landlock_cred (old); -if (old_dom) { -landlock_get_ruleset (old_dom); -landlock_cred (new)->domain = old_dom; +if (old_llcred->domain) { +landlock_get_ruleset (old_llcred->domain); + *landlock_cred (new) = *old_llcred; } }
@@ -40,10 +43,25 @@ static void hook_cred_free(struct cred *const cred)landlock_put_ruleset_deferred (dom); } +#ifdef CONFIG_AUDIT + +static int hook_bprm_creds_for_exec (struct linux_binprm *const bprm) +{ +/* Resets for each execution. */ +landlock_cred (bprm->cred)->domain_exec =0 ; +return 0 ; +} + +#endif /* CONFIG_AUDIT */ +static struct security_hook_list landlock_hooks[]__ro_after_init = {LSM_HOOK_INIT (cred_prepare, hook_cred_prepare),LSM_HOOK_INIT (cred_transfer, hook_cred_transfer),LSM_HOOK_INIT (cred_free, hook_cred_free), + +#ifdef CONFIG_AUDIT +LSM_HOOK_INIT (bprm_creds_for_exec, hook_bprm_creds_for_exec), +#endif /* CONFIG_AUDIT */ };__init void landlock_add_cred_hooks (void )
security/landlock/cred.h +31 -1
@@ -9,17 +9,47 @@#ifndef _SECURITY_LANDLOCK_CRED_H#define _SECURITY_LANDLOCK_CRED_H +#include <linux/container_of.h> #include <linux/cred.h> #include <linux/init.h> #include <linux/rcupdate.h> #include "access.h" +#include "limits.h" #include "ruleset.h" #include "setup.h" +/** +* struct landlock_cred_security - Credential security blob +* +* This structure is packed to minimize the size of struct +* landlock_file_security. However, it is always aligned in the LSM cred blob, +* see lsm_set_blob_size(). +*/ struct landlock_cred_security { +/** +* @domain: Immutable ruleset enforced on a task. +*/ struct landlock_ruleset *domain; -}; + +#ifdef CONFIG_AUDIT +/** +* @domain_exec: Bitmask identifying the domain layers that were enforced by +* the current task's executed file (i.e. no new execve(2) since +* landlock_restrict_self(2)). +*/ +u16 domain_exec; +#endif /* CONFIG_AUDIT */ +} __packed; + +#ifdef CONFIG_AUDIT + +/* Makes sure all layer executions can be stored. */ +static_assert (BITS_PER_TYPE (typeof_member(struct landlock_cred_security , + domain_exec)) >= + LANDLOCK_MAX_NUM_LAYERS); + +#endif /* CONFIG_AUDIT */ static inline struct landlock_cred_security *landlock_cred (const struct cred *cred)
security/landlock/syscalls.c +5 -0
@@ -496,5 +496,10 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,/* Replaces the old (prepared) domain. */ landlock_put_ruleset (new_llcred->domain); new_llcred->domain = new_dom; + +#ifdef CONFIG_AUDIT + new_llcred->domain_exec |=1 << (new_dom->num_layers -1 ); +#endif /* CONFIG_AUDIT */ +return commit_creds (new_cred); }
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 9/26 landlock: Add AUDIT_LANDLOCK_ACCESS and log ptrace denials
In reply to Mickaël SalaünAdd a new AUDIT_LANDLOCK_ACCESS record type dedicated to an access request denied by a Landlock domain. AUDIT_LANDLOCK_ACCESS indicates that something unexpected happened.
For now, only denied access are logged, which means that any AUDIT_LANDLOCK_ACCESS record is always followed by a SYSCALL record with "success=no". However, log parsers should check this syscall property because this is the only sign that a request was denied. Indeed, we could have "success=yes" if Landlock would support a "permissive" mode. We could also add a new field for this mode to AUDIT_LANDLOCK_DOMAIN (see following commit).
By default, the only logged access requests are those coming from the same executed program that enforced the Landlock restriction on itself. In other words, no audit record are created for a task after it called execve(2). This is required to avoid log spam because programs may only be aware of their own restrictions, but not the inherited ones.
Following commits will allow to conditionally generate AUDIT_LANDLOCK_ACCESS records according to dedicated landlock_restrict_self(2)'s flags.
The AUDIT_LANDLOCK_ACCESS message contains:
- the "domain" ID restricting the action on an object,
- the "blockers" that are missing to allow the requested access,
- a set of fields identifying the related object (e.g. task identified with "opid" and "ocomm").
The blockers are implicit restrictions (e.g. ptrace), or explicit access rights (e.g. filesystem), or explicit scopes (e.g. signal). This field contains a list of at least one element, each separated with a comma.
The initial blocker is "ptrace", which describe all implicit Landlock restrictions related to ptrace (e.g. deny tracing of tasks outside a sandbox).
Add audit support to ptrace_access_check and ptrace_traceme hooks. For the ptrace_access_check case, we log the current/parent domain and the child task. For the ptrace_traceme case, we log the parent domain and the parent task. Indeed, the requester is the current task, but the action would be performed by the parent task.
Audit event sample:
type=LANDLOCK_ACCESS msg=audit(1729738800.349:44): domain=195ba459b blockers=ptrace opid=1 ocomm="systemd" type=SYSCALL msg=audit(1729738800.349:44): arch=c000003e syscall=101 success=no [...] pid=300 auid=0
A following commit adds user documentation.
Add KUnit tests to check reading of domain ID relative to layer level.
The quick return for non-landlocked tasks is moved from task_ptrace() to each LSM hooks.
Because the landlock_log_denial() function is only called when an access is denied, the compiler should be able to optimize the struct landlock_request initializations. It is not useful to inline the audit_enabled check because other computation are performed anyway, and by the same landlock_log_denia() code.
Use scoped guards for RCU read-side critical sections.
---
Changes since v5:
- Add Acked-by Paul.
- Move request declarations in the landlock_log_denial() calls to not impact allowed requests with audit, and return as soon as possible when access is allowed.
- Remove the audit_context() check in landlock_log_denial() because the context may not already exist. This issue was identified thanks to a new test.
- Remove unlikely().
Changes since v4:
- Rename AUDIT_LANDLOCK_DENY to AUDIT_LANDLOCK_ACCESS, requested by Paul.
- Make landlock_log_denial() get Landlock credential instead of Landlock domain to be able to filter on the domain_exe variable.
- Rebase on top of the migration from struct landlock_ruleset to struct landlock_cred_security.
- Rename landlock_init_current_hierarchy() to landlock_init_hierarchy_log().
- Rebase on top of the scoped guard patches.
- By default, do not log denials after an execution.
- Use scoped guards for RCU read-side critical sections.
Changes since v3:
- Extend commit message.
Changes since v2:
- Log domain IDs as hexadecimal number: this is a more compact notation (i.e. at least one less digit), it improves alignment in logs, and it makes most IDs start with 1 as leading digit (because of the 2^32 minimal value). Do not use the "0x" prefix that would add useless data to logs.
- Constify function arguments.
- Clean up Makefile entries.
Changes since v1:
- Move most audit code to this patch.
- Rebase on the TCP patch series.
- Don't log missing access right: simplify and make it generic for rule types.
- Don't log errno and then don't wrap the error with landlock_log_request(), as suggested by Jeff.
- Add a WARN_ON_ONCE() check to never dereference null pointers.
- Only log when audit is enabled.
- Don't log task's PID/TID with log_task() because it would be redundant with the SYSCALL record.
- Move the "op" in front and rename "domain" to "denying_domain" to make it more consistent with other entries.
- Don't update the request with the domain ID but add an helper to get it from the layer masks (and in a following commit with a struct file).
- Revamp get_domain_id_from_layer_masks() into get_level_from_layer_masks().
- For ptrace_traceme, log the parent domain instead of the current one.
- Add documentation.
- Rename AUDIT_LANDLOCK_DENIAL to AUDIT_LANDLOCK_DENY.
- Only log the domain ID and the target task.
- Log "blockers", which are either implicit restrictions (e.g. ptrace) or explicit access rights (e.g. filesystem), or scopes (e.g. signal).
- Don't log LSM hook names/operations.
- Pick an audit event ID folling the IPE ones.
- Add KUnit tests.
--- include/uapi/linux/audit.h | 3 +- security/landlock/Makefile | 5 +- security/landlock/audit.c | 146 ++++++++++++++++++++++++++++++++++++ security/landlock/audit.h | 53 +++++++++++++ security/landlock/domain.c | 28 +++++++ security/landlock/domain.h | 22 ++++++ security/landlock/ruleset.c | 6 ++ security/landlock/task.c | 96 ++++++++++++++++++------ 8 files changed, 334 insertions(+), 25 deletions(-) create mode 100644 security/landlock/audit.c create mode 100644 security/landlock/audit.h create mode 100644 security/landlock/domain.c
include/uapi/linux/audit.h +2 -1
@@ -33,7 +33,7 @@* 1100 - 1199 user space trusted application messages * 1200 - 1299 messages internal to the audit daemon * 1300 - 1399 audit event messages -* 1400 - 1499 SE Linux use +* 1400 - 1499 access control messages * 1500 - 1599 kernel LSPP events * 1600 - 1699 kernel crypto events * 1700 - 1799 kernel anomaly records
@@ -146,6 +146,7 @@#define AUDIT_IPE_ACCESS 1420/* IPE denial or grant */ #define AUDIT_IPE_CONFIG_CHANGE 1421/* IPE config change */ #define AUDIT_IPE_POLICY_LOAD 1422/* IPE policy load */ +#define AUDIT_LANDLOCK_ACCESS 1423/* Landlock denial */ #define AUDIT_FIRST_KERN_ANOM_MSG 1700#define AUDIT_LAST_KERN_ANOM_MSG 1799
security/landlock/Makefile +4 -1
@@ -5,4 +5,7 @@ landlock-y := setup.o syscalls.o object.o ruleset.o \ landlock-$(CONFIG_INET) += net.o -landlock-$(CONFIG_AUDIT) += id.o +landlock-$(CONFIG_AUDIT) += \ + id.o \ + audit.o \ + domain.o
security/landlock/audit.c new file +146 -0
146 lines not on this page · raw message
security/landlock/audit.h new file +53 -0
53 lines not on this page · raw message
security/landlock/domain.c new file +28 -0
@@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* +* Landlock LSM - Domain management +* +* Copyright © 2016-2020 Mickaël Salaün <[email protected]> +* Copyright © 2018-2020 ANSSI +* Copyright © 2024-2025 Microsoft Corporation +*/ + +#include "domain.h" +#include "id.h" + +#ifdef CONFIG_AUDIT + +/** +* landlock_init_hierarchy_log - Partially initialize landlock_hierarchy +* +* @hierarchy: The hierarchy to initialize. +* +* @hierarchy->parent and @hierarchy->usage should already be set. +*/ +int landlock_init_hierarchy_log (struct landlock_hierarchy *const hierarchy) +{ + hierarchy->id =landlock_get_id_range (1 ); +return 0 ; +} + +#endif /* CONFIG_AUDIT */
security/landlock/domain.h +22 -0
@@ -4,6 +4,7 @@* * Copyright © 2016-2020 Mickaël Salaün <[email protected]> * Copyright © 2018-2020 ANSSI +* Copyright © 2024-2025 Microsoft Corporation */ #ifndef _SECURITY_LANDLOCK_DOMAIN_H
@@ -26,6 +27,13 @@ struct landlock_hierarchy {* domain. */ refcount_t usage; + +#ifdef CONFIG_AUDIT +/** +* @id: Landlock domain ID, sets once at domain creation time. +*/ +u64 id; +#endif /* CONFIG_AUDIT */ }; static inline void
@@ -45,4 +53,18 @@ static inline void landlock_put_hierarchy(struct landlock_hierarchy *hierarchy) } } +#ifdef CONFIG_AUDIT + +int landlock_init_hierarchy_log (struct landlock_hierarchy *const hierarchy); + +#else /* CONFIG_AUDIT */ + +static inline int +landlock_init_hierarchy_log (struct landlock_hierarchy *const hierarchy) +{ +return 0 ; +} + +#endif /* CONFIG_AUDIT */ +#endif /* _SECURITY_LANDLOCK_DOMAIN_H */
security/landlock/ruleset.c +6 -0
@@ -23,6 +23,7 @@#include <linux/workqueue.h> #include "access.h" +#include "audit.h" #include "domain.h" #include "limits.h" #include "object.h"
@@ -505,6 +506,7 @@ static void free_ruleset_work(struct work_struct *const work)free_ruleset (ruleset); } +/* Only called by hook_cred_free(). */ void landlock_put_ruleset_deferred (struct landlock_ruleset *const ruleset) {if (ruleset &&refcount_dec_and_test (&ruleset->usage)) {
@@ -564,6 +566,10 @@ landlock_merge_ruleset(struct landlock_ruleset *const parent,if (err)return ERR_PTR (err); + err =landlock_init_hierarchy_log (new_dom->hierarchy); +if (err) +return ERR_PTR (err); +return no_free_ptr (new_dom); }
security/landlock/task.c +73 -23
147 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 10/26 landlock: Add AUDIT_LANDLOCK_DOMAIN and log domain status
In reply to Mickaël SalaünAsynchronously log domain information when it first denies an access. This minimize the amount of generated logs, which makes it possible to always log denials for the current execution since they should not happen. These records are identified with the new AUDIT_LANDLOCK_DOMAIN type.
The AUDIT_LANDLOCK_DOMAIN message contains:
- the "domain" ID which is described;
- the "status" which can either be "allocated" or "deallocated";
- the "mode" which is for now only "enforcing";
- for the "allocated" status, a minimal set of properties to easily identify the task that loaded the domain's policy with landlock_restrict_self(2): "pid", "uid", executable path ("exe"), and command line ("comm");
- for the "deallocated" state, the number of "denials" accounted to this domain, which is at least 1.
This requires each domain to save these task properties at creation time in the new struct landlock_details. A reference to the PID is kept for the lifetime of the domain to avoid race conditions when investigating the related task. The executable path is resolved and stored to not keep a reference to the filesystem and block related actions. All these metadata are stored for the lifetime of the related domain and should then be minimal. The required memory is not accounted to the task calling landlock_restrict_self(2) contrary to most other Landlock allocations (see related comment).
The AUDIT_LANDLOCK_DOMAIN record follows the first AUDIT_LANDLOCK_ACCESS record for the same domain, which is always followed by AUDIT_SYSCALL and AUDIT_PROCTITLE. This is in line with the audit logic to first record the cause of an event, and then add context with other types of record.
Audit event sample for a first denial:
type=LANDLOCK_ACCESS msg=audit(1732186800.349:44): domain=195ba459b blockers=ptrace opid=1 ocomm="systemd"
type=LANDLOCK_DOMAIN msg=audit(1732186800.349:44): domain=195ba459b status=allocated mode=enforcing pid=300 uid=0 exe="/root/sandboxer" comm="sandboxer" type=SYSCALL msg=audit(1732186800.349:44): arch=c000003e syscall=101 success=no [...] pid=300 auid=0
Audit event sample for a following denial:
type=LANDLOCK_ACCESS msg=audit(1732186800.372:45): domain=195ba459b blockers=ptrace opid=1 ocomm="systemd" type=SYSCALL msg=audit(1732186800.372:45): arch=c000003e syscall=101 success=no [...] pid=300 auid=0
Log domain deletion with the "deallocated" state when a domain was previously logged. This makes it possible for log parsers to free potential resources when a domain ID will never show again.
The number of denied access requests is useful to easily check how many access requests a domain blocked and potentially if some of them are missing in logs because of audit rate limiting or audit rules. Rate limiting could also drop this record though.
Audit event sample for a deletion of a domain that denied something:
type=LANDLOCK_DOMAIN msg=audit(1732186800.393:46): domain=195ba459b status=deallocated denials=2
---
Changes since v5:
- Add Acked-by Paul.
- Improve comment.
- Cosmetic code move in landlock_log_denial() for consistency, and to get a cleaner diff regarding the non-changing audit_enabled check.
- Remove unlikely().
Changes since v4:
- Rename AUDIT_LANDLOCK_DOM_{INFO,DROP} to AUDIT_LANDLOCK_DOMAIN and add a "status" field, as requested by Paul.
- Add a harcoded "mode=enforcing" to leave room for a potential future permissive mode, as suggested by Paul.
- Remove the "creation" timestamp, as suggested by Paul.
- Move LANDLOCK_PATH_MAX_SIZE to domain.h, check the size of the greatest landlock_details at build time, and improve comments.
- Improve audit check in landlock_log_drop_domain().
- Add missing headers.
- Fix typo in comment.
- Rebase on top of the landlock_log_denial() and subject type changes.
Changes since v3:
- Log number of denied access requests with AUDIT_LANDLOCK_DOM_DROP records, suggested by Tyler.
- Do not store a struct path pointer but the resolved string instead. This enables us to not block unmount of the initially restricted task executable's mount point. See the new get_current_info() and get_current_exe(). A following patch add tests for this case.
- Create and allocate a new struct landlock_details for initially restricted task's information.
- Remove audit_get_ctime() call, as requested by Paul. We now always have a standalone timestamp per Landlock domain creations.
- Fix docstring.
Changes since v2:
- Fix docstring.
- Fix log_status check in log_hierarchy() to also log LANDLOCK_LOG_DISABLED.
- Add audit's creation time to domain's properties.
- Use hexadecimal notation for domain IDs.
- Remove domain's parent records: parent domains are not really useful in the logs. They will be available with the upcoming introspection feature though.
- Extend commit message with audit's timestamp explanation.
Changes since v1:
- Add a ruleset's version for atomic logs.
- Rebased on the TCP patch series.
- Rename operation using "_" instead of "-".
- Rename AUDIT_LANDLOCK to AUDIT_LANDLOCK_RULESET.
- Only log when audit is enabled, but always set domain IDs.
- Don't log task's PID/TID with log_task() because it would be redundant with the SYSCALL record.
- Remove race condition when logging ruleset creation and logging ruleset modification while the related file descriptor was already registered but the ruleset creation not logged yet.
- Fix domain drop logs.
- Move the domain drop record from the previous patch into this one.
- Do not log domain creation but log first domain use instead.
- Save task's properties that sandbox themselves.
--- include/uapi/linux/audit.h | 1 + security/landlock/audit.c | 90 ++++++++++++++++++++++++++++++-- security/landlock/audit.h | 7 +++ security/landlock/domain.c | 101 ++++++++++++++++++++++++++++++++++++ security/landlock/domain.h | 68 ++++++++++++++++++++++++ security/landlock/ruleset.c | 6 +++ 6 files changed, 270 insertions(+), 3 deletions(-)
include/uapi/linux/audit.h +1 -0
@@ -147,6 +147,7 @@#define AUDIT_IPE_CONFIG_CHANGE 1421/* IPE config change */ #define AUDIT_IPE_POLICY_LOAD 1422/* IPE policy load */ #define AUDIT_LANDLOCK_ACCESS 1423/* Landlock denial */ +#define AUDIT_LANDLOCK_DOMAIN 1424/* Landlock domain status */ #define AUDIT_FIRST_KERN_ANOM_MSG 1700#define AUDIT_LAST_KERN_ANOM_MSG 1799
security/landlock/audit.c +87 -3
117 lines not on this page · raw message
security/landlock/audit.h +7 -0
@@ -37,11 +37,18 @@ struct landlock_request {#ifdef CONFIG_AUDIT +void landlock_log_drop_domain (const struct landlock_ruleset *const domain); +void landlock_log_denial (const struct landlock_cred_security *const subject,const struct landlock_request *const request);#else /* CONFIG_AUDIT */ +static inline void +landlock_log_drop_domain (const struct landlock_ruleset *const domain) +{ +} +static inline void landlock_log_denial (const struct landlock_cred_security *const subject,const struct landlock_request *const request)
security/landlock/domain.c +101 -0
122 lines not on this page · raw message
security/landlock/domain.h +68 -0
86 lines not on this page · raw message
security/landlock/ruleset.c +6 -0
@@ -510,6 +510,9 @@ static void free_ruleset_work(struct work_struct *const work)void landlock_put_ruleset_deferred (struct landlock_ruleset *const ruleset) {if (ruleset &&refcount_dec_and_test (&ruleset->usage)) { +/* Logs with the current context. */ +landlock_log_drop_domain (ruleset); +INIT_WORK (&ruleset->work_free, free_ruleset_work);schedule_work (&ruleset->work_free); }
@@ -521,6 +524,9 @@ void landlock_put_ruleset_deferred(struct landlock_ruleset *const ruleset)* @parent: Parent domain. * @ruleset: New ruleset to be merged. * +* The current task is requesting to be restricted. The subjective credentials +* must not be in an overridden state. cf. landlock_init_hierarchy_log(). +* * Returns the intersection of @parent and @ruleset, or returns @parent if * @ruleset is empty, or returns a duplicate of @ruleset if @parent is empty. */
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 11/26 landlock: Log mount-related denials
In reply to Mickaël SalaünAdd audit support for sb_mount, move_mount, sb_umount, sb_remount, and sb_pivot_root hooks.
The new related blocker is "fs.change_layout".
Audit event sample:
type=LANDLOCK_DENY msg=audit(1729738800.349:44): domain=195ba459b blockers=fs.change_layout name="/" dev="tmpfs" ino=1
Remove landlock_get_applicable_domain() and get_current_fs_domain() which are now fully replaced with landlock_get_applicable_subject().
---
Changes since v5:
- Move request declaration in the landlock_log_denial() calls.
Changes since v4:
- Rebase on top of the landlock_log_denial() and subject type changes.
- Fix off-by-one error in landlock_match_layer_level(), now merged into landlock_get_applicable_domain().
Changes since v3:
- Cosmetic change to the "fs.change_layout" name.
Changes since v2:
- Log the domain that denied the action because not all layers block FS layout changes.
- Fix landlock_match_layer_level().
Changes since v1:
- Rebased on the TCP patch series.
- Don't log missing permissions, only domain layer, and then remove the permission word (suggested by Günther)
--- security/landlock/audit.c | 3 ++ security/landlock/audit.h | 1 + security/landlock/fs.c | 81 ++++++++++++++++++++++++++++++++----- security/landlock/ruleset.h | 30 -------------- 4 files changed, 74 insertions(+), 41 deletions(-)
security/landlock/audit.c +3 -0
@@ -21,6 +21,9 @@ static const char *get_blocker(const enum landlock_request_type type)switch (type) {case LANDLOCK_REQUEST_PTRACE :return "ptrace" ; + +case LANDLOCK_REQUEST_FS_CHANGE_LAYOUT : +return "fs.change_layout" ; }WARN_ON_ONCE (1 );
security/landlock/audit.h +1 -0
@@ -16,6 +16,7 @@enum landlock_request_type {LANDLOCK_REQUEST_PTRACE =1 , +LANDLOCK_REQUEST_FS_CHANGE_LAYOUT , };/*
security/landlock/fs.c +70 -11
139 lines not on this page · raw message
security/landlock/ruleset.h +0 -30
@@ -242,36 +242,6 @@ landlock_union_access_masks(const struct landlock_ruleset *const domain)return matches.masks; } -/** -* landlock_get_applicable_domain - Return @domain if it applies to (handles) -* at least one of the access rights specified -* in @masks -* -* @domain: Landlock ruleset (used as a domain) -* @masks: access masks -* -* Returns: @domain if any access rights specified in @masks is handled, or -* NULL otherwise. -*/ -static inline const struct landlock_ruleset * -landlock_get_applicable_domain (const struct landlock_ruleset *const domain, -const struct access_masks masks) -{ -const union access_masks_all masks_all = { - .masks = masks, - }; -union access_masks_all merge = {}; - -if (!domain) -return NULL ; - - merge.masks =landlock_union_access_masks (domain); -if (merge.all & masks_all.all) -return domain; - -return NULL ; -} - static inline void landlock_add_fs_access_mask(struct landlock_ruleset *const ruleset, const access_mask_t fs_access_mask,
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 12/26 landlock: Log file-related denials
In reply to Mickaël SalaünAdd audit support for path_mkdir, path_mknod, path_symlink, path_unlink, path_rmdir, path_truncate, path_link, path_rename, and file_open hooks.
The dedicated blockers are:
- fs.execute
- fs.write_file
- fs.read_file
- fs.read_dir
- fs.remove_dir
- fs.remove_file
- fs.make_char
- fs.make_dir
- fs.make_reg
- fs.make_sock
- fs.make_fifo
- fs.make_block
- fs.make_sym
- fs.refer
- fs.truncate
- fs.ioctl_dev
Audit event sample for a denied link action:
type=LANDLOCK_DENY msg=audit(1729738800.349:44): domain=195ba459b blockers=fs.refer path="/usr/bin" dev="vda2" ino=351 type=LANDLOCK_DENY msg=audit(1729738800.349:44): domain=195ba459b blockers=fs.make_reg,fs.refer path="/usr/local" dev="vda2" ino=365
We could pack blocker names (e.g. "fs:make_reg,refer") but that would increase complexity for the kernel and log parsers. Moreover, this could not handle blockers of different classes (e.g. fs and net). Make it simple and flexible instead.
Add KUnit tests to check the identification from a layer_mask_t array of the first layer level denying such request.
Cc: Günther Noack <[email protected]>
Depends-on: 058518c20920 ("landlock: Align partial refer access checks with final ones")
Depends-on: d617f0d72d80 ("landlock: Optimize file path walks and prepare for audit support")
---
Changes since v5:
- Fix log_request_* update typo in is_access_to_paths_allowed().
Changes since v4:
- Rebase on top of the landlock_log_denial() and subject type changes.
- Add Depends-on tags.
Changes since v3:
- Rename blockers from fs_* to fs.*
- Extend commit message.
Changes since v2:
- Replace integer with bool in log_blockers().
- Always initialize youngest_layer, spotted by Francis Laniel.
- Fix incorrect log reason by using access_masked_parent1 instead of access_request_parent1 (thanks to the previous fix patches).
- Clean up formatting.
Changes since v1:
- Move audit code to the ptrace patch.
- Revamp logging and support the path_link and path_rename hooks.
- Add KUnit tests.
--- security/landlock/audit.c | 178 ++++++++++++++++++++++++++++++++++++-- security/landlock/audit.h | 9 ++ security/landlock/fs.c | 62 +++++++++++-- 3 files changed, 233 insertions(+), 16 deletions(-)
security/landlock/audit.c +171 -7
@@ -7,23 +7,56 @@#include <kunit/test.h> #include <linux/audit.h> +#include <linux/bitops.h> #include <linux/lsm_audit.h> #include <linux/pid.h> #include <linux/uidgid.h> +#include <uapi/linux/landlock.h> #include "audit.h" +#include "common.h" #include "cred.h" #include "domain.h" #include "ruleset.h" -static const char *get_blocker (const enum landlock_request_type type) +static const char *const fs_access_strings[] = { + [BIT_INDEX (LANDLOCK_ACCESS_FS_EXECUTE )] ="fs.execute" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_WRITE_FILE )] ="fs.write_file" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_READ_FILE )] ="fs.read_file" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_READ_DIR )] ="fs.read_dir" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_REMOVE_DIR )] ="fs.remove_dir" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_REMOVE_FILE )] ="fs.remove_file" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_CHAR )] ="fs.make_char" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_DIR )] ="fs.make_dir" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_REG )] ="fs.make_reg" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_SOCK )] ="fs.make_sock" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_FIFO )] ="fs.make_fifo" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_BLOCK )] ="fs.make_block" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_MAKE_SYM )] ="fs.make_sym" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_REFER )] ="fs.refer" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_TRUNCATE )] ="fs.truncate" , + [BIT_INDEX (LANDLOCK_ACCESS_FS_IOCTL_DEV )] ="fs.ioctl_dev" , +}; + +static_assert (ARRAY_SIZE (fs_access_strings) ==LANDLOCK_NUM_ACCESS_FS ); + +static __attribute_const__ const char * +get_blocker (const enum landlock_request_type type, +const unsigned long access_bit) {switch (type) {case LANDLOCK_REQUEST_PTRACE : +WARN_ON_ONCE (access_bit !=-1 );return "ptrace" ;case LANDLOCK_REQUEST_FS_CHANGE_LAYOUT : +WARN_ON_ONCE (access_bit !=-1 );return "fs.change_layout" ; + +case LANDLOCK_REQUEST_FS_ACCESS : +if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (fs_access_strings))) +return "unknown" ; +return fs_access_strings[access_bit]; }WARN_ON_ONCE (1 );
@@ -31,9 +64,20 @@ static const char *get_blocker(const enum landlock_request_type type) }static void log_blockers (struct audit_buffer *const ab, -const enum landlock_request_type type) +const enum landlock_request_type type, +const access_mask_t access) { -audit_log_format (ab,"%s" ,get_blocker (type)); +const unsigned long access_mask = access; +unsigned long access_bit; +bool is_first = true; + +for_each_set_bit (access_bit, &access_mask,BITS_PER_TYPE (access)) { +audit_log_format (ab,"%s%s" , is_first ?"" :"," , +get_blocker (type, access_bit)); + is_first = false; + } +if (is_first) +audit_log_format (ab,"%s" ,get_blocker (type,-1 )); }static void log_node (struct landlock_hierarchy *const node)
@@ -117,9 +161,110 @@ static void test_get_hierarchy(struct kunit *const test)#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ +static size_t get_denied_layer (const struct landlock_ruleset *const domain, +access_mask_t *const access_request, +const layer_mask_t (*const layer_masks)[], +const size_t layer_masks_size) +{ +const unsigned long access_req = *access_request; +unsigned long access_bit; +access_mask_t missing =0 ; +long youngest_layer =-1 ; + +for_each_set_bit (access_bit, &access_req, layer_masks_size) { +const access_mask_t mask = (*layer_masks)[access_bit]; +long layer; + +if (!mask) +continue ; + +/* __fls(1) == 0 */ + layer =__fls (mask); +if (layer > youngest_layer) { + youngest_layer = layer; + missing =BIT (access_bit); + }else if (layer == youngest_layer) { + missing |=BIT (access_bit); + } + } + + *access_request = missing; +if (youngest_layer ==-1 ) +return domain->num_layers -1 ; + +return youngest_layer; +} + +#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST + +static void test_get_denied_layer (struct kunit *const test) +{ +const struct landlock_ruleset dom = { + .num_layers =5 , + }; +const layer_mask_t layer_masks[LANDLOCK_NUM_ACCESS_FS ] = { + [BIT_INDEX (LANDLOCK_ACCESS_FS_EXECUTE )] =BIT (0 ), + [BIT_INDEX (LANDLOCK_ACCESS_FS_READ_FILE )] =BIT (1 ), + [BIT_INDEX (LANDLOCK_ACCESS_FS_READ_DIR )] =BIT (1 ) |BIT (0 ), + [BIT_INDEX (LANDLOCK_ACCESS_FS_REMOVE_DIR )] =BIT (2 ), + }; +access_mask_t access; + + access =LANDLOCK_ACCESS_FS_EXECUTE ; +KUNIT_EXPECT_EQ (test,0 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access,LANDLOCK_ACCESS_FS_EXECUTE ); + + access =LANDLOCK_ACCESS_FS_READ_FILE ; +KUNIT_EXPECT_EQ (test,1 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access,LANDLOCK_ACCESS_FS_READ_FILE ); + + access =LANDLOCK_ACCESS_FS_READ_DIR ; +KUNIT_EXPECT_EQ (test,1 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access,LANDLOCK_ACCESS_FS_READ_DIR ); + + access =LANDLOCK_ACCESS_FS_READ_FILE |LANDLOCK_ACCESS_FS_READ_DIR ; +KUNIT_EXPECT_EQ (test,1 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access, +LANDLOCK_ACCESS_FS_READ_FILE | +LANDLOCK_ACCESS_FS_READ_DIR ); + + access =LANDLOCK_ACCESS_FS_EXECUTE |LANDLOCK_ACCESS_FS_READ_DIR ; +KUNIT_EXPECT_EQ (test,1 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access,LANDLOCK_ACCESS_FS_READ_DIR ); + + access =LANDLOCK_ACCESS_FS_WRITE_FILE ; +KUNIT_EXPECT_EQ (test,4 , +get_denied_layer (&dom, &access, &layer_masks, +sizeof (layer_masks))); +KUNIT_EXPECT_EQ (test, access,0 ); +} + +#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */ +static bool is_valid_request (const struct landlock_request *const request) { -if (WARN_ON_ONCE (!request->layer_plus_one)) +if (WARN_ON_ONCE (!(!!request->layer_plus_one ^ !!request->access))) +return false; + +if (request->access) { +if (WARN_ON_ONCE (!request->layer_masks)) +return false; + }else { +if (WARN_ON_ONCE (request->layer_masks)) +return false; + } + +if (WARN_ON_ONCE (!!request->layer_masks ^ !!request->layer_masks_size))return false;return true;
@@ -137,6 +282,7 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,struct audit_buffer *ab;struct landlock_hierarchy *youngest_denied;size_t youngest_layer; +access_mask_t missing;if (WARN_ON_ONCE (!subject || !subject->domain || !subject->domain->hierarchy || !request))
@@ -145,8 +291,25 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,if (!is_valid_request (request))return ; - youngest_layer = request->layer_plus_one -1 ; - youngest_denied =get_hierarchy (subject->domain, youngest_layer); + missing = request->access; +if (missing) { +/* Gets the nearest domain that denies the request. */ +if (request->layer_masks) { + youngest_layer =get_denied_layer ( + subject->domain, &missing, request->layer_masks, + request->layer_masks_size); + }else { +/* This will change with the next commit. */ +WARN_ON_ONCE (1 ); + youngest_layer = subject->domain->num_layers; + } + youngest_denied = +get_hierarchy (subject->domain, youngest_layer); + }else { + youngest_layer = request->layer_plus_one -1 ; + youngest_denied = +get_hierarchy (subject->domain, youngest_layer); + }/* * Consistently keeps track of the number of denied access requests
@@ -169,7 +332,7 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,return ;audit_log_format (ab,"domain=%llx blockers=" , youngest_denied->id); -log_blockers (ab, request->type); +log_blockers (ab, request->type, missing);audit_log_lsm_data (ab, &request->audit);audit_log_end (ab);
@@ -219,6 +382,7 @@ void landlock_log_drop_domain(const struct landlock_ruleset *const domain)static struct kunit_case test_cases[] = {/* clang-format off */ KUNIT_CASE (test_get_hierarchy), +KUNIT_CASE (test_get_denied_layer), {}/* clang-format on */ };
security/landlock/audit.h +9 -0
@@ -11,12 +11,14 @@#include <linux/audit.h> #include <linux/lsm_audit.h> +#include "access.h" #include "cred.h" #include "ruleset.h" enum landlock_request_type {LANDLOCK_REQUEST_PTRACE =1 ,LANDLOCK_REQUEST_FS_CHANGE_LAYOUT , +LANDLOCK_REQUEST_FS_ACCESS , };/*
@@ -34,6 +36,13 @@ struct landlock_request {* extra one is useful to detect uninitialized field. */ size_t layer_plus_one; + +/* Required field for configurable access control. */ +access_mask_t access; + +/* Required fields for requests with layer masks. */ +const layer_mask_t (*layer_masks)[]; +size_t layer_masks_size; };#ifdef CONFIG_AUDIT
security/landlock/fs.c +53 -9
141 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 13/26 landlock: Log truncate and IOCTL denials
In reply to Mickaël SalaünAdd audit support to the file_truncate and file_ioctl hooks.
Add a deny_masks_t type and related helpers to store the domain's layer level per optional access rights (i.e. LANDLOCK_ACCESS_FS_TRUNCATE and LANDLOCK_ACCESS_FS_IOCTL_DEV) when opening a file, which cannot be inferred later. In practice, the landlock_file_security aligned blob size is still 16 bytes because this new one-byte deny_masks field follows the existing two-bytes allowed_access field and precede the packed fown_subject.
Implementing deny_masks_t with a bitfield instead of a struct enables a generic implementation to store and extract layer levels.
Add KUnit tests to check the identification of a layer level from a deny_masks_t, and the computation of a deny_masks_t from an access right with its layer level or a layer_mask_t array.
Audit event sample:
type=LANDLOCK_DENY msg=audit(1729738800.349:44): domain=195ba459b blockers=fs.ioctl_dev path="/dev/tty" dev="devtmpfs" ino=9 ioctlcmd=0x5401
---
Changes since v5:
- Switch to LSM_AUDIT_DATA_IOCTL_OP for IOCTL hooks, and update sample accordingly.
- Move request declarations in the landlock_log_denial() calls to not impact allowed requests with audit, and remove update_request() which is now useless.
Changes since v4:
- Rebase on top of the landlock_log_denial() and subject type changes.
Changes since v3:
- Rename get_layer_from_deny_masks().
Changes since v2:
- Fix !CONFIG_AUDIT build warning.
- Rename ACCESS_FS_OPTIONAL to _LANDLOCK_ACCESS_FS_OPTIONAL.
--- security/landlock/access.h | 23 +++++++ security/landlock/audit.c | 102 ++++++++++++++++++++++++++-- security/landlock/audit.h | 4 ++ security/landlock/domain.c | 133 +++++++++++++++++++++++++++++++++++++ security/landlock/domain.h | 8 +++ security/landlock/fs.c | 48 +++++++++++++ security/landlock/fs.h | 9 +++ 7 files changed, 322 insertions(+), 5 deletions(-)
security/landlock/access.h +23 -0
@@ -28,6 +28,12 @@ LANDLOCK_ACCESS_FS_REFER)/* clang-format on */ +/* clang-format off */ +#define _LANDLOCK_ACCESS_FS_OPTIONAL ( \ + LANDLOCK_ACCESS_FS_TRUNCATE | \ + LANDLOCK_ACCESS_FS_IOCTL_DEV) +/* clang-format on */ +typedef u16 access_mask_t ;/* Makes sure all filesystem access rights can be stored. */
@@ -60,6 +66,23 @@ typedef u16 layer_mask_t;/* Makes sure all layers can be checked. */ static_assert (BITS_PER_TYPE (layer_mask_t) >=LANDLOCK_MAX_NUM_LAYERS ); +/* +* Tracks domains responsible of a denied access. This is required to avoid +* storing in each object the full layer_masks[] required by update_request(). +*/ +typedef u8 deny_masks_t ; + +/* +* Makes sure all optional access rights can be tied to a layer index (cf. +* get_deny_mask). +*/ +static_assert (BITS_PER_TYPE (deny_masks_t) >= + (HWEIGHT (LANDLOCK_MAX_NUM_LAYERS -1 ) * +HWEIGHT (_LANDLOCK_ACCESS_FS_OPTIONAL))); + +/* LANDLOCK_MAX_NUM_LAYERS must be a power of two (cf. deny_masks_t assert). */ +static_assert (HWEIGHT (LANDLOCK_MAX_NUM_LAYERS ) ==1 ); +/* Upgrades with all initially denied by default access rights. */ static inline struct access_masks landlock_upgrade_handled_access_masks (struct access_masks access_masks)
security/landlock/audit.c +97 -5
144 lines not on this page · raw message
security/landlock/audit.h +4 -0
@@ -43,6 +43,10 @@ struct landlock_request {/* Required fields for requests with layer masks. */ const layer_mask_t (*layer_masks)[];size_t layer_masks_size; + +/* Required fields for requests with deny masks. */ +const access_mask_t all_existing_optional_access; +deny_masks_t deny_masks; };#ifdef CONFIG_AUDIT
security/landlock/domain.c +133 -0
149 lines not on this page · raw message
security/landlock/domain.h +8 -0
@@ -19,6 +19,8 @@#include <linux/sched.h> #include <linux/slab.h> +#include "access.h" +enum landlock_log_status {LANDLOCK_LOG_PENDING =0 ,LANDLOCK_LOG_RECORDED ,
@@ -125,6 +127,12 @@ static inline void landlock_put_hierarchy(struct landlock_hierarchy *hierarchy)int landlock_init_hierarchy_log (struct landlock_hierarchy *const hierarchy); +deny_masks_t +landlock_get_deny_masks (const access_mask_t all_existing_optional_access, +const access_mask_t optional_access, +const layer_mask_t (*const layer_masks)[], +size_t layer_masks_size); +#else /* CONFIG_AUDIT */ static inline int
security/landlock/fs.c +48 -0
72 lines not on this page · raw message
security/landlock/fs.h +9 -0
@@ -54,6 +54,15 @@ struct landlock_file_security {* needed to authorize later operations on the open file. */ access_mask_t allowed_access; + +#ifdef CONFIG_AUDIT +/** +* @deny_masks: Domain layer levels that deny an optional access (see +* _LANDLOCK_ACCESS_FS_OPTIONAL). +*/ +deny_masks_t deny_masks; +#endif /* CONFIG_AUDIT */ +/** * @fown_subject: Landlock credential of the task that set the PID that * may receive a signal e.g., SIGURG when writing MSG_OOB to the
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 14/26 landlock: Log TCP bind and connect denials
In reply to Mickaël SalaünAdd audit support to socket_bind and socket_connect hooks.
The related blockers are:
- net.bind_tcp
- net.connect_tcp
Audit event sample:
type=LANDLOCK_DENY msg=audit(1729738800.349:44): domain=195ba459b blockers=net.connect_tcp daddr=127.0.0.1 dest=80
---
Changes since v5:
- Move request declaration in the landlock_log_denial() call to not impact allowed requests with audit.
Changes since v4:
- Rebase on top of the landlock_log_denial() and subject type changes.
Changes since v3:
- Rename blockers from net_* to net.*
Changes since v2:
- Remove potentially superfluous IPv6 saddr log, spotted by Francis Laniel.
- Cosmetic improvements.
--- security/landlock/audit.c | 12 +++++++++ security/landlock/audit.h | 1 + security/landlock/net.c | 51 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 60 insertions(+), 4 deletions(-)
security/landlock/audit.c +12 -0
@@ -42,6 +42,13 @@ static const char *const fs_access_strings[] = {static_assert (ARRAY_SIZE (fs_access_strings) ==LANDLOCK_NUM_ACCESS_FS ); +static const char *const net_access_strings[] = { + [BIT_INDEX (LANDLOCK_ACCESS_NET_BIND_TCP )] ="net.bind_tcp" , + [BIT_INDEX (LANDLOCK_ACCESS_NET_CONNECT_TCP )] ="net.connect_tcp" , +}; + +static_assert (ARRAY_SIZE (net_access_strings) ==LANDLOCK_NUM_ACCESS_NET ); + static __attribute_const__ const char *get_blocker (const enum landlock_request_type type,const unsigned long access_bit)
@@ -59,6 +66,11 @@ get_blocker(const enum landlock_request_type type,if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (fs_access_strings)))return "unknown" ;return fs_access_strings[access_bit]; + +case LANDLOCK_REQUEST_NET_ACCESS : +if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (net_access_strings))) +return "unknown" ; +return net_access_strings[access_bit]; }WARN_ON_ONCE (1 );
security/landlock/audit.h +1 -0
@@ -19,6 +19,7 @@ enum landlock_request_type {LANDLOCK_REQUEST_PTRACE =1 ,LANDLOCK_REQUEST_FS_CHANGE_LAYOUT ,LANDLOCK_REQUEST_FS_ACCESS , + LANDLOCK_REQUEST_NET_ACCESS, };/*
security/landlock/net.c +47 -4
87 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 15/26 landlock: Log scoped denials
In reply to Mickaël SalaünAdd audit support for unix_stream_connect, unix_may_send, task_kill, and file_send_sigiotask hooks.
The related blockers are:
- scope.abstract_unix_socket
- scope.signal
Audit event sample for abstract unix socket:
type=LANDLOCK_DENY msg=audit(1729738800.268:30): domain=195ba459b blockers=scope.abstract_unix_socket path=00666F6F
Audit event sample for signal:
type=LANDLOCK_DENY msg=audit(1729738800.291:31): domain=195ba459b blockers=scope.signal opid=1 ocomm="systemd"
Refactor and simplify error handling in LSM hooks.
Extend struct landlock_file_security with fown_layer and use it to log the blocking domain. The struct aligned size is still 16 bytes.
---
Changes since v5:
- Move request declarations in the landlock_log_denial() calls to not impact allowed requests with audit, and return as soon as possible when access is allowed.
- Store a fown_layer per file and use it to log the blocking domain.
- Refactor and simplify error handling in LSM hooks.
Changes since v4:
- Rebase on top of the landlock_log_denial() and subject type changes.
Changes since v3:
- Cosmetic change to the "scope.*" blocker names.
- Extend commit message.
Changes since v1:
- New patch.
--- security/landlock/audit.c | 8 ++++ security/landlock/audit.h | 2 + security/landlock/fs.c | 7 +++- security/landlock/fs.h | 14 +++++++ security/landlock/task.c | 79 +++++++++++++++++++++++++++++++-------- 5 files changed, 92 insertions(+), 18 deletions(-)
security/landlock/audit.c +8 -0
@@ -71,6 +71,14 @@ get_blocker(const enum landlock_request_type type,if (WARN_ON_ONCE (access_bit >=ARRAY_SIZE (net_access_strings)))return "unknown" ;return net_access_strings[access_bit]; + +case LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET : +WARN_ON_ONCE (access_bit !=-1 ); +return "scope.abstract_unix_socket" ; + +case LANDLOCK_REQUEST_SCOPE_SIGNAL : +WARN_ON_ONCE (access_bit !=-1 ); +return "scope.signal" ; }WARN_ON_ONCE (1 );
security/landlock/audit.h +2 -0
@@ -20,6 +20,8 @@ enum landlock_request_type {LANDLOCK_REQUEST_FS_CHANGE_LAYOUT ,LANDLOCK_REQUEST_FS_ACCESS ,LANDLOCK_REQUEST_NET_ACCESS , +LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET , + LANDLOCK_REQUEST_SCOPE_SIGNAL, };/*
security/landlock/fs.c +5 -2
@@ -1798,6 +1798,7 @@ static void hook_file_set_fowner(struct file *file)const struct landlock_cred_security *new_subject;struct landlock_cred_security *fown_subject;struct landlock_ruleset *prev_dom; +size_t handle_layer;/* * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix
@@ -1807,15 +1808,17 @@ static void hook_file_set_fowner(struct file *file) fown_subject = &landlock_file (file)->fown_subject; prev_dom = fown_subject->domain; - new_subject =landlock_get_applicable_subject (current_cred (), - signal_scope,NULL ); + new_subject =landlock_get_applicable_subject ( +current_cred (), signal_scope, &handle_layer);if (new_subject) {landlock_get_ruleset (new_subject->domain); *fown_subject = *new_subject; +landlock_file (file)->fown_layer = handle_layer; }else {static const struct landlock_cred_security empty = {}; *fown_subject = empty; +landlock_file (file)->fown_layer =0 ; }/* Called in an RCU read-side critical section. */
security/landlock/fs.h +14 -0
@@ -9,6 +9,7 @@#ifndef _SECURITY_LANDLOCK_FS_H#define _SECURITY_LANDLOCK_FS_H +#include <linux/build_bug.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/rcupdate.h>
@@ -61,6 +62,11 @@ struct landlock_file_security {* _LANDLOCK_ACCESS_FS_OPTIONAL). */ deny_masks_t deny_masks; +/** +* @fown_layer: Layer level of @fown_subject->domain with +* LANDLOCK_SCOPE_SIGNAL. +*/ +u8 fown_layer;#endif /* CONFIG_AUDIT */ /**
@@ -73,6 +79,14 @@ struct landlock_file_security {struct landlock_cred_security fown_subject; }; +#ifdef CONFIG_AUDIT + +/* Makes sure all layers can be identified. */ +static_assert ((typeof_member (struct landlock_file_security ,fown_layer ))~0 >= +LANDLOCK_MAX_NUM_LAYERS ); + +#endif /* CONFIG_AUDIT */ +/** * struct landlock_superblock_security - Superblock security blob *
security/landlock/task.c +63 -16
133 lines not on this page · raw message
Signature · 1 line
2.48.1
kernel test robot
build botRe: [PATCH v6 15/26] landlock: Log scoped denials
kernel test robot noticed the following build errors:
Hi Mickaël,
kernel test robot noticed the following build errors:
[auto build test ERROR on 7eb172143d5508b4da468ed59ee857c6e5e01da6]
url: https://github.com/intel-lab-lkp/linux/commits/Micka-l-Sala-n/lsm-Add-audit_log_lsm_data-helper/20250309-025251 base: 7eb172143d5508b4da468ed59ee857c6e5e01da6 patch link: https://lore.kernel.org/r/20250308184422.2159360-16-mic%40digikod.net patch subject: [PATCH v6 15/26] landlock: Log scoped denials config: i386-buildonly-randconfig-006-20250309 (https://download.01.org/0day-ci/archive/20250309/[email protected]/config) compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250309/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> security/landlock/fs.c:1816:24: error: no member named 'fown_layer' in 'struct landlock_file_security'
1816 | landlock_file(file)->fown_layer = handle_layer;
| ~~~~~~~~~~~~~~~~~~~ ^
security/landlock/fs.c:1821:24: error: no member named 'fown_layer' in 'struct landlock_file_security'
1821 | landlock_file(file)->fown_layer = 0;
| ~~~~~~~~~~~~~~~~~~~ ^
2 errors generated.
--
>> security/landlock/task.c:412:48: error: no member named 'fown_layer' in 'struct landlock_file_security'
412 | .layer_plus_one = landlock_file(fown->file)->fown_layer + 1,
| ~~~~~~~~~~~~~~~~~~~~~~~~~ ^1 error generated.
vim +1816 security/landlock/fs.c
1792
1793 static void hook_file_set_fowner(struct file *file)
1794 {
1795 static const struct access_masks signal_scope = {
1796 .scope = LANDLOCK_SCOPE_SIGNAL,
1797 };
1798 const struct landlock_cred_security *new_subject;
1799 struct landlock_cred_security *fown_subject;
1800 struct landlock_ruleset *prev_dom;
1801 size_t handle_layer;
1802
1803 /*
1804 * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix
1805 * file_set_fowner LSM hook inconsistencies").
1806 */
1807 lockdep_assert_held(&file_f_owner(file)->lock);
1808
1809 fown_subject = &landlock_file(file)->fown_subject;
1810 prev_dom = fown_subject->domain;
1811 new_subject = landlock_get_applicable_subject(
1812 current_cred(), signal_scope, &handle_layer);
1813 if (new_subject) {
1814 landlock_get_ruleset(new_subject->domain);
1815 *fown_subject = *new_subject;
> 1816 landlock_file(file)->fown_layer = handle_layer;
1817 } else {
1818 static const struct landlock_cred_security empty = {};
1819
1820 *fown_subject = empty;
1821 landlock_file(file)->fown_layer = 0;
1822 }
1823
1824 /* Called in an RCU read-side critical section. */
1825 landlock_put_ruleset_deferred(prev_dom);
1826 }
1827
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCH v6 15/26] landlock: Log scoped denials
In reply to Mickaël Salaünkernel test robot noticed the following build errors:
Hi Mickaël,
kernel test robot noticed the following build errors:
[auto build test ERROR on 7eb172143d5508b4da468ed59ee857c6e5e01da6]
url: https://github.com/intel-lab-lkp/linux/commits/Micka-l-Sala-n/lsm-Add-audit_log_lsm_data-helper/20250309-025251 base: 7eb172143d5508b4da468ed59ee857c6e5e01da6 patch link: https://lore.kernel.org/r/20250308184422.2159360-16-mic%40digikod.net patch subject: [PATCH v6 15/26] landlock: Log scoped denials config: i386-buildonly-randconfig-004-20250309 (https://download.01.org/0day-ci/archive/20250309/[email protected]/config) compiler: gcc-12 (Debian 12.2.0-14) 12.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250309/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
security/landlock/fs.c: In function 'hook_file_set_fowner':
>> security/landlock/fs.c:1816:36: error: 'struct landlock_file_security' has no member named 'fown_layer'
1816 | landlock_file(file)->fown_layer = handle_layer;
| ^~
security/landlock/fs.c:1821:36: error: 'struct landlock_file_security' has no member named 'fown_layer'
1821 | landlock_file(file)->fown_layer = 0;
| ^~
--
security/landlock/task.c: In function 'hook_file_send_sigiotask':
>> security/landlock/task.c:412:60: error: 'struct landlock_file_security' has no member named 'fown_layer'
412 | .layer_plus_one = landlock_file(fown->file)->fown_layer + 1,
| ^~vim +1816 security/landlock/fs.c
1792
1793 static void hook_file_set_fowner(struct file *file)
1794 {
1795 static const struct access_masks signal_scope = {
1796 .scope = LANDLOCK_SCOPE_SIGNAL,
1797 };
1798 const struct landlock_cred_security *new_subject;
1799 struct landlock_cred_security *fown_subject;
1800 struct landlock_ruleset *prev_dom;
1801 size_t handle_layer;
1802
1803 /*
1804 * Lock already held by __f_setown(), see commit 26f204380a3c ("fs: Fix
1805 * file_set_fowner LSM hook inconsistencies").
1806 */
1807 lockdep_assert_held(&file_f_owner(file)->lock);
1808
1809 fown_subject = &landlock_file(file)->fown_subject;
1810 prev_dom = fown_subject->domain;
1811 new_subject = landlock_get_applicable_subject(
1812 current_cred(), signal_scope, &handle_layer);
1813 if (new_subject) {
1814 landlock_get_ruleset(new_subject->domain);
1815 *fown_subject = *new_subject;
> 1816 landlock_file(file)->fown_layer = handle_layer;
1817 } else {
1818 static const struct landlock_cred_security empty = {};
1819
1820 *fown_subject = empty;
1821 landlock_file(file)->fown_layer = 0;
1822 }
1823
1824 /* Called in an RCU read-side critical section. */
1825 landlock_put_ruleset_deferred(prev_dom);
1826 }
1827
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Mickaël Salaün
maintainerPATCH v6 16/26 landlock: Add LANDLOCK_RESTRICT_SELF_LOG_*_EXEC_* flags
In reply to Mickaël SalaünTODO: Add header copyrights
Most of the time we want to log denied access because they should not happen and such information helps diagnose issues. However, when sandboxing processes that we know will try to access denied resources (e.g. unknown, bogus, or malicious binary), we might want to not log related access requests that might fill up logs.
By default, denied requests are logged until the task call execve(2).
If the LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF flag is set, denied requests will not be logged for the same executed file.
If the LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON flag is set, denied requests from after an execve(2) call will be logged.
The rationale is that a program should know its own behavior, but not necessarily the behavior of other programs.
Because LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF is set for a specific Landlock domain, it makes it possible to selectively mask some access requests that would be logged by a parent domain, which might be handy for unprivileged processes to limit logs. However, system administrators should still use the audit filtering mechanism. There is intentionally no audit nor sysctl configuration to re-enable these logs. This is delegated to the user space program.
Increment the Landlock ABI version to reflect this interface change.
---
Changes since v5:
- Rename LANDLOCK_RESTRICT_SELF_QUIET to LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF, and adjust landlock_log_denial() accordingly. This better reflects what is the impact of this flag, especially wrt the following LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON, and makes both flags compatible and complementary.
- Rename LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC to LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON to be more consistent with other flags.
- Change flag values.
- Squash the LOG_SAME_EXEC_OFF and the LOG_NEW_EXEC_ON patches to get a more consistent patch.
Changes since v4:
- Rebase on top of the scoped guard patches.
Changes since v3:
- Rename LANDLOCK_RESTRICT_SELF_LOGLESS to LANDLOCK_RESTRICT_SELF_QUIET. "quiet" is already used by kernel's cmdline to disable most log messages, so this name makes sense for Landlock.
- Improve the LANDLOCK_ABI_VERSION comment.
Changes since v2:
- Update ABI version test.
--- include/uapi/linux/landlock.h | 21 ++++++++++++ security/landlock/audit.c | 16 +++++++-- security/landlock/domain.c | 2 ++ security/landlock/domain.h | 11 +++++++ security/landlock/limits.h | 4 +++ security/landlock/syscalls.c | 34 +++++++++++++++++--- tools/testing/selftests/landlock/base_test.c | 2 +- 7 files changed, 81 insertions(+), 9 deletions(-)
include/uapi/linux/landlock.h +21 -0
@@ -4,6 +4,7 @@* * Copyright © 2017-2020 Mickaël Salaün <[email protected]> * Copyright © 2018-2020 ANSSI +* Copyright © 2021-2025 Microsoft Corporation */ #ifndef _UAPI_LINUX_LANDLOCK_H
@@ -62,6 +63,26 @@ struct landlock_ruleset_attr {#define LANDLOCK_CREATE_RULESET_VERSION (1U << 0)/* clang-format on */ +/* +* sys_landlock_restrict_self() flags: +* +* - %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF: Do not create any log related to the +* enforced restrictions. This should only be set by tools launching unknown +* or untrusted programs (e.g. a sandbox tool, container runtime, system +* service manager). Because programs sandboxing themselves should fix any +* denied access, they should not set this flag to be aware of potential +* issues reported by system's logs (i.e. audit). +* - %LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON: Explicitly ask to continue +* logging denied access requests even after an :manpage:`execve(2)` call. +* This flag should only be set if all the programs than can legitimately be +* executed will not try to request a denied access (which could spam audit +* logs). +*/ +/* clang-format off */ +#define LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF (1U << 0) +#define LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON (1U << 1) +/* clang-format on */ +/** * enum landlock_rule_type - Landlock rule type *
security/landlock/audit.c +13 -3
@@ -422,6 +422,9 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,get_hierarchy (subject->domain, youngest_layer); } +if (READ_ONCE (youngest_denied->log_status) ==LANDLOCK_LOG_DISABLED ) +return ; +/* * Consistently keeps track of the number of denied access requests * even if audit is currently disabled, or if audit rules currently
@@ -433,9 +436,16 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,if (!audit_enabled)return ; -/* Ignores denials after an execution. */ -if (!(subject->domain_exec & (1 << youngest_layer))) -return ; +/* Checks if the current exec was restricting itself. */ +if (subject->domain_exec & (1 << youngest_layer)) { +/* Ignores denials for the same execution. */ +if (!youngest_denied->log_same_exec) +return ; + }else { +/* Ignores denials after a new execution. */ +if (!youngest_denied->log_cross_exec) +return ; + } ab =audit_log_start (audit_context (),GFP_ATOMIC | __GFP_NOWARN,AUDIT_LANDLOCK_ACCESS );
security/landlock/domain.c +2 -0
@@ -127,6 +127,8 @@ int landlock_init_hierarchy_log(struct landlock_hierarchy *const hierarchy) hierarchy->details = details; hierarchy->id =landlock_get_id_range (1 ); hierarchy->log_status =LANDLOCK_LOG_PENDING ; + hierarchy->log_same_exec = true; + hierarchy->log_cross_exec = false;atomic64_set (&hierarchy->num_denials,0 );return 0 ; }
security/landlock/domain.h +11 -0
@@ -24,6 +24,7 @@enum landlock_log_status {LANDLOCK_LOG_PENDING =0 ,LANDLOCK_LOG_RECORDED , +LANDLOCK_LOG_DISABLED , };/**
@@ -103,6 +104,16 @@ struct landlock_hierarchy {* @details: Information about the related domain. */ const struct landlock_details *details; +/** +* @log_same_exec: Set if the domain is *not* configured with +* %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF. Set to true by default. +*/ + u32 log_same_exec : 1, +/** +* @log_cross_exec: Set if the domain is configured with +* %LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON. Set to false by default. +*/ + log_cross_exec : 1;#endif /* CONFIG_AUDIT */ };
security/landlock/limits.h +4 -0
@@ -29,6 +29,10 @@#define LANDLOCK_LAST_SCOPE LANDLOCK_SCOPE_SIGNAL#define LANDLOCK_MASK_SCOPE ((LANDLOCK_LAST_SCOPE << 1) - 1)#define LANDLOCK_NUM_SCOPE __const_hweight64(LANDLOCK_MASK_SCOPE) + +#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON +#define LANDLOCK_MASK_RESTRICT_SELF ((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1) +/* clang-format on */ #endif /* _SECURITY_LANDLOCK_LIMITS_H */
security/landlock/syscalls.c +29 -5
@@ -28,6 +28,7 @@#include <uapi/linux/landlock.h> #include "cred.h" +#include "domain.h" #include "fs.h" #include "limits.h" #include "net.h"
@@ -151,7 +152,14 @@ static const struct file_operations ruleset_fops = { .write = fop_dummy_write, }; -#define LANDLOCK_ABI_VERSION 6 +/* +* The Landlock ABI version should be incremented for each new Landlock-related +* user space visible change (e.g. Landlock syscalls). This version should +* only be incremented once per Linux release, and the date in +* Documentation/userspace-api/landlock.rst should be updated to reflect the +* UAPI change. +*/ +#define LANDLOCK_ABI_VERSION 7/** * sys_landlock_create_ruleset - Create a new ruleset
@@ -429,7 +437,10 @@ SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,* sys_landlock_restrict_self - Enforce a ruleset on the calling thread * * @ruleset_fd: File descriptor tied to the ruleset to merge with the target. -* @flags: Must be 0. +* @flags: Supported values: +* +* - %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF +* - %LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON * * This system call enables to enforce a Landlock ruleset on the current * thread. Enforcing a ruleset requires that the task has %CAP_SYS_ADMIN in its
@@ -439,7 +450,7 @@ SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,* Possible returned errors are: * * - %EOPNOTSUPP: Landlock is supported by the kernel but disabled at boot time; -* - %EINVAL: @flags is not 0. +* - %EINVAL: @flags contains an unknown bit. * - %EBADF: @ruleset_fd is not a file descriptor for the current thread; * - %EBADFD: @ruleset_fd is not a ruleset file descriptor; * - %EPERM: @ruleset_fd has no read access to the underlying ruleset, or the
@@ -455,6 +466,7 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32, *ruleset __free(landlock_put_ruleset) = NULL;struct cred *new_cred;struct landlock_cred_security *new_llcred; +bool log_same_exec, log_cross_exec;if (!is_initialized ())return -EOPNOTSUPP ;
@@ -467,10 +479,15 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32, !ns_capable_noaudit(current_user_ns(), CAP_SYS_ADMIN))return -EPERM ; -/* No flag for now. */ -if (flags) +if ((flags |LANDLOCK_MASK_RESTRICT_SELF ) != +LANDLOCK_MASK_RESTRICT_SELF )return -EINVAL ; +/* Translates "off" flag to boolean. */ + log_same_exec = !(flags &LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF ); +/* Translates "on" flag to boolean. */ + log_cross_exec = !!(flags &LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ); +/* Gets and checks the ruleset. */ ruleset =get_ruleset_from_fd (ruleset_fd,FMODE_CAN_READ );if (IS_ERR (ruleset))
@@ -493,6 +510,13 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,return PTR_ERR (new_dom); } +#ifdef CONFIG_AUDIT + new_dom->hierarchy->log_same_exec = log_same_exec; + new_dom->hierarchy->log_cross_exec = log_cross_exec; +if (!log_same_exec && !log_cross_exec) + new_dom->hierarchy->log_status =LANDLOCK_LOG_DISABLED ; +#endif /* CONFIG_AUDIT */ +/* Replaces the old (prepared) domain. */ landlock_put_ruleset (new_llcred->domain); new_llcred->domain = new_dom;
tools/testing/selftests/landlock/base_test.c +1 -1
@@ -76,7 +76,7 @@ TEST(abi_version)const struct landlock_ruleset_attr ruleset_attr = { .handled_access_fs =LANDLOCK_ACCESS_FS_READ_FILE , }; -ASSERT_EQ (6 ,landlock_create_ruleset (NULL ,0 , +ASSERT_EQ (7 ,landlock_create_ruleset (NULL ,0 ,LANDLOCK_CREATE_RULESET_VERSION )); ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 17/26 landlock: Add LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF
In reply to Mickaël SalaünAdd LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF for the case of sandboxer tools, init systems, or runtime containers launching programs sandboxing themselves in an inconsistent way. Setting this flag should only depends on runtime configuration (i.e. not hardcoded).
We don't create a new ruleset's option because this should not be part of the security policy: only the task that enforces the policy (not the one that create it) knows if itself or its children may request denied actions.
This is the first and only flag that can be set without actually restricting the caller (i.e. without providing a ruleset).
Extend struct landlock_cred_security with a u8 log_subdomains_off. struct landlock_file_security is still 16 bytes.
---
Changes since v5:
- Rename LANDLOCK_RESTRICT_SELF_QUIET_SUBDOMAINS to LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF. As for LANDLOCK_RESTRICT_SELF_LOG_OFF, this makes more sense.
- Store the log_subdomains bit in landlock_cred instead of landlock_hirerarchy because it is not directly related to the current domain.
- Make it possible to set this flag without actually restricting the calling task, and update the related documentation.
Changes since v4:
- New patch.
--- include/uapi/linux/landlock.h | 12 ++++++++++ security/landlock/cred.h | 7 ++++++ security/landlock/limits.h | 2 +- security/landlock/syscalls.c | 41 ++++++++++++++++++++++++++++++----- 4 files changed, 55 insertions(+), 7 deletions(-)
include/uapi/linux/landlock.h +12 -0
@@ -77,10 +77,22 @@ struct landlock_ruleset_attr {* This flag should only be set if all the programs than can legitimately be * executed will not try to request a denied access (which could spam audit * logs). +* - %LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF: Do not create any log related +* to the enforced restrictions coming from future nested domains created by +* the caller or its descendants. This should only be set according to a +* runtime configuration (i.e. not hardcoded) by programs launching other +* unknown or untrusted programs that may create their own Landlock domains +* and spam logs. The main use case is for container runtimes to enable users +* to mute buggy sandboxed programs for a specific container image. Other use +* cases include sandboxer tools and init systems. Unlike +* %LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF, +* %LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF does not impact the requested +* restriction (if any) but only the future nested domains. */ /* clang-format off */ #define LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF (1U << 0)#define LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON (1U << 1) +#define LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF (1U << 2)/* clang-format on */ /**
security/landlock/cred.h +7 -0
@@ -39,6 +39,13 @@ struct landlock_cred_security {* landlock_restrict_self(2)). */ u16 domain_exec; +/** +* @log_subdomains_off: Set if the domain descendants's log_status should be +* set to %LANDLOCK_LOG_DISABLED. This is not a landlock_hierarchy +* configuration because it applies to future descendant domains and it does +* not require a current domain. +*/ + u8 log_subdomains_off : 1;#endif /* CONFIG_AUDIT */ } __packed;
security/landlock/limits.h +1 -1
@@ -30,7 +30,7 @@#define LANDLOCK_MASK_SCOPE ((LANDLOCK_LAST_SCOPE << 1) - 1)#define LANDLOCK_NUM_SCOPE __const_hweight64(LANDLOCK_MASK_SCOPE) -#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON +#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF#define LANDLOCK_MASK_RESTRICT_SELF ((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1)/* clang-format on */
security/landlock/syscalls.c +35 -6
78 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 18/26 samples/landlock: Enable users to log sandbox denials
In reply to Mickaël SalaünBy default, denials from within the sandbox are not logged. Indeed, the sandboxer's security policy might not be fitted to the set of sandboxed processes that could be spawned (e.g. from a shell).
For test purpose, parse the LL_FORCE_LOG environment variable to log every sandbox denials, including after launching the initial sandboxed program thanks to LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON.
---
Changes since v5:
- Update with new flag.
Changes since v3:
- Extend error message, suggested by Francis Laniel.
Changes since v2:
- New patch.
--- samples/landlock/sandboxer.c | 37 +++++++++++++++++++++++++++++++++--- security/landlock/syscalls.c | 8 ++------ 2 files changed, 36 insertions(+), 9 deletions(-)
samples/landlock/sandboxer.c +34 -3
@@ -58,6 +58,7 @@ static inline int landlock_restrict_self(const int ruleset_fd,#define ENV_TCP_BIND_NAME "LL_TCP_BIND"#define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"#define ENV_SCOPED_NAME "LL_SCOPED" +#define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"#define ENV_DELIMITER ":"static int str2num (const char *numstr,__u64 *num_dst)
@@ -295,7 +296,7 @@ static bool check_ruleset_scope(const char *const env_var,/* clang-format on */ -#define LANDLOCK_ABI_LAST 6 +#define LANDLOCK_ABI_LAST 7#define XSTR (s) #s#define STR (s) XSTR(s)
@@ -322,6 +323,9 @@ static const char help[] =" - \"a\" to restrict opening abstract unix sockets\n" " - \"s\" to restrict sending signals\n" "\n" +"A sandboxer should not log denied access requests to avoid spamming logs, " +"but to test audit we can set " ENV_FORCE_LOG_NAME "=1\n" +"\n" "Example:\n" ENV_FS_RO_NAME "=\"${PATH}:/lib:/usr:/proc:/etc:/dev/urandom\" " ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
@@ -340,7 +344,7 @@ int main(const int argc, char *const argv[], char *const *const envp)const char *cmd_path;char *const *cmd_argv;int ruleset_fd, abi; -char *env_port_name; +char *env_port_name, *env_force_log;__u64 access_fs_ro =ACCESS_FS_ROUGHLY_READ , access_fs_rw =ACCESS_FS_ROUGHLY_READ |ACCESS_FS_ROUGHLY_WRITE ;
@@ -351,6 +355,8 @@ int main(const int argc, char *const argv[], char *const *const envp) .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET | LANDLOCK_SCOPE_SIGNAL, }; +int supported_restrict_flags =LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; +int set_restrict_flags =0 ;if (argc <2 ) {fprintf (stderr, help, argv[0 ]);
@@ -422,6 +428,13 @@ int main(const int argc, char *const argv[], char *const *const envp)/* Removes LANDLOCK_SCOPE_* for ABI < 6 */ ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |LANDLOCK_SCOPE_SIGNAL ); + __attribute__((fallthrough)); +case 6 : +/* Removes LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON for ABI < 7 */ + supported_restrict_flags &= + ~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; + +/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */ fprintf (stderr,"Hint: You should update the running kernel " "to leverage Landlock features "
@@ -456,6 +469,24 @@ int main(const int argc, char *const argv[], char *const *const envp)if (check_ruleset_scope (ENV_SCOPED_NAME , &ruleset_attr))return 1 ; +/* Enables optional logs. */ + env_force_log =getenv (ENV_FORCE_LOG_NAME ); +if (env_force_log) { +if (strcmp (env_force_log,"1" ) !=0 ) { +fprintf (stderr,"Unknown value for " ENV_FORCE_LOG_NAME +" (only \"1\" is handled)\n" ); +return 1 ; + } +if (!(supported_restrict_flags & +LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON )) { +fprintf (stderr, +"Audit logs not supported by current kernel\n" ); +return 1 ; + } + set_restrict_flags |=LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON ; +unsetenv (ENV_FORCE_LOG_NAME ); + } + ruleset_fd =landlock_create_ruleset (&ruleset_attr,sizeof (ruleset_attr),0 );if (ruleset_fd <0 ) {
@@ -483,7 +514,7 @@ int main(const int argc, char *const argv[], char *const *const envp)perror ("Failed to restrict privileges" ); goto err_close_ruleset; } -if (landlock_restrict_self (ruleset_fd,0 )) { +if (landlock_restrict_self (ruleset_fd, set_restrict_flags)) {perror ("Failed to enforce ruleset" ); goto err_close_ruleset; }
security/landlock/syscalls.c +2 -6
@@ -495,12 +495,8 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,/* Translates "off" flag to boolean. */ log_subdomains = !(flags &LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF ); -/* -* It is allowed to set %LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF with -1 -* as @ruleset_fd, but no other flag must be set. -*/ -if (!(ruleset_fd ==-1 && - flags ==LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )) { +if (!(flags ==LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF && + ruleset_fd ==-1 )) {/* Gets and checks the ruleset. */ ruleset =get_ruleset_from_fd (ruleset_fd,FMODE_CAN_READ );if (IS_ERR (ruleset))
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 19/26 selftests/landlock: Add test for invalid ruleset file descriptor
In reply to Mickaël SalaünTo align with fs_test's layout1.inval and layout0.proc_nsfs which test EBADFD for landlock_add_rule(2), create a new base_test's restrict_self_fd which test EBADFD for landlock_restrict_self(2).
---
Changes since v5:
- New standalone patch (that can be backported).
--- tools/testing/selftests/landlock/base_test.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
tools/testing/selftests/landlock/base_test.c +11 -0
@@ -233,6 +233,17 @@ TEST(restrict_self_checks_ordering)ASSERT_EQ (0 ,close (ruleset_fd)); } +TEST (restrict_self_fd) +{ +int fd; + + fd =open ("/dev/null" ,O_RDONLY |O_CLOEXEC ); +ASSERT_LE (0 , fd); + +EXPECT_EQ (-1 ,landlock_restrict_self (fd,0 )); +EXPECT_EQ (EBADFD , errno); +} +TEST (ruleset_fd_io) {struct landlock_ruleset_attr ruleset_attr = {
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 20/26 selftests/landlock: Extend tests for landlock_restrict_self(2)'s flags
In reply to Mickaël SalaünAdd the base_test's restrict_self_fd_flags tests to align with previous restrict_self_fd tests but with the new LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF flag.
Add the restrict_self_flags tests to check that LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF, LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON, and LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF are valid but not the next bit. Some checks are similar to restrict_self_checks_ordering's ones.
---
Changes since v5:
- Rename restrict flags.
- Update LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF test to pass with -1 as ruleset FD, and flag ordering.
- Add restrict_self_fd_flags tests.
Changes since v4:
- Update with LANDLOCK_RESTRICT_SELF_QUIET_SUBDOMAINS, and LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC.
Changes since v3:
- Use a last_flag variable.
Changes since v2:
- New patch.
--- tools/testing/selftests/landlock/base_test.c | 71 ++++++++++++++++++++ 1 file changed, 71 insertions(+)
tools/testing/selftests/landlock/base_test.c +71 -0
@@ -244,6 +244,77 @@ TEST(restrict_self_fd)EXPECT_EQ (EBADFD , errno); } +TEST (restrict_self_fd_flags) +{ +int fd; + + fd =open ("/dev/null" ,O_RDONLY |O_CLOEXEC ); +ASSERT_LE (0 , fd); + +/* +* LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF accepts -1 but not any file +* descriptor. +*/ +EXPECT_EQ (-1 ,landlock_restrict_self ( + fd,LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )); +EXPECT_EQ (EBADFD , errno); +} + +TEST (restrict_self_flags) +{ +const __u32 last_flag =LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF ; + +/* Tests invalid flag combinations. */ + +EXPECT_EQ (-1 ,landlock_restrict_self (-1 , last_flag <<1 )); +EXPECT_EQ (EINVAL , errno); + +EXPECT_EQ (-1 ,landlock_restrict_self (-1 ,-1 )); +EXPECT_EQ (EINVAL , errno); + +/* Tests valid flag combinations. */ + +EXPECT_EQ (-1 ,landlock_restrict_self (-1 ,0 )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (-1 ,landlock_restrict_self ( +-1 ,LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (-1 , +landlock_restrict_self ( +-1 , +LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF | +LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (-1 , +landlock_restrict_self ( +-1 , +LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON | +LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (-1 ,landlock_restrict_self ( +-1 ,LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (-1 , +landlock_restrict_self ( +-1 ,LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF | +LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON )); +EXPECT_EQ (EBADF , errno); + +/* Tests with an invalid ruleset_fd. */ + +EXPECT_EQ (-1 ,landlock_restrict_self ( +-2 ,LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )); +EXPECT_EQ (EBADF , errno); + +EXPECT_EQ (0 ,landlock_restrict_self ( +-1 ,LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF )); +} +TEST (ruleset_fd_io) {struct landlock_ruleset_attr ruleset_attr = {
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 21/26 selftests/landlock: Add tests for audit flags and domain IDs
In reply to Mickaël SalaünAdd audit_test.c to check with and without LANDLOCK_RESTRICT_SELF_* flags against the two Landlock audit record types:AUDIT_LANDLOCK_ACCESS and AUDIT_LANDLOCK_DOMAIN.
Check consistency of domain IDs in AUDIT_LANDLOCK_ACCESS and AUDIT_LANDLOCK_DOMAIN messages: denied access, domain allocation, and domain deallocation.
Tests are run with audit filters to ensure the audit records come from the test program. Moreover, because there can only be one audit process, tests would failed if run in parallel. Because of audit limitations, tests can only be run in the initial namespace.
The audit test helpers were inspired by libaudit and tools/testing/selftests/net/netfilter/audit_logread.c
---
There is a race condition when checking the "domain drop" event on some systems.
Changes since v5:
- Enhance audit_match_record() with an __u64 *domain_id argument set according to the audit logs.
- Rename audit_fork.flags to audit_flags.signal .
- Rename variants according to new flags.
- Check consistency of domain IDs.
Changes since v4:
- Update with the new landlock_restrict_self()'s flags, the new audit rule types, and message fields.
- Simplify audit_filter_exe() and audit_init_filter_exe().
- Test with kill() instead of umount().
- Test domain deallocation events.
Changes since v3:
- Improve audit_request() to check Netlink errors and handle multiple replies.
- Make audit_filter_exe() more generic to handle several audit rule lists.
- Merge audit_init_state() into audit_init() and create audit_init_with_exe_filter() to handle AUDIT_EXE_LANDLOCK_DENY with an arbitrary path.
- Add matches_log_dom_info().
Changes since v2:
- New patch.
--- tools/testing/selftests/landlock/audit.h | 386 ++++++++++++++++++ tools/testing/selftests/landlock/audit_test.c | 238 +++++++++++ tools/testing/selftests/landlock/common.h | 2 + tools/testing/selftests/landlock/config | 1 + 4 files changed, 627 insertions(+) create mode 100644 tools/testing/selftests/landlock/audit.h create mode 100644 tools/testing/selftests/landlock/audit_test.c
tools/testing/selftests/landlock/audit.h new file +386 -0
@@ -0,0 +1,386 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Landlock audit helpers +* +* Copyright © 2024-2025 Microsoft Corporation +*/ + +#define _GNU_SOURCE +#include <errno.h> +#include <linux/audit.h> +#include <linux/limits.h> +#include <linux/netlink.h> +#include <regex.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE (arr) (sizeof(arr) / sizeof((arr)[0])) +#endif + +#define REGEX_LANDLOCK_PREFIX "^audit([0-9.:]\\+): domain=\\([0-9a-f]\\+\\)" + +struct audit_filter { +__u32 record_type; +size_t exe_len; +char exe[PATH_MAX ]; +}; + +struct audit_message { +struct nlmsghdr header; +union { +struct audit_status status; +struct audit_features features; +struct audit_rule_data rule; +struct nlmsgerr err; +char data[PATH_MAX +200 ]; + }; +}; + +static int audit_send (const int fd,const struct audit_message *const msg) +{ +struct sockaddr_nl addr = { + .nl_family =AF_NETLINK , + }; +int ret; + +do { + ret =sendto (fd, msg, msg->header.nlmsg_len,0 , + (struct sockaddr *)&addr,sizeof (addr)); + }while (ret <0 && errno ==EINTR ); + +if (ret <0 ) +return -errno; + +if (ret != msg->header.nlmsg_len) +return -E2BIG ; + +return 0 ; +} + +static int audit_recv (const int fd,struct audit_message *msg) +{ +struct sockaddr_nl addr; +socklen_t addrlen =sizeof (addr); +struct audit_message msg_tmp; +int err; + +if (!msg) + msg = &msg_tmp; + +do { + err =recvfrom (fd, msg,sizeof (*msg),0 , + (struct sockaddr *)&addr, &addrlen); + }while (err <0 && errno ==EINTR ); + +if (err <0 ) +return -errno; + +if (addrlen !=sizeof (addr) || addr.nl_pid !=0 ) +return -EINVAL ; + +/* Checks Netlink error or end of messages. */ +if (msg->header.nlmsg_type ==NLMSG_ERROR ) +return msg->err.error; + +return 0 ; +} + +static int audit_request (const int fd, +const struct audit_message *const request, +struct audit_message *reply) +{ +struct audit_message msg_tmp; +bool first_reply = true; +int err; + + err =audit_send (fd, request); +if (err) +return err; + +if (!reply) + reply = &msg_tmp; + +do { +if (first_reply) + first_reply = false; +else + reply = &msg_tmp; + + err =audit_recv (fd, reply); +if (err) +return err; + }while (reply->header.nlmsg_type !=NLMSG_ERROR && + reply->err.msg.nlmsg_type != request->header.nlmsg_type); + +return reply->err.error; +} + +static int audit_filter_exe (const int audit_fd, +const struct audit_filter *const filter, +const __u16 type) +{ +struct audit_message msg = { + .header = { + .nlmsg_len =NLMSG_SPACE (sizeof (msg.rule)) + +NLMSG_ALIGN (filter->exe_len), + .nlmsg_type = type, + .nlmsg_flags =NLM_F_REQUEST |NLM_F_ACK , + }, + .rule = { + .flags =AUDIT_FILTER_EXCLUDE , + .action =AUDIT_NEVER , + .field_count =1 , + .fields[0 ] = filter->record_type, + .fieldflags[0 ] =AUDIT_NOT_EQUAL , + .values[0 ] = filter->exe_len, + .buflen = filter->exe_len, + } + }; + +if (filter->record_type !=AUDIT_EXE ) +return -EINVAL ; + +memcpy (msg.rule.buf, filter->exe, filter->exe_len); +return audit_request (audit_fd, &msg,NULL ); +} + +static int audit_filter_drop (const int audit_fd,const __u16 type) +{ +struct audit_message msg = { + .header = { + .nlmsg_len =NLMSG_SPACE (sizeof (msg.rule)), + .nlmsg_type = type, + .nlmsg_flags =NLM_F_REQUEST |NLM_F_ACK , + }, + .rule = { + .flags =AUDIT_FILTER_EXCLUDE , + .action =AUDIT_NEVER , + .field_count =1 , + .fields[0 ] =AUDIT_MSGTYPE , + .fieldflags[0 ] =AUDIT_NOT_EQUAL , + .values[0 ] =AUDIT_LANDLOCK_DOMAIN , + } + }; + +return audit_request (audit_fd, &msg,NULL ); +} + +static int audit_set_status (int fd,__u32 key,__u32 val) +{ +const struct audit_message msg = { + .header = { + .nlmsg_len =NLMSG_SPACE (sizeof (msg.status)), + .nlmsg_type =AUDIT_SET , + .nlmsg_flags =NLM_F_REQUEST |NLM_F_ACK , + }, + .status = { + .mask = key, + .enabled = key ==AUDIT_STATUS_ENABLED ? val :0 , + .pid = key ==AUDIT_STATUS_PID ? val :0 , + } + }; + +return audit_request (fd, &msg,NULL ); +} + +/* +* @domain_id: The domain ID extracted from the audit message (if the first part +* of @pattern is REGEX_LANDLOCK_PREFIX). It is set to 0 if the domain ID is +* not found. +*/ +static int audit_match_record (int audit_fd,const __u16 type, +const char *const pattern,__u64 *domain_id) +{ +struct audit_message msg; +int ret, err =0 ; +bool matches_record = !type; +regmatch_t matches[2 ]; +regex_t regex; + + ret =regcomp (®ex, pattern,0 ); +if (ret) +return -EINVAL ; + +do { +memset (&msg,0 ,sizeof (msg)); + err =audit_recv (audit_fd, &msg); +if (err) + goto out; + +if (msg.header.nlmsg_type == type) + matches_record = true; + }while (!matches_record); + + ret =regexec (®ex, msg.data,ARRAY_SIZE (matches), matches,0 ); +if (ret) { +printf ("DATA: %s\n" , msg.data); +printf ("ERROR: no match for pattern: %s\n" , pattern); + err = -ENOENT ; + } + +if (domain_id) { + *domain_id =0 ; +if (matches[1 ].rm_so !=-1 ) { +int match_len = matches[1 ].rm_eo - matches[1 ].rm_so; +/* The maximal characters of a 2^64 hexadecimal number is 17. */ +char dom_id[18 ]; + +if (match_len >0 && match_len <sizeof (dom_id)) { +memcpy (dom_id, msg.data + matches[1 ].rm_so, + match_len); + dom_id[match_len] ='\0' ; +if (domain_id) + *domain_id =strtoull (dom_id,NULL ,16 ); + } + } + } + +out: +regfree (®ex); +return err; +} + +struct audit_records { +size_t access; +size_t domain; +}; + +// TODO: check that audit_fd is valid +static void audit_count_records (int audit_fd,struct audit_records *records) +{ +struct audit_message msg; + + records->access =0 ; + records->domain =0 ; + +do { +memset (&msg,0 ,sizeof (msg)); +if (audit_recv (audit_fd, &msg)) +return ; + +switch (msg.header.nlmsg_type) { +case AUDIT_LANDLOCK_ACCESS : + records->access++; +break ; +case AUDIT_LANDLOCK_DOMAIN : + records->domain++; +break ; + } + }while (true); +} + +static int audit_init (void ) +{ +const struct timeval tv = { + .tv_usec =1 , + }; +int fd, err; + + fd =socket (PF_NETLINK ,SOCK_RAW ,NETLINK_AUDIT ); +if (fd <0 ) +return -errno; + + err =audit_set_status (fd,AUDIT_STATUS_ENABLED ,1 ); +if (err) +return err; + + err =audit_set_status (fd,AUDIT_STATUS_PID ,getpid ()); +if (err) +return err; + +/* Sets a timeout for negative tests. */ + err =setsockopt (fd,SOL_SOCKET ,SO_RCVTIMEO , &tv,sizeof (tv)); +if (err) +return -errno; + +return fd; +} + +static int audit_init_filter_exe (struct audit_filter *filter,const char *path) +{ +char *absolute_path =NULL ; + +// TODO: Make sure there is no rule already filtering. + + filter->record_type =AUDIT_EXE ; + +if (!path) { + filter->exe_len =readlink ("/proc/self/exe" , filter->exe, +sizeof (filter->exe) -1 ); +if (filter->exe_len <0 ) +return -errno; + +return 0 ; + } + + absolute_path =realpath (path,NULL ); +if (!absolute_path) +return -errno; + +/* No need for the terminating NULL byte. */ + filter->exe_len =strlen (absolute_path); +if (filter->exe_len >sizeof (filter->exe)) +return -E2BIG ; + +memcpy (filter->exe, absolute_path, filter->exe_len); +free (absolute_path); +return 0 ; +} + +static int audit_cleanup (int audit_fd,struct audit_filter *filter) +{ +struct audit_filter new_filter; + +if (audit_fd <0 || !filter) { +int err; + +/* +* Simulates audit_init_with_exe_filter() when called from +* FIXTURE_TEARDOWN_PARENT(). +*/ + audit_fd =audit_init (); +if (audit_fd <0 ) +return audit_fd; + + filter = &new_filter; + err =audit_init_filter_exe (filter,NULL ); +if (err) +return err; + } + +/* Filters might not be in place. */ +audit_filter_exe (audit_fd, filter,AUDIT_DEL_RULE ); +audit_filter_drop (audit_fd,AUDIT_DEL_RULE ); + +/* +* Because audit_cleanup() might not be called by the test auditd +* process, it might not be possible to explicitly set it. Anyway, +* AUDIT_STATUS_ENABLED will implicitly be set to 0 when the auditd +* process will exit. +*/ +return close (audit_fd); +} + +static int audit_init_with_exe_filter (struct audit_filter *filter) +{ +int fd, err; + + fd =audit_init (); +if (fd <0 ) +return fd; + + err =audit_init_filter_exe (filter,NULL ); +if (err) +return err; + + err =audit_filter_exe (fd, filter,AUDIT_ADD_RULE ); +if (err) +return err; + +return fd; +}
tools/testing/selftests/landlock/audit_test.c new file +238 -0
238 lines not on this page · raw message
tools/testing/selftests/landlock/common.h +2 -0
@@ -11,6 +11,7 @@#include <errno.h> #include <linux/securebits.h> #include <sys/capability.h> +#include <sys/prctl.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/wait.h>
@@ -37,6 +38,7 @@ static void _init_caps(struct __test_metadata *const _metadata, bool drop_all)/* Only these three capabilities are useful for the tests. */ const cap_value_t caps[] = {/* clang-format off */ +CAP_AUDIT_CONTROL ,CAP_DAC_OVERRIDE ,CAP_MKNOD ,CAP_NET_ADMIN ,
tools/testing/selftests/landlock/config +1 -0
@@ -1,4 +1,5 @@ CONFIG_AF_UNIX_OOB=y +CONFIG_AUDIT=y CONFIG_CGROUPS=y CONFIG_CGROUP_SCHED=y CONFIG_INET=y
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 22/26 selftests/landlock: Test audit with restrict flags
In reply to Mickaël SalaünAdd audit_exec tests to filter Landlock denials according to cross-execution or muted subdomains.
Add a wait-pipe-sandbox.c test program to sandbox itself and send a (denied) signals to its parent.
---
Changes since v5:
- Rename audit_exec.flags to audit_exec.signal_and_open .
Changes since v4:
- Revamp to test the Landlock syscall flags instead of the audit rules.
- Copy wait-pipe.c to wait-pipe-sandbox.c and extend it.
- Fix regex.
Changes since v3:
- New patch.
--- tools/testing/selftests/landlock/Makefile | 6 +- tools/testing/selftests/landlock/audit_test.c | 222 ++++++++++++++++++ tools/testing/selftests/landlock/common.h | 1 + .../selftests/landlock/wait-pipe-sandbox.c | 131 +++++++++++ 4 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/landlock/wait-pipe-sandbox.c
tools/testing/selftests/landlock/Makefile +5 -1
@@ -10,7 +10,11 @@ src_test := $(wildcard *_test.c) TEST_GEN_PROGS := $(src_test:.c=) -TEST_GEN_PROGS_EXTENDED := true sandbox-and-launch wait-pipe +TEST_GEN_PROGS_EXTENDED := \ + true \ + sandbox-and-launch \ + wait-pipe \ + wait-pipe-sandbox # Short targets: $(TEST_GEN_PROGS): LDLIBS += -lcap -lpthread
tools/testing/selftests/landlock/audit_test.c +222 -0
239 lines not on this page · raw message
tools/testing/selftests/landlock/common.h +1 -0
@@ -31,6 +31,7 @@static const char bin_sandbox_and_launch[] ="./sandbox-and-launch" ;static const char bin_wait_pipe[] ="./wait-pipe" ; +static const char bin_wait_pipe_sandbox[] ="./wait-pipe-sandbox" ;static void _init_caps (struct __test_metadata *const _metadata,bool drop_all) {
tools/testing/selftests/landlock/wait-pipe-sandbox.c new file +131 -0
131 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 23/26 selftests/landlock: Add audit tests for ptrace
In reply to Mickaël SalaünAdd tests for all ptrace actions checking "blockers=ptrace" records.
This also improves PTRACE_TRACEME and PTRACE_ATTACH tests by making sure that the restrictions comes from Landlock, and with the expected process. These extended tests are like enhanced errno checks that make sure Landlock enforcement is consistent.
---
Changes since v5:
- Move all audit tests to a new audit.trace test suite.
- Simplify tests by only checking PTRACE_TRACEME and PTRACE_ATTACH with one scenario. This is preferable to not impact existing tests.
- Make sure there is no unknown Landlock audit record.
Changes since v3:
- Update test coverage.
Changes since v2:
- New patch.
--- .../testing/selftests/landlock/ptrace_test.c | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+)
tools/testing/selftests/landlock/ptrace_test.c +140 -0
@@ -4,6 +4,7 @@* * Copyright © 2017-2020 Mickaël Salaün <[email protected]> * Copyright © 2019-2020 ANSSI +* Copyright © 2024-2025 Microsoft Corporation */ #define _GNU_SOURCE
@@ -17,6 +18,7 @@#include <sys/wait.h> #include <unistd.h> +#include "audit.h" #include "common.h" /* Copied from security/yama/yama_lsm.c */
@@ -434,4 +436,142 @@ TEST_F(hierarchy, trace) _metadata->exit_code =KSFT_FAIL ; } +static int matches_log_ptrace (struct __test_metadata *const _metadata, +int audit_fd,const pid_t opid) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=ptrace opid=%d ocomm=\"ptrace_test\"$" ; +char log_match[sizeof (log_template) +10 ]; +int log_match_len; + + log_match_len = +snprintf (log_match,sizeof (log_match), log_template, opid); +if (log_match_len >sizeof (log_match)) +return -E2BIG ; + +return audit_match_record (audit_fd,AUDIT_LANDLOCK_ACCESS , log_match, +NULL ); +} + +FIXTURE (audit) +{ +struct audit_filter audit_filter; +int audit_fd; +}; + +FIXTURE_SETUP (audit) +{ +disable_caps (_metadata); +set_cap (_metadata,CAP_AUDIT_CONTROL ); + self->audit_fd =audit_init_with_exe_filter (&self->audit_filter); +EXPECT_LE (0 , self->audit_fd); +clear_cap (_metadata,CAP_AUDIT_CONTROL ); +} + +FIXTURE_TEARDOWN_PARENT (audit) +{ +EXPECT_EQ (0 ,audit_cleanup (-1 ,NULL )); +} + +/* Test PTRACE_TRACEME and PTRACE_ATTACH for parent and child. */ +TEST_F(audit, trace) +{ +pid_t child, parent; +int status; +int pipe_child[2 ], pipe_parent[2 ]; +int yama_ptrace_scope; +char buf_parent; +struct audit_records records; + +/* Makes sure there is no superfluous logged records. */ +audit_count_records (self->audit_fd, &records); +EXPECT_EQ (0 , records.access); +EXPECT_EQ (0 , records.domain); + + yama_ptrace_scope =get_yama_ptrace_scope (); +ASSERT_LE (0 , yama_ptrace_scope); + +if (yama_ptrace_scope >YAMA_SCOPE_DISABLED ) +TH_LOG ("Incomplete tests due to Yama restrictions (scope %d)" , + yama_ptrace_scope); + +/* +* Removes all effective and permitted capabilities to not interfere +* with cap_ptrace_access_check() in case of PTRACE_MODE_FSCREDS. +*/ +drop_caps (_metadata); + + parent =getpid (); +ASSERT_EQ (0 ,pipe2 (pipe_child,O_CLOEXEC )); +ASSERT_EQ (0 ,pipe2 (pipe_parent,O_CLOEXEC )); + + child =fork (); +ASSERT_LE (0 , child); +if (child ==0 ) { +char buf_child; + +ASSERT_EQ (0 ,close (pipe_parent[1 ])); +ASSERT_EQ (0 ,close (pipe_child[0 ])); + +/* Waits for the parent to be in a domain, if any. */ +ASSERT_EQ (1 ,read (pipe_parent[0 ], &buf_child,1 )); + +/* Tests child PTRACE_TRACEME. */ +EXPECT_EQ (-1 ,ptrace (PTRACE_TRACEME )); +EXPECT_EQ (EPERM , errno); +/* We should indeed see the parent process. */ +matches_log_ptrace (_metadata, self->audit_fd, parent); + +audit_count_records (self->audit_fd, &records); +EXPECT_EQ (0 , records.access); +/* Checks for a domain creation. */ +EXPECT_EQ (1 , records.domain); + +/* +* Signals that the PTRACE_ATTACH test is done and the +* PTRACE_TRACEME test is ongoing. +*/ +ASSERT_EQ (1 ,write (pipe_child[1 ],"." ,1 )); + +/* Waits for the parent PTRACE_ATTACH test. */ +ASSERT_EQ (1 ,read (pipe_parent[0 ], &buf_child,1 )); +_exit (_metadata->exit_code); +return ; + } + +ASSERT_EQ (0 ,close (pipe_child[1 ])); +ASSERT_EQ (0 ,close (pipe_parent[0 ])); +create_domain (_metadata); + +/* Signals that the parent is in a domain. */ +ASSERT_EQ (1 ,write (pipe_parent[1 ],"." ,1 )); + +/* +* Waits for the child to test PTRACE_ATTACH on the parent and start +* testing PTRACE_TRACEME. +*/ +ASSERT_EQ (1 ,read (pipe_child[0 ], &buf_parent,1 )); + +/* The child should not be traced by the parent. */ +EXPECT_EQ (-1 ,ptrace (PTRACE_DETACH , child,NULL ,0 )); +EXPECT_EQ (ESRCH , errno); + +/* Tests PTRACE_ATTACH on the child. */ +EXPECT_EQ (-1 ,ptrace (PTRACE_ATTACH , child,NULL ,0 )); +EXPECT_EQ (EPERM , errno); +EXPECT_EQ (0 ,matches_log_ptrace (_metadata, self->audit_fd, child)); + +/* Signals that the parent PTRACE_ATTACH test is done. */ +ASSERT_EQ (1 ,write (pipe_parent[1 ],"." ,1 )); +ASSERT_EQ (child,waitpid (child, &status,0 )); +if (WIFSIGNALED (status) || !WIFEXITED (status) || +WEXITSTATUS (status) !=EXIT_SUCCESS ) + _metadata->exit_code =KSFT_FAIL ; + +/* Makes sure there is no superfluous logged records. */ +audit_count_records (self->audit_fd, &records); +EXPECT_EQ (0 , records.access); +EXPECT_EQ (0 , records.domain); +} +TEST_HARNESS_MAIN
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 24/26 selftests/landlock: Add audit tests for abstract unix socket scoping
In reply to Mickaël SalaünAdd a new scoped_uadit.connect_to_child test to check the abstract unix socket blocker.
---
Changes since v5:
- New patch.
--- .../landlock/scoped_abstract_unix_test.c | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+)
tools/testing/selftests/landlock/scoped_abstract_unix_test.c +121 -0
@@ -20,6 +20,7 @@#include <sys/wait.h> #include <unistd.h> +#include "audit.h" #include "common.h" #include "scoped_common.h"
@@ -267,6 +268,126 @@ TEST_F(scoped_domains, connect_to_child) _metadata->exit_code =KSFT_FAIL ; } +FIXTURE (scoped_audit) +{ +struct service_fixture dgram_address; +struct audit_filter audit_filter; +int audit_fd; +}; + +FIXTURE_SETUP (scoped_audit) +{ +disable_caps (_metadata); + +memset (&self->dgram_address,0 ,sizeof (self->dgram_address)); +set_unix_address (&self->dgram_address,1 ); + +set_cap (_metadata,CAP_AUDIT_CONTROL ); + self->audit_fd =audit_init_with_exe_filter (&self->audit_filter); +EXPECT_LE (0 , self->audit_fd); +drop_caps (_metadata); +} + +FIXTURE_TEARDOWN_PARENT (scoped_audit) +{ +EXPECT_EQ (0 ,audit_cleanup (-1 ,NULL )); +} + +/* python -c 'print(b"\0selftests-landlock-abstract-unix-".hex().upper())' */ +#define ABSTRACT_SOCKET_PATH_PREFIX \ + "0073656C6674657374732D6C616E646C6F636B2D61627374726163742D756E69782D" + +static int matches_log_abstract_socket (struct __test_metadata *const _metadata, +int audit_fd) +{ +static const char log_template[] =REGEX_LANDLOCK_PREFIX +" blockers=scope\\.abstract_unix_socket path=" ABSTRACT_SOCKET_PATH_PREFIX +"[0-9A-F]\\+$" ; +char log_match[sizeof (log_template) +10 ]; +int log_match_len; + + log_match_len =snprintf (log_match,sizeof (log_match), log_template); +if (log_match_len >sizeof (log_match)) +return -E2BIG ; + +return audit_match_record (audit_fd,AUDIT_LANDLOCK_ACCESS , log_match, +NULL ); +} + +/* +* Simpler version of scoped_domains.connect_to_child, but with audit tests. +*/ +TEST_F(scoped_audit, connect_to_child) +{ +pid_t child; +int err_dgram, status; +int pipe_child[2 ], pipe_parent[2 ]; +char buf; +int dgram_client; +struct audit_records records; + +/* Makes sure there is no superfluous logged records. */ +audit_count_records (self->audit_fd, &records); +EXPECT_EQ (0 , records.access); +EXPECT_EQ (0 , records.domain); + +ASSERT_EQ (0 ,pipe2 (pipe_child,O_CLOEXEC )); +ASSERT_EQ (0 ,pipe2 (pipe_parent,O_CLOEXEC )); + + child =fork (); +ASSERT_LE (0 , child); +if (child ==0 ) { +int dgram_server; + +EXPECT_EQ (0 ,close (pipe_parent[1 ])); +EXPECT_EQ (0 ,close (pipe_child[0 ])); + +/* Waits for the parent to be in a domain. */ +ASSERT_EQ (1 ,read (pipe_parent[0 ], &buf,1 )); + + dgram_server =socket (AF_UNIX ,SOCK_DGRAM ,0 ); +ASSERT_LE (0 , dgram_server); +ASSERT_EQ (0 ,bind (dgram_server, &self->dgram_address.unix_addr, + self->dgram_address.unix_addr_len)); + +/* Signals to the parent that child is listening. */ +ASSERT_EQ (1 ,write (pipe_child[1 ],"." ,1 )); + +/* Waits to connect. */ +ASSERT_EQ (1 ,read (pipe_parent[0 ], &buf,1 )); +EXPECT_EQ (0 ,close (dgram_server)); +_exit (_metadata->exit_code); +return ; + } +EXPECT_EQ (0 ,close (pipe_child[1 ])); +EXPECT_EQ (0 ,close (pipe_parent[0 ])); + +create_scoped_domain (_metadata,LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET ); + +/* Signals that the parent is in a domain, if any. */ +ASSERT_EQ (1 ,write (pipe_parent[1 ],"." ,1 )); + + dgram_client =socket (AF_UNIX ,SOCK_DGRAM ,0 ); +ASSERT_LE (0 , dgram_client); + +/* Waits for the child to listen */ +ASSERT_EQ (1 ,read (pipe_child[0 ], &buf,1 )); + err_dgram =connect (dgram_client, &self->dgram_address.unix_addr, + self->dgram_address.unix_addr_len); +EXPECT_EQ (-1 , err_dgram); +EXPECT_EQ (EPERM , errno); + +EXPECT_EQ (0 ,matches_log_abstract_socket (_metadata, self->audit_fd)); + +ASSERT_EQ (1 ,write (pipe_parent[1 ],"." ,1 )); +EXPECT_EQ (0 ,close (dgram_client)); + +ASSERT_EQ (child,waitpid (child, &status,0 )); +if (WIFSIGNALED (status) || !WIFEXITED (status) || +WEXITSTATUS (status) !=EXIT_SUCCESS ) + _metadata->exit_code =KSFT_FAIL ; +} +FIXTURE (scoped_vs_unscoped) { struct service_fixture parent_stream_address, parent_dgram_address,
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 25/26 selftests/landlock: Add audit tests for filesystem
In reply to Mickaël SalaünTest all filesystem blockers, including events with several records, and record with several blockers:
- fs.execute
- fs.write_file
- fs.read_file
- fs_read_dir
- fs.remove_dir
- fs.remove_file
- fs.make_char
- fs.make_dir
- fs.make_reg
- fs.make_sock
- fs.make_fifo
- fs.make_block
- fs.make_sym
- fs.refer
- fs.truncate
- fs.ioctl_dev
Test coverage for security/landlock is 93.4% of 1407 lines according to gcc/gcov-14.
---
Changes since v5:
- New patch.
--- tools/testing/selftests/landlock/audit.h | 39 ++ tools/testing/selftests/landlock/common.h | 16 + tools/testing/selftests/landlock/fs_test.c | 455 +++++++++++++++++++++ 3 files changed, 510 insertions(+)
tools/testing/selftests/landlock/audit.h +39 -0
@@ -22,6 +22,10 @@#define ARRAY_SIZE (arr) (sizeof(arr) / sizeof((arr)[0]))#endif +#ifndef __maybe_unused +#define __maybe_unused __attribute__((__unused__)) +#endif +#define REGEX_LANDLOCK_PREFIX "^audit([0-9.:]\\+): domain=\\([0-9a-f]\\+\\)"struct audit_filter {
@@ -188,6 +192,41 @@ static int audit_set_status(int fd, __u32 key, __u32 val)return audit_request (fd, &msg,NULL ); } +/* Returns a pointer to the last filled character of @dst, which is `\0`. */ +static __maybe_unused char *regex_escape (const char *const src,char *dst, +size_t dst_size) +{ +char *d = dst; + +for (const char *s = src; *s; s++) { +switch (*s) { +case '$' : +case '*' : +case '.' : +case '[' : +case '\\' : +case ']' : +case '^' : +if (d >= dst + dst_size -2 ) +return (char *)-ENOMEM ; + + *d++ ='\\' ; + *d++ = *s; +break ; +default : +if (d >= dst + dst_size -1 ) +return (char *)-ENOMEM ; + + *d++ = *s; + } + } +if (d >= dst + dst_size -1 ) +return (char *)-ENOMEM ; + + *d ='\0' ; +return d; +} +/* * @domain_id: The domain ID extracted from the audit message (if the first part * of @pattern is REGEX_LANDLOCK_PREFIX). It is set to 0 if the domain ID is
tools/testing/selftests/landlock/common.h +16 -0
@@ -207,6 +207,22 @@ enforce_ruleset(struct __test_metadata *const _metadata, const int ruleset_fd) } } +static void __maybe_unused +drop_access_rights (struct __test_metadata *const _metadata, +const struct landlock_ruleset_attr *const ruleset_attr) +{ +int ruleset_fd; + + ruleset_fd = +landlock_create_ruleset (ruleset_attr,sizeof (*ruleset_attr),0 ); + EXPECT_LE(0, ruleset_fd) + { +TH_LOG ("Failed to create a ruleset: %s" ,strerror (errno)); + } +enforce_ruleset (_metadata, ruleset_fd); +EXPECT_EQ (0 ,close (ruleset_fd)); +} +struct protocol_variant {int domain;int type;
tools/testing/selftests/landlock/fs_test.c +455 -0
465 lines not on this page · raw message
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerPATCH v6 26/26 landlock: Add audit documentation
In reply to Mickaël SalaünBecause audit is dedicated to the system administrator, create a new entry in Documentation/admin-guide/LSM .
Extend other Landlock documentation's pages with this new one.
Extend the guiding principles with logs.
---
Changes since v5:
- Extend the guiding principles with logs.
Changes since v4:
- New patch.
--- Documentation/admin-guide/LSM/index.rst | 1 + Documentation/admin-guide/LSM/landlock.rst | 158 +++++++++++++++++++++ Documentation/security/landlock.rst | 13 +- Documentation/userspace-api/landlock.rst | 9 +- MAINTAINERS | 1 + 5 files changed, 180 insertions(+), 2 deletions(-) create mode 100644 Documentation/admin-guide/LSM/landlock.rst
Documentation/admin-guide/LSM/index.rst +1 -0
@@ -48,3 +48,4 @@ subdirectories. Yama SafeSetID ipe + landlock
Documentation/admin-guide/LSM/landlock.rst new file +158 -0
158 lines not on this page · raw message
Documentation/security/landlock.rst +12 -1
@@ -7,7 +7,7 @@ Landlock LSM: kernel documentation ================================== :Author: Mickaël Salaün -:Date: December 2022 +:Date: March 2025 Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process,
@@ -45,6 +45,10 @@ Guiding principles for safe access controls sandboxed process shall retain their scoped accesses (at the time of resource acquisition) whatever process uses them. Cf. `File descriptor access rights`_. +* Access denials shall be logged according to system and Landlock domain + configurations. Log entries must contain information about the cause of the + denial and the owner of the related security policy. Such log generation + should have a negligible performance and memory impact on allowed requests. Design choices ==============
@@ -124,6 +128,13 @@ makes the reasoning much easier and helps avoid pitfalls. .. kernel-doc:: security/landlock/ruleset.h :identifiers: +Additional documentation +======================== + +* Documentation/userspace-api/landlock.rst +* Documentation/admin-guide/LSM/landlock.rst +* https://landlock.io + .. Links .. _tools/testing/selftests/landlock/: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/landlock/
Documentation/userspace-api/landlock.rst +8 -1
@@ -8,7 +8,7 @@ Landlock: unprivileged access control ===================================== :Author: Mickaël Salaün -:Date: January 2025 +:Date: March 2025 The goal of Landlock is to enable restriction of ambient rights (e.g. global filesystem or network access) for a set of processes. Because Landlock
@@ -683,9 +683,16 @@ fine-grained restrictions). Moreover, their complexity can lead to security issues, especially when untrusted processes can manipulate them (cf. `Controlling access to user namespaces <https://lwn.net/Articles/673597/>`_). +How to disable Landlock audit records? +-------------------------------------- + +You might want to put in place filters as explained here: +Documentation/admin-guide/LSM/landlock.rst + Additional documentation ======================== +* Documentation/admin-guide/LSM/landlock.rst * Documentation/security/landlock.rst * https://landlock.io
MAINTAINERS +1 -0
@@ -13075,6 +13075,7 @@ L: [email protected] S: Supported W: https://landlock.io T: git https://git.kernel.org/pub/scm/linux/kernel/git/mic/linux.git +F: Documentation/admin-guide/LSM/landlock.rst F: Documentation/security/landlock.rst F: Documentation/userspace-api/landlock.rst F: fs/ioctl.c
Signature · 1 line
2.48.1
Mickaël Salaün
maintainerQuoted 30 lines · Mickaël Salaün
Hi,
This patch series adds audit support to Landlock.
Logging denied requests is useful for different use cases:
- sysadmins: to look for users' issues,
- security experts: to detect attack attempts,
- power users: to understand denials,
- developers: to ease sandboxing support and get feedback from users.Because of its unprivileged nature, Landlock can compose standalone security policies (i.e. domains). To make logs useful, they need to contain the most relevant Landlock domain that denied an action, and the reason of such denial. This translates to the latest nested domain and the related blockers: missing access rights or other kind of restrictions.
# Main changes from previous version
Renamed the
landlock_restrict_self(2)flags to improve clarity and consistency, and slightly change the semantic of the first one:
-LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF: do not log denied access caused by a task with the same executable (i.e. before any new execve(2));
-LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC_ON: log denied access for processes resulting from an execve(2), which is not the case by default.
-LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF: do not log denied access from future nested domains.
Quoted 2 lines
These new
LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFFandLANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC_ONare not incompatible anymore.
As you can see in the patches, it's not LANDLOCK_RESTRICT_SELF_LOG_CROSS_EXEC_ON but LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON now. I think "new_exec" makes more sense than "cross_exec", especially compared to "same_exec", but I'm open to suggestions.
Anyway, this patch series should land Monday in linux-next. In the meantime you can find it here:
https://web.git.kernel.org/pub/scm/linux/kernel/git/mic/linux.git/log/?h=next