selinux list move final notice

2019-01-04 Thread Stephen Smalley
Hi,

As a reminder, the selinux mailing list has moved to vger.kernel.org.
If you wish to continue following the list, please subscribe by
sending a plaintext message containing "subscribe selinux" in the body
to majord...@vger.kernel.org. Be advised that vger.kernel.org does not 
accept HTML email, so configure your mail clients accordingly.  If you 
have trouble subscribing, send an email to 
owner-seli...@vger.kernel.org with a description of the problem, and if
that fails too, let us know. Archives for the new list can be found at 
https://lore.kernel.org/selinux.

The old selinux@tycho.nsa.gov mailing list will be shutting down on Feb
4th.

Thanks.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


selinux list move reminder

2018-12-06 Thread Stephen Smalley

Hi,

As a reminder, the selinux mailing list has moved to vger.kernel.org.
If you wish to continue following the list, please subscribe by sending 
a plaintext message containing "subscribe selinux" in the body to 
majord...@vger.kernel.org. Be advised that vger.kernel.org does not 
accept HTML email, so configure your mail clients accordingly.  If you 
have trouble subscribing, send an email to owner-seli...@vger.kernel.org 
with a description of the problem, and if that fails too, let us know. 
Archives for the new list can be found at https://lore.kernel.org/selinux.


Thanks.
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Android kill capability denials

2018-11-15 Thread Stephen Smalley

On 11/15/18 9:42 AM, Stephen Smalley wrote:

On 11/15/18 8:11 AM, Ondrej Mosnacek wrote:

On Mon, Nov 12, 2018 at 7:56 AM Ravi Kumar  wrote:

Hi team ,

On android- with latest kernels 4.14  we are seeing some denials 
which seem to be very much genuine to be address . Where kernel is 
trying to kill its own  created process ( might be for maintenance) .
These are seen in long Stress testing .  But  I dont see any one 
adding such rule in general so the question is  do we see any risk  
which made us not to add such rules ?


1.   avc: denied { kill } for pid=2432 comm="irq/66-90b6300." 
capability=5 scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 
tclass=capability permissive=0
2.   avc: denied { kill } for pid=69 comm="rcuop/6" capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability 
permissive=0
3.   avc: denied { kill } for pid=0 comm="swapper/1" capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability 
permissive=0
4.   avc: denied { kill } for pid=4185 comm="kworker/0:4" 
capability=5 scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 
tclass=capability permissive=0


This is self capability any one in kernel context  should be able to 
do such operations  I guess.


The reference policy does contain a rule that allows this kind of
operations, see:
https://github.com/SELinuxProject/refpolicy/blob/master/policy/modules/kernel/kernel.te#L203 



It is also present in the Fedora policy on my system:

$ sesearch -A -s kernel_t -t kernel_t -c capability -p kill
allow kernel_t kernel_t:capability { audit_control audit_write chown
dac_override dac_read_search fowner fsetid ipc_lock ipc_owner kill
lease linux_immutable mknod net_admin net_bind_service net_broadcast
net_raw setfcap setgid setpcap s
etuid sys_admin sys_boot sys_chroot sys_nice sys_pacct sys_ptrace
sys_rawio sys_resource sys_time sys_tty_config };

Therefore I would say it is perfectly fine to add such rule to your
policy as well.


Android uses a completely different policy not based on the reference 
policy at all, and tries to limit even the kernel and init domains to 
least privilege.  There are a few reasons to limit even the kernel domain:


1) To protect kernel threads and kernel usermodehelpers from being 
tricked into misusing their privileges and ensuring that they always 
transition to a non-kernel domain upon executing a usermodehelper.


2) To render typical kernel exploits that just switch to the init cred 
or otherwise rewrite their cred to use SECINITSID_KERNEL from gaining 
full privileges.


There are no unconfined domains in Android policy.

I think we would at least want to know why the permission check is 
occurring, as it might reflect a kernel bug.  If you can get system call 
audit info, then you can see additional information that may be helpful.


I guess system call audit isn't relevant here since these are 
kernel-internal callers.


This still seems like a kernel bug though, because 
check_kill_permission() will return 0 without performing any capability 
or other permission checks if !si_fromuser(info).  So kernel callers 
shouldn't trigger such permission checks unless I missed something.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: Android kill capability denials

2018-11-15 Thread Stephen Smalley

On 11/15/18 8:11 AM, Ondrej Mosnacek wrote:

On Mon, Nov 12, 2018 at 7:56 AM Ravi Kumar  wrote:

Hi team ,

On android- with latest kernels 4.14  we are seeing some denials which seem to 
be very much genuine to be address . Where kernel is trying to kill its own  
created process ( might be for maintenance) .
These are seen in long Stress testing .  But  I dont see any one adding such 
rule in general so the question is  do we see any risk  which made us not to 
add such rules ?

1.   avc: denied { kill } for pid=2432 comm="irq/66-90b6300." capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability permissive=0
2.   avc: denied { kill } for pid=69 comm="rcuop/6" capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability permissive=0
3.   avc: denied { kill } for pid=0 comm="swapper/1" capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability permissive=0
4.   avc: denied { kill } for pid=4185 comm="kworker/0:4" capability=5 
scontext=u:r:kernel:s0 tcontext=u:r:kernel:s0 tclass=capability permissive=0

This is self capability any one in kernel context  should be able to do such 
operations  I guess.


The reference policy does contain a rule that allows this kind of
operations, see:
https://github.com/SELinuxProject/refpolicy/blob/master/policy/modules/kernel/kernel.te#L203

It is also present in the Fedora policy on my system:

$ sesearch -A -s kernel_t -t kernel_t -c capability -p kill
allow kernel_t kernel_t:capability { audit_control audit_write chown
dac_override dac_read_search fowner fsetid ipc_lock ipc_owner kill
lease linux_immutable mknod net_admin net_bind_service net_broadcast
net_raw setfcap setgid setpcap s
etuid sys_admin sys_boot sys_chroot sys_nice sys_pacct sys_ptrace
sys_rawio sys_resource sys_time sys_tty_config };

Therefore I would say it is perfectly fine to add such rule to your
policy as well.


Android uses a completely different policy not based on the reference 
policy at all, and tries to limit even the kernel and init domains to 
least privilege.  There are a few reasons to limit even the kernel domain:


1) To protect kernel threads and kernel usermodehelpers from being 
tricked into misusing their privileges and ensuring that they always 
transition to a non-kernel domain upon executing a usermodehelper.


2) To render typical kernel exploits that just switch to the init cred 
or otherwise rewrite their cred to use SECINITSID_KERNEL from gaining 
full privileges.


There are no unconfined domains in Android policy.

I think we would at least want to know why the permission check is 
occurring, as it might reflect a kernel bug.  If you can get system call 
audit info, then you can see additional information that may be helpful.


___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v3] selinux: simplify mls_context_to_sid()

2018-11-14 Thread Stephen Smalley

On 11/14/18 10:23 AM, Stephen Smalley wrote:

On 11/13/18 10:14 PM, Paul Moore wrote:
On Tue, Nov 13, 2018 at 4:10 PM Stephen Smalley  
wrote:

On 11/12/18 6:44 AM, Ondrej Mosnacek wrote:

This function has only two callers, but only one of them actually needs
the special logic at the beginning. Factoring this logic out into
string_to_context_struct() allows us to drop the arguments 'oldc', 's',
and 'def_sid'.

Signed-off-by: Ondrej Mosnacek 
---

Changes in v3:
   - correct the comment about policy read lock

Changes in v2:
   - also drop unneeded #include's from mls.c

   security/selinux/ss/mls.c  | 49 
+-

   security/selinux/ss/mls.h  |  5 +---
   security/selinux/ss/services.c | 32 +++---
   3 files changed, 36 insertions(+), 50 deletions(-)

diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index 2fe459df3c85..d1da928a7e77 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -24,10 +24,7 @@
   #include 
   #include 
   #include 
-#include "sidtab.h"
   #include "mls.h"
-#include "policydb.h"
-#include "services.h"

   /*
    * Return the length in bytes for the MLS fields of the
@@ -223,20 +220,12 @@ int mls_context_isvalid(struct policydb *p, 
struct context *c)

    * This function modifies the string in place, inserting
    * NULL characters to terminate the MLS fields.
    *
- * If a def_sid is provided and no MLS field is present,
- * copy the MLS field of the associated default context.
- * Used for upgraded to MLS systems where objects may lack
- * MLS fields.
- *
- * Policy read-lock must be held for sidtab lookup.
+ * Policy read-lock must be held for policy data lookup.
    *
    */
   int mls_context_to_sid(struct policydb *pol,
-    char oldc,
  char *scontext,
-    struct context *context,
-    struct sidtab *s,
-    u32 def_sid)
+    struct context *context)
   {
   char *sensitivity, *cur_cat, *next_cat, *rngptr;
   struct level_datum *levdatum;
@@ -244,29 +233,6 @@ int mls_context_to_sid(struct policydb *pol,
   int l, rc, i;
   char *rangep[2];

- if (!pol->mls_enabled) {
- if ((def_sid != SECSID_NULL && oldc) || (*scontext) == 
'\0')

- return 0;
- return -EINVAL;
- }
-
- /*
-  * No MLS component to the security context, try and map to
-  * default if provided.
-  */
- if (!oldc) {
- struct context *defcon;
-
- if (def_sid == SECSID_NULL)
- return -EINVAL;
-
- defcon = sidtab_search(s, def_sid);
- if (!defcon)
- return -EINVAL;
-
- return mls_context_cpy(context, defcon);
- }
-
   /*
    * If we're dealing with a range, figure out where the two parts
    * of the range begin.
@@ -364,14 +330,11 @@ int mls_from_string(struct policydb *p, char 
*str, struct context *context,

   return -EINVAL;

   tmpstr = kstrdup(str, gfp_mask);
- if (!tmpstr) {
- rc = -ENOMEM;
- } else {
- rc = mls_context_to_sid(p, ':', tmpstr, context,
- NULL, SECSID_NULL);
- kfree(tmpstr);
- }
+ if (!tmpstr)
+ return -ENOMEM;

+ rc = mls_context_to_sid(p, tmpstr, context);
+ kfree(tmpstr);
   return rc;
   }

diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h
index 67093647576d..e2498f78e100 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -33,11 +33,8 @@ int mls_range_isvalid(struct policydb *p, struct 
mls_range *r);

   int mls_level_isvalid(struct policydb *p, struct mls_level *l);

   int mls_context_to_sid(struct policydb *p,
-    char oldc,
  char *scontext,
-    struct context *context,
-    struct sidtab *s,
-    u32 def_sid);
+    struct context *context);

   int mls_from_string(struct policydb *p, char *str, struct context 
*context,

   gfp_t gfp_mask);
diff --git a/security/selinux/ss/services.c 
b/security/selinux/ss/services.c

index 12e414394530..ccad4334f99d 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -1425,9 +1425,35 @@ static int string_to_context_struct(struct 
policydb *pol,


   ctx->type = typdatum->value;

- rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
- if (rc)
- goto out;
+ if (!pol->mls_enabled) {
+ rc = -EINVAL;
+ if ((def_sid == SECSID_NULL || !oldc) && (*p) != '\0')
+ goto out;


I don't think this is your bug, but unless I'm mistaken, p could be OOB
and be dereferenced here.  Seems to have been introduced by
95f

Re: [PATCH v3] selinux: simplify mls_context_to_sid()

2018-11-14 Thread Stephen Smalley

On 11/13/18 10:14 PM, Paul Moore wrote:

On Tue, Nov 13, 2018 at 4:10 PM Stephen Smalley  wrote:

On 11/12/18 6:44 AM, Ondrej Mosnacek wrote:

This function has only two callers, but only one of them actually needs
the special logic at the beginning. Factoring this logic out into
string_to_context_struct() allows us to drop the arguments 'oldc', 's',
and 'def_sid'.

Signed-off-by: Ondrej Mosnacek 
---

Changes in v3:
   - correct the comment about policy read lock

Changes in v2:
   - also drop unneeded #include's from mls.c

   security/selinux/ss/mls.c  | 49 +-
   security/selinux/ss/mls.h  |  5 +---
   security/selinux/ss/services.c | 32 +++---
   3 files changed, 36 insertions(+), 50 deletions(-)

diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index 2fe459df3c85..d1da928a7e77 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -24,10 +24,7 @@
   #include 
   #include 
   #include 
-#include "sidtab.h"
   #include "mls.h"
-#include "policydb.h"
-#include "services.h"

   /*
* Return the length in bytes for the MLS fields of the
@@ -223,20 +220,12 @@ int mls_context_isvalid(struct policydb *p, struct 
context *c)
* This function modifies the string in place, inserting
* NULL characters to terminate the MLS fields.
*
- * If a def_sid is provided and no MLS field is present,
- * copy the MLS field of the associated default context.
- * Used for upgraded to MLS systems where objects may lack
- * MLS fields.
- *
- * Policy read-lock must be held for sidtab lookup.
+ * Policy read-lock must be held for policy data lookup.
*
*/
   int mls_context_to_sid(struct policydb *pol,
-char oldc,
  char *scontext,
-struct context *context,
-struct sidtab *s,
-u32 def_sid)
+struct context *context)
   {
   char *sensitivity, *cur_cat, *next_cat, *rngptr;
   struct level_datum *levdatum;
@@ -244,29 +233,6 @@ int mls_context_to_sid(struct policydb *pol,
   int l, rc, i;
   char *rangep[2];

- if (!pol->mls_enabled) {
- if ((def_sid != SECSID_NULL && oldc) || (*scontext) == '\0')
- return 0;
- return -EINVAL;
- }
-
- /*
-  * No MLS component to the security context, try and map to
-  * default if provided.
-  */
- if (!oldc) {
- struct context *defcon;
-
- if (def_sid == SECSID_NULL)
- return -EINVAL;
-
- defcon = sidtab_search(s, def_sid);
- if (!defcon)
- return -EINVAL;
-
- return mls_context_cpy(context, defcon);
- }
-
   /*
* If we're dealing with a range, figure out where the two parts
* of the range begin.
@@ -364,14 +330,11 @@ int mls_from_string(struct policydb *p, char *str, struct 
context *context,
   return -EINVAL;

   tmpstr = kstrdup(str, gfp_mask);
- if (!tmpstr) {
- rc = -ENOMEM;
- } else {
- rc = mls_context_to_sid(p, ':', tmpstr, context,
- NULL, SECSID_NULL);
- kfree(tmpstr);
- }
+ if (!tmpstr)
+ return -ENOMEM;

+ rc = mls_context_to_sid(p, tmpstr, context);
+ kfree(tmpstr);
   return rc;
   }

diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h
index 67093647576d..e2498f78e100 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -33,11 +33,8 @@ int mls_range_isvalid(struct policydb *p, struct mls_range 
*r);
   int mls_level_isvalid(struct policydb *p, struct mls_level *l);

   int mls_context_to_sid(struct policydb *p,
-char oldc,
  char *scontext,
-struct context *context,
-struct sidtab *s,
-u32 def_sid);
+struct context *context);

   int mls_from_string(struct policydb *p, char *str, struct context *context,
   gfp_t gfp_mask);
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 12e414394530..ccad4334f99d 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -1425,9 +1425,35 @@ static int string_to_context_struct(struct policydb *pol,

   ctx->type = typdatum->value;

- rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
- if (rc)
- goto out;
+ if (!pol->mls_enabled) {
+ rc = -EINVAL;
+ if ((def_sid == SECSID_NULL || !oldc) && (*p) != '\0')
+ goto out;


I don't think this is your bug, but unless I'm mistaken, p could be OOB
and be dereferenced here.  Seems to have been introduced by
95ffe194204ae3cef88d0b59be209204bbe9b3be.  Likely not caught in 

Re: [RFC PATCH 2/3] selinux: use separate table for initial SID lookup

2018-11-14 Thread Stephen Smalley

On 11/14/18 4:45 AM, Ondrej Mosnacek wrote:

On Tue, Nov 13, 2018 at 10:35 PM Stephen Smalley  wrote:

On 11/13/18 8:52 AM, Ondrej Mosnacek wrote:

This patch is non-functional and 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.


When you say "non-functional", you mean it doesn't make any functional
changes, right?  As opposed to leaving the kernel in a broken
intermediate state until your 3rd patch?


I mean it *should* be non-functional on its own, unless I made a
mistake. I admit I didn't do very much testing on this patch, but I at
least checked that I can boot the kernel, load a policy and that
reported file contexts make sense.


Commonly non-functional means "not working".  I think you mean "this 
patch makes no functional changes".






I think you need to double check that all references to
state->ss->sidtab are preceded by a check of state->initialized since it
could be NULL before first policy load and a system could come up with
SELinux enabled but never load a policy.


Well, the original code does not initialize the sidtab field with
sidtab_init() either so state->ss->sidtab.htable would be NULL (or
some garbage pointer) after boot and any use of sidtab would cause a
GPF anyway.


Prior to the patch, the sidtab is directly embedded in the selinux_ss, 
which is static and thus all fields are initialized to 0/NULL.  But you 
could access the sidtab itself without any problem since it was not a 
pointer. Likewise for the policydb.  When you change the sidtab to be a 
pointer, then you have to deal with the possibility that it will be 
NULL.  So you might be introducing new situations where we would trigger 
a GPF.




Looking at the places that reference the sidtab (which are all
highlighted in the patch because of the switch to pointer type in the
struct selinux_ss definition), these don't seem to check for
state->initialized:
- security_port_sid


In this case, policydb->ocontexts[OCON_PORT] will be NULL at 
initialization, so c will be NULL and we will just set *out_sid to 
SECINITSID_PORT and return without ever accessing the sidtab.



- security_ib_pkey_sid
- security_ib_endport_sid
- security_netif_sid
- security_node_sid


These are all similar.


- security_sid_mls_copy, called from:


This one checks state->initialized and returns if not set.


   - selinux_socket_unix_stream_connect (avc_has_perm is called before)
   - selinux_conn_sid, called from:
 - selinux_sctp_assoc_request (selinux_policycap_extsockclass is
called before)
 - selinux_inet_conn_request
 - selinux_ip_postroute (selinux_policycap_netpeer is called before)
- security_net_peersid_resolve, called from:


This one should always return before taking the policy rwlock when 
!state->initialized because you can't have configured network labels 
without a policy IIUC (so xfrm_sid and/or nlbl_sid should be NULL), or 
regardless, policydb->mls_enabled will be 0 at this point.



   - selinux_skb_peerlbl_sid, called from:
 - selinux_socket_sock_rcv_skb (selinux_policycap_netpeer is called before)
 - selinux_socket_getpeersec_dgram
 - selinux_sctp_assoc_request (again)
 - selinux_inet_conn_request (again)
 - selinux_inet_conn_established
 - selinux_ip_forward (selinux_policycap_netpeer is called before)
 - selinux_ip_postroute (again)
- selinux_audit_rule_match


This one can't be called without a prior selinux_audit_rule_init, which 
checks state->initialized.



- security_netlbl_secattr_to_sid, called from:


This one checks state->initialized.


   - selinux_netlbl_sidlookup_cached, called from:
 - selinux_netlbl_skbuff_getsid (netlbl_enabled is called before)
 - selinux_netlbl_sock_rcv_skb (netlbl_enabled is called before)
- security_netlbl_sid_to_secattr, called from:


Ditto.


   - selinux_netlbl_sock_genattr, called from:
 - selinux_netlbl_socket_post_create, called from:
   - selinux_socket_post_create
   - selinux_netlbl_skbuff_setsid, called from:
 - selinux_ip_forward (again)
   - selinux_netlbl_sctp_assoc_request, called from:
 - selinux_sctp_assoc_request (again)
   - selinux_netlbl_inet_conn_request, called from:
 - selinux_inet_conn_request (again)

I suppose in some (or all?) of these cases state->initialized might be
implicitly always 1, but at least in these it wasn't immediately
obvious to me.

Either way, such cases would already be buggy before this patch, since
they would happily access the policy structure (likely hitting some
NULL/invalid pointers) and most likely also dereference the invalid
htable pointer in sidtab.



Aren't you still wasting a slot in the initial SIDs array, or did I miss
something?


Yes, I am, because the original code doesn't seem to guard against
SECSID_NULL being loaded as initial SI

Re: [RFC PATCH 2/3] selinux: use separate table for initial SID lookup

2018-11-13 Thread Stephen Smalley

On 11/13/18 8:52 AM, Ondrej Mosnacek wrote:

This patch is non-functional and 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.


When you say "non-functional", you mean it doesn't make any functional 
changes, right?  As opposed to leaving the kernel in a broken 
intermediate state until your 3rd patch?


I think you need to double check that all references to 
state->ss->sidtab are preceded by a check of state->initialized since it 
could be NULL before first policy load and a system could come up with 
SELinux enabled but never load a policy.


Aren't you still wasting a slot in the initial SIDs array, or did I miss 
something?




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 
---
  security/selinux/ss/policydb.c |  10 ++-
  security/selinux/ss/services.c |  88 ++
  security/selinux/ss/services.h |   2 +-
  security/selinux/ss/sidtab.c   | 158 +++--
  security/selinux/ss/sidtab.h   |  14 +--
  5 files changed, 162 insertions(+), 110 deletions(-)

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..21e4bdbcf994 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -909,13 +909,21 @@ int policydb_load_isids(struct policydb *p, struct sidtab 
*s)
if (!c->context[0].user) {
pr_err("SELinux:  SID %s was never defined.\n",
c->u.name);
+   sidtab_destroy(s);
+   goto out;
+   }
+   if (c->sid[0] > SECINITSID_NUM) {
+   pr_err("SELinux:  Initial SID %s out of range.\n",
+   c->u.name);
+   sidtab_destroy(s);
goto out;
}
  
-		rc = sidtab_insert(s, c->sid[0], >context[0]);

+   rc = sidtab_set_initial(s, c->sid[0], >context[0]);
if (rc) {
pr_err("SELinux:  unable to load initial SID %s.\n",
c->u.name);
+   sidtab_destroy(s);
goto out;
}
}
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 7337db24a6a8..30170d4c567a 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -776,7 +776,7 @@ static int security_compute_validatetrans(struct 
selinux_state *state,
read_lock(>ss->policy_rwlock);
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	if (!user)

tclass = unmap_class(>ss->map, orig_tclass);
@@ -876,7 +876,7 @@ int security_bounded_transition(struct selinux_state *state,
read_lock(>ss->policy_rwlock);
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	rc = -EINVAL;

old_context = sidtab_search(sidtab, old_sid);
@@ -1034,7 +1034,7 @@ void security_compute_xperms_decision(struct 
selinux_state *state,
goto allow;
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	scontext = sidtab_search(sidtab, ssid);

if (!scontext) {
@@ -1123,7 +1123,7 @@ void security_compute_av(struct selinux_state *state,
goto allow;
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	scontext = sidtab_search(sidtab, ssid);

if (!scontext) {
@@ -1177,7 +1177,7 @@ void security_compute_av_user(struct selinux_state *state,
goto allow;
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	scontext = sidtab_search(sidtab, ssid);

if (!scontext) {
@@ -1315,7 +1315,7 @@ static int security_sid_to_context_core(struct 
selinux_state *state,
}
read_lock(>ss->policy_rwlock);
policydb = >ss->policydb;
-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
if (force)
context = sidtab_search_force(sidtab, sid);
else
@@ -1483,7 +1483,7 @@ static int security_context_to_sid_core(struct 
selinux_state *state,
}
read_lock(>ss->policy_rwlock);
policydb = >ss->policydb;
-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
rc = string_to_context_struct(policydb, sidtab, scontext2,
  , def_sid);
if (rc == -EINVAL && force) {
@@ -1668,7 +1668,7 @@ static int security_compute_sid(struct selinux_state 
*state,
}
  
  	policydb = >ss->policydb;

-   sidtab = >ss->sidtab;
+   sidtab = state->ss->sidtab;
  
  	

Re: [RFC PATCH 1/3] selinux: refactor sidtab conversion

2018-11-13 Thread Stephen Smalley

On 11/13/18 8:52 AM, Ondrej Mosnacek wrote:

This is a purely cosmetic change that encapsulates the three-step sidtab
conversion logic (shutdown -> clone -> map) into a single function
defined in sidtab.c (as opposed to services.c).

Signed-off-by: Ondrej Mosnacek 


Acked-by: Stephen Smalley 


---
  security/selinux/ss/services.c | 22 +--
  security/selinux/ss/sidtab.c   | 50 --
  security/selinux/ss/sidtab.h   | 11 
  3 files changed, 42 insertions(+), 41 deletions(-)

diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 12e414394530..7337db24a6a8 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -1880,19 +1880,6 @@ int security_change_sid(struct selinux_state *state,
out_sid, false);
  }
  
-/* Clone the SID into the new SID table. */

-static int clone_sid(u32 sid,
-struct context *context,
-void *arg)
-{
-   struct sidtab *s = arg;
-
-   if (sid > SECINITSID_NUM)
-   return sidtab_insert(s, sid, context);
-   else
-   return 0;
-}
-
  static inline int convert_context_handle_invalid_context(
struct selinux_state *state,
struct context *context)
@@ -2186,13 +2173,6 @@ int security_load_policy(struct selinux_state *state, 
void *data, size_t len)
goto err;
}
  
-	/* Clone the SID table. */

-   sidtab_shutdown(sidtab);
-
-   rc = sidtab_map(sidtab, clone_sid, );
-   if (rc)
-   goto err;
-
/*
 * Convert the internal representations of contexts
 * in the new SID table.
@@ -2200,7 +2180,7 @@ int security_load_policy(struct selinux_state *state, 
void *data, size_t len)
args.state = state;
args.oldp = policydb;
args.newp = newpolicydb;
-   rc = sidtab_map(, convert_context, );
+   rc = sidtab_convert(sidtab, , convert_context, );
if (rc) {
pr_err("SELinux:  unable to convert the internal"
" representation of contexts in the new SID"
diff --git a/security/selinux/ss/sidtab.c b/security/selinux/ss/sidtab.c
index fd75a12fa8fc..e66a2ab3d1c2 100644
--- a/security/selinux/ss/sidtab.c
+++ b/security/selinux/ss/sidtab.c
@@ -116,11 +116,11 @@ struct context *sidtab_search_force(struct sidtab *s, u32 
sid)
return sidtab_search_core(s, sid, 1);
  }
  
-int sidtab_map(struct sidtab *s,

-  int (*apply) (u32 sid,
-struct context *context,
-void *args),
-  void *args)
+static int sidtab_map(struct sidtab *s,
+ int (*apply) (u32 sid,
+   struct context *context,
+   void *args),
+ void *args)
  {
int i, rc = 0;
struct sidtab_node *cur;
@@ -141,6 +141,37 @@ out:
return rc;
  }
  
+/* Clone the SID into the new SID table. */

+static int clone_sid(u32 sid, struct context *context, void *arg)
+{
+   struct sidtab *s = arg;
+
+   if (sid > SECINITSID_NUM)
+   return sidtab_insert(s, sid, context);
+   else
+   return 0;
+}
+
+int sidtab_convert(struct sidtab *s, struct sidtab *news,
+  int (*convert) (u32 sid,
+  struct context *context,
+  void *args),
+  void *args)
+{
+   unsigned long flags;
+   int rc;
+
+   spin_lock_irqsave(>lock, flags);
+   s->shutdown = 1;
+   spin_unlock_irqrestore(>lock, flags);
+
+   rc = sidtab_map(s, clone_sid, news);
+   if (rc)
+   return rc;
+
+   return sidtab_map(news, convert, args);
+}
+
  static void sidtab_update_cache(struct sidtab *s, struct sidtab_node *n, int 
loc)
  {
BUG_ON(loc >= SIDTAB_CACHE_LEN);
@@ -295,12 +326,3 @@ void sidtab_set(struct sidtab *dst, struct sidtab *src)
dst->cache[i] = NULL;
spin_unlock_irqrestore(>lock, flags);
  }
-
-void sidtab_shutdown(struct sidtab *s)
-{
-   unsigned long flags;
-
-   spin_lock_irqsave(>lock, flags);
-   s->shutdown = 1;
-   spin_unlock_irqrestore(>lock, flags);
-}
diff --git a/security/selinux/ss/sidtab.h b/security/selinux/ss/sidtab.h
index a1a1d2617b6f..26c74fe7afc0 100644
--- a/security/selinux/ss/sidtab.h
+++ b/security/selinux/ss/sidtab.h
@@ -37,11 +37,11 @@ int sidtab_insert(struct sidtab *s, u32 sid, struct context 
*context);
  struct context *sidtab_search(struct sidtab *s, u32 sid);
  struct context *sidtab_search_force(struct sidtab *s, u32 sid);
  
-int sidtab_map(struct sidtab *s,

-  int (*apply) (u32 sid,
-struct context *context,
-void *args),
-  void *args)

Re: [PATCH v3] selinux: simplify mls_context_to_sid()

2018-11-13 Thread Stephen Smalley

On 11/12/18 6:44 AM, Ondrej Mosnacek wrote:

This function has only two callers, but only one of them actually needs
the special logic at the beginning. Factoring this logic out into
string_to_context_struct() allows us to drop the arguments 'oldc', 's',
and 'def_sid'.

Signed-off-by: Ondrej Mosnacek 
---

Changes in v3:
  - correct the comment about policy read lock

Changes in v2:
  - also drop unneeded #include's from mls.c

  security/selinux/ss/mls.c  | 49 +-
  security/selinux/ss/mls.h  |  5 +---
  security/selinux/ss/services.c | 32 +++---
  3 files changed, 36 insertions(+), 50 deletions(-)

diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index 2fe459df3c85..d1da928a7e77 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -24,10 +24,7 @@
  #include 
  #include 
  #include 
-#include "sidtab.h"
  #include "mls.h"
-#include "policydb.h"
-#include "services.h"
  
  /*

   * Return the length in bytes for the MLS fields of the
@@ -223,20 +220,12 @@ int mls_context_isvalid(struct policydb *p, struct 
context *c)
   * This function modifies the string in place, inserting
   * NULL characters to terminate the MLS fields.
   *
- * If a def_sid is provided and no MLS field is present,
- * copy the MLS field of the associated default context.
- * Used for upgraded to MLS systems where objects may lack
- * MLS fields.
- *
- * Policy read-lock must be held for sidtab lookup.
+ * Policy read-lock must be held for policy data lookup.
   *
   */
  int mls_context_to_sid(struct policydb *pol,
-  char oldc,
   char *scontext,
-  struct context *context,
-  struct sidtab *s,
-  u32 def_sid)
+  struct context *context)
  {
char *sensitivity, *cur_cat, *next_cat, *rngptr;
struct level_datum *levdatum;
@@ -244,29 +233,6 @@ int mls_context_to_sid(struct policydb *pol,
int l, rc, i;
char *rangep[2];
  
-	if (!pol->mls_enabled) {

-   if ((def_sid != SECSID_NULL && oldc) || (*scontext) == '\0')
-   return 0;
-   return -EINVAL;
-   }
-
-   /*
-* No MLS component to the security context, try and map to
-* default if provided.
-*/
-   if (!oldc) {
-   struct context *defcon;
-
-   if (def_sid == SECSID_NULL)
-   return -EINVAL;
-
-   defcon = sidtab_search(s, def_sid);
-   if (!defcon)
-   return -EINVAL;
-
-   return mls_context_cpy(context, defcon);
-   }
-
/*
 * If we're dealing with a range, figure out where the two parts
 * of the range begin.
@@ -364,14 +330,11 @@ int mls_from_string(struct policydb *p, char *str, struct 
context *context,
return -EINVAL;
  
  	tmpstr = kstrdup(str, gfp_mask);

-   if (!tmpstr) {
-   rc = -ENOMEM;
-   } else {
-   rc = mls_context_to_sid(p, ':', tmpstr, context,
-   NULL, SECSID_NULL);
-   kfree(tmpstr);
-   }
+   if (!tmpstr)
+   return -ENOMEM;
  
+	rc = mls_context_to_sid(p, tmpstr, context);

+   kfree(tmpstr);
return rc;
  }
  
diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h

index 67093647576d..e2498f78e100 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -33,11 +33,8 @@ int mls_range_isvalid(struct policydb *p, struct mls_range 
*r);
  int mls_level_isvalid(struct policydb *p, struct mls_level *l);
  
  int mls_context_to_sid(struct policydb *p,

-  char oldc,
   char *scontext,
-  struct context *context,
-  struct sidtab *s,
-  u32 def_sid);
+  struct context *context);
  
  int mls_from_string(struct policydb *p, char *str, struct context *context,

gfp_t gfp_mask);
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 12e414394530..ccad4334f99d 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c
@@ -1425,9 +1425,35 @@ static int string_to_context_struct(struct policydb *pol,
  
  	ctx->type = typdatum->value;
  
-	rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);

-   if (rc)
-   goto out;
+   if (!pol->mls_enabled) {
+   rc = -EINVAL;
+   if ((def_sid == SECSID_NULL || !oldc) && (*p) != '\0')
+   goto out;


I don't think this is your bug, but unless I'm mistaken, p could be OOB 
and be dereferenced here.  Seems to have been introduced by 
95ffe194204ae3cef88d0b59be209204bbe9b3be.  Likely not caught in testing 
since both Linux distributions and Android enable MLS to use the 
category 

Re: SELinux MLS for Apache Process

2018-11-08 Thread Stephen Smalley

On 11/8/18 8:33 AM, Ishara Fernando wrote:

Dear Stephen ,

Many thanks for the detailed information , it has been very useful . 
Infact I have tested your steps in a similar environment (CentOS 6.10 , 
see versions below) as of yours in a Virtual machine based on 
Virtualbox  , I have reached to the step where the *selinux module is 
installed* on doing the range transition to enforce httpd to run on 
s4-s5:c1,c2 .


Unfortunately I still see the range transition denied errors in the 
audit logs (After installing the selinux module) and I do not see any 
errors related to *httpd trying to perform writes* on various 
directories/files that are labeled s0 as per your explanation .


Kindly see the details below

[root@msc-ishara-system1 ~]# sestatus -v
SELinux status: enabled
SELinuxfs mount:    /selinux
Current mode:   enforcing
Mode from config file:  enforcing
Policy version: 24
Policy from config file:    mls

Process contexts:
Current context:    staff_u:sysadm_r:sysadm_t:s4-s5:c1,c2
Init context:   system_u:system_r:init_t:s0-s15:c0.c1023
/sbin/mingetty  system_u:system_r:getty_t:s0-s15:c0.c1023
/usr/sbin/sshd  system_u:system_r:sshd_t:s0-s15:c0.c1023

File contexts:
Controlling term:   staff_u:object_r:user_devpts_t:s4
/etc/passwd system_u:object_r:etc_t:s0
/etc/shadow system_u:object_r:shadow_t:s0
/bin/bash   system_u:object_r:shell_exec_t:s0
/bin/login  system_u:object_r:login_exec_t:s0
/bin/sh system_u:object_r:bin_t:s0 -> 
system_u:object_r:shell_exec_t:s0

/sbin/agetty    system_u:object_r:getty_exec_t:s0
/sbin/init  system_u:object_r:init_exec_t:s0
/sbin/mingetty  system_u:object_r:getty_exec_t:s0
/usr/sbin/sshd  system_u:object_r:sshd_exec_t:s0



Dist: CentOS release 6.10 (Final)
Kernel : 2.6.32-754.6.3.el6.x86_64
SELinux MLS Policy RPM: selinux-policy-mls-3.7.19-312.el6.noarch
SELinux Policy version: 24


[root@msc-ishara-system1 ~]# id -Z
staff_u:sysadm_r:sysadm_t:s4-s5:c1,c2


This is the problem - you switched levels before running run_init.
And run_init tries to do an explicit transition to the context 
configured in /etc/selinux/$SELINUXTYPE/contexts/initrc_context.  Just 
leave your shell in s0-s15:c0.1023, and let the range_transition rule 
handle transitioning httpd into s4-s5:c1,c2 for you automatically.





[root@msc-ishara-system1 ~]# ls -lZ /usr/sbin/httpd
-rwxr-xr-x. root root system_u:object_r:httpd_exec_t:s0 /usr/sbin/httpd



[root@msc-ishara-system1 ~]# which run_init
/usr/sbin/run_init
[root@msc-ishara-system1 ~]# ls -lZ /usr/sbin/run_init
-rwxr-xr-x. root root system_u:object_r:run_init_exec_t:s0 
/usr/sbin/run_init




[root@msc-ishara-system1 /]# cat httpdtrans.te
policy_module(httpdtrans, 1.0)

require {
     type initrc_t;
     type httpd_exec_t;
     type httpd_t;
}

range_transition initrc_t httpd_exec_t:process s4 - s5:c1,c2;

mls_rangetrans_source(initrc_t)
mls_rangetrans_target(httpd_t)



[root@msc-ishara-system1 /]# semodule -l | grep -i httpd
httpdtrans    1.0



[root@msc-ishara-system1 ~]# sesearch --type | grep -i initrc_t | grep 
-i httpd_exec

    type_transition initrc_t httpd_exec_t : process httpd_t;


[root@msc-ishara-system1 ~]# id -Z
staff_u:sysadm_r:sysadm_t:s4-s5:c1,c2


[root@msc-ishara-system1 ~]# run_init /etc/init.d/httpd start
Authenticating root.
Password:
execvp: Permission denied


[root@msc-ishara-system1 ~]# ausearch -i -m AVC -ts recent

type=SYSCALL msg=audit(11/08/2018 18:32:36.457:160) : arch=x86_64 
syscall=execve success=no exit=-13(Permission denied) a0=0x7ffd2309581a 
a1=0x7ffd230949b0 a2=0x7ffd230949c8 a3=0x7ffd23094610 items=0 ppid=1802 
pid=3074 auid=root uid=root gid=root euid=root suid=root fsuid=root 
egid=root sgid=root fsgid=root tty=pts0 ses=3 comm=run_init 
exe=/usr/sbin/run_init subj=staff_u:sysadm_r:run_init_t:s4-s5:c1,c2 
key=(null)
type=AVC msg=audit(11/08/2018 18:32:36.457:160) :*avc:  denied  { 
transition } f*or  pid=3074 comm=run_init path=/etc/rc.d/init.d/httpd 
dev=dm-0 ino=262967 scontext=staff_u:sysadm_r:run_init_t:s4-s5:c1,c2 
tcontext=system_u:system_r:initrc_t:s0-s15:c0.c1023 tclass=process



[root@msc-ishara-system1 /]# cat  /var/log/audit/audit.log | grep -i 
httpd | grep -i write

[root@msc-ishara-system1 /]#

[root@msc-ishara-system1 /]# cat  /var/log/audit/audit.log | grep -i 
httpd | grep -i append

[root@msc-ishara-system1 /]#



I followed all your steps but not sure whether I have missed something 
which I still couldn't point out



Also regarding the constraint rules , now I understand how it works 
after your explanation about the httpd process running in the sshd_t 
domain :) . So therefore I have installed the SRC rpm to see the types 
for mlsfileread attribute 

Re: SELinux MLS for Apache Process

2018-11-07 Thread Stephen Smalley

On 11/7/18 2:04 AM, Ishara Fernando wrote:

Thanks Stephen , so below are the details of my SELinux setup


*Centos Version* : CentOS release 6.2 (Final)
*Kernel version* : 2.6.32-220.el6.x86_64
*RPM package* : selinux-policy-mls-3.7.19-312.el6.noarch


That's quite old.  Any particular reason you aren't at least on the 
latest CentOS 6.x release if not CentOS 7.x? 
CentOS/Fedora/RHEL-specific questions likely should go to the Fedora 
selinux list,

https://lists.fedoraproject.org/admin/lists/selinux.lists.fedoraproject.org/



*cat /etc/selinux/mls/contexts/securetty_types *
console_device_t
sysadm_tty_device_t
user_tty_device_t
staff_tty_device_t
auditadm_tty_device_t
secureadm_tty_device_t
user_devpts_t
sshd_devpts_t

*
*
*sestatus -v *
SELinux status: enabled
SELinuxfs mount:    /selinux
Current mode:   enforcing
Mode from config file:  enforcing
Policy version: 24
Policy from config file:    mls

Process contexts:
Current context:    system_u:system_r:sshd_t:s0-s15:c0.c1023


Your shell shouldn't be running in sshd_t; sshd should have transitioned 
to a user context (like root:sysadm_r:sysadm_t:... or 
staff_u:staff_r:staff_t:... or user_u:user_r:user_t:...).  Were there 
errors from sshd in /var/log/secure or elsewhere?



Init context:   unknown (Permission denied)

File contexts:
Controlling term:   system_u:object_r:sshd_devpts_t:s0
/etc/passwd system_u:object_r:etc_t:s0
/bin/bash   system_u:object_r:shell_exec_t:s0
/bin/sh system_u:object_r:bin_t:s0 -> 
system_u:object_r:shell_exec_t:s0

/usr/sbin/sshd  system_u:object_r:sshd_exec_t:s0


*Regarding the httpd process , i started the process by switching to a 
new role as follows , so that's why it has obtained the sshd_t type on 
the 'httpd' process*


[root@msc-ishara-system1 ~]# newrole -l s4-s5:c1,c2
Password:

[root@msc-ishara-system1 ~]# id -Z
system_u:system_r:*sshd_t*:s4-s5:c1,c2*
*
[root@msc-ishara-system1 ~]# /etc/init.d/httpd start


You first need to be in a proper user context before you do anything 
else.  Otherwise any processes you start are likely to be in the wrong 
context too.


I created a CentOS 6.10 VM, installed the mls policy, changed 
/etc/selinux/config to specify permissive and mls, touched 
/.autorelabel, rebooted to relabel filesystems, then changed 
/etc/selinux/config to enforcing and rebooted again.  If I try to ssh in 
as root, I get an error ("Unable to get valid context for root") and the 
connection is closed; /var/log/secure contains some additional error 
reporting from sshd.  That seems like a bug in selinux-policy-mls.


If I run the following command:
# semanage login -m -s staff_u root # map root to staff role
then I can ssh in as root albeit with some errors about accessing /root 
files.


Then I can do the following to switch to the sysadm role:
# newrole -r sysadm_r

I can't directly run /etc/init.d/httpd at all:
# /etc/init.d/httpd start
-bash: /etc/init.d/httpd: Permission denied

Or via service:
# service httpd start
env: /etc/init.d/httpd: Permission denied

I think -mls policy required the use of run_init to run init scripts in 
the proper context, ala the original SELinux policy:

# run_init /etc/init.d/httpd start
# ps -eZ | grep httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1704 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1706 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1707 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1708 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1709 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1710 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1711 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1712 ? 00:00:00 httpd
system_u:system_r:httpd_t:s0-s15:c0.c1023 1713 ? 00:00:00 httpd

However, if I switch levels before trying to do this, it fails:
# newrole -l s4-s5:c1,c2
# run_init /etc/init.d/httpd restart
execvp: Permission denied

And the denial is due to the change in levels:
# ausearch -i -m AVC -ts recent
type=SYSCALL msg=audit(11/07/2018 09:37:14.703:318) : arch=x86_64 
syscall=execve success=no exit=-13(Permission denied) a0=0x7fffaf68a871 
a1=0x7fffaf6893d0 a2=0x7fffaf6893e8 a3=0x7fffaf689030 items=0 ppid=1824 
pid=1838 auid=root uid=root gid=root euid=root suid=root fsuid=root 
egid=root sgid=root fsgid=root tty=pts0 ses=7 comm=run_init 
exe=/usr/sbin/run_init subj=staff_u:sysadm_r:run_init_t:s4-s5:c1,c2 
key=(null)
type=AVC msg=audit(11/07/2018 09:37:14.703:318) : avc:  denied  { 
transition } for  pid=1838 comm=run_init path=/etc/rc.d/init.d/httpd 
dev=dm-0 ino=133288 scontext=staff_u:sysadm_r:run_init_t:s4-s5:c1,c2 
tcontext=system_u:system_r:initrc_t:s0-s15:c0.c1023 tclass=process


run_init always tries to run the init script in the initrc_context, so 
you'd lose the 

selinux list move reminder

2018-11-06 Thread Stephen Smalley

Hi,

As a reminder, the selinux mailing list has moved to vger.kernel.org.
If you wish to continue following the list, please subscribe by sending 
a plaintext message containing "subscribe selinux" in the body to 
majord...@vger.kernel.org. Be advised that vger.kernel.org does not 
accept HTML email, so configure your mail clients accordingly.  If you 
have trouble subscribing, send an email to owner-selinux with a 
description of the problem, and if that fails too, let us know. Archives 
for the new list can be found at https://lore.kernel.org/selinux.


Thanks.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: SELinux MLS for Apache Process

2018-11-06 Thread Stephen Smalley

On 11/6/18 9:33 AM, Ishara Fernando wrote:

Dear all ,

I have been trying to test and see how SELinux MLS works with Apache , 
this is what I did to test


*1) As we're aware if we start apache process as the default SELinux 
user (i.e: Just as root user) , it will obtain a security context which 
has all the range of sensitivities and categories (i.e : s0-s15 , 
C0-C1023) *


[root@msc-ishara-system1 ~]# id -Z
system_u:system_r:sshd_t:*s0-s15:c0.c1023*

[root@msc-ishara-system1 ~]# ps auxZ | grep -i http
system_u:system_r:sshd_t:*s0-s15:c0.c1023* root 29161 0.0  0.4 262888 
9248 ? Ss   00:16   0:00 /usr/sbin/httpd
system_u:system_r:sshd_t:*s0-s15:c0.c1023* apache 29164 0.0  0.2 262888 
5264 ?   S    00:16   0:00 /usr/sbin/httpd



*2) Then what I did was stop apache and then Switch to a new SELinux 
role (s4-s5:c1,c2) and start Apache process as follows , apache will 
also get the same security contexts as the User ( s4-s5:c1,c2 ) *


[root@msc-ishara-system1 ~]# newrole -l s4-s5:c1,c2
Password:

[root@msc-ishara-system1 ~]# id -Z
system_u:system_r:sshd_t:*s4-s5:c1,c2
*
[root@msc-ishara-system1 ~]# /etc/init.d/httpd start


[root@msc-ishara-system1 ~]# ps auxZ  |  grep -i httpd
system_u:system_r:sshd_t:*s4-s5:c1,c2* root 29220 0.0  0.4 262888  9244 
?    Ss   00:18   0:00 /usr/sbin/httpd
system_u:system_r:sshd_t:*s4-s5:c1,c2* apache 29223 0.0  0.2 262888 5264 
?   S    00:18   0:00 /usr/sbin/httpd


*3) And now I created a file 'info.php' under /var/www/html , and then i 
changed the security context of this file as follows

*

touch  /var/www/html/info.php
chcat s0:c3 /var/www/html/info.php

*4) Now that we know the apache process is running in s4-s5:c1,c2 
security context and the file /var/www/html/info.php has s0:c3 context , 
then apache process shouldn't be able to read the /var/www/html/info.php 
file as c3 isn't read into c1,c2 apache process according to the Bell 
Lapadula model which is the security policy in SELinux MLS , but however 
when i run a curl on the apache process , it produces an output (Which 
shows the php version and stuff)

*

*curl http://localhost/info.php*

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"DTD/xhtml1-transitional.dtd">



Re: [PATCH 2/2] selinux: fix ENOMEM errors during policy reload

2018-11-01 Thread Stephen Smalley

On 10/31/2018 04:31 PM, Stephen Smalley wrote:
We'd like to 
replace the policy rwlock with RCU at some point; there is a very old 
patch that tried to do that once before, which eliminated the policy 
write lock altogether (policy switch became a single pointer update), 
but no one has yet taken that back up.


For reference, here is that old patch that tried converting the policy 
rwlock to RCU.  It applies on Linux v2.6.9 (yes, it is that old).  There 
was a more recent effort by Peter Enderborg to convert to RCU to deal 
with preempt disable holding, but I had some concerns with the approach 
to booleans, see [1]


Aside from the locking aspects, the other reason I mention it is that I 
am unsure of the implications of your model of converting within the 
sidtab for a future migration to RCU, since that doesn't seem amenable 
to a read-copy-update sequence.


[1] 
https://lore.kernel.org/selinux/20180530141104.28569-1-peter.enderb...@sony.com/



>From dca7a6167d9daa57bd7fae696d65b3ef2743b025 Mon Sep 17 00:00:00 2001
From: Kaigai Kohei 
Date: Wed, 17 Nov 2004 13:03:59 +0900
Subject: [PATCH] Updated SELinux performance patches

Hi,

This patch removes the rwlock for policydb, but significant performance
improvement for networking was NOT observed. And, this fix make
the SELinux code a bit complexity :(

- POLICY_WRLOCK/POLICY_WRUNLOCK are eliminated.
- POLICY_RDLOCK/POLICY_RDUNLOCK are redefined as rcu_read_lock()
 and rcu_read_unlock().
- policydb and sidtab is refered by pointer.
- avtab_duplicate()/hashtab_duplicate()/cond_policydb_dup() are added.
- avtab was allocated by kmalloc(), since we can't release the vmalloc()'ed
 area in RCU handler.
- I didn't touch the MLS code. We can't build the kernel
 when CONFIG_SECURITY_SELINUX_MLS=y

* When Security-Policy was loaded.
This is simple. We replace the original policydb object by the new one.
The new policydb was generated by existing code.

* When Boolean variables were modified.
This is the reason for complexity. :(
When we modify the boolean variables, p_bools(symtab[SYM_BOOLS]),
te_cond_avtab, bool_val_to_struct and cond_list in policydb have
possibility to update. When cond_policydb_dup() duplicate the policydb,
we must allocate the regions for the above members, and copy.

 * Performance Results
 I expected that performance improvement is observed in tbench,
 since stream connection referes the policydb so frequently.
 But we can't get the results expected. orz

 dbench Results [MB/s] (Bigger is better)
 -- Kernel --  - 1CPU- - 2CPU- - 4CPU- - 8CPU- -16CPU- -32CPU-
 Disable 623.2  1133.1  2044.0  3199.5  1632.5  264.7
 Enable  554.0   923.1  1138.4   624.7   406.8  123.5
 RCU 555.5  1012.6  1815.8  2939.8  1593.0  269.4
 NoLockPolicy559.5  1031.6  1848.7  3033.4  1652.3  271.5
 -

 tbench Results [MB/s] (Bigger is better)
 -- Kernel --  - 1CPU- - 2CPU- - 4CPU- - 8CPU- -16CPU- -32CPU-
 Disable 92.5   171.8   254.7   488.9   761.1   818.8
 Enable  79.6   139.6   171.088.641.219.9
 RCU 81.4   153.2   238.9   424.1   664.9   744.2
 NoLockPolicy78.8   154.4   233.5   430.8   653.9   722.0
 -
 Disable  = Vanilla 2.6.9 + SELinux Disable
 Enable   = Vanilla 2.6.9 + SELinux Enable
 RCU  = 2.6.9 + NSA SELinux(11/4)
 NoLockPolicy = 2.6.9 + NSA SELinux(11/4)
+ selinux-nolock-policydb-041110.patch

 Because we faced slowly perforamece degradation on replacing the avc_lock
 by rwlock when I tried to apply RCU to AVC, I think RCU is better than rwlock.

 I posted in 24/Aug/04
 Re: RCU issue with SELinux (Re: SELINUX performance issues)
 [write() to files on tmpfs Loop=50 Parallel=]
  -- 1CPU-- -- 2CPU-- -- 4CPU-- -- 8CPU-- --16CPU-- --32CPU--
 2.6.8.1(disable)8.29598.04308.01588.01838.01468.0037
 2.6.8.1(enable)11.8427   14.0358   78.0957  319.0451 1322.0313  too long
 2.6.8.1.rwlock 11.2485   13.8688   20.0100   49.0390   90.0200  177.0533
 2.6.8.1.rcu11.3435   11.3319   11.0464   11.0205   11.0372   11.0496

 But I feel another factor, such as the Kylene's effort, is bigger in the policydb
 case. I think it should be tuned up first.

 Thanks
---
 security/selinux/hooks.c  |  11 +-
 security/selinux/ss/avtab.c   |  38 ++-
 security/selinux/ss/avtab.h   |   5 +-
 security/selinux/ss/conditional.c | 211 ++-
 security/selinux/ss/conditional.h |   3 +
 security/selinux/ss/hashtab.c |  50 
 security/selinux/ss/hashtab.h |   7 +
 security/selinux/ss/policydb.c|   6 +
 security/selinux/ss/policydb.h|   3 +
 security/selinux/ss/services.c| 408 ++
 security/selinux/ss/services.h|   4 +-
 11 files changed, 571 insertions(+), 175 deletions(-)

diff --git a/security/selinux/hooks.c b/security/seli

Re: [PATCH 2/2] selinux: fix ENOMEM errors during policy reload

2018-10-31 Thread Stephen Smalley

On 10/31/2018 08:27 AM, Ondrej Mosnacek wrote:

Before this patch, during a policy reload the sidtab would become frozen
and trying to map a new context to SID would be unable to add a new
entry to sidtab and fail with -ENOMEM.

Such failures are usually propagated into userspace, which has no way of
distignuishing them from actual allocation failures and thus doesn't
handle them gracefully. Such situation can be triggered e.g. by the
following reproducer:

 while true; do load_policy; echo -n .; sleep 0.1; done &
 for (( i = 0; i < 1024; i++ )); do
 runcon -l s0:c$i echo -n x || break
 # or:
 # chcon -l s0:c$i  || break
 done

This patchs overhauls the sidtab so it doesn't need to be frozen during
a policy reload, thus solving the above problem.

The new SID table entries now contain two slots for the context. One of
the slots is used for the lookup and the other one is used during policy
reload to store the new converted context. Which slot is used for what
is determined by a shared index that is toggled between 0 and 1 when the
conversion is completed, together with the switch to the new policy.
After the index is toggled, the contexts in the now unused slots are
destroyed. The solution also gracefully handles conversion of entries
that are added to sidtab while the conversion is in progress.

The downside of this solution is that the sidtab now takes up
approximately twice the space and half of it is used only during policy
reload. On the other hand, this means we do not need to deal with sidtab
growing while we are allocating a new one.

Reported-by: Orion Poplawski 
Reported-by: Li Kun 
Link: https://github.com/SELinuxProject/selinux-kernel/issues/38
Signed-off-by: Ondrej Mosnacek 
---
  security/selinux/ss/mls.c  |  16 ++---
  security/selinux/ss/mls.h  |   3 +-
  security/selinux/ss/services.c |  96 +++---
  security/selinux/ss/sidtab.c   | 122 +
  security/selinux/ss/sidtab.h   |  23 ---
  5 files changed, 124 insertions(+), 136 deletions(-)

diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index cd637ee3fb11..bc3f93732658 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -441,11 +441,11 @@ int mls_setup_user_range(struct policydb *p,
   */
  int mls_convert_context(struct policydb *oldp,
struct policydb *newp,
-   struct context *c)
+   struct context *oldc,
+   struct context *newc)
  {
struct level_datum *levdatum;
struct cat_datum *catdatum;
-   struct ebitmap bitmap;
struct ebitmap_node *node;
int l, i;
  
@@ -455,28 +455,26 @@ int mls_convert_context(struct policydb *oldp,

for (l = 0; l < 2; l++) {
levdatum = hashtab_search(newp->p_levels.table,
  sym_name(oldp, SYM_LEVELS,
-  c->range.level[l].sens - 1));
+  oldc->range.level[l].sens - 
1));
  
  		if (!levdatum)

return -EINVAL;
-   c->range.level[l].sens = levdatum->level->sens;
+   newc->range.level[l].sens = levdatum->level->sens;
  
-		ebitmap_init();

-   ebitmap_for_each_positive_bit(>range.level[l].cat, node, i) {
+   ebitmap_for_each_positive_bit(>range.level[l].cat, node, 
i) {
int rc;
  
  			catdatum = hashtab_search(newp->p_cats.table,

  sym_name(oldp, SYM_CATS, i));
if (!catdatum)
return -EINVAL;
-   rc = ebitmap_set_bit(, catdatum->value - 1, 1);
+   rc = ebitmap_set_bit(>range.level[l].cat,
+catdatum->value - 1, 1);
if (rc)
return rc;
  
  			cond_resched();

}
-   ebitmap_destroy(>range.level[l].cat);
-   c->range.level[l].cat = bitmap;
}
  
  	return 0;

diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h
index 1eca02c8bc5f..00c11304f71a 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -46,7 +46,8 @@ int mls_range_set(struct context *context, struct mls_range 
*range);
  
  int mls_convert_context(struct policydb *oldp,

struct policydb *newp,
-   struct context *context);
+   struct context *oldc,
+   struct context *newc);
  
  int mls_compute_sid(struct policydb *p,

struct context *scontext,
diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
index 550a4139..292a2ccbe56f 100644
--- a/security/selinux/ss/services.c
+++ b/security/selinux/ss/services.c

Re: [PATCH 1/2] selinux: use separate table for initial SID lookup

2018-10-31 Thread Stephen Smalley

On 10/31/2018 08:27 AM, Ondrej Mosnacek wrote:

This patch separates the lookup of the initial SIDs into a separate
lookup table (implemented simply by a fixed-size array), in order to
pave the way for improving the process of converting the sidtab to a new
policy during a policy reload.

The initial SIDs are loaded directly and are skipped during sidtab
conversion, so handling them separately makes things somewhat simpler.
Since there is only a small fixed number of them, they can be stored in
a simple lookup table.

This patch also moves the fallback-to-unlabeled logic from sidtab.c to
the new helper functions in services.c that now handle the unified
lookup in both sidtab and isidtab, simplifying the sidtab interface.

Signed-off-by: Ondrej Mosnacek 
---
  security/selinux/include/security.h |   3 +
  security/selinux/ss/mls.c   |   6 +-
  security/selinux/ss/mls.h   |   2 +-
  security/selinux/ss/policydb.c  |  24 ++-
  security/selinux/ss/policydb.h  |  26 ++-
  security/selinux/ss/services.c  | 238 +++-
  security/selinux/ss/services.h  |   1 +
  security/selinux/ss/sidtab.c|  29 +---
  security/selinux/ss/sidtab.h|   3 +-
  9 files changed, 187 insertions(+), 145 deletions(-)

diff --git a/security/selinux/include/security.h 
b/security/selinux/include/security.h
index 23e762d529fa..a1b4b13c2300 100644
--- a/security/selinux/include/security.h
+++ b/security/selinux/include/security.h
@@ -221,6 +221,9 @@ struct extended_perms {
  /* definitions of av_decision.flags */
  #define AVD_FLAGS_PERMISSIVE  0x0001
  
+struct context *security_sid_to_context_struct(struct selinux_state *state,

+  u32 sid, int force);


This header is for interfaces exposed by the security server (i.e. the 
policy engine) to the AVC, hooks, and other policy enforcement code. The 
context structure is private to the security server in order to 
encapsulate the policy logic and should never be returned directly to 
code outside of the security server.  Technically you aren't actually 
exposing the structure definition but this interface isn't useful 
without doing so, so it shouldn't live here.


You could make this a services_sid_to_context_struct() interface defined 
in security/selinux/ss/services.h instead.  Or you could keep all of 
this within the sidtab, just making the isidtab part of its internal 
state, and moving this logic inside of sidtab_search() instead of 
splitting it out.



+
  void security_compute_av(struct selinux_state *state,
 u32 ssid, u32 tsid,
 u16 tclass, struct av_decision *avd,
diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index 2fe459df3c85..cd637ee3fb11 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -235,7 +235,7 @@ int mls_context_to_sid(struct policydb *pol,
   char oldc,
   char *scontext,
   struct context *context,
-  struct sidtab *s,
+  struct selinux_state *state,
   u32 def_sid)
  {
char *sensitivity, *cur_cat, *next_cat, *rngptr;
@@ -257,10 +257,10 @@ int mls_context_to_sid(struct policydb *pol,
if (!oldc) {
struct context *defcon;
  
-		if (def_sid == SECSID_NULL)

+   if (def_sid == SECSID_NULL || state == NULL)


When can state be legitimately NULL here?


return -EINVAL;
  
-		defcon = sidtab_search(s, def_sid);

+   defcon = security_sid_to_context_struct(state, def_sid, 0);
if (!defcon)
return -EINVAL;
  
diff --git a/security/selinux/ss/mls.h b/security/selinux/ss/mls.h

index 67093647576d..1eca02c8bc5f 100644
--- a/security/selinux/ss/mls.h
+++ b/security/selinux/ss/mls.h
@@ -36,7 +36,7 @@ int mls_context_to_sid(struct policydb *p,
   char oldc,
   char *scontext,
   struct context *context,
-  struct sidtab *s,
+  struct selinux_state *state,
   u32 def_sid);
  
  int mls_from_string(struct policydb *p, char *str, struct context *context,

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..8f7cd5f6e033 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -892,16 +892,12 @@ void policydb_destroy(struct policydb *p)
   * Load the initial SIDs specified in a policy database
   * structure into a SID table.
   */
-int policydb_load_isids(struct policydb *p, struct sidtab *s)
+int policydb_load_isids(struct policydb *p, struct isidtab *s)
  {
struct ocontext *head, *c;
int rc;
  
-	rc = sidtab_init(s);

-   if (rc) {
-   pr_err("SELinux:  out of memory on SID table init\n");
-   goto out;
-   }
+ 

Re: cil mlsconstrain

2018-10-23 Thread Stephen Smalley

On 10/23/2018 09:56 AM, Ted Toth wrote:



On Tue, Oct 23, 2018 at 8:39 AM Stephen Smalley <mailto:s...@tycho.nsa.gov>> wrote:


On 10/23/2018 09:33 AM, Ted Toth wrote:
 > Is it possible to modify/replace an existing mlsconstrain? In
playing
 > around I created multiple instances of a mlsconstrain and
variations of
 > mlsconstrains but haven't figured out how to clean them up as I get
 > "Error: Unknown keyword delete' when trying to delete my experiments.

Possibly I misunderstand, but can't you just remove or replace the
module that defined it previously?


We make some changes to several 'x_*' mls constraints which as far as I 
know are not part of a module.


They have to live in some module, base or otherwise.
You can extract the CIL for the module in which you defined them via 
semodule -cE , e.g. semodule -cE base.  Then you can edit 
them in that base.cil or other file and re-insert the updated one.






BTW, selinux mailing list has moved to seli...@vger.kernel.org
<mailto:seli...@vger.kernel.org>.

Thanks for the reminder now I just need gmail to remember :(


___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v6] selinux: policydb - fix byte order and alignment issues

2018-10-23 Thread Stephen Smalley

On 10/23/2018 03:02 AM, Ondrej Mosnacek wrote:

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 <
Cc: Eli Cohen 
Cc: James Morris 
Cc: Doug Ledford 
Cc:  # 4.13+
Fixes: a806f7a1616f ("selinux: Create policydb version for Infiniband support")
Signed-off-by: Ondrej Mosnacek 


Acked-by: Stephen Smalley 


---
  security/selinux/ss/policydb.c | 51 --
  1 file changed, 36 insertions(+), 15 deletions(-)

Changes in v6:
  - use U8_MAX as the limit for ibendport.port value to emphasize that it
is an 8-bit value

Changes in v5:
  - defer also assignment to 8-bit ibendport.port

Changes in v4:
  - defer assignment to 16-bit struct fields to after the range check

Changes in v3:
  - use separate buffer for the 64-bit subnet_prefix
  - add comments on the byte ordering of subnet_prefix
  - deduplicate the le32_to_cpu() calls from checks

Changes in v2:
  - add reproducer to commit message
  - update e-mail address of James Morris
  - better Cc also the old SELinux ML

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..b63ef865ce1e 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -2108,6 +2108,7 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
  {
int i, j, rc;
u32 nel, len;
+   __be64 prefixbuf[1];
__le32 buf[3];
struct ocontext *l, *c;
u32 nodebuf[8];
@@ -2217,21 +2218,30 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
goto out;
break;
}
-   case OCON_IBPKEY:
-   rc = next_entry(nodebuf, fp, sizeof(u32) * 4);
+   case OCON_IBPKEY: {
+   u32 pkey_lo, pkey_hi;
+
+   rc = next_entry(prefixbuf, fp, sizeof(u64));
+   if (rc)
+   goto out;
+
+   /* we need to have subnet_prefix in CPU order */
+   c->u.ibpkey.subnet_prefix = 
be64_to_cpu(prefixbuf[0]);
+
+   rc = next_entry(buf, fp, sizeof(u32) * 2);
if (rc)
goto out;
  
-c->u.ibpkey.subnet_prefix = be64_to_cpu(*((__be64 *)nodebuf));

+   pkey_lo = le32_to_cpu(buf[0]);
+   pkey_hi = le32_to_cpu(buf[1]);
  
-if (nodebuf[2] > 0x ||

-   nodebuf[3] > 0x) {
+   if (pkey_lo > U16_MAX || pkey_hi > U16_MAX) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibpkey.low_pkey = le32_to_cpu(nodebuf[2]);

-   c->u.ibpkey.high_pkey = le32_to_cpu(nodebuf[3]);
+   c->u.ibpkey.low_pkey  = pkey_lo;
+   c->u.ibpkey.high_pkey = pkey_hi;
  
  rc = context_read_and_validate(>context[0],

   p,
@@ -2239,7 +2249,10 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
break;
-   case OCON_IBENDPORT:
+   }
+   case OCON_IBENDPORT: {
+   u32 port;
+
rc = next_entry(buf, fp, sizeof(u32) * 2);
if (rc)
goto out;
@@ -2249,12 +2262,13 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
  
-if (buf[1] > 0xff || buf[1] == 0) {

+   port = le32_to_cpu(buf[1]);
+   if (port > U8_MAX || port == 0) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibendport.port = le32_to_cpu(buf[1]);

+   c->u.ibendport.port = port;
  
  rc = context_read_and_validate(>context[0],

   p,
@@ -2262,7 +2276,8 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,

Re: cil mlsconstrain

2018-10-23 Thread Stephen Smalley

On 10/23/2018 09:33 AM, Ted Toth wrote:
Is it possible to modify/replace an existing mlsconstrain? In playing 
around I created multiple instances of a mlsconstrain and variations of 
mlsconstrains but haven't figured out how to clean them up as I get 
"Error: Unknown keyword delete' when trying to delete my experiments.


Possibly I misunderstand, but can't you just remove or replace the 
module that defined it previously?


BTW, selinux mailing list has moved to seli...@vger.kernel.org.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v4] selinux: policydb - fix byte order and alignment issues

2018-10-19 Thread Stephen Smalley

On 10/18/2018 03:47 AM, Ondrej Mosnacek wrote:

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 <
Cc: Eli Cohen 
Cc: James Morris 
Cc: Doug Ledford 
Cc:  # 4.13+
Fixes: a806f7a1616f ("selinux: Create policydb version for Infiniband support")
Signed-off-by: Ondrej Mosnacek 
---
  security/selinux/ss/policydb.c | 46 +++---
  1 file changed, 32 insertions(+), 14 deletions(-)

Changes in v4:
  - defer assignment to 16-bit struct fields to after the range check

Changes in v3:
  - use separate buffer for the 64-bit subnet_prefix
  - add comments on the byte ordering of subnet_prefix
  - deduplicate the le32_to_cpu() calls from checks

Changes in v2:
  - add reproducer to commit message
  - update e-mail address of James Morris
  - better Cc also the old SELinux ML

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..d50668006a52 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -2108,6 +2108,7 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
  {
int i, j, rc;
u32 nel, len;
+   __be64 prefixbuf[1];
__le32 buf[3];
struct ocontext *l, *c;
u32 nodebuf[8];
@@ -2217,21 +2218,30 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
goto out;
break;
}
-   case OCON_IBPKEY:
-   rc = next_entry(nodebuf, fp, sizeof(u32) * 4);
+   case OCON_IBPKEY: {
+   u32 pkey_lo, pkey_hi;
+
+   rc = next_entry(prefixbuf, fp, sizeof(u64));
+   if (rc)
+   goto out;
+
+   /* we need to have subnet_prefix in CPU order */
+   c->u.ibpkey.subnet_prefix = 
be64_to_cpu(prefixbuf[0]);
+
+   rc = next_entry(buf, fp, sizeof(u32) * 2);
if (rc)
goto out;
  
-c->u.ibpkey.subnet_prefix = be64_to_cpu(*((__be64 *)nodebuf));

+   pkey_lo = le32_to_cpu(buf[0]);
+   pkey_hi = le32_to_cpu(buf[1]);
  
-if (nodebuf[2] > 0x ||

-   nodebuf[3] > 0x) {
+   if (pkey_lo > U16_MAX || pkey_hi > U16_MAX) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibpkey.low_pkey = le32_to_cpu(nodebuf[2]);

-   c->u.ibpkey.high_pkey = le32_to_cpu(nodebuf[3]);
+   c->u.ibpkey.low_pkey  = pkey_lo;
+   c->u.ibpkey.high_pkey = pkey_hi;
  
  rc = context_read_and_validate(>context[0],

   p,
@@ -2239,6 +2249,7 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
break;
+   }
case OCON_IBENDPORT:
rc = next_entry(buf, fp, sizeof(u32) * 2);
if (rc)
@@ -2249,13 +2260,14 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
  
-if (buf[1] > 0xff || buf[1] == 0) {

+   c->u.ibendport.port = le32_to_cpu(buf[1]);


ibendport.port is a u8 here, same issue.


+
+   if (c->u.ibendport.port > 0xff ||
+   c->u.ibendport.port == 0) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibendport.port = le32_to_cpu(buf[1]);

-
rc = context_read_and_validate(>context[0],
   p,
   fp);
@@ -3105,6 +3117,7 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,
  {
unsigned int i, j, rc;
size_t nel, len;
+   __be64 prefixbuf[1];
__le32 buf[3];
u32 nodebuf[8];
struct ocontext *c;
@@ -3192,12 +3205,17 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,

Re: [PATCH] libsepol: fix endianity in ibpkey range checks

2018-10-17 Thread Stephen Smalley

On 10/17/2018 05:18 PM, Paul Moore wrote:

On Wed, Oct 17, 2018 at 12:07 PM William Roberts
 wrote:

On Wed, Oct 17, 2018 at 7:48 AM Ondrej Mosnacek  wrote:


We need to convert from little-endian before dong range checks on the
ibpkey port numbers, otherwise we would be checking a wrong value.

Fixes: 9fbb3112769a ("libsepol: Add ibpkey ocontext handling")
Signed-off-by: Ondrej Mosnacek 
---
  libsepol/src/policydb.c | 14 ++
  1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/libsepol/src/policydb.c b/libsepol/src/policydb.c
index a6d76ca3..dc201e2f 100644
--- a/libsepol/src/policydb.c
+++ b/libsepol/src/policydb.c
@@ -2830,15 +2830,21 @@ static int ocontext_read_selinux(struct 
policydb_compat_info *info,
 break;
 case OCON_IBPKEY:
 rc = next_entry(buf, fp, sizeof(uint32_t) * 4);
-   if (rc < 0 || buf[2] > 0x || buf[3] > 
0x)
+   if (rc < 0)
 return -1;

+   c->u.ibpkey.low_pkey  = le32_to_cpu(buf[2]);
+   c->u.ibpkey.high_pkey = le32_to_cpu(buf[3]);


Ahh you're assigning a 32 bit value to a 16 bit variable low|high_pkey. I think
you need to assign them to a uint32_t if you want to actually range check them.


If you can, give me a chance to look over the kernel changes first.  I
doubt I'll see anything objectionable given the review the patches
have already seen, but one never knows.


The kernel patch has the same bug, so it will also need a re-spin.  Good 
catch.





+
+   if (c->u.ibpkey.low_pkey  > 0x ||
+   c->u.ibpkey.high_pkey > 0x)
+   return -1;
+
+   /* we want c->u.ibpkey.subnet_prefix in network
+* (big-endian) order, just memcpy it */
 memcpy(>u.ibpkey.subnet_prefix, buf,
sizeof(c->u.ibpkey.subnet_prefix));

-   c->u.ibpkey.low_pkey = le32_to_cpu(buf[2]);
-   c->u.ibpkey.high_pkey = le32_to_cpu(buf[3]);
-
 if (context_read_and_validate
 (>context[0], p, fp))
 return -1;
--
2.17.2


See job: https://travis-ci.org/SELinuxProject/selinux/jobs/442750208

Build fail with gcc:

policydb.c:2839:31: error: comparison is always false due to limited
range of data type [-Werror=type-limits]
  if (c->u.ibpkey.low_pkey  > 0x ||
^
policydb.c:2840:31: error: comparison is always false due to limited
range of data type [-Werror=type-limits]
  c->u.ibpkey.high_pkey > 0x)






___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH] libsepol: fix endianity in ibpkey range checks

2018-10-17 Thread Stephen Smalley

On 10/17/2018 10:46 AM, Ondrej Mosnacek wrote:

We need to convert from little-endian before dong range checks on the
ibpkey port numbers, otherwise we would be checking a wrong value.

Fixes: 9fbb3112769a ("libsepol: Add ibpkey ocontext handling")
Signed-off-by: Ondrej Mosnacek 


Acked-by: Stephen Smalley 


---
  libsepol/src/policydb.c | 14 ++
  1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/libsepol/src/policydb.c b/libsepol/src/policydb.c
index a6d76ca3..dc201e2f 100644
--- a/libsepol/src/policydb.c
+++ b/libsepol/src/policydb.c
@@ -2830,15 +2830,21 @@ static int ocontext_read_selinux(struct 
policydb_compat_info *info,
break;
case OCON_IBPKEY:
rc = next_entry(buf, fp, sizeof(uint32_t) * 4);
-   if (rc < 0 || buf[2] > 0x || buf[3] > 
0x)
+   if (rc < 0)
return -1;
  
+c->u.ibpkey.low_pkey  = le32_to_cpu(buf[2]);

+   c->u.ibpkey.high_pkey = le32_to_cpu(buf[3]);
+
+   if (c->u.ibpkey.low_pkey  > 0x ||
+   c->u.ibpkey.high_pkey > 0x)
+   return -1;
+
+   /* we want c->u.ibpkey.subnet_prefix in network
+* (big-endian) order, just memcpy it */
memcpy(>u.ibpkey.subnet_prefix, buf,
   sizeof(c->u.ibpkey.subnet_prefix)); >
-   c->u.ibpkey.low_pkey = le32_to_cpu(buf[2]);
-   c->u.ibpkey.high_pkey = le32_to_cpu(buf[3]);
-
if (context_read_and_validate
(>context[0], p, fp))
return -1;



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v3] selinux: policydb - fix byte order and alignment issues

2018-10-17 Thread Stephen Smalley

On 10/17/2018 10:15 AM, Ondrej Mosnacek wrote:

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 <
Cc: Eli Cohen 
Cc: James Morris 
Cc: Doug Ledford 
Cc:  # 4.13+
Fixes: a806f7a1616f ("selinux: Create policydb version for Infiniband support")
Signed-off-by: Ondrej Mosnacek 


Acked-by: Stephen Smalley 


---
  security/selinux/ss/policydb.c | 41 ++
  1 file changed, 27 insertions(+), 14 deletions(-)

Changes in v3:
  - use separate buffer for the 64-bit subnet_prefix
  - add comments on the byte ordering of subnet_prefix
  - deduplicate the le32_to_cpu() calls from checks

Changes in v2:
  - add reproducer to commit message
  - update e-mail address of James Morris
  - better Cc also the old SELinux ML

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..b9029491869b 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -2108,6 +2108,7 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
  {
int i, j, rc;
u32 nel, len;
+   __be64 prefixbuf[1];
__le32 buf[3];
struct ocontext *l, *c;
u32 nodebuf[8];
@@ -2218,21 +2219,26 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
break;
}
case OCON_IBPKEY:
-   rc = next_entry(nodebuf, fp, sizeof(u32) * 4);
+   rc = next_entry(prefixbuf, fp, sizeof(u64));
if (rc)
goto out;
  
-c->u.ibpkey.subnet_prefix = be64_to_cpu(*((__be64 *)nodebuf));

+   /* we need to have subnet_prefix in CPU order */
+   c->u.ibpkey.subnet_prefix = 
be64_to_cpu(prefixbuf[0]);
  
-if (nodebuf[2] > 0x ||

-   nodebuf[3] > 0x) {
+   rc = next_entry(buf, fp, sizeof(u32) * 2);
+   if (rc)
+   goto out;
+
+   c->u.ibpkey.low_pkey  = le32_to_cpu(buf[0]);
+   c->u.ibpkey.high_pkey = le32_to_cpu(buf[1]);
+
+   if (c->u.ibpkey.low_pkey  > 0x ||
+   c->u.ibpkey.high_pkey > 0x) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibpkey.low_pkey = le32_to_cpu(nodebuf[2]);

-   c->u.ibpkey.high_pkey = le32_to_cpu(nodebuf[3]);
-
rc = context_read_and_validate(>context[0],
   p,
   fp);
@@ -2249,13 +2255,14 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
  
-if (buf[1] > 0xff || buf[1] == 0) {

+   c->u.ibendport.port = le32_to_cpu(buf[1]);
+
+   if (c->u.ibendport.port > 0xff ||
+   c->u.ibendport.port == 0) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibendport.port = le32_to_cpu(buf[1]);

-
rc = context_read_and_validate(>context[0],
   p,
   fp);
@@ -3105,6 +3112,7 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,
  {
unsigned int i, j, rc;
size_t nel, len;
+   __be64 prefixbuf[1];
__le32 buf[3];
u32 nodebuf[8];
struct ocontext *c;
@@ -3192,12 +3200,17 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,
return rc;
break;
case OCON_IBPKEY:
-   *((__be64 *)nodebuf) = 
cpu_to_be64(c->u.ibpkey.subnet_prefix);
+   /* subnet_prefix is in CPU order */
+   prefixbuf[0] = 
cpu_to_be64(c->u.ibpkey.subnet_prefix);
  
-nodebuf[2] = cpu_to_le32(c->u.ibpkey.low_pkey);

-   nodebuf[3] = cpu_to_le32(c->u.ibpkey.

Re: Blocking exec on processes based on arguments

2018-10-16 Thread Stephen Smalley

On 10/10/2018 07:57 AM, Ville Baillie wrote:

Hi,

Does SELinux provide any sort of mechanism for blocking exec on commands
based on their command line arguments?

The proposed use case goes a little like this, allow 'wget' to access
'http://good-server-1/*' and 'http://good-server-2/*' but block access to
other hostnames and log the access type.

I understand there are probably other ways to achieve this but am wondering
if it is possible just using SELinux?


Not based on command line arguments, no.  If you wanted to provide 
SELinux-based control over the network traffic, you could configure 
iptables SECMARK rules.



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v2] selinux: fix byte order and alignment issues in policydb.c

2018-10-16 Thread Stephen Smalley

On 10/16/2018 03:09 AM, Ondrej Mosnacek wrote:

Add missing LE conversions to the Infiniband-related range checks. These
were causing a failure to load any policy with an ibendportcon rule on
BE systems. This can be reproduced by running:

cat >my_module.cil <
Cc: Eli Cohen 
Cc: James Morris 
Cc: Doug Ledford 
Cc:  # 4.13+
Fixes: a806f7a1616f ("selinux: Create policydb version for Infiniband support")
Signed-off-by: Ondrej Mosnacek 
---
  security/selinux/ss/policydb.c | 28 +++-
  1 file changed, 15 insertions(+), 13 deletions(-)

Changes in v2:
  - add reproducer to commit message
  - update e-mail address of James Morris
  - better Cc also the old SELinux ML

diff --git a/security/selinux/ss/policydb.c b/security/selinux/ss/policydb.c
index f4eadd3f7350..2b310e8f2923 100644
--- a/security/selinux/ss/policydb.c
+++ b/security/selinux/ss/policydb.c
@@ -37,6 +37,7 @@
  #include 
  #include 
  #include 
+#include 
  #include "security.h"
  
  #include "policydb.h"

@@ -2108,7 +2109,7 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
  {
int i, j, rc;
u32 nel, len;
-   __le32 buf[3];
+   __le32 buf[4];
struct ocontext *l, *c;
u32 nodebuf[8];
  
@@ -2218,20 +2219,20 @@ static int ocontext_read(struct policydb *p, struct policydb_compat_info *info,

break;
}
case OCON_IBPKEY:
-   rc = next_entry(nodebuf, fp, sizeof(u32) * 4);
+   rc = next_entry(buf, fp, sizeof(u32) * 4);
if (rc)
goto out;
  
-c->u.ibpkey.subnet_prefix = be64_to_cpu(*((__be64 *)nodebuf));

+   c->u.ibpkey.subnet_prefix = 
get_unaligned_be64(buf);
  
-if (nodebuf[2] > 0x ||

-   nodebuf[3] > 0x) {
+   if (le32_to_cpu(buf[2]) > 0x ||
+   le32_to_cpu(buf[3]) > 0x) {
rc = -EINVAL;
goto out;
}
  
-c->u.ibpkey.low_pkey = le32_to_cpu(nodebuf[2]);

-   c->u.ibpkey.high_pkey = le32_to_cpu(nodebuf[3]);
+   c->u.ibpkey.low_pkey = le32_to_cpu(buf[2]);
+   c->u.ibpkey.high_pkey = le32_to_cpu(buf[3]);


I'm wondering why the handling here is inconsistent with that of 
OCON_NODE/OCON_NODE6, which also deals with network byte order / big 
endian data.  Also it is inconsistent with the corresponding userspace 
code in libsepol for IBPKEY, which just does a memcpy() for copying 
between the subnet_prefix and the buffer.


Switching to buf entirely doesn't seem right since it is __le32 and the 
first part is actually __be64.


Maybe we ought to be splitting this into two next_entry() calls, one to 
fetch the be64 subnet prefix into an appropriately aligned and typed 
buffer and one to fetch the le32 low/high pkey values into buf?


We also need to fix the libsepol code 
(selinux/libsepol/src/policydb.c:ocontext_read_selinux) for the validity 
check at least.


  
  rc = context_read_and_validate(>context[0],

   p,
@@ -2249,7 +2250,8 @@ static int ocontext_read(struct policydb *p, struct 
policydb_compat_info *info,
if (rc)
goto out;
  
-if (buf[1] > 0xff || buf[1] == 0) {

+   if (le32_to_cpu(buf[1]) > 0xff ||
+   le32_to_cpu(buf[1]) == 0) {
rc = -EINVAL;
goto out;
}
@@ -3105,7 +3107,7 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,
  {
unsigned int i, j, rc;
size_t nel, len;
-   __le32 buf[3];
+   __le32 buf[4];
u32 nodebuf[8];
struct ocontext *c;
for (i = 0; i < info->ocon_num; i++) {
@@ -3192,12 +3194,12 @@ static int ocontext_write(struct policydb *p, struct 
policydb_compat_info *info,
return rc;
break;
case OCON_IBPKEY:
-   *((__be64 *)nodebuf) = 
cpu_to_be64(c->u.ibpkey.subnet_prefix);
+   put_unaligned_be64(c->u.ibpkey.subnet_prefix, 
buf);
  
-nodebuf[2] = cpu_to_le32(c->u.ibpkey.low_pkey);

-   nodebuf[3] = cpu_to_le32(c->u.ibpkey.high_pkey);
+   buf[2] = cpu_to_le32(c->u.ibpkey.low_pkey);
+   buf[3] = cpu_to_le32(c->u.ibpkey.high_pkey);
  
-rc = put_entry(nodebuf, sizeof(u32), 4, 

[PATCH] README: Update the SELinux mailing list location

2018-10-10 Thread Stephen Smalley
Signed-off-by: Stephen Smalley 
---
 README | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/README b/README
index 174551a1..1c009b01 100644
--- a/README
+++ b/README
@@ -1,5 +1,6 @@
-Please submit all bug reports and patches to selinux@tycho.nsa.gov.
-Subscribe via selinux-j...@tycho.nsa.gov.
+Please submit all bug reports and patches to seli...@vger.kernel.org.
+Subscribe by sending "subscribe selinux" in the body of an email
+to majord...@vger.kernel.org.
 
 Build dependencies on Fedora:
 yum install audit-libs-devel bison bzip2-devel dbus-devel dbus-glib-devel flex 
flex-devel flex-static glib2-devel libcap-devel libcap-ng-devel pam-devel 
pcre-devel python-devel setools-devel swig xmlto redhat-rpm-config
-- 
2.14.4

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


selinux list is moving

2018-10-05 Thread Stephen Smalley

Hi,

The selinux mailing list is moving to vger.kernel.org.
If you wish to continue following the list, please subscribe by sending 
a plaintext message containing "subscribe selinux" in the body to 
majord...@vger.kernel.org.


Going forward, mailing list archiving is being provided by lore, see 
https://lore.kernel.org/selinux/.  We provided the kernel.org admins 
with a snapshot of the selinux@tycho.nsa.gov mailing list archives 
yesterday that they imported so that (most) of our historical archives 
will be available from lore as well.  Unfortunately, we have not found a 
way to successfully forward subsequent postings to selinux@tycho.nsa.gov 
to the new list, so there are a few messages yesterday that did not make 
it into the new archive. You may wish to re-post those to the new list 
for posterity if you care.


Be advised that vger.kernel.org does not accept HTML email, so configure 
your mail clients accordingly.


Thanks.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: MLS dominance check behavior on el7

2018-10-04 Thread Stephen Smalley

On 09/30/2018 10:43 AM, Chris PeBenito wrote:

On 09/11/2018 04:20 PM, Stephen Smalley wrote:

On 09/11/2018 03:04 PM, Joe Nall wrote:




On Sep 11, 2018, at 1:29 PM, Stephen Smalley  wrote:

On 09/11/2018 10:41 AM, Stephen Smalley wrote:

On 09/10/2018 06:30 PM, Ted Toth wrote:
mcstrans mcscolor.c also uses the same logic I'd been using to 
check dominance so this too will no longer function as expected on 
el7. Do you any suggestions for doing a 'generic' (one not tied to 
a specific resource class) dominance check in lieu of context 
contains?
You should probably define your own permission with its own 
constraint to avoid depending on the base policy's particular 
constraint definitions.  Certainly for your own code.  For 
mcstrans, mcscolor probably ought to be switched to using at least 
a separate permission in the context class if not its own class to 
avoid overloading the meaning with pam_selinux's usage (or vice 
versa, but likely harder to change pam_selinux at this point).
It is possible to define an entirely new class, its permissions, 
and its mls constraints via a CIL module IIUC, without needing to 
change the base policy.
I don't think you can add a permission to an existing class via a 
CIL module currently, unfortunately, so you can't just extend the 
context class without modifying the base policy.  So it may be 
easier to define an entirely new class.
The class and permission ought to be specific to the usage.  For 
example, mcstrans could have its own class (mcstrans) with its own 
permissions (e.g. color_match or color_use or ...) that abstract 
away the logical check being performed.  Dominance checks performed 
for different reasons ought to use different permissions so that 
one can distinguish what TE pairs are allowed them.

Your code could likewise define and use its own class and permission.
Does that make sense?


BTW, I noticed there is another permission ("translate") defined in 
the context class and its constraint is ((h1 dom h2) or (t1 == 
mlstranslate)).  I would have guessed that it was intended as a 
front-end service check over what processes could request context 
translations from mcstrans or what contexts they could translate, 
but I don't see it being used in mcstrans anywhere.  Is this a 
legacy thing from early setransd/mcstransd days?  There is a TODO 
comment in mcstrans process_request() that suggests there was an 
intent to perform a dominance check between the requester context 
and the specified context, but that's not implemented.  Appears to 
be allowed in current policy for all domains to the setrans_t domain 
itself.


I think 'translate' predates my mcstransd work and dates from the 
original TCS implementation. There is an argument to implement that 
constraint, but we've been operating without it for so long it does 
not seem worthwhile.


Well, I guess we ought to either implement it or delete the permission 
definition from refpolicy.


I'm fine removing it.  It's just the translate permission that is 
unused, not the whole class, correct?


Correct. Only caveat is that removing translate will change the 
permission index of contains, which could break a running mcstransd upon 
a policy reload (doesn't use selinux_check_access or even the avc; won't 
flush the class/perm string mapping on a reload automatically).



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH] selinux-testsuite: update the dependencies in README.md

2018-10-04 Thread Stephen Smalley

On 10/03/2018 11:52 AM, Paul Moore wrote:

The overlayfs tests require setfattr and getfattr which are part of
the attr package in Fedora.

Signed-off-by: Paul Moore 


Acked-by: Stephen Smalley 


---
  README.md |4 +++-
  1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 2c871d3..cf90ef6 100644
--- a/README.md
+++ b/README.md
@@ -50,6 +50,7 @@ similar dependencies):
  * netlabel\_tools _(to load NetLabel configuration during `inet_socket` 
tests)_
  * iptables _(to load the `iptables SECMARK` rules during `inet_socket` tests)_
  * lksctp-tools-devel _(to build the SCTP test programs)_
+* attr _(tools used by the overlayfs tests)_
  
  On a modern Fedora system you can install these dependencies with the

  following command:
@@ -63,7 +64,8 @@ following command:
net-tools \
netlabel_tools \
iptables \
-   lksctp-tools-devel
+   lksctp-tools-devel \
+   attr
  
  The testsuite requires a pre-existing base policy configuration of SELinux,

  using either the old example policy or the reference policy as the baseline.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH] selinux: fix race when removing selinuxfs entries

2018-10-03 Thread Stephen Smalley

On 10/02/2018 11:58 AM, Al Viro wrote:

On Tue, Oct 02, 2018 at 01:18:30PM +0200, Ondrej Mosnacek wrote:

No.  With the side of Hell, No.  The bug is real, but this is
not the way to fix it.

First of all, it's still broken - e.g. mount something on a
subdirectory and watch what that thing will do to it.  And
anyone who has permission to reload policy _will_ have one
for mount.

And yes, debugfs_remove() suffers the same problem.  Frankly, the
only wish debugfs_remove() implementation inspires is to shoot it
before it breeds.  Which is the second problem with that approach -
such stuff really shouldn't be duplicated in individual filesystems.

Don't copy (let along open-code) d_walk() in there.  The guts of
dcache tree handling are subtle enough (and had more than enough
locking bugs over the years) to make spreading the dependencies
on its details all over the tree an invitation for massive PITA
down the road.

I have beginnings of patch doing that for debugfs; the same thing
should be usable for selinuxfs as well.  However, the main problem
with selinuxfs wrt policy loading is different - what to do if
sel_make_policy_nodes() fails halfway through?  And what to do
with accesses to the unholy mix of old and new nodes we currently
have left behind?

Before security_load_policy() we don't know which nodes to create;
after it we have nothing to fall back onto.  It looks like we
need to split security_load_policy() into "load", "switch over" and
"free old" parts, so that the whole thing would look like
load
create new directory trees, unconnected to the root so
they couldn't be reached by lookups until we are done
switch over
move the new directory trees in place
kill the old trees (using that invalidate+genocide carefully
combination)
free old data structures
with failures upon the first two steps handled by killing whatever detached
trees we'd created (if any) and freeing the new data structures.

However, I'd really like to have the folks familiar with selinux guts to
comment upon the feasibility of the above.  AFAICS, nobody has ever seriously
looked at that code wrt graceful error handling, etc.[*], so I'm not happy
with making inferences from what the existing code is doing.


That sounds viable to me as an approach, and hopefully the 
splitting/refactoring of security_load_policy() will be a bit easier now 
that the global selinux state is wrapped in the selinux_state structure 
and explicitly passed around.




If you are interested in getting selinuxfs into sane shape, that would
be a good place to start.  As for the kernel-side rm -rf (which is what
debugfs_remove() et.al. are trying to be)...
* it absolutely needs to be in fs/*.c - either dcache or libfs.
It's too closely tied to dcache guts to do otherwise.
* as the first step it needs to do d_invalidate(), to get rid of
anything that might be mounted on it and to prevent new mounts from appearing.
It's rather tempting to unhash everything in the victim tree at the same
time, but that needs to be done with care - I'm still not entirely happy
with the solution I've got in that area.  Alternative is to unhash them
on the way out of subtree.  simple_unlink()/simple_rmdir() are wrong
there - we don't want to bother with the parent's timestamps as we go,
for one thing; that should be done only once to parent of the root of
that subtree.  For another, we bloody well enforce the emptiness ourselves,
so this simple_empty() is pointless (especially since we have no choice other
than ignoring it anyway).

BTW, another selinuxfs unpleasantness is, the things like sel_write_enforce()
don't have any exclusion against themselves, let alone the policy reloads.
And quite a few of them obviously expect that e.g. permission check is done
against the same policy the operation will apply to, not the previous one.
That one definitely needs selinux folks involved.

[*] not too unreasonably so - anyone who gets to use _that_ as an attack
vector has already won, so it's not a security problem pretty much by
definition and running into heavy OOM at the time of policy reload is
almost certainly going to end up with the userland parts of the entire
thing not handling failures gracefully.



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-10-02 Thread Stephen Smalley

On 10/02/2018 02:48 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-21 07:40:58)

If we set the inode sid to the superblock def_sid on an invalid
context, then we lose the association to the original context value.
The support for deferred mapping of contexts requires allocating a new
SID for the invalid context and storing that SID in the inode, so that
if the context later becomes valid upon a policy update/reload, the
inode SID will refer to the now valid context.
To combine the two, we would need security_context_to_sid_core() to
save the def_sid in the context structure for invalid contexts, and
change sidtab_search_core() to use that value instead of
SECINITSID_UNLABELED for invalid SIDs.  Then the inode would be
treated as having the defcontext for access control and getxattr() w/o
CAP_MAC_ADMIN purposes, but a subsequent policy update/reload that
makes the context valid would automatically cause subsequent accesses
to the inode to start using the original context value for access
control and getxattr() purposes.  I think that's the behavior you
want.



While implementing the change I've realized that storing default context
for sidtab_search_core() in the context structure is not enough to
achieve the desired behavior. The same invalid context may exist in two
mounts with different 'defcontext', so default context can't be a
property of a context structure.

One way to address it is to propagate default context to sidtab_search() all
the way from inode hooks. But that will be a bit intrusive. Something like
avc_has_perm_default() will need to be added.

Other way is to check for context validity in inode hooks and provide a default
context to avc_has_perm() if the inode's sid is invalid. But this may have
performance implication since validity check will be done each time in fast
path.

Do you see any other options?


I think the original approach is still best.  The def_sid can be part of 
the context structure; you just need to update context_cmp() to compare 
it (as part of the first return statement) so that the same invalid 
context in two mounts with different defcontext= values will allocate 
different SIDs.  Likewise context_cpy() needs to copy the def_sid.


As a separate matter, you should also modify 
security_context_to_sid_force() to pass down the sbsec->def_sid so that 
when userspace with CAP_MAC_ADMIN sets an invalid context on an inode, 
the default context will be used in the same manner.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v5 3/5] SELinux: Prepare for PTRACE_MODE_SCHED

2018-09-27 Thread Stephen Smalley

On 09/26/2018 04:34 PM, Casey Schaufler wrote:

From: Casey Schaufler 

A ptrace access check with mode PTRACE_MODE_SCHED gets called
from process switching code. This precludes the use of audit or avc,
as the locking is incompatible. The only available check that
can be made without using avc is a comparison of the secids.
This is not very satisfactory as it will indicate possible
vulnerabilies much too aggressively.
Can you document (in the patch description and/or in the inline 
documentation in lsm_hooks.h) what locks can be safely used when this 
hook is called with PTRACE_MODE_SCHED?  rcu_read_lock() seemingly must 
be safe since it is being called by task_sid() below. Are any other 
locking primitives safe?


Does the PTRACE_MODE_SCHED check have to occur while holding the 
scheduler lock, or could it be performed before taking the lock?


Can you cite the commit or patch posting (e.g. from lore or patchwork) 
that defines PTRACE_MODE_SCHED and its usage as part of the patch 
description for context?  Is this based on the v7 patchset, e.g.

https://lore.kernel.org/lkml/nycvar.yfh.7.76.1809251437340.15...@cbobk.fhfr.pm/



Signed-off-by: Casey Schaufler 
---
  security/selinux/hooks.c | 2 ++
  1 file changed, 2 insertions(+)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index ad9a9b8e9979..160239791007 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -2267,6 +2267,8 @@ static int selinux_ptrace_access_check(struct task_struct 
*child,
u32 sid = current_sid();
u32 csid = task_sid(child);
  
+	if (mode & PTRACE_MODE_SCHED)

+   return sid == csid ? 0 : -EACCES;
IIUC, this logic is essentially the same as the uid-based check, 
including the fact that even a "privileged" process is not given any 
special handling since they always return false from ptrace_has_cap() 
for PTRACE_MODE_SCHED. If they are ok with applying IBPB whenever uids 
differ, then doing so whenever sids/contexts differ does not seem like 
an onerous thing.




if (mode & PTRACE_MODE_READ)
return avc_has_perm(_state,
sid, csid, SECCLASS_FILE, FILE__READ, NULL);



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH v5 3/5] SELinux: Prepare for PTRACE_MODE_SCHED

2018-09-26 Thread Stephen Smalley
On Wed, Sep 26, 2018, 4:35 PM Casey Schaufler 
wrote:

> From: Casey Schaufler 
>
> A ptrace access check with mode PTRACE_MODE_SCHED gets called
> from process switching code. This precludes the use of audit or avc,
> as the locking is incompatible. The only available check that
> can be made without using avc is a comparison of the secids.
> This is not very satisfactory as it will indicate possible
> vulnerabilies much too aggressively.
>

We already have a flag to disable audit. What locking conflict is presented
by the avc, which uses rcu?


> Signed-off-by: Casey Schaufler 
> ---
>  security/selinux/hooks.c | 2 ++
>  1 file changed, 2 insertions(+)
>
> diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
> index ad9a9b8e9979..160239791007 100644
> --- a/security/selinux/hooks.c
> +++ b/security/selinux/hooks.c
> @@ -2267,6 +2267,8 @@ static int selinux_ptrace_access_check(struct
> task_struct *child,
> u32 sid = current_sid();
> u32 csid = task_sid(child);
>
> +   if (mode & PTRACE_MODE_SCHED)
> +   return sid == csid ? 0 : -EACCES;
> if (mode & PTRACE_MODE_READ)
> return avc_has_perm(_state,
> sid, csid, SECCLASS_FILE, FILE__READ,
> NULL);
> --
> 2.17.1
>
>
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

[PATCH] libselinux: fix selinux_restorecon() on non-SELinux hosts

2018-09-26 Thread Stephen Smalley
The kernel only supports seclabel if it is >= 2.6.30 _and_
SELinux is enabled, since seclabel is generated by SELinux
based partly on policy (e.g. is the filesystem type configured in policy
with a labeling behavior that supports userspace labeling). For some
reason, when this logic was moved from setfiles to libselinux,
the test of whether SELinux was enabled was dropped.  Restore it.

This is necessary to enable use of setfiles on non-SELinux hosts
without requiring explicit use of the -m option.

Fixes: 602347c7422e971a5674fe2767267a96e3b4f61c ("policycoreutils: setfiles - 
Modify to use selinux_restorecon")
Reported-by: sajjad ahmed 
Signed-off-by: Stephen Smalley 
Cc: Richard Haines 
---
 libselinux/src/selinux_restorecon.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/libselinux/src/selinux_restorecon.c 
b/libselinux/src/selinux_restorecon.c
index 41f22250..34a6408a 100644
--- a/libselinux/src/selinux_restorecon.c
+++ b/libselinux/src/selinux_restorecon.c
@@ -241,6 +241,8 @@ static int exclude_non_seclabel_mounts(void)
/* Check to see if the kernel supports seclabel */
if (uname() == 0 && strverscmp(uts.release, "2.6.30") < 0)
return 0;
+   if (is_selinux_enabled() <= 0)
+   return 0;
 
fp = fopen("/proc/mounts", "re");
if (!fp)
-- 
2.14.4

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: setfiles rootfs labeling

2018-09-26 Thread Stephen Smalley

On 09/26/2018 10:18 AM, Stephen Smalley wrote:

On 09/26/2018 09:55 AM, sajjad ahmed via Selinux wrote:

Hi all,

I'm trying to use the setfiles utility (v 2.7) from policycoreutils to 
label rootfs, it seems like setfiles exclude all the directories 
straight away and labels nothing. I tried an older version (< 2.6) 
that works fine. I'm using the yocto project to build packages and 
using native setfiles utility to "label rootfs on the build system". 
Is it utility who is not doing what is supposed to?


I'm using the following command to label rootfs,
/sudosetfiles -v -r /tmp/sid/ 
/etc/selinux/refpolicy/contexts/files/file_contexts /tmp/sid//

/
/


I'll guess that your build host OS has SELinux disabled and that 
consequently /proc/mounts does not show the seclabel option for the 
filesystem.  Trying using the -m option to setfiles to ignore /proc/mounts.


I guess we should be enabling this option automatically if SELinux is 
disabled on the host?  Looks like we were skipping use of /proc/mounts 
in setfiles until moving it to use selinux_restorecon()



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: setfiles rootfs labeling

2018-09-26 Thread Stephen Smalley

On 09/26/2018 09:55 AM, sajjad ahmed via Selinux wrote:

Hi all,

I'm trying to use the setfiles utility (v 2.7) from policycoreutils to 
label rootfs, it seems like setfiles exclude all the directories 
straight away and labels nothing. I tried an older version (< 2.6) that 
works fine. I'm using the yocto project to build packages and using 
native setfiles utility to "label rootfs on the build system". Is it 
utility who is not doing what is supposed to?


I'm using the following command to label rootfs,
/sudosetfiles -v -r /tmp/sid/ 
/etc/selinux/refpolicy/contexts/files/file_contexts /tmp/sid//

/
/


I'll guess that your build host OS has SELinux disabled and that 
consequently /proc/mounts does not show the seclabel option for the 
filesystem.  Trying using the -m option to setfiles to ignore /proc/mounts.








___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-09-25 Thread Stephen Smalley

On 09/25/2018 12:03 PM, Paul Moore wrote:

On Tue, Sep 25, 2018 at 9:58 AM Stephen Smalley  wrote:

On 09/25/2018 01:45 AM, Taras Kondratiuk wrote:

Quoting Paul Moore (2018-09-24 20:46:57)

On Fri, Sep 21, 2018 at 10:39 AM Stephen Smalley  wrote:

On 09/20/2018 06:59 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-20 07:49:12)

On 09/19/2018 10:41 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-19 12:00:33)

On 09/19/2018 12:52 PM, Taras Kondratiuk wrote:


...


IMO it would be more consistent if defcontext cover all "unlabeled"
groups. It seems unlikely to me that somebody who currently uses
defcontext can somehow rely on mapping invalid labels to unlabeled
instead of default context.


Yes, and that seems more consistent with the current documentation in
the mount man page for defcontext=.

I'd be inclined to change selinux_inode_notifysecctx() to call
security_context_to_sid_default() directly instead of using
selinux_inode_setsecurity() and change security_context_to_sid_core()
and sidtab_search_core() as suggested above to save and use the def_sid
instead of SECINITSID_UNLABELED always (initializing the context def_sid
to SECINITSID_UNLABELED as the default).  selinux_inode_setsecurity() we
should leave unchanged, or if we change it at all, it should be more
like the handling in selinux_inode_setxattr().  The notifysecctx hook is
invoked by the filesystem to notify the security module of the file's
existing security context, so in that case we always want the _default
behavior, whereas the setsecurity hook is invoked by the vfs or the
filesystem to set the security context of a file to a new value, so in
that case we would only use the _force interface if the caller had
CAP_MAC_ADMIN.

Paul, what say you?  NB This would be a user-visible behavior change for
mounts specifying defcontext= on xattr filesystems; files with invalid
contexts will then show up with the defcontext value instead of the
unlabeled context.  If that's too risky, then we'd need a flag or
something to security_context_to_sid_default() to distinguish the
behaviors and only set it when called from selinux_inode_notifysecctx().


Visible changes like this are always worrisome, even though I think it
is safe to assume that the defcontext option is not widely used.  I'd
feel much better if this change was opt-in.

Which brings about it's own problems.  We have the policy capability
functionality, but that is likely a poor fit for this as the policy
capabilities are usually controlled by the Linux distribution while
the mount options are set by the system's administrator when the
filesystem is mounted.  We could add a toggle somewhere in selinuxfs,
but I really dislike that idea, and would prefer to find a different
solution if possible.  I'm not sure how much flak we would get for
introducing a new mount option, but perhaps that is the best way to
handle this: defcontext would continue to behave as it does now, but
new option X would behave as mentioned in this thread.

Thoughts?


The new option X will also mean "default context", so it will be pretty
hard to come up with a different but a sensible name. I'm afraid that
having two options with hardly distinguishable semantics will be very
confusing.

What about a kernel config option that modifies the behavior of
defcontext?


First, the existing documentation for defcontext= leaves open the door
to the proposed new behavior.  From mount(8):
"You can set the default security context for  unlabeled  files  using
defcontext= option.  This overrides the value set for unlabeled files in
the policy and requires a filesystem that supports xattr labeling."

"Unlabeled files" could just mean files without any xattr, or it could
mean all files that either lack an xattr or have an invalid one under
the policy, since both sets of files are currently mapped to the
unlabeled context.


This may be true for the major SELinux policies being shipped by
distributions, but can we say this holds true for *all* SELinux
policies in use today?


Second, under what conditions would this situation break existing
userspace?  The admin would have had to mount an xattr filesystem with
defcontext= specified, and that filesystem would have to both contain
files without any xattrs and files with invalid ones (otherwise how they
are treated by the kernel is irrelevant), and the policy would need to
distinguish access to files without xattrs vs files with invalid ones.
Seems unlikely.


I think you answered your own question.  Yes, it is unlikely, but I
*really* dislike changing visible behavior like this without some
explicit action on behalf of the user/admin.  We've done it in the
past and it has left me uneasy each time.


Third, the fact that policy maintainers remapped both SECINITSID_FILE
(the default value for defcontext) and SECINITSID_UNLABELED (used for
invalid contexts) to the unlabeled context (getting rid of file_t as a
separat

Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-09-25 Thread Stephen Smalley

On 09/25/2018 01:45 AM, Taras Kondratiuk wrote:

Quoting Paul Moore (2018-09-24 20:46:57)

On Fri, Sep 21, 2018 at 10:39 AM Stephen Smalley  wrote:

On 09/20/2018 06:59 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-20 07:49:12)

On 09/19/2018 10:41 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-19 12:00:33)

On 09/19/2018 12:52 PM, Taras Kondratiuk wrote:


...


IMO it would be more consistent if defcontext cover all "unlabeled"
groups. It seems unlikely to me that somebody who currently uses
defcontext can somehow rely on mapping invalid labels to unlabeled
instead of default context.


Yes, and that seems more consistent with the current documentation in
the mount man page for defcontext=.

I'd be inclined to change selinux_inode_notifysecctx() to call
security_context_to_sid_default() directly instead of using
selinux_inode_setsecurity() and change security_context_to_sid_core()
and sidtab_search_core() as suggested above to save and use the def_sid
instead of SECINITSID_UNLABELED always (initializing the context def_sid
to SECINITSID_UNLABELED as the default).  selinux_inode_setsecurity() we
should leave unchanged, or if we change it at all, it should be more
like the handling in selinux_inode_setxattr().  The notifysecctx hook is
invoked by the filesystem to notify the security module of the file's
existing security context, so in that case we always want the _default
behavior, whereas the setsecurity hook is invoked by the vfs or the
filesystem to set the security context of a file to a new value, so in
that case we would only use the _force interface if the caller had
CAP_MAC_ADMIN.

Paul, what say you?  NB This would be a user-visible behavior change for
mounts specifying defcontext= on xattr filesystems; files with invalid
contexts will then show up with the defcontext value instead of the
unlabeled context.  If that's too risky, then we'd need a flag or
something to security_context_to_sid_default() to distinguish the
behaviors and only set it when called from selinux_inode_notifysecctx().


Visible changes like this are always worrisome, even though I think it
is safe to assume that the defcontext option is not widely used.  I'd
feel much better if this change was opt-in.

Which brings about it's own problems.  We have the policy capability
functionality, but that is likely a poor fit for this as the policy
capabilities are usually controlled by the Linux distribution while
the mount options are set by the system's administrator when the
filesystem is mounted.  We could add a toggle somewhere in selinuxfs,
but I really dislike that idea, and would prefer to find a different
solution if possible.  I'm not sure how much flak we would get for
introducing a new mount option, but perhaps that is the best way to
handle this: defcontext would continue to behave as it does now, but
new option X would behave as mentioned in this thread.

Thoughts?


The new option X will also mean "default context", so it will be pretty
hard to come up with a different but a sensible name. I'm afraid that
having two options with hardly distinguishable semantics will be very
confusing.

What about a kernel config option that modifies the behavior of
defcontext?


First, the existing documentation for defcontext= leaves open the door 
to the proposed new behavior.  From mount(8):
"You can set the default security context for  unlabeled  files  using 
defcontext= option.  This overrides the value set for unlabeled files in 
the policy and requires a filesystem that supports xattr labeling."


"Unlabeled files" could just mean files without any xattr, or it could 
mean all files that either lack an xattr or have an invalid one under 
the policy, since both sets of files are currently mapped to the 
unlabeled context.


Second, under what conditions would this situation break existing 
userspace?  The admin would have had to mount an xattr filesystem with 
defcontext= specified, and that filesystem would have to both contain 
files without any xattrs and files with invalid ones (otherwise how they 
are treated by the kernel is irrelevant), and the policy would need to 
distinguish access to files without xattrs vs files with invalid ones. 
Seems unlikely.


Third, the fact that policy maintainers remapped both SECINITSID_FILE 
(the default value for defcontext) and SECINITSID_UNLABELED (used for 
invalid contexts) to the unlabeled context (getting rid of file_t as a 
separate type, aliased to unlabeled_t) long ago suggests that there is 
no meaningful difference there.


I'm inclined to just change the behavior for defcontext= unconditionally 
and have it apply to both native and xattr labeling.  If that's a no-go, 
then the simplest solution is to just leave defcontext= behavior 
unchanged for xattr labeling and only implement the new semantics for 
native labeling.  That's just a matter of adding a flag to 
security_context_to_sid_default

Re: [PATCH v4 00/19] LSM: Module stacking for SARA and Landlock

2018-09-24 Thread Stephen Smalley

On 09/23/2018 01:09 PM, Casey Schaufler wrote:

On 9/23/2018 8:59 AM, Tetsuo Handa wrote:

On 2018/09/23 11:43, Kees Cook wrote:

I'm excited about getting this landed!

Soon. Real soon. I hope. I would very much like for
someone from the SELinux camp to chime in, especially on
the selinux_is_enabled() removal.

Agreed.


This patchset from Casey lands before the patchset from Kees, doesn't it?


That is up for negotiation. We may end up combining them.


OK, a few comments (if I didn't overlook something).

   lsm_early_cred()/lsm_early_task() are called from only __init functions.


True.


   lsm_cred_alloc()/lsm_file_alloc() are called from only security/security.c .


Also true.


   lsm_early_inode() should be avoided because it is not appropriate to
   call panic() when lsm_early_inode() is called after __init phase.


You're correct. In fact, lsm_early_inode() isn't needed at all
until multiple inode using modules are supported.


   Since all free hooks are called when one of init hooks failed, each
   free hook needs to check whether init hook was called. An example is
   inode_free_security() in security/selinux/hooks.c (but not addressed in
   this patch).


I *think* that selinux_inode_free_security() is safe in this
case because the blob will be zeroed, hence isec->list will
be NULL.


That's not safe - look more closely at what list_empty_careful() tests, 
and then think about what happens when list_del_init() gets called on 
that isec->list.  selinux_inode_free_security() presumes that 
selinux_inode_alloc_security() has been called already.  If you are 
breaking that assumption, you have to fix it.


Is there a reason you can't make inode_alloc_security() return void 
since you moved the allocation to the framework?  Unfortunate that 
inode_init_security name is already in use for another purpose since 
essentially you have reduced these hooks to initialization only.





   This patchset might fatally prevent LKM-based LSM modules, for LKM-based
   LSMs cannot count on lsm_*_alloc() because size for lsm_*_alloc() cannot
   be updated upon loading LKM-based LSMs.


LKM based security modules will require dynamically sized blobs.
These can be added to the scheme used here. Each blob would get a
header identifying the modules for which it contains data. When an
LKM is registered if has to declare it's blob space requirements
and gets back the offsets. All alloc operations have to put their
marks in the header. All LKM blob users have to check that the blob
they are looking at has the required data.

module_cred(struct cred *cred) {
return cred->security + module_blob_sizes.lbs_cred;
}

becomes

module_cred(struct cred *cred) {
if (blob_includes(module_id))
return cred->security + module_blob_sizes.lbs_cred;
return NULL;
}

and the calling code needs to accept a NULL return.
Blobs can never get smaller because readjusting the offsets
isn't going to work, so unloading an LKM security module isn't
going to be as complete as you might like. There may be a way
around this if you unload all the LKM modules, but that's a
special case and there may be dragon lurking in the mist.


  If security_file_free() is called
   regardless of whether lsm_file_cache is defined, LKM-based LSMs can be
   loaded using current behavior (apart from the fact that legitimate
   interface for appending to security_hook_heads is currently missing).
   How do you plan to handle LKM-based LSMs?


My position all along has been that I don't plan to handle LKM
based LSMs, but that I won't do anything to prevent someone else
from adding them later. I believe that I've done that. Several
designs, including a separate list for dynamically loaded modules
have been proposed. I think some of those would work.


  include/linux/lsm_hooks.h  |6 ++
  security/security.c|   31 ++-
  security/smack/smack_lsm.c |8 +++-
  3 files changed, 15 insertions(+), 30 deletions(-)

diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
index 7e8b32f..8014614 100644
--- a/include/linux/lsm_hooks.h
+++ b/include/linux/lsm_hooks.h
@@ -2095,13 +2095,11 @@ static inline void __init yama_add_hooks(void) { }
  static inline void loadpin_add_hooks(void) { };
  #endif
  
-extern int lsm_cred_alloc(struct cred *cred, gfp_t gfp);

  extern int lsm_inode_alloc(struct inode *inode);
  
  #ifdef CONFIG_SECURITY

-void lsm_early_cred(struct cred *cred);
-void lsm_early_inode(struct inode *inode);
-void lsm_early_task(struct task_struct *task);
+void __init lsm_early_cred(struct cred *cred);
+void __init lsm_early_task(struct task_struct *task);
  #endif
  
  #endif /* ! __LINUX_LSM_HOOKS_H */

diff --git a/security/security.c b/security/security.c
index e7c85060..341e8df 100644
--- a/security/security.c
+++ b/security/security.c
@@ -267,7 +267,7 @@ int unregister_lsm_notifier(struct notifier_block *nb)
   *
   * Returns 0, or -ENOMEM if memory can't be 

Re: Bug in selinux on ubuntu 16.04 with kernel 4.15.0-34

2018-09-21 Thread Stephen Smalley

On 09/21/2018 04:50 AM, Benjamin Schüle wrote:

Hello,

  just found a bug in selinux. It appears on ubuntu 16.04 with kernel
4.15, but not with kernel 4.4.

What's going wrong:
Copy a link with "-a" option while selinux is on.


steps to reproduce:
   ~$ mkdir -p a/b
   ~$ ln -s b a/c
   ~$ cp -a a b
   cp: failed to restore the default file creation context: Invalid argument


Results of my investigation:

The "cp" of coreutils is calling "setfscreatecon (NULL)" to restore
the default file creation context (coreutils-8.30/src/copy.c:1771) as
it is stated in the selinux api
(/libselinux/include/selinux/selinux.h:71).

As we see in the result of strace below, the kernel returns an -1 on
try to restore the default file creation context. So, in my opinion,
is the bug has to be in the selinux_setprocattr method in the
security/selinux/hooks.c file.


Part of "strace  cp -a a b"

lgetxattr("a/c", "security.selinux",
"system_u:object_r:user_home_dir_t:s0", 255) = 37
readlink("a/c", "b", 2) = 1
symlink("b", "b/a/c")   = 0
open("/proc/self/task/2136/attr/fscreate", O_RDWR|O_CLOEXEC) = 3
write(3, NULL, 0)   = -1 EINVAL (Invalid argument)
close(3)= 0
open("/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=2995, ...}) = 0
read(3, "# Locale name alias data base.\n#"..., 4096) = 2995
read(3, "", 4096)   = 0
close(3)


This appears to be Ubuntu-specific; I can't reproduce upstream.  If you 
are able to reproduce with an upstream kernel, let us know; otherwise, 
file a bug with Ubuntu.  A quick look at the Ubuntu kernel git tree 
shows the following commit which would explain this regression.


commit 36788bfe15f16b2eba39d0e563ae8027c5072b98
Author: Colin Ian King 
Date:   Tue Oct 3 13:12:54 2017 +0100

UBUNTU: SAUCE: LSM stacking: check for invalid zero sized writes

BugLink: http://bugs.launchpad.net/bugs/1720779
BugLink: http://bugs.launchpad.net/bugs/1763062


Writing zero bytes to /proc/$pid/task/$pid/attr/context via
security_setprocattr cause an oops in memcpy_erms. Fix this by
checking for zero size and returning -EINVAL for this invalid
write size.

Detected by running stress-ng --procfs 0

Signed-off-by: Colin Ian King 
Signed-off-by: Seth Forshee 
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-09-21 Thread Stephen Smalley

On 09/20/2018 06:59 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-20 07:49:12)

On 09/19/2018 10:41 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-19 12:00:33)

On 09/19/2018 12:52 PM, Taras Kondratiuk wrote:

When files on NFSv4 server are not properly labeled (label doesn't match
a policy on a client) they will end up with unlabeled_t type which is
too generic. We would like to be able to set a default context per
mount. 'defcontext' mount option looks like a nice solution, but it
doesn't seem to be fully implemented for native labeling. Default
context is stored, but is never used.

The patch adds a fallback to a default context if a received context is
invalid. If the inode context is already initialized, then it is left
untouched to preserve a context set locally on a client.


Can you explain the use case further?  Why are you exporting a
filesystem with security labeling enabled to a client that doesn't
understand all of the labels used within it?  Why wouldn't you just
disable NFSv4 security labeling and/or use a regular context= mount to
assign a single context to all files in the mount?


Client and server are two embedded devices. They are part of a bigger
modular system and normally run the same SW version, so they understand
each others NFSv4 SELinux labels. But during migration from one SW
version to another a client and a server may run different versions for
some time.

The immediate issue I'm trying to address is a migration between
releases with and without SELinux policy. A client (with policy) gets
initial SID labels from a server (without policy). Those labels are
considered invalid, so files remain unlabeled. This also causes lots of
errors from nfs_setsecurity() in dmesg.


Why are you enabling SELinux on the server without loading a policy?
Are you concerned about denials on the server? For that, you could
always run it permissive until you are confident you have a working policy.

Why are you enabling security_label in exports before you have a policy
loaded?  It doesn't appear that will ever work, since nfsd asks the
security module for the labels, not the local filesystem directly.

I understand that this doesn't fully address your use case, but it seems
like you could avoid this particular situation altogether just by
loading a policy (at which point your server can return actual contexts)
or by removing security_label from your exports (at which point your
server won't try returning contexts and the client will just apply the
default for nfs) until you get to the point of loading a policy.


It wasn't intentional configuration. Server is running v4.4.x kernel
that had security labels enabled by default for NFS 4.2. This was a bug:
https://bugzilla.redhat.com/show_bug.cgi?id=1406885
Commit that introduced security_label 32ddd944a056 ("nfsd: opt in to
labeled nfs per export") appeared in v4.11 only.

We hit this bug during migration to newer releases with SELinux, but the
older release is already in the field and we need to handle it.


Ok, I understand the kernel bug, but not why your servers are in a state 
where SELinux is enabled but no policy is loaded.  That is not a 
well-tested code path aside from early system initialization prior to 
first policy load by systemd/init.  You would be better off either 
disabling SELinux on the servers entirely (thereby automatically 
disabling NFSv4.2 security labeling) or installing/loading a policy on 
the servers (thereby enabling them to produce valid security labels for 
the client at least to the extent that they agree on policy).  If you 
are concerned about denials on the server, then you could always leave 
the servers permissive initially and collect audit logs until you are 
confident your policy is adequate.








To be clear, defcontext= doesn't work that way for local/FS_USE_XATTR
filesystems. The context specified by it is only used for:
1) files that don't implement the xattr inode operations at all,
2) files that lack a security.selinux xattr,
3) the MLS portion of the context if it was missing (strictly as a
legacy compatibility mechanism for RHEL4 which predated the enabling of
the MLS field/logic).

A file with a security.selinux xattr that is invalid under policy for
any reason other than a missing MLS field will be handled as having the
unlabeled context.


inode_doinit_with_dentry() invokes security_context_to_sid_default()
that invokes security_context_to_sid_core() with 'force' flag. Won't
sidtab_context_to_sid() in this case allocate a new SID for the invalid
xattr context instead of leaving it unlabeled?


It will be treated as having the unlabeled context for access control
purposes and that is what getxattr will return to userspace processes
unless they have CAP_MAC_ADMIN and SELinux mac_admin permission, but
internally SELinux will keep track of the original xattr context value
and will later retry to map it upon a policy reload, switching over to
using it for acce

Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-09-20 Thread Stephen Smalley

On 09/19/2018 10:41 PM, Taras Kondratiuk wrote:

Quoting Stephen Smalley (2018-09-19 12:00:33)

On 09/19/2018 12:52 PM, Taras Kondratiuk wrote:

When files on NFSv4 server are not properly labeled (label doesn't match
a policy on a client) they will end up with unlabeled_t type which is
too generic. We would like to be able to set a default context per
mount. 'defcontext' mount option looks like a nice solution, but it
doesn't seem to be fully implemented for native labeling. Default
context is stored, but is never used.

The patch adds a fallback to a default context if a received context is
invalid. If the inode context is already initialized, then it is left
untouched to preserve a context set locally on a client.


Can you explain the use case further?  Why are you exporting a
filesystem with security labeling enabled to a client that doesn't
understand all of the labels used within it?  Why wouldn't you just
disable NFSv4 security labeling and/or use a regular context= mount to
assign a single context to all files in the mount?


Client and server are two embedded devices. They are part of a bigger
modular system and normally run the same SW version, so they understand
each others NFSv4 SELinux labels. But during migration from one SW
version to another a client and a server may run different versions for
some time.

The immediate issue I'm trying to address is a migration between
releases with and without SELinux policy. A client (with policy) gets
initial SID labels from a server (without policy). Those labels are
considered invalid, so files remain unlabeled. This also causes lots of
errors from nfs_setsecurity() in dmesg.


Why are you enabling SELinux on the server without loading a policy? 
Are you concerned about denials on the server? For that, you could 
always run it permissive until you are confident you have a working policy.


Why are you enabling security_label in exports before you have a policy 
loaded?  It doesn't appear that will ever work, since nfsd asks the 
security module for the labels, not the local filesystem directly.


I understand that this doesn't fully address your use case, but it seems 
like you could avoid this particular situation altogether just by 
loading a policy (at which point your server can return actual contexts) 
or by removing security_label from your exports (at which point your 
server won't try returning contexts and the client will just apply the 
default for nfs) until you get to the point of loading a policy.



Using 'context=' at mount point level is an option, but in a normal case
when both sides have a policy we need more granular labels. It is
possible to detect a case when a server doesn't have a policy and
remount with 'context=', but this special case handling looks a bit
ugly. Having something like 'defcontext' whould allow to avoid this
special case and unconditionally assign default context to the
mountpoint.

'defcontext' may also help during migration between SELinux-enabled
releases if a new release introduces labels that are not recognized by
older release. In this case they can also fallback to defcontext.


This is the more interesting case.  And what would these defcontext 
values be?  A context that is generally accessible to all domains on the 
client?  Or one that is restricted to only unconfined domains?  Would it 
be fundamentally different from unlabeled?  Will it really differ 
per-mount, and if so, why?






To be clear, defcontext= doesn't work that way for local/FS_USE_XATTR
filesystems. The context specified by it is only used for:
1) files that don't implement the xattr inode operations at all,
2) files that lack a security.selinux xattr,
3) the MLS portion of the context if it was missing (strictly as a
legacy compatibility mechanism for RHEL4 which predated the enabling of
the MLS field/logic).

A file with a security.selinux xattr that is invalid under policy for
any reason other than a missing MLS field will be handled as having the
unlabeled context.


inode_doinit_with_dentry() invokes security_context_to_sid_default()
that invokes security_context_to_sid_core() with 'force' flag. Won't
sidtab_context_to_sid() in this case allocate a new SID for the invalid
xattr context instead of leaving it unlabeled?


It will be treated as having the unlabeled context for access control 
purposes and that is what getxattr will return to userspace processes 
unless they have CAP_MAC_ADMIN and SELinux mac_admin permission, but 
internally SELinux will keep track of the original xattr context value 
and will later retry to map it upon a policy reload, switching over to 
using it for access control and getxattr if it becomes valid under a new 
policy.  That support was added to support scenarios where a package 
manager sets a file context before it has loaded the policy module that 
defines it, or scenarios where one is generating a filesystem image for 
another OS/release with different policy. That is likely something you

Re: [PATCH] checkpolicy: remove extraneous policy build noise

2018-09-19 Thread Stephen Smalley

On 09/19/2018 03:41 PM, William Roberts wrote:



On Wed, Sep 19, 2018 at 12:36 PM Stephen Smalley <mailto:s...@tycho.nsa.gov>> wrote:


On 09/19/2018 03:21 PM, William Roberts wrote:
 > Some people might be checking this output since it's been there
so long,
 > -s would be a good way to go.
 >
 > Alternatively, a way to bring back this information via a verbose
option
 > -V could
 > be considered.
 >
 > Either way, a simple logging mechanism analogous to
 > LOGV/LOGW/LOGE could be useful, I wonder what subordinate routines
 > are logging. IIRC it was all fprintf(stderr) stuff in libselinux
proper
 > as you allude
 > to in the redirection of stdout comment. We don't need to address
this
 > in this
 > patch, but we may want to consider it at some point.
 >
 > I would lean towards a silent flag as it's backwards compatible,
 > but noting that it doesn't suppress subordinate callers.
 >
 > I would also yield that opinion, as removing it works for me.

I'm ok dropping the output unless someone knows of an existing user
that
relies upon it (which I can't really envision).


Why don't we extend the review period to 72 hours, and ill apply this
Friday unless we hear of this breaking someone. Essentially
consider this a soft-ack.


With regard to subordinate routines, libsepol has sepol_debug(0) or
sepol_msg_set_callback() to suppress or redirect its logging.

checkpolicy doesn't use libselinux but it likewise has
selinux_set_callback().


What about things like:
libselinux/src/load_policy.c:299:fprintf(stderr, "libselinux:  %s\n", 
errormsg);


Yes, there are a few lingering cases that ought to be converted over to 
selinux_log().




Also utils and others are using fprintf directly perhaps something 
we wish to make common

across utilities and subordinate libs.


No, it is completely appropriate for the utilities to do it directly. 
Only the library should be using the callbacks.





 >
 > On Wed, Sep 19, 2018 at 12:13 PM Nick Kralevich via Selinux
 > mailto:selinux@tycho.nsa.gov>
<mailto:selinux@tycho.nsa.gov <mailto:selinux@tycho.nsa.gov>>> wrote:
 >
 >     Reduce noise when calling the checkpolicy command line. In
Android, this
 >     creates unnecessary build noise which we'd like to avoid.
 >
 > https://en.wikipedia.org/wiki/Unix_philosophy
 >
 >        Rule of Silence
 >        Developers should design programs so that they do not print
 >        unnecessary output. This rule aims to allow other programs
 >        and developers to pick out the information they need from a
 >        program's output without having to parse verbosity.
 >
 >     An alternative approach would be to add a -s (silent) option
to these
 >     tools, or to have the Android build system redirect stdout to
/dev/null.
 >
 >     Signed-off-by: Nick Kralevich mailto:n...@google.com> <mailto:n...@google.com <mailto:n...@google.com>>>
 >     ---
 >       checkpolicy/checkmodule.c |  8 
 >       checkpolicy/checkpolicy.c | 11 ---
 >       2 files changed, 19 deletions(-)
 >
 >     diff --git a/checkpolicy/checkmodule.c
b/checkpolicy/checkmodule.c
 >     index 46ce258f..8edc1f8c 100644
 >     --- a/checkpolicy/checkmodule.c
 >     +++ b/checkpolicy/checkmodule.c
 >     @@ -228,7 +228,6 @@ int main(int argc, char **argv)
 >                      if (optind != argc)
 >                              usage(argv[0]);
 >              }
 >     -       printf("%s:  loading policy configuration from %s\n",
 >     argv[0], file);
 >
 >              /* Set policydb and sidtab used by libsepol service
functions
 >                 to my structures, so that I can directly populate and
 >     @@ -302,8 +301,6 @@ int main(int argc, char **argv)
 >
 >              sepol_sidtab_destroy();
 >
 >     -       printf("%s:  policy configuration loaded\n", argv[0]);
 >     -
 >              if (outfile) {
 >                      FILE *outfp = fopen(outfile, "w");
 >
 >     @@ -313,16 +310,11 @@ int main(int argc, char **argv)
 >                      }
 >
 >                      if (!cil) {
 >     -                       printf("%s:  writing binary
representation
 >     (version %d) to %s\n",
 >     -                                  argv[0], policyvers, outfile);
 >     -
 >                              if (write_binary_policy(,
 >     outfp) != 0) {
 >

Re: [PATCH] checkpolicy: remove extraneous policy build noise

2018-09-19 Thread Stephen Smalley

On 09/19/2018 03:21 PM, William Roberts wrote:

Some people might be checking this output since it's been there so long,
-s would be a good way to go.

Alternatively, a way to bring back this information via a verbose option 
-V could

be considered.

Either way, a simple logging mechanism analogous to
LOGV/LOGW/LOGE could be useful, I wonder what subordinate routines
are logging. IIRC it was all fprintf(stderr) stuff in libselinux proper 
as you allude
to in the redirection of stdout comment. We don't need to address this 
in this

patch, but we may want to consider it at some point.

I would lean towards a silent flag as it's backwards compatible,
but noting that it doesn't suppress subordinate callers.

I would also yield that opinion, as removing it works for me.


I'm ok dropping the output unless someone knows of an existing user that 
relies upon it (which I can't really envision).


With regard to subordinate routines, libsepol has sepol_debug(0) or 
sepol_msg_set_callback() to suppress or redirect its logging.


checkpolicy doesn't use libselinux but it likewise has 
selinux_set_callback().




On Wed, Sep 19, 2018 at 12:13 PM Nick Kralevich via Selinux 
mailto:selinux@tycho.nsa.gov>> wrote:


Reduce noise when calling the checkpolicy command line. In Android, this
creates unnecessary build noise which we'd like to avoid.

https://en.wikipedia.org/wiki/Unix_philosophy

   Rule of Silence
   Developers should design programs so that they do not print
   unnecessary output. This rule aims to allow other programs
   and developers to pick out the information they need from a
   program's output without having to parse verbosity.

An alternative approach would be to add a -s (silent) option to these
tools, or to have the Android build system redirect stdout to /dev/null.

Signed-off-by: Nick Kralevich mailto:n...@google.com>>
---
  checkpolicy/checkmodule.c |  8 
  checkpolicy/checkpolicy.c | 11 ---
  2 files changed, 19 deletions(-)

diff --git a/checkpolicy/checkmodule.c b/checkpolicy/checkmodule.c
index 46ce258f..8edc1f8c 100644
--- a/checkpolicy/checkmodule.c
+++ b/checkpolicy/checkmodule.c
@@ -228,7 +228,6 @@ int main(int argc, char **argv)
                 if (optind != argc)
                         usage(argv[0]);
         }
-       printf("%s:  loading policy configuration from %s\n",
argv[0], file);

         /* Set policydb and sidtab used by libsepol service functions
            to my structures, so that I can directly populate and
@@ -302,8 +301,6 @@ int main(int argc, char **argv)

         sepol_sidtab_destroy();

-       printf("%s:  policy configuration loaded\n", argv[0]);
-
         if (outfile) {
                 FILE *outfp = fopen(outfile, "w");

@@ -313,16 +310,11 @@ int main(int argc, char **argv)
                 }

                 if (!cil) {
-                       printf("%s:  writing binary representation
(version %d) to %s\n",
-                                  argv[0], policyvers, outfile);
-
                         if (write_binary_policy(,
outfp) != 0) {
                                 fprintf(stderr, "%s:  error writing
%s\n", argv[0], outfile);
                                 exit(1);
                         }
                 } else {
-                       printf("%s:  writing CIL to %s\n",argv[0],
outfile);
-
                         if (sepol_module_policydb_to_cil(outfp,
, 0) != 0) {
                                 fprintf(stderr, "%s:  error writing
%s\n", argv[0], outfile);
                                 exit(1);
diff --git a/checkpolicy/checkpolicy.c b/checkpolicy/checkpolicy.c
index fbda4558..12c4c405 100644
--- a/checkpolicy/checkpolicy.c
+++ b/checkpolicy/checkpolicy.c
@@ -512,8 +512,6 @@ int main(int argc, char **argv)
                 if (optind != argc)
                         usage(argv[0]);
         }
-       printf("%s:  loading policy configuration from %s\n",
argv[0], file);
-
         /* Set policydb and sidtab used by libsepol service functions
            to my structures, so that I can directly populate and
            manipulate them. */
@@ -623,8 +621,6 @@ int main(int argc, char **argv)
         if (policydb_load_isids(, ))
                 exit(1);

-       printf("%s:  policy configuration loaded\n", argv[0]);
-
         if (outfile) {
                 outfp = fopen(outfile, "w");
                 if (!outfp) {
@@ -636,8 +632,6 @@ int main(int argc, char **argv)

                 if (!cil) {
                         if (!conf) {
-                               printf("%s:  writing binary
representation (version %d) to %s\n", argv[0], policyvers, outfile);
-
                         

Re: [RFC PATCH] selinux: add a fallback to defcontext for native labeling

2018-09-19 Thread Stephen Smalley

On 09/19/2018 12:52 PM, Taras Kondratiuk wrote:

When files on NFSv4 server are not properly labeled (label doesn't match
a policy on a client) they will end up with unlabeled_t type which is
too generic. We would like to be able to set a default context per
mount. 'defcontext' mount option looks like a nice solution, but it
doesn't seem to be fully implemented for native labeling. Default
context is stored, but is never used.

The patch adds a fallback to a default context if a received context is
invalid. If the inode context is already initialized, then it is left
untouched to preserve a context set locally on a client.


Can you explain the use case further?  Why are you exporting a 
filesystem with security labeling enabled to a client that doesn't 
understand all of the labels used within it?  Why wouldn't you just 
disable NFSv4 security labeling and/or use a regular context= mount to 
assign a single context to all files in the mount?


To be clear, defcontext= doesn't work that way for local/FS_USE_XATTR 
filesystems. The context specified by it is only used for:

1) files that don't implement the xattr inode operations at all,
2) files that lack a security.selinux xattr,
3) the MLS portion of the context if it was missing (strictly as a 
legacy compatibility mechanism for RHEL4 which predated the enabling of 
the MLS field/logic).


A file with a security.selinux xattr that is invalid under policy for 
any reason other than a missing MLS field will be handled as having the 
unlabeled context.


So this would be a divergence in semantics for defcontext= between 
local/FS_USE_XATTR and NFS/FS_USE_NATIVE filesystems.




Signed-off-by: Taras Kondratiuk 
---
  security/selinux/hooks.c | 25 -
  1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index ad9a9b8e9979..f7debe798bf5 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -6598,7 +6598,30 @@ static void selinux_inode_invalidate_secctx(struct inode 
*inode)
   */
  static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 
ctxlen)
  {
-   return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, 
ctxlen, 0);
+   struct superblock_security_struct *sbsec;
+   struct inode_security_struct *isec;
+   int rc;
+
+   rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, 
ctxlen, 0);


In this case, we likely don't gain much by reusing 
selinux_inode_setsecurity() here and could just inline the relevant 
portion of it if we were to make this change.  Logically they mean 
different things.



+
+   /*
+* In case of Native labeling with defcontext mount option fall back
+* to a default SID if received context is invalid.
+*/
+   if (rc == -EINVAL) {
+   sbsec = inode->i_sb->s_security;
+   if (sbsec->behavior == SECURITY_FS_USE_NATIVE &&
+   sbsec->flags & DEFCONTEXT_MNT) {
+   isec = inode->i_security;
+   if (!isec->initialized) {
+   isec->sclass = 
inode_mode_to_security_class(inode->i_mode);
+   isec->sid = sbsec->def_sid;
+   isec->initialized = 1;
+   }
+   rc = 0;
+   }
+   }
+   return rc;
  }
  
  /*




___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: MLS dominance check behavior on el7

2018-09-12 Thread Stephen Smalley

On 09/11/2018 04:59 PM, Ted Toth wrote:
That's awesome and now it's got me thinking about other 
classes/permissions that we could implement. Can cil macros can be 
referenced in .te/.if files?


Not sure I understand your question.  You can't directly embed cil 
statements in .te/.if files.  However, if you define a class/permission 
in a .cil module, you can certainly specify a require on it and use it 
from a conventional .te/.if module, ala:

$ cat > usemcstrans.te <On Tue, Sep 11, 2018 at 2:27 PM Stephen Smalley <mailto:s...@tycho.nsa.gov>> wrote:


On 09/11/2018 02:49 PM, Ted Toth wrote:
 > Yes I too noticed the translate permission but couldn't find any
info
 > related to it intended purpose. Regarding CIL unfortunately I
have zero
 > experience with it but I've installed the compiler and started
reading
 > through https://github.com/SELinuxProject/cil/wiki (any other
pointers
 > to useful info would be appreciated). I have written lots of policy
 > would it be possible to add a class/permissions/mlsconstraints in an
 > old-fashion policy module?

The older binary modules didn't support those kinds of statements
outside of the base module.  Try this:
$ cat > mcstrans.cil <
 > On Tue, Sep 11, 2018 at 1:27 PM Stephen Smalley
mailto:s...@tycho.nsa.gov>
 > <mailto:s...@tycho.nsa.gov <mailto:s...@tycho.nsa.gov>>> wrote:
 >
 >     On 09/11/2018 10:41 AM, Stephen Smalley wrote:
 >      > On 09/10/2018 06:30 PM, Ted Toth wrote:
 >      >> mcstrans mcscolor.c also uses the same logic I'd been
using to
 >     check
 >      >> dominance so this too will no longer function as expected on
 >     el7. Do
 >      >> you any suggestions for doing a 'generic' (one not tied to a
 >     specific
 >      >> resource class) dominance check in lieu of context contains?
 >      >
 >      > You should probably define your own permission with its own
 >     constraint
 >      > to avoid depending on the base policy's particular constraint
 >      > definitions.  Certainly for your own code.  For mcstrans,
mcscolor
 >      > probably ought to be switched to using at least a separate
 >     permission in
 >      > the context class if not its own class to avoid
overloading the
 >     meaning
 >      > with pam_selinux's usage (or vice versa, but likely harder
to change
 >      > pam_selinux at this point).
 >      >
 >      > It is possible to define an entirely new class, its
permissions,
 >     and its
 >      > mls constraints via a CIL module IIUC, without needing to
change the
 >      > base policy.
 >      >
 >      > I don't think you can add a permission to an existing
class via a
 >     CIL
 >      > module currently, unfortunately, so you can't just extend the
 >     context
 >      > class without modifying the base policy.  So it may be
easier to
 >     define
 >      > an entirely new class.
 >      >
 >      > The class and permission ought to be specific to the
usage.  For
 >      > example, mcstrans could have its own class (mcstrans) with
its own
 >      > permissions (e.g. color_match or color_use or ...) that
abstract
 >     away
 >      > the logical check being performed.  Dominance checks
performed for
 >      > different reasons ought to use different permissions so
that one can
 >      > distinguish what TE pairs are allowed them.
 >      >
 >      > Your code could likewise define and use its own class and
permission.
 >      >
 >      > Does that make sense?
 >
 >     BTW, I noticed there is another permission ("translate")
defined in the
 >     context class and its constraint is ((h1 dom h2) or (t1 ==
 >     mlstranslate)).  I would have guessed that it was intended as a
 >     front-end service check over what processes could request context
 >     translations from mcstrans or what contexts they could
translate, but I
 >     don't see it being used in mcstrans anywhere.  Is this a
legacy thing
 >     from early setransd/mcstransd days?  There is a TODO comment in
 >     mcstrans
 >     process_request() that suggests there was an intent to perform a
 >     dominance check between the requester context and the specified
 >     context,
 >     but that's not implemented.  Appears to be allowed in current
policy
 >     for
 >     all domains to the se

Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 03:04 PM, Joe Nall wrote:




On Sep 11, 2018, at 1:29 PM, Stephen Smalley  wrote:

On 09/11/2018 10:41 AM, Stephen Smalley wrote:

On 09/10/2018 06:30 PM, Ted Toth wrote:

mcstrans mcscolor.c also uses the same logic I'd been using to check dominance 
so this too will no longer function as expected on el7. Do you any suggestions 
for doing a 'generic' (one not tied to a specific resource class) dominance 
check in lieu of context contains?

You should probably define your own permission with its own constraint to avoid 
depending on the base policy's particular constraint definitions.  Certainly 
for your own code.  For mcstrans, mcscolor probably ought to be switched to 
using at least a separate permission in the context class if not its own class 
to avoid overloading the meaning with pam_selinux's usage (or vice versa, but 
likely harder to change pam_selinux at this point).
It is possible to define an entirely new class, its permissions, and its mls 
constraints via a CIL module IIUC, without needing to change the base policy.
I don't think you can add a permission to an existing class via a CIL module 
currently, unfortunately, so you can't just extend the context class without 
modifying the base policy.  So it may be easier to define an entirely new class.
The class and permission ought to be specific to the usage.  For example, 
mcstrans could have its own class (mcstrans) with its own permissions (e.g. 
color_match or color_use or ...) that abstract away the logical check being 
performed.  Dominance checks performed for different reasons ought to use 
different permissions so that one can distinguish what TE pairs are allowed 
them.
Your code could likewise define and use its own class and permission.
Does that make sense?


BTW, I noticed there is another permission ("translate") defined in the context 
class and its constraint is ((h1 dom h2) or (t1 == mlstranslate)).  I would have guessed 
that it was intended as a front-end service check over what processes could request 
context translations from mcstrans or what contexts they could translate, but I don't see 
it being used in mcstrans anywhere.  Is this a legacy thing from early setransd/mcstransd 
days?  There is a TODO comment in mcstrans process_request() that suggests there was an 
intent to perform a dominance check between the requester context and the specified 
context, but that's not implemented.  Appears to be allowed in current policy for all 
domains to the setrans_t domain itself.


I think 'translate' predates my mcstransd work and dates from the original TCS 
implementation. There is an argument to implement that constraint, but we've 
been operating without it for so long it does not seem worthwhile.


Well, I guess we ought to either implement it or delete the permission 
definition from refpolicy.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 03:29 PM, Stephen Smalley wrote:

On 09/11/2018 02:49 PM, Ted Toth wrote:
Yes I too noticed the translate permission but couldn't find any info 
related to it intended purpose. Regarding CIL unfortunately I have 
zero experience with it but I've installed the compiler and started 
reading through https://github.com/SELinuxProject/cil/wiki (any other 
pointers to useful info would be appreciated). I have written lots of 
policy would it be possible to add a class/permissions/mlsconstraints 
in an old-fashion policy module?


The older binary modules didn't support those kinds of statements 
outside of the base module.  Try this:

$ cat > mcstrans.cil <Then try performing permission checks with "mcstrans" as your class and 
"color_use" as your permission, between a domain and itself, with 
different levels.


BTW, an easy way to find CIL syntax for something is to look at how it 
is done in the base module.  You can extract a copy of that via

semodule -c -E base, then bring up base.cil in your favorite editor/viewer.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 02:49 PM, Ted Toth wrote:
Yes I too noticed the translate permission but couldn't find any info 
related to it intended purpose. Regarding CIL unfortunately I have zero 
experience with it but I've installed the compiler and started reading 
through https://github.com/SELinuxProject/cil/wiki (any other pointers 
to useful info would be appreciated). I have written lots of policy 
would it be possible to add a class/permissions/mlsconstraints in an 
old-fashion policy module?


The older binary modules didn't support those kinds of statements 
outside of the base module.  Try this:

$ cat > mcstrans.cil <Then try performing permission checks with "mcstrans" as your class and 
"color_use" as your permission, between a domain and itself, with 
different levels.




On Tue, Sep 11, 2018 at 1:27 PM Stephen Smalley <mailto:s...@tycho.nsa.gov>> wrote:


    On 09/11/2018 10:41 AM, Stephen Smalley wrote:
 > On 09/10/2018 06:30 PM, Ted Toth wrote:
 >> mcstrans mcscolor.c also uses the same logic I'd been using to
check
 >> dominance so this too will no longer function as expected on
el7. Do
 >> you any suggestions for doing a 'generic' (one not tied to a
specific
 >> resource class) dominance check in lieu of context contains?
 >
 > You should probably define your own permission with its own
constraint
 > to avoid depending on the base policy's particular constraint
 > definitions.  Certainly for your own code.  For mcstrans, mcscolor
 > probably ought to be switched to using at least a separate
permission in
 > the context class if not its own class to avoid overloading the
meaning
 > with pam_selinux's usage (or vice versa, but likely harder to change
 > pam_selinux at this point).
 >
 > It is possible to define an entirely new class, its permissions,
and its
 > mls constraints via a CIL module IIUC, without needing to change the
 > base policy.
 >
 > I don't think you can add a permission to an existing class via a
CIL
 > module currently, unfortunately, so you can't just extend the
context
 > class without modifying the base policy.  So it may be easier to
define
 > an entirely new class.
 >
 > The class and permission ought to be specific to the usage.  For
 > example, mcstrans could have its own class (mcstrans) with its own
 > permissions (e.g. color_match or color_use or ...) that abstract
away
 > the logical check being performed.  Dominance checks performed for
 > different reasons ought to use different permissions so that one can
 > distinguish what TE pairs are allowed them.
 >
 > Your code could likewise define and use its own class and permission.
 >
 > Does that make sense?

BTW, I noticed there is another permission ("translate") defined in the
context class and its constraint is ((h1 dom h2) or (t1 ==
mlstranslate)).  I would have guessed that it was intended as a
front-end service check over what processes could request context
translations from mcstrans or what contexts they could translate, but I
don't see it being used in mcstrans anywhere.  Is this a legacy thing
from early setransd/mcstransd days?  There is a TODO comment in
mcstrans
process_request() that suggests there was an intent to perform a
dominance check between the requester context and the specified
context,
but that's not implemented.  Appears to be allowed in current policy
for
all domains to the setrans_t domain itself.

 >
 >>
 >> Ted
 >>
 >> On Mon, Sep 10, 2018 at 1:19 PM Ted Toth mailto:txt...@gmail.com>
 >> <mailto:txt...@gmail.com <mailto:txt...@gmail.com>>> wrote:
 >>
 >>     Understood, thanks.
 >>
 >>     On Mon, Sep 10, 2018 at 12:46 PM Stephen Smalley
mailto:s...@tycho.nsa.gov>
 >>     <mailto:s...@tycho.nsa.gov <mailto:s...@tycho.nsa.gov>>> wrote:
 >>
 >>     On 09/10/2018 01:13 PM, Ted Toth wrote:
 >>  > We currently have code running on el6 that does a MLS
 >>     dominance check by
 >>  > calling security_compute_av_raw with the security
object class
 >>  > SECCLASS_CONTEXT with permission CONTEXT__CONTAINS as
you can
 >>     see in the
 >>  > python code below. When I run this code on el6 s1
dominates
 >>     s0 however
 >>  > when I run the same code on el7 s1 does not dominate
s0. On
 >>     both systems
 >>  > the file read dominance check works as ex

Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 10:41 AM, Stephen Smalley wrote:

On 09/10/2018 06:30 PM, Ted Toth wrote:
mcstrans mcscolor.c also uses the same logic I'd been using to check 
dominance so this too will no longer function as expected on el7. Do 
you any suggestions for doing a 'generic' (one not tied to a specific 
resource class) dominance check in lieu of context contains?


You should probably define your own permission with its own constraint 
to avoid depending on the base policy's particular constraint 
definitions.  Certainly for your own code.  For mcstrans, mcscolor 
probably ought to be switched to using at least a separate permission in 
the context class if not its own class to avoid overloading the meaning 
with pam_selinux's usage (or vice versa, but likely harder to change 
pam_selinux at this point).


It is possible to define an entirely new class, its permissions, and its 
mls constraints via a CIL module IIUC, without needing to change the 
base policy.


I don't think you can add a permission to an existing class via a CIL 
module currently, unfortunately, so you can't just extend the context 
class without modifying the base policy.  So it may be easier to define 
an entirely new class.


The class and permission ought to be specific to the usage.  For 
example, mcstrans could have its own class (mcstrans) with its own 
permissions (e.g. color_match or color_use or ...) that abstract away 
the logical check being performed.  Dominance checks performed for 
different reasons ought to use different permissions so that one can 
distinguish what TE pairs are allowed them.


Your code could likewise define and use its own class and permission.

Does that make sense?


BTW, I noticed there is another permission ("translate") defined in the 
context class and its constraint is ((h1 dom h2) or (t1 == 
mlstranslate)).  I would have guessed that it was intended as a 
front-end service check over what processes could request context 
translations from mcstrans or what contexts they could translate, but I 
don't see it being used in mcstrans anywhere.  Is this a legacy thing 
from early setransd/mcstransd days?  There is a TODO comment in mcstrans 
process_request() that suggests there was an intent to perform a 
dominance check between the requester context and the specified context, 
but that's not implemented.  Appears to be allowed in current policy for 
all domains to the setrans_t domain itself.






Ted

On Mon, Sep 10, 2018 at 1:19 PM Ted Toth <mailto:txt...@gmail.com>> wrote:


    Understood, thanks.

    On Mon, Sep 10, 2018 at 12:46 PM Stephen Smalley mailto:s...@tycho.nsa.gov>> wrote:

    On 09/10/2018 01:13 PM, Ted Toth wrote:
 > We currently have code running on el6 that does a MLS
    dominance check by
 > calling security_compute_av_raw with the security object class
 > SECCLASS_CONTEXT with permission CONTEXT__CONTAINS as you can
    see in the
 > python code below. When I run this code on el6 s1 dominates
    s0 however
 > when I run the same code on el7 s1 does not dominate s0. On
    both systems
 > the file read dominance check works as expected. Can anyone
    help me
 > understand why the context contains check does not work the
    same on both
 > systems?

    That would depend entirely on how the constraint is written in 
the

    policy.  I assume this is with the -mls policy on both?  seinfo
    --constrain | grep -C1 context would show you the constraint 
in the

    kernel policy.

    Looks like refpolicy defines it as:
    mlsconstrain context contains
          (( h1 dom h2 ) and ( l1 domby l2));

    The 2nd part of the constraint was introduced by:
    commit 4c365f4a6a6f933dd13b0127e03f832c6a6cf8fc
    Author: Harry Ciao mailto:qingtao@windriver.com>>
    Date:   Tue Feb 15 10:16:32 2011 +0800

      l1 domby l2 for contains MLS constraint

      As identified by Stephan Smalley, the current MLS
    constraint for the
      contains permission of the context class should consider
    the current
      level of a user along with the clearance level so that
    mls_systemlow
      is no longer considered contained in mls_systemhigh.

      Signed-off-by: Harry Ciao mailto:qingtao@windriver.com>>

    This was to prevent a user from logging in at a level below their
    authorized range, in the unusual scenario where the user's low
    level was
    not s0/systemlow.

 >
 > Ted
 >
 >

- 


 >
 > import selinux
   

Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 01:39 PM, Joshua Brindle wrote:

On Tue, Sep 11, 2018 at 1:33 PM, Stephen Smalley  wrote:

On 09/11/2018 12:53 PM, Joshua Brindle wrote:


On Tue, Sep 11, 2018 at 10:41 AM, Stephen Smalley 
wrote:


On 09/10/2018 06:30 PM, Ted Toth wrote:



mcstrans mcscolor.c also uses the same logic I'd been using to check
dominance so this too will no longer function as expected on el7. Do you
any
suggestions for doing a 'generic' (one not tied to a specific resource
class) dominance check in lieu of context contains?




You should probably define your own permission with its own constraint to
avoid depending on the base policy's particular constraint definitions.
Certainly for your own code.  For mcstrans, mcscolor probably ought to be
switched to using at least a separate permission in the context class if
not
its own class to avoid overloading the meaning with pam_selinux's usage
(or
vice versa, but likely harder to change pam_selinux at this point).



Isn't the actual question what the GLB of the 2 contexts is, rather
than what permissions one has on the other? It seems like a hack to
use permissions to figure out dominance.

Would a libselinux interface to determine glb and lub of 2 contexts
make sense? Or maybe add a default_range glb and lub option and then
calculate it using relabel?



At least as used in mcstrans, it appears to be a way of matching which entry
from the colors configuration to use.  So it is just a "Can context C1 use
the colors specified for context C2?" question.  It just happens that the
way they are deciding that for the MLS part is through the dominance
relation.  And determining whether context C1 dominates context C2 is
something only the kernel security server or libsepol with the same policy
file loaded into it can answer, not libselinux or anything else.



I meant an libselinux as in a library interface to some file in
selinuxfs to calculate the glb.

If it is 'permission to see a color' that makes sense, I was thinking
the source context and target context have a glb that maps to the
color to be shown.


That doesn't seem to match the existing mcstrans logic or colors 
configuration file.  So, sure he could rewrite mcstrans and its 
configuration format, add a new libselinux interface, add a new kernel 
interface, and implement a new kernel security server function, but he 
just wanted to make something that was already working on rhel6 to work 
on rhel7, and which only broke because a constraint changed out 
underneath to address a concern with pam_selinux/login.  Easiest 
approach is to define a new class/perm and define the old constraint for 
it.  Requires adding a CIL module for the policy piece and then a couple 
of lines changed in mcstrans and his own code and he is done.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/11/2018 12:53 PM, Joshua Brindle wrote:

On Tue, Sep 11, 2018 at 10:41 AM, Stephen Smalley  wrote:

On 09/10/2018 06:30 PM, Ted Toth wrote:


mcstrans mcscolor.c also uses the same logic I'd been using to check
dominance so this too will no longer function as expected on el7. Do you any
suggestions for doing a 'generic' (one not tied to a specific resource
class) dominance check in lieu of context contains?



You should probably define your own permission with its own constraint to
avoid depending on the base policy's particular constraint definitions.
Certainly for your own code.  For mcstrans, mcscolor probably ought to be
switched to using at least a separate permission in the context class if not
its own class to avoid overloading the meaning with pam_selinux's usage (or
vice versa, but likely harder to change pam_selinux at this point).



Isn't the actual question what the GLB of the 2 contexts is, rather
than what permissions one has on the other? It seems like a hack to
use permissions to figure out dominance.

Would a libselinux interface to determine glb and lub of 2 contexts
make sense? Or maybe add a default_range glb and lub option and then
calculate it using relabel?


At least as used in mcstrans, it appears to be a way of matching which 
entry from the colors configuration to use.  So it is just a "Can 
context C1 use the colors specified for context C2?" question.  It just 
happens that the way they are deciding that for the MLS part is through 
the dominance relation.  And determining whether context C1 dominates 
context C2 is something only the kernel security server or libsepol with 
the same policy file loaded into it can answer, not libselinux or 
anything else.




___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: MLS dominance check behavior on el7

2018-09-11 Thread Stephen Smalley

On 09/10/2018 06:30 PM, Ted Toth wrote:
mcstrans mcscolor.c also uses the same logic I'd been using to check 
dominance so this too will no longer function as expected on el7. Do you 
any suggestions for doing a 'generic' (one not tied to a specific 
resource class) dominance check in lieu of context contains?


You should probably define your own permission with its own constraint 
to avoid depending on the base policy's particular constraint 
definitions.  Certainly for your own code.  For mcstrans, mcscolor 
probably ought to be switched to using at least a separate permission in 
the context class if not its own class to avoid overloading the meaning 
with pam_selinux's usage (or vice versa, but likely harder to change 
pam_selinux at this point).


It is possible to define an entirely new class, its permissions, and its 
mls constraints via a CIL module IIUC, without needing to change the 
base policy.


I don't think you can add a permission to an existing class via a CIL 
module currently, unfortunately, so you can't just extend the context 
class without modifying the base policy.  So it may be easier to define 
an entirely new class.


The class and permission ought to be specific to the usage.  For 
example, mcstrans could have its own class (mcstrans) with its own 
permissions (e.g. color_match or color_use or ...) that abstract away 
the logical check being performed.  Dominance checks performed for 
different reasons ought to use different permissions so that one can 
distinguish what TE pairs are allowed them.


Your code could likewise define and use its own class and permission.

Does that make sense?



Ted

On Mon, Sep 10, 2018 at 1:19 PM Ted Toth <mailto:txt...@gmail.com>> wrote:


Understood, thanks.

On Mon, Sep 10, 2018 at 12:46 PM Stephen Smalley mailto:s...@tycho.nsa.gov>> wrote:

On 09/10/2018 01:13 PM, Ted Toth wrote:
 > We currently have code running on el6 that does a MLS
dominance check by
 > calling security_compute_av_raw with the security object class
 > SECCLASS_CONTEXT with permission CONTEXT__CONTAINS as you can
see in the
 > python code below. When I run this code on el6 s1 dominates
s0 however
 > when I run the same code on el7 s1 does not dominate s0. On
both systems
 > the file read dominance check works as expected. Can anyone
help me
 > understand why the context contains check does not work the
same on both
 > systems?

That would depend entirely on how the constraint is written in the
policy.  I assume this is with the -mls policy on both?  seinfo
--constrain | grep -C1 context would show you the constraint in the
kernel policy.

Looks like refpolicy defines it as:
mlsconstrain context contains
          (( h1 dom h2 ) and ( l1 domby l2));

The 2nd part of the constraint was introduced by:
commit 4c365f4a6a6f933dd13b0127e03f832c6a6cf8fc
Author: Harry Ciao mailto:qingtao@windriver.com>>
Date:   Tue Feb 15 10:16:32 2011 +0800

      l1 domby l2 for contains MLS constraint

      As identified by Stephan Smalley, the current MLS
constraint for the
      contains permission of the context class should consider
the current
      level of a user along with the clearance level so that
mls_systemlow
      is no longer considered contained in mls_systemhigh.

      Signed-off-by: Harry Ciao mailto:qingtao@windriver.com>>

This was to prevent a user from logging in at a level below their
authorized range, in the unusual scenario where the user's low
level was
not s0/systemlow.

 >
 > Ted
 >
 >

-
 >
 > import selinux
 >
 > SECCLASS_CONTEXT = selinux.string_to_security_class("context")
 > CONTEXT__CONTAINS =
selinux.string_to_av_perm(SECCLASS_CONTEXT, "contains")
 > SECCLASS_FILE = selinux.string_to_security_class("file")
 > FILE__READ = selinux.string_to_av_perm(SECCLASS_FILE, "read")
 >
 > raw_con1 = "user_u:user_r:user_t:s1"
 > raw_con2 = "user_u:user_r:user_t:s0"
 >
 > avd = selinux.av_decision()
 > selinux.avc_reset()
 > try:
 >      rc = selinux.security_compute_av_raw(raw_con1, raw_con2,
 > SECCLASS_CONTEXT, CONTEXT__CONTAINS, avd)
 >      if rc < 0:
 >          print("selinux.

Re: MLS dominance check behavior on el7

2018-09-10 Thread Stephen Smalley

On 09/10/2018 01:13 PM, Ted Toth wrote:
We currently have code running on el6 that does a MLS dominance check by 
calling security_compute_av_raw with the security object class 
SECCLASS_CONTEXT with permission CONTEXT__CONTAINS as you can see in the 
python code below. When I run this code on el6 s1 dominates s0 however 
when I run the same code on el7 s1 does not dominate s0. On both systems 
the file read dominance check works as expected. Can anyone help me 
understand why the context contains check does not work the same on both 
systems?


That would depend entirely on how the constraint is written in the 
policy.  I assume this is with the -mls policy on both?  seinfo 
--constrain | grep -C1 context would show you the constraint in the 
kernel policy.


Looks like refpolicy defines it as:
mlsconstrain context contains
(( h1 dom h2 ) and ( l1 domby l2));

The 2nd part of the constraint was introduced by:
commit 4c365f4a6a6f933dd13b0127e03f832c6a6cf8fc
Author: Harry Ciao 
Date:   Tue Feb 15 10:16:32 2011 +0800

l1 domby l2 for contains MLS constraint

As identified by Stephan Smalley, the current MLS constraint for the
contains permission of the context class should consider the current
level of a user along with the clearance level so that mls_systemlow
is no longer considered contained in mls_systemhigh.

Signed-off-by: Harry Ciao 

This was to prevent a user from logging in at a level below their 
authorized range, in the unusual scenario where the user's low level was 
not s0/systemlow.




Ted

-

import selinux

SECCLASS_CONTEXT = selinux.string_to_security_class("context")
CONTEXT__CONTAINS = selinux.string_to_av_perm(SECCLASS_CONTEXT, "contains")
SECCLASS_FILE = selinux.string_to_security_class("file")
FILE__READ = selinux.string_to_av_perm(SECCLASS_FILE, "read")

raw_con1 = "user_u:user_r:user_t:s1"
raw_con2 = "user_u:user_r:user_t:s0"

avd = selinux.av_decision()
selinux.avc_reset()
try:
     rc = selinux.security_compute_av_raw(raw_con1, raw_con2, 
SECCLASS_CONTEXT, CONTEXT__CONTAINS, avd)

     if rc < 0:
         print("selinux.security_compute_av_raw failed for %s %s" % 
(raw_con1, raw_con2))

     if (avd.allowed & CONTEXT__CONTAINS) == CONTEXT__CONTAINS:
         print("%s dominates %s" % (raw_con1, raw_con2))
     else:
         print("%s does not dominate %s" % (raw_con1, raw_con2))
except OSError, ex:
     print "exception calling selinux.security_compute_av_raw", ex

avd = selinux.av_decision()
selinux.avc_reset()
try:
     rc = selinux.security_compute_av_raw(raw_con1, raw_con2, 
SECCLASS_FILE, FILE__READ, avd)

     if rc < 0:
         print("selinux.security_compute_av_raw failed for %s %s" % 
(raw_con1, raw_con2))

     if (avd.allowed & FILE__READ) == FILE__READ:
         print("%s dominates %s" % (raw_con1, raw_con2))
     else:
         print("%s does not dominate %s" % (raw_con1, raw_con2))

except OSError:
     print "exception calling selinux.security_compute_av_raw", ex



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: "semanage user" and -s option

2018-09-05 Thread Stephen Smalley

On 09/05/2018 03:36 PM, Nicolas Iooss wrote:

Hello,

While reviewing the last patch sent by Vit Mojzis, I stumbled upon
something that does not feel right in "semanage user". Both "semanage
user --help" and "man 8 semanage-user" state:

usage: semanage user [-h] [-n] [-N] [-S STORE] [ --add ( -L LEVEL -R
ROLES -r RANGE -s SEUSER selinux_name) | ...

I am wondering what are the meaning of "-s SEUSER" and "selinux_name"
there. If I try to use "-s" option, semanage complains:

semanage: error: unrecognized arguments: -s

Therefore it seems that the usage would rather be "... --add ( -L
LEVEL -R ROLES -r RANGE SEUSER)". Looking at the code, it seems that
parser_add_seuser() is not used in setupUserParser() [1], and
everything works fine when using "semanage user" without -s option. Am
I missing something obvious, or should I write a patch which fixes the
documentation?


Sounds like a cut-and-paste error from the semanage login help and man page.

The examples in the man page don't ever use -s to semanage user, nor 
does python/semanage/test-semanage.py or python/sepolicy/templates/*.py.




Cheers,
Nicolas

[1] 
https://github.com/SELinuxProject/selinux/blob/libsemanage-2.8/python/semanage/semanage#L403

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


[PATCH] selinux: fix mounting of cgroup2 under older policies

2018-09-04 Thread Stephen Smalley
commit 901ef845fa2469c ("selinux: allow per-file labeling for cgroupfs")
broke mounting of cgroup2 under older SELinux policies which lacked
a genfscon rule for cgroup2.  This prevents mounting of cgroup2 even
when SELinux is permissive.

Change the handling when there is no genfscon rule in policy to
just mark the inode unlabeled and not return an error to the caller.
This permits mounting and access if allowed by policy, e.g. to
unconfined domains.

I also considered changing the behavior of security_genfs_sid() to
never return -ENOENT, but the current behavior is relied upon by
other callers to perform caller-specific handling.

Fixes: 901ef845fa2469c ("selinux: allow per-file labeling for cgroupfs")
CC: 
Reported-by: Dmitry Vyukov 
Reported-by: Waiman Long 
Signed-off-by: Stephen Smalley 
---
 security/selinux/hooks.c | 5 +
 1 file changed, 5 insertions(+)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index f78318af8254..58fee382a3bb 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -1508,6 +1508,11 @@ static int selinux_genfs_get_sid(struct dentry *dentry,
}
rc = security_genfs_sid(_state, sb->s_type->name,
path, tclass, sid);
+   if (rc == -ENOENT) {
+   /* No match in policy, mark as unlabeled. */
+   *sid = SECINITSID_UNLABELED;
+   rc = 0;
+   }
}
free_page((unsigned long)buffer);
return rc;
-- 
2.14.4

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: WARNING in apparmor_secid_to_secctx

2018-09-04 Thread Stephen Smalley

On 09/04/2018 11:38 AM, Dmitry Vyukov wrote:

On Tue, Sep 4, 2018 at 5:28 PM, Stephen Smalley  wrote:

So why not ask for help from the SELinux community? I've cc'd the selinux
list and a couple of folks involved in Debian selinux.  I see a couple of
options but I don't know your constraints for syzbot:

1) Run an instance of syzbot on a distro that supports SELinux enabled
out
of the box like Fedora. Then you don't have to fight with SELinux and can
just focus on syzbot, while still testing SELinux enabled and enforcing.

2) Report the problems you are having with enabling SELinux on newer
Debian
to the selinux list and/or the Debian selinux package maintainers so that
someone can help you resolve them.

3) Back-port the cgroup2 policy definitions to your wheezy policy,
rebuild
it, and install that.  We could help provide guidance on that. I think
you'll need to rebuild the base policy on wheezy; in distributions with
modern SELinux userspace, one could do it just by adding a CIL module
locally.



Thanks, Stephen!

I would like to understand first if failing mount(2) for unknown fs is
selinux bug or not. Because if it is and it is fixed, then it would
resolve the problem without actually doing anything (well, at least on
our side :)).



Yes, I think that's a selinux kernel regression, previously reported here:
https://lkml.org/lkml/2017/10/6/658

Unfortunately I don't think it has been fixed upstream.  Generally people
using SELinux with a newer kernel are also using a newer policy. That said,
I agree it is a regression and ought to be fixed.



How hard is it to fix it? We are on upstream head, so once it's in we
are ready to go.
Using multiple images is somewhat problematic (besides the fact that I
don't know how to build a fedora image) because syzbot does not
capture what image was used, and in the docs we just provide the
single image, so people will start complaining that bugs don't
reproduce but they are just using a wrong image.


I'll take a look and see if I can provide a trivial fix.
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: WARNING in apparmor_secid_to_secctx

2018-09-04 Thread Stephen Smalley

On 09/04/2018 11:02 AM, Dmitry Vyukov wrote:

On Tue, Sep 4, 2018 at 2:57 PM, Stephen Smalley  wrote:

 wrote:



Hello,

syzbot found the following crash on:

HEAD commit:817e60a7a2bb Merge branch 'nfp-add-NFP5000-support'
git tree:   net-next
console output:
https://syzkaller.appspot.com/x/log.txt?x=1536d29640
kernel config:
https://syzkaller.appspot.com/x/.config?x=531a917630d2a492
dashboard link:
https://syzkaller.appspot.com/bug?extid=21016130b0580a9de3b5
compiler:   gcc (GCC) 8.0.1 20180413 (experimental)

Unfortunately, I don't have any reproducer for this crash yet.

IMPORTANT: if you fix the bug, please add the following tag to the
commit:
Reported-by: syzbot+21016130b0580a9de...@syzkaller.appspotmail.com




Hi John, Tyler,

I've switched syzbot from selinux to apparmor as we discussed on lss:


https://github.com/google/syzkaller/commit/2c6cb254ae6c06f61e3aba21bb89ffb05b5db946




Sorry, does this mean that you are no longer testing selinux via
syzbot?
 That seems unfortunate.  SELinux is default-enabled and used in
Fedora, RHEL and all derivatives (e.g. CentOS), and mandatory in
Android
(and seemingly getting some use in ChromeOS now as well, at least for
the Android container and possibly wider), so it seems unwise to drop
it
from your testing altogether.  I was under the impression that you
were
just going to add apparmor to your testing matrix, not drop selinux
altogether.




It is also important to note that testing with SELinux enabled but no
policy loaded is not going to be very helpful (last we talked that is
what syzbot is/was doing).  While syzbot did uncover some issues
relating to the enabled-no-policy case, those are much less
interesting and less relevant than the loaded-policy case.




I had thought that they had switched over to at least loading a policy
but
possibly left it in permissive mode because the base distribution didn't
properly support SELinux out of the box.  But I may be mistaken.
Regardless, the right solution is to migrate to testing with a policy
loaded not to stop testing altogether.

Optimally, they'd test on at least one distribution/OS where SELinux is
in
fact supported out of the box, e.g. CentOS, Android, and/or ChromeOS.




Or Fedora, of course.



Hi,

Yes, we switched from selinux to apparmor. The thing is that we
effectively did not test selinux lately, so it's more like just
enabling apparmor rather than disabling selinux.

The story goes as follows.
We enabled selinux, but did not have policy and selinux wasn't enabled.
Then Paul (I think) pointer that out. After some debugging I figured
out that our debian wheezy actually has a policy, it's just that
selinux utilities were not installed, so init could not load the
policy.
I installed the tools, and we started loading policy.
But then it turned out that wheezy policy does not allows mounting
cgroup2 fs and maybe some others even in non-enforcing mode. As far as
I understand that's because the policy does not have definition for
the fs, and so loading bails out with an error.
We need cgroup2 both for testing and for better sandboxing (no other
way to restrict e.g. memory consumption). Moreover, we did not test
any actual interesting interactions with selinux (there must be some?
but I don't know what are they).
So I had to uninstall the tool and policy is not loaded again.
I investigated building a newer debian image with debootstrap (which
should have newer policy I guess). But they don't work, some cryptic
errors in init. Other people reported the same.
So that's we are. I don't have any ideas left...



So why not ask for help from the SELinux community? I've cc'd the selinux
list and a couple of folks involved in Debian selinux.  I see a couple of
options but I don't know your constraints for syzbot:

1) Run an instance of syzbot on a distro that supports SELinux enabled out
of the box like Fedora. Then you don't have to fight with SELinux and can
just focus on syzbot, while still testing SELinux enabled and enforcing.

2) Report the problems you are having with enabling SELinux on newer Debian
to the selinux list and/or the Debian selinux package maintainers so that
someone can help you resolve them.

3) Back-port the cgroup2 policy definitions to your wheezy policy, rebuild
it, and install that.  We could help provide guidance on that. I think
you'll need to rebuild the base policy on wheezy; in distributions with
modern SELinux userspace, one could do it just by adding a CIL module
locally.


Thanks, Stephen!

I would like to understand first if failing mount(2) for unknown fs is
selinux bug or not. Because if it is and it is fixed, then it would
resolve the problem without actually doing anything (well, at least on
our side :)).


Yes, I think that's a selinux kernel regression, previously reported here:
https://lkml.org/lkml/2017/10/6/658

Unfortunately I don't think it has been fixed upstream.  Generally 
people using SELinux with a newer kernel are also using a newer

Re: WARNING in apparmor_secid_to_secctx

2018-09-04 Thread Stephen Smalley

On 08/31/2018 06:38 PM, Dmitry Vyukov wrote:

On Fri, Aug 31, 2018 at 9:17 AM, Stephen Smalley  wrote:

On 08/31/2018 12:16 PM, Stephen Smalley wrote:


On 08/31/2018 12:07 PM, Paul Moore wrote:


On Fri, Aug 31, 2018 at 12:01 PM Stephen Smalley 
wrote:


On 08/29/2018 10:21 PM, Dmitry Vyukov wrote:


On Wed, Aug 29, 2018 at 7:17 PM, syzbot
 wrote:


Hello,

syzbot found the following crash on:

HEAD commit:817e60a7a2bb Merge branch 'nfp-add-NFP5000-support'
git tree:   net-next
console output:
https://syzkaller.appspot.com/x/log.txt?x=1536d29640
kernel config:
https://syzkaller.appspot.com/x/.config?x=531a917630d2a492
dashboard link:
https://syzkaller.appspot.com/bug?extid=21016130b0580a9de3b5
compiler:   gcc (GCC) 8.0.1 20180413 (experimental)

Unfortunately, I don't have any reproducer for this crash yet.

IMPORTANT: if you fix the bug, please add the following tag to the
commit:
Reported-by: syzbot+21016130b0580a9de...@syzkaller.appspotmail.com



Hi John, Tyler,

I've switched syzbot from selinux to apparmor as we discussed on lss:

https://github.com/google/syzkaller/commit/2c6cb254ae6c06f61e3aba21bb89ffb05b5db946



Sorry, does this mean that you are no longer testing selinux via syzbot?
That seems unfortunate.  SELinux is default-enabled and used in
Fedora, RHEL and all derivatives (e.g. CentOS), and mandatory in Android
(and seemingly getting some use in ChromeOS now as well, at least for
the Android container and possibly wider), so it seems unwise to drop it
from your testing altogether.  I was under the impression that you were
just going to add apparmor to your testing matrix, not drop selinux
altogether.



It is also important to note that testing with SELinux enabled but no
policy loaded is not going to be very helpful (last we talked that is
what syzbot is/was doing).  While syzbot did uncover some issues
relating to the enabled-no-policy case, those are much less
interesting and less relevant than the loaded-policy case.



I had thought that they had switched over to at least loading a policy but
possibly left it in permissive mode because the base distribution didn't
properly support SELinux out of the box.  But I may be mistaken.
Regardless, the right solution is to migrate to testing with a policy
loaded not to stop testing altogether.

Optimally, they'd test on at least one distribution/OS where SELinux is in
fact supported out of the box, e.g. CentOS, Android, and/or ChromeOS.



Or Fedora, of course.


Hi,

Yes, we switched from selinux to apparmor. The thing is that we
effectively did not test selinux lately, so it's more like just
enabling apparmor rather than disabling selinux.

The story goes as follows.
We enabled selinux, but did not have policy and selinux wasn't enabled.
Then Paul (I think) pointer that out. After some debugging I figured
out that our debian wheezy actually has a policy, it's just that
selinux utilities were not installed, so init could not load the
policy.
I installed the tools, and we started loading policy.
But then it turned out that wheezy policy does not allows mounting
cgroup2 fs and maybe some others even in non-enforcing mode. As far as
I understand that's because the policy does not have definition for
the fs, and so loading bails out with an error.
We need cgroup2 both for testing and for better sandboxing (no other
way to restrict e.g. memory consumption). Moreover, we did not test
any actual interesting interactions with selinux (there must be some?
but I don't know what are they).
So I had to uninstall the tool and policy is not loaded again.
I investigated building a newer debian image with debootstrap (which
should have newer policy I guess). But they don't work, some cryptic
errors in init. Other people reported the same.
So that's we are. I don't have any ideas left...


So why not ask for help from the SELinux community?  I've cc'd the 
selinux list and a couple of folks involved in Debian selinux.  I see a 
couple of options but I don't know your constraints for syzbot:


1) Run an instance of syzbot on a distro that supports SELinux enabled 
out of the box like Fedora. Then you don't have to fight with SELinux 
and can just focus on syzbot, while still testing SELinux enabled and 
enforcing.


2) Report the problems you are having with enabling SELinux on newer 
Debian to the selinux list and/or the Debian selinux package maintainers 
so that someone can help you resolve them.


3) Back-port the cgroup2 policy definitions to your wheezy policy, 
rebuild it, and install that.  We could help provide guidance on that. 
I think you'll need to rebuild the base policy on wheezy; in 
distributions with modern SELinux userspace, one could do it just by 
adding a CIL module locally.


As for exercising SELinux, you'll exercise SELinux just by enabling it 
and loading a policy, since it will perform permission checking on all 
object accesses.   But you can get more extensive coverage by running 
the selinux-testsuite.  We

Re: [PATCH] SELinux: allow other LSMs to use custom mount args

2018-08-31 Thread Stephen Smalley

On 08/29/2018 12:58 AM, Paul Moore wrote:

On Tue, Aug 28, 2018 at 5:32 PM Micah Morton  wrote:

The security_sb_copy_data LSM hook allows LSMs to copy custom string
name/value args passed to mount_fs() into a temporary buffer (called
"secdata") that will be accessible to LSM code during the
security_sb_kern_mount hook further down in mount_fs(). Currently,
SELinux effectively prevents any other LSMs from copying custom mount
args into the temporary buffer (and being able to access them during
security_sb_kern_mount), as it will fail with -EINVAL and print
"SELinux:  unknown mount option" to the kernel message buffer if args it
doesn't recognize are present in the temporary buffer when
selinux_sb_kern_mount is called. This change adds an arg to the list of
those accepted by SELinux during security_sb_kern_mount. SELinux won't
do anything with this arg besides allow the name/value pair to be passed
along to any other LSM that is stacked after SELinux.

Developed on v4.18.

Signed-off-by: Micah Morton 
---
  security/selinux/hooks.c|  7 ++-
  security/selinux/include/security.h | 11 ++-
  2 files changed, 12 insertions(+), 6 deletions(-)


SELinux patches need to be sent to the SELinux mailing list (CC'd) for
proper review.


Please also show us the user of this facility; we need to see both sides 
of the interface to fully assess it.  And that user has to be on a glide 
path to mainline; we don't add features for out-of-tree code.


WRT Casey's comments, I don't think that you necessarily have to deal 
with arbitrary stacking for this patch since the stacking support is not 
yet upstream, but it wouldn't hurt to consider whether you could solve 
the problem more generally.





diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 2b5ee5fbd652..e70ccc701eb8 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -445,6 +445,7 @@ enum {
 Opt_rootcontext = 4,
 Opt_labelsupport = 5,
 Opt_nextmntopt = 6,
+   Opt_lsm_custom_arg = 7,
  };

  #define NUM_SEL_MNT_OPTS   (Opt_nextmntopt - 1)
@@ -455,6 +456,7 @@ static const match_table_t tokens = {
 {Opt_defcontext, DEFCONTEXT_STR "%s"},
 {Opt_rootcontext, ROOTCONTEXT_STR "%s"},
 {Opt_labelsupport, LABELSUPP_STR},
+   {Opt_lsm_custom_arg, LSM_CUSTOM_ARG_STR "%s"},
 {Opt_error, NULL},
  };

@@ -1156,6 +1158,8 @@ static int selinux_parse_opts_str(char *options,
 break;
 case Opt_labelsupport:
 break;
+   case Opt_lsm_custom_arg:
+   break;
 default:
 rc = -EINVAL;
 printk(KERN_WARNING "SELinux:  unknown mount 
option\n");
@@ -2758,7 +2762,8 @@ static inline int selinux_option(char *option, int len)
 match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, 
len) ||
 match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, 
len) ||
 match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, 
option, len) ||
-   match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, 
len));
+   match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, 
len) ||
+   match_prefix(LSM_CUSTOM_ARG_STR, sizeof(LSM_CUSTOM_ARG_STR)-1, 
option, len));
  }

  static inline void take_option(char **to, char *from, int *first, int len)
diff --git a/security/selinux/include/security.h 
b/security/selinux/include/security.h
index 23e762d529fa..0ead836a0625 100644
--- a/security/selinux/include/security.h
+++ b/security/selinux/include/security.h
@@ -59,11 +59,12 @@
  #define SE_SBPROC  0x0200
  #define SE_SBGENFS 0x0400

-#define CONTEXT_STR"context="
-#define FSCONTEXT_STR  "fscontext="
-#define ROOTCONTEXT_STR"rootcontext="
-#define DEFCONTEXT_STR "defcontext="
-#define LABELSUPP_STR "seclabel"
+#define CONTEXT_STR "context="
+#define FSCONTEXT_STR   "fscontext="
+#define ROOTCONTEXT_STR "rootcontext="
+#define DEFCONTEXT_STR  "defcontext="
+#define LABELSUPP_STR   "seclabel"
+#define LSM_CUSTOM_ARG_STR  "lsm_custom_arg="

  struct netlbl_lsm_secattr;

--
2.19.0.rc0.228.g281dcd1b4d0-goog






___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Possible OOB Read in Kernel Heap Memory in call to ext4_xattr_set_entry()

2018-08-20 Thread Stephen Smalley

On 08/20/2018 10:02 AM, Stephen Smalley wrote:

On 08/20/2018 02:29 AM, Sachin Grover wrote:

Hi,

My POC uses fscreate() to modify the current SELinux context of the 
running process, it then creates a new node via mknod(), (), which is 
then going to assign the current SLEinux context over to that object.


In the call path I am seeing security_sid_to_context_core().

I see a code path where it in fact seem to correctly take the strlen() 
of the incoming context, based on the sid, and use kmemdup(), but that 
only occurs when SELinux is not initialized.


     if (!ss_initialized) {
            if (sid <= SECINITSID_NUM) {
                    char *scontextp;

                    *scontext_len = strlen(initial_sid_to_string[sid]) 
+ 1;

                    if (!scontext)
                            goto out;
                    scontextp = kmemdup(initial_sid_to_string[sid],
                                       *scontext_len, GFP_ATOMIC);
                    if (!scontextp) {
                            rc = -ENOMEM;
                            goto out;
                    }
                    *scontext = scontextp;
                    goto out;
            }
            printk(KERN_ERR "SELinux: %s:  called before initial "
                   "load_policy on unknown SID %d\n", __func__, sid);
            rc = -EINVAL;
            goto out;
     }

Once SELinux is initialized that block will be skipped and further 
down you’ll see the call to context_struct_to_string() which copies 
the context using kstrdup() and uses the incoming length rather than 
the strlen() length.


context_struct_to_string() sets *scontext_len to context->len, which was 
previously set by security_context_to_sid_core() to strlen(str) + 1 
after your prior commit. Correct?


  In addition to this I’m not sure how safe using
strlen() is in general as there seems to be an assumption that context 
strings can contain NULL characters based on this comment.


                           /* We strip a nul only if it is at the end, 
otherwise the
                            * context contains a nul and we should 
audit that */

                           if (str[size - 1] == '\0')
                                  audit_size = size - 1;
                           else
                                  audit_size = size;


This audit-related code has to deal with the possibility that there is 
an embedded NUL (and might also lack a terminating NUL) because it is 
dealing with the original user-supplied value, not a string that has 
been stored in a context structure. After this audit-related code, we 
proceed to call security_context_to_sid_force() which calls 
security_context_to_sid_core() with force=1.  This first creates a 
NUL-terminated copy of the value (scontext) as scontext2 using 
kmemdup_nul(), which could potentially contain embedded NULs if the 
original did.  In the force=1 case, it then creates a copy of scontext2 
as str using kstrdup(), yielding a NUL-terminated string with no 
embedded NULs. It is this NUL-terminated string (str) that is stored in 
the context structure as context.str and context.len is set to 
strlen(str)+1 after your earlier commit.


How would we end up with a context->len other than 
strlen(context->str)+1 in security_sid_to_context_core()?


The point is that we ought to sanitize context->len when it is set, not 
when it is read, and in theory that is exactly what we are doing in 
security_context_to_sid_core(), such that security_sid_to_context_core() 
can read that value without recomputing it.  If it is being set 
incorrectly somewhere else, we ought to fix it there.  If it is being 
corrupted through memory corruption, then we ought to fix the source of 
the memory corruption.




Call StacK:

[] kasan_report+0x32c/0x485 mm/kasan/report.c:309
[] check_memory_region_inline mm/kasan/kasan.c:301 
[inline]

[] check_memory_region+0x2b/0x130 mm/kasan/kasan.c:315
[] __asan_loadN+0xf/0x11 mm/kasan/kasan.c:745
[] ext4_xattr_set_entry+0x6a1/0x6d3 fs/ext4/xattr.c:747
[] ext4_xattr_ibody_set.isra.9+0x4f/0x118 
fs/ext4/xattr.c:1118
[] ext4_xattr_set_handle+0x39a/0x7b4 
fs/ext4/xattr.c:1224
[] ext4_initxattrs+0x6b/0x96 
fs/ext4/xattr_security.c:42
[] security_inode_init_security+0x170/0x1c9 
security/security.c:403
[] ext4_init_security+0x35/0x3d 
fs/ext4/xattr_security.c:56

[] __ext4_new_inode+0x1f24/0x2266 fs/ext4/ialloc.c:1059
[] ext4_mknod+0x11a/0x263 fs/ext4/namei.c:2510
[] vfs_mknod2+0x1ee/0x29f fs/namei.c:3722
[] SYSC_mknodat fs/namei.c:3780 [inline]
[] SyS_mknodat+0x19a/0x22a fs/namei.c:3752
[] do_syscall_64+0xf8/0x191 arch/x86/entry/common.c:282
[] entry_SYSCALL_64_after_swapgs+0x58/0xc6

Syzkaller reproducer:
# {Threaded:false Collide:false Repeat:false Procs:1 Sandbox:none 
Fault:false FaultCall:-1 FaultNth:0 EnableTun:false UseTmpDir:false 
EnableCgroups:false EnableNetdev:false ResetNet:false HandleSegv:false 
WaitRepeat:false Debug:fals

Re: [PATCH RFC v2 5/5] SELinux: Support SELinux determination of side-channel vulnerability

2018-08-20 Thread Stephen Smalley

On 08/20/2018 12:59 PM, Schaufler, Casey wrote:

-Original Message-
From: Stephen Smalley [mailto:s...@tycho.nsa.gov]
Sent: Monday, August 20, 2018 9:03 AM
To: Schaufler, Casey ; kernel-
harden...@lists.openwall.com; linux-ker...@vger.kernel.org; linux-security-
mod...@vger.kernel.org; selinux@tycho.nsa.gov; Hansen, Dave
; Dock, Deneen T ;
kris...@linux.intel.com; ar...@linux.intel.com
Subject: Re: [PATCH RFC v2 5/5] SELinux: Support SELinux determination of
side-channel vulnerability

On 08/17/2018 06:16 PM, Casey Schaufler wrote:

SELinux considers tasks to be side-channel safe if they
have PROCESS_SHARE access.


Now the description and the code no longer match.


You're right.



Signed-off-by: Casey Schaufler 
---
   security/selinux/hooks.c | 9 +
   1 file changed, 9 insertions(+)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index a8bf324130f5..7fbd7d7ac1cb 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -4219,6 +4219,14 @@ static void selinux_task_to_inode(struct

task_struct *p,

spin_unlock(>lock);
   }

+static int selinux_task_safe_sidechannel(struct task_struct *p)
+{
+   struct av_decision avd;
+
+   return avc_has_perm_noaudit(_state, current_sid(),

task_sid(p),

+   SECCLASS_FILE, FILE__READ, 0, );
+}


And my question from before still stands:  why do we need a new hook and
new security module instead of just using ptrace_may_access()?


Locking. The SELinux check, for example, will lock up solid while trying
to generate an audit record. There is no good reason aside from coding
convenience to assume that the same restrictions will apply for side-channel
as apply to ptrace. I'm actually a touch surprised you're not suggesting a
separate SECCLASS or access mode for the SELinux hook.


The PTRACE_MODE_NOAUDIT flag to ptrace_may_access() would address the 
locking concern. Duplicating the ptrace access checking logic seems 
prone to errors and inconsistencies. I can't imagine policy writers 
understanding what "safe sidechannel" means, much less deciding when to 
allow it.







+
   /* Returns error only if unable to parse addresses */
   static int selinux_parse_skb_ipv4(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
@@ -7002,6 +7010,7 @@ static struct security_hook_list selinux_hooks[]

__lsm_ro_after_init = {

LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
LSM_HOOK_INIT(task_kill, selinux_task_kill),
LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
+   LSM_HOOK_INIT(task_safe_sidechannel,

selinux_task_safe_sidechannel),


LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),





___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH RFC v2 5/5] SELinux: Support SELinux determination of side-channel vulnerability

2018-08-20 Thread Stephen Smalley

On 08/17/2018 06:16 PM, Casey Schaufler wrote:

SELinux considers tasks to be side-channel safe if they
have PROCESS_SHARE access.


Now the description and the code no longer match.



Signed-off-by: Casey Schaufler 
---
  security/selinux/hooks.c | 9 +
  1 file changed, 9 insertions(+)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index a8bf324130f5..7fbd7d7ac1cb 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -4219,6 +4219,14 @@ static void selinux_task_to_inode(struct task_struct *p,
spin_unlock(>lock);
  }
  
+static int selinux_task_safe_sidechannel(struct task_struct *p)

+{
+   struct av_decision avd;
+
+   return avc_has_perm_noaudit(_state, current_sid(), task_sid(p),
+   SECCLASS_FILE, FILE__READ, 0, );
+}


And my question from before still stands:  why do we need a new hook and 
new security module instead of just using ptrace_may_access()?



+
  /* Returns error only if unable to parse addresses */
  static int selinux_parse_skb_ipv4(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
@@ -7002,6 +7010,7 @@ static struct security_hook_list selinux_hooks[] 
__lsm_ro_after_init = {
LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
LSM_HOOK_INIT(task_kill, selinux_task_kill),
LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
+   LSM_HOOK_INIT(task_safe_sidechannel, selinux_task_safe_sidechannel),
  
  	LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),

LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Possible OOB Read in Kernel Heap Memory in call to ext4_xattr_set_entry()

2018-08-20 Thread Stephen Smalley

On 08/20/2018 02:29 AM, Sachin Grover wrote:

Hi,

My POC uses fscreate() to modify the current SELinux context of the 
running process, it then creates a new node via mknod(), (), which is 
then going to assign the current SLEinux context over to that object.


In the call path I am seeing security_sid_to_context_core().

I see a code path where it in fact seem to correctly take the strlen() 
of the incoming context, based on the sid, and use kmemdup(), but that 
only occurs when SELinux is not initialized.


     if (!ss_initialized) {
            if (sid <= SECINITSID_NUM) {
                    char *scontextp;

                    *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
                    if (!scontext)
                            goto out;
                    scontextp = kmemdup(initial_sid_to_string[sid],
                                       *scontext_len, GFP_ATOMIC);
                    if (!scontextp) {
                            rc = -ENOMEM;
                            goto out;
                    }
                    *scontext = scontextp;
                    goto out;
            }
            printk(KERN_ERR "SELinux: %s:  called before initial "
                   "load_policy on unknown SID %d\n", __func__, sid);
            rc = -EINVAL;
            goto out;
     }

Once SELinux is initialized that block will be skipped and further down 
you’ll see the call to context_struct_to_string() which copies the 
context using kstrdup() and uses the incoming length rather than the 
strlen() length.


context_struct_to_string() sets *scontext_len to context->len, which was 
previously set by security_context_to_sid_core() to strlen(str) + 1 
after your prior commit. Correct?


 In addition to this I’m not sure how safe using
strlen() is in general as there seems to be an assumption that context 
strings can contain NULL characters based on this comment.


                           /* We strip a nul only if it is at the end, 
otherwise the
                            * context contains a nul and we should audit 
that */

                           if (str[size - 1] == '\0')
                                  audit_size = size - 1;
                           else
                                  audit_size = size;


This audit-related code has to deal with the possibility that there is 
an embedded NUL (and might also lack a terminating NUL) because it is 
dealing with the original user-supplied value, not a string that has 
been stored in a context structure. After this audit-related code, we 
proceed to call security_context_to_sid_force() which calls 
security_context_to_sid_core() with force=1.  This first creates a 
NUL-terminated copy of the value (scontext) as scontext2 using 
kmemdup_nul(), which could potentially contain embedded NULs if the 
original did.  In the force=1 case, it then creates a copy of scontext2 
as str using kstrdup(), yielding a NUL-terminated string with no 
embedded NULs. It is this NUL-terminated string (str) that is stored in 
the context structure as context.str and context.len is set to 
strlen(str)+1 after your earlier commit.


How would we end up with a context->len other than 
strlen(context->str)+1 in security_sid_to_context_core()?


The point is that we ought to sanitize context->len when it is set, not 
when it is read, and in theory that is exactly what we are doing in 
security_context_to_sid_core(), such that security_sid_to_context_core() 
can read that value without recomputing it.  If it is being set 
incorrectly somewhere else, we ought to fix it there.  If it is being 
corrupted through memory corruption, then we ought to fix the source of 
the memory corruption.




Call StacK:

[] kasan_report+0x32c/0x485 mm/kasan/report.c:309
[] check_memory_region_inline mm/kasan/kasan.c:301 
[inline]

[] check_memory_region+0x2b/0x130 mm/kasan/kasan.c:315
[] __asan_loadN+0xf/0x11 mm/kasan/kasan.c:745
[] ext4_xattr_set_entry+0x6a1/0x6d3 fs/ext4/xattr.c:747
[] ext4_xattr_ibody_set.isra.9+0x4f/0x118 
fs/ext4/xattr.c:1118

[] ext4_xattr_set_handle+0x39a/0x7b4 fs/ext4/xattr.c:1224
[] ext4_initxattrs+0x6b/0x96 fs/ext4/xattr_security.c:42
[] security_inode_init_security+0x170/0x1c9 
security/security.c:403
[] ext4_init_security+0x35/0x3d 
fs/ext4/xattr_security.c:56

[] __ext4_new_inode+0x1f24/0x2266 fs/ext4/ialloc.c:1059
[] ext4_mknod+0x11a/0x263 fs/ext4/namei.c:2510
[] vfs_mknod2+0x1ee/0x29f fs/namei.c:3722
[] SYSC_mknodat fs/namei.c:3780 [inline]
[] SyS_mknodat+0x19a/0x22a fs/namei.c:3752
[] do_syscall_64+0xf8/0x191 arch/x86/entry/common.c:282
[] entry_SYSCALL_64_after_swapgs+0x58/0xc6

Syzkaller reproducer:
# {Threaded:false Collide:false Repeat:false Procs:1 Sandbox:none 
Fault:false FaultCall:-1 FaultNth:0 EnableTun:false UseTmpDir:false 
EnableCgroups:false EnableNetdev:false ResetNet:false HandleSegv:false 
WaitRepeat:false Debug:false Repro:false}
r0 = syz_open_procfs(0x, 
&(0x7f0002c0)='attr/fscreate\x00')


Re: [PATCH RFC 5/5] SELinux: Support SELinux determination of side-channel vulnerability

2018-08-16 Thread Stephen Smalley

On 08/15/2018 07:53 PM, Casey Schaufler wrote:

SELinux considers tasks to be side-channel safe if they
have PROCESS_SHARE access.

Signed-off-by: Casey Schaufler 
---
  security/selinux/hooks.c | 9 +
  1 file changed, 9 insertions(+)

diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index a8bf324130f5..7fbd7d7ac1cb 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -4219,6 +4219,14 @@ static void selinux_task_to_inode(struct task_struct *p,
spin_unlock(>lock);
  }
  
+static int selinux_task_safe_sidechannel(struct task_struct *p)

+{
+   struct av_decision avd;
+
+   return avc_has_perm_noaudit(_state, current_sid(), task_sid(p),
+   SECCLASS_PROCESS, PROCESS__SHARE, 0, );
+}


If you are going to apply this kind of check, is there a reason you 
wouldn't just use the ptrace checking logic?  Just call 
ptrace_may_access() with PTRACE_MODE_READ and dispense with having a 
separate hook altogether.  Then you get uids/gids, caps, dumpable, and 
security module checking for free.


Regardless, I don't think share permission is the right answer here; it 
has very different semantics and security implications, and is almost 
never allowed in Android policy (just one instance for kernel->init 
transition).



+
  /* Returns error only if unable to parse addresses */
  static int selinux_parse_skb_ipv4(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
@@ -7002,6 +7010,7 @@ static struct security_hook_list selinux_hooks[] 
__lsm_ro_after_init = {
LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
LSM_HOOK_INIT(task_kill, selinux_task_kill),
LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
+   LSM_HOOK_INIT(task_safe_sidechannel, selinux_task_safe_sidechannel),
  
  	LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),

LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Possible OOB Read in Kernel Heap Memory in call to ext4_xattr_set_entry()

2018-08-13 Thread Stephen Smalley

On 08/13/2018 08:59 AM, Sachin Grover wrote:
I agree with you that it cannot be exploitable on Android, but Kasan is 
able to find it as OOB if I run syzkaller on x86 based VM image. My last 
commit is actually only fixing one path, but there are multiple path 
which are having same issue, so it would be better if fix is given in 
context_struct_to_string() where length is calculated.


Let me know what is your take on this.


Are you sure that your earlier commit is included in the kernels you are 
testing? If so, can you provide one of the other code paths not 
addressed by your earlier commit?  It appears that context.len is only 
ever set by security_context_to_sid_core(), and there it is set to 
strlen(str)+1 after your commit (and context.str is set to str, which is 
the result of kstrdup of the original context).  Thus, when we reach 
context_struct_to_string() later, context->len can only be 
strlen(context->str)+1 AFAICS.  What am I missing?







From: Stephen Smalley
Sent: Monday 13 August, 18:05
Subject: Re: Possible OOB Read in Kernel Heap Memory in call to 
ext4_xattr_set_entry()

To: Sachin Grover, selinux@tycho.nsa.gov, Paul Moore


On 08/13/2018 08:23 AM, Stephen Smalley wrote: > On 08/13/2018 01:19 AM, 
Sachin Grover wrote: >> Hi Stephen/Paul, >> >> This issue was discovered 
using >> https://android.googlesource.com/kernel/common -b 
android-4.9-o, but >> I've verified the code path exists in msm-4.4. It 
likely exists in >> other kernel versions as well. >> >> As a privileged 
user, one can override the current SELinux context via >> a call to 
setfscreatecon() or by writing directly to >> /proc/self/attr/fscreate. 
The context is then used to label the next >> newly created file object, 
e.g. mknod(). Upon handling the creation of >> the new object on the 
EXT4 FS we end up calling >> selinux_inode_init_security() to create a 
new xattr object for the >> inode. This will end up calling 
context_struct_to_string() to convert >> the SID back to the string 
version of the SELinux security context >> that was stored. >> >> static 
int context_struct_to_string(struct context *context, char >> 
**scontext, u32 *scontext_len) >>   { >>      char *scontextp; >> >>
    if (scontext) >>           *scontext = NULL; >>       *scontext_len 
= 0; >> >>       if (context->len) { >>          *scontext_len = 
context->len; >>            if (scontext) { >>                *scontext 
= kstrdup(context->str, GFP_ATOMIC); >>                 if 
(!(*scontext)) >>                       return -ENOMEM; >>           } 
 >>           return 0; >>       } >> >> scontext is populated with the 
context length, directly from the >> context structure, and using 
kstrdup() to copy the string. Much later >> down the call stack 
ext4_xattr_set_entry() is called with the SELinux >> xattr object. >> >> 
 >>               if (i->value == EXT4_ZERO_XATTR_VALUE) { >>
        memset(val, 0, size); >>               } else { >>  
      /* Clear the pad bytes first. */ >>                   memset(val + 
size - EXT4_XATTR_PAD, 0, >>                          EXT4_XATTR_PAD); 
 >>                   memcpy(val, i->value, i->value_len); >>
    } >> >> SELinux allows for the creation of contexts that include 
NULL bytes. >> Unfortunately in this case if a NULL byte occurs not as 
the string >> terminator, then kstrdup() will allocate a memory region 
smaller than >> what context->len represents. Later in 
ext4_xattr_set_entry() the >> original context->len will be used in 
memcpy() and will exceed the >> heap memory allocated by kstrdup() 
leading to an OOB issue. There may >> also be the potential for memory 
corruption depending on the total >> length of the SELinux context, but 
this would require further analysis. >> >> Can you please let me know if 
my analysis is correct. >> As per me, it looks like there is problem in 
the code. > > Your earlier commit 
efe3de79e0b52ca281ef6691480c8c68c82a4657 ensures > that context->len is 
only ever set to strlen(str)+1.  So is it still > possible for this 
condition to occur? Also, as with the earlier bug, this one is only 
exploitable for a process with CAP_MAC_ADMIN that is allowed mac_admin 
permission in SELinux policy, and this is prohibited in Android policy 
via neverallow and checked by CTS.




___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: Possible OOB Read in Kernel Heap Memory in call to ext4_xattr_set_entry()

2018-08-13 Thread Stephen Smalley

On 08/13/2018 08:23 AM, Stephen Smalley wrote:

On 08/13/2018 01:19 AM, Sachin Grover wrote:

Hi Stephen/Paul,

This issue was discovered using 
https://android.googlesource.com/kernel/common -b android-4.9-o, but 
I've verified the code path exists in msm-4.4. It likely exists in 
other kernel versions as well.


As a privileged user, one can override the current SELinux context via 
a call to setfscreatecon() or by writing directly to 
/proc/self/attr/fscreate. The context is then used to label the next 
newly created file object, e.g. mknod(). Upon handling the creation of 
the new object on the EXT4 FS we end up calling 
selinux_inode_init_security() to create a new xattr object for the 
inode. This will end up calling context_struct_to_string() to convert 
the SID back to the string version of the SELinux security context 
that was stored.


static int context_struct_to_string(struct context *context, char 
**scontext, u32 *scontext_len)

  {
     char *scontextp;

      if (scontext)
          *scontext = NULL;
      *scontext_len = 0;

      if (context->len) {
         *scontext_len = context->len;
           if (scontext) {
               *scontext = kstrdup(context->str, GFP_ATOMIC);
                if (!(*scontext))
                      return -ENOMEM;
          }
          return 0;
      }

scontext is populated with the context length, directly from the 
context structure, and using kstrdup() to copy the string. Much later 
down the call stack ext4_xattr_set_entry() is called with the SELinux 
xattr object.



              if (i->value == EXT4_ZERO_XATTR_VALUE) {
                  memset(val, 0, size);
              } else {
                  /* Clear the pad bytes first. */
                  memset(val + size - EXT4_XATTR_PAD, 0,
                         EXT4_XATTR_PAD);
                  memcpy(val, i->value, i->value_len);
              }

SELinux allows for the creation of contexts that include NULL bytes. 
Unfortunately in this case if a NULL byte occurs not as the string 
terminator, then kstrdup() will allocate a memory region smaller than 
what context->len represents. Later in ext4_xattr_set_entry() the 
original context->len will be used in memcpy() and will exceed the 
heap memory allocated by kstrdup() leading to an OOB issue. There may 
also be the potential for memory corruption depending on the total 
length of the SELinux context, but this would require further analysis.


Can you please let me know if my analysis is correct.
As per me, it looks like there is problem in the code.


Your earlier commit efe3de79e0b52ca281ef6691480c8c68c82a4657 ensures 
that context->len is only ever set to strlen(str)+1.  So is it still 
possible for this condition to occur?


Also, as with the earlier bug, this one is only exploitable for a 
process with CAP_MAC_ADMIN that is allowed mac_admin permission in 
SELinux policy, and this is prohibited in Android policy via neverallow 
and checked by CTS.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: Possible OOB Read in Kernel Heap Memory in call to ext4_xattr_set_entry()

2018-08-13 Thread Stephen Smalley

On 08/13/2018 01:19 AM, Sachin Grover wrote:

Hi Stephen/Paul,

This issue was discovered using 
https://android.googlesource.com/kernel/common -b android-4.9-o, but 
I've verified the code path exists in msm-4.4. It likely exists in other 
kernel versions as well.


As a privileged user, one can override the current SELinux context via a 
call to setfscreatecon() or by writing directly to 
/proc/self/attr/fscreate. The context is then used to label the next 
newly created file object, e.g. mknod(). Upon handling the creation of 
the new object on the EXT4 FS we end up calling 
selinux_inode_init_security() to create a new xattr object for the 
inode. This will end up calling context_struct_to_string() to convert 
the SID back to the string version of the SELinux security context that 
was stored.


static int context_struct_to_string(struct context *context, char 
**scontext, u32 *scontext_len)

  {
     char *scontextp;

      if (scontext)
          *scontext = NULL;
      *scontext_len = 0;

      if (context->len) {
         *scontext_len = context->len;
           if (scontext) {
               *scontext = kstrdup(context->str, GFP_ATOMIC);
                if (!(*scontext))
                      return -ENOMEM;
          }
          return 0;
      }

scontext is populated with the context length, directly from the context 
structure, and using kstrdup() to copy the string. Much later down the 
call stack ext4_xattr_set_entry() is called with the SELinux xattr object.



              if (i->value == EXT4_ZERO_XATTR_VALUE) {
                  memset(val, 0, size);
              } else {
                  /* Clear the pad bytes first. */
                  memset(val + size - EXT4_XATTR_PAD, 0,
                         EXT4_XATTR_PAD);
                  memcpy(val, i->value, i->value_len);
              }

SELinux allows for the creation of contexts that include NULL bytes. 
Unfortunately in this case if a NULL byte occurs not as the string 
terminator, then kstrdup() will allocate a memory region smaller than 
what context->len represents. Later in ext4_xattr_set_entry() the 
original context->len will be used in memcpy() and will exceed the heap 
memory allocated by kstrdup() leading to an OOB issue. There may also be 
the potential for memory corruption depending on the total length of the 
SELinux context, but this would require further analysis.


Can you please let me know if my analysis is correct.
As per me, it looks like there is problem in the code.


Your earlier commit efe3de79e0b52ca281ef6691480c8c68c82a4657 ensures 
that context->len is only ever set to strlen(str)+1.  So is it still 
possible for this condition to occur?


>


Regards,
Sachin Grover

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH] selinux: stricter parsing in mls_context_to_sid()

2018-08-06 Thread Stephen Smalley

On 08/03/2018 05:36 AM, Jann Horn wrote:

mls_context_to_sid incorrectly accepted MLS context strings that are
followed by a dash and trailing garbage.

Before this change, the following command works:

# mount -t tmpfs -o 'context=system_u:object_r:tmp_t:s0-s0:c0-BLAH' \
none mount

After this change, it fails with the following error message in dmesg:

SELinux: security_context_str_to_sid(system_u:object_r:tmp_t:s0-s0:c0-BLAH)
failed for (dev tmpfs, type tmpfs) errno=-22

This is not an important bug; but it is a small quirk that was useful for
exploiting a vulnerability in fusermount.

This patch does not change the behavior when the policy does not have MLS
enabled.

Signed-off-by: Jann Horn 


Acked-by: Stephen Smalley 


---
  security/selinux/ss/mls.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/security/selinux/ss/mls.c b/security/selinux/ss/mls.c
index 39475fb455bc..2c73d612d2ee 100644
--- a/security/selinux/ss/mls.c
+++ b/security/selinux/ss/mls.c
@@ -344,7 +344,7 @@ int mls_context_to_sid(struct policydb *pol,
break;
}
}
-   if (delim == '-') {
+   if (delim == '-' && l == 0) {
/* Extract high sensitivity. */
scontextp = p;
while (*p && *p != ':')



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: libsemanage getpwent and nss-systemd incompability

2018-07-13 Thread Stephen Smalley
On 07/13/2018 10:26 AM, Laurent Bigonville wrote:
> Le 13/07/18 à 16:19, Laurent Bigonville a écrit :
>> Le 10/07/18 à 17:58, Stephen Smalley a écrit :
>>> On 07/10/2018 11:40 AM, Stephen Smalley wrote:
>>>> On 07/09/2018 04:20 PM, Nicolas Iooss wrote:
>>>>> Hello,
>>>>>
>>>>> While testing a systemd update on Arch Linux, I encountered the
>>>>> following message (in a Vagrant virtual machine):
>>>>>
>>>>> # semanage fcontext -m -s sysadm_u -t user_home_t '/vagrant(/.*)?'
>>>>> libsemanage.get_home_dirs: Error while fetching users. Returning list so 
>>>>> far.
>>>>>
>>>>> A quick debugging of get_home_dirs() in
>>>>> libsemanage/src/genhomedircon.c shows that the loop "while ((pwbuf =
>>>>> getpwent()) != NULL)" stops with pwbuf=NULL and errno=2 (ENOENT). My
>>>>> /etc/nsswitch.conf contains:
>>>>>
>>>>> passwd: files mymachines systemd
>>>>>
>>>>> If I remove "systemd" from this line, the error disappears. Therefore
>>>>> it seems that systemd's NSS module returns a ENOENT error when
>>>>> getpwent() is called. I have not found any clue in systemd's code [1]
>>>>> about such an error and I have not got much time to debug this issue.
>>>>> Does this occurs for someone else (using Fedora for example)?
>>>> Fedora ships with usepasswd=False in semanage.conf, so we'll never reach 
>>>> that code in a default configuration.
>>>> Fedora nsswitch.conf has following for passwd:
>>>> passwd:    files sss systemd
>>>>
>>>> Removing usepasswd=False from semanage.conf, I see the same behavior with 
>>>> libsemanage 2.8, systemd 239, and glibc 2.27 on Fedora and it did not 
>>>> occur with systemd 238.  systemd v239 does introduce support into 
>>>> nss-systemd for looking up dynamic users, so this seems to be the cause. 
>>>> Not sure yet whether this represents a bug in libsemanage or systemd, but 
>>>> it appears to just be a warning and not fatal to operation.
>>> I'm inclined to think that this is a bug in systemd.  The man page for 
>>> getpwent() says nothing about setting errno to ENOENT upon reaching the end 
>>> of the passwd database; it should just return NULL w/o setting errno AFAICT.
>>
>> I see the same warning in debian.
>>
>> If I'm reading 
>> https://www.gnu.org/software/libc/manual/html_node/NSS-Modules-Interface.html
>>  well this is actually valid to set errno=ENOENT and return 
>> NSS_STATUS_NOTFOUND if "The requested entry is not available.", so that 
>> should be OK?
> 
> There are more info at 
> https://www.gnu.org/software/libc/manual/html_node/NSS-Module-Function-Internals.html
>  as well: "The function shall return NSS_STATUS_SUCCESS as long as there are 
> more entries. When the last entry was read it should return 
> NSS_STATUS_NOTFOUND. When the buffer given as an argument is too small for 
> the data to be returned NSS_STATUS_TRYAGAIN should be returned. When the 
> service was not formerly initialized by a call to _nss_DATABASE_setdbent all 
> return values allowed for this function can also be returned here."
> 
> But indeed, it's not that clear if you should set errno or not if you reach 
> the last entry

I'm not averse to a patch for libsemanage to ignore ENOENT from getpwent(), but 
I think it is a bug in either systemd (i.e. it shouldn't be setting ENOENT) or 
glibc (it should suppress it) given that it is not documented as a possible 
errno value in getpwent(3).  If we ignore it, we likely ought to clear errno to 
avoid incorrect propagation of an ENOENT errno to later code.  But someone 
likely ought to open a bug with either systemd or glibc maintainers regardless. 
 Should be easy to create a trivial test case w/o involving libsemanage, just 
some code that calls getpwent() until it returns NULL and then tests the errno 
value, and show that it changes between systemd v238 and systemd v239.



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH 07/32] selinux: Implement the new mount API LSM hooks [ver #9]

2018-07-11 Thread Stephen Smalley
On 07/10/2018 06:42 PM, David Howells wrote:
> Implement the new mount API LSM hooks for SELinux.  At some point the old
> hooks will need to be removed.
> 
> Question: Should the ->fs_context_parse_source() hook be implemented to
> check the labels on any source devices specified?

The hook interface doesn't appear to lend itself to such validation, since you 
are just passing a string, not an inode.
Looking up the inode within the security module could easily yield a different 
object than what is ultimately used for the actual mount.

> 
> Signed-off-by: David Howells 
> cc: Paul Moore 
> cc: Stephen Smalley 
> cc: selinux@tycho.nsa.gov
> cc: linux-security-mod...@vger.kernel.org
> ---
> 
>  security/selinux/hooks.c |  264 
> ++
>  1 file changed, 264 insertions(+)
> 
> diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
> index 5bb53edd74cc..bdecae4b7306 100644
> --- a/security/selinux/hooks.c
> +++ b/security/selinux/hooks.c
> @@ -48,6 +48,7 @@
>  #include 
>  #include 
>  #include 
> +#include 
>  #include 
>  #include 
>  #include 
> @@ -2973,6 +2974,261 @@ static int selinux_umount(struct vfsmount *mnt, int 
> flags)
>  FILESYSTEM__UNMOUNT, NULL);
>  }
>  
> +/* fsopen mount context operations */
> +
> +static int selinux_fs_context_alloc(struct fs_context *fc,
> + struct dentry *reference)
> +{
> + struct security_mnt_opts *opts;
> +
> + opts = kzalloc(sizeof(*opts), GFP_KERNEL);
> + if (!opts)
> + return -ENOMEM;
> +
> + fc->security = opts;
> + return 0;
> +}
> +
> +static int selinux_fs_context_dup(struct fs_context *fc,
> +   struct fs_context *src_fc)
> +{
> + const struct security_mnt_opts *src = src_fc->security;
> + struct security_mnt_opts *opts;
> + int i, n;
> +
> + opts = kzalloc(sizeof(*opts), GFP_KERNEL);
> + if (!opts)
> + return -ENOMEM;
> + fc->security = opts;
> +
> + if (!src || !src->num_mnt_opts)
> + return 0;
> + n = opts->num_mnt_opts = src->num_mnt_opts;
> +
> + if (src->mnt_opts) {
> + opts->mnt_opts = kcalloc(n, sizeof(char *), GFP_KERNEL);
> + if (!opts->mnt_opts)
> + return -ENOMEM;
> +
> + for (i = 0; i < n; i++) {
> + if (src->mnt_opts[i]) {
> + opts->mnt_opts[i] = kstrdup(src->mnt_opts[i],
> + GFP_KERNEL);
> + if (!opts->mnt_opts[i])
> + return -ENOMEM;
> + }
> + }
> + }
> +
> + if (src->mnt_opts_flags) {
> + opts->mnt_opts_flags = kmemdup(src->mnt_opts_flags,
> +n * sizeof(int), GFP_KERNEL);
> + if (!opts->mnt_opts_flags)
> + return -ENOMEM;
> + }
> +
> + return 0;
> +}
> +
> +static void selinux_fs_context_free(struct fs_context *fc)
> +{
> + struct security_mnt_opts *opts = fc->security;
> +
> + if (opts) {
> + security_free_mnt_opts(opts);
> + fc->security = NULL;
> + }
> +}
> +
> +static int selinux_fs_context_parse_option(struct fs_context *fc, char *opt, 
> size_t len)
> +{
> + struct security_mnt_opts *opts = fc->security;
> + substring_t args[MAX_OPT_ARGS];
> + unsigned int have;
> + char *c, **oo;
> + int token, ctx, i, *of;
> +
> + token = match_token(opt, tokens, args);
> + if (token == Opt_error)
> + return 0; /* Doesn't belong to us. */
> +
> + have = 0;
> + for (i = 0; i < opts->num_mnt_opts; i++)
> + have |= 1 << opts->mnt_opts_flags[i];
> + if (have & (1 << token))
> + return -EINVAL;
> +
> + switch (token) {
> + case Opt_context:
> + if (have & (1 << Opt_defcontext))
> + goto incompatible;
> + ctx = CONTEXT_MNT;
> + goto copy_context_string;
> +
> + case Opt_fscontext:
> + ctx = FSCONTEXT_MNT;
> + goto copy_context_string;
> +
> + case Opt_rootcontext:
> + ctx = ROOTCONTEXT_MNT;
> + goto copy_context_string;
> +
> + case Opt_defcontext:
> + if (have & (1 << Opt_context))
> + got

Re: blocking / mount using containers

2018-07-10 Thread Stephen Smalley
On 07/10/2018 10:00 AM, Mclain, Warren wrote:
> I am trying to find a solution for blocking the mounting of / from 
> containers. This is a major security hole for Docker and all of those types 
> of applications.
> 
>  
> 
> I found the mount_anyfile  Boolean but nothing that digs into that to show 
> how to disable specific mountings.
> 
>  
> 
> Looking for any information that would help the container community in 
> general.

Not sure if this answers your question, but Fedora/RHEL ships with a container 
policy that should already protect the host OS filesystem from the containers.

Even if you mount / into the container when you create it, it isn't writable 
due to SELinux policy, e.g.
$ sudo docker run -v /:/mnt -i -t fedora /bin/bash 
[root@fb83953335bb /]# cd mnt
[root@fb83953335bb mnt]# cat etc/shadow
cat: etc/shadow: Permission denied
[root@fb83953335bb mnt]# touch foo
touch: cannot touch 'foo': Permission denied
[root@fb83953335bb mnt]# exit
$ sudo ausearch -i -m AVC -ts recent

type=PROCTITLE msg=audit(07/10/2018 12:40:11.083:870570) : proctitle=cat 
etc/shadow 
type=PATH msg=audit(07/10/2018 12:40:11.083:870570) : item=0 name=etc/shadow 
inode=1311125 dev=fd:01 mode=file,000 ouid=root ogid=root rdev=00:00 
obj=system_u:object_r:shadow_t:s0 nametype=NORMAL cap_fp=none cap_fi=none 
cap_fe=0 cap_fver=0 
type=CWD msg=audit(07/10/2018 12:40:11.083:870570) : cwd=/mnt 
type=SYSCALL msg=audit(07/10/2018 12:40:11.083:870570) : arch=x86_64 
syscall=openat success=no exit=EACCES(Permission denied) a0=0xff9c 
a1=0x7fffe6c7b92f a2=O_RDONLY a3=0x0 items=1 ppid=1992 pid=2044 auid=unset 
uid=root gid=root euid=root suid=root fsuid=root egid=root sgid=root fsgid=root 
tty=pts3 ses=unset comm=cat exe=/usr/bin/cat 
subj=system_u:system_r:container_t:s0:c138,c987 key=(null) 
type=AVC msg=audit(07/10/2018 12:40:11.083:870570) : avc:  denied  { read } for 
 pid=2044 comm=cat name=shadow dev="dm-1" ino=1311125 
scontext=system_u:system_r:container_t:s0:c138,c987 
tcontext=system_u:object_r:shadow_t:s0 tclass=file permissive=0 

type=PROCTITLE msg=audit(07/10/2018 12:40:19.859:870580) : proctitle=touch foo 
type=PATH msg=audit(07/10/2018 12:40:19.859:870580) : item=0 name=/mnt inode=2 
dev=fd:01 mode=dir,555 ouid=root ogid=root rdev=00:00 
obj=system_u:object_r:root_t:s0 nametype=PARENT cap_fp=none cap_fi=none 
cap_fe=0 cap_fver=0 
type=CWD msg=audit(07/10/2018 12:40:19.859:870580) : cwd=/mnt 
type=SYSCALL msg=audit(07/10/2018 12:40:19.859:870580) : arch=x86_64 
syscall=openat success=no exit=EACCES(Permission denied) a0=0xff9c 
a1=0x7ffc7550f932 a2=O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK a3=0x1b6 items=1 
ppid=1992 pid=2053 auid=unset uid=root gid=root euid=root suid=root fsuid=root 
egid=root sgid=root fsgid=root tty=pts3 ses=unset comm=touch exe=/usr/bin/touch 
subj=system_u:system_r:container_t:s0:c138,c987 key=(null) 
type=AVC msg=audit(07/10/2018 12:40:19.859:870580) : avc:  denied  { write } 
for  pid=2053 comm=touch name=/ dev="dm-1" ino=2 
scontext=system_u:system_r:container_t:s0:c138,c987 
tcontext=system_u:object_r:root_t:s0 tclass=dir permissive=0 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: libsemanage getpwent and nss-systemd incompability

2018-07-10 Thread Stephen Smalley
On 07/09/2018 04:20 PM, Nicolas Iooss wrote:
> Hello,
> 
> While testing a systemd update on Arch Linux, I encountered the
> following message (in a Vagrant virtual machine):
> 
> # semanage fcontext -m -s sysadm_u -t user_home_t '/vagrant(/.*)?'
> libsemanage.get_home_dirs: Error while fetching users.  Returning list so far.
> 
> A quick debugging of get_home_dirs() in
> libsemanage/src/genhomedircon.c shows that the loop "while ((pwbuf =
> getpwent()) != NULL)" stops with pwbuf=NULL and errno=2 (ENOENT). My
> /etc/nsswitch.conf contains:
> 
> passwd: files mymachines systemd
> 
> If I remove "systemd" from this line, the error disappears. Therefore
> it seems that systemd's NSS module returns a ENOENT error when
> getpwent() is called. I have not found any clue in systemd's code [1]
> about such an error and I have not got much time to debug this issue.
> Does this occurs for someone else (using Fedora for example)?

Fedora ships with usepasswd=False in semanage.conf, so we'll never reach that 
code in a default configuration.
Fedora nsswitch.conf has following for passwd:
passwd: files sss systemd

Removing usepasswd=False from semanage.conf, I see the same behavior with 
libsemanage 2.8, systemd 239, and glibc 2.27 on Fedora and it did not occur 
with systemd 238.  systemd v239 does introduce support into nss-systemd for 
looking up dynamic users, so this seems to be the cause. Not sure yet whether 
this represents a bug in libsemanage or systemd, but it appears to just be a 
warning and not fatal to operation.

> 
> For information, this issue occurs with SELinux release 2.8 (and git
> master branch), systemd 239.0 and glibc 2.27, on a system with SELinux
> in permissive mode.
> 
> Best,
> Nicolas
> 
> [1] 
> https://github.com/systemd/systemd/blob/master/src/nss-systemd/nss-systemd.c
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH] python/semanage: Stop logging loginRecords changes

2018-06-26 Thread Stephen Smalley
On 06/18/2018 01:22 PM, Vit Mojzis wrote:
> semanage_seuser_modify_local and semanage_seuser_del_local already do
> the logging.
> Moreover, semanage log for loginRecords.__add was flawed since it
> reported old-{seuser,role,range} of default user instead of None. This
> was caused by selinux.getseuserbyname, which returns values for default
> user when the specified username is not found.
> 
> Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=1294663

Thanks, applied.

> 
> Signed-off-by: Vit Mojzis 
> ---
>  python/semanage/seobject.py | 8 
>  1 file changed, 8 deletions(-)
> 
> diff --git a/python/semanage/seobject.py b/python/semanage/seobject.py
> index c76dce85..d3e14a8b 100644
> --- a/python/semanage/seobject.py
> +++ b/python/semanage/seobject.py
> @@ -593,7 +593,6 @@ class loginRecords(semanageRecords):
>  
>  semanage_seuser_key_free(k)
>  semanage_seuser_free(u)
> -self.mylog.log("login", name, sename=sename, serange=serange, 
> serole=",".join(serole), oldserole=",".join(oldserole), 
> oldsename=self.oldsename, oldserange=self.oldserange)
>  
>  def add(self, name, sename, serange):
>  try:
> @@ -601,7 +600,6 @@ class loginRecords(semanageRecords):
>  self.__add(name, sename, serange)
>  self.commit()
>  except ValueError as error:
> -self.mylog.commit(0)
>  raise error
>  
>  def __modify(self, name, sename="", serange=""):
> @@ -653,7 +651,6 @@ class loginRecords(semanageRecords):
>  
>  semanage_seuser_key_free(k)
>  semanage_seuser_free(u)
> -self.mylog.log("login", name, sename=self.sename, 
> serange=self.serange, serole=",".join(serole), oldserole=",".join(oldserole), 
> oldsename=self.oldsename, oldserange=self.oldserange)
>  
>  def modify(self, name, sename="", serange=""):
>  try:
> @@ -661,7 +658,6 @@ class loginRecords(semanageRecords):
>  self.__modify(name, sename, serange)
>  self.commit()
>  except ValueError as error:
> -self.mylog.commit(0)
>  raise error
>  
>  def __delete(self, name):
> @@ -694,8 +690,6 @@ class loginRecords(semanageRecords):
>  rec, self.sename, self.serange = 
> selinux.getseuserbyname("__default__")
>  range, (rc, serole) = userrec.get(self.sename)
>  
> -self.mylog.log_remove("login", name, sename=self.sename, 
> serange=self.serange, serole=",".join(serole), oldserole=",".join(oldserole), 
> oldsename=self.oldsename, oldserange=self.oldserange)
> -
>  def delete(self, name):
>  try:
>  self.begin()
> @@ -703,7 +697,6 @@ class loginRecords(semanageRecords):
>  self.commit()
>  
>  except ValueError as error:
> -self.mylog.commit(0)
>  raise error
>  
>  def deleteall(self):
> @@ -717,7 +710,6 @@ class loginRecords(semanageRecords):
>  self.__delete(semanage_seuser_get_name(u))
>  self.commit()
>  except ValueError as error:
> -self.mylog.commit(0)
>  raise error
>  
>  def get_all_logins(self):
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH 1/3] selinux: make dentry_init_security() return security module name

2018-06-26 Thread Stephen Smalley
On 06/26/2018 04:43 AM, Yan, Zheng wrote:
> This is preparation for CephFS security label. CephFS's implementation uses
> dentry_init_security() to get security context before inode is created,
> then sends open/mkdir/mknod request to MDS, together with security xattr
> "security."

Can you describe how your approach compares to the NFSv4 labeling support, and 
why it requires
exporting this information from this hook when NFSv4 did not?

> 
> Signed-off-by: "Yan, Zheng" 
> ---
>  fs/nfs/nfs4proc.c | 3 ++-
>  include/linux/lsm_hooks.h | 4 ++--
>  include/linux/security.h  | 9 +
>  security/security.c   | 7 ---
>  security/selinux/hooks.c  | 8 ++--
>  5 files changed, 19 insertions(+), 12 deletions(-)
> 
> diff --git a/fs/nfs/nfs4proc.c b/fs/nfs/nfs4proc.c
> index 6dd146885da9..d18a5fb7aec3 100644
> --- a/fs/nfs/nfs4proc.c
> +++ b/fs/nfs/nfs4proc.c
> @@ -122,7 +122,8 @@ nfs4_label_init_security(struct inode *dir, struct dentry 
> *dentry,
>   return NULL;
>  
>   err = security_dentry_init_security(dentry, sattr->ia_mode,
> - >d_name, (void **)>label, 
> >len);
> + >d_name,  NULL,
> + (void **)>label, >len);
>   if (err == 0)
>   return label;
>  
> diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
> index 8f1131c8dd54..e176c2032bdc 100644
> --- a/include/linux/lsm_hooks.h
> +++ b/include/linux/lsm_hooks.h
> @@ -1476,8 +1476,8 @@ union security_list_options {
>   unsigned long *set_kern_flags);
>   int (*sb_parse_opts_str)(char *options, struct security_mnt_opts *opts);
>   int (*dentry_init_security)(struct dentry *dentry, int mode,
> - const struct qstr *name, void **ctx,
> - u32 *ctxlen);
> + const struct qstr *name, const char 
> **label,

Seems like "label" could be confusing given that it means something else in the 
NFSv4 code,
and what is actually being provided here is the xattr name suffix.

> + void **ctx, u32 *ctxlen);
>   int (*dentry_create_files_as)(struct dentry *dentry, int mode,
>   struct qstr *name,
>   const struct cred *old,
> diff --git a/include/linux/security.h b/include/linux/security.h
> index 63030c85ee19..df2d73998c64 100644
> --- a/include/linux/security.h
> +++ b/include/linux/security.h
> @@ -246,8 +246,9 @@ int security_sb_clone_mnt_opts(const struct super_block 
> *oldsb,
>   unsigned long *set_kern_flags);
>  int security_sb_parse_opts_str(char *options, struct security_mnt_opts 
> *opts);
>  int security_dentry_init_security(struct dentry *dentry, int mode,
> - const struct qstr *name, void **ctx,
> - u32 *ctxlen);
> + const struct qstr *name,
> + const char **label,
> + void **ctx, u32 *ctxlen);
>  int security_dentry_create_files_as(struct dentry *dentry, int mode,
>   struct qstr *name,
>   const struct cred *old,
> @@ -609,8 +610,8 @@ static inline void security_inode_free(struct inode 
> *inode)
>  static inline int security_dentry_init_security(struct dentry *dentry,
>int mode,
>const struct qstr *name,
> -  void **ctx,
> -  u32 *ctxlen)
> +  const char **label,
> +  void **ctx, u32 *ctxlen)
>  {
>   return -EOPNOTSUPP;
>  }
> diff --git a/security/security.c b/security/security.c
> index 68f46d849abe..69818d46aa28 100644
> --- a/security/security.c
> +++ b/security/security.c
> @@ -450,11 +450,12 @@ void security_inode_free(struct inode *inode)
>  }
>  
>  int security_dentry_init_security(struct dentry *dentry, int mode,
> - const struct qstr *name, void **ctx,
> - u32 *ctxlen)
> + const struct qstr *name,
> + const char **label,
> + void **ctx, u32 *ctxlen)
>  {
>   return call_int_hook(dentry_init_security, -EOPNOTSUPP, dentry, mode,
> - name, ctx, ctxlen);
> + name, label, ctx, ctxlen);
>  }
>  EXPORT_SYMBOL(security_dentry_init_security);
>  
> diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
> index 2b5ee5fbd652..eca3879d9357 100644
> --- 

Re: [PATCH] selinux: move user accesses in selinuxfs out of locked regions

2018-06-26 Thread Stephen Smalley
On 06/26/2018 08:42 AM, Jann Horn wrote:
> On Tue, Jun 26, 2018 at 2:15 PM Stephen Smalley  wrote:
>>
>> On 06/25/2018 12:34 PM, Jann Horn wrote:
>>> If a user is accessing a file in selinuxfs with a pointer to a userspace
>>> buffer that is backed by e.g. a userfaultfd, the userspace access can
>>> stall indefinitely, which can block fsi->mutex if it is held.
>>>
>>> For sel_read_policy(), remove the locking, since this method doesn't seem
>>> to access anything that requires locking.
>>>
>>> For sel_read_bool(), move the user access below the locked region.
>>>
>>> For sel_write_bool() and sel_commit_bools_write(), move the user access
>>> up above the locked region.
>>>
>>> Cc: sta...@vger.kernel.org
>>> Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
>>> Signed-off-by: Jann Horn 
>>
>> Only question I have is wrt the Fixes line, i.e. was this an issue until 
>> userfaultfd was introduced, and if not,
>> do we need it to be back-ported any further than the commit which introduced 
>> it.
> 
> You can also use FUSE, if the system is configured appropriately:
> Mount a FUSE filesystem, mmap() a file from it, then pass a pointer to
> the mmapped region to a syscall. AFAICS FUSE was added to the kernel
> in commit d8a5ba45457e4a22aa39c939121efd7bb6c76672, first in
> v2.6.16.28.

Ok, then I guess it would be splitting hairs to not just take it all the way 
back.

> 
>> Otherwise, you can add my
>> Acked-by: Stephen Smalley 
> 
> This patch should go through Paul Moore's tree, right?

Yes, thanks.

> 
>>> ---
>>>  security/selinux/selinuxfs.c | 77 
>>>  1 file changed, 33 insertions(+), 44 deletions(-)
>>>
>>> diff --git a/security/selinux/selinuxfs.c b/security/selinux/selinuxfs.c
>>> index f3d374d2ca04..065f8cea84e3 100644
>>> --- a/security/selinux/selinuxfs.c
>>> +++ b/security/selinux/selinuxfs.c
>>> @@ -445,18 +445,13 @@ static ssize_t sel_read_policy(struct file *filp, 
>>> char __user *buf,
>>>   struct policy_load_memory *plm = filp->private_data;
>>>   int ret;
>>>
>>> - mutex_lock(>mutex);
>>> -
>>>   ret = avc_has_perm(_state,
>>>  current_sid(), SECINITSID_SECURITY,
>>> SECCLASS_SECURITY, SECURITY__READ_POLICY, NULL);
>>>   if (ret)
>>> - goto out;
>>> + return ret;
>>>
>>> - ret = simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
>>> -out:
>>> - mutex_unlock(>mutex);
>>> - return ret;
>>> + return simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
>>>  }
>>>
>>>  static vm_fault_t sel_mmap_policy_fault(struct vm_fault *vmf)
>>> @@ -1188,25 +1183,29 @@ static ssize_t sel_read_bool(struct file *filep, 
>>> char __user *buf,
>>>   ret = -EINVAL;
>>>   if (index >= fsi->bool_num || strcmp(name,
>>>fsi->bool_pending_names[index]))
>>> - goto out;
>>> + goto out_unlock;
>>>
>>>   ret = -ENOMEM;
>>>   page = (char *)get_zeroed_page(GFP_KERNEL);
>>>   if (!page)
>>> - goto out;
>>> + goto out_unlock;
>>>
>>>   cur_enforcing = security_get_bool_value(fsi->state, index);
>>>   if (cur_enforcing < 0) {
>>>   ret = cur_enforcing;
>>> - goto out;
>>> + goto out_unlock;
>>>   }
>>>   length = scnprintf(page, PAGE_SIZE, "%d %d", cur_enforcing,
>>> fsi->bool_pending_values[index]);
>>> - ret = simple_read_from_buffer(buf, count, ppos, page, length);
>>> -out:
>>>   mutex_unlock(>mutex);
>>> + ret = simple_read_from_buffer(buf, count, ppos, page, length);
>>> +out_free:
>>>   free_page((unsigned long)page);
>>>   return ret;
>>> +
>>> +out_unlock:
>>> + mutex_unlock(>mutex);
>>> + goto out_free;
>>>  }
>>>
>>>  static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
>>> @@ -1219,6 +1218,17 @@ static ssize_t sel_write_bool(struct file *filep, 
>>> const char __user *buf,
>>>   unsigned index = file_inode(filep)-

Re: [PATCH] selinux: move user accesses in selinuxfs out of locked regions

2018-06-26 Thread Stephen Smalley
On 06/25/2018 12:34 PM, Jann Horn wrote:
> If a user is accessing a file in selinuxfs with a pointer to a userspace
> buffer that is backed by e.g. a userfaultfd, the userspace access can
> stall indefinitely, which can block fsi->mutex if it is held.
> 
> For sel_read_policy(), remove the locking, since this method doesn't seem
> to access anything that requires locking.
> 
> For sel_read_bool(), move the user access below the locked region.
> 
> For sel_write_bool() and sel_commit_bools_write(), move the user access
> up above the locked region.
> 
> Cc: sta...@vger.kernel.org
> Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
> Signed-off-by: Jann Horn 

Only question I have is wrt the Fixes line, i.e. was this an issue until 
userfaultfd was introduced, and if not,
do we need it to be back-ported any further than the commit which introduced it.

Otherwise, you can add my
Acked-by: Stephen Smalley 

> ---
>  security/selinux/selinuxfs.c | 77 
>  1 file changed, 33 insertions(+), 44 deletions(-)
> 
> diff --git a/security/selinux/selinuxfs.c b/security/selinux/selinuxfs.c
> index f3d374d2ca04..065f8cea84e3 100644
> --- a/security/selinux/selinuxfs.c
> +++ b/security/selinux/selinuxfs.c
> @@ -445,18 +445,13 @@ static ssize_t sel_read_policy(struct file *filp, char 
> __user *buf,
>   struct policy_load_memory *plm = filp->private_data;
>   int ret;
>  
> - mutex_lock(>mutex);
> -
>   ret = avc_has_perm(_state,
>  current_sid(), SECINITSID_SECURITY,
> SECCLASS_SECURITY, SECURITY__READ_POLICY, NULL);
>   if (ret)
> - goto out;
> + return ret;
>  
> - ret = simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
> -out:
> - mutex_unlock(>mutex);
> - return ret;
> + return simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
>  }
>  
>  static vm_fault_t sel_mmap_policy_fault(struct vm_fault *vmf)
> @@ -1188,25 +1183,29 @@ static ssize_t sel_read_bool(struct file *filep, char 
> __user *buf,
>   ret = -EINVAL;
>   if (index >= fsi->bool_num || strcmp(name,
>fsi->bool_pending_names[index]))
> - goto out;
> + goto out_unlock;
>  
>   ret = -ENOMEM;
>   page = (char *)get_zeroed_page(GFP_KERNEL);
>   if (!page)
> - goto out;
> + goto out_unlock;
>  
>   cur_enforcing = security_get_bool_value(fsi->state, index);
>   if (cur_enforcing < 0) {
>   ret = cur_enforcing;
> - goto out;
> + goto out_unlock;
>   }
>   length = scnprintf(page, PAGE_SIZE, "%d %d", cur_enforcing,
> fsi->bool_pending_values[index]);
> - ret = simple_read_from_buffer(buf, count, ppos, page, length);
> -out:
>   mutex_unlock(>mutex);
> + ret = simple_read_from_buffer(buf, count, ppos, page, length);
> +out_free:
>   free_page((unsigned long)page);
>   return ret;
> +
> +out_unlock:
> + mutex_unlock(>mutex);
> + goto out_free;
>  }
>  
>  static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
> @@ -1219,6 +1218,17 @@ static ssize_t sel_write_bool(struct file *filep, 
> const char __user *buf,
>   unsigned index = file_inode(filep)->i_ino & SEL_INO_MASK;
>   const char *name = filep->f_path.dentry->d_name.name;
>  
> + if (count >= PAGE_SIZE)
> + return -ENOMEM;
> +
> + /* No partial writes. */
> + if (*ppos != 0)
> + return -EINVAL;
> +
> + page = memdup_user_nul(buf, count);
> + if (IS_ERR(page))
> + return PTR_ERR(page);
> +
>   mutex_lock(>mutex);
>  
>   length = avc_has_perm(_state,
> @@ -1233,22 +1243,6 @@ static ssize_t sel_write_bool(struct file *filep, 
> const char __user *buf,
>fsi->bool_pending_names[index]))
>   goto out;
>  
> - length = -ENOMEM;
> - if (count >= PAGE_SIZE)
> - goto out;
> -
> - /* No partial writes. */
> - length = -EINVAL;
> - if (*ppos != 0)
> - goto out;
> -
> - page = memdup_user_nul(buf, count);
> - if (IS_ERR(page)) {
> - length = PTR_ERR(page);
> - page = NULL;
> - goto out;
> - }
> -
>   length = -EINVAL;
>   if (sscanf(page, "%d", _value) != 1)
>   goto out;
> @@ -1280,6 +1274,17 @@ static ssize_t s

Re: 'setsebool -P' works but throws errors; changes not permanent

2018-06-19 Thread Stephen Smalley
On 06/18/2018 04:33 PM, Mike Hughes wrote:
>> -Original Message-
>> From: Stephen Smalley 
>> Sent: Monday, June 18, 2018 15:28
>> To: Mike Hughes ; selinux@tycho.nsa.gov
>> Subject: Re: 'setsebool -P' works but throws errors; changes not permanent
>>
>> On 06/18/2018 03:44 PM, Mike Hughes wrote:
>>> We use Yubikey for two-factor ssh authentication which requires enabling a 
>>> Boolean
>> called “authlogin_yubikey”. It has been working fine until a few weeks ago. 
>> Errors appear
>> when attempting to set the policy:
>>>
>>>
>>>
>>> --
>>>
>>> [Cent-7:root@my_server home]# getsebool authlogin_yubikey
>>>
>>> authlogin_yubikey --> off
>>>
>>>
>>>
>>> [Cent-7:root@my_server home]# setsebool -P authlogin_yubikey on
>>>
>>> libsepol.context_from_record: type gpio_device_t is not defined
>>>
>>> libsepol.context_from_record: could not create context structure
>>>
>>> libsepol.context_from_string: could not create context structure
>>>
>>> libsepol.sepol_context_to_sid: could not convert 
>>> system_u:object_r:gpio_device_t:s0 to
>> sid
>>>
>>> invalid context system_u:object_r:gpio_device_t:s0
>>
>> Sounds like your policy is in an inconsistent internal state (somewhere you 
>> have a context
>> with gpio_device_t but the type isn't defined in the policy).
>>
>> What's your policy version?  And did it perhaps fail during %post when it 
>> was updated -
>> check yum.log?
> 
> Nothing stands out to me in yum.log

There would have been error messages during the update of the 
selinux-policy-targeted package.

You didn't mention your policy version.  On an updated CentOS 7 VM, I see:
$ rpm -q selinux-policy-targeted
selinux-policy-targeted-3.13.1-192.el7_5.3.noarch

And it has gpio_device_t defined:
$ seinfo -t | grep gpio_device_t
gpio_device_t

And this type is used in file_contexts:
$ semanage fcontext -l | grep gpio_device_t
/dev/gpiochip[0-9]+ character device
system_u:object_r:gpio_device_t:s0

> 
> 
>> Does semodule -B fail?
> 
> No, it completes without error:
> 
> --
> [Cent-7:root@my_server ~]# semodule -B
> [Cent-7:root@ my_server ~]# echo $?
> 0
> [Cent-7:root@ my_server ~]#
> --
>>
>> Might have to move aside your policy and reinstall it.
> 
> How might one accomplish this?

You could try first to just reinstall the package, e.g. yum reinstall 
selinux-policy-targeted.

If that doesn't resolve it, then export any local customizations you have and 
move aside your active policy store and try again, ala
semanage export -f exports
mv /etc/selinux/targeted/active /etc/selinux/targeted/active.old
yum reinstall selinux-policy-targeted

Then check that everything in the exports file is something you want to 
preserve, and if so, re-import it.
cat exports
semanage import -f exports

If that doesn't resolve it, you could move aside the entire policy tree and try 
again, ala
mv /etc/selinux/targeted /etc/selinux/targeted.old
yum reinstall selinux-policy-targeted

And then re-import your exports if desired/appropriate.

You may also have to re-insert any local policy modules you have defined; I 
don't think export/import handles modules, just other changes.

> 
>>>
>>> [Cent-7:root@my_server home]# getsebool authlogin_yubikey
>>>
>>> authlogin_yubikey --> on
>>>
>>> ---
>>>
>>>
>>>
>>> The system accepts two-factor while the above is set to “on”. After some 
>>> undetermined
>> time (or immediately after a reboot) the Boolean toggles off. This can be 
>> confirmed since
>> semanage shows that the default is still set to “off”:
>>>
>>>
>>>
>>> --
>>>
>>> [Cent-7:root@my_server ~]# semanage boolean -l | grep "authlogin_yubikey"
>>>
>>> SELinux boolean    State  Default Description
>>>
>>> ...
>>>
>>> authlogin_yubikey  (on   ,  off)  Allow authlogin to yubikey
>>>
>>> --
>>>
>>>
>>>
>>> It looks similar to the following bug on Fedora:
>>>
>>> https://bugzilla.redhat.com/show_bug.cgi?id=1559174
> 
> 
> ___
> Selinux mailing list
> Selinux@tycho.nsa.gov
> To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
> To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: 'setsebool -P' works but throws errors; changes not permanent

2018-06-18 Thread Stephen Smalley
On 06/18/2018 03:44 PM, Mike Hughes wrote:
> We use Yubikey for two-factor ssh authentication which requires enabling a 
> Boolean called “authlogin_yubikey”. It has been working fine until a few 
> weeks ago. Errors appear when attempting to set the policy:
> 
>  
> 
> --
> 
> [Cent-7:root@my_server home]# getsebool authlogin_yubikey
> 
> authlogin_yubikey --> off
> 
>  
> 
> [Cent-7:root@my_server home]# setsebool -P authlogin_yubikey on
> 
> libsepol.context_from_record: type gpio_device_t is not defined
> 
> libsepol.context_from_record: could not create context structure
> 
> libsepol.context_from_string: could not create context structure
> 
> libsepol.sepol_context_to_sid: could not convert 
> system_u:object_r:gpio_device_t:s0 to sid
> 
> invalid context system_u:object_r:gpio_device_t:s0

Sounds like your policy is in an inconsistent internal state (somewhere you 
have a context with gpio_device_t but the type isn't defined in the policy).

What's your policy version?  And did it perhaps fail during %post when it was 
updated - check yum.log?

Does semodule -B fail?

Might have to move aside your policy and reinstall it.

> 
>  
> 
> [Cent-7:root@my_server home]# getsebool authlogin_yubikey
> 
> authlogin_yubikey --> on
> 
> ---
> 
>  
> 
> The system accepts two-factor while the above is set to “on”. After some 
> undetermined time (or immediately after a reboot) the Boolean toggles off. 
> This can be confirmed since semanage shows that the default is still set to 
> “off”:
> 
>  
> 
> --
> 
> [Cent-7:root@my_server ~]# semanage boolean -l | grep "authlogin_yubikey"
> 
> SELinux boolean    State  Default Description
> 
> ...
> 
> authlogin_yubikey  (on   ,  off)  Allow authlogin to yubikey
> 
> --
> 
>  
> 
> It looks similar to the following bug on Fedora:
> 
> https://bugzilla.redhat.com/show_bug.cgi?id=1559174
> 
> 
> 
> ___
> Selinux mailing list
> Selinux@tycho.nsa.gov
> To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
> To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: is_selinux_enabled() after chroot()

2018-06-18 Thread Stephen Smalley
On 06/18/2018 03:24 PM, Petr Lautrbach wrote:
> Hello,
> 
> libselinux sets selinut_mnt and has_selinux_config only in its constructor and
> is_selinux_enabled() and others just use selinux_mnt to check if SELinux is
> enabled. But it doesn't work correctly when you use chroot() to a directory 
> without /proc
> and /sys/fs/selinux mounted as it was discovered in
> https://bugzilla.redhat.com/show_bug.cgi?id=1321375 
> 
> In this case, is_selinux_enabled() after chroot() returns true while in a new
> program run from chrooted process it returns false. It can be demonstrated by
> the steps below.
> 
> The solution could be to check if selinux_mnt still exists whenever a function
> depending on this is called. Would this be acceptable?

You want to call stat() or access(F_OK) on selinux_mnt and/or SELINUXCONFIG in 
is_selinux_enabled()?
Could potentially trigger a permission check that wasn't previously required, 
thereby breaking existing policies.
Caller might just be checking to see if SELinux is enabled before using 
interfaces other than selinuxfs (e.g. setexeccon, setfilecon, etc) and 
therefore didn't previously need permissions to selinuxfs or 
/etc/selinux/config.
So, possible but you'd need to make sure you don't break anything.  Definitely 
don't want that changed in Android.

> 
> 
> 
> 
> $ sudo dnf --nogpg --installroot=/var/lib/machines/example  install systemd
> 
> $ cat > test_libselinux.c < #include 
> #include 
> #include 
> #include 
> #include 
> 
> int main(int argc, char *argv[]) {
>   pid_t pid;
>   int wstatus;
> 
>   if (argc > 1) {
> printf("SELinux in chrooted process: %d\n", is_selinux_enabled());
> return 0;
>   }
>   if (chroot("/var/lib/machines/example") != 0)
> return -1;
> 
>   printf("SELinux in process after chroot(): %d\n", is_selinux_enabled());
>   printf("/sys/fs/selinux exists: %d\n", access("/sys/fs/selinux", F_OK));
>   printf("/etc/selinux/config exists: %d\n\n", access("/etc/selinux/config", 
> F_OK));
> 
>   if ((pid = fork()) == 0 ) {
> execv("./test_is_selinux_enabled", (char *[]){ 
> "./test_is_selinux_enabled", "chrooted", NULL});
>   }
> 
>   wait();
>   return 0;
> }
> EOF
> 
> $ gcc -o test_is_selinux_enabled test_libselinux.c -lselinux
> 
> $ sudo ./test_is_selinux_enabled
> SELinux in process after chroot(): 1
> /sys/fs/selinux exists: -1
> /etc/selinux/config exists: -1
> 
> SELinux in chrooted process: 0
> 
> 
> 
> ___
> Selinux mailing list
> Selinux@tycho.nsa.gov
> To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
> To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH 3/3] libsepol/cil: use a colon instead of a semicolon to report rc

2018-06-15 Thread Stephen Smalley
On 06/09/2018 03:30 PM, Nicolas Iooss wrote:
> Signed-off-by: Nicolas Iooss 

Thanks, applied all three.

> ---
>  libsepol/cil/src/cil_resolve_ast.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/libsepol/cil/src/cil_resolve_ast.c 
> b/libsepol/cil/src/cil_resolve_ast.c
> index 02259241ddfe..fb9d91745629 100644
> --- a/libsepol/cil/src/cil_resolve_ast.c
> +++ b/libsepol/cil/src/cil_resolve_ast.c
> @@ -2923,7 +2923,7 @@ int cil_resolve_call1(struct cil_tree_node *current, 
> void *extra_args)
>  
>   rc = cil_fill_ipaddr(pc->cl_head, 
> ipaddr);
>   if (rc != SEPOL_OK) {
> - cil_log(CIL_ERR, "Failed to 
> create anonymous ip address, rc; %d\n", rc);
> + cil_log(CIL_ERR, "Failed to 
> create anonymous ip address, rc: %d\n", rc);
>   cil_destroy_ipaddr(ipaddr);
>   goto exit;
>   }
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH 1/1] scripts: add a helper script to run clang's static analyzer

2018-06-15 Thread Stephen Smalley
On 06/09/2018 04:08 PM, Nicolas Iooss wrote:
> Using clang's static analyzer is as simple as running "scan-build make",
> but in order to obtain clean and reproducible results, the build
> environment has to be cleaned beforehand ("make clean distclean").
> 
> Moreover the project requires running "make install" before "make test"
> in order to install the dependencies needed for the tests, and running
> these tests with the newly-built libraries requires a specific
> LD_LIBRARY_PATH. This new script takes care of setting up everything
> which is needed.
> 
> Signed-off-by: Nicolas Iooss 

Thanks, applied.

> ---
>  scripts/.gitignore |  1 +
>  scripts/run-scan-build | 33 +
>  2 files changed, 34 insertions(+)
>  create mode 100644 scripts/.gitignore
>  create mode 100755 scripts/run-scan-build
> 
> diff --git a/scripts/.gitignore b/scripts/.gitignore
> new file mode 100644
> index ..54882b3b1507
> --- /dev/null
> +++ b/scripts/.gitignore
> @@ -0,0 +1 @@
> +/output-scan-build/
> diff --git a/scripts/run-scan-build b/scripts/run-scan-build
> new file mode 100755
> index ..8b24a4d04647
> --- /dev/null
> +++ b/scripts/run-scan-build
> @@ -0,0 +1,33 @@
> +#!/bin/sh
> +# Run clang's static analyzer (scan-build) and record its output in 
> output-scan-build/
> +
> +# Ensure the current directory is where this script is
> +cd "$(dirname -- "$0")" || exit $?
> +
> +OUTPUTDIR="$(pwd)/output-scan-build"
> +
> +# Display the commands which are run, and make sure they succeed
> +set -x -e
> +
> +# Use a temporary directory as an installation directory, if $DESTDIR is not 
> set
> +if [ -z "$DESTDIR" ] ; then
> +DESTDIR="$(mktemp --tmpdir -d scan-build-destdir-XX)"
> +fi
> +
> +# Make sure to use the newly-installed libraries when running tests
> +export LD_LIBRARY_PATH="$DESTDIR/usr/lib:$DESTDIR/lib"
> +export 
> PATH="$DESTDIR/usr/sbin:$DESTDIR/usr/bin:$DESTDIR/sbin:$DESTDIR/bin:$PATH"
> +export PYTHONPATH="$DESTDIR$(${PYTHON:-python} -c "from distutils.sysconfig 
> import *;print(get_python_lib(prefix='/usr'))")"
> +export RUBYLIB="$DESTDIR/$(${RUBY:-ruby} -e 'puts 
> RbConfig::CONFIG["vendorlibdir"]'):$DESTDIR/$(${RUBY:-ruby} -e 'puts 
> RbConfig::CONFIG["vendorarchdir"]')"
> +
> +# Build and analyze
> +make -C .. CC=clang clean distclean -j"$(nproc)"
> +scan-build -analyze-headers -o "$OUTPUTDIR" make -C .. CC=clang 
> DESTDIR="$DESTDIR" install install-pywrap install-rubywrap all test
> +
> +# Reduce the verbosity in order to keep the message from scan-build saying
> +# "scan-build: Run 'scan-view /.../output-scan-build/2018-...' to examine 
> bug reports.
> +set +x
> +
> +# Remove the destination directory without using "rm -rf"
> +chmod u+w "$DESTDIR/usr/bin/newrole"
> +rm -r "$DESTDIR"
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH 4/4] policycoreutils/hll/pp: remove unused variable

2018-06-06 Thread Stephen Smalley
On 06/03/2018 12:25 PM, Nicolas Iooss wrote:
> pp's main() never set outfd to anything else than -1 so there is no
> point in closing it.

Thanks, applied all four patches.

> 
> Signed-off-by: Nicolas Iooss 
> ---
>  policycoreutils/hll/pp/pp.c | 7 ---
>  1 file changed, 7 deletions(-)
> 
> diff --git a/policycoreutils/hll/pp/pp.c b/policycoreutils/hll/pp/pp.c
> index b97a9b34816a..98969eb2f5f3 100644
> --- a/policycoreutils/hll/pp/pp.c
> +++ b/policycoreutils/hll/pp/pp.c
> @@ -73,7 +73,6 @@ int main(int argc, char **argv)
>   const char *ofile = NULL;
>   FILE *in = NULL;
>   FILE *out = NULL;
> - int outfd = -1;
>  
>   // ignore sigpipe so we can check the return code of write, and 
> potentially
>   // return a more helpful error message
> @@ -159,12 +158,6 @@ exit:
>   if (out != NULL) {
>   fclose(out);
>   }
> - if (outfd != -1) {
> - close(outfd);
> - if (rc != 0) {
> - unlink(argv[2]);
> - }
> - }
>   sepol_module_package_free(mod_pkg);
>  
>   return rc;
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: BTRFS losing SE Linux labels on power failure or "reboot -nffd".

2018-06-04 Thread Stephen Smalley
On 06/01/2018 09:03 AM, Russell Coker via Selinux wrote:
> The command "reboot -nffd" (kernel reboot without flushing kernel buffers or 
> writing status) when run on a BTRFS system will often result in 
> /var/log/audit/audit.log being unlabeled. It also results in some 
> systemd-journald files like 
> /var/log/journal/c195779d29154ed8bcb4e8444c4a1728/system.journal being 
> unlabeled but that is rarer. I think that the same problem afflicts both 
> systemd-journald and auditd but it's a race condition that on my systems 
> (both production and test) is more likely to affect auditd.
> 
>  
> 
> If this issue just affected "reboot -nffd" then a solution might be to just 
> not run that command. However this affects systems after a power outage.
> 
>  
> 
> I have reproduced this bug with kernel 4.9.0-6-amd64 (the latest security 
> update for Debian/Stretch which is the latest supported release of Debian). I 
> have also reported it in an identical manner with kernel 4.16.0-1-amd64 (the 
> latest from Debian/Unstable). For testing I reproduced this with a 4G 
> filesystem in a VM, but in production it has happened on BTRFS RAID-1 arrays, 
> both SSD and HDD.
> 
>  
> 
> #!/bin/bash
> set -e
> COUNT=$(ps aux|grep [s]bin/auditd|wc -l)
> date
> if [ "$COUNT" = "1" ]; then
>  echo "all good"
> else
>  echo "failed"
>  exit 1
> fi
> 
> Firstly the above is the script /usr/local/sbin/testit, I test for auditd 
> running because it aborts if the context on it's log file is wrong.
> 
>  
> 
> root@stretch:~# ls -liZ /var/log/audit/audit.log
> 37952 -rw---. 1 root root system_u:object_r:auditd_log_t:s0 4385230 Jun  
> 1 12:23 /var/log/audit/audit.log
> 
> Above is before I do the tests.
> 
>  
> 
> while ssh stretch /usr/local/sbin/testit ; do
>  ssh btrfs-local "reboot -nffd" > /dev/null 2>&1 &
>  sleep 20
> done
> 
> Above is the shell code I run to do the tests. Note that the VM in question 
> runs on SSD storage which is why it can consistently boot in less than 20 
> seconds.
> 
>  
> 
> Fri  1 Jun 12:26:13 UTC 2018
> all good
> Fri  1 Jun 12:26:33 UTC 2018
> failed
> 
> Above is the output from the shell code in question. After the first reboot 
> it fails. The probability of failure on my test system is greater than 50%.
> 
>  
> 
> root@stretch:~# ls -liZ /var/log/audit/audit.log  
> 37952 -rw---. 1 root root system_u:object_r:unlabeled_t:s0 4396803 Jun  1 
> 12:26 /var/log/audit/audit.log
> 
> Now the result. Note that the Inode has not changed. I could understand a 
> newly created file missing an xattr, but this is an existing file which 
> shouldn't have had it's xattr changed. But somehow it gets corrupted.
> 
>  
> 
> Could this be the fault of SE Linux code? I don't think it's likely but this 
> is what the BTRFS developers will ask so it's best to discuss this here 
> before sending it to them.

No, that's definitely a filesystem bug.  It is the filesystem's responsibility 
to ensure that new inodes are assigned a security.* xattr in the same 
transaction as the file creation (ext[234] does this, for example, e.g. via 
ext4_init_security()), and that they don't lose them.  SELinux just provides 
the xattr suffix ("selinux") and the value/value_len pair.

> 
>  
> 
> Does anyone have any ideas of other tests I should run? Anyone want me to try 
> a different kernel? I can give root on a VM to anyone who wants to poke at 
> it. Anything else I should add when sending this to the BTRFS developers?

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH V3 0/5] selinux:Significant reduce of preempt_disable holds

2018-05-31 Thread Stephen Smalley
On 05/31/2018 10:21 AM, Stephen Smalley wrote:
> On 05/31/2018 10:12 AM, peter enderborg wrote:
>> On 05/31/2018 02:42 PM, Stephen Smalley wrote:
>>> On 05/31/2018 05:04 AM, peter enderborg wrote:
>>>> On 05/30/2018 10:34 PM, Stephen Smalley wrote:
>>>>> On 05/30/2018 10:10 AM, Peter Enderborg wrote:
>>>>>> The boolean change becomes a lot more heavy with this patch,
>>>>>> but it is a very rare usage in compare with read only operations.
>>>>>> The lock held during a policydb_copy is about 1ms on a XEON.
>>>>> This has a very substantial performance impact on setsebool, e.g. time 
>>>>> setsebool httpd_can_sendmail=1.
>>>>> That's because you are doing a full 
>>>>> vmalloc();policydb_write();policydb_read();vfree() sequence on it.
>>>>> In comparison, KaiGai's old attempt to replace the policy rwlock with RCU 
>>>>> only duplicated the conditional policydb state (via a cond_policydb_dup) 
>>>>> that he introduced.  Is there a reason you couldn't use that approach?
>>>> That one did not make it, so I went for a other path. Make it simple, 
>>>> using the same serialisation that exist. That also make it easier to 
>>>> maintain.
>>>> We do not  use the booleans in android since they are not allowed so im 
>>>> not aware of any use case where this administrative function are
>>>> used in such frequent manner that it would have an impact. And it must be 
>>>> some other large overhead with interprocess communication and
>>>> a multiple writes to sysfs during a boolean settings?  However my concern 
>>>> is/was memory pressure, setting booleans will generate pressure
>>>> with lot of atomic allocation and large vmallocs.
>>> Yes, that is also a concern.  I would prefer to only duplicate the 
>>> conditional policydb state as in KaiGai's patch.
>>> Keeping temporary setting of booleans lightweight is desirable for other 
>>> use cases than Android.
>>>
>>> I'm also concerned by the implications of switching all of the allocations 
>>> to atomic.  KaiGai's patch did not take that approach either, and it 
>>> obviously could make policy reload more prone to transient failures.
>>
>> On the version 2 of the patchset you pointed out that I did a shallow copy, 
>> so I did a "deap" copy. As I see it the KaiGai cond_policydb_dup also do a 
>> shallow copy.
> 
> In your earlier patch set, you just did a memcpy of the policydb and then 
> proceeded to mutate parts of the conditional policydb state, which would have 
> modified the original too.  KaiGai was performing a deep copy of the 
> conditional portions of the policydb I believe.
> 
>> You dont happend to know exactly why KaiGai's patch never was accepted?
> 
> As I recall, there wasn't anything wrong with the code itself; he just wasn't 
> satisfied that it ended up being a worthwhile tradeoff based on his own 
> performance testing.

His use case however was different - he was concerned with networking 
performance, and the introduction of the netnode/netport caches largely 
eliminated the policy rwlock as a concern there.

> 
>>
>>>  But my goal is the fast path for real time critical functions such as 
>>> audio, and it will be a cost for
>>>> administrative tasks. On the xeon it takes about ~98 ms to run the 
>>>> security_set_bools compared to about ~8 ms without the overhead
>>>> of copying the policydb.  About ~6 ms is rcu sync and ~8 ms is the same as 
>>>> the original update of selinux statuses, and about ~25 ms
>>>> is policydb_destroy() of the old copy.
>>>
>>>
>>>

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH V3 0/5] selinux:Significant reduce of preempt_disable holds

2018-05-31 Thread Stephen Smalley
On 05/31/2018 10:12 AM, peter enderborg wrote:
> On 05/31/2018 02:42 PM, Stephen Smalley wrote:
>> On 05/31/2018 05:04 AM, peter enderborg wrote:
>>> On 05/30/2018 10:34 PM, Stephen Smalley wrote:
>>>> On 05/30/2018 10:10 AM, Peter Enderborg wrote:
>>>>> The boolean change becomes a lot more heavy with this patch,
>>>>> but it is a very rare usage in compare with read only operations.
>>>>> The lock held during a policydb_copy is about 1ms on a XEON.
>>>> This has a very substantial performance impact on setsebool, e.g. time 
>>>> setsebool httpd_can_sendmail=1.
>>>> That's because you are doing a full 
>>>> vmalloc();policydb_write();policydb_read();vfree() sequence on it.
>>>> In comparison, KaiGai's old attempt to replace the policy rwlock with RCU 
>>>> only duplicated the conditional policydb state (via a cond_policydb_dup) 
>>>> that he introduced.  Is there a reason you couldn't use that approach?
>>> That one did not make it, so I went for a other path. Make it simple, using 
>>> the same serialisation that exist. That also make it easier to maintain.
>>> We do not  use the booleans in android since they are not allowed so im not 
>>> aware of any use case where this administrative function are
>>> used in such frequent manner that it would have an impact. And it must be 
>>> some other large overhead with interprocess communication and
>>> a multiple writes to sysfs during a boolean settings?  However my concern 
>>> is/was memory pressure, setting booleans will generate pressure
>>> with lot of atomic allocation and large vmallocs.
>> Yes, that is also a concern.  I would prefer to only duplicate the 
>> conditional policydb state as in KaiGai's patch.
>> Keeping temporary setting of booleans lightweight is desirable for other use 
>> cases than Android.
>>
>> I'm also concerned by the implications of switching all of the allocations 
>> to atomic.  KaiGai's patch did not take that approach either, and it 
>> obviously could make policy reload more prone to transient failures.
> 
> On the version 2 of the patchset you pointed out that I did a shallow copy, 
> so I did a "deap" copy. As I see it the KaiGai cond_policydb_dup also do a 
> shallow copy.

In your earlier patch set, you just did a memcpy of the policydb and then 
proceeded to mutate parts of the conditional policydb state, which would have 
modified the original too.  KaiGai was performing a deep copy of the 
conditional portions of the policydb I believe.

> You dont happend to know exactly why KaiGai's patch never was accepted?

As I recall, there wasn't anything wrong with the code itself; he just wasn't 
satisfied that it ended up being a worthwhile tradeoff based on his own 
performance testing.

> 
>>  But my goal is the fast path for real time critical functions such as 
>> audio, and it will be a cost for
>>> administrative tasks. On the xeon it takes about ~98 ms to run the 
>>> security_set_bools compared to about ~8 ms without the overhead
>>> of copying the policydb.  About ~6 ms is rcu sync and ~8 ms is the same as 
>>> the original update of selinux statuses, and about ~25 ms
>>> is policydb_destroy() of the old copy.
>>
>>
>>
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH V3 0/5] selinux:Significant reduce of preempt_disable holds

2018-05-31 Thread Stephen Smalley
On 05/31/2018 05:04 AM, peter enderborg wrote:
> On 05/30/2018 10:34 PM, Stephen Smalley wrote:
>> On 05/30/2018 10:10 AM, Peter Enderborg wrote:
>>> The boolean change becomes a lot more heavy with this patch,
>>> but it is a very rare usage in compare with read only operations.
>>> The lock held during a policydb_copy is about 1ms on a XEON.
>> This has a very substantial performance impact on setsebool, e.g. time 
>> setsebool httpd_can_sendmail=1.
>> That's because you are doing a full 
>> vmalloc();policydb_write();policydb_read();vfree() sequence on it.
>> In comparison, KaiGai's old attempt to replace the policy rwlock with RCU 
>> only duplicated the conditional policydb state (via a cond_policydb_dup) 
>> that he introduced.  Is there a reason you couldn't use that approach?
> That one did not make it, so I went for a other path. Make it simple, using 
> the same serialisation that exist. That also make it easier to maintain.
> We do not  use the booleans in android since they are not allowed so im not 
> aware of any use case where this administrative function are
> used in such frequent manner that it would have an impact. And it must be 
> some other large overhead with interprocess communication and
> a multiple writes to sysfs during a boolean settings?  However my concern 
> is/was memory pressure, setting booleans will generate pressure
> with lot of atomic allocation and large vmallocs.

Yes, that is also a concern.  I would prefer to only duplicate the conditional 
policydb state as in KaiGai's patch.
Keeping temporary setting of booleans lightweight is desirable for other use 
cases than Android.

I'm also concerned by the implications of switching all of the allocations to 
atomic.  KaiGai's patch did not take that approach either, and it obviously 
could make policy reload more prone to transient failures.

 But my goal is the fast path for real time critical functions such as audio, 
and it will be a cost for
> administrative tasks. On the xeon it takes about ~98 ms to run the 
> security_set_bools compared to about ~8 ms without the overhead
> of copying the policydb.  About ~6 ms is rcu sync and ~8 ms is the same as 
> the original update of selinux statuses, and about ~25 ms
> is policydb_destroy() of the old copy.
>>



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [PATCH V3 0/5] selinux:Significant reduce of preempt_disable holds

2018-05-30 Thread Stephen Smalley
On 05/30/2018 10:10 AM, Peter Enderborg wrote:
> Holding the preempt_disable is very bad for low latency tasks
> such as audio and therefore we need to break out the rule-set dependent
> part from this disable. By using a RCU instead of rwlock we
> have an efficient locking and less preemption interference.
> 
> Selinux uses a lot of read_locks. This patch replaces the rwlock
> with RCU that does not hold preempt_disable.
> 
> Intel Xeon W3520 2.67 Ghz running FC27 with 4.15.0-rc9git (+measurement)
> I get preempt_disable of about 1.2ms in security_compute_av().
> With the patch I get 960us as the longest security_compute_av()
> without preempt disabeld. There are very much noise in the measurement
> but it is not likely a degrade.
> 
> And the preempt_disable times is also very dependent on the selinux
> rule-set.
> 
> In security_get_user_sids() we have two nested for-loops and the
> inner part calls sittab_context_to_sid() that calls
> sidtab_search_context() that has a for loop() over a while() where
> the loops is dependent on the rules.
> 
> On the test system the average lookup time is 60us and does
> not change with the introduced RCU usage.
> 
> The boolean change becomes a lot more heavy with this patch,
> but it is a very rare usage in compare with read only operations.
> The lock held during a policydb_copy is about 1ms on a XEON.

This has a very substantial performance impact on setsebool, e.g. time 
setsebool httpd_can_sendmail=1.
That's because you are doing a full 
vmalloc();policydb_write();policydb_read();vfree() sequence on it.
In comparison, KaiGai's old attempt to replace the policy rwlock with RCU only 
duplicated the conditional policydb state (via a cond_policydb_dup) that he 
introduced.  Is there a reason you couldn't use that approach?

> 
> To use RCU the structure of policydb has to be accesses through a pointer.
> We need 5 patches to get there.
>  
> [PATCH V3 1/5 selinux-next] selinux: Make allocation atomic in policydb 
> objects functions.
> This patch change the allocation for policydb objects. They are in its own 
> patch
> to make the complicated part easier to read.
> 
> [PATCH V3 2/5 selinux-next] selinux: Introduce selinux_ruleset struct
> This makes the access for the rule evaluation going though a single pointer.
> 
> [PATCH V3 3/5 selinux-next] selinux: sidtab_clone switch to use rwlock.
> We need to make sidtabs copys so this patch change the locks to a rwlock
> and create a copy function.
> 
> [PATCH V3 4/5 selinux-next] selinux: seqno separation
> This patch adds separation of the read and write and uses
> the pointer to switch rule set. It uses seqno for error handling
> since there are a possibility to have multiple access.
> 
> [PATCH V3 5/5 selinux-next] selinux: Switch to rcu read locks for avc_compute
> All the preparation is done so this patch do the change of locks to rcu.
> 
> History:
> V1 rwsem
> V2 did not handle all policydb objects, solved with the policydb_copy
>did not handle sidtab for booleans, I think this one does however
>shutdown is not used but not removed. 
> 
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [PATCH] selinux: KASAN: slab-out-of-bounds in xattr_getsecurity

2018-05-30 Thread Stephen Smalley
On 05/30/2018 11:19 AM, Paul Moore wrote:
> On Fri, May 25, 2018 at 4:31 AM, Sachin Grover  wrote:
>> Call trace:
>>  [] dump_backtrace+0x0/0x428
>>  [] show_stack+0x28/0x38
>>  [] dump_stack+0xd4/0x124
>>  [] print_address_description+0x68/0x258
>>  [] kasan_report.part.2+0x228/0x2f0
>>  [] kasan_report+0x5c/0x70
>>  [] check_memory_region+0x12c/0x1c0
>>  [] memcpy+0x34/0x68
>>  [] xattr_getsecurity+0xe0/0x160
>>  [] vfs_getxattr+0xc8/0x120
>>  [] getxattr+0x100/0x2c8
>>  [] SyS_fgetxattr+0x64/0xa0
>>  [] el0_svc_naked+0x24/0x28
>>
>> If user get root access and calls security.selinux setxattr() with an
>> embedded NUL on a file and then if some process performs a getxattr()
>> on that file with a length greater than the actual length of the string,
>> it would result in a panic.
>>
>> To fix this, add the actual length of the string to the security context
>> instead of the length passed by the userspace process.
>>
>> Signed-off-by: Sachin Grover 
>> ---
>>  security/selinux/ss/services.c | 2 +-
>>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> Thanks for reporting this and providing a patch.  It's small enough,
> and passes all the regular tests, so I've merged it into
> selinux/stable-4.17 (adding the stable metadata) and I'm going to send
> it up to Linus today.
> 
> If Linus doesn't pull the fix in time for v4.17 I'll send it up during
> the upcoming merge window.

NB Such a setxattr() call can only be performed by a process with CAP_MAC_ADMIN 
that is also allowed mac_admin permission in SELinux policy. Consequently, this 
is never possible on Android (no process is allowed mac_admin permission, 
always enforcing) and is only possible in Fedora/RHEL for a few domains (if 
enforcing).

Fixes: 9a59daa03df72526d234b91dd3e32ded5aebd3ef ("SELinux: fix sleeping 
allocation in security_context_to_sid")

> 
>> diff --git a/security/selinux/ss/services.c b/security/selinux/ss/services.c
>> index 66ea81c..d17f5b4 100644
>> --- a/security/selinux/ss/services.c
>> +++ b/security/selinux/ss/services.c
>> @@ -1434,7 +1434,7 @@ static int security_context_to_sid_core(const char 
>> *scontext, u32 scontext_len,
>>   scontext_len, , def_sid);
>> if (rc == -EINVAL && force) {
>> context.str = str;
>> -   context.len = scontext_len;
>> +   context.len = strlen(str) + 1;
>> str = NULL;
>> } else if (rc)
>> goto out_unlock;
>> --
>> 1.9.1
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: fixfiles and load_policy moved from /sbin to /usr/sbin

2018-05-29 Thread Stephen Smalley
On 05/29/2018 02:28 PM, Stephen Smalley wrote:
> On 05/29/2018 11:19 AM, Laurent Bigonville wrote:
>> Hello,
>>
>> While packaging policycoreutils 2.8 I've seen that the fixfiles and 
>> load_policy executables were moved from /sbin to /usr/sbin
>>
>> Any reasons for this? This seems to me like an involuntary side effect of 
>> the cleanup for DESTDIR and PREFIX in the build system.
>>
>> For distribution with usr-merge that will not change anything, but for 
>> others that could prevent early boot scripts to load the policy
>>
>> Shouldn't that be reverted?
> 
> Yes, I think that was an oversight.  However, generally policy loading is 
> handled directly by init (both sysvinit and systemd) via libselinux w/o 
> executing the load_policy executable, and libsemanage checks both locations 
> for it, so I wouldn't expect policy loading to be broken.  fixfiles 
> invocation from init scripts may be a different matter.  Likely should revert 
> the location change for both (but not the rest of DESTDIR/PREFIX fixes).

I guess the change might break systems calling load_policy from dracut 
initramfs scripts to load policy instead of calling libselinux from init, e.g. 
RHEL 6.  I'm not sure though that any distro other than RHEL 6 ever did that.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: fixfiles and load_policy moved from /sbin to /usr/sbin

2018-05-29 Thread Stephen Smalley
On 05/29/2018 11:19 AM, Laurent Bigonville wrote:
> Hello,
> 
> While packaging policycoreutils 2.8 I've seen that the fixfiles and 
> load_policy executables were moved from /sbin to /usr/sbin
> 
> Any reasons for this? This seems to me like an involuntary side effect of the 
> cleanup for DESTDIR and PREFIX in the build system.
> 
> For distribution with usr-merge that will not change anything, but for others 
> that could prevent early boot scripts to load the policy
> 
> Shouldn't that be reverted?

Yes, I think that was an oversight.  However, generally policy loading is 
handled directly by init (both sysvinit and systemd) via libselinux w/o 
executing the load_policy executable, and libsemanage checks both locations for 
it, so I wouldn't expect policy loading to be broken.  fixfiles invocation from 
init scripts may be a different matter.  Likely should revert the location 
change for both (but not the rest of DESTDIR/PREFIX fixes).



___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Invalid security context while executing audit2alllow.orig

2018-05-29 Thread Stephen Smalley
On 05/29/2018 07:39 AM, bhawna goel wrote:
> Hi Team,
> 
> We are getting below error while creating policies using command 
> audit2allow.orig. Can you help in identifying what could be the possible 
> reason of such error.
> 
> Error:
> libsepol.context_from_record: invalid security context: 
> "specialuser_u:system_r:ssh_t:s0"
> libsepol.context_from_record: could not create context structure
> libsepol.context_from_string: could not create context structure
> libsepol.sepol_context_to_sid: could not convert 
> specialuser_u:system_r:ssh_t:s0 to sid

This means that a security context from the avc messages that you fed into 
audit2allow (or read from the audit logs) is not valid under the currently 
loaded policy, e.g. specialuser_u might not be defined or it might not be 
authorized for the system_r role.

This commonly happens when you take avc denials / audit logs from one system 
and try to apply audit2allow to them on a different system with a different 
policy, or if the denials occurred while a different policy was loaded.

You can specify a policy to audit2allow via -p and have it use that policy when 
decoding the security contexts.
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Selinux load_policy command on chrooted partition is loading policy on active partition

2018-05-25 Thread Stephen Smalley
On 05/25/2018 04:08 AM, bhawna goel wrote:
> Hi Team,
> 
> We are facing an issue with load_policy command on Centos 7.4.. Need to 
> understand what it exactly does.
> 
> We have Centos 7.4 machine which have two partitions .
> Ist partition (partA) have all the policies with unconfined and when we are 
> installing second partition (partB) we are adding all the policies for 
> sysadm. 
> During installation of partB below command is getting executed from partA
> chroot partB load_policy -qi.
> 
> Just after executing this command partA stops working with unconfined 
> policies . partA giving denials which was working before executing this 
> command.
> 
> Just to recover my system i executed load_policy -q in partA and it gets back 
> to normal.
> 
> I wanted to understand what exactly load_policy do . Why my partA stopped 
> working when load_policy is executed in partB .Is this expected behavior or 
> there is some issue.
> 
> Thanks in advance.

I thought I answered this yesterday, but let's try again: load_policy always 
loads the active policy as defined by /etc/selinux/config relative to its root. 
So if you perform a chroot /path/to/partB load_policy it will load the policy 
from /path/to/partB/etc/selinux into the kernel.  And then your partA will stop 
working.  There is only one kernel policy; it isn't relative to any particular 
root.  Don't load policy from partB unless you are actually booting from partB.
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

ANN: SELinux userspace release 20180524 / 2.8

2018-05-24 Thread Stephen Smalley
The 20180524 / 2.8 release for the SELinux userspace is now available at:
https://github.com/SELinuxProject/selinux/wiki/Releases

A github release has also been created at:
https://github.com/SELinuxProject/selinux/releases/tag/20180524

In the future, we will likely stop hosting the releases on the wiki and
just have it link to the github releases.  We may also alter the versioning
and tagging scheme. For this release however, I have left these unchanged.

Below are some notes on this release for packagers and users of the
SELinux userspace.  git log and git shortlog output for all changes
since the 20170804 / 2.7 release are available from the release page. 

Thanks to all the contributors to this release!

RELEASE 20180524 (2.8)

User-visible changes:

* semanage fcontext -l now also lists home directory entries from
file_contexts.homedirs.

* semodule can now enable or disable multiple modules in the same
operation by specifying a list of modules after -e or -d, making them
consistent with the -i/u/r/E options.

* CIL now supports multiple declarations of types, attributes, and
(non-conflicting) object contexts (e.g. genfscon), enabled via the -m
or --multiple-decls option to secilc.

* libsemanage no longer deletes the tmp directory if there is an error
while committing the policy transaction, so that any temporary files
can be further inspected for debugging purposes (e.g. to examine a
particular line of the generated CIL module).  The tmp directory will
be deleted upon the next transaction, so no manual removal is needed.

* Support was added for SCTP portcon statements. The corresponding
kernel support was introduced in Linux 4.17, and is only active if the
extended_socket_class policy capability is enabled in the policy.  This
support is required to build the refpolicy master branch (and thus future
refpolicy releases).

* sepol_polcap_getnum/name() were exported as part of the shared libsepol
interface, initially for use by setools4.

* semodule_deps was removed since it has long been broken and is not useful
for CIL modules.

Packaging-relevant changes:

* When overriding PREFIX, BINDIR, SBINDIR, SHLIBDIR, LIBEXECDIR, etc.,
DESTDIR has to be removed from the definition. For example on Arch
Linux, SBINDIR="${pkgdir}/usr/bin" was changed to SBINDIR="/usr/bin".

* Defining variable LIBSEPOLA (to /usr/lib/libsepol.a, for example) is
no longer mandatory (thanks to the switch to "-l:libsepol.a" in
Makefiles).

* PYSITEDIR has been renamed PYTHONLIBDIR (and its definition changed).

* selinux-gui (i.e. system-config-selinux GUI application) is now
compatible with Python 3. Doing this required migrating away from
PyGTK to the supported PyGI library. This means that selinux-gui now
depends on python-gobject, Gtk+ 3 and selinux-python. It no longer
requires PyGtk or Python 2.
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: Selinux load_policy command on inactive partition is loading policy on active partition

2018-05-24 Thread Stephen Smalley
On 05/24/2018 01:48 AM, shagun maheshwari wrote:
> Hi,
> 
> We have done changes in our Centos7.4 to disable the unconfined user from our 
> code. We have created an iso in which we have replaced unconfined with sysadm 
> and we are performing an upgrade using the new iso. 
> After upgrade current partition stop working. It started expecting policies 
> for unconfined when we perform reboot things started working fine again. 
> We are suspecting some issues with this command "load_policy -qi" when this 
> command is being executed on partB in permissive mode and after we move the 
> system to enforcing mode. It starts giving denials for unconfined. 
> 
> Can you explain what exactly load_policy do? 
> Does it load the policies for all the partitions of the system?

load_policy always loads the active system policy as defined by 
/etc/selinux/config.  If you want it to load a policy from another partition 
you need to run it under chroot or a filesystem namespace such that it uses 
/etc/selinux from the other partition.  It only loads one policy though, not 
multiple.

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: [Bug][KASAN] crash in xattr_getsecurity()

2018-05-24 Thread Stephen Smalley
On 05/24/2018 02:12 AM, Sachin Grover wrote:
> Hi,
> 
> Kernel panic is coming on calling lgetxattr() sys api with random user space 
> value.
> 
> [   25.833951] Call trace:
> [   25.833954] [] dump_backtrace+0x0/0x2a8
> [   25.833957] [] show_stack+0x20/0x28
> [   25.833959] [] dump_stack+0xa8/0xe0
> [   25.833962] [] xattr_getsecurity+0xac/0xd4
> [   25.833964] [] vfs_getxattr+0x98/0xcc
> [   25.833966] [] getxattr+0x9c/0x1d4
> [   25.833969] [] path_getxattr+0x74/0xc4
> [   25.833971] [] SyS_lgetxattr+0x3c/0x48
> [   25.833973] [] el0_svc_naked+0x24/0x28
> 
> setxattr() is getting size and value from the userspace, if I am giving size 
> as 64840, my code is entering this part and crashing on doing memcpy under  
> xattr_getsecurity().
> 
> rc  = 
> string_to_context_struct(, , scontext2,
> scontext_len 
> ,
>   
> , 
> def_sid 
> );
>   *if* (rc 
>  == 
> -EINVAL 
>  && 
> force 
> ) {
>   context 
> .str
>  = str;
>   context 
> .len
>   = 
> scontext_len 
> ;
>   str = NULL 
> ;
> 
> 
> 
> //rc value is coming as EINVAL(-22). In pass case rc value is always 0.
> 
> 
> Please let me know if this fix is good enough.
> 
> 
> rc  = 
> string_to_context_struct(, , scontext2,
> scontext_len 
> ,
>   
> , 
> def_sid 
> );
>   *if* (rc 
>  == 
> -EINVAL 
>  && 
> force 
> ) {
>   context 
> .str
>  = str;
> -  context 
> .len
>   = 
> scontext_len 
> ;
> 
> +  context.len = strlen(str);
> 
>   str = NULL 
> ;

IIUC, this is only possible if a process with CAP_MAC_ADMIN and that is allowed 
mac_admin permission in SELinux policy (or if SELinux is permissive) sets a 
security.selinux xattr with an embedded NUL on a file and then it or any other 
process performs a getxattr() on that file with a length greater than the 
length of the string up to the embedded NUL.  Is that accurate?  If so, then 
this is never possible on Android (no process is allowed mac_admin permission 
and SELinux is always enforcing) and is only possible in Fedora/RHEL for a few 
specific root/CAP_MAC_ADMIN processes in specific SELinux domains (sesearch -A 
-p mac_admin) if SELinux is enforcing or any root/CAP_MAC_ADMIN process if 
SELinux is permissive.  Regardless, not exploitable without CAP_MAC_ADMIN.  
Also possible with a crafted filesystem image that already contains such an 
xattr.

Generally we include the terminating NUL in the length, so context.len would be 
strlen(str)+1.  Otherwise, I think your fix is reasonable.  I think this bug 
goes back to 9a59daa03df72526d234b91dd3e32ded5aebd3ef ("SELinux: fix sleeping 
allocation in security_context_to_sid").
___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.

Re: ANN: SELinux userspace 2.8-rc3 release candidate

2018-05-23 Thread Stephen Smalley
On 05/16/2018 01:31 PM, Jason Zaman wrote:
> Just a quick note in case the release is soon.
> I have a couple patches to make everything work on
> Musl libc that im gonna clean them up and post in the morning.

Given that these have been merged and I've seen no other activity, I assume we 
can make a final 2.8 release anytime.
If anyone objects, speak up now.

> 
> On Thu, May 10, 2018 at 11:20:01AM -0400, Stephen Smalley wrote:
>> A 2.8-rc3 release candidate for the SELinux userspace is now available at:
>> https://github.com/SELinuxProject/selinux/wiki/Releases
>>
>> Please give it a test and let us know if there are any issues.
>>
>> A draft of the release notes is available from the Releases page, as
>> is the full git log output and git shortlog output since the 2.7
>> release.  If there are further items we should mention or if something
>> should be amended in the release notes, let us know.
>>  
>> Thanks to all the contributors to this release candidate!
>>  
>> A shortlog of changes since the 2.8-rc2 release candidate is below.
>>
>> Stephen Smalley (7):
>>   libsepol: remove unused function and type
>>   libselinux: fix build warning in save_booleans()
>>   libselinux: avcstat: fix build warning
>>   libselinux: audit2why: fix build warnings
>>   libsemanage: prevent string overflow on final paths
>>   libsepol: cil: prevent stack buffer overflow in cil_expr_to_string
>>   Update VERSION files to 2.8-rc3
>>
>> Vit Mojzis (1):
>>   python/semanage/seobject.py: Fix undefined store check
> 
> 

___
Selinux mailing list
Selinux@tycho.nsa.gov
To unsubscribe, send email to selinux-le...@tycho.nsa.gov.
To get help, send an email containing "help" to selinux-requ...@tycho.nsa.gov.


Re: [RFC V4 PATCH 1/1] selinux-testsuite: Add binder tests

2018-05-22 Thread Stephen Smalley
On 05/22/2018 07:37 AM, Richard Haines wrote:
> Add binder tests. See tests/binder/test_binder.c for details on
> message flows to test security_binder*() functions.
> 
> Signed-off-by: Richard Haines <richard_c_hai...@btinternet.com>

Passes for me with 4.17-rc5 on F28 and properly skipped on earlier Fedora/RHEL.

Acked-by: Stephen Smalley <s...@tycho.nsa.gov>

> ---
>  README.md   |   8 +
>  defconfig   |   7 +
>  policy/Makefile |   4 +
>  policy/test_binder.te   | 120 +++
>  tests/Makefile  |   5 +
>  tests/binder/Makefile   |   7 +
>  tests/binder/check_binder.c |  80 +
>  tests/binder/test   |  89 +
>  tests/binder/test_binder.c  | 684 
>  9 files changed, 1004 insertions(+)
>  create mode 100644 policy/test_binder.te
>  create mode 100644 tests/binder/Makefile
>  create mode 100644 tests/binder/check_binder.c
>  create mode 100644 tests/binder/test
>  create mode 100644 tests/binder/test_binder.c
> 
> diff --git a/README.md b/README.md
> index c9f3b2b..60a249e 100644
> --- a/README.md
> +++ b/README.md
> @@ -141,6 +141,14 @@ directory or you can follow these broken-out steps:
>  The broken-out steps allow you to run the tests multiple times without
>  loading policy each time.
>  
> +Note that if leaving the test policy in-place for further testing, the
> +policy build process changes a boolean:
> +   On policy load:   setsebool allow_domain_fd_use=0
> +   On policy unload: setsebool allow_domain_fd_use=1
> +The consequence of this is that after a system reboot, the boolean
> +defaults to true. Therefore if running the fdreceive or binder tests,
> +reset the boolean to false, otherwise some tests will fail.
> +
>  4) Review the test results.
>  
>  As each test script is run, the name of the script will be displayed followed
> diff --git a/defconfig b/defconfig
> index 7dce8bc..c48d3cc 100644
> --- a/defconfig
> +++ b/defconfig
> @@ -51,3 +51,10 @@ CONFIG_CRYPTO_USER=m
>  # This is enabled to test overlayfs SELinux integration.
>  # It is not required for SELinux operation itself.
>  CONFIG_OVERLAY_FS=m
> +
> +# Android binder implementations.
> +# These are enabled to test the binder controls in
> +# tests/binder; they are not required for SELinux operation itself.
> +CONFIG_ANDROID=y
> +CONFIG_ANDROID_BINDER_DEVICES="binder"
> +CONFIG_ANDROID_BINDER_IPC=y
> diff --git a/policy/Makefile b/policy/Makefile
> index 5e07ee2..15e3a0c 100644
> --- a/policy/Makefile
> +++ b/policy/Makefile
> @@ -63,6 +63,10 @@ ifeq ($(shell grep -q nnp_transition 
> $(POLDEV)/include/support/all_perms.spt &&
>  export M4PARAM += -Dnnp_nosuid_transition_permission_defined
>  endif
>  
> +ifeq ($(shell grep -q binder $(POLDEV)/include/support/all_perms.spt && echo 
> true),true)
> +TARGETS += test_binder.te
> +endif
> +
>  ifeq (x$(DISTRO),$(filter x$(DISTRO),xRHEL4 xRHEL5 xRHEL6))
>  TARGETS:=$(filter-out test_overlayfs.te test_mqueue.te, $(TARGETS))
>  endif
> diff --git a/policy/test_binder.te b/policy/test_binder.te
> new file mode 100644
> index 000..0589396
> --- /dev/null
> +++ b/policy/test_binder.te
> @@ -0,0 +1,120 @@
> +
> +attribute binderdomain;
> +
> +#
> +## Manager 
> ###
> +#
> +type test_binder_mgr_t;
> +domain_type(test_binder_mgr_t)
> +unconfined_runs_test(test_binder_mgr_t)
> +typeattribute test_binder_mgr_t testdomain;
> +typeattribute test_binder_mgr_t binderdomain;
> +allow test_binder_mgr_t self:binder { set_context_mgr call };
> +allow test_binder_mgr_t test_binder_provider_t:binder call;
> +allow test_binder_mgr_t device_t:chr_file { ioctl open read write };
> +allow_map(test_binder_mgr_t, device_t, chr_file)
> +allow test_binder_mgr_t self:capability { sys_nice };
> +allow test_binder_provider_t test_binder_mgr_t:fd use;
> +fs_getattr_tmpfs(test_binder_mgr_t)
> +allow test_binder_mgr_t tmpfs_t:file { read write open };
> +allow_map(test_binder_mgr_t, tmpfs_t, file)
> +fs_manage_tmpfs_dirs(test_binder_mgr_t)
> +fs_manage_tmpfs_files(test_binder_mgr_t)
> +
> +#
> +## Manager no fd {use} 
> ###
> +#
> +type test_binder_mgr_no_fd_t;
> +domain_type(test_binder_mgr_no_fd_t)
> +unconfined_runs_test(test_binder_mgr_no_fd_t)
> +typeattribute test_binder_mgr_no_fd_t testdomain;
> +typeattribute test_binder_mgr_no_fd_t binderdomain;
> +allow test_binder_mgr_no_fd_t self:binder { set_context_mgr call };
> +allow test_binder_mgr_no_fd_t test_binder_provider_t:binder { call };
> +allow test_bi

Re: [RFC V4 PATCH 0/1] selinux-testsuite: Add binder tests

2018-05-22 Thread Stephen Smalley
On 05/22/2018 09:53 AM, Stephen Smalley wrote:
> On 05/22/2018 09:11 AM, Stephen Smalley wrote:
>> On 05/22/2018 09:01 AM, Stephen Smalley wrote:
>>> On 05/22/2018 07:37 AM, Richard Haines wrote:
>>>> Could you try this version where I've packed the transaction structures.
>>>> I could not get the tests to fail on my two systems (but then V3 didn't).
>>>
>>> Hmmm...I saw one instance of a failure in test 6 when running ./test by
>>> hand but am now having problems replicating it.
>>>
>>> dmesg output during all 6 tests was:
>>>
>>> [  263.831513] binder: release 2025:2025 transaction 2 out, still active
>>> [  263.831519] binder: 2024:2024 transaction failed 29189/0, size 24-8 line 
>>> 2788
>>> [  263.831522] binder: send failed reply for transaction 2, target dead
>>> [  263.846321] binder: 2026:2026 transaction failed 29201/-1, size 24-8 
>>> line 2864
>>> [  263.858613] binder: 2024:2027 transaction failed 29201/-1, size 0-0 line 
>>> 2864
>>> [  263.872764] binder: 2028:2028 transaction failed 29201/-1, size 24-8 
>>> line 3050
>>> [  263.883684] binder: 2029:2029 ioctl 40046207 0 returned -13
>>> [  263.895261] binder: 2030 RLIMIT_NICE not set
>>> [  264.151699] binder: 2030 RLIMIT_NICE not set
>>> [  264.151879] binder: 2030 RLIMIT_NICE not set
>>> [  264.152212] binder: undelivered transaction 19, process died.
>>> [  264.152219] binder: 2030 RLIMIT_NICE not set
>>> [  264.153438] binder: 2030 RLIMIT_NICE not set
>>>
>>> Are all of those expected?
>>
>> Now it is repeating upon a fresh reboot and running ./test by hand 
>> repeatedly.
>> Also seeing these errors:
>> [  176.467915] binder_alloc: 1998: binder_alloc_buf, no vma
>> [  176.468046] binder: undelivered TRANSACTION_ERROR: 29189
>>
>> Running it via make test passes though, oddly enough.
>>
>> This is with completely stock 4.17-rc5 on F28.
> 
> ./test -v reports the following for test 6:
> Manager PID: 1949 Process context:
>   unconfined_u:unconfined_r:test_binder_mgr_no_fd_t:s0-s0:c0.c1023
> Service Provider PID: 1950 Process context:
>   unconfined_u:unconfined_r:test_binder_provider_t:s0-s0:c0.c1023
> Service Provider sending transaction to Manager - ADD_TEST_SERVICE
> Service Provider read_consumed: 48
> Service Provider command: BR_NOOP
> Service Provider command: BR_INCREFS
> Service Provider command: BR_ACQUIRE
> Service Provider command: BR_TRANSACTION_COMPLETE
> Manager read_consumed: 72
> Manager command: BR_NOOP
> Manager command: BR_TRANSACTION
> Manager BR_TRANSACTION data:
>   handle: 0
>   cookie: 0
>   code: 100
>   flag: TF_ACCEPT_FDS
>   sender pid: 1950
>   sender euid: 0
>   data_size: 24
>   offsets_size: 8
>   hdr: BINDER_TYPE_HANDLE
>   handle: 1
>   flags: priority: 0x7f accept FDS: YES
>   cookie: 0
> Manager has BINDER_TYPE_HANDLE obj->handle: 1
> Manager acquired handle: 1 for Service Provider
> Manager sending BC_REPLY to obtain its FD
> Manager handle: 0 and its FD: 3
> Manager read_consumed: 8
> Manager command: BR_NOOP
> Manager command: BR_TRANSACTION_COMPLETE
> Service Provider read_consumed: 72
> Service Provider command: BR_NOOP
> Service Provider command: BR_REPLY
> Service Provider BR_REPLY data:
>   handle: 0
>   cookie: 0
>   code: 100
>   flag: TF_ACCEPT_FDS
>   sender pid: 0
>   sender euid: 0
>   data_size: 24
>   offsets_size: 8
>   hdr: BINDER_TYPE_FD
>   fd: 5
>   flags: priority: 0x7f accept FDS: YES
>   cookie: 0
> Service Provider retrieved Managers fd: 5 st_dev: 6
> Service Provider read_consumed: 8
> Service Provider command: BR_NOOP
> Service Provider command: BR_TRANSACTION_COMPLETE
> Service Provider using Managers FD
> Manager read_consumed: 4
> Manager command: BR_NOOP
> not ok 6
> #   Failed test at ./test line 84.
> # Looks like you failed 1 test of 6.

Never mind, bug in user, forgot to setsebool domain_fd_use=off before running 
after a reboot (or
re-running make -C policy load).

Test passes for me now.




  1   2   3   4   5   6   7   8   9   10   >