Skip to contentSkip to conversation

bpf, x86: Drop the PROBE_MEM address range check under SMAP

PATCH In review Kumar Kartikeya Dwivedi 2 participants 8 messages Nov 28

Subsystems (7)
x86 Kselftest BPF BPF selftests +3 more subsystems
lore
Share & tools
lore

Kumar Kartikeya Dwivedi

author maintainer
#0 lore raw

v2 cover bpf, x86: Drop the PROBE_MEM address range check under SMAP

GPL-compatible BPF programs loaded with CAP_PERFMON can read through pointers that the verifier cannot prove valid. The verifier marks such loads PROBE_MEM and the JIT gives each one an exception table entry: on a fault, the destination register is zeroed and the program continues. Each load is a single mov, movzx, movsx or movsxd into a register, and it is not retried.

On x86 this does not work for user addresses. With SMAP, a kernel-mode fault on a user address oopses without looking at the exception table, so the JIT puts a range check in front of every PROBE_MEM load: five instructions and 17 or 18 bytes, for a load of three to eight bytes.

Patch 1 lets do_user_addr_fault() fix up such a fault when it came from kernel mode, is a read, and the faulting instruction has an EX_TYPE_BPF exception table entry. Every other fault there still oopses. Patch 2 drops the range check from the JIT when SMAP is enabled. Patch 3 adds a selftest that reads through NULL, user, guard page, non-canonical and vsyscall addresses. It oopses on a kernel with only patch 2 applied.

Limits:

* Kernels without SMAP keep the range check.
* Programs loaded without CAP_BPF keep it too. They are not in kallsyms, so the fault handler cannot find their exception table.
* The addresses a program can read do not change. SMAP still refuses user memory. MMIO and, in confidential guests, unaccepted pages are filtered neither by the range check nor by copy_from_kernel_nofault(), before or after the series. Patch 1 has a table.

Patch 2 depends on patch 1, so the series is meant for bpf-next as a whole. Patch 1 needs an x86 Ack.

Results
-------

JITed code size from veristat, on one kernel booted with and without clearcpuid=smap (bpf-next at 8dfce13340ae with the series), over the BPF selftests and 474 production objects from Meta:

programs with PROBE_MEM reduction per program
mean median max

  BPF selftests             5486             100  20.2%  19.9%  58.2%
  Meta production programs  1942             262   3.5%   0.8%  51.4%

No program grows. Most programs are unchanged, because loads through trusted pointers and the probe_read helpers do not use PROBE_MEM.

The branchless mask Peter suggested for v3 (lea, mov, sar, inc, and, dec, no x86/mm change) was measured the same way on bpf-next at 0fb18ce8a2e9. It is larger than the current range check: programs with PROBE_MEM loads grow by 2.9% on average in the selftests and by 0.5% in production. It also lets the vsyscall page through, so such a load still oopses under SMAP, and the selftest from patch 3 crashes that kernel at that address.

BPF selftests:

Largest relative savings (JITed bytes before->after, saved, percent):

  type_cast/md_xdp                                    584->  244   -340  -58.2%
  connect_unix_prog/connect_unix_prog                1075->  571   -504  -46.9%
  sendmsg_unix_prog/sendmsg_unix_prog                1075->  571   -504  -46.9%
  test_lwt_ip_encap/fexit_lwt_push_ip_encap           362->  205   -157  -43.4%
  sock_iter_batch/iter_udp_soreuse                    548->  327   -221  -40.3%
  test_skc_to_unix_sock/unix_listen                   330->  205   -125  -37.9%
  bpf_smc/bpf_smc_release                              90->   56    -34  -37.8%
  cgrp_ls_attach_cgroup/update_cookie_tracing         183->  115    -68  -37.2%
  verifier_typedef/resolve_typedef                     48->   31    -17  -35.4%
  bpf_iter_vma_offset/get_vma_offset                  369->  240   -129  -35.0%
  type_cast/md_skb                                    198->  130    -68  -34.3%
  kfree_skb/fentry_eth_type_trans                     102->   68    -34  -33.3%
  socket_cookie_prog/update_cookie_tracing            156->  105    -51  -32.7%
  bpf_iter_tcp6/dump_tcp6                            3142-> 2129  -1013  -32.2%
  mptcp_sock/_sockops                                 410->  280   -130  -31.7%
  plain_c_mptcp_subflow/_getsockopt_subflow          1433->  980   -453  -31.6%
  mptcp_subflow/_getsockopt_subflow                  1462-> 1012   -450  -30.8%
  mem_rdonly_untrusted/btf_id_to_ptr_mem              118->   82    -36  -30.5%
  sock_iter_batch/iter_tcp_soreuse                   1025->  714   -311  -30.3%
  test_signed_loader_lsm/inspect_prog_load            197->  138    -59  -29.9%
  bpf_iter_task_file/dump_task_file                   464->  328   -136  -29.3%
  verifier_kfunc_perfmon/rdonly_cast_noperfmon         59->   42    -17  -28.8%
  bpf_iter_ksym/dump_ksym                             900->  642   -258  -28.7%
  plain_c_test_wakeup_source/iterate_wakeupsources    719->  513   -206  -28.7%
  kfree_skb/fexit_eth_type_trans                      119->   85    -34  -28.6%
  bpf_iter_unix/dump_unix                             897->  641   -256  -28.5%
  bpf_iter_ipv6_route/dump_ipv6_route                 725->  519   -206  -28.4%
  bpf_iter_tcp4/dump_tcp4                            2621-> 1914   -707  -27.0%
  bpf_iter_bpf_sk_storage_helpers/fill_socket_owner   127->   93    -34  -26.8%
  bpf_iter_netlink/dump_netlink                       660->  490   -170  -25.8%
  sk_storage_omem_uncharge/bpf_sk_storage_free        135->  101    -34  -25.2%
  bpf_iter_setsockopt/change_tcp_cc                   409->  307   -102  -24.9%
  bpf_iter_task_vmas/proc_maps                        766->  577   -189  -24.7%
  fentry_test/test8                                    70->   53    -17  -24.3%
  fexit_test/test8                                     70->   53    -17  -24.3%
  mptcp_sock/trace_mptcp_pm_new_connection             70->   53    -17  -24.3%
  test_wakeup_source/iterate_wakeupsources            867->  660   -207  -23.9%
  core_kern/fentry_eth_type_trans                     219->  168    -51  -23.3%
  core_kern/fexit_eth_type_trans                      219->  168    -51  -23.3%
  rcu_read_lock/rcu_untrusted_union_ld                 73->   56    -17  -23.3%
  lsm/test_sys_setdomainname                          148->  114    -34  -23.0%
  lsm_bdev/bdev_free_security                          74->   57    -17  -23.0%
  plain_c_mem_rdonly_untrusted/offset_not_tracked      75->   58    -17  -22.7%
  bpf_smc/bpf_smc_switch_to_fallback                   77->   60    -17  -22.1%
  verifier_kfunc_perfmon/arg_untrusted_read_noperf~    77->   60    -17  -22.1%
  verifier_btf_array_access/flex_array_far_join        78->   61    -17  -21.8%
  bpf_iter_setsockopt_unix/change_sndbuf              822->  644   -178  -21.7%
  btf_type_tag_percpu/test_percpu_helper               81->   64    -17  -21.0%
  bpf_smc/smc_run                                     167->  133    -34  -20.4%
  find_vma/handle_getpid                              342->  274    -68  -19.9%

Largest absolute savings (JITed bytes before->after, saved, percent):

  bpf_iter_tcp6/dump_tcp6                            3142-> 2129  -1013  -32.2%
  bpf_iter_tcp4/dump_tcp4                            2621-> 1914   -707  -27.0%
  connect_unix_prog/connect_unix_prog                1075->  571   -504  -46.9%
  sendmsg_unix_prog/sendmsg_unix_prog                1075->  571   -504  -46.9%
  plain_c_mptcp_subflow/_getsockopt_subflow          1433->  980   -453  -31.6%
  mptcp_subflow/_getsockopt_subflow                  1462-> 1012   -450  -30.8%
  type_cast/md_xdp                                    584->  244   -340  -58.2%
  sock_iter_batch/iter_tcp_soreuse                   1025->  714   -311  -30.3%
  setget_sockopt/skops_sockopt                       4862-> 4563   -299   -6.1%
  bpf_iter_ksym/dump_ksym                             900->  642   -258  -28.7%
  bpf_iter_unix/dump_unix                             897->  641   -256  -28.5%
  sock_iter_batch/iter_udp_soreuse                    548->  327   -221  -40.3%
  test_wakeup_source/iterate_wakeupsources            867->  660   -207  -23.9%
  bpf_iter_ipv6_route/dump_ipv6_route                 725->  519   -206  -28.4%
  plain_c_test_wakeup_source/iterate_wakeupsources    719->  513   -206  -28.7%
  bpf_iter_task_vmas/proc_maps                        766->  577   -189  -24.7%
  bpf_iter_setsockopt_unix/change_sndbuf              822->  644   -178  -21.7%
  bpf_iter_netlink/dump_netlink                       660->  490   -170  -25.8%
  test_lwt_ip_encap/fexit_lwt_push_ip_encap           362->  205   -157  -43.4%
  bpf_iter_task_file/dump_task_file                   464->  328   -136  -29.3%
  mptcp_sock/_sockops                                 410->  280   -130  -31.7%
  bpf_iter_vma_offset/get_vma_offset                  369->  240   -129  -35.0%
  test_skc_to_unix_sock/unix_listen                   330->  205   -125  -37.9%
  test_tc_tunnel/decap_f                             1074->  955   -119  -11.1%
  bpf_iter_setsockopt/change_tcp_cc                   409->  307   -102  -24.9%
  kfree_skb/trace_kfree_skb                           479->  409    -70  -14.6%
  cgroup_hierarchical_stats/flusher                   430->  361    -69  -16.0%
  bpf_ma_ttrace/check_ttrace                          548->  480    -68  -12.4%
  cgrp_ls_attach_cgroup/update_cookie_tracing         183->  115    -68  -37.2%
  find_vma/handle_getpid                              342->  274    -68  -19.9%
  find_vma/handle_pe                                  342->  274    -68  -19.9%
  net_timestamping/skops_sockopt                     1043->  975    -68   -6.5%
  plain_c_bpf_ma_ttrace/check_ttrace                  397->  329    -68  -17.1%
  type_cast/md_skb                                    198->  130    -68  -34.3%
  test_signed_loader_lsm/inspect_prog_load            197->  138    -59  -29.9%
  bpf_qdisc_fq/bpf_fq_init                            765->  713    -52   -6.8%
  plain_c_bpf_qdisc_fq/bpf_fq_init                    765->  713    -52   -6.8%
  core_kern/fentry_eth_type_trans                     219->  168    -51  -23.3%
  core_kern/fexit_eth_type_trans                      219->  168    -51  -23.3%
  sk_bypass_prot_mem/fentry_tcp_init_sock             357->  306    -51  -14.3%
  sk_bypass_prot_mem/fentry_udp_init_sock             357->  306    -51  -14.3%
  socket_cookie_prog/update_cookie_tracing            156->  105    -51  -32.7%
  tcp_autolowat/tcp_autolowat_enqueue_rcvq            670->  619    -51   -7.6%
  test_ksyms_btf/handler                              300->  249    -51  -17.0%
  verifier_global_ptr_args/anything_to_untrusted_m~   313->  262    -51  -16.3%
  test_tcpbpf_kern/bpf_testcb                        1029->  989    -40   -3.9%
  test_cgroup1_hierarchy/lsm_s_run                    306->  267    -39  -12.7%
  cgroup_ancestor/log_cgroup_id                       196->  158    -38  -19.4%
  tcp_autolowat/tcp_autolowat_setsockopt              271->  233    -38  -14.0%
  test_btf_skc_cls_ingress/cls_ingress               1107-> 1069    -38   -3.4%

Meta production programs, listed by category only:

Largest relative savings (JITed bytes before->after, saved, percent):

  security enforcement 14     280->  136   -144  -51.4%
  TCP congestion control 24   511->  257   -254  -49.7%
  container runtime 9         520->  310   -210  -40.4%
  network tuning 46           201->  125    -76  -37.8%
  security monitoring 145     100->   66    -34  -34.0%
  profiling 22                433->  310   -123  -28.4%
  security monitoring 35      154->  119    -35  -22.7%
  security monitoring 37      154->  119    -35  -22.7%
  security monitoring 33       83->   66    -17  -20.5%
  security monitoring 25      346->  287    -59  -17.1%
  load balancing 20           401->  333    -68  -17.0%
  profiling 21                426->  358    -68  -16.0%
  host monitoring 10          983->  830   -153  -15.6%
  security monitoring 157     675->  573   -102  -15.1%
  security monitoring 158     711->  609   -102  -14.3%
  security monitoring 48      119->  102    -17  -14.3%
  security enforcement 2     1487-> 1293   -194  -13.0%
  network telemetry 4         423->  371    -52  -12.3%
  network telemetry 3         428->  376    -52  -12.1%
  TCP congestion control 3   2344-> 2072   -272  -11.6%
  TCP congestion control 10  2344-> 2072   -272  -11.6%
  network telemetry 18        982->  880   -102  -10.4%
  security enforcement 85     170->  153    -17  -10.0%
  security enforcement 92     175->  158    -17   -9.7%
  security enforcement 93     175->  158    -17   -9.7%
  network telemetry 2         361->  326    -35   -9.7%
  security monitoring 194     975->  889    -86   -8.8%
  TCP congestion control 26  3699-> 3427   -272   -7.4%
  TCP congestion control 32  3699-> 3427   -272   -7.4%
  storage telemetry 44       1297-> 1208    -89   -6.9%
  storage telemetry 36       1300-> 1211    -89   -6.8%
  storage telemetry 42       1300-> 1211    -89   -6.8%
  storage telemetry 46       1300-> 1211    -89   -6.8%
  storage telemetry 50       1300-> 1211    -89   -6.8%
  storage telemetry 71       1300-> 1211    -89   -6.8%
  storage telemetry 38       1308-> 1219    -89   -6.8%
  storage telemetry 40       1308-> 1219    -89   -6.8%
  storage telemetry 48       1308-> 1219    -89   -6.8%
  storage telemetry 52       1308-> 1219    -89   -6.8%
  storage telemetry 54       1308-> 1219    -89   -6.8%
  storage telemetry 56       1308-> 1219    -89   -6.8%
  storage telemetry 58       1308-> 1219    -89   -6.8%
  storage telemetry 60       1308-> 1219    -89   -6.8%
  security monitoring 197    1301-> 1215    -86   -6.6%
  host monitoring 11          801->  750    -51   -6.4%
  security monitoring 114     844->  793    -51   -6.0%
  security enforcement 34     606->  572    -34   -5.6%
  host monitoring 12          303->  286    -17   -5.6%
  network tuning 48          2619-> 2479   -140   -5.3%
  security enforcement 110   6224-> 5894   -330   -5.3%

Largest absolute savings (JITed bytes before->after, saved, percent):

  security enforcement 77   13763->13404   -359   -2.6%
  security enforcement 110   6224-> 5894   -330   -5.3%
  security enforcement 75   13240->12966   -274   -2.1%
  security enforcement 69   11670->11397   -273   -2.3%
  TCP congestion control 3   2344-> 2072   -272  -11.6%
  TCP congestion control 10  2344-> 2072   -272  -11.6%
  TCP congestion control 26  3699-> 3427   -272   -7.4%
  TCP congestion control 32  3699-> 3427   -272   -7.4%
  load balancing 15          5059-> 4797   -262   -5.2%
  load balancing 16          5059-> 4797   -262   -5.2%
  security enforcement 71   13064->12808   -256   -2.0%
  TCP congestion control 24   511->  257   -254  -49.7%
  security enforcement 46   11198->10955   -243   -2.2%
  security monitoring 115   10522->10280   -242   -2.3%
  security enforcement 73    9054-> 8815   -239   -2.6%
  security enforcement 15   33473->33249   -224   -0.7%
  security enforcement 16   25000->24778   -222   -0.9%
  security enforcement 19   25039->24817   -222   -0.9%
  security enforcement 20   25039->24817   -222   -0.9%
  security enforcement 21   25039->24817   -222   -0.9%
  security enforcement 76   12863->12641   -222   -1.7%
  security enforcement 17   25336->25115   -221   -0.9%
  container runtime 9         520->  310   -210  -40.4%
  security enforcement 4    24666->24459   -207   -0.8%
  security enforcement 2     1487-> 1293   -194  -13.0%
  security enforcement 18   28083->27895   -188   -0.7%
  security enforcement 50   10779->10626   -153   -1.4%
  security enforcement 97   22794->22641   -153   -0.7%
  security enforcement 98    8869-> 8716   -153   -1.7%
  host monitoring 10          983->  830   -153  -15.6%
  security enforcement 14     280->  136   -144  -51.4%
  security monitoring 5     20270->20128   -142   -0.7%
  security enforcement 61   25296->25156   -140   -0.6%
  security enforcement 64   25296->25156   -140   -0.6%
  security enforcement 65   20458->20318   -140   -0.7%
  network tuning 47          2644-> 2504   -140   -5.3%
  network tuning 48          2619-> 2479   -140   -5.3%
  security enforcement 74   12340->12203   -137   -1.1%
  security enforcement 24   25005->24869   -136   -0.5%
  security enforcement 1    10135->10012   -123   -1.2%
  security enforcement 8    19588->19465   -123   -0.6%
  security enforcement 56   16559->16436   -123   -0.7%
  security enforcement 57   17098->16975   -123   -0.7%
  security enforcement 58   18871->18748   -123   -0.7%
  security enforcement 59   16532->16409   -123   -0.7%
  security enforcement 62   22632->22509   -123   -0.5%
  security enforcement 66   22632->22509   -123   -0.5%
  security enforcement 101  15340->15217   -123   -0.8%
  profiling 22                433->  310   -123  -28.4%
  security enforcement 44   16189->16069   -120   -0.7%

Changelog:
----------
v1 (Reworked) -> v2
v1: https://lore.kernel.org/bpf/[email protected]

* Keep the range check for programs loaded without CAP_BPF, which are not registered in kallsyms, so the fault handler cannot find their exception table entries; add bpf_prog_kallsyms_allowed() for the decision. (BPF CI)
* Stop crediting arm64, riscv and loongarch with bare PROBE_MEM loads; they use the verifier's generic user address guard. (BPF CI)
* Mention the LASS #GP path in the JIT comment and the commit messages, and update the bpf_arch_uaddress_limit() comment. (BPF CI)
* Rewrite the commit message of patch 1 around a concrete program and the check the JIT emits for it, without references to neighbouring patches. (Boris)
* Use __u64 for the test addresses and the BPF global. (Sashiko)
* Cover the last user page and the guard page of both paging layouts in the selftest.
* Leave the NULL and low user address subtests out on s390x, which has its lowcore there.
* Rebase on bpf-next, where the range check is down to five instructions and 17 or 18 bytes (lea, shr, jne, xor, jmp); redo the code size measurements against it, over 474 current production objects.
* Take the listing in the commit message of patch 1 from the JIT; the offsets in the old one were wrong.
* Report that the branchless mask now produces larger code than the range check in bpf-next.
* Rebase onto commit 4eaf4d71b91a ("bpf: Keep the symbols of a program until it has ended"), which keeps a program in kallsyms until it can no longer run, so a faulting load in a program whose last reference is gone still finds its exception table. (Sashiko)
* Check for kernel mode, a read fault and an EX_TYPE_BPF exception table entry in do_user_addr_fault() instead of is_bpf_text_address(). (Boris, Alexei)
* List the instructions a PROBE_MEM entry covers and say what the fixup does. (Dave)
* Replace the comparison with get_kernel_nofault() by a table of who refuses which address. (Dave)
* Say that MMIO is filtered neither before nor after the series. (Andy)
* Say that PROBE_MEM needs CAP_PERFMON and a GPL-compatible program. (Dave)
* Aim the series at bpf-next as a whole, since patch 2 depends on patch 1. (Alexei)
* Drop Puranjay's Ack on patch 1 since the check changed.
* Shorten the commit messages of patches 1 and 2 and the cover letter.

v3 -> v1 (Reworked)
v3: https://lore.kernel.org/bpf/[email protected]

* Rebase on bpf-next.
* Drop "zero overhead" from the title and state the fault handler cost up front. (Dave)
* Spell out what the series does and does not change for confidential guests. (Dave)
* Measure code size over the selftests and Meta production objects, for this series and for the branchless mask alternative. (Peter)
* Add a selftest for PROBE_MEM loads from user, vsyscall and non-canonical addresses.
* Call fixup_exception() directly in the SMAP branch and fall through to the existing page_fault_oops() instead of kernelmode_fixup_or_oops().
* Restructure the JIT change around probe_mem and bounds_check flags instead of a goto; drop Puranjay's Ack on it since the code changed.

v2 -> v3
v2: https://lore.kernel.org/bpf/[email protected]

* Rebase on bpf-next
* Add Puranjay's Acks

v1 -> v2
v1: https://lore.kernel.org/bpf/[email protected]

* Rebase on bpf-next

Kumar Kartikeya Dwivedi (3):
x86/mm: Resolve BPF exception fixups for user address faults under
SMAP
bpf, x86: Skip the PROBE_MEM address range check under SMAP selftests/bpf: Test PROBE_MEM loads from invalid addresses

 arch/x86/mm/fault.c                           | 11 ++-
 arch/x86/net/bpf_jit_comp.c                   | 33 ++++++--
 include/linux/bpf.h                           |  1 +
 include/linux/filter.h                        |  1 +
 kernel/bpf/core.c                             | 16 +++-
 kernel/bpf/syscall.c                          |  1 +
 .../bpf/prog_tests/probe_mem_fault.c          | 77 +++++++++++++++++++
 .../selftests/bpf/progs/probe_mem_fault.c     | 41 ++++++++++
 8 files changed, 172 insertions(+), 9 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/probe_mem_fault.c
 create mode 100644 tools/testing/selftests/bpf/progs/probe_mem_fault.c

base-commit: 7bba28b399b36f6d50f904a53cfe900e79f1e1e5

Signature · 1 line
2.53.1-Meta
author maintainer
#1 lore raw

PATCH v2 1/3 x86/mm: Resolve BPF exception fixups for user address faults under SMAP

BPF tracing programs read through pointers that cannot be checked when the program is loaded. For example:

  SEC("fentry/tcp_retransmit_skb")
  int BPF_PROG(retrans, struct sock *sk)
  {
          struct file *f = sk->sk_socket->file;
          ...

sk is valid, but sk->sk_socket is NULL for an orphaned socket. The verifier marks such a load PROBE_MEM and the JIT gives it an exception table entry of type EX_TYPE_BPF. The load is a single mov, movzx, movsx or movsxd into a register. On a fault, ex_handler_bpf() zeroes the register and skips the instruction. The load is not retried.

This does not work for user addresses. With SMAP enabled, do_user_addr_fault() treats a kernel-mode fault on a user address with EFLAGS.AC clear as a kernel bug and oopses without looking at the exception table. So the x86 JIT puts a range check in front of every PROBE_MEM load to keep user addresses, the guard page above them and the vsyscall page away from it. For the second load above, with five-level paging, it emits:

  leaq    10485776(%rdi), %r11      # 16 - VSYSCALL_ADDR
  shrq    $57, %r11                 # zero for user and vsyscall addresses
  jne     load
  xorl    %edi, %edi
  jmp     done

load:
movq 16(%rdi), %rdi # offsetof(struct socket, file)
done:

That is 17 or 18 bytes of check for a load of three to eight bytes, and it repeats in software what the CPU already refuses under SMAP. The pointer is only known at run time, so the check cannot be done at load time.

Fix up the fault through the exception table when it came from kernel mode, is a read, and the faulting instruction has an EX_TYPE_BPF entry. error_context() uses ex_get_fixup_type() the same way for machine checks. SMAP stays on and the access is not retried, so no user memory is read: the register reads zero, as it does with the range check. The new check only runs for faults that oops today, and every other fault there still oopses. With LASS the access raises #GP instead, which already goes through fixup_exception().

The JIT also uses EX_TYPE_BPF for arena accesses and unwind entries. Arena addresses are kernel addresses, and no instruction starts at the address of an unwind entry, so neither can match a fault on a user address.

The addresses a PROBE_MEM load can read stay the same. What changes is who refuses a user address: a compare in software, or the CPU with a fault and a fixup.

                              user, guard,                  kernel address
                              vsyscall page  non-canonical  unmapped  mapped
  copy_from_kernel_nofault()  compare        compare        CPU       load
  PROBE_MEM, range check      compare        CPU            CPU       load
  PROBE_MEM, SMAP alone       CPU            CPU            CPU       load

None of the three filters MMIO. ioremap() space is read in every row, and a BAR mapped into user space is a user address, refused in every row.

This lets the x86 JIT drop the range check when SMAP is enabled. Kernels without SMAP keep the check and never take this path.

---
 arch/x86/mm/fault.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
arch/x86/mm/fault.c +10 -1
index aa88370ce739..9fe8705eff04 100644
@@ -1263,7 +1263,16 @@ void do_user_addr_fault(struct pt_regs *regs,
 		     !(error_code & X86_PF_USER) &&
 		     !(regs->flags & X86_EFLAGS_AC))) {
 		/*
-		 * No extable entry here.  This was a kernel access to an
+		 * The CPU refused the access. If the BPF JIT marked this load
+		 * as one that may fault, skip it and zero the destination.
+		 */
+		if (!user_mode(regs) && !(error_code & X86_PF_WRITE) &&
+		    ex_get_fixup_type(regs->ip) == EX_TYPE_BPF &&
+		    fixup_exception(regs, X86_TRAP_PF, error_code, address))
+			return;
+
+		/*
+		 * No other fixups here.  This was a kernel access to an
 		 * invalid pointer.  get_kernel_nofault() will not get here.
 		 */
 		page_fault_oops(regs, error_code, address);
Signature · 1 line
2.53.1-Meta
author maintainer
#4 lore raw

PATCH v2 2/3 bpf, x86: Skip the PROBE_MEM address range check under SMAP

In reply to Kumar Kartikeya Dwivedi

The x86 JIT puts a range check in front of every PROBE_MEM load to keep user addresses, the guard page above them and the vsyscall page away from it. A fault on a user or vsyscall address used to oops under SMAP instead of using the load's exception table entry. The check is five instructions (lea, shr, jne, xor, jmp) and 17 or 18 bytes, for a load of three to eight bytes.

do_user_addr_fault() now fixes up such a fault when the faulting instruction has an EX_TYPE_BPF exception table entry. With LASS the access raises #GP, which exc_general_protection() has always fixed up. So emit the bare load when SMAP is enabled. The feature cannot change after boot, so it is checked at JIT time. Kernels without SMAP, including those booted with clearcpuid=smap, keep the check. bpf_arch_uaddress_limit() still returns 0 on x86, so the verifier adds no check of its own.

Programs loaded without CAP_BPF keep the check too. The fault handler finds a program's exception table through the BPF ksym tree, and bpf_prog_kallsyms_add() leaves such programs out of it. They can still have PROBE_MEM loads: with kernel.unprivileged_bpf_disabled=0, a socket filter loaded with only CAP_PERFMON can call bpf_skc_to_tcp_sock() and walk pointers from the result. bpf_prog_load() now records whether the loader had CAP_BPF, and the new bpf_prog_kallsyms_allowed() gives that answer to both the JIT and bpf_prog_kallsyms_add().

JITed code size from veristat, on one kernel booted with and without clearcpuid=smap, over the BPF selftests and 474 production objects from Meta:

programs with PROBE_MEM reduction per program
mean median max

  BPF selftests             5486             100  20.2%  19.9%  58.2%
  Meta production programs  1942             262   3.5%   0.8%  51.4%

No program grows; dump_tcp6 of the selftests shrinks from 3142 to 2129 bytes. Most programs are unchanged, because loads through trusted pointers and the probe_read helpers do not use PROBE_MEM.

---
 arch/x86/net/bpf_jit_comp.c | 33 +++++++++++++++++++++++++++------
 include/linux/bpf.h         |  1 +
 include/linux/filter.h      |  1 +
 kernel/bpf/core.c           | 16 ++++++++++++++--
 kernel/bpf/syscall.c        |  1 +
 5 files changed, 44 insertions(+), 8 deletions(-)
arch/x86/net/bpf_jit_comp.c +27 -6
index d51ae52fef71..019e5da72136 100644
@@ -299,6 +299,9 @@ struct jit_context {
 	 */
 	int tail_call_direct_label;
 	int tail_call_indirect_label;
+
+	/* Emit the address range check in front of PROBE_MEM loads */
+	bool probe_mem_check;
 };
 
 /* Maximum number of bytes emitted while JITing one eBPF insn */
@@ -2547,6 +2550,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		const s32 imm32 = insn->imm;
 		u32 dst_reg = insn->dst_reg;
 		u32 src_reg = insn->src_reg;
+		bool probe_mem, bounds_check;
 		bool accesses_stack_only;
 		u8 b3 = 0;
 		u8 *start_of_ldx;
@@ -3091,6 +3095,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_B:
 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_H:
 		case BPF_LDX | BPF_PROBE_MEMSX | BPF_W:
+			probe_mem = BPF_MODE(insn->code) == BPF_PROBE_MEM ||
+				    BPF_MODE(insn->code) == BPF_PROBE_MEMSX;
+			bounds_check = probe_mem && ctx->probe_mem_check;
 			insn_off = insn->off;
 			if (src_reg == BPF_REG_PARAMS) {
 				if (insn_off == 8 && !arena_sp) {
@@ -3108,8 +3115,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				 */
 			}
 
-			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
-			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
+			if (bounds_check) {
 				/* Conservatively check that src_reg + insn->off is a kernel address:
 				 *   src_reg + insn->off > TASK_SIZE_MAX + PAGE_SIZE
 				 *   and
@@ -3150,6 +3156,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				/* populate jmp_offset for JNE above to jump to start_of_ldx */
 				start_of_ldx = prog;
 				end_of_jmp[-1] = start_of_ldx - end_of_jmp;
+			} else if (probe_mem) {
+				start_of_ldx = prog;
 			} else if (!accesses_stack_only) {
 				err = emit_kasan_check(env, &prog, src_reg,
 						       insn_off,
@@ -3163,14 +3171,14 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				emit_ldsx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
 			else
 				emit_ldx(&prog, BPF_SIZE(insn->code), dst_reg, src_reg, insn_off);
-			if (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
-			    BPF_MODE(insn->code) == BPF_PROBE_MEMSX) {
+			if (probe_mem) {
 				struct exception_table_entry *ex;
 				u8 *_insn = image + proglen + (start_of_ldx - temp);
 				s64 delta;
 
 				/* populate jmp_offset for JMP above */
-				start_of_ldx[-1] = prog - start_of_ldx;
+				if (bounds_check)
+					start_of_ldx[-1] = prog - start_of_ldx;
 
 				if (!bpf_prog->aux->extable)
 					break;
@@ -4862,6 +4870,15 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		addrs[i] = proglen;
 	}
 	ctx.cleanup_addr = proglen;
+	/*
+	 * With SMAP enabled, a PROBE_MEM load of a user address faults (#PF, or
+	 * #GP with LASS) and the fault handler resolves the exception table
+	 * entry of the program, as for an unmapped kernel address. That lookup
+	 * only finds programs in the BPF ksym tree, so programs loaded without
+	 * CAP_BPF keep the address range check, as do kernels without SMAP.
+	 */
+	ctx.probe_mem_check = !cpu_feature_enabled(X86_FEATURE_SMAP) ||
+			      !bpf_prog_kallsyms_allowed(prog);
 skip_init_addrs:
 
 	/*
@@ -5204,7 +5221,11 @@ bool bpf_jit_supports_ptr_xchg(void)
 	return true;
 }
 
-/* x86-64 JIT emits its own code to filter user addresses so return 0 here */
+/*
+ * The x86-64 JIT keeps user addresses away from PROBE_MEM loads itself, with
+ * its own range check or by leaving the access to SMAP and the fault handler
+ * (see bpf_int_jit_compile()), so return 0 here.
+ */
 u64 bpf_arch_uaddress_limit(void)
 {
 	return 0;
include/linux/bpf.h +1 -0
index c7996515a03d..bce1da58f96a 100644
@@ -1924,6 +1924,7 @@ struct bpf_prog_aux {
 	enum bpf_attach_type saved_dst_attach_type;
 	bool verifier_zext; /* Zero extensions has been inserted by verifier. */
 	bool dev_bound; /* Program is bound to the netdev. */
+	bool bpf_capable; /* Program was loaded with CAP_BPF. */
 	bool offload_requested; /* Program is bound and offloaded to the netdev. */
 	bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */
 	bool attach_tracing_prog; /* true if tracing another tracing program */
include/linux/filter.h +1 -0
index 61448be53f8d..eb6d38233ea7 100644
@@ -1676,6 +1676,7 @@ int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
 		    char *sym);
 struct bpf_prog *bpf_prog_ksym_find(unsigned long addr);
 
+bool bpf_prog_kallsyms_allowed(const struct bpf_prog *fp);
 void bpf_prog_kallsyms_add(struct bpf_prog *fp);
 void bpf_prog_kallsyms_del(struct bpf_prog *fp);
 
kernel/bpf/core.c +14 -2
index 20765ec22395..7f35d6403ded 100644
@@ -952,10 +952,22 @@ static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
 	return fp->jited && !bpf_prog_was_classic(fp);
 }
 
+/*
+ * Programs loaded without CAP_BPF are kept out of the BPF ksym tree, so
+ * search_bpf_extables() does not find their exception tables. A JIT that
+ * relies on the exception table to recover from a faulting PROBE_MEM load needs
+ * this answer at JIT time, before bpf_prog_kallsyms_add() runs. Both get the
+ * answer that bpf_prog_load() recorded, so they cannot disagree, and the JIT
+ * makes no capability check of its own.
+ */
+bool bpf_prog_kallsyms_allowed(const struct bpf_prog *fp)
+{
+	return fp->aux->main_prog_aux->bpf_capable;
+}
+
 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
 {
-	if (!bpf_prog_kallsyms_candidate(fp) ||
-	    !bpf_token_capable(fp->aux->token, CAP_BPF))
+	if (!bpf_prog_kallsyms_candidate(fp) || !bpf_prog_kallsyms_allowed(fp))
 		return;
 
 	bpf_prog_ksym_set_addr(fp);
kernel/bpf/syscall.c +1 -0
index f07a0aa5ed40..de8ce2b00e2f 100644
@@ -3102,6 +3102,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at
 	/* move token into prog->aux, reuse taken refcnt */
 	prog->aux->token = token;
 	token = NULL;
+	prog->aux->bpf_capable = bpf_cap;
 
 	prog->aux->user = get_current_user();
 	prog->len = attr->insn_cnt;
Signature · 1 line
2.53.1-Meta
author maintainer
#7 lore raw

PATCH v2 3/3 selftests/bpf: Test PROBE_MEM loads from invalid addresses

In reply to Kumar Kartikeya Dwivedi

Add a test that performs PROBE_MEM loads of three sizes through a bpf_core_cast() pointer whose value is chosen by userspace: NULL, a low user address, the last user page and the guard page of both the four and five level paging layouts, a non-canonical address and, on x86-64, the vsyscall page and an offset into it. Each load must read zero and the kernel must survive. A load through the current task pointer checks that the same loads read real values when the address is valid. NULL and the low user address are left out on s390x, which has its lowcore there.

The test passes on kernels that reject the addresses with the JIT's range check and on kernels that rely on the fault handler. With only the JIT change applied, the first subtest oopses.

---
 .../bpf/prog_tests/probe_mem_fault.c          | 77 +++++++++++++++++++
 .../selftests/bpf/progs/probe_mem_fault.c     | 41 ++++++++++
 2 files changed, 118 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/probe_mem_fault.c
 create mode 100644 tools/testing/selftests/bpf/progs/probe_mem_fault.c
tools/testing/selftests/bpf/prog_tests/probe_mem_fault.c new file +77 -0
new file mode 100644
index 000000000000..9b89864b9ac2
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+#include <test_progs.h>
+#include "probe_mem_fault.skel.h"
+
+#if defined(__x86_64__)
+#include <asm/vsyscall.h>
+#endif
+
+/*
+ * Addresses a PROBE_MEM load has to survive. Either the JIT's address check
+ * or the fault handler must turn each load into a zero result. The user and
+ * guard page addresses are those of x86-64 with four and five paging levels;
+ * on other kernels they are merely unmapped.
+ */
+static const struct {
+	const char *name;
+	__u64 addr;
+} bad_addrs[] = {
+#if !defined(__s390x__)
+	/* s390x has its lowcore at these addresses, so the loads read it. */
+	{ "null", 0 },
+	{ "low_user", 4096 },
+#endif
+	{ "last_user_page_4l", (1ULL << 47) - 2 * 4096 },
+	{ "guard_page_4l", (1ULL << 47) - 4096 },
+	{ "last_user_page_5l", (1ULL << 56) - 2 * 4096 },
+	{ "guard_page_5l", (1ULL << 56) - 4096 },
+	{ "non_canonical", 1ULL << 63 },
+#if defined(__x86_64__)
+	{ "vsyscall", VSYSCALL_ADDR },
+	{ "vsyscall_tail", VSYSCALL_ADDR + 0x800 },
+#endif
+};
+
+static void trigger(struct probe_mem_fault *skel, int *runs)
+{
+	skel->bss->val_dw = ~0ULL;
+	skel->bss->val_w = ~0U;
+	skel->bss->val_b = ~0;
+	usleep(1);
+	ASSERT_EQ(skel->bss->runs, ++*runs, "runs");
+}
+
+void test_probe_mem_fault(void)
+{
+	struct probe_mem_fault *skel;
+	int runs = 0, i;
+
+	skel = probe_mem_fault__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "open_and_load"))
+		return;
+
+	skel->bss->target_pid = getpid();
+	if (!ASSERT_OK(probe_mem_fault__attach(skel), "attach"))
+		goto out;
+
+	/* A valid kernel address is read for real. */
+	skel->bss->use_current_task = true;
+	trigger(skel, &runs);
+	ASSERT_EQ(skel->bss->val_w, getpid(), "pid");
+	ASSERT_NEQ(skel->bss->val_dw, 0, "start_time");
+	ASSERT_NEQ(skel->bss->val_b, 0, "comm");
+
+	skel->bss->use_current_task = false;
+	for (i = 0; i < ARRAY_SIZE(bad_addrs); i++) {
+		if (!test__start_subtest(bad_addrs[i].name))
+			continue;
+		skel->bss->addr = bad_addrs[i].addr;
+		trigger(skel, &runs);
+		ASSERT_EQ(skel->bss->val_dw, 0, "start_time");
+		ASSERT_EQ(skel->bss->val_w, 0, "pid");
+		ASSERT_EQ(skel->bss->val_b, 0, "comm");
+	}
+out:
+	probe_mem_fault__destroy(skel);
+}
tools/testing/selftests/bpf/progs/probe_mem_fault.c new file +41 -0

41 lines not on this page · raw message

Signature · 1 line
2.53.1-Meta
#5 lore raw

Re: [PATCH bpf-next v2 2/3] bpf, x86: Skip the PROBE_MEM address range check under SMAP

In reply to Kumar Kartikeya Dwivedi
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf, x86: skipping PROBE_MEM range check breaks flex_array_far_join() test --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf, x86: skipping PROBE_MEM range check breaks flex_array_far_join() test
--

commit 519a06c0e9f33f01690a25837946e3048111ee57
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf, x86: Skip the PROBE_MEM address range check under SMAP

This commit omits the x86-64 JIT runtime address range check before BPF_PROBE_MEM and BPF_PROBE_MEMSX loads when SMAP is enabled and the program was loaded with CAP_BPF, relying on SMAP and the page fault handler's exception table lookup instead.

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
index d51ae52fef719..019e5da72136d 100644

[ ... ]

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
@@ -4862,6 +4870,15 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		addrs[i] = proglen;
 	}
 	ctx.cleanup_addr = proglen;

arch/x86/net/bpf_jit_comp.c struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr · line 4882

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +9 -0
+	/*
+	 * With SMAP enabled, a PROBE_MEM load of a user address faults (#PF, or
+	 * #GP with LASS) and the fault handler resolves the exception table
+	 * entry of the program, as for an unmapped kernel address. That lookup
+	 * only finds programs in the BPF ksym tree, so programs loaded without
+	 * CAP_BPF keep the address range check, as do kernels without SMAP.
+	 */
+	ctx.probe_mem_check = !cpu_feature_enabled(X86_FEATURE_SMAP) ||
+			      !bpf_prog_kallsyms_allowed(prog);
 skip_init_addrs:

[Severity: Medium]
Does skipping the range check break the flex_array_far_join() BPF selftest on x86-64 systems with SMAP enabled?

tools/testing/selftests/bpf/progs/verifier_btf_array_access.c:flex_array_far_join() {
	SEC("tp_btf/exit_mmap")
	__success __arch_x86_64
	__jited("	leaq	0xa00000(%rbx), %r11")
	__naked void flex_array_far_join(void)
}

That test is loaded with CAP_BPF and matches the "leaq 0xa00000(%rbx), %r11" instruction from the PROBE_MEM range check to verify that the load was converted to BPF_PROBE_MEM, so its __jited() check fails when ctx.probe_mem_check is false.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#2 lore raw

Re: [PATCH bpf-next v2 1/3] x86/mm: Resolve BPF exception fixups for user address faults under SMAP

In reply to Kumar Kartikeya Dwivedi
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] x86/mm: SMAP does not fault on supervisor mappings below TASK_SIZE_MAX --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] x86/mm: SMAP does not fault on supervisor mappings below TASK_SIZE_MAX
--

commit 9b387754d627ac256ae9705ce7d6a4e7a2935051
Author: Kumar Kartikeya Dwivedi <[email protected]>

x86/mm: Resolve BPF exception fixups for user address faults under SMAP

This commit resolves EX_TYPE_BPF exception table entries on kernel-mode read faults in do_user_addr_fault() under SMAP, allowing the x86 BPF JIT to omit its software range check before PROBE_MEM loads.

Quoted 6 lines
arch/x86/mm/fault.c +0 -0
index aa88370ce7394..9fe8705eff043 100644
@@ -1263,7 +1263,16 @@ void do_user_addr_fault(struct pt_regs *regs,
 		     !(error_code & X86_PF_USER) &&

arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1272

Quoted 10 lines
arch/x86/mm/fault.c +7 -1
 		     !(regs->flags & X86_EFLAGS_AC))) {
 		/*
-		 * No extable entry here.  This was a kernel access to an
+		 * The CPU refused the access. If the BPF JIT marked this load
+		 * as one that may fault, skip it and zero the destination.
+		 */
+		if (!user_mode(regs) && !(error_code & X86_PF_WRITE) &&
+		    ex_get_fixup_type(regs->ip) == EX_TYPE_BPF &&
+		    fixup_exception(regs, X86_TRAP_PF, error_code, address))
+			return;

[Severity: Medium]
Can relying on SMAP to refuse PROBE_MEM loads below TASK_SIZE_MAX allow reads from supervisor mappings in the low address range when a temporary mm such as efi_mm is active in CR3?

SMAP only faults when the page-table entries mapping the linear address have _PAGE_USER set. efi_setup_page_tables() permanently maps 0x0..0xfff 1:1 in efi_mm.pgd without _PAGE_USER, and efi_map_region() likewise creates 1:1 supervisor mappings below TASK_SIZE_MAX for EFI runtime and MMIO regions:

arch/x86/platform/efi/efi_64.c:efi_setup_page_tables() {
    ...
	pf = _PAGE_NX | _PAGE_RW;
	if (sev_es_active())
		pf |= _PAGE_ENC;

	if (kernel_map_pages_in_pgd(pgd, 0x0, 0x0, 1, pf)) {
    ...
}

While arch_efi_call_virt_setup() has efi_mm loaded in CR3 (with LASS disabled and interrupts and NMIs enabled), a BPF tracing program executing a PROBE_MEM load through a NULL pointer or into a 1:1 EFI region will not fault into do_user_addr_fault() and will instead read physical page 0 or trigger an unintended firmware/MMIO read rather than zeroing the destination register.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

Re: [PATCH bpf-next v2 1/3] x86/mm: Resolve BPF exception fixups for user address faults under SMAP

Quoted 28 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] x86/mm: SMAP does not fault on supervisor mappings below TASK_SIZE_MAX
--

commit 9b387754d627ac256ae9705ce7d6a4e7a2935051
Author: Kumar Kartikeya Dwivedi <[email protected]>

x86/mm: Resolve BPF exception fixups for user address faults under SMAP

This commit resolves EX_TYPE_BPF exception table entries on kernel-mode read faults in do_user_addr_fault() under SMAP, allowing the x86 BPF JIT to omit its software range check before PROBE_MEM loads.

Quoted 13 lines
arch/x86/mm/fault.c +4 -1
index aa88370ce7394..9fe8705eff043 100644
@@ -1263,7 +1263,16 @@ void do_user_addr_fault(struct pt_regs *regs,
 		     !(error_code & X86_PF_USER) &&
 		     !(regs->flags & X86_EFLAGS_AC))) {
 		/*
-		 * No extable entry here.  This was a kernel access to an
+		 * The CPU refused the access. If the BPF JIT marked this load
+		 * as one that may fault, skip it and zero the destination.
+		 */
+		if (!user_mode(regs) && !(error_code & X86_PF_WRITE) &&
Quoted 9 lines

arch/x86/mm/fault.c void do_user_addr_fault(struct pt_regs *regs, · line 1272

Quoted 3 lines
arch/x86/mm/fault.c +3 -0
+		    ex_get_fixup_type(regs->ip) == EX_TYPE_BPF &&
+		    fixup_exception(regs, X86_TRAP_PF, error_code, address))
+			return;

[Severity: Medium]
Can relying on SMAP to refuse PROBE_MEM loads below TASK_SIZE_MAX allow reads from supervisor mappings in the low address range when a temporary mm such as efi_mm is active in CR3?

Which is fine, the read just goes through in that case. Bot is confused about the semantics of the feature.

Quoted 1 line

[...]

author maintainer
#6 lore raw

Re: [PATCH bpf-next v2 2/3] bpf, x86: Skip the PROBE_MEM address range check under SMAP

In reply to [email protected]
Quoted 47 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf, x86: skipping PROBE_MEM range check breaks flex_array_far_join() test
--

commit 519a06c0e9f33f01690a25837946e3048111ee57
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf, x86: Skip the PROBE_MEM address range check under SMAP

This commit omits the x86-64 JIT runtime address range check before BPF_PROBE_MEM and BPF_PROBE_MEMSX loads when SMAP is enabled and the program was loaded with CAP_BPF, relying on SMAP and the page fault handler's exception table lookup instead.

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
index d51ae52fef719..019e5da72136d 100644

[ ... ]

Quoted 4 lines
arch/x86/net/bpf_jit_comp.c +0 -0
@@ -4862,6 +4870,15 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		addrs[i] = proglen;
 	}
 	ctx.cleanup_addr = proglen;

arch/x86/net/bpf_jit_comp.c struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr · line 4882

Quoted 10 lines
arch/x86/net/bpf_jit_comp.c +9 -0
+	/*
+	 * With SMAP enabled, a PROBE_MEM load of a user address faults (#PF, or
+	 * #GP with LASS) and the fault handler resolves the exception table
+	 * entry of the program, as for an unmapped kernel address. That lookup
+	 * only finds programs in the BPF ksym tree, so programs loaded without
+	 * CAP_BPF keep the address range check, as do kernels without SMAP.
+	 */
+	ctx.probe_mem_check = !cpu_feature_enabled(X86_FEATURE_SMAP) ||
+			      !bpf_prog_kallsyms_allowed(prog);
 skip_init_addrs:

[Severity: Medium]
Does skipping the range check break the flex_array_far_join() BPF selftest on x86-64 systems with SMAP enabled?

tools/testing/selftests/bpf/progs/verifier_btf_array_access.c:flex_array_far_join() {
	SEC("tp_btf/exit_mmap")
	__success __arch_x86_64
	__jited("	leaq	0xa00000(%rbx), %r11")
	__naked void flex_array_far_join(void)
}
Quoted 4 lines

That test is loaded with CAP_BPF and matches the "leaq 0xa00000(%rbx), %r11" instruction from the PROBE_MEM range check to verify that the load was converted to BPF_PROBE_MEM, so its __jited() check fails when ctx.probe_mem_check is false.

Yes, this was an oversight on my part. Will fix in v3 respin (after some time).