Skip to contentSkip to conversation

Problem with 9ba09998baa9 ("selinux: Implement the watch_key security hook") in linux-next

PATCH In review Paul Moore 6 participants 35 messages Apr 17, 2020 – May 15, 2020

Subsystems (4)
lore
Share & tools
lore

Paul Moore

author maintainer Acked-by Stephen Smalley
#0 lore raw

I just notice that the "selinux: Implement the watch_key security hook" patch made it's way into linux-next via 9ba09998baa9:

commit 9ba09998baa995518d94c9a32e6329b28ccb9045
Author: David Howells <[email protected]>
Date: Tue Jan 14 17:07:13 2020 +0000

selinux: Implement the watch_key security hook

Implement the watch_key security hook to make sure that a key grants the caller View permission in order to set a watch on a key.

For the moment, the watch_devices security hook is left unimplemented as it's not obvious what the object should be since the queue is global and didn't previously exist.

I'm reasonably confident that this code hasn't been tested as I expect it would fail, or at the very least behave in unintended ways. The problem is the selinux_watch_key(...) function, shown below:

+static int selinux_watch_key(struct key *key)
+{
+ struct key_security_struct *ksec = key->security;
+ u32 sid = current_sid();
+
+ return avc_has_perm(&selinux_state,
+ sid, ksec->sid, SECCLASS_KEY, KEY_NEED_VIEW, NULL);
+}

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux permission and would likely result in odd behavior when passed to avc_has_perm(). Given that the keyring permission to SELinux object class permission is variable depending on the key_perms policy capability, it probably makes the most sense to pull the permission mapping in selinux_key_permission() out into a separate function, e.g. key_perm_to_av(...) (see the other XXX_to_av() functions in security/selinux/hooks.c), and then use this newly created mapping function in both selinux_key_permission() and selinux_watch_key(). Or you could just duplicate the KEY_NEED_VIEW mapping code in both functions, but I would advise against that.

Signature · 2 lines
paul moore
www.paul-moore.com
#1 lore raw
Quoted 19 lines · Paul Moore

I just notice that the "selinux: Implement the watch_key security hook" patch made it's way into linux-next via 9ba09998baa9:

commit 9ba09998baa995518d94c9a32e6329b28ccb9045
Author: David Howells <[email protected]>
Date: Tue Jan 14 17:07:13 2020 +0000

selinux: Implement the watch_key security hook

Implement the watch_key security hook to make sure that a key
grants the
caller View permission in order to set a watch on a key.

For the moment, the watch_devices security hook is left
unimplemented as
it's not obvious what the object should be since the queue is
global and
didn't previously exist.

Quoted 7 lines

I'm reasonably confident that this code hasn't been tested as I expect
it would fail, or at the very least behave in unintended ways. The problem is the selinux_watch_key(...) function, shown below:

I built an selinx-testsuite test for this last year and it worked fine then. I'll send the test as an RFC patch as its been some time since I ran it. David also has a test in kernel samples/watch_queue/watch_test.c

Quoted 11 lines
(quoted diff) +7 -0
+static int selinux_watch_key(struct key *key)
+{
+       struct key_security_struct *ksec = key->security;
+       u32 sid = current_sid();
+
+       return avc_has_perm(&selinux_state,
+                           sid, ksec->sid, SECCLASS_KEY,

KEY_NEED_VIEW, NULL);
+}

Quoted 2 lines

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux

True, however by magic the KEY_NEED_* perms match with the bits defined in classmap.h. I did some work on this during the 'keys' saga, see various emails in list like [1]

[1]
https://lore.kernel.org/selinux/[email protected]/

Quoted 13 lines

permission and would likely result in odd behavior when passed to avc_has_perm(). Given that the keyring permission to SELinux object class permission is variable depending on the key_perms policy capability, it probably makes the most sense to pull the permission mapping in selinux_key_permission() out into a separate function, e.g.
key_perm_to_av(...) (see the other XXX_to_av() functions in security/selinux/hooks.c), and then use this newly created mapping function in both selinux_key_permission() and selinux_watch_key(). Or
you could just duplicate the KEY_NEED_VIEW mapping code in both functions, but I would advise against that.

author maintainer
#2 lore raw
Quoted 28 lines · Richard Haines
Quoted 19 lines · Paul Moore

I just notice that the "selinux: Implement the watch_key security hook" patch made it's way into linux-next via 9ba09998baa9:

commit 9ba09998baa995518d94c9a32e6329b28ccb9045
Author: David Howells <[email protected]>
Date: Tue Jan 14 17:07:13 2020 +0000

selinux: Implement the watch_key security hook

Implement the watch_key security hook to make sure that a key
grants the
caller View permission in order to set a watch on a key.

For the moment, the watch_devices security hook is left
unimplemented as
it's not obvious what the object should be since the queue is
global and
didn't previously exist.

Quoted 7 lines

I'm reasonably confident that this code hasn't been tested as I expect
it would fail, or at the very least behave in unintended ways. The problem is the selinux_watch_key(...) function, shown below:

Quoted 4 lines

I built an selinx-testsuite test for this last year and it worked fine then. I'll send the test as an RFC patch as its been some time since I ran it. David also has a test in kernel samples/watch_queue/watch_test.c

See below.

Quoted 17 lines
Quoted 10 lines
(quoted diff) +7 -0
+static int selinux_watch_key(struct key *key)
+{
+       struct key_security_struct *ksec = key->security;
+       u32 sid = current_sid();
+
+       return avc_has_perm(&selinux_state,
+                           sid, ksec->sid, SECCLASS_KEY,

KEY_NEED_VIEW, NULL);
+}

Quoted 2 lines

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux

True, however by magic the KEY_NEED_* perms match with the bits defined in classmap.h. I did some work on this during the 'keys' saga, see various emails in list like [1]

Quoted 2 lines

[1]
https://lore.kernel.org/selinux/[email protected]/

Esh, relying on the constants to line up is a recipe for disaster. We really need that permission translation layer.

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#3 lore raw
In reply to Paul Moore
Quoted 4 lines · Paul Moore

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux permission and would likely result in odd behavior when passed to avc_has_perm().

I think it works because KEY_NEED_VIEW happens to coincide with KEY__VIEW. It should just use KEY__VIEW instead.

Quoted 3 lines

it probably makes the most sense to pull the permission mapping in selinux_key_permission() out into a separate function, e.g. key_perm_to_av(...)

Agreed. How about the attached patch? I wonder if I should do bit-by-bit translation rather than using a switch? But then it's difficult to decide what it means if someone passes in two KEY_NEED_* flags OR'd together - is it either or both?

Quoted 2 lines

and then use this newly created mapping function in [...] selinux_watch_key()

No, I think I should just hard-code KEY__VIEW there.

David
---
commit 70d1d82aa014ae4511976b4d80c17138006dddec

Author: David Howells <[email protected]>
Date:   Tue Apr 21 13:15:16 2020 +0100

selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
security/selinux/hooks.c +17 -1
index 0b4e32161b77..32f7fa538c5f 100644
@@ -6539,12 +6539,27 @@ static void selinux_key_free(struct key *k)
 	kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+	switch (need_perm) {
+	case KEY_NEED_VIEW:	return KEY__VIEW;
+	case KEY_NEED_READ:	return KEY__READ;
+	case KEY_NEED_WRITE:	return KEY__WRITE;
+	case KEY_NEED_SEARCH:	return KEY__SEARCH;
+	case KEY_NEED_LINK:	return KEY__LINK;
+	case KEY_NEED_SETATTR:	return KEY__SETATTR;
+	default:
+		return 0;
+	}
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  unsigned need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
+	unsigned int perm;
 	u32 sid;
 
 	/* if no specific permissions are requested, we skip the
@@ -6553,6 +6568,7 @@ static int selinux_key_permission(key_ref_t key_ref,
 	if (perm == 0)
 		return 0;
 
+	perm = selinux_keyperm_to_av(need_perm);
 	sid = cred_sid(cred);
 
 	key = key_ref_to_ptr(key_ref);
author maintainer
#4 lore raw
Quoted 9 lines · David Howells
Quoted 4 lines · Paul Moore

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux permission and would likely result in odd behavior when passed to avc_has_perm().

I think it works because KEY_NEED_VIEW happens to coincide with KEY__VIEW. It should just use KEY__VIEW instead.

Yes, it looks like it. To be clear, it is dangerous to rely on permission values from outside SELinux aligning with SELinux permissions; changing the outside permission values w/o adjusting the SELinux hook code to do the necessary translation will result in some scary behavior (wrong permission checks).

Quoted 8 lines
Quoted 3 lines

it probably makes the most sense to pull the permission mapping in selinux_key_permission() out into a separate function, e.g. key_perm_to_av(...)

Agreed. How about the attached patch? I wonder if I should do bit-by-bit translation rather than using a switch? But then it's difficult to decide what it means if someone passes in two KEY_NEED_* flags OR'd together - is it either or both?

Comments inline.

Quoted 4 lines
Quoted 2 lines

and then use this newly created mapping function in [...] selinux_watch_key()

No, I think I should just hard-code KEY__VIEW there.

FWIW, my comment was based on a version of linux-next where you were making policycap based permission adjustments to KEY_VIEW and I thought you would want the same adjustments to be applied to both access control points. That code appears to now be gone in linux-next.

Quoted 25 lines

---
commit 70d1d82aa014ae4511976b4d80c17138006dddec

Author: David Howells <[email protected]>
Date:   Tue Apr 21 13:15:16 2020 +0100

selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
security/selinux/hooks.c +2 -0
index 0b4e32161b77..32f7fa538c5f 100644
@@ -6539,12 +6539,27 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6553

Quoted 10 lines
security/selinux/hooks.c +10 -0
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:
+               return 0;
+       }

Regarding your question of permission translation via switch-statement as opposed to bit-by-bit comparison, I think it depends on if multiple permissions are going to be required in a single call to the hook. The failure mode for the code above if multiple permissions are requested is not very good, it defaults to *no* permission which means that if someone requested KEY_NEED_SEARCH|KEY_NEED_VIEW (or some other combination) then the SELinux check would not check any permissions ... that seems wrong to me.

If we want to stick with a switch statement I think we should have it return -EPERM for the default case to protect against this. We don't need the full 32-bits afforded us by the unsigned int.

Quoted 14 lines
security/selinux/hooks.c +4 -1
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 
        /* if no specific permissions are requested, we skip the

security/selinux/hooks.c static int selinux_key_permission(key_ref_t key_ref, · line 6571

Quoted 4 lines
security/selinux/hooks.c +1 -0
@@ -6553,6 +6568,7 @@ static int selinux_key_permission(key_ref_t key_ref,
        if (perm = 0)
                return 0;
 
+       perm = selinux_keyperm_to_av(need_perm);

... and add a check for (perm < 0) as discussed above if we stick with the switch statement.

Quoted 4 lines
security/selinux/hooks.c +0 -0
        sid = cred_sid(cred);
 
        key = key_ref_to_ptr(key_ref);
Signature · 2 lines
paul moore
www.paul-moore.com
author maintainer
#5 lore raw
Quoted 106 lines · Paul Moore
Quoted 9 lines · David Howells
Quoted 4 lines · Paul Moore

... in particular it is the fifth argument to avc_has_perm(), "KEY_NEED_VIEW" which is a problem. KEY_NEED_VIEW is not a SELinux permission and would likely result in odd behavior when passed to avc_has_perm().

I think it works because KEY_NEED_VIEW happens to coincide with KEY__VIEW. It should just use KEY__VIEW instead.

Yes, it looks like it. To be clear, it is dangerous to rely on permission values from outside SELinux aligning with SELinux permissions; changing the outside permission values w/o adjusting the SELinux hook code to do the necessary translation will result in some scary behavior (wrong permission checks).

Quoted 8 lines
Quoted 3 lines

it probably makes the most sense to pull the permission mapping in selinux_key_permission() out into a separate function, e.g. key_perm_to_av(...)

Agreed. How about the attached patch? I wonder if I should do bit-by-bit translation rather than using a switch? But then it's difficult to decide what it means if someone passes in two KEY_NEED_* flags OR'd together - is it either or both?

Comments inline.

Quoted 4 lines
Quoted 2 lines

and then use this newly created mapping function in [...] selinux_watch_key()

No, I think I should just hard-code KEY__VIEW there.

FWIW, my comment was based on a version of linux-next where you were making policycap based permission adjustments to KEY_VIEW and I thought you would want the same adjustments to be applied to both access control points. That code appears to now be gone in linux-next.

Quoted 25 lines

---
commit 70d1d82aa014ae4511976b4d80c17138006dddec

Author: David Howells <[email protected]>
Date:   Tue Apr 21 13:15:16 2020 +0100

selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
security/selinux/hooks.c +2 -0
index 0b4e32161b77..32f7fa538c5f 100644
@@ -6539,12 +6539,27 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6553

Quoted 10 lines
security/selinux/hooks.c +10 -0
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:
+               return 0;
+       }

Regarding your question of permission translation via switch-statement as opposed to bit-by-bit comparison, I think it depends on if multiple permissions are going to be required in a single call to the hook. The failure mode for the code above if multiple permissions are requested is not very good, it defaults to *no* permission which means that if someone requested KEY_NEED_SEARCH|KEY_NEED_VIEW (or some other combination) then the SELinux check would not check any permissions ... that seems wrong to me.

If we want to stick with a switch statement I think we should have it return -EPERM for the default case to protect against this. We don't need the full 32-bits afforded us by the unsigned int.

Quoted 17 lines
security/selinux/hooks.c +4 -1
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 
        /* if no specific permissions are requested, we skip the
@@ -6553,6 +6568,7 @@ static int selinux_key_permission(key_ref_t key_ref,
        if (perm = 0)
                return 0;
 
Quoted 4 lines

security/selinux/hooks.c static int selinux_key_permission(key_ref_t key_ref, · line 6571

Quoted 1 line
security/selinux/hooks.c +1 -0
+       perm = selinux_keyperm_to_av(need_perm);

... and add a check for (perm < 0) as discussed above if we stick with the switch statement.

... and we should probably emit some sort of message to indicate that an invalid permission set was used.

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#6 lore raw
In reply to Paul Moore
Quoted 10 lines · Paul Moore
Quoted 4 lines
Quoted 2 lines

and then use this newly created mapping function in [...] selinux_watch_key()

No, I think I should just hard-code KEY__VIEW there.

FWIW, my comment was based on a version of linux-next where you were making policycap based permission adjustments to KEY_VIEW and I thought you would want the same adjustments to be applied to both access control points. That code appears to now be gone in linux-next.

I don't think I changed KEY_VIEW specifically; anyway, that code is on hold for the moment since it collides with this.

What I was wondering is if I should change KEY_NEED_xxx from a bitmask into an enum to remove the confusion about whether or not you're allowed to provide multiple 'needs' OR'd together.

Quoted 4 lines
Quoted 1 line

+ perm = selinux_keyperm_to_av(need_perm);

... and add a check for (perm < 0) as discussed above if we stick with the switch statement.

Actually, there was supposed to be a:

	if (!perm)
		return -EPERM;

after that line.

David

author maintainer
#7 lore raw
Quoted 26 lines · David Howells
Quoted 10 lines · Paul Moore
Quoted 4 lines
Quoted 2 lines

and then use this newly created mapping function in [...] selinux_watch_key()

No, I think I should just hard-code KEY__VIEW there.

FWIW, my comment was based on a version of linux-next where you were making policycap based permission adjustments to KEY_VIEW and I thought you would want the same adjustments to be applied to both access control points. That code appears to now be gone in linux-next.

I don't think I changed KEY_VIEW specifically; anyway, that code is on hold for the moment since it collides with this.

What I was wondering is if I should change KEY_NEED_xxx from a bitmask into an enum to remove the confusion about whether or not you're allowed to provide multiple 'needs' OR'd together.

Quoted 4 lines
Quoted 1 line

+ perm = selinux_keyperm_to_av(need_perm);

... and add a check for (perm < 0) as discussed above if we stick with the switch statement.

Quoted 6 lines

Actually, there was supposed to be a:

        if (!perm)
                return -EPERM;

after that line.

Okay, can you send the next version of the patch to the SELinux list for review?

Thank you.

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#8 lore raw

PATCH 1/1 selinux: Fix use of KEY_NEED_* instead of KEY__* perms

Quoted 2 lines · Paul Moore

Okay, can you send the next version of the patch to the SELinux list for review?

Here you go. Note that I did this a few days ago and I actually used EACCES rather than EPERM. Which one is one preferred for this?

David
---
selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
---
 security/selinux/hooks.c |   22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
security/selinux/hooks.c +20 -2
index 0b4e32161b77..6087955b49d8 100644
@@ -6539,20 +6539,38 @@ static void selinux_key_free(struct key *k)
 	kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+	switch (need_perm) {
+	case KEY_NEED_VIEW:	return KEY__VIEW;
+	case KEY_NEED_READ:	return KEY__READ;
+	case KEY_NEED_WRITE:	return KEY__WRITE;
+	case KEY_NEED_SEARCH:	return KEY__SEARCH;
+	case KEY_NEED_LINK:	return KEY__LINK;
+	case KEY_NEED_SETATTR:	return KEY__SETATTR;
+	default:
+		return 0;
+	}
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  unsigned need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
+	unsigned int perm;
 	u32 sid;
 
 	/* if no specific permissions are requested, we skip the
 	   permission check. No serious, additional covert channels
 	   appear to be created. */
-	if (perm = 0)
+	if (need_perm = 0)
 		return 0;
 
+	perm = selinux_keyperm_to_av(need_perm);
+	if (perm = 0)
+		return -EACCES;
 	sid = cred_sid(cred);
 
 	key = key_ref_to_ptr(key_ref);
maintainer
#9 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms

Quoted 8 lines · David Howells
Quoted 2 lines · Paul Moore

Okay, can you send the next version of the patch to the SELinux list for review?

Here you go. Note that I did this a few days ago and I actually used EACCES rather than EPERM. Which one is one preferred for this?

Generally SELinux returns EACCES unless the hook normally returns EPERM (e.g. capable).
Should we use a build-time or runtime guard to catch introduction of new KEY_NEED values without corresponding SELinux permissions?

Quoted 7 lines

David
---
selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work

s/security_sid_to_context/avc_has_perm

Quoted 1 line

because the values are all coincident.

Shrug. That was just a requirement on key permissions when they were introduced; same is true of capabilities.
Not opposed to explicitly mapping them now but it isn't really a bug.

Quoted 54 lines
Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
---
 security/selinux/hooks.c |   22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
security/selinux/hooks.c +20 -2
index 0b4e32161b77..6087955b49d8 100644
@@ -6539,20 +6539,38 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:
+               return 0;
+       }
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 
        /* if no specific permissions are requested, we skip the
           permission check. No serious, additional covert channels
           appear to be created. */
-       if (perm = 0)
+       if (need_perm = 0)
                return 0;
 
+       perm = selinux_keyperm_to_av(need_perm);
+       if (perm = 0)
+               return -EACCES;
        sid = cred_sid(cred);
 
        key = key_ref_to_ptr(key_ref);
author maintainer
#10 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms

Quoted 24 lines · Stephen Smalley
Quoted 8 lines · David Howells
Quoted 2 lines · Paul Moore

Okay, can you send the next version of the patch to the SELinux list for review?

Here you go. Note that I did this a few days ago and I actually used EACCES rather than EPERM. Which one is one preferred for this?

Generally SELinux returns EACCES unless the hook normally returns EPERM (e.g. capable).
Should we use a build-time or runtime guard to catch introduction of new KEY_NEED values without corresponding SELinux permissions?

Quoted 7 lines

David
---
selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work

Quoted 7 lines

s/security_sid_to_context/avc_has_perm

Quoted 1 line

because the values are all coincident.

Shrug. That was just a requirement on key permissions when they were introduced; same is true of capabilities.
Not opposed to explicitly mapping them now but it isn't really a bug.

I haven't looked at the rest of the patch yet, but I wanted to make a quick comment on this ... over the years I've seen a number of problems that crop up because of cross-subsytem assumptions, unless there is some performance critical path where the mapping is problematic I would prefer to see a translation layer to help protect SELinux.

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#11 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms

In reply to David Howells
Quoted 9 lines · David Howells
Quoted 2 lines · Paul Moore

Okay, can you send the next version of the patch to the SELinux list for review?

Here you go. Note that I did this a few days ago and I actually used EACCES rather than EPERM. Which one is one preferred for this?

Quoted 7 lines

David
---
selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_getsecurity() is passing the KEY_NEED_* permissions to security_sid_to_context() instead of the KEY__* values. It happens to work because the values are all coincident.

Both function names in the above description are wrong.

Quoted 15 lines
Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
---
 security/selinux/hooks.c |   22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
security/selinux/hooks.c +0 -0
index 0b4e32161b77..6087955b49d8 100644
@@ -6539,20 +6539,38 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6551

Quoted 10 lines
security/selinux/hooks.c +10 -0
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:

Possibly WARN() or BUG() here? Or BUILD_BUG_ON(KEY_NEED_ALL != 0x3f) to force an update here
whenever a new key permission is defined?

Quoted 14 lines
security/selinux/hooks.c +6 -1
+               return 0;
+       }
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6573

Quoted 10 lines
security/selinux/hooks.c +4 -1
        /* if no specific permissions are requested, we skip the
           permission check. No serious, additional covert channels
           appear to be created. */
-       if (perm = 0)
+       if (need_perm = 0)
                return 0;
 
+       perm = selinux_keyperm_to_av(need_perm);
+       if (perm = 0)
+               return -EACCES;

We should log or audit some kind of message here, whether via WARN(), audit_log(), or something, to avoid silent denials.

Quoted 4 lines
security/selinux/hooks.c +0 -0
        sid = cred_sid(cred);
 
        key = key_ref_to_ptr(key_ref);
author maintainer
#12 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms

Quoted 1 line · Stephen Smalley

On Mon, Apr 27, 2020 at 10:13 AM David Howells <[email protected]> wrote:

...

Quoted 8 lines
Quoted 8 lines
security/selinux/hooks.c +0 -0
index 0b4e32161b77..6087955b49d8 100644
@@ -6539,20 +6539,38 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 
Quoted 14 lines

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6551

Quoted 10 lines
security/selinux/hooks.c +10 -0
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:

Possibly WARN() or BUG() here? Or BUILD_BUG_ON(KEY_NEED_ALL != 0x3f) to force an update here
whenever a new key permission is defined?

My vote is for a build time check via BUILD_BUG_ON() or similar mechanism. It's worked really well in other places, I'm thinking specifically of the SELinux netlink mapping.

Quoted 21 lines
Quoted 21 lines
security/selinux/hooks.c +7 -2
+               return 0;
+       }
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 
        /* if no specific permissions are requested, we skip the
           permission check. No serious, additional covert channels
           appear to be created. */
-       if (perm = 0)
+       if (need_perm = 0)
                return 0;
 
Quoted 6 lines

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6573

Quoted 3 lines
security/selinux/hooks.c +3 -0
+       perm = selinux_keyperm_to_av(need_perm);
+       if (perm = 0)
+               return -EACCES;

We should log or audit some kind of message here, whether via WARN(), audit_log(), or something, to avoid silent denials.

Assuming we add a build time check (see above), I think a WARN here is okay.

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#13 lore raw

PATCH 1/1 selinux: Fix use of KEY_NEED_* instead of KEY__* perms [v2]

In reply to Paul Moore

selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_permission() is passing the KEY_NEED_* permissions to avc_has_perm() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
---
 security/selinux/hooks.c |   23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
security/selinux/hooks.c +21 -2
index 0b4e32161b77..4b6624e5dab4 100644
@@ -6539,20 +6539,39 @@ static void selinux_key_free(struct key *k)
 	kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+	switch (need_perm) {
+	case KEY_NEED_VIEW:	return KEY__VIEW;
+	case KEY_NEED_READ:	return KEY__READ;
+	case KEY_NEED_WRITE:	return KEY__WRITE;
+	case KEY_NEED_SEARCH:	return KEY__SEARCH;
+	case KEY_NEED_LINK:	return KEY__LINK;
+	case KEY_NEED_SETATTR:	return KEY__SETATTR;
+	default:
+		WARN_ON(1);
+		return 0;
+	}
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  unsigned need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
+	unsigned int perm;
 	u32 sid;
 
 	/* if no specific permissions are requested, we skip the
 	   permission check. No serious, additional covert channels
 	   appear to be created. */
-	if (perm = 0)
+	if (need_perm = 0)
 		return 0;
 
+	perm = selinux_keyperm_to_av(need_perm);
+	if (perm = 0)
+		return -EPERM;
 	sid = cred_sid(cred);
 
 	key = key_ref_to_ptr(key_ref);
maintainer
#14 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms [v2]

Quoted 50 lines · David Howells

selinux: Fix use of KEY_NEED_* instead of KEY__* perms

selinux_key_permission() is passing the KEY_NEED_* permissions to avc_has_perm() instead of the KEY__* values. It happens to work because the values are all coincident.

Fixes d720024e94de ("[PATCH] selinux: add hooks for key subsystem")
---
 security/selinux/hooks.c |   23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
security/selinux/hooks.c +17 -1
index 0b4e32161b77..4b6624e5dab4 100644
@@ -6539,20 +6539,39 @@ static void selinux_key_free(struct key *k)
        kfree(ksec);
 }
 
+static unsigned int selinux_keyperm_to_av(unsigned int need_perm)
+{
+       switch (need_perm) {
+       case KEY_NEED_VIEW:     return KEY__VIEW;
+       case KEY_NEED_READ:     return KEY__READ;
+       case KEY_NEED_WRITE:    return KEY__WRITE;
+       case KEY_NEED_SEARCH:   return KEY__SEARCH;
+       case KEY_NEED_LINK:     return KEY__LINK;
+       case KEY_NEED_SETATTR:  return KEY__SETATTR;
+       default:
+               WARN_ON(1);
+               return 0;
+       }
+}
+
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 unsigned need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
+       unsigned int perm;
        u32 sid;
 
        /* if no specific permissions are requested, we skip the
           permission check. No serious, additional covert channels
           appear to be created. */

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6577

Quoted 10 lines
security/selinux/hooks.c +4 -1
-       if (perm = 0)
+       if (need_perm = 0)
                return 0;
 
+       perm = selinux_keyperm_to_av(need_perm);
+       if (perm = 0)
+               return -EPERM;
        sid = cred_sid(cred);
 
        key = key_ref_to_ptr(key_ref);

1) Are we guaranteed that the caller only ever passes a single KEY_NEED_* perm at a time (i.e. hook is never called with a bitmask of multiple permissions)? Where is that guarantee enforced?

2) We had talked about adding a BUILD_BUG_ON() or other build-time guard to ensure that new KEY_NEED_* permissions
are not added without updating SELinux. We already have similar constructs for catching new capabilities (#if CAP_LAST_CAP > 63 #error ...), socket address families (#if PF_MAX > 45 #error ...), RTM_* and XFRM_MSG* values.

maintainer
#15 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms [v2]

Quoted 3 lines · Stephen Smalley

1) Are we guaranteed that the caller only ever passes a single KEY_NEED_* perm at a time (i.e. hook is never called with a bitmask of multiple permissions)? Where is that guarantee enforced?

Currently it's the case that only one perm is ever used at once. I'm tempted to enforce this by switching the KEY_NEED_* to an enum rather than a bitmask.

I'm not sure how I would actually define the meaning of two perms being OR'd together. Either okay? Both required?

Quoted 2 lines

2) We had talked about adding a BUILD_BUG_ON() or other build-time guard

That doesn't help you trap unallowed perm combinations, though.

Quoted 5 lines

to ensure that new KEY_NEED_* permissions
are not added without updating SELinux. We already have similar constructs for catching new capabilities (#if CAP_LAST_CAP > 63 #error ...), socket address families (#if PF_MAX > 45 #error ...), RTM_* and XFRM_MSG* values.

David

maintainer
#16 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms [v2]

Quoted 7 lines · David Howells
Quoted 3 lines · Stephen Smalley

1) Are we guaranteed that the caller only ever passes a single KEY_NEED_* perm at a time (i.e. hook is never called with a bitmask of multiple permissions)? Where is that guarantee enforced?

Quoted 5 lines

Currently it's the case that only one perm is ever used at once. I'm tempted to enforce this by switching the KEY_NEED_* to an enum rather than a bitmask.

I'm not sure how I would actually define the meaning of two perms being OR'd together. Either okay? Both required?

Both required is the usual convention in functions like inode_permission() or avc_has_perm().
But if you know that you'll never use combinations, we should just prohibit it up front, e.g.
key_task_permission() or whatever can reject them before they reach the hook call. Then the
hook code doesn't have to revisit the issue.

Quoted 5 lines
Quoted 3 lines

2) We had talked about adding a BUILD_BUG_ON() or other build-time guard

That doesn't help you trap unallowed perm combinations, though.

I think we want both.

Quoted 9 lines
Quoted 6 lines

to ensure that new KEY_NEED_* permissions
are not added without updating SELinux. We already have similar constructs for catching new capabilities (#if CAP_LAST_CAP > 63 #error ...), socket address families (#if PF_MAX > 45 #error ...), RTM_* and XFRM_MSG* values.

David

author maintainer
#17 lore raw

Re: [PATCH] selinux: Fix use of KEY_NEED_* instead of KEY__* perms [v2]

Quoted 22 lines · Stephen Smalley
Quoted 11 lines · David Howells
Quoted 3 lines · Stephen Smalley

1) Are we guaranteed that the caller only ever passes a single KEY_NEED_* perm at a time (i.e. hook is never called with a bitmask of multiple permissions)? Where is that guarantee enforced?

Currently it's the case that only one perm is ever used at once. I'm tempted to enforce this by switching the KEY_NEED_* to an enum rather than a bitmask.

I'm not sure how I would actually define the meaning of two perms being OR'd together. Either okay? Both required?

Both required is the usual convention in functions like inode_permission() or avc_has_perm().
But if you know that you'll never use combinations, we should just prohibit it up front, e.g.
key_task_permission() or whatever can reject them before they reach the hook call. Then the
hook code doesn't have to revisit the issue.

Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

2) We had talked about adding a BUILD_BUG_ON() or other build-time guard

That doesn't help you trap unallowed perm combinations, though.

I think we want both.

Yep, we want both. #moarsafety

Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#18 lore raw

PATCH 1/1 keys: Make the KEY_NEED_* perms an enum rather than a mask

In reply to Stephen Smalley

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

(4) An override due to an instantiation token being present.

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.

cc Jarkko Sakkinen <[email protected]>
cc Paul Moore <[email protected]>
cc Stephen Smalley <[email protected]>
cc Casey Schaufler <[email protected]>

---

 include/linux/key.h          |   30 ++++++++++++++++-----------
 include/linux/security.h     |    6 +++--
 security/keys/internal.h     |    8 ++++---
 security/keys/keyctl.c       |   16 ++++++++-------
 security/keys/permission.c   |   31 ++++++++++++++++++++++------
 security/keys/process_keys.c |   46 ++++++++++++++++++++----------------------
 security/security.c          |    6 +++--
 security/selinux/hooks.c     |   25 ++++++++++++++++-------
 security/smack/smack_lsm.c   |   31 +++++++++++++++++++++-------
 9 files changed, 124 insertions(+), 75 deletions(-)
include/linux/key.h +18 -12
index b99b40db08fc..0f2e24f13c2b 100644
@@ -71,6 +71,23 @@ struct net;
 
 #define KEY_PERM_UNDEF	0xffffffff
 
+/*
+ * The permissions required on a key that we're looking up.
+ */
+enum key_need_perm {
+	KEY_NEED_UNSPECIFIED,	/* Needed permission unspecified */
+	KEY_NEED_VIEW,		/* Require permission to view attributes */
+	KEY_NEED_READ,		/* Require permission to read content */
+	KEY_NEED_WRITE,		/* Require permission to update / modify */
+	KEY_NEED_SEARCH,	/* Require permission to search (keyring) or find (key) */
+	KEY_NEED_LINK,		/* Require permission to link */
+	KEY_NEED_SETATTR,	/* Require permission to change attributes */
+	KEY_NEED_UNLINK,	/* Require permission to unlink key */
+	KEY_SYSADMIN_OVERRIDE,	/* Special: override by CAP_SYS_ADMIN */
+	KEY_AUTHTOKEN_OVERRIDE,	/* Special: override by possession of auth token */
+	KEY_DEFER_PERM_CHECK,	/* Special: permission check is deferred */
+};
+
 struct seq_file;
 struct user_struct;
 struct signal_struct;
@@ -420,20 +437,9 @@ static inline key_serial_t key_serial(const struct key *key)
 extern void key_set_timeout(struct key *, unsigned);
 
 extern key_ref_t lookup_user_key(key_serial_t id, unsigned long flags,
-				 key_perm_t perm);
+				 enum key_need_perm need_perm);
 extern void key_free_user_ns(struct user_namespace *);
 
-/*
- * The permissions required on a key that we're looking up.
- */
-#define	KEY_NEED_VIEW	0x01	/* Require permission to view attributes */
-#define	KEY_NEED_READ	0x02	/* Require permission to read content */
-#define	KEY_NEED_WRITE	0x04	/* Require permission to update / modify */
-#define	KEY_NEED_SEARCH	0x08	/* Require permission to search (keyring) or find (key) */
-#define	KEY_NEED_LINK	0x10	/* Require permission to link */
-#define	KEY_NEED_SETATTR 0x20	/* Require permission to change attributes */
-#define	KEY_NEED_ALL	0x3f	/* All the above permissions */
-
 static inline short key_read_state(const struct key *key)
 {
 	/* Barrier versus mark_key_instantiated(). */
include/linux/security.h +3 -3
index e7914e4e0b02..57aac14e3418 100644
@@ -1767,8 +1767,8 @@ static inline int security_path_chroot(const struct path *path)
 
 int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags);
 void security_key_free(struct key *key);
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm);
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm);
 int security_key_getsecurity(struct key *key, char **_buffer);
 
 #else
@@ -1786,7 +1786,7 @@ static inline void security_key_free(struct key *key)
 
 static inline int security_key_permission(key_ref_t key_ref,
 					  const struct cred *cred,
-					  unsigned perm)
+					  enum key_need_perm need_perm)
 {
 	return 0;
 }
security/keys/internal.h +4 -4
index 28e17f4f3328..1fc17cb317a9 100644
@@ -167,7 +167,6 @@ extern bool lookup_user_key_possessed(const struct key *key,
 				      const struct key_match_data *match_data);
 #define KEY_LOOKUP_CREATE	0x01
 #define KEY_LOOKUP_PARTIAL	0x02
-#define KEY_LOOKUP_FOR_UNLINK	0x04
 
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
@@ -183,7 +182,7 @@ extern void key_gc_keytype(struct key_type *ktype);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
-			       key_perm_t perm);
+			       enum key_need_perm need_perm);
 
 static inline void notify_key(struct key *key,
 			      enum key_notification_subtype subtype, u32 aux)
@@ -205,9 +204,10 @@ static inline void notify_key(struct key *key,
 /*
  * Check to see whether permission is granted to use a key in the desired way.
  */
-static inline int key_permission(const key_ref_t key_ref, unsigned perm)
+static inline int key_permission(const key_ref_t key_ref,
+				 enum key_need_perm need_perm)
 {
-	return key_task_permission(key_ref, current_cred(), perm);
+	return key_task_permission(key_ref, current_cred(), need_perm);
 }
 
 extern struct key_type key_type_request_key_auth;
security/keys/keyctl.c +9 -7
index 7d8de1c9a478..6763ee45e04d 100644
@@ -434,7 +434,7 @@ long keyctl_invalidate_key(key_serial_t id)
 
 		/* Root is permitted to invalidate certain special keys */
 		if (capable(CAP_SYS_ADMIN)) {
-			key_ref = lookup_user_key(id, 0, 0);
+			key_ref = lookup_user_key(id, 0, KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(key_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_INVAL,
@@ -479,7 +479,8 @@ long keyctl_keyring_clear(key_serial_t ringid)
 
 		/* Root is permitted to invalidate certain special keyrings */
 		if (capable(CAP_SYS_ADMIN)) {
-			keyring_ref = lookup_user_key(ringid, 0, 0);
+			keyring_ref = lookup_user_key(ringid, 0,
+						      KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(keyring_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR,
@@ -563,7 +564,7 @@ long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
 		goto error;
 	}
 
-	key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0);
+	key_ref = lookup_user_key(id, KEY_LOOKUP_PARTIAL, KEY_NEED_UNLINK);
 	if (IS_ERR(key_ref)) {
 		ret = PTR_ERR(key_ref);
 		goto error2;
@@ -663,7 +664,7 @@ long keyctl_describe_key(key_serial_t keyid,
 				key_put(instkey);
 				key_ref = lookup_user_key(keyid,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -833,7 +834,7 @@ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
 	size_t key_data_len;
 
 	/* find the key first */
-	key_ref = lookup_user_key(keyid, 0, 0);
+	key_ref = lookup_user_key(keyid, 0, KEY_DEFER_PERM_CHECK);
 	if (IS_ERR(key_ref)) {
 		ret = -ENOKEY;
 		goto out;
@@ -1471,7 +1472,7 @@ long keyctl_set_timeout(key_serial_t id, unsigned timeout)
 				key_put(instkey);
 				key_ref = lookup_user_key(id,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -1579,7 +1580,8 @@ long keyctl_get_security(key_serial_t keyid,
 			return PTR_ERR(instkey);
 		key_put(instkey);
 
-		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
+		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL,
+					  KEY_AUTHTOKEN_OVERRIDE);
 		if (IS_ERR(key_ref))
 			return PTR_ERR(key_ref);
 	}
security/keys/permission.c +24 -7
index 085f907b64ac..4a61f804e80f 100644
@@ -13,7 +13,7 @@
  * key_task_permission - Check a key can be used
  * @key_ref: The key to check.
  * @cred: The credentials to use.
- * @perm: The permissions to check for.
+ * @need_perm: The permission required.
  *
  * Check to see whether permission is granted to use a key in the desired way,
  * but permit the security modules to override.
@@ -24,12 +24,30 @@
  * permissions bits or the LSM check.
  */
 int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
-			unsigned perm)
+			enum key_need_perm need_perm)
 {
 	struct key *key;
-	key_perm_t kperm;
+	key_perm_t kperm, mask;
 	int ret;
 
+	switch (need_perm) {
+	default:
+		WARN_ON(1);
+		return -EACCES;
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		goto lsm;
+
+	case KEY_NEED_VIEW:	mask = KEY_OTH_VIEW;	break;
+	case KEY_NEED_READ:	mask = KEY_OTH_READ;	break;
+	case KEY_NEED_WRITE:	mask = KEY_OTH_WRITE;	break;
+	case KEY_NEED_SEARCH:	mask = KEY_OTH_SEARCH;	break;
+	case KEY_NEED_LINK:	mask = KEY_OTH_LINK;	break;
+	case KEY_NEED_SETATTR:	mask = KEY_OTH_SETATTR;	break;
+	}
+
 	key = key_ref_to_ptr(key_ref);
 
 	/* use the second 8-bits of permissions for keys the caller owns */
@@ -64,13 +82,12 @@ int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
 	if (is_key_possessed(key_ref))
 		kperm |= key->perm >> 24;
 
-	kperm = kperm & perm & KEY_NEED_ALL;
-
-	if (kperm != perm)
+	if ((kperm & mask) != mask)
 		return -EACCES;
 
 	/* let LSM be the final arbiter */
-	return security_key_permission(key_ref, cred, perm);
+lsm:
+	return security_key_permission(key_ref, cred, need_perm);
 }
 EXPORT_SYMBOL(key_task_permission);
 
security/keys/process_keys.c +22 -24

64 lines not on this page · raw message

security/security.c +3 -3
index c73334ab2882..af32d4cd0462 100644
@@ -2398,10 +2398,10 @@ void security_key_free(struct key *key)
 	call_void_hook(key_free, key);
 }
 
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm)
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm)
 {
-	return call_int_hook(key_permission, 0, key_ref, cred, perm);
+	return call_int_hook(key_permission, 0, key_ref, cred, need_perm);
 }
 
 int security_key_getsecurity(struct key *key, char **_buffer)
security/selinux/hooks.c +18 -7
index 0b4e32161b77..3ff6b6dfc5ca 100644
@@ -6541,20 +6541,31 @@ static void selinux_key_free(struct key *k)
 
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  enum key_need_perm need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
-	u32 sid;
+	u32 perm, sid;
 
-	/* if no specific permissions are requested, we skip the
-	   permission check. No serious, additional covert channels
-	   appear to be created. */
-	if (perm = 0)
+	switch (need_perm) {
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
 		return 0;
+	default:
+		WARN_ON(1);
+		return -EPERM;
 
-	sid = cred_sid(cred);
+	case KEY_NEED_VIEW:	perm = KEY__VIEW;	break;
+	case KEY_NEED_READ:	perm = KEY__READ;	break;
+	case KEY_NEED_WRITE:	perm = KEY__WRITE;	break;
+	case KEY_NEED_SEARCH:	perm = KEY__SEARCH;	break;
+	case KEY_NEED_LINK:	perm = KEY__LINK;	break;
+	case KEY_NEED_SETATTR:	perm = KEY__SETATTR;	break;
+	}
 
+	sid = cred_sid(cred);
 	key = key_ref_to_ptr(key_ref);
 	ksec = key->security;
 
security/smack/smack_lsm.c +23 -8
index 8c61d175e195..627ca7dc9b27 100644
@@ -4230,13 +4230,14 @@ static void smack_key_free(struct key *key)
  * smack_key_permission - Smack access on a key
  * @key_ref: gets to the object
  * @cred: the credentials to use
- * @perm: requested key permissions
+ * @need_perm: requested key permission
  *
  * Return 0 if the task has read and write to the object,
  * an error code otherwise
  */
 static int smack_key_permission(key_ref_t key_ref,
-				const struct cred *cred, unsigned perm)
+				const struct cred *cred,
+				enum key_need_perm need_perm)
 {
 	struct key *keyp;
 	struct smk_audit_info ad;
@@ -4247,8 +4248,26 @@ static int smack_key_permission(key_ref_t key_ref,
 	/*
 	 * Validate requested permissions
 	 */
-	if (perm & ~KEY_NEED_ALL)
-		return -EINVAL;
+	switch (need_perm) {
+	default:
+		return -EACCES;
+	case KEY_NEED_UNSPECIFIED:
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		return 0;
+	case KEY_NEED_READ:
+	case KEY_NEED_SEARCH:
+	case KEY_NEED_VIEW:
+		request |= MAY_READ;
+		break;
+	case KEY_NEED_WRITE:
+	case KEY_NEED_LINK:
+	case KEY_NEED_SETATTR:
+		request |= MAY_WRITE;
+		break;
+	}
 
 	keyp = key_ref_to_ptr(key_ref);
 	if (keyp = NULL)
@@ -4273,10 +4292,6 @@ static int smack_key_permission(key_ref_t key_ref,
 	ad.a.u.key_struct.key = keyp->serial;
 	ad.a.u.key_struct.key_desc = keyp->description;
 #endif
-	if (perm & (KEY_NEED_READ | KEY_NEED_SEARCH | KEY_NEED_VIEW))
-		request |= MAY_READ;
-	if (perm & (KEY_NEED_WRITE | KEY_NEED_LINK | KEY_NEED_SETATTR))
-		request |= MAY_WRITE;
 	rc = smk_access(tkp, keyp->security, request, &ad);
 	rc = smk_bu_note("key access", tkp, keyp->security, request, rc);
 	return rc;
author maintainer
#19 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 30 lines · David Howells

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

(4) An override due to an instantiation token being present.

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.

cc Jarkko Sakkinen <[email protected]>
cc Paul Moore <[email protected]>
cc Stephen Smalley <[email protected]>
cc Casey Schaufler <[email protected]>

---

Quoted 10 lines
 include/linux/key.h          |   30 ++++++++++++++++-----------
 include/linux/security.h     |    6 +++--
 security/keys/internal.h     |    8 ++++---
 security/keys/keyctl.c       |   16 ++++++++-------
 security/keys/permission.c   |   31 ++++++++++++++++++++++------
 security/keys/process_keys.c |   46 ++++++++++++++++++++----------------------
 security/security.c          |    6 +++--
 security/selinux/hooks.c     |   25 ++++++++++++++++-------
 security/smack/smack_lsm.c   |   31 +++++++++++++++++++++-------
 9 files changed, 124 insertions(+), 75 deletions(-)

Thanks for clarifying this, it helps a lot.

My comments below are nitpicky, but take them into account, the style of the SELinux code changes makes my eyes hurt.

Quoted 19 lines
security/selinux/hooks.c +2 -5
index 0b4e32161b77..3ff6b6dfc5ca 100644
@@ -6541,20 +6541,31 @@ static void selinux_key_free(struct key *k)
 
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 enum key_need_perm need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
-       u32 sid;
+       u32 perm, sid;
 
-       /* if no specific permissions are requested, we skip the
-          permission check. No serious, additional covert channels
-          appear to be created. */

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6558

Quoted 10 lines
security/selinux/hooks.c +8 -1
-       if (perm = 0)
+       switch (need_perm) {
+       case KEY_NEED_UNLINK:
+       case KEY_SYSADMIN_OVERRIDE:
+       case KEY_AUTHTOKEN_OVERRIDE:
+       case KEY_DEFER_PERM_CHECK:
                return 0;
+       default:
+               WARN_ON(1);
+               return -EPERM;

Please move the default case to the bottom of the switch statement.

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6565

Quoted 7 lines
security/selinux/hooks.c +6 -1
-       sid = cred_sid(cred);
+       case KEY_NEED_VIEW:     perm = KEY__VIEW;       break;
+       case KEY_NEED_READ:     perm = KEY__READ;       break;
+       case KEY_NEED_WRITE:    perm = KEY__WRITE;      break;
+       case KEY_NEED_SEARCH:   perm = KEY__SEARCH;     break;
+       case KEY_NEED_LINK:     perm = KEY__LINK;       break;
+       case KEY_NEED_SETATTR:  perm = KEY__SETATTR;    break;

Please don't put the case statements all on one line, use the more traditional multi-line format. For example:

  case KEY_NEED_SETATTR:
          perm = KEY__SETATTR;
          break;
Quoted 5 lines
security/selinux/hooks.c +2 -0
+       }
 
+       sid = cred_sid(cred);
        key = key_ref_to_ptr(key_ref);
        ksec = key->security;
Signature · 2 lines
paul moore
www.paul-moore.com
maintainer
#20 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 7 lines · Paul Moore

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6565

Quoted 6 lines
security/selinux/hooks.c +6 -0
+       case KEY_NEED_VIEW:     perm = KEY__VIEW;       break;
+       case KEY_NEED_READ:     perm = KEY__READ;       break;
+       case KEY_NEED_WRITE:    perm = KEY__WRITE;      break;
+       case KEY_NEED_SEARCH:   perm = KEY__SEARCH;     break;
+       case KEY_NEED_LINK:     perm = KEY__LINK;       break;
+       case KEY_NEED_SETATTR:  perm = KEY__SETATTR;    break;
Quoted 6 lines

Please don't put the case statements all on one line, use the more traditional multi-line format. For example:

  case KEY_NEED_SETATTR:
          perm = KEY__SETATTR;
          break;

Tabulation was invented something like 6000 years ago for just this kind of purpose;-) It's less readable your way, but whatever...

David

maintainer
#21 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

In reply to David Howells
Quoted 7 lines · David Howells

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

Quoted 7 lines

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

CAP_SYS_ADMIN should never skip SELinux checking. Even for Smack, there is a separate capability (CAP_MAC_ADMIN) for that purpose.

Quoted 1 line

(4) An override due to an instantiation token being present.

Not sure what this means but again we shouldn't skip SELinux checking based on mere possession of an object capability (not a POSIX capability).

Quoted 12 lines

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.
---

security/keys/keyctl.c +0 -0
index 7d8de1c9a478..6763ee45e04d 100644

security/keys/keyctl.c long keyctl_invalidate_key(key_serial_t id) · line 437

Quoted 5 lines
security/keys/keyctl.c +1 -1
@@ -434,7 +434,7 @@ long keyctl_invalidate_key(key_serial_t id)
 
                /* Root is permitted to invalidate certain special keys */
                if (capable(CAP_SYS_ADMIN)) {
-                       key_ref = lookup_user_key(id, 0, 0);
+                       key_ref = lookup_user_key(id, 0, KEY_SYSADMIN_OVERRIDE);

It would be better if the permission indicated the actual operation (e.g. KEY_NEED_INVALIDATE_SPECIAL), and the decision whether to permit CAP_SYS_ADMIN processes to override was left to the security modules. SELinux doesn't automatically allow CAP_SYS_ADMIN processes to do everything.

security/keys/keyctl.c long keyctl_keyring_clear(key_serial_t ringid) · line 483

Quoted 7 lines
security/keys/keyctl.c +2 -1
@@ -479,7 +479,8 @@ long keyctl_keyring_clear(key_serial_t ringid)
 
                /* Root is permitted to invalidate certain special keyrings */
                if (capable(CAP_SYS_ADMIN)) {
-                       keyring_ref = lookup_user_key(ringid, 0, 0);
+                       keyring_ref = lookup_user_key(ringid, 0,
+                                                     KEY_SYSADMIN_OVERRIDE);

Ditto.

security/keys/keyctl.c long keyctl_describe_key(key_serial_t keyid, · line 667

Quoted 6 lines
security/keys/keyctl.c +1 -1
@@ -663,7 +664,7 @@ long keyctl_describe_key(key_serial_t keyid,
                                key_put(instkey);
                                key_ref = lookup_user_key(keyid,
                                                          KEY_LOOKUP_PARTIAL,
-                                                         0);
+                                                         KEY_AUTHTOKEN_OVERRIDE);

Similarly, it would be better if the permission indicated the operation (e.g. KEY_NEED_DESCRIBE) rather than the means by which it is being authorized. A MAC scheme won't allow mere knowledge of a token/password-capability to permit violation of its policy.

security/keys/keyctl.c long keyctl_set_timeout(key_serial_t id, unsigned timeout) · line 1475

Quoted 6 lines
security/keys/keyctl.c +1 -1
@@ -1471,7 +1472,7 @@ long keyctl_set_timeout(key_serial_t id, unsigned timeout)
                                key_put(instkey);
                                key_ref = lookup_user_key(id,
                                                          KEY_LOOKUP_PARTIAL,
-                                                         0);
+                                                         KEY_AUTHTOKEN_OVERRIDE);

Ditto.

security/keys/keyctl.c long keyctl_get_security(key_serial_t keyid, · line 1584

Quoted 7 lines
security/keys/keyctl.c +2 -1
@@ -1579,7 +1580,8 @@ long keyctl_get_security(key_serial_t keyid,
                        return PTR_ERR(instkey);
                key_put(instkey);
 
-               key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
+               key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL,
+                                         KEY_AUTHTOKEN_OVERRIDE);

Ditto

Quoted 16 lines
security/selinux/hooks.c +2 -2
index 0b4e32161b77..3ff6b6dfc5ca 100644
@@ -6541,20 +6541,31 @@ static void selinux_key_free(struct key *k)
 
 static int selinux_key_permission(key_ref_t key_ref,
                                  const struct cred *cred,
-                                 unsigned perm)
+                                 enum key_need_perm need_perm)
 {
        struct key *key;
        struct key_security_struct *ksec;
-       u32 sid;
+       u32 perm, sid;
 

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6555

Quoted 10 lines
security/selinux/hooks.c +5 -4
-       /* if no specific permissions are requested, we skip the
-          permission check. No serious, additional covert channels
-          appear to be created. */
-       if (perm = 0)
+       switch (need_perm) {
+       case KEY_NEED_UNLINK:
+       case KEY_SYSADMIN_OVERRIDE:
+       case KEY_AUTHTOKEN_OVERRIDE:
+       case KEY_DEFER_PERM_CHECK:
                return 0;

We really shouldn't be skipping any/all checking on CAP_SYS_ADMIN or an AUTHTOKEN; those should still be subject to MAC policy.

maintainer
#22 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 4 lines · Stephen Smalley
Quoted 1 line

(3) An override due to CAP_SYS_ADMIN.

CAP_SYS_ADMIN should never skip SELinux checking. Even for Smack, there is a separate capability (CAP_MAC_ADMIN) for that purpose.

The LSM doesn't get consulted at the moment. With this patch, it will get consulted.

Quoted 5 lines
Quoted 1 line

(4) An override due to an instantiation token being present.

Not sure what this means but again we shouldn't skip SELinux checking based on mere possession of an object capability (not a POSIX capability).

The kernel has delegated the instantiation of a key to the calling process and has given it a temporary key of type ".request_key_auth" which it has put into force with keyctl(KEYCTL_ASSUME_AUTHORITY).

This authorisation token grants the caller the ability to (a) perform operations on the key it wouldn't otherwise have permission to do, (b) use the key instantiation keyctls and (c) temporarily search the keyrings of the caller of request_key() using the creds of that caller and to read/use the keys found therein if the caller was permitted to do so.

Quoted 5 lines

It would be better if the permission indicated the actual operation (e.g. KEY_NEED_INVALIDATE_SPECIAL), and the decision whether to permit CAP_SYS_ADMIN processes to override was left to the security modules. SELinux doesn't automatically allow CAP_SYS_ADMIN processes to do everything.

These individual permissions don't exist yet. I have an ACL patchset that allows me to add a greater range - though there's issues with SELinux there also.

Also, the keyrings are specially marked to say that the sysadmin is allowed to flush them at the moment - but that can go away with the ACL stuff.

Quoted 9 lines

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6555

Quoted 6 lines
security/selinux/hooks.c +5 -0
+       switch (need_perm) {
+       case KEY_NEED_UNLINK:
+       case KEY_SYSADMIN_OVERRIDE:
+       case KEY_AUTHTOKEN_OVERRIDE:
+       case KEY_DEFER_PERM_CHECK:
                return 0;

We really shouldn't be skipping any/all checking on CAP_SYS_ADMIN or an AUTHTOKEN; those should still be subject to MAC policy.

I'm not sure how to do that.

Note that KEY_NEED_UNLINK *must not* be overruled by the MAC policy. The value is only there because lookup_user_key() requires something to be put into that parameter - it's more of a courtesy thing, I suppose.

Why should AUTHTOKEN be subject to MAC policy? The kernel has told the process to go and instantiate a key. It shouldn't really then turn around and tell the process "oh, but you're not actually allowed to do that".

David

maintainer
#23 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 52 lines · David Howells
Quoted 4 lines · Stephen Smalley
Quoted 1 line

(3) An override due to CAP_SYS_ADMIN.

CAP_SYS_ADMIN should never skip SELinux checking. Even for Smack, there is a separate capability (CAP_MAC_ADMIN) for that purpose.

The LSM doesn't get consulted at the moment. With this patch, it will get consulted.

Quoted 5 lines
Quoted 1 line

(4) An override due to an instantiation token being present.

Not sure what this means but again we shouldn't skip SELinux checking based on mere possession of an object capability (not a POSIX capability).

The kernel has delegated the instantiation of a key to the calling process and has given it a temporary key of type ".request_key_auth" which it has put into force with keyctl(KEYCTL_ASSUME_AUTHORITY).

This authorisation token grants the caller the ability to (a) perform operations on the key it wouldn't otherwise have permission to do, (b) use the key instantiation keyctls and (c) temporarily search the keyrings of the caller of request_key() using the creds of that caller and to read/use the keys found therein if the caller was permitted to do so.

Quoted 5 lines

It would be better if the permission indicated the actual operation (e.g. KEY_NEED_INVALIDATE_SPECIAL), and the decision whether to permit CAP_SYS_ADMIN processes to override was left to the security modules. SELinux doesn't automatically allow CAP_SYS_ADMIN processes to do everything.

These individual permissions don't exist yet. I have an ACL patchset that allows me to add a greater range - though there's issues with SELinux there also.

Also, the keyrings are specially marked to say that the sysadmin is allowed to flush them at the moment - but that can go away with the ACL stuff.

Quoted 9 lines

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6555

Quoted 6 lines
security/selinux/hooks.c +5 -0
+       switch (need_perm) {
+       case KEY_NEED_UNLINK:
+       case KEY_SYSADMIN_OVERRIDE:
+       case KEY_AUTHTOKEN_OVERRIDE:
+       case KEY_DEFER_PERM_CHECK:
                return 0;

We really shouldn't be skipping any/all checking on CAP_SYS_ADMIN or an AUTHTOKEN; those should still be subject to MAC policy.

I'm not sure how to do that.

Quoted 7 lines

Note that KEY_NEED_UNLINK *must not* be overruled by the MAC policy. The value is only there because lookup_user_key() requires something to be put into that parameter - it's more of a courtesy thing, I suppose.

Why should AUTHTOKEN be subject to MAC policy? The kernel has told the process to go and instantiate a key. It shouldn't really then turn around and tell the process "oh, but you're not actually allowed to do that".

On what basis did the kernel authorize the process to instantiate the key? At what point did a security module get involved in the decision as to what process(es) are authorize to instantiate a key, particularly for a process with a different credential/security context?

maintainer
#24 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 62 lines · Stephen Smalley
Quoted 52 lines · David Howells
Quoted 4 lines · Stephen Smalley
Quoted 1 line

(3) An override due to CAP_SYS_ADMIN.

CAP_SYS_ADMIN should never skip SELinux checking. Even for Smack, there is a separate capability (CAP_MAC_ADMIN) for that purpose.

The LSM doesn't get consulted at the moment. With this patch, it will get consulted.

Quoted 5 lines
Quoted 1 line

(4) An override due to an instantiation token being present.

Not sure what this means but again we shouldn't skip SELinux checking based on mere possession of an object capability (not a POSIX capability).

The kernel has delegated the instantiation of a key to the calling process and has given it a temporary key of type ".request_key_auth" which it has put into force with keyctl(KEYCTL_ASSUME_AUTHORITY).

This authorisation token grants the caller the ability to (a) perform operations on the key it wouldn't otherwise have permission to do, (b) use the key instantiation keyctls and (c) temporarily search the keyrings of the caller of request_key() using the creds of that caller and to read/use the keys found therein if the caller was permitted to do so.

Quoted 5 lines

It would be better if the permission indicated the actual operation (e.g. KEY_NEED_INVALIDATE_SPECIAL), and the decision whether to permit CAP_SYS_ADMIN processes to override was left to the security modules. SELinux doesn't automatically allow CAP_SYS_ADMIN processes to do everything.

These individual permissions don't exist yet. I have an ACL patchset that allows me to add a greater range - though there's issues with SELinux there also.

Also, the keyrings are specially marked to say that the sysadmin is allowed to flush them at the moment - but that can go away with the ACL stuff.

Quoted 9 lines

security/selinux/hooks.c static void selinux_key_free(struct key *k) · line 6555

Quoted 6 lines
security/selinux/hooks.c +5 -0
+       switch (need_perm) {
+       case KEY_NEED_UNLINK:
+       case KEY_SYSADMIN_OVERRIDE:
+       case KEY_AUTHTOKEN_OVERRIDE:
+       case KEY_DEFER_PERM_CHECK:
                return 0;

We really shouldn't be skipping any/all checking on CAP_SYS_ADMIN or an AUTHTOKEN; those should still be subject to MAC policy.

I'm not sure how to do that.

Quoted 7 lines

Note that KEY_NEED_UNLINK *must not* be overruled by the MAC policy. The value is only there because lookup_user_key() requires something to be put into that parameter - it's more of a courtesy thing, I suppose.

Why should AUTHTOKEN be subject to MAC policy? The kernel has told the process to go and instantiate a key. It shouldn't really then turn around and tell the process "oh, but you're not actually allowed to do that".

Quoted 5 lines

On what basis did the kernel authorize the process to instantiate the key? At what point did a security module get involved in the decision as to what process(es) are authorize to instantiate a key, particularly for a process with a different credential/security context?

BTW I'm not saying you have to change this patch since IIUC it merely preserves the existing behavior for these special cases. But we will want to address these gaps (or clarify that no real gap exists) in LSM control over key operations going forward.

maintainer
#25 lore raw

PATCH 1/1 keys: Move permissions checking decisions into the checking code

In reply to Stephen Smalley

How about this then?

David
---
commit fa37b6c7e2f86d16ede1e0e3cb73857152d51825

Author: David Howells <[email protected]>
Date:   Thu May 14 17:48:55 2020 +0100

keys: Move permissions checking decisions into the checking code

Overhaul the permissions checking, moving the decisions of which permits to request for what operation and what overrides to allow into the permissions checking functions in keyrings, SELinux and Smack.

To this end, the KEY_NEED_* constants are turned into an enum and expanded in number to cover operation types individually.

Note that some more tweaking is probably needed to separate kernel uses, e.g. AFS using rxrpc keys, from direct userspace users.

Some overrides are available and this needs to be handled specially:

(1) KEY_FLAG_KEEP in key->flags - The key may not be deleted and/or things may not be removed from the keyring.

(2) KEY_FLAG_ROOT_CAN_CLEAR in key->flags - The keyring can be cleared by CAP_SYS_ADMIN.

(3) KEY_FLAG_ROOT_CAN_INVAL in key->flags - The key can be invalidated by CAP_SYS_ADMIN.

(4) An appropriate auth token being set in cred->request_key_auth that gives a process transient permission to view and instantiate a key. This is used by the kernel to delegate instantiation to userspace.

Note that this requires some tweaks to the testsuite as some of the error codes change.

include/linux/key.h +29 -12
index b99b40db08fc..7fb00128c5ba 100644
@@ -71,6 +71,34 @@ struct net;
 
 #define KEY_PERM_UNDEF	0xffffffff
 
+/*
+ * The permissions required on a key that we're looking up.
+ */
+enum key_need_perm {
+	/* 0 is left undefined */
+	KEY_NEED_ASSUME_AUTHORITY = 1,	/* Want to assume instantiation authority */
+	KEY_NEED_CHOWN,			/* Want to change key's ownership/group */
+	KEY_NEED_DESCRIBE,		/* Want to get a key's attributes */
+	KEY_NEED_GET_SECURITY,		/* Want to get a key's security label */
+	KEY_NEED_INSTANTIATE,		/* Want to instantiate a key */
+	KEY_NEED_INVALIDATE,		/* Want to invalidate key */
+	KEY_NEED_JOIN,			/* Want to set a keyring as the session keyring */
+	KEY_NEED_KEYRING_ADD,		/* Want to add a link to a keyring */
+	KEY_NEED_KEYRING_CLEAR,		/* Want to clear a keyring */
+	KEY_NEED_KEYRING_DELETE,	/* Want to remove a link from a keyring */
+	KEY_NEED_LINK,			/* Want to create a link to a key */
+	KEY_NEED_READ,			/* Want to read content to userspace */
+	KEY_NEED_REVOKE,		/* Want to revoke a key */
+	KEY_NEED_SEARCH,		/* Want to find a key in a search */
+	KEY_NEED_SETPERM,		/* Want to set the permissions mask */
+	KEY_NEED_SET_RESTRICTION,	/* Want to set a restriction on a keyring */
+	KEY_NEED_SET_TIMEOUT,		/* Want to set the expiration time on a key */
+	KEY_NEED_UNLINK,		/* Want to remove a link from a key */
+	KEY_NEED_UPDATE,		/* Want to update a key's payload */
+	KEY_NEED_USE,			/* Want to use a key (in kernel) */
+	KEY_NEED_WATCH,			/* Want to watch a key for events */
+};
+
 struct seq_file;
 struct user_struct;
 struct signal_struct;
@@ -420,20 +448,9 @@ static inline key_serial_t key_serial(const struct key *key)
 extern void key_set_timeout(struct key *, unsigned);
 
 extern key_ref_t lookup_user_key(key_serial_t id, unsigned long flags,
-				 key_perm_t perm);
+				 enum key_need_perm need_perm);
 extern void key_free_user_ns(struct user_namespace *);
 
-/*
- * The permissions required on a key that we're looking up.
- */
-#define	KEY_NEED_VIEW	0x01	/* Require permission to view attributes */
-#define	KEY_NEED_READ	0x02	/* Require permission to read content */
-#define	KEY_NEED_WRITE	0x04	/* Require permission to update / modify */
-#define	KEY_NEED_SEARCH	0x08	/* Require permission to search (keyring) or find (key) */
-#define	KEY_NEED_LINK	0x10	/* Require permission to link */
-#define	KEY_NEED_SETATTR 0x20	/* Require permission to change attributes */
-#define	KEY_NEED_ALL	0x3f	/* All the above permissions */
-
 static inline short key_read_state(const struct key *key)
 {
 	/* Barrier versus mark_key_instantiated(). */
include/linux/lsm_hook_defs.h +1 -1
index 733659613bf8..72debb96b002 100644
@@ -357,7 +357,7 @@ LSM_HOOK(int, 0, key_alloc, struct key *key, const struct cred *cred,
 	 unsigned long flags)
 LSM_HOOK(void, LSM_RET_VOID, key_free, struct key *key)
 LSM_HOOK(int, 0, key_permission, key_ref_t key_ref, const struct cred *cred,
-	 unsigned perm)
+	 enum key_need_perm need_perm, unsigned int flags)
 LSM_HOOK(int, 0, key_getsecurity, struct key *key, char **_buffer)
 #endif /* CONFIG_KEYS */
 
include/linux/lsm_hooks.h +8 -0
index 3f1374cffb76..1cb01f6d2bed 100644
@@ -1102,6 +1102,14 @@
  *	@cred points to the credentials to provide the context against which to
  *	evaluate the security data on the key.
  *	@perm describes the combination of permissions required of this key.
+ *	@flags indicates any special conditions set in the normal checks, such
+ *	as:
+ *		KEY_PERMISSION_USED_AUTH_OVERRIDE - A lack of permission was
+ *		overridden by the presence of an instantiation authorisation
+ *		token.
+ *		KEY_PERMISSION_USED_SYSADMIN_OVERRIDE - A lack of permission was
+ *		overridden by the presence of a KEY_FLAG_ROOT_CAN_xxx flag on
+ *		the key an the success of a CAP_SYS_ADMIN check.
  *	Return 0 if permission is granted, -ve error otherwise.
  * @key_getsecurity:
  *	Get a textual representation of the security context attached to a key
include/linux/security.h +8 -3
index e7914e4e0b02..a6a5fefcf4e0 100644
@@ -1762,13 +1762,17 @@ static inline int security_path_chroot(const struct path *path)
 }
 #endif	/* CONFIG_SECURITY_PATH */
 
+/* Flags for security_key_permission() */
+#define KEY_PERMISSION_USED_AUTH_OVERRIDE	0x01 /* Auth token overrode lack of permission */
+#define KEY_PERMISSION_USED_SYSADMIN_OVERRIDE	0x02 /* Sysadmin overrode lack of permission */
+
 #ifdef CONFIG_KEYS
 #ifdef CONFIG_SECURITY
 
 int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags);
 void security_key_free(struct key *key);
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm);
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm, unsigned int flags);
 int security_key_getsecurity(struct key *key, char **_buffer);
 
 #else
@@ -1786,7 +1790,8 @@ static inline void security_key_free(struct key *key)
 
 static inline int security_key_permission(key_ref_t key_ref,
 					  const struct cred *cred,
-					  unsigned perm)
+					  enum key_need_perm need_perm,
+					  unsigned int flags)
 {
 	return 0;
 }
security/keys/dh.c +2 -5
index c4c629bb1c03..e43731d22310 100644
@@ -22,10 +22,8 @@ static ssize_t dh_data_from_key(key_serial_t keyid, void **data)
 	ssize_t ret;
 
 	key_ref = lookup_user_key(keyid, 0, KEY_NEED_READ);
-	if (IS_ERR(key_ref)) {
-		ret = -ENOKEY;
-		goto error;
-	}
+	if (IS_ERR(key_ref))
+		return PTR_ERR(key_ref);
 
 	key = key_ref_to_ptr(key_ref);
 
@@ -52,7 +50,6 @@ static ssize_t dh_data_from_key(key_serial_t keyid, void **data)
 	}
 
 	key_put(key);
-error:
 	return ret;
 }
 
security/keys/internal.h +15 -6
index 28e17f4f3328..d97cb9d98dc3 100644
@@ -108,6 +108,14 @@ extern void __key_link_end(struct key *keyring,
 
 extern key_ref_t find_key_to_update(key_ref_t keyring_ref,
 				    const struct keyring_index_key *index_key);
+extern key_ref_t key_create_or_update_perm_checked(key_ref_t keyring_ref,
+						   const char *type,
+						   const char *description,
+						   const void *payload,
+						   size_t plen,
+						   key_perm_t perm,
+						   unsigned long flags);
+extern int key_update_perm_checked(key_ref_t key_ref, const void *payload, size_t plen);
 
 extern struct key *keyring_search_instkey(struct key *keyring,
 					  key_serial_t target_id);
@@ -165,9 +173,9 @@ extern struct key *request_key_and_link(struct key_type *type,
 
 extern bool lookup_user_key_possessed(const struct key *key,
 				      const struct key_match_data *match_data);
-#define KEY_LOOKUP_CREATE	0x01
-#define KEY_LOOKUP_PARTIAL	0x02
-#define KEY_LOOKUP_FOR_UNLINK	0x04
+#define KEY_LOOKUP_CREATE		0x01
+#define KEY_LOOKUP_PARTIAL		0x02
+#define KEY_LOOKUP_AUTH_OVERRIDE	0x04
 
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
@@ -183,7 +191,7 @@ extern void key_gc_keytype(struct key_type *ktype);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
-			       key_perm_t perm);
+			       enum key_need_perm need_perm);
 
 static inline void notify_key(struct key *key,
 			      enum key_notification_subtype subtype, u32 aux)
@@ -205,9 +213,10 @@ static inline void notify_key(struct key *key,
 /*
  * Check to see whether permission is granted to use a key in the desired way.
  */
-static inline int key_permission(const key_ref_t key_ref, unsigned perm)
+static inline int key_permission(const key_ref_t key_ref,
+				 enum key_need_perm need_perm)
 {
-	return key_task_permission(key_ref, current_cred(), perm);
+	return key_task_permission(key_ref, current_cred(), need_perm);
 }
 
 extern struct key_type key_type_request_key_auth;
security/keys/key.c +44 -24

109 lines not on this page · raw message

security/keys/keyctl.c +123 -250

662 lines not on this page · raw message

security/keys/keyctl_pkey.c +10 -7
index 931d8dfb4a7f..aece0651eeae 100644
@@ -77,7 +77,8 @@ static int keyctl_pkey_params_parse(struct kernel_pkey_params *params)
  */
 static int keyctl_pkey_params_get(key_serial_t id,
 				  const char __user *_info,
-				  struct kernel_pkey_params *params)
+				  struct kernel_pkey_params *params,
+				  enum key_need_perm need_perm)
 {
 	key_ref_t key_ref;
 	void *p;
@@ -95,7 +96,7 @@ static int keyctl_pkey_params_get(key_serial_t id,
 	if (ret < 0)
 		return ret;
 
-	key_ref = lookup_user_key(id, 0, KEY_NEED_SEARCH);
+	key_ref = lookup_user_key(id, 0, need_perm);
 	if (IS_ERR(key_ref))
 		return PTR_ERR(key_ref);
 	params->key = key_ref_to_ptr(key_ref);
@@ -113,7 +114,8 @@ static int keyctl_pkey_params_get(key_serial_t id,
 static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_params,
 				    const char __user *_info,
 				    int op,
-				    struct kernel_pkey_params *params)
+				    struct kernel_pkey_params *params,
+				    enum key_need_perm need_perm)
 {
 	struct keyctl_pkey_params uparams;
 	struct kernel_pkey_query info;
@@ -125,7 +127,7 @@ static int keyctl_pkey_params_get_2(const struct keyctl_pkey_params __user *_par
 	if (copy_from_user(&uparams, _params, sizeof(uparams)) != 0)
 		return -EFAULT;
 
-	ret = keyctl_pkey_params_get(uparams.key_id, _info, params);
+	ret = keyctl_pkey_params_get(uparams.key_id, _info, params, need_perm);
 	if (ret < 0)
 		return ret;
 
@@ -168,7 +170,7 @@ long keyctl_pkey_query(key_serial_t id,
 
 	memset(&params, 0, sizeof(params));
 
-	ret = keyctl_pkey_params_get(id, _info, &params);
+	ret = keyctl_pkey_params_get(id, _info, &params, KEY_NEED_DESCRIBE);
 	if (ret < 0)
 		goto error;
 
@@ -213,7 +215,8 @@ long keyctl_pkey_e_d_s(int op,
 	void *in, *out;
 	long ret;
 
-	ret = keyctl_pkey_params_get_2(_params, _info, op, &params);
+	ret = keyctl_pkey_params_get_2(_params, _info, op, &params,
+				       KEY_NEED_USE);
 	if (ret < 0)
 		goto error_params;
 
@@ -289,7 +292,7 @@ long keyctl_pkey_verify(const struct keyctl_pkey_params __user *_params,
 	long ret;
 
 	ret = keyctl_pkey_params_get_2(_params, _info, KEYCTL_PKEY_VERIFY,
-				       &params);
+				       &params, KEY_NEED_USE);
 	if (ret < 0)
 		goto error_params;
 
security/keys/keyring.c +1 -1
index 14abfe765b7e..6199efbe19b4 100644
@@ -1167,7 +1167,7 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
 				continue;
 		} else {
 			if (key_permission(make_key_ref(keyring, 0),
-					   KEY_NEED_SEARCH) < 0)
+					   KEY_NEED_JOIN) < 0)
 				continue;
 		}
 
security/keys/permission.c +114 -9

154 lines not on this page · raw message

security/keys/persistent.c +1 -1
index 97af230aa4b2..6131a1528680 100644
@@ -151,7 +151,7 @@ long keyctl_get_persistent(uid_t _uid, key_serial_t destid)
 	}
 
 	/* There must be a destination keyring */
-	dest_ref = lookup_user_key(destid, KEY_LOOKUP_CREATE, KEY_NEED_WRITE);
+	dest_ref = lookup_user_key(destid, KEY_LOOKUP_CREATE, KEY_NEED_KEYRING_ADD);
 	if (IS_ERR(dest_ref))
 		return PTR_ERR(dest_ref);
 	if (key_ref_to_ptr(dest_ref)->type != &key_type_keyring) {
security/keys/proc.c +1 -1
index d0cde6685627..373e62556fa5 100644
@@ -188,7 +188,7 @@ static int proc_keys_show(struct seq_file *m, void *v)
 	}
 
 	/* check whether the current task is allowed to view the key */
-	rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
+	rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_DESCRIBE);
 	if (rc < 0)
 		return 0;
 
security/keys/process_keys.c +13 -24
index 09541de31f2f..e39d9033c34c 100644
@@ -609,7 +609,7 @@ bool lookup_user_key_possessed(const struct key *key,
  * returned key reference.
  */
 key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
-			  key_perm_t perm)
+			  enum key_need_perm need_perm)
 {
 	struct keyring_search_context ctx = {
 		.match_data.cmp		= lookup_user_key_possessed,
@@ -773,35 +773,24 @@ key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
 
 	/* unlink does not use the nominated key in any way, so can skip all
 	 * the permission checks as it is only concerned with the keyring */
-	if (lflags & KEY_LOOKUP_FOR_UNLINK) {
-		ret = 0;
-		goto error;
-	}
+	if (need_perm != KEY_NEED_UNLINK) {
+		if (!(lflags & KEY_LOOKUP_PARTIAL)) {
+			ret = wait_for_key_construction(key, true);
+			if (ret < 0)
+				goto invalid_key;
 
-	if (!(lflags & KEY_LOOKUP_PARTIAL)) {
-		ret = wait_for_key_construction(key, true);
-		switch (ret) {
-		case -ERESTARTSYS:
-			goto invalid_key;
-		default:
-			if (perm)
+			ret = -EIO;
+			if (key_read_state(key) == KEY_IS_UNINSTANTIATED)
+				goto invalid_key;
+		} else {
+			ret = key_validate(key);
+			if (ret < 0)
 				goto invalid_key;
-		case 0:
-			break;
 		}
-	} else if (perm) {
-		ret = key_validate(key);
-		if (ret < 0)
-			goto invalid_key;
 	}
 
-	ret = -EIO;
-	if (!(lflags & KEY_LOOKUP_PARTIAL) &&
-	    key_read_state(key) == KEY_IS_UNINSTANTIATED)
-		goto invalid_key;
-
 	/* check the permissions */
-	ret = key_task_permission(key_ref, ctx.cred, perm);
+	ret = key_task_permission(key_ref, ctx.cred, need_perm);
 	if (ret < 0)
 		goto invalid_key;
 
security/keys/request_key.c +5 -5
index e1b9f1a80676..c835b7407a5f 100644
@@ -332,10 +332,10 @@ static int construct_get_dest_keyring(struct key **_dest_keyring)
 			BUG();
 		}
 
-		/*
-		 * Require Write permission on the keyring.  This is essential
-		 * because the default keyring may be the session keyring, and
-		 * joining a keyring only requires Search permission.
+		/* Require permission to add a link to the keyring.  This is
+		 * essential because the default keyring may be the session
+		 * keyring, and joining a keyring only requires Search
+		 * permission.
 		 *
 		 * However, this check is skipped for the "requestor keyring" so
 		 * that /sbin/request-key can itself use request_key() to add
@@ -343,7 +343,7 @@ static int construct_get_dest_keyring(struct key **_dest_keyring)
 		 */
 		if (dest_keyring && do_perm_check) {
 			ret = key_permission(make_key_ref(dest_keyring, 1),
-					     KEY_NEED_WRITE);
+					     KEY_NEED_KEYRING_ADD);
 			if (ret) {
 				key_put(dest_keyring);
 				return ret;
security/keys/request_key_auth.c +7 -0
index 41e9735006d0..588130b631b8 100644
@@ -258,6 +258,7 @@ struct key *key_get_instantiation_authkey(key_serial_t target_id)
 	};
 	struct key *authkey;
 	key_ref_t authkey_ref;
+	int ret;
 
 	ctx.index_key.desc_len = sprintf(description, "%x", target_id);
 
@@ -272,6 +273,12 @@ struct key *key_get_instantiation_authkey(key_serial_t target_id)
 		goto error;
 	}
 
+	ret = key_permission(authkey_ref, KEY_NEED_ASSUME_AUTHORITY);
+	if (ret < 0) {
+		key_ref_put(authkey_ref);
+		authkey = ERR_PTR(ret);
+	}
+
 	authkey = key_ref_to_ptr(authkey_ref);
 	if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) {
 		key_put(authkey);
security/security.c +3 -3
index c73334ab2882..e5e2200796f7 100644
@@ -2398,10 +2398,10 @@ void security_key_free(struct key *key)
 	call_void_hook(key_free, key);
 }
 
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm)
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm, unsigned int flags)
 {
-	return call_int_hook(key_permission, 0, key_ref, cred, perm);
+	return call_int_hook(key_permission, 0, key_ref, cred, need_perm, flags);
 }
 
 int security_key_getsecurity(struct key *key, char **_buffer)
security/selinux/hooks.c +130 -12

163 lines not on this page · raw message

security/smack/smack_lsm.c +69 -12

110 lines not on this page · raw message

maintainer
#26 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

Quoted 38 lines · David Howells

How about this then?

David
---
commit fa37b6c7e2f86d16ede1e0e3cb73857152d51825

Author: David Howells <[email protected]>
Date:   Thu May 14 17:48:55 2020 +0100

keys: Move permissions checking decisions into the checking code

Overhaul the permissions checking, moving the decisions of which permits to request for what operation and what overrides to allow into the permissions checking functions in keyrings, SELinux and Smack.

To this end, the KEY_NEED_* constants are turned into an enum and expanded in number to cover operation types individually.

Note that some more tweaking is probably needed to separate kernel uses, e.g. AFS using rxrpc keys, from direct userspace users.

Some overrides are available and this needs to be handled specially:

(1) KEY_FLAG_KEEP in key->flags - The key may not be deleted and/or things may not be removed from the keyring.

(2) KEY_FLAG_ROOT_CAN_CLEAR in key->flags - The keyring can be cleared by CAP_SYS_ADMIN.

(3) KEY_FLAG_ROOT_CAN_INVAL in key->flags - The key can be invalidated by CAP_SYS_ADMIN.

(4) An appropriate auth token being set in cred->request_key_auth that gives a process transient permission to view and instantiate a key. This is used by the kernel to delegate instantiation to userspace.

Note that this requires some tweaks to the testsuite as some of the error codes change.

Quoted 9 lines

<snip> ...

Quoted 107 lines
security/smack/smack_lsm.c +68 -8
index 8c61d175e195..ac9c93c48097 100644
@@ -4230,13 +4230,15 @@ static void smack_key_free(struct key *key)
  * smack_key_permission - Smack access on a key
  * @key_ref: gets to the object
  * @cred: the credentials to use
- * @perm: requested key permissions
+ * @need_perm: requested key permission
  *
  * Return 0 if the task has read and write to the object,
  * an error code otherwise
  */
 static int smack_key_permission(key_ref_t key_ref,
-				const struct cred *cred, unsigned perm)
+				const struct cred *cred,
+				enum key_need_perm need_perm,
+				unsigned int flags)
 {
 	struct key *keyp;
 	struct smk_audit_info ad;
@@ -4244,12 +4246,6 @@ static int smack_key_permission(key_ref_t key_ref,
 	int request = 0;
 	int rc;
 
-	/*
-	 * Validate requested permissions
-	 */
-	if (perm & ~KEY_NEED_ALL)
-		return -EINVAL;
-
 	keyp = key_ref_to_ptr(key_ref);
 	if (keyp = NULL)
 		return -EINVAL;
@@ -4265,6 +4261,71 @@ static int smack_key_permission(key_ref_t key_ref,
 	if (tkp = NULL)
 		return -EACCES;
 
+	/*
+	 * Validate requested permissions
+	 */
+	switch (need_perm) {
+	case KEY_NEED_ASSUME_AUTHORITY:
+		return 0;
+
+	case KEY_NEED_DESCRIBE:
+	case KEY_NEED_GET_SECURITY:
+		request |= MAY_READ;
+		auth_can_override = true;
+		break;
+
+	case KEY_NEED_CHOWN:
+	case KEY_NEED_INVALIDATE:
+	case KEY_NEED_JOIN:
+	case KEY_NEED_LINK:
+	case KEY_NEED_KEYRING_ADD:
+	case KEY_NEED_KEYRING_CLEAR:
+	case KEY_NEED_KEYRING_DELETE:
+	case KEY_NEED_REVOKE:
+	case KEY_NEED_SETPERM:
+	case KEY_NEED_SET_RESTRICTION:
+	case KEY_NEED_UPDATE:
+		request |= MAY_WRITE;
+		break;
+
+	case KEY_NEED_INSTANTIATE:
+		auth_can_override = true;
+		break;
+
+	case KEY_NEED_READ:
+	case KEY_NEED_SEARCH:
+	case KEY_NEED_USE:
+	case KEY_NEED_WATCH:
+		request |= MAY_READ;
+		break;
+
+	case KEY_NEED_SET_TIMEOUT:
+		request |= MAY_WRITE;
+		auth_can_override = true;
+		break;
+
+	case KEY_NEED_UNLINK:
+		return 0; /* Mustn't prevent this; KEY_FLAG_KEEP is already
+			   * dealt with. */
+
+	default:
+		WARN_ON(1);
+		return -EINVAL;
+	}
+
+	/* Just allow the operation if the process has an authorisation token.
+	 * The presence of the token means that the kernel delegated
+	 * instantiation of a key to the process - which is problematic if we
+	 * then say that the process isn't allowed to get the description of
+	 * the key or actually instantiate it.
+	 */
+	if (auth_can_override && cred->request_key_auth) {
+		struct request_key_auth *rka > +			cred->request_key_auth->payload.data[0];
+		if (rka->target_key = key)
+			*_perm = 0;
+	}
+
 	if (smack_privileged_cred(CAP_MAC_OVERRIDE, cred))
 		return 0;
 

security/smack/smack_lsm.c static int smack_key_permission(key_ref_t key_ref, · line 4339

Quoted 10 lines
security/smack/smack_lsm.c +0 -4
@@ -4273,10 +4334,6 @@ static int smack_key_permission(key_ref_t key_ref,
 	ad.a.u.key_struct.key = keyp->serial;
 	ad.a.u.key_struct.key_desc = keyp->description;
 #endif
-	if (perm & (KEY_NEED_READ | KEY_NEED_SEARCH | KEY_NEED_VIEW))
-		request |= MAY_READ;
-	if (perm & (KEY_NEED_WRITE | KEY_NEED_LINK | KEY_NEED_SETATTR))
-		request |= MAY_WRITE;
 	rc = smk_access(tkp, keyp->security, request, &ad);
 	rc = smk_bu_note("key access", tkp, keyp->security, request, rc);
 	return rc;

Better. Thank you.

maintainer
#27 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

In reply to David Howells
Quoted 18 lines · David Howells

How about this then?

David
---
commit fa37b6c7e2f86d16ede1e0e3cb73857152d51825

Author: David Howells <[email protected]>
Date:   Thu May 14 17:48:55 2020 +0100

keys: Move permissions checking decisions into the checking code

Overhaul the permissions checking, moving the decisions of which permits to request for what operation and what overrides to allow into the permissions checking functions in keyrings, SELinux and Smack.

To this end, the KEY_NEED_* constants are turned into an enum and expanded in number to cover operation types individually.

Quoted 7 lines

Note that some more tweaking is probably needed to separate kernel uses, e.g. AFS using rxrpc keys, from direct userspace users.

Some overrides are available and this needs to be handled specially:

(1) KEY_FLAG_KEEP in key->flags - The key may not be deleted and/or things may not be removed from the keyring.

Why can't they be deleted / removed? They can't ever be deleted or removed or for some period of time?

Quoted 2 lines
     (2) KEY_FLAG_ROOT_CAN_CLEAR in key->flags - The keyring can be cleared by
         CAP_SYS_ADMIN.

Why do some keyrings get this flag and others do not? Under what conditions? Why is CAP_SYS_ADMIN the right capability for this?

Quoted 2 lines
     (3) KEY_FLAG_ROOT_CAN_INVAL in key->flags - The key can be invalidated by
         CAP_SYS_ADMIN.

Ditto.

Quoted 3 lines

(4) An appropriate auth token being set in cred->request_key_auth that gives a process transient permission to view and instantiate a key. This is used by the kernel to delegate instantiation to userspace.

Is this ever allowed across different credentials? When? Why? Is there a check between the different credentials before the auth token is created?

Quoted 2 lines

Note that this requires some tweaks to the testsuite as some of the error codes change.

Which testsuite? keyring or selinux or both? What error codes change (from what to what)? Does this constitute an ABI change?

I like moving more of the permission checking logic into the security modules and giving them greater visibility and control. That said, I am somewhat concerned by the scale of this change, by the extent to which you are exposing keyring internals inside the security modules, and by the extent to which logic is getting duplicated in each security module. I'd suggest a more incremental approach, e.g. start with just the enum patch, then migrate the easy cases, then consider the more complicated cases. And possibly we need multiple different security hooks for the keyring subsystem that are more specialized for the complicated cases. If we authorize the delegation up front, we don't need to check it later.

maintainer
#28 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

Quoted 5 lines · Stephen Smalley
Quoted 2 lines

(1) KEY_FLAG_KEEP in key->flags - The key may not be deleted and/or things may not be removed from the keyring.

Why can't they be deleted / removed? They can't ever be deleted or removed or for some period of time?

This is only settable internally to keep special keys, such as the blacklist loaded from the EFI BIOS, from being removed.

Quoted 10 lines
Quoted 2 lines
     (2) KEY_FLAG_ROOT_CAN_CLEAR in key->flags - The keyring can be cleared by
         CAP_SYS_ADMIN.

Why do some keyrings get this flag and others do not? Under what conditions? Why is CAP_SYS_ADMIN the right capability for this?

Quoted 2 lines
     (3) KEY_FLAG_ROOT_CAN_INVAL in key->flags - The key can be invalidated by
         CAP_SYS_ADMIN.

Ditto.

So that the sysadmin can clear, say, the NFS idmapper keyring or invalidate DNS lookup keys.

Quoted 5 lines
Quoted 3 lines

(4) An appropriate auth token being set in cred->request_key_auth that gives a process transient permission to view and instantiate a key. This is used by the kernel to delegate instantiation to userspace.

Is this ever allowed across different credentials?

The kernel upcalls by spawning a daemon. I want to change this as it's not compatible with containers since namespaces make this problematic.

Quoted 1 line

When?

The request_key() system call will do this. The normal use case is something like the AFS filesystem asking for a key so that it can do an operation. The possibility exists for the kernel to upcall, say, to something that does aklog on behalf of the user - but aklog in turn needs to get the TGT out of the keyrings.

Quoted 2 lines

Why? Is there a check between the different credentials before the auth token is created?

No. I don't even know what the target creds will necessarily be at this point.

Quoted 4 lines
Quoted 2 lines

Note that this requires some tweaks to the testsuite as some of the error codes change.

Which testsuite? keyring or selinux or both?

The keyring testsuite. No idea about the SELinux one.

Quoted 2 lines

What error codes change (from what to what)? Does this constitute an ABI change?

The following:

(1) Passing the wrong type of key to KEYCTL_DH_COMPUTE now gets you EOPNOTSUPP rather than ENOKEY. This is now as documented in the manual page.

(2) Passing key ID 0 or an invalid negative key ID to KEYCTL_DH_COMPUTE now gets you EINVAL rather than ENOKEY.

(3) Passing key ID 0 or an invalid negative key ID to KEYCTL_READ now gets you EINVAL rather than ENOKEY.

Technically, it consistutes an ABI change, I suppose, but I think it is probably sufficiently minor.

Or maybe on (2) and (3) I should go the other way. You get ENOKEY for invalid key IDs (such as 0 or unsupported negative ones) across all callers of lookup_user_key(). This would at least by consistent with the manual pages.

Quoted 6 lines

I like moving more of the permission checking logic into the security modules and giving them greater visibility and control. That said, I am somewhat concerned by the scale of this change, by the extent to which you are exposing keyring internals inside the security modules, and by the extent to which logic is getting duplicated in each security module.

It's what you asked for.

Now, I don't know if the LSM needs to know that the main keyutils permissions checker invoked an override. At least one of the overrides will have gone through the LSM anyway when capable() was called.

Quoted 5 lines

I'd suggest a more incremental approach, e.g. start with just the enum patch, then migrate the easy cases, then consider the more complicated cases. And possibly we need multiple different security hooks for the keyring subsystem that are more specialized for the complicated cases. If we authorize the delegation up front, we don't need to check it later.

I'll consider it. But I really need to get what I'm going to include in the middle of the notifications patchset sorted now - or risk the notifications and fsinfo patchsets getting bumped again.

Maybe what's needed is a pair of hooks whereby the call to capable() is replaced with LSM hook specifically to ask about the overrides:

	security_key_use_sysadmin_override(key, cred);
	security_key_use_construction_override(key, cred);

And/or a hook to ask whether the process is allowed to do the request_key() call that they want:

security_request_key(struct key_type *type,
const char *description, struct key_tag *domain_tag, const void *callout_info, size_t callout_len, void *aux);

I don't really want to do a "can the kernel delegate to process X?" hook just at the moment, since I want to change/extend that code and I don't want to commit to any particular security information being present yet.

I can go back to the enum patch for the moment if you and Casey can put up with that for the moment?

David

maintainer
#29 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

Quoted 2 lines · David Howells

I can go back to the enum patch for the moment if you and Casey can put up with that for the moment?

Yes, let's do that.

maintainer
#30 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

Quoted 4 lines · Stephen Smalley
Quoted 2 lines · David Howells

I can go back to the enum patch for the moment if you and Casey can put up with that for the moment?

Yes, let's do that.

OK by me.

maintainer
#31 lore raw

Re: [PATCH] keys: Move permissions checking decisions into the checking code

In reply to Stephen Smalley
Quoted 4 lines · Stephen Smalley
Quoted 2 lines

I can go back to the enum patch for the moment if you and Casey can put up with that for the moment?

Yes, let's do that.

Okay. I'll use the attached. I've added a note into the commit message to indicate what should be done in future. I won't put the other patch into my keys-next branch yet as it will conflict with this.

David
---
commit e9c98329b2201e6df4edb34dc386e6ef1eeeb78b

Author: David Howells <[email protected]>
Date:   Tue May 12 15:16:29 2020 +0100

keys: Make the KEY_NEED_* perms an enum rather than a mask

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

(4) An override due to an instantiation token being present.

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.

[Note: This really needs overhauling so that lookup_user_key() tells
key_task_permission() and the LSM what operation is being done and leaves it to those functions to decide how to map that onto the available permits. However, I don't really want to make these change in the middle of the notifications patchset.]

cc Jarkko Sakkinen <[email protected]>
cc Paul Moore <[email protected]>
cc Stephen Smalley <[email protected]>
cc Casey Schaufler <[email protected]>
include/linux/key.h +18 -12
index b99b40db08fc..0f2e24f13c2b 100644
@@ -71,6 +71,23 @@ struct net;
 
 #define KEY_PERM_UNDEF	0xffffffff
 
+/*
+ * The permissions required on a key that we're looking up.
+ */
+enum key_need_perm {
+	KEY_NEED_UNSPECIFIED,	/* Needed permission unspecified */
+	KEY_NEED_VIEW,		/* Require permission to view attributes */
+	KEY_NEED_READ,		/* Require permission to read content */
+	KEY_NEED_WRITE,		/* Require permission to update / modify */
+	KEY_NEED_SEARCH,	/* Require permission to search (keyring) or find (key) */
+	KEY_NEED_LINK,		/* Require permission to link */
+	KEY_NEED_SETATTR,	/* Require permission to change attributes */
+	KEY_NEED_UNLINK,	/* Require permission to unlink key */
+	KEY_SYSADMIN_OVERRIDE,	/* Special: override by CAP_SYS_ADMIN */
+	KEY_AUTHTOKEN_OVERRIDE,	/* Special: override by possession of auth token */
+	KEY_DEFER_PERM_CHECK,	/* Special: permission check is deferred */
+};
+
 struct seq_file;
 struct user_struct;
 struct signal_struct;
@@ -420,20 +437,9 @@ static inline key_serial_t key_serial(const struct key *key)
 extern void key_set_timeout(struct key *, unsigned);
 
 extern key_ref_t lookup_user_key(key_serial_t id, unsigned long flags,
-				 key_perm_t perm);
+				 enum key_need_perm need_perm);
 extern void key_free_user_ns(struct user_namespace *);
 
-/*
- * The permissions required on a key that we're looking up.
- */
-#define	KEY_NEED_VIEW	0x01	/* Require permission to view attributes */
-#define	KEY_NEED_READ	0x02	/* Require permission to read content */
-#define	KEY_NEED_WRITE	0x04	/* Require permission to update / modify */
-#define	KEY_NEED_SEARCH	0x08	/* Require permission to search (keyring) or find (key) */
-#define	KEY_NEED_LINK	0x10	/* Require permission to link */
-#define	KEY_NEED_SETATTR 0x20	/* Require permission to change attributes */
-#define	KEY_NEED_ALL	0x3f	/* All the above permissions */
-
 static inline short key_read_state(const struct key *key)
 {
 	/* Barrier versus mark_key_instantiated(). */
include/linux/security.h +3 -3
index e7914e4e0b02..57aac14e3418 100644
@@ -1767,8 +1767,8 @@ static inline int security_path_chroot(const struct path *path)
 
 int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags);
 void security_key_free(struct key *key);
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm);
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm);
 int security_key_getsecurity(struct key *key, char **_buffer);
 
 #else
@@ -1786,7 +1786,7 @@ static inline void security_key_free(struct key *key)
 
 static inline int security_key_permission(key_ref_t key_ref,
 					  const struct cred *cred,
-					  unsigned perm)
+					  enum key_need_perm need_perm)
 {
 	return 0;
 }
security/keys/internal.h +4 -4
index 28e17f4f3328..1fc17cb317a9 100644
@@ -167,7 +167,6 @@ extern bool lookup_user_key_possessed(const struct key *key,
 				      const struct key_match_data *match_data);
 #define KEY_LOOKUP_CREATE	0x01
 #define KEY_LOOKUP_PARTIAL	0x02
-#define KEY_LOOKUP_FOR_UNLINK	0x04
 
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
@@ -183,7 +182,7 @@ extern void key_gc_keytype(struct key_type *ktype);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
-			       key_perm_t perm);
+			       enum key_need_perm need_perm);
 
 static inline void notify_key(struct key *key,
 			      enum key_notification_subtype subtype, u32 aux)
@@ -205,9 +204,10 @@ static inline void notify_key(struct key *key,
 /*
  * Check to see whether permission is granted to use a key in the desired way.
  */
-static inline int key_permission(const key_ref_t key_ref, unsigned perm)
+static inline int key_permission(const key_ref_t key_ref,
+				 enum key_need_perm need_perm)
 {
-	return key_task_permission(key_ref, current_cred(), perm);
+	return key_task_permission(key_ref, current_cred(), need_perm);
 }
 
 extern struct key_type key_type_request_key_auth;
security/keys/keyctl.c +9 -7
index 7d8de1c9a478..6763ee45e04d 100644
@@ -434,7 +434,7 @@ long keyctl_invalidate_key(key_serial_t id)
 
 		/* Root is permitted to invalidate certain special keys */
 		if (capable(CAP_SYS_ADMIN)) {
-			key_ref = lookup_user_key(id, 0, 0);
+			key_ref = lookup_user_key(id, 0, KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(key_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_INVAL,
@@ -479,7 +479,8 @@ long keyctl_keyring_clear(key_serial_t ringid)
 
 		/* Root is permitted to invalidate certain special keyrings */
 		if (capable(CAP_SYS_ADMIN)) {
-			keyring_ref = lookup_user_key(ringid, 0, 0);
+			keyring_ref = lookup_user_key(ringid, 0,
+						      KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(keyring_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR,
@@ -563,7 +564,7 @@ long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
 		goto error;
 	}
 
-	key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0);
+	key_ref = lookup_user_key(id, KEY_LOOKUP_PARTIAL, KEY_NEED_UNLINK);
 	if (IS_ERR(key_ref)) {
 		ret = PTR_ERR(key_ref);
 		goto error2;
@@ -663,7 +664,7 @@ long keyctl_describe_key(key_serial_t keyid,
 				key_put(instkey);
 				key_ref = lookup_user_key(keyid,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -833,7 +834,7 @@ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
 	size_t key_data_len;
 
 	/* find the key first */
-	key_ref = lookup_user_key(keyid, 0, 0);
+	key_ref = lookup_user_key(keyid, 0, KEY_DEFER_PERM_CHECK);
 	if (IS_ERR(key_ref)) {
 		ret = -ENOKEY;
 		goto out;
@@ -1471,7 +1472,7 @@ long keyctl_set_timeout(key_serial_t id, unsigned timeout)
 				key_put(instkey);
 				key_ref = lookup_user_key(id,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -1579,7 +1580,8 @@ long keyctl_get_security(key_serial_t keyid,
 			return PTR_ERR(instkey);
 		key_put(instkey);
 
-		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
+		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL,
+					  KEY_AUTHTOKEN_OVERRIDE);
 		if (IS_ERR(key_ref))
 			return PTR_ERR(key_ref);
 	}
security/keys/permission.c +24 -7
index 085f907b64ac..4a61f804e80f 100644
@@ -13,7 +13,7 @@
  * key_task_permission - Check a key can be used
  * @key_ref: The key to check.
  * @cred: The credentials to use.
- * @perm: The permissions to check for.
+ * @need_perm: The permission required.
  *
  * Check to see whether permission is granted to use a key in the desired way,
  * but permit the security modules to override.
@@ -24,12 +24,30 @@
  * permissions bits or the LSM check.
  */
 int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
-			unsigned perm)
+			enum key_need_perm need_perm)
 {
 	struct key *key;
-	key_perm_t kperm;
+	key_perm_t kperm, mask;
 	int ret;
 
+	switch (need_perm) {
+	default:
+		WARN_ON(1);
+		return -EACCES;
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		goto lsm;
+
+	case KEY_NEED_VIEW:	mask = KEY_OTH_VIEW;	break;
+	case KEY_NEED_READ:	mask = KEY_OTH_READ;	break;
+	case KEY_NEED_WRITE:	mask = KEY_OTH_WRITE;	break;
+	case KEY_NEED_SEARCH:	mask = KEY_OTH_SEARCH;	break;
+	case KEY_NEED_LINK:	mask = KEY_OTH_LINK;	break;
+	case KEY_NEED_SETATTR:	mask = KEY_OTH_SETATTR;	break;
+	}
+
 	key = key_ref_to_ptr(key_ref);
 
 	/* use the second 8-bits of permissions for keys the caller owns */
@@ -64,13 +82,12 @@ int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
 	if (is_key_possessed(key_ref))
 		kperm |= key->perm >> 24;
 
-	kperm = kperm & perm & KEY_NEED_ALL;
-
-	if (kperm != perm)
+	if ((kperm & mask) != mask)
 		return -EACCES;
 
 	/* let LSM be the final arbiter */
-	return security_key_permission(key_ref, cred, perm);
+lsm:
+	return security_key_permission(key_ref, cred, need_perm);
 }
 EXPORT_SYMBOL(key_task_permission);
 
security/keys/process_keys.c +22 -24

64 lines not on this page · raw message

security/security.c +3 -3
index c73334ab2882..af32d4cd0462 100644
@@ -2398,10 +2398,10 @@ void security_key_free(struct key *key)
 	call_void_hook(key_free, key);
 }
 
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm)
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm)
 {
-	return call_int_hook(key_permission, 0, key_ref, cred, perm);
+	return call_int_hook(key_permission, 0, key_ref, cred, need_perm);
 }
 
 int security_key_getsecurity(struct key *key, char **_buffer)
security/selinux/hooks.c +30 -7
index 0b4e32161b77..0de048705f0e 100644
@@ -6541,20 +6541,43 @@ static void selinux_key_free(struct key *k)
 
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  enum key_need_perm need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
-	u32 sid;
+	u32 perm, sid;
 
-	/* if no specific permissions are requested, we skip the
-	   permission check. No serious, additional covert channels
-	   appear to be created. */
-	if (perm == 0)
+	switch (need_perm) {
+	case KEY_NEED_VIEW:
+		perm = KEY__VIEW;
+		break;
+	case KEY_NEED_READ:
+		perm = KEY__READ;
+		break;
+	case KEY_NEED_WRITE:
+		perm = KEY__WRITE;
+		break;
+	case KEY_NEED_SEARCH:
+		perm = KEY__SEARCH;
+		break;
+	case KEY_NEED_LINK:
+		perm = KEY__LINK;
+		break;
+	case KEY_NEED_SETATTR:
+		perm = KEY__SETATTR;
+		break;
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
 		return 0;
+	default:
+		WARN_ON(1);
+		return -EPERM;
 
-	sid = cred_sid(cred);
+	}
 
+	sid = cred_sid(cred);
 	key = key_ref_to_ptr(key_ref);
 	ksec = key->security;
 
security/smack/smack_lsm.c +22 -7
index 8c61d175e195..0d6bb53efe74 100644
@@ -4230,13 +4230,14 @@ static void smack_key_free(struct key *key)
  * smack_key_permission - Smack access on a key
  * @key_ref: gets to the object
  * @cred: the credentials to use
- * @perm: requested key permissions
+ * @need_perm: requested key permission
  *
  * Return 0 if the task has read and write to the object,
  * an error code otherwise
  */
 static int smack_key_permission(key_ref_t key_ref,
-				const struct cred *cred, unsigned perm)
+				const struct cred *cred,
+				enum key_need_perm need_perm)
 {
 	struct key *keyp;
 	struct smk_audit_info ad;
@@ -4247,8 +4248,26 @@ static int smack_key_permission(key_ref_t key_ref,
 	/*
 	 * Validate requested permissions
 	 */
-	if (perm & ~KEY_NEED_ALL)
+	switch (need_perm) {
+	case KEY_NEED_READ:
+	case KEY_NEED_SEARCH:
+	case KEY_NEED_VIEW:
+		request |= MAY_READ;
+		break;
+	case KEY_NEED_WRITE:
+	case KEY_NEED_LINK:
+	case KEY_NEED_SETATTR:
+		request |= MAY_WRITE;
+		break;
+	case KEY_NEED_UNSPECIFIED:
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		return 0;
+	default:
 		return -EINVAL;
+	}
 
 	keyp = key_ref_to_ptr(key_ref);
 	if (keyp == NULL)
@@ -4273,10 +4292,6 @@ static int smack_key_permission(key_ref_t key_ref,
 	ad.a.u.key_struct.key = keyp->serial;
 	ad.a.u.key_struct.key_desc = keyp->description;
 #endif
-	if (perm & (KEY_NEED_READ | KEY_NEED_SEARCH | KEY_NEED_VIEW))
-		request |= MAY_READ;
-	if (perm & (KEY_NEED_WRITE | KEY_NEED_LINK | KEY_NEED_SETATTR))
-		request |= MAY_WRITE;
 	rc = smk_access(tkp, keyp->security, request, &ad);
 	rc = smk_bu_note("key access", tkp, keyp->security, request, rc);
 	return rc;
maintainer
#32 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

In reply to David Howells
Quoted 434 lines · David Howells

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

(4) An override due to an instantiation token being present.

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.

cc Jarkko Sakkinen <[email protected]>
cc Paul Moore <[email protected]>
cc Stephen Smalley <[email protected]>
cc Casey Schaufler <[email protected]>

---

 include/linux/key.h          |   30 ++++++++++++++++-----------
 include/linux/security.h     |    6 +++--
 security/keys/internal.h     |    8 ++++---
 security/keys/keyctl.c       |   16 ++++++++-------
 security/keys/permission.c   |   31 ++++++++++++++++++++++------
 security/keys/process_keys.c |   46 ++++++++++++++++++++----------------------
 security/security.c          |    6 +++--
 security/selinux/hooks.c     |   25 ++++++++++++++++-------
 security/smack/smack_lsm.c   |   31 +++++++++++++++++++++-------
 9 files changed, 124 insertions(+), 75 deletions(-)
include/linux/key.h +18 -12
index b99b40db08fc..0f2e24f13c2b 100644
@@ -71,6 +71,23 @@ struct net;
 
 #define KEY_PERM_UNDEF	0xffffffff
 
+/*
+ * The permissions required on a key that we're looking up.
+ */
+enum key_need_perm {
+	KEY_NEED_UNSPECIFIED,	/* Needed permission unspecified */
+	KEY_NEED_VIEW,		/* Require permission to view attributes */
+	KEY_NEED_READ,		/* Require permission to read content */
+	KEY_NEED_WRITE,		/* Require permission to update / modify */
+	KEY_NEED_SEARCH,	/* Require permission to search (keyring) or find (key) */
+	KEY_NEED_LINK,		/* Require permission to link */
+	KEY_NEED_SETATTR,	/* Require permission to change attributes */
+	KEY_NEED_UNLINK,	/* Require permission to unlink key */
+	KEY_SYSADMIN_OVERRIDE,	/* Special: override by CAP_SYS_ADMIN */
+	KEY_AUTHTOKEN_OVERRIDE,	/* Special: override by possession of auth token */
+	KEY_DEFER_PERM_CHECK,	/* Special: permission check is deferred */
+};
+
 struct seq_file;
 struct user_struct;
 struct signal_struct;
@@ -420,20 +437,9 @@ static inline key_serial_t key_serial(const struct key *key)
 extern void key_set_timeout(struct key *, unsigned);
 
 extern key_ref_t lookup_user_key(key_serial_t id, unsigned long flags,
-				 key_perm_t perm);
+				 enum key_need_perm need_perm);
 extern void key_free_user_ns(struct user_namespace *);
 
-/*
- * The permissions required on a key that we're looking up.
- */
-#define	KEY_NEED_VIEW	0x01	/* Require permission to view attributes */
-#define	KEY_NEED_READ	0x02	/* Require permission to read content */
-#define	KEY_NEED_WRITE	0x04	/* Require permission to update / modify */
-#define	KEY_NEED_SEARCH	0x08	/* Require permission to search (keyring) or find (key) */
-#define	KEY_NEED_LINK	0x10	/* Require permission to link */
-#define	KEY_NEED_SETATTR 0x20	/* Require permission to change attributes */
-#define	KEY_NEED_ALL	0x3f	/* All the above permissions */
-
 static inline short key_read_state(const struct key *key)
 {
 	/* Barrier versus mark_key_instantiated(). */
include/linux/security.h +3 -3
index e7914e4e0b02..57aac14e3418 100644
@@ -1767,8 +1767,8 @@ static inline int security_path_chroot(const struct path *path)
 
 int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags);
 void security_key_free(struct key *key);
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm);
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm);
 int security_key_getsecurity(struct key *key, char **_buffer);
 
 #else
@@ -1786,7 +1786,7 @@ static inline void security_key_free(struct key *key)
 
 static inline int security_key_permission(key_ref_t key_ref,
 					  const struct cred *cred,
-					  unsigned perm)
+					  enum key_need_perm need_perm)
 {
 	return 0;
 }
security/keys/internal.h +4 -4
index 28e17f4f3328..1fc17cb317a9 100644
@@ -167,7 +167,6 @@ extern bool lookup_user_key_possessed(const struct key *key,
 				      const struct key_match_data *match_data);
 #define KEY_LOOKUP_CREATE	0x01
 #define KEY_LOOKUP_PARTIAL	0x02
-#define KEY_LOOKUP_FOR_UNLINK	0x04
 
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
@@ -183,7 +182,7 @@ extern void key_gc_keytype(struct key_type *ktype);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
-			       key_perm_t perm);
+			       enum key_need_perm need_perm);
 
 static inline void notify_key(struct key *key,
 			      enum key_notification_subtype subtype, u32 aux)
@@ -205,9 +204,10 @@ static inline void notify_key(struct key *key,
 /*
  * Check to see whether permission is granted to use a key in the desired way.
  */
-static inline int key_permission(const key_ref_t key_ref, unsigned perm)
+static inline int key_permission(const key_ref_t key_ref,
+				 enum key_need_perm need_perm)
 {
-	return key_task_permission(key_ref, current_cred(), perm);
+	return key_task_permission(key_ref, current_cred(), need_perm);
 }
 
 extern struct key_type key_type_request_key_auth;
security/keys/keyctl.c +9 -7
index 7d8de1c9a478..6763ee45e04d 100644
@@ -434,7 +434,7 @@ long keyctl_invalidate_key(key_serial_t id)
 
 		/* Root is permitted to invalidate certain special keys */
 		if (capable(CAP_SYS_ADMIN)) {
-			key_ref = lookup_user_key(id, 0, 0);
+			key_ref = lookup_user_key(id, 0, KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(key_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_INVAL,
@@ -479,7 +479,8 @@ long keyctl_keyring_clear(key_serial_t ringid)
 
 		/* Root is permitted to invalidate certain special keyrings */
 		if (capable(CAP_SYS_ADMIN)) {
-			keyring_ref = lookup_user_key(ringid, 0, 0);
+			keyring_ref = lookup_user_key(ringid, 0,
+						      KEY_SYSADMIN_OVERRIDE);
 			if (IS_ERR(keyring_ref))
 				goto error;
 			if (test_bit(KEY_FLAG_ROOT_CAN_CLEAR,
@@ -563,7 +564,7 @@ long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)
 		goto error;
 	}
 
-	key_ref = lookup_user_key(id, KEY_LOOKUP_FOR_UNLINK, 0);
+	key_ref = lookup_user_key(id, KEY_LOOKUP_PARTIAL, KEY_NEED_UNLINK);
 	if (IS_ERR(key_ref)) {
 		ret = PTR_ERR(key_ref);
 		goto error2;
@@ -663,7 +664,7 @@ long keyctl_describe_key(key_serial_t keyid,
 				key_put(instkey);
 				key_ref = lookup_user_key(keyid,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -833,7 +834,7 @@ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
 	size_t key_data_len;
 
 	/* find the key first */
-	key_ref = lookup_user_key(keyid, 0, 0);
+	key_ref = lookup_user_key(keyid, 0, KEY_DEFER_PERM_CHECK);
 	if (IS_ERR(key_ref)) {
 		ret = -ENOKEY;
 		goto out;
@@ -1471,7 +1472,7 @@ long keyctl_set_timeout(key_serial_t id, unsigned timeout)
 				key_put(instkey);
 				key_ref = lookup_user_key(id,
 							  KEY_LOOKUP_PARTIAL,
-							  0);
+							  KEY_AUTHTOKEN_OVERRIDE);
 				if (!IS_ERR(key_ref))
 					goto okay;
 			}
@@ -1579,7 +1580,8 @@ long keyctl_get_security(key_serial_t keyid,
 			return PTR_ERR(instkey);
 		key_put(instkey);
 
-		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL, 0);
+		key_ref = lookup_user_key(keyid, KEY_LOOKUP_PARTIAL,
+					  KEY_AUTHTOKEN_OVERRIDE);
 		if (IS_ERR(key_ref))
 			return PTR_ERR(key_ref);
 	}
security/keys/permission.c +24 -7
index 085f907b64ac..4a61f804e80f 100644
@@ -13,7 +13,7 @@
  * key_task_permission - Check a key can be used
  * @key_ref: The key to check.
  * @cred: The credentials to use.
- * @perm: The permissions to check for.
+ * @need_perm: The permission required.
  *
  * Check to see whether permission is granted to use a key in the desired way,
  * but permit the security modules to override.
@@ -24,12 +24,30 @@
  * permissions bits or the LSM check.
  */
 int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
-			unsigned perm)
+			enum key_need_perm need_perm)
 {
 	struct key *key;
-	key_perm_t kperm;
+	key_perm_t kperm, mask;
 	int ret;
 
+	switch (need_perm) {
+	default:
+		WARN_ON(1);
+		return -EACCES;
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		goto lsm;
+
+	case KEY_NEED_VIEW:	mask = KEY_OTH_VIEW;	break;
+	case KEY_NEED_READ:	mask = KEY_OTH_READ;	break;
+	case KEY_NEED_WRITE:	mask = KEY_OTH_WRITE;	break;
+	case KEY_NEED_SEARCH:	mask = KEY_OTH_SEARCH;	break;
+	case KEY_NEED_LINK:	mask = KEY_OTH_LINK;	break;
+	case KEY_NEED_SETATTR:	mask = KEY_OTH_SETATTR;	break;
+	}
+
 	key = key_ref_to_ptr(key_ref);
 
 	/* use the second 8-bits of permissions for keys the caller owns */
@@ -64,13 +82,12 @@ int key_task_permission(const key_ref_t key_ref, const struct cred *cred,
 	if (is_key_possessed(key_ref))
 		kperm |= key->perm >> 24;
 
-	kperm = kperm & perm & KEY_NEED_ALL;
-
-	if (kperm != perm)
+	if ((kperm & mask) != mask)
 		return -EACCES;
 
 	/* let LSM be the final arbiter */
-	return security_key_permission(key_ref, cred, perm);
+lsm:
+	return security_key_permission(key_ref, cred, need_perm);
 }
 EXPORT_SYMBOL(key_task_permission);
 
security/keys/process_keys.c +22 -24
index 09541de31f2f..7e0232db1707 100644
@@ -609,7 +609,7 @@ bool lookup_user_key_possessed(const struct key *key,
  * returned key reference.
  */
 key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
-			  key_perm_t perm)
+			  enum key_need_perm need_perm)
 {
 	struct keyring_search_context ctx = {
 		.match_data.cmp		= lookup_user_key_possessed,
@@ -773,35 +773,33 @@ key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
 
 	/* unlink does not use the nominated key in any way, so can skip all
 	 * the permission checks as it is only concerned with the keyring */
-	if (lflags & KEY_LOOKUP_FOR_UNLINK) {
-		ret = 0;
-		goto error;
-	}
-
-	if (!(lflags & KEY_LOOKUP_PARTIAL)) {
-		ret = wait_for_key_construction(key, true);
-		switch (ret) {
-		case -ERESTARTSYS:
-			goto invalid_key;
-		default:
-			if (perm)
+	if (need_perm != KEY_NEED_UNLINK) {
+		if (!(lflags & KEY_LOOKUP_PARTIAL)) {
+			ret = wait_for_key_construction(key, true);
+			switch (ret) {
+			case -ERESTARTSYS:
+				goto invalid_key;
+			default:
+				if (need_perm != KEY_AUTHTOKEN_OVERRIDE &&
+				    need_perm != KEY_DEFER_PERM_CHECK)
+					goto invalid_key;
+			case 0:
+				break;
+			}
+		} else if (need_perm != KEY_DEFER_PERM_CHECK) {
+			ret = key_validate(key);
+			if (ret < 0)
 				goto invalid_key;
-		case 0:
-			break;
 		}
-	} else if (perm) {
-		ret = key_validate(key);
-		if (ret < 0)
+
+		ret = -EIO;
+		if (!(lflags & KEY_LOOKUP_PARTIAL) &&
+		    key_read_state(key) == KEY_IS_UNINSTANTIATED)
 			goto invalid_key;
 	}
 
-	ret = -EIO;
-	if (!(lflags & KEY_LOOKUP_PARTIAL) &&
-	    key_read_state(key) == KEY_IS_UNINSTANTIATED)
-		goto invalid_key;
-
 	/* check the permissions */
-	ret = key_task_permission(key_ref, ctx.cred, perm);
+	ret = key_task_permission(key_ref, ctx.cred, need_perm);
 	if (ret < 0)
 		goto invalid_key;
 
security/security.c +3 -3
index c73334ab2882..af32d4cd0462 100644
@@ -2398,10 +2398,10 @@ void security_key_free(struct key *key)
 	call_void_hook(key_free, key);
 }
 
-int security_key_permission(key_ref_t key_ref,
-			    const struct cred *cred, unsigned perm)
+int security_key_permission(key_ref_t key_ref, const struct cred *cred,
+			    enum key_need_perm need_perm)
 {
-	return call_int_hook(key_permission, 0, key_ref, cred, perm);
+	return call_int_hook(key_permission, 0, key_ref, cred, need_perm);
 }
 
 int security_key_getsecurity(struct key *key, char **_buffer)
security/selinux/hooks.c +18 -7
index 0b4e32161b77..3ff6b6dfc5ca 100644
@@ -6541,20 +6541,31 @@ static void selinux_key_free(struct key *k)
 
 static int selinux_key_permission(key_ref_t key_ref,
 				  const struct cred *cred,
-				  unsigned perm)
+				  enum key_need_perm need_perm)
 {
 	struct key *key;
 	struct key_security_struct *ksec;
-	u32 sid;
+	u32 perm, sid;
 
-	/* if no specific permissions are requested, we skip the
-	   permission check. No serious, additional covert channels
-	   appear to be created. */
-	if (perm == 0)
+	switch (need_perm) {
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
 		return 0;
+	default:
+		WARN_ON(1);
+		return -EPERM;
 
-	sid = cred_sid(cred);
+	case KEY_NEED_VIEW:	perm = KEY__VIEW;	break;
+	case KEY_NEED_READ:	perm = KEY__READ;	break;
+	case KEY_NEED_WRITE:	perm = KEY__WRITE;	break;
+	case KEY_NEED_SEARCH:	perm = KEY__SEARCH;	break;
+	case KEY_NEED_LINK:	perm = KEY__LINK;	break;
+	case KEY_NEED_SETATTR:	perm = KEY__SETATTR;	break;
+	}
 
+	sid = cred_sid(cred);
 	key = key_ref_to_ptr(key_ref);
 	ksec = key->security;
 
security/smack/smack_lsm.c +3 -2
index 8c61d175e195..627ca7dc9b27 100644
@@ -4230,13 +4230,14 @@ static void smack_key_free(struct key *key)
  * smack_key_permission - Smack access on a key
  * @key_ref: gets to the object
  * @cred: the credentials to use
- * @perm: requested key permissions
+ * @need_perm: requested key permission
  *
  * Return 0 if the task has read and write to the object,
  * an error code otherwise
  */
 static int smack_key_permission(key_ref_t key_ref,
-				const struct cred *cred, unsigned perm)
+				const struct cred *cred,
+				enum key_need_perm need_perm)
 {
 	struct key *keyp;
 	struct smk_audit_info ad;

security/smack/smack_lsm.c static int smack_key_permission(key_ref_t key_ref, · line 4253

Quoted 8 lines
security/smack/smack_lsm.c +3 -2
@@ -4247,8 +4248,26 @@ static int smack_key_permission(key_ref_t key_ref,
 	/*
 	 * Validate requested permissions
 	 */
-	if (perm & ~KEY_NEED_ALL)
-		return -EINVAL;
+	switch (need_perm) {
+	default:
+		return -EACCES;

Put the default at the end of the switch.
Because that's just the way it's done.

Is the change from -EINVAL to -EACCES a bug fix?
Does it introduce an incompatibility?

Quoted 33 lines
security/smack/smack_lsm.c +17 -4
+	case KEY_NEED_UNSPECIFIED:
+	case KEY_NEED_UNLINK:
+	case KEY_SYSADMIN_OVERRIDE:
+	case KEY_AUTHTOKEN_OVERRIDE:
+	case KEY_DEFER_PERM_CHECK:
+		return 0;
+	case KEY_NEED_READ:
+	case KEY_NEED_SEARCH:
+	case KEY_NEED_VIEW:
+		request |= MAY_READ;
+		break;
+	case KEY_NEED_WRITE:
+	case KEY_NEED_LINK:
+	case KEY_NEED_SETATTR:
+		request |= MAY_WRITE;
+		break;
+	}
 
 	keyp = key_ref_to_ptr(key_ref);
 	if (keyp == NULL)
@@ -4273,10 +4292,6 @@ static int smack_key_permission(key_ref_t key_ref,
 	ad.a.u.key_struct.key = keyp->serial;
 	ad.a.u.key_struct.key_desc = keyp->description;
 #endif
-	if (perm & (KEY_NEED_READ | KEY_NEED_SEARCH | KEY_NEED_VIEW))
-		request |= MAY_READ;
-	if (perm & (KEY_NEED_WRITE | KEY_NEED_LINK | KEY_NEED_SETATTR))
-		request |= MAY_WRITE;
 	rc = smk_access(tkp, keyp->security, request, &ad);
 	rc = smk_bu_note("key access", tkp, keyp->security, request, rc);
 	return rc;
maintainer
#33 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

Quoted 8 lines · Casey Schaufler

security/smack/smack_lsm.c static int smack_key_permission(key_ref_t key_ref, · line 4253

Quoted 5 lines
security/smack/smack_lsm.c +3 -2
-	if (perm & ~KEY_NEED_ALL)
-		return -EINVAL;
+	switch (need_perm) {
+	default:
+		return -EACCES;

...
Is the change from -EINVAL to -EACCES a bug fix?
Does it introduce an incompatibility?

It shouldn't happen. All the actual cases should be covered explicitly in the switch. It's to catch a programming issue in the kernel where a new value gets added to the enum but not propagated to all the places that check for it.

I'd actually prefer it to be something even more obvious, especially as EINVAL is so widely used in the kernel. Should I put a WARN_ON in there?

David

#34 lore raw

Re: [PATCH] keys: Make the KEY_NEED_* perms an enum rather than a mask

In reply to David Howells
Quoted 21 lines · David Howells

Since the meaning of combining the KEY_NEED_* constants is undefined, make it so that you can't do that by turning them into an enum.

The enum is also given some extra values to represent special circumstances, such as:

(1) The '0' value is reserved and causes a warning to trap the parameter being unset.

(2) The key is to be unlinked and we require no permissions on it, only the keyring, (this replaces the KEY_LOOKUP_FOR_UNLINK flag).

(3) An override due to CAP_SYS_ADMIN.

(4) An override due to an instantiation token being present.

(5) The permissions check is being deferred to later key_permission() calls.

The extra values give the opportunity for LSMs to audit these situations.

Quoted 7 lines
cc Jarkko Sakkinen <[email protected]>
cc Paul Moore <[email protected]>
cc Stephen Smalley <[email protected]>
cc Casey Schaufler <[email protected]>

So extensive comments already from Stephen and Paul that I'll just wait for the next version (agree with the idea though).

/Jarkko