Merge git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf
[linux-2.6-block.git] / net / bpfilter / bpfilter_kern.c
CommitLineData
d2ba09c1
AS
1// SPDX-License-Identifier: GPL-2.0
2#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3#include <linux/init.h>
4#include <linux/module.h>
5#include <linux/umh.h>
6#include <linux/bpfilter.h>
7#include <linux/sched.h>
8#include <linux/sched/signal.h>
9#include <linux/fs.h>
10#include <linux/file.h>
11#include "msgfmt.h"
12
13#define UMH_start _binary_net_bpfilter_bpfilter_umh_start
14#define UMH_end _binary_net_bpfilter_bpfilter_umh_end
15
16extern char UMH_start;
17extern char UMH_end;
18
19static struct umh_info info;
20/* since ip_getsockopt() can run in parallel, serialize access to umh */
21static DEFINE_MUTEX(bpfilter_lock);
22
23static void shutdown_umh(struct umh_info *info)
24{
25 struct task_struct *tsk;
26
27 tsk = pid_task(find_vpid(info->pid), PIDTYPE_PID);
28 if (tsk)
29 force_sig(SIGKILL, tsk);
30 fput(info->pipe_to_umh);
31 fput(info->pipe_from_umh);
32}
33
34static void __stop_umh(void)
35{
d71dbdaa
AB
36 if (IS_ENABLED(CONFIG_INET) &&
37 bpfilter_process_sockopt) {
d2ba09c1
AS
38 bpfilter_process_sockopt = NULL;
39 shutdown_umh(&info);
40 }
41}
42
43static void stop_umh(void)
44{
45 mutex_lock(&bpfilter_lock);
46 __stop_umh();
47 mutex_unlock(&bpfilter_lock);
48}
49
50static int __bpfilter_process_sockopt(struct sock *sk, int optname,
51 char __user *optval,
52 unsigned int optlen, bool is_set)
53{
54 struct mbox_request req;
55 struct mbox_reply reply;
56 loff_t pos;
57 ssize_t n;
58 int ret;
59
60 req.is_set = is_set;
61 req.pid = current->pid;
62 req.cmd = optname;
63 req.addr = (long)optval;
64 req.len = optlen;
65 mutex_lock(&bpfilter_lock);
66 n = __kernel_write(info.pipe_to_umh, &req, sizeof(req), &pos);
67 if (n != sizeof(req)) {
68 pr_err("write fail %zd\n", n);
69 __stop_umh();
70 ret = -EFAULT;
71 goto out;
72 }
73 pos = 0;
74 n = kernel_read(info.pipe_from_umh, &reply, sizeof(reply), &pos);
75 if (n != sizeof(reply)) {
76 pr_err("read fail %zd\n", n);
77 __stop_umh();
78 ret = -EFAULT;
79 goto out;
80 }
81 ret = reply.status;
82out:
83 mutex_unlock(&bpfilter_lock);
84 return ret;
85}
86
87static int __init load_umh(void)
88{
89 int err;
90
91 /* fork usermode process */
92 err = fork_usermode_blob(&UMH_start, &UMH_end - &UMH_start, &info);
93 if (err)
94 return err;
95 pr_info("Loaded bpfilter_umh pid %d\n", info.pid);
96
97 /* health check that usermode process started correctly */
98 if (__bpfilter_process_sockopt(NULL, 0, 0, 0, 0) != 0) {
99 stop_umh();
100 return -EFAULT;
101 }
d71dbdaa
AB
102 if (IS_ENABLED(CONFIG_INET))
103 bpfilter_process_sockopt = &__bpfilter_process_sockopt;
104
d2ba09c1
AS
105 return 0;
106}
107
108static void __exit fini_umh(void)
109{
110 stop_umh();
111}
112module_init(load_umh);
113module_exit(fini_umh);
114MODULE_LICENSE("GPL");