]> asedeno.scripts.mit.edu Git - linux.git/blob - kernel/bpf/cgroup.c
077ed3a19848e29dd783760223703fefb87e5d3b
[linux.git] / kernel / bpf / cgroup.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Functions to manage eBPF programs attached to cgroups
4  *
5  * Copyright (c) 2016 Daniel Mack
6  */
7
8 #include <linux/kernel.h>
9 #include <linux/atomic.h>
10 #include <linux/cgroup.h>
11 #include <linux/filter.h>
12 #include <linux/slab.h>
13 #include <linux/sysctl.h>
14 #include <linux/string.h>
15 #include <linux/bpf.h>
16 #include <linux/bpf-cgroup.h>
17 #include <net/sock.h>
18
19 #include "../cgroup/cgroup-internal.h"
20
21 DEFINE_STATIC_KEY_FALSE(cgroup_bpf_enabled_key);
22 EXPORT_SYMBOL(cgroup_bpf_enabled_key);
23
24 void cgroup_bpf_offline(struct cgroup *cgrp)
25 {
26         cgroup_get(cgrp);
27         percpu_ref_kill(&cgrp->bpf.refcnt);
28 }
29
30 /**
31  * cgroup_bpf_release() - put references of all bpf programs and
32  *                        release all cgroup bpf data
33  * @work: work structure embedded into the cgroup to modify
34  */
35 static void cgroup_bpf_release(struct work_struct *work)
36 {
37         struct cgroup *cgrp = container_of(work, struct cgroup,
38                                            bpf.release_work);
39         enum bpf_cgroup_storage_type stype;
40         struct bpf_prog_array *old_array;
41         unsigned int type;
42
43         mutex_lock(&cgroup_mutex);
44
45         for (type = 0; type < ARRAY_SIZE(cgrp->bpf.progs); type++) {
46                 struct list_head *progs = &cgrp->bpf.progs[type];
47                 struct bpf_prog_list *pl, *tmp;
48
49                 list_for_each_entry_safe(pl, tmp, progs, node) {
50                         list_del(&pl->node);
51                         bpf_prog_put(pl->prog);
52                         for_each_cgroup_storage_type(stype) {
53                                 bpf_cgroup_storage_unlink(pl->storage[stype]);
54                                 bpf_cgroup_storage_free(pl->storage[stype]);
55                         }
56                         kfree(pl);
57                         static_branch_dec(&cgroup_bpf_enabled_key);
58                 }
59                 old_array = rcu_dereference_protected(
60                                 cgrp->bpf.effective[type],
61                                 lockdep_is_held(&cgroup_mutex));
62                 bpf_prog_array_free(old_array);
63         }
64
65         mutex_unlock(&cgroup_mutex);
66
67         percpu_ref_exit(&cgrp->bpf.refcnt);
68         cgroup_put(cgrp);
69 }
70
71 /**
72  * cgroup_bpf_release_fn() - callback used to schedule releasing
73  *                           of bpf cgroup data
74  * @ref: percpu ref counter structure
75  */
76 static void cgroup_bpf_release_fn(struct percpu_ref *ref)
77 {
78         struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
79
80         INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
81         queue_work(system_wq, &cgrp->bpf.release_work);
82 }
83
84 /* count number of elements in the list.
85  * it's slow but the list cannot be long
86  */
87 static u32 prog_list_length(struct list_head *head)
88 {
89         struct bpf_prog_list *pl;
90         u32 cnt = 0;
91
92         list_for_each_entry(pl, head, node) {
93                 if (!pl->prog)
94                         continue;
95                 cnt++;
96         }
97         return cnt;
98 }
99
100 /* if parent has non-overridable prog attached,
101  * disallow attaching new programs to the descendent cgroup.
102  * if parent has overridable or multi-prog, allow attaching
103  */
104 static bool hierarchy_allows_attach(struct cgroup *cgrp,
105                                     enum bpf_attach_type type,
106                                     u32 new_flags)
107 {
108         struct cgroup *p;
109
110         p = cgroup_parent(cgrp);
111         if (!p)
112                 return true;
113         do {
114                 u32 flags = p->bpf.flags[type];
115                 u32 cnt;
116
117                 if (flags & BPF_F_ALLOW_MULTI)
118                         return true;
119                 cnt = prog_list_length(&p->bpf.progs[type]);
120                 WARN_ON_ONCE(cnt > 1);
121                 if (cnt == 1)
122                         return !!(flags & BPF_F_ALLOW_OVERRIDE);
123                 p = cgroup_parent(p);
124         } while (p);
125         return true;
126 }
127
128 /* compute a chain of effective programs for a given cgroup:
129  * start from the list of programs in this cgroup and add
130  * all parent programs.
131  * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
132  * to programs in this cgroup
133  */
134 static int compute_effective_progs(struct cgroup *cgrp,
135                                    enum bpf_attach_type type,
136                                    struct bpf_prog_array **array)
137 {
138         enum bpf_cgroup_storage_type stype;
139         struct bpf_prog_array *progs;
140         struct bpf_prog_list *pl;
141         struct cgroup *p = cgrp;
142         int cnt = 0;
143
144         /* count number of effective programs by walking parents */
145         do {
146                 if (cnt == 0 || (p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
147                         cnt += prog_list_length(&p->bpf.progs[type]);
148                 p = cgroup_parent(p);
149         } while (p);
150
151         progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
152         if (!progs)
153                 return -ENOMEM;
154
155         /* populate the array with effective progs */
156         cnt = 0;
157         p = cgrp;
158         do {
159                 if (cnt > 0 && !(p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
160                         continue;
161
162                 list_for_each_entry(pl, &p->bpf.progs[type], node) {
163                         if (!pl->prog)
164                                 continue;
165
166                         progs->items[cnt].prog = pl->prog;
167                         for_each_cgroup_storage_type(stype)
168                                 progs->items[cnt].cgroup_storage[stype] =
169                                         pl->storage[stype];
170                         cnt++;
171                 }
172         } while ((p = cgroup_parent(p)));
173
174         *array = progs;
175         return 0;
176 }
177
178 static void activate_effective_progs(struct cgroup *cgrp,
179                                      enum bpf_attach_type type,
180                                      struct bpf_prog_array *old_array)
181 {
182         rcu_swap_protected(cgrp->bpf.effective[type], old_array,
183                            lockdep_is_held(&cgroup_mutex));
184         /* free prog array after grace period, since __cgroup_bpf_run_*()
185          * might be still walking the array
186          */
187         bpf_prog_array_free(old_array);
188 }
189
190 /**
191  * cgroup_bpf_inherit() - inherit effective programs from parent
192  * @cgrp: the cgroup to modify
193  */
194 int cgroup_bpf_inherit(struct cgroup *cgrp)
195 {
196 /* has to use marco instead of const int, since compiler thinks
197  * that array below is variable length
198  */
199 #define NR ARRAY_SIZE(cgrp->bpf.effective)
200         struct bpf_prog_array *arrays[NR] = {};
201         int ret, i;
202
203         ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
204                               GFP_KERNEL);
205         if (ret)
206                 return ret;
207
208         for (i = 0; i < NR; i++)
209                 INIT_LIST_HEAD(&cgrp->bpf.progs[i]);
210
211         for (i = 0; i < NR; i++)
212                 if (compute_effective_progs(cgrp, i, &arrays[i]))
213                         goto cleanup;
214
215         for (i = 0; i < NR; i++)
216                 activate_effective_progs(cgrp, i, arrays[i]);
217
218         return 0;
219 cleanup:
220         for (i = 0; i < NR; i++)
221                 bpf_prog_array_free(arrays[i]);
222
223         percpu_ref_exit(&cgrp->bpf.refcnt);
224
225         return -ENOMEM;
226 }
227
228 static int update_effective_progs(struct cgroup *cgrp,
229                                   enum bpf_attach_type type)
230 {
231         struct cgroup_subsys_state *css;
232         int err;
233
234         /* allocate and recompute effective prog arrays */
235         css_for_each_descendant_pre(css, &cgrp->self) {
236                 struct cgroup *desc = container_of(css, struct cgroup, self);
237
238                 if (percpu_ref_is_zero(&desc->bpf.refcnt))
239                         continue;
240
241                 err = compute_effective_progs(desc, type, &desc->bpf.inactive);
242                 if (err)
243                         goto cleanup;
244         }
245
246         /* all allocations were successful. Activate all prog arrays */
247         css_for_each_descendant_pre(css, &cgrp->self) {
248                 struct cgroup *desc = container_of(css, struct cgroup, self);
249
250                 if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
251                         if (unlikely(desc->bpf.inactive)) {
252                                 bpf_prog_array_free(desc->bpf.inactive);
253                                 desc->bpf.inactive = NULL;
254                         }
255                         continue;
256                 }
257
258                 activate_effective_progs(desc, type, desc->bpf.inactive);
259                 desc->bpf.inactive = NULL;
260         }
261
262         return 0;
263
264 cleanup:
265         /* oom while computing effective. Free all computed effective arrays
266          * since they were not activated
267          */
268         css_for_each_descendant_pre(css, &cgrp->self) {
269                 struct cgroup *desc = container_of(css, struct cgroup, self);
270
271                 bpf_prog_array_free(desc->bpf.inactive);
272                 desc->bpf.inactive = NULL;
273         }
274
275         return err;
276 }
277
278 #define BPF_CGROUP_MAX_PROGS 64
279
280 /**
281  * __cgroup_bpf_attach() - Attach the program to a cgroup, and
282  *                         propagate the change to descendants
283  * @cgrp: The cgroup which descendants to traverse
284  * @prog: A program to attach
285  * @type: Type of attach operation
286  * @flags: Option flags
287  *
288  * Must be called with cgroup_mutex held.
289  */
290 int __cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
291                         enum bpf_attach_type type, u32 flags)
292 {
293         struct list_head *progs = &cgrp->bpf.progs[type];
294         struct bpf_prog *old_prog = NULL;
295         struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE],
296                 *old_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {NULL};
297         enum bpf_cgroup_storage_type stype;
298         struct bpf_prog_list *pl;
299         bool pl_was_allocated;
300         int err;
301
302         if ((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI))
303                 /* invalid combination */
304                 return -EINVAL;
305
306         if (!hierarchy_allows_attach(cgrp, type, flags))
307                 return -EPERM;
308
309         if (!list_empty(progs) && cgrp->bpf.flags[type] != flags)
310                 /* Disallow attaching non-overridable on top
311                  * of existing overridable in this cgroup.
312                  * Disallow attaching multi-prog if overridable or none
313                  */
314                 return -EPERM;
315
316         if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
317                 return -E2BIG;
318
319         for_each_cgroup_storage_type(stype) {
320                 storage[stype] = bpf_cgroup_storage_alloc(prog, stype);
321                 if (IS_ERR(storage[stype])) {
322                         storage[stype] = NULL;
323                         for_each_cgroup_storage_type(stype)
324                                 bpf_cgroup_storage_free(storage[stype]);
325                         return -ENOMEM;
326                 }
327         }
328
329         if (flags & BPF_F_ALLOW_MULTI) {
330                 list_for_each_entry(pl, progs, node) {
331                         if (pl->prog == prog) {
332                                 /* disallow attaching the same prog twice */
333                                 for_each_cgroup_storage_type(stype)
334                                         bpf_cgroup_storage_free(storage[stype]);
335                                 return -EINVAL;
336                         }
337                 }
338
339                 pl = kmalloc(sizeof(*pl), GFP_KERNEL);
340                 if (!pl) {
341                         for_each_cgroup_storage_type(stype)
342                                 bpf_cgroup_storage_free(storage[stype]);
343                         return -ENOMEM;
344                 }
345
346                 pl_was_allocated = true;
347                 pl->prog = prog;
348                 for_each_cgroup_storage_type(stype)
349                         pl->storage[stype] = storage[stype];
350                 list_add_tail(&pl->node, progs);
351         } else {
352                 if (list_empty(progs)) {
353                         pl = kmalloc(sizeof(*pl), GFP_KERNEL);
354                         if (!pl) {
355                                 for_each_cgroup_storage_type(stype)
356                                         bpf_cgroup_storage_free(storage[stype]);
357                                 return -ENOMEM;
358                         }
359                         pl_was_allocated = true;
360                         list_add_tail(&pl->node, progs);
361                 } else {
362                         pl = list_first_entry(progs, typeof(*pl), node);
363                         old_prog = pl->prog;
364                         for_each_cgroup_storage_type(stype) {
365                                 old_storage[stype] = pl->storage[stype];
366                                 bpf_cgroup_storage_unlink(old_storage[stype]);
367                         }
368                         pl_was_allocated = false;
369                 }
370                 pl->prog = prog;
371                 for_each_cgroup_storage_type(stype)
372                         pl->storage[stype] = storage[stype];
373         }
374
375         cgrp->bpf.flags[type] = flags;
376
377         err = update_effective_progs(cgrp, type);
378         if (err)
379                 goto cleanup;
380
381         static_branch_inc(&cgroup_bpf_enabled_key);
382         for_each_cgroup_storage_type(stype) {
383                 if (!old_storage[stype])
384                         continue;
385                 bpf_cgroup_storage_free(old_storage[stype]);
386         }
387         if (old_prog) {
388                 bpf_prog_put(old_prog);
389                 static_branch_dec(&cgroup_bpf_enabled_key);
390         }
391         for_each_cgroup_storage_type(stype)
392                 bpf_cgroup_storage_link(storage[stype], cgrp, type);
393         return 0;
394
395 cleanup:
396         /* and cleanup the prog list */
397         pl->prog = old_prog;
398         for_each_cgroup_storage_type(stype) {
399                 bpf_cgroup_storage_free(pl->storage[stype]);
400                 pl->storage[stype] = old_storage[stype];
401                 bpf_cgroup_storage_link(old_storage[stype], cgrp, type);
402         }
403         if (pl_was_allocated) {
404                 list_del(&pl->node);
405                 kfree(pl);
406         }
407         return err;
408 }
409
410 /**
411  * __cgroup_bpf_detach() - Detach the program from a cgroup, and
412  *                         propagate the change to descendants
413  * @cgrp: The cgroup which descendants to traverse
414  * @prog: A program to detach or NULL
415  * @type: Type of detach operation
416  *
417  * Must be called with cgroup_mutex held.
418  */
419 int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
420                         enum bpf_attach_type type)
421 {
422         struct list_head *progs = &cgrp->bpf.progs[type];
423         enum bpf_cgroup_storage_type stype;
424         u32 flags = cgrp->bpf.flags[type];
425         struct bpf_prog *old_prog = NULL;
426         struct bpf_prog_list *pl;
427         int err;
428
429         if (flags & BPF_F_ALLOW_MULTI) {
430                 if (!prog)
431                         /* to detach MULTI prog the user has to specify valid FD
432                          * of the program to be detached
433                          */
434                         return -EINVAL;
435         } else {
436                 if (list_empty(progs))
437                         /* report error when trying to detach and nothing is attached */
438                         return -ENOENT;
439         }
440
441         if (flags & BPF_F_ALLOW_MULTI) {
442                 /* find the prog and detach it */
443                 list_for_each_entry(pl, progs, node) {
444                         if (pl->prog != prog)
445                                 continue;
446                         old_prog = prog;
447                         /* mark it deleted, so it's ignored while
448                          * recomputing effective
449                          */
450                         pl->prog = NULL;
451                         break;
452                 }
453                 if (!old_prog)
454                         return -ENOENT;
455         } else {
456                 /* to maintain backward compatibility NONE and OVERRIDE cgroups
457                  * allow detaching with invalid FD (prog==NULL)
458                  */
459                 pl = list_first_entry(progs, typeof(*pl), node);
460                 old_prog = pl->prog;
461                 pl->prog = NULL;
462         }
463
464         err = update_effective_progs(cgrp, type);
465         if (err)
466                 goto cleanup;
467
468         /* now can actually delete it from this cgroup list */
469         list_del(&pl->node);
470         for_each_cgroup_storage_type(stype) {
471                 bpf_cgroup_storage_unlink(pl->storage[stype]);
472                 bpf_cgroup_storage_free(pl->storage[stype]);
473         }
474         kfree(pl);
475         if (list_empty(progs))
476                 /* last program was detached, reset flags to zero */
477                 cgrp->bpf.flags[type] = 0;
478
479         bpf_prog_put(old_prog);
480         static_branch_dec(&cgroup_bpf_enabled_key);
481         return 0;
482
483 cleanup:
484         /* and restore back old_prog */
485         pl->prog = old_prog;
486         return err;
487 }
488
489 /* Must be called with cgroup_mutex held to avoid races. */
490 int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
491                        union bpf_attr __user *uattr)
492 {
493         __u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
494         enum bpf_attach_type type = attr->query.attach_type;
495         struct list_head *progs = &cgrp->bpf.progs[type];
496         u32 flags = cgrp->bpf.flags[type];
497         struct bpf_prog_array *effective;
498         int cnt, ret = 0, i;
499
500         effective = rcu_dereference_protected(cgrp->bpf.effective[type],
501                                               lockdep_is_held(&cgroup_mutex));
502
503         if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE)
504                 cnt = bpf_prog_array_length(effective);
505         else
506                 cnt = prog_list_length(progs);
507
508         if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
509                 return -EFAULT;
510         if (copy_to_user(&uattr->query.prog_cnt, &cnt, sizeof(cnt)))
511                 return -EFAULT;
512         if (attr->query.prog_cnt == 0 || !prog_ids || !cnt)
513                 /* return early if user requested only program count + flags */
514                 return 0;
515         if (attr->query.prog_cnt < cnt) {
516                 cnt = attr->query.prog_cnt;
517                 ret = -ENOSPC;
518         }
519
520         if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE) {
521                 return bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
522         } else {
523                 struct bpf_prog_list *pl;
524                 u32 id;
525
526                 i = 0;
527                 list_for_each_entry(pl, progs, node) {
528                         id = pl->prog->aux->id;
529                         if (copy_to_user(prog_ids + i, &id, sizeof(id)))
530                                 return -EFAULT;
531                         if (++i == cnt)
532                                 break;
533                 }
534         }
535         return ret;
536 }
537
538 int cgroup_bpf_prog_attach(const union bpf_attr *attr,
539                            enum bpf_prog_type ptype, struct bpf_prog *prog)
540 {
541         struct cgroup *cgrp;
542         int ret;
543
544         cgrp = cgroup_get_from_fd(attr->target_fd);
545         if (IS_ERR(cgrp))
546                 return PTR_ERR(cgrp);
547
548         ret = cgroup_bpf_attach(cgrp, prog, attr->attach_type,
549                                 attr->attach_flags);
550         cgroup_put(cgrp);
551         return ret;
552 }
553
554 int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
555 {
556         struct bpf_prog *prog;
557         struct cgroup *cgrp;
558         int ret;
559
560         cgrp = cgroup_get_from_fd(attr->target_fd);
561         if (IS_ERR(cgrp))
562                 return PTR_ERR(cgrp);
563
564         prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
565         if (IS_ERR(prog))
566                 prog = NULL;
567
568         ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type, 0);
569         if (prog)
570                 bpf_prog_put(prog);
571
572         cgroup_put(cgrp);
573         return ret;
574 }
575
576 int cgroup_bpf_prog_query(const union bpf_attr *attr,
577                           union bpf_attr __user *uattr)
578 {
579         struct cgroup *cgrp;
580         int ret;
581
582         cgrp = cgroup_get_from_fd(attr->query.target_fd);
583         if (IS_ERR(cgrp))
584                 return PTR_ERR(cgrp);
585
586         ret = cgroup_bpf_query(cgrp, attr, uattr);
587
588         cgroup_put(cgrp);
589         return ret;
590 }
591
592 /**
593  * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
594  * @sk: The socket sending or receiving traffic
595  * @skb: The skb that is being sent or received
596  * @type: The type of program to be exectuted
597  *
598  * If no socket is passed, or the socket is not of type INET or INET6,
599  * this function does nothing and returns 0.
600  *
601  * The program type passed in via @type must be suitable for network
602  * filtering. No further check is performed to assert that.
603  *
604  * For egress packets, this function can return:
605  *   NET_XMIT_SUCCESS    (0)    - continue with packet output
606  *   NET_XMIT_DROP       (1)    - drop packet and notify TCP to call cwr
607  *   NET_XMIT_CN         (2)    - continue with packet output and notify TCP
608  *                                to call cwr
609  *   -EPERM                     - drop packet
610  *
611  * For ingress packets, this function will return -EPERM if any
612  * attached program was found and if it returned != 1 during execution.
613  * Otherwise 0 is returned.
614  */
615 int __cgroup_bpf_run_filter_skb(struct sock *sk,
616                                 struct sk_buff *skb,
617                                 enum bpf_attach_type type)
618 {
619         unsigned int offset = skb->data - skb_network_header(skb);
620         struct sock *save_sk;
621         void *saved_data_end;
622         struct cgroup *cgrp;
623         int ret;
624
625         if (!sk || !sk_fullsock(sk))
626                 return 0;
627
628         if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
629                 return 0;
630
631         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
632         save_sk = skb->sk;
633         skb->sk = sk;
634         __skb_push(skb, offset);
635
636         /* compute pointers for the bpf prog */
637         bpf_compute_and_save_data_end(skb, &saved_data_end);
638
639         if (type == BPF_CGROUP_INET_EGRESS) {
640                 ret = BPF_PROG_CGROUP_INET_EGRESS_RUN_ARRAY(
641                         cgrp->bpf.effective[type], skb, __bpf_prog_run_save_cb);
642         } else {
643                 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], skb,
644                                           __bpf_prog_run_save_cb);
645                 ret = (ret == 1 ? 0 : -EPERM);
646         }
647         bpf_restore_data_end(skb, saved_data_end);
648         __skb_pull(skb, offset);
649         skb->sk = save_sk;
650
651         return ret;
652 }
653 EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
654
655 /**
656  * __cgroup_bpf_run_filter_sk() - Run a program on a sock
657  * @sk: sock structure to manipulate
658  * @type: The type of program to be exectuted
659  *
660  * socket is passed is expected to be of type INET or INET6.
661  *
662  * The program type passed in via @type must be suitable for sock
663  * filtering. No further check is performed to assert that.
664  *
665  * This function will return %-EPERM if any if an attached program was found
666  * and if it returned != 1 during execution. In all other cases, 0 is returned.
667  */
668 int __cgroup_bpf_run_filter_sk(struct sock *sk,
669                                enum bpf_attach_type type)
670 {
671         struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
672         int ret;
673
674         ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sk, BPF_PROG_RUN);
675         return ret == 1 ? 0 : -EPERM;
676 }
677 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
678
679 /**
680  * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
681  *                                       provided by user sockaddr
682  * @sk: sock struct that will use sockaddr
683  * @uaddr: sockaddr struct provided by user
684  * @type: The type of program to be exectuted
685  * @t_ctx: Pointer to attach type specific context
686  *
687  * socket is expected to be of type INET or INET6.
688  *
689  * This function will return %-EPERM if an attached program is found and
690  * returned value != 1 during execution. In all other cases, 0 is returned.
691  */
692 int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
693                                       struct sockaddr *uaddr,
694                                       enum bpf_attach_type type,
695                                       void *t_ctx)
696 {
697         struct bpf_sock_addr_kern ctx = {
698                 .sk = sk,
699                 .uaddr = uaddr,
700                 .t_ctx = t_ctx,
701         };
702         struct sockaddr_storage unspec;
703         struct cgroup *cgrp;
704         int ret;
705
706         /* Check socket family since not all sockets represent network
707          * endpoint (e.g. AF_UNIX).
708          */
709         if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
710                 return 0;
711
712         if (!ctx.uaddr) {
713                 memset(&unspec, 0, sizeof(unspec));
714                 ctx.uaddr = (struct sockaddr *)&unspec;
715         }
716
717         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
718         ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
719
720         return ret == 1 ? 0 : -EPERM;
721 }
722 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
723
724 /**
725  * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
726  * @sk: socket to get cgroup from
727  * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
728  * sk with connection information (IP addresses, etc.) May not contain
729  * cgroup info if it is a req sock.
730  * @type: The type of program to be exectuted
731  *
732  * socket passed is expected to be of type INET or INET6.
733  *
734  * The program type passed in via @type must be suitable for sock_ops
735  * filtering. No further check is performed to assert that.
736  *
737  * This function will return %-EPERM if any if an attached program was found
738  * and if it returned != 1 during execution. In all other cases, 0 is returned.
739  */
740 int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
741                                      struct bpf_sock_ops_kern *sock_ops,
742                                      enum bpf_attach_type type)
743 {
744         struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
745         int ret;
746
747         ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sock_ops,
748                                  BPF_PROG_RUN);
749         return ret == 1 ? 0 : -EPERM;
750 }
751 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
752
753 int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
754                                       short access, enum bpf_attach_type type)
755 {
756         struct cgroup *cgrp;
757         struct bpf_cgroup_dev_ctx ctx = {
758                 .access_type = (access << 16) | dev_type,
759                 .major = major,
760                 .minor = minor,
761         };
762         int allow = 1;
763
764         rcu_read_lock();
765         cgrp = task_dfl_cgroup(current);
766         allow = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx,
767                                    BPF_PROG_RUN);
768         rcu_read_unlock();
769
770         return !allow;
771 }
772 EXPORT_SYMBOL(__cgroup_bpf_check_dev_permission);
773
774 static const struct bpf_func_proto *
775 cgroup_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
776 {
777         switch (func_id) {
778         case BPF_FUNC_map_lookup_elem:
779                 return &bpf_map_lookup_elem_proto;
780         case BPF_FUNC_map_update_elem:
781                 return &bpf_map_update_elem_proto;
782         case BPF_FUNC_map_delete_elem:
783                 return &bpf_map_delete_elem_proto;
784         case BPF_FUNC_map_push_elem:
785                 return &bpf_map_push_elem_proto;
786         case BPF_FUNC_map_pop_elem:
787                 return &bpf_map_pop_elem_proto;
788         case BPF_FUNC_map_peek_elem:
789                 return &bpf_map_peek_elem_proto;
790         case BPF_FUNC_get_current_uid_gid:
791                 return &bpf_get_current_uid_gid_proto;
792         case BPF_FUNC_get_local_storage:
793                 return &bpf_get_local_storage_proto;
794         case BPF_FUNC_get_current_cgroup_id:
795                 return &bpf_get_current_cgroup_id_proto;
796         case BPF_FUNC_trace_printk:
797                 if (capable(CAP_SYS_ADMIN))
798                         return bpf_get_trace_printk_proto();
799                 /* fall through */
800         default:
801                 return NULL;
802         }
803 }
804
805 static const struct bpf_func_proto *
806 cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
807 {
808         return cgroup_base_func_proto(func_id, prog);
809 }
810
811 static bool cgroup_dev_is_valid_access(int off, int size,
812                                        enum bpf_access_type type,
813                                        const struct bpf_prog *prog,
814                                        struct bpf_insn_access_aux *info)
815 {
816         const int size_default = sizeof(__u32);
817
818         if (type == BPF_WRITE)
819                 return false;
820
821         if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
822                 return false;
823         /* The verifier guarantees that size > 0. */
824         if (off % size != 0)
825                 return false;
826
827         switch (off) {
828         case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
829                 bpf_ctx_record_field_size(info, size_default);
830                 if (!bpf_ctx_narrow_access_ok(off, size, size_default))
831                         return false;
832                 break;
833         default:
834                 if (size != size_default)
835                         return false;
836         }
837
838         return true;
839 }
840
841 const struct bpf_prog_ops cg_dev_prog_ops = {
842 };
843
844 const struct bpf_verifier_ops cg_dev_verifier_ops = {
845         .get_func_proto         = cgroup_dev_func_proto,
846         .is_valid_access        = cgroup_dev_is_valid_access,
847 };
848
849 /**
850  * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
851  *
852  * @head: sysctl table header
853  * @table: sysctl table
854  * @write: sysctl is being read (= 0) or written (= 1)
855  * @buf: pointer to buffer passed by user space
856  * @pcount: value-result argument: value is size of buffer pointed to by @buf,
857  *      result is size of @new_buf if program set new value, initial value
858  *      otherwise
859  * @ppos: value-result argument: value is position at which read from or write
860  *      to sysctl is happening, result is new position if program overrode it,
861  *      initial value otherwise
862  * @new_buf: pointer to pointer to new buffer that will be allocated if program
863  *      overrides new value provided by user space on sysctl write
864  *      NOTE: it's caller responsibility to free *new_buf if it was set
865  * @type: type of program to be executed
866  *
867  * Program is run when sysctl is being accessed, either read or written, and
868  * can allow or deny such access.
869  *
870  * This function will return %-EPERM if an attached program is found and
871  * returned value != 1 during execution. In all other cases 0 is returned.
872  */
873 int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
874                                    struct ctl_table *table, int write,
875                                    void __user *buf, size_t *pcount,
876                                    loff_t *ppos, void **new_buf,
877                                    enum bpf_attach_type type)
878 {
879         struct bpf_sysctl_kern ctx = {
880                 .head = head,
881                 .table = table,
882                 .write = write,
883                 .ppos = ppos,
884                 .cur_val = NULL,
885                 .cur_len = PAGE_SIZE,
886                 .new_val = NULL,
887                 .new_len = 0,
888                 .new_updated = 0,
889         };
890         struct cgroup *cgrp;
891         int ret;
892
893         ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
894         if (ctx.cur_val) {
895                 mm_segment_t old_fs;
896                 loff_t pos = 0;
897
898                 old_fs = get_fs();
899                 set_fs(KERNEL_DS);
900                 if (table->proc_handler(table, 0, (void __user *)ctx.cur_val,
901                                         &ctx.cur_len, &pos)) {
902                         /* Let BPF program decide how to proceed. */
903                         ctx.cur_len = 0;
904                 }
905                 set_fs(old_fs);
906         } else {
907                 /* Let BPF program decide how to proceed. */
908                 ctx.cur_len = 0;
909         }
910
911         if (write && buf && *pcount) {
912                 /* BPF program should be able to override new value with a
913                  * buffer bigger than provided by user.
914                  */
915                 ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
916                 ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
917                 if (!ctx.new_val ||
918                     copy_from_user(ctx.new_val, buf, ctx.new_len))
919                         /* Let BPF program decide how to proceed. */
920                         ctx.new_len = 0;
921         }
922
923         rcu_read_lock();
924         cgrp = task_dfl_cgroup(current);
925         ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
926         rcu_read_unlock();
927
928         kfree(ctx.cur_val);
929
930         if (ret == 1 && ctx.new_updated) {
931                 *new_buf = ctx.new_val;
932                 *pcount = ctx.new_len;
933         } else {
934                 kfree(ctx.new_val);
935         }
936
937         return ret == 1 ? 0 : -EPERM;
938 }
939 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sysctl);
940
941 static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
942                               size_t *lenp)
943 {
944         ssize_t tmp_ret = 0, ret;
945
946         if (dir->header.parent) {
947                 tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
948                 if (tmp_ret < 0)
949                         return tmp_ret;
950         }
951
952         ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
953         if (ret < 0)
954                 return ret;
955         *bufp += ret;
956         *lenp -= ret;
957         ret += tmp_ret;
958
959         /* Avoid leading slash. */
960         if (!ret)
961                 return ret;
962
963         tmp_ret = strscpy(*bufp, "/", *lenp);
964         if (tmp_ret < 0)
965                 return tmp_ret;
966         *bufp += tmp_ret;
967         *lenp -= tmp_ret;
968
969         return ret + tmp_ret;
970 }
971
972 BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
973            size_t, buf_len, u64, flags)
974 {
975         ssize_t tmp_ret = 0, ret;
976
977         if (!buf)
978                 return -EINVAL;
979
980         if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
981                 if (!ctx->head)
982                         return -EINVAL;
983                 tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
984                 if (tmp_ret < 0)
985                         return tmp_ret;
986         }
987
988         ret = strscpy(buf, ctx->table->procname, buf_len);
989
990         return ret < 0 ? ret : tmp_ret + ret;
991 }
992
993 static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
994         .func           = bpf_sysctl_get_name,
995         .gpl_only       = false,
996         .ret_type       = RET_INTEGER,
997         .arg1_type      = ARG_PTR_TO_CTX,
998         .arg2_type      = ARG_PTR_TO_MEM,
999         .arg3_type      = ARG_CONST_SIZE,
1000         .arg4_type      = ARG_ANYTHING,
1001 };
1002
1003 static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
1004                              size_t src_len)
1005 {
1006         if (!dst)
1007                 return -EINVAL;
1008
1009         if (!dst_len)
1010                 return -E2BIG;
1011
1012         if (!src || !src_len) {
1013                 memset(dst, 0, dst_len);
1014                 return -EINVAL;
1015         }
1016
1017         memcpy(dst, src, min(dst_len, src_len));
1018
1019         if (dst_len > src_len) {
1020                 memset(dst + src_len, '\0', dst_len - src_len);
1021                 return src_len;
1022         }
1023
1024         dst[dst_len - 1] = '\0';
1025
1026         return -E2BIG;
1027 }
1028
1029 BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
1030            char *, buf, size_t, buf_len)
1031 {
1032         return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
1033 }
1034
1035 static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
1036         .func           = bpf_sysctl_get_current_value,
1037         .gpl_only       = false,
1038         .ret_type       = RET_INTEGER,
1039         .arg1_type      = ARG_PTR_TO_CTX,
1040         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1041         .arg3_type      = ARG_CONST_SIZE,
1042 };
1043
1044 BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
1045            size_t, buf_len)
1046 {
1047         if (!ctx->write) {
1048                 if (buf && buf_len)
1049                         memset(buf, '\0', buf_len);
1050                 return -EINVAL;
1051         }
1052         return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
1053 }
1054
1055 static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
1056         .func           = bpf_sysctl_get_new_value,
1057         .gpl_only       = false,
1058         .ret_type       = RET_INTEGER,
1059         .arg1_type      = ARG_PTR_TO_CTX,
1060         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
1061         .arg3_type      = ARG_CONST_SIZE,
1062 };
1063
1064 BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
1065            const char *, buf, size_t, buf_len)
1066 {
1067         if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
1068                 return -EINVAL;
1069
1070         if (buf_len > PAGE_SIZE - 1)
1071                 return -E2BIG;
1072
1073         memcpy(ctx->new_val, buf, buf_len);
1074         ctx->new_len = buf_len;
1075         ctx->new_updated = 1;
1076
1077         return 0;
1078 }
1079
1080 static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
1081         .func           = bpf_sysctl_set_new_value,
1082         .gpl_only       = false,
1083         .ret_type       = RET_INTEGER,
1084         .arg1_type      = ARG_PTR_TO_CTX,
1085         .arg2_type      = ARG_PTR_TO_MEM,
1086         .arg3_type      = ARG_CONST_SIZE,
1087 };
1088
1089 static const struct bpf_func_proto *
1090 sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1091 {
1092         switch (func_id) {
1093         case BPF_FUNC_strtol:
1094                 return &bpf_strtol_proto;
1095         case BPF_FUNC_strtoul:
1096                 return &bpf_strtoul_proto;
1097         case BPF_FUNC_sysctl_get_name:
1098                 return &bpf_sysctl_get_name_proto;
1099         case BPF_FUNC_sysctl_get_current_value:
1100                 return &bpf_sysctl_get_current_value_proto;
1101         case BPF_FUNC_sysctl_get_new_value:
1102                 return &bpf_sysctl_get_new_value_proto;
1103         case BPF_FUNC_sysctl_set_new_value:
1104                 return &bpf_sysctl_set_new_value_proto;
1105         default:
1106                 return cgroup_base_func_proto(func_id, prog);
1107         }
1108 }
1109
1110 static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
1111                                    const struct bpf_prog *prog,
1112                                    struct bpf_insn_access_aux *info)
1113 {
1114         const int size_default = sizeof(__u32);
1115
1116         if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
1117                 return false;
1118
1119         switch (off) {
1120         case offsetof(struct bpf_sysctl, write):
1121                 if (type != BPF_READ)
1122                         return false;
1123                 bpf_ctx_record_field_size(info, size_default);
1124                 return bpf_ctx_narrow_access_ok(off, size, size_default);
1125         case offsetof(struct bpf_sysctl, file_pos):
1126                 if (type == BPF_READ) {
1127                         bpf_ctx_record_field_size(info, size_default);
1128                         return bpf_ctx_narrow_access_ok(off, size, size_default);
1129                 } else {
1130                         return size == size_default;
1131                 }
1132         default:
1133                 return false;
1134         }
1135 }
1136
1137 static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
1138                                      const struct bpf_insn *si,
1139                                      struct bpf_insn *insn_buf,
1140                                      struct bpf_prog *prog, u32 *target_size)
1141 {
1142         struct bpf_insn *insn = insn_buf;
1143
1144         switch (si->off) {
1145         case offsetof(struct bpf_sysctl, write):
1146                 *insn++ = BPF_LDX_MEM(
1147                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
1148                         bpf_target_off(struct bpf_sysctl_kern, write,
1149                                        FIELD_SIZEOF(struct bpf_sysctl_kern,
1150                                                     write),
1151                                        target_size));
1152                 break;
1153         case offsetof(struct bpf_sysctl, file_pos):
1154                 /* ppos is a pointer so it should be accessed via indirect
1155                  * loads and stores. Also for stores additional temporary
1156                  * register is used since neither src_reg nor dst_reg can be
1157                  * overridden.
1158                  */
1159                 if (type == BPF_WRITE) {
1160                         int treg = BPF_REG_9;
1161
1162                         if (si->src_reg == treg || si->dst_reg == treg)
1163                                 --treg;
1164                         if (si->src_reg == treg || si->dst_reg == treg)
1165                                 --treg;
1166                         *insn++ = BPF_STX_MEM(
1167                                 BPF_DW, si->dst_reg, treg,
1168                                 offsetof(struct bpf_sysctl_kern, tmp_reg));
1169                         *insn++ = BPF_LDX_MEM(
1170                                 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1171                                 treg, si->dst_reg,
1172                                 offsetof(struct bpf_sysctl_kern, ppos));
1173                         *insn++ = BPF_STX_MEM(
1174                                 BPF_SIZEOF(u32), treg, si->src_reg, 0);
1175                         *insn++ = BPF_LDX_MEM(
1176                                 BPF_DW, treg, si->dst_reg,
1177                                 offsetof(struct bpf_sysctl_kern, tmp_reg));
1178                 } else {
1179                         *insn++ = BPF_LDX_MEM(
1180                                 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1181                                 si->dst_reg, si->src_reg,
1182                                 offsetof(struct bpf_sysctl_kern, ppos));
1183                         *insn++ = BPF_LDX_MEM(
1184                                 BPF_SIZE(si->code), si->dst_reg, si->dst_reg, 0);
1185                 }
1186                 *target_size = sizeof(u32);
1187                 break;
1188         }
1189
1190         return insn - insn_buf;
1191 }
1192
1193 const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
1194         .get_func_proto         = sysctl_func_proto,
1195         .is_valid_access        = sysctl_is_valid_access,
1196         .convert_ctx_access     = sysctl_convert_ctx_access,
1197 };
1198
1199 const struct bpf_prog_ops cg_sysctl_prog_ops = {
1200 };