diff mbox series

[RFC] net/bpfilter: Remove this broken and apparently unmantained

Message ID 875zc4c86z.fsf_-_@x220.int.ebiederm.org
State RFC
Delegated to: David Miller
Headers show
Series [RFC] net/bpfilter: Remove this broken and apparently unmantained | expand

Commit Message

Eric W. Biederman June 6, 2020, 7:20 p.m. UTC
Tetsuo Honda recently noticed that the exec support of bpfilter is buggy.
https://lore.kernel.org/linux-fsdevel/2a8775b4-1dd5-9d5c-aa42-9872445e0942@i-love.sakura.ne.jp/

I agree with Al that Tetsuo's patch does not lend clarity to the code in
exec.  At a rough glance Tetsuo's patch does appear correct.

There have been no replies from the people who I expect would be
maintainers of the code.  When I look at the history of the code all it
appears to have received since it was merged was trivial maintenance
updates.  There has been no apparent work to finish fleshing out the
code to do what it is was aimed to do.

Examinine the code the pid handling is questionable.  The custom hook
into do_exit might prevent it but it appears that shutdown_umh has every
possibility of sending SIGKILL to the wrong process.

The Kconfig documentation lists this code as experimental.

The code only supports ipv4 not ipv6 another strong sign that this
code has not been going anywhere.

So as far as I can tell this bpfilter code was an experiment that did
not succeed and now no one cares about it.

So let's fix all of the bugs by removing the code.

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

Kees, Tesuo.  Unless someone chimes in and says they care I will
rebase this patch onto -rc1 to ensure I haven't missed something
because of the merge window and send this to Linus.

 fs/exec.c                        |  38 ++-----
 include/linux/binfmts.h          |   1 -
 include/linux/sched.h            |   8 --
 include/linux/umh.h              |  11 ---
 kernel/exit.c                    |   1 -
 kernel/umh.c                     | 163 +------------------------------
 net/Kconfig                      |   1 -
 net/Makefile                     |   1 -
 net/bpfilter/.gitignore          |   2 -
 net/bpfilter/Kconfig             |  16 ---
 net/bpfilter/Makefile            |  21 ----
 net/bpfilter/bpfilter_kern.c     | 128 ------------------------
 net/bpfilter/bpfilter_umh_blob.S |   7 --
 net/bpfilter/main.c              |  64 ------------
 net/bpfilter/msgfmt.h            |  17 ----
 net/ipv4/Makefile                |   1 -
 net/ipv4/bpfilter/Makefile       |   2 -
 net/ipv4/bpfilter/sockopt.c      |  78 ---------------
 18 files changed, 12 insertions(+), 548 deletions(-)
 delete mode 100644 net/bpfilter/.gitignore
 delete mode 100644 net/bpfilter/Kconfig
 delete mode 100644 net/bpfilter/Makefile
 delete mode 100644 net/bpfilter/bpfilter_kern.c
 delete mode 100644 net/bpfilter/bpfilter_umh_blob.S
 delete mode 100644 net/bpfilter/main.c
 delete mode 100644 net/bpfilter/msgfmt.h
 delete mode 100644 net/ipv4/bpfilter/Makefile
 delete mode 100644 net/ipv4/bpfilter/sockopt.c

Comments

Alexei Starovoitov June 6, 2020, 8:19 p.m. UTC | #1
On Sat, Jun 06, 2020 at 02:20:36PM -0500, Eric W. Biederman wrote:
> 
> Tetsuo Honda recently noticed that the exec support of bpfilter is buggy.
> https://lore.kernel.org/linux-fsdevel/2a8775b4-1dd5-9d5c-aa42-9872445e0942@i-love.sakura.ne.jp/
> 
> I agree with Al that Tetsuo's patch does not lend clarity to the code in
> exec.  At a rough glance Tetsuo's patch does appear correct.
> 
> There have been no replies from the people who I expect would be
> maintainers of the code.  When I look at the history of the code all it
> appears to have received since it was merged was trivial maintenance
> updates.  There has been no apparent work to finish fleshing out the
> code to do what it is was aimed to do.
> 
> Examinine the code the pid handling is questionable.  The custom hook
> into do_exit might prevent it but it appears that shutdown_umh has every
> possibility of sending SIGKILL to the wrong process.
> 
> The Kconfig documentation lists this code as experimental.
> 
> The code only supports ipv4 not ipv6 another strong sign that this
> code has not been going anywhere.
> 
> So as far as I can tell this bpfilter code was an experiment that did
> not succeed and now no one cares about it.
> 
> So let's fix all of the bugs by removing the code.
> 
> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
> ---
> 
> Kees, Tesuo.  Unless someone chimes in and says they care I will
> rebase this patch onto -rc1 to ensure I haven't missed something
> because of the merge window and send this to Linus.

NACKed-by: Alexei Starovoitov <ast@kernel.org>

Please mention specific bugs and let's fix them.
Matthew Wilcox June 6, 2020, 8:43 p.m. UTC | #2
On Sat, Jun 06, 2020 at 02:20:36PM -0500, Eric W. Biederman wrote:
> @@ -39,7 +37,6 @@ static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
>  static DEFINE_SPINLOCK(umh_sysctl_lock);
>  static DECLARE_RWSEM(umhelper_sem);
>  static LIST_HEAD(umh_list);
> -static DEFINE_MUTEX(umh_list_lock);

You can delete the umh_list too; you've deleted all its users.
Linus Torvalds June 6, 2020, 10:33 p.m. UTC | #3
On Sat, Jun 6, 2020 at 1:20 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>
> Please mention specific bugs and let's fix them.

Well, Eric did mention one explicit bug, and several "looks dodgy" bugs.

And the fact is, this isn't used.

It's clever, and I like the concept, but it was probably a mistake to
do this as a user-mode-helper thing.

If people really convert netfilter rules to bpf, they'll likely do so
in user space. This bpfilter thing hasn't gone anywhere, and it _has_
caused problems.

So Alexei, I think the burden of proof is not on Eric, but on you.

Eric's claim is that

 (a) it has bugs (and yes, he pointed to at lelast one)

 (b) it's not doing anything useful

 (b) it's a maintenance issue for execve, which is what Eric maintains.

So you can't just dismiss this, ignore the reported bug, and say
"we'll fix them".

That only answers (a) (well, it _would_ have answered (a)., except you
actually didn't even read Eric's report of existing bugs).

What is your answer to (b)-(c)?

             Linus
Tetsuo Handa June 7, 2020, 1:13 a.m. UTC | #4
On 2020/06/07 4:20, Eric W. Biederman wrote:
> Kees, Tesuo.  Unless someone chimes in and says they care I will
> rebase this patch onto -rc1 to ensure I haven't missed something
> because of the merge window and send this to Linus.

Is the exec support of bpfilter already supported by distributions?
I can see that RHEL8's 4.18 kernel contains several changelogs
( https://git.centos.org/rpms/kernel/blob/c8/f/SPECS/kernel.spec )
that might be relevant to the exec support of bpfilter.
If it is not supported yet, removing the code would be a choice.
Alexei Starovoitov June 7, 2020, 1:49 a.m. UTC | #5
On Sat, Jun 06, 2020 at 03:33:14PM -0700, Linus Torvalds wrote:
> On Sat, Jun 6, 2020 at 1:20 PM Alexei Starovoitov
> <alexei.starovoitov@gmail.com> wrote:
> >
> > Please mention specific bugs and let's fix them.
> 
> Well, Eric did mention one explicit bug, and several "looks dodgy" bugs.
> 
> And the fact is, this isn't used.
> 
> It's clever, and I like the concept, but it was probably a mistake to
> do this as a user-mode-helper thing.
> 
> If people really convert netfilter rules to bpf, they'll likely do so
> in user space. This bpfilter thing hasn't gone anywhere, and it _has_
> caused problems.
> 
> So Alexei, I think the burden of proof is not on Eric, but on you.
> 
> Eric's claim is that
> 
>  (a) it has bugs (and yes, he pointed to at lelast one)

the patch from March 12 ?
I thought it landed long ago. Is there an issue with it?
'handling is questionable' is not very constructive.

>  (b) it's not doing anything useful

true.

>  (b) it's a maintenance issue for execve, which is what Eric maintains.

I'm not aware of execve issues. I don't remember being cc-ed on them.
To me this 'lets remove everything' patch comes out of nowhere with
a link to three month old patch as a justification.

> So you can't just dismiss this, ignore the reported bug, and say
> "we'll fix them".
> 
> That only answers (a) (well, it _would_ have answered (a)., except you
> actually didn't even read Eric's report of existing bugs).
> 
> What is your answer to (b)-(c)?

So far we had two attempts at converting netfilter rules to bpf. Both ended up
with user space implementation and short cuts. bpf side didn't have loops and
couldn't support 10k+ rules. That is what stalled the effort. imo it's a
pointless corner case, but to be a true replacement people kept bringing it up
as something valid. Now we have bpf iterator concept and soon bpf will be able
to handle millions of rules. Also folks are also realizing that this effort has
to be project managed appropriately. Will it materialize in patches tomorrow?
Unlikely. Probably another 6 month at least. Also outside of netfilter
conversion we've started /proc extension effort that will use the same umh
facility. It won't be ready tomorrow as well, but both need umh. initrd is not
an option due to operational constraints. We need a way to ship kernel tarball
where bpf things are ready at boot. I suspect /proc extensions patches will
land sooner. Couple month ago people used umh to do ovs->xdp translatation. It
didn't land. People argued that the same thing can be achieved in user space
and they were correct. So you're right that for most folks user space is the
answer. But there are cases where kernel has to have these things before
systemd starts.
Linus Torvalds June 7, 2020, 2:19 a.m. UTC | #6
On Sat, Jun 6, 2020 at 6:49 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>>
> I'm not aware of execve issues. I don't remember being cc-ed on them.
> To me this 'lets remove everything' patch comes out of nowhere with
> a link to three month old patch as a justification.

Well, it's out of nowhere as far as bpf is concerned, but we've had a
fair amount of discussions about execve cleanups (and a fair amount of
work too, not just discussion) lately

So it comes out of "execve is rather grotty", and trying to make it
simpler have fewer special cases.

> So far we had two attempts at converting netfilter rules to bpf. Both ended up
> with user space implementation and short cuts.

So I have a question: are we convinced that doing this "netfilter
conversion" in user space is required at all?

I realize that yes, running clang is not something we'd want to do in
kernel space, that's not what I'm asking.

But how much might be doable at kernel compile time (run clang to
generate bpf statically when building the kernel) together with some
simplistic run-time parameterized JITting for the table details that
the kernel could do on its own without a real compiler?

Because the problem with this code isn't the "use bpf for netfilter
rules", it's the "run a user mode helper". The execve thing is
actually only incidental, it also ends up being a somewhat interesting
issue wrt namespacing and security (and bootstrapping - I'm not
convinced people want to have a clang bpf compiler in initrd etc).

So particularly if we accept the fact that we won't necessarily need
all of netfilter converted in general - some will be just translated
entirely independently in user space and not use netfilter at all
(just bpf loaded normally)

IOW there would potentially only be a (fairly small?) core set that
the kernel would need to be able to handle "natively".

Am I just blathering?

                  Linus
Tetsuo Handa June 7, 2020, 2:31 a.m. UTC | #7
On 2020/06/07 10:49, Alexei Starovoitov wrote:
> So you're right that for most folks user space is the
> answer. But there are cases where kernel has to have these things before
> systemd starts.

Why such cases can't use init= kernel command line argument?
The program specified via init= kernel command line argument can do anything
before systemd (a.k.a. global init process) starts.

By the way, from the LSM perspective, doing a lot of things before global init
process starts is not desirable, for access decision can be made only after policy
is loaded (which is generally when /sbin/init on a device specified via root=
kernel command line argument becomes ready). Since
fork_usermode_blob((void *) "#!/bin/true\n", 12, info) is possible, I worry that
the ability to start userspace code is abused for bypassing dentry/inode-based
permission checks.
Eric W. Biederman June 7, 2020, 5:58 a.m. UTC | #8
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Sat, Jun 06, 2020 at 03:33:14PM -0700, Linus Torvalds wrote:
>> On Sat, Jun 6, 2020 at 1:20 PM Alexei Starovoitov
>> <alexei.starovoitov@gmail.com> wrote:
>> >
>> > Please mention specific bugs and let's fix them.
>> 
>> Well, Eric did mention one explicit bug, and several "looks dodgy" bugs.
>> 
>> And the fact is, this isn't used.
>> 
>> It's clever, and I like the concept, but it was probably a mistake to
>> do this as a user-mode-helper thing.
>> 
>> If people really convert netfilter rules to bpf, they'll likely do so
>> in user space. This bpfilter thing hasn't gone anywhere, and it _has_
>> caused problems.
>> 
>> So Alexei, I think the burden of proof is not on Eric, but on you.
>> 
>> Eric's claim is that
>> 
>>  (a) it has bugs (and yes, he pointed to at lelast one)
>
> the patch from March 12 ?
> I thought it landed long ago. Is there an issue with it?
> 'handling is questionable' is not very constructive.

It was half a fix.  Tetsuo still doesn't know how to fix tomoyo to work
with fork_usermode_blob.

He was asking for your feedback and you did not give it.

The truth is Tetsuo's fix was only a fix for the symptoms.  It was not a
good fix to the code.

>>  (b) it's not doing anything useful
>
> true.
>
>>  (b) it's a maintenance issue for execve, which is what Eric maintains.
>
> I'm not aware of execve issues. I don't remember being cc-ed on them.
> To me this 'lets remove everything' patch comes out of nowhere with
> a link to three month old patch as a justification.

I needed to know how dead the code is and your reply has confirmed
that the code is dead.

Deleting the code is much easier than the detailed careful work it would
take to make code that is in use work correctly.

>> So you can't just dismiss this, ignore the reported bug, and say
>> "we'll fix them".
>> 
>> That only answers (a) (well, it _would_ have answered (a)., except you
>> actually didn't even read Eric's report of existing bugs).
>> 
>> What is your answer to (b)-(c)?
>
> So far we had two attempts at converting netfilter rules to bpf. Both ended up
> with user space implementation and short cuts. bpf side didn't have loops and
> couldn't support 10k+ rules. That is what stalled the effort. imo it's a
> pointless corner case, but to be a true replacement people kept bringing it up
> as something valid. Now we have bpf iterator concept and soon bpf will be able
> to handle millions of rules. Also folks are also realizing that this effort has
> to be project managed appropriately. Will it materialize in patches tomorrow?
> Unlikely. Probably another 6 month at least. Also outside of netfilter
> conversion we've started /proc extension effort that will use the same umh
> facility. It won't be ready tomorrow as well, but both need umh.

Given that I am one of the folks who looks after proc I haven't seen
that either.  The direction I have seen in the last 20 years is people
figuring out how to reduce proc not really how to extend it so I can't
imagine what a /proc extension effort is.

> initrd is not
> an option due to operational constraints. We need a way to ship kernel tarball
> where bpf things are ready at boot. I suspect /proc extensions patches will
> land sooner. Couple month ago people used umh to do ovs->xdp translatation. It
> didn't land. People argued that the same thing can be achieved in user space
> and they were correct. So you're right that for most folks user space is the
> answer. But there are cases where kernel has to have these things before
> systemd starts.

You may have a valid case for doing things in the kernel before systemd
starts.  The current mechanism is fundamentally in conflict with the
LSMs which is an unresolved problem.

I don't see why you can't have a userspace process that does:

	pid = fork();
        if (pid == 0) {
        	/* Do bpf stuff */
        }
        else if (pid > 0) {
        	execve("/sbin/init", ...);
        }

You can build an initramfs with that code right into the kernel, so
I can't imagine the existing mechanisms being insufficient.

That said the fork_usermode_blob code needs to be taken out and
rewritten so as not to impose a burden on the rest of the code.  There
is no reason why code that is called only one time can not allocate a
filename and pass it to __do_execve_file.

There is no reason to allow modules access to any of that functionality
if you need something before an initramfs can be processed.

exit_umh() is completely unnecessary all that is needed is a reference
to a struct pid.

There are all of these layers and abstractions but with only the single
user in net/bpfilter/bpfilter_kern.c they all appear to have been
jumbled together without good layering inbetween then.

That is just what I see from looking at the code quickly.

All of those problems need to be addressed before fork_usermode_blob
grows any real users.

As for other users that want to use for_usermode_blob in the future
currently the code in the kernel is not at all straightforward to tell
if it is correct or not.  So before it grows any living users the code
need to be rewitten so that it is easy to tell that it is correct.

I have sympathy with your efforts but since the code is currently dead,
and in need of work.  I will write a good version of removing
CONFIG_BPFILTER_UMH on top of -rc1, leaving CONFIG_BPFILTER.

That should give you a solid foundation to build upon, while making the
kernel maintainble.

Eric
Eric W. Biederman June 7, 2020, 11:56 a.m. UTC | #9
ebiederm@xmission.com (Eric W. Biederman) writes:

> I have sympathy with your efforts but since the code is currently dead,
> and in need of work.  I will write a good version of removing
> CONFIG_BPFILTER_UMH on top of -rc1, leaving CONFIG_BPFILTER.

Of course when I just limit my code removal to code that depends upon
the user mode helper all that is left is a Kconfig entry and
include/uapi/linux/bpfilter.h.

I don't get it.

I also noticed that the type of do_exeve_file is wrong. envp and argv
are not "void *", they should be "const char __user *const __user *__argv".

Eric
Eric W. Biederman June 7, 2020, 3:51 p.m. UTC | #10
Matthew Wilcox <willy@infradead.org> writes:

> On Sat, Jun 06, 2020 at 02:20:36PM -0500, Eric W. Biederman wrote:
>> @@ -39,7 +37,6 @@ static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
>>  static DEFINE_SPINLOCK(umh_sysctl_lock);
>>  static DECLARE_RWSEM(umhelper_sem);
>>  static LIST_HEAD(umh_list);
>> -static DEFINE_MUTEX(umh_list_lock);
>
> You can delete the umh_list too; you've deleted all its users.

Good catch, thank you.

Eric
Eric W. Biederman June 7, 2020, 4:09 p.m. UTC | #11
Linus Torvalds <torvalds@linux-foundation.org> writes:

> On Sat, Jun 6, 2020 at 6:49 PM Alexei Starovoitov
> <alexei.starovoitov@gmail.com> wrote:
>>>
>> I'm not aware of execve issues. I don't remember being cc-ed on them.
>> To me this 'lets remove everything' patch comes out of nowhere with
>> a link to three month old patch as a justification.
>
> Well, it's out of nowhere as far as bpf is concerned, but we've had a
> fair amount of discussions about execve cleanups (and a fair amount of
> work too, not just discussion) lately
>
> So it comes out of "execve is rather grotty", and trying to make it
> simpler have fewer special cases.
>
>> So far we had two attempts at converting netfilter rules to bpf. Both ended up
>> with user space implementation and short cuts.
>
> So I have a question: are we convinced that doing this "netfilter
> conversion" in user space is required at all?
>
> I realize that yes, running clang is not something we'd want to do in
> kernel space, that's not what I'm asking.
>
> But how much might be doable at kernel compile time (run clang to
> generate bpf statically when building the kernel) together with some
> simplistic run-time parameterized JITting for the table details that
> the kernel could do on its own without a real compiler?
>
> Because the problem with this code isn't the "use bpf for netfilter
> rules", it's the "run a user mode helper". The execve thing is
> actually only incidental, it also ends up being a somewhat interesting
> issue wrt namespacing and security (and bootstrapping - I'm not
> convinced people want to have a clang bpf compiler in initrd etc).
>
> So particularly if we accept the fact that we won't necessarily need
> all of netfilter converted in general - some will be just translated
> entirely independently in user space and not use netfilter at all
> (just bpf loaded normally)
>
> IOW there would potentially only be a (fairly small?) core set that
> the kernel would need to be able to handle "natively".
>
> Am I just blathering?

I wish I could answer you.

All the code does at this time is connect some ipv4 bpfilter specific
setsockopt commands to a usermode helper with a read pipe and a write
pipe.  The userspace portion does absolutely nothing with those
commands.

I don't have the foggiest idea what that code hopes to be doing when
that code is fully fleshed out.

If the goal is to become a backwards compatible compiler from historic
netfilter commands to bpf it isn't the craziest design in the world.
But that isn't what is implemented today.

With no users it just isn't clear what the code needs to be doing so I
can't tell what needs to be done to bugs in the code.  I can't answer
which behaviors do the users care about.

Eric
Alexei Starovoitov June 8, 2020, 4:20 p.m. UTC | #12
On Sat, Jun 06, 2020 at 07:19:56PM -0700, Linus Torvalds wrote:
> On Sat, Jun 6, 2020 at 6:49 PM Alexei Starovoitov
> <alexei.starovoitov@gmail.com> wrote:
> >>
> > I'm not aware of execve issues. I don't remember being cc-ed on them.
> > To me this 'lets remove everything' patch comes out of nowhere with
> > a link to three month old patch as a justification.
> 
> Well, it's out of nowhere as far as bpf is concerned, but we've had a
> fair amount of discussions about execve cleanups (and a fair amount of
> work too, not just discussion) lately
> 
> So it comes out of "execve is rather grotty", and trying to make it
> simpler have fewer special cases.
> 
> > So far we had two attempts at converting netfilter rules to bpf. Both ended up
> > with user space implementation and short cuts.
> 
> So I have a question: are we convinced that doing this "netfilter
> conversion" in user space is required at all?
> 
> I realize that yes, running clang is not something we'd want to do in
> kernel space, that's not what I'm asking.
> 
> But how much might be doable at kernel compile time (run clang to
> generate bpf statically when building the kernel) together with some
> simplistic run-time parameterized JITting for the table details that
> the kernel could do on its own without a real compiler?

Right. There is no room for large user space application like clang
in vmlinux. The idea for umh was to stay small and self contained.
Its advantage vs kernel module is to execute with user privs
and use normal syscalls to drive kernel instead of export_symbol apis.

There are two things in this discussion. bpfilter that intercepting
netfilter sockopt and elf file embedded into vmlinux that executes
as user process.
The pro/con of bpfilter approach is hard to argue now because
bpfilter itself didn't materialize yet. I'm fine with removal of that part
from the kernel, but I'm still arguing that 'embed elf into vmlinux'
is necessary, useful and there is no alternative.
There are builtin kernel modules. 'elf in vmlinux' is similar to that.
The primary use case is bpf driven features like bpf_lsm.
bpf_lsm needs to load many different bpf programs, create bpf maps, populate
them, attach to lsm hooks to make the whole thing ready. That initialization of
bpf_lsm is currently done after everything booted, but folks want it to be
active much early. Like other LSMs.
Take android for example. It can certify vmlinux, but not boot fs image.
vmlinux needs to apply security policy via bpf_lsm during the boot.
In such case 'embedded elf in vmlinux' would start early, do its thing
via bpf syscall and exit. Unlike bpfilter approach it won't stay running.
Its job is to setup all bpf things and quit.
Theoretically we can do it as proper kernel module, but then it would mean huge
refactoring of all bpf syscall commands to be accessible from the kernel module.
It's simpler to embed elf into vmlinux and run it as user process doing normal
syscalls. I can imagine that in other cases this elf executable would keep
running after setup.
It doesn't have to be bpf related. Folks thought they can do usb drivers
running in user space and ready at boot. 'elf in vmlinux' would work as well.
Alexei Starovoitov June 8, 2020, 4:23 p.m. UTC | #13
On Sun, Jun 07, 2020 at 11:31:05AM +0900, Tetsuo Handa wrote:
> On 2020/06/07 10:49, Alexei Starovoitov wrote:
> > So you're right that for most folks user space is the
> > answer. But there are cases where kernel has to have these things before
> > systemd starts.
> 
> Why such cases can't use init= kernel command line argument?
> The program specified via init= kernel command line argument can do anything
> before systemd (a.k.a. global init process) starts.
> 
> By the way, from the LSM perspective, doing a lot of things before global init
> process starts is not desirable, for access decision can be made only after policy
> is loaded (which is generally when /sbin/init on a device specified via root=
> kernel command line argument becomes ready). Since
> fork_usermode_blob((void *) "#!/bin/true\n", 12, info) is possible, I worry that
> the ability to start userspace code is abused for bypassing dentry/inode-based
> permission checks.

bpf_lsm is that thing that needs to load and start acting early.
It's somewhat chicken and egg. fork_usermode_blob() will start a process
that will load and apply security policy to all further forks and execs.
Alexei Starovoitov June 8, 2020, 4:33 p.m. UTC | #14
On Sun, Jun 07, 2020 at 12:58:12AM -0500, Eric W. Biederman wrote:
> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> 
> > On Sat, Jun 06, 2020 at 03:33:14PM -0700, Linus Torvalds wrote:
> >> On Sat, Jun 6, 2020 at 1:20 PM Alexei Starovoitov
> >> <alexei.starovoitov@gmail.com> wrote:
> >> >
> >> > Please mention specific bugs and let's fix them.
> >> 
> >> Well, Eric did mention one explicit bug, and several "looks dodgy" bugs.
> >> 
> >> And the fact is, this isn't used.
> >> 
> >> It's clever, and I like the concept, but it was probably a mistake to
> >> do this as a user-mode-helper thing.
> >> 
> >> If people really convert netfilter rules to bpf, they'll likely do so
> >> in user space. This bpfilter thing hasn't gone anywhere, and it _has_
> >> caused problems.
> >> 
> >> So Alexei, I think the burden of proof is not on Eric, but on you.
> >> 
> >> Eric's claim is that
> >> 
> >>  (a) it has bugs (and yes, he pointed to at lelast one)
> >
> > the patch from March 12 ?
> > I thought it landed long ago. Is there an issue with it?
> > 'handling is questionable' is not very constructive.
> 
> It was half a fix.  Tetsuo still doesn't know how to fix tomoyo to work
> with fork_usermode_blob.
> 
> He was asking for your feedback and you did not give it.
> 
> The truth is Tetsuo's fix was only a fix for the symptoms.  It was not a
> good fix to the code.
> 
> >>  (b) it's not doing anything useful
> >
> > true.
> >
> >>  (b) it's a maintenance issue for execve, which is what Eric maintains.
> >
> > I'm not aware of execve issues. I don't remember being cc-ed on them.
> > To me this 'lets remove everything' patch comes out of nowhere with
> > a link to three month old patch as a justification.
> 
> I needed to know how dead the code is and your reply has confirmed
> that the code is dead.
> 
> Deleting the code is much easier than the detailed careful work it would
> take to make code that is in use work correctly.
> 
> >> So you can't just dismiss this, ignore the reported bug, and say
> >> "we'll fix them".
> >> 
> >> That only answers (a) (well, it _would_ have answered (a)., except you
> >> actually didn't even read Eric's report of existing bugs).
> >> 
> >> What is your answer to (b)-(c)?
> >
> > So far we had two attempts at converting netfilter rules to bpf. Both ended up
> > with user space implementation and short cuts. bpf side didn't have loops and
> > couldn't support 10k+ rules. That is what stalled the effort. imo it's a
> > pointless corner case, but to be a true replacement people kept bringing it up
> > as something valid. Now we have bpf iterator concept and soon bpf will be able
> > to handle millions of rules. Also folks are also realizing that this effort has
> > to be project managed appropriately. Will it materialize in patches tomorrow?
> > Unlikely. Probably another 6 month at least. Also outside of netfilter
> > conversion we've started /proc extension effort that will use the same umh
> > facility. It won't be ready tomorrow as well, but both need umh.
> 
> Given that I am one of the folks who looks after proc I haven't seen
> that either.  The direction I have seen in the last 20 years is people
> figuring out how to reduce proc not really how to extend it so I can't
> imagine what a /proc extension effort is.

We already made it extensible without changing /proc.
Folks can mount bpffs into /newproc, pin bpf prog in there and it
will be cat-able.
It's not quite /proc, of course. It's a flexible alternative
with unstable cat-able files that are kernel specific.

> 
> > initrd is not
> > an option due to operational constraints. We need a way to ship kernel tarball
> > where bpf things are ready at boot. I suspect /proc extensions patches will
> > land sooner. Couple month ago people used umh to do ovs->xdp translatation. It
> > didn't land. People argued that the same thing can be achieved in user space
> > and they were correct. So you're right that for most folks user space is the
> > answer. But there are cases where kernel has to have these things before
> > systemd starts.
> 
> You may have a valid case for doing things in the kernel before systemd
> starts.  The current mechanism is fundamentally in conflict with the
> LSMs which is an unresolved problem.

It's the other way around. fork_usermode_blob is a mechanism to launch bpf_lsm.

> I don't see why you can't have a userspace process that does:
> 
> 	pid = fork();
>         if (pid == 0) {
>         	/* Do bpf stuff */
>         }
>         else if (pid > 0) {
>         	execve("/sbin/init", ...);
>         }
> 
> You can build an initramfs with that code right into the kernel, so
> I can't imagine the existing mechanisms being insufficient.

that doesn't work for android.
It also doesn't work for us. We ship the kernel package.
It has vmlinux and kernel modules. That's it.

> That said the fork_usermode_blob code needs to be taken out and
> rewritten so as not to impose a burden on the rest of the code.  There
> is no reason why code that is called only one time can not allocate a
> filename and pass it to __do_execve_file.

Sure. Let's alloc filename.

> There is no reason to allow modules access to any of that functionality
> if you need something before an initramfs can be processed.
> 
> exit_umh() is completely unnecessary all that is needed is a reference
> to a struct pid.

So there are no bugs, but there are few layering concerns, right?
Let's switch to pid from task_struct.

> There are all of these layers and abstractions but with only the single
> user in net/bpfilter/bpfilter_kern.c they all appear to have been
> jumbled together without good layering inbetween then.

I'm totally fine tweaking the layering if it makes exec code easier
to maintain.
Sounds like alloc filename and pid vs task_struct are the only things
that needs to be tweaked.
Alexei Starovoitov June 8, 2020, 4:35 p.m. UTC | #15
On Sun, Jun 07, 2020 at 06:56:38AM -0500, Eric W. Biederman wrote:
> ebiederm@xmission.com (Eric W. Biederman) writes:
> 
> > I have sympathy with your efforts but since the code is currently dead,
> > and in need of work.  I will write a good version of removing
> > CONFIG_BPFILTER_UMH on top of -rc1, leaving CONFIG_BPFILTER.
> 
> Of course when I just limit my code removal to code that depends upon
> the user mode helper all that is left is a Kconfig entry and
> include/uapi/linux/bpfilter.h.

This bit you can actually remove.
bpfilter didn't materialize.
But 'elf in vmlinux' is useful. Please keep it.

> I also noticed that the type of do_exeve_file is wrong. envp and argv
> are not "void *", they should be "const char __user *const __user *__argv".

Sounds like a trivial fix.
Greg KH June 8, 2020, 4:40 p.m. UTC | #16
On Mon, Jun 08, 2020 at 09:20:27AM -0700, Alexei Starovoitov wrote:
> On Sat, Jun 06, 2020 at 07:19:56PM -0700, Linus Torvalds wrote:
> > On Sat, Jun 6, 2020 at 6:49 PM Alexei Starovoitov
> > <alexei.starovoitov@gmail.com> wrote:
> > >>
> > > I'm not aware of execve issues. I don't remember being cc-ed on them.
> > > To me this 'lets remove everything' patch comes out of nowhere with
> > > a link to three month old patch as a justification.
> > 
> > Well, it's out of nowhere as far as bpf is concerned, but we've had a
> > fair amount of discussions about execve cleanups (and a fair amount of
> > work too, not just discussion) lately
> > 
> > So it comes out of "execve is rather grotty", and trying to make it
> > simpler have fewer special cases.
> > 
> > > So far we had two attempts at converting netfilter rules to bpf. Both ended up
> > > with user space implementation and short cuts.
> > 
> > So I have a question: are we convinced that doing this "netfilter
> > conversion" in user space is required at all?
> > 
> > I realize that yes, running clang is not something we'd want to do in
> > kernel space, that's not what I'm asking.
> > 
> > But how much might be doable at kernel compile time (run clang to
> > generate bpf statically when building the kernel) together with some
> > simplistic run-time parameterized JITting for the table details that
> > the kernel could do on its own without a real compiler?
> 
> Right. There is no room for large user space application like clang
> in vmlinux. The idea for umh was to stay small and self contained.
> Its advantage vs kernel module is to execute with user privs
> and use normal syscalls to drive kernel instead of export_symbol apis.
> 
> There are two things in this discussion. bpfilter that intercepting
> netfilter sockopt and elf file embedded into vmlinux that executes
> as user process.
> The pro/con of bpfilter approach is hard to argue now because
> bpfilter itself didn't materialize yet. I'm fine with removal of that part
> from the kernel, but I'm still arguing that 'embed elf into vmlinux'
> is necessary, useful and there is no alternative.
> There are builtin kernel modules. 'elf in vmlinux' is similar to that.
> The primary use case is bpf driven features like bpf_lsm.
> bpf_lsm needs to load many different bpf programs, create bpf maps, populate
> them, attach to lsm hooks to make the whole thing ready. That initialization of
> bpf_lsm is currently done after everything booted, but folks want it to be
> active much early. Like other LSMs.
> Take android for example. It can certify vmlinux, but not boot fs image.

Huh?  dm-verity does this for the whole "boot fs partition" already,
right?  Or one of the "dm-" modules...

> vmlinux needs to apply security policy via bpf_lsm during the boot.
> In such case 'embedded elf in vmlinux' would start early, do its thing
> via bpf syscall and exit. Unlike bpfilter approach it won't stay running.
> Its job is to setup all bpf things and quit.
> Theoretically we can do it as proper kernel module, but then it would mean huge
> refactoring of all bpf syscall commands to be accessible from the kernel module.
> It's simpler to embed elf into vmlinux and run it as user process doing normal
> syscalls. I can imagine that in other cases this elf executable would keep
> running after setup.
> It doesn't have to be bpf related. Folks thought they can do usb drivers
> running in user space and ready at boot. 'elf in vmlinux' would work as well.

I still want to work on the "usb drivers in userspace" like this, it's
on my TODO for this year.  But don't let that "sometime in the future
wish" keep this code around if no one is currently using it.

thanks,

greg k-h
Kees Cook June 8, 2020, 6:35 p.m. UTC | #17
On Mon, Jun 08, 2020 at 09:20:27AM -0700, Alexei Starovoitov wrote:
> Take android for example. It can certify vmlinux, but not boot fs image.

Huh? Yes it does, and for a while now. It uses Android uses dm-verity[1]
and fs-verity[2].

[1] https://source.android.com/security/verifiedboot/dm-verity
    https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/verity.html
[2] https://source.android.com/security/apksigning/v3
    https://www.kernel.org/doc/html/latest/filesystems/fsverity.html
Tetsuo Handa June 8, 2020, 11:22 p.m. UTC | #18
On 2020/06/09 1:23, Alexei Starovoitov wrote:
> On Sun, Jun 07, 2020 at 11:31:05AM +0900, Tetsuo Handa wrote:
>> On 2020/06/07 10:49, Alexei Starovoitov wrote:
>>> So you're right that for most folks user space is the
>>> answer. But there are cases where kernel has to have these things before
>>> systemd starts.
>>
>> Why such cases can't use init= kernel command line argument?
>> The program specified via init= kernel command line argument can do anything
>> before systemd (a.k.a. global init process) starts.
>>
>> By the way, from the LSM perspective, doing a lot of things before global init
>> process starts is not desirable, for access decision can be made only after policy
>> is loaded (which is generally when /sbin/init on a device specified via root=
>> kernel command line argument becomes ready). Since
>> fork_usermode_blob((void *) "#!/bin/true\n", 12, info) is possible, I worry that
>> the ability to start userspace code is abused for bypassing dentry/inode-based
>> permission checks.
> 
> bpf_lsm is that thing that needs to load and start acting early.
> It's somewhat chicken and egg. fork_usermode_blob() will start a process
> that will load and apply security policy to all further forks and execs.

fork_usermode_blob() would start a process in userspace, but early in the boot
stage means that things in the kernel might not be ready to serve for userspace
processes (e.g. we can't open a shared library before a filesystem containing
that file becomes ready, we can't mount a filesystem before mount point becomes
ready, we can't access mount point before a device that contains that directory
becomes ready).

TOMOYO LSM module uses call_usermodehelper() from tomoyo_load_policy() in order to
load and apply security policy. What is so nice with fork_usermode_blob() compared
to existing call_usermodehelper(), at the cost of confusing LSM modules by allowing
file-less execve() request from fork_usermode_blob() ?
Alexei Starovoitov June 9, 2020, 1:26 a.m. UTC | #19
On Mon, Jun 08, 2020 at 11:35:12AM -0700, Kees Cook wrote:
> On Mon, Jun 08, 2020 at 09:20:27AM -0700, Alexei Starovoitov wrote:
> > Take android for example. It can certify vmlinux, but not boot fs image.
> 
> Huh? Yes it does, and for a while now. It uses Android uses dm-verity[1]
> and fs-verity[2].

I didn't mean 'certified' like untrusted or insecure.
I meant the vendor kernel has to satisfy and pass SDK checks to be
certified as an android phone whereas vendor can put more or less whatever
they like on the fs. Their own bloatware, etc.
So for android to make sure something is part of the whole sw package
it has to come from the kernel and its modules.
Well, at least that's what I've been told.
Similarly kernel upgrade doesn't necessary include boot image upgrade.
In that sense 'elf in vmlinux' addresses packaging issue.
Alexei Starovoitov June 9, 2020, 1:28 a.m. UTC | #20
On Tue, Jun 09, 2020 at 08:22:13AM +0900, Tetsuo Handa wrote:
> On 2020/06/09 1:23, Alexei Starovoitov wrote:
> > On Sun, Jun 07, 2020 at 11:31:05AM +0900, Tetsuo Handa wrote:
> >> On 2020/06/07 10:49, Alexei Starovoitov wrote:
> >>> So you're right that for most folks user space is the
> >>> answer. But there are cases where kernel has to have these things before
> >>> systemd starts.
> >>
> >> Why such cases can't use init= kernel command line argument?
> >> The program specified via init= kernel command line argument can do anything
> >> before systemd (a.k.a. global init process) starts.
> >>
> >> By the way, from the LSM perspective, doing a lot of things before global init
> >> process starts is not desirable, for access decision can be made only after policy
> >> is loaded (which is generally when /sbin/init on a device specified via root=
> >> kernel command line argument becomes ready). Since
> >> fork_usermode_blob((void *) "#!/bin/true\n", 12, info) is possible, I worry that
> >> the ability to start userspace code is abused for bypassing dentry/inode-based
> >> permission checks.
> > 
> > bpf_lsm is that thing that needs to load and start acting early.
> > It's somewhat chicken and egg. fork_usermode_blob() will start a process
> > that will load and apply security policy to all further forks and execs.
> 
> fork_usermode_blob() would start a process in userspace, but early in the boot
> stage means that things in the kernel might not be ready to serve for userspace
> processes (e.g. we can't open a shared library before a filesystem containing
> that file becomes ready, we can't mount a filesystem before mount point becomes
> ready, we can't access mount point before a device that contains that directory
> becomes ready).
> 
> TOMOYO LSM module uses call_usermodehelper() from tomoyo_load_policy() in order to
> load and apply security policy. What is so nice with fork_usermode_blob() compared
> to existing call_usermodehelper(), at the cost of confusing LSM modules by allowing
> file-less execve() request from fork_usermode_blob() ?

For the same reason you did commit 0e4ae0e0dec6 ("TOMOYO: Make several options configurable.")
Quoting your words from that commit:
"To be able to start using enforcing mode from the early stage of boot sequence,
 this patch adds support for activating access control without calling external
 policy loader program."
Tetsuo Handa June 9, 2020, 5:29 a.m. UTC | #21
On 2020/06/09 10:28, Alexei Starovoitov wrote:
>> TOMOYO LSM module uses call_usermodehelper() from tomoyo_load_policy() in order to
>> load and apply security policy. What is so nice with fork_usermode_blob() compared
>> to existing call_usermodehelper(), at the cost of confusing LSM modules by allowing
>> file-less execve() request from fork_usermode_blob() ?
> 
> For the same reason you did commit 0e4ae0e0dec6 ("TOMOYO: Make several options configurable.")
> Quoting your words from that commit:
> "To be able to start using enforcing mode from the early stage of boot sequence,
>  this patch adds support for activating access control without calling external
>  policy loader program."
> 

I can't catch what you mean. That commit is to allow not to call usermode helper.

You can't start a usermode helper which requires access to filesystems (e.g. ELF loaders,
shared libraries) before call_usermodehelper() can start a usermode helper which requires
access to filesystems. Under such a restricted condition, what is nice with starting a
usermode helper? Programs which can be started under such condition will be quite limited.
My question is: why you can't use existing call_usermodehelper() (if you need to call
a usermode helper) ?
Kees Cook June 9, 2020, 3:37 p.m. UTC | #22
On Mon, Jun 08, 2020 at 06:26:36PM -0700, Alexei Starovoitov wrote:
> On Mon, Jun 08, 2020 at 11:35:12AM -0700, Kees Cook wrote:
> > On Mon, Jun 08, 2020 at 09:20:27AM -0700, Alexei Starovoitov wrote:
> > > Take android for example. It can certify vmlinux, but not boot fs image.
> > 
> > Huh? Yes it does, and for a while now. It uses Android uses dm-verity[1]
> > and fs-verity[2].
> 
> I didn't mean 'certified' like untrusted or insecure.
> I meant the vendor kernel has to satisfy and pass SDK checks to be
> certified as an android phone whereas vendor can put more or less whatever
> they like on the fs. Their own bloatware, etc.
> So for android to make sure something is part of the whole sw package
> it has to come from the kernel and its modules.
> Well, at least that's what I've been told.
> Similarly kernel upgrade doesn't necessary include boot image upgrade.
> In that sense 'elf in vmlinux' addresses packaging issue.

Well, it's much more complex than that, but I see what you mean: it's an
ELF tied to a specific kernel, like modules are. But Android's control
over modules cover such an ELF as well, if it were separate from the
kernel. Regardless, we're off in the weeds. :)
Eric W. Biederman June 9, 2020, 7:51 p.m. UTC | #23
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Sat, Jun 06, 2020 at 07:19:56PM -0700, Linus Torvalds wrote:
>> On Sat, Jun 6, 2020 at 6:49 PM Alexei Starovoitov
>> <alexei.starovoitov@gmail.com> wrote:
>> >>
>> > I'm not aware of execve issues. I don't remember being cc-ed on them.
>> > To me this 'lets remove everything' patch comes out of nowhere with
>> > a link to three month old patch as a justification.
>> 
>> Well, it's out of nowhere as far as bpf is concerned, but we've had a
>> fair amount of discussions about execve cleanups (and a fair amount of
>> work too, not just discussion) lately
>> 
>> So it comes out of "execve is rather grotty", and trying to make it
>> simpler have fewer special cases.
>> 
>> > So far we had two attempts at converting netfilter rules to bpf. Both ended up
>> > with user space implementation and short cuts.
>> 
>> So I have a question: are we convinced that doing this "netfilter
>> conversion" in user space is required at all?
>> 
>> I realize that yes, running clang is not something we'd want to do in
>> kernel space, that's not what I'm asking.
>> 
>> But how much might be doable at kernel compile time (run clang to
>> generate bpf statically when building the kernel) together with some
>> simplistic run-time parameterized JITting for the table details that
>> the kernel could do on its own without a real compiler?
>
> Right. There is no room for large user space application like clang
> in vmlinux. The idea for umh was to stay small and self contained.
> Its advantage vs kernel module is to execute with user privs
> and use normal syscalls to drive kernel instead of export_symbol apis.
>
> There are two things in this discussion. bpfilter that intercepting
> netfilter sockopt and elf file embedded into vmlinux that executes
> as user process.
> The pro/con of bpfilter approach is hard to argue now because
> bpfilter itself didn't materialize yet. I'm fine with removal of that part
> from the kernel, but I'm still arguing that 'embed elf into vmlinux'
> is necessary, useful and there is no alternative.
> There are builtin kernel modules. 'elf in vmlinux' is similar to that.
> The primary use case is bpf driven features like bpf_lsm.
> bpf_lsm needs to load many different bpf programs, create bpf maps, populate
> them, attach to lsm hooks to make the whole thing ready. That initialization of
> bpf_lsm is currently done after everything booted, but folks want it to be
> active much early. Like other LSMs.
> Take android for example. It can certify vmlinux, but not boot fs image.
> vmlinux needs to apply security policy via bpf_lsm during the boot.
> In such case 'embedded elf in vmlinux' would start early, do its thing
> via bpf syscall and exit. Unlike bpfilter approach it won't stay running.
> Its job is to setup all bpf things and quit.
> Theoretically we can do it as proper kernel module, but then it would mean huge
> refactoring of all bpf syscall commands to be accessible from the kernel module.
> It's simpler to embed elf into vmlinux and run it as user process doing normal
> syscalls. I can imagine that in other cases this elf executable would keep
> running after setup.
> It doesn't have to be bpf related. Folks thought they can do usb drivers
> running in user space and ready at boot. 'elf in vmlinux' would work as well.

To be 100% clear.  This is not a rejection of the concept of behind
fork_usermode_blob.

I see nothing fundamentally wrong with the concept and I have no problem
sorting out the details and remerging that code when it is ready.

If there is a user of fork_usermode_blob that it should be ready for the
next merge window let's keep the code, and let's come up with some clean
fixes to waiting for a process and for passing a struct file to exec.

If it is simply coming one of these days like moving usb drivers into
userspace let's come back to the concept when we have a user ready to
use it.  What exists today will still be in the git history for people
to find.

Eric
Eric W. Biederman June 9, 2020, 8:02 p.m. UTC | #24
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> bpf_lsm is that thing that needs to load and start acting early.
> It's somewhat chicken and egg. fork_usermode_blob() will start a process
> that will load and apply security policy to all further forks and
> execs.

What is the timeframe for bpf_lsm patches wanting to use
fork_usermode_blob()?

Are we possibly looking at something that will be ready for the next
merge window?

Eric
Alexei Starovoitov June 9, 2020, 10:32 p.m. UTC | #25
On Tue, Jun 09, 2020 at 02:29:09PM +0900, Tetsuo Handa wrote:
> On 2020/06/09 10:28, Alexei Starovoitov wrote:
> >> TOMOYO LSM module uses call_usermodehelper() from tomoyo_load_policy() in order to
> >> load and apply security policy. What is so nice with fork_usermode_blob() compared
> >> to existing call_usermodehelper(), at the cost of confusing LSM modules by allowing
> >> file-less execve() request from fork_usermode_blob() ?
> > 
> > For the same reason you did commit 0e4ae0e0dec6 ("TOMOYO: Make several options configurable.")
> > Quoting your words from that commit:
> > "To be able to start using enforcing mode from the early stage of boot sequence,
> >  this patch adds support for activating access control without calling external
> >  policy loader program."
> > 
> 
> I can't catch what you mean. That commit is to allow not to call usermode helper.
> 
> You can't start a usermode helper which requires access to filesystems (e.g. ELF loaders,
> shared libraries) before call_usermodehelper() can start a usermode helper which requires
> access to filesystems. Under such a restricted condition, what is nice with starting a
> usermode helper? Programs which can be started under such condition will be quite limited.
> My question is: why you can't use existing call_usermodehelper() (if you need to call
> a usermode helper) ?

I think the confusion comes from assumption that usermode blob is a dynamic file that
needs ld.so, shared libs and rootfs. This mode is supported by the blob loading
logic, but it's not a primary use case. It's nice to be able to compile
that blob with -g and be able to 'gdb -p' into it. That works and very
convenient when it comes to debugging. Compare that to debugging a kernel module!
It's pretty cool to have vmlinux with kernel module-like feature
that folks can breakpoint and single step while the kernel is running.
That's how we've been developing bpfilter. Sadly the other two patches
(by Davem and Daniel) didn't land:
https://lore.kernel.org/patchwork/patch/902785/
https://lore.kernel.org/patchwork/patch/902783/
and without them bpfilter looks completely useless.

The main mode of bpfilter operation was envisioned as rootfs-less.
It must work with any init= including busybox. For production the bpfilter
user mode blob was compiled as static binary with no dependencies.
So there is no path to point to. It should be ready before pid 1
will do its first iptables sys_setsockopt. If user reboots the kernel
with different init= cmdline the bpfilter should still be doing its job.
Like builtin kernel module.
Anyway bpfilter is only one of the use cases for 'elf in vmlinux'.
I think better name would have been 'user space kernel modules'.
Tetsuo Handa June 9, 2020, 11:30 p.m. UTC | #26
On 2020/06/10 7:32, Alexei Starovoitov wrote:
>> You can't start a usermode helper which requires access to filesystems (e.g. ELF loaders,
>> shared libraries) before call_usermodehelper() can start a usermode helper which requires
>> access to filesystems. Under such a restricted condition, what is nice with starting a
>> usermode helper? Programs which can be started under such condition will be quite limited.
>> My question is: why you can't use existing call_usermodehelper() (if you need to call
>> a usermode helper) ?
> 
> I think the confusion comes from assumption that usermode blob is a dynamic file that
> needs ld.so, shared libs and rootfs.

Yes, I assume that usermode blob needs to be able to access the rootfs.

>                                      This mode is supported by the blob loading
> logic, but it's not a primary use case. It's nice to be able to compile
> that blob with -g and be able to 'gdb -p' into it.

Where can the gdb come from when the rootfs is not accessible?

>                                                    That works and very
> convenient when it comes to debugging. Compare that to debugging a kernel module!

Userspace is convenient for debugging, at the cost of robustness (e.g. being killed
by SIGKILL).

> 
> The main mode of bpfilter operation was envisioned as rootfs-less.
> It must work with any init= including busybox. For production the bpfilter
> user mode blob was compiled as static binary with no dependencies.

I still can't imagine. Compiling a user mode blob as a static binary is possible.
But what does 'It must work with any init=' mean? The use of init= depends on
the rootfs being ready.

> So there is no path to point to. It should be ready before pid 1
> will do its first iptables sys_setsockopt.

There has to be at least the root directory in order to use init= parameter.

What does the "pid 1" mean? Why you can't specify your "user mode blob" using init=
parameter and then transfer the control of "pid 1" from your "user mode blob" to
"some program which will do its first iptables sys_setsockopt()" ?

>                                            If user reboots the kernel
> with different init= cmdline the bpfilter should still be doing its job.
> Like builtin kernel module.

Even when rebooting the kernel with different init= cmdline, you have a space for
running your "user mode blob" (e.g.

  init=/path/to/your/user/mode/blob init_after_blob=/path/to/some/program/which/will/do/something/else

), don't you?

There is no need to use call_usermodehelper(), let alone fork_usermode_blob()...
Alexei Starovoitov June 9, 2020, 11:56 p.m. UTC | #27
On Tue, Jun 09, 2020 at 03:02:30PM -0500, Eric W. Biederman wrote:
> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> 
> > bpf_lsm is that thing that needs to load and start acting early.
> > It's somewhat chicken and egg. fork_usermode_blob() will start a process
> > that will load and apply security policy to all further forks and
> > execs.
> 
> What is the timeframe for bpf_lsm patches wanting to use
> fork_usermode_blob()?
> 
> Are we possibly looking at something that will be ready for the next
> merge window?

In bpf space there are these that want to use usermode_blobs:
1. bpfilter itself.
First of all I think we made a mistake delaying landing the main patches:
https://lore.kernel.org/patchwork/patch/902785/
https://lore.kernel.org/patchwork/patch/902783/
without them bpfilter is indeed dead. That probably was the reason
no one was brave enough to continue working on it.
So I think the landed skeleton of bpfilter can be removed.
I think no user space code will notice that include/uapi/linux/bpfilter.h
is gone. So it won't be considered as user space breakage.
Similarly CONFIG_BPFILTER can be nuked too.
bpftool is checking for it (see tools/bpf/bpftool/feature.c)
but it's fine to remove it.
I still think that the approach taken was a correct one, but
lifting that project off the ground was too much for three of us.
So when it's staffed appropriately we can re-add that code.

2. bpf_lsm.
It's very active at the moment. I'm working on it as well
(sleepable progs is targeting that), but I'm not sure when folks
would have to have it during the boot. So far it sounds that
they're addressing more critical needs first. "bpf_lsm ready at boot"
came up several times during "bpf office hours" conference calls,
so it's certainly on the radar. If I to guess I don't think
bpf_lsm will use usermode_blobs in the next 6 weeks.
More likely 2-4 month.

3. bpf iterator.
It's already capable extension of several things in /proc.
See https://lore.kernel.org/bpf/20200509175921.2477493-1-yhs@fb.com/
Cat-ing bpf program as "cat /sys/fs/bpf/my_ipv6_route"
will produce the same human output as "cat /proc/net/ipv6_route".
The key difference is that bpf is all tracing based and it's unstable.
struct fib6_info can change and prog will stop loading.
There are few FIXME in there. That is being addressed right now.
After that the next step is to make cat-able progs available
right after boot via usermode_blobs.
Unlike cases 1 and 2 here we don't care that they appear before pid 1.
They can certainly be chef installed and started as services.
But they are kernel dependent, so deploying them to production
is much more complicated when they're done as separate rpm.
Testing is harder and so on. Operational issues pile up when something
that almost like kernel module is done as a separate package.
Hence usermode_blob fits the best.
Of course we were not planning to add a bunch of them to kernel tree.
The idea was to add only _one_ such cat-able bpf prog and have it as
a selftest for usermode_blob + bpf_iter. What we want our users to
see in 'cat my_ipv6_route' is probably different from other companies.
These patches will likely be using usermode_blob() in the next month.

But we don't need to wait. We can make the progress right now.
How about we remove bpfilter uapi and rename net/bpfilter/bpfilter_kern.c
into net/umb/umb_test.c only to exercise Makefile to build elf file
from simple main.c including .S with incbin trick
and kernel side that does fork_usermode_blob().
And that's it.
net/ipv4/bpfilter/sockopt.c and kconfig can be removed.
That would be enough base to do use cases 2 and 3 above.
Having such selftest will be enough to adjust the layering
for fork_usermode_blob(), right?
If I understood you correctly you want to replace pid_t
in 'struct umh_info' with proper 'struct pid' pointer that
is refcounted, so user process's exit is clean? What else?
Alexei Starovoitov June 10, 2020, 12:05 a.m. UTC | #28
On Wed, Jun 10, 2020 at 08:30:31AM +0900, Tetsuo Handa wrote:
> On 2020/06/10 7:32, Alexei Starovoitov wrote:
> >> You can't start a usermode helper which requires access to filesystems (e.g. ELF loaders,
> >> shared libraries) before call_usermodehelper() can start a usermode helper which requires
> >> access to filesystems. Under such a restricted condition, what is nice with starting a
> >> usermode helper? Programs which can be started under such condition will be quite limited.
> >> My question is: why you can't use existing call_usermodehelper() (if you need to call
> >> a usermode helper) ?
> > 
> > I think the confusion comes from assumption that usermode blob is a dynamic file that
> > needs ld.so, shared libs and rootfs.
> 
> Yes, I assume that usermode blob needs to be able to access the rootfs.
> 
> >                                      This mode is supported by the blob loading
> > logic, but it's not a primary use case. It's nice to be able to compile
> > that blob with -g and be able to 'gdb -p' into it.
> 
> Where can the gdb come from when the rootfs is not accessible?
> 
> >                                                    That works and very
> > convenient when it comes to debugging. Compare that to debugging a kernel module!
> 
> Userspace is convenient for debugging, at the cost of robustness (e.g. being killed
> by SIGKILL).
> 
> > 
> > The main mode of bpfilter operation was envisioned as rootfs-less.
> > It must work with any init= including busybox. For production the bpfilter
> > user mode blob was compiled as static binary with no dependencies.
> 
> I still can't imagine. Compiling a user mode blob as a static binary is possible.
> But what does 'It must work with any init=' mean? The use of init= depends on
> the rootfs being ready.
> 
> > So there is no path to point to. It should be ready before pid 1
> > will do its first iptables sys_setsockopt.
> 
> There has to be at least the root directory in order to use init= parameter.

I think you're still missing that usermode_blob is completely fs-less.
It doesn't need any fs to work.

> 
> What does the "pid 1" mean? Why you can't specify your "user mode blob" using init=
> parameter and then transfer the control of "pid 1" from your "user mode blob" to
> "some program which will do its first iptables sys_setsockopt()" ?

because init= is user cmdline and usermode_blob() is used by the kernel feature.
they are independent.

> >                                            If user reboots the kernel
> > with different init= cmdline the bpfilter should still be doing its job.
> > Like builtin kernel module.
> 
> Even when rebooting the kernel with different init= cmdline, you have a space for
> running your "user mode blob" (e.g.
> 
>   init=/path/to/your/user/mode/blob init_after_blob=/path/to/some/program/which/will/do/something/else
> 
> ), don't you?
> 
> There is no need to use call_usermodehelper(), let alone fork_usermode_blob()...

Using the same argument there is no need for kernel modules and certainly
no need for builtin kernel modules. That back and forth is not going anywhere.
Let's table it.
Tetsuo Handa June 10, 2020, 3:08 a.m. UTC | #29
On 2020/06/10 9:05, Alexei Starovoitov wrote:
> I think you're still missing that usermode_blob is completely fs-less.
> It doesn't need any fs to work.

fork_usermode_blob() allows usage like fork_usermode_blob("#!/bin/sh").
A problem for LSMs is not "It doesn't need any fs to work." but "It can access any fs and
it can issue arbitrary syscalls.".

LSM modules switch their security context upon execve(), based on available information like
"What is the !AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
"What is the AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
"What are argv[]/envp[] for the requested program passed to execve()?", "What is the inode's
security context passed to execve()?" etc. And file-less execve() request (a.k.a.
fork_usermode_blob()) makes pathname information (which pathname-based LSMs depend on)
unavailable.

Since fork_usermode_blob() can execute arbitrary code in userspace, fork_usermode_blob() can
allow execution of e.g. statically linked HTTP server and statically linked DBMS server, without
giving LSM modules a chance to understand the intent of individual file-less execve() request.
If many different statically linked programs were executed via fork_usermode_blob(), how LSM
modules can determine whether a syscall from a file-less process should be permitted/denied?

By the way, TOMOYO LSM wants to know meaningful AT_SYMLINK_NOFOLLOW pathname and !AT_SYMLINK_NOFOLLOW
pathname, and currently there is no API for allow obtaining both pathnames atomically. But that is a
different problem, for what this mail thread is discussing would be whether we can avoid file-less
execve() request (i.e. get rid of fork_usermode_blob()).
Alexei Starovoitov June 10, 2020, 3:32 a.m. UTC | #30
On Wed, Jun 10, 2020 at 12:08:20PM +0900, Tetsuo Handa wrote:
> On 2020/06/10 9:05, Alexei Starovoitov wrote:
> > I think you're still missing that usermode_blob is completely fs-less.
> > It doesn't need any fs to work.
> 
> fork_usermode_blob() allows usage like fork_usermode_blob("#!/bin/sh").
> A problem for LSMs is not "It doesn't need any fs to work." but "It can access any fs and
> it can issue arbitrary syscalls.".
> 
> LSM modules switch their security context upon execve(), based on available information like
> "What is the !AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
> "What is the AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
> "What are argv[]/envp[] for the requested program passed to execve()?", "What is the inode's
> security context passed to execve()?" etc. And file-less execve() request (a.k.a.
> fork_usermode_blob()) makes pathname information (which pathname-based LSMs depend on)
> unavailable.
> 
> Since fork_usermode_blob() can execute arbitrary code in userspace, fork_usermode_blob() can
> allow execution of e.g. statically linked HTTP server and statically linked DBMS server, without
> giving LSM modules a chance to understand the intent of individual file-less execve() request.
> If many different statically linked programs were executed via fork_usermode_blob(), how LSM
> modules can determine whether a syscall from a file-less process should be permitted/denied?

What you're saying is tomoyo doesn't trust kernel modules that are built-in
as part of vmlinux and doesn't trust vmlinux build.
I cannot really comprehend that since it means that tomoyo doesn't trust itself.

> By the way, TOMOYO LSM wants to know meaningful AT_SYMLINK_NOFOLLOW pathname and !AT_SYMLINK_NOFOLLOW
> pathname, and currently there is no API for allow obtaining both pathnames atomically. But that is a
> different problem, for what this mail thread is discussing would be whether we can avoid file-less
> execve() request (i.e. get rid of fork_usermode_blob()).

tomoyo does path name resolution as a string and using that for security?
I'm looking at tomoyo_realpath*() and tomoyo_pathcmp(). Ouch.
Path based security is anti pattern of security.
I didn't realize tomoyo so broken.
Tetsuo Handa June 10, 2020, 7:30 a.m. UTC | #31
Forwarding to LSM-ML. Security people, any comments?

On 2020/06/10 12:32, Alexei Starovoitov wrote:
> On Wed, Jun 10, 2020 at 12:08:20PM +0900, Tetsuo Handa wrote:
>> On 2020/06/10 9:05, Alexei Starovoitov wrote:
>>> I think you're still missing that usermode_blob is completely fs-less.
>>> It doesn't need any fs to work.
>>
>> fork_usermode_blob() allows usage like fork_usermode_blob("#!/bin/sh").
>> A problem for LSMs is not "It doesn't need any fs to work." but "It can access any fs and
>> it can issue arbitrary syscalls.".
>>
>> LSM modules switch their security context upon execve(), based on available information like
>> "What is the !AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
>> "What is the AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
>> "What are argv[]/envp[] for the requested program passed to execve()?", "What is the inode's
>> security context passed to execve()?" etc. And file-less execve() request (a.k.a.
>> fork_usermode_blob()) makes pathname information (which pathname-based LSMs depend on)
>> unavailable.
>>
>> Since fork_usermode_blob() can execute arbitrary code in userspace, fork_usermode_blob() can
>> allow execution of e.g. statically linked HTTP server and statically linked DBMS server, without
>> giving LSM modules a chance to understand the intent of individual file-less execve() request.
>> If many different statically linked programs were executed via fork_usermode_blob(), how LSM
>> modules can determine whether a syscall from a file-less process should be permitted/denied?
> 
> What you're saying is tomoyo doesn't trust kernel modules that are built-in
> as part of vmlinux and doesn't trust vmlinux build.
> I cannot really comprehend that since it means that tomoyo doesn't trust itself.
> 
>> By the way, TOMOYO LSM wants to know meaningful AT_SYMLINK_NOFOLLOW pathname and !AT_SYMLINK_NOFOLLOW
>> pathname, and currently there is no API for allow obtaining both pathnames atomically. But that is a
>> different problem, for what this mail thread is discussing would be whether we can avoid file-less
>> execve() request (i.e. get rid of fork_usermode_blob()).
> 
> tomoyo does path name resolution as a string and using that for security?
> I'm looking at tomoyo_realpath*() and tomoyo_pathcmp(). Ouch.
> Path based security is anti pattern of security.
> I didn't realize tomoyo so broken.
>
Casey Schaufler June 10, 2020, 4:24 p.m. UTC | #32
On 6/10/2020 12:30 AM, Tetsuo Handa wrote:
> Forwarding to LSM-ML. Security people, any comments?
>
> On 2020/06/10 12:32, Alexei Starovoitov wrote:
>> On Wed, Jun 10, 2020 at 12:08:20PM +0900, Tetsuo Handa wrote:
>>> On 2020/06/10 9:05, Alexei Starovoitov wrote:
>>>> I think you're still missing that usermode_blob is completely fs-less.
>>>> It doesn't need any fs to work.
>>> fork_usermode_blob() allows usage like fork_usermode_blob("#!/bin/sh").
>>> A problem for LSMs is not "It doesn't need any fs to work." but "It can access any fs and
>>> it can issue arbitrary syscalls.".
>>>
>>> LSM modules switch their security context upon execve(), based on available information like
>>> "What is the !AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
>>> "What is the AT_SYMLINK_NOFOLLOW pathname for the requested program passed to execve()?",
>>> "What are argv[]/envp[] for the requested program passed to execve()?", "What is the inode's
>>> security context passed to execve()?" etc. And file-less execve() request (a.k.a.
>>> fork_usermode_blob()) makes pathname information (which pathname-based LSMs depend on)
>>> unavailable.
>>>
>>> Since fork_usermode_blob() can execute arbitrary code in userspace, fork_usermode_blob() can
>>> allow execution of e.g. statically linked HTTP server and statically linked DBMS server, without
>>> giving LSM modules a chance to understand the intent of individual file-less execve() request.
>>> If many different statically linked programs were executed via fork_usermode_blob(), how LSM
>>> modules can determine whether a syscall from a file-less process should be permitted/denied?
>> What you're saying is tomoyo doesn't trust kernel modules that are built-in
>> as part of vmlinux and doesn't trust vmlinux build.
>> I cannot really comprehend that since it means that tomoyo doesn't trust itself.

That's not a rational conclusion.

>>> By the way, TOMOYO LSM wants to know meaningful AT_SYMLINK_NOFOLLOW pathname and !AT_SYMLINK_NOFOLLOW
>>> pathname, and currently there is no API for allow obtaining both pathnames atomically. But that is a
>>> different problem, for what this mail thread is discussing would be whether we can avoid file-less
>>> execve() request (i.e. get rid of fork_usermode_blob()).
>> tomoyo does path name resolution as a string and using that for security?
>> I'm looking at tomoyo_realpath*() and tomoyo_pathcmp(). Ouch.
>> Path based security is anti pattern of security.
>> I didn't realize tomoyo so broken.

A lawyer would respond "asked and answered". This argument is
old. We had it in the 1980's with Unix systems. While you can't
identify a *object* using a path name, you can and must use a
path name to identify *user intentions*. If that were not the case
the audit system would be massively less sophisticated. Whether
path name based controls are valuable on a system with the
namespace characteristics of Linux (complete anarchy) is in the
eye of the beholder.

We have Linux Security Modules (LSM) because, as Linus put it,
"security people are insane" and incapable of agreeing on anything.
Security is inherently subjective. AppArmor make some people feel safe,
while others like SELinux. I understand that eBPF is now the cat's
pajamas. We don't go ripping out existing security just because
someone thinks poorly of it. Security features don't go in all that
often without some malice aforethought.
Eric W. Biederman June 10, 2020, 9:12 p.m. UTC | #33
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Tue, Jun 09, 2020 at 03:02:30PM -0500, Eric W. Biederman wrote:
>> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>> 
>> > bpf_lsm is that thing that needs to load and start acting early.
>> > It's somewhat chicken and egg. fork_usermode_blob() will start a process
>> > that will load and apply security policy to all further forks and
>> > execs.
>> 
>> What is the timeframe for bpf_lsm patches wanting to use
>> fork_usermode_blob()?
>> 
>> Are we possibly looking at something that will be ready for the next
>> merge window?
>
> In bpf space there are these that want to use usermode_blobs:
> 1. bpfilter itself.
> First of all I think we made a mistake delaying landing the main patches:
> https://lore.kernel.org/patchwork/patch/902785/
> https://lore.kernel.org/patchwork/patch/902783/
> without them bpfilter is indeed dead. That probably was the reason
> no one was brave enough to continue working on it.
> So I think the landed skeleton of bpfilter can be removed.
> I think no user space code will notice that include/uapi/linux/bpfilter.h
> is gone. So it won't be considered as user space breakage.
> Similarly CONFIG_BPFILTER can be nuked too.
> bpftool is checking for it (see tools/bpf/bpftool/feature.c)
> but it's fine to remove it.
> I still think that the approach taken was a correct one, but
> lifting that project off the ground was too much for three of us.
> So when it's staffed appropriately we can re-add that code.
>
> 2. bpf_lsm.
> It's very active at the moment. I'm working on it as well
> (sleepable progs is targeting that), but I'm not sure when folks
> would have to have it during the boot. So far it sounds that
> they're addressing more critical needs first. "bpf_lsm ready at boot"
> came up several times during "bpf office hours" conference calls,
> so it's certainly on the radar. If I to guess I don't think
> bpf_lsm will use usermode_blobs in the next 6 weeks.
> More likely 2-4 month.
>
> 3. bpf iterator.
> It's already capable extension of several things in /proc.
> See https://lore.kernel.org/bpf/20200509175921.2477493-1-yhs@fb.com/
> Cat-ing bpf program as "cat /sys/fs/bpf/my_ipv6_route"
> will produce the same human output as "cat /proc/net/ipv6_route".
> The key difference is that bpf is all tracing based and it's unstable.
> struct fib6_info can change and prog will stop loading.
> There are few FIXME in there. That is being addressed right now.
> After that the next step is to make cat-able progs available
> right after boot via usermode_blobs.
> Unlike cases 1 and 2 here we don't care that they appear before pid 1.
> They can certainly be chef installed and started as services.
> But they are kernel dependent, so deploying them to production
> is much more complicated when they're done as separate rpm.
> Testing is harder and so on. Operational issues pile up when something
> that almost like kernel module is done as a separate package.
> Hence usermode_blob fits the best.
> Of course we were not planning to add a bunch of them to kernel tree.
> The idea was to add only _one_ such cat-able bpf prog and have it as
> a selftest for usermode_blob + bpf_iter. What we want our users to
> see in 'cat my_ipv6_route' is probably different from other companies.
> These patches will likely be using usermode_blob() in the next month.
>
> But we don't need to wait. We can make the progress right now.
> How about we remove bpfilter uapi and rename net/bpfilter/bpfilter_kern.c
> into net/umb/umb_test.c only to exercise Makefile to build elf file
> from simple main.c including .S with incbin trick
> and kernel side that does fork_usermode_blob().
> And that's it.
> net/ipv4/bpfilter/sockopt.c and kconfig can be removed.
> That would be enough base to do use cases 2 and 3 above.
> Having such selftest will be enough to adjust the layering
> for fork_usermode_blob(), right?

If I understand correctly you are asking people to support out of tree
code.  I see some justification for this functionality for in-tree code.
For out of tree code there really is no way to understand support or
maintain the code.

We probably also need to have a conversation about why this
functionality is a better choice that using a compiled in initramfs,
such as can be had by setting CONFIG_INITRAMFS_SOURCE.

Even with this write up and the conversations so far I don't understand
what problem fork_usermode_blob is supposed to be solving.  Is there
anything kernel version dependent about bpf_lsm?  For me the primary
justification of something like fork_usermode_blob is something that is
for all practical purposes a kernel module but it just happens to run in
usermode.

From what little I know about bpf_lsm that isn't the case.  So far all
you have mentioned is that bpf_lsm needs to load early.  That seems like
something that could be solved by a couple of lines init/main.c that
forks and exec's a program before init if it is present.  Maybe that
also needs a bit of protection so the bootloader can't override the
binary.

The entire concept of a loadable lsm has me scratching my head.  Last
time that concept was seriously looked at the races for initializing per
object data were difficult enough to deal with modular support was
removed from all of the existing lsms.

Not to mention there are places where the lsm hooks are a pretty lousy
API and will be refactored to make things better with no thought of any
out of tree code.

> If I understood you correctly you want to replace pid_t
> in 'struct umh_info' with proper 'struct pid' pointer that
> is refcounted, so user process's exit is clean? What else?

No "if (filename)" or "if (file)" on the exec code paths.  No extra case
for the LSM's to have to deal with.  Nothing fork_usermode_blob does is
something that can't be done from userspace as far as execve is
concerned so there is no justification for any special cases in the core
of the exec code.

Getting the deny_write_count and the reference count correct on the file
argument as well as getting BPRM_FLAGS_PATH_INACCESSIBLE set.

Using the proper type for argv and envp.

Those are the things I know of that need to be addressed.


Getting the code refactored so that the do_open_execat can be called
in do_execveat_common instead of __do_execve_file is enough of a
challenge of code motion I really would rather not do that.   Unfortunately that is
the only way I can see right now to have both do_execveat_common and
do_execve_file pass in a struct file.

Calling deny_write_access and get_file in do_execve_file and probably
a bit more is the only way I can see to cleanly isoloate the special
cases fork_usermode_blob brings to the table.


Strictly speaking I am also aware of the issue that the kernel has to
use set_fs(KERNEL_DS) to allow argv and envp to exist in kernel space
instead of userspace.  That needs to be fixed as well, but for all
kernel uses of exec.  So any work fixing fork_usermode_blob can ignore
that issue.

Eric
Alexei Starovoitov June 11, 2020, 11:31 p.m. UTC | #34
On Wed, Jun 10, 2020 at 04:12:29PM -0500, Eric W. Biederman wrote:
> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> 
> > On Tue, Jun 09, 2020 at 03:02:30PM -0500, Eric W. Biederman wrote:
> >> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> >> 
> >> > bpf_lsm is that thing that needs to load and start acting early.
> >> > It's somewhat chicken and egg. fork_usermode_blob() will start a process
> >> > that will load and apply security policy to all further forks and
> >> > execs.
> >> 
> >> What is the timeframe for bpf_lsm patches wanting to use
> >> fork_usermode_blob()?
> >> 
> >> Are we possibly looking at something that will be ready for the next
> >> merge window?
> >
> > In bpf space there are these that want to use usermode_blobs:
> > 1. bpfilter itself.
> > First of all I think we made a mistake delaying landing the main patches:
> > https://lore.kernel.org/patchwork/patch/902785/
> > https://lore.kernel.org/patchwork/patch/902783/
> > without them bpfilter is indeed dead. That probably was the reason
> > no one was brave enough to continue working on it.
> > So I think the landed skeleton of bpfilter can be removed.
> > I think no user space code will notice that include/uapi/linux/bpfilter.h
> > is gone. So it won't be considered as user space breakage.
> > Similarly CONFIG_BPFILTER can be nuked too.
> > bpftool is checking for it (see tools/bpf/bpftool/feature.c)
> > but it's fine to remove it.
> > I still think that the approach taken was a correct one, but
> > lifting that project off the ground was too much for three of us.
> > So when it's staffed appropriately we can re-add that code.
> >
> > 2. bpf_lsm.
> > It's very active at the moment. I'm working on it as well
> > (sleepable progs is targeting that), but I'm not sure when folks
> > would have to have it during the boot. So far it sounds that
> > they're addressing more critical needs first. "bpf_lsm ready at boot"
> > came up several times during "bpf office hours" conference calls,
> > so it's certainly on the radar. If I to guess I don't think
> > bpf_lsm will use usermode_blobs in the next 6 weeks.
> > More likely 2-4 month.
> >
> > 3. bpf iterator.
> > It's already capable extension of several things in /proc.
> > See https://lore.kernel.org/bpf/20200509175921.2477493-1-yhs@fb.com/
> > Cat-ing bpf program as "cat /sys/fs/bpf/my_ipv6_route"
> > will produce the same human output as "cat /proc/net/ipv6_route".
> > The key difference is that bpf is all tracing based and it's unstable.
> > struct fib6_info can change and prog will stop loading.
> > There are few FIXME in there. That is being addressed right now.
> > After that the next step is to make cat-able progs available
> > right after boot via usermode_blobs.
> > Unlike cases 1 and 2 here we don't care that they appear before pid 1.
> > They can certainly be chef installed and started as services.
> > But they are kernel dependent, so deploying them to production
> > is much more complicated when they're done as separate rpm.
> > Testing is harder and so on. Operational issues pile up when something
> > that almost like kernel module is done as a separate package.
> > Hence usermode_blob fits the best.
> > Of course we were not planning to add a bunch of them to kernel tree.
> > The idea was to add only _one_ such cat-able bpf prog and have it as
> > a selftest for usermode_blob + bpf_iter. What we want our users to
> > see in 'cat my_ipv6_route' is probably different from other companies.
> > These patches will likely be using usermode_blob() in the next month.
> >
> > But we don't need to wait. We can make the progress right now.
> > How about we remove bpfilter uapi and rename net/bpfilter/bpfilter_kern.c
> > into net/umb/umb_test.c only to exercise Makefile to build elf file
> > from simple main.c including .S with incbin trick
> > and kernel side that does fork_usermode_blob().
> > And that's it.
> > net/ipv4/bpfilter/sockopt.c and kconfig can be removed.
> > That would be enough base to do use cases 2 and 3 above.
> > Having such selftest will be enough to adjust the layering
> > for fork_usermode_blob(), right?
> 
> If I understand correctly you are asking people to support out of tree
> code.  I see some justification for this functionality for in-tree code.
> For out of tree code there really is no way to understand support or
> maintain the code.

It's just like saying that sys_finit_module() is there to support out
of tree code. There are in- and out- tree modules and there will be
in- and out- of tree bpf programs, but the focus is on those that
are relevant for the long term future of the kernel.
The 1 case above is in-tree only. There is nothing in bpfilter
that makes sense out of tree.
The 2 case (bpf_lsm) is primarily in-tree. Security is something
everyone wants its own way, but majority of bpf_lsm functionality
should live in-tree.
The 3 case is mostly out-of-tree. If there was obvious way to
extend /proc it could have been in-tree, but no one will agree.

> We probably also need to have a conversation about why this
> functionality is a better choice that using a compiled in initramfs,
> such as can be had by setting CONFIG_INITRAMFS_SOURCE.

I explained it several times already. I don't see how initramfs solves 1 and 2.

> Even with this write up and the conversations so far I don't understand
> what problem fork_usermode_blob is supposed to be solving.  Is there
> anything kernel version dependent about bpf_lsm?  For me the primary
> justification of something like fork_usermode_blob is something that is
> for all practical purposes a kernel module but it just happens to run in
> usermode.

that's what it is. It's a kernel module that runs in user space.

> From what little I know about bpf_lsm that isn't the case.  So far all

It is.

> you have mentioned is that bpf_lsm needs to load early.  That seems like
> something that could be solved by a couple of lines init/main.c that
> forks and exec's a program before init if it is present.  Maybe that
> also needs a bit of protection so the bootloader can't override the
> binary.
> 
> The entire concept of a loadable lsm has me scratching my head.  Last
> time that concept was seriously looked at the races for initializing per
> object data were difficult enough to deal with modular support was
> removed from all of the existing lsms.

I'm not sure what races you're talking about.
usermode_blob will interact with kernel via syscalls and other standard
communication mechanism.

> Not to mention there are places where the lsm hooks are a pretty lousy
> API and will be refactored to make things better with no thought of any
> out of tree code.

I don't see how refactoring LSM hooks is relevant in this discussion.

> 
> > If I understood you correctly you want to replace pid_t
> > in 'struct umh_info' with proper 'struct pid' pointer that
> > is refcounted, so user process's exit is clean? What else?
> 
> No "if (filename)" or "if (file)" on the exec code paths.  No extra case
> for the LSM's to have to deal with.  Nothing fork_usermode_blob does is
> something that can't be done from userspace as far as execve is
> concerned so there is no justification for any special cases in the core
> of the exec code.

Adding getname_kernel() instead of filename==NULL is trivial enough
and makes sense as a cleanup.
But where do you see 'if (file)' ?
The correct 'file' pointer is passed from shmem_kernel_file_setup() all
the way to exec.

> Getting the deny_write_count and the reference count correct on the file
> argument as well as getting BPRM_FLAGS_PATH_INACCESSIBLE set.

There is no fd because there is no task, but there is a file. I think 
do_execve should assume BINPRM_FLAGS_PATH_INACCESSIBLE in this case.

> Using the proper type for argv and envp.

I guess that's going to be a part of other cleanup.

> Those are the things I know of that need to be addressed.
> 
> 
> Getting the code refactored so that the do_open_execat can be called
> in do_execveat_common instead of __do_execve_file is enough of a
> challenge of code motion I really would rather not do that.   Unfortunately that is
> the only way I can see right now to have both do_execveat_common and
> do_execve_file pass in a struct file.

The 'struct file' is there. Please take another look at the code.

> Calling deny_write_access and get_file in do_execve_file and probably
> a bit more is the only way I can see to cleanly isoloate the special
> cases fork_usermode_blob brings to the table.
> 
> 
> Strictly speaking I am also aware of the issue that the kernel has to
> use set_fs(KERNEL_DS) to allow argv and envp to exist in kernel space
> instead of userspace.  That needs to be fixed as well, but for all
> kernel uses of exec.  So any work fixing fork_usermode_blob can ignore
> that issue.

well, this is the problem of usermodehelper_exec.
usermode_blob doesn't use argv/envp.
They could be NULL for all practical purpose.
Tetsuo Handa June 12, 2020, 12:57 a.m. UTC | #35
On 2020/06/12 8:31, Alexei Starovoitov wrote:
> On Wed, Jun 10, 2020 at 04:12:29PM -0500, Eric W. Biederman wrote:
>> We probably also need to have a conversation about why this
>> functionality is a better choice that using a compiled in initramfs,
>> such as can be had by setting CONFIG_INITRAMFS_SOURCE.

I agree. CONFIG_INITRAMFS_SOURCE or call_usermodehelper() should be fine.

>> Even with this write up and the conversations so far I don't understand
>> what problem fork_usermode_blob is supposed to be solving.  Is there
>> anything kernel version dependent about bpf_lsm?  For me the primary
>> justification of something like fork_usermode_blob is something that is
>> for all practical purposes a kernel module but it just happens to run in
>> usermode.
> 
> that's what it is. It's a kernel module that runs in user space.
> 

How can the code running in the userspace memory be protected? Like you said

  It's nice to be able to compile that blob with -g and be able to 'gdb -p' into it.
  That works and very convenient when it comes to debugging. Compare that to debugging
  a kernel module!

, the userspace memory can be easily interfered from userspace. The kernel module
running in kernel space is protected (unless methods like /dev/{mem,kmem} are used)
but the kernel module running in user space is not protected.

You said

  What you're saying is tomoyo doesn't trust kernel modules that are built-in
  as part of vmlinux and doesn't trust vmlinux build.

but the word 'trust' has multiple aspects. One of aspects is "can the program
contain malicious code?" which would be mitigated by cryptographic signing
technology. But another aspect is "does the program contain vulnerability or
bugs?" which would be mitigated by updating programs as soon as possible.
Yet another aspect is "is the program protected from interference?" which would
be mitigated by enforcing sandbox like seccomp. But to enforce it, we need
information for identifying what does the code need to do.

We might need to invent built-in "protected userspace" because existing
"unprotected userspace" is not trustworthy enough to run kernel modules.
That's not just inventing fork_usermode_blob().



>> Strictly speaking I am also aware of the issue that the kernel has to
>> use set_fs(KERNEL_DS) to allow argv and envp to exist in kernel space
>> instead of userspace.  That needs to be fixed as well, but for all
>> kernel uses of exec.  So any work fixing fork_usermode_blob can ignore
>> that issue.
> 
> well, this is the problem of usermodehelper_exec.
> usermode_blob doesn't use argv/envp.
> They could be NULL for all practical purpose.
> 

That's what TOMOYO LSM does not like. You said

  tomoyo does path name resolution as a string and using that for security?
  I'm looking at tomoyo_realpath*() and tomoyo_pathcmp(). Ouch.
  Path based security is anti pattern of security.

but, like Casey mentioned, pathnames/argv/envp etc. represents *user intentions*
for controlling what that code can do.

A method for allow anonymously running arbitrary code in userspace memory (which
can be interfered) is so painful. I won't be able to trust kernel modules running
in userspace memory.
Alexei Starovoitov June 13, 2020, 3:38 a.m. UTC | #36
On Fri, Jun 12, 2020 at 09:57:40AM +0900, Tetsuo Handa wrote:
> 
> , the userspace memory can be easily interfered from userspace. The kernel module
> running in kernel space is protected (unless methods like /dev/{mem,kmem} are used)
> but the kernel module running in user space is not protected.

huh? One user process 'can easily interfere' with memory of other process?

> 
> You said
> 
>   What you're saying is tomoyo doesn't trust kernel modules that are built-in
>   as part of vmlinux and doesn't trust vmlinux build.
> 
> but the word 'trust' has multiple aspects. One of aspects is "can the program
> contain malicious code?" which would be mitigated by cryptographic signing

usermode_blob is either part of kernel module or part of vmlinux.
If it's part of vmlinux it's inherently trusted.
If it's part of ko it's signed along with the rest of ko.

> We might need to invent built-in "protected userspace" because existing
> "unprotected userspace" is not trustworthy enough to run kernel modules.
> That's not just inventing fork_usermode_blob().

sorry, but this makes no sense at all to me.

> can be interfered) is so painful. I won't be able to trust kernel modules running
> in userspace memory.

The part that I suspect is still missing is what triggers fork_usermode_blob().
It's always kernel code == trusted code.

Currently we have the following:

vmlinux {
  core code of kernel
  built-in mod_A {
    kernel code
  }
  built-in mod_B {
    kernel code
  }
}
loadable mod_C {
  kernel code
}

With fork_usermode_blob() kernel modules can delegate parts of their
functionality to run in user space:

vmlinux {
  core code of kernel
  built-in mod_A {
    kernel code
    code to run in user space
  }
  built-in mod_B {
    kernel code
    code to run in user space
  }
}
loadable mod_C {
  kernel code
  code to run in user space
}

The interface between kernel part of .ko and user part of .ko is
specific to that particular kernel module. It's not a typical user space.
Take bpfilter, for example. It has its own format of structures
that are being passed between kernel side of bpfilter and user side
of bpfilter. It's bpfilter's internal interface that doesn't
create user api. bpfilter in kernel 5.x could be passing different
structs vs bpfilter in kernel 6.x.
It also cannot be started via init=, but it has to be ready
if pid 1 needs it.
Say, bpfilter was compiled as loadable kernel module.
In such case bpfilter.ko will not be loaded into the kernel
until the first iptables sockopt. It may never be loaded.
But when loaded the bpfilter.ko will start its user space side
via fork_usermode_blob() that is specific to that version of .ko.
Other kernel modules like bpf_lsm.ko will decide what's appropriate
for them in terms of when user side should start and exit.
Likely bpf_lsm.ko would want to be built-in.
In all cases kernel module cannot rely on traditional usermode_helper,
because usermode_helper is true uapi. The admin can boot kernel 5.x
and it must work with usermode_helpers installed in rootfs. The admin
will reboot to kernel 6.x and it should still work without changing rootfs.
Whereas usermode_blobs are ko and kernel specific.
Tetsuo Handa June 13, 2020, 4:22 a.m. UTC | #37
On 2020/06/13 12:38, Alexei Starovoitov wrote:
> On Fri, Jun 12, 2020 at 09:57:40AM +0900, Tetsuo Handa wrote:
>>
>> , the userspace memory can be easily interfered from userspace. The kernel module
>> running in kernel space is protected (unless methods like /dev/{mem,kmem} are used)
>> but the kernel module running in user space is not protected.
> 
> huh? One user process 'can easily interfere' with memory of other process?

It is an execution environment problem.

Somebody can send SIGKILL (e.g. OOM-killker, SysRq-i) to kill kernel code running as
usermode process, somebody can send SIGSTOP to make kernel code running as usermode
process defunctional, somebody can /usr/bin/strace in order to eavesdrop on secret
data used by kernel code running as usermode process etc.

>> can be interfered) is so painful. I won't be able to trust kernel modules running
>> in userspace memory.
> 
> The part that I suspect is still missing is what triggers fork_usermode_blob().
> It's always kernel code == trusted code.

How can that part be guaranteed?
In future somebody might add a caller that allows

  sys_execute_anonymously_in_usermode(const char code, const int len) {
     return fork_usermode_blob(code, len);
  }

or something similar.

> The interface between kernel part of .ko and user part of .ko is
> specific to that particular kernel module. It's not a typical user space.

How can that part be guaranteed? A caller can pass arbitrary code including
typical user space program (e.g. /bin/sh).

> But when loaded the bpfilter.ko will start its user space side
> via fork_usermode_blob() that is specific to that version of .ko.

How can we guarantee that its user space side started via fork_usermode_blob()
is not disturbed (e.g. SIGKILL, SIGSTOP, /usr/bin/strace) ?

I consider that reliability (from "robustness" perspective) of fork_usermode_blob()
is same with CONFIG_INITRAMFS_SOURCE or call_usermodehelper() or init= approach.
Eric W. Biederman June 13, 2020, 2:08 p.m. UTC | #38
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Wed, Jun 10, 2020 at 04:12:29PM -0500, Eric W. Biederman wrote:
>> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>> 
>> > On Tue, Jun 09, 2020 at 03:02:30PM -0500, Eric W. Biederman wrote:
>> >> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>> >> 
>> >> > bpf_lsm is that thing that needs to load and start acting early.
>> >> > It's somewhat chicken and egg. fork_usermode_blob() will start a process
>> >> > that will load and apply security policy to all further forks and
>> >> > execs.
>> >> 
>> >> What is the timeframe for bpf_lsm patches wanting to use
>> >> fork_usermode_blob()?
>> >> 
>> >> Are we possibly looking at something that will be ready for the next
>> >> merge window?
>> >
>> > In bpf space there are these that want to use usermode_blobs:
>> > 1. bpfilter itself.
>> > First of all I think we made a mistake delaying landing the main patches:
>> > https://lore.kernel.org/patchwork/patch/902785/
>> > https://lore.kernel.org/patchwork/patch/902783/
>> > without them bpfilter is indeed dead. That probably was the reason
>> > no one was brave enough to continue working on it.
>> > So I think the landed skeleton of bpfilter can be removed.
>> > I think no user space code will notice that include/uapi/linux/bpfilter.h
>> > is gone. So it won't be considered as user space breakage.
>> > Similarly CONFIG_BPFILTER can be nuked too.
>> > bpftool is checking for it (see tools/bpf/bpftool/feature.c)
>> > but it's fine to remove it.
>> > I still think that the approach taken was a correct one, but
>> > lifting that project off the ground was too much for three of us.
>> > So when it's staffed appropriately we can re-add that code.
>> >
>> > 2. bpf_lsm.
>> > It's very active at the moment. I'm working on it as well
>> > (sleepable progs is targeting that), but I'm not sure when folks
>> > would have to have it during the boot. So far it sounds that
>> > they're addressing more critical needs first. "bpf_lsm ready at boot"
>> > came up several times during "bpf office hours" conference calls,
>> > so it's certainly on the radar. If I to guess I don't think
>> > bpf_lsm will use usermode_blobs in the next 6 weeks.
>> > More likely 2-4 month.
>> >
>> > 3. bpf iterator.
>> > It's already capable extension of several things in /proc.
>> > See https://lore.kernel.org/bpf/20200509175921.2477493-1-yhs@fb.com/
>> > Cat-ing bpf program as "cat /sys/fs/bpf/my_ipv6_route"
>> > will produce the same human output as "cat /proc/net/ipv6_route".
>> > The key difference is that bpf is all tracing based and it's unstable.
>> > struct fib6_info can change and prog will stop loading.
>> > There are few FIXME in there. That is being addressed right now.
>> > After that the next step is to make cat-able progs available
>> > right after boot via usermode_blobs.
>> > Unlike cases 1 and 2 here we don't care that they appear before pid 1.
>> > They can certainly be chef installed and started as services.
>> > But they are kernel dependent, so deploying them to production
>> > is much more complicated when they're done as separate rpm.
>> > Testing is harder and so on. Operational issues pile up when something
>> > that almost like kernel module is done as a separate package.
>> > Hence usermode_blob fits the best.
>> > Of course we were not planning to add a bunch of them to kernel tree.
>> > The idea was to add only _one_ such cat-able bpf prog and have it as
>> > a selftest for usermode_blob + bpf_iter. What we want our users to
>> > see in 'cat my_ipv6_route' is probably different from other companies.
>> > These patches will likely be using usermode_blob() in the next month.
>> >
>> > But we don't need to wait. We can make the progress right now.
>> > How about we remove bpfilter uapi and rename net/bpfilter/bpfilter_kern.c
>> > into net/umb/umb_test.c only to exercise Makefile to build elf file
>> > from simple main.c including .S with incbin trick
>> > and kernel side that does fork_usermode_blob().
>> > And that's it.
>> > net/ipv4/bpfilter/sockopt.c and kconfig can be removed.
>> > That would be enough base to do use cases 2 and 3 above.
>> > Having such selftest will be enough to adjust the layering
>> > for fork_usermode_blob(), right?
>> 
>> If I understand correctly you are asking people to support out of tree
>> code.  I see some justification for this functionality for in-tree code.
>> For out of tree code there really is no way to understand support or
>> maintain the code.
>
> It's just like saying that sys_finit_module() is there to support out
> of tree code. There are in- and out- tree modules and there will be
> in- and out- of tree bpf programs, but the focus is on those that
> are relevant for the long term future of the kernel.
> The 1 case above is in-tree only. There is nothing in bpfilter
> that makes sense out of tree.
> The 2 case (bpf_lsm) is primarily in-tree. Security is something
> everyone wants its own way, but majority of bpf_lsm functionality
> should live in-tree.
> The 3 case is mostly out-of-tree. If there was obvious way to
> extend /proc it could have been in-tree, but no one will agree.
>
>> We probably also need to have a conversation about why this
>> functionality is a better choice that using a compiled in initramfs,
>> such as can be had by setting CONFIG_INITRAMFS_SOURCE.
>
> I explained it several times already. I don't see how initramfs solves 1 and 2.

You said whatever it was needed to live in the kernel image.
A compiled in initramfs that can be supplemented by a initramfs from the
bootloader is that compiled in situation.  That is what is implemented
with CONFIG_INITRAMFS_SOURCE.

>> Even with this write up and the conversations so far I don't understand
>> what problem fork_usermode_blob is supposed to be solving.  Is there
>> anything kernel version dependent about bpf_lsm?  For me the primary
>> justification of something like fork_usermode_blob is something that is
>> for all practical purposes a kernel module but it just happens to run in
>> usermode.
>
> that's what it is. It's a kernel module that runs in user space.
>
>> From what little I know about bpf_lsm that isn't the case.  So far all
>
> It is.

So the bpf programs will live in the kernel?  Where can I look or has
that part not been merged yet?

>> you have mentioned is that bpf_lsm needs to load early.  That seems like
>> something that could be solved by a couple of lines init/main.c that
>> forks and exec's a program before init if it is present.  Maybe that
>> also needs a bit of protection so the bootloader can't override the
>> binary.
>> 
>> The entire concept of a loadable lsm has me scratching my head.  Last
>> time that concept was seriously looked at the races for initializing per
>> object data were difficult enough to deal with modular support was
>> removed from all of the existing lsms.
>
> I'm not sure what races you're talking about.
> usermode_blob will interact with kernel via syscalls and other standard
> communication mechanism.

The races between the kernel allocating objects say inodes and the code
to place security labels or other markes onto those objects so an
LSM can later make security decisions.

>> Not to mention there are places where the lsm hooks are a pretty lousy
>> API and will be refactored to make things better with no thought of any
>> out of tree code.
>
> I don't see how refactoring LSM hooks is relevant in this discussion.

We were talking about the bpf_lsm, and I have been refactoring the lsm
hooks that run through exec, because they did not have obvious calling
conventions.

If all of the bpf programs for bpf_lsm live in the kernel tree then I
guess there is no problem, but I don't see why in that case you are
using bpf instead of compiling things to C.

When I looked at the bpf_lsm code all I see is a hooks that call out to
bpf programs.  So I made the rather obvious assumption that those bpf
programs are loaded like any other bpf programs from ordinary userspace.

>> > If I understood you correctly you want to replace pid_t
>> > in 'struct umh_info' with proper 'struct pid' pointer that
>> > is refcounted, so user process's exit is clean? What else?
>> 
>> No "if (filename)" or "if (file)" on the exec code paths.  No extra case
>> for the LSM's to have to deal with.  Nothing fork_usermode_blob does is
>> something that can't be done from userspace as far as execve is
>> concerned so there is no justification for any special cases in the core
>> of the exec code.
>
> Adding getname_kernel() instead of filename==NULL is trivial enough
> and makes sense as a cleanup.
> But where do you see 'if (file)' ?
> The correct 'file' pointer is passed from shmem_kernel_file_setup() all
> the way to exec.

In the middle of __do_execve_file:

	if (!file)
		file = do_open_execat(fd, filename, flags);
	retval = PTR_ERR(file);
	if (IS_ERR(file))
		goto out_unmark;

Then just after it we have:

	if (!filename) {
		bprm->filename = "none";
	} else if (fd == AT_FDCWD || filename->name[0] == '/') {
		bprm->filename = filename->name;
	} else {
		if (filename->name[0] == '\0')
			pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd);
		else
			pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s",
					    fd, filename->name);
		if (!pathbuf) {
			retval = -ENOMEM;
			goto out_unmark;
		}
		/*
		 * Record that a name derived from an O_CLOEXEC fd will be
		 * inaccessible after exec. Relies on having exclusive access to
		 * current->files (due to unshare_files above).
		 */
		if (close_on_exec(fd, rcu_dereference_raw(current->files->fdt)))
			bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE;
		bprm->filename = pathbuf;
	}

So we have two core cases in the code that are specific to
fork_usermode_blob, and quite frankly they are both wrong today.

The if (!filename) case does not set BINPRM_FLAGS_PATH_INACCESSIBLE.
The if (file) case does not call get_file(file) and deny_write_access(file).

>> Getting the deny_write_count and the reference count correct on the file
>> argument as well as getting BPRM_FLAGS_PATH_INACCESSIBLE set.
>
> There is no fd because there is no task, but there is a file. I think 
> do_execve should assume BINPRM_FLAGS_PATH_INACCESSIBLE in this case.

I agree that why I said it needs to set that flag, as you can see above
that flag is not set today.

Having BINPRM_FLAGS_PATH_INACCESSIBLE set would slightly relieve
Tetsuo's concern about fork_usermode_blob having a shell script.

>> Using the proper type for argv and envp.
>
> I guess that's going to be a part of other cleanup.

No.  Already answered but again.  Today do_execve_file has the prototype:

int do_execve_file(struct file *file, void *__argv, void *__envp);

void * is definitely not the type that is passed to __argv and __envp,
and that needs to be fixed for that function to remain.

>> Those are the things I know of that need to be addressed.
>> 
>> 
>> Getting the code refactored so that the do_open_execat can be called
>> in do_execveat_common instead of __do_execve_file is enough of a
>> challenge of code motion I really would rather not do that.   Unfortunately that is
>> the only way I can see right now to have both do_execveat_common and
>> do_execve_file pass in a struct file.
>
> The 'struct file' is there. Please take another look at the code.

do_execveat_common passes a NULL file.
While do_execveat_common to be maintainable in this scenario needs to
perform the do_open_execat and pass the file.

That would allow separating out what is specific to do_execve_file
from do_execveat_common.

Which would fundamentally simplify the logic in what is today
__do_execve_file.  The way things are factored today it takes serious
digging to figure out what is going with !file and the !filename
arguments.  We can and should do much better.

Another possible solution which would clean up the code in exec and make
things easier to understand is that there could exist a directory in an
initramfs filesystem somewhere with the names of the programs matching
the module names, and do_execveat_common could just be called with a cwd
on that directory and the name of the module.  Which would remove the
need to have a do_execve_file and do_execve could be used like
everywhere else.

I don't understand why fork_usermode_blob has to reimplement
INITRAMFS_SOURCE but perhaps there is good reason for it.

>> Calling deny_write_access and get_file in do_execve_file and probably
>> a bit more is the only way I can see to cleanly isoloate the special
>> cases fork_usermode_blob brings to the table.
>> 
>> 
>> Strictly speaking I am also aware of the issue that the kernel has to
>> use set_fs(KERNEL_DS) to allow argv and envp to exist in kernel space
>> instead of userspace.  That needs to be fixed as well, but for all
>> kernel uses of exec.  So any work fixing fork_usermode_blob can ignore
>> that issue.
>
> well, this is the problem of usermodehelper_exec.
> usermode_blob doesn't use argv/envp.
> They could be NULL for all practical purpose.

fork_usermode_blob
   call_usermode_helper_setup_file
      split_argv

Addmittedly the only argument split_argv is called on currently is
"bpfilter_umh".  But the code does try and support more.

Should that split_argv be removed?

....

Anyway you asked what needs to be done in exec.

I am in the middle of cleaning up exec.  Send the patches that address
the issues and make this mess not a maintenance issue, and I will be
happy to leave fork_usermode_blob alone.  Otherwise I plan to just
remove the code for now as it is all dead at the moment.

Enough of the argument has been the code which is not merged yet needs
to do X, that this conversation has not been able to point at concrete
parts of the code and argue about them.  I strongly suspect for this
code to be maintainable we need the in-tree users so we can discuss what
is going on.

Eric
Alexei Starovoitov June 13, 2020, 3:33 p.m. UTC | #39
On Sat, Jun 13, 2020 at 7:13 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
> I am in the middle of cleaning up exec.  Send the patches that address
> the issues and make this mess not a maintenance issue, and I will be
> happy to leave fork_usermode_blob alone.  Otherwise I plan to just
> remove the code for now as it is all dead at the moment.

May be stop being a jerk first ?
It's a Nack to remove the code.
Alexei Starovoitov June 13, 2020, 4:14 p.m. UTC | #40
On Sat, Jun 13, 2020 at 8:33 AM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>
> On Sat, Jun 13, 2020 at 7:13 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
> > I am in the middle of cleaning up exec.  Send the patches that address
> > the issues and make this mess not a maintenance issue, and I will be
> > happy to leave fork_usermode_blob alone.  Otherwise I plan to just
> > remove the code for now as it is all dead at the moment.
>
> May be stop being a jerk first ?
> It's a Nack to remove the code.

I'm happy to work on changes, but your removal threats must stop
before we can continue discussion. ok?
Eric W. Biederman June 14, 2020, 2:51 p.m. UTC | #41
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Sat, Jun 13, 2020 at 8:33 AM Alexei Starovoitov
> <alexei.starovoitov@gmail.com> wrote:
>>
>> On Sat, Jun 13, 2020 at 7:13 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
>> > I am in the middle of cleaning up exec.  Send the patches that address
>> > the issues and make this mess not a maintenance issue, and I will be
>> > happy to leave fork_usermode_blob alone.  Otherwise I plan to just
>> > remove the code for now as it is all dead at the moment.
>>
>> May be stop being a jerk first ?
>> It's a Nack to remove the code.
>
> I'm happy to work on changes, but your removal threats must stop
> before we can continue discussion. ok?

I am looking for reasons to not remove the code.  What I can't
personally do is justify spending the time fixing unused code.

The code is currently unused, and has an implementation that can be
improved.  All of which argues for removal on technical grounds.

The implementation issues are a problem for maintaining other code so
they need to be addressed, again that argues for removal on technical
grounds.

There are some asperations to use fork_usermode_blob but no commitments
that I can see to actually use this code.

If someone who cares can step up so other developers don't have to deal
with the maintenance problems, then there is no problem in keeping the
code.




Now there is one technical issue I see that has implications for how
this gets fixed.  The current implementation requires that 2 copies
of the user mode executable be kept.

int fork_usermode_blob(void *data, size_t len, struct umh_info *info);


The function fork_usermode_blob is passed an array and a length.  Today
that array is stored in .rodata.  Not in a init section where it could
be discared.

Now userspace in general and exec in particular requires the executable
to be in a mmapable file.  So fork_usermode_blob creates a mini
filesystem that only supports one file and no file names and opens
a file within it, and passes that open file to exec.

If creation of the filesystem and copying of the data can be separated
from the actual execution of the code, then there will be no need to
keep 2 copies of the executable in memory.  If the file was also given a
name there would be no need for fork_usermode_blob to open the file.
All fork_usermode_blob would need to do is make make it possible for
exec to find that file.

The implification this has for fixing the issues with exec is that once
the file has a name fork_usermode_blob no longer needs to preopen the
file and call do_execve_file.  Instead fork_usermode_blob can call
do_execve.  Which means do_execve_file and all of it's strange corner
cases can go away.

We have all of the infrastructure to decode a cpio in init/initramfs.c
so it would be practically no code at all to place the code into a
filesystem instead of just into a file at startup time.  At which
point it could be guaranteed that the section the filesystem lives in is
an init section and is not used past the point of loading it into a
filesystem.  Making the code use half the memory.

Eric
Alexei Starovoitov June 16, 2020, 1:55 a.m. UTC | #42
On Sun, Jun 14, 2020 at 09:51:09AM -0500, Eric W. Biederman wrote:
> 
> There are some asperations to use fork_usermode_blob but no commitments
> that I can see to actually use this code.

huh? I've listed three projects with concrete timelines that are going to use
fork_usermode_blob.

> If someone who cares can step up so other developers don't have to deal
> with the maintenance problems, then there is no problem in keeping the
> code.

That code has been there for two years and wasn't causing 'maintenance
problems'. Quite the opposite was happening. Initial way of embedding blob
into ko has changed quite a bit thanks to work from Masahiro.
See commit 8e75887d321d ("bpfilter: include bpfilter_umh in assembly instead of using objcopy")

What is happening that this bit of code is somehow in a way of some refactoring
that you're doing (I'm not even sure what kind of refactoring you have in
mind), but instead of working with the community on the best ways to do this
refactoring you're arguing for removal just to avoid tweaking few lines of code.

> Now there is one technical issue I see that has implications for how
> this gets fixed.  The current implementation requires that 2 copies
> of the user mode executable be kept.
> 
> int fork_usermode_blob(void *data, size_t len, struct umh_info *info);
> 
> 
> The function fork_usermode_blob is passed an array and a length.  Today
> that array is stored in .rodata.  Not in a init section where it could
> be discared.

It's a one line change in bpfilter_umh_blob.S to make it .init section,
but for bpfilter init may not work.
For some ko init is appropriate for some other it's not.

> Now userspace in general and exec in particular requires the executable
> to be in a mmapable file.  So fork_usermode_blob creates a mini
> filesystem that only supports one file and no file names and opens
> a file within it, and passes that open file to exec.
> 
> If creation of the filesystem and copying of the data can be separated
> from the actual execution of the code, then there will be no need to
> keep 2 copies of the executable in memory.  If the file was also given a
> name there would be no need for fork_usermode_blob to open the file.
> All fork_usermode_blob would need to do is make make it possible for
> exec to find that file.
> 
> The implification this has for fixing the issues with exec is that once
> the file has a name fork_usermode_blob no longer needs to preopen the
> file and call do_execve_file.  Instead fork_usermode_blob can call
> do_execve.  Which means do_execve_file and all of it's strange corner
> cases can go away.
> 
> We have all of the infrastructure to decode a cpio in init/initramfs.c
> so it would be practically no code at all to place the code into a
> filesystem instead of just into a file at startup time.  At which
> point it could be guaranteed that the section the filesystem lives in is
> an init section and is not used past the point of loading it into a
> filesystem.  Making the code use half the memory.

Could you please re-read the explanation just up the thread:
https://lore.kernel.org/bpf/20200613033821.l62q2ed5ligheyhu@ast-mbp/
that goes into detail how bpfilter is invoking this blob.
Now explain how initramfs could work?
How bpfilter can load its blob when bpfilter.ko was loaded into
the kernel a day after boot ? Where is initramfs?
bpfilter can be normal ko and builtin. In both cases it cannot rely on
a path. That path may not exist. initramfs is not present after boot.
Any path based approach has serious disadvantages.
The ko cannot rely on an external fs hieararchy. The ko is a self contained
object. It has kernel and user code. A blob inside ko is like another kernel
function of that particular ko, but it runs in user space. The root fs could
have been corrupted but ko needs to be operational if it was builtin.

Another reason why single fs (initramfs or other) doesn't work is multiple
ko-s. Theoretically all ko-s can agree on dir layout, but ko-s are built and
loaded at different times. Say we put all possibles blobs from all ko-s into
some new special fs that is available during the boot and after the boot. In
such case the majority of that ram is going to be wasted. Since ko-s may not
need that blob to run or ko-s may not even load, but ram is wasted anyway.
All these show stoppers with fs and path were considered two years ago
when design of user mode blobs was done.
Alexei Starovoitov June 16, 2020, 4:21 p.m. UTC | #43
On Mon, Jun 15, 2020 at 6:55 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
> >
> > int fork_usermode_blob(void *data, size_t len, struct umh_info *info);
> >
> >
> > The function fork_usermode_blob is passed an array and a length.  Today
> > that array is stored in .rodata.  Not in a init section where it could
> > be discared.
>
> It's a one line change in bpfilter_umh_blob.S to make it .init section,
> but for bpfilter init may not work.
> For some ko init is appropriate for some other it's not.

since I remember discussing the desire to have only one copy of the blob
with Andy back then I did a bit of git archeology.
Sure enough it was in .init.rodata when usermode_blob() landed.
But then commit 61fbf5933d42 ("net: bpfilter: restart bpfilter_umh
when error occurred")
added blob restart logic.
It's kinda questionable whether bpfilter needs restart or not.
But because the kernel module now starts the blob multiple times it had to move
them from .init.rodata to .rodata.
Regardless the point is that init or not-init is a decision of a
particular kernel module.
Eric W. Biederman June 23, 2020, 6:04 p.m. UTC | #44
Sigh.  I was busy last week so I left reading this until now in the
hopes I would see something reasonable.

What I see is rejecting of everything that is said to you.

What I do not see are patches fixing issues.  I will await patches.

Eric
Alexei Starovoitov June 23, 2020, 6:35 p.m. UTC | #45
On Tue, Jun 23, 2020 at 01:04:02PM -0500, Eric W. Biederman wrote:
> 
> Sigh.  I was busy last week so I left reading this until now in the
> hopes I would see something reasonable.
> 
> What I see is rejecting of everything that is said to you.
> 
> What I do not see are patches fixing issues.  I will await patches.

huh?
I can say exactly the same. You keep ignoring numerous points I brought up.
You still haven't showed what kind of refactoring you have in mind and
why fork_blob is in its way.
Eric W. Biederman June 23, 2020, 6:53 p.m. UTC | #46
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Tue, Jun 23, 2020 at 01:04:02PM -0500, Eric W. Biederman wrote:
>> 
>> Sigh.  I was busy last week so I left reading this until now in the
>> hopes I would see something reasonable.
>> 
>> What I see is rejecting of everything that is said to you.
>> 
>> What I do not see are patches fixing issues.  I will await patches.
>
> huh?
> I can say exactly the same. You keep ignoring numerous points I brought up.
> You still haven't showed what kind of refactoring you have in mind and
> why fork_blob is in its way.

That is correct.  What I wind up doing with exec is irrelevant.

What is relevant is getting correct working code on the fork_blob path.
Something that is clean enough that whatever weird things it winds up
doing are readable.  The way things are intermingled today it took 2
years for someone to realize there was a basic reference counting bug.

This isn't work anyone else can do because there are not yet any real in
tree users of fork_blob.  The fact that no one else can make
substantials changes to the code because it has no users is what gets in
the way of maintenance.


One of the 2 year old bugs that needs to be fixed is that some LSMs
work in terms of paths.  Tetsuo has been very gracious in pointing that
out.  Either a path needs to be provided or the LSMs that work in terms
of paths need to be fixed.



Now I really don't care how the bugs are fixed.


My recomendation for long term maintenance is to split fork_blob into 2
functions: fs_from_blob, and the ordinary call_usermodehelper_exec.
That removes the need for any special support for anything in the exec
path because your blob will also have a path for your file, and the
file in the filesystem can be reused for restart.

That feels like the least long term work on everyone.

But with no in-tree users none of us can do anything bug guess what
the actual requirements of fork_usermode_blob are.


So patches to fix the bugs please.

Eric
Alexei Starovoitov June 23, 2020, 7:40 p.m. UTC | #47
On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:
> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> 
> > On Tue, Jun 23, 2020 at 01:04:02PM -0500, Eric W. Biederman wrote:
> >> 
> >> Sigh.  I was busy last week so I left reading this until now in the
> >> hopes I would see something reasonable.
> >> 
> >> What I see is rejecting of everything that is said to you.
> >> 
> >> What I do not see are patches fixing issues.  I will await patches.
> >
> > huh?
> > I can say exactly the same. You keep ignoring numerous points I brought up.
> > You still haven't showed what kind of refactoring you have in mind and
> > why fork_blob is in its way.
> 
> That is correct.  What I wind up doing with exec is irrelevant.
> 
> What is relevant is getting correct working code on the fork_blob path.
> Something that is clean enough that whatever weird things it winds up
> doing are readable.  The way things are intermingled today it took 2
> years for someone to realize there was a basic reference counting bug.

There is no refcnt bug. It was a user error on tomoyo side.
fork_blob() works as expected.

> This isn't work anyone else can do because there are not yet any real in
> tree users of fork_blob.  The fact that no one else can make
> substantials changes to the code because it has no users is what gets in
> the way of maintenance.

Not true either.
bpfilter is a full blown user. bpfilter itself didn't go anywhere,
but that's a different story.

> One of the 2 year old bugs that needs to be fixed is that some LSMs
> work in terms of paths.  Tetsuo has been very gracious in pointing that
> out.  Either a path needs to be provided or the LSMs that work in terms
> of paths need to be fixed.

Not true again.
usermode_blob is part of the kernel module.
Kernel module when loaded doesn't have path.
tomoyo has to fix itself.

> Now I really don't care how the bugs are fixed.
> 
> 
> My recomendation for long term maintenance is to split fork_blob into 2
> functions: fs_from_blob, and the ordinary call_usermodehelper_exec.

what is fs_from_blob() ?
If you mean to create a file system from a blob then it makes no sense.
Please read upthread why. I'm not going to repeat the same points.

> So patches to fix the bugs please.

There are bugs. Ok?
This pointless thread is happening because you want to do some refactoring
of the code and somehow believe that fork_blob is in your way.
If you cannot do refactoring without screaming about removal and misreading
implementation details may be you shouldn't be doing that refactoring.
Tetsuo Handa June 24, 2020, 1:51 a.m. UTC | #48
On 2020/06/24 4:40, Alexei Starovoitov wrote:
> There is no refcnt bug. It was a user error on tomoyo side.
> fork_blob() works as expected.

Absolutely wrong! Any check which returns an error during current->in_execve == 1
will cause this refcnt bug. You are simply ignoring that there is possibility
that execve() fails.

> Not true again.
> usermode_blob is part of the kernel module.

Disagree.

> Kernel module when loaded doesn't have path.

Disagree.

Kernel modules can be trusted via module signature mechanism, and the byte array
(which contains code / data) is protected by keeping that byte array within the
kernel address space. Therefore, pathname based security does not need to complain
that there is no pathname when kernel module is loaded.

However, regarding usermode_blob, although the byte array (which contains code / data)
might be initially loaded from the kernel space (which is protected), that byte array
is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
in the user address space. Thus, LSM modules (including pathname based security) want
to control how that byte array can behave.

> tomoyo has to fix itself.

TOMOYO needs to somehow handle /dev/fd/ case from execveat(), but fork_blob() is a
different story.

On 2020/06/24 3:53, Eric W. Biederman wrote:
> This isn't work anyone else can do because there are not yet any real in
> tree users of fork_blob.  The fact that no one else can make
> substantials changes to the code because it has no users is what gets in
> the way of maintenance.

It sounds to me that fork_blob() is a dangerous interface which anonymously
allows arbitrary behavior in an unprotected environment. Therefore,

> Either a path needs to be provided or the LSMs that work in terms
> of paths need to be fixed.

LSM modules want to control how that byte array can behave. But Alexei
still does not explain how information for LSM modules can be provided.

> My recomendation for long term maintenance is to split fork_blob into 2
> functions: fs_from_blob, and the ordinary call_usermodehelper_exec.
> That removes the need for any special support for anything in the exec
> path because your blob will also have a path for your file, and the
> file in the filesystem can be reused for restart.

Yes, that would be an approach for providing information for LSM modules.

> But with no in-tree users none of us can do anything bug guess what
> the actual requirements of fork_usermode_blob are.

Exactly. Since it is not explained why the usermode process started by
fork_usermode_blob() cannot interfere (or be interfered by) the rest of
the system (including normal usermode processes), the byte array comes from
the kernel address space is insufficient for convincing LSM modules to
ignore what that byte array can do.
Alexei Starovoitov June 24, 2020, 4 a.m. UTC | #49
On Wed, Jun 24, 2020 at 10:51:15AM +0900, Tetsuo Handa wrote:
> On 2020/06/24 4:40, Alexei Starovoitov wrote:
> > There is no refcnt bug. It was a user error on tomoyo side.
> > fork_blob() works as expected.
> 
> Absolutely wrong! Any check which returns an error during current->in_execve == 1
> will cause this refcnt bug. You are simply ignoring that there is possibility
> that execve() fails.

you mean security_bprm_creds_for_exec() denying exec?
hmm. got it. refcnt model needs to change then.

> > Not true again.
> > usermode_blob is part of the kernel module.
> 
> Disagree.

Disagree with what? that blob is part of kernel module? huh?
what is it then?

> 
> > Kernel module when loaded doesn't have path.
> 
> Disagree.
> 
> Kernel modules can be trusted via module signature mechanism, and the byte array
> (which contains code / data) is protected by keeping that byte array within the
> kernel address space. Therefore, pathname based security does not need to complain
> that there is no pathname when kernel module is loaded.

I already explained upthread that blob is part of .rodata or .init.rodata
of kernel module and covered by the same signature mechanism.

> However, regarding usermode_blob, although the byte array (which contains code / data)
> might be initially loaded from the kernel space (which is protected), that byte array
> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
> in the user address space. Thus, LSM modules (including pathname based security) want
> to control how that byte array can behave.

It's privileged memory regardless. root can poke into kernel or any process memory.

> On 2020/06/24 3:53, Eric W. Biederman wrote:
> > This isn't work anyone else can do because there are not yet any real in
> > tree users of fork_blob.  The fact that no one else can make
> > substantials changes to the code because it has no users is what gets in
> > the way of maintenance.
> 
> It sounds to me that fork_blob() is a dangerous interface which anonymously
> allows arbitrary behavior in an unprotected environment. Therefore,

I think you missed the part that user blob is signed as part of kernel module.

> > Either a path needs to be provided or the LSMs that work in terms
> > of paths need to be fixed.
> 
> LSM modules want to control how that byte array can behave. But Alexei
> still does not explain how information for LSM modules can be provided.

huh?
please see net/bpfilter/.

> 
> > My recomendation for long term maintenance is to split fork_blob into 2
> > functions: fs_from_blob, and the ordinary call_usermodehelper_exec.
> > That removes the need for any special support for anything in the exec
> > path because your blob will also have a path for your file, and the
> > file in the filesystem can be reused for restart.
> 
> Yes, that would be an approach for providing information for LSM modules.
> 
> > But with no in-tree users none of us can do anything bug guess what
> > the actual requirements of fork_usermode_blob are.
> 
> Exactly. Since it is not explained why the usermode process started by
> fork_usermode_blob() cannot interfere (or be interfered by) the rest of
> the system (including normal usermode processes), the byte array comes from
> the kernel address space is insufficient for convincing LSM modules to
> ignore what that byte array can do.

Sounds like tomoyo doesn't trust kernel modules. I don't think that is
fixable with any amount of explantation.
Tetsuo Handa June 24, 2020, 4:58 a.m. UTC | #50
On 2020/06/24 13:00, Alexei Starovoitov wrote:
>> However, regarding usermode_blob, although the byte array (which contains code / data)
>> might be initially loaded from the kernel space (which is protected), that byte array
>> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
>> in the user address space. Thus, LSM modules (including pathname based security) want
>> to control how that byte array can behave.
> 
> It's privileged memory regardless. root can poke into kernel or any process memory.

LSM is there to restrict processes running as "root".
Your "root can poke into kernel or any process memory." response is out of step with the times.

Initial byte array used for usermode blob might be protected because of "part of .rodata or
.init.rodata of kernel module", but that byte array after started in userspace is no longer
protected. I don't trust such byte array as "part of kernel module", and I'm asking you how
such byte array does not interfere (or be interfered by) the rest of the system.
Alexei Starovoitov June 24, 2020, 6:05 a.m. UTC | #51
On Tue, Jun 23, 2020 at 9:00 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>
> On Wed, Jun 24, 2020 at 10:51:15AM +0900, Tetsuo Handa wrote:
> > On 2020/06/24 4:40, Alexei Starovoitov wrote:
> > > There is no refcnt bug. It was a user error on tomoyo side.
> > > fork_blob() works as expected.
> >
> > Absolutely wrong! Any check which returns an error during current->in_execve == 1
> > will cause this refcnt bug. You are simply ignoring that there is possibility
> > that execve() fails.
>
> you mean security_bprm_creds_for_exec() denying exec?
> hmm. got it. refcnt model needs to change then.

I think the following trivial change should do it:

diff --git a/kernel/umh.c b/kernel/umh.c
index 79f139a7ca03..f80dd2a93ca4 100644
--- a/kernel/umh.c
+++ b/kernel/umh.c
@@ -512,7 +512,9 @@ int fork_usermode_blob(void *data, size_t len,
struct umh_info *info)
        file = shmem_kernel_file_setup("", len, 0);
        if (IS_ERR(file))
                return PTR_ERR(file);
-
+       err = deny_write_access(file);
+       if (err)
+               goto out_fput;
        written = kernel_write(file, data, len, &pos);
        if (written != len) {
                err = written;
@@ -532,8 +534,11 @@ int fork_usermode_blob(void *data, size_t len,
struct umh_info *info)
                mutex_lock(&umh_list_lock);
                list_add(&info->list, &umh_list);
                mutex_unlock(&umh_list_lock);
+               return 0;
        }
 out:
+       allow_write_access(file);
+out_fput:
        fput(file);
        return err;
 }

I'll do more tests tomorrow and send it with SOB.
Alexei Starovoitov June 24, 2020, 6:39 a.m. UTC | #52
On Wed, Jun 24, 2020 at 01:58:33PM +0900, Tetsuo Handa wrote:
> On 2020/06/24 13:00, Alexei Starovoitov wrote:
> >> However, regarding usermode_blob, although the byte array (which contains code / data)
> >> might be initially loaded from the kernel space (which is protected), that byte array
> >> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
> >> in the user address space. Thus, LSM modules (including pathname based security) want
> >> to control how that byte array can behave.
> > 
> > It's privileged memory regardless. root can poke into kernel or any process memory.
> 
> LSM is there to restrict processes running as "root".

hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
LSM can certainly provide extra level of foolproof-ness against accidental
mistakes, but it's not a security boundary.

> Your "root can poke into kernel or any process memory." response is out of step with the times.
> 
> Initial byte array used for usermode blob might be protected because of "part of .rodata or
> .init.rodata of kernel module", but that byte array after started in userspace is no longer
> protected. 
>
> I don't trust such byte array as "part of kernel module", and I'm asking you how
> such byte array does not interfere (or be interfered by) the rest of the system.

Could you please explain the attack vector that you see in such scenario?
How elf binaries embedded in the kernel modules different from pid 1?
If anything can peek into their memory the system is compromised.
Say, there are no user blobs in kernel modules. How pid 1 memory is different
from all the JITed images? How is it different for all memory regions shared
between kernel and user processes?
I see an opportunity for an LSM to provide a protection against non-security
bugs when system is running trusted apps, but not when arbitrary code can
execute under root.
Tetsuo Handa June 24, 2020, 7:05 a.m. UTC | #53
Forwarding to LSM-ML again. Any comments?

On 2020/06/24 15:39, Alexei Starovoitov wrote:
> On Wed, Jun 24, 2020 at 01:58:33PM +0900, Tetsuo Handa wrote:
>> On 2020/06/24 13:00, Alexei Starovoitov wrote:
>>>> However, regarding usermode_blob, although the byte array (which contains code / data)
>>>> might be initially loaded from the kernel space (which is protected), that byte array
>>>> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
>>>> in the user address space. Thus, LSM modules (including pathname based security) want
>>>> to control how that byte array can behave.
>>>
>>> It's privileged memory regardless. root can poke into kernel or any process memory.
>>
>> LSM is there to restrict processes running as "root".
> 
> hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
> LSM can certainly provide extra level of foolproof-ness against accidental
> mistakes, but it's not a security boundary.
> 
>> Your "root can poke into kernel or any process memory." response is out of step with the times.
>>
>> Initial byte array used for usermode blob might be protected because of "part of .rodata or
>> .init.rodata of kernel module", but that byte array after started in userspace is no longer
>> protected. 
>>
>> I don't trust such byte array as "part of kernel module", and I'm asking you how
>> such byte array does not interfere (or be interfered by) the rest of the system.
> 
> Could you please explain the attack vector that you see in such scenario?
> How elf binaries embedded in the kernel modules different from pid 1?
> If anything can peek into their memory the system is compromised.
> Say, there are no user blobs in kernel modules. How pid 1 memory is different
> from all the JITed images? How is it different for all memory regions shared
> between kernel and user processes?
> I see an opportunity for an LSM to provide a protection against non-security
> bugs when system is running trusted apps, but not when arbitrary code can
> execute under root.
>
Eric W. Biederman June 24, 2020, 12:13 p.m. UTC | #54
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:

> There is no refcnt bug. It was a user error on tomoyo side.
> fork_blob() works as expected.

Nope.  I have independently confirmed it myself.

fork_usermode_blob holds a reference and puts that reference.  An
additional reference is needed for execve to hold and put.

Now can you write some patches to make that obvious please?

Eric
Alexei Starovoitov June 24, 2020, 2:18 p.m. UTC | #55
On Tue, Jun 23, 2020 at 11:05 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>
> On Tue, Jun 23, 2020 at 9:00 PM Alexei Starovoitov
> <alexei.starovoitov@gmail.com> wrote:
> >
> > On Wed, Jun 24, 2020 at 10:51:15AM +0900, Tetsuo Handa wrote:
> > > On 2020/06/24 4:40, Alexei Starovoitov wrote:
> > > > There is no refcnt bug. It was a user error on tomoyo side.
> > > > fork_blob() works as expected.
> > >
> > > Absolutely wrong! Any check which returns an error during current->in_execve == 1
> > > will cause this refcnt bug. You are simply ignoring that there is possibility
> > > that execve() fails.
> >
> > you mean security_bprm_creds_for_exec() denying exec?
> > hmm. got it. refcnt model needs to change then.
>
> I think the following trivial change should do it:
>
> diff --git a/kernel/umh.c b/kernel/umh.c
> index 79f139a7ca03..f80dd2a93ca4 100644
> --- a/kernel/umh.c
> +++ b/kernel/umh.c
> @@ -512,7 +512,9 @@ int fork_usermode_blob(void *data, size_t len,
> struct umh_info *info)
>         file = shmem_kernel_file_setup("", len, 0);
>         if (IS_ERR(file))
>                 return PTR_ERR(file);
> -
> +       err = deny_write_access(file);
> +       if (err)
> +               goto out_fput;
>         written = kernel_write(file, data, len, &pos);
>         if (written != len) {
>                 err = written;
> @@ -532,8 +534,11 @@ int fork_usermode_blob(void *data, size_t len,
> struct umh_info *info)
>                 mutex_lock(&umh_list_lock);
>                 list_add(&info->list, &umh_list);
>                 mutex_unlock(&umh_list_lock);
> +               return 0;
>         }
>  out:
> +       allow_write_access(file);
> +out_fput:
>         fput(file);
>         return err;
>  }
>
> I'll do more tests tomorrow...

yeah. sorry. -enocoffee. It needs more work.
Alexei Starovoitov June 24, 2020, 2:26 p.m. UTC | #56
On Wed, Jun 24, 2020 at 5:17 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
>
> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>
> > On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:
>
> > There is no refcnt bug. It was a user error on tomoyo side.
> > fork_blob() works as expected.
>
> Nope.  I have independently confirmed it myself.

I guess you've tried Tetsuo's fork_blob("#!/bin/true") kernel module ?
yes. that fails. It never meant to be used for this.
With elf blob it works, but breaks if there are rejections
in things like security_bprm_creds_for_exec().
In my mind that path was 'must succeed or kernel module is toast'.
Like passing NULL into a function that doesn't check for it.
Working on a fix for that since Tetsuo cares.
Casey Schaufler June 24, 2020, 3:41 p.m. UTC | #57
On 6/24/2020 12:05 AM, Tetsuo Handa wrote:
> Forwarding to LSM-ML again. Any comments?

Hey, BPF folks - you *really* need to do better about keeping the LSM
community in the loop when you're discussing LSM issues. 

>
> On 2020/06/24 15:39, Alexei Starovoitov wrote:
>> On Wed, Jun 24, 2020 at 01:58:33PM +0900, Tetsuo Handa wrote:
>>> On 2020/06/24 13:00, Alexei Starovoitov wrote:
>>>>> However, regarding usermode_blob, although the byte array (which contains code / data)
>>>>> might be initially loaded from the kernel space (which is protected), that byte array
>>>>> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
>>>>> in the user address space. Thus, LSM modules (including pathname based security) want
>>>>> to control how that byte array can behave.
>>>> It's privileged memory regardless. root can poke into kernel or any process memory.
>>> LSM is there to restrict processes running as "root".
>> hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?

I think that SELinux works hard to do just that. SELinux implements it's own
privilege model that is tangential to the capabilities model.

More directly, it is simple to create a security module to provide finer privilege
granularity than capabilities. I have one lurking in a source tree, and I would
be surprised if it's the only one waiting for the next round of LSM stacking.

>> LSM can certainly provide extra level of foolproof-ness against accidental
>> mistakes, but it's not a security boundary.

Gasp! Them's fight'n words. How do you justify such an outrageous claim?

>>> Your "root can poke into kernel or any process memory." response is out of step with the times.
>>>
>>> Initial byte array used for usermode blob might be protected because of "part of .rodata or
>>> .init.rodata of kernel module", but that byte array after started in userspace is no longer
>>> protected. 
>>>
>>> I don't trust such byte array as "part of kernel module", and I'm asking you how
>>> such byte array does not interfere (or be interfered by) the rest of the system.
>> Could you please explain the attack vector that you see in such scenario?
>> How elf binaries embedded in the kernel modules different from pid 1?
>> If anything can peek into their memory the system is compromised.
>> Say, there are no user blobs in kernel modules. How pid 1 memory is different
>> from all the JITed images? How is it different for all memory regions shared
>> between kernel and user processes?
>> I see an opportunity for an LSM to provide a protection against non-security
>> bugs when system is running trusted apps, but not when arbitrary code can
>> execute under root.
>>
Alexei Starovoitov June 24, 2020, 5:54 p.m. UTC | #58
On Wed, Jun 24, 2020 at 08:41:37AM -0700, Casey Schaufler wrote:
> On 6/24/2020 12:05 AM, Tetsuo Handa wrote:
> > Forwarding to LSM-ML again. Any comments?
> 
> Hey, BPF folks - you *really* need to do better about keeping the LSM
> community in the loop when you're discussing LSM issues. 
> 
> >
> > On 2020/06/24 15:39, Alexei Starovoitov wrote:
> >> On Wed, Jun 24, 2020 at 01:58:33PM +0900, Tetsuo Handa wrote:
> >>> On 2020/06/24 13:00, Alexei Starovoitov wrote:
> >>>>> However, regarding usermode_blob, although the byte array (which contains code / data)
> >>>>> might be initially loaded from the kernel space (which is protected), that byte array
> >>>>> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
> >>>>> in the user address space. Thus, LSM modules (including pathname based security) want
> >>>>> to control how that byte array can behave.
> >>>> It's privileged memory regardless. root can poke into kernel or any process memory.
> >>> LSM is there to restrict processes running as "root".
> >> hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
> 
> I think that SELinux works hard to do just that. SELinux implements it's own
> privilege model that is tangential to the capabilities model.

of course. no argument here.

> More directly, it is simple to create a security module to provide finer privilege
> granularity than capabilities. I have one lurking in a source tree, and I would
> be surprised if it's the only one waiting for the next round of LSM stacking.

no one is arguing with that either.

> 
> >> LSM can certainly provide extra level of foolproof-ness against accidental
> >> mistakes, but it's not a security boundary.
> 
> Gasp! Them's fight'n words. How do you justify such an outrageous claim?

.. for root user processes.
What's outrageous about that?
Did you capture the context or just replying to few sentences out of the context?
Casey Schaufler June 24, 2020, 7:48 p.m. UTC | #59
On 6/24/2020 10:54 AM, Alexei Starovoitov wrote:
> On Wed, Jun 24, 2020 at 08:41:37AM -0700, Casey Schaufler wrote:
>> On 6/24/2020 12:05 AM, Tetsuo Handa wrote:
>>> Forwarding to LSM-ML again. Any comments?
>> Hey, BPF folks - you *really* need to do better about keeping the LSM
>> community in the loop when you're discussing LSM issues. 
>>
>>> On 2020/06/24 15:39, Alexei Starovoitov wrote:
>>>> On Wed, Jun 24, 2020 at 01:58:33PM +0900, Tetsuo Handa wrote:
>>>>> On 2020/06/24 13:00, Alexei Starovoitov wrote:
>>>>>>> However, regarding usermode_blob, although the byte array (which contains code / data)
>>>>>>> might be initially loaded from the kernel space (which is protected), that byte array
>>>>>>> is no longer protected (e.g. SIGKILL, strace()) when executed because they are placed
>>>>>>> in the user address space. Thus, LSM modules (including pathname based security) want
>>>>>>> to control how that byte array can behave.
>>>>>> It's privileged memory regardless. root can poke into kernel or any process memory.
>>>>> LSM is there to restrict processes running as "root".
>>>> hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
>> I think that SELinux works hard to do just that. SELinux implements it's own
>> privilege model that is tangential to the capabilities model.
> of course. no argument here.
>
>> More directly, it is simple to create a security module to provide finer privilege
>> granularity than capabilities. I have one lurking in a source tree, and I would
>> be surprised if it's the only one waiting for the next round of LSM stacking.
> no one is arguing with that either.
>
>>>> LSM can certainly provide extra level of foolproof-ness against accidental
>>>> mistakes, but it's not a security boundary.
>> Gasp! Them's fight'n words. How do you justify such an outrageous claim?
> .. for root user processes.
> What's outrageous about that?
> Did you capture the context or just replying to few sentences out of the context?

As I mentioned above, you need to include the LSM list in these discussions.
If you don't want "out of context" comments. I replied to what's presented.
And regardless of the context, saying that an LSM can't provide a security
boundary for "root user processes" is just wrong. Obviously there's been more
to the conversation than is included here.
Tetsuo Handa June 24, 2020, 11:14 p.m. UTC | #60
On 2020/06/24 23:26, Alexei Starovoitov wrote:
> On Wed, Jun 24, 2020 at 5:17 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
>>
>> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>>
>>> On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:
>>
>>> There is no refcnt bug. It was a user error on tomoyo side.
>>> fork_blob() works as expected.
>>
>> Nope.  I have independently confirmed it myself.
> 
> I guess you've tried Tetsuo's fork_blob("#!/bin/true") kernel module ?
> yes. that fails. It never meant to be used for this.
> With elf blob it works, but breaks if there are rejections
> in things like security_bprm_creds_for_exec().
> In my mind that path was 'must succeed or kernel module is toast'.
> Like passing NULL into a function that doesn't check for it.
> Working on a fix for that since Tetsuo cares.
> 

What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
a file with empty filename. I can imagine that somebody would start abusing
fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
udevd and sshd. When such situation happened, how fork_usermode_blob() provides
information for identifying the intent of such execve() requests?

fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
to associate appropriate security labels based on the content of the byte array
because files are created on-demand. Is fork_usermode_blob() friendly to inode
based LSMs?
Alexei Starovoitov June 25, 2020, 1:35 a.m. UTC | #61
On Thu, Jun 25, 2020 at 08:14:20AM +0900, Tetsuo Handa wrote:
> On 2020/06/24 23:26, Alexei Starovoitov wrote:
> > On Wed, Jun 24, 2020 at 5:17 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
> >>
> >> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
> >>
> >>> On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:
> >>
> >>> There is no refcnt bug. It was a user error on tomoyo side.
> >>> fork_blob() works as expected.
> >>
> >> Nope.  I have independently confirmed it myself.
> > 
> > I guess you've tried Tetsuo's fork_blob("#!/bin/true") kernel module ?
> > yes. that fails. It never meant to be used for this.
> > With elf blob it works, but breaks if there are rejections
> > in things like security_bprm_creds_for_exec().
> > In my mind that path was 'must succeed or kernel module is toast'.
> > Like passing NULL into a function that doesn't check for it.
> > Working on a fix for that since Tetsuo cares.
> > 
> 
> What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
> a file with empty filename. I can imagine that somebody would start abusing
> fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
> udevd and sshd. When such situation happened, how fork_usermode_blob() provides
> information for identifying the intent of such execve() requests?
> 
> fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
> SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
> to associate appropriate security labels based on the content of the byte array
> because files are created on-demand. Is fork_usermode_blob() friendly to inode
> based LSMs?

blob is started by a kernel module. Regardless of path existence that kernel module
could have disabled any LSM and any kernel security mechanism.
People who write out of tree kernel modules found ways to bypass EXPORT_SYMBOL
with and without _GPL. Modules can do anything. It's only the number of hoops
they need to jump through to get what they want. 
Signed and in-tree kernel module is the only way to protect the integrity of the system.
That's why user blob is part of kernel module elf object and it's covered by the same
module signature verification logic.
Tetsuo Handa June 25, 2020, 6:38 a.m. UTC | #62
On 2020/06/25 10:35, Alexei Starovoitov wrote:
>> What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
>> a file with empty filename. I can imagine that somebody would start abusing
>> fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
>> udevd and sshd. When such situation happened, how fork_usermode_blob() provides
>> information for identifying the intent of such execve() requests?
>>
>> fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
>> SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
>> to associate appropriate security labels based on the content of the byte array
>> because files are created on-demand. Is fork_usermode_blob() friendly to inode
>> based LSMs?
> 
> blob is started by a kernel module. Regardless of path existence that kernel module
> could have disabled any LSM and any kernel security mechanism.
> People who write out of tree kernel modules found ways to bypass EXPORT_SYMBOL
> with and without _GPL. Modules can do anything. It's only the number of hoops
> they need to jump through to get what they want.

So what? I know that. That's irrelevant to my questions.

> Signed and in-tree kernel module is the only way to protect the integrity of the system.
> That's why user blob is part of kernel module elf object and it's covered by the same
> module signature verification logic.

My questions are:

(1) "Signed and in-tree kernel module" assertion is pointless.
    In future, some of in-tree kernel modules might start using fork_usermode_blob()
    instead of call_usermodehelper(), with instructions containing what your initial
    use case does not use. There is no guarantee that such thing can't happen.
    Assuming that there will be multiple blobs, we need a way to identify these blobs.
    How does fork_usermode_blob() provide information for identification?

(2) Running some blob in usermode means that permission checks by LSM modules will
    be enforced. For example, socket's shutdown operation via shutdown() syscall from
    usermode blob will involve security_socket_shutdown() check.
    
    ----------
    int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
    {
            return sock->ops->shutdown(sock, how);
    }
    ----------
    
    ----------
    int __sys_shutdown(int fd, int how)
    {
            int err, fput_needed;
            struct socket *sock;
    
            sock = sockfd_lookup_light(fd, &err, &fput_needed);
            if (sock != NULL) {
                    err = security_socket_shutdown(sock, how);
                    if (!err)
                            err = sock->ops->shutdown(sock, how);
                    fput_light(sock->file, fput_needed);
            }
            return err;
    }
    
    SYSCALL_DEFINE2(shutdown, int, fd, int, how)
    {
            return __sys_shutdown(fd, how);
    }
    ----------
    
    I don't know what instructions your blob would contain. But even if the blobs
    containing your initial use case use only setsockopt()/getsockopt() syscalls,
    LSM modules have rights to inspect and reject these requests from usermode blobs
    via security_socket_setsockopt()/security_socket_getsockopt() hooks. In order to
    inspect these requests, LSM modules need information (so called "security context"),
    and fork_usermode_blob() has to be able to somehow teach that information to LSM
    modules. Pathname is one of information for pathname based LSM modules. Inode's
    security label is one of information for inode based LSM modules.
    
    call_usermodehelper() can teach LSM modules via pre-existing file's pathname and
    inode's security label at security_bprm_creds_for_exec()/security_bprm_check() etc.
    But since fork_usermode_blob() accepts only "byte array" and "length of byte array"
    arguments, I'm not sure whether LSM modules can obtain information needed for
    inspection. How does fork_usermode_blob() tell that information?

(3) Again, "root can poke into kernel or any process memory." assertion is pointless.
    Answering to your questions

      > hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
      Not every LSM module restricts CAP_* flags. But LSM modules can implement finer grained
      restrictions than plain CAP_* flags.

      > How elf binaries embedded in the kernel modules different from pid 1?
      No difference.

      > If anything can peek into their memory the system is compromised.
      Permission checks via LSM modules are there to prevent such behavior.

      > Say, there are no user blobs in kernel modules. How pid 1 memory is different
      > from all the JITed images? How is it different for all memory regions shared
      > between kernel and user processes?
      I don't know what "the JITed images" means. But I guess that the answer is
      "No difference".

    Then, I ask you back.

    Although the byte array (which contains code / data) might be initially loaded from
    the kernel space (which is protected), that byte array is no longer protected (e.g.
    SIGKILL, ptrace()) when executed because they are placed in the user address space.

    Why the usermode process started by fork_usermode_blob() cannot interfere (or be
    interfered by) the rest of the system (including normal usermode processes) ?
    And I guess that your answer is "the usermode process started by fork_usermode_blob()
    _can_ (and be interfered by) the rest of the system, for they are nothing but
    normal usermode processes."

    Thus, LSM modules (including pathname based security) want to control how that byte
    array can behave. And how does fork_usermode_blob() tell necessary information?

Your answers up to now did not convince LSM modules to ignore what the usermode process
started by fork_usermode_blob() can do. If you again don't answer my questions, I'll
ack to https://lkml.kernel.org/r/875zc4c86z.fsf_-_@x220.int.ebiederm.org .
Greg KH June 25, 2020, 9:57 a.m. UTC | #63
On Thu, Jun 25, 2020 at 03:38:14PM +0900, Tetsuo Handa wrote:
> On 2020/06/25 10:35, Alexei Starovoitov wrote:
> >> What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
> >> a file with empty filename. I can imagine that somebody would start abusing
> >> fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
> >> udevd and sshd. When such situation happened, how fork_usermode_blob() provides
> >> information for identifying the intent of such execve() requests?
> >>
> >> fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
> >> SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
> >> to associate appropriate security labels based on the content of the byte array
> >> because files are created on-demand. Is fork_usermode_blob() friendly to inode
> >> based LSMs?
> > 
> > blob is started by a kernel module. Regardless of path existence that kernel module
> > could have disabled any LSM and any kernel security mechanism.
> > People who write out of tree kernel modules found ways to bypass EXPORT_SYMBOL
> > with and without _GPL. Modules can do anything. It's only the number of hoops
> > they need to jump through to get what they want.
> 
> So what? I know that. That's irrelevant to my questions.
> 
> > Signed and in-tree kernel module is the only way to protect the integrity of the system.
> > That's why user blob is part of kernel module elf object and it's covered by the same
> > module signature verification logic.
> 
> My questions are:
> 
> (1) "Signed and in-tree kernel module" assertion is pointless.
>     In future, some of in-tree kernel modules might start using fork_usermode_blob()
>     instead of call_usermodehelper(), with instructions containing what your initial
>     use case does not use. There is no guarantee that such thing can't happen.

I hope that this would happen for some tools, what's wrong with that?
That means we can ship those programs from within the kernel source tree
instead of trying to rely on keeping a specific user/kernel api stable
for forever.

That would be a good thing, right?

>     Assuming that there will be multiple blobs, we need a way to identify these blobs.
>     How does fork_usermode_blob() provide information for identification?

If the kernel itself was running these blobs, why would LSM care about
it?  These are coming from "within the building!" don't you trust the
kernel already?

I don't understand the issue here.


> (2) Running some blob in usermode means that permission checks by LSM modules will
>     be enforced. For example, socket's shutdown operation via shutdown() syscall from
>     usermode blob will involve security_socket_shutdown() check.
>     
>     ----------
>     int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
>     {
>             return sock->ops->shutdown(sock, how);
>     }
>     ----------
>     
>     ----------
>     int __sys_shutdown(int fd, int how)
>     {
>             int err, fput_needed;
>             struct socket *sock;
>     
>             sock = sockfd_lookup_light(fd, &err, &fput_needed);
>             if (sock != NULL) {
>                     err = security_socket_shutdown(sock, how);
>                     if (!err)
>                             err = sock->ops->shutdown(sock, how);
>                     fput_light(sock->file, fput_needed);
>             }
>             return err;
>     }
>     
>     SYSCALL_DEFINE2(shutdown, int, fd, int, how)
>     {
>             return __sys_shutdown(fd, how);
>     }
>     ----------
>     
>     I don't know what instructions your blob would contain. But even if the blobs
>     containing your initial use case use only setsockopt()/getsockopt() syscalls,
>     LSM modules have rights to inspect and reject these requests from usermode blobs
>     via security_socket_setsockopt()/security_socket_getsockopt() hooks. In order to
>     inspect these requests, LSM modules need information (so called "security context"),
>     and fork_usermode_blob() has to be able to somehow teach that information to LSM
>     modules. Pathname is one of information for pathname based LSM modules. Inode's
>     security label is one of information for inode based LSM modules.
>     
>     call_usermodehelper() can teach LSM modules via pre-existing file's pathname and
>     inode's security label at security_bprm_creds_for_exec()/security_bprm_check() etc.
>     But since fork_usermode_blob() accepts only "byte array" and "length of byte array"
>     arguments, I'm not sure whether LSM modules can obtain information needed for
>     inspection. How does fork_usermode_blob() tell that information?

It would seem that the "security context" for those would be the same as
anything created before userspace launches today, right?  You handle
that ok, and this should be just the same.

But again, as these programs are coming from "within the kernel", why
would you want to disallow them?  If you don't want to allow them, don't
build them into your kernel?  :)

> (3) Again, "root can poke into kernel or any process memory." assertion is pointless.
>     Answering to your questions
> 
>       > hmm. do you really mean that it's possible for an LSM to restrict CAP_SYS_ADMIN effectively?
>       Not every LSM module restricts CAP_* flags. But LSM modules can implement finer grained
>       restrictions than plain CAP_* flags.
> 
>       > How elf binaries embedded in the kernel modules different from pid 1?
>       No difference.
> 
>       > If anything can peek into their memory the system is compromised.
>       Permission checks via LSM modules are there to prevent such behavior.
> 
>       > Say, there are no user blobs in kernel modules. How pid 1 memory is different
>       > from all the JITed images? How is it different for all memory regions shared
>       > between kernel and user processes?
>       I don't know what "the JITed images" means. But I guess that the answer is
>       "No difference".
> 
>     Then, I ask you back.
> 
>     Although the byte array (which contains code / data) might be initially loaded from
>     the kernel space (which is protected), that byte array is no longer protected (e.g.
>     SIGKILL, ptrace()) when executed because they are placed in the user address space.
>
>     Why the usermode process started by fork_usermode_blob() cannot interfere (or be
>     interfered by) the rest of the system (including normal usermode processes) ?
>     And I guess that your answer is "the usermode process started by fork_usermode_blob()
>     _can_ (and be interfered by) the rest of the system, for they are nothing but
>     normal usermode processes."
> 
>     Thus, LSM modules (including pathname based security) want to control how that byte
>     array can behave. And how does fork_usermode_blob() tell necessary information?

Think of these blobs just as any other kernel module would be today.
Right now I, as a kernel module, can read/write to any file in the
system, and do all sorts of other fun things.  You can't mediate that
today from a LSM, and this is just one other example of this.

The "only" change is that now this code is running in userspace context,
which for an overall security/system issue, should be better than
running it in kernel context, right?

Perhaps we just add new LSM hooks for every place that we call this new
function to run a blob?  That will give you the needed "the kernel is
about to run a blob that we think is a userspace USB IR filter driver",
or whatever the blob does.

Would that help out?

But, given that we don't even have any in-kernel users, all of this
feels like a lot of arguing over something that no one can currently
even have happen...

thanks,

greg k-h
Tetsuo Handa June 25, 2020, 11:03 a.m. UTC | #64
On 2020/06/25 18:57, Greg KH wrote:
> On Thu, Jun 25, 2020 at 03:38:14PM +0900, Tetsuo Handa wrote:
>> My questions are:
>>
>> (1) "Signed and in-tree kernel module" assertion is pointless.
>>     In future, some of in-tree kernel modules might start using fork_usermode_blob()
>>     instead of call_usermodehelper(), with instructions containing what your initial
>>     use case does not use. There is no guarantee that such thing can't happen.
> 
> I hope that this would happen for some tools, what's wrong with that?
> That means we can ship those programs from within the kernel source tree
> instead of trying to rely on keeping a specific user/kernel api stable
> for forever.
> 
> That would be a good thing, right?

Some in-tree users might start embedding byte array containing userspace programs
like /bin/sh when building kernels. How can we prove that such thing won't happen?
I consider that the byte array can contain arbitrary instructions (regardless of
some tools used for building the byte array).

> 
>>     Assuming that there will be multiple blobs, we need a way to identify these blobs.
>>     How does fork_usermode_blob() provide information for identification?
> 
> If the kernel itself was running these blobs, why would LSM care about
> it?  These are coming from "within the building!" don't you trust the
> kernel already?
> 
> I don't understand the issue here.

The byte array came from the kernel, but due to possibility of "root can poke into
kernel or any process memory.", that byte array can become as untrusted as byte
array coming from userspace. There is no concept like "the kernel itself _is_ running
these blobs". Only a fact "the byte array _was_ copied from the kernel address space
(rather than from some file on the filesystem)" exists. We need a mechanism (ideally,
without counting on LSMs) for avoid peeking/poking etc. into/from the byte array
which was copied from the kernel address space to user address space.



>>     call_usermodehelper() can teach LSM modules via pre-existing file's pathname and
>>     inode's security label at security_bprm_creds_for_exec()/security_bprm_check() etc.
>>     But since fork_usermode_blob() accepts only "byte array" and "length of byte array"
>>     arguments, I'm not sure whether LSM modules can obtain information needed for
>>     inspection. How does fork_usermode_blob() tell that information?
> 
> It would seem that the "security context" for those would be the same as
> anything created before userspace launches today, right?  You handle
> that ok, and this should be just the same.

I don't think so. Today when call_usermodehelper() is called, LSMs switch their security
context (at least TOMOYO does it) for further syscalls from the usermode process started
by the kernel context. But when fork_usermode_blob() is called, how LSMs can switch their
security context for further syscalls from the usermode process started by the kernel
context?

> 
> But again, as these programs are coming from "within the kernel", why
> would you want to disallow them?  If you don't want to allow them, don't
> build them into your kernel?  :)

I'm talking about not only "disallow unauthorized execve() request" but also "disallow
unauthorized syscalls after execve() request". Coming from the kernel is not important.



>>     Thus, LSM modules (including pathname based security) want to control how that byte
>>     array can behave. And how does fork_usermode_blob() tell necessary information?
> 
> Think of these blobs just as any other kernel module would be today.

No, I can't. How can we guarantee that the byte array came from kernel remains intact
despite the possibility of "root can poke into kernel or any process memory" ?

> Right now I, as a kernel module, can read/write to any file in the
> system, and do all sorts of other fun things.  You can't mediate that
> today from a LSM, and this is just one other example of this.

Some functions (e.g. kernel_sock_shutdown()) bypass permission checks by LSMs
comes from a sort of trustness that the byte array kept inside kernel address
space remains secure/intact.

> 
> The "only" change is that now this code is running in userspace context,
> which for an overall security/system issue, should be better than
> running it in kernel context, right?

As soon as exposing that byte array outside of kernel address space, processes
running such byte array are considered insecure/tampered. We can't prove that
the byte array exposed to outside of kernel address space does only limited
set of instructions, and we have to perform permission checks by LSMs.

And LSMs need to receive the intent (or "security context" argument) from fork_usermode_blob()
for restricting further syscalls by the usermode process started via fork_usermode_blob().

> 
> Perhaps we just add new LSM hooks for every place that we call this new
> function to run a blob?  That will give you the needed "the kernel is
> about to run a blob that we think is a userspace USB IR filter driver",
> or whatever the blob does.

Yes, that would be the intent (or "security context" argument) fork_usermode_blob()
is missing. Though I don't know how such stringuish argument can be represented for
individual LSM modules...
Greg KH June 25, 2020, 12:07 p.m. UTC | #65
On Thu, Jun 25, 2020 at 08:03:26PM +0900, Tetsuo Handa wrote:
> On 2020/06/25 18:57, Greg KH wrote:
> > On Thu, Jun 25, 2020 at 03:38:14PM +0900, Tetsuo Handa wrote:
> >> My questions are:
> >>
> >> (1) "Signed and in-tree kernel module" assertion is pointless.
> >>     In future, some of in-tree kernel modules might start using fork_usermode_blob()
> >>     instead of call_usermodehelper(), with instructions containing what your initial
> >>     use case does not use. There is no guarantee that such thing can't happen.
> > 
> > I hope that this would happen for some tools, what's wrong with that?
> > That means we can ship those programs from within the kernel source tree
> > instead of trying to rely on keeping a specific user/kernel api stable
> > for forever.
> > 
> > That would be a good thing, right?
> 
> Some in-tree users might start embedding byte array containing userspace programs
> like /bin/sh when building kernels. How can we prove that such thing won't happen?

We have the code, we can read it, we can say, "hey, looks like you are
including bash, do you want to do that?"  :)

> I consider that the byte array can contain arbitrary instructions (regardless of
> some tools used for building the byte array).

Sure, and is this a problem?

> >>     Assuming that there will be multiple blobs, we need a way to identify these blobs.
> >>     How does fork_usermode_blob() provide information for identification?
> > 
> > If the kernel itself was running these blobs, why would LSM care about
> > it?  These are coming from "within the building!" don't you trust the
> > kernel already?
> > 
> > I don't understand the issue here.
> 
> The byte array came from the kernel, but due to possibility of "root can poke into
> kernel or any process memory.", that byte array can become as untrusted as byte
> array coming from userspace. There is no concept like "the kernel itself _is_ running
> these blobs". Only a fact "the byte array _was_ copied from the kernel address space
> (rather than from some file on the filesystem)" exists. We need a mechanism (ideally,
> without counting on LSMs) for avoid peeking/poking etc. into/from the byte array
> which was copied from the kernel address space to user address space.

And what are you going to do with that if you can "look at the array"?
I really don't understand the objection here, why is this any different
than any other random kernel driver for what it can do?

> >>     call_usermodehelper() can teach LSM modules via pre-existing file's pathname and
> >>     inode's security label at security_bprm_creds_for_exec()/security_bprm_check() etc.
> >>     But since fork_usermode_blob() accepts only "byte array" and "length of byte array"
> >>     arguments, I'm not sure whether LSM modules can obtain information needed for
> >>     inspection. How does fork_usermode_blob() tell that information?
> > 
> > It would seem that the "security context" for those would be the same as
> > anything created before userspace launches today, right?  You handle
> > that ok, and this should be just the same.
> 
> I don't think so. Today when call_usermodehelper() is called, LSMs switch their security
> context (at least TOMOYO does it) for further syscalls from the usermode process started
> by the kernel context. But when fork_usermode_blob() is called, how LSMs can switch their
> security context for further syscalls from the usermode process started by the kernel
> context?

Ok, that makes a bit more sense.  Why not just do the same thing that
you do today with call_usermodehelper()?  The logic in a way is the
same, right?

> > But again, as these programs are coming from "within the kernel", why
> > would you want to disallow them?  If you don't want to allow them, don't
> > build them into your kernel?  :)
> 
> I'm talking about not only "disallow unauthorized execve() request" but also "disallow
> unauthorized syscalls after execve() request". Coming from the kernel is not important.

Ok, then do the same thing that you do for call_usermodehelper() to
prevent this.

> >>     Thus, LSM modules (including pathname based security) want to control how that byte
> >>     array can behave. And how does fork_usermode_blob() tell necessary information?
> > 
> > Think of these blobs just as any other kernel module would be today.
> 
> No, I can't. How can we guarantee that the byte array came from kernel remains intact
> despite the possibility of "root can poke into kernel or any process memory" ?

You guarantee it the same way you guarantee that the wifi driver really
is running the code you think it is running.  There is no difference
here.

> > Right now I, as a kernel module, can read/write to any file in the
> > system, and do all sorts of other fun things.  You can't mediate that
> > today from a LSM, and this is just one other example of this.
> 
> Some functions (e.g. kernel_sock_shutdown()) bypass permission checks by LSMs
> comes from a sort of trustness that the byte array kept inside kernel address
> space remains secure/intact.

And what is going to change that "trustness" here?  The byte array came
from the kernel address space to start with.  Are you thinking something
outside of the kernel will then tamper with those bytes to do something
else with them?  If so, shouldn't you be preventing that userspace
program that does the tampering from doing that in the first place with
the LSM running?

> > The "only" change is that now this code is running in userspace context,
> > which for an overall security/system issue, should be better than
> > running it in kernel context, right?
> 
> As soon as exposing that byte array outside of kernel address space, processes
> running such byte array are considered insecure/tampered.

Why?  Do you mean that you do not trust any program once it has been
started either?  If you can, why not do the same thing here?

> We can't prove that
> the byte array exposed to outside of kernel address space does only limited
> set of instructions, and we have to perform permission checks by LSMs.

Those checks should come through the same way you check any other
userspace program through an LSM.  Fix up the context like mentioned
above with call_usermodehelper() and you should be fine, right?

> And LSMs need to receive the intent (or "security context" argument) from fork_usermode_blob()
> for restricting further syscalls by the usermode process started via fork_usermode_blob().
> 
> > 
> > Perhaps we just add new LSM hooks for every place that we call this new
> > function to run a blob?  That will give you the needed "the kernel is
> > about to run a blob that we think is a userspace USB IR filter driver",
> > or whatever the blob does.
> 
> Yes, that would be the intent (or "security context" argument) fork_usermode_blob()
> is missing. Though I don't know how such stringuish argument can be represented for
> individual LSM modules...

The same way we do it today for any LSM callback?  i.e. by a new
function call :)

thanks,

greg k-h
Stephen Smalley June 25, 2020, 12:56 p.m. UTC | #66
On Wed, Jun 24, 2020 at 7:16 PM Tetsuo Handa
<penguin-kernel@i-love.sakura.ne.jp> wrote:
> What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
> a file with empty filename. I can imagine that somebody would start abusing
> fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
> udevd and sshd. When such situation happened, how fork_usermode_blob() provides
> information for identifying the intent of such execve() requests?
>
> fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
> SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
> to associate appropriate security labels based on the content of the byte array
> because files are created on-demand. Is fork_usermode_blob() friendly to inode
> based LSMs?

No, because we cannot label the inode based on the program's purpose
and therefore cannot configure an automatic transition to a suitable
security context for the process, unlike call_usermodehelper(). It is
important to note that the goal of such transitions is not merely to
restrict the program from doing bad things but also to protect the
program from untrustworthy inputs, e.g. one can run kmod/modprobe in a
domain that can only read from authorized kernel modules, prevent
following untrusted symlinks, etc.  Further, at present, the
implementation creates the inode via shmem_kernel_file_setup(), which
is supposed to be for inodes private to the kernel not exposed to
userspace (hence marked S_PRIVATE), which I believe in this case will
end up leaving the inode unlabeled but still end up firing checks in
the bprm hooks on the file inode, thereby potentially yielding denials
in SELinux on the exec of unlabeled files.  Not exactly what we would
want.  If users were to switch from using call_usermodehelper() to
fork_usermode_blob() we would need them to label the inode in some
manner to reflect the program purpose prior to exec.  I suppose they
could pass in some string key and SELinux could look it up in policy
to get a context to use or something.

On a different note, will the usermode blob be measured by IMA prior
to execution?  What ensures that the blob was actually embedded in the
kernel image and wasn't just supplied as data through exploitation of
a kernel vulnerability or malicious kernel module?  Yes, things are
already bad at that point but it would be good to be able to detect
launch of the malicious userspace payload regardless (kernel exploit
can't undo the measurement extended into the TPM even if it tampers
with the IMA measurement list in the kernel, nor fake a quote signed
by the TPM).
Greg KH June 25, 2020, 1:25 p.m. UTC | #67
On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
> On Wed, Jun 24, 2020 at 7:16 PM Tetsuo Handa
> <penguin-kernel@i-love.sakura.ne.jp> wrote:
> > What is unhappy for pathname based LSMs is that fork_usermode_blob() creates
> > a file with empty filename. I can imagine that somebody would start abusing
> > fork_usermode_blob() as an interface for starting programs like modprobe, hotplug,
> > udevd and sshd. When such situation happened, how fork_usermode_blob() provides
> > information for identifying the intent of such execve() requests?
> >
> > fork_usermode_blob() might also be an unhappy behavior for inode based LSMs (like
> > SELinux and Smack) because it seems that fork_usermode_blob() can't have a chance
> > to associate appropriate security labels based on the content of the byte array
> > because files are created on-demand. Is fork_usermode_blob() friendly to inode
> > based LSMs?
> 
> No, because we cannot label the inode based on the program's purpose
> and therefore cannot configure an automatic transition to a suitable
> security context for the process, unlike call_usermodehelper().

Why, what prevents this?  Can you not just do that based on the "blob
address" or signature of it or something like that?  Right now you all
do this based on inode of a random file on a disk, what's the difference
between a random blob in memory?

> It is
> important to note that the goal of such transitions is not merely to
> restrict the program from doing bad things but also to protect the
> program from untrustworthy inputs, e.g. one can run kmod/modprobe in a
> domain that can only read from authorized kernel modules, prevent
> following untrusted symlinks, etc.  Further, at present, the
> implementation creates the inode via shmem_kernel_file_setup(), which
> is supposed to be for inodes private to the kernel not exposed to
> userspace (hence marked S_PRIVATE), which I believe in this case will
> end up leaving the inode unlabeled but still end up firing checks in
> the bprm hooks on the file inode, thereby potentially yielding denials
> in SELinux on the exec of unlabeled files.  Not exactly what we would
> want.  If users were to switch from using call_usermodehelper() to
> fork_usermode_blob() we would need them to label the inode in some
> manner to reflect the program purpose prior to exec.  I suppose they
> could pass in some string key and SELinux could look it up in policy
> to get a context to use or something.

Sure, that would work.

> On a different note, will the usermode blob be measured by IMA prior
> to execution?  What ensures that the blob was actually embedded in the
> kernel image and wasn't just supplied as data through exploitation of
> a kernel vulnerability or malicious kernel module?

No reason it couldn't be passed to IMA for measuring, if people want to
do that.

thanks,

greg k-h
Tetsuo Handa June 25, 2020, 2:21 p.m. UTC | #68
On 2020/06/25 21:07, Greg KH wrote:
>>>>     call_usermodehelper() can teach LSM modules via pre-existing file's pathname and
>>>>     inode's security label at security_bprm_creds_for_exec()/security_bprm_check() etc.
>>>>     But since fork_usermode_blob() accepts only "byte array" and "length of byte array"
>>>>     arguments, I'm not sure whether LSM modules can obtain information needed for
>>>>     inspection. How does fork_usermode_blob() tell that information?
>>>
>>> It would seem that the "security context" for those would be the same as
>>> anything created before userspace launches today, right?  You handle
>>> that ok, and this should be just the same.
>>
>> I don't think so. Today when call_usermodehelper() is called, LSMs switch their security
>> context (at least TOMOYO does it) for further syscalls from the usermode process started
>> by the kernel context. But when fork_usermode_blob() is called, how LSMs can switch their
>> security context for further syscalls from the usermode process started by the kernel
>> context?
> 
> Ok, that makes a bit more sense.  Why not just do the same thing that
> you do today with call_usermodehelper()?  The logic in a way is the
> same, right?
> 

call_usermodehelper() provides information like "the kernel is about to run
/sbin/modprobe in order to load foo module" but fork_usermode_blob() does not
provide information like "the kernel is about to run a blob that we think is
a userspace USB IR filter driver". That is unfriendly to LSM modules.

> 
>>> Right now I, as a kernel module, can read/write to any file in the
>>> system, and do all sorts of other fun things.  You can't mediate that
>>> today from a LSM, and this is just one other example of this.
>>
>> Some functions (e.g. kernel_sock_shutdown()) bypass permission checks by LSMs
>> comes from a sort of trustness that the byte array kept inside kernel address
>> space remains secure/intact.
> 
> And what is going to change that "trustness" here?  The byte array came
> from the kernel address space to start with.  Are you thinking something
> outside of the kernel will then tamper with those bytes to do something
> else with them?

Right. e.g. ptrace() will allow reading/writing those bytes to do something
else with them. I guess 'gdb -p' is the same meaning.

>                  If so, shouldn't you be preventing that userspace
> program that does the tampering from doing that in the first place with
> the LSM running?

SELinux can handle process isolation very well. But the reality is that none of customers
I'm working for can afford using SELinux because SELinux is too complicated to support.
Instead, they use proprietary antivirus kernel modules (which tamper with syscall tables
and/or security_hook_heads). Therefore, I wish that isolation between processes running
fork_usermode_blob() and processes running normal usermode programs is implemented by
built-in mechanism (like DAC), and I said

  We might need to invent built-in "protected userspace" because existing
  "unprotected userspace" is not trustworthy enough to run kernel modules.
  That's not just inventing fork_usermode_blob().

at https://lkml.kernel.org/r/62859212-df69-b913-c1e0-cd2e358d1adf@i-love.sakura.ne.jp .
I'm happy if we can implement such isolation without counting on in-tree LSMs.
Stephen Smalley June 25, 2020, 2:26 p.m. UTC | #69
On Thu, Jun 25, 2020 at 9:25 AM Greg Kroah-Hartman
<gregkh@linuxfoundation.org> wrote:
>
> On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
> > No, because we cannot label the inode based on the program's purpose
> > and therefore cannot configure an automatic transition to a suitable
> > security context for the process, unlike call_usermodehelper().
>
> Why, what prevents this?  Can you not just do that based on the "blob
> address" or signature of it or something like that?  Right now you all
> do this based on inode of a random file on a disk, what's the difference
> between a random blob in memory?

Given some kind of key to identify the blob and look up a suitable
context in policy, I think it would work.  We just don't have that
with the current interface.  With /bin/kmod and the like, we have a
security xattr assigned to the file when it was created that we can
use as the basis for determining the process security context.

> > On a different note, will the usermode blob be measured by IMA prior
> > to execution?  What ensures that the blob was actually embedded in the
> > kernel image and wasn't just supplied as data through exploitation of
> > a kernel vulnerability or malicious kernel module?
>
> No reason it couldn't be passed to IMA for measuring, if people want to
> do that.

Actually, I think it probably happens already via IMA's existing hooks
but just wanted to confirm that IMA doesn't ignore S_PRIVATE inodes.
Stephen Smalley June 25, 2020, 2:36 p.m. UTC | #70
On Thu, Jun 25, 2020 at 10:26 AM Stephen Smalley
<stephen.smalley.work@gmail.com> wrote:
>
> On Thu, Jun 25, 2020 at 9:25 AM Greg Kroah-Hartman
> <gregkh@linuxfoundation.org> wrote:
> >
> > On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
> > > No, because we cannot label the inode based on the program's purpose
> > > and therefore cannot configure an automatic transition to a suitable
> > > security context for the process, unlike call_usermodehelper().
> >
> > Why, what prevents this?  Can you not just do that based on the "blob
> > address" or signature of it or something like that?  Right now you all
> > do this based on inode of a random file on a disk, what's the difference
> > between a random blob in memory?
>
> Given some kind of key to identify the blob and look up a suitable
> context in policy, I think it would work.  We just don't have that
> with the current interface.  With /bin/kmod and the like, we have a
> security xattr assigned to the file when it was created that we can
> use as the basis for determining the process security context.

Looks like info->cmdline could be used as that key if set; we would
just need a LSM hook to permit setting up the inode's security state
based on that key.  If that were passed to shmem_kernel_file_setup()
as the name argument, then that might also help path-based LSMs
although it seems potentially ambiguous.
Tetsuo Handa June 25, 2020, 3:21 p.m. UTC | #71
On 2020/06/25 23:26, Stephen Smalley wrote:
> On Thu, Jun 25, 2020 at 9:25 AM Greg Kroah-Hartman
> <gregkh@linuxfoundation.org> wrote:
>>
>> On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
>>> No, because we cannot label the inode based on the program's purpose
>>> and therefore cannot configure an automatic transition to a suitable
>>> security context for the process, unlike call_usermodehelper().
>>
>> Why, what prevents this?  Can you not just do that based on the "blob
>> address" or signature of it or something like that?  Right now you all
>> do this based on inode of a random file on a disk, what's the difference
>> between a random blob in memory?
> 
> Given some kind of key to identify the blob and look up a suitable
> context in policy, I think it would work.  We just don't have that
> with the current interface.  With /bin/kmod and the like, we have a
> security xattr assigned to the file when it was created that we can
> use as the basis for determining the process security context.

My understanding is that fork_usermode_blob() is intended to be able to run
without filesystems so that usermode blobs can start even before global init
program (pid=1) starts.

But SELinux's policy is likely stored inside filesystems which would be
accessible only after global init program (pid=1) started.

Therefore, I wonder whether SELinux can look up a suitable context in policy
even if "some kind of key to identify the blob" is provided.
Also, since (at least some of) usermode blob processes started via
fork_usermode_blob() will remain after SELinux loads policy from filesystems,
I guess that we will need a method for moving already running usermode blob
processes to appropriate security contexts.

Is my understanding/concerns correct?
Stephen Smalley June 25, 2020, 4:03 p.m. UTC | #72
On Thu, Jun 25, 2020 at 11:21 AM Tetsuo Handa
<penguin-kernel@i-love.sakura.ne.jp> wrote:
>
> On 2020/06/25 23:26, Stephen Smalley wrote:
> > On Thu, Jun 25, 2020 at 9:25 AM Greg Kroah-Hartman
> > <gregkh@linuxfoundation.org> wrote:
> >>
> >> On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
> >>> No, because we cannot label the inode based on the program's purpose
> >>> and therefore cannot configure an automatic transition to a suitable
> >>> security context for the process, unlike call_usermodehelper().
> >>
> >> Why, what prevents this?  Can you not just do that based on the "blob
> >> address" or signature of it or something like that?  Right now you all
> >> do this based on inode of a random file on a disk, what's the difference
> >> between a random blob in memory?
> >
> > Given some kind of key to identify the blob and look up a suitable
> > context in policy, I think it would work.  We just don't have that
> > with the current interface.  With /bin/kmod and the like, we have a
> > security xattr assigned to the file when it was created that we can
> > use as the basis for determining the process security context.
>
> My understanding is that fork_usermode_blob() is intended to be able to run
> without filesystems so that usermode blobs can start even before global init
> program (pid=1) starts.
>
> But SELinux's policy is likely stored inside filesystems which would be
> accessible only after global init program (pid=1) started.
>
> Therefore, I wonder whether SELinux can look up a suitable context in policy
> even if "some kind of key to identify the blob" is provided.
> Also, since (at least some of) usermode blob processes started via
> fork_usermode_blob() will remain after SELinux loads policy from filesystems,
> I guess that we will need a method for moving already running usermode blob
> processes to appropriate security contexts.
>
> Is my understanding/concerns correct?

It isn't fundamentally different than the issue of program execution
from a filesystem prior to initial policy load, e.g. executing
programs from the initrd or executing init from the "real" root.
Absent a policy, the process will just remain in the initial
SID/context (kernel SID), which will later be mapped to a context when
policy is loaded.  Typical init programs address this by either
re-exec'ing themselves after policy load or by dynamically switching
contexts via write to /proc/self/attr/current.  The kernel doesn't try
to retroactively transition previously started processes; they are
expected to either exit prior to policy load (ala transient processes
run from initrd) or re-exec or set their contexts after policy load.
Casey Schaufler June 25, 2020, 4:06 p.m. UTC | #73
On 6/25/2020 8:21 AM, Tetsuo Handa wrote:
> On 2020/06/25 23:26, Stephen Smalley wrote:
>> On Thu, Jun 25, 2020 at 9:25 AM Greg Kroah-Hartman
>> <gregkh@linuxfoundation.org> wrote:
>>> On Thu, Jun 25, 2020 at 08:56:10AM -0400, Stephen Smalley wrote:
>>>> No, because we cannot label the inode based on the program's purpose
>>>> and therefore cannot configure an automatic transition to a suitable
>>>> security context for the process, unlike call_usermodehelper().
>>> Why, what prevents this?  Can you not just do that based on the "blob
>>> address" or signature of it or something like that?  Right now you all
>>> do this based on inode of a random file on a disk, what's the difference
>>> between a random blob in memory?
>> Given some kind of key to identify the blob and look up a suitable
>> context in policy, I think it would work.  We just don't have that
>> with the current interface.  With /bin/kmod and the like, we have a
>> security xattr assigned to the file when it was created that we can
>> use as the basis for determining the process security context.

It should also be noted that Smack uses multiple xattrs. It is also
possible for multiple current security modules to use xattrs, including
capabilities. It's not sufficient to provide "the security xattr", there
would have to be provision for general security xattrs.

> My understanding is that fork_usermode_blob() is intended to be able to run
> without filesystems so that usermode blobs can start even before global init
> program (pid=1) starts.
>
> But SELinux's policy is likely stored inside filesystems which would be
> accessible only after global init program (pid=1) started.
>
> Therefore, I wonder whether SELinux can look up a suitable context in policy
> even if "some kind of key to identify the blob" is provided.

A security module has to have some sort of policy for whatever happens prior
to "policy load" as it is. That's not unique to this situation.
David Miller June 25, 2020, 7:34 p.m. UTC | #74
From: Greg KH <greg@kroah.com>
Date: Thu, 25 Jun 2020 14:07:25 +0200

> I really don't understand the objection here, why is this any different
> than any other random kernel driver for what it can do?

It's kernel code executing in userspace.  If you don't trust the
signed code you don't trust the signed code.

Nothing is magic about a piece of code executing in userspace.

I seriously think this dicussion is trying to create an issue
that simply doesn't exist in reality.

If some kernel module executed "/bin/sh" it's the same problem.
There is no way to argue around this, so please stop doing so
it's silly.
Linus Torvalds June 26, 2020, 1:36 a.m. UTC | #75
On Thu, Jun 25, 2020 at 12:34 PM David Miller <davem@davemloft.net> wrote:
>
> It's kernel code executing in userspace.  If you don't trust the
> signed code you don't trust the signed code.
>
> Nothing is magic about a piece of code executing in userspace.

Well, there's one real issue: the most likely thing that code is going
to do is execute llvm to generate more code.

And that's I think the real security issue here: the context in which
the code executes. It may be triggered in one namespace, but what
namespaces and what rules should the thing actually then execute in.

So no, trying to dismiss this as "there are no security issues" is
bogus. There very much are security issues.

It's just that the current code that is just a dummy wrapper around
something that doesn't actually do anything doesn't happen to _show_
those issues, because it does nothing.

I've stayed away from this discussion because I wanted to see if it
went anywhere, but it doesn't seem to.

My personally strongest argument for remoiving this kernel code is
that it's been there for a couple of years now, and it has never
actually done anything useful, and there's no actual sign that it ever
will, or that there is a solid plan in place for it.

So to me, it really looks like it was an interesting idea, but one
that hasn't proven itself, and most certainly not one that has shown
itself to be the _right_ idea.

We can dance around the "what about security modules", but that
fundamental problem of "this code hasn't done anything useful for two
years and we don't even know if it's the right thing to do or what the
real security issues _will_ be" is I think the real issue here.

Hmm?

             Linus
Alexei Starovoitov June 26, 2020, 1:51 a.m. UTC | #76
On Thu, Jun 25, 2020 at 06:36:34PM -0700, Linus Torvalds wrote:
> On Thu, Jun 25, 2020 at 12:34 PM David Miller <davem@davemloft.net> wrote:
> >
> > It's kernel code executing in userspace.  If you don't trust the
> > signed code you don't trust the signed code.
> >
> > Nothing is magic about a piece of code executing in userspace.
> 
> Well, there's one real issue: the most likely thing that code is going
> to do is execute llvm to generate more code.
> 
> And that's I think the real security issue here: the context in which
> the code executes. It may be triggered in one namespace, but what
> namespaces and what rules should the thing actually then execute in.
> 
> So no, trying to dismiss this as "there are no security issues" is
> bogus. There very much are security issues.

I think you're referring to:

>>   We might need to invent built-in "protected userspace" because existing
>>   "unprotected userspace" is not trustworthy enough to run kernel modules.
>>   That's not just inventing fork_usermode_blob().

Another root process can modify the memory of usermode_blob process.
I think that's Tetsuo's point about lack of LSM hooks is kernel_sock_shutdown().
Obviously, kernel_sock_shutdown() can be called by kernel only.
I suspect he's imaging a hypothetical situation where kernel bits of kernel module
interact with userblob bits of kernel module.
Then another root process tampers with memory of userblob.
Then userblob interaction with kernel module can do kernel_sock_shutdown()
on something that initial design of kernel+userblob module didn't intend.
I think this is trivially enforceable without creating new features.
Existing security_ptrace_access_check() LSM hook can prevent tampering with
memory of userblob.

As far as userblob calling llvm and other things in sequence.
That is no different from systemd calling things.
security label can carry that execution context.

> My personally strongest argument for remoiving this kernel code is
> that it's been there for a couple of years now, and it has never
> actually done anything useful, and there's no actual sign that it ever
> will, or that there is a solid plan in place for it.

you probably missed the detailed plan:
https://lore.kernel.org/bpf/20200609235631.ukpm3xngbehfqthz@ast-mbp.dhcp.thefacebook.com/

The project #3 is the above is the one we're working on right now.
It should be ready to post in a week.

> We can dance around the "what about security modules", but that
> fundamental problem of "this code hasn't done anything useful for two
> years and we don't even know if it's the right thing to do or what the
> real security issues _will_ be" is I think the real issue here.

Please see above link. bpfilter didn't go anywhere, but fork_usermode_blob()
has plenty of use cases that will materialize soon.
Tetsuo Handa June 26, 2020, 4:58 a.m. UTC | #77
On 2020/06/26 10:51, Alexei Starovoitov wrote:
> On Thu, Jun 25, 2020 at 06:36:34PM -0700, Linus Torvalds wrote:
>> On Thu, Jun 25, 2020 at 12:34 PM David Miller <davem@davemloft.net> wrote:
>>>
>>> It's kernel code executing in userspace.  If you don't trust the
>>> signed code you don't trust the signed code.
>>>
>>> Nothing is magic about a piece of code executing in userspace.
>>
>> Well, there's one real issue: the most likely thing that code is going
>> to do is execute llvm to generate more code.

Wow! Are we going to allow execution of such complicated programs?

I was hoping that fork_usermode_blob() accepts only simple program
like the content of "hello64" generated by

----------
; nasm -f elf64 hello64.asm && ld -s -m elf_x86_64 -o hello64 hello64.o
section .text
global _start

_start:
  mov rax, 1        ; write(
  mov rdi, 1        ;   1,
  mov rsi, msg      ;   "Hello world\n",
  mov rdx, 12       ;   12
  syscall           ; );
  mov rax, 231      ; _exit(
  mov rdi, 0        ;   0
  syscall           ; );

section .rodata
  msg: db "Hello world", 0x0a
----------

which can be contained by mechanisms like seccomp; there is no pathname
resolution, no networking access etc.

>>
>> And that's I think the real security issue here: the context in which
>> the code executes. It may be triggered in one namespace, but what
>> namespaces and what rules should the thing actually then execute in.
>>
>> So no, trying to dismiss this as "there are no security issues" is
>> bogus. There very much are security issues.
> 
> I think you're referring to:
> 
>>>   We might need to invent built-in "protected userspace" because existing
>>>   "unprotected userspace" is not trustworthy enough to run kernel modules.
>>>   That's not just inventing fork_usermode_blob().
> 
> Another root process can modify the memory of usermode_blob process.

I'm not familiar with ptrace(); I'm just using /usr/bin/strace and /usr/bin/ltrace .
What I'm worrying is that some root process tampers with memory which initially
contained "hello64" above in order to let that memory do something different behavior.

For example, a usermode process started by fork_usermode_blob() which was initially
containing

----------
while (read(0, &uid, sizeof(uid)) == sizeof(uid)) {
    if (uid == 0)
        write(1, "OK\n", 3);
    else
        write(1, "NG\n", 3);
}
----------

can be somehow tampered like

----------
while (read(0, &uid, sizeof(uid)) == sizeof(uid)) {
    if (uid != 0)
        write(1, "OK\n", 3);
    else
        write(1, "NG\n", 3);
}
----------

due to interference from the rest of the system, how can we say "we trust kernel
code executing in userspace" ?

My question is: how is the byte array (which was copied from kernel space) kept secure/intact
under "root can poke into kernel or any process memory." environment? It is obvious that
we can't say "we trust kernel code executing in userspace" without some mechanism.

Currently fork_usermode_blob() is not providing security context for the byte array to be
executed. We could modify fork_usermode_blob() to provide security context for LSMs, but
I'll be more happy if we can implement that mechanism without counting on in-tree LSMs, for
SELinux is too complicated to support.

> I think that's Tetsuo's point about lack of LSM hooks is kernel_sock_shutdown().
> Obviously, kernel_sock_shutdown() can be called by kernel only.

I can't catch what you mean. The kernel code executing in userspace uses syscall
interface (e.g. SYSCALL_DEFINE2(shutdown, int, fd, int, how) path), doesn't it?

> I suspect he's imaging a hypothetical situation where kernel bits of kernel module
> interact with userblob bits of kernel module.
> Then another root process tampers with memory of userblob.

Yes, how to protect the memory of userblob is a concern. The memory of userblob can
interfere (or can be interfered by) the rest of the system is a problem.

> Then userblob interaction with kernel module can do kernel_sock_shutdown()
> on something that initial design of kernel+userblob module didn't intend.

I can't catch what you mean.

> I think this is trivially enforceable without creating new features.
> Existing security_ptrace_access_check() LSM hook can prevent tampering with
> memory of userblob.

There is security_ptrace_access_check() LSM hook, but no zero-configuration
method is available.

> 
> As far as userblob calling llvm and other things in sequence.
> That is no different from systemd calling things.

Right.

> security label can carry that execution context.

If files get a chance to be associated with appropriate pathname and
security label.

> 
>> My personally strongest argument for remoiving this kernel code is
>> that it's been there for a couple of years now, and it has never
>> actually done anything useful, and there's no actual sign that it ever
>> will, or that there is a solid plan in place for it.
> 
> you probably missed the detailed plan:
> https://lore.kernel.org/bpf/20200609235631.ukpm3xngbehfqthz@ast-mbp.dhcp.thefacebook.com/
> 
> The project #3 is the above is the one we're working on right now.
> It should be ready to post in a week.

I got a question on project #3. Given that "cat /sys/fs/bpf/my_ipv6_route"
produces the same human output as "cat /proc/net/ipv6_route", how security
checks which are done for "cat /proc/net/ipv6_route" can be enforced for
"cat /sys/fs/bpf/my_ipv6_route" ? Unless same security checks (e.g. permission
to read /proc/net/ipv6_route ) is enforced, such bpf usage sounds like a method
for bypassing existing security mechanisms.
Alexei Starovoitov June 26, 2020, 5:41 a.m. UTC | #78
On Fri, Jun 26, 2020 at 01:58:35PM +0900, Tetsuo Handa wrote:
> On 2020/06/26 10:51, Alexei Starovoitov wrote:
> > On Thu, Jun 25, 2020 at 06:36:34PM -0700, Linus Torvalds wrote:
> >> On Thu, Jun 25, 2020 at 12:34 PM David Miller <davem@davemloft.net> wrote:
> >>>
> >>> It's kernel code executing in userspace.  If you don't trust the
> >>> signed code you don't trust the signed code.
> >>>
> >>> Nothing is magic about a piece of code executing in userspace.
> >>
> >> Well, there's one real issue: the most likely thing that code is going
> >> to do is execute llvm to generate more code.
> 
> Wow! Are we going to allow execution of such complicated programs?

No. llvm was _never_ intended to be run from the blob.
bpfilter was envisioned as self contained binary. If it needed to do
optimizations on generated bpf code it would have to do them internally.

> I was hoping that fork_usermode_blob() accepts only simple program
> like the content of "hello64" generated by

pretty much. statically compiled elf that is self contained.

> For example, a usermode process started by fork_usermode_blob() which was initially
> containing
> 
> ----------
> while (read(0, &uid, sizeof(uid)) == sizeof(uid)) {
>     if (uid == 0)
>         write(1, "OK\n", 3);
>     else
>         write(1, "NG\n", 3);
> }
> ----------
> 
> can be somehow tampered like
> 
> ----------
> while (read(0, &uid, sizeof(uid)) == sizeof(uid)) {
>     if (uid != 0)
>         write(1, "OK\n", 3);
>     else
>         write(1, "NG\n", 3);
> }
> ----------
> 
> due to interference from the rest of the system, how can we say "we trust kernel
> code executing in userspace" ?

I answered this already in the previous email.
Use security_ptrace_access_check() LSM hook to make sure that no other process
can tamper with blob's memory when it's running as user process.
In the future it would be trivial to add a new ptrace flag to
make sure that blob's memory is not ptraceable from the start.

> My question is: how is the byte array (which was copied from kernel space) kept secure/intact
> under "root can poke into kernel or any process memory." environment? It is obvious that
> we can't say "we trust kernel code executing in userspace" without some mechanism.

Already answered.

> Currently fork_usermode_blob() is not providing security context for the byte array to be
> executed. We could modify fork_usermode_blob() to provide security context for LSMs, but
> I'll be more happy if we can implement that mechanism without counting on in-tree LSMs, for
> SELinux is too complicated to support.

I'm pretty sure it was answered in the upthread by selinux folks.
Quick recap: we can add security labels, sha, strings, you_name_it to the blob that
lsm hooks can track.
We can also add another LSM hook to fork_usermode_blob(), so if tomoyo is so worried
about blobs it would be able to reject all of them without too much work.

> 
> > I think that's Tetsuo's point about lack of LSM hooks is kernel_sock_shutdown().
> > Obviously, kernel_sock_shutdown() can be called by kernel only.
> 
> I can't catch what you mean. The kernel code executing in userspace uses syscall
> interface (e.g. SYSCALL_DEFINE2(shutdown, int, fd, int, how) path), doesn't it?

yes.

> > I suspect he's imaging a hypothetical situation where kernel bits of kernel module
> > interact with userblob bits of kernel module.
> > Then another root process tampers with memory of userblob.
> 
> Yes, how to protect the memory of userblob is a concern. The memory of userblob can
> interfere (or can be interfered by) the rest of the system is a problem.

answered.

> > I think this is trivially enforceable without creating new features.
> > Existing security_ptrace_access_check() LSM hook can prevent tampering with
> > memory of userblob.
> 
> There is security_ptrace_access_check() LSM hook, but no zero-configuration
> method is available.

huh?
tomoyo is not using that hook, but selinux and many other LSMs do.
please learn from others.

> > security label can carry that execution context.
> 
> If files get a chance to be associated with appropriate pathname and
> security label.

I can easily add a fake pathname to the blob, but it won't help tomoyo.
That's what I was saying all along.
pathname based security provides false sense of security.

I'm pretty sure this old blog has been read by many folks who
are following this thread, but it's worth reminding again:
https://securityblog.org/2006/04/19/security-anti-pattern-path-based-access-control/
I cannot agree more with Joshua.
Here is a quote:
"The most obvious problem with this is that not all objects are files and thus do not have paths."

> >> My personally strongest argument for remoiving this kernel code is
> >> that it's been there for a couple of years now, and it has never
> >> actually done anything useful, and there's no actual sign that it ever
> >> will, or that there is a solid plan in place for it.
> > 
> > you probably missed the detailed plan:
> > https://lore.kernel.org/bpf/20200609235631.ukpm3xngbehfqthz@ast-mbp.dhcp.thefacebook.com/
> > 
> > The project #3 is the above is the one we're working on right now.
> > It should be ready to post in a week.
> 
> I got a question on project #3. Given that "cat /sys/fs/bpf/my_ipv6_route"
> produces the same human output as "cat /proc/net/ipv6_route", how security
> checks which are done for "cat /proc/net/ipv6_route" can be enforced for
> "cat /sys/fs/bpf/my_ipv6_route" ? Unless same security checks (e.g. permission
> to read /proc/net/ipv6_route ) is enforced, such bpf usage sounds like a method
> for bypassing existing security mechanisms.

Standard file permissions. Nothing to do with bpf.
Tetsuo Handa June 26, 2020, 6:20 a.m. UTC | #79
On 2020/06/26 14:41, Alexei Starovoitov wrote:
>> I was hoping that fork_usermode_blob() accepts only simple program
>> like the content of "hello64" generated by
> 
> pretty much. statically compiled elf that is self contained.

But fork_usermode_blob() itself does not check that.

>> due to interference from the rest of the system, how can we say "we trust kernel
>> code executing in userspace" ?
> 
> I answered this already in the previous email.

Previous post is mostly summary for David Miller who responded

  It's kernel code executing in userspace.  If you don't trust the
  signed code you don't trust the signed code.

  Nothing is magic about a piece of code executing in userspace.

without understanding my concerns.

> Use security_ptrace_access_check() LSM hook to make sure that no other process
> can tamper with blob's memory when it's running as user process.

Yes, security_ptrace_access_check() hook is there. But see the reality explained later.

> In the future it would be trivial to add a new ptrace flag to
> make sure that blob's memory is not ptraceable from the start.

I guess it is some PF_* flag (like PF_KTHREAD is used for avoiding some interference).

>> There is security_ptrace_access_check() LSM hook, but no zero-configuration
>> method is available.
> 
> huh?
> tomoyo is not using that hook, but selinux and many other LSMs do.
> please learn from others.

What I am hoping is that we can restrict interference between usermode blob processes
and other processes without using LSMs, for the reality is

  (1) Linux kernel community does not allow legally accessing LSM infrastructure from
      loadable kernel modules since Linux 2.6.24.
  (2) Red Hat folks enable only SELinux in their kernels.
  (3) Customers I'm working for cannot afford enabling SELinux in their environments.

and therefore

  (4) I have to maintain loadable kernel module version of LSM modules which illegally
      access LSM infrastructure in order to implement single function LSM modules.

Implementing security_ptrace_access_check() hook in TOMOYO is not a solution.

>>> security label can carry that execution context.
>>
>> If files get a chance to be associated with appropriate pathname and
>> security label.
> 
> I can easily add a fake pathname to the blob, but it won't help tomoyo.
> That's what I was saying all along.
> pathname based security provides false sense of security.
> 
> I'm pretty sure this old blog has been read by many folks who
> are following this thread, but it's worth reminding again:
> https://securityblog.org/2006/04/19/security-anti-pattern-path-based-access-control/
> I cannot agree more with Joshua.
> Here is a quote:
> "The most obvious problem with this is that not all objects are files and thus do not have paths."

Don't you know that TOMOYO can coexist with SELinux/Smack/AppArmor since Linux 5.1 ? ;-)
Alexei Starovoitov June 26, 2020, 6:39 a.m. UTC | #80
On Fri, Jun 26, 2020 at 03:20:35PM +0900, Tetsuo Handa wrote:
> On 2020/06/26 14:41, Alexei Starovoitov wrote:
> >> I was hoping that fork_usermode_blob() accepts only simple program
> >> like the content of "hello64" generated by
> > 
> > pretty much. statically compiled elf that is self contained.
> 
> But fork_usermode_blob() itself does not check that.

As I said few emails back it's trivial to add such check.

> > In the future it would be trivial to add a new ptrace flag to
> > make sure that blob's memory is not ptraceable from the start.
> 
> I guess it is some PF_* flag (like PF_KTHREAD is used for avoiding some interference).

Kinda.
I was thinking about PTRACE_MODE_xxx flag.

> What I am hoping is that we can restrict interference between usermode blob processes
> and other processes without using LSMs,

I don't see why not.
Extra piece of mind that blob memory is untouchable by other root processes is nice to have.
Eric W. Biederman June 26, 2020, 11:30 a.m. UTC | #81
Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:

> On Wed, Jun 24, 2020 at 5:17 AM Eric W. Biederman <ebiederm@xmission.com> wrote:
>>
>> Alexei Starovoitov <alexei.starovoitov@gmail.com> writes:
>>
>> > On Tue, Jun 23, 2020 at 01:53:48PM -0500, Eric W. Biederman wrote:
>>
>> > There is no refcnt bug. It was a user error on tomoyo side.
>> > fork_blob() works as expected.
>>
>> Nope.  I have independently confirmed it myself.
>
> I guess you've tried Tetsuo's fork_blob("#!/bin/true") kernel module ?
> yes. that fails. It never meant to be used for this.
> With elf blob it works, but breaks if there are rejections
> in things like security_bprm_creds_for_exec().
> In my mind that path was 'must succeed or kernel module is toast'.
> Like passing NULL into a function that doesn't check for it.
> Working on a fix for that since Tetsuo cares.

No.  The reference counting issue is present with the elf blob.

It is very straight forward to see when you take a minute to look.

The file is created with shmem_kernel_file_setup in fork_usermode_blob.
The file is put in fork_usermode_blob
The file is put in free_bprm by exec.

Eric
diff mbox series

Patch

diff --git a/fs/exec.c b/fs/exec.c
index e8599236290d..e6c24dabc1e4 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -1795,13 +1795,14 @@  static int exec_binprm(struct linux_binprm *bprm)
 /*
  * sys_execve() executes a new program.
  */
-static int __do_execve_file(int fd, struct filename *filename,
-			    struct user_arg_ptr argv,
-			    struct user_arg_ptr envp,
-			    int flags, struct file *file)
+static int do_execveat_common(int fd, struct filename *filename,
+			      struct user_arg_ptr argv,
+			      struct user_arg_ptr envp,
+			      int flags)
 {
 	char *pathbuf = NULL;
 	struct linux_binprm *bprm;
+	struct file *file;
 	struct files_struct *displaced;
 	int retval;
 
@@ -1840,8 +1841,7 @@  static int __do_execve_file(int fd, struct filename *filename,
 	check_unsafe_exec(bprm);
 	current->in_execve = 1;
 
-	if (!file)
-		file = do_open_execat(fd, filename, flags);
+	file = do_open_execat(fd, filename, flags);
 	retval = PTR_ERR(file);
 	if (IS_ERR(file))
 		goto out_unmark;
@@ -1849,9 +1849,7 @@  static int __do_execve_file(int fd, struct filename *filename,
 	sched_exec();
 
 	bprm->file = file;
-	if (!filename) {
-		bprm->filename = "none";
-	} else if (fd == AT_FDCWD || filename->name[0] == '/') {
+	if (fd == AT_FDCWD || filename->name[0] == '/') {
 		bprm->filename = filename->name;
 	} else {
 		if (filename->name[0] == '\0')
@@ -1912,8 +1910,7 @@  static int __do_execve_file(int fd, struct filename *filename,
 	task_numa_free(current, false);
 	free_bprm(bprm);
 	kfree(pathbuf);
-	if (filename)
-		putname(filename);
+	putname(filename);
 	if (displaced)
 		put_files_struct(displaced);
 	return retval;
@@ -1944,27 +1941,10 @@  static int __do_execve_file(int fd, struct filename *filename,
 	if (displaced)
 		reset_files_struct(displaced);
 out_ret:
-	if (filename)
-		putname(filename);
+	putname(filename);
 	return retval;
 }
 
-static int do_execveat_common(int fd, struct filename *filename,
-			      struct user_arg_ptr argv,
-			      struct user_arg_ptr envp,
-			      int flags)
-{
-	return __do_execve_file(fd, filename, argv, envp, flags, NULL);
-}
-
-int do_execve_file(struct file *file, void *__argv, void *__envp)
-{
-	struct user_arg_ptr argv = { .ptr.native = __argv };
-	struct user_arg_ptr envp = { .ptr.native = __envp };
-
-	return __do_execve_file(AT_FDCWD, NULL, argv, envp, 0, file);
-}
-
 int do_execve(struct filename *filename,
 	const char __user *const __user *__argv,
 	const char __user *const __user *__envp)
diff --git a/include/linux/binfmts.h b/include/linux/binfmts.h
index aece1b340e7d..e01eddc42750 100644
--- a/include/linux/binfmts.h
+++ b/include/linux/binfmts.h
@@ -142,6 +142,5 @@  extern int do_execveat(int, struct filename *,
 		       const char __user * const __user *,
 		       const char __user * const __user *,
 		       int);
-int do_execve_file(struct file *file, void *__argv, void *__envp);
 
 #endif /* _LINUX_BINFMTS_H */
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 4418f5cb8324..73d0eb46a67f 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -1986,14 +1986,6 @@  static inline void rseq_execve(struct task_struct *t)
 
 #endif
 
-void __exit_umh(struct task_struct *tsk);
-
-static inline void exit_umh(struct task_struct *tsk)
-{
-	if (unlikely(tsk->flags & PF_UMH))
-		__exit_umh(tsk);
-}
-
 #ifdef CONFIG_DEBUG_RSEQ
 
 void rseq_syscall(struct pt_regs *regs);
diff --git a/include/linux/umh.h b/include/linux/umh.h
index 0c08de356d0d..128ae92e6983 100644
--- a/include/linux/umh.h
+++ b/include/linux/umh.h
@@ -22,10 +22,8 @@  struct subprocess_info {
 	const char *path;
 	char **argv;
 	char **envp;
-	struct file *file;
 	int wait;
 	int retval;
-	pid_t pid;
 	int (*init)(struct subprocess_info *info, struct cred *new);
 	void (*cleanup)(struct subprocess_info *info);
 	void *data;
@@ -43,15 +41,6 @@  call_usermodehelper_setup(const char *path, char **argv, char **envp,
 struct subprocess_info *call_usermodehelper_setup_file(struct file *file,
 			  int (*init)(struct subprocess_info *info, struct cred *new),
 			  void (*cleanup)(struct subprocess_info *), void *data);
-struct umh_info {
-	const char *cmdline;
-	struct file *pipe_to_umh;
-	struct file *pipe_from_umh;
-	struct list_head list;
-	void (*cleanup)(struct umh_info *info);
-	pid_t pid;
-};
-int fork_usermode_blob(void *data, size_t len, struct umh_info *info);
 
 extern int
 call_usermodehelper_exec(struct subprocess_info *info, int wait);
diff --git a/kernel/exit.c b/kernel/exit.c
index ce2a75bc0ade..989f1ada0bf1 100644
--- a/kernel/exit.c
+++ b/kernel/exit.c
@@ -795,7 +795,6 @@  void __noreturn do_exit(long code)
 	exit_task_namespaces(tsk);
 	exit_task_work(tsk);
 	exit_thread(tsk);
-	exit_umh(tsk);
 
 	/*
 	 * Flush inherited counters to the parent - before the parent
diff --git a/kernel/umh.c b/kernel/umh.c
index 7f255b5a8845..a9a6032e08a6 100644
--- a/kernel/umh.c
+++ b/kernel/umh.c
@@ -26,8 +26,6 @@ 
 #include <linux/ptrace.h>
 #include <linux/async.h>
 #include <linux/uaccess.h>
-#include <linux/shmem_fs.h>
-#include <linux/pipe_fs_i.h>
 
 #include <trace/events/module.h>
 
@@ -39,7 +37,6 @@  static kernel_cap_t usermodehelper_inheritable = CAP_FULL_SET;
 static DEFINE_SPINLOCK(umh_sysctl_lock);
 static DECLARE_RWSEM(umhelper_sem);
 static LIST_HEAD(umh_list);
-static DEFINE_MUTEX(umh_list_lock);
 
 static void call_usermodehelper_freeinfo(struct subprocess_info *info)
 {
@@ -102,16 +99,9 @@  static int call_usermodehelper_exec_async(void *data)
 
 	commit_creds(new);
 
-	sub_info->pid = task_pid_nr(current);
-	if (sub_info->file) {
-		retval = do_execve_file(sub_info->file,
-					sub_info->argv, sub_info->envp);
-		if (!retval)
-			current->flags |= PF_UMH;
-	} else
-		retval = do_execve(getname_kernel(sub_info->path),
-				   (const char __user *const __user *)sub_info->argv,
-				   (const char __user *const __user *)sub_info->envp);
+	retval = do_execve(getname_kernel(sub_info->path),
+			   (const char __user *const __user *)sub_info->argv,
+			   (const char __user *const __user *)sub_info->envp);
 out:
 	sub_info->retval = retval;
 	/*
@@ -405,133 +395,6 @@  struct subprocess_info *call_usermodehelper_setup(const char *path, char **argv,
 }
 EXPORT_SYMBOL(call_usermodehelper_setup);
 
-struct subprocess_info *call_usermodehelper_setup_file(struct file *file,
-		int (*init)(struct subprocess_info *info, struct cred *new),
-		void (*cleanup)(struct subprocess_info *info), void *data)
-{
-	struct subprocess_info *sub_info;
-	struct umh_info *info = data;
-	const char *cmdline = (info->cmdline) ? info->cmdline : "usermodehelper";
-
-	sub_info = kzalloc(sizeof(struct subprocess_info), GFP_KERNEL);
-	if (!sub_info)
-		return NULL;
-
-	sub_info->argv = argv_split(GFP_KERNEL, cmdline, NULL);
-	if (!sub_info->argv) {
-		kfree(sub_info);
-		return NULL;
-	}
-
-	INIT_WORK(&sub_info->work, call_usermodehelper_exec_work);
-	sub_info->path = "none";
-	sub_info->file = file;
-	sub_info->init = init;
-	sub_info->cleanup = cleanup;
-	sub_info->data = data;
-	return sub_info;
-}
-
-static int umh_pipe_setup(struct subprocess_info *info, struct cred *new)
-{
-	struct umh_info *umh_info = info->data;
-	struct file *from_umh[2];
-	struct file *to_umh[2];
-	int err;
-
-	/* create pipe to send data to umh */
-	err = create_pipe_files(to_umh, 0);
-	if (err)
-		return err;
-	err = replace_fd(0, to_umh[0], 0);
-	fput(to_umh[0]);
-	if (err < 0) {
-		fput(to_umh[1]);
-		return err;
-	}
-
-	/* create pipe to receive data from umh */
-	err = create_pipe_files(from_umh, 0);
-	if (err) {
-		fput(to_umh[1]);
-		replace_fd(0, NULL, 0);
-		return err;
-	}
-	err = replace_fd(1, from_umh[1], 0);
-	fput(from_umh[1]);
-	if (err < 0) {
-		fput(to_umh[1]);
-		replace_fd(0, NULL, 0);
-		fput(from_umh[0]);
-		return err;
-	}
-
-	umh_info->pipe_to_umh = to_umh[1];
-	umh_info->pipe_from_umh = from_umh[0];
-	return 0;
-}
-
-static void umh_clean_and_save_pid(struct subprocess_info *info)
-{
-	struct umh_info *umh_info = info->data;
-
-	argv_free(info->argv);
-	umh_info->pid = info->pid;
-}
-
-/**
- * fork_usermode_blob - fork a blob of bytes as a usermode process
- * @data: a blob of bytes that can be do_execv-ed as a file
- * @len: length of the blob
- * @info: information about usermode process (shouldn't be NULL)
- *
- * If info->cmdline is set it will be used as command line for the
- * user process, else "usermodehelper" is used.
- *
- * Returns either negative error or zero which indicates success
- * in executing a blob of bytes as a usermode process. In such
- * case 'struct umh_info *info' is populated with two pipes
- * and a pid of the process. The caller is responsible for health
- * check of the user process, killing it via pid, and closing the
- * pipes when user process is no longer needed.
- */
-int fork_usermode_blob(void *data, size_t len, struct umh_info *info)
-{
-	struct subprocess_info *sub_info;
-	struct file *file;
-	ssize_t written;
-	loff_t pos = 0;
-	int err;
-
-	file = shmem_kernel_file_setup("", len, 0);
-	if (IS_ERR(file))
-		return PTR_ERR(file);
-
-	written = kernel_write(file, data, len, &pos);
-	if (written != len) {
-		err = written;
-		if (err >= 0)
-			err = -ENOMEM;
-		goto out;
-	}
-
-	err = -ENOMEM;
-	sub_info = call_usermodehelper_setup_file(file, umh_pipe_setup,
-						  umh_clean_and_save_pid, info);
-	if (!sub_info)
-		goto out;
-
-	err = call_usermodehelper_exec(sub_info, UMH_WAIT_EXEC);
-	if (!err) {
-		mutex_lock(&umh_list_lock);
-		list_add(&info->list, &umh_list);
-		mutex_unlock(&umh_list_lock);
-	}
-out:
-	fput(file);
-	return err;
-}
-EXPORT_SYMBOL_GPL(fork_usermode_blob);
 
 /**
  * call_usermodehelper_exec - start a usermode application
@@ -689,26 +552,6 @@  static int proc_cap_handler(struct ctl_table *table, int write,
 	return 0;
 }
 
-void __exit_umh(struct task_struct *tsk)
-{
-	struct umh_info *info;
-	pid_t pid = tsk->pid;
-
-	mutex_lock(&umh_list_lock);
-	list_for_each_entry(info, &umh_list, list) {
-		if (info->pid == pid) {
-			list_del(&info->list);
-			mutex_unlock(&umh_list_lock);
-			goto out;
-		}
-	}
-	mutex_unlock(&umh_list_lock);
-	return;
-out:
-	if (info->cleanup)
-		info->cleanup(info);
-}
-
 struct ctl_table usermodehelper_table[] = {
 	{
 		.procname	= "bset",
diff --git a/net/Kconfig b/net/Kconfig
index df8d8c9bd021..56066e279336 100644
--- a/net/Kconfig
+++ b/net/Kconfig
@@ -209,7 +209,6 @@  source "net/bridge/netfilter/Kconfig"
 
 endif
 
-source "net/bpfilter/Kconfig"
 
 source "net/dccp/Kconfig"
 source "net/sctp/Kconfig"
diff --git a/net/Makefile b/net/Makefile
index 07ea48160874..5148cce5f588 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -20,7 +20,6 @@  obj-$(CONFIG_TLS)		+= tls/
 obj-$(CONFIG_XFRM)		+= xfrm/
 obj-$(CONFIG_UNIX_SCM)		+= unix/
 obj-$(CONFIG_NET)		+= ipv6/
-obj-$(CONFIG_BPFILTER)		+= bpfilter/
 obj-$(CONFIG_PACKET)		+= packet/
 obj-$(CONFIG_NET_KEY)		+= key/
 obj-$(CONFIG_BRIDGE)		+= bridge/
diff --git a/net/bpfilter/.gitignore b/net/bpfilter/.gitignore
deleted file mode 100644
index f34e85ee8204..000000000000
--- a/net/bpfilter/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@ 
-# SPDX-License-Identifier: GPL-2.0-only
-bpfilter_umh
diff --git a/net/bpfilter/Kconfig b/net/bpfilter/Kconfig
deleted file mode 100644
index fed9290e3b41..000000000000
--- a/net/bpfilter/Kconfig
+++ /dev/null
@@ -1,16 +0,0 @@ 
-# SPDX-License-Identifier: GPL-2.0-only
-menuconfig BPFILTER
-	bool "BPF based packet filtering framework (BPFILTER)"
-	depends on NET && BPF && INET
-	help
-	  This builds experimental bpfilter framework that is aiming to
-	  provide netfilter compatible functionality via BPF
-
-if BPFILTER
-config BPFILTER_UMH
-	tristate "bpfilter kernel module with user mode helper"
-	depends on CC_CAN_LINK
-	default m
-	help
-	  This builds bpfilter kernel module with embedded user mode helper
-endif
diff --git a/net/bpfilter/Makefile b/net/bpfilter/Makefile
deleted file mode 100644
index 36580301da70..000000000000
--- a/net/bpfilter/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@ 
-# SPDX-License-Identifier: GPL-2.0
-#
-# Makefile for the Linux BPFILTER layer.
-#
-
-hostprogs := bpfilter_umh
-bpfilter_umh-objs := main.o
-KBUILD_HOSTCFLAGS += -I $(srctree)/tools/include/ -I $(srctree)/tools/include/uapi
-HOSTCC := $(CC)
-
-ifeq ($(CONFIG_BPFILTER_UMH), y)
-# builtin bpfilter_umh should be compiled with -static
-# since rootfs isn't mounted at the time of __init
-# function is called and do_execv won't find elf interpreter
-KBUILD_HOSTLDFLAGS += -static
-endif
-
-$(obj)/bpfilter_umh_blob.o: $(obj)/bpfilter_umh
-
-obj-$(CONFIG_BPFILTER_UMH) += bpfilter.o
-bpfilter-objs += bpfilter_kern.o bpfilter_umh_blob.o
diff --git a/net/bpfilter/bpfilter_kern.c b/net/bpfilter/bpfilter_kern.c
deleted file mode 100644
index c0f0990f30b6..000000000000
--- a/net/bpfilter/bpfilter_kern.c
+++ /dev/null
@@ -1,128 +0,0 @@ 
-// SPDX-License-Identifier: GPL-2.0
-#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
-#include <linux/init.h>
-#include <linux/module.h>
-#include <linux/umh.h>
-#include <linux/bpfilter.h>
-#include <linux/sched.h>
-#include <linux/sched/signal.h>
-#include <linux/fs.h>
-#include <linux/file.h>
-#include "msgfmt.h"
-
-extern char bpfilter_umh_start;
-extern char bpfilter_umh_end;
-
-static void shutdown_umh(void)
-{
-	struct task_struct *tsk;
-
-	if (bpfilter_ops.stop)
-		return;
-
-	tsk = get_pid_task(find_vpid(bpfilter_ops.info.pid), PIDTYPE_PID);
-	if (tsk) {
-		send_sig(SIGKILL, tsk, 1);
-		put_task_struct(tsk);
-	}
-}
-
-static void __stop_umh(void)
-{
-	if (IS_ENABLED(CONFIG_INET))
-		shutdown_umh();
-}
-
-static int __bpfilter_process_sockopt(struct sock *sk, int optname,
-				      char __user *optval,
-				      unsigned int optlen, bool is_set)
-{
-	struct mbox_request req;
-	struct mbox_reply reply;
-	loff_t pos;
-	ssize_t n;
-	int ret = -EFAULT;
-
-	req.is_set = is_set;
-	req.pid = current->pid;
-	req.cmd = optname;
-	req.addr = (long __force __user)optval;
-	req.len = optlen;
-	if (!bpfilter_ops.info.pid)
-		goto out;
-	n = __kernel_write(bpfilter_ops.info.pipe_to_umh, &req, sizeof(req),
-			   &pos);
-	if (n != sizeof(req)) {
-		pr_err("write fail %zd\n", n);
-		__stop_umh();
-		ret = -EFAULT;
-		goto out;
-	}
-	pos = 0;
-	n = kernel_read(bpfilter_ops.info.pipe_from_umh, &reply, sizeof(reply),
-			&pos);
-	if (n != sizeof(reply)) {
-		pr_err("read fail %zd\n", n);
-		__stop_umh();
-		ret = -EFAULT;
-		goto out;
-	}
-	ret = reply.status;
-out:
-	return ret;
-}
-
-static int start_umh(void)
-{
-	int err;
-
-	/* fork usermode process */
-	err = fork_usermode_blob(&bpfilter_umh_start,
-				 &bpfilter_umh_end - &bpfilter_umh_start,
-				 &bpfilter_ops.info);
-	if (err)
-		return err;
-	bpfilter_ops.stop = false;
-	pr_info("Loaded bpfilter_umh pid %d\n", bpfilter_ops.info.pid);
-
-	/* health check that usermode process started correctly */
-	if (__bpfilter_process_sockopt(NULL, 0, NULL, 0, 0) != 0) {
-		shutdown_umh();
-		return -EFAULT;
-	}
-
-	return 0;
-}
-
-static int __init load_umh(void)
-{
-	int err;
-
-	mutex_lock(&bpfilter_ops.lock);
-	if (!bpfilter_ops.stop) {
-		err = -EFAULT;
-		goto out;
-	}
-	err = start_umh();
-	if (!err && IS_ENABLED(CONFIG_INET)) {
-		bpfilter_ops.sockopt = &__bpfilter_process_sockopt;
-		bpfilter_ops.start = &start_umh;
-	}
-out:
-	mutex_unlock(&bpfilter_ops.lock);
-	return err;
-}
-
-static void __exit fini_umh(void)
-{
-	mutex_lock(&bpfilter_ops.lock);
-	if (IS_ENABLED(CONFIG_INET)) {
-		shutdown_umh();
-		bpfilter_ops.start = NULL;
-		bpfilter_ops.sockopt = NULL;
-	}
-	mutex_unlock(&bpfilter_ops.lock);
-}
-module_init(load_umh);
-module_exit(fini_umh);
-MODULE_LICENSE("GPL");
diff --git a/net/bpfilter/bpfilter_umh_blob.S b/net/bpfilter/bpfilter_umh_blob.S
deleted file mode 100644
index 9ea6100dca87..000000000000
--- a/net/bpfilter/bpfilter_umh_blob.S
+++ /dev/null
@@ -1,7 +0,0 @@ 
-/* SPDX-License-Identifier: GPL-2.0 */
-	.section .rodata, "a"
-	.global bpfilter_umh_start
-bpfilter_umh_start:
-	.incbin "net/bpfilter/bpfilter_umh"
-	.global bpfilter_umh_end
-bpfilter_umh_end:
diff --git a/net/bpfilter/main.c b/net/bpfilter/main.c
deleted file mode 100644
index 05e1cfc1e5cd..000000000000
--- a/net/bpfilter/main.c
+++ /dev/null
@@ -1,64 +0,0 @@ 
-// SPDX-License-Identifier: GPL-2.0
-#define _GNU_SOURCE
-#include <sys/uio.h>
-#include <errno.h>
-#include <stdio.h>
-#include <sys/socket.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include "../../include/uapi/linux/bpf.h"
-#include <asm/unistd.h>
-#include "msgfmt.h"
-
-FILE *debug_f;
-
-static int handle_get_cmd(struct mbox_request *cmd)
-{
-	switch (cmd->cmd) {
-	case 0:
-		return 0;
-	default:
-		break;
-	}
-	return -ENOPROTOOPT;
-}
-
-static int handle_set_cmd(struct mbox_request *cmd)
-{
-	return -ENOPROTOOPT;
-}
-
-static void loop(void)
-{
-	while (1) {
-		struct mbox_request req;
-		struct mbox_reply reply;
-		int n;
-
-		n = read(0, &req, sizeof(req));
-		if (n != sizeof(req)) {
-			fprintf(debug_f, "invalid request %d\n", n);
-			return;
-		}
-
-		reply.status = req.is_set ?
-			handle_set_cmd(&req) :
-			handle_get_cmd(&req);
-
-		n = write(1, &reply, sizeof(reply));
-		if (n != sizeof(reply)) {
-			fprintf(debug_f, "reply failed %d\n", n);
-			return;
-		}
-	}
-}
-
-int main(void)
-{
-	debug_f = fopen("/dev/kmsg", "w");
-	setvbuf(debug_f, 0, _IOLBF, 0);
-	fprintf(debug_f, "Started bpfilter\n");
-	loop();
-	fclose(debug_f);
-	return 0;
-}
diff --git a/net/bpfilter/msgfmt.h b/net/bpfilter/msgfmt.h
deleted file mode 100644
index 98d121c62945..000000000000
--- a/net/bpfilter/msgfmt.h
+++ /dev/null
@@ -1,17 +0,0 @@ 
-/* SPDX-License-Identifier: GPL-2.0 */
-#ifndef _NET_BPFILTER_MSGFMT_H
-#define _NET_BPFILTER_MSGFMT_H
-
-struct mbox_request {
-	__u64 addr;
-	__u32 len;
-	__u32 is_set;
-	__u32 cmd;
-	__u32 pid;
-};
-
-struct mbox_reply {
-	__u32 status;
-};
-
-#endif
diff --git a/net/ipv4/Makefile b/net/ipv4/Makefile
index 9e1a186a3671..e4c1cb8df316 100644
--- a/net/ipv4/Makefile
+++ b/net/ipv4/Makefile
@@ -16,7 +16,6 @@  obj-y     := route.o inetpeer.o protocol.o \
 	     inet_fragment.o ping.o ip_tunnel_core.o gre_offload.o \
 	     metrics.o netlink.o nexthop.o
 
-obj-$(CONFIG_BPFILTER) += bpfilter/
 
 obj-$(CONFIG_NET_IP_TUNNEL) += ip_tunnel.o
 obj-$(CONFIG_SYSCTL) += sysctl_net_ipv4.o
diff --git a/net/ipv4/bpfilter/Makefile b/net/ipv4/bpfilter/Makefile
deleted file mode 100644
index 00af5305e05a..000000000000
--- a/net/ipv4/bpfilter/Makefile
+++ /dev/null
@@ -1,2 +0,0 @@ 
-# SPDX-License-Identifier: GPL-2.0-only
-obj-$(CONFIG_BPFILTER) += sockopt.o
diff --git a/net/ipv4/bpfilter/sockopt.c b/net/ipv4/bpfilter/sockopt.c
deleted file mode 100644
index 0480918bfc7c..000000000000
--- a/net/ipv4/bpfilter/sockopt.c
+++ /dev/null
@@ -1,78 +0,0 @@ 
-// SPDX-License-Identifier: GPL-2.0
-#include <linux/init.h>
-#include <linux/module.h>
-#include <linux/uaccess.h>
-#include <linux/bpfilter.h>
-#include <uapi/linux/bpf.h>
-#include <linux/wait.h>
-#include <linux/kmod.h>
-#include <linux/fs.h>
-#include <linux/file.h>
-
-struct bpfilter_umh_ops bpfilter_ops;
-EXPORT_SYMBOL_GPL(bpfilter_ops);
-
-static void bpfilter_umh_cleanup(struct umh_info *info)
-{
-	mutex_lock(&bpfilter_ops.lock);
-	bpfilter_ops.stop = true;
-	fput(info->pipe_to_umh);
-	fput(info->pipe_from_umh);
-	info->pid = 0;
-	mutex_unlock(&bpfilter_ops.lock);
-}
-
-static int bpfilter_mbox_request(struct sock *sk, int optname,
-				 char __user *optval,
-				 unsigned int optlen, bool is_set)
-{
-	int err;
-	mutex_lock(&bpfilter_ops.lock);
-	if (!bpfilter_ops.sockopt) {
-		mutex_unlock(&bpfilter_ops.lock);
-		request_module("bpfilter");
-		mutex_lock(&bpfilter_ops.lock);
-
-		if (!bpfilter_ops.sockopt) {
-			err = -ENOPROTOOPT;
-			goto out;
-		}
-	}
-	if (bpfilter_ops.stop) {
-		err = bpfilter_ops.start();
-		if (err)
-			goto out;
-	}
-	err = bpfilter_ops.sockopt(sk, optname, optval, optlen, is_set);
-out:
-	mutex_unlock(&bpfilter_ops.lock);
-	return err;
-}
-
-int bpfilter_ip_set_sockopt(struct sock *sk, int optname, char __user *optval,
-			    unsigned int optlen)
-{
-	return bpfilter_mbox_request(sk, optname, optval, optlen, true);
-}
-
-int bpfilter_ip_get_sockopt(struct sock *sk, int optname, char __user *optval,
-			    int __user *optlen)
-{
-	int len;
-
-	if (get_user(len, optlen))
-		return -EFAULT;
-
-	return bpfilter_mbox_request(sk, optname, optval, len, false);
-}
-
-static int __init bpfilter_sockopt_init(void)
-{
-	mutex_init(&bpfilter_ops.lock);
-	bpfilter_ops.stop = true;
-	bpfilter_ops.info.cmdline = "bpfilter_umh";
-	bpfilter_ops.info.cleanup = &bpfilter_umh_cleanup;
-
-	return 0;
-}
-device_initcall(bpfilter_sockopt_init);