* Re: An opinion about Linux security
From: Timur Chernykh @ 2025-12-12 17:22 UTC (permalink / raw)
To: Paul Moore
Cc: Stephen Smalley, Casey Schaufler, torvalds, linux-security-module,
greg
In-Reply-To: <CAHC9VhSU5yLQkCchCMUx+OLk+_2YY=1fjzth4s+_ELwgXg5t-A@mail.gmail.com>
> While Timur was
> added to the conversation by someone, I don't see any mail from him in
> that thread.
I probably missed this thread.
> Beyond that, I'm a bit lost. As far as I can remember, and both lore
> and my own sent mail folder appear to support this, I've never
> commented on ESF. At this point I think Timur may be mistaken
> regarding my commenting on ESF, but if I am wrong please provide a
> lore link so I can refresh my memory.
Sorry for misleading you. My mistake, I should have checked the thread
first instead of relying on my memory.
> In this post Timur provides links to his ESF project on GitHub, but no
> patches.
Am I correct in understanding that any proposals and questions I'd
like to discuss with the maintainers and the community should start
with patches? Even if the goal isn't to implement a change right away,
but merely to evaluate the idea.
When I proposed the prototype, it seemed excessive to me to prepare
patches for something that could be "finished" at the idea stage.
On Fri, Dec 12, 2025 at 8:06 PM Paul Moore <paul@paul-moore.com> wrote:
>
> On Fri, Dec 12, 2025 at 11:12 AM Stephen Smalley
> <stephen.smalley.work@gmail.com> wrote:
> > On Fri, Dec 12, 2025 at 9:47 AM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
> > >
> > > I’m lucky enough to have already built a working prototype, which I
> > > once offered for review:
> > >
> > > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> > > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
> > >
> > > Less lucky was the reaction I received. Paul Moore was strongly
> > > opposed, as far as I remember. Dr. Greg once said that heat death of
> > > the universe is more likely than this approach being accepted into the
> > > kernel.
> >
> > Not seeing an actual response from Paul in the archives, but did you
> > ever actually post patches to the list?
>
> I was wondering about this too. I searched through my sent mail and
> while it's possible I'm missing some mail, the only conversation I see
> with Timur is an off-list discussion from 2024 regarding changes in
> the upstream kernel to support out-of-tree LSMs. While Timur was
> added to the conversation by someone, I don't see any mail from him in
> that thread. My comments in that thread are consistent with my
> comments in on-list threads from around that same time when
> out-of-tree code was discussed. Here is a snippet from one of my
> responses, which still holds true as far as I'm concerned:
>
> "As stated many times in the past, the LSM framework as
> well as the Linux kernel in general, does not provide the
> same level of consideration to out-of-tree code that it does
> to upstream, mainline code. My policy on this remains the
> same as last time we talked: while I have no goal to make
> things difficult for out-of-tree code, I will not sacrifice
> the continued development and maintenance of existing
> upstream code in favor of out-of-tree code."
>
> Searching for "Timur Chernykh" in all of the lore archives shows some
> BPF related threads and the following LSM thread from June 2024:
>
> https://lore.kernel.org/all/CABZOZnS13-KscVQY0YqqWZsBwmQaKyRO_G=kzCL8zc9jHxAC=A@mail.gmail.com
>
> In this post Timur provides links to his ESF project on GitHub, but no
> patches. I see comments from Stephen, Tetsuo, Casey, and Dr. Greg; I
> did not comment on that thread.
>
> Beyond that, I'm a bit lost. As far as I can remember, and both lore
> and my own sent mail folder appear to support this, I've never
> commented on ESF. At this point I think Timur may be mistaken
> regarding my commenting on ESF, but if I am wrong please provide a
> lore link so I can refresh my memory.
>
> --
> paul-moore.com
^ permalink raw reply
* [RFC][PATCH v2] ima: Add support for staging measurements for deletion and trimming
From: Roberto Sassu @ 2025-12-12 17:19 UTC (permalink / raw)
To: corbet, zohar, dmitry.kasatkin, eric.snowberg, paul, jmorris,
serge
Cc: linux-doc, linux-kernel, linux-integrity, linux-security-module,
gregorylumen, chenste, nramas, Roberto Sassu
From: Roberto Sassu <roberto.sassu@huawei.com>
Introduce the ability of staging the entire (or a portion of the) IMA
measurement list for deletion. Staging means moving the current content of
the measurement list to a separate location, and allowing users to read and
delete it. This causes the measurement list to be atomically truncated
before new measurements can be added. Staging can be done only once at a
time. In the event of kexec(), staging is reverted and staged entries will
be carried over to the new kernel.
User space is responsible to concatenate the staged IMA measurements list
portions following the temporal order in which the operations were done,
together with the current measurement list. Then, it can send the collected
data to the remote verifiers.
Also introduce the ability of trimming N measurements entries from the IMA
measurements list, provided that user space has already read them. Trimming
combines staging and deletion in one operation.
The benefit of these solutions is the ability to free precious kernel
memory, in exchange of delegating user space to reconstruct the full
measurement list from the chunks. No trust needs to be given to user space,
since the integrity of the measurement list is protected by the TPM.
By default, staging/trimming the measurements list does not alter the hash
table. When staging/trimming are done, IMA is still able to detect
collisions on the staged and later deleted measurement entries, by keeping
the entry digests (only template data are freed).
However, since during the measurements list serialization only the SHA1
digest is passed, and since there are no template data to recalculate the
other digests from, the hash table is currently not populated with digests
from staged/deleted entries after kexec().
Introduce the new kernel option ima_flush_htable to decide whether or not
the digests of staged measurement entries are flushed from the hash table.
Then, introduce ascii_runtime_measurements_staged_<algo> and
binary_runtime_measurement_staged_<algo> interfaces to stage/trim/delete
the measurements. Use 'echo A > <IMA interface>' and
'echo D > <IMA interface>' to respectively stage and delete the entire
measurements list. Use 'echo N > <IMA interface>', with N between 1 and
LONG_MAX, to stage the selected portion of the measurements list, and
'echo -N > <IMA interface>' to trim N measurements entries.
The ima_measure_users counter (protected by the ima_measure_lock mutex) has
been introduced to protect access to the measurements list and the staged
part. The open method of all the measurement interfaces has been extended
to allow only one writer at a time or, in alternative, multiple readers.
The write permission is used to stage/trim/delete the measurements, the
read permission to read them. Write requires also the CAP_SYS_ADMIN
capability.
Finally, introduce and maintain dedicate counters for the number of
measurement entries and binary size, for the current measurements list
(BINARY_SIZE), for the current measurements list plus staged entries
(BINARY_SIZE_STAGED) useful for kexec() segment allocation, and for the
entire measurement list without staging/trimming (BINARY_SIZE_FULL) useful
for the kexec-related critical data records.
Note: This code derives from the Alt-IMA Huawei project, and is being
released under the dual license model (GPL-2.0 OR MIT).
Link: https://github.com/linux-integrity/linux/issues/1
Signed-off-by: Roberto Sassu <roberto.sassu@huawei.com>
---
.../admin-guide/kernel-parameters.txt | 4 +
security/integrity/ima/ima.h | 18 +-
security/integrity/ima/ima_fs.c | 240 +++++++++++++++++-
security/integrity/ima/ima_kexec.c | 42 ++-
security/integrity/ima/ima_queue.c | 169 +++++++++++-
5 files changed, 439 insertions(+), 34 deletions(-)
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 6c42061ca20e..e5f1e11bd0a2 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -2215,6 +2215,10 @@
Use the canonical format for the binary runtime
measurements, instead of host native format.
+ ima_flush_htable [IMA]
+ Flush the IMA hash table when staging for deletion or
+ trimming measurement entries.
+
ima_hash= [IMA]
Format: { md5 | sha1 | rmd160 | sha256 | sha384
| sha512 | ... }
diff --git a/security/integrity/ima/ima.h b/security/integrity/ima/ima.h
index e3d71d8d56e3..8a6be4284210 100644
--- a/security/integrity/ima/ima.h
+++ b/security/integrity/ima/ima.h
@@ -28,6 +28,15 @@ enum ima_show_type { IMA_SHOW_BINARY, IMA_SHOW_BINARY_NO_FIELD_LEN,
IMA_SHOW_BINARY_OLD_STRING_FMT, IMA_SHOW_ASCII };
enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8, TPM_PCR10 = 10 };
+/*
+ * BINARY_SIZE: size of the current measurements list
+ * BINARY_SIZE_STAGED: size of current measurements list + staged entries
+ * BINARY_SIZE_FULL: size of measurements list since IMA initialization
+ */
+enum binary_size_types {
+ BINARY_SIZE, BINARY_SIZE_STAGED, BINARY_SIZE_FULL, BINARY__LAST
+};
+
/* digest size for IMA, fits SHA1 or MD5 */
#define IMA_DIGEST_SIZE SHA1_DIGEST_SIZE
#define IMA_EVENT_NAME_LEN_MAX 255
@@ -117,6 +126,8 @@ struct ima_queue_entry {
struct ima_template_entry *entry;
};
extern struct list_head ima_measurements; /* list of all measurements */
+extern struct list_head ima_measurements_staged; /* list of staged meas. */
+extern bool ima_measurements_staged_exist; /* If there are staged meas. */
/* Some details preceding the binary serialized measurement list */
struct ima_kexec_hdr {
@@ -281,10 +292,12 @@ struct ima_template_desc *ima_template_desc_current(void);
struct ima_template_desc *ima_template_desc_buf(void);
struct ima_template_desc *lookup_template_desc(const char *name);
bool ima_template_has_modsig(const struct ima_template_desc *ima_template);
+int ima_queue_stage_trim(unsigned long req_value, bool trim);
+int ima_queue_delete_staged_trimmed(bool staged_moved);
int ima_restore_measurement_entry(struct ima_template_entry *entry);
int ima_restore_measurement_list(loff_t bufsize, void *buf);
int ima_measurements_show(struct seq_file *m, void *v);
-unsigned long ima_get_binary_runtime_size(void);
+unsigned long ima_get_binary_runtime_size(enum binary_size_types type);
int ima_init_template(void);
void ima_init_template_list(void);
int __init ima_init_digests(void);
@@ -298,11 +311,12 @@ int ima_lsm_policy_change(struct notifier_block *nb, unsigned long event,
extern spinlock_t ima_queue_lock;
struct ima_h_table {
- atomic_long_t len; /* number of stored measurements in the list */
+ atomic_long_t len[BINARY__LAST]; /* num of stored meas. in the list */
atomic_long_t violations;
struct hlist_head queue[IMA_MEASURE_HTABLE_SIZE];
};
extern struct ima_h_table ima_htable;
+extern struct mutex ima_extend_list_mutex;
static inline unsigned int ima_hash_key(u8 *digest)
{
diff --git a/security/integrity/ima/ima_fs.c b/security/integrity/ima/ima_fs.c
index 87045b09f120..a96f7c36b34a 100644
--- a/security/integrity/ima/ima_fs.c
+++ b/security/integrity/ima/ima_fs.c
@@ -24,7 +24,18 @@
#include "ima.h"
+/*
+ * Requests:
+ * 'A\n': stage the entire measurements list
+ * '[1, LONG_MAX]\n' stage N measurements entries
+ * '-[1, LONG_MAX]\n' trim N measurements entries
+ * 'D\n': delete staged measurements
+ */
+#define STAGED_REQ_LENGTH 21
+
static DEFINE_MUTEX(ima_write_mutex);
+static DEFINE_MUTEX(ima_measure_lock);
+static long ima_measure_users;
bool ima_canonical_fmt;
static int __init default_canonical_fmt_setup(char *str)
@@ -64,7 +75,8 @@ static ssize_t ima_show_measurements_count(struct file *filp,
char __user *buf,
size_t count, loff_t *ppos)
{
- return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
+ return ima_show_htable_value(buf, count, ppos,
+ &ima_htable.len[BINARY_SIZE]);
}
@@ -74,14 +86,15 @@ static const struct file_operations ima_measurements_count_ops = {
};
/* returns pointer to hlist_node */
-static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
+static void *_ima_measurements_start(struct seq_file *m, loff_t *pos,
+ struct list_head *head)
{
loff_t l = *pos;
struct ima_queue_entry *qe;
/* we need a lock since pos could point beyond last element */
rcu_read_lock();
- list_for_each_entry_rcu(qe, &ima_measurements, later) {
+ list_for_each_entry_rcu(qe, head, later) {
if (!l--) {
rcu_read_unlock();
return qe;
@@ -91,7 +104,18 @@ static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
return NULL;
}
-static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
+static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
+{
+ return _ima_measurements_start(m, pos, &ima_measurements);
+}
+
+static void *ima_measurements_staged_start(struct seq_file *m, loff_t *pos)
+{
+ return _ima_measurements_start(m, pos, &ima_measurements_staged);
+}
+
+static void *_ima_measurements_next(struct seq_file *m, void *v, loff_t *pos,
+ struct list_head *head)
{
struct ima_queue_entry *qe = v;
@@ -103,7 +127,18 @@ static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
rcu_read_unlock();
(*pos)++;
- return (&qe->later == &ima_measurements) ? NULL : qe;
+ return (&qe->later == head) ? NULL : qe;
+}
+
+static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
+{
+ return _ima_measurements_next(m, v, pos, &ima_measurements);
+}
+
+static void *ima_measurements_staged_next(struct seq_file *m, void *v,
+ loff_t *pos)
+{
+ return _ima_measurements_next(m, v, pos, &ima_measurements_staged);
}
static void ima_measurements_stop(struct seq_file *m, void *v)
@@ -202,16 +237,147 @@ static const struct seq_operations ima_measurments_seqops = {
.show = ima_measurements_show
};
+static int _ima_measurements_open(struct inode *inode, struct file *file,
+ const struct seq_operations *seq_ops)
+{
+ bool write = !!(file->f_mode & FMODE_WRITE);
+ int ret;
+
+ if (write && !capable(CAP_SYS_ADMIN))
+ return -EPERM;
+
+ mutex_lock(&ima_measure_lock);
+ if ((write && ima_measure_users != 0) ||
+ (!write && ima_measure_users < 0)) {
+ mutex_unlock(&ima_measure_lock);
+ return -EBUSY;
+ }
+
+ ret = seq_open(file, seq_ops);
+ if (ret < 0) {
+ mutex_unlock(&ima_measure_lock);
+ return ret;
+ }
+
+ if (write)
+ ima_measure_users--;
+ else
+ ima_measure_users++;
+
+ mutex_unlock(&ima_measure_lock);
+ return ret;
+}
+
static int ima_measurements_open(struct inode *inode, struct file *file)
{
- return seq_open(file, &ima_measurments_seqops);
+ return _ima_measurements_open(inode, file, &ima_measurments_seqops);
+}
+
+static int ima_measurements_release(struct inode *inode, struct file *file)
+{
+ bool write = !!(file->f_mode & FMODE_WRITE);
+ int ret;
+
+ mutex_lock(&ima_measure_lock);
+ ret = seq_release(inode, file);
+ if (!ret) {
+ if (write)
+ ima_measure_users++;
+ else
+ ima_measure_users--;
+ }
+
+ mutex_unlock(&ima_measure_lock);
+ return ret;
}
static const struct file_operations ima_measurements_ops = {
.open = ima_measurements_open,
.read = seq_read,
.llseek = seq_lseek,
- .release = seq_release,
+ .release = ima_measurements_release,
+};
+
+static const struct seq_operations ima_measurments_staged_seqops = {
+ .start = ima_measurements_staged_start,
+ .next = ima_measurements_staged_next,
+ .stop = ima_measurements_stop,
+ .show = ima_measurements_show
+};
+
+static int ima_measurements_staged_open(struct inode *inode, struct file *file)
+{
+ return _ima_measurements_open(inode, file,
+ &ima_measurments_staged_seqops);
+}
+
+static ssize_t ima_measurements_staged_read(struct file *file, char __user *buf,
+ size_t size, loff_t *ppos)
+{
+ if (!ima_measurements_staged_exist)
+ return -ENOENT;
+
+ return seq_read(file, buf, size, ppos);
+}
+
+static ssize_t ima_measurements_staged_write(struct file *file,
+ const char __user *buf,
+ size_t datalen, loff_t *ppos)
+{
+ char req[STAGED_REQ_LENGTH], *req_ptr = req;
+ unsigned long req_value;
+ bool trim = false;
+ int ret;
+
+ if (*ppos > 0 || datalen < 2 || datalen > STAGED_REQ_LENGTH)
+ return -EINVAL;
+
+ if (copy_from_user(req, buf, datalen) != 0)
+ return -EFAULT;
+
+ if (req[datalen - 1] != '\n')
+ return -EINVAL;
+
+ req[datalen - 1] = '\0';
+ req_ptr = req;
+
+ switch (req[0]) {
+ case 'A':
+ if (datalen != 2 || req[1] != '\0')
+ return -EINVAL;
+
+ ret = ima_queue_stage_trim(LONG_MAX, false);
+ break;
+ case 'D':
+ if (datalen != 2 || req[1] != '\0')
+ return -EINVAL;
+
+ ret = ima_queue_delete_staged_trimmed(false);
+ break;
+ case '-':
+ trim = true;
+ req_ptr++;
+ fallthrough;
+ default:
+ ret = kstrtoul(req_ptr, 0, &req_value);
+ if (ret < 0)
+ return ret;
+
+ ret = ima_queue_stage_trim(req_value, trim);
+ }
+
+ if (ret < 0)
+ return ret;
+
+ return datalen;
+}
+
+static const struct file_operations ima_measurements_staged_ops = {
+ .open = ima_measurements_staged_open,
+ .read = ima_measurements_staged_read,
+ .write = ima_measurements_staged_write,
+ .llseek = seq_lseek,
+ .release = ima_measurements_release,
};
void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
@@ -279,14 +445,37 @@ static const struct seq_operations ima_ascii_measurements_seqops = {
static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
{
- return seq_open(file, &ima_ascii_measurements_seqops);
+ return _ima_measurements_open(inode, file,
+ &ima_ascii_measurements_seqops);
}
static const struct file_operations ima_ascii_measurements_ops = {
.open = ima_ascii_measurements_open,
.read = seq_read,
.llseek = seq_lseek,
- .release = seq_release,
+ .release = ima_measurements_release,
+};
+
+static const struct seq_operations ima_ascii_measurements_staged_seqops = {
+ .start = ima_measurements_staged_start,
+ .next = ima_measurements_staged_next,
+ .stop = ima_measurements_stop,
+ .show = ima_ascii_measurements_show
+};
+
+static int ima_ascii_measurements_staged_open(struct inode *inode,
+ struct file *file)
+{
+ return _ima_measurements_open(inode, file,
+ &ima_ascii_measurements_staged_seqops);
+}
+
+static const struct file_operations ima_ascii_measurements_staged_ops = {
+ .open = ima_ascii_measurements_staged_open,
+ .read = ima_measurements_staged_read,
+ .write = ima_measurements_staged_write,
+ .llseek = seq_lseek,
+ .release = ima_measurements_release,
};
static ssize_t ima_read_policy(char *path)
@@ -419,6 +608,25 @@ static int __init create_securityfs_measurement_lists(void)
&ima_measurements_ops);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
+
+ sprintf(file_name, "ascii_runtime_measurements_staged_%s",
+ hash_algo_name[algo]);
+ dentry = securityfs_create_file(file_name,
+ S_IRUSR | S_IRGRP | S_IWUSR | S_IWGRP,
+ ima_dir, (void *)(uintptr_t)i,
+ &ima_ascii_measurements_staged_ops);
+ if (IS_ERR(dentry))
+ return PTR_ERR(dentry);
+
+ sprintf(file_name, "binary_runtime_measurements_staged_%s",
+ hash_algo_name[algo]);
+ dentry = securityfs_create_file(file_name,
+ S_IRUSR | S_IRGRP |
+ S_IWUSR | S_IWGRP,
+ ima_dir, (void *)(uintptr_t)i,
+ &ima_measurements_staged_ops);
+ if (IS_ERR(dentry))
+ return PTR_ERR(dentry);
}
return 0;
@@ -528,6 +736,20 @@ int __init ima_fs_init(void)
goto out;
}
+ dentry = securityfs_create_symlink("binary_runtime_measurements_staged",
+ ima_dir, "binary_runtime_measurements_staged_sha1", NULL);
+ if (IS_ERR(dentry)) {
+ ret = PTR_ERR(dentry);
+ goto out;
+ }
+
+ dentry = securityfs_create_symlink("ascii_runtime_measurements_staged",
+ ima_dir, "ascii_runtime_measurements_staged_sha1", NULL);
+ if (IS_ERR(dentry)) {
+ ret = PTR_ERR(dentry);
+ goto out;
+ }
+
dentry = securityfs_create_file("runtime_measurements_count",
S_IRUSR | S_IRGRP, ima_dir, NULL,
&ima_measurements_count_ops);
diff --git a/security/integrity/ima/ima_kexec.c b/security/integrity/ima/ima_kexec.c
index 7362f68f2d8b..13c7e78aeefd 100644
--- a/security/integrity/ima/ima_kexec.c
+++ b/security/integrity/ima/ima_kexec.c
@@ -40,8 +40,8 @@ void ima_measure_kexec_event(const char *event_name)
long len;
int n;
- buf_size = ima_get_binary_runtime_size();
- len = atomic_long_read(&ima_htable.len);
+ buf_size = ima_get_binary_runtime_size(BINARY_SIZE_FULL);
+ len = atomic_long_read(&ima_htable.len[BINARY_SIZE_FULL]);
n = scnprintf(ima_kexec_event, IMA_KEXEC_EVENT_LEN,
"kexec_segment_size=%lu;ima_binary_runtime_size=%lu;"
@@ -78,6 +78,17 @@ static int ima_alloc_kexec_file_buf(size_t segment_size)
return 0;
}
+static int ima_dump_measurement(struct ima_kexec_hdr *khdr,
+ struct ima_queue_entry *qe)
+{
+ if (ima_kexec_file.count >= ima_kexec_file.size)
+ return -EINVAL;
+
+ khdr->count++;
+ ima_measurements_show(&ima_kexec_file, qe);
+ return 0;
+}
+
static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
unsigned long segment_size)
{
@@ -93,17 +104,25 @@ static int ima_dump_measurement_list(unsigned long *buffer_size, void **buffer,
memset(&khdr, 0, sizeof(khdr));
khdr.version = 1;
- /* This is an append-only list, no need to hold the RCU read lock */
- list_for_each_entry_rcu(qe, &ima_measurements, later, true) {
- if (ima_kexec_file.count < ima_kexec_file.size) {
- khdr.count++;
- ima_measurements_show(&ima_kexec_file, qe);
- } else {
- ret = -EINVAL;
+
+ /* It can race with ima_queue_stage_trim(). */
+ mutex_lock(&ima_extend_list_mutex);
+
+ list_for_each_entry(qe, &ima_measurements_staged, later) {
+ ret = ima_dump_measurement(&khdr, qe);
+ if (ret < 0)
+ break;
+ }
+
+ list_for_each_entry(qe, &ima_measurements, later) {
+ if (!ret)
+ ret = ima_dump_measurement(&khdr, qe);
+ if (ret < 0)
break;
- }
}
+ mutex_unlock(&ima_extend_list_mutex);
+
/*
* fill in reserved space with some buffer details
* (eg. version, buffer size, number of measurements)
@@ -157,7 +176,8 @@ void ima_add_kexec_buffer(struct kimage *image)
else
extra_memory = CONFIG_IMA_KEXEC_EXTRA_MEMORY_KB * 1024;
- binary_runtime_size = ima_get_binary_runtime_size() + extra_memory;
+ binary_runtime_size = ima_get_binary_runtime_size(BINARY_SIZE_STAGED) +
+ extra_memory;
if (binary_runtime_size >= ULONG_MAX - PAGE_SIZE)
kexec_segment_size = ULONG_MAX;
diff --git a/security/integrity/ima/ima_queue.c b/security/integrity/ima/ima_queue.c
index 590637e81ad1..7dfa24b8ae31 100644
--- a/security/integrity/ima/ima_queue.c
+++ b/security/integrity/ima/ima_queue.c
@@ -22,19 +22,32 @@
#define AUDIT_CAUSE_LEN_MAX 32
+bool ima_flush_htable;
+static int __init ima_flush_htable_setup(char *str)
+{
+ ima_flush_htable = true;
+ return 1;
+}
+__setup("ima_flush_htable", ima_flush_htable_setup);
+
/* pre-allocated array of tpm_digest structures to extend a PCR */
static struct tpm_digest *digests;
LIST_HEAD(ima_measurements); /* list of all measurements */
+LIST_HEAD(ima_measurements_staged); /* list of staged measurements */
+static LIST_HEAD(ima_measurements_trim); /* list of measurements to trim */
+bool ima_measurements_staged_exist; /* If there are staged measurements */
#ifdef CONFIG_IMA_KEXEC
-static unsigned long binary_runtime_size;
+static unsigned long binary_runtime_size[BINARY__LAST];
#else
-static unsigned long binary_runtime_size = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE] = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE_FULL] = ULONG_MAX;
+static unsigned long binary_runtime_size[BINARY_SIZE_STAGED] = ULONG_MAX;
#endif
/* key: inode (before secure-hashing a file) */
struct ima_h_table ima_htable = {
- .len = ATOMIC_LONG_INIT(0),
+ .len = { ATOMIC_LONG_INIT(0) },
.violations = ATOMIC_LONG_INIT(0),
.queue[0 ... IMA_MEASURE_HTABLE_SIZE - 1] = HLIST_HEAD_INIT
};
@@ -43,7 +56,7 @@ struct ima_h_table ima_htable = {
* and extending the TPM PCR aggregate. Since tpm_extend can take
* long (and the tpm driver uses a mutex), we can't use the spinlock.
*/
-static DEFINE_MUTEX(ima_extend_list_mutex);
+DEFINE_MUTEX(ima_extend_list_mutex);
/*
* Used internally by the kernel to suspend measurements.
@@ -101,7 +114,7 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
bool update_htable)
{
struct ima_queue_entry *qe;
- unsigned int key;
+ unsigned int i, key;
qe = kmalloc(sizeof(*qe), GFP_KERNEL);
if (qe == NULL) {
@@ -113,18 +126,23 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
INIT_LIST_HEAD(&qe->later);
list_add_tail_rcu(&qe->later, &ima_measurements);
- atomic_long_inc(&ima_htable.len);
+ for (i = 0; i < BINARY__LAST; i++)
+ atomic_long_inc(&ima_htable.len[i]);
+
if (update_htable) {
key = ima_hash_key(entry->digests[ima_hash_algo_idx].digest);
hlist_add_head_rcu(&qe->hnext, &ima_htable.queue[key]);
}
- if (binary_runtime_size != ULONG_MAX) {
+ if (binary_runtime_size[BINARY_SIZE_FULL] != ULONG_MAX) {
int size;
size = get_binary_runtime_size(entry);
- binary_runtime_size = (binary_runtime_size < ULONG_MAX - size) ?
- binary_runtime_size + size : ULONG_MAX;
+
+ for (i = 0; i < BINARY__LAST; i++)
+ binary_runtime_size[i] =
+ (binary_runtime_size[i] < ULONG_MAX - size) ?
+ binary_runtime_size[i] + size : ULONG_MAX;
}
return 0;
}
@@ -134,12 +152,18 @@ static int ima_add_digest_entry(struct ima_template_entry *entry,
* entire binary_runtime_measurement list, including the ima_kexec_hdr
* structure.
*/
-unsigned long ima_get_binary_runtime_size(void)
+unsigned long ima_get_binary_runtime_size(enum binary_size_types type)
{
- if (binary_runtime_size >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
+ unsigned long val;
+
+ mutex_lock(&ima_extend_list_mutex);
+ val = binary_runtime_size[type];
+ mutex_unlock(&ima_extend_list_mutex);
+
+ if (val >= (ULONG_MAX - sizeof(struct ima_kexec_hdr)))
return ULONG_MAX;
else
- return binary_runtime_size + sizeof(struct ima_kexec_hdr);
+ return val + sizeof(struct ima_kexec_hdr);
}
static int ima_pcr_extend(struct tpm_digest *digests_arg, int pcr)
@@ -220,6 +244,127 @@ int ima_add_template_entry(struct ima_template_entry *entry, int violation,
return result;
}
+int ima_queue_stage_trim(unsigned long req_value, bool trim)
+{
+ unsigned long req_value_copy = req_value, to_remove = 0;
+ struct list_head *moved = &ima_measurements_staged;
+ struct ima_queue_entry *qe;
+
+ if (req_value == 0 || req_value > LONG_MAX)
+ return -EINVAL;
+
+ if (ima_measurements_staged_exist)
+ return -EEXIST;
+
+ if (trim)
+ moved = &ima_measurements_trim;
+
+ mutex_lock(&ima_extend_list_mutex);
+ if (list_empty(&ima_measurements)) {
+ mutex_unlock(&ima_extend_list_mutex);
+ return -ENOENT;
+ }
+
+ if (req_value == LONG_MAX) {
+ list_replace(&ima_measurements, moved);
+ INIT_LIST_HEAD(&ima_measurements);
+ atomic_long_set(&ima_htable.len[BINARY_SIZE], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE] = 0;
+
+ if (trim) {
+ atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] = 0;
+ }
+ } else {
+ list_for_each_entry(qe, &ima_measurements, later) {
+ to_remove += get_binary_runtime_size(qe->entry);
+ if (--req_value_copy == 0)
+ break;
+ }
+
+ if (req_value_copy > 0) {
+ mutex_unlock(&ima_extend_list_mutex);
+ return -ENOENT;
+ }
+
+ __list_cut_position(moved, &ima_measurements, &qe->later);
+ atomic_long_sub(req_value, &ima_htable.len[BINARY_SIZE]);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE] -= to_remove;
+
+ if (trim) {
+ atomic_long_sub(req_value,
+ &ima_htable.len[BINARY_SIZE_STAGED]);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] -=
+ to_remove;
+ }
+ }
+
+ if (ima_flush_htable)
+ /* Either staged/trimmed entries are removed from hash table. */
+ list_for_each_entry(qe, moved, later)
+ /* It can race with ima_lookup_digest_entry(). */
+ hlist_del_rcu(&qe->hnext);
+
+ mutex_unlock(&ima_extend_list_mutex);
+ ima_measurements_staged_exist = true;
+
+ if (ima_flush_htable)
+ synchronize_rcu();
+
+ if (trim)
+ return ima_queue_delete_staged_trimmed(true);
+
+ return 0;
+}
+
+int ima_queue_delete_staged_trimmed(bool staged_moved)
+{
+ struct ima_queue_entry *qe, *qe_tmp;
+ unsigned int i;
+
+ if (!ima_measurements_staged_exist)
+ return -ENOENT;
+
+ if (!staged_moved) {
+ mutex_lock(&ima_extend_list_mutex);
+ list_replace(&ima_measurements_staged, &ima_measurements_trim);
+ INIT_LIST_HEAD(&ima_measurements_staged);
+ atomic_long_set(&ima_htable.len[BINARY_SIZE_STAGED], 0);
+ if (IS_ENABLED(CONFIG_IMA_KEXEC))
+ binary_runtime_size[BINARY_SIZE_STAGED] = 0;
+
+ mutex_unlock(&ima_extend_list_mutex);
+ }
+
+ list_for_each_entry_safe(qe, qe_tmp, &ima_measurements_trim, later) {
+ /*
+ * Ok because after list delete qe is only accessed by
+ * ima_lookup_digest_entry().
+ */
+ for (i = 0; i < qe->entry->template_desc->num_fields; i++) {
+ kfree(qe->entry->template_data[i].data);
+ qe->entry->template_data[i].data = NULL;
+ qe->entry->template_data[i].len = 0;
+ }
+
+ list_del(&qe->later);
+
+ /* No leak if !ima_flush_htable, referenced by ima_htable. */
+ if (ima_flush_htable) {
+ kfree(qe->entry->digests);
+ kfree(qe->entry);
+ kfree(qe);
+ }
+ }
+
+ ima_measurements_staged_exist = false;
+ return 0;
+}
+
int ima_restore_measurement_entry(struct ima_template_entry *entry)
{
int result = 0;
--
2.43.0
^ permalink raw reply related
* Re: An opinion about Linux security
From: Paul Moore @ 2025-12-12 17:06 UTC (permalink / raw)
To: Stephen Smalley
Cc: Timur Chernykh, Casey Schaufler, torvalds, linux-security-module,
greg
In-Reply-To: <CAEjxPJ6CbZC-=onSGgELygnt_hsqaN0JS_jJFxWn+hYt90s2Ng@mail.gmail.com>
On Fri, Dec 12, 2025 at 11:12 AM Stephen Smalley
<stephen.smalley.work@gmail.com> wrote:
> On Fri, Dec 12, 2025 at 9:47 AM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
> >
> > I’m lucky enough to have already built a working prototype, which I
> > once offered for review:
> >
> > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> > https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
> >
> > Less lucky was the reaction I received. Paul Moore was strongly
> > opposed, as far as I remember. Dr. Greg once said that heat death of
> > the universe is more likely than this approach being accepted into the
> > kernel.
>
> Not seeing an actual response from Paul in the archives, but did you
> ever actually post patches to the list?
I was wondering about this too. I searched through my sent mail and
while it's possible I'm missing some mail, the only conversation I see
with Timur is an off-list discussion from 2024 regarding changes in
the upstream kernel to support out-of-tree LSMs. While Timur was
added to the conversation by someone, I don't see any mail from him in
that thread. My comments in that thread are consistent with my
comments in on-list threads from around that same time when
out-of-tree code was discussed. Here is a snippet from one of my
responses, which still holds true as far as I'm concerned:
"As stated many times in the past, the LSM framework as
well as the Linux kernel in general, does not provide the
same level of consideration to out-of-tree code that it does
to upstream, mainline code. My policy on this remains the
same as last time we talked: while I have no goal to make
things difficult for out-of-tree code, I will not sacrifice
the continued development and maintenance of existing
upstream code in favor of out-of-tree code."
Searching for "Timur Chernykh" in all of the lore archives shows some
BPF related threads and the following LSM thread from June 2024:
https://lore.kernel.org/all/CABZOZnS13-KscVQY0YqqWZsBwmQaKyRO_G=kzCL8zc9jHxAC=A@mail.gmail.com
In this post Timur provides links to his ESF project on GitHub, but no
patches. I see comments from Stephen, Tetsuo, Casey, and Dr. Greg; I
did not comment on that thread.
Beyond that, I'm a bit lost. As far as I can remember, and both lore
and my own sent mail folder appear to support this, I've never
commented on ESF. At this point I think Timur may be mistaken
regarding my commenting on ESF, but if I am wrong please provide a
lore link so I can refresh my memory.
--
paul-moore.com
^ permalink raw reply
* [RFC PATCH v3 1/8] landlock: Minor reword of docs for TCP access rights
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
- Move ABI requirement next to each access right to prepare adding more
access rights;
- Mention the possibility to remove the random component of a socket's
ephemeral port choice within the netns-wide ephemeral port range,
since it allows choosing the "random" ephemeral port.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
include/uapi/linux/landlock.h | 17 +++++++++--------
1 file changed, 9 insertions(+), 8 deletions(-)
diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index f030adc462ee..efb383af40b2 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -182,11 +182,13 @@ struct landlock_net_port_attr {
* It should be noted that port 0 passed to :manpage:`bind(2)` will bind
* to an available port from the ephemeral port range. This can be
* configured with the ``/proc/sys/net/ipv4/ip_local_port_range`` sysctl
- * (also used for IPv6).
+ * (also used for IPv6), and within that range, on a per-socket basis
+ * with ``setsockopt(IP_LOCAL_PORT_RANGE)``.
*
- * A Landlock rule with port 0 and the ``LANDLOCK_ACCESS_NET_BIND_TCP``
+ * A Landlock rule with port 0 and the %LANDLOCK_ACCESS_NET_BIND_TCP
* right means that requesting to bind on port 0 is allowed and it will
- * automatically translate to binding on the related port range.
+ * automatically translate to binding on a kernel-assigned ephemeral
+ * port.
*/
__u64 port;
};
@@ -332,13 +334,12 @@ struct landlock_net_port_attr {
* These flags enable to restrict a sandboxed process to a set of network
* actions.
*
- * This is supported since Landlock ABI version 4.
- *
* The following access rights apply to TCP port numbers:
*
- * - %LANDLOCK_ACCESS_NET_BIND_TCP: Bind a TCP socket to a local port.
- * - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect an active TCP socket to
- * a remote port.
+ * - %LANDLOCK_ACCESS_NET_BIND_TCP: Bind TCP sockets to the given local
+ * port. Support added in Landlock ABI version 4.
+ * - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect TCP sockets to the given
+ * remote port. Support added in Landlock ABI version 4.
*/
/* clang-format off */
#define LANDLOCK_ACCESS_NET_BIND_TCP (1ULL << 0)
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 3/8] landlock: Add UDP bind+connect access control
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
If a process doesn't need to be able to open UDP sockets, it should be
denied the right to create UDP sockets altogether. For processes using
UDP, add support for two more fine-grained access rights:
- LANDLOCK_ACCESS_NET_CONNECT_UDP, to gate the possibility to connect()
a UDP socket. For client apps (those which want to avoid specifying a
destination for each datagram they send), and for a few servers (those
creating per-client sockets, which want to receive traffic only from a
specific address)
- LANDLOCK_ACCESS_NET_BIND_UDP, to gate the possibility to bind() a UDP
socket. For most servers (to start receiving datagrams), and some
clients that need to use a specific source port (e.g. mDNS requires to
use port 5353)
Access control is only enforced when trying to set the local or remote
end of a UDP socket. So, nothing prevents a client with the right to
send datagrams to use it to get an automatically bound socket and
receive datagrams on an ephemeral port of their choice, without having
LANDLOCK_ACCESS_NET_BIND_UDP. Restricting send/recv semantics is left
for a future patch, as it would require tagging sockets or a netfilter
hook.
Bump ABI to v8 to allow userland to detect and use these new access
rights.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
include/uapi/linux/landlock.h | 20 ++++++++++++++---
security/landlock/audit.c | 2 ++
security/landlock/limits.h | 2 +-
security/landlock/net.c | 41 ++++++++++++++++++++++-------------
security/landlock/syscalls.c | 2 +-
5 files changed, 47 insertions(+), 20 deletions(-)
diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index efb383af40b2..8f748fcf79dd 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -186,9 +186,9 @@ struct landlock_net_port_attr {
* with ``setsockopt(IP_LOCAL_PORT_RANGE)``.
*
* A Landlock rule with port 0 and the %LANDLOCK_ACCESS_NET_BIND_TCP
- * right means that requesting to bind on port 0 is allowed and it will
- * automatically translate to binding on a kernel-assigned ephemeral
- * port.
+ * or %LANDLOCK_ACCESS_NET_BIND_UDP right means that requesting to bind
+ * on port 0 is allowed and it will automatically translate to binding
+ * on a kernel-assigned ephemeral port.
*/
__u64 port;
};
@@ -340,10 +340,24 @@ struct landlock_net_port_attr {
* port. Support added in Landlock ABI version 4.
* - %LANDLOCK_ACCESS_NET_CONNECT_TCP: Connect TCP sockets to the given
* remote port. Support added in Landlock ABI version 4.
+ *
+ * And similarly for UDP port numbers:
+ *
+ * - %LANDLOCK_ACCESS_NET_BIND_UDP: Bind UDP sockets to the given local
+ * port. Support added in Landlock ABI version 8.
+ * Note: this access right is not required if your program sends
+ * datagrams and just uses the implicitly bound port assigned by the
+ * kernel to reply. Conversely, denying this right only blocks a
+ * program from binding to non-ephemeral ports if it can send datagrams.
+ * - %LANDLOCK_ACCESS_NET_CONNECT_UDP: Connect UDP sockets to remote
+ * addresses with the given remote port. Support added in Landlock ABI
+ * version 8.
*/
/* clang-format off */
#define LANDLOCK_ACCESS_NET_BIND_TCP (1ULL << 0)
#define LANDLOCK_ACCESS_NET_CONNECT_TCP (1ULL << 1)
+#define LANDLOCK_ACCESS_NET_BIND_UDP (1ULL << 2)
+#define LANDLOCK_ACCESS_NET_CONNECT_UDP (1ULL << 3)
/* clang-format on */
/**
diff --git a/security/landlock/audit.c b/security/landlock/audit.c
index e899995f1fd5..23d8dee320ef 100644
--- a/security/landlock/audit.c
+++ b/security/landlock/audit.c
@@ -44,6 +44,8 @@ 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",
+ [BIT_INDEX(LANDLOCK_ACCESS_NET_BIND_UDP)] = "net.bind_udp",
+ [BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_UDP)] = "net.connect_udp",
};
static_assert(ARRAY_SIZE(net_access_strings) == LANDLOCK_NUM_ACCESS_NET);
diff --git a/security/landlock/limits.h b/security/landlock/limits.h
index 65b5ff051674..13dd5503e471 100644
--- a/security/landlock/limits.h
+++ b/security/landlock/limits.h
@@ -23,7 +23,7 @@
#define LANDLOCK_MASK_ACCESS_FS ((LANDLOCK_LAST_ACCESS_FS << 1) - 1)
#define LANDLOCK_NUM_ACCESS_FS __const_hweight64(LANDLOCK_MASK_ACCESS_FS)
-#define LANDLOCK_LAST_ACCESS_NET LANDLOCK_ACCESS_NET_CONNECT_TCP
+#define LANDLOCK_LAST_ACCESS_NET LANDLOCK_ACCESS_NET_CONNECT_UDP
#define LANDLOCK_MASK_ACCESS_NET ((LANDLOCK_LAST_ACCESS_NET << 1) - 1)
#define LANDLOCK_NUM_ACCESS_NET __const_hweight64(LANDLOCK_MASK_ACCESS_NET)
diff --git a/security/landlock/net.c b/security/landlock/net.c
index 59438285e73b..9bddcf466ce9 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -68,28 +68,31 @@ static int current_check_access_socket(struct socket *const sock,
switch (address->sa_family) {
case AF_UNSPEC:
- if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+ if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
/*
* Connecting to an address with AF_UNSPEC dissolves
- * the TCP association, which have the same effect as
- * closing the connection while retaining the socket
- * object (i.e., the file descriptor). As for dropping
- * privileges, closing connections is always allowed.
- *
- * For a TCP access control system, this request is
- * legitimate. Let the network stack handle potential
+ * the remote association while retaining the socket
+ * object (i.e., the file descriptor). For TCP, it has
+ * the same effect as closing the connection. For UDP,
+ * it removes any preset remote address. As for
+ * dropping privileges, these actions are always
+ * allowed.
+ * Let the network stack handle potential
* inconsistencies and return -EINVAL if needed.
*/
return 0;
- } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+ } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
/*
* Binding to an AF_UNSPEC address is treated
* differently by IPv4 and IPv6 sockets. The socket's
* family may change under our feet due to
* setsockopt(IPV6_ADDRFORM), but that's ok: we either
* reject entirely or require
- * %LANDLOCK_ACCESS_NET_BIND_TCP for the given port, so
- * it cannot be used to bypass the policy.
+ * %LANDLOCK_ACCESS_NET_BIND_TCP or
+ * %LANDLOCK_ACCESS_NET_BIND_UDP for the given port,
+ * so it cannot be used to bypass the policy.
*
* IPv4 sockets map AF_UNSPEC to AF_INET for
* retrocompatibility for bind accesses, only if the
@@ -132,10 +135,12 @@ static int current_check_access_socket(struct socket *const sock,
addr4 = (struct sockaddr_in *)address;
port = addr4->sin_port;
- if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+ if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
audit_net.dport = port;
audit_net.v4info.daddr = addr4->sin_addr.s_addr;
- } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+ } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
audit_net.sport = port;
audit_net.v4info.saddr = addr4->sin_addr.s_addr;
} else {
@@ -154,10 +159,12 @@ static int current_check_access_socket(struct socket *const sock,
addr6 = (struct sockaddr_in6 *)address;
port = addr6->sin6_port;
- if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+ if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
audit_net.dport = port;
audit_net.v6info.daddr = addr6->sin6_addr;
- } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP) {
+ } else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
+ access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
audit_net.sport = port;
audit_net.v6info.saddr = addr6->sin6_addr;
} else {
@@ -215,6 +222,8 @@ static int hook_socket_bind(struct socket *const sock,
if (sk_is_tcp(sock->sk))
access_request = LANDLOCK_ACCESS_NET_BIND_TCP;
+ else if (sk_is_udp(sock->sk))
+ access_request = LANDLOCK_ACCESS_NET_BIND_UDP;
else
return 0;
@@ -230,6 +239,8 @@ static int hook_socket_connect(struct socket *const sock,
if (sk_is_tcp(sock->sk))
access_request = LANDLOCK_ACCESS_NET_CONNECT_TCP;
+ else if (sk_is_udp(sock->sk))
+ access_request = LANDLOCK_ACCESS_NET_CONNECT_UDP;
else
return 0;
diff --git a/security/landlock/syscalls.c b/security/landlock/syscalls.c
index 0116e9f93ffe..66fd196be85a 100644
--- a/security/landlock/syscalls.c
+++ b/security/landlock/syscalls.c
@@ -161,7 +161,7 @@ static const struct file_operations ruleset_fops = {
* Documentation/userspace-api/landlock.rst should be updated to reflect the
* UAPI change.
*/
-const int landlock_abi_version = 7;
+const int landlock_abi_version = 8;
/**
* sys_landlock_create_ruleset - Create a new ruleset
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 0/8] landlock: Add UDP access control support
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
Hi Mickaël, Günther, Mikhail, Konstantin,
Here is v3 of UDP support for Landlock. My apologies for the delay, I've
had to deal with unrelated problems. All feedback from v1/v2 should be
merged, thanks again for taking the time to review them.
I based these patches on linux-mic/next commit 1a3cedbdc156 ("landlock:
Fix wrong type usage") plus my previous patch "landlock: Fix TCP
handling of short AF_UNSPEC addresses" to avoid adding UDP with already
known bugs, duplicated from TCP. I waited a bit to get feedback on that
patch and no one yelled, so I hope it's acceptable, tell me if it's not.
Link: https://lore.kernel.org/linux-security-module/20251027190726.626244-4-matthieu@buffet.re/
Changes since v2
================
Link: https://lore.kernel.org/all/20241214184540.3835222-1-matthieu@buffet.re/
- removed support for sending datagrams with explicit destination
address of family AF_UNSPEC, which allowed to bypass restrictions with
a race condition
- rebased on linux-mic/next => add support for auditing
- fixed mistake in selftests when using unspec_srv variables, which were
implicitly of type SOCK_STREAM and did not actually test UDP code
- add tests for IPPROTO_IP
- improved docs, split off TCP-related refactoring into another commit
Changes since v1
================
Link: https://lore.kernel.org/all/20240916122230.114800-1-matthieu@buffet.re/
- recvmsg hook is gone and sendmsg hook doesn't apply to connected
sockets anymore, to improve performance
- don't add a get_addr_port() helper function, which required a weird
"am I in IPv4 or IPv6 context" to avoid a addrlen > sizeof(struct
sockaddr_in) check in connect(AF_UNSPEC) IPv6 context. A helper was
useful when ports also needed to be read in a recvmsg() hook, now it
is just a simple switch case in the sendmsg() hook, more readable
- rename sendmsg access right to LANDLOCK_ACCESS_NET_UDP_SENDTO
- reorder hook prologue for consistency: check domain, then type and
family
- add additional selftests cases around minimal address length
- update documentation
All important cases should have a selftest now. lcov gives me net.c
going from 91.9% lines/82.5% branches to 93.4% lines/87% branches.
Thank you for taking the time to read this!
Closes: https://github.com/landlock-lsm/linux/issues/10
Matthieu Buffet (8):
landlock: Minor reword of docs for TCP access rights
landlock: Refactor TCP socket type check
landlock: Add UDP bind+connect access control
selftests/landlock: Add UDP bind/connect tests
landlock: Add UDP sendmsg access control
selftests/landlock: Add tests for UDP sendmsg
samples/landlock: Add sandboxer UDP access control
landlock: Add documentation for UDP support
Documentation/userspace-api/landlock.rst | 94 ++-
include/uapi/linux/landlock.h | 46 +-
samples/landlock/sandboxer.c | 58 +-
security/landlock/audit.c | 3 +
security/landlock/limits.h | 2 +-
security/landlock/net.c | 119 +++-
security/landlock/syscalls.c | 2 +-
tools/testing/selftests/landlock/base_test.c | 2 +-
tools/testing/selftests/landlock/net_test.c | 691 ++++++++++++++++---
9 files changed, 869 insertions(+), 148 deletions(-)
base-commit: 1a3cedbdc156e100eb1a5208a8562a3265c35d87
prerequisite-patch-id: 22051d5d4076a87481b22798c127ce84e219ca97
prerequisite-patch-id: 37a1b44596a2d861ba91989edb1d7aac005931d6
prerequisite-patch-id: c7be1c906699a2590ab7112cdf2ab6892178ec07
--
2.47.3
^ permalink raw reply
* [RFC PATCH v3 2/8] landlock: Refactor TCP socket type check
From: Matthieu Buffet @ 2025-12-12 16:36 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Move the socket type check earlier, so that we will later be able to add
elseifs for other types. Ordering of checks (socket is of a type we
enforce restrictions on) / (current creds have landlock restrictions)
should not change anything.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
security/landlock/net.c | 21 ++++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git a/security/landlock/net.c b/security/landlock/net.c
index e6367e30e5b0..59438285e73b 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -62,9 +62,6 @@ static int current_check_access_socket(struct socket *const sock,
if (!subject)
return 0;
- if (!sk_is_tcp(sock->sk))
- return 0;
-
/* Checks for minimal header length to safely read sa_family. */
if (addrlen < offsetofend(typeof(*address), sa_family))
return -EINVAL;
@@ -214,16 +211,30 @@ static int current_check_access_socket(struct socket *const sock,
static int hook_socket_bind(struct socket *const sock,
struct sockaddr *const address, const int addrlen)
{
+ access_mask_t access_request;
+
+ if (sk_is_tcp(sock->sk))
+ access_request = LANDLOCK_ACCESS_NET_BIND_TCP;
+ else
+ return 0;
+
return current_check_access_socket(sock, address, addrlen,
- LANDLOCK_ACCESS_NET_BIND_TCP);
+ access_request);
}
static int hook_socket_connect(struct socket *const sock,
struct sockaddr *const address,
const int addrlen)
{
+ access_mask_t access_request;
+
+ if (sk_is_tcp(sock->sk))
+ access_request = LANDLOCK_ACCESS_NET_CONNECT_TCP;
+ else
+ return 0;
+
return current_check_access_socket(sock, address, addrlen,
- LANDLOCK_ACCESS_NET_CONNECT_TCP);
+ access_request);
}
static struct security_hook_list landlock_hooks[] __ro_after_init = {
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 8/8] landlock: Add documentation for UDP support
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Add example of UDP usage, without detailing each access right, but with
an explicit note about the need to handle both SENDTO and CONNECT to
completely block sending (which could otherwise be overlooked).
Slightly change the example used in code blocks: build a ruleset for a
DNS client, so that it uses both TCP and UDP. Also consider an opaque
implementation so that we get to introduce both the right to connect()
and sendmsg(addr != NULL) within the same example.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
Documentation/userspace-api/landlock.rst | 94 ++++++++++++++++++------
1 file changed, 72 insertions(+), 22 deletions(-)
diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst
index 1d0c2c15c22e..758217c2b260 100644
--- a/Documentation/userspace-api/landlock.rst
+++ b/Documentation/userspace-api/landlock.rst
@@ -8,7 +8,7 @@ Landlock: unprivileged access control
=====================================
:Author: Mickaël Salaün
-:Date: March 2025
+:Date: October 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
@@ -40,8 +40,8 @@ Filesystem rules
and the related filesystem actions are defined with
`filesystem access rights`.
-Network rules (since ABI v4)
- For these rules, the object is a TCP port,
+Network rules (since ABI v4 for TCP and v8 for UDP)
+ For these rules, the object is a TCP or UDP port,
and the related actions are defined with `network access rights`.
Defining and enforcing a security policy
@@ -49,11 +49,11 @@ Defining and enforcing a security policy
We first need to define the ruleset that will contain our rules.
-For this example, the ruleset will contain rules that only allow filesystem
-read actions and establish a specific TCP connection. Filesystem write
-actions and other TCP actions will be denied.
+For this example, the ruleset will contain rules that only allow some
+filesystem read actions and some specific UDP and TCP accesses. Filesystem
+write actions and other TCP/UDP actions will be denied.
-The ruleset then needs to handle both these kinds of actions. This is
+The ruleset then needs to handle all these kinds of actions. This is
required for backward and forward compatibility (i.e. the kernel and user
space may not know each other's supported restrictions), hence the need
to be explicit about the denied-by-default access rights.
@@ -80,7 +80,10 @@ to be explicit about the denied-by-default access rights.
LANDLOCK_ACCESS_FS_IOCTL_DEV,
.handled_access_net =
LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ LANDLOCK_ACCESS_NET_CONNECT_TCP |
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP,
.scoped =
LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
LANDLOCK_SCOPE_SIGNAL,
@@ -127,6 +130,14 @@ version, and only use the available subset of access rights:
/* Removes LANDLOCK_SCOPE_* for ABI < 6 */
ruleset_attr.scoped &= ~(LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
LANDLOCK_SCOPE_SIGNAL);
+ __attribute__((fallthrough));
+ case 6:
+ case 7:
+ /* Removes LANDLOCK_ACCESS_*_UDP for ABI < 8 */
+ ruleset_attr.handled_access_net &=
+ ~(LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP);
}
This enables the creation of an inclusive ruleset that will contain our rules.
@@ -175,26 +186,53 @@ descriptor.
It may also be required to create rules following the same logic as explained
for the ruleset creation, by filtering access rights according to the Landlock
-ABI version. In this example, this is not required because all of the requested
-``allowed_access`` rights are already available in ABI 1.
+ABI version. So far, this was not required because all of the requested
+``allowed_access`` rights have always been available, from ABI 1.
-For network access-control, we can add a set of rules that allow to use a port
-number for a specific action: HTTPS connections.
+For network access-control, we will add a set of rules to allow DNS
+queries, which requires both UDP and TCP. For TCP, we need to allow
+outbound connections to port 53, which can be handled and granted starting
+with ABI 4:
.. code-block:: c
- struct landlock_net_port_attr net_port = {
- .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
- .port = 443,
- };
+ if (ruleset_attr.handled_access_net & LANDLOCK_ACCESS_NET_CONNECT_TCP) {
+ struct landlock_net_port_attr net_port = {
+ .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .port = 53,
+ };
- err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &net_port, 0);
+ err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+ &net_port, 0);
+
+We also need to be able to send UDP datagrams to port 53: we don't know if
+the client will call e.g. :manpage:`sendto(2)` with an explicit destination
+address, or :manpage:`connect(2)` then e.g. :manpage:`send(2)`, so we
+allow both. Note that granting ``LANDLOCK_ACCESS_NET_BIND_UDP`` is not
+necessary here because the client's socket will be automatically bound to
+an ephemeral port by the kernel. Also note that we need to handle both
+``LANDLOCK_ACCESS_NET_CONNECT_UDP`` and ``LANDLOCK_ACCESS_NET_SENDTO_UDP``
+to effectively block sending UDP datagrams to arbitrary ports.
+
+.. code-block:: c
+
+ if ((ruleset_attr.handled_access_net & (LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP)) ==
+ (LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP)) {
+ struct landlock_net_port_attr net_port = {
+ .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP,
+ .port = 53,
+ };
+
+ err = landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+ &net_port, 0);
The next step is to restrict the current thread from gaining more privileges
(e.g. through a SUID binary). We now have a ruleset with the first rule
allowing read access to ``/usr`` while denying all other handled accesses for
-the filesystem, and a second rule allowing HTTPS connections.
+the filesystem, and two more rules allowing DNS queries.
.. code-block:: c
@@ -604,6 +642,18 @@ Landlock audit events with the ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``,
sys_landlock_restrict_self(). See Documentation/admin-guide/LSM/landlock.rst
for more details on audit.
+UDP networking (ABI < 8)
+------------------------
+
+Starting with the Landlock ABI version 8, it is possible to restrict
+setting the local/remote ports of UDP sockets to specific values. Restrictions
+are now enforced at :manpage:`bind(2)` time with the new
+``LANDLOCK_ACCESS_NET_BIND_UDP`` access right, and at :manpage:`connect(2)`
+time with ``LANDLOCK_ACCESS_NET_CONNECT_UDP``. Finally,
+``LANDLOCK_ACCESS_NET_SENDTO_UDP`` also restricts sending datagrams with
+an explicit destination address (e.g. with :manpage:`sendmsg(2)`) to only some
+specific remote ports.
+
.. _kernel_support:
Kernel support
@@ -666,10 +716,10 @@ the boot loader.
Network support
---------------
-To be able to explicitly allow TCP operations (e.g., adding a network rule with
-``LANDLOCK_ACCESS_NET_BIND_TCP``), the kernel must support TCP
+To be able to explicitly allow TCP or UDP operations (e.g., adding a network rule with
+``LANDLOCK_ACCESS_NET_BIND_TCP``), the kernel must support the TCP/IP protocol suite
(``CONFIG_INET=y``). Otherwise, sys_landlock_add_rule() returns an
-``EAFNOSUPPORT`` error, which can safely be ignored because this kind of TCP
+``EAFNOSUPPORT`` error, which can safely be ignored because this kind of TCP or UDP
operation is already not possible.
Questions and answers
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 7/8] samples/landlock: Add sandboxer UDP access control
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Add environment variables to control associated access rights:
- LL_UDP_BIND
- LL_UDP_CONNECT
- LL_UDP_SENDTO
Each one takes a list of ports separated by colons, like other list
options.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
samples/landlock/sandboxer.c | 58 ++++++++++++++++++++++++++++++++++--
1 file changed, 56 insertions(+), 2 deletions(-)
diff --git a/samples/landlock/sandboxer.c b/samples/landlock/sandboxer.c
index e7af02f98208..65accc095926 100644
--- a/samples/landlock/sandboxer.c
+++ b/samples/landlock/sandboxer.c
@@ -62,6 +62,9 @@ static inline int landlock_restrict_self(const int ruleset_fd,
#define ENV_TCP_CONNECT_NAME "LL_TCP_CONNECT"
#define ENV_SCOPED_NAME "LL_SCOPED"
#define ENV_FORCE_LOG_NAME "LL_FORCE_LOG"
+#define ENV_UDP_BIND_NAME "LL_UDP_BIND"
+#define ENV_UDP_CONNECT_NAME "LL_UDP_CONNECT"
+#define ENV_UDP_SENDTO_NAME "LL_UDP_SENDTO"
#define ENV_DELIMITER ":"
static int str2num(const char *numstr, __u64 *num_dst)
@@ -299,7 +302,7 @@ static bool check_ruleset_scope(const char *const env_var,
/* clang-format on */
-#define LANDLOCK_ABI_LAST 7
+#define LANDLOCK_ABI_LAST 8
#define XSTR(s) #s
#define STR(s) XSTR(s)
@@ -322,6 +325,12 @@ static const char help[] =
"means an empty list):\n"
"* " ENV_TCP_BIND_NAME ": ports allowed to bind (server)\n"
"* " ENV_TCP_CONNECT_NAME ": ports allowed to connect (client)\n"
+ "* " ENV_UDP_BIND_NAME ": local UDP ports allowed to bind (server: "
+ "prepare to receive on port / client: set as source port)\n"
+ "* " ENV_UDP_CONNECT_NAME ": remote UDP ports allowed to connect "
+ "(client: set as destination port / server: receive only from it)\n"
+ "* " ENV_UDP_SENDTO_NAME ": remote UDP ports allowed to send to "
+ "without prior connect()\n"
"* " ENV_SCOPED_NAME ": actions denied on the outside of the landlock domain\n"
" - \"a\" to restrict opening abstract unix sockets\n"
" - \"s\" to restrict sending signals\n"
@@ -334,6 +343,8 @@ static const char help[] =
ENV_FS_RW_NAME "=\"/dev/null:/dev/full:/dev/zero:/dev/pts:/tmp\" "
ENV_TCP_BIND_NAME "=\"9418\" "
ENV_TCP_CONNECT_NAME "=\"80:443\" "
+ ENV_UDP_CONNECT_NAME "=\"53\" "
+ ENV_UDP_SENDTO_NAME "=\"53\" "
ENV_SCOPED_NAME "=\"a:s\" "
"%1$s bash -i\n"
"\n"
@@ -354,7 +365,10 @@ int main(const int argc, char *const argv[], char *const *const envp)
struct landlock_ruleset_attr ruleset_attr = {
.handled_access_fs = access_fs_rw,
.handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ LANDLOCK_ACCESS_NET_CONNECT_TCP |
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP,
.scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET |
LANDLOCK_SCOPE_SIGNAL,
};
@@ -436,6 +450,13 @@ int main(const int argc, char *const argv[], char *const *const envp)
/* Removes LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON for ABI < 7 */
supported_restrict_flags &=
~LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON;
+ __attribute__((fallthrough));
+ case 7:
+ /* Removes UDP support for ABI < 8 */
+ ruleset_attr.handled_access_net &=
+ ~(LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP |
+ LANDLOCK_ACCESS_NET_SENDTO_UDP);
/* Must be printed for any ABI < LANDLOCK_ABI_LAST. */
fprintf(stderr,
@@ -468,6 +489,27 @@ int main(const int argc, char *const argv[], char *const *const envp)
ruleset_attr.handled_access_net &=
~LANDLOCK_ACCESS_NET_CONNECT_TCP;
}
+ /* Removes UDP bind access control if not supported by a user. */
+ env_port_name = getenv(ENV_UDP_BIND_NAME);
+ if (!env_port_name) {
+ ruleset_attr.handled_access_net &=
+ ~LANDLOCK_ACCESS_NET_BIND_UDP;
+ }
+ /* Removes UDP connect access control if not supported by a user. */
+ env_port_name = getenv(ENV_UDP_CONNECT_NAME);
+ if (!env_port_name) {
+ ruleset_attr.handled_access_net &=
+ ~LANDLOCK_ACCESS_NET_CONNECT_UDP;
+ }
+ /*
+ * Removes UDP send with explicit address access control if not
+ * supported by a user.
+ */
+ env_port_name = getenv(ENV_UDP_SENDTO_NAME);
+ if (!env_port_name) {
+ ruleset_attr.handled_access_net &=
+ ~LANDLOCK_ACCESS_NET_SENDTO_UDP;
+ }
if (check_ruleset_scope(ENV_SCOPED_NAME, &ruleset_attr))
return 1;
@@ -512,6 +554,18 @@ int main(const int argc, char *const argv[], char *const *const envp)
LANDLOCK_ACCESS_NET_CONNECT_TCP)) {
goto err_close_ruleset;
}
+ if (populate_ruleset_net(ENV_UDP_BIND_NAME, ruleset_fd,
+ LANDLOCK_ACCESS_NET_BIND_UDP)) {
+ goto err_close_ruleset;
+ }
+ if (populate_ruleset_net(ENV_UDP_CONNECT_NAME, ruleset_fd,
+ LANDLOCK_ACCESS_NET_CONNECT_UDP)) {
+ goto err_close_ruleset;
+ }
+ if (populate_ruleset_net(ENV_UDP_SENDTO_NAME, ruleset_fd,
+ LANDLOCK_ACCESS_NET_SENDTO_UDP)) {
+ goto err_close_ruleset;
+ }
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("Failed to restrict privileges");
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 6/8] selftests/landlock: Add tests for UDP sendmsg
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Add tests specific to UDP sendmsg(), orthogonal to whether the process
is allowed to bind()/connect(). Make this part of the protocol_*
variants to ensure behaviour is consistent across AF_INET, AF_INET6 and
AF_UNIX.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
tools/testing/selftests/landlock/net_test.c | 306 +++++++++++++++++++-
1 file changed, 299 insertions(+), 7 deletions(-)
diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c
index 977d82eb9934..79ce52907ef3 100644
--- a/tools/testing/selftests/landlock/net_test.c
+++ b/tools/testing/selftests/landlock/net_test.c
@@ -268,9 +268,68 @@ static int connect_variant(const int sock_fd,
return connect_variant_addrlen(sock_fd, srv, get_addrlen(srv, false));
}
+static int sendto_variant_addrlen(const int sock_fd,
+ const struct service_fixture *const srv,
+ const socklen_t addrlen, void *buf,
+ size_t len, size_t flags)
+{
+ const struct sockaddr *dst = NULL;
+ ssize_t ret;
+
+ /*
+ * We never want our processes to be killed by SIGPIPE: we check
+ * return codes and errno, so that we have actual error messages.
+ */
+ flags |= MSG_NOSIGNAL;
+
+ if (srv != NULL) {
+ switch (srv->protocol.domain) {
+ case AF_UNSPEC:
+ case AF_INET:
+ dst = (const struct sockaddr *)&srv->ipv4_addr;
+ break;
+
+ case AF_INET6:
+ dst = (const struct sockaddr *)&srv->ipv6_addr;
+ break;
+
+ case AF_UNIX:
+ dst = (const struct sockaddr *)&srv->unix_addr;
+ break;
+
+ default:
+ errno = -EAFNOSUPPORT;
+ return -errno;
+ }
+ }
+
+ ret = sendto(sock_fd, buf, len, flags, dst, addrlen);
+ if (ret < 0)
+ return -errno;
+
+ /* errno is not set in cases of partial writes. */
+ if (ret != len)
+ return -EINTR;
+
+ return 0;
+}
+
+static int sendto_variant(const int sock_fd,
+ const struct service_fixture *const srv, void *buf,
+ size_t len, size_t flags)
+{
+ socklen_t addrlen = 0;
+
+ if (srv != NULL)
+ addrlen = get_addrlen(srv, false);
+
+ return sendto_variant_addrlen(sock_fd, srv, addrlen, buf, len, flags);
+}
+
FIXTURE(protocol)
{
- struct service_fixture srv0, srv1, srv2, unspec_any0, unspec_srv0;
+ struct service_fixture srv0, srv1, srv2;
+ struct service_fixture unspec_any0, unspec_srv0, unspec_srv1;
};
FIXTURE_VARIANT(protocol)
@@ -292,6 +351,7 @@ FIXTURE_SETUP(protocol)
ASSERT_EQ(0, set_service(&self->srv2, variant->prot, 2));
ASSERT_EQ(0, set_service(&self->unspec_srv0, prot_unspec, 0));
+ ASSERT_EQ(0, set_service(&self->unspec_srv1, prot_unspec, 1));
ASSERT_EQ(0, set_service(&self->unspec_any0, prot_unspec, 0));
self->unspec_any0.ipv4_addr.sin_addr.s_addr = htonl(INADDR_ANY);
@@ -1075,6 +1135,185 @@ TEST_F(protocol, connect_unspec)
EXPECT_EQ(0, close(bind_fd));
}
+TEST_F(protocol, sendmsg)
+{
+ /* Arbitrary value just to not block other tests indefinitely. */
+ const struct timeval read_timeout = {
+ .tv_sec = 0,
+ .tv_usec = 100000,
+ };
+ const bool sandboxed = variant->sandbox == UDP_SANDBOX &&
+ (variant->prot.domain == AF_INET ||
+ variant->prot.domain == AF_INET6);
+ int res, srv1_fd, srv0_fd, client_fd;
+ char read_buf[1] = { 0 };
+
+ if (variant->prot.type != SOCK_DGRAM)
+ return;
+
+ disable_caps(_metadata);
+
+ /* Prepare server on port #0 to be denied */
+ ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
+ srv0_fd = socket_variant(&self->srv0);
+ ASSERT_LE(0, srv0_fd);
+ ASSERT_EQ(0, bind_variant(srv0_fd, &self->srv0));
+
+ /* And another server on port #1 to be allowed */
+ ASSERT_EQ(0, set_service(&self->srv1, variant->prot, 1));
+ srv1_fd = socket_variant(&self->srv1);
+ ASSERT_LE(0, srv1_fd);
+ ASSERT_EQ(0, bind_variant(srv1_fd, &self->srv1));
+
+ EXPECT_EQ(0, setsockopt(srv0_fd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout,
+ sizeof(read_timeout)));
+ EXPECT_EQ(0, setsockopt(srv1_fd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout,
+ sizeof(read_timeout)));
+
+ client_fd = socket_variant(&self->srv0);
+ ASSERT_LE(0, client_fd);
+
+ if (sandboxed) {
+ const struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_net = LANDLOCK_ACCESS_NET_SENDTO_UDP |
+ LANDLOCK_ACCESS_NET_BIND_UDP,
+ };
+ const struct landlock_net_port_attr allow_one_server = {
+ .allowed_access = LANDLOCK_ACCESS_NET_SENDTO_UDP,
+ .port = self->srv1.port,
+ };
+ const int ruleset_fd = landlock_create_ruleset(
+ &ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+ ASSERT_EQ(0,
+ landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+ &allow_one_server, 0));
+ enforce_ruleset(_metadata, ruleset_fd);
+ EXPECT_EQ(0, close(ruleset_fd));
+ }
+
+ /* No connect(), NULL address */
+ EXPECT_EQ(-1, write(client_fd, "A", 1));
+ if (variant->prot.domain == AF_UNIX) {
+ EXPECT_EQ(ENOTCONN, errno);
+ } else {
+ EXPECT_EQ(EDESTADDRREQ, errno);
+ }
+
+ /* No connect(), non-NULL but too small explicit address */
+ EXPECT_EQ(-EINVAL,
+ sendto_variant_addrlen(client_fd, &self->srv0,
+ get_addrlen(&self->srv0, true) - 1,
+ "B", 1, 0));
+
+ /* No connect(), explicit denied port */
+ res = sendto_variant(client_fd, &self->srv0, "C", 1, 0);
+ if (sandboxed) {
+ EXPECT_EQ(-EACCES, res);
+ } else {
+ EXPECT_EQ(0, res);
+ EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+ EXPECT_EQ(read_buf[0], 'C');
+ }
+
+ /* No connect(), explicit allowed port */
+ EXPECT_EQ(0, sendto_variant(client_fd, &self->srv1, "D", 1, 0));
+ EXPECT_EQ(1, read(srv1_fd, read_buf, 1));
+ EXPECT_EQ(read_buf[0], 'D');
+
+ /* Explicit AF_UNSPEC address but truncated */
+ EXPECT_EQ(-EINVAL, sendto_variant_addrlen(
+ client_fd, &self->unspec_srv0,
+ get_addrlen(&self->unspec_srv0, true) - 1,
+ "E", 1, 0));
+
+ /* Explicit AF_UNSPEC address, should always be denied */
+ res = sendto_variant(client_fd, &self->unspec_srv1, "F", 1, 0);
+ if (sandboxed) {
+ EXPECT_EQ(-EACCES, res);
+ } else {
+ if (variant->prot.domain == AF_INET) {
+ /* IPv4 sockets treat AF_UNSPEC as AF_INET */
+ EXPECT_EQ(0, res);
+ EXPECT_EQ(1, read(srv1_fd, read_buf, 1))
+ {
+ TH_LOG("read() failed: %s", strerror(errno));
+ }
+ EXPECT_EQ(read_buf[0], 'F');
+ } else if (variant->prot.domain == AF_INET6) {
+ /* IPv6 sockets treat AF_UNSPEC as a NULL address */
+ EXPECT_EQ(-EDESTADDRREQ, res);
+ } else {
+ /* Unix sockets don't accept AF_UNSPEC */
+ EXPECT_EQ(-EINVAL, res);
+ }
+ }
+
+ /* With connect() on an allowed explicit port, no explicit address */
+ ASSERT_EQ(0, connect_variant(client_fd, &self->srv1));
+ EXPECT_EQ(0, sendto_variant(client_fd, NULL, "G", 1, 0));
+ EXPECT_EQ(1, read(srv1_fd, read_buf, 1));
+ EXPECT_EQ(read_buf[0], 'G');
+
+ /* With connect() on a denied explicit port, no explicit address */
+ ASSERT_EQ(0, connect_variant(client_fd, &self->srv0));
+ EXPECT_EQ(0, sendto_variant(client_fd, NULL, "H", 1, 0));
+ EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+ EXPECT_EQ(read_buf[0], 'H');
+
+ /* Explicit AF_UNSPEC minimal address (just the sa_family_t field) */
+ res = sendto_variant_addrlen(client_fd, &self->unspec_srv0,
+ get_addrlen(&self->unspec_srv0, true), "I",
+ 1, 0);
+ if (sandboxed) {
+ EXPECT_EQ(-EACCES, res);
+ } else if (variant->prot.domain == AF_INET6) {
+ /*
+ * IPv6 sockets treat AF_UNSPEC as a NULL address,
+ * falling back to the connected address
+ */
+ EXPECT_EQ(0, res);
+ EXPECT_EQ(1, read(srv0_fd, read_buf, 1));
+ EXPECT_EQ(read_buf[0], 'I');
+ } else {
+ /*
+ * IPv4 socket will expect a struct sockaddr_in, our address
+ * is considered truncated.
+ * And Unix sockets don't accept AF_UNSPEC at all.
+ */
+ EXPECT_EQ(-EINVAL, res);
+ }
+
+ /* Explicit AF_UNSPEC address, should always be denied */
+ res = sendto_variant(client_fd, &self->unspec_srv1, "J", 1, 0);
+ if (sandboxed) {
+ EXPECT_EQ(-EACCES, res);
+ } else if (variant->prot.domain == AF_INET ||
+ variant->prot.domain == AF_INET6) {
+ int read_fd;
+
+ EXPECT_EQ(0, res);
+ if (variant->prot.domain == AF_INET) {
+ /* IPv4 sockets treat AF_UNSPEC as AF_INET */
+ read_fd = srv1_fd;
+ } else {
+ /*
+ * IPv6 sockets treat AF_UNSPEC as a NULL address,
+ * falling back to the connected address
+ */
+ read_fd = srv0_fd;
+ }
+ EXPECT_EQ(1, read(read_fd, read_buf, 1))
+ {
+ TH_LOG("read failed: %s", strerror(errno));
+ }
+ EXPECT_EQ(read_buf[0], 'J');
+ } else {
+ /* Unix sockets don't accept AF_UNSPEC */
+ EXPECT_EQ(-EINVAL, res);
+ }
+}
+
FIXTURE(ipv4)
{
struct service_fixture srv0, srv1;
@@ -1470,13 +1709,14 @@ FIXTURE_TEARDOWN(mini)
/* clang-format off */
-#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_UDP
+#define ACCESS_LAST LANDLOCK_ACCESS_NET_SENDTO_UDP
#define ACCESS_ALL ( \
LANDLOCK_ACCESS_NET_BIND_TCP | \
LANDLOCK_ACCESS_NET_CONNECT_TCP | \
LANDLOCK_ACCESS_NET_BIND_UDP | \
- LANDLOCK_ACCESS_NET_CONNECT_UDP)
+ LANDLOCK_ACCESS_NET_CONNECT_UDP | \
+ LANDLOCK_ACCESS_NET_SENDTO_UDP)
/* clang-format on */
@@ -2078,19 +2318,26 @@ static int matches_log_prot(const int audit_fd, const char *const blockers,
const char *const dir_addr, const char *const addr,
const char *const dir_port)
{
- static const char log_template[] = REGEX_LANDLOCK_PREFIX
+ static const char tmpl_with_addr_port[] = REGEX_LANDLOCK_PREFIX
" blockers=%s %s=%s %s=1024$";
+ static const char tmpl_no_addr_port[] = REGEX_LANDLOCK_PREFIX
+ " blockers=%s$";
/*
* Max strlen(blockers): 16
* Max strlen(dir_addr): 5
* Max strlen(addr): 12
* Max strlen(dir_port): 4
*/
- char log_match[sizeof(log_template) + 37];
+ char log_match[sizeof(tmpl_with_addr_port) + 37];
int log_match_len;
- log_match_len = snprintf(log_match, sizeof(log_match), log_template,
- blockers, dir_addr, addr, dir_port);
+ if (addr != NULL)
+ log_match_len = snprintf(log_match, sizeof(log_match), tmpl_with_addr_port,
+ blockers, dir_addr, addr, dir_port);
+ else
+ log_match_len = snprintf(log_match, sizeof(log_match), tmpl_no_addr_port,
+ blockers);
+
if (log_match_len > sizeof(log_match))
return -E2BIG;
@@ -2101,6 +2348,7 @@ static int matches_log_prot(const int audit_fd, const char *const blockers,
FIXTURE(audit)
{
struct service_fixture srv0;
+ struct service_fixture unspec_srv0;
struct audit_filter audit_filter;
int audit_fd;
};
@@ -2153,7 +2401,13 @@ FIXTURE_VARIANT_ADD(audit, ipv6_udp) {
FIXTURE_SETUP(audit)
{
+ struct protocol_variant prot_unspec = variant->prot;
+
+ prot_unspec.domain = AF_UNSPEC;
+
ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
+ ASSERT_EQ(0, set_service(&self->unspec_srv0, prot_unspec, 0));
+
setup_loopback(_metadata);
set_cap(_metadata, CAP_AUDIT_CONTROL);
@@ -2241,4 +2495,42 @@ TEST_F(audit, connect)
EXPECT_EQ(0, close(sock_fd));
}
+TEST_F(audit, sendmsg)
+{
+ const struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_net = LANDLOCK_ACCESS_NET_SENDTO_UDP,
+ };
+ struct audit_records records;
+ int ruleset_fd, sock_fd;
+
+ if (variant->prot.type != SOCK_DGRAM)
+ return;
+
+ ruleset_fd =
+ landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+ enforce_ruleset(_metadata, ruleset_fd);
+ EXPECT_EQ(0, close(ruleset_fd));
+
+ sock_fd = socket_variant(&self->srv0);
+ ASSERT_LE(0, sock_fd);
+ EXPECT_EQ(-EACCES, sendto_variant(sock_fd, &self->srv0, "A", 1, 0));
+ EXPECT_EQ(0, matches_log_prot(self->audit_fd, "net.sendto_udp", "daddr",
+ variant->addr, "dest"));
+
+ EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+ EXPECT_EQ(0, records.access);
+ EXPECT_EQ(1, records.domain);
+
+ EXPECT_EQ(-EACCES, sendto_variant(sock_fd, &self->unspec_srv0, "B", 1, 0));
+ EXPECT_EQ(0, matches_log_prot(self->audit_fd, "net.sendto_udp", "daddr",
+ NULL, "dest"));
+
+ EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
+ EXPECT_EQ(0, records.access);
+ EXPECT_EQ(0, records.domain);
+
+ EXPECT_EQ(0, close(sock_fd));
+}
+
TEST_HARNESS_MAIN
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 4/8] selftests/landlock: Add UDP bind/connect tests
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Make basic changes to the existing bind() and connect() test suite to
also encompass testing UDP access control.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
tools/testing/selftests/landlock/base_test.c | 2 +-
tools/testing/selftests/landlock/net_test.c | 389 ++++++++++++++-----
2 files changed, 303 insertions(+), 88 deletions(-)
diff --git a/tools/testing/selftests/landlock/base_test.c b/tools/testing/selftests/landlock/base_test.c
index 7b69002239d7..f4b1a275d8d9 100644
--- a/tools/testing/selftests/landlock/base_test.c
+++ b/tools/testing/selftests/landlock/base_test.c
@@ -76,7 +76,7 @@ TEST(abi_version)
const struct landlock_ruleset_attr ruleset_attr = {
.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
};
- ASSERT_EQ(7, landlock_create_ruleset(NULL, 0,
+ ASSERT_EQ(8, landlock_create_ruleset(NULL, 0,
LANDLOCK_CREATE_RULESET_VERSION));
ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c
index b34b139b3f89..977d82eb9934 100644
--- a/tools/testing/selftests/landlock/net_test.c
+++ b/tools/testing/selftests/landlock/net_test.c
@@ -35,6 +35,7 @@ enum sandbox_type {
NO_SANDBOX,
/* This may be used to test rules that allow *and* deny accesses. */
TCP_SANDBOX,
+ UDP_SANDBOX,
};
static int set_service(struct service_fixture *const srv,
@@ -93,11 +94,20 @@ static bool prot_is_tcp(const struct protocol_variant *const prot)
(prot->protocol == IPPROTO_TCP || prot->protocol == IPPROTO_IP);
}
+static bool prot_is_udp(const struct protocol_variant *const prot)
+{
+ return (prot->domain == AF_INET || prot->domain == AF_INET6) &&
+ prot->type == SOCK_DGRAM &&
+ (prot->protocol == IPPROTO_UDP || prot->protocol == IPPROTO_IP);
+}
+
static bool is_restricted(const struct protocol_variant *const prot,
const enum sandbox_type sandbox)
{
if (sandbox == TCP_SANDBOX)
return prot_is_tcp(prot);
+ else if (sandbox == UDP_SANDBOX)
+ return prot_is_udp(prot);
return false;
}
@@ -271,10 +281,9 @@ FIXTURE_VARIANT(protocol)
FIXTURE_SETUP(protocol)
{
- const struct protocol_variant prot_unspec = {
- .domain = AF_UNSPEC,
- .type = SOCK_STREAM,
- };
+ struct protocol_variant prot_unspec = variant->prot;
+
+ prot_unspec.domain = AF_UNSPEC;
disable_caps(_metadata);
@@ -510,6 +519,92 @@ FIXTURE_VARIANT_ADD(protocol, tcp_sandbox_with_unix_datagram) {
},
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_udp1) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET,
+ .type = SOCK_DGRAM,
+ .protocol = IPPROTO_UDP,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_udp2) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET,
+ .type = SOCK_DGRAM,
+ /* IPPROTO_IP == 0 */
+ .protocol = IPPROTO_IP,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_udp1) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET6,
+ .type = SOCK_DGRAM,
+ .protocol = IPPROTO_UDP,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_udp2) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET6,
+ .type = SOCK_DGRAM,
+ /* IPPROTO_IP == 0 */
+ .protocol = IPPROTO_IP,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv4_tcp) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET,
+ .type = SOCK_STREAM,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_ipv6_tcp) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET6,
+ .type = SOCK_STREAM,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_unix_stream) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_UNIX,
+ .type = SOCK_STREAM,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(protocol, udp_sandbox_with_unix_datagram) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_UNIX,
+ .type = SOCK_DGRAM,
+ },
+};
+
static void test_bind_and_connect(struct __test_metadata *const _metadata,
const struct service_fixture *const srv,
const bool deny_bind, const bool deny_connect)
@@ -602,7 +697,7 @@ static void test_bind_and_connect(struct __test_metadata *const _metadata,
ret = connect_variant(connect_fd, srv);
if (deny_connect) {
EXPECT_EQ(-EACCES, ret);
- } else if (deny_bind) {
+ } else if (deny_bind && srv->protocol.type == SOCK_STREAM) {
/* No listening server. */
EXPECT_EQ(-ECONNREFUSED, ret);
} else {
@@ -641,18 +736,25 @@ static void test_bind_and_connect(struct __test_metadata *const _metadata,
TEST_F(protocol, bind)
{
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const __u64 bind_access =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP);
+ const __u64 connect_access =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = bind_access | connect_access,
};
- const struct landlock_net_port_attr tcp_bind_connect_p0 = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr bind_connect_p0 = {
+ .allowed_access = bind_access | connect_access,
.port = self->srv0.port,
};
- const struct landlock_net_port_attr tcp_connect_p1 = {
- .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr connect_p1 = {
+ .allowed_access = connect_access,
.port = self->srv1.port,
};
int ruleset_fd;
@@ -664,12 +766,12 @@ TEST_F(protocol, bind)
/* Allows connect and bind for the first port. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_connect_p0, 0));
+ &bind_connect_p0, 0));
/* Allows connect and denies bind for the second port. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_connect_p1, 0));
+ &connect_p1, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
@@ -691,18 +793,25 @@ TEST_F(protocol, bind)
TEST_F(protocol, connect)
{
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const __u64 bind_access =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP);
+ const __u64 connect_access =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = bind_access | connect_access,
};
- const struct landlock_net_port_attr tcp_bind_connect_p0 = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr bind_connect_p0 = {
+ .allowed_access = bind_access | connect_access,
.port = self->srv0.port,
};
- const struct landlock_net_port_attr tcp_bind_p1 = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+ const struct landlock_net_port_attr bind_p1 = {
+ .allowed_access = bind_access,
.port = self->srv1.port,
};
int ruleset_fd;
@@ -714,12 +823,12 @@ TEST_F(protocol, connect)
/* Allows connect and bind for the first port. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_connect_p0, 0));
+ &bind_connect_p0, 0));
/* Allows bind and denies connect for the second port. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_p1, 0));
+ &bind_p1, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
@@ -737,16 +846,24 @@ TEST_F(protocol, connect)
TEST_F(protocol, bind_unspec)
{
- const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
- };
- const struct landlock_net_port_attr tcp_bind = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
- .port = self->srv0.port,
- };
+ const int bind_access_right = (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP);
int bind_fd, ret;
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_net = bind_access_right,
+ };
+ const struct landlock_net_port_attr bind = {
+ .allowed_access =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP),
+ .port = self->srv0.port,
+ };
+
const int ruleset_fd = landlock_create_ruleset(
&ruleset_attr, sizeof(ruleset_attr), 0);
ASSERT_LE(0, ruleset_fd);
@@ -754,7 +871,7 @@ TEST_F(protocol, bind_unspec)
/* Allows bind. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind, 0));
+ &bind, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
}
@@ -782,7 +899,11 @@ TEST_F(protocol, bind_unspec)
}
EXPECT_EQ(0, close(bind_fd));
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_net = bind_access_right,
+ };
const int ruleset_fd = landlock_create_ruleset(
&ruleset_attr, sizeof(ruleset_attr), 0);
ASSERT_LE(0, ruleset_fd);
@@ -829,10 +950,12 @@ TEST_F(protocol, bind_unspec)
TEST_F(protocol, connect_unspec)
{
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = LANDLOCK_ACCESS_NET_CONNECT_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP,
};
- const struct landlock_net_port_attr tcp_connect = {
- .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr connect = {
+ .allowed_access = LANDLOCK_ACCESS_NET_CONNECT_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP,
.port = self->srv0.port,
};
int bind_fd, client_fd, status;
@@ -865,7 +988,8 @@ TEST_F(protocol, connect_unspec)
EXPECT_EQ(0, ret);
}
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
const int ruleset_fd = landlock_create_ruleset(
&ruleset_attr, sizeof(ruleset_attr), 0);
ASSERT_LE(0, ruleset_fd);
@@ -873,7 +997,7 @@ TEST_F(protocol, connect_unspec)
/* Allows connect. */
ASSERT_EQ(0, landlock_add_rule(ruleset_fd,
LANDLOCK_RULE_NET_PORT,
- &tcp_connect, 0));
+ &connect, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
}
@@ -896,7 +1020,8 @@ TEST_F(protocol, connect_unspec)
EXPECT_EQ(0, ret);
}
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
const int ruleset_fd = landlock_create_ruleset(
&ruleset_attr, sizeof(ruleset_attr), 0);
ASSERT_LE(0, ruleset_fd);
@@ -975,6 +1100,13 @@ FIXTURE_VARIANT_ADD(ipv4, tcp_sandbox_with_tcp) {
.type = SOCK_STREAM,
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(ipv4, udp_sandbox_with_tcp) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .type = SOCK_STREAM,
+};
+
/* clang-format off */
FIXTURE_VARIANT_ADD(ipv4, no_sandbox_with_udp) {
/* clang-format on */
@@ -989,6 +1121,13 @@ FIXTURE_VARIANT_ADD(ipv4, tcp_sandbox_with_udp) {
.type = SOCK_DGRAM,
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(ipv4, udp_sandbox_with_udp) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .type = SOCK_DGRAM,
+};
+
FIXTURE_SETUP(ipv4)
{
const struct protocol_variant prot = {
@@ -1010,16 +1149,21 @@ FIXTURE_TEARDOWN(ipv4)
TEST_F(ipv4, from_unix_to_inet)
{
+ const int access_rights =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
int unix_stream_fd, unix_dgram_fd;
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = access_rights,
};
- const struct landlock_net_port_attr tcp_bind_connect_p0 = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr bind_connect_p0 = {
+ .allowed_access = access_rights,
.port = self->srv0.port,
};
int ruleset_fd;
@@ -1032,7 +1176,7 @@ TEST_F(ipv4, from_unix_to_inet)
/* Allows connect and bind for srv0. */
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_connect_p0, 0));
+ &bind_connect_p0, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
@@ -1326,11 +1470,13 @@ FIXTURE_TEARDOWN(mini)
/* clang-format off */
-#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_TCP
+#define ACCESS_LAST LANDLOCK_ACCESS_NET_CONNECT_UDP
#define ACCESS_ALL ( \
LANDLOCK_ACCESS_NET_BIND_TCP | \
- LANDLOCK_ACCESS_NET_CONNECT_TCP)
+ LANDLOCK_ACCESS_NET_CONNECT_TCP | \
+ LANDLOCK_ACCESS_NET_BIND_UDP | \
+ LANDLOCK_ACCESS_NET_CONNECT_UDP)
/* clang-format on */
@@ -1697,7 +1843,7 @@ FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv4) {
};
/* clang-format off */
-FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv4) {
+FIXTURE_VARIANT_ADD(port_specific, tcp_sandbox_with_ipv4) {
/* clang-format on */
.sandbox = TCP_SANDBOX,
.prot = {
@@ -1706,6 +1852,16 @@ FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv4) {
},
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(port_specific, udp_sandbox_with_ipv4) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET,
+ .type = SOCK_DGRAM,
+ },
+};
+
/* clang-format off */
FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv6) {
/* clang-format on */
@@ -1717,7 +1873,7 @@ FIXTURE_VARIANT_ADD(port_specific, no_sandbox_with_ipv6) {
};
/* clang-format off */
-FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv6) {
+FIXTURE_VARIANT_ADD(port_specific, tcp_sandbox_with_ipv6) {
/* clang-format on */
.sandbox = TCP_SANDBOX,
.prot = {
@@ -1726,6 +1882,16 @@ FIXTURE_VARIANT_ADD(port_specific, sandbox_with_ipv6) {
},
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(port_specific, udp_sandbox_with_ipv6) {
+ /* clang-format on */
+ .sandbox = UDP_SANDBOX,
+ .prot = {
+ .domain = AF_INET6,
+ .type = SOCK_DGRAM,
+ },
+};
+
FIXTURE_SETUP(port_specific)
{
disable_caps(_metadata);
@@ -1745,14 +1911,19 @@ TEST_F(port_specific, bind_connect_zero)
uint16_t port;
/* Adds a rule layer with bind and connect actions. */
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const int access_rights =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP
+ .handled_access_net = access_rights,
};
const struct landlock_net_port_attr tcp_bind_connect_zero = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .allowed_access = access_rights,
.port = 0,
};
int ruleset_fd;
@@ -1785,11 +1956,13 @@ TEST_F(port_specific, bind_connect_zero)
ret = bind_variant(bind_fd, &self->srv0);
EXPECT_EQ(0, ret);
- EXPECT_EQ(0, listen(bind_fd, backlog));
+ if (variant->prot.type == SOCK_STREAM) {
+ EXPECT_EQ(0, listen(bind_fd, backlog));
- /* Connects on port 0. */
- ret = connect_variant(connect_fd, &self->srv0);
- EXPECT_EQ(-ECONNREFUSED, ret);
+ /* Connects on port 0. */
+ ret = connect_variant(connect_fd, &self->srv0);
+ EXPECT_EQ(-ECONNREFUSED, ret);
+ }
/* Sets binded port for both protocol families. */
port = get_binded_port(bind_fd, &variant->prot);
@@ -1813,21 +1986,25 @@ TEST_F(port_specific, bind_connect_1023)
int bind_fd, connect_fd, ret;
/* Adds a rule layer with bind and connect actions. */
- if (variant->sandbox == TCP_SANDBOX) {
+ if (variant->sandbox == TCP_SANDBOX ||
+ variant->sandbox == UDP_SANDBOX) {
+ const int access_rights =
+ (variant->sandbox == TCP_SANDBOX ?
+ LANDLOCK_ACCESS_NET_BIND_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP
+ .handled_access_net = access_rights,
};
/* A rule with port value less than 1024. */
- const struct landlock_net_port_attr tcp_bind_connect_low_range = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr bind_connect_low_range = {
+ .allowed_access = access_rights,
.port = 1023,
};
/* A rule with 1024 port. */
- const struct landlock_net_port_attr tcp_bind_connect = {
- .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ const struct landlock_net_port_attr bind_connect = {
+ .allowed_access = access_rights,
.port = 1024,
};
int ruleset_fd;
@@ -1838,10 +2015,10 @@ TEST_F(port_specific, bind_connect_1023)
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_connect_low_range, 0));
+ &bind_connect_low_range, 0));
ASSERT_EQ(0,
landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
- &tcp_bind_connect, 0));
+ &bind_connect, 0));
enforce_ruleset(_metadata, ruleset_fd);
EXPECT_EQ(0, close(ruleset_fd));
@@ -1865,7 +2042,8 @@ TEST_F(port_specific, bind_connect_1023)
ret = bind_variant(bind_fd, &self->srv0);
clear_cap(_metadata, CAP_NET_BIND_SERVICE);
EXPECT_EQ(0, ret);
- EXPECT_EQ(0, listen(bind_fd, backlog));
+ if (variant->prot.type == SOCK_STREAM)
+ EXPECT_EQ(0, listen(bind_fd, backlog));
/* Connects on the binded port 1023. */
ret = connect_variant(connect_fd, &self->srv0);
@@ -1885,7 +2063,8 @@ TEST_F(port_specific, bind_connect_1023)
/* Binds on port 1024. */
ret = bind_variant(bind_fd, &self->srv0);
EXPECT_EQ(0, ret);
- EXPECT_EQ(0, listen(bind_fd, backlog));
+ if (variant->prot.type == SOCK_STREAM)
+ EXPECT_EQ(0, listen(bind_fd, backlog));
/* Connects on the binded port 1024. */
ret = connect_variant(connect_fd, &self->srv0);
@@ -1895,9 +2074,9 @@ TEST_F(port_specific, bind_connect_1023)
EXPECT_EQ(0, close(bind_fd));
}
-static int matches_log_tcp(const int audit_fd, const char *const blockers,
- const char *const dir_addr, const char *const addr,
- const char *const dir_port)
+static int matches_log_prot(const int audit_fd, const char *const blockers,
+ const char *const dir_addr, const char *const addr,
+ const char *const dir_port)
{
static const char log_template[] = REGEX_LANDLOCK_PREFIX
" blockers=%s %s=%s %s=1024$";
@@ -1933,7 +2112,7 @@ FIXTURE_VARIANT(audit)
};
/* clang-format off */
-FIXTURE_VARIANT_ADD(audit, ipv4) {
+FIXTURE_VARIANT_ADD(audit, ipv4_tcp) {
/* clang-format on */
.addr = "127\\.0\\.0\\.1",
.prot = {
@@ -1943,7 +2122,17 @@ FIXTURE_VARIANT_ADD(audit, ipv4) {
};
/* clang-format off */
-FIXTURE_VARIANT_ADD(audit, ipv6) {
+FIXTURE_VARIANT_ADD(audit, ipv4_udp) {
+ /* clang-format on */
+ .addr = "127\\.0\\.0\\.1",
+ .prot = {
+ .domain = AF_INET,
+ .type = SOCK_DGRAM,
+ },
+};
+
+/* clang-format off */
+FIXTURE_VARIANT_ADD(audit, ipv6_tcp) {
/* clang-format on */
.addr = "::1",
.prot = {
@@ -1952,6 +2141,16 @@ FIXTURE_VARIANT_ADD(audit, ipv6) {
},
};
+/* clang-format off */
+FIXTURE_VARIANT_ADD(audit, ipv6_udp) {
+ /* clang-format on */
+ .addr = "::1",
+ .prot = {
+ .domain = AF_INET6,
+ .type = SOCK_DGRAM,
+ },
+};
+
FIXTURE_SETUP(audit)
{
ASSERT_EQ(0, set_service(&self->srv0, variant->prot, 0));
@@ -1972,9 +2171,17 @@ FIXTURE_TEARDOWN(audit)
TEST_F(audit, bind)
{
+ const char *audit_evt = (variant->prot.type == SOCK_STREAM ?
+ "net\\.bind_tcp" :
+ "net\\.bind_udp");
+ const int access_rights =
+ (variant->prot.type == SOCK_STREAM ?
+ LANDLOCK_ACCESS_NET_BIND_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = access_rights,
};
struct audit_records records;
int ruleset_fd, sock_fd;
@@ -1988,8 +2195,8 @@ TEST_F(audit, bind)
sock_fd = socket_variant(&self->srv0);
ASSERT_LE(0, sock_fd);
EXPECT_EQ(-EACCES, bind_variant(sock_fd, &self->srv0));
- EXPECT_EQ(0, matches_log_tcp(self->audit_fd, "net\\.bind_tcp", "saddr",
- variant->addr, "src"));
+ EXPECT_EQ(0, matches_log_prot(self->audit_fd, audit_evt, "saddr",
+ variant->addr, "src"));
EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
EXPECT_EQ(0, records.access);
@@ -2000,9 +2207,17 @@ TEST_F(audit, bind)
TEST_F(audit, connect)
{
+ const char *audit_evt = (variant->prot.type == SOCK_STREAM ?
+ "net\\.connect_tcp" :
+ "net\\.connect_udp");
+ const int access_rights =
+ (variant->prot.type == SOCK_STREAM ?
+ LANDLOCK_ACCESS_NET_BIND_TCP |
+ LANDLOCK_ACCESS_NET_CONNECT_TCP :
+ LANDLOCK_ACCESS_NET_BIND_UDP |
+ LANDLOCK_ACCESS_NET_CONNECT_UDP);
const struct landlock_ruleset_attr ruleset_attr = {
- .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP |
- LANDLOCK_ACCESS_NET_CONNECT_TCP,
+ .handled_access_net = access_rights,
};
struct audit_records records;
int ruleset_fd, sock_fd;
@@ -2016,8 +2231,8 @@ TEST_F(audit, connect)
sock_fd = socket_variant(&self->srv0);
ASSERT_LE(0, sock_fd);
EXPECT_EQ(-EACCES, connect_variant(sock_fd, &self->srv0));
- EXPECT_EQ(0, matches_log_tcp(self->audit_fd, "net\\.connect_tcp",
- "daddr", variant->addr, "dest"));
+ EXPECT_EQ(0, matches_log_prot(self->audit_fd, audit_evt, "daddr",
+ variant->addr, "dest"));
EXPECT_EQ(0, audit_count_records(self->audit_fd, &records));
EXPECT_EQ(0, records.access);
--
2.47.3
^ permalink raw reply related
* [RFC PATCH v3 5/8] landlock: Add UDP sendmsg access control
From: Matthieu Buffet @ 2025-12-12 16:37 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, linux-security-module, Mikhail Ivanov,
konstantin.meskhidze, netdev, Matthieu Buffet
In-Reply-To: <20251212163704.142301-1-matthieu@buffet.re>
Add support for a LANDLOCK_ACCESS_NET_SENDTO_UDP access right, providing
control over specifying a UDP datagram's destination address explicitly
in sendto(), sendmsg(), and sendmmsg().
This complements the previous control of connect() via
LANDLOCK_ACCESS_NET_CONNECT_UDP.
Signed-off-by: Matthieu Buffet <matthieu@buffet.re>
---
include/uapi/linux/landlock.h | 13 ++++++++
security/landlock/audit.c | 1 +
security/landlock/limits.h | 2 +-
security/landlock/net.c | 61 +++++++++++++++++++++++++++++++++--
4 files changed, 74 insertions(+), 3 deletions(-)
diff --git a/include/uapi/linux/landlock.h b/include/uapi/linux/landlock.h
index 8f748fcf79dd..c43586e02216 100644
--- a/include/uapi/linux/landlock.h
+++ b/include/uapi/linux/landlock.h
@@ -352,12 +352,25 @@ struct landlock_net_port_attr {
* - %LANDLOCK_ACCESS_NET_CONNECT_UDP: Connect UDP sockets to remote
* addresses with the given remote port. Support added in Landlock ABI
* version 8.
+ * - %LANDLOCK_ACCESS_NET_SENDTO_UDP: Send datagrams on UDP sockets with
+ * an explicit destination address set to the given remote port.
+ * Support added in Landlock ABI version 8. Note: this access right
+ * does not control sending datagrams with no explicit destination
+ * (e.g. via :manpage:`send(2)` or ``sendto(..., NULL, 0)``, so this
+ * access right is not necessary when specifying a destination address
+ * once and for all in :manpage:`connect(2)`.
+ *
+ * Note: sending datagrams to an explicit ``AF_UNSPEC`` destination
+ * address family is not supported. For IPv4 sockets, you will need to
+ * use an ``AF_INET`` address instead, and for IPv6 sockets, you will
+ * need to use a ``NULL`` address.
*/
/* clang-format off */
#define LANDLOCK_ACCESS_NET_BIND_TCP (1ULL << 0)
#define LANDLOCK_ACCESS_NET_CONNECT_TCP (1ULL << 1)
#define LANDLOCK_ACCESS_NET_BIND_UDP (1ULL << 2)
#define LANDLOCK_ACCESS_NET_CONNECT_UDP (1ULL << 3)
+#define LANDLOCK_ACCESS_NET_SENDTO_UDP (1ULL << 4)
/* clang-format on */
/**
diff --git a/security/landlock/audit.c b/security/landlock/audit.c
index 23d8dee320ef..e0c030727dab 100644
--- a/security/landlock/audit.c
+++ b/security/landlock/audit.c
@@ -46,6 +46,7 @@ static const char *const net_access_strings[] = {
[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_TCP)] = "net.connect_tcp",
[BIT_INDEX(LANDLOCK_ACCESS_NET_BIND_UDP)] = "net.bind_udp",
[BIT_INDEX(LANDLOCK_ACCESS_NET_CONNECT_UDP)] = "net.connect_udp",
+ [BIT_INDEX(LANDLOCK_ACCESS_NET_SENDTO_UDP)] = "net.sendto_udp",
};
static_assert(ARRAY_SIZE(net_access_strings) == LANDLOCK_NUM_ACCESS_NET);
diff --git a/security/landlock/limits.h b/security/landlock/limits.h
index 13dd5503e471..b6d26bc5c49e 100644
--- a/security/landlock/limits.h
+++ b/security/landlock/limits.h
@@ -23,7 +23,7 @@
#define LANDLOCK_MASK_ACCESS_FS ((LANDLOCK_LAST_ACCESS_FS << 1) - 1)
#define LANDLOCK_NUM_ACCESS_FS __const_hweight64(LANDLOCK_MASK_ACCESS_FS)
-#define LANDLOCK_LAST_ACCESS_NET LANDLOCK_ACCESS_NET_CONNECT_UDP
+#define LANDLOCK_LAST_ACCESS_NET LANDLOCK_ACCESS_NET_SENDTO_UDP
#define LANDLOCK_MASK_ACCESS_NET ((LANDLOCK_LAST_ACCESS_NET << 1) - 1)
#define LANDLOCK_NUM_ACCESS_NET __const_hweight64(LANDLOCK_MASK_ACCESS_NET)
diff --git a/security/landlock/net.c b/security/landlock/net.c
index 9bddcf466ce9..061a531339de 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -121,6 +121,34 @@ static int current_check_access_socket(struct socket *const sock,
else
return -EAFNOSUPPORT;
}
+ } else if (access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
+ /*
+ * We cannot allow LANDLOCK_ACCESS_NET_SENDTO_UDP on an
+ * explicit AF_UNSPEC address. That's because semantics
+ * of AF_UNSPEC change between socket families (e.g.
+ * IPv6 treat it as "no address" in the sendmsg()
+ * syscall family, so we should always allow, whilst
+ * IPv4 treat it as AF_INET, so we should filter based
+ * on port, and future address families might even do
+ * something else), and the socket's family can change
+ * under our feet due to setsockopt(IPV6_ADDRFORM).
+ */
+ audit_net.family = AF_UNSPEC;
+ landlock_init_layer_masks(subject->domain,
+ access_request, &layer_masks,
+ LANDLOCK_KEY_NET_PORT);
+ landlock_log_denial(
+ subject,
+ &(struct landlock_request){
+ .type = LANDLOCK_REQUEST_NET_ACCESS,
+ .audit.type = LSM_AUDIT_DATA_NET,
+ .audit.u.net = &audit_net,
+ .access = access_request,
+ .layer_masks = &layer_masks,
+ .layer_masks_size =
+ ARRAY_SIZE(layer_masks),
+ });
+ return -EACCES;
} else {
WARN_ON_ONCE(1);
}
@@ -136,7 +164,8 @@ static int current_check_access_socket(struct socket *const sock,
port = addr4->sin_port;
if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
- access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
+ access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP ||
+ access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
audit_net.dport = port;
audit_net.v4info.daddr = addr4->sin_addr.s_addr;
} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
@@ -160,7 +189,8 @@ static int current_check_access_socket(struct socket *const sock,
port = addr6->sin6_port;
if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
- access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP) {
+ access_request == LANDLOCK_ACCESS_NET_CONNECT_UDP ||
+ access_request == LANDLOCK_ACCESS_NET_SENDTO_UDP) {
audit_net.dport = port;
audit_net.v6info.daddr = addr6->sin6_addr;
} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
@@ -248,9 +278,36 @@ static int hook_socket_connect(struct socket *const sock,
access_request);
}
+static int hook_socket_sendmsg(struct socket *const sock,
+ struct msghdr *const msg, const int size)
+{
+ struct sockaddr *const address = msg->msg_name;
+ const int addrlen = msg->msg_namelen;
+ access_mask_t access_request;
+
+ /*
+ * If there is no explicit address in the message, we have no
+ * policy to enforce here because either:
+ * - the socket has a remote address assigned, so the appropriate
+ * access check has already been done back then at assignment time;
+ * - or, we can let the networking stack reply -EDESTADDRREQ.
+ */
+ if (!address)
+ return 0;
+
+ if (sk_is_udp(sock->sk))
+ access_request = LANDLOCK_ACCESS_NET_SENDTO_UDP;
+ else
+ return 0;
+
+ return current_check_access_socket(sock, address, addrlen,
+ access_request);
+}
+
static struct security_hook_list landlock_hooks[] __ro_after_init = {
LSM_HOOK_INIT(socket_bind, hook_socket_bind),
LSM_HOOK_INIT(socket_connect, hook_socket_connect),
+ LSM_HOOK_INIT(socket_sendmsg, hook_socket_sendmsg),
};
__init void landlock_add_net_hooks(void)
--
2.47.3
^ permalink raw reply related
* Re: An opinion about Linux security
From: Stephen Smalley @ 2025-12-12 16:11 UTC (permalink / raw)
To: Timur Chernykh; +Cc: Casey Schaufler, torvalds, linux-security-module, greg
In-Reply-To: <CABZOZnRQ=b4K5jpNM8Z=Zr=+66COwLpC8gynzw88==mL0FCrOw@mail.gmail.com>
On Fri, Dec 12, 2025 at 9:47 AM Timur Chernykh <tim.cherry.co@gmail.com> wrote:
>
> Thanks for the answer!
>
> > eBPF has been accepted because of these restrictions. Without them
> > an eBPF program could very easily reek havoc on the system's behavior.
>
> Unfortunately, these restrictions also make it impossible to use eBPF
> effectively for security. We can certainly discuss the limitations
> themselves if needed, but that’s not the main point I’m trying to make
> here.
There was no shortage of talks about using eBPF for security at LPC this week,
https://lpc.events/event/19/sessions/235/#all
If eBPF can't do what you want today, I suspect it will in the
not-too-distant future.
The best way to make it so would be to try implementing your desired
functionality using it, find the cases where it is currently
insufficient and then take those to LPC or other venues to argue for
enhancements to enable it to do so. Doing so may require re-thinking
how you implement that functionality to fit within the required safety
constraints but that doesn't mean it is impossible.
> > Please propose the interfaces you want. An API definition would be
> > good, and patches even better.
>
> I’m lucky enough to have already built a working prototype, which I
> once offered for review:
>
> https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
> https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
>
> Less lucky was the reaction I received. Paul Moore was strongly
> opposed, as far as I remember. Dr. Greg once said that heat death of
> the universe is more likely than this approach being accepted into the
> kernel.
Not seeing an actual response from Paul in the archives, but did you
ever actually post patches to the list? Posting a GitHub URL is NOT a
real request for review.
> I don’t want to “poke old wounds”, but the design I proposed was
> largely inspired by Apple’s Endpoint Security Framework (originally
> “mac policies”):
> https://developer.apple.com/documentation/endpointsecurity
>
> In my view, it is an exemplary model. The kernel provides a consistent
> stream of events to userspace, hides the complexity of data collection
> and transport, and ensures fault-tolerance if userspace fails to
> process events quickly enough.
> Audit, for comparison, simply hangs the system if its buffer
> overflows. ESF does not have that problem and even lets userspace
> control the event stream.
>
> > There are numerous cases where LSMs have mitigated attacks. One case:
>
> And there are thousands of cases where LSMs did not. Most companies
> never disclose successful breaches because of NDAs and fear of
> investor backlash. The few disclosures we see typically appear only
> when it’s safe for the company, or when they specifically want to
> appear transparent.
>
> > Your assertion that LSMs don't provide "real" value is not substantiated
> > in the literature.
>
> Which literature do you mean?
> As I mentioned above, public reports about successful attacks are rare.
>
> Maybe I poorly delivered my point. I'll try again.
>
> The strongest protection on Linux today is provided by proprietary
> security vendors. Unfortunately, they often achieve this using
> kernel-module “hacks” rather than LSMs. It’s not because they prefer
> hacks — it’s because Linux doesn’t offer proper APIs to implement the
> required functionality.
>
> > Each of the existing LSMs addresses one or more real world issues. I would
> > hardly call any of the Linux security mechanisms, from mode bits and setuid
> > through SELinux, landlock and EVM, "theoretical".
>
> In practice, most LSM modules are either disabled or misconfigured on
> real servers, and the responsibility falls on AV/EDR vendors. As
> someone who has been building such systems professionally for years, I
> can say with confidence: there is no clean, reliable mechanism
> available today.
> As much as I love Linux, its security and its friendliness toward
> security vendors are its weak side.
>
> In the real world, deploying a modern security product means dealing
> with endless pain: missing kernel headers (sometimes there isn’t even
> Internet access to download them), unstable kernel APIs, lack of BTF,
> constant fights with the eBPF verifier, and all the other limitations
> of eBPF.
>
> To be honest, many developers — and I’m taking the liberty to speak
> broadly here — would simply like to see something similar to Apple’s
> ESF available on Linux.
>
> Best regards,
> Timur Chernykh
>
> On Wed, Dec 10, 2025 at 11:08 PM Casey Schaufler <casey@schaufler-ca.com> wrote:
> >
> > On 12/9/2025 4:15 PM, Timur Chernykh wrote:
> > > Hello Linus,
> > >
> > > I’m writing to ask for your opinion. What do you think about Linux’s
> > > current readiness for security-focused commercial products? I’m
> > > particularly interested in several areas.
> > >
> > > First, in today’s 3rd-party (out-of-tree) EDR development — EDR being
> > > the most common commercial class of security products — eBPF has
> > > effectively become the main option. Yet eBPF is extremely restrictive.
> >
> > eBPF has been accepted because of these restrictions. Without them
> > an eBPF program could very easily reek havoc on the system's behavior.
> >
> > > It is not possible to write fully expressive real-time analysis code:
> > > the verifier is overly strict,
> >
> > This is of necessity. It is the only protection against malicious and
> > badly written eBPF programs.
> >
> > > non-deterministic loops are not
> > > allowed,
> >
> > Without this restriction denial of service attacks become trivial.
> >
> > > and older kernels lack BTF support.
> >
> > Yes. That's true for many kernel features.
> >
> > > These issues create real
> > > limitations.
> > >
> > > Second, the removal of the out-of-tree LSM API in the 4.x kernel
> > > series caused significant problems for many AV/EDR vendors. I was
> > > unable to find an explanation in the mailing lists that convincingly
> > > justified that decision.
> >
> > To the best of my understanding, and I have been working with LSMs
> > and the infrastructure for quite some time, there has never been an
> > out-of-tree LSM API. We have been very clear that the LSM interfaces
> > are fluid. We have also been very clear that supporting out-of-tree
> > security modules is not a requirement. There are members of the
> > community who would prefer that they be completely prohibited.
> >
> >
> > > The next closest mechanism, fanotify, was a genuine improvement.
> > > However, it does not allow an AV/EDR vendor to protect the integrity
> > > of its own product. Is Linux truly expecting modern AV/EDR solutions
> > > to rely on fanotify alone?
> >
> > You will need to provide more detail about why you believe that the
> > integrity of an AV/EDR product cannot be protected.
> >
> > > My main question is: what are the future plans?
> >
> > Security remains a dynamic technology. There are quite a few plans,
> > from a variety of sources, with no shortage of security goals. Trying
> > to keep up with the concern/crisis of the day is more than sufficient
> > to consume the resources committed to Linux security.
> >
> > > Linux provides very
> > > few APIs for security and dynamic analysis.
> >
> > What APIs do you want? It's possible that some exist that you haven't
> > discovered.
> >
> > > eBPF is still immature,
> >
> > And it will be for some time. That is, until it is mature.
> >
> > > fanotify is insufficient,
> >
> > Without specifics it is quite difficult to do anything about that.
> > And, as we like to say, patches are welcome.
> >
> > > and driver workarounds that bypass kernel
> > > restrictions are risky — they introduce both stability and security
> > > problems.
> >
> > Yes. Don't do that.
> >
> > > At the same time, properly implemented in-tree LSMs are not
> > > inherently dangerous and remain the safer, supported path for
> > > extending security functionality. Without safe, supported interfaces,
> > > however, commercial products struggle to be competitive. At the
> > > moment, macOS with its Endpoint Security Framework is significantly
> > > ahead.
> >
> > Please propose the interfaces you want. An API definition would be
> > good, and patches even better.
> >
> > > Yes, the kernel includes multiple in-tree LSM modules, but in practice
> > > SELinux does not simplify operations — it often complicates them,
> > > despite its long-standing presence. Many of the other LSMs are rarely
> > > used in production. As an EDR developer, I seldom encounter them, and
> > > when I do, they usually provide little practical value. Across
> > > numerous real-world server intrusions, none of these LSM modules have
> > > meaningfully prevented attacks, despite many years of kernel
> > > development.
> >
> > There are numerous cases where LSMs have mitigated attacks. One case:
> >
> > https://mihail-milev.medium.com/mitigating-malware-risks-with-selinux-e37cf1db7c56
> >
> > Your assertion that LSMs don't provide "real" value is not substantiated
> > in the literature.
> >
> > > Perhaps it is time for Linux to focus on more than a theoretical model
> > > of security.
> >
> > Each of the existing LSMs addresses one or more real world issues. I would
> > hardly call any of the Linux security mechanisms, from mode bits and setuid
> > through SELinux, landlock and EVM, "theoretical".
> >
> > > P.S.
> > > Everything above reflects only my personal opinion. I would greatly
> > > appreciate your response and any criticism you may have.
> >
> > We are always ready to improve the security infrastructure of Linux.
> > If it does not meet your needs, help us improve it. The best way to
> > accomplish this is to provide the changes required.
> >
> > > Best regards,
> > > Timur Chernykh
> > >
>
^ permalink raw reply
* Re: An opinion about Linux security
From: Timur Chernykh @ 2025-12-12 14:47 UTC (permalink / raw)
To: Casey Schaufler; +Cc: torvalds, linux-security-module, greg
In-Reply-To: <a3d28a4b-ee63-463e-8c5c-2597e2dcba98@schaufler-ca.com>
Thanks for the answer!
> eBPF has been accepted because of these restrictions. Without them
> an eBPF program could very easily reek havoc on the system's behavior.
Unfortunately, these restrictions also make it impossible to use eBPF
effectively for security. We can certainly discuss the limitations
themselves if needed, but that’s not the main point I’m trying to make
here.
> Yes. That's true for many kernel features.
Right, and that’s a well-known issue that has no clean solution other
than backporting. I completely agree with that.
> To the best of my understanding, and I have been working with LSMs
> and the infrastructure for quite some time, there has never been an
> out-of-tree LSM API.
I was under the impression that there was something of that sort.
For example: https://elixir.bootlin.com/linux/v3.10/source/include/linux/security.h#L1688
It may not have been “officially” exported, but people who needed it
simply resolved the symbol through `kallsyms` or a kprobe and used it.
I’m not claiming that this is good practice, but it did work.
> You will need to provide more detail about why you believe that the
> integrity of an AV/EDR product cannot be protected.
Consider the case where an attacker already has root access. The first
thing they typically do is disable or tamper with security tools.
After that, they establish persistence. Access-control models alone
are not enough here — sometimes they need to be adjusted dynamically,
based on complex real-time analysis.
> What APIs do you want? It's possible that some exist that you haven't
> discovered.
I’m confident I’ve studied all the mechanisms available for real-time
system protection. I’ve even given talks and published material on
approaches to securing Linux.
I may not have covered every LSM module in depth, but in practice they
simply don’t provide the capabilities required for modern security
workloads.
And I don’t want to sound overly categorical, but the current path of
security development feels like a dead end to me, for several reasons.
Modern security relies on analyzing hundreds of thousands of events
per second. eBPF isn’t particularly fast to begin with, and on top of
that it imposes strict technological limitations that prevent
meaningful in-kernel analysis. Every EDR vendor ends up doing the same
thing: collecting raw data (which is already difficult) and pushing it
into userspace for processing. That adds transport overhead on top of
everything else.
Or, of course, writes a dirty and unsafe kernel module. For me in the
perfect world seems to it's better to provide an API for userspace.
It's safe enough and doesn't contain a restriction that eBPF has.
> Please propose the interfaces you want. An API definition would be
> good, and patches even better.
I’m lucky enough to have already built a working prototype, which I
once offered for review:
https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/security/esf
https://github.com/Linux-Endpoint-Security-Framework/linux/tree/esf/main/include/uapi/linux/esf
Less lucky was the reaction I received. Paul Moore was strongly
opposed, as far as I remember. Dr. Greg once said that heat death of
the universe is more likely than this approach being accepted into the
kernel.
I don’t want to “poke old wounds”, but the design I proposed was
largely inspired by Apple’s Endpoint Security Framework (originally
“mac policies”):
https://developer.apple.com/documentation/endpointsecurity
In my view, it is an exemplary model. The kernel provides a consistent
stream of events to userspace, hides the complexity of data collection
and transport, and ensures fault-tolerance if userspace fails to
process events quickly enough.
Audit, for comparison, simply hangs the system if its buffer
overflows. ESF does not have that problem and even lets userspace
control the event stream.
> There are numerous cases where LSMs have mitigated attacks. One case:
And there are thousands of cases where LSMs did not. Most companies
never disclose successful breaches because of NDAs and fear of
investor backlash. The few disclosures we see typically appear only
when it’s safe for the company, or when they specifically want to
appear transparent.
> Your assertion that LSMs don't provide "real" value is not substantiated
> in the literature.
Which literature do you mean?
As I mentioned above, public reports about successful attacks are rare.
Maybe I poorly delivered my point. I'll try again.
The strongest protection on Linux today is provided by proprietary
security vendors. Unfortunately, they often achieve this using
kernel-module “hacks” rather than LSMs. It’s not because they prefer
hacks — it’s because Linux doesn’t offer proper APIs to implement the
required functionality.
> Each of the existing LSMs addresses one or more real world issues. I would
> hardly call any of the Linux security mechanisms, from mode bits and setuid
> through SELinux, landlock and EVM, "theoretical".
In practice, most LSM modules are either disabled or misconfigured on
real servers, and the responsibility falls on AV/EDR vendors. As
someone who has been building such systems professionally for years, I
can say with confidence: there is no clean, reliable mechanism
available today.
As much as I love Linux, its security and its friendliness toward
security vendors are its weak side.
In the real world, deploying a modern security product means dealing
with endless pain: missing kernel headers (sometimes there isn’t even
Internet access to download them), unstable kernel APIs, lack of BTF,
constant fights with the eBPF verifier, and all the other limitations
of eBPF.
To be honest, many developers — and I’m taking the liberty to speak
broadly here — would simply like to see something similar to Apple’s
ESF available on Linux.
Best regards,
Timur Chernykh
On Wed, Dec 10, 2025 at 11:08 PM Casey Schaufler <casey@schaufler-ca.com> wrote:
>
> On 12/9/2025 4:15 PM, Timur Chernykh wrote:
> > Hello Linus,
> >
> > I’m writing to ask for your opinion. What do you think about Linux’s
> > current readiness for security-focused commercial products? I’m
> > particularly interested in several areas.
> >
> > First, in today’s 3rd-party (out-of-tree) EDR development — EDR being
> > the most common commercial class of security products — eBPF has
> > effectively become the main option. Yet eBPF is extremely restrictive.
>
> eBPF has been accepted because of these restrictions. Without them
> an eBPF program could very easily reek havoc on the system's behavior.
>
> > It is not possible to write fully expressive real-time analysis code:
> > the verifier is overly strict,
>
> This is of necessity. It is the only protection against malicious and
> badly written eBPF programs.
>
> > non-deterministic loops are not
> > allowed,
>
> Without this restriction denial of service attacks become trivial.
>
> > and older kernels lack BTF support.
>
> Yes. That's true for many kernel features.
>
> > These issues create real
> > limitations.
> >
> > Second, the removal of the out-of-tree LSM API in the 4.x kernel
> > series caused significant problems for many AV/EDR vendors. I was
> > unable to find an explanation in the mailing lists that convincingly
> > justified that decision.
>
> To the best of my understanding, and I have been working with LSMs
> and the infrastructure for quite some time, there has never been an
> out-of-tree LSM API. We have been very clear that the LSM interfaces
> are fluid. We have also been very clear that supporting out-of-tree
> security modules is not a requirement. There are members of the
> community who would prefer that they be completely prohibited.
>
>
> > The next closest mechanism, fanotify, was a genuine improvement.
> > However, it does not allow an AV/EDR vendor to protect the integrity
> > of its own product. Is Linux truly expecting modern AV/EDR solutions
> > to rely on fanotify alone?
>
> You will need to provide more detail about why you believe that the
> integrity of an AV/EDR product cannot be protected.
>
> > My main question is: what are the future plans?
>
> Security remains a dynamic technology. There are quite a few plans,
> from a variety of sources, with no shortage of security goals. Trying
> to keep up with the concern/crisis of the day is more than sufficient
> to consume the resources committed to Linux security.
>
> > Linux provides very
> > few APIs for security and dynamic analysis.
>
> What APIs do you want? It's possible that some exist that you haven't
> discovered.
>
> > eBPF is still immature,
>
> And it will be for some time. That is, until it is mature.
>
> > fanotify is insufficient,
>
> Without specifics it is quite difficult to do anything about that.
> And, as we like to say, patches are welcome.
>
> > and driver workarounds that bypass kernel
> > restrictions are risky — they introduce both stability and security
> > problems.
>
> Yes. Don't do that.
>
> > At the same time, properly implemented in-tree LSMs are not
> > inherently dangerous and remain the safer, supported path for
> > extending security functionality. Without safe, supported interfaces,
> > however, commercial products struggle to be competitive. At the
> > moment, macOS with its Endpoint Security Framework is significantly
> > ahead.
>
> Please propose the interfaces you want. An API definition would be
> good, and patches even better.
>
> > Yes, the kernel includes multiple in-tree LSM modules, but in practice
> > SELinux does not simplify operations — it often complicates them,
> > despite its long-standing presence. Many of the other LSMs are rarely
> > used in production. As an EDR developer, I seldom encounter them, and
> > when I do, they usually provide little practical value. Across
> > numerous real-world server intrusions, none of these LSM modules have
> > meaningfully prevented attacks, despite many years of kernel
> > development.
>
> There are numerous cases where LSMs have mitigated attacks. One case:
>
> https://mihail-milev.medium.com/mitigating-malware-risks-with-selinux-e37cf1db7c56
>
> Your assertion that LSMs don't provide "real" value is not substantiated
> in the literature.
>
> > Perhaps it is time for Linux to focus on more than a theoretical model
> > of security.
>
> Each of the existing LSMs addresses one or more real world issues. I would
> hardly call any of the Linux security mechanisms, from mode bits and setuid
> through SELinux, landlock and EVM, "theoretical".
>
> > P.S.
> > Everything above reflects only my personal opinion. I would greatly
> > appreciate your response and any criticism you may have.
>
> We are always ready to improve the security infrastructure of Linux.
> If it does not meet your needs, help us improve it. The best way to
> accomplish this is to provide the changes required.
>
> > Best regards,
> > Timur Chernykh
> >
^ permalink raw reply
* Re: [PATCH v4 1/5] landlock: Implement LANDLOCK_ADD_RULE_NO_INHERIT
From: Mickaël Salaün @ 2025-12-12 13:27 UTC (permalink / raw)
To: Justin Suess
Cc: Tingmao Wang, Günther Noack, Jan Kara, Abhinav Saxena,
linux-security-module
In-Reply-To: <20251207015132.800576-2-utilityemal77@gmail.com>
Thanks for this patch series. This feature would be useful, but the
related patches add a lot of new code. We should try to minimize that
as much as possible, especially when similar/close logic already exist
(e.g. path walk).
On Sat, Dec 06, 2025 at 08:51:27PM -0500, Justin Suess wrote:
> Implements a flag to prevent access grant inheritance within the filesystem
> hierarchy for landlock rules.
>
> If a landlock rule on an inode has this flag, any access grants on parent
> inodes will be ignored. Moreover, operations that involve altering the
> ancestors of the subject with LANDLOCK_ADD_RULE_NO_INHERIT will be
> denied up to the VFS root (new in v4).
>
> For example, if /a/b/c/ = read only + LANDLOCK_ADD_RULE_NO_INHERIT and
> / = read write, writes to files in /a/b/c will be denied. Moreover,
> moving /a to /bad, removing /a/b/c, or creating links to /a will be
> prohibited.
>
> Parent flag inheritance is automatically suppressed by the permission
> harvesting logic, which will finish processing early if all relevant
> layers are tagged with NO_INHERIT.
>
> And if / has LANDLOCK_ADD_RULE_QUIET, /a/b/c will still audit (handled)
> accesses. This is because LANDLOCK_ADD_RULE_NO_INHERIT also
> suppresses flag inheritance from parent objects.
>
> The parent directory restrictions mitigate sandbox-restart attacks. For
> example, if a sandboxed program is able to move a
> LANDLOCK_ADD_RULE_NO_INHERIT restricted directory, upon sandbox restart,
> the policy applied naively on the same filenames would be invalid.
> Preventing these operations mitigates these attacks.
>
Your Signed-off-by and Cc should be here, followed by "---", followed by
the changelog (to exclude it from the git message e.g., when using
git am).
> v3..v4 changes:
>
> * Rebased on v6 of Tingmao Wang's "quiet flag" series.
> * Removed unnecessary mask_no_inherit_descendant_layers and related
> code at Tingmao Wang's suggestion, simplifying patch.
> * Updated to use new disconnected directory handling.
> * Improved WARN_ON_ONCE usage. (Thanks Tingmao Wang!)
> * Removed redundant loop for single-layer rulesets (again thanks Tingmao
> Wang!)
> * Protections now apply up to the VFS root, not just the mountpoint.
> * Indentation fixes.
> * Removed redundant flag marker blocked_flag_masks.
>
> v2..v3 changes:
>
> * Parent directory topology protections now work by lazily
> inserting blank rules on parent inodes if they do not
> exist. This replaces the previous xarray implementation
> with simplified logic.
> * Added an optimization to skip further processing if all layers
> collected have no inherit.
> * Added support to block flag inheritance.
>
> Cc: Tingmao Wang <m@maowtm.org>
> Signed-off-by: Justin Suess <utilityemal77@gmail.com>
> ---
> security/landlock/fs.c | 389 +++++++++++++++++++++++++++++++++++-
> security/landlock/ruleset.c | 19 +-
> security/landlock/ruleset.h | 29 ++-
> 3 files changed, 433 insertions(+), 4 deletions(-)
>
> diff --git a/security/landlock/fs.c b/security/landlock/fs.c
> index 0b589263ea42..7b0b77859778 100644
> --- a/security/landlock/fs.c
> +++ b/security/landlock/fs.c
> @@ -317,6 +317,207 @@ static struct landlock_object *get_inode_object(struct inode *const inode)
> LANDLOCK_ACCESS_FS_IOCTL_DEV)
> /* clang-format on */
>
> +static const struct landlock_rule *find_rule(const struct landlock_ruleset *const domain,
> + const struct dentry *const dentry);
> +
> +/**
> + * landlock_domain_layers_mask - Build a mask covering all layers of a domain
> + * @domain: The ruleset (domain) to inspect.
> + *
> + * Return a layer mask with a 1 bit for each existing layer of @domain.
> + * If @domain has no layers 0 is returned. If the number of layers is
> + * greater than or equal to the number of bits in layer_mask_t, all bits
> + * are set.
> + */
> +static layer_mask_t landlock_domain_layers_mask(const struct landlock_ruleset
> + *const domain)
> +{
> + if (!domain || !domain->num_layers)
> + return 0;
> +
> + if (domain->num_layers >= sizeof(layer_mask_t) * BITS_PER_BYTE)
> + return (layer_mask_t)~0ULL;
> +
> + return GENMASK_ULL(domain->num_layers - 1, 0);
> +}
> +
> +/**
> + * rule_blocks_all_layers_no_inherit - check whether a rule disables inheritance
> + * @domain_layers_mask: Mask describing the domain's active layers.
> + * @rule: Rule to inspect.
> + *
> + * Return true if every layer present in @rule has its no_inherit flag set
> + * and the set of layers covered by the rule equals @domain_layers_mask.
> + * This indicates that the rule prevents inheritance on all layers of the
> + * domain and thus further walking for inheritance checks can stop.
> + */
> +static bool rule_blocks_all_layers_no_inherit(const layer_mask_t domain_layers_mask,
> + const struct landlock_rule *const rule)
> +{
> + layer_mask_t rule_layers = 0;
> + u32 layer_index;
> +
> + if (!domain_layers_mask || !rule)
> + return false;
> +
> + for (layer_index = 0; layer_index < rule->num_layers; layer_index++) {
> + const struct landlock_layer *const layer =
> + &rule->layers[layer_index];
> + const layer_mask_t layer_bit = BIT_ULL(layer->level - 1);
> +
> + if (!layer->flags.no_inherit)
> + return false;
> +
> + rule_layers |= layer_bit;
> + }
> +
> + return rule_layers && rule_layers == domain_layers_mask;
> +}
> +
> +/**
> + * ensure_rule_for_dentry - ensure a ruleset contains a rule entry for dentry,
> + * inserting a blank rule if needed.
> + * @ruleset: Ruleset to modify/inspect. Caller must hold @ruleset->lock.
> + * @dentry: Dentry to ensure a rule exists for.
> + *
> + * If no rule is currently associated with @dentry, insert an empty rule
> + * (with zero access) tied to the backing inode. Returns a pointer to the
> + * rule associated with @dentry on success, NULL when @dentry is negative, or
> + * an ERR_PTR()-encoded error if the rule cannot be created.
> + *
> + * This is useful for LANDLOCK_ADD_RULE_NO_INHERIT processing, where a rule
> + * may need to be created for an ancestor dentry that does not yet have one
> + * to properly track no_inherit flags.
> + *
> + * The flags are set to zero if a rule is newly created, and the caller
> + * is responsible for setting them appropriately.
> + *
> + * The returned rule pointer's lifetime is tied to @ruleset.
> + */
> +static const struct landlock_rule *
> +ensure_rule_for_dentry(struct landlock_ruleset *const ruleset,
> + struct dentry *const dentry)
> +{
> + struct landlock_id id = {
> + .type = LANDLOCK_KEY_INODE,
> + };
> + const struct landlock_rule *rule;
> + int err;
> +
> + if (WARN_ON_ONCE(!ruleset || !dentry || d_is_negative(dentry)))
> + return NULL;
> +
> + lockdep_assert_held(&ruleset->lock);
> +
> + rule = find_rule(ruleset, dentry);
> + if (rule)
> + return rule;
> +
> + id.key.object = get_inode_object(d_backing_inode(dentry));
> + if (IS_ERR(id.key.object))
> + return ERR_CAST(id.key.object);
> +
> + err = landlock_insert_rule(ruleset, id, 0, 0);
> + landlock_put_object(id.key.object);
> + if (err)
> + return ERR_PTR(err);
> +
> + rule = find_rule(ruleset, dentry);
> + if (WARN_ON_ONCE(!rule))
> + return ERR_PTR(-ENOENT);
> + return rule;
> +}
> +
> +/**
> + * mark_no_inherit_ancestors - mark ancestors as having no_inherit descendants
> + * @ruleset: Ruleset to modify. Caller must hold @ruleset->lock.
> + * @path: Path representing the descendant that carries no_inherit bits.
> + * @descendant_layers: Mask of layers from the descendant that should be
> + * advertised to ancestors via has_no_inherit_descendant.
> + *
> + * Walks upward from @dentry and ensures that any ancestor rule contains the
> + * has_no_inherit_descendant marker for the specified @descendant_layers so
> + * parent lookups can quickly detect descendant no_inherit influence.
> + *
> + * Returns 0 on success or a negative errno if ancestor bookkeeping fails.
> + */
> +static int mark_no_inherit_ancestors(struct landlock_ruleset *ruleset,
> + const struct path *const path,
> + layer_mask_t descendant_layers)
> +{
> + struct dentry *cursor;
> + struct path walk_path;
> + int err = 0;
> +
> + if (WARN_ON_ONCE(!ruleset || !path || !path->dentry || !path->mnt ||
> + !descendant_layers))
> + return -EINVAL;
> +
> + lockdep_assert_held(&ruleset->lock);
> +
> + walk_path.mnt = path->mnt;
> + walk_path.dentry = path->dentry;
> + path_get(&walk_path);
> +
> + cursor = dget(walk_path.dentry);
> + while (cursor) {
> + struct dentry *parent;
> + const struct landlock_rule *rule;
> +
> + /* Follow mounts all the way up to the root. */
> + if (IS_ROOT(cursor)) {
> + dput(cursor);
> + if (!follow_up(&walk_path)) {
This path walk is inconsistent and a duplicate of the (correct)
is_access_to_paths_allowed() one. Please add a patch to factor out the
common parts as much as possible. Ditto for the
collect_domain_accesses() and collect_topology_sealed_layers().
> + cursor = NULL;
> + continue;
> + }
> + cursor = dget(walk_path.dentry);
> + }
> +
> + parent = dget_parent(cursor);
> + dput(cursor);
> + if (!parent)
> + break;
> +
> + if (WARN_ON_ONCE(d_is_negative(parent))) {
> + dput(parent);
> + break;
> + }
> + /*
> + * Ensures a rule exists for the parent dentry,
> + * inserting a blank one if needed.
> + */
> + rule = ensure_rule_for_dentry(ruleset, parent);
> + if (IS_ERR(rule)) {
> + err = PTR_ERR(rule);
> + dput(parent);
> + cursor = NULL;
> + break;
> + }
> + if (rule) {
> + struct landlock_rule *mutable_rule =
> + (struct landlock_rule *)rule;
> + /*
> + * Unmerged rulesets should only have one layer.
> + */
> + if (WARN_ON_ONCE(mutable_rule->num_layers != 1)) {
> + dput(parent);
> + err = -EINVAL;
> + cursor = NULL;
> + break;
> + }
> +
> + if (descendant_layers & BIT_ULL(0))
> + mutable_rule->layers[0]
> + .flags.has_no_inherit_descendant = true;
> + }
> +
> + cursor = parent;
> + }
> + path_put(&walk_path);
> + return err;
> +}
> +/**
> + * collect_topology_sealed_layers - collect layers sealed against topology changes
> + * @domain: Ruleset to consult.
> + * @dentry: Starting dentry for the upward walk.
> + * @override_layers: Optional out parameter filled with layers that are
> + * present on ancestors but considered overrides (not
> + * sealing the topology for descendants).
> + *
> + * Walk upwards from @dentry and return a mask of layers where either the
> + * visited dentry contains a no_inherit rule or ancestors were previously
> + * marked as having a descendant with no_inherit. @override_layers, if not
> + * NULL, is filled with layers that would normally be overridden by more
> + * specific descendant rules.
> + *
> + * Returns a layer mask where set bits indicate layers that are "sealed"
> + * (topology changes like rename/rmdir are denied) for the subtree rooted at
> + * @dentry.
> + *
> + * Useful for LANDLOCK_ADD_RULE_NO_INHERIT parent directory enforcement to ensure
> + * that topology changes do not violate the no_inherit constraints.
> + */
> +static layer_mask_t
> +collect_topology_sealed_layers(const struct landlock_ruleset *const domain,
> + struct dentry *dentry,
> + layer_mask_t *const override_layers)
> +{
> + struct dentry *cursor, *parent;
> + bool include_descendants = true;
> + layer_mask_t sealed_layers = 0;
> +
> + if (override_layers)
> + *override_layers = 0;
> +
> + if (WARN_ON_ONCE(!domain || !dentry || d_is_negative(dentry)))
> + return 0;
> +
> + cursor = dget(dentry);
> + while (cursor) {
> + const struct landlock_rule *rule;
> + u32 layer_index;
> +
> + rule = find_rule(domain, cursor);
> + if (rule) {
> + for (layer_index = 0; layer_index < rule->num_layers;
> + layer_index++) {
> + const struct landlock_layer *layer =
> + &rule->layers[layer_index];
> + layer_mask_t layer_bit =
> + BIT_ULL(layer->level - 1);
> +
> + if (include_descendants &&
> + (layer->flags.no_inherit ||
> + layer->flags.has_no_inherit_descendant)) {
> + sealed_layers |= layer_bit;
> + } else if (override_layers) {
> + *override_layers |= layer_bit;
> + }
> + }
> + }
> +
> + if (sealed_layers || IS_ROOT(cursor))
> + break;
> +
> + parent = dget_parent(cursor);
> + dput(cursor);
> + if (!parent)
> + return sealed_layers;
> +
> + cursor = parent;
> + include_descendants = false;
> + }
> + dput(cursor);
> + return sealed_layers;
> +}
^ permalink raw reply
* Re: [PATCH v6 04/10] landlock: Fix wrong type usage
From: Mickaël Salaün @ 2025-12-12 11:13 UTC (permalink / raw)
To: Günther Noack
Cc: Tingmao Wang, Justin Suess, Jan Kara, Abhinav Saxena,
linux-security-module
In-Reply-To: <aTvqrOomA3v52sIg@google.com>
On Fri, Dec 12, 2025 at 11:13:19AM +0100, Günther Noack wrote:
> On Sat, Dec 06, 2025 at 05:11:06PM +0000, Tingmao Wang wrote:
> > I think, based on my best understanding, that this type is likely a typo
> > (even though in the end both are u16)
> >
> > Signed-off-by: Tingmao Wang <m@maowtm.org>
> > Fixes: 2fc80c69df82 ("landlock: Log file-related denials")
> > ---
> >
> > Changes in v2:
> > - Added Fixes tag
> >
> > security/landlock/audit.c | 2 +-
> > 1 file changed, 1 insertion(+), 1 deletion(-)
> >
> > diff --git a/security/landlock/audit.c b/security/landlock/audit.c
> > index 1a9d3f4e3369..d51563712325 100644
> > --- a/security/landlock/audit.c
> > +++ b/security/landlock/audit.c
> > @@ -191,7 +191,7 @@ static size_t get_denied_layer(const struct landlock_ruleset *const domain,
> > long youngest_layer = -1;
> >
> > for_each_set_bit(access_bit, &access_req, layer_masks_size) {
> > - const access_mask_t mask = (*layer_masks)[access_bit];
> > + const layer_mask_t mask = (*layer_masks)[access_bit];
> > long layer;
> >
> > if (!mask)
> > --
> > 2.52.0
>
> Agreed, thanks!
>
> Reviewed-by: Günther Noack <gnoack@google.com>
Thanks, I pushed it to the next branch.
>
> —Günther
>
^ permalink raw reply
* Re: [PATCH v4 06/35] cleanup: Basic compatibility with context analysis
From: Peter Zijlstra @ 2025-12-12 11:09 UTC (permalink / raw)
To: Marco Elver
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <CANpmjNP=s33L6LgYWHygEuLtWTq-s2n4yFDvvGcF3HjbGH+hqw@mail.gmail.com>
On Fri, Dec 12, 2025 at 11:15:29AM +0100, Marco Elver wrote:
> On Fri, 12 Dec 2025 at 10:43, Peter Zijlstra <peterz@infradead.org> wrote:
> [..]
> > > Correct. We're trading false negatives over false positives at this
> > > point, just to get things to compile cleanly.
> >
> > Right, and this all 'works' right up to the point someone sticks a
> > must_not_hold somewhere.
> >
> > > > > Better support for Linux's scoped guard design could be added in
> > > > > future if deemed critical.
> > > >
> > > > I would think so, per the above I don't think this is 'right'.
> > >
> > > It's not sound, but we'll avoid false positives for the time being.
> > > Maybe we can wrangle the jigsaw of macros to let it correctly acquire
> > > and then release (via a 2nd cleanup function), it might be as simple
> > > as marking the 'constructor' with the right __acquires(..), and then
> > > have a 2nd __attribute__((cleanup)) variable that just does a no-op
> > > release via __release(..) so we get the already supported pattern
> > > above.
> >
> > Right, like I mentioned in my previous email; it would be lovely if at
> > the very least __always_inline would get a *very* early pass such that
> > the above could be resolved without inter-procedural bits. I really
> > don't consider an __always_inline as another procedure.
> >
> > Because as I already noted yesterday, cleanup is now all
> > __always_inline, and as such *should* all end up in the one function.
> >
> > But yes, if we can get a magical mash-up of __cleanup and __release (let
> > it be knows as __release_on_cleanup ?) that might also work I suppose.
> > But I vastly prefer __always_inline actually 'working' ;-)
>
> The truth is that __always_inline working in this way is currently
> infeasible. Clang and LLVM's architecture simply disallow this today:
> the semantic analysis that -Wthread-safety does happens over the AST,
> whereas always_inline is processed by early passes in the middle-end
> already within LLVM's pipeline, well after semantic analysis. There's
> a complexity budget limit for semantic analysis (type checking,
> warnings, assorted other errors), and path-sensitive &
> intra-procedural analysis over the plain AST is outside that budget.
> Which is why tools like clang-analyzer exist (symbolic execution),
> where it's possible to afford that complexity since that's not
> something that runs for a normal compile.
>
> I think I've pushed the current version of Clang's -Wthread-safety
> already far beyond what folks were thinking is possible (a variant of
> alias analysis), but even my healthy disregard for the impossible
> tells me that making path-sensitive intra-procedural analysis even if
> just for __always_inline functions is quite possibly a fool's errand.
Well, I had to propose it. Gotta push the envelope :-)
> So either we get it to work with what we have, or give up.
So I think as is, we can start. But I really do want the cleanup thing
sorted, even if just with that __release_on_cleanup mashup or so.
^ permalink raw reply
* Re: [PATCH v4 07/35] lockdep: Annotate lockdep assertions for context analysis
From: Marco Elver @ 2025-12-12 10:48 UTC (permalink / raw)
To: Peter Zijlstra
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <20251212095943.GM3911114@noisy.programming.kicks-ass.net>
On Fri, 12 Dec 2025 at 10:59, Peter Zijlstra <peterz@infradead.org> wrote:
>
> On Thu, Dec 11, 2025 at 02:24:57PM +0100, Marco Elver wrote:
>
> > > It is *NOT* (as the clang naming suggests) an assertion of holding the
> > > lock (which is requires_ctx), but rather an annotation that forces the
> > > ctx to be considered held.
> >
> > Noted. I'll add some appropriate wording above the
> > __assumes_ctx_guard() attribute, so this is not lost in the commit
> > logs.
>
> On IRC you stated:
>
> <melver> peterz: 'assume' just forces the compiler to think something is
> held, whether or not it is then becomes the programmer's problem. we
> need it in 2 places at least: for the runtime assertions (to help
> patterns beyond the compiler's static reasoning abilities), and for
> initialization (so we can access guarded variables right after
> initialization; nobody should hold the lock yet)
>
> I'm really not much a fan of that init hack either ;-)
>
> Once we get the scope crap working sanely, I would much rather we move
> to something like:
>
> scoped_guard (spinlock_init, &foo->lock) {
> // init foo fields
> }
>
> or perhaps:
>
> guard(mutex_init)(&bar->lock);
> // init until end of current scope
>
> Where this latter form is very similar to the current semantics where
> mutex_init() will implicitly 'leak' the holding of the lock. But the
> former gives more control where we need it.
I like it. It would also more clearly denote where initialization
start+ends if not confined to a dedicated function.
^ permalink raw reply
* Re: [PATCH v4 02/35] compiler-context-analysis: Add infrastructure for Context Analysis with Clang
From: Marco Elver @ 2025-12-12 10:37 UTC (permalink / raw)
To: Peter Zijlstra
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <20251212093149.GJ3911114@noisy.programming.kicks-ass.net>
On Fri, 12 Dec 2025 at 10:32, Peter Zijlstra <peterz@infradead.org> wrote:
> On Thu, Dec 11, 2025 at 02:12:19PM +0100, Marco Elver wrote:
>
> > What's a better name?
>
> That must be the hardest question in programming; screw this P-vs-NP
> debate :-)
>
> > context_lock_struct -> and call it "context lock" rather than "context
> > guard"; it might work also for things like RCU, PREEMPT, BH, etc. that
> > aren't normal "locks", but could claim they are "context locks".
> >
> > context_handle_struct -> "context handle" ...
>
> Both work for me I suppose, although I think I have a slight preference
> to the former: 'context_lock_struct'.
>
> One other possibility is wrapping things like so:
>
> #define define_context_struct(name) ... // the big thing
>
> #define define_lock_struct(name) define_context_struct(name)
Note that 'context_lock_struct' (assuming that's the new name) can be
used to just forward declare structs, too, so 'define' in the name is
probably incorrect. And to avoid more levels of indirection I'd just
stick with one name; if 'context_lock_struct' isn't too offensive to
anyone, that'd be the name for the next version.
Thanks,
-- Marco
^ permalink raw reply
* Re: [PATCH v4 06/35] cleanup: Basic compatibility with context analysis
From: Marco Elver @ 2025-12-12 10:15 UTC (permalink / raw)
To: Peter Zijlstra
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <20251212094352.GL3911114@noisy.programming.kicks-ass.net>
On Fri, 12 Dec 2025 at 10:43, Peter Zijlstra <peterz@infradead.org> wrote:
[..]
> > Correct. We're trading false negatives over false positives at this
> > point, just to get things to compile cleanly.
>
> Right, and this all 'works' right up to the point someone sticks a
> must_not_hold somewhere.
>
> > > > Better support for Linux's scoped guard design could be added in
> > > > future if deemed critical.
> > >
> > > I would think so, per the above I don't think this is 'right'.
> >
> > It's not sound, but we'll avoid false positives for the time being.
> > Maybe we can wrangle the jigsaw of macros to let it correctly acquire
> > and then release (via a 2nd cleanup function), it might be as simple
> > as marking the 'constructor' with the right __acquires(..), and then
> > have a 2nd __attribute__((cleanup)) variable that just does a no-op
> > release via __release(..) so we get the already supported pattern
> > above.
>
> Right, like I mentioned in my previous email; it would be lovely if at
> the very least __always_inline would get a *very* early pass such that
> the above could be resolved without inter-procedural bits. I really
> don't consider an __always_inline as another procedure.
>
> Because as I already noted yesterday, cleanup is now all
> __always_inline, and as such *should* all end up in the one function.
>
> But yes, if we can get a magical mash-up of __cleanup and __release (let
> it be knows as __release_on_cleanup ?) that might also work I suppose.
> But I vastly prefer __always_inline actually 'working' ;-)
The truth is that __always_inline working in this way is currently
infeasible. Clang and LLVM's architecture simply disallow this today:
the semantic analysis that -Wthread-safety does happens over the AST,
whereas always_inline is processed by early passes in the middle-end
already within LLVM's pipeline, well after semantic analysis. There's
a complexity budget limit for semantic analysis (type checking,
warnings, assorted other errors), and path-sensitive &
intra-procedural analysis over the plain AST is outside that budget.
Which is why tools like clang-analyzer exist (symbolic execution),
where it's possible to afford that complexity since that's not
something that runs for a normal compile.
I think I've pushed the current version of Clang's -Wthread-safety
already far beyond what folks were thinking is possible (a variant of
alias analysis), but even my healthy disregard for the impossible
tells me that making path-sensitive intra-procedural analysis even if
just for __always_inline functions is quite possibly a fool's errand.
So either we get it to work with what we have, or give up.
Thanks,
-- Marco
^ permalink raw reply
* Re: [PATCH v6 04/10] landlock: Fix wrong type usage
From: Günther Noack @ 2025-12-12 10:13 UTC (permalink / raw)
To: Tingmao Wang
Cc: Mickaël Salaün, Justin Suess, Jan Kara, Abhinav Saxena,
linux-security-module
In-Reply-To: <7339ad7b47f998affd84ca629a334a71f913616d.1765040503.git.m@maowtm.org>
On Sat, Dec 06, 2025 at 05:11:06PM +0000, Tingmao Wang wrote:
> I think, based on my best understanding, that this type is likely a typo
> (even though in the end both are u16)
>
> Signed-off-by: Tingmao Wang <m@maowtm.org>
> Fixes: 2fc80c69df82 ("landlock: Log file-related denials")
> ---
>
> Changes in v2:
> - Added Fixes tag
>
> security/landlock/audit.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/security/landlock/audit.c b/security/landlock/audit.c
> index 1a9d3f4e3369..d51563712325 100644
> --- a/security/landlock/audit.c
> +++ b/security/landlock/audit.c
> @@ -191,7 +191,7 @@ static size_t get_denied_layer(const struct landlock_ruleset *const domain,
> long youngest_layer = -1;
>
> for_each_set_bit(access_bit, &access_req, layer_masks_size) {
> - const access_mask_t mask = (*layer_masks)[access_bit];
> + const layer_mask_t mask = (*layer_masks)[access_bit];
> long layer;
>
> if (!mask)
> --
> 2.52.0
Agreed, thanks!
Reviewed-by: Günther Noack <gnoack@google.com>
—Günther
^ permalink raw reply
* Re: [PATCH v4 07/35] lockdep: Annotate lockdep assertions for context analysis
From: Peter Zijlstra @ 2025-12-12 9:59 UTC (permalink / raw)
To: Marco Elver
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <CANpmjNObaGarY1_niCkgEXMNm2bLAVwKwQsLVYekE=Ce6y3ehQ@mail.gmail.com>
On Thu, Dec 11, 2025 at 02:24:57PM +0100, Marco Elver wrote:
> > It is *NOT* (as the clang naming suggests) an assertion of holding the
> > lock (which is requires_ctx), but rather an annotation that forces the
> > ctx to be considered held.
>
> Noted. I'll add some appropriate wording above the
> __assumes_ctx_guard() attribute, so this is not lost in the commit
> logs.
On IRC you stated:
<melver> peterz: 'assume' just forces the compiler to think something is
held, whether or not it is then becomes the programmer's problem. we
need it in 2 places at least: for the runtime assertions (to help
patterns beyond the compiler's static reasoning abilities), and for
initialization (so we can access guarded variables right after
initialization; nobody should hold the lock yet)
I'm really not much a fan of that init hack either ;-)
Once we get the scope crap working sanely, I would much rather we move
to something like:
scoped_guard (spinlock_init, &foo->lock) {
// init foo fields
}
or perhaps:
guard(mutex_init)(&bar->lock);
// init until end of current scope
Where this latter form is very similar to the current semantics where
mutex_init() will implicitly 'leak' the holding of the lock. But the
former gives more control where we need it.
^ permalink raw reply
* Re: [RFC 04/11] crypto: pkcs7: add flag for validated trust on a signed info block
From: David Howells @ 2025-12-12 9:45 UTC (permalink / raw)
To: Blaise Boscaccy
Cc: dhowells, Jonathan Corbet, Paul Moore, James Morris,
Serge E. Hallyn, Mickaël Salaün, Günther Noack,
Dr. David Alan Gilbert, Andrew Morton, James.Bottomley,
linux-security-module, linux-doc, linux-kernel, bpf
In-Reply-To: <20251211021257.1208712-5-bboscaccy@linux.microsoft.com>
Note that there are two other potentially conflicting sets of changes to the
PKCS#7 code that will need to be coordinated: ML-DSA support and RSASSA-PSS
support. The former wants to do the hashing itself, the latter requires
signature parameters.
David
^ permalink raw reply
* Re: [PATCH v4 06/35] cleanup: Basic compatibility with context analysis
From: Peter Zijlstra @ 2025-12-12 9:43 UTC (permalink / raw)
To: Marco Elver
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <CANpmjNOmAYFj518rH0FdPp=cqK8EeKEgh1ok_zFUwHU5Fu92=w@mail.gmail.com>
On Thu, Dec 11, 2025 at 02:19:28PM +0100, Marco Elver wrote:
> On Thu, 11 Dec 2025 at 13:17, Peter Zijlstra <peterz@infradead.org> wrote:
> >
> > On Thu, Nov 20, 2025 at 04:09:31PM +0100, Marco Elver wrote:
> > > Introduce basic compatibility with cleanup.h infrastructure: introduce
> > > DECLARE_LOCK_GUARD_*_ATTRS() helpers to add attributes to constructors
> > > and destructors respectively.
> > >
> > > Note: Due to the scoped cleanup helpers used for lock guards wrapping
> > > acquire and release around their own constructors/destructors that store
> > > pointers to the passed locks in a separate struct, we currently cannot
> > > accurately annotate *destructors* which lock was released. While it's
> > > possible to annotate the constructor to say which lock was acquired,
> > > that alone would result in false positives claiming the lock was not
> > > released on function return.
> > >
> > > Instead, to avoid false positives, we can claim that the constructor
> > > "assumes" that the taken lock is held via __assumes_ctx_guard().
>
>
> > Moo, so the alias analysis didn't help here?
>
> Unfortunately no, because intra-procedural alias analysis for these
> kinds of diagnostics is infeasible. The compiler can only safely
> perform alias analysis for local variables that do not escape the
> function. The layers of wrapping here make this a bit tricky.
>
> The compiler (unlike before) is now able to deal with things like:
> {
> spinlock_t *lock_scope __attribute__((cleanup(spin_unlock))) = &lock;
> spin_lock(&lock); // lock through &lock
> ... critical section ...
> } // unlock through lock_scope (alias -> &lock)
>
> > What is the scope of this __assumes_ctx stuff? The way it is used in the
> > lock initializes seems to suggest it escapes scope. But then something
> > like:
>
> It escapes scope.
>
> > scoped_guard (mutex, &foo) {
> > ...
> > }
> > // context analysis would still assume foo held
> >
> > is somewhat sub-optimal, no?
>
> Correct. We're trading false negatives over false positives at this
> point, just to get things to compile cleanly.
Right, and this all 'works' right up to the point someone sticks a
must_not_hold somewhere.
> > > Better support for Linux's scoped guard design could be added in
> > > future if deemed critical.
> >
> > I would think so, per the above I don't think this is 'right'.
>
> It's not sound, but we'll avoid false positives for the time being.
> Maybe we can wrangle the jigsaw of macros to let it correctly acquire
> and then release (via a 2nd cleanup function), it might be as simple
> as marking the 'constructor' with the right __acquires(..), and then
> have a 2nd __attribute__((cleanup)) variable that just does a no-op
> release via __release(..) so we get the already supported pattern
> above.
Right, like I mentioned in my previous email; it would be lovely if at
the very least __always_inline would get a *very* early pass such that
the above could be resolved without inter-procedural bits. I really
don't consider an __always_inline as another procedure.
Because as I already noted yesterday, cleanup is now all
__always_inline, and as such *should* all end up in the one function.
But yes, if we can get a magical mash-up of __cleanup and __release (let
it be knows as __release_on_cleanup ?) that might also work I suppose.
But I vastly prefer __always_inline actually 'working' ;-)
^ permalink raw reply
* Re: [PATCH v4 16/35] kref: Add context-analysis annotations
From: Peter Zijlstra @ 2025-12-12 9:33 UTC (permalink / raw)
To: Marco Elver
Cc: Boqun Feng, Ingo Molnar, Will Deacon, David S. Miller,
Luc Van Oostenryck, Chris Li, Paul E. McKenney,
Alexander Potapenko, Arnd Bergmann, Bart Van Assche,
Christoph Hellwig, Dmitry Vyukov, Eric Dumazet,
Frederic Weisbecker, Greg Kroah-Hartman, Herbert Xu, Ian Rogers,
Jann Horn, Joel Fernandes, Johannes Berg, Jonathan Corbet,
Josh Triplett, Justin Stitt, Kees Cook, Kentaro Takeda,
Lukas Bulwahn, Mark Rutland, Mathieu Desnoyers, Miguel Ojeda,
Nathan Chancellor, Neeraj Upadhyay, Nick Desaulniers,
Steven Rostedt, Tetsuo Handa, Thomas Gleixner, Thomas Graf,
Uladzislau Rezki, Waiman Long, kasan-dev, linux-crypto, linux-doc,
linux-kbuild, linux-kernel, linux-mm, linux-security-module,
linux-sparse, linux-wireless, llvm, rcu
In-Reply-To: <CANpmjNN+zafzhvUBBmjyy+TL1ecqJUHQNRX3bo9fBJi2nFUt=A@mail.gmail.com>
On Thu, Dec 11, 2025 at 02:54:06PM +0100, Marco Elver wrote:
> Wrappers will need their own annotations; for this kind of static
> analysis (built-in warning diagnostic), inferring things like
> __cond_acquires(true, lock) is far too complex (requires
> intra-procedural control-flow analysis), and would likely be
> incomplete too.
>
> It might also be reasonable to argue that the explicit annotation is
> good for documentation.
>
> Aside: There's other static analysis tooling, like clang-analyzer that
> can afford to do more complex flow-sensitive intra-procedural
> analysis. But that has its own limitations, requires separate
> invocation, and is pretty slow in comparison.
I was sorta hoping that (perhaps only for __always_inline) the thing
would indeed do an early inline pass on the AST such that these cases
would not in fact require inter-procedural analysis.
^ permalink raw reply
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox