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