xref: /linux/Documentation/userspace-api/landlock.rst (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1.. SPDX-License-Identifier: GPL-2.0
2.. Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net>
3.. Copyright © 2019-2020 ANSSI
4.. Copyright © 2021-2022 Microsoft Corporation
5
6=====================================
7Landlock: unprivileged access control
8=====================================
9
10:Author: Mickaël Salaün
11:Date: August 2026
12
13The goal of Landlock is to enable restriction of ambient rights (e.g. global
14filesystem or network access) for a set of processes.  Because Landlock
15is a stackable LSM, it makes it possible to create safe security sandboxes as
16new security layers in addition to the existing system-wide access-controls.
17This kind of sandbox is expected to help mitigate the security impact of bugs or
18unexpected/malicious behaviors in user space applications.  Landlock empowers
19any process, including unprivileged ones, to securely restrict themselves.
20
21We can quickly make sure that Landlock is enabled in the running system by
22looking for "landlock: Up and running" in kernel logs (as root):
23``dmesg | grep landlock || journalctl -kb -g landlock`` .
24Developers can also easily check for Landlock support with a
25:ref:`related system call <landlock_abi_versions>`.
26If Landlock is not currently supported, we need to
27:ref:`configure the kernel appropriately <kernel_support>`.
28
29Landlock rules
30==============
31
32A Landlock rule describes an action on an object which the process intends to
33perform.  A set of rules is aggregated in a ruleset, which can then restrict
34the thread enforcing it, and its future children.
35
36The two existing types of rules are:
37
38Filesystem rules
39    For these rules, the object is a file hierarchy,
40    and the related filesystem actions are defined with
41    `filesystem access rights`.
42
43Network rules (since ABI v4 for TCP and v10 for UDP)
44    For these rules, the object is a TCP or UDP port,
45    and the related actions are defined with `network access rights`.
46
47Defining and enforcing a security policy
48----------------------------------------
49
50We first need to define the ruleset that will contain our rules.
51
52For this example, the ruleset will contain rules that only allow some
53filesystem read actions and some specific UDP and TCP actions. Filesystem
54write actions and other TCP/UDP actions will be denied.
55
56The ruleset then needs to handle all these kinds of actions.  This is
57required for backward and forward compatibility (i.e. the kernel and user
58space may not know each other's supported restrictions), hence the need
59to be explicit about the denied-by-default access rights.
60
61.. code-block:: c
62
63    struct landlock_ruleset_attr ruleset_attr = {
64        .handled_access_fs =
65            LANDLOCK_ACCESS_FS_EXECUTE |
66            LANDLOCK_ACCESS_FS_WRITE_FILE |
67            LANDLOCK_ACCESS_FS_READ_FILE |
68            LANDLOCK_ACCESS_FS_READ_DIR |
69            LANDLOCK_ACCESS_FS_REMOVE_DIR |
70            LANDLOCK_ACCESS_FS_REMOVE_FILE |
71            LANDLOCK_ACCESS_FS_MAKE_CHAR |
72            LANDLOCK_ACCESS_FS_MAKE_DIR |
73            LANDLOCK_ACCESS_FS_MAKE_REG |
74            LANDLOCK_ACCESS_FS_MAKE_SOCK |
75            LANDLOCK_ACCESS_FS_MAKE_FIFO |
76            LANDLOCK_ACCESS_FS_MAKE_BLOCK |
77            LANDLOCK_ACCESS_FS_MAKE_SYM |
78            LANDLOCK_ACCESS_FS_REFER |
79            LANDLOCK_ACCESS_FS_TRUNCATE |
80            LANDLOCK_ACCESS_FS_IOCTL_DEV |
81            LANDLOCK_ACCESS_FS_RESOLVE_UNIX,
82        .handled_access_net =
83            LANDLOCK_ACCESS_NET_BIND_TCP |
84            LANDLOCK_ACCESS_NET_CONNECT_TCP |
85            LANDLOCK_ACCESS_NET_BIND_UDP |
86            LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP,
87        .scoped =
88            LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
89            LANDLOCK_SCOPE_SIGNAL,
90    };
91
92Because we may not know which kernel version an application will be executed
93on, it is safer to follow a best-effort security approach.  Indeed, we
94should try to protect users as much as possible whatever the kernel they are
95using.
96
97To be compatible with older Linux versions, we detect the available Landlock ABI
98version, and only use the available subset of access rights:
99
100.. code-block:: c
101
102    int abi;
103
104    abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
105    if (abi < 0) {
106        /* Degrades gracefully if Landlock is not handled. */
107        perror("The running kernel does not enable to use Landlock");
108        return 0;
109    }
110    switch (abi) {
111    case 1:
112        /* Removes LANDLOCK_ACCESS_FS_REFER for ABI < 2 */
113        ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_REFER;
114        __attribute__((fallthrough));
115    case 2:
116        /* Removes LANDLOCK_ACCESS_FS_TRUNCATE for ABI < 3 */
117        ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
118        __attribute__((fallthrough));
119    case 3:
120        /* Removes network support for ABI < 4 */
121        ruleset_attr.handled_access_net &=
122            ~(LANDLOCK_ACCESS_NET_BIND_TCP |
123              LANDLOCK_ACCESS_NET_CONNECT_TCP);
124        __attribute__((fallthrough));
125    case 4:
126        /* Removes LANDLOCK_ACCESS_FS_IOCTL_DEV for ABI < 5 */
127        ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_IOCTL_DEV;
128        __attribute__((fallthrough));
129    case 5:
130        /* Removes LANDLOCK_SCOPE_* for ABI < 6 */
131        ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
132                                 LANDLOCK_SCOPE_SIGNAL);
133        __attribute__((fallthrough));
134    case 6 ... 8:
135        /* Removes LANDLOCK_ACCESS_FS_RESOLVE_UNIX for ABI < 9 */
136        ruleset_attr.handled_access_fs &= ~LANDLOCK_ACCESS_FS_RESOLVE_UNIX;
137        __attribute__((fallthrough));
138    case 9:
139        /* Removes LANDLOCK_ACCESS_NET_*_UDP for ABI < 10 */
140        ruleset_attr.handled_access_net &=
141            ~(LANDLOCK_ACCESS_NET_BIND_UDP |
142              LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP);
143    }
144
145This enables the creation of an inclusive ruleset that will contain our rules.
146
147.. code-block:: c
148
149    int ruleset_fd;
150
151    ruleset_fd = landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
152    if (ruleset_fd < 0) {
153        perror("Failed to create a ruleset");
154        return 1;
155    }
156
157We can now add a new rule to this ruleset thanks to the returned file
158descriptor referring to this ruleset.  The rule will allow reading and
159executing the file hierarchy ``/usr``.  Without another rule, write actions
160would then be denied by the ruleset.  To add ``/usr`` to the ruleset, we open
161it with the ``O_PATH`` flag and fill the &struct landlock_path_beneath_attr with
162this file descriptor.
163
164.. code-block:: c
165
166    int err = 0;
167    struct landlock_path_beneath_attr path_beneath = {
168        .allowed_access =
169            LANDLOCK_ACCESS_FS_EXECUTE |
170            LANDLOCK_ACCESS_FS_READ_FILE |
171            LANDLOCK_ACCESS_FS_READ_DIR,
172    };
173
174    path_beneath.allowed_access &= ruleset_attr.handled_access_fs;
175    if (path_beneath.allowed_access) {
176        path_beneath.parent_fd = open("/usr", O_PATH | O_CLOEXEC);
177        if (path_beneath.parent_fd < 0) {
178            perror("Failed to open file");
179            close(ruleset_fd);
180            return 1;
181        }
182        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
183                                &path_beneath, 0);
184        close(path_beneath.parent_fd);
185        if (err) {
186            perror("Failed to update ruleset");
187            close(ruleset_fd);
188            return 1;
189        }
190    }
191
192As shown above, masking the rule's ``allowed_access`` against the ruleset's
193``handled_access_*`` is the recommended best-effort pattern: rights the running
194kernel does not support are dropped (the compatibility switch above already
195cleared them in ``handled_access_*``), and the rule is skipped if no supported
196right remains.
197
198For network access-control, we will add a set of rules to allow DNS
199queries, which requires both UDP and TCP. For TCP, we need to allow
200outbound connections to port 53, which can be handled and granted starting
201with ABI 4:
202
203.. code-block:: c
204
205    struct landlock_net_port_attr tcp_conn = {
206        .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
207        .port = 53,
208    };
209
210    tcp_conn.allowed_access &= ruleset_attr.handled_access_net;
211    if (tcp_conn.allowed_access)
212        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
213                                &tcp_conn, 0);
214
215We also need to be able to send UDP datagrams to port 53, which requires
216granting ``LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP``. Since our DNS client will
217emit datagrams without explicitly binding to a specific source port, its UDP
218socket will automatically bind an ephemeral port. To allow this behaviour,
219we also need to grant ``LANDLOCK_ACCESS_NET_BIND_UDP`` on port 0, as if
220the program explicitly called :manpage:`bind(2)` on port 0.
221
222.. code-block:: c
223
224    struct landlock_net_port_attr udp_send = {
225        .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP,
226        .port = 53,
227    };
228
229    udp_send.allowed_access &= ruleset_attr.handled_access_net;
230    if (udp_send.allowed_access)
231        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
232                                &udp_send, 0);
233    [...]
234
235    struct landlock_net_port_attr udp_bind = {
236        .allowed_access = LANDLOCK_ACCESS_NET_BIND_UDP,
237        .port = 0,
238    };
239
240    udp_bind.allowed_access &= ruleset_attr.handled_access_net;
241    if (udp_bind.allowed_access)
242        err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
243                                &udp_bind, 0);
244
245When passing a non-zero ``flags`` argument to ``landlock_restrict_self()``, a
246similar backwards compatibility check is needed for the restrict flags
247(see sys_landlock_restrict_self() documentation for available flags):
248
249.. code-block:: c
250
251    __u32 restrict_flags =
252        LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON |
253        LANDLOCK_RESTRICT_SELF_TSYNC |
254        LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS;
255    switch (abi) {
256    case 1 ... 6:
257        /* Removes logging flags for ABI < 7 */
258        restrict_flags &= ~(LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF |
259                            LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON |
260                            LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF);
261        __attribute__((fallthrough));
262    case 7:
263        /*
264         * Removes multithreaded enforcement flag for ABI < 8
265         *
266         * WARNING: Without this flag, calling landlock_restrict_self(2) is
267         * only equivalent if the calling process is single-threaded. Below
268         * ABI v8 (and as of ABI v8, when not using this flag), a Landlock
269         * policy would only be enforced for the calling thread and its
270         * children (and not for all threads, including parents and siblings).
271         */
272        restrict_flags &= ~LANDLOCK_RESTRICT_SELF_TSYNC;
273        __attribute__((fallthrough));
274    case 8 ... 10:
275        /* Removes no new privs flag for ABI < 11 */
276        restrict_flags &= ~LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS;
277    }
278
279The next step is to restrict the current thread from gaining more privileges
280(e.g. through a SUID binary).  For unprivileged processes, setting the
281no_new_privs attribute is required by Landlock.
282
283Processes with ``CAP_SYS_ADMIN`` in their namespace can enforce a ruleset
284without setting no_new_privs, but leaving no_new_privs unset is risky even
285when Landlock does not require this attribute: sandboxed processes could
286still execute set-user-ID, set-group-ID or file-capability binaries, which
287would then run with elevated privileges while being restricted by a Landlock
288domain they may not expect, making them potential confused deputies.
289no_new_privs should only be left unset if such a privilege transition is
290expected.
291
292We now have a ruleset with the first rule allowing read and execute access to
293``/usr`` while denying all other handled accesses for the filesystem, and two
294more rules allowing DNS queries.
295
296.. code-block:: c
297
298    /*
299     * If the ABI > 10, we can tie setting no_new_privs with successful ruleset
300     * enforcement and skip the manual prctl(PR_SET_NO_NEW_PRIVS, ...) call.
301     */
302    if (!(restrict_flags & LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS) &&
303        prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
304        perror("Failed to restrict privileges");
305        close(ruleset_fd);
306        return 1;
307    }
308
309The current thread is now ready to sandbox itself with the ruleset.
310
311.. code-block:: c
312
313    if (landlock_restrict_self(ruleset_fd, restrict_flags)) {
314        perror("Failed to enforce ruleset");
315        close(ruleset_fd);
316        return 1;
317    }
318    close(ruleset_fd);
319
320If the ``landlock_restrict_self`` system call succeeds, the current thread is
321now restricted and this policy will be enforced on all its subsequently created
322children as well.  Once a thread is landlocked, there is no way to remove its
323security policy; only adding more restrictions is allowed.  These threads are
324now in a new Landlock domain, which is a merger of their parent one (if any)
325with the new ruleset.
326
327Full working code can be found in `samples/landlock/sandboxer.c`_.
328
329Good practices
330--------------
331
332It is recommended to set access rights to file hierarchy leaves as much as
333possible.  For instance, it is better to be able to have ``~/doc/`` as a
334read-only hierarchy and ``~/tmp/`` as a read-write hierarchy, compared to
335``~/`` as a read-only hierarchy and ``~/tmp/`` as a read-write hierarchy.
336Following this good practice leads to self-sufficient hierarchies that do not
337depend on their location (i.e. parent directories).  This is particularly
338relevant when we want to allow linking or renaming.  Indeed, having consistent
339access rights per directory enables changing the location of such directories
340without relying on the destination directory access rights (except those that
341are required for this operation, see ``LANDLOCK_ACCESS_FS_REFER``
342documentation).
343
344Having self-sufficient hierarchies also helps to tighten the required access
345rights to the minimal set of data.  This also helps avoid sinkhole directories,
346i.e. directories where data can be linked to but not linked from.  However,
347this depends on data organization, which might not be controlled by developers.
348In this case, granting read-write access to ``~/tmp/``, instead of write-only
349access, would potentially allow moving ``~/tmp/`` to a non-readable directory
350and still keep the ability to list the content of ``~/tmp/``.
351
352Layers of file path access rights
353---------------------------------
354
355Each time a thread enforces a ruleset on itself, it updates its Landlock domain
356with a new layer of policy.  This complementary policy is stacked with any
357other rulesets potentially already restricting this thread.  A sandboxed thread
358can then safely add more constraints to itself with a new enforced ruleset.
359
360One policy layer grants access to a file path if at least one of its rules
361encountered on the path grants the access.  A sandboxed thread can only access
362a file path if all its enforced policy layers grant the access as well as all
363the other system access controls (e.g. filesystem DAC, other LSM policies,
364etc.).
365
366Bind mounts and OverlayFS
367-------------------------
368
369Landlock enables restricting access to file hierarchies, which means that these
370access rights can be propagated with bind mounts (cf.
371Documentation/filesystems/sharedsubtree.rst) but not with
372Documentation/filesystems/overlayfs.rst.
373
374A bind mount mirrors a source file hierarchy to a destination.  The destination
375hierarchy is then composed of the exact same files, on which Landlock rules can
376be tied, either via the source or the destination path.  These rules restrict
377access when they are encountered on a path, which means that they can restrict
378access to multiple file hierarchies at the same time, whether these hierarchies
379are the result of bind mounts or not.
380
381An OverlayFS mount point consists of upper and lower layers.  These layers are
382combined in a merge directory, and that merged directory becomes available at
383the mount point.  This merge hierarchy may include files from the upper and
384lower layers, but modifications performed on the merge hierarchy only reflect
385on the upper layer.  From a Landlock policy point of view, all OverlayFS layers
386and merge hierarchies are standalone and each contains their own set of files
387and directories, which is different from bind mounts.  A policy restricting an
388OverlayFS layer will not restrict the resulted merged hierarchy, and vice versa.
389Landlock users should then only think about file hierarchies they want to allow
390access to, regardless of the underlying filesystem.
391
392Inheritance
393-----------
394
395Every new thread resulting from a :manpage:`clone(2)` inherits Landlock domain
396restrictions from its parent.  This is similar to seccomp inheritance (cf.
397Documentation/userspace-api/seccomp_filter.rst) or any other LSM dealing with
398task's :manpage:`credentials(7)`.  For instance, one process's thread may apply
399Landlock rules to itself, but they will not be automatically applied to other
400sibling threads (unlike POSIX thread credential changes, cf.
401:manpage:`nptl(7)`).
402
403When a thread sandboxes itself, we have the guarantee that the related security
404policy will stay enforced on all this thread's descendants.  This allows
405creating standalone and modular security policies per application, which will
406automatically be composed between themselves according to their runtime parent
407policies.
408
409Ptrace restrictions
410-------------------
411
412A sandboxed process has less privileges than a non-sandboxed process and must
413then be subject to additional restrictions when manipulating another process.
414To be allowed to use :manpage:`ptrace(2)` and related syscalls on a target
415process, a sandboxed process should have a superset of the target process's
416access rights, which means the tracee must be in a sub-domain of the tracer.
417
418IPC scoping
419-----------
420
421Similar to the implicit `Ptrace restrictions`_, we may want to further restrict
422interactions between sandboxes.  Therefore, at ruleset creation time, each
423Landlock domain can restrict the scope for certain operations, so that these
424operations can only reach out to processes within the same Landlock domain or in
425a nested Landlock domain (the "scope").
426
427The operations which can be scoped are:
428
429``LANDLOCK_SCOPE_SIGNAL``
430    This limits the sending of signals to target processes which run within the
431    same or a nested Landlock domain.
432
433``LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET``
434    This limits the set of abstract :manpage:`unix(7)` sockets to which we can
435    :manpage:`connect(2)` to socket addresses which were created by a process in
436    the same or a nested Landlock domain.
437
438    A :manpage:`sendto(2)` on a non-connected datagram socket is treated as if
439    it were doing an implicit :manpage:`connect(2)` and will be blocked if the
440    remote end does not stem from the same or a nested Landlock domain.
441
442    A :manpage:`sendto(2)` on a socket which was previously connected will not
443    be restricted.  This works for both datagram and stream sockets.
444
445IPC scoping does not support exceptions via :manpage:`landlock_add_rule(2)`.
446If an operation is scoped within a domain, no rules can be added to allow access
447to resources or processes outside of the scope.
448
449Truncating files
450----------------
451
452The operations covered by ``LANDLOCK_ACCESS_FS_WRITE_FILE`` and
453``LANDLOCK_ACCESS_FS_TRUNCATE`` both change the contents of a file and sometimes
454overlap in non-intuitive ways.  It is strongly recommended to always specify
455both of these together (either granting both, or granting none).
456
457A particularly surprising example is :manpage:`creat(2)`.  The name suggests
458that this system call requires the rights to create and write files.  However,
459it also requires the truncate right if an existing file under the same name is
460already present.
461
462It should also be noted that truncating files does not require the
463``LANDLOCK_ACCESS_FS_WRITE_FILE`` right.  Apart from the :manpage:`truncate(2)`
464system call, this can also be done through :manpage:`open(2)` with the flags
465``O_RDONLY | O_TRUNC``.
466
467At the same time, on some filesystems, :manpage:`fallocate(2)` offers a way to
468shorten file contents with ``FALLOC_FL_COLLAPSE_RANGE`` when the file is opened
469for writing, sidestepping the ``LANDLOCK_ACCESS_FS_TRUNCATE`` right.
470
471The truncate right is associated with the opened file (see below).
472
473Rights associated with file descriptors
474---------------------------------------
475
476When opening a file, the availability of the ``LANDLOCK_ACCESS_FS_TRUNCATE`` and
477``LANDLOCK_ACCESS_FS_IOCTL_DEV`` rights is associated with the newly created
478file descriptor and will be used for subsequent truncation and ioctl attempts
479using :manpage:`ftruncate(2)` and :manpage:`ioctl(2)`.  The behavior is similar
480to opening a file for reading or writing, where permissions are checked during
481:manpage:`open(2)`, but not during the subsequent :manpage:`read(2)` and
482:manpage:`write(2)` calls.
483
484As a consequence, it is possible that a process has multiple open file
485descriptors referring to the same file, but Landlock enforces different things
486when operating with these file descriptors.  This can happen when a Landlock
487ruleset gets enforced and the process keeps file descriptors which were opened
488both before and after the enforcement.  It is also possible to pass such file
489descriptors between processes, keeping their Landlock properties, even when some
490of the involved processes do not have an enforced Landlock ruleset.
491
492Compatibility
493=============
494
495Backward and forward compatibility
496----------------------------------
497
498Landlock is designed to be compatible with past and future versions of the
499kernel.  This is achieved thanks to the system call attributes and the
500associated bitflags, particularly the ruleset's ``handled_access_fs``.  Making
501handled access rights explicit enables the kernel and user space to have a clear
502contract with each other.  This is required to make sure sandboxing will not
503get stricter with a system update, which could break applications.
504
505Developers can subscribe to the `Landlock mailing list
506<https://subspace.kernel.org/lists.linux.dev.html>`_ to knowingly update and
507test their applications with the latest available features.  In the interest of
508users, and because they may use different kernel versions, it is strongly
509encouraged to follow a best-effort security approach by checking the Landlock
510ABI version at runtime and only enforcing the supported features.
511
512.. _landlock_abi_versions:
513
514Landlock ABI versions
515---------------------
516
517The Landlock ABI version can be read with the sys_landlock_create_ruleset()
518system call:
519
520.. code-block:: c
521
522    int abi;
523
524    abi = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
525    if (abi < 0) {
526        switch (errno) {
527        case ENOSYS:
528            printf("Landlock is not supported by the current kernel.\n");
529            break;
530        case EOPNOTSUPP:
531            printf("Landlock is currently disabled.\n");
532            break;
533        }
534        return 0;
535    }
536    if (abi >= 2) {
537        printf("Landlock supports LANDLOCK_ACCESS_FS_REFER.\n");
538    }
539
540All Landlock kernel interfaces are supported by the first ABI version unless
541explicitly noted in their documentation.
542
543Landlock errata
544---------------
545
546In addition to ABI versions, Landlock provides an errata mechanism to track
547fixes for issues that may affect backwards compatibility or require userspace
548awareness.  The errata bitmask can be queried using:
549
550.. code-block:: c
551
552    int errata;
553
554    errata = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_ERRATA);
555    if (errata < 0) {
556        /* Landlock not available or disabled */
557        return 0;
558    }
559
560The returned value is a bitmask where each bit represents a specific erratum.
561If bit N is set (``errata & (1 << (N - 1))``), then erratum N has been fixed
562in the running kernel.
563
564.. warning::
565
566   **Most applications should NOT check errata.** In 99.9% of cases, checking
567   errata is unnecessary, increases code complexity, and can potentially
568   decrease protection if misused.  For example, disabling the sandbox when an
569   erratum is not fixed could leave the system less secure than using
570   Landlock's best-effort protection.  When in doubt, ignore errata.
571
572.. kernel-doc:: security/landlock/errata/abi-4.h
573    :doc: erratum_1
574
575.. kernel-doc:: security/landlock/errata/abi-6.h
576    :doc: erratum_2
577
578.. kernel-doc:: security/landlock/errata/abi-1.h
579    :doc: erratum_3
580
581.. kernel-doc:: security/landlock/errata/abi-1.h
582    :doc: erratum_4
583
584How to check for errata
585~~~~~~~~~~~~~~~~~~~~~~~
586
587If you determine that your application needs to check for specific errata,
588use this pattern:
589
590.. code-block:: c
591
592    int errata = landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_ERRATA);
593    if (errata >= 0) {
594        /* Check for specific erratum (1-indexed) */
595        if (errata & (1 << (erratum_number - 1))) {
596            /* Erratum N is fixed in this kernel */
597        } else {
598            /* Erratum N is NOT fixed - consider implications for your use case */
599        }
600    }
601
602**Important:** Only check errata if your application specifically relies on
603behavior that changed due to the fix.  The fixes generally make Landlock less
604restrictive or more correct, not more restrictive.
605
606Kernel interface
607================
608
609Access rights
610-------------
611
612.. kernel-doc:: include/uapi/linux/landlock.h
613    :identifiers: fs_access net_access scope
614
615Creating a new ruleset
616----------------------
617
618.. kernel-doc:: security/landlock/syscalls.c
619    :identifiers: sys_landlock_create_ruleset
620
621.. kernel-doc:: include/uapi/linux/landlock.h
622    :identifiers: landlock_ruleset_attr
623
624Extending a ruleset
625-------------------
626
627.. kernel-doc:: security/landlock/syscalls.c
628    :identifiers: sys_landlock_add_rule
629
630.. kernel-doc:: include/uapi/linux/landlock.h
631    :identifiers: landlock_rule_type landlock_path_beneath_attr
632                  landlock_net_port_attr
633
634Enforcing a ruleset
635-------------------
636
637.. kernel-doc:: security/landlock/syscalls.c
638    :identifiers: sys_landlock_restrict_self
639
640Current limitations
641===================
642
643Filesystem topology modification
644--------------------------------
645
646Threads sandboxed with filesystem restrictions cannot modify filesystem
647topology, whether via :manpage:`mount(2)` or :manpage:`pivot_root(2)`.
648However, :manpage:`chroot(2)` calls are not denied.
649
650Special filesystems
651-------------------
652
653Access to regular files and directories can be restricted by Landlock,
654according to the handled accesses of a ruleset.  However, files that do not
655come from a user-visible filesystem (e.g. pipe, socket), but can still be
656accessed through ``/proc/<pid>/fd/*``, cannot currently be explicitly
657restricted.  Likewise, some special kernel filesystems such as nsfs, which can
658be accessed through ``/proc/<pid>/ns/*``, cannot currently be explicitly
659restricted.  However, thanks to the `ptrace restrictions`_, access to such
660sensitive ``/proc`` files are automatically restricted according to domain
661hierarchies.  Future Landlock evolutions could still enable to explicitly
662restrict such paths with dedicated ruleset flags.
663
664Ruleset layers
665--------------
666
667There is a limit of 16 layers of stacked rulesets.  This can be an issue for a
668task willing to enforce a new ruleset in complement to its 16 inherited
669rulesets.  Once this limit is reached, sys_landlock_restrict_self() returns
670E2BIG.  It is then strongly suggested to carefully build rulesets once in the
671life of a thread, especially for applications able to launch other applications
672that may also want to sandbox themselves (e.g. shells, container managers,
673etc.).
674
675Memory usage
676------------
677
678Kernel memory allocated to create rulesets is accounted and can be restricted
679by the Documentation/admin-guide/cgroup-v1/memory.rst.
680
681IOCTL support
682-------------
683
684The ``LANDLOCK_ACCESS_FS_IOCTL_DEV`` right restricts the use of
685:manpage:`ioctl(2)`, but it only applies to *newly opened* device files.  This
686means specifically that pre-existing file descriptors like stdin, stdout and
687stderr are unaffected.
688
689Users should be aware that TTY devices have traditionally permitted to control
690other processes on the same TTY through the ``TIOCSTI`` and ``TIOCLINUX`` IOCTL
691commands.  Both of these require ``CAP_SYS_ADMIN`` on modern Linux systems, but
692the behavior is configurable for ``TIOCSTI``.
693
694On older systems, it is therefore recommended to close inherited TTY file
695descriptors, or to reopen them from ``/proc/self/fd/*`` without the
696``LANDLOCK_ACCESS_FS_IOCTL_DEV`` right, if possible.
697
698Landlock's IOCTL support is coarse-grained at the moment, but may become more
699fine-grained in the future.  Until then, users are advised to establish the
700guarantees that they need through the file hierarchy, by only allowing the
701``LANDLOCK_ACCESS_FS_IOCTL_DEV`` right on files where it is really required.
702
703Previous limitations
704====================
705
706File renaming and linking (ABI < 2)
707-----------------------------------
708
709Because Landlock targets unprivileged access controls, it needs to properly
710handle composition of rules.  Such property also implies rules nesting.
711Properly handling multiple layers of rulesets, each one of them able to
712restrict access to files, also implies inheritance of the ruleset restrictions
713from a parent to its hierarchy.  Because files are identified and restricted by
714their hierarchy, moving or linking a file from one directory to another implies
715propagation of the hierarchy constraints, or restriction of these actions
716according to the potentially lost constraints.  To protect against privilege
717escalations through renaming or linking, and for the sake of simplicity,
718Landlock previously limited linking and renaming to the same directory.
719Starting with the Landlock ABI version 2, it is now possible to securely
720control renaming and linking thanks to the new ``LANDLOCK_ACCESS_FS_REFER``
721access right.
722
723File truncation (ABI < 3)
724-------------------------
725
726File truncation could not be denied before the third Landlock ABI, so it is
727always allowed when using a kernel that only supports the first or second ABI.
728
729Starting with the Landlock ABI version 3, it is now possible to securely control
730truncation thanks to the new ``LANDLOCK_ACCESS_FS_TRUNCATE`` access right.
731
732TCP bind and connect (ABI < 4)
733------------------------------
734
735Starting with the Landlock ABI version 4, it is now possible to restrict TCP
736bind and connect actions to only a set of allowed ports thanks to the new
737``LANDLOCK_ACCESS_NET_BIND_TCP`` and ``LANDLOCK_ACCESS_NET_CONNECT_TCP``
738access rights.
739
740Device IOCTL (ABI < 5)
741----------------------
742
743IOCTL operations could not be denied before the fifth Landlock ABI, so
744:manpage:`ioctl(2)` is always allowed when using a kernel that only supports an
745earlier ABI.
746
747Starting with the Landlock ABI version 5, it is possible to restrict the use of
748:manpage:`ioctl(2)` on character and block devices using the new
749``LANDLOCK_ACCESS_FS_IOCTL_DEV`` right.
750
751Abstract UNIX socket (ABI < 6)
752------------------------------
753
754Starting with the Landlock ABI version 6, it is possible to restrict
755connections to an abstract :manpage:`unix(7)` socket by setting
756``LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET`` to the ``scoped`` ruleset attribute.
757
758Signal (ABI < 6)
759----------------
760
761Starting with the Landlock ABI version 6, it is possible to restrict
762:manpage:`signal(7)` sending by setting ``LANDLOCK_SCOPE_SIGNAL`` to the
763``scoped`` ruleset attribute.
764
765.. _landlock_log_flags:
766
767Logging (ABI < 7)
768-----------------
769
770Starting with the Landlock ABI version 7, it is possible to control logging of
771Landlock audit events with the ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``,
772``LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON``, and
773``LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF`` flags passed to
774sys_landlock_restrict_self().  These flags control audit record generation.
775Landlock tracepoints are not affected by these flags and always fire when
776enabled, providing an alternative observability channel for debugging and
777monitoring.  See Documentation/admin-guide/LSM/landlock.rst for more
778details on audit and tracepoints, and
779Documentation/trace/events-landlock.rst for the complete trace event
780reference.
781
782Thread synchronization (ABI < 8)
783--------------------------------
784
785Starting with the Landlock ABI version 8, it is now possible to
786enforce Landlock rulesets across all threads of the calling process
787using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to
788sys_landlock_restrict_self().
789
790Pathname UNIX sockets (ABI < 9)
791-------------------------------
792
793Starting with the Landlock ABI version 9, it is possible to restrict
794connections to pathname UNIX domain sockets (:manpage:`unix(7)`) using
795the new ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX`` right.
796
797UDP bind, connect and send* (ABI < 10)
798--------------------------------------
799
800Starting with the Landlock ABI version 10, it is possible to restrict
801setting the local port of UDP sockets with the
802``LANDLOCK_ACCESS_NET_BIND_UDP`` right. This includes restricting the
803ability to trigger autobind of an ephemeral port by the kernel by e.g.
804sending a first datagram or setting the remote peer of a socket.
805The ``LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP`` right controls setting the
806remote port of UDP sockets (via :manpage:`connect(2)`), and sending
807datagrams to an explicit remote port (ignoring any destination set on
808UDP sockets, via e.g. :manpage:`sendto(2)`).
809
810Quiet rule flag (ABI < 10)
811--------------------------
812
813Starting with the Landlock ABI version 10, it is possible to selectively
814suppress logs for specific denied accesses on a per-object basis with
815the ``LANDLOCK_ADD_RULE_QUIET`` flag of sys_landlock_add_rule(), in
816combination with the ``quiet_access_fs`` and ``quiet_access_net`` fields
817of struct landlock_ruleset_attr.  It is also now possible to suppress
818logs for scope accesses via the ``quiet_scoped`` field of struct
819landlock_ruleset_attr.  The object is marked as quiet within a ruleset
820when at least one sys_landlock_add_rule() call is made for it with the
821``LANDLOCK_ADD_RULE_QUIET`` flag, additional add-rule calls for the same
822object without this flag do not clear it.
823
824no_new_privs flag (ABI < 11)
825----------------------------
826
827Starting with the Landlock ABI version 11, sys_landlock_restrict_self()
828accepts the ``LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS`` flag, which sets the
829no_new_privs attribute of the calling thread only once the enforcement of
830the ruleset succeeded: no_new_privs is set if and only if the call
831succeeds.  This removes the need for a prior :manpage:`prctl(2)`
832``PR_SET_NO_NEW_PRIVS`` call (or ``CAP_SYS_ADMIN`` use).  When combined
833with ``LANDLOCK_RESTRICT_SELF_TSYNC``, no_new_privs is set on all threads
834of the process.  As explained in the tutorial above, leaving no_new_privs
835unset is risky even when Landlock does not require it.
836
837.. _kernel_support:
838
839Kernel support
840==============
841
842Build time configuration
843------------------------
844
845Landlock was first introduced in Linux 5.13 but it must be configured at build
846time with ``CONFIG_SECURITY_LANDLOCK=y``.  Landlock must also be enabled at boot
847time like other security modules.  The list of security modules enabled by
848default is set with ``CONFIG_LSM``.  The kernel configuration should then
849contain ``CONFIG_LSM=landlock,[...]`` with ``[...]``  as the list of other
850potentially useful security modules for the running system (see the
851``CONFIG_LSM`` help).
852
853Boot time configuration
854-----------------------
855
856If the running kernel does not have ``landlock`` in ``CONFIG_LSM``, then we can
857enable Landlock by adding ``lsm=landlock,[...]`` to
858Documentation/admin-guide/kernel-parameters.rst in the boot loader
859configuration.
860
861For example, if the current built-in configuration is:
862
863.. code-block:: console
864
865    $ zgrep -h "^CONFIG_LSM=" "/boot/config-$(uname -r)" /proc/config.gz 2>/dev/null
866    CONFIG_LSM="lockdown,yama,integrity,apparmor"
867
868...and if the cmdline doesn't contain ``landlock`` either:
869
870.. code-block:: console
871
872    $ sed -n 's/.*\(\<lsm=\S\+\).*/\1/p' /proc/cmdline
873    lsm=lockdown,yama,integrity,apparmor
874
875...we should configure the boot loader to set a cmdline extending the ``lsm``
876list with the ``landlock,`` prefix::
877
878  lsm=landlock,lockdown,yama,integrity,apparmor
879
880After a reboot, we can check that Landlock is up and running by looking at
881kernel logs:
882
883.. code-block:: console
884
885    # dmesg | grep landlock || journalctl -kb -g landlock
886    [    0.000000] Command line: [...] lsm=landlock,lockdown,yama,integrity,apparmor
887    [    0.000000] Kernel command line: [...] lsm=landlock,lockdown,yama,integrity,apparmor
888    [    0.000000] LSM: initializing lsm=lockdown,capability,landlock,yama,integrity,apparmor
889    [    0.000000] landlock: Up and running.
890
891The kernel may be configured at build time to always load the ``lockdown`` and
892``capability`` LSMs.  In that case, these LSMs will appear at the beginning of
893the ``LSM: initializing`` log line as well, even if they are not configured in
894the boot loader.
895
896Network support
897---------------
898
899To be able to explicitly allow TCP or UDP operations (e.g., adding a network rule with
900``LANDLOCK_ACCESS_NET_BIND_TCP``), the kernel must support the TCP/IP protocol suite
901(``CONFIG_INET=y``).  Otherwise, sys_landlock_add_rule() returns an
902``EAFNOSUPPORT`` error, which can safely be ignored because this kind of TCP or UDP
903operation is already not possible.
904
905Questions and answers
906=====================
907
908What about user space sandbox managers?
909---------------------------------------
910
911Using user space processes to enforce restrictions on kernel resources can lead
912to race conditions or inconsistent evaluations (i.e. `Incorrect mirroring of
913the OS code and state
914<https://www.ndss-symposium.org/ndss2003/traps-and-pitfalls-practical-problems-system-call-interposition-based-security-tools/>`_).
915
916What about namespaces and containers?
917-------------------------------------
918
919Namespaces can help create sandboxes but they are not designed for
920access-control and then miss useful features for such use case (e.g. no
921fine-grained restrictions).  Moreover, their complexity can lead to security
922issues, especially when untrusted processes can manipulate them (cf.
923`Controlling access to user namespaces <https://lwn.net/Articles/673597/>`_).
924
925How to disable Landlock audit records?
926--------------------------------------
927
928You might want to put in place filters as explained here:
929Documentation/admin-guide/LSM/landlock.rst
930
931Additional documentation
932========================
933
934* Documentation/admin-guide/LSM/landlock.rst
935* Documentation/trace/events-landlock.rst
936* Documentation/security/landlock.rst
937* https://landlock.io
938
939.. Links
940.. _samples/landlock/sandboxer.c:
941   https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/samples/landlock/sandboxer.c
942