Loading...
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 <linux/bpf_lsm.h>
18#include <linux/bpf_verifier.h>
19#include <net/sock.h>
20#include <net/bpf_sk_storage.h>
21
22#include "../cgroup/cgroup-internal.h"
23
24DEFINE_STATIC_KEY_ARRAY_FALSE(cgroup_bpf_enabled_key, MAX_CGROUP_BPF_ATTACH_TYPE);
25EXPORT_SYMBOL(cgroup_bpf_enabled_key);
26
27/*
28 * cgroup bpf destruction makes heavy use of work items and there can be a lot
29 * of concurrent destructions. Use a separate workqueue so that cgroup bpf
30 * destruction work items don't end up filling up max_active of system_wq
31 * which may lead to deadlock.
32 */
33static struct workqueue_struct *cgroup_bpf_destroy_wq;
34
35static int __init cgroup_bpf_wq_init(void)
36{
37 cgroup_bpf_destroy_wq = alloc_workqueue("cgroup_bpf_destroy", 0, 1);
38 if (!cgroup_bpf_destroy_wq)
39 panic("Failed to alloc workqueue for cgroup bpf destroy.\n");
40 return 0;
41}
42core_initcall(cgroup_bpf_wq_init);
43
44/* __always_inline is necessary to prevent indirect call through run_prog
45 * function pointer.
46 */
47static __always_inline int
48bpf_prog_run_array_cg(const struct cgroup_bpf *cgrp,
49 enum cgroup_bpf_attach_type atype,
50 const void *ctx, bpf_prog_run_fn run_prog,
51 int retval, u32 *ret_flags)
52{
53 const struct bpf_prog_array_item *item;
54 const struct bpf_prog *prog;
55 const struct bpf_prog_array *array;
56 struct bpf_run_ctx *old_run_ctx;
57 struct bpf_cg_run_ctx run_ctx;
58 u32 func_ret;
59
60 run_ctx.retval = retval;
61 migrate_disable();
62 rcu_read_lock();
63 array = rcu_dereference(cgrp->effective[atype]);
64 item = &array->items[0];
65 old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
66 while ((prog = READ_ONCE(item->prog))) {
67 run_ctx.prog_item = item;
68 func_ret = run_prog(prog, ctx);
69 if (ret_flags) {
70 *(ret_flags) |= (func_ret >> 1);
71 func_ret &= 1;
72 }
73 if (!func_ret && !IS_ERR_VALUE((long)run_ctx.retval))
74 run_ctx.retval = -EPERM;
75 item++;
76 }
77 bpf_reset_run_ctx(old_run_ctx);
78 rcu_read_unlock();
79 migrate_enable();
80 return run_ctx.retval;
81}
82
83unsigned int __cgroup_bpf_run_lsm_sock(const void *ctx,
84 const struct bpf_insn *insn)
85{
86 const struct bpf_prog *shim_prog;
87 struct sock *sk;
88 struct cgroup *cgrp;
89 int ret = 0;
90 u64 *args;
91
92 args = (u64 *)ctx;
93 sk = (void *)(unsigned long)args[0];
94 /*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
95 shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
96
97 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
98 if (likely(cgrp))
99 ret = bpf_prog_run_array_cg(&cgrp->bpf,
100 shim_prog->aux->cgroup_atype,
101 ctx, bpf_prog_run, 0, NULL);
102 return ret;
103}
104
105unsigned int __cgroup_bpf_run_lsm_socket(const void *ctx,
106 const struct bpf_insn *insn)
107{
108 const struct bpf_prog *shim_prog;
109 struct socket *sock;
110 struct cgroup *cgrp;
111 int ret = 0;
112 u64 *args;
113
114 args = (u64 *)ctx;
115 sock = (void *)(unsigned long)args[0];
116 /*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
117 shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
118
119 cgrp = sock_cgroup_ptr(&sock->sk->sk_cgrp_data);
120 if (likely(cgrp))
121 ret = bpf_prog_run_array_cg(&cgrp->bpf,
122 shim_prog->aux->cgroup_atype,
123 ctx, bpf_prog_run, 0, NULL);
124 return ret;
125}
126
127unsigned int __cgroup_bpf_run_lsm_current(const void *ctx,
128 const struct bpf_insn *insn)
129{
130 const struct bpf_prog *shim_prog;
131 struct cgroup *cgrp;
132 int ret = 0;
133
134 /*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
135 shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
136
137 /* We rely on trampoline's __bpf_prog_enter_lsm_cgroup to grab RCU read lock. */
138 cgrp = task_dfl_cgroup(current);
139 if (likely(cgrp))
140 ret = bpf_prog_run_array_cg(&cgrp->bpf,
141 shim_prog->aux->cgroup_atype,
142 ctx, bpf_prog_run, 0, NULL);
143 return ret;
144}
145
146#ifdef CONFIG_BPF_LSM
147struct cgroup_lsm_atype {
148 u32 attach_btf_id;
149 int refcnt;
150};
151
152static struct cgroup_lsm_atype cgroup_lsm_atype[CGROUP_LSM_NUM];
153
154static enum cgroup_bpf_attach_type
155bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
156{
157 int i;
158
159 lockdep_assert_held(&cgroup_mutex);
160
161 if (attach_type != BPF_LSM_CGROUP)
162 return to_cgroup_bpf_attach_type(attach_type);
163
164 for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
165 if (cgroup_lsm_atype[i].attach_btf_id == attach_btf_id)
166 return CGROUP_LSM_START + i;
167
168 for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
169 if (cgroup_lsm_atype[i].attach_btf_id == 0)
170 return CGROUP_LSM_START + i;
171
172 return -E2BIG;
173
174}
175
176void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype)
177{
178 int i = cgroup_atype - CGROUP_LSM_START;
179
180 lockdep_assert_held(&cgroup_mutex);
181
182 WARN_ON_ONCE(cgroup_lsm_atype[i].attach_btf_id &&
183 cgroup_lsm_atype[i].attach_btf_id != attach_btf_id);
184
185 cgroup_lsm_atype[i].attach_btf_id = attach_btf_id;
186 cgroup_lsm_atype[i].refcnt++;
187}
188
189void bpf_cgroup_atype_put(int cgroup_atype)
190{
191 int i = cgroup_atype - CGROUP_LSM_START;
192
193 cgroup_lock();
194 if (--cgroup_lsm_atype[i].refcnt <= 0)
195 cgroup_lsm_atype[i].attach_btf_id = 0;
196 WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0);
197 cgroup_unlock();
198}
199#else
200static enum cgroup_bpf_attach_type
201bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
202{
203 if (attach_type != BPF_LSM_CGROUP)
204 return to_cgroup_bpf_attach_type(attach_type);
205 return -EOPNOTSUPP;
206}
207#endif /* CONFIG_BPF_LSM */
208
209void cgroup_bpf_offline(struct cgroup *cgrp)
210{
211 cgroup_get(cgrp);
212 percpu_ref_kill(&cgrp->bpf.refcnt);
213}
214
215static void bpf_cgroup_storages_free(struct bpf_cgroup_storage *storages[])
216{
217 enum bpf_cgroup_storage_type stype;
218
219 for_each_cgroup_storage_type(stype)
220 bpf_cgroup_storage_free(storages[stype]);
221}
222
223static int bpf_cgroup_storages_alloc(struct bpf_cgroup_storage *storages[],
224 struct bpf_cgroup_storage *new_storages[],
225 enum bpf_attach_type type,
226 struct bpf_prog *prog,
227 struct cgroup *cgrp)
228{
229 enum bpf_cgroup_storage_type stype;
230 struct bpf_cgroup_storage_key key;
231 struct bpf_map *map;
232
233 key.cgroup_inode_id = cgroup_id(cgrp);
234 key.attach_type = type;
235
236 for_each_cgroup_storage_type(stype) {
237 map = prog->aux->cgroup_storage[stype];
238 if (!map)
239 continue;
240
241 storages[stype] = cgroup_storage_lookup((void *)map, &key, false);
242 if (storages[stype])
243 continue;
244
245 storages[stype] = bpf_cgroup_storage_alloc(prog, stype);
246 if (IS_ERR(storages[stype])) {
247 bpf_cgroup_storages_free(new_storages);
248 return -ENOMEM;
249 }
250
251 new_storages[stype] = storages[stype];
252 }
253
254 return 0;
255}
256
257static void bpf_cgroup_storages_assign(struct bpf_cgroup_storage *dst[],
258 struct bpf_cgroup_storage *src[])
259{
260 enum bpf_cgroup_storage_type stype;
261
262 for_each_cgroup_storage_type(stype)
263 dst[stype] = src[stype];
264}
265
266static void bpf_cgroup_storages_link(struct bpf_cgroup_storage *storages[],
267 struct cgroup *cgrp,
268 enum bpf_attach_type attach_type)
269{
270 enum bpf_cgroup_storage_type stype;
271
272 for_each_cgroup_storage_type(stype)
273 bpf_cgroup_storage_link(storages[stype], cgrp, attach_type);
274}
275
276/* Called when bpf_cgroup_link is auto-detached from dying cgroup.
277 * It drops cgroup and bpf_prog refcounts, and marks bpf_link as defunct. It
278 * doesn't free link memory, which will eventually be done by bpf_link's
279 * release() callback, when its last FD is closed.
280 */
281static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)
282{
283 cgroup_put(link->cgroup);
284 link->cgroup = NULL;
285}
286
287/**
288 * cgroup_bpf_release() - put references of all bpf programs and
289 * release all cgroup bpf data
290 * @work: work structure embedded into the cgroup to modify
291 */
292static void cgroup_bpf_release(struct work_struct *work)
293{
294 struct cgroup *p, *cgrp = container_of(work, struct cgroup,
295 bpf.release_work);
296 struct bpf_prog_array *old_array;
297 struct list_head *storages = &cgrp->bpf.storages;
298 struct bpf_cgroup_storage *storage, *stmp;
299
300 unsigned int atype;
301
302 cgroup_lock();
303
304 for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) {
305 struct hlist_head *progs = &cgrp->bpf.progs[atype];
306 struct bpf_prog_list *pl;
307 struct hlist_node *pltmp;
308
309 hlist_for_each_entry_safe(pl, pltmp, progs, node) {
310 hlist_del(&pl->node);
311 if (pl->prog) {
312 if (pl->prog->expected_attach_type == BPF_LSM_CGROUP)
313 bpf_trampoline_unlink_cgroup_shim(pl->prog);
314 bpf_prog_put(pl->prog);
315 }
316 if (pl->link) {
317 if (pl->link->link.prog->expected_attach_type == BPF_LSM_CGROUP)
318 bpf_trampoline_unlink_cgroup_shim(pl->link->link.prog);
319 bpf_cgroup_link_auto_detach(pl->link);
320 }
321 kfree(pl);
322 static_branch_dec(&cgroup_bpf_enabled_key[atype]);
323 }
324 old_array = rcu_dereference_protected(
325 cgrp->bpf.effective[atype],
326 lockdep_is_held(&cgroup_mutex));
327 bpf_prog_array_free(old_array);
328 }
329
330 list_for_each_entry_safe(storage, stmp, storages, list_cg) {
331 bpf_cgroup_storage_unlink(storage);
332 bpf_cgroup_storage_free(storage);
333 }
334
335 cgroup_unlock();
336
337 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
338 cgroup_bpf_put(p);
339
340 percpu_ref_exit(&cgrp->bpf.refcnt);
341 cgroup_put(cgrp);
342}
343
344/**
345 * cgroup_bpf_release_fn() - callback used to schedule releasing
346 * of bpf cgroup data
347 * @ref: percpu ref counter structure
348 */
349static void cgroup_bpf_release_fn(struct percpu_ref *ref)
350{
351 struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
352
353 INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
354 queue_work(cgroup_bpf_destroy_wq, &cgrp->bpf.release_work);
355}
356
357/* Get underlying bpf_prog of bpf_prog_list entry, regardless if it's through
358 * link or direct prog.
359 */
360static struct bpf_prog *prog_list_prog(struct bpf_prog_list *pl)
361{
362 if (pl->prog)
363 return pl->prog;
364 if (pl->link)
365 return pl->link->link.prog;
366 return NULL;
367}
368
369/* count number of elements in the list.
370 * it's slow but the list cannot be long
371 */
372static u32 prog_list_length(struct hlist_head *head)
373{
374 struct bpf_prog_list *pl;
375 u32 cnt = 0;
376
377 hlist_for_each_entry(pl, head, node) {
378 if (!prog_list_prog(pl))
379 continue;
380 cnt++;
381 }
382 return cnt;
383}
384
385/* if parent has non-overridable prog attached,
386 * disallow attaching new programs to the descendent cgroup.
387 * if parent has overridable or multi-prog, allow attaching
388 */
389static bool hierarchy_allows_attach(struct cgroup *cgrp,
390 enum cgroup_bpf_attach_type atype)
391{
392 struct cgroup *p;
393
394 p = cgroup_parent(cgrp);
395 if (!p)
396 return true;
397 do {
398 u32 flags = p->bpf.flags[atype];
399 u32 cnt;
400
401 if (flags & BPF_F_ALLOW_MULTI)
402 return true;
403 cnt = prog_list_length(&p->bpf.progs[atype]);
404 WARN_ON_ONCE(cnt > 1);
405 if (cnt == 1)
406 return !!(flags & BPF_F_ALLOW_OVERRIDE);
407 p = cgroup_parent(p);
408 } while (p);
409 return true;
410}
411
412/* compute a chain of effective programs for a given cgroup:
413 * start from the list of programs in this cgroup and add
414 * all parent programs.
415 * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
416 * to programs in this cgroup
417 */
418static int compute_effective_progs(struct cgroup *cgrp,
419 enum cgroup_bpf_attach_type atype,
420 struct bpf_prog_array **array)
421{
422 struct bpf_prog_array_item *item;
423 struct bpf_prog_array *progs;
424 struct bpf_prog_list *pl;
425 struct cgroup *p = cgrp;
426 int cnt = 0;
427
428 /* count number of effective programs by walking parents */
429 do {
430 if (cnt == 0 || (p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
431 cnt += prog_list_length(&p->bpf.progs[atype]);
432 p = cgroup_parent(p);
433 } while (p);
434
435 progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
436 if (!progs)
437 return -ENOMEM;
438
439 /* populate the array with effective progs */
440 cnt = 0;
441 p = cgrp;
442 do {
443 if (cnt > 0 && !(p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
444 continue;
445
446 hlist_for_each_entry(pl, &p->bpf.progs[atype], node) {
447 if (!prog_list_prog(pl))
448 continue;
449
450 item = &progs->items[cnt];
451 item->prog = prog_list_prog(pl);
452 bpf_cgroup_storages_assign(item->cgroup_storage,
453 pl->storage);
454 cnt++;
455 }
456 } while ((p = cgroup_parent(p)));
457
458 *array = progs;
459 return 0;
460}
461
462static void activate_effective_progs(struct cgroup *cgrp,
463 enum cgroup_bpf_attach_type atype,
464 struct bpf_prog_array *old_array)
465{
466 old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array,
467 lockdep_is_held(&cgroup_mutex));
468 /* free prog array after grace period, since __cgroup_bpf_run_*()
469 * might be still walking the array
470 */
471 bpf_prog_array_free(old_array);
472}
473
474/**
475 * cgroup_bpf_inherit() - inherit effective programs from parent
476 * @cgrp: the cgroup to modify
477 */
478int cgroup_bpf_inherit(struct cgroup *cgrp)
479{
480/* has to use marco instead of const int, since compiler thinks
481 * that array below is variable length
482 */
483#define NR ARRAY_SIZE(cgrp->bpf.effective)
484 struct bpf_prog_array *arrays[NR] = {};
485 struct cgroup *p;
486 int ret, i;
487
488 ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
489 GFP_KERNEL);
490 if (ret)
491 return ret;
492
493 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
494 cgroup_bpf_get(p);
495
496 for (i = 0; i < NR; i++)
497 INIT_HLIST_HEAD(&cgrp->bpf.progs[i]);
498
499 INIT_LIST_HEAD(&cgrp->bpf.storages);
500
501 for (i = 0; i < NR; i++)
502 if (compute_effective_progs(cgrp, i, &arrays[i]))
503 goto cleanup;
504
505 for (i = 0; i < NR; i++)
506 activate_effective_progs(cgrp, i, arrays[i]);
507
508 return 0;
509cleanup:
510 for (i = 0; i < NR; i++)
511 bpf_prog_array_free(arrays[i]);
512
513 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
514 cgroup_bpf_put(p);
515
516 percpu_ref_exit(&cgrp->bpf.refcnt);
517
518 return -ENOMEM;
519}
520
521static int update_effective_progs(struct cgroup *cgrp,
522 enum cgroup_bpf_attach_type atype)
523{
524 struct cgroup_subsys_state *css;
525 int err;
526
527 /* allocate and recompute effective prog arrays */
528 css_for_each_descendant_pre(css, &cgrp->self) {
529 struct cgroup *desc = container_of(css, struct cgroup, self);
530
531 if (percpu_ref_is_zero(&desc->bpf.refcnt))
532 continue;
533
534 err = compute_effective_progs(desc, atype, &desc->bpf.inactive);
535 if (err)
536 goto cleanup;
537 }
538
539 /* all allocations were successful. Activate all prog arrays */
540 css_for_each_descendant_pre(css, &cgrp->self) {
541 struct cgroup *desc = container_of(css, struct cgroup, self);
542
543 if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
544 if (unlikely(desc->bpf.inactive)) {
545 bpf_prog_array_free(desc->bpf.inactive);
546 desc->bpf.inactive = NULL;
547 }
548 continue;
549 }
550
551 activate_effective_progs(desc, atype, desc->bpf.inactive);
552 desc->bpf.inactive = NULL;
553 }
554
555 return 0;
556
557cleanup:
558 /* oom while computing effective. Free all computed effective arrays
559 * since they were not activated
560 */
561 css_for_each_descendant_pre(css, &cgrp->self) {
562 struct cgroup *desc = container_of(css, struct cgroup, self);
563
564 bpf_prog_array_free(desc->bpf.inactive);
565 desc->bpf.inactive = NULL;
566 }
567
568 return err;
569}
570
571#define BPF_CGROUP_MAX_PROGS 64
572
573static struct bpf_prog_list *find_attach_entry(struct hlist_head *progs,
574 struct bpf_prog *prog,
575 struct bpf_cgroup_link *link,
576 struct bpf_prog *replace_prog,
577 bool allow_multi)
578{
579 struct bpf_prog_list *pl;
580
581 /* single-attach case */
582 if (!allow_multi) {
583 if (hlist_empty(progs))
584 return NULL;
585 return hlist_entry(progs->first, typeof(*pl), node);
586 }
587
588 hlist_for_each_entry(pl, progs, node) {
589 if (prog && pl->prog == prog && prog != replace_prog)
590 /* disallow attaching the same prog twice */
591 return ERR_PTR(-EINVAL);
592 if (link && pl->link == link)
593 /* disallow attaching the same link twice */
594 return ERR_PTR(-EINVAL);
595 }
596
597 /* direct prog multi-attach w/ replacement case */
598 if (replace_prog) {
599 hlist_for_each_entry(pl, progs, node) {
600 if (pl->prog == replace_prog)
601 /* a match found */
602 return pl;
603 }
604 /* prog to replace not found for cgroup */
605 return ERR_PTR(-ENOENT);
606 }
607
608 return NULL;
609}
610
611/**
612 * __cgroup_bpf_attach() - Attach the program or the link to a cgroup, and
613 * propagate the change to descendants
614 * @cgrp: The cgroup which descendants to traverse
615 * @prog: A program to attach
616 * @link: A link to attach
617 * @replace_prog: Previously attached program to replace if BPF_F_REPLACE is set
618 * @type: Type of attach operation
619 * @flags: Option flags
620 *
621 * Exactly one of @prog or @link can be non-null.
622 * Must be called with cgroup_mutex held.
623 */
624static int __cgroup_bpf_attach(struct cgroup *cgrp,
625 struct bpf_prog *prog, struct bpf_prog *replace_prog,
626 struct bpf_cgroup_link *link,
627 enum bpf_attach_type type, u32 flags)
628{
629 u32 saved_flags = (flags & (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI));
630 struct bpf_prog *old_prog = NULL;
631 struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
632 struct bpf_cgroup_storage *new_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
633 struct bpf_prog *new_prog = prog ? : link->link.prog;
634 enum cgroup_bpf_attach_type atype;
635 struct bpf_prog_list *pl;
636 struct hlist_head *progs;
637 int err;
638
639 if (((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI)) ||
640 ((flags & BPF_F_REPLACE) && !(flags & BPF_F_ALLOW_MULTI)))
641 /* invalid combination */
642 return -EINVAL;
643 if (link && (prog || replace_prog))
644 /* only either link or prog/replace_prog can be specified */
645 return -EINVAL;
646 if (!!replace_prog != !!(flags & BPF_F_REPLACE))
647 /* replace_prog implies BPF_F_REPLACE, and vice versa */
648 return -EINVAL;
649
650 atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id);
651 if (atype < 0)
652 return -EINVAL;
653
654 progs = &cgrp->bpf.progs[atype];
655
656 if (!hierarchy_allows_attach(cgrp, atype))
657 return -EPERM;
658
659 if (!hlist_empty(progs) && cgrp->bpf.flags[atype] != saved_flags)
660 /* Disallow attaching non-overridable on top
661 * of existing overridable in this cgroup.
662 * Disallow attaching multi-prog if overridable or none
663 */
664 return -EPERM;
665
666 if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
667 return -E2BIG;
668
669 pl = find_attach_entry(progs, prog, link, replace_prog,
670 flags & BPF_F_ALLOW_MULTI);
671 if (IS_ERR(pl))
672 return PTR_ERR(pl);
673
674 if (bpf_cgroup_storages_alloc(storage, new_storage, type,
675 prog ? : link->link.prog, cgrp))
676 return -ENOMEM;
677
678 if (pl) {
679 old_prog = pl->prog;
680 } else {
681 struct hlist_node *last = NULL;
682
683 pl = kmalloc(sizeof(*pl), GFP_KERNEL);
684 if (!pl) {
685 bpf_cgroup_storages_free(new_storage);
686 return -ENOMEM;
687 }
688 if (hlist_empty(progs))
689 hlist_add_head(&pl->node, progs);
690 else
691 hlist_for_each(last, progs) {
692 if (last->next)
693 continue;
694 hlist_add_behind(&pl->node, last);
695 break;
696 }
697 }
698
699 pl->prog = prog;
700 pl->link = link;
701 bpf_cgroup_storages_assign(pl->storage, storage);
702 cgrp->bpf.flags[atype] = saved_flags;
703
704 if (type == BPF_LSM_CGROUP) {
705 err = bpf_trampoline_link_cgroup_shim(new_prog, atype);
706 if (err)
707 goto cleanup;
708 }
709
710 err = update_effective_progs(cgrp, atype);
711 if (err)
712 goto cleanup_trampoline;
713
714 if (old_prog) {
715 if (type == BPF_LSM_CGROUP)
716 bpf_trampoline_unlink_cgroup_shim(old_prog);
717 bpf_prog_put(old_prog);
718 } else {
719 static_branch_inc(&cgroup_bpf_enabled_key[atype]);
720 }
721 bpf_cgroup_storages_link(new_storage, cgrp, type);
722 return 0;
723
724cleanup_trampoline:
725 if (type == BPF_LSM_CGROUP)
726 bpf_trampoline_unlink_cgroup_shim(new_prog);
727
728cleanup:
729 if (old_prog) {
730 pl->prog = old_prog;
731 pl->link = NULL;
732 }
733 bpf_cgroup_storages_free(new_storage);
734 if (!old_prog) {
735 hlist_del(&pl->node);
736 kfree(pl);
737 }
738 return err;
739}
740
741static int cgroup_bpf_attach(struct cgroup *cgrp,
742 struct bpf_prog *prog, struct bpf_prog *replace_prog,
743 struct bpf_cgroup_link *link,
744 enum bpf_attach_type type,
745 u32 flags)
746{
747 int ret;
748
749 cgroup_lock();
750 ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags);
751 cgroup_unlock();
752 return ret;
753}
754
755/* Swap updated BPF program for given link in effective program arrays across
756 * all descendant cgroups. This function is guaranteed to succeed.
757 */
758static void replace_effective_prog(struct cgroup *cgrp,
759 enum cgroup_bpf_attach_type atype,
760 struct bpf_cgroup_link *link)
761{
762 struct bpf_prog_array_item *item;
763 struct cgroup_subsys_state *css;
764 struct bpf_prog_array *progs;
765 struct bpf_prog_list *pl;
766 struct hlist_head *head;
767 struct cgroup *cg;
768 int pos;
769
770 css_for_each_descendant_pre(css, &cgrp->self) {
771 struct cgroup *desc = container_of(css, struct cgroup, self);
772
773 if (percpu_ref_is_zero(&desc->bpf.refcnt))
774 continue;
775
776 /* find position of link in effective progs array */
777 for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
778 if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
779 continue;
780
781 head = &cg->bpf.progs[atype];
782 hlist_for_each_entry(pl, head, node) {
783 if (!prog_list_prog(pl))
784 continue;
785 if (pl->link == link)
786 goto found;
787 pos++;
788 }
789 }
790found:
791 BUG_ON(!cg);
792 progs = rcu_dereference_protected(
793 desc->bpf.effective[atype],
794 lockdep_is_held(&cgroup_mutex));
795 item = &progs->items[pos];
796 WRITE_ONCE(item->prog, link->link.prog);
797 }
798}
799
800/**
801 * __cgroup_bpf_replace() - Replace link's program and propagate the change
802 * to descendants
803 * @cgrp: The cgroup which descendants to traverse
804 * @link: A link for which to replace BPF program
805 * @new_prog: &struct bpf_prog for the target BPF program with its refcnt
806 * incremented
807 *
808 * Must be called with cgroup_mutex held.
809 */
810static int __cgroup_bpf_replace(struct cgroup *cgrp,
811 struct bpf_cgroup_link *link,
812 struct bpf_prog *new_prog)
813{
814 enum cgroup_bpf_attach_type atype;
815 struct bpf_prog *old_prog;
816 struct bpf_prog_list *pl;
817 struct hlist_head *progs;
818 bool found = false;
819
820 atype = bpf_cgroup_atype_find(link->type, new_prog->aux->attach_btf_id);
821 if (atype < 0)
822 return -EINVAL;
823
824 progs = &cgrp->bpf.progs[atype];
825
826 if (link->link.prog->type != new_prog->type)
827 return -EINVAL;
828
829 hlist_for_each_entry(pl, progs, node) {
830 if (pl->link == link) {
831 found = true;
832 break;
833 }
834 }
835 if (!found)
836 return -ENOENT;
837
838 old_prog = xchg(&link->link.prog, new_prog);
839 replace_effective_prog(cgrp, atype, link);
840 bpf_prog_put(old_prog);
841 return 0;
842}
843
844static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog,
845 struct bpf_prog *old_prog)
846{
847 struct bpf_cgroup_link *cg_link;
848 int ret;
849
850 cg_link = container_of(link, struct bpf_cgroup_link, link);
851
852 cgroup_lock();
853 /* link might have been auto-released by dying cgroup, so fail */
854 if (!cg_link->cgroup) {
855 ret = -ENOLINK;
856 goto out_unlock;
857 }
858 if (old_prog && link->prog != old_prog) {
859 ret = -EPERM;
860 goto out_unlock;
861 }
862 ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog);
863out_unlock:
864 cgroup_unlock();
865 return ret;
866}
867
868static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs,
869 struct bpf_prog *prog,
870 struct bpf_cgroup_link *link,
871 bool allow_multi)
872{
873 struct bpf_prog_list *pl;
874
875 if (!allow_multi) {
876 if (hlist_empty(progs))
877 /* report error when trying to detach and nothing is attached */
878 return ERR_PTR(-ENOENT);
879
880 /* to maintain backward compatibility NONE and OVERRIDE cgroups
881 * allow detaching with invalid FD (prog==NULL) in legacy mode
882 */
883 return hlist_entry(progs->first, typeof(*pl), node);
884 }
885
886 if (!prog && !link)
887 /* to detach MULTI prog the user has to specify valid FD
888 * of the program or link to be detached
889 */
890 return ERR_PTR(-EINVAL);
891
892 /* find the prog or link and detach it */
893 hlist_for_each_entry(pl, progs, node) {
894 if (pl->prog == prog && pl->link == link)
895 return pl;
896 }
897 return ERR_PTR(-ENOENT);
898}
899
900/**
901 * purge_effective_progs() - After compute_effective_progs fails to alloc new
902 * cgrp->bpf.inactive table we can recover by
903 * recomputing the array in place.
904 *
905 * @cgrp: The cgroup which descendants to travers
906 * @prog: A program to detach or NULL
907 * @link: A link to detach or NULL
908 * @atype: Type of detach operation
909 */
910static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog *prog,
911 struct bpf_cgroup_link *link,
912 enum cgroup_bpf_attach_type atype)
913{
914 struct cgroup_subsys_state *css;
915 struct bpf_prog_array *progs;
916 struct bpf_prog_list *pl;
917 struct hlist_head *head;
918 struct cgroup *cg;
919 int pos;
920
921 /* recompute effective prog array in place */
922 css_for_each_descendant_pre(css, &cgrp->self) {
923 struct cgroup *desc = container_of(css, struct cgroup, self);
924
925 if (percpu_ref_is_zero(&desc->bpf.refcnt))
926 continue;
927
928 /* find position of link or prog in effective progs array */
929 for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
930 if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
931 continue;
932
933 head = &cg->bpf.progs[atype];
934 hlist_for_each_entry(pl, head, node) {
935 if (!prog_list_prog(pl))
936 continue;
937 if (pl->prog == prog && pl->link == link)
938 goto found;
939 pos++;
940 }
941 }
942
943 /* no link or prog match, skip the cgroup of this layer */
944 continue;
945found:
946 progs = rcu_dereference_protected(
947 desc->bpf.effective[atype],
948 lockdep_is_held(&cgroup_mutex));
949
950 /* Remove the program from the array */
951 WARN_ONCE(bpf_prog_array_delete_safe_at(progs, pos),
952 "Failed to purge a prog from array at index %d", pos);
953 }
954}
955
956/**
957 * __cgroup_bpf_detach() - Detach the program or link from a cgroup, and
958 * propagate the change to descendants
959 * @cgrp: The cgroup which descendants to traverse
960 * @prog: A program to detach or NULL
961 * @link: A link to detach or NULL
962 * @type: Type of detach operation
963 *
964 * At most one of @prog or @link can be non-NULL.
965 * Must be called with cgroup_mutex held.
966 */
967static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
968 struct bpf_cgroup_link *link, enum bpf_attach_type type)
969{
970 enum cgroup_bpf_attach_type atype;
971 struct bpf_prog *old_prog;
972 struct bpf_prog_list *pl;
973 struct hlist_head *progs;
974 u32 attach_btf_id = 0;
975 u32 flags;
976
977 if (prog)
978 attach_btf_id = prog->aux->attach_btf_id;
979 if (link)
980 attach_btf_id = link->link.prog->aux->attach_btf_id;
981
982 atype = bpf_cgroup_atype_find(type, attach_btf_id);
983 if (atype < 0)
984 return -EINVAL;
985
986 progs = &cgrp->bpf.progs[atype];
987 flags = cgrp->bpf.flags[atype];
988
989 if (prog && link)
990 /* only one of prog or link can be specified */
991 return -EINVAL;
992
993 pl = find_detach_entry(progs, prog, link, flags & BPF_F_ALLOW_MULTI);
994 if (IS_ERR(pl))
995 return PTR_ERR(pl);
996
997 /* mark it deleted, so it's ignored while recomputing effective */
998 old_prog = pl->prog;
999 pl->prog = NULL;
1000 pl->link = NULL;
1001
1002 if (update_effective_progs(cgrp, atype)) {
1003 /* if update effective array failed replace the prog with a dummy prog*/
1004 pl->prog = old_prog;
1005 pl->link = link;
1006 purge_effective_progs(cgrp, old_prog, link, atype);
1007 }
1008
1009 /* now can actually delete it from this cgroup list */
1010 hlist_del(&pl->node);
1011
1012 kfree(pl);
1013 if (hlist_empty(progs))
1014 /* last program was detached, reset flags to zero */
1015 cgrp->bpf.flags[atype] = 0;
1016 if (old_prog) {
1017 if (type == BPF_LSM_CGROUP)
1018 bpf_trampoline_unlink_cgroup_shim(old_prog);
1019 bpf_prog_put(old_prog);
1020 }
1021 static_branch_dec(&cgroup_bpf_enabled_key[atype]);
1022 return 0;
1023}
1024
1025static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
1026 enum bpf_attach_type type)
1027{
1028 int ret;
1029
1030 cgroup_lock();
1031 ret = __cgroup_bpf_detach(cgrp, prog, NULL, type);
1032 cgroup_unlock();
1033 return ret;
1034}
1035
1036/* Must be called with cgroup_mutex held to avoid races. */
1037static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1038 union bpf_attr __user *uattr)
1039{
1040 __u32 __user *prog_attach_flags = u64_to_user_ptr(attr->query.prog_attach_flags);
1041 bool effective_query = attr->query.query_flags & BPF_F_QUERY_EFFECTIVE;
1042 __u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
1043 enum bpf_attach_type type = attr->query.attach_type;
1044 enum cgroup_bpf_attach_type from_atype, to_atype;
1045 enum cgroup_bpf_attach_type atype;
1046 struct bpf_prog_array *effective;
1047 int cnt, ret = 0, i;
1048 int total_cnt = 0;
1049 u32 flags;
1050
1051 if (effective_query && prog_attach_flags)
1052 return -EINVAL;
1053
1054 if (type == BPF_LSM_CGROUP) {
1055 if (!effective_query && attr->query.prog_cnt &&
1056 prog_ids && !prog_attach_flags)
1057 return -EINVAL;
1058
1059 from_atype = CGROUP_LSM_START;
1060 to_atype = CGROUP_LSM_END;
1061 flags = 0;
1062 } else {
1063 from_atype = to_cgroup_bpf_attach_type(type);
1064 if (from_atype < 0)
1065 return -EINVAL;
1066 to_atype = from_atype;
1067 flags = cgrp->bpf.flags[from_atype];
1068 }
1069
1070 for (atype = from_atype; atype <= to_atype; atype++) {
1071 if (effective_query) {
1072 effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1073 lockdep_is_held(&cgroup_mutex));
1074 total_cnt += bpf_prog_array_length(effective);
1075 } else {
1076 total_cnt += prog_list_length(&cgrp->bpf.progs[atype]);
1077 }
1078 }
1079
1080 /* always output uattr->query.attach_flags as 0 during effective query */
1081 flags = effective_query ? 0 : flags;
1082 if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
1083 return -EFAULT;
1084 if (copy_to_user(&uattr->query.prog_cnt, &total_cnt, sizeof(total_cnt)))
1085 return -EFAULT;
1086 if (attr->query.prog_cnt == 0 || !prog_ids || !total_cnt)
1087 /* return early if user requested only program count + flags */
1088 return 0;
1089
1090 if (attr->query.prog_cnt < total_cnt) {
1091 total_cnt = attr->query.prog_cnt;
1092 ret = -ENOSPC;
1093 }
1094
1095 for (atype = from_atype; atype <= to_atype && total_cnt; atype++) {
1096 if (effective_query) {
1097 effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1098 lockdep_is_held(&cgroup_mutex));
1099 cnt = min_t(int, bpf_prog_array_length(effective), total_cnt);
1100 ret = bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
1101 } else {
1102 struct hlist_head *progs;
1103 struct bpf_prog_list *pl;
1104 struct bpf_prog *prog;
1105 u32 id;
1106
1107 progs = &cgrp->bpf.progs[atype];
1108 cnt = min_t(int, prog_list_length(progs), total_cnt);
1109 i = 0;
1110 hlist_for_each_entry(pl, progs, node) {
1111 prog = prog_list_prog(pl);
1112 id = prog->aux->id;
1113 if (copy_to_user(prog_ids + i, &id, sizeof(id)))
1114 return -EFAULT;
1115 if (++i == cnt)
1116 break;
1117 }
1118
1119 if (prog_attach_flags) {
1120 flags = cgrp->bpf.flags[atype];
1121
1122 for (i = 0; i < cnt; i++)
1123 if (copy_to_user(prog_attach_flags + i,
1124 &flags, sizeof(flags)))
1125 return -EFAULT;
1126 prog_attach_flags += cnt;
1127 }
1128 }
1129
1130 prog_ids += cnt;
1131 total_cnt -= cnt;
1132 }
1133 return ret;
1134}
1135
1136static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1137 union bpf_attr __user *uattr)
1138{
1139 int ret;
1140
1141 cgroup_lock();
1142 ret = __cgroup_bpf_query(cgrp, attr, uattr);
1143 cgroup_unlock();
1144 return ret;
1145}
1146
1147int cgroup_bpf_prog_attach(const union bpf_attr *attr,
1148 enum bpf_prog_type ptype, struct bpf_prog *prog)
1149{
1150 struct bpf_prog *replace_prog = NULL;
1151 struct cgroup *cgrp;
1152 int ret;
1153
1154 cgrp = cgroup_get_from_fd(attr->target_fd);
1155 if (IS_ERR(cgrp))
1156 return PTR_ERR(cgrp);
1157
1158 if ((attr->attach_flags & BPF_F_ALLOW_MULTI) &&
1159 (attr->attach_flags & BPF_F_REPLACE)) {
1160 replace_prog = bpf_prog_get_type(attr->replace_bpf_fd, ptype);
1161 if (IS_ERR(replace_prog)) {
1162 cgroup_put(cgrp);
1163 return PTR_ERR(replace_prog);
1164 }
1165 }
1166
1167 ret = cgroup_bpf_attach(cgrp, prog, replace_prog, NULL,
1168 attr->attach_type, attr->attach_flags);
1169
1170 if (replace_prog)
1171 bpf_prog_put(replace_prog);
1172 cgroup_put(cgrp);
1173 return ret;
1174}
1175
1176int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
1177{
1178 struct bpf_prog *prog;
1179 struct cgroup *cgrp;
1180 int ret;
1181
1182 cgrp = cgroup_get_from_fd(attr->target_fd);
1183 if (IS_ERR(cgrp))
1184 return PTR_ERR(cgrp);
1185
1186 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
1187 if (IS_ERR(prog))
1188 prog = NULL;
1189
1190 ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type);
1191 if (prog)
1192 bpf_prog_put(prog);
1193
1194 cgroup_put(cgrp);
1195 return ret;
1196}
1197
1198static void bpf_cgroup_link_release(struct bpf_link *link)
1199{
1200 struct bpf_cgroup_link *cg_link =
1201 container_of(link, struct bpf_cgroup_link, link);
1202 struct cgroup *cg;
1203
1204 /* link might have been auto-detached by dying cgroup already,
1205 * in that case our work is done here
1206 */
1207 if (!cg_link->cgroup)
1208 return;
1209
1210 cgroup_lock();
1211
1212 /* re-check cgroup under lock again */
1213 if (!cg_link->cgroup) {
1214 cgroup_unlock();
1215 return;
1216 }
1217
1218 WARN_ON(__cgroup_bpf_detach(cg_link->cgroup, NULL, cg_link,
1219 cg_link->type));
1220 if (cg_link->type == BPF_LSM_CGROUP)
1221 bpf_trampoline_unlink_cgroup_shim(cg_link->link.prog);
1222
1223 cg = cg_link->cgroup;
1224 cg_link->cgroup = NULL;
1225
1226 cgroup_unlock();
1227
1228 cgroup_put(cg);
1229}
1230
1231static void bpf_cgroup_link_dealloc(struct bpf_link *link)
1232{
1233 struct bpf_cgroup_link *cg_link =
1234 container_of(link, struct bpf_cgroup_link, link);
1235
1236 kfree(cg_link);
1237}
1238
1239static int bpf_cgroup_link_detach(struct bpf_link *link)
1240{
1241 bpf_cgroup_link_release(link);
1242
1243 return 0;
1244}
1245
1246static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link,
1247 struct seq_file *seq)
1248{
1249 struct bpf_cgroup_link *cg_link =
1250 container_of(link, struct bpf_cgroup_link, link);
1251 u64 cg_id = 0;
1252
1253 cgroup_lock();
1254 if (cg_link->cgroup)
1255 cg_id = cgroup_id(cg_link->cgroup);
1256 cgroup_unlock();
1257
1258 seq_printf(seq,
1259 "cgroup_id:\t%llu\n"
1260 "attach_type:\t%d\n",
1261 cg_id,
1262 cg_link->type);
1263}
1264
1265static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link,
1266 struct bpf_link_info *info)
1267{
1268 struct bpf_cgroup_link *cg_link =
1269 container_of(link, struct bpf_cgroup_link, link);
1270 u64 cg_id = 0;
1271
1272 cgroup_lock();
1273 if (cg_link->cgroup)
1274 cg_id = cgroup_id(cg_link->cgroup);
1275 cgroup_unlock();
1276
1277 info->cgroup.cgroup_id = cg_id;
1278 info->cgroup.attach_type = cg_link->type;
1279 return 0;
1280}
1281
1282static const struct bpf_link_ops bpf_cgroup_link_lops = {
1283 .release = bpf_cgroup_link_release,
1284 .dealloc = bpf_cgroup_link_dealloc,
1285 .detach = bpf_cgroup_link_detach,
1286 .update_prog = cgroup_bpf_replace,
1287 .show_fdinfo = bpf_cgroup_link_show_fdinfo,
1288 .fill_link_info = bpf_cgroup_link_fill_link_info,
1289};
1290
1291int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
1292{
1293 struct bpf_link_primer link_primer;
1294 struct bpf_cgroup_link *link;
1295 struct cgroup *cgrp;
1296 int err;
1297
1298 if (attr->link_create.flags)
1299 return -EINVAL;
1300
1301 cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
1302 if (IS_ERR(cgrp))
1303 return PTR_ERR(cgrp);
1304
1305 link = kzalloc(sizeof(*link), GFP_USER);
1306 if (!link) {
1307 err = -ENOMEM;
1308 goto out_put_cgroup;
1309 }
1310 bpf_link_init(&link->link, BPF_LINK_TYPE_CGROUP, &bpf_cgroup_link_lops,
1311 prog);
1312 link->cgroup = cgrp;
1313 link->type = attr->link_create.attach_type;
1314
1315 err = bpf_link_prime(&link->link, &link_primer);
1316 if (err) {
1317 kfree(link);
1318 goto out_put_cgroup;
1319 }
1320
1321 err = cgroup_bpf_attach(cgrp, NULL, NULL, link,
1322 link->type, BPF_F_ALLOW_MULTI);
1323 if (err) {
1324 bpf_link_cleanup(&link_primer);
1325 goto out_put_cgroup;
1326 }
1327
1328 return bpf_link_settle(&link_primer);
1329
1330out_put_cgroup:
1331 cgroup_put(cgrp);
1332 return err;
1333}
1334
1335int cgroup_bpf_prog_query(const union bpf_attr *attr,
1336 union bpf_attr __user *uattr)
1337{
1338 struct cgroup *cgrp;
1339 int ret;
1340
1341 cgrp = cgroup_get_from_fd(attr->query.target_fd);
1342 if (IS_ERR(cgrp))
1343 return PTR_ERR(cgrp);
1344
1345 ret = cgroup_bpf_query(cgrp, attr, uattr);
1346
1347 cgroup_put(cgrp);
1348 return ret;
1349}
1350
1351/**
1352 * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
1353 * @sk: The socket sending or receiving traffic
1354 * @skb: The skb that is being sent or received
1355 * @atype: The type of program to be executed
1356 *
1357 * If no socket is passed, or the socket is not of type INET or INET6,
1358 * this function does nothing and returns 0.
1359 *
1360 * The program type passed in via @type must be suitable for network
1361 * filtering. No further check is performed to assert that.
1362 *
1363 * For egress packets, this function can return:
1364 * NET_XMIT_SUCCESS (0) - continue with packet output
1365 * NET_XMIT_DROP (1) - drop packet and notify TCP to call cwr
1366 * NET_XMIT_CN (2) - continue with packet output and notify TCP
1367 * to call cwr
1368 * -err - drop packet
1369 *
1370 * For ingress packets, this function will return -EPERM if any
1371 * attached program was found and if it returned != 1 during execution.
1372 * Otherwise 0 is returned.
1373 */
1374int __cgroup_bpf_run_filter_skb(struct sock *sk,
1375 struct sk_buff *skb,
1376 enum cgroup_bpf_attach_type atype)
1377{
1378 unsigned int offset = -skb_network_offset(skb);
1379 struct sock *save_sk;
1380 void *saved_data_end;
1381 struct cgroup *cgrp;
1382 int ret;
1383
1384 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1385 return 0;
1386
1387 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1388 save_sk = skb->sk;
1389 skb->sk = sk;
1390 __skb_push(skb, offset);
1391
1392 /* compute pointers for the bpf prog */
1393 bpf_compute_and_save_data_end(skb, &saved_data_end);
1394
1395 if (atype == CGROUP_INET_EGRESS) {
1396 u32 flags = 0;
1397 bool cn;
1398
1399 ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, skb,
1400 __bpf_prog_run_save_cb, 0, &flags);
1401
1402 /* Return values of CGROUP EGRESS BPF programs are:
1403 * 0: drop packet
1404 * 1: keep packet
1405 * 2: drop packet and cn
1406 * 3: keep packet and cn
1407 *
1408 * The returned value is then converted to one of the NET_XMIT
1409 * or an error code that is then interpreted as drop packet
1410 * (and no cn):
1411 * 0: NET_XMIT_SUCCESS skb should be transmitted
1412 * 1: NET_XMIT_DROP skb should be dropped and cn
1413 * 2: NET_XMIT_CN skb should be transmitted and cn
1414 * 3: -err skb should be dropped
1415 */
1416
1417 cn = flags & BPF_RET_SET_CN;
1418 if (ret && !IS_ERR_VALUE((long)ret))
1419 ret = -EFAULT;
1420 if (!ret)
1421 ret = (cn ? NET_XMIT_CN : NET_XMIT_SUCCESS);
1422 else
1423 ret = (cn ? NET_XMIT_DROP : ret);
1424 } else {
1425 ret = bpf_prog_run_array_cg(&cgrp->bpf, atype,
1426 skb, __bpf_prog_run_save_cb, 0,
1427 NULL);
1428 if (ret && !IS_ERR_VALUE((long)ret))
1429 ret = -EFAULT;
1430 }
1431 bpf_restore_data_end(skb, saved_data_end);
1432 __skb_pull(skb, offset);
1433 skb->sk = save_sk;
1434
1435 return ret;
1436}
1437EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
1438
1439/**
1440 * __cgroup_bpf_run_filter_sk() - Run a program on a sock
1441 * @sk: sock structure to manipulate
1442 * @atype: The type of program to be executed
1443 *
1444 * socket is passed is expected to be of type INET or INET6.
1445 *
1446 * The program type passed in via @type must be suitable for sock
1447 * filtering. No further check is performed to assert that.
1448 *
1449 * This function will return %-EPERM if any if an attached program was found
1450 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1451 */
1452int __cgroup_bpf_run_filter_sk(struct sock *sk,
1453 enum cgroup_bpf_attach_type atype)
1454{
1455 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1456
1457 return bpf_prog_run_array_cg(&cgrp->bpf, atype, sk, bpf_prog_run, 0,
1458 NULL);
1459}
1460EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
1461
1462/**
1463 * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
1464 * provided by user sockaddr
1465 * @sk: sock struct that will use sockaddr
1466 * @uaddr: sockaddr struct provided by user
1467 * @uaddrlen: Pointer to the size of the sockaddr struct provided by user. It is
1468 * read-only for AF_INET[6] uaddr but can be modified for AF_UNIX
1469 * uaddr.
1470 * @atype: The type of program to be executed
1471 * @t_ctx: Pointer to attach type specific context
1472 * @flags: Pointer to u32 which contains higher bits of BPF program
1473 * return value (OR'ed together).
1474 *
1475 * socket is expected to be of type INET, INET6 or UNIX.
1476 *
1477 * This function will return %-EPERM if an attached program is found and
1478 * returned value != 1 during execution. In all other cases, 0 is returned.
1479 */
1480int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
1481 struct sockaddr *uaddr,
1482 int *uaddrlen,
1483 enum cgroup_bpf_attach_type atype,
1484 void *t_ctx,
1485 u32 *flags)
1486{
1487 struct bpf_sock_addr_kern ctx = {
1488 .sk = sk,
1489 .uaddr = uaddr,
1490 .t_ctx = t_ctx,
1491 };
1492 struct sockaddr_storage unspec;
1493 struct cgroup *cgrp;
1494 int ret;
1495
1496 /* Check socket family since not all sockets represent network
1497 * endpoint (e.g. AF_UNIX).
1498 */
1499 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6 &&
1500 sk->sk_family != AF_UNIX)
1501 return 0;
1502
1503 if (!ctx.uaddr) {
1504 memset(&unspec, 0, sizeof(unspec));
1505 ctx.uaddr = (struct sockaddr *)&unspec;
1506 ctx.uaddrlen = 0;
1507 } else {
1508 ctx.uaddrlen = *uaddrlen;
1509 }
1510
1511 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1512 ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run,
1513 0, flags);
1514
1515 if (!ret && uaddr)
1516 *uaddrlen = ctx.uaddrlen;
1517
1518 return ret;
1519}
1520EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
1521
1522/**
1523 * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
1524 * @sk: socket to get cgroup from
1525 * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
1526 * sk with connection information (IP addresses, etc.) May not contain
1527 * cgroup info if it is a req sock.
1528 * @atype: The type of program to be executed
1529 *
1530 * socket passed is expected to be of type INET or INET6.
1531 *
1532 * The program type passed in via @type must be suitable for sock_ops
1533 * filtering. No further check is performed to assert that.
1534 *
1535 * This function will return %-EPERM if any if an attached program was found
1536 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1537 */
1538int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
1539 struct bpf_sock_ops_kern *sock_ops,
1540 enum cgroup_bpf_attach_type atype)
1541{
1542 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1543
1544 return bpf_prog_run_array_cg(&cgrp->bpf, atype, sock_ops, bpf_prog_run,
1545 0, NULL);
1546}
1547EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
1548
1549int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
1550 short access, enum cgroup_bpf_attach_type atype)
1551{
1552 struct cgroup *cgrp;
1553 struct bpf_cgroup_dev_ctx ctx = {
1554 .access_type = (access << 16) | dev_type,
1555 .major = major,
1556 .minor = minor,
1557 };
1558 int ret;
1559
1560 rcu_read_lock();
1561 cgrp = task_dfl_cgroup(current);
1562 ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1563 NULL);
1564 rcu_read_unlock();
1565
1566 return ret;
1567}
1568
1569BPF_CALL_2(bpf_get_local_storage, struct bpf_map *, map, u64, flags)
1570{
1571 /* flags argument is not used now,
1572 * but provides an ability to extend the API.
1573 * verifier checks that its value is correct.
1574 */
1575 enum bpf_cgroup_storage_type stype = cgroup_storage_type(map);
1576 struct bpf_cgroup_storage *storage;
1577 struct bpf_cg_run_ctx *ctx;
1578 void *ptr;
1579
1580 /* get current cgroup storage from BPF run context */
1581 ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1582 storage = ctx->prog_item->cgroup_storage[stype];
1583
1584 if (stype == BPF_CGROUP_STORAGE_SHARED)
1585 ptr = &READ_ONCE(storage->buf)->data[0];
1586 else
1587 ptr = this_cpu_ptr(storage->percpu_buf);
1588
1589 return (unsigned long)ptr;
1590}
1591
1592const struct bpf_func_proto bpf_get_local_storage_proto = {
1593 .func = bpf_get_local_storage,
1594 .gpl_only = false,
1595 .ret_type = RET_PTR_TO_MAP_VALUE,
1596 .arg1_type = ARG_CONST_MAP_PTR,
1597 .arg2_type = ARG_ANYTHING,
1598};
1599
1600BPF_CALL_0(bpf_get_retval)
1601{
1602 struct bpf_cg_run_ctx *ctx =
1603 container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1604
1605 return ctx->retval;
1606}
1607
1608const struct bpf_func_proto bpf_get_retval_proto = {
1609 .func = bpf_get_retval,
1610 .gpl_only = false,
1611 .ret_type = RET_INTEGER,
1612};
1613
1614BPF_CALL_1(bpf_set_retval, int, retval)
1615{
1616 struct bpf_cg_run_ctx *ctx =
1617 container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1618
1619 ctx->retval = retval;
1620 return 0;
1621}
1622
1623const struct bpf_func_proto bpf_set_retval_proto = {
1624 .func = bpf_set_retval,
1625 .gpl_only = false,
1626 .ret_type = RET_INTEGER,
1627 .arg1_type = ARG_ANYTHING,
1628};
1629
1630static const struct bpf_func_proto *
1631cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1632{
1633 const struct bpf_func_proto *func_proto;
1634
1635 func_proto = cgroup_common_func_proto(func_id, prog);
1636 if (func_proto)
1637 return func_proto;
1638
1639 func_proto = cgroup_current_func_proto(func_id, prog);
1640 if (func_proto)
1641 return func_proto;
1642
1643 switch (func_id) {
1644 case BPF_FUNC_perf_event_output:
1645 return &bpf_event_output_data_proto;
1646 default:
1647 return bpf_base_func_proto(func_id, prog);
1648 }
1649}
1650
1651static bool cgroup_dev_is_valid_access(int off, int size,
1652 enum bpf_access_type type,
1653 const struct bpf_prog *prog,
1654 struct bpf_insn_access_aux *info)
1655{
1656 const int size_default = sizeof(__u32);
1657
1658 if (type == BPF_WRITE)
1659 return false;
1660
1661 if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
1662 return false;
1663 /* The verifier guarantees that size > 0. */
1664 if (off % size != 0)
1665 return false;
1666
1667 switch (off) {
1668 case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
1669 bpf_ctx_record_field_size(info, size_default);
1670 if (!bpf_ctx_narrow_access_ok(off, size, size_default))
1671 return false;
1672 break;
1673 default:
1674 if (size != size_default)
1675 return false;
1676 }
1677
1678 return true;
1679}
1680
1681const struct bpf_prog_ops cg_dev_prog_ops = {
1682};
1683
1684const struct bpf_verifier_ops cg_dev_verifier_ops = {
1685 .get_func_proto = cgroup_dev_func_proto,
1686 .is_valid_access = cgroup_dev_is_valid_access,
1687};
1688
1689/**
1690 * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
1691 *
1692 * @head: sysctl table header
1693 * @table: sysctl table
1694 * @write: sysctl is being read (= 0) or written (= 1)
1695 * @buf: pointer to buffer (in and out)
1696 * @pcount: value-result argument: value is size of buffer pointed to by @buf,
1697 * result is size of @new_buf if program set new value, initial value
1698 * otherwise
1699 * @ppos: value-result argument: value is position at which read from or write
1700 * to sysctl is happening, result is new position if program overrode it,
1701 * initial value otherwise
1702 * @atype: type of program to be executed
1703 *
1704 * Program is run when sysctl is being accessed, either read or written, and
1705 * can allow or deny such access.
1706 *
1707 * This function will return %-EPERM if an attached program is found and
1708 * returned value != 1 during execution. In all other cases 0 is returned.
1709 */
1710int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
1711 const struct ctl_table *table, int write,
1712 char **buf, size_t *pcount, loff_t *ppos,
1713 enum cgroup_bpf_attach_type atype)
1714{
1715 struct bpf_sysctl_kern ctx = {
1716 .head = head,
1717 .table = table,
1718 .write = write,
1719 .ppos = ppos,
1720 .cur_val = NULL,
1721 .cur_len = PAGE_SIZE,
1722 .new_val = NULL,
1723 .new_len = 0,
1724 .new_updated = 0,
1725 };
1726 struct cgroup *cgrp;
1727 loff_t pos = 0;
1728 int ret;
1729
1730 ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
1731 if (!ctx.cur_val ||
1732 table->proc_handler(table, 0, ctx.cur_val, &ctx.cur_len, &pos)) {
1733 /* Let BPF program decide how to proceed. */
1734 ctx.cur_len = 0;
1735 }
1736
1737 if (write && *buf && *pcount) {
1738 /* BPF program should be able to override new value with a
1739 * buffer bigger than provided by user.
1740 */
1741 ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
1742 ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
1743 if (ctx.new_val) {
1744 memcpy(ctx.new_val, *buf, ctx.new_len);
1745 } else {
1746 /* Let BPF program decide how to proceed. */
1747 ctx.new_len = 0;
1748 }
1749 }
1750
1751 rcu_read_lock();
1752 cgrp = task_dfl_cgroup(current);
1753 ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1754 NULL);
1755 rcu_read_unlock();
1756
1757 kfree(ctx.cur_val);
1758
1759 if (ret == 1 && ctx.new_updated) {
1760 kfree(*buf);
1761 *buf = ctx.new_val;
1762 *pcount = ctx.new_len;
1763 } else {
1764 kfree(ctx.new_val);
1765 }
1766
1767 return ret;
1768}
1769
1770#ifdef CONFIG_NET
1771static int sockopt_alloc_buf(struct bpf_sockopt_kern *ctx, int max_optlen,
1772 struct bpf_sockopt_buf *buf)
1773{
1774 if (unlikely(max_optlen < 0))
1775 return -EINVAL;
1776
1777 if (unlikely(max_optlen > PAGE_SIZE)) {
1778 /* We don't expose optvals that are greater than PAGE_SIZE
1779 * to the BPF program.
1780 */
1781 max_optlen = PAGE_SIZE;
1782 }
1783
1784 if (max_optlen <= sizeof(buf->data)) {
1785 /* When the optval fits into BPF_SOCKOPT_KERN_BUF_SIZE
1786 * bytes avoid the cost of kzalloc.
1787 */
1788 ctx->optval = buf->data;
1789 ctx->optval_end = ctx->optval + max_optlen;
1790 return max_optlen;
1791 }
1792
1793 ctx->optval = kzalloc(max_optlen, GFP_USER);
1794 if (!ctx->optval)
1795 return -ENOMEM;
1796
1797 ctx->optval_end = ctx->optval + max_optlen;
1798
1799 return max_optlen;
1800}
1801
1802static void sockopt_free_buf(struct bpf_sockopt_kern *ctx,
1803 struct bpf_sockopt_buf *buf)
1804{
1805 if (ctx->optval == buf->data)
1806 return;
1807 kfree(ctx->optval);
1808}
1809
1810static bool sockopt_buf_allocated(struct bpf_sockopt_kern *ctx,
1811 struct bpf_sockopt_buf *buf)
1812{
1813 return ctx->optval != buf->data;
1814}
1815
1816int __cgroup_bpf_run_filter_setsockopt(struct sock *sk, int *level,
1817 int *optname, sockptr_t optval,
1818 int *optlen, char **kernel_optval)
1819{
1820 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1821 struct bpf_sockopt_buf buf = {};
1822 struct bpf_sockopt_kern ctx = {
1823 .sk = sk,
1824 .level = *level,
1825 .optname = *optname,
1826 };
1827 int ret, max_optlen;
1828
1829 /* Allocate a bit more than the initial user buffer for
1830 * BPF program. The canonical use case is overriding
1831 * TCP_CONGESTION(nv) to TCP_CONGESTION(cubic).
1832 */
1833 max_optlen = max_t(int, 16, *optlen);
1834 max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1835 if (max_optlen < 0)
1836 return max_optlen;
1837
1838 ctx.optlen = *optlen;
1839
1840 if (copy_from_sockptr(ctx.optval, optval,
1841 min(*optlen, max_optlen))) {
1842 ret = -EFAULT;
1843 goto out;
1844 }
1845
1846 lock_sock(sk);
1847 ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_SETSOCKOPT,
1848 &ctx, bpf_prog_run, 0, NULL);
1849 release_sock(sk);
1850
1851 if (ret)
1852 goto out;
1853
1854 if (ctx.optlen == -1) {
1855 /* optlen set to -1, bypass kernel */
1856 ret = 1;
1857 } else if (ctx.optlen > max_optlen || ctx.optlen < -1) {
1858 /* optlen is out of bounds */
1859 if (*optlen > PAGE_SIZE && ctx.optlen >= 0) {
1860 pr_info_once("bpf setsockopt: ignoring program buffer with optlen=%d (max_optlen=%d)\n",
1861 ctx.optlen, max_optlen);
1862 ret = 0;
1863 goto out;
1864 }
1865 ret = -EFAULT;
1866 } else {
1867 /* optlen within bounds, run kernel handler */
1868 ret = 0;
1869
1870 /* export any potential modifications */
1871 *level = ctx.level;
1872 *optname = ctx.optname;
1873
1874 /* optlen == 0 from BPF indicates that we should
1875 * use original userspace data.
1876 */
1877 if (ctx.optlen != 0) {
1878 *optlen = ctx.optlen;
1879 /* We've used bpf_sockopt_kern->buf as an intermediary
1880 * storage, but the BPF program indicates that we need
1881 * to pass this data to the kernel setsockopt handler.
1882 * No way to export on-stack buf, have to allocate a
1883 * new buffer.
1884 */
1885 if (!sockopt_buf_allocated(&ctx, &buf)) {
1886 void *p = kmalloc(ctx.optlen, GFP_USER);
1887
1888 if (!p) {
1889 ret = -ENOMEM;
1890 goto out;
1891 }
1892 memcpy(p, ctx.optval, ctx.optlen);
1893 *kernel_optval = p;
1894 } else {
1895 *kernel_optval = ctx.optval;
1896 }
1897 /* export and don't free sockopt buf */
1898 return 0;
1899 }
1900 }
1901
1902out:
1903 sockopt_free_buf(&ctx, &buf);
1904 return ret;
1905}
1906
1907int __cgroup_bpf_run_filter_getsockopt(struct sock *sk, int level,
1908 int optname, sockptr_t optval,
1909 sockptr_t optlen, int max_optlen,
1910 int retval)
1911{
1912 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1913 struct bpf_sockopt_buf buf = {};
1914 struct bpf_sockopt_kern ctx = {
1915 .sk = sk,
1916 .level = level,
1917 .optname = optname,
1918 .current_task = current,
1919 };
1920 int orig_optlen;
1921 int ret;
1922
1923 orig_optlen = max_optlen;
1924 ctx.optlen = max_optlen;
1925 max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1926 if (max_optlen < 0)
1927 return max_optlen;
1928
1929 if (!retval) {
1930 /* If kernel getsockopt finished successfully,
1931 * copy whatever was returned to the user back
1932 * into our temporary buffer. Set optlen to the
1933 * one that kernel returned as well to let
1934 * BPF programs inspect the value.
1935 */
1936 if (copy_from_sockptr(&ctx.optlen, optlen,
1937 sizeof(ctx.optlen))) {
1938 ret = -EFAULT;
1939 goto out;
1940 }
1941
1942 if (ctx.optlen < 0) {
1943 ret = -EFAULT;
1944 goto out;
1945 }
1946 orig_optlen = ctx.optlen;
1947
1948 if (copy_from_sockptr(ctx.optval, optval,
1949 min(ctx.optlen, max_optlen))) {
1950 ret = -EFAULT;
1951 goto out;
1952 }
1953 }
1954
1955 lock_sock(sk);
1956 ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1957 &ctx, bpf_prog_run, retval, NULL);
1958 release_sock(sk);
1959
1960 if (ret < 0)
1961 goto out;
1962
1963 if (!sockptr_is_null(optval) &&
1964 (ctx.optlen > max_optlen || ctx.optlen < 0)) {
1965 if (orig_optlen > PAGE_SIZE && ctx.optlen >= 0) {
1966 pr_info_once("bpf getsockopt: ignoring program buffer with optlen=%d (max_optlen=%d)\n",
1967 ctx.optlen, max_optlen);
1968 ret = retval;
1969 goto out;
1970 }
1971 ret = -EFAULT;
1972 goto out;
1973 }
1974
1975 if (ctx.optlen != 0) {
1976 if (!sockptr_is_null(optval) &&
1977 copy_to_sockptr(optval, ctx.optval, ctx.optlen)) {
1978 ret = -EFAULT;
1979 goto out;
1980 }
1981 if (copy_to_sockptr(optlen, &ctx.optlen, sizeof(ctx.optlen))) {
1982 ret = -EFAULT;
1983 goto out;
1984 }
1985 }
1986
1987out:
1988 sockopt_free_buf(&ctx, &buf);
1989 return ret;
1990}
1991
1992int __cgroup_bpf_run_filter_getsockopt_kern(struct sock *sk, int level,
1993 int optname, void *optval,
1994 int *optlen, int retval)
1995{
1996 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1997 struct bpf_sockopt_kern ctx = {
1998 .sk = sk,
1999 .level = level,
2000 .optname = optname,
2001 .optlen = *optlen,
2002 .optval = optval,
2003 .optval_end = optval + *optlen,
2004 .current_task = current,
2005 };
2006 int ret;
2007
2008 /* Note that __cgroup_bpf_run_filter_getsockopt doesn't copy
2009 * user data back into BPF buffer when reval != 0. This is
2010 * done as an optimization to avoid extra copy, assuming
2011 * kernel won't populate the data in case of an error.
2012 * Here we always pass the data and memset() should
2013 * be called if that data shouldn't be "exported".
2014 */
2015
2016 ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
2017 &ctx, bpf_prog_run, retval, NULL);
2018 if (ret < 0)
2019 return ret;
2020
2021 if (ctx.optlen > *optlen)
2022 return -EFAULT;
2023
2024 /* BPF programs can shrink the buffer, export the modifications.
2025 */
2026 if (ctx.optlen != 0)
2027 *optlen = ctx.optlen;
2028
2029 return ret;
2030}
2031#endif
2032
2033static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
2034 size_t *lenp)
2035{
2036 ssize_t tmp_ret = 0, ret;
2037
2038 if (dir->header.parent) {
2039 tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
2040 if (tmp_ret < 0)
2041 return tmp_ret;
2042 }
2043
2044 ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
2045 if (ret < 0)
2046 return ret;
2047 *bufp += ret;
2048 *lenp -= ret;
2049 ret += tmp_ret;
2050
2051 /* Avoid leading slash. */
2052 if (!ret)
2053 return ret;
2054
2055 tmp_ret = strscpy(*bufp, "/", *lenp);
2056 if (tmp_ret < 0)
2057 return tmp_ret;
2058 *bufp += tmp_ret;
2059 *lenp -= tmp_ret;
2060
2061 return ret + tmp_ret;
2062}
2063
2064BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
2065 size_t, buf_len, u64, flags)
2066{
2067 ssize_t tmp_ret = 0, ret;
2068
2069 if (!buf)
2070 return -EINVAL;
2071
2072 if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
2073 if (!ctx->head)
2074 return -EINVAL;
2075 tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
2076 if (tmp_ret < 0)
2077 return tmp_ret;
2078 }
2079
2080 ret = strscpy(buf, ctx->table->procname, buf_len);
2081
2082 return ret < 0 ? ret : tmp_ret + ret;
2083}
2084
2085static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
2086 .func = bpf_sysctl_get_name,
2087 .gpl_only = false,
2088 .ret_type = RET_INTEGER,
2089 .arg1_type = ARG_PTR_TO_CTX,
2090 .arg2_type = ARG_PTR_TO_MEM,
2091 .arg3_type = ARG_CONST_SIZE,
2092 .arg4_type = ARG_ANYTHING,
2093};
2094
2095static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
2096 size_t src_len)
2097{
2098 if (!dst)
2099 return -EINVAL;
2100
2101 if (!dst_len)
2102 return -E2BIG;
2103
2104 if (!src || !src_len) {
2105 memset(dst, 0, dst_len);
2106 return -EINVAL;
2107 }
2108
2109 memcpy(dst, src, min(dst_len, src_len));
2110
2111 if (dst_len > src_len) {
2112 memset(dst + src_len, '\0', dst_len - src_len);
2113 return src_len;
2114 }
2115
2116 dst[dst_len - 1] = '\0';
2117
2118 return -E2BIG;
2119}
2120
2121BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
2122 char *, buf, size_t, buf_len)
2123{
2124 return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
2125}
2126
2127static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
2128 .func = bpf_sysctl_get_current_value,
2129 .gpl_only = false,
2130 .ret_type = RET_INTEGER,
2131 .arg1_type = ARG_PTR_TO_CTX,
2132 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
2133 .arg3_type = ARG_CONST_SIZE,
2134};
2135
2136BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
2137 size_t, buf_len)
2138{
2139 if (!ctx->write) {
2140 if (buf && buf_len)
2141 memset(buf, '\0', buf_len);
2142 return -EINVAL;
2143 }
2144 return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
2145}
2146
2147static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
2148 .func = bpf_sysctl_get_new_value,
2149 .gpl_only = false,
2150 .ret_type = RET_INTEGER,
2151 .arg1_type = ARG_PTR_TO_CTX,
2152 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
2153 .arg3_type = ARG_CONST_SIZE,
2154};
2155
2156BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
2157 const char *, buf, size_t, buf_len)
2158{
2159 if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
2160 return -EINVAL;
2161
2162 if (buf_len > PAGE_SIZE - 1)
2163 return -E2BIG;
2164
2165 memcpy(ctx->new_val, buf, buf_len);
2166 ctx->new_len = buf_len;
2167 ctx->new_updated = 1;
2168
2169 return 0;
2170}
2171
2172static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
2173 .func = bpf_sysctl_set_new_value,
2174 .gpl_only = false,
2175 .ret_type = RET_INTEGER,
2176 .arg1_type = ARG_PTR_TO_CTX,
2177 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
2178 .arg3_type = ARG_CONST_SIZE,
2179};
2180
2181static const struct bpf_func_proto *
2182sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2183{
2184 const struct bpf_func_proto *func_proto;
2185
2186 func_proto = cgroup_common_func_proto(func_id, prog);
2187 if (func_proto)
2188 return func_proto;
2189
2190 func_proto = cgroup_current_func_proto(func_id, prog);
2191 if (func_proto)
2192 return func_proto;
2193
2194 switch (func_id) {
2195 case BPF_FUNC_sysctl_get_name:
2196 return &bpf_sysctl_get_name_proto;
2197 case BPF_FUNC_sysctl_get_current_value:
2198 return &bpf_sysctl_get_current_value_proto;
2199 case BPF_FUNC_sysctl_get_new_value:
2200 return &bpf_sysctl_get_new_value_proto;
2201 case BPF_FUNC_sysctl_set_new_value:
2202 return &bpf_sysctl_set_new_value_proto;
2203 case BPF_FUNC_ktime_get_coarse_ns:
2204 return &bpf_ktime_get_coarse_ns_proto;
2205 case BPF_FUNC_perf_event_output:
2206 return &bpf_event_output_data_proto;
2207 default:
2208 return bpf_base_func_proto(func_id, prog);
2209 }
2210}
2211
2212static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
2213 const struct bpf_prog *prog,
2214 struct bpf_insn_access_aux *info)
2215{
2216 const int size_default = sizeof(__u32);
2217
2218 if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
2219 return false;
2220
2221 switch (off) {
2222 case bpf_ctx_range(struct bpf_sysctl, write):
2223 if (type != BPF_READ)
2224 return false;
2225 bpf_ctx_record_field_size(info, size_default);
2226 return bpf_ctx_narrow_access_ok(off, size, size_default);
2227 case bpf_ctx_range(struct bpf_sysctl, file_pos):
2228 if (type == BPF_READ) {
2229 bpf_ctx_record_field_size(info, size_default);
2230 return bpf_ctx_narrow_access_ok(off, size, size_default);
2231 } else {
2232 return size == size_default;
2233 }
2234 default:
2235 return false;
2236 }
2237}
2238
2239static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
2240 const struct bpf_insn *si,
2241 struct bpf_insn *insn_buf,
2242 struct bpf_prog *prog, u32 *target_size)
2243{
2244 struct bpf_insn *insn = insn_buf;
2245 u32 read_size;
2246
2247 switch (si->off) {
2248 case offsetof(struct bpf_sysctl, write):
2249 *insn++ = BPF_LDX_MEM(
2250 BPF_SIZE(si->code), si->dst_reg, si->src_reg,
2251 bpf_target_off(struct bpf_sysctl_kern, write,
2252 sizeof_field(struct bpf_sysctl_kern,
2253 write),
2254 target_size));
2255 break;
2256 case offsetof(struct bpf_sysctl, file_pos):
2257 /* ppos is a pointer so it should be accessed via indirect
2258 * loads and stores. Also for stores additional temporary
2259 * register is used since neither src_reg nor dst_reg can be
2260 * overridden.
2261 */
2262 if (type == BPF_WRITE) {
2263 int treg = BPF_REG_9;
2264
2265 if (si->src_reg == treg || si->dst_reg == treg)
2266 --treg;
2267 if (si->src_reg == treg || si->dst_reg == treg)
2268 --treg;
2269 *insn++ = BPF_STX_MEM(
2270 BPF_DW, si->dst_reg, treg,
2271 offsetof(struct bpf_sysctl_kern, tmp_reg));
2272 *insn++ = BPF_LDX_MEM(
2273 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2274 treg, si->dst_reg,
2275 offsetof(struct bpf_sysctl_kern, ppos));
2276 *insn++ = BPF_RAW_INSN(
2277 BPF_CLASS(si->code) | BPF_MEM | BPF_SIZEOF(u32),
2278 treg, si->src_reg,
2279 bpf_ctx_narrow_access_offset(
2280 0, sizeof(u32), sizeof(loff_t)),
2281 si->imm);
2282 *insn++ = BPF_LDX_MEM(
2283 BPF_DW, treg, si->dst_reg,
2284 offsetof(struct bpf_sysctl_kern, tmp_reg));
2285 } else {
2286 *insn++ = BPF_LDX_MEM(
2287 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2288 si->dst_reg, si->src_reg,
2289 offsetof(struct bpf_sysctl_kern, ppos));
2290 read_size = bpf_size_to_bytes(BPF_SIZE(si->code));
2291 *insn++ = BPF_LDX_MEM(
2292 BPF_SIZE(si->code), si->dst_reg, si->dst_reg,
2293 bpf_ctx_narrow_access_offset(
2294 0, read_size, sizeof(loff_t)));
2295 }
2296 *target_size = sizeof(u32);
2297 break;
2298 }
2299
2300 return insn - insn_buf;
2301}
2302
2303const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
2304 .get_func_proto = sysctl_func_proto,
2305 .is_valid_access = sysctl_is_valid_access,
2306 .convert_ctx_access = sysctl_convert_ctx_access,
2307};
2308
2309const struct bpf_prog_ops cg_sysctl_prog_ops = {
2310};
2311
2312#ifdef CONFIG_NET
2313BPF_CALL_1(bpf_get_netns_cookie_sockopt, struct bpf_sockopt_kern *, ctx)
2314{
2315 const struct net *net = ctx ? sock_net(ctx->sk) : &init_net;
2316
2317 return net->net_cookie;
2318}
2319
2320static const struct bpf_func_proto bpf_get_netns_cookie_sockopt_proto = {
2321 .func = bpf_get_netns_cookie_sockopt,
2322 .gpl_only = false,
2323 .ret_type = RET_INTEGER,
2324 .arg1_type = ARG_PTR_TO_CTX_OR_NULL,
2325};
2326#endif
2327
2328static const struct bpf_func_proto *
2329cg_sockopt_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2330{
2331 const struct bpf_func_proto *func_proto;
2332
2333 func_proto = cgroup_common_func_proto(func_id, prog);
2334 if (func_proto)
2335 return func_proto;
2336
2337 func_proto = cgroup_current_func_proto(func_id, prog);
2338 if (func_proto)
2339 return func_proto;
2340
2341 switch (func_id) {
2342#ifdef CONFIG_NET
2343 case BPF_FUNC_get_netns_cookie:
2344 return &bpf_get_netns_cookie_sockopt_proto;
2345 case BPF_FUNC_sk_storage_get:
2346 return &bpf_sk_storage_get_proto;
2347 case BPF_FUNC_sk_storage_delete:
2348 return &bpf_sk_storage_delete_proto;
2349 case BPF_FUNC_setsockopt:
2350 if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2351 return &bpf_sk_setsockopt_proto;
2352 return NULL;
2353 case BPF_FUNC_getsockopt:
2354 if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2355 return &bpf_sk_getsockopt_proto;
2356 return NULL;
2357#endif
2358#ifdef CONFIG_INET
2359 case BPF_FUNC_tcp_sock:
2360 return &bpf_tcp_sock_proto;
2361#endif
2362 case BPF_FUNC_perf_event_output:
2363 return &bpf_event_output_data_proto;
2364 default:
2365 return bpf_base_func_proto(func_id, prog);
2366 }
2367}
2368
2369static bool cg_sockopt_is_valid_access(int off, int size,
2370 enum bpf_access_type type,
2371 const struct bpf_prog *prog,
2372 struct bpf_insn_access_aux *info)
2373{
2374 const int size_default = sizeof(__u32);
2375
2376 if (off < 0 || off >= sizeof(struct bpf_sockopt))
2377 return false;
2378
2379 if (off % size != 0)
2380 return false;
2381
2382 if (type == BPF_WRITE) {
2383 switch (off) {
2384 case offsetof(struct bpf_sockopt, retval):
2385 if (size != size_default)
2386 return false;
2387 return prog->expected_attach_type ==
2388 BPF_CGROUP_GETSOCKOPT;
2389 case offsetof(struct bpf_sockopt, optname):
2390 fallthrough;
2391 case offsetof(struct bpf_sockopt, level):
2392 if (size != size_default)
2393 return false;
2394 return prog->expected_attach_type ==
2395 BPF_CGROUP_SETSOCKOPT;
2396 case offsetof(struct bpf_sockopt, optlen):
2397 return size == size_default;
2398 default:
2399 return false;
2400 }
2401 }
2402
2403 switch (off) {
2404 case offsetof(struct bpf_sockopt, sk):
2405 if (size != sizeof(__u64))
2406 return false;
2407 info->reg_type = PTR_TO_SOCKET;
2408 break;
2409 case offsetof(struct bpf_sockopt, optval):
2410 if (size != sizeof(__u64))
2411 return false;
2412 info->reg_type = PTR_TO_PACKET;
2413 break;
2414 case offsetof(struct bpf_sockopt, optval_end):
2415 if (size != sizeof(__u64))
2416 return false;
2417 info->reg_type = PTR_TO_PACKET_END;
2418 break;
2419 case offsetof(struct bpf_sockopt, retval):
2420 if (size != size_default)
2421 return false;
2422 return prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT;
2423 default:
2424 if (size != size_default)
2425 return false;
2426 break;
2427 }
2428 return true;
2429}
2430
2431#define CG_SOCKOPT_READ_FIELD(F) \
2432 BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F), \
2433 si->dst_reg, si->src_reg, \
2434 offsetof(struct bpf_sockopt_kern, F))
2435
2436#define CG_SOCKOPT_WRITE_FIELD(F) \
2437 BPF_RAW_INSN((BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F) | \
2438 BPF_MEM | BPF_CLASS(si->code)), \
2439 si->dst_reg, si->src_reg, \
2440 offsetof(struct bpf_sockopt_kern, F), \
2441 si->imm)
2442
2443static u32 cg_sockopt_convert_ctx_access(enum bpf_access_type type,
2444 const struct bpf_insn *si,
2445 struct bpf_insn *insn_buf,
2446 struct bpf_prog *prog,
2447 u32 *target_size)
2448{
2449 struct bpf_insn *insn = insn_buf;
2450
2451 switch (si->off) {
2452 case offsetof(struct bpf_sockopt, sk):
2453 *insn++ = CG_SOCKOPT_READ_FIELD(sk);
2454 break;
2455 case offsetof(struct bpf_sockopt, level):
2456 if (type == BPF_WRITE)
2457 *insn++ = CG_SOCKOPT_WRITE_FIELD(level);
2458 else
2459 *insn++ = CG_SOCKOPT_READ_FIELD(level);
2460 break;
2461 case offsetof(struct bpf_sockopt, optname):
2462 if (type == BPF_WRITE)
2463 *insn++ = CG_SOCKOPT_WRITE_FIELD(optname);
2464 else
2465 *insn++ = CG_SOCKOPT_READ_FIELD(optname);
2466 break;
2467 case offsetof(struct bpf_sockopt, optlen):
2468 if (type == BPF_WRITE)
2469 *insn++ = CG_SOCKOPT_WRITE_FIELD(optlen);
2470 else
2471 *insn++ = CG_SOCKOPT_READ_FIELD(optlen);
2472 break;
2473 case offsetof(struct bpf_sockopt, retval):
2474 BUILD_BUG_ON(offsetof(struct bpf_cg_run_ctx, run_ctx) != 0);
2475
2476 if (type == BPF_WRITE) {
2477 int treg = BPF_REG_9;
2478
2479 if (si->src_reg == treg || si->dst_reg == treg)
2480 --treg;
2481 if (si->src_reg == treg || si->dst_reg == treg)
2482 --treg;
2483 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, treg,
2484 offsetof(struct bpf_sockopt_kern, tmp_reg));
2485 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2486 treg, si->dst_reg,
2487 offsetof(struct bpf_sockopt_kern, current_task));
2488 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2489 treg, treg,
2490 offsetof(struct task_struct, bpf_ctx));
2491 *insn++ = BPF_RAW_INSN(BPF_CLASS(si->code) | BPF_MEM |
2492 BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2493 treg, si->src_reg,
2494 offsetof(struct bpf_cg_run_ctx, retval),
2495 si->imm);
2496 *insn++ = BPF_LDX_MEM(BPF_DW, treg, si->dst_reg,
2497 offsetof(struct bpf_sockopt_kern, tmp_reg));
2498 } else {
2499 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2500 si->dst_reg, si->src_reg,
2501 offsetof(struct bpf_sockopt_kern, current_task));
2502 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2503 si->dst_reg, si->dst_reg,
2504 offsetof(struct task_struct, bpf_ctx));
2505 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2506 si->dst_reg, si->dst_reg,
2507 offsetof(struct bpf_cg_run_ctx, retval));
2508 }
2509 break;
2510 case offsetof(struct bpf_sockopt, optval):
2511 *insn++ = CG_SOCKOPT_READ_FIELD(optval);
2512 break;
2513 case offsetof(struct bpf_sockopt, optval_end):
2514 *insn++ = CG_SOCKOPT_READ_FIELD(optval_end);
2515 break;
2516 }
2517
2518 return insn - insn_buf;
2519}
2520
2521static int cg_sockopt_get_prologue(struct bpf_insn *insn_buf,
2522 bool direct_write,
2523 const struct bpf_prog *prog)
2524{
2525 /* Nothing to do for sockopt argument. The data is kzalloc'ated.
2526 */
2527 return 0;
2528}
2529
2530const struct bpf_verifier_ops cg_sockopt_verifier_ops = {
2531 .get_func_proto = cg_sockopt_func_proto,
2532 .is_valid_access = cg_sockopt_is_valid_access,
2533 .convert_ctx_access = cg_sockopt_convert_ctx_access,
2534 .gen_prologue = cg_sockopt_get_prologue,
2535};
2536
2537const struct bpf_prog_ops cg_sockopt_prog_ops = {
2538};
2539
2540/* Common helpers for cgroup hooks. */
2541const struct bpf_func_proto *
2542cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2543{
2544 switch (func_id) {
2545 case BPF_FUNC_get_local_storage:
2546 return &bpf_get_local_storage_proto;
2547 case BPF_FUNC_get_retval:
2548 switch (prog->expected_attach_type) {
2549 case BPF_CGROUP_INET_INGRESS:
2550 case BPF_CGROUP_INET_EGRESS:
2551 case BPF_CGROUP_SOCK_OPS:
2552 case BPF_CGROUP_UDP4_RECVMSG:
2553 case BPF_CGROUP_UDP6_RECVMSG:
2554 case BPF_CGROUP_UNIX_RECVMSG:
2555 case BPF_CGROUP_INET4_GETPEERNAME:
2556 case BPF_CGROUP_INET6_GETPEERNAME:
2557 case BPF_CGROUP_UNIX_GETPEERNAME:
2558 case BPF_CGROUP_INET4_GETSOCKNAME:
2559 case BPF_CGROUP_INET6_GETSOCKNAME:
2560 case BPF_CGROUP_UNIX_GETSOCKNAME:
2561 return NULL;
2562 default:
2563 return &bpf_get_retval_proto;
2564 }
2565 case BPF_FUNC_set_retval:
2566 switch (prog->expected_attach_type) {
2567 case BPF_CGROUP_INET_INGRESS:
2568 case BPF_CGROUP_INET_EGRESS:
2569 case BPF_CGROUP_SOCK_OPS:
2570 case BPF_CGROUP_UDP4_RECVMSG:
2571 case BPF_CGROUP_UDP6_RECVMSG:
2572 case BPF_CGROUP_UNIX_RECVMSG:
2573 case BPF_CGROUP_INET4_GETPEERNAME:
2574 case BPF_CGROUP_INET6_GETPEERNAME:
2575 case BPF_CGROUP_UNIX_GETPEERNAME:
2576 case BPF_CGROUP_INET4_GETSOCKNAME:
2577 case BPF_CGROUP_INET6_GETSOCKNAME:
2578 case BPF_CGROUP_UNIX_GETSOCKNAME:
2579 return NULL;
2580 default:
2581 return &bpf_set_retval_proto;
2582 }
2583 default:
2584 return NULL;
2585 }
2586}
2587
2588/* Common helpers for cgroup hooks with valid process context. */
2589const struct bpf_func_proto *
2590cgroup_current_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2591{
2592 switch (func_id) {
2593 case BPF_FUNC_get_current_uid_gid:
2594 return &bpf_get_current_uid_gid_proto;
2595 case BPF_FUNC_get_current_comm:
2596 return &bpf_get_current_comm_proto;
2597#ifdef CONFIG_CGROUP_NET_CLASSID
2598 case BPF_FUNC_get_cgroup_classid:
2599 return &bpf_get_cgroup_classid_curr_proto;
2600#endif
2601 case BPF_FUNC_current_task_under_cgroup:
2602 return &bpf_current_task_under_cgroup_proto;
2603 default:
2604 return NULL;
2605 }
2606}
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#include <net/bpf_sk_storage.h>
19
20#include "../cgroup/cgroup-internal.h"
21
22DEFINE_STATIC_KEY_FALSE(cgroup_bpf_enabled_key);
23EXPORT_SYMBOL(cgroup_bpf_enabled_key);
24
25void cgroup_bpf_offline(struct cgroup *cgrp)
26{
27 cgroup_get(cgrp);
28 percpu_ref_kill(&cgrp->bpf.refcnt);
29}
30
31static void bpf_cgroup_storages_free(struct bpf_cgroup_storage *storages[])
32{
33 enum bpf_cgroup_storage_type stype;
34
35 for_each_cgroup_storage_type(stype)
36 bpf_cgroup_storage_free(storages[stype]);
37}
38
39static int bpf_cgroup_storages_alloc(struct bpf_cgroup_storage *storages[],
40 struct bpf_cgroup_storage *new_storages[],
41 enum bpf_attach_type type,
42 struct bpf_prog *prog,
43 struct cgroup *cgrp)
44{
45 enum bpf_cgroup_storage_type stype;
46 struct bpf_cgroup_storage_key key;
47 struct bpf_map *map;
48
49 key.cgroup_inode_id = cgroup_id(cgrp);
50 key.attach_type = type;
51
52 for_each_cgroup_storage_type(stype) {
53 map = prog->aux->cgroup_storage[stype];
54 if (!map)
55 continue;
56
57 storages[stype] = cgroup_storage_lookup((void *)map, &key, false);
58 if (storages[stype])
59 continue;
60
61 storages[stype] = bpf_cgroup_storage_alloc(prog, stype);
62 if (IS_ERR(storages[stype])) {
63 bpf_cgroup_storages_free(new_storages);
64 return -ENOMEM;
65 }
66
67 new_storages[stype] = storages[stype];
68 }
69
70 return 0;
71}
72
73static void bpf_cgroup_storages_assign(struct bpf_cgroup_storage *dst[],
74 struct bpf_cgroup_storage *src[])
75{
76 enum bpf_cgroup_storage_type stype;
77
78 for_each_cgroup_storage_type(stype)
79 dst[stype] = src[stype];
80}
81
82static void bpf_cgroup_storages_link(struct bpf_cgroup_storage *storages[],
83 struct cgroup *cgrp,
84 enum bpf_attach_type attach_type)
85{
86 enum bpf_cgroup_storage_type stype;
87
88 for_each_cgroup_storage_type(stype)
89 bpf_cgroup_storage_link(storages[stype], cgrp, attach_type);
90}
91
92/* Called when bpf_cgroup_link is auto-detached from dying cgroup.
93 * It drops cgroup and bpf_prog refcounts, and marks bpf_link as defunct. It
94 * doesn't free link memory, which will eventually be done by bpf_link's
95 * release() callback, when its last FD is closed.
96 */
97static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)
98{
99 cgroup_put(link->cgroup);
100 link->cgroup = NULL;
101}
102
103/**
104 * cgroup_bpf_release() - put references of all bpf programs and
105 * release all cgroup bpf data
106 * @work: work structure embedded into the cgroup to modify
107 */
108static void cgroup_bpf_release(struct work_struct *work)
109{
110 struct cgroup *p, *cgrp = container_of(work, struct cgroup,
111 bpf.release_work);
112 struct bpf_prog_array *old_array;
113 struct list_head *storages = &cgrp->bpf.storages;
114 struct bpf_cgroup_storage *storage, *stmp;
115
116 unsigned int type;
117
118 mutex_lock(&cgroup_mutex);
119
120 for (type = 0; type < ARRAY_SIZE(cgrp->bpf.progs); type++) {
121 struct list_head *progs = &cgrp->bpf.progs[type];
122 struct bpf_prog_list *pl, *pltmp;
123
124 list_for_each_entry_safe(pl, pltmp, progs, node) {
125 list_del(&pl->node);
126 if (pl->prog)
127 bpf_prog_put(pl->prog);
128 if (pl->link)
129 bpf_cgroup_link_auto_detach(pl->link);
130 kfree(pl);
131 static_branch_dec(&cgroup_bpf_enabled_key);
132 }
133 old_array = rcu_dereference_protected(
134 cgrp->bpf.effective[type],
135 lockdep_is_held(&cgroup_mutex));
136 bpf_prog_array_free(old_array);
137 }
138
139 list_for_each_entry_safe(storage, stmp, storages, list_cg) {
140 bpf_cgroup_storage_unlink(storage);
141 bpf_cgroup_storage_free(storage);
142 }
143
144 mutex_unlock(&cgroup_mutex);
145
146 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
147 cgroup_bpf_put(p);
148
149 percpu_ref_exit(&cgrp->bpf.refcnt);
150 cgroup_put(cgrp);
151}
152
153/**
154 * cgroup_bpf_release_fn() - callback used to schedule releasing
155 * of bpf cgroup data
156 * @ref: percpu ref counter structure
157 */
158static void cgroup_bpf_release_fn(struct percpu_ref *ref)
159{
160 struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
161
162 INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
163 queue_work(system_wq, &cgrp->bpf.release_work);
164}
165
166/* Get underlying bpf_prog of bpf_prog_list entry, regardless if it's through
167 * link or direct prog.
168 */
169static struct bpf_prog *prog_list_prog(struct bpf_prog_list *pl)
170{
171 if (pl->prog)
172 return pl->prog;
173 if (pl->link)
174 return pl->link->link.prog;
175 return NULL;
176}
177
178/* count number of elements in the list.
179 * it's slow but the list cannot be long
180 */
181static u32 prog_list_length(struct list_head *head)
182{
183 struct bpf_prog_list *pl;
184 u32 cnt = 0;
185
186 list_for_each_entry(pl, head, node) {
187 if (!prog_list_prog(pl))
188 continue;
189 cnt++;
190 }
191 return cnt;
192}
193
194/* if parent has non-overridable prog attached,
195 * disallow attaching new programs to the descendent cgroup.
196 * if parent has overridable or multi-prog, allow attaching
197 */
198static bool hierarchy_allows_attach(struct cgroup *cgrp,
199 enum bpf_attach_type type)
200{
201 struct cgroup *p;
202
203 p = cgroup_parent(cgrp);
204 if (!p)
205 return true;
206 do {
207 u32 flags = p->bpf.flags[type];
208 u32 cnt;
209
210 if (flags & BPF_F_ALLOW_MULTI)
211 return true;
212 cnt = prog_list_length(&p->bpf.progs[type]);
213 WARN_ON_ONCE(cnt > 1);
214 if (cnt == 1)
215 return !!(flags & BPF_F_ALLOW_OVERRIDE);
216 p = cgroup_parent(p);
217 } while (p);
218 return true;
219}
220
221/* compute a chain of effective programs for a given cgroup:
222 * start from the list of programs in this cgroup and add
223 * all parent programs.
224 * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
225 * to programs in this cgroup
226 */
227static int compute_effective_progs(struct cgroup *cgrp,
228 enum bpf_attach_type type,
229 struct bpf_prog_array **array)
230{
231 struct bpf_prog_array_item *item;
232 struct bpf_prog_array *progs;
233 struct bpf_prog_list *pl;
234 struct cgroup *p = cgrp;
235 int cnt = 0;
236
237 /* count number of effective programs by walking parents */
238 do {
239 if (cnt == 0 || (p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
240 cnt += prog_list_length(&p->bpf.progs[type]);
241 p = cgroup_parent(p);
242 } while (p);
243
244 progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
245 if (!progs)
246 return -ENOMEM;
247
248 /* populate the array with effective progs */
249 cnt = 0;
250 p = cgrp;
251 do {
252 if (cnt > 0 && !(p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
253 continue;
254
255 list_for_each_entry(pl, &p->bpf.progs[type], node) {
256 if (!prog_list_prog(pl))
257 continue;
258
259 item = &progs->items[cnt];
260 item->prog = prog_list_prog(pl);
261 bpf_cgroup_storages_assign(item->cgroup_storage,
262 pl->storage);
263 cnt++;
264 }
265 } while ((p = cgroup_parent(p)));
266
267 *array = progs;
268 return 0;
269}
270
271static void activate_effective_progs(struct cgroup *cgrp,
272 enum bpf_attach_type type,
273 struct bpf_prog_array *old_array)
274{
275 old_array = rcu_replace_pointer(cgrp->bpf.effective[type], old_array,
276 lockdep_is_held(&cgroup_mutex));
277 /* free prog array after grace period, since __cgroup_bpf_run_*()
278 * might be still walking the array
279 */
280 bpf_prog_array_free(old_array);
281}
282
283/**
284 * cgroup_bpf_inherit() - inherit effective programs from parent
285 * @cgrp: the cgroup to modify
286 */
287int cgroup_bpf_inherit(struct cgroup *cgrp)
288{
289/* has to use marco instead of const int, since compiler thinks
290 * that array below is variable length
291 */
292#define NR ARRAY_SIZE(cgrp->bpf.effective)
293 struct bpf_prog_array *arrays[NR] = {};
294 struct cgroup *p;
295 int ret, i;
296
297 ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
298 GFP_KERNEL);
299 if (ret)
300 return ret;
301
302 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
303 cgroup_bpf_get(p);
304
305 for (i = 0; i < NR; i++)
306 INIT_LIST_HEAD(&cgrp->bpf.progs[i]);
307
308 INIT_LIST_HEAD(&cgrp->bpf.storages);
309
310 for (i = 0; i < NR; i++)
311 if (compute_effective_progs(cgrp, i, &arrays[i]))
312 goto cleanup;
313
314 for (i = 0; i < NR; i++)
315 activate_effective_progs(cgrp, i, arrays[i]);
316
317 return 0;
318cleanup:
319 for (i = 0; i < NR; i++)
320 bpf_prog_array_free(arrays[i]);
321
322 for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
323 cgroup_bpf_put(p);
324
325 percpu_ref_exit(&cgrp->bpf.refcnt);
326
327 return -ENOMEM;
328}
329
330static int update_effective_progs(struct cgroup *cgrp,
331 enum bpf_attach_type type)
332{
333 struct cgroup_subsys_state *css;
334 int err;
335
336 /* allocate and recompute effective prog arrays */
337 css_for_each_descendant_pre(css, &cgrp->self) {
338 struct cgroup *desc = container_of(css, struct cgroup, self);
339
340 if (percpu_ref_is_zero(&desc->bpf.refcnt))
341 continue;
342
343 err = compute_effective_progs(desc, type, &desc->bpf.inactive);
344 if (err)
345 goto cleanup;
346 }
347
348 /* all allocations were successful. Activate all prog arrays */
349 css_for_each_descendant_pre(css, &cgrp->self) {
350 struct cgroup *desc = container_of(css, struct cgroup, self);
351
352 if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
353 if (unlikely(desc->bpf.inactive)) {
354 bpf_prog_array_free(desc->bpf.inactive);
355 desc->bpf.inactive = NULL;
356 }
357 continue;
358 }
359
360 activate_effective_progs(desc, type, desc->bpf.inactive);
361 desc->bpf.inactive = NULL;
362 }
363
364 return 0;
365
366cleanup:
367 /* oom while computing effective. Free all computed effective arrays
368 * since they were not activated
369 */
370 css_for_each_descendant_pre(css, &cgrp->self) {
371 struct cgroup *desc = container_of(css, struct cgroup, self);
372
373 bpf_prog_array_free(desc->bpf.inactive);
374 desc->bpf.inactive = NULL;
375 }
376
377 return err;
378}
379
380#define BPF_CGROUP_MAX_PROGS 64
381
382static struct bpf_prog_list *find_attach_entry(struct list_head *progs,
383 struct bpf_prog *prog,
384 struct bpf_cgroup_link *link,
385 struct bpf_prog *replace_prog,
386 bool allow_multi)
387{
388 struct bpf_prog_list *pl;
389
390 /* single-attach case */
391 if (!allow_multi) {
392 if (list_empty(progs))
393 return NULL;
394 return list_first_entry(progs, typeof(*pl), node);
395 }
396
397 list_for_each_entry(pl, progs, node) {
398 if (prog && pl->prog == prog && prog != replace_prog)
399 /* disallow attaching the same prog twice */
400 return ERR_PTR(-EINVAL);
401 if (link && pl->link == link)
402 /* disallow attaching the same link twice */
403 return ERR_PTR(-EINVAL);
404 }
405
406 /* direct prog multi-attach w/ replacement case */
407 if (replace_prog) {
408 list_for_each_entry(pl, progs, node) {
409 if (pl->prog == replace_prog)
410 /* a match found */
411 return pl;
412 }
413 /* prog to replace not found for cgroup */
414 return ERR_PTR(-ENOENT);
415 }
416
417 return NULL;
418}
419
420/**
421 * __cgroup_bpf_attach() - Attach the program or the link to a cgroup, and
422 * propagate the change to descendants
423 * @cgrp: The cgroup which descendants to traverse
424 * @prog: A program to attach
425 * @link: A link to attach
426 * @replace_prog: Previously attached program to replace if BPF_F_REPLACE is set
427 * @type: Type of attach operation
428 * @flags: Option flags
429 *
430 * Exactly one of @prog or @link can be non-null.
431 * Must be called with cgroup_mutex held.
432 */
433int __cgroup_bpf_attach(struct cgroup *cgrp,
434 struct bpf_prog *prog, struct bpf_prog *replace_prog,
435 struct bpf_cgroup_link *link,
436 enum bpf_attach_type type, u32 flags)
437{
438 u32 saved_flags = (flags & (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI));
439 struct list_head *progs = &cgrp->bpf.progs[type];
440 struct bpf_prog *old_prog = NULL;
441 struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
442 struct bpf_cgroup_storage *new_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
443 struct bpf_prog_list *pl;
444 int err;
445
446 if (((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI)) ||
447 ((flags & BPF_F_REPLACE) && !(flags & BPF_F_ALLOW_MULTI)))
448 /* invalid combination */
449 return -EINVAL;
450 if (link && (prog || replace_prog))
451 /* only either link or prog/replace_prog can be specified */
452 return -EINVAL;
453 if (!!replace_prog != !!(flags & BPF_F_REPLACE))
454 /* replace_prog implies BPF_F_REPLACE, and vice versa */
455 return -EINVAL;
456
457 if (!hierarchy_allows_attach(cgrp, type))
458 return -EPERM;
459
460 if (!list_empty(progs) && cgrp->bpf.flags[type] != saved_flags)
461 /* Disallow attaching non-overridable on top
462 * of existing overridable in this cgroup.
463 * Disallow attaching multi-prog if overridable or none
464 */
465 return -EPERM;
466
467 if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
468 return -E2BIG;
469
470 pl = find_attach_entry(progs, prog, link, replace_prog,
471 flags & BPF_F_ALLOW_MULTI);
472 if (IS_ERR(pl))
473 return PTR_ERR(pl);
474
475 if (bpf_cgroup_storages_alloc(storage, new_storage, type,
476 prog ? : link->link.prog, cgrp))
477 return -ENOMEM;
478
479 if (pl) {
480 old_prog = pl->prog;
481 } else {
482 pl = kmalloc(sizeof(*pl), GFP_KERNEL);
483 if (!pl) {
484 bpf_cgroup_storages_free(new_storage);
485 return -ENOMEM;
486 }
487 list_add_tail(&pl->node, progs);
488 }
489
490 pl->prog = prog;
491 pl->link = link;
492 bpf_cgroup_storages_assign(pl->storage, storage);
493 cgrp->bpf.flags[type] = saved_flags;
494
495 err = update_effective_progs(cgrp, type);
496 if (err)
497 goto cleanup;
498
499 if (old_prog)
500 bpf_prog_put(old_prog);
501 else
502 static_branch_inc(&cgroup_bpf_enabled_key);
503 bpf_cgroup_storages_link(new_storage, cgrp, type);
504 return 0;
505
506cleanup:
507 if (old_prog) {
508 pl->prog = old_prog;
509 pl->link = NULL;
510 }
511 bpf_cgroup_storages_free(new_storage);
512 if (!old_prog) {
513 list_del(&pl->node);
514 kfree(pl);
515 }
516 return err;
517}
518
519/* Swap updated BPF program for given link in effective program arrays across
520 * all descendant cgroups. This function is guaranteed to succeed.
521 */
522static void replace_effective_prog(struct cgroup *cgrp,
523 enum bpf_attach_type type,
524 struct bpf_cgroup_link *link)
525{
526 struct bpf_prog_array_item *item;
527 struct cgroup_subsys_state *css;
528 struct bpf_prog_array *progs;
529 struct bpf_prog_list *pl;
530 struct list_head *head;
531 struct cgroup *cg;
532 int pos;
533
534 css_for_each_descendant_pre(css, &cgrp->self) {
535 struct cgroup *desc = container_of(css, struct cgroup, self);
536
537 if (percpu_ref_is_zero(&desc->bpf.refcnt))
538 continue;
539
540 /* find position of link in effective progs array */
541 for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
542 if (pos && !(cg->bpf.flags[type] & BPF_F_ALLOW_MULTI))
543 continue;
544
545 head = &cg->bpf.progs[type];
546 list_for_each_entry(pl, head, node) {
547 if (!prog_list_prog(pl))
548 continue;
549 if (pl->link == link)
550 goto found;
551 pos++;
552 }
553 }
554found:
555 BUG_ON(!cg);
556 progs = rcu_dereference_protected(
557 desc->bpf.effective[type],
558 lockdep_is_held(&cgroup_mutex));
559 item = &progs->items[pos];
560 WRITE_ONCE(item->prog, link->link.prog);
561 }
562}
563
564/**
565 * __cgroup_bpf_replace() - Replace link's program and propagate the change
566 * to descendants
567 * @cgrp: The cgroup which descendants to traverse
568 * @link: A link for which to replace BPF program
569 * @type: Type of attach operation
570 *
571 * Must be called with cgroup_mutex held.
572 */
573static int __cgroup_bpf_replace(struct cgroup *cgrp,
574 struct bpf_cgroup_link *link,
575 struct bpf_prog *new_prog)
576{
577 struct list_head *progs = &cgrp->bpf.progs[link->type];
578 struct bpf_prog *old_prog;
579 struct bpf_prog_list *pl;
580 bool found = false;
581
582 if (link->link.prog->type != new_prog->type)
583 return -EINVAL;
584
585 list_for_each_entry(pl, progs, node) {
586 if (pl->link == link) {
587 found = true;
588 break;
589 }
590 }
591 if (!found)
592 return -ENOENT;
593
594 old_prog = xchg(&link->link.prog, new_prog);
595 replace_effective_prog(cgrp, link->type, link);
596 bpf_prog_put(old_prog);
597 return 0;
598}
599
600static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog,
601 struct bpf_prog *old_prog)
602{
603 struct bpf_cgroup_link *cg_link;
604 int ret;
605
606 cg_link = container_of(link, struct bpf_cgroup_link, link);
607
608 mutex_lock(&cgroup_mutex);
609 /* link might have been auto-released by dying cgroup, so fail */
610 if (!cg_link->cgroup) {
611 ret = -ENOLINK;
612 goto out_unlock;
613 }
614 if (old_prog && link->prog != old_prog) {
615 ret = -EPERM;
616 goto out_unlock;
617 }
618 ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog);
619out_unlock:
620 mutex_unlock(&cgroup_mutex);
621 return ret;
622}
623
624static struct bpf_prog_list *find_detach_entry(struct list_head *progs,
625 struct bpf_prog *prog,
626 struct bpf_cgroup_link *link,
627 bool allow_multi)
628{
629 struct bpf_prog_list *pl;
630
631 if (!allow_multi) {
632 if (list_empty(progs))
633 /* report error when trying to detach and nothing is attached */
634 return ERR_PTR(-ENOENT);
635
636 /* to maintain backward compatibility NONE and OVERRIDE cgroups
637 * allow detaching with invalid FD (prog==NULL) in legacy mode
638 */
639 return list_first_entry(progs, typeof(*pl), node);
640 }
641
642 if (!prog && !link)
643 /* to detach MULTI prog the user has to specify valid FD
644 * of the program or link to be detached
645 */
646 return ERR_PTR(-EINVAL);
647
648 /* find the prog or link and detach it */
649 list_for_each_entry(pl, progs, node) {
650 if (pl->prog == prog && pl->link == link)
651 return pl;
652 }
653 return ERR_PTR(-ENOENT);
654}
655
656/**
657 * __cgroup_bpf_detach() - Detach the program or link from a cgroup, and
658 * propagate the change to descendants
659 * @cgrp: The cgroup which descendants to traverse
660 * @prog: A program to detach or NULL
661 * @prog: A link to detach or NULL
662 * @type: Type of detach operation
663 *
664 * At most one of @prog or @link can be non-NULL.
665 * Must be called with cgroup_mutex held.
666 */
667int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
668 struct bpf_cgroup_link *link, enum bpf_attach_type type)
669{
670 struct list_head *progs = &cgrp->bpf.progs[type];
671 u32 flags = cgrp->bpf.flags[type];
672 struct bpf_prog_list *pl;
673 struct bpf_prog *old_prog;
674 int err;
675
676 if (prog && link)
677 /* only one of prog or link can be specified */
678 return -EINVAL;
679
680 pl = find_detach_entry(progs, prog, link, flags & BPF_F_ALLOW_MULTI);
681 if (IS_ERR(pl))
682 return PTR_ERR(pl);
683
684 /* mark it deleted, so it's ignored while recomputing effective */
685 old_prog = pl->prog;
686 pl->prog = NULL;
687 pl->link = NULL;
688
689 err = update_effective_progs(cgrp, type);
690 if (err)
691 goto cleanup;
692
693 /* now can actually delete it from this cgroup list */
694 list_del(&pl->node);
695 kfree(pl);
696 if (list_empty(progs))
697 /* last program was detached, reset flags to zero */
698 cgrp->bpf.flags[type] = 0;
699 if (old_prog)
700 bpf_prog_put(old_prog);
701 static_branch_dec(&cgroup_bpf_enabled_key);
702 return 0;
703
704cleanup:
705 /* restore back prog or link */
706 pl->prog = old_prog;
707 pl->link = link;
708 return err;
709}
710
711/* Must be called with cgroup_mutex held to avoid races. */
712int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
713 union bpf_attr __user *uattr)
714{
715 __u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
716 enum bpf_attach_type type = attr->query.attach_type;
717 struct list_head *progs = &cgrp->bpf.progs[type];
718 u32 flags = cgrp->bpf.flags[type];
719 struct bpf_prog_array *effective;
720 struct bpf_prog *prog;
721 int cnt, ret = 0, i;
722
723 effective = rcu_dereference_protected(cgrp->bpf.effective[type],
724 lockdep_is_held(&cgroup_mutex));
725
726 if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE)
727 cnt = bpf_prog_array_length(effective);
728 else
729 cnt = prog_list_length(progs);
730
731 if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
732 return -EFAULT;
733 if (copy_to_user(&uattr->query.prog_cnt, &cnt, sizeof(cnt)))
734 return -EFAULT;
735 if (attr->query.prog_cnt == 0 || !prog_ids || !cnt)
736 /* return early if user requested only program count + flags */
737 return 0;
738 if (attr->query.prog_cnt < cnt) {
739 cnt = attr->query.prog_cnt;
740 ret = -ENOSPC;
741 }
742
743 if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE) {
744 return bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
745 } else {
746 struct bpf_prog_list *pl;
747 u32 id;
748
749 i = 0;
750 list_for_each_entry(pl, progs, node) {
751 prog = prog_list_prog(pl);
752 id = prog->aux->id;
753 if (copy_to_user(prog_ids + i, &id, sizeof(id)))
754 return -EFAULT;
755 if (++i == cnt)
756 break;
757 }
758 }
759 return ret;
760}
761
762int cgroup_bpf_prog_attach(const union bpf_attr *attr,
763 enum bpf_prog_type ptype, struct bpf_prog *prog)
764{
765 struct bpf_prog *replace_prog = NULL;
766 struct cgroup *cgrp;
767 int ret;
768
769 cgrp = cgroup_get_from_fd(attr->target_fd);
770 if (IS_ERR(cgrp))
771 return PTR_ERR(cgrp);
772
773 if ((attr->attach_flags & BPF_F_ALLOW_MULTI) &&
774 (attr->attach_flags & BPF_F_REPLACE)) {
775 replace_prog = bpf_prog_get_type(attr->replace_bpf_fd, ptype);
776 if (IS_ERR(replace_prog)) {
777 cgroup_put(cgrp);
778 return PTR_ERR(replace_prog);
779 }
780 }
781
782 ret = cgroup_bpf_attach(cgrp, prog, replace_prog, NULL,
783 attr->attach_type, attr->attach_flags);
784
785 if (replace_prog)
786 bpf_prog_put(replace_prog);
787 cgroup_put(cgrp);
788 return ret;
789}
790
791int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
792{
793 struct bpf_prog *prog;
794 struct cgroup *cgrp;
795 int ret;
796
797 cgrp = cgroup_get_from_fd(attr->target_fd);
798 if (IS_ERR(cgrp))
799 return PTR_ERR(cgrp);
800
801 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
802 if (IS_ERR(prog))
803 prog = NULL;
804
805 ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type);
806 if (prog)
807 bpf_prog_put(prog);
808
809 cgroup_put(cgrp);
810 return ret;
811}
812
813static void bpf_cgroup_link_release(struct bpf_link *link)
814{
815 struct bpf_cgroup_link *cg_link =
816 container_of(link, struct bpf_cgroup_link, link);
817 struct cgroup *cg;
818
819 /* link might have been auto-detached by dying cgroup already,
820 * in that case our work is done here
821 */
822 if (!cg_link->cgroup)
823 return;
824
825 mutex_lock(&cgroup_mutex);
826
827 /* re-check cgroup under lock again */
828 if (!cg_link->cgroup) {
829 mutex_unlock(&cgroup_mutex);
830 return;
831 }
832
833 WARN_ON(__cgroup_bpf_detach(cg_link->cgroup, NULL, cg_link,
834 cg_link->type));
835
836 cg = cg_link->cgroup;
837 cg_link->cgroup = NULL;
838
839 mutex_unlock(&cgroup_mutex);
840
841 cgroup_put(cg);
842}
843
844static void bpf_cgroup_link_dealloc(struct bpf_link *link)
845{
846 struct bpf_cgroup_link *cg_link =
847 container_of(link, struct bpf_cgroup_link, link);
848
849 kfree(cg_link);
850}
851
852static int bpf_cgroup_link_detach(struct bpf_link *link)
853{
854 bpf_cgroup_link_release(link);
855
856 return 0;
857}
858
859static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link,
860 struct seq_file *seq)
861{
862 struct bpf_cgroup_link *cg_link =
863 container_of(link, struct bpf_cgroup_link, link);
864 u64 cg_id = 0;
865
866 mutex_lock(&cgroup_mutex);
867 if (cg_link->cgroup)
868 cg_id = cgroup_id(cg_link->cgroup);
869 mutex_unlock(&cgroup_mutex);
870
871 seq_printf(seq,
872 "cgroup_id:\t%llu\n"
873 "attach_type:\t%d\n",
874 cg_id,
875 cg_link->type);
876}
877
878static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link,
879 struct bpf_link_info *info)
880{
881 struct bpf_cgroup_link *cg_link =
882 container_of(link, struct bpf_cgroup_link, link);
883 u64 cg_id = 0;
884
885 mutex_lock(&cgroup_mutex);
886 if (cg_link->cgroup)
887 cg_id = cgroup_id(cg_link->cgroup);
888 mutex_unlock(&cgroup_mutex);
889
890 info->cgroup.cgroup_id = cg_id;
891 info->cgroup.attach_type = cg_link->type;
892 return 0;
893}
894
895static const struct bpf_link_ops bpf_cgroup_link_lops = {
896 .release = bpf_cgroup_link_release,
897 .dealloc = bpf_cgroup_link_dealloc,
898 .detach = bpf_cgroup_link_detach,
899 .update_prog = cgroup_bpf_replace,
900 .show_fdinfo = bpf_cgroup_link_show_fdinfo,
901 .fill_link_info = bpf_cgroup_link_fill_link_info,
902};
903
904int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
905{
906 struct bpf_link_primer link_primer;
907 struct bpf_cgroup_link *link;
908 struct cgroup *cgrp;
909 int err;
910
911 if (attr->link_create.flags)
912 return -EINVAL;
913
914 cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
915 if (IS_ERR(cgrp))
916 return PTR_ERR(cgrp);
917
918 link = kzalloc(sizeof(*link), GFP_USER);
919 if (!link) {
920 err = -ENOMEM;
921 goto out_put_cgroup;
922 }
923 bpf_link_init(&link->link, BPF_LINK_TYPE_CGROUP, &bpf_cgroup_link_lops,
924 prog);
925 link->cgroup = cgrp;
926 link->type = attr->link_create.attach_type;
927
928 err = bpf_link_prime(&link->link, &link_primer);
929 if (err) {
930 kfree(link);
931 goto out_put_cgroup;
932 }
933
934 err = cgroup_bpf_attach(cgrp, NULL, NULL, link, link->type,
935 BPF_F_ALLOW_MULTI);
936 if (err) {
937 bpf_link_cleanup(&link_primer);
938 goto out_put_cgroup;
939 }
940
941 return bpf_link_settle(&link_primer);
942
943out_put_cgroup:
944 cgroup_put(cgrp);
945 return err;
946}
947
948int cgroup_bpf_prog_query(const union bpf_attr *attr,
949 union bpf_attr __user *uattr)
950{
951 struct cgroup *cgrp;
952 int ret;
953
954 cgrp = cgroup_get_from_fd(attr->query.target_fd);
955 if (IS_ERR(cgrp))
956 return PTR_ERR(cgrp);
957
958 ret = cgroup_bpf_query(cgrp, attr, uattr);
959
960 cgroup_put(cgrp);
961 return ret;
962}
963
964/**
965 * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
966 * @sk: The socket sending or receiving traffic
967 * @skb: The skb that is being sent or received
968 * @type: The type of program to be exectuted
969 *
970 * If no socket is passed, or the socket is not of type INET or INET6,
971 * this function does nothing and returns 0.
972 *
973 * The program type passed in via @type must be suitable for network
974 * filtering. No further check is performed to assert that.
975 *
976 * For egress packets, this function can return:
977 * NET_XMIT_SUCCESS (0) - continue with packet output
978 * NET_XMIT_DROP (1) - drop packet and notify TCP to call cwr
979 * NET_XMIT_CN (2) - continue with packet output and notify TCP
980 * to call cwr
981 * -EPERM - drop packet
982 *
983 * For ingress packets, this function will return -EPERM if any
984 * attached program was found and if it returned != 1 during execution.
985 * Otherwise 0 is returned.
986 */
987int __cgroup_bpf_run_filter_skb(struct sock *sk,
988 struct sk_buff *skb,
989 enum bpf_attach_type type)
990{
991 unsigned int offset = skb->data - skb_network_header(skb);
992 struct sock *save_sk;
993 void *saved_data_end;
994 struct cgroup *cgrp;
995 int ret;
996
997 if (!sk || !sk_fullsock(sk))
998 return 0;
999
1000 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1001 return 0;
1002
1003 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1004 save_sk = skb->sk;
1005 skb->sk = sk;
1006 __skb_push(skb, offset);
1007
1008 /* compute pointers for the bpf prog */
1009 bpf_compute_and_save_data_end(skb, &saved_data_end);
1010
1011 if (type == BPF_CGROUP_INET_EGRESS) {
1012 ret = BPF_PROG_CGROUP_INET_EGRESS_RUN_ARRAY(
1013 cgrp->bpf.effective[type], skb, __bpf_prog_run_save_cb);
1014 } else {
1015 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], skb,
1016 __bpf_prog_run_save_cb);
1017 ret = (ret == 1 ? 0 : -EPERM);
1018 }
1019 bpf_restore_data_end(skb, saved_data_end);
1020 __skb_pull(skb, offset);
1021 skb->sk = save_sk;
1022
1023 return ret;
1024}
1025EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
1026
1027/**
1028 * __cgroup_bpf_run_filter_sk() - Run a program on a sock
1029 * @sk: sock structure to manipulate
1030 * @type: The type of program to be exectuted
1031 *
1032 * socket is passed is expected to be of type INET or INET6.
1033 *
1034 * The program type passed in via @type must be suitable for sock
1035 * filtering. No further check is performed to assert that.
1036 *
1037 * This function will return %-EPERM if any if an attached program was found
1038 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1039 */
1040int __cgroup_bpf_run_filter_sk(struct sock *sk,
1041 enum bpf_attach_type type)
1042{
1043 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1044 int ret;
1045
1046 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sk, BPF_PROG_RUN);
1047 return ret == 1 ? 0 : -EPERM;
1048}
1049EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
1050
1051/**
1052 * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
1053 * provided by user sockaddr
1054 * @sk: sock struct that will use sockaddr
1055 * @uaddr: sockaddr struct provided by user
1056 * @type: The type of program to be exectuted
1057 * @t_ctx: Pointer to attach type specific context
1058 *
1059 * socket is expected to be of type INET or INET6.
1060 *
1061 * This function will return %-EPERM if an attached program is found and
1062 * returned value != 1 during execution. In all other cases, 0 is returned.
1063 */
1064int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
1065 struct sockaddr *uaddr,
1066 enum bpf_attach_type type,
1067 void *t_ctx)
1068{
1069 struct bpf_sock_addr_kern ctx = {
1070 .sk = sk,
1071 .uaddr = uaddr,
1072 .t_ctx = t_ctx,
1073 };
1074 struct sockaddr_storage unspec;
1075 struct cgroup *cgrp;
1076 int ret;
1077
1078 /* Check socket family since not all sockets represent network
1079 * endpoint (e.g. AF_UNIX).
1080 */
1081 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1082 return 0;
1083
1084 if (!ctx.uaddr) {
1085 memset(&unspec, 0, sizeof(unspec));
1086 ctx.uaddr = (struct sockaddr *)&unspec;
1087 }
1088
1089 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1090 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
1091
1092 return ret == 1 ? 0 : -EPERM;
1093}
1094EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
1095
1096/**
1097 * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
1098 * @sk: socket to get cgroup from
1099 * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
1100 * sk with connection information (IP addresses, etc.) May not contain
1101 * cgroup info if it is a req sock.
1102 * @type: The type of program to be exectuted
1103 *
1104 * socket passed is expected to be of type INET or INET6.
1105 *
1106 * The program type passed in via @type must be suitable for sock_ops
1107 * filtering. No further check is performed to assert that.
1108 *
1109 * This function will return %-EPERM if any if an attached program was found
1110 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1111 */
1112int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
1113 struct bpf_sock_ops_kern *sock_ops,
1114 enum bpf_attach_type type)
1115{
1116 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1117 int ret;
1118
1119 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sock_ops,
1120 BPF_PROG_RUN);
1121 return ret == 1 ? 0 : -EPERM;
1122}
1123EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
1124
1125int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
1126 short access, enum bpf_attach_type type)
1127{
1128 struct cgroup *cgrp;
1129 struct bpf_cgroup_dev_ctx ctx = {
1130 .access_type = (access << 16) | dev_type,
1131 .major = major,
1132 .minor = minor,
1133 };
1134 int allow = 1;
1135
1136 rcu_read_lock();
1137 cgrp = task_dfl_cgroup(current);
1138 allow = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx,
1139 BPF_PROG_RUN);
1140 rcu_read_unlock();
1141
1142 return !allow;
1143}
1144
1145static const struct bpf_func_proto *
1146cgroup_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1147{
1148 switch (func_id) {
1149 case BPF_FUNC_get_current_uid_gid:
1150 return &bpf_get_current_uid_gid_proto;
1151 case BPF_FUNC_get_local_storage:
1152 return &bpf_get_local_storage_proto;
1153 case BPF_FUNC_get_current_cgroup_id:
1154 return &bpf_get_current_cgroup_id_proto;
1155 case BPF_FUNC_perf_event_output:
1156 return &bpf_event_output_data_proto;
1157 default:
1158 return bpf_base_func_proto(func_id);
1159 }
1160}
1161
1162static const struct bpf_func_proto *
1163cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1164{
1165 return cgroup_base_func_proto(func_id, prog);
1166}
1167
1168static bool cgroup_dev_is_valid_access(int off, int size,
1169 enum bpf_access_type type,
1170 const struct bpf_prog *prog,
1171 struct bpf_insn_access_aux *info)
1172{
1173 const int size_default = sizeof(__u32);
1174
1175 if (type == BPF_WRITE)
1176 return false;
1177
1178 if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
1179 return false;
1180 /* The verifier guarantees that size > 0. */
1181 if (off % size != 0)
1182 return false;
1183
1184 switch (off) {
1185 case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
1186 bpf_ctx_record_field_size(info, size_default);
1187 if (!bpf_ctx_narrow_access_ok(off, size, size_default))
1188 return false;
1189 break;
1190 default:
1191 if (size != size_default)
1192 return false;
1193 }
1194
1195 return true;
1196}
1197
1198const struct bpf_prog_ops cg_dev_prog_ops = {
1199};
1200
1201const struct bpf_verifier_ops cg_dev_verifier_ops = {
1202 .get_func_proto = cgroup_dev_func_proto,
1203 .is_valid_access = cgroup_dev_is_valid_access,
1204};
1205
1206/**
1207 * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
1208 *
1209 * @head: sysctl table header
1210 * @table: sysctl table
1211 * @write: sysctl is being read (= 0) or written (= 1)
1212 * @buf: pointer to buffer (in and out)
1213 * @pcount: value-result argument: value is size of buffer pointed to by @buf,
1214 * result is size of @new_buf if program set new value, initial value
1215 * otherwise
1216 * @ppos: value-result argument: value is position at which read from or write
1217 * to sysctl is happening, result is new position if program overrode it,
1218 * initial value otherwise
1219 * @type: type of program to be executed
1220 *
1221 * Program is run when sysctl is being accessed, either read or written, and
1222 * can allow or deny such access.
1223 *
1224 * This function will return %-EPERM if an attached program is found and
1225 * returned value != 1 during execution. In all other cases 0 is returned.
1226 */
1227int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
1228 struct ctl_table *table, int write,
1229 void **buf, size_t *pcount, loff_t *ppos,
1230 enum bpf_attach_type type)
1231{
1232 struct bpf_sysctl_kern ctx = {
1233 .head = head,
1234 .table = table,
1235 .write = write,
1236 .ppos = ppos,
1237 .cur_val = NULL,
1238 .cur_len = PAGE_SIZE,
1239 .new_val = NULL,
1240 .new_len = 0,
1241 .new_updated = 0,
1242 };
1243 struct cgroup *cgrp;
1244 loff_t pos = 0;
1245 int ret;
1246
1247 ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
1248 if (!ctx.cur_val ||
1249 table->proc_handler(table, 0, ctx.cur_val, &ctx.cur_len, &pos)) {
1250 /* Let BPF program decide how to proceed. */
1251 ctx.cur_len = 0;
1252 }
1253
1254 if (write && *buf && *pcount) {
1255 /* BPF program should be able to override new value with a
1256 * buffer bigger than provided by user.
1257 */
1258 ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
1259 ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
1260 if (ctx.new_val) {
1261 memcpy(ctx.new_val, *buf, ctx.new_len);
1262 } else {
1263 /* Let BPF program decide how to proceed. */
1264 ctx.new_len = 0;
1265 }
1266 }
1267
1268 rcu_read_lock();
1269 cgrp = task_dfl_cgroup(current);
1270 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
1271 rcu_read_unlock();
1272
1273 kfree(ctx.cur_val);
1274
1275 if (ret == 1 && ctx.new_updated) {
1276 kfree(*buf);
1277 *buf = ctx.new_val;
1278 *pcount = ctx.new_len;
1279 } else {
1280 kfree(ctx.new_val);
1281 }
1282
1283 return ret == 1 ? 0 : -EPERM;
1284}
1285
1286#ifdef CONFIG_NET
1287static bool __cgroup_bpf_prog_array_is_empty(struct cgroup *cgrp,
1288 enum bpf_attach_type attach_type)
1289{
1290 struct bpf_prog_array *prog_array;
1291 bool empty;
1292
1293 rcu_read_lock();
1294 prog_array = rcu_dereference(cgrp->bpf.effective[attach_type]);
1295 empty = bpf_prog_array_is_empty(prog_array);
1296 rcu_read_unlock();
1297
1298 return empty;
1299}
1300
1301static int sockopt_alloc_buf(struct bpf_sockopt_kern *ctx, int max_optlen)
1302{
1303 if (unlikely(max_optlen < 0))
1304 return -EINVAL;
1305
1306 if (unlikely(max_optlen > PAGE_SIZE)) {
1307 /* We don't expose optvals that are greater than PAGE_SIZE
1308 * to the BPF program.
1309 */
1310 max_optlen = PAGE_SIZE;
1311 }
1312
1313 ctx->optval = kzalloc(max_optlen, GFP_USER);
1314 if (!ctx->optval)
1315 return -ENOMEM;
1316
1317 ctx->optval_end = ctx->optval + max_optlen;
1318
1319 return max_optlen;
1320}
1321
1322static void sockopt_free_buf(struct bpf_sockopt_kern *ctx)
1323{
1324 kfree(ctx->optval);
1325}
1326
1327int __cgroup_bpf_run_filter_setsockopt(struct sock *sk, int *level,
1328 int *optname, char __user *optval,
1329 int *optlen, char **kernel_optval)
1330{
1331 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1332 struct bpf_sockopt_kern ctx = {
1333 .sk = sk,
1334 .level = *level,
1335 .optname = *optname,
1336 };
1337 int ret, max_optlen;
1338
1339 /* Opportunistic check to see whether we have any BPF program
1340 * attached to the hook so we don't waste time allocating
1341 * memory and locking the socket.
1342 */
1343 if (!cgroup_bpf_enabled ||
1344 __cgroup_bpf_prog_array_is_empty(cgrp, BPF_CGROUP_SETSOCKOPT))
1345 return 0;
1346
1347 /* Allocate a bit more than the initial user buffer for
1348 * BPF program. The canonical use case is overriding
1349 * TCP_CONGESTION(nv) to TCP_CONGESTION(cubic).
1350 */
1351 max_optlen = max_t(int, 16, *optlen);
1352
1353 max_optlen = sockopt_alloc_buf(&ctx, max_optlen);
1354 if (max_optlen < 0)
1355 return max_optlen;
1356
1357 ctx.optlen = *optlen;
1358
1359 if (copy_from_user(ctx.optval, optval, min(*optlen, max_optlen)) != 0) {
1360 ret = -EFAULT;
1361 goto out;
1362 }
1363
1364 lock_sock(sk);
1365 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[BPF_CGROUP_SETSOCKOPT],
1366 &ctx, BPF_PROG_RUN);
1367 release_sock(sk);
1368
1369 if (!ret) {
1370 ret = -EPERM;
1371 goto out;
1372 }
1373
1374 if (ctx.optlen == -1) {
1375 /* optlen set to -1, bypass kernel */
1376 ret = 1;
1377 } else if (ctx.optlen > max_optlen || ctx.optlen < -1) {
1378 /* optlen is out of bounds */
1379 ret = -EFAULT;
1380 } else {
1381 /* optlen within bounds, run kernel handler */
1382 ret = 0;
1383
1384 /* export any potential modifications */
1385 *level = ctx.level;
1386 *optname = ctx.optname;
1387
1388 /* optlen == 0 from BPF indicates that we should
1389 * use original userspace data.
1390 */
1391 if (ctx.optlen != 0) {
1392 *optlen = ctx.optlen;
1393 *kernel_optval = ctx.optval;
1394 }
1395 }
1396
1397out:
1398 if (ret)
1399 sockopt_free_buf(&ctx);
1400 return ret;
1401}
1402
1403int __cgroup_bpf_run_filter_getsockopt(struct sock *sk, int level,
1404 int optname, char __user *optval,
1405 int __user *optlen, int max_optlen,
1406 int retval)
1407{
1408 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1409 struct bpf_sockopt_kern ctx = {
1410 .sk = sk,
1411 .level = level,
1412 .optname = optname,
1413 .retval = retval,
1414 };
1415 int ret;
1416
1417 /* Opportunistic check to see whether we have any BPF program
1418 * attached to the hook so we don't waste time allocating
1419 * memory and locking the socket.
1420 */
1421 if (!cgroup_bpf_enabled ||
1422 __cgroup_bpf_prog_array_is_empty(cgrp, BPF_CGROUP_GETSOCKOPT))
1423 return retval;
1424
1425 ctx.optlen = max_optlen;
1426
1427 max_optlen = sockopt_alloc_buf(&ctx, max_optlen);
1428 if (max_optlen < 0)
1429 return max_optlen;
1430
1431 if (!retval) {
1432 /* If kernel getsockopt finished successfully,
1433 * copy whatever was returned to the user back
1434 * into our temporary buffer. Set optlen to the
1435 * one that kernel returned as well to let
1436 * BPF programs inspect the value.
1437 */
1438
1439 if (get_user(ctx.optlen, optlen)) {
1440 ret = -EFAULT;
1441 goto out;
1442 }
1443
1444 if (copy_from_user(ctx.optval, optval,
1445 min(ctx.optlen, max_optlen)) != 0) {
1446 ret = -EFAULT;
1447 goto out;
1448 }
1449 }
1450
1451 lock_sock(sk);
1452 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[BPF_CGROUP_GETSOCKOPT],
1453 &ctx, BPF_PROG_RUN);
1454 release_sock(sk);
1455
1456 if (!ret) {
1457 ret = -EPERM;
1458 goto out;
1459 }
1460
1461 if (ctx.optlen > max_optlen) {
1462 ret = -EFAULT;
1463 goto out;
1464 }
1465
1466 /* BPF programs only allowed to set retval to 0, not some
1467 * arbitrary value.
1468 */
1469 if (ctx.retval != 0 && ctx.retval != retval) {
1470 ret = -EFAULT;
1471 goto out;
1472 }
1473
1474 if (ctx.optlen != 0) {
1475 if (copy_to_user(optval, ctx.optval, ctx.optlen) ||
1476 put_user(ctx.optlen, optlen)) {
1477 ret = -EFAULT;
1478 goto out;
1479 }
1480 }
1481
1482 ret = ctx.retval;
1483
1484out:
1485 sockopt_free_buf(&ctx);
1486 return ret;
1487}
1488#endif
1489
1490static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
1491 size_t *lenp)
1492{
1493 ssize_t tmp_ret = 0, ret;
1494
1495 if (dir->header.parent) {
1496 tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
1497 if (tmp_ret < 0)
1498 return tmp_ret;
1499 }
1500
1501 ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
1502 if (ret < 0)
1503 return ret;
1504 *bufp += ret;
1505 *lenp -= ret;
1506 ret += tmp_ret;
1507
1508 /* Avoid leading slash. */
1509 if (!ret)
1510 return ret;
1511
1512 tmp_ret = strscpy(*bufp, "/", *lenp);
1513 if (tmp_ret < 0)
1514 return tmp_ret;
1515 *bufp += tmp_ret;
1516 *lenp -= tmp_ret;
1517
1518 return ret + tmp_ret;
1519}
1520
1521BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
1522 size_t, buf_len, u64, flags)
1523{
1524 ssize_t tmp_ret = 0, ret;
1525
1526 if (!buf)
1527 return -EINVAL;
1528
1529 if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
1530 if (!ctx->head)
1531 return -EINVAL;
1532 tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
1533 if (tmp_ret < 0)
1534 return tmp_ret;
1535 }
1536
1537 ret = strscpy(buf, ctx->table->procname, buf_len);
1538
1539 return ret < 0 ? ret : tmp_ret + ret;
1540}
1541
1542static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
1543 .func = bpf_sysctl_get_name,
1544 .gpl_only = false,
1545 .ret_type = RET_INTEGER,
1546 .arg1_type = ARG_PTR_TO_CTX,
1547 .arg2_type = ARG_PTR_TO_MEM,
1548 .arg3_type = ARG_CONST_SIZE,
1549 .arg4_type = ARG_ANYTHING,
1550};
1551
1552static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
1553 size_t src_len)
1554{
1555 if (!dst)
1556 return -EINVAL;
1557
1558 if (!dst_len)
1559 return -E2BIG;
1560
1561 if (!src || !src_len) {
1562 memset(dst, 0, dst_len);
1563 return -EINVAL;
1564 }
1565
1566 memcpy(dst, src, min(dst_len, src_len));
1567
1568 if (dst_len > src_len) {
1569 memset(dst + src_len, '\0', dst_len - src_len);
1570 return src_len;
1571 }
1572
1573 dst[dst_len - 1] = '\0';
1574
1575 return -E2BIG;
1576}
1577
1578BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
1579 char *, buf, size_t, buf_len)
1580{
1581 return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
1582}
1583
1584static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
1585 .func = bpf_sysctl_get_current_value,
1586 .gpl_only = false,
1587 .ret_type = RET_INTEGER,
1588 .arg1_type = ARG_PTR_TO_CTX,
1589 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
1590 .arg3_type = ARG_CONST_SIZE,
1591};
1592
1593BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
1594 size_t, buf_len)
1595{
1596 if (!ctx->write) {
1597 if (buf && buf_len)
1598 memset(buf, '\0', buf_len);
1599 return -EINVAL;
1600 }
1601 return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
1602}
1603
1604static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
1605 .func = bpf_sysctl_get_new_value,
1606 .gpl_only = false,
1607 .ret_type = RET_INTEGER,
1608 .arg1_type = ARG_PTR_TO_CTX,
1609 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
1610 .arg3_type = ARG_CONST_SIZE,
1611};
1612
1613BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
1614 const char *, buf, size_t, buf_len)
1615{
1616 if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
1617 return -EINVAL;
1618
1619 if (buf_len > PAGE_SIZE - 1)
1620 return -E2BIG;
1621
1622 memcpy(ctx->new_val, buf, buf_len);
1623 ctx->new_len = buf_len;
1624 ctx->new_updated = 1;
1625
1626 return 0;
1627}
1628
1629static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
1630 .func = bpf_sysctl_set_new_value,
1631 .gpl_only = false,
1632 .ret_type = RET_INTEGER,
1633 .arg1_type = ARG_PTR_TO_CTX,
1634 .arg2_type = ARG_PTR_TO_MEM,
1635 .arg3_type = ARG_CONST_SIZE,
1636};
1637
1638static const struct bpf_func_proto *
1639sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1640{
1641 switch (func_id) {
1642 case BPF_FUNC_strtol:
1643 return &bpf_strtol_proto;
1644 case BPF_FUNC_strtoul:
1645 return &bpf_strtoul_proto;
1646 case BPF_FUNC_sysctl_get_name:
1647 return &bpf_sysctl_get_name_proto;
1648 case BPF_FUNC_sysctl_get_current_value:
1649 return &bpf_sysctl_get_current_value_proto;
1650 case BPF_FUNC_sysctl_get_new_value:
1651 return &bpf_sysctl_get_new_value_proto;
1652 case BPF_FUNC_sysctl_set_new_value:
1653 return &bpf_sysctl_set_new_value_proto;
1654 default:
1655 return cgroup_base_func_proto(func_id, prog);
1656 }
1657}
1658
1659static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
1660 const struct bpf_prog *prog,
1661 struct bpf_insn_access_aux *info)
1662{
1663 const int size_default = sizeof(__u32);
1664
1665 if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
1666 return false;
1667
1668 switch (off) {
1669 case bpf_ctx_range(struct bpf_sysctl, write):
1670 if (type != BPF_READ)
1671 return false;
1672 bpf_ctx_record_field_size(info, size_default);
1673 return bpf_ctx_narrow_access_ok(off, size, size_default);
1674 case bpf_ctx_range(struct bpf_sysctl, file_pos):
1675 if (type == BPF_READ) {
1676 bpf_ctx_record_field_size(info, size_default);
1677 return bpf_ctx_narrow_access_ok(off, size, size_default);
1678 } else {
1679 return size == size_default;
1680 }
1681 default:
1682 return false;
1683 }
1684}
1685
1686static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
1687 const struct bpf_insn *si,
1688 struct bpf_insn *insn_buf,
1689 struct bpf_prog *prog, u32 *target_size)
1690{
1691 struct bpf_insn *insn = insn_buf;
1692 u32 read_size;
1693
1694 switch (si->off) {
1695 case offsetof(struct bpf_sysctl, write):
1696 *insn++ = BPF_LDX_MEM(
1697 BPF_SIZE(si->code), si->dst_reg, si->src_reg,
1698 bpf_target_off(struct bpf_sysctl_kern, write,
1699 sizeof_field(struct bpf_sysctl_kern,
1700 write),
1701 target_size));
1702 break;
1703 case offsetof(struct bpf_sysctl, file_pos):
1704 /* ppos is a pointer so it should be accessed via indirect
1705 * loads and stores. Also for stores additional temporary
1706 * register is used since neither src_reg nor dst_reg can be
1707 * overridden.
1708 */
1709 if (type == BPF_WRITE) {
1710 int treg = BPF_REG_9;
1711
1712 if (si->src_reg == treg || si->dst_reg == treg)
1713 --treg;
1714 if (si->src_reg == treg || si->dst_reg == treg)
1715 --treg;
1716 *insn++ = BPF_STX_MEM(
1717 BPF_DW, si->dst_reg, treg,
1718 offsetof(struct bpf_sysctl_kern, tmp_reg));
1719 *insn++ = BPF_LDX_MEM(
1720 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1721 treg, si->dst_reg,
1722 offsetof(struct bpf_sysctl_kern, ppos));
1723 *insn++ = BPF_STX_MEM(
1724 BPF_SIZEOF(u32), treg, si->src_reg,
1725 bpf_ctx_narrow_access_offset(
1726 0, sizeof(u32), sizeof(loff_t)));
1727 *insn++ = BPF_LDX_MEM(
1728 BPF_DW, treg, si->dst_reg,
1729 offsetof(struct bpf_sysctl_kern, tmp_reg));
1730 } else {
1731 *insn++ = BPF_LDX_MEM(
1732 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1733 si->dst_reg, si->src_reg,
1734 offsetof(struct bpf_sysctl_kern, ppos));
1735 read_size = bpf_size_to_bytes(BPF_SIZE(si->code));
1736 *insn++ = BPF_LDX_MEM(
1737 BPF_SIZE(si->code), si->dst_reg, si->dst_reg,
1738 bpf_ctx_narrow_access_offset(
1739 0, read_size, sizeof(loff_t)));
1740 }
1741 *target_size = sizeof(u32);
1742 break;
1743 }
1744
1745 return insn - insn_buf;
1746}
1747
1748const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
1749 .get_func_proto = sysctl_func_proto,
1750 .is_valid_access = sysctl_is_valid_access,
1751 .convert_ctx_access = sysctl_convert_ctx_access,
1752};
1753
1754const struct bpf_prog_ops cg_sysctl_prog_ops = {
1755};
1756
1757static const struct bpf_func_proto *
1758cg_sockopt_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1759{
1760 switch (func_id) {
1761#ifdef CONFIG_NET
1762 case BPF_FUNC_sk_storage_get:
1763 return &bpf_sk_storage_get_proto;
1764 case BPF_FUNC_sk_storage_delete:
1765 return &bpf_sk_storage_delete_proto;
1766#endif
1767#ifdef CONFIG_INET
1768 case BPF_FUNC_tcp_sock:
1769 return &bpf_tcp_sock_proto;
1770#endif
1771 default:
1772 return cgroup_base_func_proto(func_id, prog);
1773 }
1774}
1775
1776static bool cg_sockopt_is_valid_access(int off, int size,
1777 enum bpf_access_type type,
1778 const struct bpf_prog *prog,
1779 struct bpf_insn_access_aux *info)
1780{
1781 const int size_default = sizeof(__u32);
1782
1783 if (off < 0 || off >= sizeof(struct bpf_sockopt))
1784 return false;
1785
1786 if (off % size != 0)
1787 return false;
1788
1789 if (type == BPF_WRITE) {
1790 switch (off) {
1791 case offsetof(struct bpf_sockopt, retval):
1792 if (size != size_default)
1793 return false;
1794 return prog->expected_attach_type ==
1795 BPF_CGROUP_GETSOCKOPT;
1796 case offsetof(struct bpf_sockopt, optname):
1797 fallthrough;
1798 case offsetof(struct bpf_sockopt, level):
1799 if (size != size_default)
1800 return false;
1801 return prog->expected_attach_type ==
1802 BPF_CGROUP_SETSOCKOPT;
1803 case offsetof(struct bpf_sockopt, optlen):
1804 return size == size_default;
1805 default:
1806 return false;
1807 }
1808 }
1809
1810 switch (off) {
1811 case offsetof(struct bpf_sockopt, sk):
1812 if (size != sizeof(__u64))
1813 return false;
1814 info->reg_type = PTR_TO_SOCKET;
1815 break;
1816 case offsetof(struct bpf_sockopt, optval):
1817 if (size != sizeof(__u64))
1818 return false;
1819 info->reg_type = PTR_TO_PACKET;
1820 break;
1821 case offsetof(struct bpf_sockopt, optval_end):
1822 if (size != sizeof(__u64))
1823 return false;
1824 info->reg_type = PTR_TO_PACKET_END;
1825 break;
1826 case offsetof(struct bpf_sockopt, retval):
1827 if (size != size_default)
1828 return false;
1829 return prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT;
1830 default:
1831 if (size != size_default)
1832 return false;
1833 break;
1834 }
1835 return true;
1836}
1837
1838#define CG_SOCKOPT_ACCESS_FIELD(T, F) \
1839 T(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F), \
1840 si->dst_reg, si->src_reg, \
1841 offsetof(struct bpf_sockopt_kern, F))
1842
1843static u32 cg_sockopt_convert_ctx_access(enum bpf_access_type type,
1844 const struct bpf_insn *si,
1845 struct bpf_insn *insn_buf,
1846 struct bpf_prog *prog,
1847 u32 *target_size)
1848{
1849 struct bpf_insn *insn = insn_buf;
1850
1851 switch (si->off) {
1852 case offsetof(struct bpf_sockopt, sk):
1853 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, sk);
1854 break;
1855 case offsetof(struct bpf_sockopt, level):
1856 if (type == BPF_WRITE)
1857 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, level);
1858 else
1859 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, level);
1860 break;
1861 case offsetof(struct bpf_sockopt, optname):
1862 if (type == BPF_WRITE)
1863 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optname);
1864 else
1865 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optname);
1866 break;
1867 case offsetof(struct bpf_sockopt, optlen):
1868 if (type == BPF_WRITE)
1869 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optlen);
1870 else
1871 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optlen);
1872 break;
1873 case offsetof(struct bpf_sockopt, retval):
1874 if (type == BPF_WRITE)
1875 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, retval);
1876 else
1877 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, retval);
1878 break;
1879 case offsetof(struct bpf_sockopt, optval):
1880 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval);
1881 break;
1882 case offsetof(struct bpf_sockopt, optval_end):
1883 *insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval_end);
1884 break;
1885 }
1886
1887 return insn - insn_buf;
1888}
1889
1890static int cg_sockopt_get_prologue(struct bpf_insn *insn_buf,
1891 bool direct_write,
1892 const struct bpf_prog *prog)
1893{
1894 /* Nothing to do for sockopt argument. The data is kzalloc'ated.
1895 */
1896 return 0;
1897}
1898
1899const struct bpf_verifier_ops cg_sockopt_verifier_ops = {
1900 .get_func_proto = cg_sockopt_func_proto,
1901 .is_valid_access = cg_sockopt_is_valid_access,
1902 .convert_ctx_access = cg_sockopt_convert_ctx_access,
1903 .gen_prologue = cg_sockopt_get_prologue,
1904};
1905
1906const struct bpf_prog_ops cg_sockopt_prog_ops = {
1907};