1 // SPDX-License-Identifier: GPL-2.0-only
3 * Functions to manage eBPF programs attached to cgroups
5 * Copyright (c) 2016 Daniel Mack
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>
19 #include "../cgroup/cgroup-internal.h"
21 DEFINE_STATIC_KEY_FALSE(cgroup_bpf_enabled_key);
22 EXPORT_SYMBOL(cgroup_bpf_enabled_key);
24 void cgroup_bpf_offline(struct cgroup *cgrp)
27 percpu_ref_kill(&cgrp->bpf.refcnt);
31 * cgroup_bpf_release() - put references of all bpf programs and
32 * release all cgroup bpf data
33 * @work: work structure embedded into the cgroup to modify
35 static void cgroup_bpf_release(struct work_struct *work)
37 struct cgroup *cgrp = container_of(work, struct cgroup,
39 enum bpf_cgroup_storage_type stype;
40 struct bpf_prog_array *old_array;
43 mutex_lock(&cgroup_mutex);
45 for (type = 0; type < ARRAY_SIZE(cgrp->bpf.progs); type++) {
46 struct list_head *progs = &cgrp->bpf.progs[type];
47 struct bpf_prog_list *pl, *tmp;
49 list_for_each_entry_safe(pl, tmp, progs, node) {
51 bpf_prog_put(pl->prog);
52 for_each_cgroup_storage_type(stype) {
53 bpf_cgroup_storage_unlink(pl->storage[stype]);
54 bpf_cgroup_storage_free(pl->storage[stype]);
57 static_branch_dec(&cgroup_bpf_enabled_key);
59 old_array = rcu_dereference_protected(
60 cgrp->bpf.effective[type],
61 lockdep_is_held(&cgroup_mutex));
62 bpf_prog_array_free(old_array);
65 mutex_unlock(&cgroup_mutex);
67 percpu_ref_exit(&cgrp->bpf.refcnt);
72 * cgroup_bpf_release_fn() - callback used to schedule releasing
74 * @ref: percpu ref counter structure
76 static void cgroup_bpf_release_fn(struct percpu_ref *ref)
78 struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
80 INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
81 queue_work(system_wq, &cgrp->bpf.release_work);
84 /* count number of elements in the list.
85 * it's slow but the list cannot be long
87 static u32 prog_list_length(struct list_head *head)
89 struct bpf_prog_list *pl;
92 list_for_each_entry(pl, head, node) {
100 /* if parent has non-overridable prog attached,
101 * disallow attaching new programs to the descendent cgroup.
102 * if parent has overridable or multi-prog, allow attaching
104 static bool hierarchy_allows_attach(struct cgroup *cgrp,
105 enum bpf_attach_type type,
110 p = cgroup_parent(cgrp);
114 u32 flags = p->bpf.flags[type];
117 if (flags & BPF_F_ALLOW_MULTI)
119 cnt = prog_list_length(&p->bpf.progs[type]);
120 WARN_ON_ONCE(cnt > 1);
122 return !!(flags & BPF_F_ALLOW_OVERRIDE);
123 p = cgroup_parent(p);
128 /* compute a chain of effective programs for a given cgroup:
129 * start from the list of programs in this cgroup and add
130 * all parent programs.
131 * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
132 * to programs in this cgroup
134 static int compute_effective_progs(struct cgroup *cgrp,
135 enum bpf_attach_type type,
136 struct bpf_prog_array **array)
138 enum bpf_cgroup_storage_type stype;
139 struct bpf_prog_array *progs;
140 struct bpf_prog_list *pl;
141 struct cgroup *p = cgrp;
144 /* count number of effective programs by walking parents */
146 if (cnt == 0 || (p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
147 cnt += prog_list_length(&p->bpf.progs[type]);
148 p = cgroup_parent(p);
151 progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
155 /* populate the array with effective progs */
159 if (cnt > 0 && !(p->bpf.flags[type] & BPF_F_ALLOW_MULTI))
162 list_for_each_entry(pl, &p->bpf.progs[type], node) {
166 progs->items[cnt].prog = pl->prog;
167 for_each_cgroup_storage_type(stype)
168 progs->items[cnt].cgroup_storage[stype] =
172 } while ((p = cgroup_parent(p)));
178 static void activate_effective_progs(struct cgroup *cgrp,
179 enum bpf_attach_type type,
180 struct bpf_prog_array *old_array)
182 rcu_swap_protected(cgrp->bpf.effective[type], old_array,
183 lockdep_is_held(&cgroup_mutex));
184 /* free prog array after grace period, since __cgroup_bpf_run_*()
185 * might be still walking the array
187 bpf_prog_array_free(old_array);
191 * cgroup_bpf_inherit() - inherit effective programs from parent
192 * @cgrp: the cgroup to modify
194 int cgroup_bpf_inherit(struct cgroup *cgrp)
196 /* has to use marco instead of const int, since compiler thinks
197 * that array below is variable length
199 #define NR ARRAY_SIZE(cgrp->bpf.effective)
200 struct bpf_prog_array *arrays[NR] = {};
203 ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
208 for (i = 0; i < NR; i++)
209 INIT_LIST_HEAD(&cgrp->bpf.progs[i]);
211 for (i = 0; i < NR; i++)
212 if (compute_effective_progs(cgrp, i, &arrays[i]))
215 for (i = 0; i < NR; i++)
216 activate_effective_progs(cgrp, i, arrays[i]);
220 for (i = 0; i < NR; i++)
221 bpf_prog_array_free(arrays[i]);
223 percpu_ref_exit(&cgrp->bpf.refcnt);
228 static int update_effective_progs(struct cgroup *cgrp,
229 enum bpf_attach_type type)
231 struct cgroup_subsys_state *css;
234 /* allocate and recompute effective prog arrays */
235 css_for_each_descendant_pre(css, &cgrp->self) {
236 struct cgroup *desc = container_of(css, struct cgroup, self);
238 if (percpu_ref_is_zero(&desc->bpf.refcnt))
241 err = compute_effective_progs(desc, type, &desc->bpf.inactive);
246 /* all allocations were successful. Activate all prog arrays */
247 css_for_each_descendant_pre(css, &cgrp->self) {
248 struct cgroup *desc = container_of(css, struct cgroup, self);
250 if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
251 if (unlikely(desc->bpf.inactive)) {
252 bpf_prog_array_free(desc->bpf.inactive);
253 desc->bpf.inactive = NULL;
258 activate_effective_progs(desc, type, desc->bpf.inactive);
259 desc->bpf.inactive = NULL;
265 /* oom while computing effective. Free all computed effective arrays
266 * since they were not activated
268 css_for_each_descendant_pre(css, &cgrp->self) {
269 struct cgroup *desc = container_of(css, struct cgroup, self);
271 bpf_prog_array_free(desc->bpf.inactive);
272 desc->bpf.inactive = NULL;
278 #define BPF_CGROUP_MAX_PROGS 64
281 * __cgroup_bpf_attach() - Attach the program to a cgroup, and
282 * propagate the change to descendants
283 * @cgrp: The cgroup which descendants to traverse
284 * @prog: A program to attach
285 * @type: Type of attach operation
286 * @flags: Option flags
288 * Must be called with cgroup_mutex held.
290 int __cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
291 enum bpf_attach_type type, u32 flags)
293 struct list_head *progs = &cgrp->bpf.progs[type];
294 struct bpf_prog *old_prog = NULL;
295 struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE],
296 *old_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {NULL};
297 enum bpf_cgroup_storage_type stype;
298 struct bpf_prog_list *pl;
299 bool pl_was_allocated;
302 if ((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI))
303 /* invalid combination */
306 if (!hierarchy_allows_attach(cgrp, type, flags))
309 if (!list_empty(progs) && cgrp->bpf.flags[type] != flags)
310 /* Disallow attaching non-overridable on top
311 * of existing overridable in this cgroup.
312 * Disallow attaching multi-prog if overridable or none
316 if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
319 for_each_cgroup_storage_type(stype) {
320 storage[stype] = bpf_cgroup_storage_alloc(prog, stype);
321 if (IS_ERR(storage[stype])) {
322 storage[stype] = NULL;
323 for_each_cgroup_storage_type(stype)
324 bpf_cgroup_storage_free(storage[stype]);
329 if (flags & BPF_F_ALLOW_MULTI) {
330 list_for_each_entry(pl, progs, node) {
331 if (pl->prog == prog) {
332 /* disallow attaching the same prog twice */
333 for_each_cgroup_storage_type(stype)
334 bpf_cgroup_storage_free(storage[stype]);
339 pl = kmalloc(sizeof(*pl), GFP_KERNEL);
341 for_each_cgroup_storage_type(stype)
342 bpf_cgroup_storage_free(storage[stype]);
346 pl_was_allocated = true;
348 for_each_cgroup_storage_type(stype)
349 pl->storage[stype] = storage[stype];
350 list_add_tail(&pl->node, progs);
352 if (list_empty(progs)) {
353 pl = kmalloc(sizeof(*pl), GFP_KERNEL);
355 for_each_cgroup_storage_type(stype)
356 bpf_cgroup_storage_free(storage[stype]);
359 pl_was_allocated = true;
360 list_add_tail(&pl->node, progs);
362 pl = list_first_entry(progs, typeof(*pl), node);
364 for_each_cgroup_storage_type(stype) {
365 old_storage[stype] = pl->storage[stype];
366 bpf_cgroup_storage_unlink(old_storage[stype]);
368 pl_was_allocated = false;
371 for_each_cgroup_storage_type(stype)
372 pl->storage[stype] = storage[stype];
375 cgrp->bpf.flags[type] = flags;
377 err = update_effective_progs(cgrp, type);
381 static_branch_inc(&cgroup_bpf_enabled_key);
382 for_each_cgroup_storage_type(stype) {
383 if (!old_storage[stype])
385 bpf_cgroup_storage_free(old_storage[stype]);
388 bpf_prog_put(old_prog);
389 static_branch_dec(&cgroup_bpf_enabled_key);
391 for_each_cgroup_storage_type(stype)
392 bpf_cgroup_storage_link(storage[stype], cgrp, type);
396 /* and cleanup the prog list */
398 for_each_cgroup_storage_type(stype) {
399 bpf_cgroup_storage_free(pl->storage[stype]);
400 pl->storage[stype] = old_storage[stype];
401 bpf_cgroup_storage_link(old_storage[stype], cgrp, type);
403 if (pl_was_allocated) {
411 * __cgroup_bpf_detach() - Detach the program from a cgroup, and
412 * propagate the change to descendants
413 * @cgrp: The cgroup which descendants to traverse
414 * @prog: A program to detach or NULL
415 * @type: Type of detach operation
417 * Must be called with cgroup_mutex held.
419 int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
420 enum bpf_attach_type type)
422 struct list_head *progs = &cgrp->bpf.progs[type];
423 enum bpf_cgroup_storage_type stype;
424 u32 flags = cgrp->bpf.flags[type];
425 struct bpf_prog *old_prog = NULL;
426 struct bpf_prog_list *pl;
429 if (flags & BPF_F_ALLOW_MULTI) {
431 /* to detach MULTI prog the user has to specify valid FD
432 * of the program to be detached
436 if (list_empty(progs))
437 /* report error when trying to detach and nothing is attached */
441 if (flags & BPF_F_ALLOW_MULTI) {
442 /* find the prog and detach it */
443 list_for_each_entry(pl, progs, node) {
444 if (pl->prog != prog)
447 /* mark it deleted, so it's ignored while
448 * recomputing effective
456 /* to maintain backward compatibility NONE and OVERRIDE cgroups
457 * allow detaching with invalid FD (prog==NULL)
459 pl = list_first_entry(progs, typeof(*pl), node);
464 err = update_effective_progs(cgrp, type);
468 /* now can actually delete it from this cgroup list */
470 for_each_cgroup_storage_type(stype) {
471 bpf_cgroup_storage_unlink(pl->storage[stype]);
472 bpf_cgroup_storage_free(pl->storage[stype]);
475 if (list_empty(progs))
476 /* last program was detached, reset flags to zero */
477 cgrp->bpf.flags[type] = 0;
479 bpf_prog_put(old_prog);
480 static_branch_dec(&cgroup_bpf_enabled_key);
484 /* and restore back old_prog */
489 /* Must be called with cgroup_mutex held to avoid races. */
490 int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
491 union bpf_attr __user *uattr)
493 __u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
494 enum bpf_attach_type type = attr->query.attach_type;
495 struct list_head *progs = &cgrp->bpf.progs[type];
496 u32 flags = cgrp->bpf.flags[type];
497 struct bpf_prog_array *effective;
500 effective = rcu_dereference_protected(cgrp->bpf.effective[type],
501 lockdep_is_held(&cgroup_mutex));
503 if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE)
504 cnt = bpf_prog_array_length(effective);
506 cnt = prog_list_length(progs);
508 if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
510 if (copy_to_user(&uattr->query.prog_cnt, &cnt, sizeof(cnt)))
512 if (attr->query.prog_cnt == 0 || !prog_ids || !cnt)
513 /* return early if user requested only program count + flags */
515 if (attr->query.prog_cnt < cnt) {
516 cnt = attr->query.prog_cnt;
520 if (attr->query.query_flags & BPF_F_QUERY_EFFECTIVE) {
521 return bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
523 struct bpf_prog_list *pl;
527 list_for_each_entry(pl, progs, node) {
528 id = pl->prog->aux->id;
529 if (copy_to_user(prog_ids + i, &id, sizeof(id)))
538 int cgroup_bpf_prog_attach(const union bpf_attr *attr,
539 enum bpf_prog_type ptype, struct bpf_prog *prog)
544 cgrp = cgroup_get_from_fd(attr->target_fd);
546 return PTR_ERR(cgrp);
548 ret = cgroup_bpf_attach(cgrp, prog, attr->attach_type,
554 int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
556 struct bpf_prog *prog;
560 cgrp = cgroup_get_from_fd(attr->target_fd);
562 return PTR_ERR(cgrp);
564 prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
568 ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type, 0);
576 int cgroup_bpf_prog_query(const union bpf_attr *attr,
577 union bpf_attr __user *uattr)
582 cgrp = cgroup_get_from_fd(attr->query.target_fd);
584 return PTR_ERR(cgrp);
586 ret = cgroup_bpf_query(cgrp, attr, uattr);
593 * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
594 * @sk: The socket sending or receiving traffic
595 * @skb: The skb that is being sent or received
596 * @type: The type of program to be exectuted
598 * If no socket is passed, or the socket is not of type INET or INET6,
599 * this function does nothing and returns 0.
601 * The program type passed in via @type must be suitable for network
602 * filtering. No further check is performed to assert that.
604 * For egress packets, this function can return:
605 * NET_XMIT_SUCCESS (0) - continue with packet output
606 * NET_XMIT_DROP (1) - drop packet and notify TCP to call cwr
607 * NET_XMIT_CN (2) - continue with packet output and notify TCP
609 * -EPERM - drop packet
611 * For ingress packets, this function will return -EPERM if any
612 * attached program was found and if it returned != 1 during execution.
613 * Otherwise 0 is returned.
615 int __cgroup_bpf_run_filter_skb(struct sock *sk,
617 enum bpf_attach_type type)
619 unsigned int offset = skb->data - skb_network_header(skb);
620 struct sock *save_sk;
621 void *saved_data_end;
625 if (!sk || !sk_fullsock(sk))
628 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
631 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
634 __skb_push(skb, offset);
636 /* compute pointers for the bpf prog */
637 bpf_compute_and_save_data_end(skb, &saved_data_end);
639 if (type == BPF_CGROUP_INET_EGRESS) {
640 ret = BPF_PROG_CGROUP_INET_EGRESS_RUN_ARRAY(
641 cgrp->bpf.effective[type], skb, __bpf_prog_run_save_cb);
643 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], skb,
644 __bpf_prog_run_save_cb);
645 ret = (ret == 1 ? 0 : -EPERM);
647 bpf_restore_data_end(skb, saved_data_end);
648 __skb_pull(skb, offset);
653 EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
656 * __cgroup_bpf_run_filter_sk() - Run a program on a sock
657 * @sk: sock structure to manipulate
658 * @type: The type of program to be exectuted
660 * socket is passed is expected to be of type INET or INET6.
662 * The program type passed in via @type must be suitable for sock
663 * filtering. No further check is performed to assert that.
665 * This function will return %-EPERM if any if an attached program was found
666 * and if it returned != 1 during execution. In all other cases, 0 is returned.
668 int __cgroup_bpf_run_filter_sk(struct sock *sk,
669 enum bpf_attach_type type)
671 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
674 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sk, BPF_PROG_RUN);
675 return ret == 1 ? 0 : -EPERM;
677 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
680 * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
681 * provided by user sockaddr
682 * @sk: sock struct that will use sockaddr
683 * @uaddr: sockaddr struct provided by user
684 * @type: The type of program to be exectuted
685 * @t_ctx: Pointer to attach type specific context
687 * socket is expected to be of type INET or INET6.
689 * This function will return %-EPERM if an attached program is found and
690 * returned value != 1 during execution. In all other cases, 0 is returned.
692 int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
693 struct sockaddr *uaddr,
694 enum bpf_attach_type type,
697 struct bpf_sock_addr_kern ctx = {
702 struct sockaddr_storage unspec;
706 /* Check socket family since not all sockets represent network
707 * endpoint (e.g. AF_UNIX).
709 if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
713 memset(&unspec, 0, sizeof(unspec));
714 ctx.uaddr = (struct sockaddr *)&unspec;
717 cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
718 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
720 return ret == 1 ? 0 : -EPERM;
722 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
725 * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
726 * @sk: socket to get cgroup from
727 * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
728 * sk with connection information (IP addresses, etc.) May not contain
729 * cgroup info if it is a req sock.
730 * @type: The type of program to be exectuted
732 * socket passed is expected to be of type INET or INET6.
734 * The program type passed in via @type must be suitable for sock_ops
735 * filtering. No further check is performed to assert that.
737 * This function will return %-EPERM if any if an attached program was found
738 * and if it returned != 1 during execution. In all other cases, 0 is returned.
740 int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
741 struct bpf_sock_ops_kern *sock_ops,
742 enum bpf_attach_type type)
744 struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
747 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], sock_ops,
749 return ret == 1 ? 0 : -EPERM;
751 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
753 int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
754 short access, enum bpf_attach_type type)
757 struct bpf_cgroup_dev_ctx ctx = {
758 .access_type = (access << 16) | dev_type,
765 cgrp = task_dfl_cgroup(current);
766 allow = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx,
772 EXPORT_SYMBOL(__cgroup_bpf_check_dev_permission);
774 static const struct bpf_func_proto *
775 cgroup_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
778 case BPF_FUNC_map_lookup_elem:
779 return &bpf_map_lookup_elem_proto;
780 case BPF_FUNC_map_update_elem:
781 return &bpf_map_update_elem_proto;
782 case BPF_FUNC_map_delete_elem:
783 return &bpf_map_delete_elem_proto;
784 case BPF_FUNC_map_push_elem:
785 return &bpf_map_push_elem_proto;
786 case BPF_FUNC_map_pop_elem:
787 return &bpf_map_pop_elem_proto;
788 case BPF_FUNC_map_peek_elem:
789 return &bpf_map_peek_elem_proto;
790 case BPF_FUNC_get_current_uid_gid:
791 return &bpf_get_current_uid_gid_proto;
792 case BPF_FUNC_get_local_storage:
793 return &bpf_get_local_storage_proto;
794 case BPF_FUNC_get_current_cgroup_id:
795 return &bpf_get_current_cgroup_id_proto;
796 case BPF_FUNC_trace_printk:
797 if (capable(CAP_SYS_ADMIN))
798 return bpf_get_trace_printk_proto();
805 static const struct bpf_func_proto *
806 cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
808 return cgroup_base_func_proto(func_id, prog);
811 static bool cgroup_dev_is_valid_access(int off, int size,
812 enum bpf_access_type type,
813 const struct bpf_prog *prog,
814 struct bpf_insn_access_aux *info)
816 const int size_default = sizeof(__u32);
818 if (type == BPF_WRITE)
821 if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
823 /* The verifier guarantees that size > 0. */
828 case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
829 bpf_ctx_record_field_size(info, size_default);
830 if (!bpf_ctx_narrow_access_ok(off, size, size_default))
834 if (size != size_default)
841 const struct bpf_prog_ops cg_dev_prog_ops = {
844 const struct bpf_verifier_ops cg_dev_verifier_ops = {
845 .get_func_proto = cgroup_dev_func_proto,
846 .is_valid_access = cgroup_dev_is_valid_access,
850 * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
852 * @head: sysctl table header
853 * @table: sysctl table
854 * @write: sysctl is being read (= 0) or written (= 1)
855 * @buf: pointer to buffer passed by user space
856 * @pcount: value-result argument: value is size of buffer pointed to by @buf,
857 * result is size of @new_buf if program set new value, initial value
859 * @ppos: value-result argument: value is position at which read from or write
860 * to sysctl is happening, result is new position if program overrode it,
861 * initial value otherwise
862 * @new_buf: pointer to pointer to new buffer that will be allocated if program
863 * overrides new value provided by user space on sysctl write
864 * NOTE: it's caller responsibility to free *new_buf if it was set
865 * @type: type of program to be executed
867 * Program is run when sysctl is being accessed, either read or written, and
868 * can allow or deny such access.
870 * This function will return %-EPERM if an attached program is found and
871 * returned value != 1 during execution. In all other cases 0 is returned.
873 int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
874 struct ctl_table *table, int write,
875 void __user *buf, size_t *pcount,
876 loff_t *ppos, void **new_buf,
877 enum bpf_attach_type type)
879 struct bpf_sysctl_kern ctx = {
885 .cur_len = PAGE_SIZE,
893 ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
900 if (table->proc_handler(table, 0, (void __user *)ctx.cur_val,
901 &ctx.cur_len, &pos)) {
902 /* Let BPF program decide how to proceed. */
907 /* Let BPF program decide how to proceed. */
911 if (write && buf && *pcount) {
912 /* BPF program should be able to override new value with a
913 * buffer bigger than provided by user.
915 ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
916 ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
918 copy_from_user(ctx.new_val, buf, ctx.new_len))
919 /* Let BPF program decide how to proceed. */
924 cgrp = task_dfl_cgroup(current);
925 ret = BPF_PROG_RUN_ARRAY(cgrp->bpf.effective[type], &ctx, BPF_PROG_RUN);
930 if (ret == 1 && ctx.new_updated) {
931 *new_buf = ctx.new_val;
932 *pcount = ctx.new_len;
937 return ret == 1 ? 0 : -EPERM;
939 EXPORT_SYMBOL(__cgroup_bpf_run_filter_sysctl);
941 static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
944 ssize_t tmp_ret = 0, ret;
946 if (dir->header.parent) {
947 tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
952 ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
959 /* Avoid leading slash. */
963 tmp_ret = strscpy(*bufp, "/", *lenp);
969 return ret + tmp_ret;
972 BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
973 size_t, buf_len, u64, flags)
975 ssize_t tmp_ret = 0, ret;
980 if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
983 tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
988 ret = strscpy(buf, ctx->table->procname, buf_len);
990 return ret < 0 ? ret : tmp_ret + ret;
993 static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
994 .func = bpf_sysctl_get_name,
996 .ret_type = RET_INTEGER,
997 .arg1_type = ARG_PTR_TO_CTX,
998 .arg2_type = ARG_PTR_TO_MEM,
999 .arg3_type = ARG_CONST_SIZE,
1000 .arg4_type = ARG_ANYTHING,
1003 static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
1012 if (!src || !src_len) {
1013 memset(dst, 0, dst_len);
1017 memcpy(dst, src, min(dst_len, src_len));
1019 if (dst_len > src_len) {
1020 memset(dst + src_len, '\0', dst_len - src_len);
1024 dst[dst_len - 1] = '\0';
1029 BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
1030 char *, buf, size_t, buf_len)
1032 return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
1035 static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
1036 .func = bpf_sysctl_get_current_value,
1038 .ret_type = RET_INTEGER,
1039 .arg1_type = ARG_PTR_TO_CTX,
1040 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
1041 .arg3_type = ARG_CONST_SIZE,
1044 BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
1049 memset(buf, '\0', buf_len);
1052 return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
1055 static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
1056 .func = bpf_sysctl_get_new_value,
1058 .ret_type = RET_INTEGER,
1059 .arg1_type = ARG_PTR_TO_CTX,
1060 .arg2_type = ARG_PTR_TO_UNINIT_MEM,
1061 .arg3_type = ARG_CONST_SIZE,
1064 BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
1065 const char *, buf, size_t, buf_len)
1067 if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
1070 if (buf_len > PAGE_SIZE - 1)
1073 memcpy(ctx->new_val, buf, buf_len);
1074 ctx->new_len = buf_len;
1075 ctx->new_updated = 1;
1080 static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
1081 .func = bpf_sysctl_set_new_value,
1083 .ret_type = RET_INTEGER,
1084 .arg1_type = ARG_PTR_TO_CTX,
1085 .arg2_type = ARG_PTR_TO_MEM,
1086 .arg3_type = ARG_CONST_SIZE,
1089 static const struct bpf_func_proto *
1090 sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1093 case BPF_FUNC_strtol:
1094 return &bpf_strtol_proto;
1095 case BPF_FUNC_strtoul:
1096 return &bpf_strtoul_proto;
1097 case BPF_FUNC_sysctl_get_name:
1098 return &bpf_sysctl_get_name_proto;
1099 case BPF_FUNC_sysctl_get_current_value:
1100 return &bpf_sysctl_get_current_value_proto;
1101 case BPF_FUNC_sysctl_get_new_value:
1102 return &bpf_sysctl_get_new_value_proto;
1103 case BPF_FUNC_sysctl_set_new_value:
1104 return &bpf_sysctl_set_new_value_proto;
1106 return cgroup_base_func_proto(func_id, prog);
1110 static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
1111 const struct bpf_prog *prog,
1112 struct bpf_insn_access_aux *info)
1114 const int size_default = sizeof(__u32);
1116 if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
1120 case offsetof(struct bpf_sysctl, write):
1121 if (type != BPF_READ)
1123 bpf_ctx_record_field_size(info, size_default);
1124 return bpf_ctx_narrow_access_ok(off, size, size_default);
1125 case offsetof(struct bpf_sysctl, file_pos):
1126 if (type == BPF_READ) {
1127 bpf_ctx_record_field_size(info, size_default);
1128 return bpf_ctx_narrow_access_ok(off, size, size_default);
1130 return size == size_default;
1137 static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
1138 const struct bpf_insn *si,
1139 struct bpf_insn *insn_buf,
1140 struct bpf_prog *prog, u32 *target_size)
1142 struct bpf_insn *insn = insn_buf;
1145 case offsetof(struct bpf_sysctl, write):
1146 *insn++ = BPF_LDX_MEM(
1147 BPF_SIZE(si->code), si->dst_reg, si->src_reg,
1148 bpf_target_off(struct bpf_sysctl_kern, write,
1149 FIELD_SIZEOF(struct bpf_sysctl_kern,
1153 case offsetof(struct bpf_sysctl, file_pos):
1154 /* ppos is a pointer so it should be accessed via indirect
1155 * loads and stores. Also for stores additional temporary
1156 * register is used since neither src_reg nor dst_reg can be
1159 if (type == BPF_WRITE) {
1160 int treg = BPF_REG_9;
1162 if (si->src_reg == treg || si->dst_reg == treg)
1164 if (si->src_reg == treg || si->dst_reg == treg)
1166 *insn++ = BPF_STX_MEM(
1167 BPF_DW, si->dst_reg, treg,
1168 offsetof(struct bpf_sysctl_kern, tmp_reg));
1169 *insn++ = BPF_LDX_MEM(
1170 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1172 offsetof(struct bpf_sysctl_kern, ppos));
1173 *insn++ = BPF_STX_MEM(
1174 BPF_SIZEOF(u32), treg, si->src_reg, 0);
1175 *insn++ = BPF_LDX_MEM(
1176 BPF_DW, treg, si->dst_reg,
1177 offsetof(struct bpf_sysctl_kern, tmp_reg));
1179 *insn++ = BPF_LDX_MEM(
1180 BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
1181 si->dst_reg, si->src_reg,
1182 offsetof(struct bpf_sysctl_kern, ppos));
1183 *insn++ = BPF_LDX_MEM(
1184 BPF_SIZE(si->code), si->dst_reg, si->dst_reg, 0);
1186 *target_size = sizeof(u32);
1190 return insn - insn_buf;
1193 const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
1194 .get_func_proto = sysctl_func_proto,
1195 .is_valid_access = sysctl_is_valid_access,
1196 .convert_ctx_access = sysctl_convert_ctx_access,
1199 const struct bpf_prog_ops cg_sysctl_prog_ops = {