aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/security/selinux/ss/policydb.c (follow)
AgeCommit message (Collapse)AuthorFilesLines
2024-02-23selinux: fix style issues in security/selinux/ss/policydb.cPaul Moore1-192/+213
As part of on ongoing effort to perform more automated testing and provide more tools for individual developers to validate their patches before submitting, we are trying to make our code "clang-format clean". My hope is that once we have fixed all of our style "quirks", developers will be able to run clang-format on their patches to help avoid silly formatting problems and ensure their changes fit in well with the rest of the SELinux kernel code. Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-11-21selinux: introduce an initial SID for early boot processesOndrej Mosnacek1-0/+27
Currently, SELinux doesn't allow distinguishing between kernel threads and userspace processes that are started before the policy is first loaded - both get the label corresponding to the kernel SID. The only way a process that persists from early boot can get a meaningful label is by doing a voluntary dyntransition or re-executing itself. Reusing the kernel label for userspace processes is problematic for several reasons: 1. The kernel is considered to be a privileged domain and generally needs to have a wide range of permissions allowed to work correctly, which prevents the policy writer from effectively hardening against early boot processes that might remain running unintentionally after the policy is loaded (they represent a potential extra attack surface that should be mitigated). 2. Despite the kernel being treated as a privileged domain, the policy writer may want to impose certain special limitations on kernel threads that may conflict with the requirements of intentional early boot processes. For example, it is a good hardening practice to limit what executables the kernel can execute as usermode helpers and to confine the resulting usermode helper processes. However, a (legitimate) process surviving from early boot may need to execute a different set of executables. 3. As currently implemented, overlayfs remembers the security context of the process that created an overlayfs mount and uses it to bound subsequent operations on files using this context. If an overlayfs mount is created before the SELinux policy is loaded, these "mounter" checks are made against the kernel context, which may clash with restrictions on the kernel domain (see 2.). To resolve this, introduce a new initial SID (reusing the slot of the former "init" initial SID) that will be assigned to any userspace process started before the policy is first loaded. This is easy to do, as we can simply label any process that goes through the bprm_creds_for_exec LSM hook with the new init-SID instead of propagating the kernel SID from the parent. To provide backwards compatibility for existing policies that are unaware of this new semantic of the "init" initial SID, introduce a new policy capability "userspace_initial_context" and set the "init" SID to the same context as the "kernel" SID unless this capability is set by the policy. Another small backwards compatibility measure is needed in security_sid_to_context_core() for before the initial SELinux policy load - see the code comment for explanation. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Reviewed-by: Stephen Smalley <stephen.smalley.work@gmail.com> [PM: edited comments based on feedback/discussion] Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-11-16selinux: update filenametr_hash() to use full_name_hash()Paul Moore1-9/+2
Using full_name_hash() instead of partial_name_hash() should result in cleaner and better performing code. Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-09-13selinux: improve role transition hashingChristian Göttsche1-1/+1
The number of buckets is calculated by performing a binary AND against the mask of the hash table, which is one less than its size (which is a power of two). This leads to all top bits being discarded, e.g. with the Reference Policy on Debian there exists 376 entries, leading to a size of 512, discarding the top 23 bits. Use jhash to improve the hash table utilization: # current roletr: 376 entries and 124/512 buckets used, longest chain length 8, sum of chain length^2 1496 # patch roletr: 376 entries and 266/512 buckets used, longest chain length 4, sum of chain length^2 646 Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Reviewed-by: Stephen Smalley <stephen.smalley.work@gmail.com> [PM: line wrap in the commit description] Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-09-13selinux: print sum of chain lengths^2 for hash tablesChristian Göttsche1-2/+2
Print the sum of chain lengths squared as a metric for hash tables to provide more insights, similar to avtabs. While on it add a comma in the avtab message to improve readability of the output. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Reviewed-by: Stephen Smalley <stephen.smalley.work@gmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-08-30Merge tag 'selinux-pr-20230829' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinuxLinus Torvalds1-46/+52
Pull selinux updates from Paul Moore: "Thirty three SELinux patches, which is a pretty big number for us, but there isn't really anything scary in here; in fact we actually manage to remove 10 lines of code with this :) - Promote the SELinux DEBUG_HASHES macro to CONFIG_SECURITY_SELINUX_DEBUG The DEBUG_HASHES macro was a buried SELinux specific preprocessor debug macro that was a problem waiting to happen. Promoting the debug macro to a proper Kconfig setting should help both improve the visibility of the feature as well enable improved test coverage. We've moved some additional debug functions under the CONFIG_SECURITY_SELINUX_DEBUG flag and we may see more work in the future. - Emit a pr_notice() message if virtual memory is executable by default As this impacts the SELinux access control policy enforcement, if the system's configuration is such that virtual memory is executable by default we print a single line notice to the console. - Drop avtab_search() in favor of avtab_search_node() Both functions are nearly identical so we removed avtab_search() and converted the callers to avtab_search_node(). - Add some SELinux network auditing helpers The helpers not only reduce a small amount of code duplication, but they provide an opportunity to improve UDP flood performance slightly by delaying initialization of the audit data in some cases. - Convert GFP_ATOMIC allocators to GFP_KERNEL when reading SELinux policy There were two SELinux policy load helper functions that were allocating memory using GFP_ATOMIC, they have been converted to GFP_KERNEL. - Quiet a KMSAN warning in selinux_inet_conn_request() A one-line error path (re)set patch that resolves a KMSAN warning. It is important to note that this doesn't represent a real bug in the current code, but it quiets KMSAN and arguably hardens the code against future changes. - Cleanup the policy capability accessor functions This is a follow-up to the patch which reverted SELinux to using a global selinux_state pointer. This patch cleans up some artifacts of that change and turns each accessor into a one-line READ_ONCE() call into the policy capabilities array. - A number of patches from Christian Göttsche Christian submitted almost two-thirds of the patches in this pull request as he worked to harden the SELinux code against type differences, variable overflows, etc. - Support for separating early userspace from the kernel in policy, with a later revert We did have a patch that added a new userspace initial SID which would allow SELinux to distinguish between early user processes created before the initial policy load and the kernel itself. Unfortunately additional post-merge testing revealed a problematic interaction with an old SELinux userspace on an old version of Ubuntu so we've reverted the patch until we can resolve the compatibility issue. - Remove some outdated comments dealing with LSM hook registration When we removed the runtime disable functionality we forgot to remove some old comments discussing the importance of LSM hook registration ordering. - Minor administrative changes Stephen Smalley updated his email address and "debranded" SELinux from "NSA SELinux" to simply "SELinux". We've come a long way from the original NSA submission and I would consider SELinux a true community project at this point so removing the NSA branding just makes sense" * tag 'selinux-pr-20230829' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux: (33 commits) selinux: prevent KMSAN warning in selinux_inet_conn_request() selinux: use unsigned iterator in nlmsgtab code selinux: avoid implicit conversions in policydb code selinux: avoid implicit conversions in selinuxfs code selinux: make left shifts well defined selinux: update type for number of class permissions in services code selinux: avoid implicit conversions in avtab code selinux: revert SECINITSID_INIT support selinux: use GFP_KERNEL while reading binary policy selinux: update comment on selinux_hooks[] selinux: avoid implicit conversions in services code selinux: avoid implicit conversions in mls code selinux: use identical iterator type in hashtab_duplicate() selinux: move debug functions into debug configuration selinux: log about VM being executable by default selinux: fix a 0/NULL mistmatch in ad_net_init_from_iif() selinux: introduce SECURITY_SELINUX_DEBUG configuration selinux: introduce and use lsm_ad_net_init*() helpers selinux: update my email address selinux: add missing newlines in pr_err() statements ...
2023-08-18selinux: set next pointer before attaching to listChristian Göttsche1-1/+1
Set the next pointer in filename_trans_read_helper() before attaching the new node under construction to the list, otherwise garbage would be dereferenced on subsequent failure during cleanup in the out goto label. Cc: <stable@vger.kernel.org> Fixes: 430059024389 ("selinux: implement new format of filename transitions") Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-08-09selinux: avoid implicit conversions in policydb codeChristian Göttsche1-32/+37
Use the identical type for local variables, e.g. loop counters. Declare members of struct policydb_compat_info unsigned to consistently use unsigned iterators. They hold read-only non-negative numbers in the global variable policydb_compat. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-08-09selinux: revert SECINITSID_INIT supportPaul Moore1-27/+0
This commit reverts 5b0eea835d4e ("selinux: introduce an initial SID for early boot processes") as it was found to cause problems on distros with old SELinux userspace tools/libraries, specifically Ubuntu 16.04. Hopefully we will be able to re-add this functionality at a later date, but let's revert this for now to help ensure a stable and backwards compatible SELinux tree. Link: https://lore.kernel.org/selinux/87edkseqf8.fsf@mail.lhotse Acked-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-08-08selinux: use GFP_KERNEL while reading binary policyChristian Göttsche1-5/+5
Use GFP_KERNEL instead of GFP_ATOMIC while reading a binary policy in sens_read() and cat_read(), similar to surrounding code. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-07-28selinux: move debug functions into debug configurationChristian Göttsche1-2/+3
avtab_hash_eval() and hashtab_stat() are only used in policydb.c when the configuration SECURITY_SELINUX_DEBUG is enabled. Move the function definitions under that configuration as well and provide empty definitions in case SECURITY_SELINUX_DEBUG is disabled, to avoid using #ifdef in the callers. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-07-20selinux: introduce SECURITY_SELINUX_DEBUG configurationChristian Göttsche1-4/+4
The policy database code contains several debug output statements related to hashtable utilization. Those are guarded by the macro DEBUG_HASHES, which is neither documented nor set anywhere. Introduce a new Kconfig configuration guarding this and potential other future debugging related code. Disable the setting by default. Suggested-by: Paul Moore <paul@paul-moore.com> Signed-off-by: Christian Göttsche <cgzones@googlemail.com> [PM: fixed line lengths in the help text] Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-07-19selinux: update my email addressStephen Smalley1-1/+1
Update my email address; MAINTAINERS was updated some time ago. Signed-off-by: Stephen Smalley <stephen.smalley.work@gmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-07-19selinux: add missing newlines in pr_err() statementsChristian Göttsche1-3/+3
The kernel print statements do not append an implicit newline to format strings. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> [PM: subject line tweak] Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-07-10selinux: introduce an initial SID for early boot processesOndrej Mosnacek1-0/+27
Currently, SELinux doesn't allow distinguishing between kernel threads and userspace processes that are started before the policy is first loaded - both get the label corresponding to the kernel SID. The only way a process that persists from early boot can get a meaningful label is by doing a voluntary dyntransition or re-executing itself. Reusing the kernel label for userspace processes is problematic for several reasons: 1. The kernel is considered to be a privileged domain and generally needs to have a wide range of permissions allowed to work correctly, which prevents the policy writer from effectively hardening against early boot processes that might remain running unintentionally after the policy is loaded (they represent a potential extra attack surface that should be mitigated). 2. Despite the kernel being treated as a privileged domain, the policy writer may want to impose certain special limitations on kernel threads that may conflict with the requirements of intentional early boot processes. For example, it is a good hardening practice to limit what executables the kernel can execute as usermode helpers and to confine the resulting usermode helper processes. However, a (legitimate) process surviving from early boot may need to execute a different set of executables. 3. As currently implemented, overlayfs remembers the security context of the process that created an overlayfs mount and uses it to bound subsequent operations on files using this context. If an overlayfs mount is created before the SELinux policy is loaded, these "mounter" checks are made against the kernel context, which may clash with restrictions on the kernel domain (see 2.). To resolve this, introduce a new initial SID (reusing the slot of the former "init" initial SID) that will be assigned to any userspace process started before the policy is first loaded. This is easy to do, as we can simply label any process that goes through the bprm_creds_for_exec LSM hook with the new init-SID instead of propagating the kernel SID from the parent. To provide backwards compatibility for existing policies that are unaware of this new semantic of the "init" initial SID, introduce a new policy capability "userspace_initial_context" and set the "init" SID to the same context as the "kernel" SID unless this capability is set by the policy. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-05-23selinux: deprecated fs oconChristian Göttsche1-0/+4
The object context type `fs`, not to be confused with the well used object context type `fscon`, was introduced in the initial git commit 1da177e4c3f4 ("Linux-2.6.12-rc2") but never actually used since. The paper "A Security Policy Configuration for the Security-Enhanced Linux" [1] mentions it under `7.2 File System Contexts` but also states: Currently, this configuration is unused. The policy statement defining such object contexts is `fscon`, e.g.: fscon 2 3 gen_context(system_u:object_r:conA_t,s0) \ gen_context(system_u:object_r:conB_t,s0) It is not documented at selinuxproject.org or in the SELinux notebook and not supported by the Reference Policy buildsystem - the statement is not properly sorted - and thus not used in the Reference or Fedora Policy. Print a warning message at policy load for each such object context: SELinux: void and deprecated fs ocon 02:03 This topic was initially highlighted by Nicolas Iooss [2]. [1]: https://media.defense.gov/2021/Jul/29/2002815735/-1/-1/0/SELINUX-SECURITY-POLICY-CONFIGURATION-REPORT.PDF [2]: https://lore.kernel.org/selinux/CAJfZ7=mP2eJaq2BfO3y0VnwUJaY2cS2p=HZMN71z1pKjzaT0Eg@mail.gmail.com/ Signed-off-by: Christian Göttsche <cgzones@googlemail.com> [PM: tweaked deprecation comment, description line wrapping] Signed-off-by: Paul Moore <paul@paul-moore.com>
2023-05-08selinux: declare read-only data arrays constChristian Göttsche1-1/+1
The array of mount tokens in only used in match_opt_prefix() and never modified. The array of symtab names is never modified and only used in the DEBUG_HASHES configuration as output. The array of files for the SElinux filesystem sub-directory `ss` is similar to the other `struct tree_descr` usages only read from to construct the containing entries. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2022-05-03selinux: declare data arrays constChristian Göttsche1-17/+15
The arrays for the policy capability names, the initial sid identifiers and the class and permission names are not changed at runtime. Declare them const to avoid accidental modification. Do not override the classmap and the initial sid list in the build time script genheaders. Check flose(3) is successful in genheaders.c, otherwise the written data might be corrupted or incomplete. Signed-off-by: Christian Göttsche <cgzones@googlemail.com> [PM: manual merge due to fuzz, minor style tweaks] Signed-off-by: Paul Moore <paul@paul-moore.com>
2022-05-03selinux: resolve checkpatch errorsChristian Göttsche1-8/+4
Reported by checkpatch: security/selinux/nlmsgtab.c --------------------------- ERROR: that open brace { should be on the previous line #29: FILE: security/selinux/nlmsgtab.c:29: +static const struct nlmsg_perm nlmsg_route_perms[] = +{ ERROR: that open brace { should be on the previous line #97: FILE: security/selinux/nlmsgtab.c:97: +static const struct nlmsg_perm nlmsg_tcpdiag_perms[] = +{ ERROR: that open brace { should be on the previous line #105: FILE: security/selinux/nlmsgtab.c:105: +static const struct nlmsg_perm nlmsg_xfrm_perms[] = +{ ERROR: that open brace { should be on the previous line #134: FILE: security/selinux/nlmsgtab.c:134: +static const struct nlmsg_perm nlmsg_audit_perms[] = +{ security/selinux/ss/policydb.c ------------------------------ ERROR: that open brace { should be on the previous line #318: FILE: security/selinux/ss/policydb.c:318: +static int (*destroy_f[SYM_NUM]) (void *key, void *datum, void *datap) = +{ ERROR: that open brace { should be on the previous line #674: FILE: security/selinux/ss/policydb.c:674: +static int (*index_f[SYM_NUM]) (void *key, void *datum, void *datap) = +{ ERROR: that open brace { should be on the previous line #1643: FILE: security/selinux/ss/policydb.c:1643: +static int (*read_f[SYM_NUM]) (struct policydb *p, struct symtab *s, void *fp) = +{ ERROR: that open brace { should be on the previous line #3246: FILE: security/selinux/ss/policydb.c:3246: + void *datap) = +{ Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2022-01-26selinux: drop unused macroChristian Göttsche1-2/+0
The macro _DEBUG_HASHES is nowhere used. The configuration DEBUG_HASHES enables debugging of the SELinux hash tables, but the with an underscore prefixed macro definition has no direct impact or any documentation. Reported by clang [-Wunused-macros] Signed-off-by: Christian Göttsche <cgzones@googlemail.com> Reviewed-by: Nick Desaulniers <ndesaulniers@google.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2022-01-26selinux: declare name parameter of hash_eval constChristian Göttsche1-1/+1
String literals are passed as second argument to hash_eval(). Also the parameter is already declared const in the DEBUG_HASHES configuration. Reported by clang [-Wwrite-strings]: security/selinux/ss/policydb.c:1881:26: error: passing 'const char [8]' to parameter of type 'char *' discards qualifiers hash_eval(&p->range_tr, rangetr); ^~~~~~~~~ security/selinux/ss/policydb.c:707:55: note: passing argument to parameter 'hash_name' here static inline void hash_eval(struct hashtab *h, char *hash_name) ^ security/selinux/ss/policydb.c:2099:32: error: passing 'const char [11]' to parameter of type 'char *' discards qualifiers hash_eval(&p->filename_trans, filenametr); ^~~~~~~~~~~~ security/selinux/ss/policydb.c:707:55: note: passing argument to parameter 'hash_name' here static inline void hash_eval(struct hashtab *h, char *hash_name) ^ Signed-off-by: Christian Göttsche <cgzones@googlemail.com> [PM: line wrapping in description] Signed-off-by: Paul Moore <paul@paul-moore.com>
2021-08-02selinux: correct the return value when loads initial sidsXiu Jianfeng1-6/+4
It should not return 0 when SID 0 is assigned to isids. This patch fixes it. Cc: stable@vger.kernel.org Fixes: e3e0b582c321a ("selinux: remove unused initial SIDs and improve handling") Signed-off-by: Xiu Jianfeng <xiujianfeng@huawei.com> [PM: remove changelog from description] Signed-off-by: Paul Moore <paul@paul-moore.com>
2021-05-10selinux: Remove redundant assignment to rcJiapeng Chong1-1/+0
Variable rc is set to '-EINVAL' but this value is never read as it is overwritten or not used later on, hence it is a redundant assignment and can be removed. Cleans up the following clang-analyzer warning: security/selinux/ss/services.c:2103:3: warning: Value stored to 'rc' is never read [clang-analyzer-deadcode.DeadStores]. security/selinux/ss/services.c:2079:2: warning: Value stored to 'rc' is never read [clang-analyzer-deadcode.DeadStores]. security/selinux/ss/services.c:2071:2: warning: Value stored to 'rc' is never read [clang-analyzer-deadcode.DeadStores]. security/selinux/ss/services.c:2062:2: warning: Value stored to 'rc' is never read [clang-analyzer-deadcode.DeadStores]. security/selinux/ss/policydb.c:2592:3: warning: Value stored to 'rc' is never read [clang-analyzer-deadcode.DeadStores]. Reported-by: Abaci Robot <abaci@linux.alibaba.com> Signed-off-by: Jiapeng Chong <jiapeng.chong@linux.alibaba.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-07-09selinux: prepare for inlining of hashtab functionsOndrej Mosnacek1-22/+54
Refactor searching and inserting into hashtabs to pave the way for converting hashtab_search() and hashtab_insert() to inline functions in the next patch. This will avoid indirect calls and allow the compiler to better optimize individual callers, leading to a significant performance improvement. In order to avoid the indirect calls, the key hashing and comparison callbacks need to be extracted from the hashtab struct and passed directly to hashtab_search()/_insert() by the callers so that the callback address is always known at compile time. The kernel's rhashtable library (<linux/rhashtable*.h>) does the same thing. This of course makes the hashtab functions slightly easier to misuse by passing a wrong callback set, but unfortunately there is no better way to implement a hash table that is both generic and efficient in C. This patch tries to somewhat mitigate this by only calling the hashtab functions in the same file where the corresponding callbacks are defined (wrapping them into more specialized functions as needed). Note that this patch doesn't bring any benefit without also moving the definitions of hashtab_search() and -_insert() to the header file, which is done in a follow-up patch for easier review of the hashtab.c changes in this patch. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-07-08selinux: specialize symtab insert and search functionsOndrej Mosnacek1-26/+26
This encapsulates symtab a little better and will help with further refactoring later. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <stephen.smalley.work@gmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-06-23selinux: log error messages on required process class / permissionsStephen Smalley1-5/+15
In general SELinux no longer treats undefined object classes or permissions in the policy as a fatal error, instead handling them in accordance with handle_unknown. However, the process class and process transition and dyntransition permissions are still required to be defined due to dependencies on these definitions for default labeling behaviors, role and range transitions in older policy versions that lack an explicit class field, and role allow checking. Log error messages in these cases since otherwise the policy load will fail silently with no indication to the user as to the underlying cause. While here, fix the checking for process transition / dyntransition so that omitting either permission is handled as an error; both are needed in order to ensure that role allow checking is consistently applied. Reported-by: bauen1 <j2468h@googlemail.com> Signed-off-by: Stephen Smalley <stephen.smalley.work@gmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-06-02Merge tag 'selinux-pr-20200601' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinuxLinus Torvalds1-136/+315
Pull SELinux updates from Paul Moore: "The highlights: - A number of improvements to various SELinux internal data structures to help improve performance. We move the role transitions into a hash table. In the content structure we shift from hashing the content string (aka SELinux label) to the structure itself, when it is valid. This last change not only offers a speedup, but it helps us simplify the code some as well. - Add a new SELinux policy version which allows for a more space efficient way of storing the filename transitions in the binary policy. Given the default Fedora SELinux policy with the unconfined module enabled, this change drops the policy size from ~7.6MB to ~3.3MB. The kernel policy load time dropped as well. - Some fixes to the error handling code in the policy parser to properly return error codes when things go wrong" * tag 'selinux-pr-20200601' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux: selinux: netlabel: Remove unused inline function selinux: do not allocate hashtabs dynamically selinux: fix return value on error in policydb_read() selinux: simplify range_write() selinux: fix error return code in policydb_read() selinux: don't produce incorrect filename_trans_count selinux: implement new format of filename transitions selinux: move context hashing under sidtab selinux: hash context structure directly selinux: store role transitions in a hash table selinux: drop unnecessary smp_load_acquire() call selinux: fix warning Comparison to bool
2020-05-01selinux: do not allocate hashtabs dynamicallyOndrej Mosnacek1-67/+60
It is simpler to allocate them statically in the corresponding structure, avoiding unnecessary kmalloc() calls and pointer dereferencing. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> [PM: manual merging required in policydb.c] Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-05-01selinux: fix return value on error in policydb_read()Ondrej Mosnacek1-0/+1
The value of rc is still zero from the last assignment when the error path is taken. Fix it by setting it to -ENOMEM before the hashtab_create() call. Reported-by: Dan Carpenter <dan.carpenter@oracle.com> Fixes: e67b2ec9f617 ("selinux: store role transitions in a hash table") Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-05-01selinux: simplify range_write()Ondrej Mosnacek1-16/+2
No need to traverse the hashtab to count its elements, hashtab already tracks it for us. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-05-01selinux: fix error return code in policydb_read()Wei Yongjun1-0/+1
Fix to return negative error code -ENOMEM from the kvcalloc() error handling case instead of 0, as done elsewhere in this function. Fixes: acdf52d97f82 ("selinux: convert to kvmalloc") Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-22selinux: don't produce incorrect filename_trans_countOndrej Mosnacek1-8/+3
I thought I fixed the counting in filename_trans_read_helper() to count the compat rule count correctly in the final version, but it's still wrong. To really count the same thing as in the compat path, we'd need to add up the cardinalities of stype bitmaps of all datums. Since the kernel currently doesn't implement an ebitmap_cardinality() function (and computing the proper count would just waste CPU cycles anyway), just document that we use the field only in case of the old format and stop updating it in filename_trans_read_helper(). Fixes: 430059024389 ("selinux: implement new format of filename transitions") Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-17selinux: implement new format of filename transitionsOndrej Mosnacek1-25/+187
Implement a new, more space-efficient way of storing filename transitions in the binary policy. The internal structures have already been converted to this new representation; this patch just implements reading/writing an equivalent represntation from/to the binary policy. This new format reduces the size of Fedora policy from 7.6 MB to only 3.3 MB (with policy optimization enabled in both cases). With the unconfined module disabled, the size is reduced from 3.3 MB to 2.4 MB. The time to load policy into kernel is also shorter with the new format. On Fedora Rawhide x86_64 it dropped from 157 ms to 106 ms; without the unconfined module from 115 ms to 105 ms. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-17selinux: move context hashing under sidtabOndrej Mosnacek1-2/+0
Now that context hash computation no longer depends on policydb, we can simplify things by moving the context hashing completely under sidtab. The hash is still cached in sidtab entries, but not for the in-flight context structures. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-17selinux: hash context structure directlyOndrej Mosnacek1-5/+2
Always hashing the string representation is inefficient. Just hash the contents of the structure directly (using jhash). If the context is invalid (str & len are set), then hash the string as before, otherwise hash the structured data. Since the context hashing function is now faster (about 10 times), this patch decreases the overhead of security_transition_sid(), which is called from many hooks. The jhash function seemed as a good choice, since it is used as the default hashing algorithm in rhashtable. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Reviewed-by: Jeff Vander Stoep <jeffv@google.com> Tested-by: Jeff Vander Stoep <jeffv@google.com> [PM: fixed some spelling errors in the comments pointed out by JVS] Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-17selinux: store role transitions in a hash tableOndrej Mosnacek1-46/+92
Currently, they are stored in a linked list, which adds significant overhead to security_transition_sid(). On Fedora, with 428 role transitions in policy, converting this list to a hash table cuts down its run time by about 50%. This was measured by running 'stress-ng --msg 1 --msg-ops 100000' under perf with and without this patch. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-04-15selinux: free str on error in str_read()Ondrej Mosnacek1-4/+4
In [see "Fixes:"] I missed the fact that str_read() may give back an allocated pointer even if it returns an error, causing a potential memory leak in filename_trans_read_one(). Fix this by making the function free the allocated string whenever it returns a non-zero value, which also makes its behavior more obvious and prevents repeating the same mistake in the future. Reported-by: coverity-bot <keescook+coverity-bot@chromium.org> Addresses-Coverity-ID: 1461665 ("Resource leaks") Fixes: c3a276111ea2 ("selinux: optimize storage of filename transitions") Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Reviewed-by: Kees Cook <keescook@chromium.org> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-03-30selinux: clean up indentation issue with assignment statementColin Ian King1-4/+3
The assignment of e->type_names is indented one level too deep, clean this up by removing the extraneous tab. Signed-off-by: Colin Ian King <colin.king@canonical.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-03-05selinux: avtab_init() and cond_policydb_init() return voidPaul Moore1-9/+2
The avtab_init() and cond_policydb_init() functions always return zero so mark them as returning void and update the callers not to check for a return value. Suggested-by: Stephen Smalley <stephen.smalley.work@gmail.com> Reviewed-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-03-05selinux: clean up error path in policydb_init()Ondrej Mosnacek1-13/+5
Commit e0ac568de1fa ("selinux: reduce the use of hard-coded hash sizes") moved symtab initialization out of policydb_init(), but left the cleanup of symtabs from the error path. This patch fixes the oversight. Suggested-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-02-27selinux: remove unused initial SIDs and improve handlingStephen Smalley1-13/+12
Remove initial SIDs that have never been used or are no longer used by the kernel from its string table, which is also used to generate the SECINITSID_* symbols referenced in code. Update the code to gracefully handle the fact that these can now be NULL. Stop treating it as an error if a policy defines additional initial SIDs unknown to the kernel. Do not load unused initial SID contexts into the sidtab. Fix the incorrect usage of the name from the ocontext in error messages when loading initial SIDs since these are not presently written to the kernel policy and are therefore always NULL. After this change, it is possible to safely reclaim and reuse some of the unused initial SIDs without compatibility issues. Specifically, unused initial SIDs that were being assigned the same context as the unlabeled initial SID in policies can be reclaimed and reused for another purpose, with existing policies still treating them as having the unlabeled context and future policies having the option of mapping them to a more specific context. For example, this could have been used when the infiniband labeling support was introduced to define initial SIDs for the default pkey and endport SIDs similar to the handling of port/netif/node SIDs rather than always using SECINITSID_UNLABELED as the default. The set of safely reclaimable unused initial SIDs across all known policies is igmp_packet (13), icmp_socket (14), tcp_socket (15), kmod (24), policy (25), and scmp_packet (26); these initial SIDs were assigned the same context as unlabeled in all known policies including mls. If only considering non-mls policies (i.e. assuming that mls users always upgrade policy with their kernels), the set of safely reclaimable unused initial SIDs further includes file_labels (6), init (7), sysctl_modprobe (16), and sysctl_fs (18) through sysctl_dev (23). Adding new initial SIDs beyond SECINITSID_NUM to policy unfortunately became a fatal error in commit 24ed7fdae669 ("selinux: use separate table for initial SID lookup") and even before that it could cause problems on a policy reload (collision between the new initial SID and one allocated at runtime) ever since commit 42596eafdd75 ("selinux: load the initial SIDs upon every policy load") so we cannot safely start adding new initial SIDs to policies beyond SECINITSID_NUM (27) until such a time as all such kernels do not need to be supported and only those that include this commit are relevant. That is not a big deal since we haven't added a new initial SID since 2004 (v2.6.7) and we have plenty of unused ones we can reclaim if we truly need one. If we want to avoid the wasted storage in initial_sid_to_string[] and/or sidtab->isids[] for the unused initial SIDs, we could introduce an indirection between the kernel initial SID values and the policy initial SID values and just map the policy SID values in the ocontexts to the kernel values during policy_load_isids(). Originally I thought we'd do this by preserving the initial SID names in the kernel policy and creating a mapping at load time like we do for the security classes and permissions but that would require a new kernel policy format version and associated changes to libsepol/checkpolicy and I'm not sure it is justified. Simpler approach is just to create a fixed mapping table in the kernel from the existing fixed policy values to the kernel values. Less flexible but probably sufficient. A separate selinux userspace change was applied in https://github.com/SELinuxProject/selinux/commit/8677ce5e8f592950ae6f14cea1b68a20ddc1ac25 to enable removal of most of the unused initial SID contexts from policies, but there is no dependency between that change and this one. That change permits removing all of the unused initial SID contexts from policy except for the fs and sysctl SID contexts. The initial SID declarations themselves would remain in policy to preserve the values of subsequent ones but the contexts can be dropped. If/when the kernel decides to reuse one of them, future policies can change the name and start assigning a context again without breaking compatibility. Here is how I would envision staging changes to the initial SIDs in a compatible manner after this commit is applied: 1. At any time after this commit is applied, the kernel could choose to reclaim one of the safely reclaimable unused initial SIDs listed above for a new purpose (i.e. replace its NULL entry in the initial_sid_to_string[] table with a new name and start using the newly generated SECINITSID_name symbol in code), and refpolicy could at that time rename its declaration of that initial SID to reflect its new purpose and start assigning it a context going forward. Existing/old policies would map the reclaimed initial SID to the unlabeled context, so that would be the initial default behavior until policies are updated. This doesn't depend on the selinux userspace change; it will work with existing policies and userspace. 2. In 6 months or so we'll have another SELinux userspace release that will include the libsepol/checkpolicy support for omitting unused initial SID contexts. 3. At any time after that release, refpolicy can make that release its minimum build requirement and drop the sid context statements (but not the sid declarations) for all of the unused initial SIDs except for fs and sysctl, which must remain for compatibility on policy reload with old kernels and for compatibility with kernels that were still using SECINITSID_SYSCTL (< 2.6.39). This doesn't depend on this kernel commit; it will work with previous kernels as well. 4. After N years for some value of N, refpolicy decides that it no longer cares about policy reload compatibility for kernels that predate this kernel commit, and refpolicy drops the fs and sysctl SID contexts from policy too (but retains the declarations). 5. After M years for some value of M, the kernel decides that it no longer cares about compatibility with refpolicies that predate step 4 (dropping the fs and sysctl SIDs), and those two SIDs also become safely reclaimable. This step is optional and need not ever occur unless we decide that the need to reclaim those two SIDs outweighs the compatibility cost. 6. After O years for some value of O, refpolicy decides that it no longer cares about policy load (not just reload) compatibility for kernels that predate this kernel commit, and both kernel and refpolicy can then start adding and using new initial SIDs beyond 27. This does not depend on the previous change (step 5) and can occur independent of it. Fixes: https://github.com/SELinuxProject/selinux-kernel/issues/12 Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-02-27selinux: reduce the use of hard-coded hash sizesOndrej Mosnacek1-33/+20
Instead allocate hash tables with just the right size based on the actual number of elements (which is almost always known beforehand, we just need to defer the hashtab allocation to the right time). The only case when we don't know the size (with the current policy format) is the new filename transitions hashtable. Here I just left the existing value. After this patch, the time to load Fedora policy on x86_64 decreases from 790 ms to 167 ms. If the unconfined module is removed, it decreases from 750 ms to 122 ms. It is also likely that other operations are going to be faster, mainly string_to_context_struct() or mls_compute_sid(), but I didn't try to quantify that. The memory usage of all hash table arrays increases from ~58 KB to ~163 KB (with Fedora policy on x86_64). Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-02-22selinux: optimize storage of filename transitionsOndrej Mosnacek1-71/+95
In these rules, each rule with the same (target type, target class, filename) values is (in practice) always mapped to the same result type. Therefore, it is much more efficient to group the rules by (ttype, tclass, filename). Thus, this patch drops the stype field from the key and changes the datum to be a linked list of one or more structures that contain a result type and an ebitmap of source types that map the given target to the given result type under the given filename. The size of the hash table is also incremented to 2048 to be more optimal for Fedora policy (which currently has ~2500 unique (ttype, tclass, filename) tuples, regardless of whether the 'unconfined' module is enabled). Not only does this dramtically reduce memory usage when the policy contains a lot of unconfined domains (ergo a lot of filename based transitions), but it also slightly reduces memory usage of strongly confined policies (modeled on Fedora policy with 'unconfined' module disabled) and significantly reduces lookup times of these rules on Fedora (roughly matches the performance of the rhashtable conversion patch [1] posted recently to selinux@vger.kernel.org). An obvious next step is to change binary policy format to match this layout, so that disk space is also saved. However, since that requires more work (including matching userspace changes) and this patch is already beneficial on its own, I'm posting it separately. Performance/memory usage comparison: Kernel | Policy load | Policy load | Mem usage | Mem usage | openbench | | (-unconfined) | | (-unconfined) | (createfiles) -----------------|-------------|---------------|-----------|---------------|-------------- reference | 1,30s | 0,91s | 90MB | 77MB | 55 us/file rhashtable patch | 0.98s | 0,85s | 85MB | 75MB | 38 us/file this patch | 0,95s | 0,87s | 75MB | 75MB | 40 us/file (Memory usage is measured after boot. With SELinux disabled the memory usage was ~60MB on the same system.) [1] https://lore.kernel.org/selinux/20200116213937.77795-1-dev@lynxeye.de/T/ Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-02-13selinux: factor out loop body from filename_trans_read()Ondrej Mosnacek1-59/+63
It simplifies cleanup in the error path. This will be extra useful in later patch. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Acked-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-02-11selinux: convert cond_list to arrayOndrej Mosnacek1-1/+1
Since it is fixed-size after allocation and we know the size beforehand, using a plain old array is simpler and more efficient. While there, also fix signedness of some related variables/parameters. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2020-01-16selinux: fix wrong buffer types in policydb.cOndrej Mosnacek1-2/+2
Two places used u32 where there should have been __le32. Fixes sparse warnings: CHECK [...]/security/selinux/ss/services.c [...]/security/selinux/ss/policydb.c:2669:16: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2669:16: expected unsigned int [...]/security/selinux/ss/policydb.c:2669:16: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2674:24: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2674:24: expected unsigned int [...]/security/selinux/ss/policydb.c:2674:24: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2675:24: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2675:24: expected unsigned int [...]/security/selinux/ss/policydb.c:2675:24: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2676:24: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2676:24: expected unsigned int [...]/security/selinux/ss/policydb.c:2676:24: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2681:32: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2681:32: expected unsigned int [...]/security/selinux/ss/policydb.c:2681:32: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2701:16: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2701:16: expected unsigned int [...]/security/selinux/ss/policydb.c:2701:16: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2706:24: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2706:24: expected unsigned int [...]/security/selinux/ss/policydb.c:2706:24: got restricted __le32 [usertype] [...]/security/selinux/ss/policydb.c:2707:24: warning: incorrect type in assignment (different base types) [...]/security/selinux/ss/policydb.c:2707:24: expected unsigned int [...]/security/selinux/ss/policydb.c:2707:24: got restricted __le32 [usertype] Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Reviewed-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-12-09selinux: sidtab reverse lookup hash tableJeff Vander Stoep1-0/+5
This replaces the reverse table lookup and reverse cache with a hashtable which improves cache-miss reverse-lookup times from O(n) to O(1)* and maintains the same performance as a reverse cache hit. This reduces the time needed to add a new sidtab entry from ~500us to 5us on a Pixel 3 when there are ~10,000 sidtab entries. The implementation uses the kernel's generic hashtable API, It uses the context's string represtation as the hash source, and the kernels generic string hashing algorithm full_name_hash() to reduce the string to a 32 bit value. This change also maintains the improvement introduced in commit ee1a84fdfeed ("selinux: overhaul sidtab to fix bug and improve performance") which removed the need to keep the current sidtab locked during policy reload. It does however introduce periodic locking of the target sidtab while converting the hashtable. Sidtab entries are never modified or removed, so the context struct stored in the sid_to_context tree can also be used for the context_to_sid hashtable to reduce memory usage. This bug was reported by: - On the selinux bug tracker. BUG: kernel softlockup due to too many SIDs/contexts #37 https://github.com/SELinuxProject/selinux-kernel/issues/37 - Jovana Knezevic on Android's bugtracker. Bug: 140252993 "During multi-user performance testing, we create and remove users many times. selinux_android_restorecon_pkgdir goes from 1ms to over 20ms after about 200 user creations and removals. Accumulated over ~280 packages, that adds a significant time to user creation, making perf benchmarks unreliable." * Hashtable lookup is only O(1) when n < the number of buckets. Signed-off-by: Jeff Vander Stoep <jeffv@google.com> Reported-by: Stephen Smalley <sds@tycho.nsa.gov> Reported-by: Jovana Knezevic <jovanak@google.com> Reviewed-by: Stephen Smalley <sds@tycho.nsa.gov> Tested-by: Stephen Smalley <sds@tycho.nsa.gov> [PM: subj tweak, removed changelog from patch description] Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-10-07selinux: default_range glblub implementationJoshua Brindle1-0/+5
A policy developer can now specify glblub as a default_range default and the computed transition will be the intersection of the mls range of the two contexts. The glb (greatest lower bound) lub (lowest upper bound) of a range is calculated as the greater of the low sensitivities and the lower of the high sensitivities and the and of each category bitmap. This can be used by MLS solution developers to compute a context that satisfies, for example, the range of a network interface and the range of a user logging in. Some examples are: User Permitted Range | Network Device Label | Computed Label ---------------------|----------------------|---------------- s0-s1:c0.c12 | s0 | s0 s0-s1:c0.c12 | s0-s1:c0.c1023 | s0-s1:c0.c12 s0-s4:c0.c512 | s1-s1:c0.c1023 | s1-s1:c0.c512 s0-s15:c0,c2 | s4-s6:c0.c128 | s4-s6:c0,c2 s0-s4 | s2-s6 | s2-s4 s0-s4 | s5-s8 | INVALID s5-s8 | s0-s4 | INVALID Signed-off-by: Joshua Brindle <joshua.brindle@crunchydata.com> [PM: subject lines and checkpatch.pl fixes] Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-09-23Merge tag 'selinux-pr-20190917' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinuxLinus Torvalds1-200/+202
Pull selinux updates from Paul Moore: - Add LSM hooks, and SELinux access control hooks, for dnotify, fanotify, and inotify watches. This has been discussed with both the LSM and fs/notify folks and everybody is good with these new hooks. - The LSM stacking changes missed a few calls to current_security() in the SELinux code; we fix those and remove current_security() for good. - Improve our network object labeling cache so that we always return the object's label, even when under memory pressure. Previously we would return an error if we couldn't allocate a new cache entry, now we always return the label even if we can't create a new cache entry for it. - Convert the sidtab atomic_t counter to a normal u32 with READ/WRITE_ONCE() and memory barrier protection. - A few patches to policydb.c to clean things up (remove forward declarations, long lines, bad variable names, etc) * tag 'selinux-pr-20190917' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux: lsm: remove current_security() selinux: fix residual uses of current_security() for the SELinux blob selinux: avoid atomic_t usage in sidtab fanotify, inotify, dnotify, security: add security hook for fs notifications selinux: always return a secid from the network caches if we find one selinux: policydb - rename type_val_to_struct_array selinux: policydb - fix some checkpatch.pl warnings selinux: shuffle around policydb.c to get rid of forward declarations
2019-08-05selinux: policydb - rename type_val_to_struct_arrayOndrej Mosnacek1-7/+7
The name is overly long and inconsistent with the other *_val_to_struct members. Dropping the "_array" prefix makes the code easier to read and gets rid of one line over 80 characters warning. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>