Skip to contentSkip to conversation

Reduce overhead of LSMs with static calls

PATCH Superseded KP Singh 5 participants 20 messages Sep 22, 2023 – Sep 27, 2023

Subsystems (4)

v4 of 15 Superseded Latest is v15 →

lore
Share & tools
lore

KP Singh

author maintainer
#0 lore raw

v4 cover Reduce overhead of LSMs with static calls

# Background

LSM hooks (callbacks) are currently invoked as indirect function calls. These callbacks are registered into a linked list at boot time as the order of the LSMs can be configured on the kernel command line with the "lsm=" command line parameter.

Indirect function calls have a high overhead due to retpoline mitigation for various speculative execution attacks.

Retpolines remain relevant even with newer generation CPUs as recently discovered speculative attacks, like Spectre BHB need Retpolines to mitigate against branch history injection and still need to be used in combination with newer mitigation features like eIBRS.

This overhead is especially significant for the "bpf" LSM which allows the user to implement LSM functionality with eBPF program. In order to facilitate this the "bpf" LSM provides a default callback for all LSM hooks. When enabled, the "bpf" LSM incurs an unnecessary / avoidable indirect call. This is especially bad in OS hot paths (e.g. in the networking stack). This overhead prevents the adoption of bpf LSM on performance critical systems, and also, in general, slows down all LSMs.

Since we know the address of the enabled LSM callbacks at compile time and only the order is determined at boot time, the LSM framework can allocate static calls for each of the possible LSM callbacks and these calls can be updated once the order is determined at boot.

This series is a respin of the RFC proposed by Paul Renauld ([email protected]) and Brendan Jackman ([email protected]) [1]

# Performance improvement

With this patch-set some syscalls with lots of LSM hooks in their path benefitted at an average of ~3% and I/O and Pipe based system calls benefitting the most.

Here are the results of the relevant Unixbench system benchmarks with BPF LSM and SELinux enabled with default policies enabled with and without these patches.

Benchmark Delta(%): (+ is better)
===============================================================================

Execl Throughput                                             +1.9356
File Write 1024 bufsize 2000 maxblocks                       +6.5953
Pipe Throughput                                              +9.5499
Pipe-based Context Switching                                 +3.0209
Process Creation                                             +2.3246
Shell Scripts (1 concurrent)                                 +1.4975
System Call Overhead                                         +2.7815
System Benchmarks Index Score (Partial Only):                +3.4859

In the best case, some syscalls like eventfd_create benefitted to about ~10%. The full analysis can be viewed at https://kpsingh.ch/lsm-perf

[1] https://lore.kernel.org/linux-security-module/[email protected]/

# BPF LSM Side effects

Patch 4 of the series also addresses the issues with the side effects of the default value return values of the BPF LSM callbacks and also removes the overheads associated with them making it deployable at hyperscale.

# v3 -> v4

* Refactor LSM count macros to use COUNT_ARGS
* Change CONFIG_SECURITY_HOOK_LIKELY likely's default value to be based on the LSM enabled and have it depend on CONFIG_EXPERT. There are a lot of subtle options behind CONFIG_EXPERT and this should, hopefully alleviate concerns about yet another knob.
* __randomize_layout for struct lsm_static_call and, in addition to the cover letter add performance numbers to 3rd patch and some minor commit message updates.
* Rebase to linux-next.

# v2 -> v3

* Fixed a build issue on archs which don't have static calls and enable CONFIG_SECURITY.
* Updated the LSM_COUNT macros based on Andrii's suggestions.
* Changed the security_ prefix to lsm_prefix based on Casey's suggestion.
* Inlined static_branch_maybe into lsm_for_each_hook on Kees' feedback.

# v1 -> v2 (based on linux-next, next-20230614)

* Incorporated suggestions from Kees
* Changed the way MAX_LSMs are counted from a binary based generator to a clever header.
* Add CONFIG_SECURITY_HOOK_LIKELY to configure the likelihood of LSM hooks.

KP Singh (5):
kernel: Add helper macros for loop unrolling
security: Count the LSMs enabled at compile time
security: Replace indirect LSM hook calls with static calls
bpf: Only enable BPF LSM hooks when an LSM program is attached
security: Add CONFIG_SECURITY_HOOK_LIKELY

 include/linux/bpf.h       |   1 +
 include/linux/bpf_lsm.h   |   5 +
 include/linux/lsm_count.h | 107 +++++++++++++++++++
 include/linux/lsm_hooks.h |  81 +++++++++++++--
 include/linux/unroll.h    |  36 +++++++
 kernel/bpf/trampoline.c   |  29 +++++-
 security/Kconfig          |  11 ++
 security/bpf/hooks.c      |  25 ++++-
 security/security.c       | 213 +++++++++++++++++++++++++-------------
 9 files changed, 425 insertions(+), 83 deletions(-)
 create mode 100644 include/linux/lsm_count.h
 create mode 100644 include/linux/unroll.h
Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
author maintainer
#1 lore raw

PATCH v4 1/5 kernel: Add helper macros for loop unrolling

This helps in easily initializing blocks of code (e.g. static calls and keys).

UNROLL(N, MACRO, __VA_ARGS__) calls MACRO N times with the first argument as the index of the iteration. This allows string pasting to create unique tokens for variable names, function calls etc.

As an example:

	#include <linux/unroll.h>

	#define MACRO(N, a, b)            \
		int add_##N(int a, int b) \
		{                         \
			return a + b + N; \
		}

	UNROLL(2, MACRO, x, y)

expands to:

	int add_0(int x, int y)
	{
		return x + y + 0;
	}

	int add_1(int x, int y)
	{
		return x + y + 1;
	}
---
 include/linux/unroll.h | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
 create mode 100644 include/linux/unroll.h
include/linux/unroll.h new file +36 -0
new file mode 100644
index 000000000000..d42fd6366373
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (C) 2023 Google LLC.
+ */
+
+#ifndef __UNROLL_H
+#define __UNROLL_H
+
+#include <linux/args.h>
+
+#define UNROLL(N, MACRO, args...) CONCATENATE(__UNROLL_, N)(MACRO, args)
+
+#define __UNROLL_0(MACRO, args...)
+#define __UNROLL_1(MACRO, args...)  __UNROLL_0(MACRO, args)  MACRO(0, args)
+#define __UNROLL_2(MACRO, args...)  __UNROLL_1(MACRO, args)  MACRO(1, args)
+#define __UNROLL_3(MACRO, args...)  __UNROLL_2(MACRO, args)  MACRO(2, args)
+#define __UNROLL_4(MACRO, args...)  __UNROLL_3(MACRO, args)  MACRO(3, args)
+#define __UNROLL_5(MACRO, args...)  __UNROLL_4(MACRO, args)  MACRO(4, args)
+#define __UNROLL_6(MACRO, args...)  __UNROLL_5(MACRO, args)  MACRO(5, args)
+#define __UNROLL_7(MACRO, args...)  __UNROLL_6(MACRO, args)  MACRO(6, args)
+#define __UNROLL_8(MACRO, args...)  __UNROLL_7(MACRO, args)  MACRO(7, args)
+#define __UNROLL_9(MACRO, args...)  __UNROLL_8(MACRO, args)  MACRO(8, args)
+#define __UNROLL_10(MACRO, args...) __UNROLL_9(MACRO, args)  MACRO(9, args)
+#define __UNROLL_11(MACRO, args...) __UNROLL_10(MACRO, args) MACRO(10, args)
+#define __UNROLL_12(MACRO, args...) __UNROLL_11(MACRO, args) MACRO(11, args)
+#define __UNROLL_13(MACRO, args...) __UNROLL_12(MACRO, args) MACRO(12, args)
+#define __UNROLL_14(MACRO, args...) __UNROLL_13(MACRO, args) MACRO(13, args)
+#define __UNROLL_15(MACRO, args...) __UNROLL_14(MACRO, args) MACRO(14, args)
+#define __UNROLL_16(MACRO, args...) __UNROLL_15(MACRO, args) MACRO(15, args)
+#define __UNROLL_17(MACRO, args...) __UNROLL_16(MACRO, args) MACRO(16, args)
+#define __UNROLL_18(MACRO, args...) __UNROLL_17(MACRO, args) MACRO(17, args)
+#define __UNROLL_19(MACRO, args...) __UNROLL_18(MACRO, args) MACRO(18, args)
+#define __UNROLL_20(MACRO, args...) __UNROLL_19(MACRO, args) MACRO(19, args)
+
+#endif /* __UNROLL_H */
Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
author maintainer
#2 lore raw

PATCH v4 2/5 security: Count the LSMs enabled at compile time

In reply to KP Singh

These macros are a clever trick to determine a count of the number of LSMs that are enabled in the config to ascertain the maximum number of static calls that need to be configured per LSM hook.

Without this one would need to generate static calls for the total number of LSMs in the kernel (even if they are not compiled) times the number of LSM hooks which ends up being quite wasteful.

---
 include/linux/lsm_count.h | 107 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 107 insertions(+)
 create mode 100644 include/linux/lsm_count.h
include/linux/lsm_count.h new file +107 -0
new file mode 100644
index 000000000000..4d6dac6efb75
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (C) 2023 Google LLC.
+ */
+
+#ifndef __LINUX_LSM_COUNT_H
+#define __LINUX_LSM_COUNT_H
+
+#include <linux/args.h>
+
+#ifdef CONFIG_SECURITY
+
+/*
+ * Macros to count the number of LSMs enabled in the kernel at compile time.
+ */
+
+/*
+ * Capabilities is enabled when CONFIG_SECURITY is enabled.
+ */
+#if IS_ENABLED(CONFIG_SECURITY)
+#define CAPABILITIES_ENABLED 1,
+#else
+#define CAPABILITIES_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_SELINUX)
+#define SELINUX_ENABLED 1,
+#else
+#define SELINUX_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_SMACK)
+#define SMACK_ENABLED 1,
+#else
+#define SMACK_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_APPARMOR)
+#define APPARMOR_ENABLED 1,
+#else
+#define APPARMOR_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_TOMOYO)
+#define TOMOYO_ENABLED 1,
+#else
+#define TOMOYO_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_YAMA)
+#define YAMA_ENABLED 1,
+#else
+#define YAMA_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_LOADPIN)
+#define LOADPIN_ENABLED 1,
+#else
+#define LOADPIN_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_LOCKDOWN_LSM)
+#define LOCKDOWN_ENABLED 1,
+#else
+#define LOCKDOWN_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_BPF_LSM)
+#define BPF_LSM_ENABLED 1,
+#else
+#define BPF_LSM_ENABLED
+#endif
+
+#if IS_ENABLED(CONFIG_SECURITY_LANDLOCK)
+#define LANDLOCK_ENABLED 1,
+#else
+#define LANDLOCK_ENABLED
+#endif
+
+/*
+ *  There is a trailing comma that we need to be accounted for. This is done by
+ *  using a skipped argument in __COUNT_LSMS
+ */
+#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args)
+#define COUNT_LSMS(args...) __COUNT_LSMS(args)
+
+#define MAX_LSM_COUNT			\
+	COUNT_LSMS(			\
+		CAPABILITIES_ENABLED	\
+		SELINUX_ENABLED		\
+		SMACK_ENABLED		\
+		APPARMOR_ENABLED	\
+		TOMOYO_ENABLED		\
+		YAMA_ENABLED		\
+		LOADPIN_ENABLED		\
+		LOCKDOWN_ENABLED	\
+		BPF_LSM_ENABLED		\
+		LANDLOCK_ENABLED)
+
+#else
+
+#define MAX_LSM_COUNT 0
+
+#endif /* CONFIG_SECURITY */
+
+#endif  /* __LINUX_LSM_COUNT_H */
Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
Reviewed-by on v4 2/5
#3 lore raw

Re: [PATCH v4 2/5] security: Count the LSMs enabled at compile time

Quoted 4 lines · KP Singh

These macros are a clever trick to determine a count of the number of LSMs that are enabled in the config to ascertain the maximum number of static calls that need to be configured per LSM hook.

Quoted 8 lines

Without this one would need to generate static calls for the total number of LSMs in the kernel (even if they are not compiled) times the number of LSM hooks which ends up being quite wasteful.

Thought below, but regardless of result:

Quoted 26 lines
---
 include/linux/lsm_count.h | 107 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 107 insertions(+)
 create mode 100644 include/linux/lsm_count.h
include/linux/lsm_count.h new file +15 -0
new file mode 100644
index 000000000000..4d6dac6efb75
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (C) 2023 Google LLC.
+ */
+
+#ifndef __LINUX_LSM_COUNT_H
+#define __LINUX_LSM_COUNT_H
+
+#include <linux/args.h>
+
+#ifdef CONFIG_SECURITY
+
+/*
+ * Macros to count the number of LSMs enabled in the kernel at compile time.

include/linux/lsm_count.h line 25

Quoted 10 lines
include/linux/lsm_count.h new file +10 -0
+ */
+
+/*
+ * Capabilities is enabled when CONFIG_SECURITY is enabled.
+ */
+#if IS_ENABLED(CONFIG_SECURITY)
+#define CAPABILITIES_ENABLED 1,
+#else
+#define CAPABILITIES_ENABLED
+#endif

We're in an #ifdef CONFIG_SECURITY, so CAPABILITIES_ENABLED will always be set. As such, we could leave off the trailing comma and list it _last_ in the macro, and then ...

include/linux/lsm_count.h line 86

Quoted 6 lines
include/linux/lsm_count.h new file +6 -0
+/*
+ *  There is a trailing comma that we need to be accounted for. This is done by
+ *  using a skipped argument in __COUNT_LSMS
+ */
+#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args)
+#define COUNT_LSMS(args...) __COUNT_LSMS(args)

This wouldn't be needed...

include/linux/lsm_count.h line 99

Quoted 13 lines
include/linux/lsm_count.h new file +13 -0
+
+#define MAX_LSM_COUNT			\
+	COUNT_LSMS(			\
+		CAPABILITIES_ENABLED	\
+		SELINUX_ENABLED		\
+		SMACK_ENABLED		\
+		APPARMOR_ENABLED	\
+		TOMOYO_ENABLED		\
+		YAMA_ENABLED		\
+		LOADPIN_ENABLED		\
+		LOCKDOWN_ENABLED	\
+		BPF_LSM_ENABLED		\
+		LANDLOCK_ENABLED)
	COUNT_ARGS(			\
		SELINUX_ENABLED		\
		SMACK_ENABLED		\
		...
		CAPABILITIES_ENABLED)

-Kees

Signature · 1 line
Kees Cook
author maintainer
#4 lore raw

Re: [PATCH v4 2/5] security: Count the LSMs enabled at compile time

Quoted 61 lines · Kees Cook
Quoted 4 lines · KP Singh

These macros are a clever trick to determine a count of the number of LSMs that are enabled in the config to ascertain the maximum number of static calls that need to be configured per LSM hook.

Quoted 8 lines

Without this one would need to generate static calls for the total number of LSMs in the kernel (even if they are not compiled) times the number of LSM hooks which ends up being quite wasteful.

Thought below, but regardless of result:

Quoted 26 lines
---
 include/linux/lsm_count.h | 107 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 107 insertions(+)
 create mode 100644 include/linux/lsm_count.h
include/linux/lsm_count.h new file +15 -0
new file mode 100644
index 000000000000..4d6dac6efb75
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (C) 2023 Google LLC.
+ */
+
+#ifndef __LINUX_LSM_COUNT_H
+#define __LINUX_LSM_COUNT_H
+
+#include <linux/args.h>
+
+#ifdef CONFIG_SECURITY
+
+/*
+ * Macros to count the number of LSMs enabled in the kernel at compile time.

include/linux/lsm_count.h line 25

Quoted 10 lines
include/linux/lsm_count.h new file +10 -0
+ */
+
+/*
+ * Capabilities is enabled when CONFIG_SECURITY is enabled.
+ */
+#if IS_ENABLED(CONFIG_SECURITY)
+#define CAPABILITIES_ENABLED 1,
+#else
+#define CAPABILITIES_ENABLED
+#endif

We're in an #ifdef CONFIG_SECURITY, so CAPABILITIES_ENABLED will always be set. As such, we could leave off the trailing comma and list it _last_ in the macro, and then ...

Quoted 8 lines

include/linux/lsm_count.h line 86

Quoted 6 lines
include/linux/lsm_count.h new file +6 -0
+/*
+ *  There is a trailing comma that we need to be accounted for. This is done by
+ *  using a skipped argument in __COUNT_LSMS
+ */
+#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args)
+#define COUNT_LSMS(args...) __COUNT_LSMS(args)

This wouldn't be needed...

Slight preference for explicitly having the capabilities listed than implicitly over counting. But no strong opinion, fine with either approches.

Quoted 26 lines
Quoted 4 lines
include/linux/lsm_count.h new file +3 -0
+
+#define MAX_LSM_COUNT                        \
+     COUNT_LSMS(                     \

include/linux/lsm_count.h line 99

Quoted 10 lines
include/linux/lsm_count.h new file +10 -0
+             CAPABILITIES_ENABLED    \
+             SELINUX_ENABLED         \
+             SMACK_ENABLED           \
+             APPARMOR_ENABLED        \
+             TOMOYO_ENABLED          \
+             YAMA_ENABLED            \
+             LOADPIN_ENABLED         \
+             LOCKDOWN_ENABLED        \
+             BPF_LSM_ENABLED         \
+             LANDLOCK_ENABLED)
        COUNT_ARGS(                     \
                SELINUX_ENABLED         \
                SMACK_ENABLED           \
                ...
                CAPABILITIES_ENABLED)

-Kees

--
Kees Cook

author maintainer
#5 lore raw

Re: [PATCH v4 2/5] security: Count the LSMs enabled at compile time

Quoted 72 lines · KP Singh
Quoted 61 lines · Kees Cook
Quoted 4 lines · KP Singh

These macros are a clever trick to determine a count of the number of LSMs that are enabled in the config to ascertain the maximum number of static calls that need to be configured per LSM hook.

Quoted 8 lines

Without this one would need to generate static calls for the total number of LSMs in the kernel (even if they are not compiled) times the number of LSM hooks which ends up being quite wasteful.

Thought below, but regardless of result:

Quoted 26 lines
---
 include/linux/lsm_count.h | 107 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 107 insertions(+)
 create mode 100644 include/linux/lsm_count.h
include/linux/lsm_count.h new file +15 -0
new file mode 100644
index 000000000000..4d6dac6efb75
@@ -0,0 +1,107 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * Copyright (C) 2023 Google LLC.
+ */
+
+#ifndef __LINUX_LSM_COUNT_H
+#define __LINUX_LSM_COUNT_H
+
+#include <linux/args.h>
+
+#ifdef CONFIG_SECURITY
+
+/*
+ * Macros to count the number of LSMs enabled in the kernel at compile time.

include/linux/lsm_count.h line 25

Quoted 10 lines
include/linux/lsm_count.h new file +10 -0
+ */
+
+/*
+ * Capabilities is enabled when CONFIG_SECURITY is enabled.
+ */
+#if IS_ENABLED(CONFIG_SECURITY)
+#define CAPABILITIES_ENABLED 1,
+#else
+#define CAPABILITIES_ENABLED
+#endif

We're in an #ifdef CONFIG_SECURITY, so CAPABILITIES_ENABLED will always be set. As such, we could leave off the trailing comma and list it _last_ in the macro, and then ...

Quoted 8 lines

include/linux/lsm_count.h line 86

Quoted 6 lines
include/linux/lsm_count.h new file +6 -0
+/*
+ *  There is a trailing comma that we need to be accounted for. This is done by
+ *  using a skipped argument in __COUNT_LSMS
+ */
+#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args)
+#define COUNT_LSMS(args...) __COUNT_LSMS(args)

This wouldn't be needed...

Quoted 3 lines

Slight preference for explicitly having the capabilities listed than implicitly over counting. But no strong opinion, fine with either approches.

Actually it's not just a preference but really required. When the CAPABILITIES is absent and all other LSMs are disabled it leads to COUNT_ARGS() which evaluates to 0

This also happens here:

https://lore.kernel.org/bpf/[email protected]/

and to fix this we need:

-#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args) +#define __COUNT_LSMS(skipped_arg, args...) COUNT_ARGS(args...)

And I checked the edge cases with a simple c file

int test(void) {
int count = MAX_LSM_COUNT;
}

and make security/count.i:

for just CONFIG_SECURITY enabled:

int test(void) {
int count = 1;
}

with another LSM:

int test(void) {
int count = 2;
}

- KP

Quoted 27 lines
Quoted 27 lines
Quoted 5 lines
include/linux/lsm_count.h new file +3 -0
+
+#define MAX_LSM_COUNT                        \
+     COUNT_LSMS(                     \

include/linux/lsm_count.h line 99

Quoted 10 lines
include/linux/lsm_count.h new file +10 -0
+             CAPABILITIES_ENABLED    \
+             SELINUX_ENABLED         \
+             SMACK_ENABLED           \
+             APPARMOR_ENABLED        \
+             TOMOYO_ENABLED          \
+             YAMA_ENABLED            \
+             LOADPIN_ENABLED         \
+             LOCKDOWN_ENABLED        \
+             BPF_LSM_ENABLED         \
+             LANDLOCK_ENABLED)
        COUNT_ARGS(                     \
                SELINUX_ENABLED         \
                SMACK_ENABLED           \
                ...
                CAPABILITIES_ENABLED)

-Kees

--
Kees Cook

author maintainer
#6 lore raw

PATCH v4 3/5 security: Replace indirect LSM hook calls with static calls

In reply to KP Singh

LSM hooks are currently invoked from a linked list as indirect calls which are invoked using retpolines as a mitigation for speculative attacks (Branch History / Target injection) and add extra overhead which is especially bad in kernel hot paths:

security_file_ioctl:
0xffffffff814f0320 <+0>: endbr64

   0xffffffff814f0324 <+4>:	push   %rbp
   0xffffffff814f0325 <+5>:	push   %r15
   0xffffffff814f0327 <+7>:	push   %r14
   0xffffffff814f0329 <+9>:	push   %rbx
   0xffffffff814f032a <+10>:	mov    %rdx,%rbx
   0xffffffff814f032d <+13>:	mov    %esi,%ebp
   0xffffffff814f032f <+15>:	mov    %rdi,%r14
   0xffffffff814f0332 <+18>:	mov    $0xffffffff834a7030,%r15
   0xffffffff814f0339 <+25>:	mov    (%r15),%r15
   0xffffffff814f033c <+28>:	test   %r15,%r15
   0xffffffff814f033f <+31>:	je     0xffffffff814f0358 <security_file_ioctl+56>
   0xffffffff814f0341 <+33>:	mov    0x18(%r15),%r11
   0xffffffff814f0345 <+37>:	mov    %r14,%rdi
   0xffffffff814f0348 <+40>:	mov    %ebp,%esi
   0xffffffff814f034a <+42>:	mov    %rbx,%rdx

0xffffffff814f034d <+45>: call 0xffffffff81f742e0 <__x86_indirect_thunk_array+352>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Indirect calls that use retpolines leading to overhead, not just due to extra instruction but also branch misses.

   0xffffffff814f0352 <+50>:	test   %eax,%eax
   0xffffffff814f0354 <+52>:	je     0xffffffff814f0339 <security_file_ioctl+25>
   0xffffffff814f0356 <+54>:	jmp    0xffffffff814f035a <security_file_ioctl+58>
   0xffffffff814f0358 <+56>:	xor    %eax,%eax
   0xffffffff814f035a <+58>:	pop    %rbx
   0xffffffff814f035b <+59>:	pop    %r14
   0xffffffff814f035d <+61>:	pop    %r15
   0xffffffff814f035f <+63>:	pop    %rbp
   0xffffffff814f0360 <+64>:	jmp    0xffffffff81f747c4 <__x86_return_thunk>

The indirect calls are not really needed as one knows the addresses of enabled LSM callbacks at boot time and only the order can possibly change at boot time with the lsm= kernel command line parameter.

An array of static calls is defined per LSM hook and the static calls are updated at boot time once the order has been determined.

A static key guards whether an LSM static call is enabled or not, without this static key, for LSM hooks that return an int, the presence of the hook that returns a default value can create side-effects which has resulted in bugs [1].

With the hook now exposed as a static call, one can see that the retpolines are no longer there and the LSM callbacks are invoked directly:

security_file_ioctl:
0xffffffff818f0ca0 <+0>: endbr64
0xffffffff818f0ca4 <+4>: nopl 0x0(%rax,%rax,1)
0xffffffff818f0ca9 <+9>: push %rbp

   0xffffffff818f0caa <+10>:	push   %r14
   0xffffffff818f0cac <+12>:	push   %rbx
   0xffffffff818f0cad <+13>:	mov    %rdx,%rbx
   0xffffffff818f0cb0 <+16>:	mov    %esi,%ebp
   0xffffffff818f0cb2 <+18>:	mov    %rdi,%r14
   0xffffffff818f0cb5 <+21>:	jmp    0xffffffff818f0cc7 <security_file_ioctl+39>

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Static key enabled for SELinux

0xffffffff818f0cb7 <+23>: jmp 0xffffffff818f0cde <security_file_ioctl+62>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Static key enabled for BPF LSM. This is something that is changed to default to false to avoid the existing side effect issues of BPF LSM
[1] in a subsequent patch.

   0xffffffff818f0cb9 <+25>:	xor    %eax,%eax
   0xffffffff818f0cbb <+27>:	xchg   %ax,%ax
   0xffffffff818f0cbd <+29>:	pop    %rbx
   0xffffffff818f0cbe <+30>:	pop    %r14
   0xffffffff818f0cc0 <+32>:	pop    %rbp
   0xffffffff818f0cc1 <+33>:	cs jmp 0xffffffff82c00000 <__x86_return_thunk>
   0xffffffff818f0cc7 <+39>:	endbr64
   0xffffffff818f0ccb <+43>:	mov    %r14,%rdi
   0xffffffff818f0cce <+46>:	mov    %ebp,%esi
   0xffffffff818f0cd0 <+48>:	mov    %rbx,%rdx
   0xffffffff818f0cd3 <+51>:	call   0xffffffff81903230 <selinux_file_ioctl>

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Direct call to SELinux.

   0xffffffff818f0cd8 <+56>:	test   %eax,%eax
   0xffffffff818f0cda <+58>:	jne    0xffffffff818f0cbd <security_file_ioctl+29>
   0xffffffff818f0cdc <+60>:	jmp    0xffffffff818f0cb7 <security_file_ioctl+23>
   0xffffffff818f0cde <+62>:	endbr64
   0xffffffff818f0ce2 <+66>:	mov    %r14,%rdi
   0xffffffff818f0ce5 <+69>:	mov    %ebp,%esi
   0xffffffff818f0ce7 <+71>:	mov    %rbx,%rdx
   0xffffffff818f0cea <+74>:	call   0xffffffff8141e220 <bpf_lsm_file_ioctl>

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Direct call to BPF LSM.

   0xffffffff818f0cef <+79>:	test   %eax,%eax
   0xffffffff818f0cf1 <+81>:	jne    0xffffffff818f0cbd <security_file_ioctl+29>
   0xffffffff818f0cf3 <+83>:	jmp    0xffffffff818f0cb9 <security_file_ioctl+25>
   0xffffffff818f0cf5 <+85>:	endbr64
   0xffffffff818f0cf9 <+89>:	mov    %r14,%rdi
   0xffffffff818f0cfc <+92>:	mov    %ebp,%esi
   0xffffffff818f0cfe <+94>:	mov    %rbx,%rdx
   0xffffffff818f0d01 <+97>:	pop    %rbx
   0xffffffff818f0d02 <+98>:	pop    %r14

0xffffffff818f0d04 <+100>: pop %rbp
0xffffffff818f0d05 <+101>: ret
0xffffffff818f0d06 <+102>: int3
0xffffffff818f0d07 <+103>: int3
0xffffffff818f0d08 <+104>: int3
0xffffffff818f0d09 <+105>: int3

While this patch uses static_branch_unlikely indicating that an LSM hook is likely to be not present, a subsequent makes it configurable. In most cases this is still a better choice as even when an LSM with one hook is added, empty slots are created for all LSM hooks (especially when many LSMs that do not initialize most hooks are present on the system).

There are some hooks that don't use the call_int_hook and call_void_hook. These hooks are updated to use a new macro called security_for_each_hook where the lsm_callback is directly invoked as an indirect call. Currently, there are no performance sensitive hooks that use the security_for_each_hook macro. However, if, some performance sensitive hooks are discovered, these can be updated to use static calls with loop unrolling as well using a custom macro.

Below are results of the relevant Unixbench system benchmarks with BPF LSM and SELinux enabled with default policies enabled with and without these patches.

Benchmark Delta(%): (+ is better)
===============================================================================

Execl Throughput                                             +1.9356
File Write 1024 bufsize 2000 maxblocks                       +6.5953
Pipe Throughput                                              +9.5499
Pipe-based Context Switching                                 +3.0209
Process Creation                                             +2.3246
Shell Scripts (1 concurrent)                                 +1.4975
System Call Overhead                                         +2.7815
System Benchmarks Index Score (Partial Only):                +3.4859

In the best case, some syscalls like eventfd_create benefitted to about ~10%.

---
 include/linux/lsm_hooks.h |  70 +++++++++++--
 security/security.c       | 208 +++++++++++++++++++++++++-------------
 2 files changed, 199 insertions(+), 79 deletions(-)
include/linux/lsm_hooks.h +62 -8
index dcb5e5b5eb13..c77a1859214d 100644
@@ -29,26 +29,77 @@
 #include <linux/init.h>
 #include <linux/rculist.h>
 #include <linux/xattr.h>
+#include <linux/static_call.h>
+#include <linux/unroll.h>
+#include <linux/jump_label.h>
+#include <linux/lsm_count.h>
+
+#define SECURITY_HOOK_ACTIVE_KEY(HOOK, IDX) security_hook_active_##HOOK##_##IDX
+
+/*
+ * Identifier for the LSM static calls.
+ * HOOK is an LSM hook as defined in linux/lsm_hookdefs.h
+ * IDX is the index of the static call. 0 <= NUM < MAX_LSM_COUNT
+ */
+#define LSM_STATIC_CALL(HOOK, IDX) lsm_static_call_##HOOK##_##IDX
+
+/*
+ * Call the macro M for each LSM hook MAX_LSM_COUNT times.
+ */
+#define LSM_LOOP_UNROLL(M, ...) 		\
+do {						\
+	UNROLL(MAX_LSM_COUNT, M, __VA_ARGS__)	\
+} while (0)
+
+#define LSM_DEFINE_UNROLL(M, ...) UNROLL(MAX_LSM_COUNT, M, __VA_ARGS__)
 
 union security_list_options {
 	#define LSM_HOOK(RET, DEFAULT, NAME, ...) RET (*NAME)(__VA_ARGS__);
 	#include "lsm_hook_defs.h"
 	#undef LSM_HOOK
+	void *lsm_callback;
 };
 
-struct security_hook_heads {
-	#define LSM_HOOK(RET, DEFAULT, NAME, ...) struct hlist_head NAME;
-	#include "lsm_hook_defs.h"
+/*
+ * @key: static call key as defined by STATIC_CALL_KEY
+ * @trampoline: static call trampoline as defined by STATIC_CALL_TRAMP
+ * @hl: The security_hook_list as initialized by the owning LSM.
+ * @active: Enabled when the static call has an LSM hook associated.
+ */
+struct lsm_static_call {
+	struct static_call_key *key;
+	void *trampoline;
+	struct security_hook_list *hl;
+	/* this needs to be true or false based on what the key defaults to */
+	struct static_key_false *active;
+} __randomize_layout;
+
+/*
+ * Table of the static calls for each LSM hook.
+ * Once the LSMs are initialized, their callbacks will be copied to these
+ * tables such that the calls are filled backwards (from last to first).
+ * This way, we can jump directly to the first used static call, and execute
+ * all of them after. This essentially makes the entry point
+ * dynamic to adapt the number of static calls to the number of callbacks.
+ */
+struct lsm_static_calls_table {
+	#define LSM_HOOK(RET, DEFAULT, NAME, ...) \
+		struct lsm_static_call NAME[MAX_LSM_COUNT];
+	#include <linux/lsm_hook_defs.h>
 	#undef LSM_HOOK
 } __randomize_layout;
 
 /*
  * Security module hook list structure.
  * For use with generic list macros for common operations.
+ *
+ * struct security_hook_list - Contents of a cacheable, mappable object.
+ * @scalls: The beginning of the array of static calls assigned to this hook.
+ * @hook: The callback for the hook.
+ * @lsm: The name of the lsm that owns this hook.
  */
 struct security_hook_list {
-	struct hlist_node		list;
-	struct hlist_head		*head;
+	struct lsm_static_call	*scalls;
 	union security_list_options	hook;
 	const char			*lsm;
 } __randomize_layout;
@@ -97,10 +148,12 @@ static inline struct xattr *lsm_get_xattr_slot(struct xattr *xattrs,
  * care of the common case and reduces the amount of
  * text involved.
  */
-#define LSM_HOOK_INIT(HEAD, HOOK) \
-	{ .head = &security_hook_heads.HEAD, .hook = { .HEAD = HOOK } }
+#define LSM_HOOK_INIT(NAME, CALLBACK)			\
+	{						\
+		.scalls = static_calls_table.NAME,	\
+		.hook = { .NAME = CALLBACK }		\
+	}
 
-extern struct security_hook_heads security_hook_heads;
 extern char *lsm_names;
 
 extern void security_add_hooks(struct security_hook_list *hooks, int count,
@@ -138,5 +191,6 @@ extern struct lsm_info __start_early_lsm_info[], __end_early_lsm_info[];
 		__aligned(sizeof(unsigned long))
 
 extern int lsm_inode_alloc(struct inode *inode);
+extern struct lsm_static_calls_table static_calls_table __ro_after_init;
 
 #endif /* ! __LINUX_LSM_HOOKS_H */
security/security.c +137 -71

392 lines not on this page · raw message

Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
#7 lore raw

Re: [PATCH v4 3/5] security: Replace indirect LSM hook calls with static calls

kernel test robot noticed the following build warnings:

Hi KP,

kernel test robot noticed the following build warnings:

[auto build test WARNING on bpf-next/master]
[also build test WARNING on bpf/master pcmoore-selinux/next linus/master v6.6-rc2 next-20230921] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/KP-Singh/kernel-Add-helper-macros-for-loop-unrolling/20230922-225925
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230922145505.4044003-4-kpsingh%40kernel.org
patch subject: [PATCH v4 3/5] security: Replace indirect LSM hook calls with static calls
config: arm64-defconfig (https://download.01.org/0day-ci/archive/20230923/[email protected]/config)
compiler: aarch64-linux-gcc (GCC) 13.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20230923/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

security/security.c: In function 'security_binder_set_context_mgr':

>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:872:16: note: in expansion of macro 'call_int_hook'
     872 |         return call_int_hook(binder_set_context_mgr, 0, mgr);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_binder_transaction':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:887:16: note: in expansion of macro 'call_int_hook'
     887 |         return call_int_hook(binder_transaction, 0, from, to);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_binder_transfer_binder':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:902:16: note: in expansion of macro 'call_int_hook'
     902 |         return call_int_hook(binder_transfer_binder, 0, from, to);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_binder_transfer_file':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:918:16: note: in expansion of macro 'call_int_hook'
     918 |         return call_int_hook(binder_transfer_file, 0, from, to, file);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_ptrace_access_check':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:937:16: note: in expansion of macro 'call_int_hook'
     937 |         return call_int_hook(ptrace_access_check, 0, child, mode);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_ptrace_traceme':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:952:16: note: in expansion of macro 'call_int_hook'
     952 |         return call_int_hook(ptrace_traceme, 0, parent);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_capget':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:974:16: note: in expansion of macro 'call_int_hook'
     974 |         return call_int_hook(capget, 0, target,
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_capset':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:996:16: note: in expansion of macro 'call_int_hook'
     996 |         return call_int_hook(capset, 0, new, old,
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_capable':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1018:16: note: in expansion of macro 'call_int_hook'
    1018 |         return call_int_hook(capable, 0, cred, ns, cap, opts);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_quotactl':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1034:16: note: in expansion of macro 'call_int_hook'
    1034 |         return call_int_hook(quotactl, 0, cmds, type, id, sb);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_quota_on':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1047:16: note: in expansion of macro 'call_int_hook'
    1047 |         return call_int_hook(quota_on, 0, dentry);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_syslog':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1062:16: note: in expansion of macro 'call_int_hook'
    1062 |         return call_int_hook(syslog, 0, type);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_settime64':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1077:16: note: in expansion of macro 'call_int_hook'
    1077 |         return call_int_hook(settime, 0, ts, tz);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_bprm_creds_for_exec':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1132:16: note: in expansion of macro 'call_int_hook'
    1132 |         return call_int_hook(bprm_creds_for_exec, 0, bprm);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_bprm_creds_from_file':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1156:16: note: in expansion of macro 'call_int_hook'
    1156 |         return call_int_hook(bprm_creds_from_file, 0, bprm, file);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_bprm_check':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1175:15: note: in expansion of macro 'call_int_hook'
    1175 |         ret = call_int_hook(bprm_check_security, 0, bprm);
         |               ^~~~~~~~~~~~~
   security/security.c: In function 'security_fs_context_submount':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1225:16: note: in expansion of macro 'call_int_hook'
    1225 |         return call_int_hook(fs_context_submount, 0, fc, reference);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_fs_context_dup':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1241:16: note: in expansion of macro 'call_int_hook'
    1241 |         return call_int_hook(fs_context_dup, 0, fc, src_fc);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_alloc':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1289:14: note: in expansion of macro 'call_int_hook'
    1289 |         rc = call_int_hook(sb_alloc_security, 0, sb);
         |              ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_eat_lsm_opts':
>> security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1347:16: note: in expansion of macro 'call_int_hook'
    1347 |         return call_int_hook(sb_eat_lsm_opts, 0, options, mnt_opts);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_mnt_opts_compat':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1364:16: note: in expansion of macro 'call_int_hook'
    1364 |         return call_int_hook(sb_mnt_opts_compat, 0, sb, mnt_opts);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_remount':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1381:16: note: in expansion of macro 'call_int_hook'
    1381 |         return call_int_hook(sb_remount, 0, sb, mnt_opts);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_kern_mount':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1395:16: note: in expansion of macro 'call_int_hook'
    1395 |         return call_int_hook(sb_kern_mount, 0, sb);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_show_options':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1409:16: note: in expansion of macro 'call_int_hook'
    1409 |         return call_int_hook(sb_show_options, 0, m, sb);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_statfs':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1423:16: note: in expansion of macro 'call_int_hook'
    1423 |         return call_int_hook(sb_statfs, 0, dentry);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_mount':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1446:16: note: in expansion of macro 'call_int_hook'
    1446 |         return call_int_hook(sb_mount, 0, dev_name, path, type, flags, data);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_umount':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1460:16: note: in expansion of macro 'call_int_hook'
    1460 |         return call_int_hook(sb_umount, 0, mnt, flags);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_pivotroot':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1475:16: note: in expansion of macro 'call_int_hook'
    1475 |         return call_int_hook(sb_pivotroot, 0, old_path, new_path);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_set_mnt_opts':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1494:16: note: in expansion of macro 'call_int_hook'
    1494 |         return call_int_hook(sb_set_mnt_opts,
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_sb_clone_mnt_opts':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1516:16: note: in expansion of macro 'call_int_hook'
    1516 |         return call_int_hook(sb_clone_mnt_opts, 0, oldsb, newsb,
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_move_mount':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1533:16: note: in expansion of macro 'call_int_hook'
    1533 |         return call_int_hook(move_mount, 0, from_path, to_path);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_path_notify':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1550:16: note: in expansion of macro 'call_int_hook'
    1550 |         return call_int_hook(path_notify, 0, path, mask, obj_type);
         |                ^~~~~~~~~~~~~
   security/security.c: In function 'security_inode_alloc':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~
   security/security.c:1569:14: note: in expansion of macro 'call_int_hook'
    1569 |         rc = call_int_hook(inode_alloc_security, 0, inode);
         |              ^~~~~~~~~~~~~
   security/security.c: In function 'security_dentry_create_files_as':
   security/security.c:851:1: warning: label 'out' defined but not used [-Wunused-label]
     851 | out:                                                                    \
         | ^~~

vim +/out +851 security/security.c

845
846 #define call_int_hook(FUNC, IRC, ...) \
847 ({ \
848 __label__ out; \
849 int RC = IRC; \
850 LSM_LOOP_UNROLL(__CALL_STATIC_INT, RC, FUNC, out, __VA_ARGS__); \

 > 851	out:									\

852 RC; \
853 })
854

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#8 lore raw

Re: [PATCH v4 3/5] security: Replace indirect LSM hook calls with static calls

In reply to KP Singh
kernel test robot noticed "Kernel_panic-not_syncing:lsm_static_call_init-Ran_out_of_static_slots" on:

Hello,

kernel test robot noticed "Kernel_panic-not_syncing:lsm_static_call_init-Ran_out_of_static_slots" on:

commit: e75df0d5718c3d39cd53e2459b04806ed8789253 ("[PATCH v4 3/5] security: Replace indirect LSM hook calls with static calls")
url: https://github.com/intel-lab-lkp/linux/commits/KP-Singh/kernel-Add-helper-macros-for-loop-unrolling/20230922-225925
base: https://git.kernel.org/cgit/linux/kernel/git/bpf/bpf-next.git master
patch link: https://lore.kernel.org/all/[email protected]/
patch subject: [PATCH v4 3/5] security: Replace indirect LSM hook calls with static calls

in testcase: boot

compiler: gcc-12
test machine: qemu-system-x86_64 -enable-kvm -cpu SandyBridge -smp 2 -m 16G

(please refer to attached dmesg/kmsg for entire log/backtrace)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-lkp/[email protected]

[    1.002757][    T0] MDS: Vulnerable: Clear CPU buffers attempted, no microcode
[    1.006940][    T0] MMIO Stale Data: Unknown: No mitigations
[    1.010166][    T0] x86/fpu: x87 FPU will use FXSAVE
[    1.012429][    T0] pid_max: default: 32768 minimum: 301
[    1.014553][    T0] LSM: initializing lsm=capability,integrity
[    1.016244][    T0] Kernel panic - not syncing: lsm_static_call_init - Ran out of static slots.
[    1.018151][    T0] CPU: 0 PID: 0 Comm: swapper Not tainted 6.6.0-rc2-00661-ge75df0d5718c-dirty #1
[    1.018151][    T0] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
[    1.018151][    T0] Call Trace:
[ 1.018151][ T0] dump_stack_lvl (??:?) 
[ 1.018151][ T0] dump_stack (??:?) 
[ 1.018151][ T0] panic (??:?) 
[ 1.018151][ T0] security_add_hooks (??:?) 
[ 1.018151][ T0] capability_init (commoncap.c:?) 

The kernel config and materials to reproduce are available at:
https://download.01.org/0day-ci/archive/20230927/[email protected]

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author maintainer
#9 lore raw

PATCH v4 4/5 bpf: Only enable BPF LSM hooks when an LSM program is attached

In reply to KP Singh

BPF LSM hooks have side-effects (even when a default value is returned), as some hooks end up behaving differently due to the very presence of the hook.

The static keys guarding the BPF LSM hooks are disabled by default and enabled only when a BPF program is attached implementing the hook logic. This avoids the issue of the side-effects and also the minor overhead associated with the empty callback.

security_file_ioctl:
0xffffffff818f0e30 <+0>: endbr64
0xffffffff818f0e34 <+4>: nopl 0x0(%rax,%rax,1)
0xffffffff818f0e39 <+9>: push %rbp

   0xffffffff818f0e3a <+10>:	push   %r14
   0xffffffff818f0e3c <+12>:	push   %rbx
   0xffffffff818f0e3d <+13>:	mov    %rdx,%rbx
   0xffffffff818f0e40 <+16>:	mov    %esi,%ebp
   0xffffffff818f0e42 <+18>:	mov    %rdi,%r14
   0xffffffff818f0e45 <+21>:	jmp    0xffffffff818f0e57 <security_file_ioctl+39>

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Static key enabled for SELinux

0xffffffff818f0e47 <+23>: xchg %ax,%ax
^^^^^^^^^^^^^^

Static key disabled for BPF. This gets patched when a BPF LSM program is attached

   0xffffffff818f0e49 <+25>:	xor    %eax,%eax
   0xffffffff818f0e4b <+27>:	xchg   %ax,%ax
   0xffffffff818f0e4d <+29>:	pop    %rbx
   0xffffffff818f0e4e <+30>:	pop    %r14
   0xffffffff818f0e50 <+32>:	pop    %rbp
   0xffffffff818f0e51 <+33>:	cs jmp 0xffffffff82c00000 <__x86_return_thunk>
   0xffffffff818f0e57 <+39>:	endbr64
   0xffffffff818f0e5b <+43>:	mov    %r14,%rdi
   0xffffffff818f0e5e <+46>:	mov    %ebp,%esi
   0xffffffff818f0e60 <+48>:	mov    %rbx,%rdx
   0xffffffff818f0e63 <+51>:	call   0xffffffff819033c0 <selinux_file_ioctl>
   0xffffffff818f0e68 <+56>:	test   %eax,%eax
   0xffffffff818f0e6a <+58>:	jne    0xffffffff818f0e4d <security_file_ioctl+29>
   0xffffffff818f0e6c <+60>:	jmp    0xffffffff818f0e47 <security_file_ioctl+23>
   0xffffffff818f0e6e <+62>:	endbr64
   0xffffffff818f0e72 <+66>:	mov    %r14,%rdi
   0xffffffff818f0e75 <+69>:	mov    %ebp,%esi
   0xffffffff818f0e77 <+71>:	mov    %rbx,%rdx
   0xffffffff818f0e7a <+74>:	call   0xffffffff8141e3b0 <bpf_lsm_file_ioctl>
   0xffffffff818f0e7f <+79>:	test   %eax,%eax
   0xffffffff818f0e81 <+81>:	jne    0xffffffff818f0e4d <security_file_ioctl+29>
   0xffffffff818f0e83 <+83>:	jmp    0xffffffff818f0e49 <security_file_ioctl+25>
   0xffffffff818f0e85 <+85>:	endbr64
   0xffffffff818f0e89 <+89>:	mov    %r14,%rdi
   0xffffffff818f0e8c <+92>:	mov    %ebp,%esi
   0xffffffff818f0e8e <+94>:	mov    %rbx,%rdx
   0xffffffff818f0e91 <+97>:	pop    %rbx
   0xffffffff818f0e92 <+98>:	pop    %r14

0xffffffff818f0e94 <+100>: pop %rbp
0xffffffff818f0e95 <+101>: ret

---
 include/linux/bpf.h       |  1 +
 include/linux/bpf_lsm.h   |  5 +++++
 include/linux/lsm_hooks.h | 13 ++++++++++++-
 kernel/bpf/trampoline.c   | 29 +++++++++++++++++++++++++++--
 security/bpf/hooks.c      | 25 ++++++++++++++++++++++++-
 security/security.c       |  3 ++-
 6 files changed, 71 insertions(+), 5 deletions(-)
include/linux/bpf.h +1 -0
index a34ac7f00c86..d52d5205e9ba 100644
@@ -1159,6 +1159,7 @@ struct bpf_attach_target_info {
 	struct module *tgt_mod;
 	const char *tgt_name;
 	const struct btf_type *tgt_type;
+	bool is_lsm_target;
 };
 
 #define BPF_DISPATCHER_MAX 48 /* Fits in 2048B */
include/linux/bpf_lsm.h +5 -0
index 1de7ece5d36d..5bbc31ac948c 100644
@@ -29,6 +29,7 @@ int bpf_lsm_verify_prog(struct bpf_verifier_log *vlog,
 
 bool bpf_lsm_is_sleepable_hook(u32 btf_id);
 bool bpf_lsm_is_trusted(const struct bpf_prog *prog);
+void bpf_lsm_toggle_hook(void *addr, bool value);
 
 static inline struct bpf_storage_blob *bpf_inode(
 	const struct inode *inode)
@@ -78,6 +79,10 @@ static inline void bpf_lsm_find_cgroup_shim(const struct bpf_prog *prog,
 {
 }
 
+static inline void bpf_lsm_toggle_hook(void *addr, bool value)
+{
+}
+
 #endif /* CONFIG_BPF_LSM */
 
 #endif /* _LINUX_BPF_LSM_H */
include/linux/lsm_hooks.h +12 -1
index c77a1859214d..57ffe4eb6d30 100644
@@ -97,11 +97,14 @@ struct lsm_static_calls_table {
  * @scalls: The beginning of the array of static calls assigned to this hook.
  * @hook: The callback for the hook.
  * @lsm: The name of the lsm that owns this hook.
+ * @default_state: The state of the LSM hook when initialized. If set to false,
+ * the static key guarding the hook will be set to disabled.
  */
 struct security_hook_list {
 	struct lsm_static_call	*scalls;
 	union security_list_options	hook;
 	const char			*lsm;
+	bool				default_state;
 } __randomize_layout;
 
 /*
@@ -151,7 +154,15 @@ static inline struct xattr *lsm_get_xattr_slot(struct xattr *xattrs,
 #define LSM_HOOK_INIT(NAME, CALLBACK)			\
 	{						\
 		.scalls = static_calls_table.NAME,	\
-		.hook = { .NAME = CALLBACK }		\
+		.hook = { .NAME = CALLBACK },		\
+		.default_state = true			\
+	}
+
+#define LSM_HOOK_INIT_DISABLED(NAME, CALLBACK)		\
+	{						\
+		.scalls = static_calls_table.NAME,	\
+		.hook = { .NAME = CALLBACK },		\
+		.default_state = false			\
 	}
 
 extern char *lsm_names;
kernel/bpf/trampoline.c +27 -2
index e97aeda3a86b..df9699bce372 100644
@@ -13,6 +13,7 @@
 #include <linux/bpf_verifier.h>
 #include <linux/bpf_lsm.h>
 #include <linux/delay.h>
+#include <linux/bpf_lsm.h>
 
 /* dummy _ops. The verifier will operate on target program's ops. */
 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
@@ -514,7 +515,7 @@ static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_tr
 {
 	enum bpf_tramp_prog_type kind;
 	struct bpf_tramp_link *link_exiting;
-	int err = 0;
+	int err = 0, num_lsm_progs = 0;
 	int cnt = 0, i;
 
 	kind = bpf_attach_type_to_tramp(link->link.prog);
@@ -545,8 +546,14 @@ static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_tr
 			continue;
 		/* prog already linked */
 		return -EBUSY;
+
+		if (link_exiting->link.prog->type == BPF_PROG_TYPE_LSM)
+			num_lsm_progs++;
 	}
 
+	if (!num_lsm_progs && link->link.prog->type == BPF_PROG_TYPE_LSM)
+		bpf_lsm_toggle_hook(tr->func.addr, true);
+
 	hlist_add_head(&link->tramp_hlist, &tr->progs_hlist[kind]);
 	tr->progs_cnt[kind]++;
 	err = bpf_trampoline_update(tr, true /* lock_direct_mutex */);
@@ -569,8 +576,10 @@ int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline
 
 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
 {
+	struct bpf_tramp_link *link_exiting;
 	enum bpf_tramp_prog_type kind;
-	int err;
+	bool lsm_link_found = false;
+	int err, num_lsm_progs = 0;
 
 	kind = bpf_attach_type_to_tramp(link->link.prog);
 	if (kind == BPF_TRAMP_REPLACE) {
@@ -580,8 +589,24 @@ static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_
 		tr->extension_prog = NULL;
 		return err;
 	}
+
+	if (link->link.prog->type == BPF_PROG_TYPE_LSM) {
+		hlist_for_each_entry(link_exiting, &tr->progs_hlist[kind],
+				     tramp_hlist) {
+			if (link_exiting->link.prog->type == BPF_PROG_TYPE_LSM)
+				num_lsm_progs++;
+
+			if (link_exiting->link.prog == link->link.prog)
+				lsm_link_found = true;
+		}
+	}
+
 	hlist_del_init(&link->tramp_hlist);
 	tr->progs_cnt[kind]--;
+
+	if (lsm_link_found && num_lsm_progs == 1)
+		bpf_lsm_toggle_hook(tr->func.addr, false);
+
 	return bpf_trampoline_update(tr, true /* lock_direct_mutex */);
 }
 
security/bpf/hooks.c +24 -1
index cfaf1d0e6a5f..1957244196d0 100644
@@ -8,7 +8,7 @@
 
 static struct security_hook_list bpf_lsm_hooks[] __ro_after_init = {
 	#define LSM_HOOK(RET, DEFAULT, NAME, ...) \
-	LSM_HOOK_INIT(NAME, bpf_lsm_##NAME),
+	LSM_HOOK_INIT_DISABLED(NAME, bpf_lsm_##NAME),
 	#include <linux/lsm_hook_defs.h>
 	#undef LSM_HOOK
 	LSM_HOOK_INIT(inode_free_security, bpf_inode_storage_free),
@@ -32,3 +32,26 @@ DEFINE_LSM(bpf) = {
 	.init = bpf_lsm_init,
 	.blobs = &bpf_lsm_blob_sizes
 };
+
+void bpf_lsm_toggle_hook(void *addr, bool value)
+{
+	struct lsm_static_call *scalls;
+	struct security_hook_list *h;
+	int i, j;
+
+	for (i = 0; i < ARRAY_SIZE(bpf_lsm_hooks); i++) {
+		h = &bpf_lsm_hooks[i];
+		scalls = h->scalls;
+		if (h->hook.lsm_callback == addr)
+			continue;
+
+		for (j = 0; j < MAX_LSM_COUNT; j++) {
+			if (scalls[j].hl != h)
+				continue;
+			if (value)
+				static_branch_enable(scalls[j].active);
+			else
+				static_branch_disable(scalls[j].active);
+		}
+	}
+}
security/security.c +2 -1
index c2c2cf6b711f..d1ee72e563cc 100644
@@ -382,7 +382,8 @@ static void __init lsm_static_call_init(struct security_hook_list *hl)
 			__static_call_update(scall->key, scall->trampoline,
 					     hl->hook.lsm_callback);
 			scall->hl = hl;
-			static_branch_enable(scall->active);
+			if (hl->default_state)
+				static_branch_enable(scall->active);
 			return;
 		}
 		scall++;
Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
author maintainer
#10 lore raw

PATCH v4 5/5 security: Add CONFIG_SECURITY_HOOK_LIKELY

In reply to KP Singh

This config influences the nature of the static key that guards the static call for LSM hooks.

When enabled, it indicates that an LSM static call slot is more likely to be initialized. When disabled, it optimizes for the case when static call slot is more likely to be not initialized.

When a major LSM like (SELinux, AppArmor, Smack etc) is active on a system the system would benefit from enabling the config. However there are other cases which would benefit from the config being disabled (e.g. a system with a BPF LSM with no hooks enabled by default, or an LSM like loadpin / yama). Ultimately, there is no one-size fits all solution.

with CONFIG_SECURITY_HOOK_LIKELY enabled, the inactive / uninitialized case is penalized with a direct jmp (still better than an indirect jmp):

function security_file_ioctl:
0xffffffff818f0c80 <+0>: endbr64
0xffffffff818f0c84 <+4>: nopl 0x0(%rax,%rax,1)
0xffffffff818f0c89 <+9>: push %rbp

   0xffffffff818f0c8a <+10>:	push   %r14
   0xffffffff818f0c8c <+12>:	push   %rbx
   0xffffffff818f0c8d <+13>:	mov    %rdx,%rbx
   0xffffffff818f0c90 <+16>:	mov    %esi,%ebp
   0xffffffff818f0c92 <+18>:	mov    %rdi,%r14
   0xffffffff818f0c95 <+21>:	jmp    0xffffffff818f0ca8 <security_file_ioctl+40>

jump to skip the inactive BPF LSM hook.

   0xffffffff818f0c97 <+23>:	mov    %r14,%rdi
   0xffffffff818f0c9a <+26>:	mov    %ebp,%esi
   0xffffffff818f0c9c <+28>:	mov    %rbx,%rdx
   0xffffffff818f0c9f <+31>:	call   0xffffffff8141e3b0 <bpf_lsm_file_ioctl>
   0xffffffff818f0ca4 <+36>:	test   %eax,%eax
   0xffffffff818f0ca6 <+38>:	jne    0xffffffff818f0cbf <security_file_ioctl+63>

0xffffffff818f0ca8 <+40>: endbr64
0xffffffff818f0cac <+44>: jmp 0xffffffff818f0ccd <security_file_ioctl+77>

jump to skip the empty slot.

   0xffffffff818f0cae <+46>:	mov    %r14,%rdi
   0xffffffff818f0cb1 <+49>:	mov    %ebp,%esi
   0xffffffff818f0cb3 <+51>:	mov    %rbx,%rdx
   0xffffffff818f0cb6 <+54>:	nopl   0x0(%rax,%rax,1)

^^^^^^^^^^^^^^^^^^^^^^^ Empty slot

0xffffffff818f0cbb <+59>: test %eax,%eax
0xffffffff818f0cbd <+61>: je 0xffffffff818f0ccd <security_file_ioctl+77>
0xffffffff818f0cbf <+63>: endbr64

   0xffffffff818f0cc3 <+67>:	pop    %rbx
   0xffffffff818f0cc4 <+68>:	pop    %r14
   0xffffffff818f0cc6 <+70>:	pop    %rbp
   0xffffffff818f0cc7 <+71>:	cs jmp 0xffffffff82c00000 <__x86_return_thunk>
   0xffffffff818f0ccd <+77>:	endbr64
   0xffffffff818f0cd1 <+81>:	xor    %eax,%eax
   0xffffffff818f0cd3 <+83>:	jmp    0xffffffff818f0cbf <security_file_ioctl+63>
   0xffffffff818f0cd5 <+85>:	mov    %r14,%rdi
   0xffffffff818f0cd8 <+88>:	mov    %ebp,%esi
   0xffffffff818f0cda <+90>:	mov    %rbx,%rdx
   0xffffffff818f0cdd <+93>:	pop    %rbx
   0xffffffff818f0cde <+94>:	pop    %r14
   0xffffffff818f0ce0 <+96>:	pop    %rbp

0xffffffff818f0ce1 <+97>: ret

When the config is disabled, the case optimizes the scenario above.

security_file_ioctl:
0xffffffff818f0e30 <+0>: endbr64
0xffffffff818f0e34 <+4>: nopl 0x0(%rax,%rax,1)
0xffffffff818f0e39 <+9>: push %rbp

   0xffffffff818f0e3a <+10>:	push   %r14
   0xffffffff818f0e3c <+12>:	push   %rbx
   0xffffffff818f0e3d <+13>:	mov    %rdx,%rbx
   0xffffffff818f0e40 <+16>:	mov    %esi,%ebp
   0xffffffff818f0e42 <+18>:	mov    %rdi,%r14
   0xffffffff818f0e45 <+21>:	xchg   %ax,%ax
   0xffffffff818f0e47 <+23>:	xchg   %ax,%ax

The static keys in their disabled state do not create jumps leading to faster code.

   0xffffffff818f0e49 <+25>:	xor    %eax,%eax
   0xffffffff818f0e4b <+27>:	xchg   %ax,%ax
   0xffffffff818f0e4d <+29>:	pop    %rbx
   0xffffffff818f0e4e <+30>:	pop    %r14
   0xffffffff818f0e50 <+32>:	pop    %rbp
   0xffffffff818f0e51 <+33>:	cs jmp 0xffffffff82c00000 <__x86_return_thunk>
   0xffffffff818f0e57 <+39>:	endbr64
   0xffffffff818f0e5b <+43>:	mov    %r14,%rdi
   0xffffffff818f0e5e <+46>:	mov    %ebp,%esi
   0xffffffff818f0e60 <+48>:	mov    %rbx,%rdx
   0xffffffff818f0e63 <+51>:	call   0xffffffff8141e3b0 <bpf_lsm_file_ioctl>
   0xffffffff818f0e68 <+56>:	test   %eax,%eax
   0xffffffff818f0e6a <+58>:	jne    0xffffffff818f0e4d <security_file_ioctl+29>
   0xffffffff818f0e6c <+60>:	jmp    0xffffffff818f0e47 <security_file_ioctl+23>
   0xffffffff818f0e6e <+62>:	endbr64
   0xffffffff818f0e72 <+66>:	mov    %r14,%rdi
   0xffffffff818f0e75 <+69>:	mov    %ebp,%esi
   0xffffffff818f0e77 <+71>:	mov    %rbx,%rdx
   0xffffffff818f0e7a <+74>:	nopl   0x0(%rax,%rax,1)
   0xffffffff818f0e7f <+79>:	test   %eax,%eax
   0xffffffff818f0e81 <+81>:	jne    0xffffffff818f0e4d <security_file_ioctl+29>
   0xffffffff818f0e83 <+83>:	jmp    0xffffffff818f0e49 <security_file_ioctl+25>
   0xffffffff818f0e85 <+85>:	endbr64
   0xffffffff818f0e89 <+89>:	mov    %r14,%rdi
   0xffffffff818f0e8c <+92>:	mov    %ebp,%esi
   0xffffffff818f0e8e <+94>:	mov    %rbx,%rdx
   0xffffffff818f0e91 <+97>:	pop    %rbx
   0xffffffff818f0e92 <+98>:	pop    %r14

0xffffffff818f0e94 <+100>: pop %rbp
0xffffffff818f0e95 <+101>: ret

---
 security/Kconfig    | 11 +++++++++++
 security/security.c |  6 ++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
security/Kconfig +11 -0
index 52c9af08ad35..317018dcbc67 100644
@@ -32,6 +32,17 @@ config SECURITY
 
 	  If you are unsure how to answer this question, answer N.
 
+config SECURITY_HOOK_LIKELY
+	bool "LSM hooks are likely to be initialized"
+	depends on SECURITY && EXPERT
+	default SECURITY_SELINUX || SECURITY_SMACK || SECURITY_TOMOYO || SECURITY_APPARMOR
+	help
+	  This controls the behaviour of the static keys that guard LSM hooks.
+	  If LSM hooks are likely to be initialized by LSMs, then one gets
+	  better performance by enabling this option. However, if the system is
+	  using an LSM where hooks are much likely to be disabled, one gets
+	  better performance by disabling this config.
+
 config SECURITYFS
 	bool "Enable the securityfs filesystem"
 	help
security/security.c +4 -2
index d1ee72e563cc..b8eac2e8a59d 100644
@@ -825,7 +825,8 @@ static int lsm_superblock_alloc(struct super_block *sb)
  */
 #define __CALL_STATIC_VOID(NUM, HOOK, ...)				     \
 do {									     \
-	if (static_branch_unlikely(&SECURITY_HOOK_ACTIVE_KEY(HOOK, NUM))) {    \
+	if (static_branch_maybe(CONFIG_SECURITY_HOOK_LIKELY,		     \
+				&SECURITY_HOOK_ACTIVE_KEY(HOOK, NUM))) {     \
 		static_call(LSM_STATIC_CALL(HOOK, NUM))(__VA_ARGS__);	     \
 	}								     \
 } while (0);
@@ -837,7 +838,8 @@ do {									     \
 
 #define __CALL_STATIC_INT(NUM, R, HOOK, LABEL, ...)			     \
 do {									     \
-	if (static_branch_unlikely(&SECURITY_HOOK_ACTIVE_KEY(HOOK, NUM))) {  \
+	if (static_branch_maybe(CONFIG_SECURITY_HOOK_LIKELY,		     \
+				&SECURITY_HOOK_ACTIVE_KEY(HOOK, NUM))) {     \
 		R = static_call(LSM_STATIC_CALL(HOOK, NUM))(__VA_ARGS__);    \
 		if (R != 0)						     \
 			goto LABEL;					     \
Signature · 1 line
2.42.0.515.g380fc7ccd1-goog
Reviewed-by on v4 5/5
#11 lore raw

Re: [PATCH v4 5/5] security: Add CONFIG_SECURITY_HOOK_LIKELY

Quoted 13 lines · KP Singh

This config influences the nature of the static key that guards the static call for LSM hooks.

When enabled, it indicates that an LSM static call slot is more likely to be initialized. When disabled, it optimizes for the case when static call slot is more likely to be not initialized.

When a major LSM like (SELinux, AppArmor, Smack etc) is active on a system the system would benefit from enabling the config. However there are other cases which would benefit from the config being disabled (e.g. a system with a BPF LSM with no hooks enabled by default, or an LSM like loadpin / yama). Ultimately, there is no one-size fits all solution.

Quoted 3 lines

Looks great!

Signature · 1 line
Kees Cook
#12 lore raw
In reply to KP Singh
Quoted 21 lines · KP Singh

# Performance improvement

With this patch-set some syscalls with lots of LSM hooks in their path benefitted at an average of ~3% and I/O and Pipe based system calls benefitting the most.

Here are the results of the relevant Unixbench system benchmarks with BPF LSM and SELinux enabled with default policies enabled with and without these patches.

Benchmark Delta(%): (+ is better)
===============================================================================

Execl Throughput                                             +1.9356
File Write 1024 bufsize 2000 maxblocks                       +6.5953
Pipe Throughput                                              +9.5499
Pipe-based Context Switching                                 +3.0209
Process Creation                                             +2.3246
Shell Scripts (1 concurrent)                                 +1.4975
System Call Overhead                                         +2.7815
System Benchmarks Index Score (Partial Only):                +3.4859
Quoted 2 lines

In the best case, some syscalls like eventfd_create benefitted to about ~10%. The full analysis can be viewed at https://kpsingh.ch/lsm-perf

Ship it! ;)

Thanks for continuing to work on this; this is a classic case for static_call.

-Kees

Signature · 1 line
Kees Cook
#13 lore raw
In reply to KP Singh
Quoted 5 lines · KP Singh

Since we know the address of the enabled LSM callbacks at compile time and only the order is determined at boot time, the LSM framework can allocate static calls for each of the possible LSM callbacks and these calls can be updated once the order is determined at boot.

Any plans to further depessimize the state by not calling into these modules if not configured?

For example Debian has a milipede:
CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf"

Everything is enabled (but not configured).

In particular tomoyo is quite nasty, rolling with big memsets only to find it is not even enabled.

author maintainer
#14 lore raw
Quoted 8 lines · Mateusz Guzik
Quoted 5 lines · KP Singh

Since we know the address of the enabled LSM callbacks at compile time and only the order is determined at boot time, the LSM framework can allocate static calls for each of the possible LSM callbacks and these calls can be updated once the order is determined at boot.

Quoted 7 lines

Any plans to further depessimize the state by not calling into these modules if not configured?

For example Debian has a milipede:
CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf"

Everything is enabled (but not configured).

If it's not configured, we won't generate static call slots and even if they are in the CONFIG_LSM (or lsm=) they are simply ignored.

- KP

Quoted 3 lines

In particular tomoyo is quite nasty, rolling with big memsets only to find it is not even enabled.

#15 lore raw
Quoted 15 lines · KP Singh
Quoted 14 lines · Mateusz Guzik
Quoted 8 lines · KP Singh

Since we know the address of the enabled LSM callbacks at compile time and only
the order is determined at boot time, the LSM framework can allocate static
calls for each of the possible LSM callbacks and these calls can be updated once
the order is determined at boot.

Any plans to further depessimize the state by not calling into these modules if not configured?

Quoted 8 lines
Quoted 4 lines

For example Debian has a milipede:
CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf"

Everything is enabled (but not configured).

If it's not configured, we won't generate static call slots and even if they are in the CONFIG_LSM (or lsm=) they are simply ignored.

Maybe there is a terminology mismatch here, so let me be more specific with tomoyo as an example.

In debian you have:
CONFIG_SECURITY_TOMOYO=y

CONFIG_LSM, as per above, includes it on the list.

At the same time debian does not ship any tooling to configure tomoyo -- it is compiled into the kernel but not configured to enforce anything.

On stock kernel this results in tons of calls to tomoyo_init_request_info, which are quite expensive due to an avoidable memset thrown in, and which always return tomoyo_init_request_info.

Does not look like your patch whacks this problem.

Signature · 1 line
Mateusz Guzik <mjguzik gmail.com>
#16 lore raw
Quoted 33 lines · Mateusz Guzik
Quoted 15 lines · KP Singh
Quoted 14 lines · Mateusz Guzik
Quoted 8 lines · KP Singh

Since we know the address of the enabled LSM callbacks at compile time and only
the order is determined at boot time, the LSM framework can allocate static
calls for each of the possible LSM callbacks and these calls can be updated once
the order is determined at boot.

Any plans to further depessimize the state by not calling into these modules if not configured?

Quoted 8 lines
Quoted 4 lines

For example Debian has a milipede:
CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf"

Everything is enabled (but not configured).

If it's not configured, we won't generate static call slots and even if they are in the CONFIG_LSM (or lsm=) they are simply ignored.

Maybe there is a terminology mismatch here, so let me be more specific with tomoyo as an example.

In debian you have:
CONFIG_SECURITY_TOMOYO=y

CONFIG_LSM, as per above, includes it on the list.

Quoted 9 lines

At the same time debian does not ship any tooling to configure tomoyo -- it is compiled into the kernel but not configured to enforce anything.

On stock kernel this results in tons of calls to tomoyo_init_request_info, which are quite expensive due to an avoidable memset thrown in, and which always return tomoyo_init_request_info.

Erm, which always return TOMOYO_CONFIG_DISABLED.

Quoted 2 lines

Does not look like your patch whacks this problem.

So I am asking if there are plans to make these modules get out of the way if they have nothing to do, like tomoyo in the example above.

Of course preferably distros would not make these weird configs, but I suspect this ship has sailed.

Signature · 1 line
Mateusz Guzik <mjguzik gmail.com>
#17 lore raw
Quoted 46 lines · Mateusz Guzik
Quoted 33 lines · Mateusz Guzik
Quoted 15 lines · KP Singh
Quoted 14 lines · Mateusz Guzik
Quoted 8 lines · KP Singh

Since we know the address of the enabled LSM callbacks at compile time and only
the order is determined at boot time, the LSM framework can allocate static
calls for each of the possible LSM callbacks and these calls can be updated once
the order is determined at boot.

Any plans to further depessimize the state by not calling into these modules if not configured?

Quoted 8 lines
Quoted 4 lines

For example Debian has a milipede:
CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,integrity,apparmor,selinux,smack,tomoyo,bpf"

Everything is enabled (but not configured).

If it's not configured, we won't generate static call slots and even if they are in the CONFIG_LSM (or lsm=) they are simply ignored.

Maybe there is a terminology mismatch here, so let me be more specific with tomoyo as an example.

In debian you have:
CONFIG_SECURITY_TOMOYO=y

CONFIG_LSM, as per above, includes it on the list.

Quoted 9 lines

At the same time debian does not ship any tooling to configure tomoyo -- it is compiled into the kernel but not configured to enforce anything.

On stock kernel this results in tons of calls to tomoyo_init_request_info, which are quite expensive due to an avoidable memset thrown in, and which always return tomoyo_init_request_info.

Erm, which always return TOMOYO_CONFIG_DISABLED.

Quoted 8 lines
Quoted 2 lines

Does not look like your patch whacks this problem.

So I am asking if there are plans to make these modules get out of the way if they have nothing to do, like tomoyo in the example above.

Of course preferably distros would not make these weird configs, but I suspect this ship has sailed.

This is an artifact of the existing stacking behavior (and solving it, if needed, can be done in parallel to this series). Specifically it seems Tomoyo is in the "lsm=" list when it shouldn't be.

That said, I've long advocated[1] for a way to explicitly disable LSMs without affecting operational ordering. I think it would be very nice to be able to boot with something like:

lsm=!yama

to disable Yama. Or for your case, "lsm=!tomoyo". Right now, you have to figure out what the lsm list is, and then create a new one with the LSM you want disabled removed from the list. i.e. with v6.2 and later check the boot log, and you'll see:

LSM: initializing lsm=lockdown,capability,landlock,yama,integrity,apparmor

If you wanted to boot with Yama removed, you'd then pass:

lsm=lockdown,capability,landlock,integrity,apparmor

As a boot param. But I think this is fragile since now any new LSMs will be by-default disabled once a sysadmin overrides the "lsm" list. Note that booting with "lsm.debug=1" will show even more details. See commit 86ef3c735ec8 ("LSM: Better reporting of actual LSMs at boot").

So, if a distro has no support for an LSM but they want it _available_ in the kernel, they should leave it built in, but remove it from the "lsm=" list. That's a reasonable bug to file against a distro...

-Kees

[1] https://lore.kernel.org/linux-security-module/202210171111.21E3983165@keescook/

Signature · 1 line
Kees Cook
#18 lore raw
Quoted 17 lines · Kees Cook

That said, I've long advocated[1] for a way to explicitly disable LSMs without affecting operational ordering. I think it would be very nice to be able to boot with something like:

lsm=!yama

to disable Yama. Or for your case, "lsm=!tomoyo". Right now, you have to figure out what the lsm list is, and then create a new one with the LSM you want disabled removed from the list. i.e. with v6.2 and later check the boot log, and you'll see:

LSM: initializing lsm=lockdown,capability,landlock,yama,integrity,apparmor

If you wanted to boot with Yama removed, you'd then pass:

lsm=lockdown,capability,landlock,integrity,apparmor

Quoted 9 lines

As a boot param. But I think this is fragile since now any new LSMs will be by-default disabled once a sysadmin overrides the "lsm" list. Note that booting with "lsm.debug=1" will show even more details. See commit 86ef3c735ec8 ("LSM: Better reporting of actual LSMs at boot").

So, if a distro has no support for an LSM but they want it _available_ in the kernel, they should leave it built in, but remove it from the "lsm=" list. That's a reasonable bug to file against a distro...

Maybe I once more expressed myself poorly, I meant to say stock Debian does not ship any tooling for tomoyo, but the kernel has support compiled in.

Ultimately, after stacking got implemented, it was inevitable diestros like Debian will enable whatever modules and expect them to not be a problem if not configured by userspace.

I don't think any form of messing with CONFIG_LSM is a viable option, even if you make it a boot param.

What should happen instead is that modules which are not given any config don't get in the way.

Signature · 1 line
Mateusz Guzik <mjguzik gmail.com>
#19 lore raw
Quoted 23 lines · Mateusz Guzik
Quoted 22 lines · Kees Cook

That said, I've long advocated[1] for a way to explicitly disable LSMs without affecting operational ordering. I think it would be very nice to be able to boot with something like:

lsm=!yama

to disable Yama. Or for your case, "lsm=!tomoyo". Right now, you have to figure out what the lsm list is, and then create a new one with the LSM you want disabled removed from the list. i.e. with v6.2 and later check the boot log, and you'll see:

LSM: initializing lsm=lockdown,capability,landlock,yama,integrity,apparmor

If you wanted to boot with Yama removed, you'd then pass:

lsm=lockdown,capability,landlock,integrity,apparmor

As a boot param. But I think this is fragile since now any new LSMs will be by-default disabled once a sysadmin overrides the "lsm" list. Note that booting with "lsm.debug=1" will show even more details. See commit 86ef3c735ec8 ("LSM: Better reporting of actual LSMs at boot").

Quoted 8 lines
Quoted 4 lines

So, if a distro has no support for an LSM but they want it _available_ in the kernel, they should leave it built in, but remove it from the "lsm=" list. That's a reasonable bug to file against a distro...

Maybe I once more expressed myself poorly, I meant to say stock Debian does not ship any tooling for tomoyo, but the kernel has support compiled in.

If there is no tooling Debian should either not build the support into the kernel or should leave it out of the CONFIG_LSM list.

Quoted 9 lines

Ultimately, after stacking got implemented, it was inevitable diestros like Debian will enable whatever modules and expect them to not be a problem if not configured by userspace.

I don't think any form of messing with CONFIG_LSM is a viable option, even if you make it a boot param.

What should happen instead is that modules which are not given any config don't get in the way.

Right -- this is an open problem, and I think we can solve it using the static_call system (much like how the BPF LSM is doing it).

-Kees

Signature · 1 line
Kees Cook