History log of /linux-master/security/apparmor/lsm.c
Revision Date Author Comments
# a5a858f6 14-Mar-2024 Casey Schaufler <casey@schaufler-ca.com>

lsm: use 32-bit compatible data types in LSM syscalls

Change the size parameters in lsm_list_modules(), lsm_set_self_attr()
and lsm_get_self_attr() from size_t to u32. This avoids the need to
have different interfaces for 32 and 64 bit systems.

Cc: stable@vger.kernel.org
Fixes: a04a1198088a ("LSM: syscalls for current process attributes")
Fixes: ad4aff9ec25f ("LSM: Create lsm_list_modules system call")
Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reported-and-reviewed-by: Dmitry V. Levin <ldv@strace.io>
[PM: subject and metadata tweaks, syscall.h fixes]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 6d2fb472 23-Feb-2024 Mickaël Salaün <mic@digikod.net>

apparmor: fix lsm_get_self_attr()

In apparmor_getselfattr() when an invalid AppArmor attribute is
requested, or a value hasn't been explicitly set for the requested
attribute, the label passed to aa_put_label() is not properly
initialized which can cause problems when the pointer value is non-NULL
and AppArmor attempts to drop a reference on the bogus label object.

Cc: Casey Schaufler <casey@schaufler-ca.com>
Cc: John Johansen <john.johansen@canonical.com>
Fixes: 223981db9baf ("AppArmor: Add selfattr hooks")
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Reviewed-by: Paul Moore <paul@paul-moore.com>
[PM: description changes as discussed with MS]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 4759ff71 24-Jan-2024 Kees Cook <keescook@chromium.org>

exec: Check __FMODE_EXEC instead of in_execve for LSMs

After commit 978ffcbf00d8 ("execve: open the executable file before
doing anything else"), current->in_execve was no longer in sync with the
open(). This broke AppArmor and TOMOYO which depend on this flag to
distinguish "open" operations from being "exec" operations.

Instead of moving around in_execve, switch to using __FMODE_EXEC, which
is where the "is this an exec?" intent is stored. Note that TOMOYO still
uses in_execve around cred handling.

Reported-by: Kevin Locke <kevin@kevinlocke.name>
Closes: https://lore.kernel.org/all/ZbE4qn9_h14OqADK@kevinlocke.name
Suggested-by: Linus Torvalds <torvalds@linux-foundation.org>
Fixes: 978ffcbf00d8 ("execve: open the executable file before doing anything else")
Cc: Josh Triplett <josh@joshtriplett.org>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: James Morris <jmorris@namei.org>
Cc: Serge E. Hallyn <serge@hallyn.com>
Cc: Kentaro Takeda <takedakn@nttdata.co.jp>
Cc: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Cc: Alexander Viro <viro@zeniv.linux.org.uk>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Jan Kara <jack@suse.cz>
Cc: Eric Biederman <ebiederm@xmission.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
Cc: <linux-fsdevel@vger.kernel.org>
Cc: <linux-mm@kvack.org>
Cc: <apparmor@lists.ubuntu.com>
Cc: <linux-security-module@vger.kernel.org>
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 2cb54a19 29-Dec-2023 John Johansen <john.johansen@canonical.com>

apparmor: Fix ref count leak in task_kill

apparmor_task_kill was not putting the task_cred reference tc, or the
cred_label reference tc when dealing with a passed in cred, fix this
by using a single fn exit.

Fixes: 90c436a64a6e ("apparmor: pass cred through to audit info.")
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 1cba2750 26-Nov-2023 John Johansen <john.johansen@canonical.com>

apparmor: cleanup network hook comments

Drop useless partial kernel doc style comments. Finish/update kerneldoc
comment where there is useful information

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 735ad5d1 19-Nov-2023 John Johansen <john.johansen@canonical.com>

apparmor: declare nulldfa as static

With the conversion to a refcounted pdb the nulldfa is now only used
in security/apparmor/lsm.c so declar it as static.

Reported-by: kernel test robot <lkp@intel.com>
Closes: https://lore.kernel.org/oe-kbuild-all/202311092038.lqfYnvmf-lkp@intel.com/
Signed-off-by: John Johansen <john.johansen@canonical.com>


# b1a867ee 09-Nov-2023 Paul Moore <paul@paul-moore.com>

lsm: mark the lsm_id variables are marked as static

As the kernel test robot helpfully reminded us, all of the lsm_id
instances defined inside the various LSMs should be marked as static.
The one exception is Landlock which uses its lsm_id variable across
multiple source files with an extern declaration in a header file.

Reported-by: kernel test robot <lkp@intel.com>
Suggested-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# d7cf3412 24-Oct-2023 Paul Moore <paul@paul-moore.com>

lsm: consolidate buffer size handling into lsm_fill_user_ctx()

While we have a lsm_fill_user_ctx() helper function designed to make
life easier for LSMs which return lsm_ctx structs to userspace, we
didn't include all of the buffer length safety checks and buffer
padding adjustments in the helper. This led to code duplication
across the different LSMs and the possibility for mistakes across the
different LSM subsystems. In order to reduce code duplication and
decrease the chances of silly mistakes, we're consolidating all of
this code into the lsm_fill_user_ctx() helper.

The buffer padding is also modified from a fixed 8-byte alignment to
an alignment that matches the word length of the machine
(BITS_PER_LONG / 8).

Signed-off-by: Paul Moore <paul@paul-moore.com>


# 223981db 12-Sep-2023 Casey Schaufler <casey@schaufler-ca.com>

AppArmor: Add selfattr hooks

Add hooks for setselfattr and getselfattr. These hooks are not very
different from their setprocattr and getprocattr equivalents, and
much of the code is shared.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
[PM: forward ported beyond v6.6 due merge window changes]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# f3b8788c 12-Sep-2023 Casey Schaufler <casey@schaufler-ca.com>

LSM: Identify modules by more than name

Create a struct lsm_id to contain identifying information about Linux
Security Modules (LSMs). At inception this contains the name of the
module and an identifier associated with the security module. Change
the security_add_hooks() interface to use this structure. Change the
individual modules to maintain their own struct lsm_id and pass it to
security_add_hooks().

The values are for LSM identifiers are defined in a new UAPI
header file linux/lsm.h. Each existing LSM has been updated to
include it's LSMID in the lsm_id.

The LSM ID values are sequential, with the oldest module
LSM_ID_CAPABILITY being the lowest value and the existing modules
numbered in the order they were included in the main line kernel.
This is an arbitrary convention for assigning the values, but
none better presents itself. The value 0 is defined as being invalid.
The values 1-99 are reserved for any special case uses which may
arise in the future. This may include attributes of the LSM
infrastructure itself, possibly related to namespacing or network
attribute management. A special range is identified for such attributes
to help reduce confusion for developers unfamiliar with LSMs.

LSM attribute values are defined for the attributes presented by
modules that are available today. As with the LSM IDs, The value 0
is defined as being invalid. The values 1-99 are reserved for any
special case uses which may arise in the future.

Cc: linux-security-module <linux-security-module@vger.kernel.org>
Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Serge Hallyn <serge@hallyn.com>
Reviewed-by: Mickael Salaun <mic@digikod.net>
Reviewed-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: Kees Cook <keescook@chromium.org>
Nacked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
[PM: forward ported beyond v6.6 due merge window changes]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 7060d3cc 20-Oct-2023 Arnd Bergmann <arnd@arndb.de>

apparmor: mark new functions static

Two new functions were introduced as global functions when they are
only called from inside the file that defines them and should have
been static:

security/apparmor/lsm.c:658:5: error: no previous prototype for 'apparmor_uring_override_creds' [-Werror=missing-prototypes]
security/apparmor/lsm.c:682:5: error: no previous prototype for 'apparmor_uring_sqpoll' [-Werror=missing-prototypes]

Fixes: c4371d90633b7 ("apparmor: add io_uring mediation")
Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 157a3537 10-Sep-2023 John Johansen <john.johansen@canonical.com>

apparmor: Fix regression in mount mediation

commit 2db154b3ea8e ("vfs: syscall: Add move_mount(2) to move mounts around")

introduced a new move_mount(2) system call and a corresponding new LSM
security_move_mount hook but did not implement this hook for any
existing LSM. This creates a regression for AppArmor mediation of
mount. This patch provides a base mapping of the move_mount syscall to
the existing mount mediation. In the future we may introduce
additional mediations around the new mount calls.

Fixes: 2db154b3ea8e ("vfs: syscall: Add move_mount(2) to move mounts around")
CC: stable@vger.kernel.org
Reported-by: Andreas Steinmetz <anstein99@googlemail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# ea9bae12 25-Oct-2022 John Johansen <john.johansen@canonical.com>

apparmor: cache buffers on percpu list if there is lock contention

commit df323337e507 ("apparmor: Use a memory pool instead per-CPU caches")

changed buffer allocation to use a memory pool, however on a heavily
loaded machine there can be lock contention on the global buffers
lock. Add a percpu list to cache buffers on when lock contention is
encountered.

When allocating buffers attempt to use cached buffers first,
before taking the global buffers lock. When freeing buffers
try to put them back to the global list but if contention is
encountered, put the buffer on the percpu list.

The length of time a buffer is held on the percpu list is dynamically
adjusted based on lock contention. The amount of hold time is
increased and decreased linearly.

v5:
- simplify base patch by removing: improvements can be added later
- MAX_LOCAL and must lock
- contention scaling.
v4:
- fix percpu ->count buffer count which had been spliced across a
debug patch.
- introduce define for MAX_LOCAL_COUNT
- rework count check and locking around it.
- update commit message to reference commit that introduced the
memory.
v3:
- limit number of buffers that can be pushed onto the percpu
list. This avoids a problem on some kernels where one percpu
list can inherit buffers from another cpu after a reschedule,
causing more kernel memory to used than is necessary. Under
normal conditions this should eventually return to normal
but under pathelogical conditions the extra memory consumption
may have been unbouanded
v2:
- dynamically adjust buffer hold time on percpu list based on
lock contention.
v1:
- cache buffers on percpu list on lock contention

Reported-by: Sergey Senozhatsky <senozhatsky@chromium.org>
Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# c4371d90 20-Mar-2023 Georgia Garcia <georgia.garcia@canonical.com>

apparmor: add io_uring mediation

For now, the io_uring mediation is limited to sqpoll and
override_creds.

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# fa9b63ad 09-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: add user namespace creation mediation

Unprivileged user namespace creation is often used as a first step
in privilege escalation attacks. Instead of disabling it at the
sysrq level, which blocks its legitimate use as for setting up a sandbox,
allow control on a per domain basis.

This allows an admin to quickly lock down a system while also still
allowing legitimate use.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 2d9da9b1 09-Aug-2023 John Johansen <john.johansen@canonical.com>

apparmor: allow restricting unprivileged change_profile

unprivileged unconfined can use change_profile to alter the confinement
set by the mac admin.

Allow restricting unprivileged unconfined by still allowing change_profile
but stacking the change against unconfined. This allows unconfined to
still apply system policy but allows the task to enter the new confinement.

If unprivileged unconfined is required a sysctl is provided to switch
to the previous behavior.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 98b824ff 28-Apr-2023 John Johansen <john.johansen@canonical.com>

apparmor: refcount the pdb

With the move to permission tables the dfa is no longer a stand
alone entity when used, needing a minimum of a permission table.
However it still could be shared among different pdbs each using
a different permission table.

Instead of duping the permission table when sharing a pdb, add a
refcount to the pdb so it can be easily shared.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 90c436a6 19-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: pass cred through to audit info.

The cred is needed to properly audit some messages, and will be needed
in the future for uid conditional mediation. So pass it through to
where the apparmor_audit_data struct gets defined.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# d20f5a1a 19-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: rename audit_data->label to audit_data->subj_label

rename audit_data's label field to subj_label to better reflect its
use. Also at the same time drop unneeded assignments to ->subj_label
as the later call to aa_check_perms will do the assignment if needed.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# bd7bd201 14-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: combine common_audit_data and apparmor_audit_data

Everywhere where common_audit_data is used apparmor audit_data is also
used. We can simplify the code and drop the use of the aad macro
everywhere by combining the two structures.

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 79ddd4a7 06-Mar-2023 John Johansen <john.johansen@canonical.com>

apparmor: rename SK_CTX() to aa_sock and make it an inline fn

In preparation for LSM stacking rework the macro to an inline fn

Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 2516fde1 31-Aug-2023 Vinicius Costa Gomes <vinicius.gomes@intel.com>

apparmor: Optimize retrieving current task secid

When running will-it-scale[1] open2_process testcase, in a system with a
large number of cores, a bottleneck in retrieving the current task
secid was detected:

27.73% ima_file_check;do_open (inlined);path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_x64 (inlined);do_syscall_64;entry_SYSCALL_64_after_hwframe (inlined);__libc_open64 (inlined)
27.72% 0.01% [kernel.vmlinux] [k] security_current_getsecid_subj - -
27.71% security_current_getsecid_subj;ima_file_check;do_open (inlined);path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_x64 (inlined);do_syscall_64;entry_SYSCALL_64_after_hwframe (inlined);__libc_open64 (inlined)
27.71% 27.68% [kernel.vmlinux] [k] apparmor_current_getsecid_subj - -
19.94% __refcount_add (inlined);__refcount_inc (inlined);refcount_inc (inlined);kref_get (inlined);aa_get_label (inlined);aa_get_label (inlined);aa_get_current_label (inlined);apparmor_current_getsecid_subj;security_current_getsecid_subj;ima_file_check;do_open (inlined);path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_x64 (inlined);do_syscall_64;entry_SYSCALL_64_after_hwframe (inlined);__libc_open64 (inlined)
7.72% __refcount_sub_and_test (inlined);__refcount_dec_and_test (inlined);refcount_dec_and_test (inlined);kref_put (inlined);aa_put_label (inlined);aa_put_label (inlined);apparmor_current_getsecid_subj;security_current_getsecid_subj;ima_file_check;do_open (inlined);path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_x64 (inlined);do_syscall_64;entry_SYSCALL_64_after_hwframe (inlined);__libc_open64 (inlined)

A large amount of time was spent in the refcount.

The most common case is that the current task label is available, and
no need to take references for that one. That is exactly what the
critical section helpers do, make use of them.

New perf output:

39.12% vfs_open;path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_64;entry_SYSCALL_64_after_hwframe;__libc_open64 (inlined)
39.07% 0.13% [kernel.vmlinux] [k] do_dentry_open - -
39.05% do_dentry_open;vfs_open;path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_64;entry_SYSCALL_64_after_hwframe;__libc_open64 (inlined)
38.71% 0.01% [kernel.vmlinux] [k] security_file_open - -
38.70% security_file_open;do_dentry_open;vfs_open;path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_64;entry_SYSCALL_64_after_hwframe;__libc_open64 (inlined)
38.65% 38.60% [kernel.vmlinux] [k] apparmor_file_open - -
38.65% apparmor_file_open;security_file_open;do_dentry_open;vfs_open;path_openat;do_filp_open;do_sys_openat2;__x64_sys_openat;do_syscall_64;entry_SYSCALL_64_after_hwframe;__libc_open64 (inlined)

The result is a throughput improvement of around 20% across the board
on the open2 testcase. On more realistic workloads the impact should
be much less.

[1] https://github.com/antonblanchard/will-it-scale

Signed-off-by: Vinicius Costa Gomes <vinicius.gomes@intel.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# a721f7b8 23-Aug-2023 Khadija Kamran <kamrankhadijadj@gmail.com>

lsm: constify 'bprm' parameter in security_bprm_committed_creds()

Three LSMs register the implementations for the 'bprm_committed_creds()'
hook: AppArmor, SELinux and tomoyo. Looking at the function
implementations we may observe that the 'bprm' parameter is not changing.

Mark the 'bprm' parameter of LSM hook security_bprm_committed_creds() as
'const' since it will not be changing in the LSM hook.

Signed-off-by: Khadija Kamran <kamrankhadijadj@gmail.com>
[PM: minor merge fuzzing due to other constification patches]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 64fc9526 22-Aug-2023 Khadija Kamran <kamrankhadijadj@gmail.com>

lsm: constify 'bprm' parameter in security_bprm_committing_creds()

The 'bprm_committing_creds' hook has implementations registered in
SELinux and Apparmor. Looking at the function implementations we observe
that the 'bprm' parameter is not changing.

Mark the 'bprm' parameter of LSM hook security_bprm_committing_creds()
as 'const' since it will not be changing in the LSM hook.

Signed-off-by: Khadija Kamran <kamrankhadijadj@gmail.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 6672efbb 07-Aug-2023 Khadija Kamran <kamrankhadijadj@gmail.com>

lsm: constify the 'target' parameter in security_capget()

Three LSMs register the implementations for the "capget" hook: AppArmor,
SELinux, and the normal capability code. Looking at the function
implementations we may observe that the first parameter "target" is not
changing.

Mark the first argument "target" of LSM hook security_capget() as
"const" since it will not be changing in the LSM hook.

cap_capget() LSM hook declaration exceeds the 80 characters per line
limit. Split the function declaration to multiple lines to decrease the
line length.

Signed-off-by: Khadija Kamran <kamrankhadijadj@gmail.com>
Acked-by: John Johansen <john.johansen@canonical.com>
[PM: align the cap_capget() declaration, spelling fixes]
Signed-off-by: Paul Moore <paul@paul-moore.com>


# ba808cb5 11-May-2023 Kees Cook <keescook@chromium.org>

apparmor: aa_buffer: Convert 1-element array to flexible array

In the ongoing effort to convert all fake flexible arrays to proper
flexible arrays, replace aa_buffer's 1-element "buffer" member with a
flexible array.

Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 96200952 02-Mar-2023 Luis Chamberlain <mcgrof@kernel.org>

apparmor: simplify sysctls with register_sysctl_init()

Using register_sysctl_paths() is really only needed if you have
subdirectories with entries. We can use the simple register_sysctl()
instead.

Acked-by: John Johansen <john.johansen@canonical.com>
Reviewed-by: Georgia Garcia <georgia.garcia@canonical.com>
Signed-off-by: Luis Chamberlain <mcgrof@kernel.org>


# f22f9aaf 16-Mar-2023 Paul Moore <paul@paul-moore.com>

selinux: remove the runtime disable functionality

After working with the larger SELinux-based distros for several
years, we're finally at a place where we can disable the SELinux
runtime disable functionality. The existing kernel deprecation
notice explains the functionality and why we want to remove it:

The selinuxfs "disable" node allows SELinux to be disabled at
runtime prior to a policy being loaded into the kernel. If
disabled via this mechanism, SELinux will remain disabled until
the system is rebooted.

The preferred method of disabling SELinux is via the "selinux=0"
boot parameter, but the selinuxfs "disable" node was created to
make it easier for systems with primitive bootloaders that did not
allow for easy modification of the kernel command line.
Unfortunately, allowing for SELinux to be disabled at runtime makes
it difficult to secure the kernel's LSM hooks using the
"__ro_after_init" feature.

It is that last sentence, mentioning the '__ro_after_init' hardening,
which is the real motivation for this change, and if you look at the
diffstat you'll see that the impact of this patch reaches across all
the different LSMs, helping prevent tampering at the LSM hook level.

From a SELinux perspective, it is important to note that if you
continue to disable SELinux via "/etc/selinux/config" it may appear
that SELinux is disabled, but it is simply in an uninitialized state.
If you load a policy with `load_policy -i`, you will see SELinux
come alive just as if you had loaded the policy during early-boot.

It is also worth noting that the "/sys/fs/selinux/disable" file is
always writable now, regardless of the Kconfig settings, but writing
to the file has no effect on the system, other than to display an
error on the console if a non-zero/true value is written.

Finally, in the several years where we have been working on
deprecating this functionality, there has only been one instance of
someone mentioning any user visible breakage. In this particular
case it was an individual's kernel test system, and the workaround
documented in the deprecation notice ("selinux=0" on the kernel
command line) resolved the issue without problem.

Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# e67fe633 12-Jan-2023 Christian Brauner <brauner@kernel.org>

fs: port i_{g,u}id_into_vfs{g,u}id() to mnt_idmap

Convert to struct mnt_idmap.
Remove legacy file_mnt_user_ns() and mnt_user_ns().

Last cycle we merged the necessary infrastructure in
256c8aed2b42 ("fs: introduce dedicated idmap type for mounts").
This is just the conversion to struct mnt_idmap.

Currently we still pass around the plain namespace that was attached to a
mount. This is in general pretty convenient but it makes it easy to
conflate namespaces that are relevant on the filesystem with namespaces
that are relevent on the mount level. Especially for non-vfs developers
without detailed knowledge in this area this can be a potential source for
bugs.

Once the conversion to struct mnt_idmap is done all helpers down to the
really low-level helpers will take a struct mnt_idmap argument instead of
two namespace arguments. This way it becomes impossible to conflate the two
eliminating the possibility of any bugs. All of the vfs and all filesystems
only operate on struct mnt_idmap.

Acked-by: Dave Chinner <dchinner@redhat.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Christian Brauner (Microsoft) <brauner@kernel.org>


# 37923d43 20-Oct-2022 Xiu Jianfeng <xiujianfeng@huawei.com>

apparmor: Use pointer to struct aa_label for lbs_cred

According to the implementations of cred_label() and set_cred_label(),
we should use pointer to struct aa_label for lbs_cred instead of struct
aa_task_ctx, this patch fixes it.

Fixes: bbd3662a8348 ("Infrastructure management of the cred security blob")
Signed-off-by: Xiu Jianfeng <xiujianfeng@huawei.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 391f1211 08-Oct-2022 Jiapeng Chong <jiapeng.chong@linux.alibaba.com>

LSM: Fix kernel-doc

security/apparmor/lsm.c:753: warning: expecting prototype for apparmor_bprm_committed_cred(). Prototype was for apparmor_bprm_committed_creds() instead.

Link: https://bugzilla.openanolis.cn/show_bug.cgi?id=2338
Reported-by: Abaci Robot <abaci@linux.alibaba.com>
Signed-off-by: Jiapeng Chong <jiapeng.chong@linux.alibaba.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 70f24a9f 29-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: Fix undefined references to zstd_ symbols

Unfortunately the switch to using zstd compression did not properly
ifdef all the code that uses zstd_ symbols. So that if exporting of
binary policy is disabled in the config the compile will fail with the
following errors

security/apparmor/lsm.c:1545: undefined reference to `zstd_min_clevel'
aarch64-linux-ld: security/apparmor/lsm.c:1545: undefined reference to `zstd_max_clevel'

Reported-by: kernel test robot <lkp@intel.com>
Fixes: 52ccc20c652b ("apparmor: use zstd compression for profile data")
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Jon Tourville <jon.tourville@canonical.com>


# 1ad22fcc 05-Sep-2022 John Johansen <john.johansen@canonical.com>

apparmor: rework profile->rules to be a list

Convert profile->rules to a list as the next step towards supporting
multiple rulesets in a profile. For this step only support a single
list entry item. The logic for iterating the list will come as a
separate step.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 217af7e2 29-Jul-2022 John Johansen <john.johansen@canonical.com>

apparmor: refactor profile rules and attachments

In preparation for moving from a single set of rules and a single
attachment to multiple rulesets and attachments separate from the
profile refactor attachment information and ruleset info into their
own structures.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 8c4b785a 19-Apr-2022 John Johansen <john.johansen@canonical.com>

apparmor: add mediation class information to auditing

Audit messages currently don't contain the mediation class which can
make them less clear than they should be in some circumstances. With
newer mediation classes coming this potential confusion will become
worse.

Fix this by adding the mediatin class to the messages.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# f4d6b94b 11-Jul-2022 Jon Tourville <jon.tourville@canonical.com>

apparmor: use zstd compression for profile data

Change the algorithm used by apparmor to compress profile data from
zlib to zstd, using the new zstd API introduced in 5.16.

Zstd provides a larger range of compression levels than zlib and
significantly better performance at the default level (for a relatively
small increase in compressed size).

The apparmor module parameter raw_data_compression_level is now clamped
to the minimum and maximum compression levels reported by the zstd
library. A compression level of 0 retains the previous behavior of
disabling policy compression instead of using zstd's behavior, which is
to use the default compression level.

Signed-off-by: Jon Tourville <jon.tourville@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# b10b9c34 09-Oct-2022 Paul Moore <paul@paul-moore.com>

lsm: make security_socket_getpeersec_stream() sockptr_t safe

Commit 4ff09db1b79b ("bpf: net: Change sk_getsockopt() to take the
sockptr_t argument") made it possible to call sk_getsockopt()
with both user and kernel address space buffers through the use of
the sockptr_t type. Unfortunately at the time of conversion the
security_socket_getpeersec_stream() LSM hook was written to only
accept userspace buffers, and in a desire to avoid having to change
the LSM hook the commit author simply passed the sockptr_t's
userspace buffer pointer. Since the only sk_getsockopt() callers
at the time of conversion which used kernel sockptr_t buffers did
not allow SO_PEERSEC, and hence the
security_socket_getpeersec_stream() hook, this was acceptable but
also very fragile as future changes presented the possibility of
silently passing kernel space pointers to the LSM hook.

There are several ways to protect against this, including careful
code review of future commits, but since relying on code review to
catch bugs is a recipe for disaster and the upstream eBPF maintainer
is "strongly against defensive programming", this patch updates the
LSM hook, and all of the implementations to support sockptr_t and
safely handle both user and kernel space buffers.

Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 5e26a01e 26-Jun-2022 Christian Brauner <brauner@kernel.org>

apparmor: use type safe idmapping helpers

We already ported most parts and filesystems over for v6.0 to the new
vfs{g,u}id_t type and associated helpers for v6.0. Convert the remaining
places so we can remove all the old helpers.
This is a non-functional change.

Reviewed-by: Seth Forshee (DigitalOcean) <sforshee@kernel.org>
Acked-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: Christian Brauner (Microsoft) <brauner@kernel.org>


# 3350607d 18-Oct-2022 Günther Noack <gnoack3000@gmail.com>

security: Create file_truncate hook from path_truncate hook

Like path_truncate, the file_truncate hook also restricts file
truncation, but is called in the cases where truncation is attempted
on an already-opened file.

This is required in a subsequent commit to handle ftruncate()
operations differently to truncate() operations.

Acked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Paul Moore <paul@paul-moore.com>
Signed-off-by: Günther Noack <gnoack3000@gmail.com>
Link: https://lore.kernel.org/r/20221018182216.301684-2-gnoack3000@gmail.com
Signed-off-by: Mickaël Salaün <mic@digikod.net>


# c8e477c6 30-Jan-2022 Al Viro <viro@zeniv.linux.org.uk>

->getprocattr(): attribute name is const char *, TYVM...

cast of ->d_name.name to char * is completely wrong - nothing is
allowed to modify its contents.

Reviewed-by: Christian Brauner (Microsoft) <brauner@kernel.org>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 79eb2711 20-Jul-2022 Lukas Bulwahn <lukas.bulwahn@gmail.com>

apparmor: correct config reference to intended one

Commit 5bfcbd22ee4e ("apparmor: Enable tuning of policy paranoid load for
embedded systems") introduces the config SECURITY_APPARMOR_PARANOID_LOAD,
but then refers in the code to SECURITY_PARANOID_LOAD; note the missing
APPARMOR in the middle.

Correct this to the introduced and intended config option.

Fixes: 5bfcbd22ee4e ("apparmor: Enable tuning of policy paranoid load for embedded systems")
Signed-off-by: Lukas Bulwahn <lukas.bulwahn@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 524d8e14 06-Oct-2020 John Johansen <john.johansen@canonical.com>

apparmor: disable showing the mode as part of a secid to secctx

Displaying the mode as part of the seectx takes up unnecessary memory,
makes it so we can't use refcounted secctx so we need to alloc/free on
every conversion from secid to secctx and introduces a space that
could be potentially mishandled by tooling.

Eg. In an audit record we get

subj_type=firefix (enforce)

Having the mode reported is not necessary, and might even be confusing
eg. when writing an audit rule to match the above record field you
would use

-F subj_type=firefox

ie. the mode is not included. AppArmor provides ways to find the mode
without reporting as part of the secctx. So disable this by default
before its use is wide spread and we can't. For now we add a sysctl
to control the behavior as we can't guarantee no one is using this.

Acked-by: Andrea Righi <andrea.righi@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# df439093 06-Jun-2022 Matthew Wilcox <willy@infradead.org>

apparmor: Convert secid mapping to XArrays instead of IDR

XArrays are a better match than IDR for how AppArmor is mapping
secids. Specifically AppArmor is trying to keep the allocation
dense. XArrays also have the advantage of avoiding the complexity IDRs
preallocation.

In addition this avoids/fixes a lockdep issue raised in the LKML thread
"Linux 5.18-rc4"

where there is a report of an interaction between apparmor and IPC,
this warning may have been spurious as the reported issue is in a
per-cpu local lock taken by the IDR. With the one side in the IPC id
allocation and the other in AppArmor's secid allocation.

Description by John Johansen <john.johansen@canonical.com>

Message-Id: <226cee6a-6ca1-b603-db08-8500cd8f77b7@gnuweeb.org>
Signed-off-by: Matthew Wilcox <willy@infradead.org>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 95c0581f 24-May-2022 John Johansen <john.johansen@canonical.com>

apparmor: add a kernel label to use on kernel objects

Separate kernel objects from unconfined. This is done so we can
distinguish between the two in debugging, auditing and in preparation
for being able to replace unconfined, which is not appropriate for the
kernel.

The kernel label will continue to behave similar to unconfined.

Acked-by: Jon Tourville <jon.tourville@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 84117994 12-Jan-2022 Minghao Chi <chi.minghao@zte.com.cn>

security/apparmor: remove redundant ret variable

Return value from nf_register_net_hooks() directly instead
of taking this in another redundant variable.

Reported-by: Zeal Robot <zealci@zte.com.cn>
Signed-off-by: Minghao Chi <chi.minghao@zte.com.cn>
Signed-off-by: CGEL ZTE <cgel.zte@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 5bfcbd22 03-Feb-2021 John Johansen <john.johansen@canonical.com>

apparmor: Enable tuning of policy paranoid load for embedded systems

AppArmor by default does an extensive check on loaded policy that
can take quite some time on limited resource systems. Allow
disabling this check for embedded systems where system images are
readonly and have checksumming making the need for the embedded
policy to be fully checked to be redundant.

Note: basic policy checks are still done.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# d61c57fd 01-Feb-2021 John Johansen <john.johansen@canonical.com>

apparmor: make export of raw binary profile to userspace optional

Embedded systems have limited space and don't need the introspection
or checkpoint restore capability provided by exporting the raw
profile binary data so make it so make it a config option.

This will reduce run time memory use and also speed up policy loads.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 0fc6ab40 09-Dec-2021 Yang Li <yang.lee@linux.alibaba.com>

lsm: Fix kernel-doc

Fix function name in lsm.c kernel-doc comment
to remove some warnings found by running scripts/kernel-doc,
which is caused by using 'make W=1'.

security/apparmor/lsm.c:819: warning: expecting prototype for
apparmor_clone_security(). Prototype was for
apparmor_sk_clone_security() instead
security/apparmor/lsm.c:923: warning: expecting prototype for
apparmor_socket_list(). Prototype was for apparmor_socket_listen()
instead
security/apparmor/lsm.c:1028: warning: expecting prototype for
apparmor_getsockopt(). Prototype was for apparmor_socket_getsockopt()
instead
security/apparmor/lsm.c:1038: warning: expecting prototype for
apparmor_setsockopt(). Prototype was for apparmor_socket_setsockopt()
instead
ecurity/apparmor/lsm.c:1061: warning: expecting prototype for
apparmor_socket_sock_recv_skb(). Prototype was for
apparmor_socket_sock_rcv_skb() instead

Reported-by: Abaci Robot <abaci@linux.alibaba.com>
Signed-off-by: Yang Li <yang.lee@linux.alibaba.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 100f59d9 06-May-2022 Mickaël Salaün <mic@digikod.net>

LSM: Remove double path_rename hook calls for RENAME_EXCHANGE

In order to be able to identify a file exchange with renameat2(2) and
RENAME_EXCHANGE, which will be useful for Landlock [1], propagate the
rename flags to LSMs. This may also improve performance because of the
switch from two set of LSM hook calls to only one, and because LSMs
using this hook may optimize the double check (e.g. only one lock,
reduce the number of path walks).

AppArmor, Landlock and Tomoyo are updated to leverage this change. This
should not change the current behavior (same check order), except
(different level of) speed boosts.

[1] https://lore.kernel.org/r/20220221212522.320243-1-mic@digikod.net

Cc: James Morris <jmorris@namei.org>
Cc: Kentaro Takeda <takedakn@nttdata.co.jp>
Cc: Serge E. Hallyn <serge@hallyn.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Reviewed-by: Paul Moore <paul@paul-moore.com>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
Link: https://lore.kernel.org/r/20220506161102.525323-7-mic@digikod.net


# 6326948f 29-Sep-2021 Paul Moore <paul@paul-moore.com>

lsm: security_task_getsecid_subj() -> security_current_getsecid_subj()

The security_task_getsecid_subj() LSM hook invites misuse by allowing
callers to specify a task even though the hook is only safe when the
current task is referenced. Fix this by removing the task_struct
argument to the hook, requiring LSM implementations to use the
current task. While we are changing the hook declaration we also
rename the function to security_current_getsecid_subj() in an effort
to reinforce that the hook captures the subjective credentials of the
current task and not an arbitrary task on the system.

Reviewed-by: Serge Hallyn <serge@hallyn.com>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 7b721124 11-Oct-2021 Florian Westphal <fw@strlen.de>

apparmor: remove unneeded one-line hook wrappers

Use the common function directly.

Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 92de220a 30-Jun-2020 John Johansen <john.johansen@canonical.com>

apparmor: update policy capable checks to use a label

Previously the policy capable checks assumed they were using the
current task. Make them take the task label so the query can be
made against an arbitrary task.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 2cf002d1 02-Jun-2020 Mauricio Faria de Oliveira <mfo@canonical.com>

apparmor: check/put label on apparmor_sk_clone_security()

Currently apparmor_sk_clone_security() does not check for existing
label/peer in the 'new' struct sock; it just overwrites it, if any
(with another reference to the label of the source sock.)

static void apparmor_sk_clone_security(const struct sock *sk,
struct sock *newsk)
{
struct aa_sk_ctx *ctx = SK_CTX(sk);
struct aa_sk_ctx *new = SK_CTX(newsk);

new->label = aa_get_label(ctx->label);
new->peer = aa_get_label(ctx->peer);
}

This might leak label references, which might overflow under load.
Thus, check for and put labels, to prevent such errors.

Note this is similarly done on:

static int apparmor_socket_post_create(struct socket *sock, ...)
...
if (sock->sk) {
struct aa_sk_ctx *ctx = SK_CTX(sock->sk);

aa_put_label(ctx->label);
ctx->label = aa_get_label(label);
}
...

Context:
-------

The label reference count leak is observed if apparmor_sock_graft()
is called previously: this sets the 'ctx->label' field by getting
a reference to the current label (later overwritten, without put.)

static void apparmor_sock_graft(struct sock *sk, ...)
{
struct aa_sk_ctx *ctx = SK_CTX(sk);

if (!ctx->label)
ctx->label = aa_get_current_label();
}

And that is the case on crypto/af_alg.c:af_alg_accept():

int af_alg_accept(struct sock *sk, struct socket *newsock, ...)
...
struct sock *sk2;
...
sk2 = sk_alloc(...);
...
security_sock_graft(sk2, newsock);
security_sk_clone(sk, sk2);
...

Apparently both calls are done on their own right, especially for
other LSMs, being introduced in 2010/2014, before apparmor socket
mediation in 2017 (see commits [1,2,3,4]).

So, it looks OK there! Let's fix the reference leak in apparmor.

Test-case:
---------

Exercise that code path enough to overflow label reference count.

$ cat aa-refcnt-af_alg.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/if_alg.h>

int main() {
int sockfd;
struct sockaddr_alg sa;

/* Setup the crypto API socket */
sockfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (sockfd < 0) {
perror("socket");
return 1;
}

memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
strcpy((char *) sa.salg_type, "rng");
strcpy((char *) sa.salg_name, "stdrng");

if (bind(sockfd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
perror("bind");
return 1;
}

/* Accept a "connection" and close it; repeat. */
while (!close(accept(sockfd, NULL, 0)));

return 0;
}

$ gcc -o aa-refcnt-af_alg aa-refcnt-af_alg.c

$ ./aa-refcnt-af_alg
<a few hours later>

[ 9928.475953] refcount_t overflow at apparmor_sk_clone_security+0x37/0x70 in aa-refcnt-af_alg[1322], uid/euid: 1000/1000
...
[ 9928.507443] RIP: 0010:apparmor_sk_clone_security+0x37/0x70
...
[ 9928.514286] security_sk_clone+0x33/0x50
[ 9928.514807] af_alg_accept+0x81/0x1c0 [af_alg]
[ 9928.516091] alg_accept+0x15/0x20 [af_alg]
[ 9928.516682] SYSC_accept4+0xff/0x210
[ 9928.519609] SyS_accept+0x10/0x20
[ 9928.520190] do_syscall_64+0x73/0x130
[ 9928.520808] entry_SYSCALL_64_after_hwframe+0x3d/0xa2

Note that other messages may be seen, not just overflow, depending on
the value being incremented by kref_get(); on another run:

[ 7273.182666] refcount_t: saturated; leaking memory.
...
[ 7273.185789] refcount_t: underflow; use-after-free.

Kprobes:
-------

Using kprobe events to monitor sk -> sk_security -> label -> count (kref):

Original v5.7 (one reference leak every iteration)

... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd2
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd4
... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd3
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd5
... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd4
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd6

Patched v5.7 (zero reference leak per iteration)

... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594
... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594
... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594

Commits:
-------

[1] commit 507cad355fc9 ("crypto: af_alg - Make sure sk_security is initialized on accept()ed sockets")
[2] commit 4c63f83c2c2e ("crypto: af_alg - properly label AF_ALG socket")
[3] commit 2acce6aa9f65 ("Networking") a.k.a ("crypto: af_alg - Avoid sock_graft call warning)
[4] commit 56974a6fcfef ("apparmor: add base infastructure for socket mediation")

Reported-by: Brian Moyles <bmoyles@netflix.com>
Signed-off-by: Mauricio Faria de Oliveira <mfo@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 4ebd7651 19-Feb-2021 Paul Moore <paul@paul-moore.com>

lsm: separate security_task_getsecid() into subjective and objective variants

Of the three LSMs that implement the security_task_getsecid() LSM
hook, all three LSMs provide the task's objective security
credentials. This turns out to be unfortunate as most of the hook's
callers seem to expect the task's subjective credentials, although
a small handful of callers do correctly expect the objective
credentials.

This patch is the first step towards fixing the problem: it splits
the existing security_task_getsecid() hook into two variants, one
for the subjective creds, one for the objective creds.

void security_task_getsecid_subj(struct task_struct *p,
u32 *secid);
void security_task_getsecid_obj(struct task_struct *p,
u32 *secid);

While this patch does fix all of the callers to use the correct
variant, in order to keep this patch focused on the callers and to
ease review, the LSMs continue to use the same implementation for
both hooks. The net effect is that this patch should not change
the behavior of the kernel in any way, it will be up to the latter
LSM specific patches in this series to change the hook
implementations and return the correct credentials.

Acked-by: Mimi Zohar <zohar@linux.ibm.com> (IMA)
Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Richard Guy Briggs <rgb@redhat.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 3cee6079 21-Jan-2021 Christian Brauner <christian.brauner@ubuntu.com>

apparmor: handle idmapped mounts

The i_uid and i_gid are mostly used when logging for AppArmor. This is
broken in a bunch of places where the global root id is reported instead
of the i_uid or i_gid of the file. Nonetheless, be kind and log the
mapped inode if we're coming from an idmapped mount. If the initial user
namespace is passed nothing changes so non-idmapped mounts will see
identical behavior as before.

Link: https://lore.kernel.org/r/20210121131959.646623-26-christian.brauner@ubuntu.com
Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>


# 41dd9596 30-Nov-2020 Florian Westphal <fw@strlen.de>

security: add const qualifier to struct sock in various places

A followup change to tcp_request_sock_op would have to drop the 'const'
qualifier from the 'route_req' function as the
'security_inet_conn_request' call is moved there - and that function
expects a 'struct sock *'.

However, it turns out its also possible to add a const qualifier to
security_inet_conn_request instead.

Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: James Morris <jamorris@linux.microsoft.com>
Signed-off-by: Jakub Kicinski <kuba@kernel.org>


# 3b646abc 02-Jun-2020 Mauricio Faria de Oliveira <mfo@canonical.com>

apparmor: check/put label on apparmor_sk_clone_security()

Currently apparmor_sk_clone_security() does not check for existing
label/peer in the 'new' struct sock; it just overwrites it, if any
(with another reference to the label of the source sock.)

static void apparmor_sk_clone_security(const struct sock *sk,
struct sock *newsk)
{
struct aa_sk_ctx *ctx = SK_CTX(sk);
struct aa_sk_ctx *new = SK_CTX(newsk);

new->label = aa_get_label(ctx->label);
new->peer = aa_get_label(ctx->peer);
}

This might leak label references, which might overflow under load.
Thus, check for and put labels, to prevent such errors.

Note this is similarly done on:

static int apparmor_socket_post_create(struct socket *sock, ...)
...
if (sock->sk) {
struct aa_sk_ctx *ctx = SK_CTX(sock->sk);

aa_put_label(ctx->label);
ctx->label = aa_get_label(label);
}
...

Context:
-------

The label reference count leak is observed if apparmor_sock_graft()
is called previously: this sets the 'ctx->label' field by getting
a reference to the current label (later overwritten, without put.)

static void apparmor_sock_graft(struct sock *sk, ...)
{
struct aa_sk_ctx *ctx = SK_CTX(sk);

if (!ctx->label)
ctx->label = aa_get_current_label();
}

And that is the case on crypto/af_alg.c:af_alg_accept():

int af_alg_accept(struct sock *sk, struct socket *newsock, ...)
...
struct sock *sk2;
...
sk2 = sk_alloc(...);
...
security_sock_graft(sk2, newsock);
security_sk_clone(sk, sk2);
...

Apparently both calls are done on their own right, especially for
other LSMs, being introduced in 2010/2014, before apparmor socket
mediation in 2017 (see commits [1,2,3,4]).

So, it looks OK there! Let's fix the reference leak in apparmor.

Test-case:
---------

Exercise that code path enough to overflow label reference count.

$ cat aa-refcnt-af_alg.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/if_alg.h>

int main() {
int sockfd;
struct sockaddr_alg sa;

/* Setup the crypto API socket */
sockfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (sockfd < 0) {
perror("socket");
return 1;
}

memset(&sa, 0, sizeof(sa));
sa.salg_family = AF_ALG;
strcpy((char *) sa.salg_type, "rng");
strcpy((char *) sa.salg_name, "stdrng");

if (bind(sockfd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
perror("bind");
return 1;
}

/* Accept a "connection" and close it; repeat. */
while (!close(accept(sockfd, NULL, 0)));

return 0;
}

$ gcc -o aa-refcnt-af_alg aa-refcnt-af_alg.c

$ ./aa-refcnt-af_alg
<a few hours later>

[ 9928.475953] refcount_t overflow at apparmor_sk_clone_security+0x37/0x70 in aa-refcnt-af_alg[1322], uid/euid: 1000/1000
...
[ 9928.507443] RIP: 0010:apparmor_sk_clone_security+0x37/0x70
...
[ 9928.514286] security_sk_clone+0x33/0x50
[ 9928.514807] af_alg_accept+0x81/0x1c0 [af_alg]
[ 9928.516091] alg_accept+0x15/0x20 [af_alg]
[ 9928.516682] SYSC_accept4+0xff/0x210
[ 9928.519609] SyS_accept+0x10/0x20
[ 9928.520190] do_syscall_64+0x73/0x130
[ 9928.520808] entry_SYSCALL_64_after_hwframe+0x3d/0xa2

Note that other messages may be seen, not just overflow, depending on
the value being incremented by kref_get(); on another run:

[ 7273.182666] refcount_t: saturated; leaking memory.
...
[ 7273.185789] refcount_t: underflow; use-after-free.

Kprobes:
-------

Using kprobe events to monitor sk -> sk_security -> label -> count (kref):

Original v5.7 (one reference leak every iteration)

... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd2
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd4
... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd3
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd5
... (af_alg_accept+0x0/0x1c0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd4
... (af_alg_release_parent+0x0/0xd0) label=0xffff8a0f36c25eb0 label_refcnt=0x11fd6

Patched v5.7 (zero reference leak per iteration)

... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594
... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594
... (af_alg_accept+0x0/0x1c0) label=0xffff9ff376c25eb0 label_refcnt=0x593
... (af_alg_release_parent+0x0/0xd0) label=0xffff9ff376c25eb0 label_refcnt=0x594

Commits:
-------

[1] commit 507cad355fc9 ("crypto: af_alg - Make sure sk_security is initialized on accept()ed sockets")
[2] commit 4c63f83c2c2e ("crypto: af_alg - properly label AF_ALG socket")
[3] commit 2acce6aa9f65 ("Networking") a.k.a ("crypto: af_alg - Avoid sock_graft call warning)
[4] commit 56974a6fcfef ("apparmor: add base infastructure for socket mediation")

Fixes: 56974a6fcfef ("apparmor: add base infastructure for socket mediation")
Reported-by: Brian Moyles <bmoyles@netflix.com>
Signed-off-by: Mauricio Faria de Oliveira <mfo@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# b8bff599 22-Mar-2020 Eric W. Biederman <ebiederm@xmission.com>

exec: Factor security_bprm_creds_for_exec out of security_bprm_set_creds

Today security_bprm_set_creds has several implementations:
apparmor_bprm_set_creds, cap_bprm_set_creds, selinux_bprm_set_creds,
smack_bprm_set_creds, and tomoyo_bprm_set_creds.

Except for cap_bprm_set_creds they all test bprm->called_set_creds and
return immediately if it is true. The function cap_bprm_set_creds
ignores bprm->calld_sed_creds entirely.

Create a new LSM hook security_bprm_creds_for_exec that is called just
before prepare_binprm in __do_execve_file, resulting in a LSM hook
that is called exactly once for the entire of exec. Modify the bits
of security_bprm_set_creds that only want to be called once per exec
into security_bprm_creds_for_exec, leaving only cap_bprm_set_creds
behind.

Remove bprm->called_set_creds all of it's former users have been moved
to security_bprm_creds_for_exec.

Add or upate comments a appropriate to bring them up to date and
to reflect this change.

Link: https://lkml.kernel.org/r/87v9kszrzh.fsf_-_@x220.int.ebiederm.org
Acked-by: Linus Torvalds <torvalds@linux-foundation.org>
Acked-by: Casey Schaufler <casey@schaufler-ca.com> # For the LSM and Smack bits
Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>


# 32927393 24-Apr-2020 Christoph Hellwig <hch@lst.de>

sysctl: pass kernel pointers to ->proc_handler

Instead of having all the sysctl handlers deal with user pointers, which
is rather hairy in terms of the BPF interaction, copy the input to and
from userspace in common code. This also means that the strings are
always NUL-terminated by the common code, making the API a little bit
safer.

As most handler just pass through the data to one of the common handlers
a lot of the changes are mechnical.

Signed-off-by: Christoph Hellwig <hch@lst.de>
Acked-by: Andrey Ignatov <rdna@fb.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 341c1fda 14-Sep-2019 John Johansen <john.johansen@canonical.com>

apparmor: make it so work buffers can be allocated from atomic context

In some situations AppArmor needs to be able to use its work buffers
from atomic context. Add the ability to specify when in atomic context
and hold a set of work buffers in reserve for atomic context to
reduce the chance that a large work buffer allocation will need to
be done.

Fixes: df323337e507 ("apparmor: Use a memory pool instead per-CPU caches")
Signed-off-by: John Johansen <john.johansen@canonical.com>


# df323337 03-May-2019 Sebastian Andrzej Siewior <bigeasy@linutronix.de>

apparmor: Use a memory pool instead per-CPU caches

The get_buffers() macro may provide one or two buffers to the caller.
Those buffers are pre-allocated on init for each CPU. By default it
allocates
2* 2 * MAX_PATH * POSSIBLE_CPU

which equals 64KiB on a system with 4 CPUs or 1MiB with 64 CPUs and so
on.

Replace the per-CPU buffers with a common memory pool which is shared
across all CPUs. The pool grows on demand and never shrinks. The pool
starts with two (UP) or four (SMP) elements. By using this pool it is
possible to request a buffer and keeping preemption enabled which avoids
the hack in profile_transition().

It has been pointed out by Tetsuo Handa that GFP_KERNEL allocations for
small amount of memory do not fail. In order not to have an endless
retry, __GFP_RETRY_MAYFAIL is passed (so the memory allocation is not
repeated until success) and retried once hoping that in the meantime a
buffer has been returned to the pool. Since now NULL is possible all
allocation paths check the buffer pointer and return -ENOMEM on failure.

Signed-off-by: Sebastian Andrzej Siewior <bigeasy@linutronix.de>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# bf1d2ee7 23-Apr-2019 Bharath Vedartham <linux.bhar@gmail.com>

apparmor: Force type-casting of current->real_cred

This patch fixes the sparse warning:
warning: cast removes address space '<asn:4>' of expression.

Signed-off-by: Bharath Vedartham <linux.bhar@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# b886d83c 01-Jun-2019 Thomas Gleixner <tglx@linutronix.de>

treewide: Replace GPLv2 boilerplate/reference with SPDX - rule 441

Based on 1 normalized pattern(s):

this program is free software you can redistribute it and or modify
it under the terms of the gnu general public license as published by
the free software foundation version 2 of the license

extracted by the scancode license scanner the SPDX license identifier

GPL-2.0-only

has been chosen to replace the boilerplate/reference in 315 file(s).

Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Reviewed-by: Allison Randal <allison@lohutok.net>
Reviewed-by: Armijn Hemel <armijn@tjaldur.nl>
Cc: linux-spdx@vger.kernel.org
Link: https://lkml.kernel.org/r/20190531190115.503150771@linutronix.de
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>


# 63c16c3a 23-Jan-2019 Chris Coulson <chris.coulson@canonical.com>

apparmor: Initial implementation of raw policy blob compression

This adds an initial implementation of raw policy blob compression,
using deflate. Compression level can be controlled via a new sysctl,
"apparmor.rawdata_compression_level", which can be set to a value
between 0 (no compression) and 9 (highest compression).

Signed-off-by: Chris Coulson <chris.coulson@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# e33c1b99 08-Apr-2019 Kees Cook <keescook@chromium.org>

apparmor: Restore Y/N in /sys for apparmor's "enabled"

Before commit c5459b829b71 ("LSM: Plumb visibility into optional "enabled"
state"), /sys/module/apparmor/parameters/enabled would show "Y" or "N"
since it was using the "bool" handler. After being changed to "int",
this switched to "1" or "0", breaking the userspace AppArmor detection
of dbus-broker. This restores the Y/N output while keeping the LSM
infrastructure happy.

Before:
$ cat /sys/module/apparmor/parameters/enabled
1

After:
$ cat /sys/module/apparmor/parameters/enabled
Y

Reported-by: David Rheinsberg <david.rheinsberg@gmail.com>
Reviewed-by: David Rheinsberg <david.rheinsberg@gmail.com>
Link: https://lkml.kernel.org/r/CADyDSO6k8vYb1eryT4g6+EHrLCvb68GAbHVWuULkYjcZcYNhhw@mail.gmail.com
Fixes: c5459b829b71 ("LSM: Plumb visibility into optional "enabled" state")
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# a1a02062 12-Nov-2018 Petr Vorel <pvorel@suse.cz>

apparmor: Fix warning about unused function apparmor_ipv6_postroute

when compiled without CONFIG_IPV6:
security/apparmor/lsm.c:1601:21: warning: ‘apparmor_ipv6_postroute’ defined but not used [-Wunused-function]
static unsigned int apparmor_ipv6_postroute(void *priv,
^~~~~~~~~~~~~~~~~~~~~~~

Reported-by: Jordan Glover <Golden_Miller83@protonmail.ch>
Tested-by: Jordan Glover <Golden_Miller83@protonmail.ch>
Signed-off-by: Petr Vorel <pvorel@suse.cz>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 1cfb2a51 18-Jan-2019 Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>

LSM: Make lsm_early_cred() and lsm_early_task() local functions.

Since current->cred == current->real_cred when ordered_lsm_init()
is called, and lsm_early_cred()/lsm_early_task() need to be called
between the amount of required bytes is determined and module specific
initialization function is called, we can move these calls from
individual modules to ordered_lsm_init().

Signed-off-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: James Morris <james.morris@microsoft.com>


# c1a85a00 07-Jan-2019 Micah Morton <mortonm@chromium.org>

LSM: generalize flag passing to security_capable

This patch provides a general mechanism for passing flags to the
security_capable LSM hook. It replaces the specific 'audit' flag that is
used to tell security_capable whether it should log an audit message for
the given capability check. The reason for generalizing this flag
passing is so we can add an additional flag that signifies whether
security_capable is being called by a setid syscall (which is needed by
the proposed SafeSetID LSM).

Signed-off-by: Micah Morton <mortonm@chromium.org>
Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: James Morris <james.morris@microsoft.com>


# f4ad8f2c 21-Sep-2018 Casey Schaufler <casey@schaufler-ca.com>

LSM: Infrastructure management of the task security

Move management of the task_struct->security blob out
of the individual security modules and into the security
infrastructure. Instead of allocating the blobs from within
the modules the modules tell the infrastructure how much
space is required, and the space is allocated there.
The only user of this blob is AppArmor. The AppArmor use
is abstracted to avoid future conflict.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
[kees: adjusted for ordered init series]
Signed-off-by: Kees Cook <keescook@chromium.org>


# 33bf60ca 12-Nov-2018 Casey Schaufler <casey@schaufler-ca.com>

LSM: Infrastructure management of the file security

Move management of the file->f_security blob out of the
individual security modules and into the infrastructure.
The modules no longer allocate or free the data, instead
they tell the infrastructure how much space they require.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
[kees: adjusted for ordered init series]
Signed-off-by: Kees Cook <keescook@chromium.org>


# bbd3662a 12-Nov-2018 Casey Schaufler <casey@schaufler-ca.com>

Infrastructure management of the cred security blob

Move management of the cred security blob out of the
security modules and into the security infrastructre.
Instead of allocating and freeing space the security
modules tell the infrastructure how much space they
require.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
[kees: adjusted for ordered init series]
Signed-off-by: Kees Cook <keescook@chromium.org>


# 69b5a44a 21-Sep-2018 Casey Schaufler <casey@schaufler-ca.com>

AppArmor: Abstract use of cred security blob

Don't use the cred->security pointer directly.
Provide a helper function that provides the security blob pointer.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
[kees: adjusted for ordered init series]
Signed-off-by: Kees Cook <keescook@chromium.org>


# 0102fb83 01-Oct-2018 Kees Cook <keescook@chromium.org>

apparmor: Remove SECURITY_APPARMOR_BOOTPARAM_VALUE

In preparation for removing CONFIG_DEFAULT_SECURITY, this removes the
soon-to-be redundant SECURITY_APPARMOR_BOOTPARAM_VALUE. Since explicit
ordering via CONFIG_LSM or "lsm=" will define whether an LSM is enabled or
not, this CONFIG will become effectively ignored, so remove it. However,
in order to stay backward-compatible with "security=apparmor", the enable
variable defaults to true.

Signed-off-by: Kees Cook <keescook@chromium.org>


# 14bd99c8 19-Sep-2018 Kees Cook <keescook@chromium.org>

LSM: Separate idea of "major" LSM from "exclusive" LSM

In order to both support old "security=" Legacy Major LSM selection, and
handling real exclusivity, this creates LSM_FLAG_EXCLUSIVE and updates
the selection logic to handle them.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>


# f4941d75 14-Sep-2018 Kees Cook <keescook@chromium.org>

LSM: Lift LSM selection out of individual LSMs

As a prerequisite to adjusting LSM selection logic in the future, this
moves the selection logic up out of the individual major LSMs, making
their init functions only run when actually enabled. This considers all
LSMs enabled by default unless they specified an external "enable"
variable.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: John Johansen <john.johansen@canonical.com>


# c5459b82 13-Sep-2018 Kees Cook <keescook@chromium.org>

LSM: Plumb visibility into optional "enabled" state

In preparation for lifting the "is this LSM enabled?" logic out of the
individual LSMs, pass in any special enabled state tracking (as needed
for SELinux, AppArmor, and LoadPin). This should be an "int" to include
handling any future cases where "enabled" is exposed via sysctl which
has no "bool" type.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: John Johansen <john.johansen@canonical.com>


# 47008e51 19-Sep-2018 Kees Cook <keescook@chromium.org>

LSM: Introduce LSM_FLAG_LEGACY_MAJOR

This adds a flag for the current "major" LSMs to distinguish them when
we have a universal method for ordering all LSMs. It's called "legacy"
since the distinction of "major" will go away in the blob-sharing world.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: John Johansen <john.johansen@canonical.com>


# e262e32d 01-Nov-2018 David Howells <dhowells@redhat.com>

vfs: Suppress MS_* flag defs within the kernel unless explicitly enabled

Only the mount namespace code that implements mount(2) should be using the
MS_* flags. Suppress them inside the kernel unless uapi/linux/mount.h is
included.

Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
Reviewed-by: David Howells <dhowells@redhat.com>


# 43aa09fe 12-Nov-2018 Petr Vorel <pvorel@suse.cz>

apparmor: Fix warning about unused function apparmor_ipv6_postroute

when compiled without CONFIG_IPV6:
security/apparmor/lsm.c:1601:21: warning: ‘apparmor_ipv6_postroute’ defined but not used [-Wunused-function]
static unsigned int apparmor_ipv6_postroute(void *priv,
^~~~~~~~~~~~~~~~~~~~~~~

Reported-by: Jordan Glover <Golden_Miller83@protonmail.ch>
Tested-by: Jordan Glover <Golden_Miller83@protonmail.ch>
Signed-off-by: Petr Vorel <pvorel@suse.cz>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# e1af4779 05-Oct-2018 Arnd Bergmann <arnd@arndb.de>

apparmor: add #ifdef checks for secmark filtering

The newly added code fails to build when either SECMARK or
NETFILTER are disabled:

security/apparmor/lsm.c: In function 'apparmor_socket_sock_rcv_skb':
security/apparmor/lsm.c:1138:12: error: 'struct sk_buff' has no member named 'secmark'; did you mean 'mark'?

security/apparmor/lsm.c:1671:21: error: 'struct nf_hook_state' declared inside parameter list will not be visible outside of this definition or declaration [-Werror]

Add a set of #ifdef checks around it to only enable the code that
we can compile and that makes sense in that configuration.

Fixes: ab9f2115081a ("apparmor: Allow filtering based on secmark policy")
Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 07aed2f2 10-Oct-2018 Kees Cook <keescook@chromium.org>

LSM: Record LSM name in struct lsm_info

In preparation for making LSM selections outside of the LSMs, include
the name of LSMs in struct lsm_info.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Signed-off-by: James Morris <james.morris@microsoft.com>


# 3d6e5f6d 10-Oct-2018 Kees Cook <keescook@chromium.org>

LSM: Convert security_initcall() into DEFINE_LSM()

Instead of using argument-based initializers, switch to defining the
contents of struct lsm_info on a per-LSM basis. This also drops
the final use of the now inaccurate "initcall" naming.

Signed-off-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Casey Schaufler <casey@schaufler-ca.com>
Reviewed-by: James Morris <james.morris@microsoft.com>
Signed-off-by: James Morris <james.morris@microsoft.com>


# ae7795bc 25-Sep-2018 Eric W. Biederman <ebiederm@xmission.com>

signal: Distinguish between kernel_siginfo and siginfo

Linus recently observed that if we did not worry about the padding
member in struct siginfo it is only about 48 bytes, and 48 bytes is
much nicer than 128 bytes for allocating on the stack and copying
around in the kernel.

The obvious thing of only adding the padding when userspace is
including siginfo.h won't work as there are sigframe definitions in
the kernel that embed struct siginfo.

So split siginfo in two; kernel_siginfo and siginfo. Keeping the
traditional name for the userspace definition. While the version that
is used internally to the kernel and ultimately will not be padded to
128 bytes is called kernel_siginfo.

The definition of struct kernel_siginfo I have put in include/signal_types.h

A set of buildtime checks has been added to verify the two structures have
the same field offsets.

To make it easy to verify the change kernel_siginfo retains the same
size as siginfo. The reduction in size comes in a following change.

Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>


# ca3fde52 28-Sep-2018 Jann Horn <jannh@google.com>

apparmor: don't try to replace stale label in ptraceme check

begin_current_label_crit_section() must run in sleepable context because
when label_is_stale() is true, aa_replace_current_label() runs, which uses
prepare_creds(), which can sleep.

Until now, the ptraceme access check (which runs with tasklist_lock held)
violated this rule.

Fixes: b2d09ae449ced ("apparmor: move ptrace checks to using labels")
Reported-by: Cyrill Gorcunov <gorcunov@gmail.com>
Reported-by: kernel test robot <rong.a.chen@intel.com>
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# ab9f2115 24-May-2018 Matthew Garrett <mjg59@google.com>

apparmor: Allow filtering based on secmark policy

Add support for dropping or accepting packets based on their secmark
tags.

Signed-off-by: Matthew Garrett <mjg59@google.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 1f8266ff 13-Sep-2018 Jann Horn <jannh@google.com>

apparmor: don't try to replace stale label in ptrace access check

As a comment above begin_current_label_crit_section() explains,
begin_current_label_crit_section() must run in sleepable context because
when label_is_stale() is true, aa_replace_current_label() runs, which uses
prepare_creds(), which can sleep.
Until now, the ptrace access check (which runs with a task lock held)
violated this rule.

Also add a might_sleep() assertion to begin_current_label_crit_section(),
because asserts are less likely to be ignored than comments.

Fixes: b2d09ae449ced ("apparmor: move ptrace checks to using labels")
Signed-off-by: Jann Horn <jannh@google.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 94817692 10-Jul-2018 Al Viro <viro@zeniv.linux.org.uk>

->file_open(): lose cred argument

Acked-by: Linus Torvalds <torvalds@linux-foundation.org>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 338d0be4 07-Jun-2018 John Johansen <john.johansen@canonical.com>

apparmor: fix ptrace read check

The ptrace read check is incorrect resulting in policy that is
broader than it needs to be. Fix the check so that read access
permission can be properly detected when other ptrace flags are
set.

Fixes: b2d09ae449ce ("apparmor: move ptrace checks to using labels")
Signed-off-by: John Johansen <john.johansen@canonical.com>


# a4c3f89c 04-Jun-2018 John Johansen <john.johansen@canonical.com>

apparmor: fixup secid map conversion to using IDR

The IDR conversion did not handle an error case for when allocating a
mapping fails, and it did not ensure that mappings did not allocate or
use a 0 value, which is used as an invalid secid. Which is used when a
mapping fails.

Fixes: 3ae7eb49a2be ("apparmor: Use an IDR to allocate apparmor secids")
Signed-off-by: John Johansen <john.johansen@canonical.com>


# e79c26d0 16-Apr-2018 Matthew Garrett <mjg59@google.com>

apparmor: Add support for audit rule filtering

This patch adds support to Apparmor for integrating with audit rule
filtering. Right now it only handles SUBJ_ROLE, interpreting it as a
single component of a label. This is sufficient to get Apparmor working
with IMA's appraisal rules without any modifications on the IMA side.

Signed-off-by: Matthew Garrett <mjg59@google.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 5d8779a5 07-May-2018 Andy Shevchenko <andriy.shevchenko@linux.intel.com>

apparmor: Convert to use match_string() helper

The new helper returns index of the matching string in an array.
We are going to use it here.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Reviewed-by: Jay Freyensee <why2jjj.linux@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# a7ae3645 11-Sep-2017 John Johansen <john.johansen@canonical.com>

apparmor: add the ability to get a task's secid

Signed-off-by: John Johansen <john.johansen@canonical.com>


# c0929212 31-Jul-2017 John Johansen <john.johansen@canonical.com>

apparmor: add support for mapping secids and using secctxes

Use a radix tree to provide a map between the secid and the label,
and along with it a basic ability to provide secctx conversion.

Shared/cached secctx will be added later.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 514c6032 05-Apr-2018 Randy Dunlap <rdunlap@infradead.org>

headers: untangle kmemleak.h from mm.h

Currently <linux/slab.h> #includes <linux/kmemleak.h> for no obvious
reason. It looks like it's only a convenience, so remove kmemleak.h
from slab.h and add <linux/kmemleak.h> to any users of kmemleak_* that
don't already #include it. Also remove <linux/kmemleak.h> from source
files that do not use it.

This is tested on i386 allmodconfig and x86_64 allmodconfig. It would
be good to run it through the 0day bot for other $ARCHes. I have
neither the horsepower nor the storage space for the other $ARCHes.

Update: This patch has been extensively build-tested by both the 0day
bot & kisskb/ozlabs build farms. Both of them reported 2 build failures
for which patches are included here (in v2).

[ slab.h is the second most used header file after module.h; kernel.h is
right there with slab.h. There could be some minor error in the
counting due to some #includes having comments after them and I didn't
combine all of those. ]

[akpm@linux-foundation.org: security/keys/big_key.c needs vmalloc.h, per sfr]
Link: http://lkml.kernel.org/r/e4309f98-3749-93e1-4bb7-d9501a39d015@infradead.org
Link: http://kisskb.ellerman.id.au/kisskb/head/13396/
Signed-off-by: Randy Dunlap <rdunlap@infradead.org>
Reviewed-by: Ingo Molnar <mingo@kernel.org>
Reported-by: Michael Ellerman <mpe@ellerman.id.au> [2 build failures]
Reported-by: Fengguang Wu <fengguang.wu@intel.com> [2 build failures]
Reviewed-by: Andrew Morton <akpm@linux-foundation.org>
Cc: Wei Yongjun <weiyongjun1@huawei.com>
Cc: Luis R. Rodriguez <mcgrof@kernel.org>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Mimi Zohar <zohar@linux.vnet.ibm.com>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Stephen Rothwell <sfr@canb.auug.org.au>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 56974a6f 19-Jul-2017 John Johansen <john.johansen@canonical.com>

apparmor: add base infastructure for socket mediation

version 2 - Force an abi break. Network mediation will only be
available in v8 abi complaint policy.

Provide a basic mediation of sockets. This is not a full net mediation
but just whether a spcific family of socket can be used by an
application, along with setting up some basic infrastructure for
network mediation to follow.

the user space rule hav the basic form of
NETWORK RULE = [ QUALIFIERS ] 'network' [ DOMAIN ]
[ TYPE | PROTOCOL ]

DOMAIN = ( 'inet' | 'ax25' | 'ipx' | 'appletalk' | 'netrom' |
'bridge' | 'atmpvc' | 'x25' | 'inet6' | 'rose' |
'netbeui' | 'security' | 'key' | 'packet' | 'ash' |
'econet' | 'atmsvc' | 'sna' | 'irda' | 'pppox' |
'wanpipe' | 'bluetooth' | 'netlink' | 'unix' | 'rds' |
'llc' | 'can' | 'tipc' | 'iucv' | 'rxrpc' | 'isdn' |
'phonet' | 'ieee802154' | 'caif' | 'alg' | 'nfc' |
'vsock' | 'mpls' | 'ib' | 'kcm' ) ','

TYPE = ( 'stream' | 'dgram' | 'seqpacket' | 'rdm' | 'raw' |
'packet' )

PROTOCOL = ( 'tcp' | 'udp' | 'icmp' )

eg.
network,
network inet,

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# 6b4f3d01 07-Sep-2017 Stephen Smalley <sds@tycho.nsa.gov>

usb, signal, security: only pass the cred, not the secid, to kill_pid_info_as_cred and security_task_kill

commit d178bc3a708f39cbfefc3fab37032d3f2511b4ec ("user namespace: usb:
make usb urbs user namespace aware (v2)") changed kill_pid_info_as_uid
to kill_pid_info_as_cred, saving and passing a cred structure instead of
uids. Since the secid can be obtained from the cred, drop the secid fields
from the usb_dev_state and async structures, and drop the secid argument to
kill_pid_info_as_cred. Replace the secid argument to security_task_kill
with the cred. Update SELinux, Smack, and AppArmor to use the cred, which
avoids the need for Smack and AppArmor to use a secid at all in this hook.
Further changes to Smack might still be required to take full advantage of
this change, since it should now be possible to perform capability
checking based on the supplied cred. The changes to Smack and AppArmor
have only been compile-tested.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <james.morris@microsoft.com>


# d8889d49 11-Oct-2017 John Johansen <john.johansen@canonical.com>

apparmor: move context.h to cred.h

Now that file contexts have been moved into file, and task context
fns() and data have been split from the context, only the cred context
remains in context.h so rename to cred.h to better reflect what it
deals with.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# de62de59 08-Oct-2017 John Johansen <john.johansen@canonical.com>

apparmor: move task related defines and fns to task.X files

Signed-off-by: John Johansen <john.johansen@canonical.com>


# f175221a 27-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: rename tctx to ctx

now that cred_ctx has been removed we can rename task_ctxs from tctx
without causing confusion.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# d9087c49 27-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: drop cred_ctx and reference the label directly

With the task domain change information now stored in the task->security
context, the cred->security context only stores the label. We can get
rid of the cred_ctx and directly reference the label, removing a layer
of indirection, and unneeded extra allocations.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 3b529a76 20-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: move task domain change info to task security

The task domain change info is task specific and its and abuse of
the cred to store the information in there. Now that a task->security
field exists store it in the proper place.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 4d2f8ba3 19-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: rename task_ctx to the more accurate cred_ctx

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 954317fe 07-Oct-2017 Thomas Meyer <thomas@m3y3r.de>

apparmor: Fix bool initialization/comparison

Bool initializations should use true and false. Bool tests don't need
comparisons.

Signed-off-by: Thomas Meyer <thomas@m3y3r.de>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# e4dca7b7 17-Oct-2017 Kees Cook <keescook@chromium.org>

treewide: Fix function prototypes for module_param_call()

Several function prototypes for the set/get functions defined by
module_param_call() have a slightly wrong argument types. This fixes
those in an effort to clean up the calls when running under type-enforced
compiler instrumentation for CFI. This is the result of running the
following semantic patch:

@match_module_param_call_function@
declarer name module_param_call;
identifier _name, _set_func, _get_func;
expression _arg, _mode;
@@

module_param_call(_name, _set_func, _get_func, _arg, _mode);

@fix_set_prototype
depends on match_module_param_call_function@
identifier match_module_param_call_function._set_func;
identifier _val, _param;
type _val_type, _param_type;
@@

int _set_func(
-_val_type _val
+const char * _val
,
-_param_type _param
+const struct kernel_param * _param
) { ... }

@fix_get_prototype
depends on match_module_param_call_function@
identifier match_module_param_call_function._get_func;
identifier _val, _param;
type _val_type, _param_type;
@@

int _get_func(
-_val_type _val
+char * _val
,
-_param_type _param
+const struct kernel_param * _param
) { ... }

Two additional by-hand changes are included for places where the above
Coccinelle script didn't notice them:

drivers/platform/x86/thinkpad_acpi.c
fs/lockd/svc.c

Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Jessica Yu <jeyu@kernel.org>


# 80c094a4 26-Oct-2017 Linus Torvalds <torvalds@linux-foundation.org>

Revert "apparmor: add base infastructure for socket mediation"

This reverts commit 651e28c5537abb39076d3949fb7618536f1d242e.

This caused a regression:
"The specific problem is that dnsmasq refuses to start on openSUSE Leap
42.2. The specific cause is that and attempt to open a PF_LOCAL socket
gets EACCES. This means that networking doesn't function on a system
with a 4.14-rc2 system."

Sadly, the developers involved seemed to be in denial for several weeks
about this, delaying the revert. This has not been a good release for
the security subsystem, and this area needs to change development
practices.

Reported-and-bisected-by: James Bottomley <James.Bottomley@hansenpartnership.com>
Tracked-by: Thorsten Leemhuis <regressions@leemhuis.info>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Vlastimil Babka <vbabka@suse.cz>
Cc: Seth Arnold <seth.arnold@canonical.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 651e28c5 19-Jul-2017 John Johansen <john.johansen@canonical.com>

apparmor: add base infastructure for socket mediation

Provide a basic mediation of sockets. This is not a full net mediation
but just whether a spcific family of socket can be used by an
application, along with setting up some basic infrastructure for
network mediation to follow.

the user space rule hav the basic form of
NETWORK RULE = [ QUALIFIERS ] 'network' [ DOMAIN ]
[ TYPE | PROTOCOL ]

DOMAIN = ( 'inet' | 'ax25' | 'ipx' | 'appletalk' | 'netrom' |
'bridge' | 'atmpvc' | 'x25' | 'inet6' | 'rose' |
'netbeui' | 'security' | 'key' | 'packet' | 'ash' |
'econet' | 'atmsvc' | 'sna' | 'irda' | 'pppox' |
'wanpipe' | 'bluetooth' | 'netlink' | 'unix' | 'rds' |
'llc' | 'can' | 'tipc' | 'iucv' | 'rxrpc' | 'isdn' |
'phonet' | 'ieee802154' | 'caif' | 'alg' | 'nfc' |
'vsock' | 'mpls' | 'ib' | 'kcm' ) ','

TYPE = ( 'stream' | 'dgram' | 'seqpacket' | 'rdm' | 'raw' |
'packet' )

PROTOCOL = ( 'tcp' | 'udp' | 'icmp' )

eg.
network,
network inet,

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# 2ea3ffb7 19-Jul-2017 John Johansen <john.johansen@canonical.com>

apparmor: add mount mediation

Add basic mount mediation. That allows controlling based on basic
mount parameters. It does not include special mount parameters for
apparmor, super block labeling, or any triggers for apparmor namespace
parameter modifications on pivot root.

default userspace policy rules have the form of
MOUNT RULE = ( MOUNT | REMOUNT | UMOUNT )

MOUNT = [ QUALIFIERS ] 'mount' [ MOUNT CONDITIONS ] [ SOURCE FILEGLOB ]
[ '->' MOUNTPOINT FILEGLOB ]

REMOUNT = [ QUALIFIERS ] 'remount' [ MOUNT CONDITIONS ]
MOUNTPOINT FILEGLOB

UMOUNT = [ QUALIFIERS ] 'umount' [ MOUNT CONDITIONS ] MOUNTPOINT FILEGLOB

MOUNT CONDITIONS = [ ( 'fstype' | 'vfstype' ) ( '=' | 'in' )
MOUNT FSTYPE EXPRESSION ]
[ 'options' ( '=' | 'in' ) MOUNT FLAGS EXPRESSION ]

MOUNT FSTYPE EXPRESSION = ( MOUNT FSTYPE LIST | MOUNT EXPRESSION )

MOUNT FSTYPE LIST = Comma separated list of valid filesystem and
virtual filesystem types (eg ext4, debugfs, etc)

MOUNT FLAGS EXPRESSION = ( MOUNT FLAGS LIST | MOUNT EXPRESSION )

MOUNT FLAGS LIST = Comma separated list of MOUNT FLAGS.

MOUNT FLAGS = ( 'ro' | 'rw' | 'nosuid' | 'suid' | 'nodev' | 'dev' |
'noexec' | 'exec' | 'sync' | 'async' | 'remount' |
'mand' | 'nomand' | 'dirsync' | 'noatime' | 'atime' |
'nodiratime' | 'diratime' | 'bind' | 'rbind' | 'move' |
'verbose' | 'silent' | 'loud' | 'acl' | 'noacl' |
'unbindable' | 'runbindable' | 'private' | 'rprivate' |
'slave' | 'rslave' | 'shared' | 'rshared' |
'relatime' | 'norelatime' | 'iversion' | 'noiversion' |
'strictatime' | 'nouser' | 'user' )

MOUNT EXPRESSION = ( ALPHANUMERIC | AARE ) ...

PIVOT ROOT RULE = [ QUALIFIERS ] pivot_root [ oldroot=OLD PUT FILEGLOB ]
[ NEW ROOT FILEGLOB ]

SOURCE FILEGLOB = FILEGLOB

MOUNTPOINT FILEGLOB = FILEGLOB

eg.
mount,
mount /dev/foo,
mount options=ro /dev/foo -> /mnt/,
mount options in (ro,atime) /dev/foo -> /mnt/,
mount options=ro options=atime,

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# cd1dbf76 18-Jul-2017 John Johansen <john.johansen@canonical.com>

apparmor: add the ability to mediate signals

Add signal mediation where the signal can be mediated based on the
signal, direction, or the label or the peer/target. The signal perms
are verified on a cross check to ensure policy consistency in the case
of incremental policy load/replacement.

The optimization of skipping the cross check when policy is guaranteed
to be consistent (single compile unit) remains to be done.

policy rules have the form of
SIGNAL_RULE = [ QUALIFIERS ] 'signal' [ SIGNAL ACCESS PERMISSIONS ]
[ SIGNAL SET ] [ SIGNAL PEER ]

SIGNAL ACCESS PERMISSIONS = SIGNAL ACCESS | SIGNAL ACCESS LIST

SIGNAL ACCESS LIST = '(' Comma or space separated list of SIGNAL
ACCESS ')'

SIGNAL ACCESS = ( 'r' | 'w' | 'rw' | 'read' | 'write' | 'send' |
'receive' )

SIGNAL SET = 'set' '=' '(' SIGNAL LIST ')'

SIGNAL LIST = Comma or space separated list of SIGNALS

SIGNALS = ( 'hup' | 'int' | 'quit' | 'ill' | 'trap' | 'abrt' |
'bus' | 'fpe' | 'kill' | 'usr1' | 'segv' | 'usr2' |
'pipe' | 'alrm' | 'term' | 'stkflt' | 'chld' | 'cont' |
'stop' | 'stp' | 'ttin' | 'ttou' | 'urg' | 'xcpu' |
'xfsz' | 'vtalrm' | 'prof' | 'winch' | 'io' | 'pwr' |
'sys' | 'emt' | 'exists' | 'rtmin+0' ... 'rtmin+32'
)

SIGNAL PEER = 'peer' '=' AARE

eg.
signal, # allow all signals
signal send set=(hup, kill) peer=foo,

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# 993b3ab0 18-Jul-2017 Kees Cook <keescook@chromium.org>

apparmor: Refactor to remove bprm_secureexec hook

The AppArmor bprm_secureexec hook can be merged with the bprm_set_creds
hook since it's dealing with the same information, and all of the details
are finalized during the first call to the bprm_set_creds hook via
prepare_binprm() (subsequent calls due to binfmt_script, etc, are ignored
via bprm->called_set_creds).

Here, all the comments describe how secureexec is actually calculated
during bprm_set_creds, so this actually does it, drops the bprm flag that
was being used internally by AppArmor, and drops the bprm_secureexec hook.

Signed-off-by: Kees Cook <keescook@chromium.org>
Acked-by: John Johansen <john.johansen@canonical.com>
Reviewed-by: James Morris <james.l.morris@oracle.com>
Acked-by: Serge Hallyn <serge@hallyn.com>


# 6c5fc8f1 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: add stacked domain labels interface

Update the user interface to support the stacked change_profile transition.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 064dc947 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: mediate files when they are received

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 8014370f 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move path_link mediation to using labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# aebd873e 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: refactor path name lookup and permission checks around labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 190a9518 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move aa_file_perm() to use labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# b2d09ae4 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move ptrace checks to using labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 86b92cb7 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move resource checks to using labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# c70c86c4 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move capability checks to using labels

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 76a1d263 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: switch getprocattr to using label_print fns()

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 637f688d 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: switch from profiles to using labels on contexts

Begin the actual switch to using domain labels by storing them on
the context and converting the label to a singular profile where
possible.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 192ca6b5 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: revalidate files during exec

Instead of running file revalidation lazily when read/write are called
copy selinux and revalidate the file table on exec. This avoids
extra mediation overhead in read/write and also prevents file handles
being passed through to a grand child unchecked.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 2835a13b 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: cleanup rename XXX_file_context() to XXX_file_ctx()

Signed-off-by: John Johansen <john.johansen@canonical.com>


# df8073c6 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: convert aa_change_XXX bool parameters to flags

Instead of passing multiple booleans consolidate on a single flags
field.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# cf797c0e 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: convert to profile block critical sections

There are still a few places where profile replacement fails to update
and a stale profile is used for mediation. Fix this by moving to
accessing the current label through a critical section that will
always ensure mediation is using the current label regardless of
whether the tasks cred has been updated or not.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# fe864821 09-Jun-2017 John Johansen <john.johansen@canonical.com>

apparmor: move bprm_committing_creds/committed_creds to lsm.c

There is no reason to have the small stubs that don't use domain
private functions in domain.c, instead move them to lsm.c and make
them static.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 39d84824 30-Mar-2017 John Johansen <john.johansen@canonical.com>

apparmor: provide information about path buffer size at boot

Signed-off-by: John Johansen <john.johansen@canonical.com>


# e53cfe6c 26-May-2017 John Johansen <john.johansen@canonical.com>

apparmor: rework perm mapping to a slightly broader set

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 622f6e32 06-Apr-2017 John Johansen <john.johansen@canonical.com>

apparmor: Make path_max parameter readonly

The path_max parameter determines the max size of buffers allocated
but it should not be setable at run time. If can be used to cause an
oops

root@ubuntu:~# echo 16777216 > /sys/module/apparmor/parameters/path_max
root@ubuntu:~# cat /sys/module/apparmor/parameters/path_max
Killed

[ 122.141911] BUG: unable to handle kernel paging request at ffff880080945fff
[ 122.143497] IP: [<ffffffff81228844>] d_absolute_path+0x44/0xa0
[ 122.144742] PGD 220c067 PUD 0
[ 122.145453] Oops: 0002 [#1] SMP
[ 122.146204] Modules linked in: vmw_vsock_vmci_transport vsock ppdev vmw_balloon snd_ens1371 btusb snd_ac97_codec gameport snd_rawmidi btrtl snd_seq_device ac97_bus btbcm btintel snd_pcm input_leds bluetooth snd_timer snd joydev soundcore serio_raw coretemp shpchp nfit parport_pc i2c_piix4 8250_fintek vmw_vmci parport mac_hid ib_iser rdma_cm iw_cm ib_cm ib_sa ib_mad ib_core ib_addr iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi autofs4 btrfs raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx xor raid6_pq libcrc32c raid1 raid0 multipath linear hid_generic usbhid hid crct10dif_pclmul crc32_pclmul ghash_clmulni_intel aesni_intel aes_x86_64 lrw gf128mul glue_helper ablk_helper cryptd vmwgfx psmouse mptspi ttm mptscsih drm_kms_helper mptbase syscopyarea scsi_transport_spi sysfillrect
[ 122.163365] ahci sysimgblt e1000 fb_sys_fops libahci drm pata_acpi fjes
[ 122.164747] CPU: 3 PID: 1501 Comm: bash Not tainted 4.4.0-59-generic #80-Ubuntu
[ 122.166250] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 07/02/2015
[ 122.168611] task: ffff88003496aa00 ti: ffff880076474000 task.ti: ffff880076474000
[ 122.170018] RIP: 0010:[<ffffffff81228844>] [<ffffffff81228844>] d_absolute_path+0x44/0xa0
[ 122.171525] RSP: 0018:ffff880076477b90 EFLAGS: 00010206
[ 122.172462] RAX: ffff880080945fff RBX: 0000000000000000 RCX: 0000000001000000
[ 122.173709] RDX: 0000000000ffffff RSI: ffff880080946000 RDI: ffff8800348a1010
[ 122.174978] RBP: ffff880076477bb8 R08: ffff880076477c80 R09: 0000000000000000
[ 122.176227] R10: 00007ffffffff000 R11: ffff88007f946000 R12: ffff88007f946000
[ 122.177496] R13: ffff880076477c80 R14: ffff8800348a1010 R15: ffff8800348a2400
[ 122.178745] FS: 00007fd459eb4700(0000) GS:ffff88007b6c0000(0000) knlGS:0000000000000000
[ 122.180176] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 122.181186] CR2: ffff880080945fff CR3: 0000000073422000 CR4: 00000000001406e0
[ 122.182469] Stack:
[ 122.182843] 00ffffff00000001 ffff880080946000 0000000000000000 0000000000000000
[ 122.184409] 00000000570f789c ffff880076477c30 ffffffff81385671 ffff88007a2e7a58
[ 122.185810] 0000000000000000 ffff880076477c88 01000000008a1000 0000000000000000
[ 122.187231] Call Trace:
[ 122.187680] [<ffffffff81385671>] aa_path_name+0x81/0x370
[ 122.188637] [<ffffffff813875dd>] profile_transition+0xbd/0xb80
[ 122.190181] [<ffffffff811af9bc>] ? zone_statistics+0x7c/0xa0
[ 122.191674] [<ffffffff81389b20>] apparmor_bprm_set_creds+0x9b0/0xac0
[ 122.193288] [<ffffffff812e1971>] ? ext4_xattr_get+0x81/0x220
[ 122.194793] [<ffffffff812e800c>] ? ext4_xattr_security_get+0x1c/0x30
[ 122.196392] [<ffffffff813449b9>] ? get_vfs_caps_from_disk+0x69/0x110
[ 122.198004] [<ffffffff81232d4f>] ? mnt_may_suid+0x3f/0x50
[ 122.199737] [<ffffffff81344b03>] ? cap_bprm_set_creds+0xa3/0x600
[ 122.201377] [<ffffffff81346e53>] security_bprm_set_creds+0x33/0x50
[ 122.203024] [<ffffffff81214ce5>] prepare_binprm+0x85/0x190
[ 122.204515] [<ffffffff81216545>] do_execveat_common.isra.33+0x485/0x710
[ 122.206200] [<ffffffff81216a6a>] SyS_execve+0x3a/0x50
[ 122.207615] [<ffffffff81838795>] stub_execve+0x5/0x5
[ 122.208978] [<ffffffff818384f2>] ? entry_SYSCALL_64_fastpath+0x16/0x71
[ 122.210615] Code: f8 31 c0 48 63 c2 83 ea 01 48 c7 45 e8 00 00 00 00 48 01 c6 85 d2 48 c7 45 f0 00 00 00 00 48 89 75 e0 89 55 dc 78 0c 48 8d 46 ff <c6> 46 ff 00 48 89 45 e0 48 8d 55 e0 48 8d 4d dc 48 8d 75 e8 e8
[ 122.217320] RIP [<ffffffff81228844>] d_absolute_path+0x44/0xa0
[ 122.218860] RSP <ffff880076477b90>
[ 122.219919] CR2: ffff880080945fff
[ 122.220936] ---[ end trace 506cdbd85eb6c55e ]---

Reported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# 545de8fe 06-Apr-2017 John Johansen <john.johansen@canonical.com>

apparmor: fix parameters so that the permission test is bypassed at boot

Boot parameters are written before apparmor is ready to answer whether
the user is policy_view_capable(). Setting the parameters at boot results
in an oops and failure to boot. Setting the parameters at boot is
obviously allowed so skip the permission check when apparmor is not
initialized.

While we are at it move the more complicated check to last.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# eea7a05f 06-Apr-2017 Valentin Rothberg <valentinrothberg@gmail.com>

security/apparmor/lsm.c: set debug messages

Add the _APPARMOR substring to reference the intended Kconfig option.

Signed-off-by: Valentin Rothberg <valentinrothberg@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# ca97d939 14-Feb-2017 James Morris <jmorris@namei.org>

security: mark LSM hooks as __ro_after_init

Mark all of the registration hooks as __ro_after_init (via the
__lsm_ro_after_init macro).

Signed-off-by: James Morris <james.l.morris@oracle.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Kees Cook <keescook@chromium.org>


# d69dece5 18-Jan-2017 Casey Schaufler <casey@schaufler-ca.com>

LSM: Add /sys/kernel/security/lsm

I am still tired of having to find indirect ways to determine
what security modules are active on a system. I have added
/sys/kernel/security/lsm, which contains a comma separated
list of the active security modules. No more groping around
in /proc/filesystems or other clever hacks.

Unchanged from previous versions except for being updated
to the latest security next branch.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Kees Cook <keescook@chromium.org>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# 3ccb76c5 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: fix undefined reference to `aa_g_hash_policy'

The kernel build bot turned up a bad config combination when
CONFIG_SECURITY_APPARMOR is y and CONFIG_SECURITY_APPARMOR_HASH is n,
resulting in the build error
security/built-in.o: In function `aa_unpack':
(.text+0x841e2): undefined reference to `aa_g_hash_policy'

Signed-off-by: John Johansen <john.johansen@canonical.com>


# e6bfa25d 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: replace remaining BUG_ON() asserts with AA_BUG()

AA_BUG() uses WARN and won't break the kernel like BUG_ON().

Signed-off-by: John Johansen <john.johansen@canonical.com>


# ca4bd5ae 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add check for apparmor enabled in module parameters missing it

Signed-off-by: John Johansen <john.johansen@canonical.com>


# d4669f0b 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add per cpu work buffers to avoid allocating buffers at every hook

Signed-off-by: John Johansen <john.johansen@canonical.com>


# e3ea1ca5 16-Mar-2016 Tyler Hicks <tyhicks@canonical.com>

apparmor: sysctl to enable unprivileged user ns AppArmor policy loading

If this sysctl is set to non-zero and a process with CAP_MAC_ADMIN in
the root namespace has created an AppArmor policy namespace,
unprivileged processes will be able to change to a profile in the
newly created AppArmor policy namespace and, if the profile allows
CAP_MAC_ADMIN and appropriate file permissions, will be able to load
policy in the respective policy namespace.

Signed-off-by: Tyler Hicks <tyhicks@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# e025be0f 15-Jan-2017 William Hua <william.hua@canonical.com>

apparmor: support querying extended trusted helper extra data

Allow a profile to carry extra data that can be queried via userspace.
This provides a means to store extra data in a profile that a trusted
helper can extract and use from live policy.

Signed-off-by: William Hua <william.hua@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# 31f75bfe 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: make computing policy hashes conditional on kernel parameter

Allow turning off the computation of the policy hashes via the
apparmor.hash_policy kernel parameter.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# aa9a39ad 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: convert change_profile to use fqname later to give better control

Moving the use of fqname to later allows learning profiles to be based
on the fqname request instead of just the hname. It also allows cleaning
up some of the name parsing and lookup by allowing the use of
the fqlookupn_profile() lib fn.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# ef88a7ac 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: change aad apparmor_audit_data macro to a fn macro

The aad macro can replace aad strings when it is not intended to. Switch
to a fn macro so it is only applied when intended.

Also at the same time cleanup audit_data initialization by putting
common boiler plate behind a macro, and dropping the gfp_t parameter
which will become useless.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 47f6e5cc 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: change op from int to const char *

Having ops be an integer that is an index into an op name table is
awkward and brittle. Every op change requires an edit for both the
op constant and a string in the table. Instead switch to using const
strings directly, eliminating the need for the table that needs to
be kept in sync.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 55a26ebf 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: rename context abreviation cxt to the more standard ctx

Signed-off-by: John Johansen <john.johansen@canonical.com>


# fd2a8043 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add ns being viewed as a param to policy_admin_capable()

Prepare for a tighter pairing of user namespaces and apparmor policy
namespaces, by making the ns to be viewed available.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 2bd8dbbf 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add ns being viewed as a param to policy_view_capable()

Prepare for a tighter pairing of user namespaces and apparmor policy
namespaces, by making the ns to be viewed available and checking
that the user namespace level is the same as the policy ns level.

This strict pairing will be relaxed once true support of user namespaces
lands.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 11c236b8 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add a default null dfa

Instead of testing whether a given dfa exists in every code path, have
a default null dfa that is used when loaded policy doesn't provide a
dfa.

This will let us get rid of special casing and avoid dereference bugs
when special casing is missed.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# abbf8734 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: remove paranoid load switch

Policy should always under go a full paranoid verification.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# efeee83a 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: rename mediated_filesystem() to path_mediated_fs()

Rename to indicate the test is only about whether path mediation is used,
not whether other types of mediation might be used.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 680cd62e 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: add debug assert AA_BUG and Kconfig to control debug info

Signed-off-by: John Johansen <john.johansen@canonical.com>


# cff281f6 16-Jan-2017 John Johansen <john.johansen@canonical.com>

apparmor: split apparmor policy namespaces code into its own file

Policy namespaces will be diverging from profile management and
expanding so put it in its own file.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 8486adf0 16-Dec-2016 Kees Cook <keescook@chromium.org>

apparmor: use designated initializers

Prepare to mark sensitive kernel structures for randomization by making
sure they're using designated initializers. These were identified during
allyesconfig builds of x86, arm, and arm64, with most initializer fixes
extracted from grsecurity.

Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# b21507e2 09-Jan-2017 Stephen Smalley <sds@tycho.nsa.gov>

proc,security: move restriction on writing /proc/pid/attr nodes to proc

Processes can only alter their own security attributes via
/proc/pid/attr nodes. This is presently enforced by each individual
security module and is also imposed by the Linux credentials
implementation, which only allows a task to alter its own credentials.
Move the check enforcing this restriction from the individual
security modules to proc_pid_attr_write() before calling the security hook,
and drop the unnecessary task argument to the security hook since it can
only ever be the current task.

Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: Paul Moore <paul@paul-moore.com>


# 7616ac70 25-Jul-2016 Arnd Bergmann <arnd@arndb.de>

apparmor: fix SECURITY_APPARMOR_HASH_DEFAULT parameter handling

The newly added Kconfig option could never work and just causes a build error
when disabled:

security/apparmor/lsm.c:675:25: error: 'CONFIG_SECURITY_APPARMOR_HASH_DEFAULT' undeclared here (not in a function)
bool aa_g_hash_policy = CONFIG_SECURITY_APPARMOR_HASH_DEFAULT;

The problem is that the macro undefined in this case, and we need to use the IS_ENABLED()
helper to turn it into a boolean constant.

Another minor problem with the original patch is that the option is even offered
in sysfs when SECURITY_APPARMOR_HASH is not enabled, so this also hides the option
in that case.

Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Fixes: 6059f71f1e94 ("apparmor: add parameter to control whether policy hashing is used")
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# d4d03f74 10-Jul-2016 John Johansen <john.johansen@canonical.com>

apparmor: fix arg_size computation for when setprocattr is null terminated

Signed-off-by: John Johansen <john.johansen@canonical.com>


# e89b8081 07-Jul-2016 Vegard Nossum <vegard.nossum@oracle.com>

apparmor: fix oops, validate buffer size in apparmor_setprocattr()

When proc_pid_attr_write() was changed to use memdup_user apparmor's
(interface violating) assumption that the setprocattr buffer was always
a single page was violated.

The size test is not strictly speaking needed as proc_pid_attr_write()
will reject anything larger, but for the sake of robustness we can keep
it in.

SMACK and SELinux look safe to me, but somebody else should probably
have a look just in case.

Based on original patch from Vegard Nossum <vegard.nossum@oracle.com>
modified for the case that apparmor provides null termination.

Fixes: bb646cdb12e75d82258c2f2e7746d5952d3e321a
Reported-by: Vegard Nossum <vegard.nossum@oracle.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Stephen Smalley <sds@tycho.nsa.gov>
Cc: Eric Paris <eparis@parisplace.org>
Cc: Casey Schaufler <casey@schaufler-ca.com>
Cc: stable@kernel.org
Signed-off-by: John Johansen <john.johansen@canonical.com>
Reviewed-by: Tyler Hicks <tyhicks@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# 58acf9d9 22-Jun-2016 John Johansen <john.johansen@canonical.com>

apparmor: fix module parameters can be changed after policy is locked

the policy_lock parameter is a one way switch that prevents policy
from being further modified. Unfortunately some of the module parameters
can effectively modify policy by turning off enforcement.

split policy_admin_capable into a view check and a full admin check,
and update the admin check to test the policy_lock parameter.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 6059f71f 24-Oct-2014 John Johansen <john.johansen@canonical.com>

apparmor: add parameter to control whether policy hashing is used

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Tyler Hicks <tyhicks@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# 30a46a46 07-Jul-2016 Vegard Nossum <vegard.nossum@oracle.com>

apparmor: fix oops, validate buffer size in apparmor_setprocattr()

When proc_pid_attr_write() was changed to use memdup_user apparmor's
(interface violating) assumption that the setprocattr buffer was always
a single page was violated.

The size test is not strictly speaking needed as proc_pid_attr_write()
will reject anything larger, but for the sake of robustness we can keep
it in.

SMACK and SELinux look safe to me, but somebody else should probably
have a look just in case.

Based on original patch from Vegard Nossum <vegard.nossum@oracle.com>
modified for the case that apparmor provides null termination.

Fixes: bb646cdb12e75d82258c2f2e7746d5952d3e321a
Reported-by: Vegard Nossum <vegard.nossum@oracle.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Stephen Smalley <sds@tycho.nsa.gov>
Cc: Eric Paris <eparis@parisplace.org>
Cc: Casey Schaufler <casey@schaufler-ca.com>
Cc: stable@kernel.org
Signed-off-by: John Johansen <john.johansen@canonical.com>
Reviewed-by: Tyler Hicks <tyhicks@canonical.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# 3ccee46a 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify security_path_{link,rename}

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 8db01856 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

apparmor: remove useless checks for NULL ->mnt

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# d3607752 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify security_path_{mkdir,mknod,symlink}

... as well as unix_mknod() and may_o_create()

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 989f74e0 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify security_path_{unlink,rmdir}

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# d6b49f7a 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

apparmor: constify common_perm_...()

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 741aca71 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

apparmor: new helper - common_path_perm()

was open-coded in several places...

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# be01f9f2 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify chmod_common/security_path_chmod

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 7fd25dac 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify chown_common/security_path_chown

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 928e1ebf 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

apparmor_path_truncate(): path->mnt is never NULL

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 81f4c506 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

constify security_path_truncate()

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 2c7661ff 25-Mar-2016 Al Viro <viro@zeniv.linux.org.uk>

[apparmor] constify struct path * in a bunch of helpers

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 9c27847d 26-May-2015 Luis R. Rodriguez <mcgrof@suse.com>

kernel/params: constify struct kernel_param_ops uses

Most code already uses consts for the struct kernel_param_ops,
sweep the kernel for the last offending stragglers. Other than
include/linux/moduleparam.h and kernel/params.c all other changes
were generated with the following Coccinelle SmPL patch. Merge
conflicts between trees can be handled with Coccinelle.

In the future git could get Coccinelle merge support to deal with
patch --> fail --> grammar --> Coccinelle --> new patch conflicts
automatically for us on patches where the grammar is available and
the patch is of high confidence. Consider this a feature request.

Test compiled on x86_64 against:

* allnoconfig
* allmodconfig
* allyesconfig

@ const_found @
identifier ops;
@@

const struct kernel_param_ops ops = {
};

@ const_not_found depends on !const_found @
identifier ops;
@@

-struct kernel_param_ops ops = {
+const struct kernel_param_ops ops = {
};

Generated-by: Coccinelle SmPL
Cc: Rusty Russell <rusty@rustcorp.com.au>
Cc: Junio C Hamano <gitster@pobox.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Kees Cook <keescook@chromium.org>
Cc: Tejun Heo <tj@kernel.org>
Cc: Ingo Molnar <mingo@kernel.org>
Cc: cocci@systeme.lip6.fr
Cc: linux-kernel@vger.kernel.org
Signed-off-by: Luis R. Rodriguez <mcgrof@suse.com>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>


# b1d9e6b0 02-May-2015 Casey Schaufler <casey@schaufler-ca.com>

LSM: Switch to lists of hooks

Instead of using a vector of security operations
with explicit, special case stacking of the capability
and yama hooks use lists of hooks with capability and
yama hooks included as appropriate.

The security_operations structure is no longer required.
Instead, there is a union of the function pointers that
allows all the hooks lists to use a common mechanism for
list management while retaining typing. Each module
supplies an array describing the hooks it provides instead
of a sparsely populated security_operations structure.
The description includes the element that gets put on
the hook list, avoiding the issues surrounding individual
element allocation.

The method for registering security modules is changed to
reflect the information available. The method for removing
a module, currently only used by SELinux, has also changed.
It should be generic now, however if there are potential
race conditions based on ordering of hook removal that needs
to be addressed by the calling module.

The security hooks are called from the lists and the first
failure is returned.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Kees Cook <keescook@chromium.org>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# e20b043a 02-May-2015 Casey Schaufler <casey@schaufler-ca.com>

LSM: Add security module hook list heads

Add a list header for each security hook. They aren't used until
later in the patch series. They are grouped together in a structure
so that there doesn't need to be an external address for each.

Macro-ize the initialization of the security_operations
for each security module in anticipation of changing out
the security_operations structure.

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Kees Cook <keescook@chromium.org>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# 3c4ed7bd 02-May-2015 Casey Schaufler <casey@schaufler-ca.com>

LSM: Split security.h

The security.h header file serves two purposes,
interfaces for users of the security modules and
interfaces for security modules. Users of the
security modules don't need to know about what's
in the security_operations structure, so pull it
out into it's own header, lsm_hooks.h

Signed-off-by: Casey Schaufler <casey@schaufler-ca.com>
Acked-by: John Johansen <john.johansen@canonical.com>
Acked-by: Kees Cook <keescook@chromium.org>
Acked-by: Paul Moore <paul@paul-moore.com>
Acked-by: Stephen Smalley <sds@tycho.nsa.gov>
Acked-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# c6f493d6 17-Mar-2015 David Howells <dhowells@redhat.com>

VFS: security/: d_backing_inode() annotations

most of the ->d_inode uses there refer to the same inode IO would
go to, i.e. d_backing_inode()

Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 3f7036a0 08-Mar-2015 Al Viro <viro@zeniv.linux.org.uk>

switch security_inode_getattr() to struct path *

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 7ac2856d 28-Jan-2015 David Howells <dhowells@redhat.com>

Apparmor: mediated_filesystem() should use dentry->d_sb not inode->i_sb

mediated_filesystem() should use dentry->d_sb not dentry->d_inode->i_sb and
should avoid file_inode() also since it is really dealing with the path.

Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 6a4c2643 26-Aug-2014 Jani Nikula <jani.nikula@intel.com>

module: rename KERNEL_PARAM_FL_NOARG to avoid confusion

Make it clear this is about kernel_param_ops, not kernel_param (which
will soon have a flags field of its own). No functional changes.

Cc: Rusty Russell <rusty@rustcorp.com.au>
Cc: Jean Delvare <khali@linux-fr.org>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Li Zhong <zhong@linux.vnet.ibm.com>
Cc: Jon Mason <jon.mason@intel.com>
Cc: Daniel Vetter <daniel.vetter@ffwll.ch>
Signed-off-by: Jani Nikula <jani.nikula@intel.com>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>


# 29707b20 04-Feb-2014 Jingoo Han <jg1.han@samsung.com>

security: replace strict_strto*() with kstrto*()

The usage of strict_strto*() is not preferred, because
strict_strto*() is obsolete. Thus, kstrto*() should be
used.

Signed-off-by: Jingoo Han <jg1.han@samsung.com>
Signed-off-by: James Morris <james.l.morris@oracle.com>


# dd0c6e86 08-Oct-2013 John Johansen <john.johansen@canonical.com>

apparmor: fix capability to not use the current task, during reporting

Mediation is based off of the cred but auditing includes the current
task which may not be related to the actual request.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 5265fc62 20-Aug-2013 Steven Rostedt <rostedt@goodmis.org>

module/lsm: Have apparmor module parameters work with no args

The apparmor module parameters for param_ops_aabool and
param_ops_aalockpolicy are both based off of the param_ops_bool,
and can handle a NULL value passed in as val. Have it enable the
new KERNEL_PARAM_FL_NOARGS flag to allow the parameters to be set
without having to state "=y" or "=1".

Cc: John Johansen <john.johansen@canonical.com>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>


# 0d259f04 10-Jul-2013 John Johansen <john.johansen@canonical.com>

apparmor: add interface files for profiles and namespaces

Add basic interface files to access namespace and profile information.
The interface files are created when a profile is loaded and removed
when the profile or namespace is removed.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 77b071b3 10-Jul-2013 John Johansen <john.johansen@canonical.com>

apparmor: change how profile replacement update is done

remove the use of replaced by chaining and move to profile invalidation
and lookup to handle task replacement.

Replacement chaining can result in large chains of profiles being pinned
in memory when one profile in the chain is use. With implicit labeling
this will be even more of a problem, so move to a direct lookup method.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# c611616c 10-Jul-2013 John Johansen <john.johansen@canonical.com>

apparmor: enable users to query whether apparmor is enabled

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 3eea57c2 27-Feb-2013 John Johansen <john.johansen@canonical.com>

apparmor: fix setprocattr arg processing for onexec

the exec file isn't processing its command arg. It should only set be
responding to a command of exec.

Also cleanup setprocattr some more while we are at it.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 214beaca 27-Feb-2013 John Johansen <john.johansen@canonical.com>

apparmor: localize getting the security context to a few macros

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Seth Arnold <seth.arnold@canonical.com>


# 53fe8b99 21-Feb-2013 John Johansen <john.johansen@canonical.com>

apparmor: fix sparse warnings

Fix a couple of warning reported by sparse

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 4b7c331f 18-Feb-2013 John Johansen <john.johansen@canonical.com>

apparmor: remove "permipc" command

The "permipc" command is unused and unfinished, remove it.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Kees Cook <kees@ubuntu.com>


# 04266236 18-Feb-2013 John Johansen <john.johansen@canonical.com>

apparmor: Remove -W1 warnings

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-By: Steve Beattie <sbeattie@ubuntu.com>


# 496ad9aa 23-Jan-2013 Al Viro <viro@zeniv.linux.org.uk>

new helper: file_inode(file)

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# d2b31ca6 01-Jun-2012 Eric W. Biederman <ebiederm@xmission.com>

userns: Teach security_path_chown to take kuids and kgids

Don't make the security modules deal with raw user space uid and
gids instead pass in a kuid_t and a kgid_t so that security modules
only have to deal with internal kernel uids and gids.

Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: James Morris <james.l.morris@oracle.com>
Cc: John Johansen <john.johansen@canonical.com>
Cc: Kentaro Takeda <takedakn@nttdata.co.jp>
Cc: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp>
Acked-by: Serge Hallyn <serge.hallyn@canonical.com>
Signed-off-by: Eric W. Biederman <ebiederm@xmission.com>


# e5467859 30-May-2012 Al Viro <viro@zeniv.linux.org.uk>

split ->file_mmap() into ->mmap_addr()/->mmap_file()

... i.e. file-dependent and address-dependent checks.

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# d007794a 30-May-2012 Al Viro <viro@zeniv.linux.org.uk>

split cap_mmap_addr() out of cap_file_mmap()

... switch callers.

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 50c205f5 04-Apr-2012 Eric Paris <eparis@redhat.com>

LSM: do not initialize common_audit_data to 0

It isn't needed. If you don't set the type of the data associated with
that type it is a pretty obvious programming bug. So why waste the cycles?

Signed-off-by: Eric Paris <eparis@redhat.com>


# bd5e50f9 04-Apr-2012 Eric Paris <eparis@redhat.com>

LSM: remove the COMMON_AUDIT_DATA_INIT type expansion

Just open code it so grep on the source code works better.

Signed-off-by: Eric Paris <eparis@redhat.com>


# 83d49856 04-Apr-2012 Eric Paris <eparis@redhat.com>

SELinux: rename dentry_open to file_open

dentry_open takes a file, rename it to file_open

Signed-off-by: Eric Paris <eparis@redhat.com>


# 3b3b0e4f 03-Apr-2012 Eric Paris <eparis@redhat.com>

LSM: shrink sizeof LSM specific portion of common_audit_data

Linus found that the gigantic size of the common audit data caused a big
perf hit on something as simple as running stat() in a loop. This patch
requires LSMs to declare the LSM specific portion separately rather than
doing it in a union. Thus each LSM can be responsible for shrinking their
portion and don't have to pay a penalty just because other LSMs have a
bigger space requirement.

Signed-off-by: Eric Paris <eparis@redhat.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 90ab5ee9 12-Jan-2012 Rusty Russell <rusty@rustcorp.com.au>

module_param: make bool parameters really bool (drivers & misc)

module_param(bool) used to counter-intuitively take an int. In
fddd5201 (mid-2009) we allowed bool or int/unsigned int using a messy
trick.

It's time to remove the int/unsigned int option. For this version
it'll simply give a warning, but it'll break next kernel version.

Acked-by: Mauro Carvalho Chehab <mchehab@redhat.com>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>


# cdcf116d 08-Dec-2011 Al Viro <viro@zeniv.linux.org.uk>

switch security_path_chmod() to struct path *

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 6a9de491 02-Jan-2012 Eric Paris <eparis@redhat.com>

capabilities: remove the task from capable LSM hook entirely

The capabilities framework is based around credentials, not necessarily the
current task. Yet we still passed the current task down into LSMs from the
security_capable() LSM hook as if it was a meaningful portion of the security
decision. This patch removes the 'generic' passing of current and instead
forces individual LSMs to use current explicitly if they think it is
appropriate. In our case those LSMs are SELinux and AppArmor.

I believe the AppArmor use of current is incorrect, but that is wholely
unrelated to this patch. This patch does not change what AppArmor does, it
just makes it clear in the AppArmor code that it is doing it.

The SELinux code still uses current in it's audit message, which may also be
wrong and needs further investigation. Again this is NOT a change, it may
have always been wrong, this patch just makes it clear what is happening.

Signed-off-by: Eric Paris <eparis@redhat.com>


# 04fc66e7 21-Nov-2011 Al Viro <viro@zeniv.linux.org.uk>

switch ->path_mknod() to umode_t

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 4572befe 21-Nov-2011 Al Viro <viro@zeniv.linux.org.uk>

switch ->path_mkdir() to umode_t

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# 910f4ece 26-Jul-2011 Al Viro <viro@zeniv.linux.org.uk>

switch security_path_chmod() to umode_t

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>


# b8aa09fd 14-Dec-2011 Rusty Russell <rusty@rustcorp.com.au>

apparmor: fix module parameter handling

The 'aabool' wrappers actually pass off to the 'bool' parse functions,
so you should use the same check function. Similarly for aauint and
uint.

(Note that 'bool' module parameters also allow 'int', which is why you
got away with this, but that's changing very soon.)

Cc: linux-security-module@vger.kernel.org
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Acked-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>


# 25e75dff 25-Jun-2011 John Johansen <john.johansen@canonical.com>

AppArmor: Fix masking of capabilities in complain mode

AppArmor is masking the capabilities returned by capget against the
capabilities mask in the profile. This is wrong, in complain mode the
profile has effectively all capabilities, as the profile restrictions are
not being enforced, merely tested against to determine if an access is
known by the profile.

This can result in the wrong behavior of security conscience applications
like sshd which examine their capability set, and change their behavior
accordingly. In this case because of the masked capability set being
returned sshd fails due to DAC checks, even when the profile is in complain
mode.

Kernels affected: 2.6.36 - 3.0.

Signed-off-by: John Johansen <john.johansen@canonical.com>


# 1780f2d3 08-Jun-2011 John Johansen <john.johansen@canonical.com>

AppArmor: Fix sleep in invalid context from task_setrlimit

Affected kernels 2.6.36 - 3.0

AppArmor may do a GFP_KERNEL memory allocation with task_lock(tsk->group_leader);
held when called from security_task_setrlimit. This will only occur when the
task's current policy has been replaced, and the task's creds have not been
updated before entering the LSM security_task_setrlimit() hook.

BUG: sleeping function called from invalid context at mm/slub.c:847
in_atomic(): 1, irqs_disabled(): 0, pid: 1583, name: cupsd
2 locks held by cupsd/1583:
#0: (tasklist_lock){.+.+.+}, at: [<ffffffff8104dafa>] do_prlimit+0x61/0x189
#1: (&(&p->alloc_lock)->rlock){+.+.+.}, at: [<ffffffff8104db2d>]
do_prlimit+0x94/0x189
Pid: 1583, comm: cupsd Not tainted 3.0.0-rc2-git1 #7
Call Trace:
[<ffffffff8102ebf2>] __might_sleep+0x10d/0x112
[<ffffffff810e6f46>] slab_pre_alloc_hook.isra.49+0x2d/0x33
[<ffffffff810e7bc4>] kmem_cache_alloc+0x22/0x132
[<ffffffff8105b6e6>] prepare_creds+0x35/0xe4
[<ffffffff811c0675>] aa_replace_current_profile+0x35/0xb2
[<ffffffff811c4d2d>] aa_current_profile+0x45/0x4c
[<ffffffff811c4d4d>] apparmor_task_setrlimit+0x19/0x3a
[<ffffffff811beaa5>] security_task_setrlimit+0x11/0x13
[<ffffffff8104db6b>] do_prlimit+0xd2/0x189
[<ffffffff8104dea9>] sys_setrlimit+0x3b/0x48
[<ffffffff814062bb>] system_call_fastpath+0x16/0x1b

Signed-off-by: John Johansen <john.johansen@canonical.com>
Reported-by: Miles Lane <miles.lane@gmail.com>
Cc: stable@kernel.org
Signed-off-by: James Morris <jmorris@namei.org>


# a5b2c5b2 31-May-2011 Kees Cook <keescook@chromium.org>

AppArmor: fix oops in apparmor_setprocattr

When invalid parameters are passed to apparmor_setprocattr a NULL deref
oops occurs when it tries to record an audit message. This is because
it is passing NULL for the profile parameter for aa_audit. But aa_audit
now requires that the profile passed is not NULL.

Fix this by passing the current profile on the task that is trying to
setprocattr.

Signed-off-by: Kees Cook <kees@ubuntu.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Cc: stable@kernel.org
Signed-off-by: James Morris <jmorris@namei.org>


# 3486740a 23-Mar-2011 Serge E. Hallyn <serge@hallyn.com>

userns: security: make capabilities relative to the user namespace

- Introduce ns_capable to test for a capability in a non-default
user namespace.
- Teach cap_capable to handle capabilities in a non-default
user namespace.

The motivation is to get to the unprivileged creation of new
namespaces. It looks like this gets us 90% of the way there, with
only potential uid confusion issues left.

I still need to handle getting all caps after creation but otherwise I
think I have a good starter patch that achieves all of your goals.

Changelog:
11/05/2010: [serge] add apparmor
12/14/2010: [serge] fix capabilities to created user namespaces
Without this, if user serge creates a user_ns, he won't have
capabilities to the user_ns he created. THis is because we
were first checking whether his effective caps had the caps
he needed and returning -EPERM if not, and THEN checking whether
he was the creator. Reverse those checks.
12/16/2010: [serge] security_real_capable needs ns argument in !security case
01/11/2011: [serge] add task_ns_capable helper
01/11/2011: [serge] add nsown_capable() helper per Bastian Blank suggestion
02/16/2011: [serge] fix a logic bug: the root user is always creator of
init_user_ns, but should not always have capabilities to
it! Fix the check in cap_capable().
02/21/2011: Add the required user_ns parameter to security_capable,
fixing a compile failure.
02/23/2011: Convert some macros to functions as per akpm comments. Some
couldn't be converted because we can't easily forward-declare
them (they are inline if !SECURITY, extern if SECURITY). Add
a current_user_ns function so we can use it in capability.h
without #including cred.h. Move all forward declarations
together to the top of the #ifdef __KERNEL__ section, and use
kernel-doc format.
02/23/2011: Per dhowells, clean up comment in cap_capable().
02/23/2011: Per akpm, remove unreachable 'return -EPERM' in cap_capable.

(Original written and signed off by Eric; latest, modified version
acked by him)

[akpm@linux-foundation.org: fix build]
[akpm@linux-foundation.org: export current_user_ns() for ecryptfs]
[serge.hallyn@canonical.com: remove unneeded extra argument in selinux's task_has_capability]
Signed-off-by: Eric W. Biederman <ebiederm@xmission.com>
Signed-off-by: Serge E. Hallyn <serge.hallyn@canonical.com>
Acked-by: "Eric W. Biederman" <ebiederm@xmission.com>
Acked-by: Daniel Lezcano <daniel.lezcano@free.fr>
Acked-by: David Howells <dhowells@redhat.com>
Cc: James Morris <jmorris@namei.org>
Signed-off-by: Serge E. Hallyn <serge.hallyn@canonical.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>


# 1936113c 20-Jan-2011 Shan Wei <shanwei@cn.fujitsu.com>

AppArmor: kill unused macros in lsm.c

Remove unused macros.

Signed-off-by: Shan Wei <shanwei@cn.fujitsu.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>


# a26d279e 10-Nov-2010 wzt.wzt@gmail.com <wzt.wzt@gmail.com>

APPARMOR: Fix memory leak of apparmor_init()

set_init_cxt() allocted sizeof(struct aa_task_cxt) bytes for cxt,
if register_security() failed, it will cause memory leak.

Signed-off-by: Zhitong Wang <zhitong.wangzt@alibaba-inc.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>


# 3a2dc838 06-Sep-2010 John Johansen <john.johansen@canonical.com>

AppArmor: Fix security_task_setrlimit logic for 2.6.36 changes

2.6.36 introduced the abilitiy to specify the task that is having its
rlimits set. Update mediation to ensure that confined tasks can only
set their own group_leader as expected by current policy.

Add TODO note about extending policy to support setting other tasks
rlimits.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>


# 7cb4dc9f 11-Aug-2010 Jiri Slaby <jirislaby@kernel.org>

AppArmor: fix task_setrlimit prototype

After rlimits tree was merged we get the following errors:
security/apparmor/lsm.c:663:2: warning: initialization from incompatible pointer type

It is because AppArmor was merged in the meantime, but uses the old
prototype. So fix it by adding struct task_struct as a first parameter
of apparmor_task_setrlimit.

NOTE that this is ONLY a compilation warning fix (and crashes caused
by that). It needs proper handling in AppArmor depending on who is the
'task'.

Signed-off-by: Jiri Slaby <jslaby@suse.cz>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>


# 101d6c82 01-Aug-2010 Stephen Rothwell <sfr@canb.auug.org.au>

AppArmor: update for module_param_named API change

Fixes these build errors:
security/apparmor/lsm.c:701: error: 'param_ops_aabool' undeclared here (not in a function)
security/apparmor/lsm.c:721: error: 'param_ops_aalockpolicy' undeclared here (not in a function)
security/apparmor/lsm.c:729: error: 'param_ops_aauint' undeclared here (not in a function)

Signed-off-by: Stephen Rothwell <sfr@canb.auug.org.au>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>


# 4d6ec10b 29-Jul-2010 James Morris <jmorris@namei.org>

AppArmor: update path_truncate method to latest version

Remove extraneous path_truncate arguments from the AppArmor hook,
as they've been removed from the LSM API.

Signed-off-by: James Morris <jmorris@namei.org>


# b5e95b48 29-Jul-2010 John Johansen <john.johansen@canonical.com>

AppArmor: LSM interface, and security module initialization

AppArmor hooks to interface with the LSM, module parameters and module
initialization.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Signed-off-by: James Morris <jmorris@namei.org>