1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (c) 2019 Netronome Systems, Inc. */
10 #include <sys/capability.h>
12 #include <sys/utsname.h>
15 #include <linux/filter.h>
16 #include <linux/limits.h>
19 #include <bpf/libbpf.h>
24 #ifndef PROC_SUPER_MAGIC
25 # define PROC_SUPER_MAGIC 0x9fa0
28 enum probe_component {
34 #define BPF_HELPER_MAKE_ENTRY(name) [BPF_FUNC_ ## name] = "bpf_" # name
35 static const char * const helper_name[] = {
36 __BPF_FUNC_MAPPER(BPF_HELPER_MAKE_ENTRY)
39 #undef BPF_HELPER_MAKE_ENTRY
41 static bool full_mode;
43 static bool run_as_unprivileged;
46 /* Miscellaneous utility functions */
48 static bool check_procfs(void)
52 if (statfs("/proc", &st_fs) < 0)
54 if ((unsigned long)st_fs.f_type != PROC_SUPER_MAGIC)
60 static void uppercase(char *str, size_t len)
64 for (i = 0; i < len && str[i] != '\0'; i++)
65 str[i] = toupper(str[i]);
68 /* Printing utility functions */
71 print_bool_feature(const char *feat_name, const char *plain_name,
72 const char *define_name, bool res, const char *define_prefix)
75 jsonw_bool_field(json_wtr, feat_name, res);
76 else if (define_prefix)
77 printf("#define %s%sHAVE_%s\n", define_prefix,
78 res ? "" : "NO_", define_name);
80 printf("%s is %savailable\n", plain_name, res ? "" : "NOT ");
83 static void print_kernel_option(const char *name, const char *value,
84 const char *define_prefix)
91 jsonw_null_field(json_wtr, name);
95 res = strtol(value, &endptr, 0);
96 if (!errno && *endptr == '\n')
97 jsonw_int_field(json_wtr, name, res);
99 jsonw_string_field(json_wtr, name, value);
100 } else if (define_prefix) {
102 printf("#define %s%s %s\n", define_prefix,
105 printf("/* %s%s is not set */\n", define_prefix, name);
108 printf("%s is set to %s\n", name, value);
110 printf("%s is not set\n", name);
115 print_start_section(const char *json_title, const char *plain_title,
116 const char *define_comment, const char *define_prefix)
119 jsonw_name(json_wtr, json_title);
120 jsonw_start_object(json_wtr);
121 } else if (define_prefix) {
122 printf("%s\n", define_comment);
124 printf("%s\n", plain_title);
128 static void print_end_section(void)
131 jsonw_end_object(json_wtr);
136 /* Probing functions */
138 static int read_procfs(const char *path)
140 char *endptr, *line = NULL;
145 fd = fopen(path, "r");
149 res = getline(&line, &len, fd);
155 res = strtol(line, &endptr, 10);
156 if (errno || *line == '\0' || *endptr != '\n')
163 static void probe_unprivileged_disabled(void)
167 /* No support for C-style ouptut */
169 res = read_procfs("/proc/sys/kernel/unprivileged_bpf_disabled");
171 jsonw_int_field(json_wtr, "unprivileged_bpf_disabled", res);
175 printf("bpf() syscall for unprivileged users is enabled\n");
178 printf("bpf() syscall restricted to privileged users\n");
181 printf("Unable to retrieve required privileges for bpf() syscall\n");
184 printf("bpf() syscall restriction has unknown value %d\n", res);
189 static void probe_jit_enable(void)
193 /* No support for C-style ouptut */
195 res = read_procfs("/proc/sys/net/core/bpf_jit_enable");
197 jsonw_int_field(json_wtr, "bpf_jit_enable", res);
201 printf("JIT compiler is disabled\n");
204 printf("JIT compiler is enabled\n");
207 printf("JIT compiler is enabled with debugging traces in kernel logs\n");
210 printf("Unable to retrieve JIT-compiler status\n");
213 printf("JIT-compiler status has unknown value %d\n",
219 static void probe_jit_harden(void)
223 /* No support for C-style ouptut */
225 res = read_procfs("/proc/sys/net/core/bpf_jit_harden");
227 jsonw_int_field(json_wtr, "bpf_jit_harden", res);
231 printf("JIT compiler hardening is disabled\n");
234 printf("JIT compiler hardening is enabled for unprivileged users\n");
237 printf("JIT compiler hardening is enabled for all users\n");
240 printf("Unable to retrieve JIT hardening status\n");
243 printf("JIT hardening status has unknown value %d\n",
249 static void probe_jit_kallsyms(void)
253 /* No support for C-style ouptut */
255 res = read_procfs("/proc/sys/net/core/bpf_jit_kallsyms");
257 jsonw_int_field(json_wtr, "bpf_jit_kallsyms", res);
261 printf("JIT compiler kallsyms exports are disabled\n");
264 printf("JIT compiler kallsyms exports are enabled for root\n");
267 printf("Unable to retrieve JIT kallsyms export status\n");
270 printf("JIT kallsyms exports status has unknown value %d\n", res);
275 static void probe_jit_limit(void)
279 /* No support for C-style ouptut */
281 res = read_procfs("/proc/sys/net/core/bpf_jit_limit");
283 jsonw_int_field(json_wtr, "bpf_jit_limit", res);
287 printf("Unable to retrieve global memory limit for JIT compiler for unprivileged users\n");
290 printf("Global memory limit for JIT compiler for unprivileged users is %d bytes\n", res);
295 static bool read_next_kernel_config_option(gzFile file, char *buf, size_t n,
300 while (gzgets(file, buf, n)) {
301 if (strncmp(buf, "CONFIG_", 7))
304 sep = strchr(buf, '=');
308 /* Trim ending '\n' */
309 buf[strlen(buf) - 1] = '\0';
311 /* Split on '=' and ensure that a value is present. */
323 static void probe_kernel_image_config(const char *define_prefix)
325 static const struct {
326 const char * const name;
331 /* Enable bpf() syscall */
332 { "CONFIG_BPF_SYSCALL", },
333 /* Does selected architecture support eBPF JIT compiler */
334 { "CONFIG_HAVE_EBPF_JIT", },
335 /* Compile eBPF JIT compiler */
336 { "CONFIG_BPF_JIT", },
337 /* Avoid compiling eBPF interpreter (use JIT only) */
338 { "CONFIG_BPF_JIT_ALWAYS_ON", },
341 { "CONFIG_CGROUPS", },
342 /* BPF programs attached to cgroups */
343 { "CONFIG_CGROUP_BPF", },
344 /* bpf_get_cgroup_classid() helper */
345 { "CONFIG_CGROUP_NET_CLASSID", },
346 /* bpf_skb_{,ancestor_}cgroup_id() helpers */
347 { "CONFIG_SOCK_CGROUP_DATA", },
349 /* Tracing: attach BPF to kprobes, tracepoints, etc. */
350 { "CONFIG_BPF_EVENTS", },
352 { "CONFIG_KPROBE_EVENTS", },
354 { "CONFIG_UPROBE_EVENTS", },
356 { "CONFIG_TRACING", },
357 /* Syscall tracepoints */
358 { "CONFIG_FTRACE_SYSCALLS", },
359 /* bpf_override_return() helper support for selected arch */
360 { "CONFIG_FUNCTION_ERROR_INJECTION", },
361 /* bpf_override_return() helper */
362 { "CONFIG_BPF_KPROBE_OVERRIDE", },
367 { "CONFIG_XDP_SOCKETS", },
368 /* BPF_PROG_TYPE_LWT_* and related helpers */
369 { "CONFIG_LWTUNNEL_BPF", },
370 /* BPF_PROG_TYPE_SCHED_ACT, TC (traffic control) actions */
371 { "CONFIG_NET_ACT_BPF", },
372 /* BPF_PROG_TYPE_SCHED_CLS, TC filters */
373 { "CONFIG_NET_CLS_BPF", },
374 /* TC clsact qdisc */
375 { "CONFIG_NET_CLS_ACT", },
376 /* Ingress filtering with TC */
377 { "CONFIG_NET_SCH_INGRESS", },
378 /* bpf_skb_get_xfrm_state() helper */
380 /* bpf_get_route_realm() helper */
381 { "CONFIG_IP_ROUTE_CLASSID", },
382 /* BPF_PROG_TYPE_LWT_SEG6_LOCAL and related helpers */
383 { "CONFIG_IPV6_SEG6_BPF", },
384 /* BPF_PROG_TYPE_LIRC_MODE2 and related helpers */
385 { "CONFIG_BPF_LIRC_MODE2", },
386 /* BPF stream parser and BPF socket maps */
387 { "CONFIG_BPF_STREAM_PARSER", },
388 /* xt_bpf module for passing BPF programs to netfilter */
389 { "CONFIG_NETFILTER_XT_MATCH_BPF", },
390 /* bpfilter back-end for iptables */
391 { "CONFIG_BPFILTER", },
392 /* bpftilter module with "user mode helper" */
393 { "CONFIG_BPFILTER_UMH", },
395 /* test_bpf module for BPF tests */
396 { "CONFIG_TEST_BPF", },
398 /* Misc configs useful in BPF C programs */
399 /* jiffies <-> sec conversion for bpf_jiffies64() helper */
400 { "CONFIG_HZ", true, }
402 char *values[ARRAY_SIZE(options)] = { };
411 snprintf(path, sizeof(path), "/boot/config-%s", utsn.release);
413 /* gzopen also accepts uncompressed files. */
414 file = gzopen(path, "r");
418 /* Some distributions build with CONFIG_IKCONFIG=y and put the
419 * config file at /proc/config.gz.
421 file = gzopen("/proc/config.gz", "r");
424 p_info("skipping kernel config, can't open file: %s",
429 if (!gzgets(file, buf, sizeof(buf)) ||
430 !gzgets(file, buf, sizeof(buf))) {
431 p_info("skipping kernel config, can't read from file: %s",
435 if (strcmp(buf, "# Automatically generated file; DO NOT EDIT.\n")) {
436 p_info("skipping kernel config, can't find correct file");
440 while (read_next_kernel_config_option(file, buf, sizeof(buf), &value)) {
441 for (i = 0; i < ARRAY_SIZE(options); i++) {
442 if ((define_prefix && !options[i].macro_dump) ||
443 values[i] || strcmp(buf, options[i].name))
446 values[i] = strdup(value);
454 for (i = 0; i < ARRAY_SIZE(options); i++) {
455 if (define_prefix && !options[i].macro_dump)
457 print_kernel_option(options[i].name, values[i], define_prefix);
462 static bool probe_bpf_syscall(const char *define_prefix)
466 bpf_load_program(BPF_PROG_TYPE_UNSPEC, NULL, 0, NULL, 0, NULL, 0);
467 res = (errno != ENOSYS);
469 print_bool_feature("have_bpf_syscall",
478 probe_prog_type(enum bpf_prog_type prog_type, bool *supported_types,
479 const char *define_prefix, __u32 ifindex)
481 char feat_name[128], plain_desc[128], define_name[128];
482 const char *plain_comment = "eBPF program_type ";
487 /* Only test offload-able program types */
489 case BPF_PROG_TYPE_SCHED_CLS:
490 case BPF_PROG_TYPE_XDP:
496 res = bpf_probe_prog_type(prog_type, ifindex);
498 /* Probe may succeed even if program load fails, for unprivileged users
499 * check that we did not fail because of insufficient permissions
501 if (run_as_unprivileged && errno == EPERM)
505 supported_types[prog_type] |= res;
507 if (!prog_type_name[prog_type]) {
508 p_info("program type name not found (type %d)", prog_type);
511 maxlen = sizeof(plain_desc) - strlen(plain_comment) - 1;
512 if (strlen(prog_type_name[prog_type]) > maxlen) {
513 p_info("program type name too long");
517 sprintf(feat_name, "have_%s_prog_type", prog_type_name[prog_type]);
518 sprintf(define_name, "%s_prog_type", prog_type_name[prog_type]);
519 uppercase(define_name, sizeof(define_name));
520 sprintf(plain_desc, "%s%s", plain_comment, prog_type_name[prog_type]);
521 print_bool_feature(feat_name, plain_desc, define_name, res,
526 probe_map_type(enum bpf_map_type map_type, const char *define_prefix,
529 char feat_name[128], plain_desc[128], define_name[128];
530 const char *plain_comment = "eBPF map_type ";
534 res = bpf_probe_map_type(map_type, ifindex);
536 /* Probe result depends on the success of map creation, no additional
537 * check required for unprivileged users
540 if (!map_type_name[map_type]) {
541 p_info("map type name not found (type %d)", map_type);
544 maxlen = sizeof(plain_desc) - strlen(plain_comment) - 1;
545 if (strlen(map_type_name[map_type]) > maxlen) {
546 p_info("map type name too long");
550 sprintf(feat_name, "have_%s_map_type", map_type_name[map_type]);
551 sprintf(define_name, "%s_map_type", map_type_name[map_type]);
552 uppercase(define_name, sizeof(define_name));
553 sprintf(plain_desc, "%s%s", plain_comment, map_type_name[map_type]);
554 print_bool_feature(feat_name, plain_desc, define_name, res,
559 probe_helper_for_progtype(enum bpf_prog_type prog_type, bool supported_type,
560 const char *define_prefix, unsigned int id,
561 const char *ptype_name, __u32 ifindex)
565 if (supported_type) {
566 res = bpf_probe_helper(id, prog_type, ifindex);
568 /* Probe may succeed even if program load fails, for
569 * unprivileged users check that we did not fail because of
570 * insufficient permissions
572 if (run_as_unprivileged && errno == EPERM)
579 jsonw_string(json_wtr, helper_name[id]);
580 } else if (define_prefix) {
581 printf("#define %sBPF__PROG_TYPE_%s__HELPER_%s %s\n",
582 define_prefix, ptype_name, helper_name[id],
586 printf("\n\t- %s", helper_name[id]);
591 probe_helpers_for_progtype(enum bpf_prog_type prog_type, bool supported_type,
592 const char *define_prefix, __u32 ifindex)
594 const char *ptype_name = prog_type_name[prog_type];
599 /* Only test helpers for offload-able program types */
601 case BPF_PROG_TYPE_SCHED_CLS:
602 case BPF_PROG_TYPE_XDP:
609 sprintf(feat_name, "%s_available_helpers", ptype_name);
610 jsonw_name(json_wtr, feat_name);
611 jsonw_start_array(json_wtr);
612 } else if (!define_prefix) {
613 printf("eBPF helpers supported for program type %s:",
617 for (id = 1; id < ARRAY_SIZE(helper_name); id++) {
618 /* Skip helper functions which emit dmesg messages when not in
622 case BPF_FUNC_trace_printk:
623 case BPF_FUNC_probe_write_user:
628 probe_helper_for_progtype(prog_type, supported_type,
629 define_prefix, id, ptype_name,
635 jsonw_end_array(json_wtr);
636 else if (!define_prefix)
641 probe_large_insn_limit(const char *define_prefix, __u32 ifindex)
645 res = bpf_probe_large_insn_limit(ifindex);
646 print_bool_feature("have_large_insn_limit",
647 "Large program size limit",
653 section_system_config(enum probe_component target, const char *define_prefix)
656 case COMPONENT_KERNEL:
657 case COMPONENT_UNSPEC:
658 print_start_section("system_config",
659 "Scanning system configuration...",
660 "/*** Misc kernel config items ***/",
662 if (!define_prefix) {
663 if (check_procfs()) {
664 probe_unprivileged_disabled();
667 probe_jit_kallsyms();
670 p_info("/* procfs not mounted, skipping related probes */");
673 probe_kernel_image_config(define_prefix);
681 static bool section_syscall_config(const char *define_prefix)
685 print_start_section("syscall_config",
686 "Scanning system call availability...",
687 "/*** System call availability ***/",
689 res = probe_bpf_syscall(define_prefix);
696 section_program_types(bool *supported_types, const char *define_prefix,
701 print_start_section("program_types",
702 "Scanning eBPF program types...",
703 "/*** eBPF program types ***/",
706 for (i = BPF_PROG_TYPE_UNSPEC + 1; i < prog_type_name_size; i++)
707 probe_prog_type(i, supported_types, define_prefix, ifindex);
712 static void section_map_types(const char *define_prefix, __u32 ifindex)
716 print_start_section("map_types",
717 "Scanning eBPF map types...",
718 "/*** eBPF map types ***/",
721 for (i = BPF_MAP_TYPE_UNSPEC + 1; i < map_type_name_size; i++)
722 probe_map_type(i, define_prefix, ifindex);
728 section_helpers(bool *supported_types, const char *define_prefix, __u32 ifindex)
732 print_start_section("helpers",
733 "Scanning eBPF helper functions...",
734 "/*** eBPF helper functions ***/",
739 " * Use %sHAVE_PROG_TYPE_HELPER(prog_type_name, helper_name)\n"
740 " * to determine if <helper_name> is available for <prog_type_name>,\n"
742 " * #if %sHAVE_PROG_TYPE_HELPER(xdp, bpf_redirect)\n"
743 " * // do stuff with this helper\n"
745 " * // use a workaround\n"
748 "#define %sHAVE_PROG_TYPE_HELPER(prog_type, helper) \\\n"
749 " %sBPF__PROG_TYPE_ ## prog_type ## __HELPER_ ## helper\n",
750 define_prefix, define_prefix, define_prefix,
752 for (i = BPF_PROG_TYPE_UNSPEC + 1; i < prog_type_name_size; i++)
753 probe_helpers_for_progtype(i, supported_types[i], define_prefix,
759 static void section_misc(const char *define_prefix, __u32 ifindex)
761 print_start_section("misc",
762 "Scanning miscellaneous eBPF features...",
763 "/*** eBPF misc features ***/",
765 probe_large_insn_limit(define_prefix, ifindex);
770 #define capability(c) { c, false, #c }
771 #define capability_msg(a, i) a[i].set ? "" : a[i].name, a[i].set ? "" : ", "
774 static int handle_perms(void)
780 char name[14]; /* strlen("CAP_SYS_ADMIN") */
782 capability(CAP_SYS_ADMIN),
785 capability(CAP_NET_ADMIN),
786 capability(CAP_PERFMON),
789 cap_value_t cap_list[ARRAY_SIZE(bpf_caps)];
790 unsigned int i, nb_bpf_caps = 0;
791 bool cap_sys_admin_only = true;
792 cap_flag_value_t val;
796 caps = cap_get_proc();
798 p_err("failed to get capabilities for process: %s",
804 if (CAP_IS_SUPPORTED(CAP_BPF))
805 cap_sys_admin_only = false;
808 for (i = 0; i < ARRAY_SIZE(bpf_caps); i++) {
809 const char *cap_name = bpf_caps[i].name;
810 cap_value_t cap = bpf_caps[i].cap;
812 if (cap_get_flag(caps, cap, CAP_EFFECTIVE, &val)) {
813 p_err("bug: failed to retrieve %s status: %s", cap_name,
818 if (val == CAP_SET) {
819 bpf_caps[i].set = true;
820 cap_list[nb_bpf_caps++] = cap;
823 if (cap_sys_admin_only)
824 /* System does not know about CAP_BPF, meaning that
825 * CAP_SYS_ADMIN is the only capability required. We
826 * just checked it, break.
831 if ((run_as_unprivileged && !nb_bpf_caps) ||
832 (!run_as_unprivileged && nb_bpf_caps == ARRAY_SIZE(bpf_caps)) ||
833 (!run_as_unprivileged && cap_sys_admin_only && nb_bpf_caps)) {
834 /* We are all good, exit now */
839 if (!run_as_unprivileged) {
840 if (cap_sys_admin_only)
841 p_err("missing %s, required for full feature probing; run as root or use 'unprivileged'",
844 p_err("missing %s%s%s%s%s%s%s%srequired for full feature probing; run as root or use 'unprivileged'",
845 capability_msg(bpf_caps, 0),
846 capability_msg(bpf_caps, 1),
847 capability_msg(bpf_caps, 2),
848 capability_msg(bpf_caps, 3));
852 /* if (run_as_unprivileged && nb_bpf_caps > 0), drop capabilities. */
853 if (cap_set_flag(caps, CAP_EFFECTIVE, nb_bpf_caps, cap_list,
855 p_err("bug: failed to clear capabilities: %s", strerror(errno));
859 if (cap_set_proc(caps)) {
860 p_err("failed to drop capabilities: %s", strerror(errno));
867 if (cap_free(caps) && !res) {
868 p_err("failed to clear storage object for capabilities: %s",
875 /* Detection assumes user has specific privileges.
876 * We do not use libpcap so let's approximate, and restrict usage to
880 p_err("full feature probing requires root privileges");
885 #endif /* USE_LIBCAP */
888 static int do_probe(int argc, char **argv)
890 enum probe_component target = COMPONENT_UNSPEC;
891 const char *define_prefix = NULL;
892 bool supported_types[128] = {};
899 if (is_prefix(*argv, "kernel")) {
900 if (target != COMPONENT_UNSPEC) {
901 p_err("component to probe already specified");
904 target = COMPONENT_KERNEL;
906 } else if (is_prefix(*argv, "dev")) {
909 if (target != COMPONENT_UNSPEC || ifindex) {
910 p_err("component to probe already specified");
916 target = COMPONENT_DEVICE;
918 ifindex = if_nametoindex(ifname);
920 p_err("unrecognized netdevice '%s': %s", ifname,
924 } else if (is_prefix(*argv, "full")) {
927 } else if (is_prefix(*argv, "macros") && !define_prefix) {
930 } else if (is_prefix(*argv, "prefix")) {
931 if (!define_prefix) {
932 p_err("'prefix' argument can only be use after 'macros'");
935 if (strcmp(define_prefix, "")) {
936 p_err("'prefix' already defined");
943 define_prefix = GET_ARG();
944 } else if (is_prefix(*argv, "unprivileged")) {
946 run_as_unprivileged = true;
949 p_err("unprivileged run not supported, recompile bpftool with libcap");
953 p_err("expected no more arguments, 'kernel', 'dev', 'macros' or 'prefix', got: '%s'?",
959 /* Full feature detection requires specific privileges.
960 * Let's approximate, and warn if user is not root.
966 define_prefix = NULL;
967 jsonw_start_object(json_wtr);
970 section_system_config(target, define_prefix);
971 if (!section_syscall_config(define_prefix))
972 /* bpf() syscall unavailable, don't probe other BPF features */
973 goto exit_close_json;
974 section_program_types(supported_types, define_prefix, ifindex);
975 section_map_types(define_prefix, ifindex);
976 section_helpers(supported_types, define_prefix, ifindex);
977 section_misc(define_prefix, ifindex);
981 /* End root object */
982 jsonw_end_object(json_wtr);
987 static int do_help(int argc, char **argv)
990 jsonw_null(json_wtr);
995 "Usage: %1$s %2$s probe [COMPONENT] [full] [unprivileged] [macros [prefix PREFIX]]\n"
998 " COMPONENT := { kernel | dev NAME }\n"
1000 bin_name, argv[-2]);
1005 static const struct cmd cmds[] = {
1006 { "probe", do_probe },
1007 { "help", do_help },
1011 int do_feature(int argc, char **argv)
1013 return cmd_select(cmds, argc, argv, do_help);