aboutsummaryrefslogtreecommitdiffstats
path: root/security/selinux/ss/policydb.c (follow)
AgeCommit message (Collapse)AuthorFilesLines
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>
2019-08-05selinux: policydb - fix some checkpatch.pl warningsOndrej Mosnacek1-4/+8
Fix most of the code style warnings discovered when moving code around. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-08-05selinux: shuffle around policydb.c to get rid of forward declarationsPaul Moore1-189/+187
No code changes, but move a lot of the policydb destructors higher up so we can get rid of a forward declaration. This patch does expose a few old checkpatch.pl errors, but those will be dealt with in a separate (set of) patches. Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-08-02Merge tag 'selinux-pr-20190801' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinuxLinus Torvalds1-1/+5
Pull selinux fix from Paul Moore: "One more small fix for a potential memory leak in an error path" * tag 'selinux-pr-20190801' of git://git.kernel.org/pub/scm/linux/kernel/git/pcmoore/selinux: selinux: fix memory leak in policydb_init()
2019-07-31selinux: fix memory leak in policydb_init()Ondrej Mosnacek1-1/+5
Since roles_init() adds some entries to the role hash table, we need to destroy also its keys/values on error, otherwise we get a memory leak in the error path. Cc: <stable@vger.kernel.org> Reported-by: syzbot+fee3a14d4cdf92646287@syzkaller.appspotmail.com Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2019-06-05treewide: Replace GPLv2 boilerplate/reference with SPDX - rule 372Thomas Gleixner1-3/+1
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 extracted by the scancode license scanner the SPDX license identifier GPL-2.0-only has been chosen to replace the boilerplate/reference in 135 file(s). Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Allison Randal <allison@lohutok.net> Cc: linux-spdx@vger.kernel.org Link: https://lkml.kernel.org/r/20190531081036.435762997@linutronix.de Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2019-03-18selinux: fix NULL dereference in policydb_destroy()Ondrej Mosnacek1-4/+9
The conversion to kvmalloc() forgot to account for the possibility that p->type_attr_map_array might be null in policydb_destroy(). Fix this by destroying its contents only if it is not NULL. Also make sure ebitmap_init() is called on all entries before policydb_destroy() can be called. Right now this is a no-op, because both kvcalloc() and ebitmap_init() just zero out the whole struct, but let's rather not rely on a specific implementation. Reported-by: syzbot+a57b2aff60832666fc28@syzkaller.appspotmail.com Fixes: acdf52d97f82 ("selinux: convert to kvmalloc") 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>
2019-03-12selinux: convert to kvmallocKent Overstreet1-92/+30
The flex arrays were being used for constant sized arrays, so there's no benefit to using flex_arrays over something simpler. Link: http://lkml.kernel.org/r/20181217131929.11727-4-kent.overstreet@gmail.com Signed-off-by: Kent Overstreet <kent.overstreet@gmail.com> Cc: Paul Moore <paul@paul-moore.com> Cc: Stephen Smalley <sds@tycho.nsa.gov> Cc: Eric Paris <eparis@parisplace.org> Cc: Alexey Dobriyan <adobriyan@gmail.com> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Dave Hansen <dave.hansen@intel.com> Cc: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com> Cc: Matthew Wilcox <willy@infradead.org> Cc: Neil Horman <nhorman@tuxdriver.com> Cc: Pravin B Shelar <pshelar@ovn.org> Cc: Shaohua Li <shli@kernel.org> Cc: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
2019-01-10selinux: fix GPF on invalid policyStephen Smalley1-1/+2
levdatum->level can be NULL if we encounter an error while loading the policy during sens_read prior to initializing it. Make sure sens_destroy handles that case correctly. Reported-by: syzbot+6664500f0f18f07a5c0e@syzkaller.appspotmail.com Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2018-12-05selinux: use separate table for initial SID lookupOndrej Mosnacek1-1/+9
This moves handling of initial SIDs into a separate table. Note that the SIDs stored in the main table are now shifted by SECINITSID_NUM and converted to/from the actual SIDs transparently by helper functions. This change doesn't make much sense on its own, but it simplifies further sidtab overhaul in a succeeding patch. Signed-off-by: Ondrej Mosnacek <omosnace@redhat.com> Reviewed-by: Stephen Smalley <sds@tycho.nsa.gov> [PM: fixed some checkpatch warnings on line length, whitespace] Signed-off-by: Paul Moore <paul@paul-moore.com>
2018-11-05selinux: policydb - fix byte order and alignment issuesOndrej Mosnacek1-15/+36
Do the LE conversions before doing the Infiniband-related range checks. The incorrect checks are otherwise causing a failure to load any policy with an ibendportcon rule on BE systems. This can be reproduced by running (on e.g. ppc64): cat >my_module.cil <<EOF (type test_ibendport_t) (roletype object_r test_ibendport_t) (ibendportcon mlx4_0 1 (system_u object_r test_ibendport_t ((s0) (s0)))) EOF semodule -i my_module.cil Also, fix loading/storing the 64-bit subnet prefix for OCON_IBPKEY to use a correctly aligned buffer. Finally, do not use the 'nodebuf' (u32) buffer where 'buf' (__le32) should be used instead. Tested internally on a ppc64 machine with a RHEL 7 kernel with this patch applied. Cc: Daniel Jurgens <danielj@mellanox.com> Cc: Eli Cohen <eli@mellanox.com> Cc: James Morris <jmorris@namei.org> Cc: Doug Ledford <dledford@redhat.com> Cc: <stable@vger.kernel.org> # 4.13+ Fixes: a806f7a1616f ("selinux: Create policydb version for Infiniband support") 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>
2018-09-13selinux: Add __GFP_NOWARN to allocation at str_read()Tetsuo Handa1-1/+1
syzbot is hitting warning at str_read() [1] because len parameter can become larger than KMALLOC_MAX_SIZE. We don't need to emit warning for this case. [1] https://syzkaller.appspot.com/bug?id=7f2f5aad79ea8663c296a2eedb81978401a908f0 Signed-off-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> Reported-by: syzbot <syzbot+ac488b9811036cea7ea0@syzkaller.appspotmail.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2018-06-19selinux: Cleanup printk logging in policydbpeter enderborg1-45/+46
Replace printk with pr_* to avoid checkpatch warnings and replace KERN_CONT with 2 longer prints. Signed-off-by: Peter Enderborg <peter.enderborg@sony.com> [PM: fixed some missing newlines identified by Joe Perches] Signed-off-by: Paul Moore <paul@paul-moore.com>
2017-08-17selinux: update my email addressStephen Smalley1-1/+1
Update my email address since epoch.ncsc.mil no longer exists. MAINTAINERS and CREDITS are already correct. Signed-off-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2017-05-23selinux: Create policydb version for Infiniband supportDaniel Jurgens1-15/+97
Support for Infiniband requires the addition of two new object contexts, one for infiniband PKeys and another IB Ports. Added handlers to read and write the new ocontext types when reading or writing a binary policy representation. Signed-off-by: Daniel Jurgens <danielj@mellanox.com> Reviewed-by: Eli Cohen <eli@mellanox.com> Reviewed-by: James Morris <james.l.morris@oracle.com> Acked-by: Doug Ledford <dledford@redhat.com> Signed-off-by: Paul Moore <paul@paul-moore.com>
2017-05-23selinux: Return directly after a failed memory allocation in policydb_index()Markus Elfring1-10/+5
Replace five goto statements (and previous variable assignments) by direct returns after a memory allocation failure in this function. Signed-off-by: Markus Elfring <elfring@users.sourceforge.net> Signed-off-by: Paul Moore <paul@paul-moore.com>
2017-03-31selinux: Fix an uninitialized variable bugDan Carpenter1-1/+1
We removed this initialization as a cleanup but it is probably required. The concern is that "nel" can be zero. I'm not an expert on SELinux code but I think it looks possible to write an SELinux policy which triggers this bug. GCC doesn't catch this, but my static checker does. Fixes: 9c312e79d6af ("selinux: Delete an unnecessary variable initialisation in range_read()") Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Acked-by: Stephen Smalley <sds@tycho.nsa.gov> Signed-off-by: Paul Moore <paul@paul-moore.com>
2017-03-29selinux: Return directly after a failed kzalloc() in roles_init()Markus Elfring1-2/+1
Return directly after a call of the function "kzalloc" failed at the beginning. Signed-off-by: Markus Elfring <elfring@users.sourceforge.net> Signed-off-by: Paul Moore <paul@paul-moore.com>