Skip to content

eBPF-based security platform

shirudo: add XDP attach with signed device classes

John Fastabend5e7fd2da3a25
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 2f7eae83..7d12632b 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -170,6 +170,8 @@ signed config image.
- Attach kinds the builder refuses
* - ``t3011-string-bounds``
- Names and the tree repository are refused rather than cut
+ * - ``t3012-xdp-metadata``
+ - Signed XDP device-class masks, object inputs and invalid sections
* - ``t3101-target-fixtures``
- Prebuilt fixtures load and unload, foreign and own-keyring
fixtures are refused, a map fixture exports
@@ -194,6 +196,13 @@ signed config image.
maps
* - ``t3110-double-load``
- A second load of a loaded upatch is refused as ``already_loaded``
+ * - ``t3111-xdp``
+ - Native XDP class selection, veth pair deduplication with both
+ endpoint index orderings, cross-namespace pairs, a bridge without
+ native XDP skipped, rollback, signed unload and descriptor
+ and alternate-attachment lockdown; a repeated init adopts the
+ archived XDP without another event. Each case cleans up its state
+ so a failed assertion does not contaminate later cases.
``tpm`` (4)
~~~~~~~~~~~
@@ -281,7 +290,8 @@ signed config image.
* - ``t5103-verity-cli``
- Key and repository changes require a signed config
* - ``t5104-verity-revocation``
- - Signed revocation unlinks the signer and purges its upatch
+ - Signed revocation unlinks the signer and purges its measured
+ tracing and XDP upatches and their archives
* - ``t5105-verity-interruption``
- An interruption after measurement blocks changes and attestation
diff --git a/Documentation/internals/architecture.rst b/Documentation/internals/architecture.rst
index 620f12c6..4a4322c6 100644
--- a/Documentation/internals/architecture.rst
+++ b/Documentation/internals/architecture.rst
@@ -75,7 +75,8 @@ The binary embeds three BPF objects, compiled from :src:`bpf/` and included
with ``.incbin`` in :src:`util/loader.c`:
``bpf2``
- BPF admission (``lsm/bpf``, ``lsm/bpf_map``, ``lsm/bpf_prog_load``),
+ BPF admission (``lsm/bpf``, ``lsm/bpf_map``, ``lsm/bpf_prog``,
+ ``lsm/bpf_prog_load``),
the guards of the private bpffs and of ``/run/shirudo``, the mount
guards, the keyring and TPM command guards, the kexec refusal, the
device-mapper and perf ioctl guards and the dm-verity device records.
diff --git a/Documentation/internals/enforcement.rst b/Documentation/internals/enforcement.rst
index f1cd05f9..de469463 100644
--- a/Documentation/internals/enforcement.rst
+++ b/Documentation/internals/enforcement.rst
@@ -147,8 +147,10 @@ Descriptors and pins
such a task, read-only or writable. ``lsm/file_open`` refuses such a
task the opening of anything but a directory in the private bpffs,
since a pin opened as a file reads a map's contents; directories stay
- listable. ``BPF_PROG_GET_FD_BY_ID`` and ``BPF_BTF_GET_FD_BY_ID`` stay
- allowed. Root without runtime authority therefore cannot read
+ listable. ``BPF_PROG_GET_FD_BY_ID`` stays allowed for types other than
+ XDP. ``lsm/bpf_prog`` keeps XDP descriptors to runtime authority,
+ since netlink can attach them without passing through ``bpf()``.
+ ``BPF_BTF_GET_FD_BY_ID`` stays allowed. Root without authority cannot read
shirudo's maps or hold one of its links open by pin or by id.
``lsm/file_ioctl`` refuses ``PERF_EVENT_IOC_SET_BPF``, which binds a
program to a perf event without a ``bpf()`` command, to the same
@@ -225,7 +227,8 @@ order:
the recorder notes the mount, and freeze that record.
#. Load ``seal`` on the shared maps, freeze its scratch map, and attach
its twenty-seven hooks, then ``mmap_file`` and ``file_mprotect``.
-#. Attach ``lsm/bpf_map``, then ``lsm/bpf_prog_load``, then ``lsm/bpf``.
+#. Attach ``lsm/bpf_map``, then ``lsm/bpf_prog``, then
+ ``lsm/bpf_prog_load``, then ``lsm/bpf``.
``init`` pins every link as it attaches it, before the next fallible
step. A link that is not pinned detaches when ``init`` exits, and a
@@ -321,6 +324,12 @@ when the record it needs is missing.
- ``EACCES``
- ``MapFdWrite`` (writable), ``ObjGet`` (read-only)
- Closed.
+ * - ``lsm/bpf_prog`` (``bpf2``)
+ - An XDP program descriptor to a task without authority, including
+ acquisition by program ID. Other program types stay allowed.
+ - ``EACCES``
+ - ``ObjGet``
+ - Closed.
* - ``lsm/file_open`` (``bpf2``)
- Opening a non-directory inode of the private bpffs, through any
mount of it, to a task without authority. Records the bpffs mount
@@ -589,7 +598,8 @@ The hooks decide only what reaches them. These paths do not:
- The ``kernel`` argument is true for every ``bpf()`` call through a
kernel pointer, including BPF that kernel code loads with
``kern_sys_bpf()``, such as a light skeleton in a module.
-- ``BPF_PROG_GET_FD_BY_ID`` stays open. ``lsm/bpf`` and
+- ``BPF_PROG_GET_FD_BY_ID`` stays open except for XDP descriptors,
+ which ``lsm/bpf_prog`` guards. ``lsm/bpf`` and
``lsm/file_ioctl`` refuse the ``bpf()`` attach commands and the perf
ioctl to tasks without authority; other kernel interfaces that take a
program descriptor are not hooked here.
diff --git a/Documentation/internals/kernel-interfaces.rst b/Documentation/internals/kernel-interfaces.rst
index addbbd14..07fd2764 100644
--- a/Documentation/internals/kernel-interfaces.rst
+++ b/Documentation/internals/kernel-interfaces.rst
@@ -62,6 +62,18 @@ hooks and the trusted ``d_parent`` are not in bpf-next;
:doc:`kernel-patches` lists the patches the test kernel carries. A
kernel is admitted by the ABI check below, not by its release string.
+XDP attachment
+--------------
+
+XDP uses ``BPF_LINK_CREATE`` with ``attach_type=BPF_XDP``,
+``target_ifindex`` from runtime discovery and ``flags=XDP_FLAGS_DRV_MODE``.
+shirudo verifies ``BPF_LINK_TYPE_XDP`` and the returned ``xdp.ifindex``
+before pinning. Discovery uses kernel ``RTM_GETLINK`` replies,
+``ETHTOOL_GDRVINFO`` and devlink ``DEVLINK_CMD_PORT_GET``; it does not
+read sysfs to classify devices. The ``lsm/bpf_prog`` guard refuses XDP
+descriptors to unauthorized callers, including ``BPF_PROG_GET_FD_BY_ID``,
+because netlink accepts these descriptors outside ``bpf()``.
+
Signing ABI check
-----------------
@@ -188,12 +200,17 @@ where the caller is the loader.
``BPF_TRACE_UPROBE_MULTI``, ``offsets``, ``cnt``, ``flags``
``BPF_F_UPROBE_MULTI_PATH_FD``, ``path_fd`` a descriptor of the
target binary opened and checked by build ID.
+ Kind 8, XDP: ``target_ifindex`` a selected device,
+ ``attach_type`` ``BPF_XDP``, ``flags`` ``XDP_FLAGS_DRV_MODE``.
* - ``BPF_OBJ_GET_INFO_BY_FD``
- On each link before it is pinned. Cgroup links: ``cgroup_id`` 1.
Netfilter: ``pf``, ``hooknum``, ``priority`` as set, and the
caller's network namespace cookie (``SO_NETNS_COOKIE``) 7. Kprobe:
perf event type, function name and offset as signed. Uprobe:
offset count. ``fmod_ret``: ``BPF_MODIFY_RETURN``.
+ XDP: ``BPF_LINK_TYPE_XDP`` and ``xdp.ifindex`` matching the selected
+ device; the initial namespace, device class and peer scope are
+ rechecked around attachment.
* - ``BPF_OBJ_PIN``
- Links at ``upatches/<name>/link`` or ``link_<n>``, serializer
programs at ``serializers/<map>``, the test-run program at
diff --git a/Documentation/internals/signed-loader.rst b/Documentation/internals/signed-loader.rst
index b997393f..4dac40d8 100644
--- a/Documentation/internals/signed-loader.rst
+++ b/Documentation/internals/signed-loader.rst
@@ -131,6 +131,9 @@ loader inside the kernel, which ``lsm/bpf`` sees with ``kernel`` true.
- ``lsm/bpf``, runtime authority (``ProgAttach``). shirudo then
compares the link the kernel reports with the signed metadata and
refuses ``attach_scope_mismatch`` when they differ.
+ XDP expands each program's signed class mask into links on matching
+ interfaces in the initial network namespace, with one endpoint per
+ veth pair, using native driver mode only.
* - userspace
- ``BPF_OBJ_PIN`` of each link and map
- ``lsm/bpf``, runtime authority (``ObjPin``), and the bpffs inode
@@ -155,6 +158,10 @@ dot in the name is written as ``~d`` there. The directory carries the
``security.bpf.shirudo.payload`` extended attribute with the payload
digest, which only a task with runtime authority can set.
:doc:`kernel-interfaces` lists the attributes each call sets.
+Artifacts containing XDP always use ``link_<n>`` pins, including when only
+one link is created. Every XDP program must attach somewhere; unsupported
+native-XDP devices are skipped, and any other attachment failure removes
+all links the load created.
Telling the loader apart from root
----------------------------------
diff --git a/Documentation/operate/plan/interoperability.rst b/Documentation/operate/plan/interoperability.rst
index 4ade7084..4cbb3914 100644
--- a/Documentation/operate/plan/interoperability.rst
+++ b/Documentation/operate/plan/interoperability.rst
@@ -73,7 +73,7 @@ runtime authority:
- ``MapFdWrite``
* - ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID``,
``BPF_LINK_GET_FD_BY_ID``, a read-only map descriptor, opening a
- pin in shirudo's private bpffs
+ pin in shirudo's private bpffs, an XDP program descriptor
- ``ObjGet``
* - ``BPF_LINK_CREATE``, ``BPF_RAW_TRACEPOINT_OPEN``
- ``ProgAttach``
diff --git a/Documentation/reference/cli/upatch-load.rst b/Documentation/reference/cli/upatch-load.rst
index 1fd3f095..d2a11539 100644
--- a/Documentation/reference/cli/upatch-load.rst
+++ b/Documentation/reference/cli/upatch-load.rst
@@ -86,6 +86,13 @@ them before it acts.
LSM still apply. ``bpm`` passes it when it loads the upatches of a
package.
+For XDP, the signed device-class mask selects interfaces present in the
+initial network namespace at load time, with one endpoint per veth pair.
+Each program can produce several ``link_<n>`` pins. Native XDP is
+required: unsupported devices are logged and skipped, and no attachable
+device is ``attach_target_missing``. Other errors undo all links the load
+created. :doc:`/upatches/write/attach-kinds` defines the classes and limits.
+
Options
-------
@@ -176,11 +183,13 @@ Exit status and failure categories
- The upatch is loaded and measured.
* - 1
- Refused or failed. The report and the message name the category.
+ Includes XDP with no attachable target (``ENODEV``).
* - 2
- A usage error: an unknown option, an option given last without
its value, a second file, no file, or an ``--expect-chain`` that
- is not 64 hexadecimal characters. Also the category
- ``attach_target_missing``.
+ is not 64 hexadecimal characters. Also ``attach_target_missing``
+ for missing probe targets; XDP ``ENODEV`` returns 1 so tree sync
+ does not advance past an unattached device policy.
``load`` reports these categories: ``version_mismatch``,
``kernel_abi_unsupported``, ``keyring_missing``, ``tampered``,
diff --git a/Documentation/reference/failure-categories.rst b/Documentation/reference/failure-categories.rst
index 6de97f37..241a0f98 100644
--- a/Documentation/reference/failure-categories.rst
+++ b/Documentation/reference/failure-categories.rst
@@ -129,11 +129,14 @@ Categories
``shirudo upatch info``.
* - ``attach_target_missing``
- ``target_verify``, ``link_create``
- - ``ENOENT``, ``ENOTDIR``
+ - ``ENOENT``, ``ENOTDIR``, ``ENODEV``
- The uprobe binary, the kprobe symbol or its module is absent.
``upatch load`` exits 2. ``bpm tree sync`` records the operation as
``skipped: module not loaded`` and continues.
- - Load the module or install the binary, then load again.
+ XDP with no attachable interface reports ``ENODEV`` and exits 1;
+ tree sync fails without advancing that operation.
+ - Load the module, install the binary or provide an interface with
+ native XDP support in a selected class, then load again.
* - ``binary_mismatch``
- ``target_verify``, ``link_create``
- ``ESTALE``
@@ -175,6 +178,8 @@ Categories
metadata names: a cgroup link not at the root cgroup, a netfilter
link outside the initial network namespace or at another hook or
priority, a kprobe at another function or offset.
+ For XDP, a non-initial network namespace, changed device class or
+ peer scope, or a returned link with another ifindex.
- Run the load in the host's initial cgroup and network namespaces
and with the host's sysfs.
* - ``already_loaded``
diff --git a/Documentation/reference/files.rst b/Documentation/reference/files.rst
index ee7043cd..b7f99f5a 100644
--- a/Documentation/reference/files.rst
+++ b/Documentation/reference/files.rst
@@ -327,7 +327,7 @@ by ``BPF_OBJ_GET`` (``ObjGet``). Directories stay listable.
* - ``lsm_link``
- Link of ``lsm/bpf``, the ``bpf()`` admission hook. Its presence
makes the ``LsmAttached`` condition report ``OK``.
- * - ``bpf2_bpf_map_link``, ``bpf2_bpf_prog_load_link``,
+ * - ``bpf2_bpf_map_link``, ``bpf2_bpf_prog_link``, ``bpf2_bpf_prog_load_link``,
``bpf2_inode_unlink_link``, ``bpf2_inode_setxattr_link``,
``bpf2_inode_removexattr_link``, ``bpf2_key_permission_link``,
``bpf2_tpm_command_link``
@@ -378,9 +378,11 @@ written as ``~d``.
* - Pin
- Content
* - ``link``
- - The link of the only attached program.
+ - The link of the only attached program, when the artifact has no XDP.
* - ``link_<n>``
- - The link of attached program ``<n>`` when there are several.
+ - Attachment ``<n>`` when there are several programs or the artifact
+ contains XDP. XDP can produce multiple links per program, ordered
+ by program and then ifindex; skipped devices consume no pin number.
* - ``test``
- A program with the test-run role.
* - ``serializers/<map>``
diff --git a/Documentation/reference/formats/upatch-format.rst b/Documentation/reference/formats/upatch-format.rst
index 02c504bd..3c3886dd 100644
--- a/Documentation/reference/formats/upatch-format.rst
+++ b/Documentation/reference/formats/upatch-format.rst
@@ -360,9 +360,11 @@ Each program entry is 160 bytes:
roles.
* - +8
- 8
- - ``offset``
- - Byte offset into the function for ``kprobe``. 0 for every other
- kind and role.
+ - ``offset`` / ``xdp``
+ - Byte offset into the function for ``kprobe``. For XDP, a
+ little-endian ``u32 device_classes`` followed by ``u32 reserved``
+ (0). The mask is nonzero and uses only bits 1, 2, 4, 8 and 16.
+ 0 for every other kind and role.
* - +16
- 128
- ``target``
@@ -424,8 +426,16 @@ Each program entry is 160 bytes:
* - 7
- uprobe.multi entry probe
- ``uprobe.multi/<absolute-path>:<function-glob>``
+ * - 8
+ - native XDP device classes
+ - ``xdp/<decimal-mask>``
:doc:`/upatches/write/attach-kinds` describes how the target attaches each kind.
+XDP retains the 160-byte entry and UPGM version 1; readers that do not
+know kind 8 refuse it. Its ``target`` and ``map`` are empty. Device-class
+bits mean network-facing (1), virtual (2), VM (8) and unknown (16); 27
+selects all classes. Bit 4 is not a class, and a reader refuses a mask
+that sets it or any bit above 16.
When any entry has kind 7, one ``UPUT`` block follows the program entries
and ends the section. Without a kind 7 entry the section ends after the
diff --git a/Documentation/security/tamper-counters.rst b/Documentation/security/tamper-counters.rst
index e50025b5..afd8fa54 100644
--- a/Documentation/security/tamper-counters.rst
+++ b/Documentation/security/tamper-counters.rst
@@ -200,10 +200,11 @@ counter.
from any caller
- ``EACCES``
* - ``ObjGet``
- - pin, map or link opened by another executable
+ - pin, map, link or XDP program opened by another executable
- ``lsm/bpf``: ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID``,
``BPF_LINK_GET_FD_BY_ID``; ``lsm/bpf_map``: a read-only
- descriptor; ``lsm/file_open`` in the ``bpf2`` object: a
+ descriptor; ``lsm/bpf_prog``: an XDP program descriptor;
+ ``lsm/file_open`` in the ``bpf2`` object: a
non-directory inode in the private bpffs
- ``EACCES``
* - ``SealSignal``
diff --git a/Documentation/security/threat-model.rst b/Documentation/security/threat-model.rst
index dc8cf7a9..053d5f33 100644
--- a/Documentation/security/threat-model.rst
+++ b/Documentation/security/threat-model.rst
@@ -585,8 +585,11 @@ refuses ``BPF_OBJ_GET``, ``BPF_MAP_GET_FD_BY_ID`` and
``lsm/file_open`` in the ``bpf2`` object refuses them the opening of any
non-directory inode in the private bpffs (``ObjGet``). Directories stay
listable. ``BPF_PROG_GET_FD_BY_ID`` and ``BPF_BTF_GET_FD_BY_ID`` stay
-open, because a descriptor of a program type shirudo ships attaches
-nowhere without the commands above or the ioctl below (R18).
+open for other program types. ``lsm/bpf_prog`` refuses an XDP descriptor
+to a task without runtime authority (``ObjGet``), including acquisition by
+ID, because netlink accepts it outside the ``bpf()`` attach guard. Other
+shipped types attach nowhere without the commands above or the ioctl
+below (R18).
The one attach that does not pass through ``bpf()`` is
``PERF_EVENT_IOC_SET_BPF``, which binds a program reached by id to a
@@ -624,11 +627,15 @@ caller's network namespace, and a kprobe through the PMU that sysfs
names. The load compares the link the kernel reports with the signed
attach metadata before it pins the link, and refuses
``attach_scope_mismatch``.
+XDP discovery requires the initial network namespace, classifies devices
+from kernel interfaces and expands the signed device-class mask there.
+It selects one endpoint per veth pair and checks device class, peer scope
+and the returned link's ifindex around attachment.
.. rst-class:: facts
:Adversary: ADV-B, root on the target without the signing key
-:Enforced at: ``lsm/bpf``, ``lsm/file_open``, ``lsm/file_ioctl``,
+:Enforced at: ``lsm/bpf``, ``lsm/bpf_prog``, ``lsm/file_open``, ``lsm/file_ioctl``,
``lsm/file_ioctl_compat``, ``lsm/inode_unlink``,
``lsm/inode_rename``, ``lsm/inode_mkdir``, ``lsm/inode_symlink``,
``lsm/inode_link``, ``lsm/inode_rmdir``, ``lsm/inode_setxattr``,
@@ -641,7 +648,7 @@ attach metadata before it pins the link, and refuses
``PerfAttach``, ``PinUnlink``, ``PinRename``, ``PinEntry``,
``PinXattr``, ``BpffsUmount``, ``BpffsUmountAbove``, ``BpffsMount``
:Tests: ``t6105``, ``t6106``, ``t6107``, ``t6108``, ``t6109``,
- ``t6116``, ``t6119``, ``t6120``, ``t6121``, ``t6138``
+ ``t6116``, ``t6119``, ``t6120``, ``t6121``, ``t6138``, ``t3111``
:Residual: R1, R2, R3, U17
.. _tm-t3:
@@ -1511,11 +1518,12 @@ R18 BPF outside the gates
loaded through ``kern_sys_bpf()``, such as the ``bpf_preload`` module,
which a signed module can bring in (A4). Classic BPF, for seccomp
filters and ``SO_ATTACH_FILTER``, does not use ``bpf()``. Program
- descriptors stay open to root, and the attach paths outside
+ descriptors other than XDP stay open to root, and the attach paths outside
``bpf()`` that take one, socket options and netlink among them,
accept only program types those paths support. The operator's build
- refuses sections of those types; the kernel does not refuse them in
- a signed loader.
+ refuses sections of those types except XDP, whose descriptors
+ ``lsm/bpf_prog`` guards; the kernel does not refuse these types in a
+ signed loader.
R19 Raw device and offline writes bypass the seal
The seal guards file operations. A write to the block device under
@@ -1534,13 +1542,20 @@ R20 The TPM owner password is not a secret on the target
owner hierarchy.
An image shared across a fleet shares the password.
-R21 upatches can be neutralized without detaching them
+R21 upatches can be neutralized by changing their targets
An upatch stays loaded and measured while root makes it ineffective:
by unloading the module a kprobe targets, by replacing the binary a
``uprobe.multi`` target names with a new inode, or, without lockdown
(A4), by disabling kprobes through debugfs. These are readings of the
kernel source and are not tested.
+ XDP discovery is a load-time snapshot: creating interfaces later does
+ not attach the upatch to them. Removing a device can detach its XDP
+ link while its pin remains, and changing topology can bypass the
+ selected ingress path. TPM evidence covers the signed class mask and
+ loaded artifact, not the live device inventory. ``t3111`` exercises
+ load-time selection and signed unload; hotplug is not reconciled.
+
R22 Labeled inodes are interchangeable
The label carries no identity. Any labeled inode passes shirudo's
checks at any sealed path, and ``lsm/sb_mount`` does not guard the
diff --git a/Documentation/upatches/write/attach-kinds.rst b/Documentation/upatches/write/attach-kinds.rst
index 501a0dd8..d6a293ac 100644
--- a/Documentation/upatches/write/attach-kinds.rst
+++ b/Documentation/upatches/write/attach-kinds.rst
@@ -66,6 +66,10 @@ the link against the metadata and pins it.
- netfilter
- ``BPF_LINK_CREATE``, ``BPF_NETFILTER``, IPv6 pre-routing
- ``CONFIG_NETFILTER``, ``CONFIG_NETFILTER_BPF_LINK``
+ * - ``xdp/<decimal-mask>``
+ - XDP
+ - ``BPF_LINK_CREATE``, ``BPF_XDP``, native driver mode
+ - native XDP support on selected devices
* - ``syscall``, named ``shirudo_serialize__<map>``
- syscall
- not attached, run by ``shirudo upatch map``
@@ -83,6 +87,8 @@ Every attached program becomes one link pinned at
``/run/shirudo/bpffs/upatches/<name>/link`` when the upatch has one attach
program, and at ``link_0``, ``link_1`` and so on, in the order of the
object, when it has several. ``<name>`` has every ``.`` written as ``~d``.
+An upatch containing XDP always uses ``link_0``, ``link_1`` and so on,
+because one program can attach to several interfaces.
fentry and fexit
----------------
@@ -236,6 +242,73 @@ shirudo fixes the family, hook and priority. The section name carries
none of them. A shield that needs another family or hook is written as a
``cgroup_skb`` or ``lsm`` program.
+XDP
+---
+
+``xdp/<decimal-mask>`` signs a device-class selection, rather than a
+device name or an ifindex. For example, ``SEC("xdp/3")`` selects network
+ports and virtual devices; ``SEC("xdp/27")`` selects all classes. The
+mask is mandatory, nonzero and contains only the bits below. Bare
+``xdp``, ``xdp.frags``, devmap and cpumap sections are refused.
+
+.. list-table::
+ :header-rows: 1
+ :widths: 12 22 66
+
+ * - Bit
+ - Class
+ - Devices
+ * - 1
+ - Network-facing
+ - Hardware-backed NICs and physical devlink ports.
+ * - 2
+ - Virtual
+ - Software interfaces, host tap devices and devlink representors.
+ * - 8
+ - VM
+ - Guest adapters using virtio-net, vmxnet3, Hyper-V netvsc or Xen
+ netfront. Emulated hardware and passthrough NICs use their
+ hardware class.
+ * - 16
+ - Unknown
+ - Devices without sufficient classification evidence. This bit is
+ a catchall class, not a wildcard; 27 selects every class.
+
+Bit 4 is not a class, and a mask with it is refused. Loopback has no
+native XDP, so it has no class and no mask selects it. Every other
+interface has exactly one class. shirudo checks the driver names ``virtio_net``, ``vmxnet3``, ``hv_netvsc``,
+``xen-netfront`` and ``vif`` for VM adapters. Next it uses devlink port
+flavour: physical ports are network-facing; CPU, DSA, PCI PF, VF, SF
+and virtual ports are virtual; other flavours are unknown. Without a
+devlink port, ``netdevsim`` is virtual, a device with a hardware parent
+bus is network-facing, a device with a kernel software link kind is
+virtual, and the rest are unknown. Facts come from rtnetlink, devlink
+and ethtool, without interface-name or sysfs heuristics.
+
+At load and boot restore, shirudo snapshots interfaces in the initial
+network namespace, selects matching classes and attaches in increasing
+ifindex order. A veth pair gets one attachment: the endpoint in the
+initial namespace when its peer is elsewhere, or the lower ifindex when
+both ends are in that namespace. Peer namespace information prevents
+equal ifindexes in separate namespaces from being mistaken for a pair.
+Pairs entirely outside the initial namespace are excluded.
+
+Links use ``XDP_FLAGS_DRV_MODE``. Devices that refuse native XDP with
+``EOPNOTSUPP``, such as a bridge, are logged and skipped. Every XDP
+program must attach to at least one device, else the load fails with
+``attach_target_missing``. Other errors, including an occupied XDP
+attachment point or changed device scope, undo the load's links. Existing
+XDP programs are never replaced. Device classification and peer identity
+are rechecked around attachment, and the returned link's ifindex is
+checked before pinning.
+
+Discovery runs once per load or restore. New devices require reload;
+there is no background reconciliation. Removing a device can detach its
+XDP link while its pin remains. The signed artifact and TPM measurement
+cover the class policy, not a fixed device inventory.
+Boot restore requires a matching native-XDP interface to be present when
+``init`` restores the archive; otherwise initialization fails.
+
Programs that attach nowhere
----------------------------
diff --git a/Documentation/upatches/write/memory-consistency/hazards.rst b/Documentation/upatches/write/memory-consistency/hazards.rst
index a74b09b1..cabb0f29 100644
--- a/Documentation/upatches/write/memory-consistency/hazards.rst
+++ b/Documentation/upatches/write/memory-consistency/hazards.rst
@@ -66,6 +66,12 @@ program types against a second run and not others:
egress run on the same CPU, and an ingress run in a softirq can
run on top of it. ``netfilter`` programs run at IPv6
pre-routing, mostly in a softirq.
+ * - ``xdp``
+ - Run in a device's NAPI poll with bottom halves disabled, and are not
+ guarded. No task and no other softirq comes between on one CPU,
+ except on ``PREEMPT_RT``, where a bottom-half section can be
+ preempted. An interrupt or NMI can run other programs on top. The
+ receive queues of a device run on different CPUs at once.
The table covers the attach kinds ``shirudo build`` accepts, which
:doc:`/upatches/write/attach-kinds` lists.
@@ -104,7 +110,8 @@ kernel.
``syscall`` and sleepable programs, and where a program that an
interrupt, a softirq or an NMI runs shares the memory with one
that a process runs. Not where only ``kprobe`` and ``kretprobe``
- programs use it, nor where one guarded program uses it alone.
+ programs use it, nor where one guarded program uses it alone, nor,
+ outside ``PREEMPT_RT``, where only ``xdp`` programs use it.
* - Updates of shared values, inserting a missing key,
compare-and-swap, using a value after deleting its entry, reading
user memory twice
diff --git a/Documentation/upatches/write/pitfalls.rst b/Documentation/upatches/write/pitfalls.rst
index 474a5382..ca7308fe 100644
--- a/Documentation/upatches/write/pitfalls.rst
+++ b/Documentation/upatches/write/pitfalls.rst
@@ -35,8 +35,8 @@ program's ``recursion_misses``, which ``struct bpf_prog_info`` reports:
and twice the number of CPUs.
A detector built on these kinds can therefore miss the event it looks
-for, and a count it keeps is a lower bound. ``lsm`` programs are never
-skipped.
+for, and a count it keeps is a lower bound. ``lsm`` and ``xdp`` programs
+are never skipped.
Enforce in lsm programs
-----------------------
@@ -77,7 +77,29 @@ was running. There ``bpf_get_current_pid_tgid()``,
``bpf_get_current_task_btf()``, ``bpf_get_current_comm()`` and
``bpf_get_current_cgroup_id()`` describe that task, not the packet.
Attribute a packet by its socket, with ``bpf_skb_cgroup_id()`` or
-socket storage, and keep such programs off task storage.
+socket storage, and keep such programs off task storage. An ``xdp``
+program runs there too, before the packet has a socket, so nothing
+attributes it: decide on the packet alone.
+
+What an xdp program does not see
+--------------------------------
+
+``xdp`` runs in the driver on receive, before the kernel builds an
+``sk_buff``:
+
+- It sees what a device receives, not what the host sends out of it. On
+ a veth pair with one endpoint attached, it sees only what arrives at
+ that endpoint.
+- It sees only the devices it is attached to, and a device with no program
+ passes everything. :doc:`attach-kinds` says which devices are selected
+ and when.
+- It sees packets as they arrive, before GRO joins them, so a transfer
+ is many runs.
+- A VLAN tag the NIC stripped is not in the packet.
+- It sees one buffer per packet. ``xdp/<mask>`` programs are loaded without
+ multi-buffer support, as ``xdp.frags`` is refused, and a driver refuses
+ them outright on a device whose MTU does not fit one buffer, which
+ leaves that device uncovered.
RCU pointers in sleepable programs
----------------------------------
diff --git a/Makefile.shirudo b/Makefile.shirudo
index 5d2dfd88..fd8f3f43 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -221,6 +221,7 @@ UTIL_SRCS := \
$(TLS_SRC) \
util/loader.c \
util/upatch.c \
+ util/xdp.c \
util/measured.c \
util/keyring.c \
util/keys.c \
@@ -678,6 +679,7 @@ TEST_HELPERS := $(VERITY_TEST_HELPERS) \
testing/helper/test-upatch-serializer-pages \
testing/helper/test-signed-load \
testing/helper/test-upatch-link-lockdown \
+ testing/helper/test-xdp \
testing/helper/test-exec-churn \
testing/end2end/exec-paths \
testing/end2end/policy-exec
@@ -808,6 +810,10 @@ testing/helper/test-upatch-link-lockdown: testing/helper/test-upatch-link-lockdo
@printf ' CC $@\n'
$(Q)$(CC) $(CFLAGS) -I$(BPF_UAPI_INCLUDE) -o $@ $^
+testing/helper/test-xdp: testing/helper/test-xdp.c $(LIBBPF_A)
+ @printf ' CC $@\n'
+ $(Q)$(CC) $(CFLAGS) -o $@ $^ $(LIBELF_LIBS) $(ZLIB_LIBS)
+
# Needs the vendored uapi bpf.h (excl_prog_hash / fd_array_cnt / keyring_id
# are newer than a stock system header) and libcrypto for SHA-256.
testing/helper/test-signed-load: testing/helper/test-signed-load.c
diff --git a/bpf/bpf2.c b/bpf/bpf2.c
index d5d25c23..69a457de 100644
--- a/bpf/bpf2.c
+++ b/bpf/bpf2.c
@@ -147,6 +147,17 @@ int BPF_PROG(shirudo_lsm_bpf_map, struct bpf_map *map, fmode_t fmode,
return shirudo_self_or_deny(TAMPER_OBJ_GET);
}
+/* XDP descriptors also authorize netlink attachment, outside lsm/bpf. */
+SEC("lsm/bpf_prog")
+int BPF_PROG(shirudo_lsm_bpf_prog, struct bpf_prog *prog, int ret)
+{
+ if (ret)
+ return ret;
+ if (BPF_CORE_READ(prog, type) == BPF_PROG_TYPE_XDP)
+ return shirudo_self_or_deny(TAMPER_OBJ_GET);
+ return 0;
+}
+
/*
* Admission gate. Fires from a single call site inside the verifier
* (bpf_check), after the kernel has verified any PKCS#7 signature and
diff --git a/builtin-init.c b/builtin-init.c
index 26ca59d3..9250071a 100644
--- a/builtin-init.c
+++ b/builtin-init.c
@@ -579,22 +579,24 @@ static int record_ek_name(struct identity *id)
static int init_lsm(void)
{
- struct bpf_link *image_links[IMAGE_OBSERVER_HOOK_COUNT] = {};
- struct bpf_link *image_seal[IMAGE_SEAL_HOOK_COUNT] = {};
- struct bpf_link *link_setx = NULL, *link_rmx = NULL, *link_pload = NULL;
struct bpf_link *identity_links[ARRAY_SIZE(shirudo_observer_guards)] = {};
+ struct bpf_link *link_setx = NULL, *link_rmx = NULL, *link_pload = NULL;
struct bpf_link *mount_links[ARRAY_SIZE(shirudo_mount_guards)] = {};
struct bpf_program *p_bpf, *p_bpf_map, *p_unlink, *p_setx, *p_rmx;
- const struct embedded_bpf *blob = bpf2_blob();
- struct bpf_link *seal_links[SEAL_HOOK_COUNT] = {};
+ struct bpf_link *image_links[IMAGE_OBSERVER_HOOK_COUNT] = {};
+ struct bpf_link *image_seal[IMAGE_SEAL_HOOK_COUNT] = {};
struct bpf_link *link_bpf = NULL, *link_bpf_map = NULL;
- struct bpf_object *obj = NULL, *seal_obj = NULL;
struct bpf_link *link_keyperm = NULL, *link_tpm = NULL;
+ struct bpf_link *seal_links[SEAL_HOOK_COUNT] = {};
+ struct bpf_object *obj = NULL, *seal_obj = NULL;
+ const struct embedded_bpf *blob = bpf2_blob();
+ struct bpf_link *link_bpf_prog = NULL;
struct bpf_link *link_unlink = NULL;
- struct identity id = {};
+ struct bpf_program *p_key, *p_tpm;
+ struct bpf_program *p_bpf_prog;
struct anchor_keys keys = {};
struct bpf_program *p_pload;
- struct bpf_program *p_key, *p_tpm;
+ struct identity id = {};
key_serial_t keyring;
struct bpf_map *m_sb;
int err, map_fd, i;
@@ -757,11 +759,12 @@ static int init_lsm(void)
p_rmx = guard_program(obj, GUARD_REMOVEXATTR);
p_pload = guard_program(obj, GUARD_PROG_LOAD);
p_bpf_map = guard_program(obj, GUARD_BPF_MAP);
+ p_bpf_prog = guard_program(obj, GUARD_BPF_PROG);
p_key = guard_program(obj, GUARD_KEY_PERMISSION);
p_tpm = guard_program(obj, GUARD_TPM_COMMAND);
p_bpf = guard_program(obj, GUARD_BPF);
if (!p_unlink || !p_setx || !p_rmx || !p_pload || !p_bpf_map ||
- !p_bpf ||
+ !p_bpf || !p_bpf_prog ||
!p_key || !p_tpm) {
pr_err("expected programs missing in bpf2 object");
err = -ENOENT;
@@ -825,6 +828,12 @@ static int init_lsm(void)
goto out;
}
+ err = attach_guard(p_bpf_prog, GUARD_BPF_PROG, &link_bpf_prog);
+ if (err) {
+ pr_err("attach lsm/bpf_prog: %s", strerror(-err));
+ goto out;
+ }
+
err = attach_guard(p_pload, GUARD_PROG_LOAD, &link_pload);
if (err) {
pr_err("attach lsm/bpf_prog_load: %s", strerror(-err));
@@ -868,7 +877,8 @@ out:
}
if (err) {
struct bpf_link *links[] = {
- link_bpf, link_bpf_map, link_pload, link_keyperm, link_tpm,
+ link_bpf, link_bpf_map, link_bpf_prog, link_pload,
+ link_keyperm, link_tpm,
link_rmx, link_setx, link_unlink,
};
@@ -886,6 +896,7 @@ out:
bpf_object__close(seal_obj);
bpf_link__destroy(link_bpf);
bpf_link__destroy(link_bpf_map);
+ bpf_link__destroy(link_bpf_prog);
bpf_link__destroy(link_pload);
bpf_link__destroy(link_keyperm);
bpf_link__destroy(link_tpm);
diff --git a/builtin-upatch.c b/builtin-upatch.c
index 1fc16c2c..751fd8e1 100644
--- a/builtin-upatch.c
+++ b/builtin-upatch.c
@@ -26,6 +26,7 @@
#include <linux/bpf.h>
#include <linux/perf_event.h>
+#include <linux/if_link.h>
#include <linux/keyctl.h>
#include <bpf/bpf.h>
@@ -64,6 +65,7 @@
#include "util/upatch_resolve.h"
#include "util/upatch_table.h"
#include "util/version.h"
+#include "util/xdp.h"
#ifndef NFPROTO_IPV6
#define NFPROTO_IPV6 10
@@ -1049,6 +1051,8 @@ static const char *attach_kind_name(__u32 kind)
return "netfilter/ipv6-pre-routing";
case UPATCH_ATTACH_UPROBE_MULTI:
return "uprobe.multi";
+ case UPATCH_ATTACH_XDP:
+ return "xdp";
default:
return "unknown";
}
@@ -1214,7 +1218,7 @@ static int netns_initial(void)
* link is pinned; -EXDEV when they differ.
*/
static int link_matches_spec(int link_fd,
- const struct prog_spec *spec)
+ const struct prog_spec *spec, __u32 ifindex)
{
char func[UPATCH_ATTACH_TARGET_MAX] = {};
struct bpf_link_info info = {};
@@ -1232,6 +1236,11 @@ static int link_matches_spec(int link_fd,
return info.cgroup.cgroup_id == ROOT_CGROUP_ID ?
0 : -EXDEV;
switch (spec->kind) {
+ case UPATCH_ATTACH_XDP:
+ if (info.type != BPF_LINK_TYPE_XDP || !ifindex ||
+ info.xdp.ifindex != ifindex)
+ return -EXDEV;
+ return netns_initial();
case UPATCH_ATTACH_CGROUP_SKB_INGRESS:
case UPATCH_ATTACH_CGROUP_SKB_EGRESS:
return -EXDEV;
@@ -1322,6 +1331,60 @@ static int prog_pin_path(char *pin, size_t sz, const char *dir,
return n < 0 ? -ENAMETOOLONG : 0;
}
+static int attach_xdp_devices(int prog_fd, const struct prog_spec *spec,
+ const struct xdp_device *devices, size_t count,
+ const char *dir, __u32 *pinned)
+{
+ LIBBPF_OPTS(bpf_link_create_opts, opts, .flags = XDP_FLAGS_DRV_MODE);
+ __u32 attached = 0;
+ size_t i;
+
+ for (i = 0; i < count; i++) {
+ const struct xdp_device *dev = &devices[i];
+ char pin[PATH_MAX + 32];
+ int fd, ret;
+
+ if (!xdp_device_selected(devices, count, i, spec->device_classes))
+ continue;
+ if (*pinned == UINT32_MAX)
+ return -EOVERFLOW;
+ if (strsprintf(pin, sizeof(pin), "%s/link_%u", dir, *pinned) < 0)
+ return -ENAMETOOLONG;
+ ret = xdp_device_verify(dev);
+ if (ret)
+ return ret;
+ fd = bpf_link_create(prog_fd, (int)dev->ifindex, BPF_XDP, &opts);
+ if (fd == -EOPNOTSUPP) {
+ pr_warn("XDP: skipping %s (ifindex %u, class %u): native XDP unsupported",
+ dev->name, dev->ifindex, xdp_device_class(dev));
+ continue;
+ }
+ if (fd < 0) {
+ pr_err("XDP: attach %s (ifindex %u): %s", dev->name,
+ dev->ifindex, strerror(-fd));
+ return fd;
+ }
+ ret = link_matches_spec(fd, spec, dev->ifindex);
+ if (!ret)
+ ret = xdp_device_verify(dev);
+ if (!ret)
+ ret = obj_pin(fd, pin);
+ close(fd);
+ if (ret)
+ return ret;
+ (*pinned)++;
+ attached++;
+ pr_info("XDP: attached %s (ifindex %u, class %u) at %s",
+ dev->name, dev->ifindex, xdp_device_class(dev), pin);
+ }
+ if (!attached) {
+ pr_err("XDP: no attachable interface matches signed class mask %u",
+ spec->device_classes);
+ return -ENODEV;
+ }
+ return 0;
+}
+
/*
* Serializers are pinned as programs for `upatch map`; the rest as links.
* A failure unpins what this call pinned: the upatch is then neither
@@ -1333,9 +1396,13 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
const struct prog_spec *specs)
{
char dir[PATH_MAX], serializers_dir[PATH_MAX + 16];
- __u32 i, attach_count = 0, attach_seen = 0;
bool made_dir = false, made_serializers = false;
+ __u32 i, attach_count = 0, attach_seen = 0;
+ struct xdp_device *devices = NULL;
char pin[PATH_MAX + 32];
+ __u32 pinned_links = 0;
+ size_t nr_devices = 0;
+ bool has_xdp = false;
bool *made = NULL;
int test_fd = -1;
int ret;
@@ -1346,6 +1413,9 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
}
if (upatch_pin_path(dir, sizeof(dir), name, NULL))
return -ENAMETOOLONG;
+ for (i = 0; i < nr_progs; i++)
+ if (specs[i].kind == UPATCH_ATTACH_XDP)
+ has_xdp = true;
ret = mkdir_if_absent(BPFFS_UPATCHES_DIR, 0700, NULL);
if (ret) {
@@ -1359,6 +1429,13 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
made = xcalloc(nr_progs, sizeof(*made));
if (!made)
return -ENOMEM;
+ if (has_xdp) {
+ ret = netns_initial();
+ if (!ret)
+ ret = xdp_devices_read(&devices, &nr_devices);
+ if (ret)
+ goto out;
+ }
ret = mkdir_if_absent(dir, 0700, &made_dir);
if (ret) {
pr_err("mkdir %s: %s", dir, strerror(-ret));
@@ -1436,6 +1513,24 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
continue;
}
attach_seen++;
+ if (spec->kind == UPATCH_ATTACH_XDP) {
+ ret = attach_xdp_devices(inner_fd, spec, devices, nr_devices,
+ dir, &pinned_links);
+ if (ret)
+ goto out;
+ continue;
+ }
+ if (has_xdp) {
+ if (pinned_links == UINT32_MAX) {
+ ret = -EOVERFLOW;
+ goto out;
+ }
+ if (strsprintf(pin, sizeof(pin), "%s/link_%u", dir,
+ pinned_links) < 0) {
+ ret = -ENAMETOOLONG;
+ goto out;
+ }
+ }
link_fd = prog_attach_for_spec(inner_fd, spec);
if (link_fd < 0) {
@@ -1456,7 +1551,7 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
goto out;
}
/* Unpinned, a closed link detaches. */
- ret = link_matches_spec(link_fd, spec);
+ ret = link_matches_spec(link_fd, spec, 0);
if (ret) {
pr_err("attach prog %u (%s %s): the link is not at "
"the site the metadata names: %s", i,
@@ -1472,6 +1567,8 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
goto out;
}
made[i] = true;
+ if (has_xdp)
+ pinned_links++;
pr_info("upatch load: program %u (%s) pinned at %s",
i, attach_kind_name(spec->kind), pin);
}
@@ -1492,9 +1589,16 @@ static int attach_and_pin_progs(const struct loader_ctx *cx,
}
out:
if (ret) {
+ while (pinned_links) {
+ pinned_links--;
+ if (strsprintf(pin, sizeof(pin), "%s/link_%u", dir,
+ pinned_links) >= 0)
+ unlink(pin);
+ }
attach_seen = 0;
for (i = 0; i < nr_progs; i++) {
if (made[i] &&
+ !(has_xdp && specs[i].role == UPATCH_PROG_ROLE_ATTACH) &&
!prog_pin_path(pin, sizeof(pin), dir,
serializers_dir, &specs[i],
attach_count, attach_seen))
@@ -1507,6 +1611,7 @@ out:
if (made_dir)
rmdir(dir);
}
+ xfree(devices, size_mul(nr_devices, sizeof(*devices)));
xfree(made, nr_progs * sizeof(*made));
return ret;
}
@@ -2149,7 +2254,7 @@ static int __upatch_apply(const char *path, bool verify_only,
int e = -ret;
const char *cat;
- if (e == ENOENT || e == ENOTDIR)
+ if (e == ENOENT || e == ENOTDIR || e == ENODEV)
cat = "attach_target_missing";
else if (e == ESTALE)
cat = "binary_mismatch";
@@ -2932,7 +3037,7 @@ static int upatch_load(const struct load_args *args)
done:
eventlog_unlock(lock);
if (ret == 1 && rep.category &&
- !strcmp(rep.category, "attach_target_missing"))
+ !strcmp(rep.category, "attach_target_missing") && rep.err != ENODEV)
ret = UPATCH_INSTALL_TARGET_MISSING;
if (staged[0])
unlink(staged);
diff --git a/include/shirudo/upatch.h b/include/shirudo/upatch.h
index 9746e75b..b9d9afc8 100644
--- a/include/shirudo/upatch.h
+++ b/include/shirudo/upatch.h
@@ -178,7 +178,8 @@ struct upatch_decoder_blob {
* Programs without a special attach kind use RAW_TRACEPOINT, preserving
* the original attach_btf_id behavior. The program bytes are hash-locked
* by the signed loader; the site a kprobe, uprobe, cgroup or netfilter
- * program attaches at comes from here, which is why it is signed.
+ * program attaches at, and the classes XDP may attach to, come from
+ * here, which is why it is signed.
*/
#define UPATCH_ATTACH_TARGET_MAX 128u
#define UPATCH_PROG_MAGIC 0x4d475055u /* "UPGM" le */
@@ -199,6 +200,16 @@ enum upatch_attach_kind {
UPATCH_ATTACH_FMOD_RET = 5,
UPATCH_ATTACH_NETFILTER_IPV6_PRE_ROUTING = 6,
UPATCH_ATTACH_UPROBE_MULTI = 7,
+ UPATCH_ATTACH_XDP = 8,
+};
+
+/* Bit 4 is not a class: loopback has no native XDP, so nothing selects it. */
+enum upatch_xdp_device_class {
+ UPATCH_XDP_NETWORK = 1,
+ UPATCH_XDP_VIRTUAL = 2,
+ UPATCH_XDP_VM = 8,
+ UPATCH_XDP_UNKNOWN = 16,
+ UPATCH_XDP_ALL = 27,
};
enum upatch_prog_role {
@@ -210,7 +221,13 @@ enum upatch_prog_role {
struct upatch_prog_entry {
__le32 role; /* enum upatch_prog_role */
__le32 kind; /* enum upatch_attach_kind */
- __le64 offset; /* kprobe offset; zero for kretprobe */
+ union {
+ __le64 offset; /* kprobe offset */
+ struct {
+ __le32 device_classes;
+ __le32 reserved;
+ } xdp;
+ };
char target[UPATCH_ATTACH_TARGET_MAX]; /* kprobe symbol */
char map[UPATCH_PROG_MAP_MAX];
};
diff --git a/testing/fixtures/xdp-virtual.bpf.c b/testing/fixtures/xdp-virtual.bpf.c
new file mode 100644
index 00000000..007f9815
--- /dev/null
+++ b/testing/fixtures/xdp-virtual.bpf.c
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+
+SEC("xdp/2")
+int xdp_virtual(struct xdp_md *ctx)
+{
+ return XDP_PASS;
+}
+
+char _license[] SEC("license") = "Dual BSD/GPL";
diff --git a/testing/fixtures/xdp-vm.bpf.c b/testing/fixtures/xdp-vm.bpf.c
new file mode 100644
index 00000000..d5beb49a
--- /dev/null
+++ b/testing/fixtures/xdp-vm.bpf.c
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+
+SEC("xdp/8")
+int xdp_vm(struct xdp_md *ctx)
+{
+ return XDP_PASS;
+}
+
+char _license[] SEC("license") = "Dual BSD/GPL";
diff --git a/testing/functional/image/t5104-verity-revocation.py b/testing/functional/image/t5104-verity-revocation.py
index ae51e650..8a80a75e 100644
--- a/testing/functional/image/t5104-verity-revocation.py
+++ b/testing/functional/image/t5104-verity-revocation.py
@@ -7,6 +7,7 @@ import importlib.util
import json
from pathlib import Path
import sys
+import subprocess
spec = importlib.util.spec_from_file_location(
"signer_test", Path(__file__).with_name("t5101-verity-boot-signers.py"))
@@ -18,6 +19,10 @@ NAME = "shirudo-test-revoked-key"
UPATCH = signer.FIXTURES / (NAME + ".upatch")
PIN = Path("/run/shirudo/bpffs/upatches") / NAME
ARCHIVE = Path("/var/lib/shirudo/upatches") / (NAME + ".upatch")
+XDP_NAME = "shirudo-test-revoked-xdp"
+XDP_UPATCH = signer.FIXTURES / (XDP_NAME + ".upatch")
+XDP_PIN = PIN.parent / XDP_NAME
+XDP_ARCHIVE = ARCHIVE.parent / (XDP_NAME + ".upatch")
def snapshot(label, expected):
@@ -30,9 +35,9 @@ def snapshot(label, expected):
return view
-def extension(before, after, kind, payload):
+def extension(before, after, kind, payload, name=NAME):
event = hashlib.sha256(b"shirudo-" + kind + b"\0" +
- bytes.fromhex(payload) + NAME.encode()).digest()
+ bytes.fromhex(payload) + name.encode()).digest()
expected = hashlib.sha256(bytes.fromhex(before["chain"]) + event).hexdigest()
require(after["chain"] == expected, "unexpected upatch NV extension")
@@ -64,7 +69,8 @@ def revocation_extensions(before, after):
f"wrong unload event digest: {event}")
unloaded.add(name)
chain = hashlib.sha256(chain + digest).digest()
- require(NAME in unloaded, "revoked signer upatch has no measured unload")
+ require({NAME, XDP_NAME} <= unloaded,
+ "revoked signer upatches have no measured unload")
require(after["chain"] == chain.hex(),
f"NV chain does not replay added revocation events: {events}")
@@ -73,8 +79,11 @@ def main():
mode = sys.argv[1]
if mode == "initial":
require(UPATCH.is_file(), "missing boot-signed upatch fixture")
+ require(XDP_UPATCH.is_file(), "missing boot-signed XDP fixture")
signer.check_members(signer.keyring())
require(not PIN.exists() and not ARCHIVE.exists(), "stale revoked upatch")
+ require(not XDP_PIN.exists() and not XDP_ARCHIVE.exists(),
+ "stale revoked XDP upatch")
before = snapshot("before", 2)
before["nv_events"] = len(
Path("/var/lib/shirudo/eventlog").read_text().splitlines())
@@ -88,6 +97,25 @@ def main():
after = snapshot("loaded", 2)
require(before["config"] == after["config"], "load changed CONFIG")
extension(before, after, b"upatch", info["payload_sha256"])
+ subprocess.run(["ip", "link", "add", "xdprev0", "type", "veth",
+ "peer", "name", "xdprev1"], check=True)
+ for device in ("xdprev0", "xdprev1"):
+ subprocess.run(["ip", "link", "set", device, "up"], check=True)
+ xdp_info = json.loads(config.run("xdp-info", "upatch", "info",
+ XDP_UPATCH, "--json"))
+ config.run("xdp-load", "upatch", "load", XDP_UPATCH, "--no-precheck")
+ require((XDP_PIN / "link_0").exists() and XDP_ARCHIVE.is_file(),
+ "XDP upatch not installed")
+ attached = []
+ for device in ("xdprev0", "xdprev1"):
+ query = subprocess.run(["helper/test-xdp", "query", device],
+ check=True, capture_output=True, text=True)
+ attached.append(int(query.stdout.strip()))
+ require(sum(bool(value) for value in attached) == 1,
+ "XDP must attach to exactly one veth endpoint")
+ xdp_after = snapshot("xdp-loaded", 2)
+ extension(after, xdp_after, b"upatch", xdp_info["payload_sha256"], XDP_NAME)
+ after = xdp_after
after["nv_events"] = len(
Path("/var/lib/shirudo/eventlog").read_text().splitlines())
config.save("loaded", after)
@@ -96,6 +124,13 @@ def main():
config.run("revoke-config", "image", "update", signer.FIXTURES / "config-revoke")
after = snapshot("revoked", 1)
require(not PIN.exists() and not ARCHIVE.exists(), "revoked upatch remains")
+ require(not XDP_PIN.exists() and not XDP_ARCHIVE.exists(),
+ "revoked XDP upatch remains")
+ for device in ("xdprev0", "xdprev1"):
+ query = subprocess.run(["helper/test-xdp", "query", device],
+ check=True, capture_output=True, text=True)
+ require(query.stdout.strip() == "0", "revoked XDP is still attached")
+ subprocess.run(["ip", "link", "del", "xdprev0"], check=True)
require(after["status"]["root_hash"] == config.root("config-revoke"),
"revocation image not active")
require(after["status"]["sequence"] == before["status"]["sequence"] + 1 and
diff --git a/testing/functional/tamperproof/t6117-signed-metadata.sh b/testing/functional/tamperproof/t6117-signed-metadata.sh
index 435bb0d5..76701986 100755
--- a/testing/functional/tamperproof/t6117-signed-metadata.sh
+++ b/testing/functional/tamperproof/t6117-signed-metadata.sh
@@ -60,6 +60,21 @@ elif what == "section":
data[start + i:start + i + len(old)] = new.encode().ljust(len(old), b"\0")
payload = bytes(data[loader_off:loader_off + loader_len]) + bytes(data[data_off:data_off + data_len])
data[272:304] = hashlib.sha256(payload).digest()
+elif what == "xdp-mask":
+ magic, version, directory, count = struct.unpack_from(
+ "<4sIII", data, data_off + data_len - 16)
+ assert magic == b"SGTR" and version == 1
+ for i in range(count):
+ tag, _, off, length = struct.unpack_from(
+ "<4sIII", data, data_off + directory + i * 16)
+ if tag == b"UPGM":
+ assert struct.unpack_from("<I", data, data_off + off + 20)[0] == 8
+ struct.pack_into("<I", data, data_off + off + 24, 27)
+ break
+ else:
+ raise AssertionError("no signed XDP metadata")
+ payload = data[loader_off:loader_off + loader_len] + data[data_off:data_off + data_len]
+ data[272:304] = hashlib.sha256(payload).digest()
pathlib.Path(dst).write_bytes(data)
PY
}
@@ -74,6 +89,13 @@ test_expect_success 'the kernel refuses a load whose kprobe symbol was edited' '
[ ! -e "$B/shirudo-test-scope-kprobe" ]
'
+test_expect_success 'the kernel refuses a widened signed XDP device mask' '
+ mutate "$FIXTURES/shirudo-test-xdp-virtual.upatch" \
+ "$WORK/xdp-widened.upatch" xdp-mask &&
+ [ "$(category upatch load "$WORK/xdp-widened.upatch")" = signature_rejected ] &&
+ [ ! -e "$B/shirudo-test-xdp-virtual" ]
+'
+
test_expect_success 'a load whose header name differs from the signed name is refused' '
mutate "$KP" "$WORK/renamed.upatch" header-name shirudo-test-renamed &&
[ "$(category upatch load "$WORK/renamed.upatch")" = parser_rejected ] &&
diff --git a/testing/functional/upatch/t3010-unsupported-network-sections.sh b/testing/functional/upatch/t3010-unsupported-network-sections.sh
index 860ff2c0..7752e731 100644
--- a/testing/functional/upatch/t3010-unsupported-network-sections.sh
+++ b/testing/functional/upatch/t3010-unsupported-network-sections.sh
@@ -113,7 +113,7 @@ test_expect_success 'generic cgroup skb sections require ingress or egress' '
"$WORK/cgroup-skb-generic.out"
'
-test_expect_success 'a section the target cannot attach is rejected' '
+test_expect_success 'XDP without an explicit signed device class mask is rejected' '
! ( cd .. && "$B" "$WORK/xdp.bpf.c" \
-o "$WORK/xdp.upatch" \
--vmlinux vendor/linux/vmlinux.h --name xdp \
diff --git a/testing/functional/upatch/t3012-xdp-metadata.sh b/testing/functional/upatch/t3012-xdp-metadata.sh
new file mode 100644
index 00000000..6ba94836
--- /dev/null
+++ b/testing/functional/upatch/t3012-xdp-metadata.sh
@@ -0,0 +1,68 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+cd "$(dirname "$0")/../.."
+. ./test-lib.sh
+
+SHB="$(pwd)/../tools/shirudo-build/shirudo-build"
+CHECK=helper/test-upatch-prog-metadata
+[ -x "$SHB" ] || test_skip_all "shirudo-build not built"
+[ -x "$CHECK" ] || test_skip_all "metadata helper not built"
+WORK=$(mktemp -d)
+trap 'rm -rf "$WORK"' EXIT
+
+openssl req -x509 -newkey ML-DSA-87 -nodes -keyout "$WORK/k.pem" \
+ -outform DER -out "$WORK/c.der" -days 1 -subj /CN=t3012 \
+ >/dev/null 2>&1 || test_skip_all "OpenSSL ML-DSA unavailable"
+
+build_xdp() {
+ cat >"$WORK/xdp.bpf.c" <<-EOF
+ // SPDX-License-Identifier: GPL-2.0 OR BSD-2-Clause
+ #include "vmlinux.h"
+ #include <bpf/bpf_helpers.h>
+ char _license[] SEC("license") = "Dual BSD/GPL";
+ SEC("$1")
+ int pass(struct xdp_md *ctx) { return XDP_PASS; }
+ EOF
+ (cd .. && "$SHB" "$WORK/xdp.bpf.c" -o "$WORK/xdp.upatch" \
+ --name xdp --emit-artifacts --vmlinux vendor/linux/vmlinux.h \
+ --key "$WORK/k.pem" --cert "$WORK/c.der") >"$WORK/log" 2>&1
+}
+
+check_masks() {
+ for mask in $(seq 1 31); do
+ if [ $((mask & 4)) -ne 0 ]; then
+ ! build_xdp "xdp/$mask" || return 1
+ continue
+ fi
+ build_xdp "xdp/$mask" &&
+ "$CHECK" "$WORK/xdp.upatch" xdp "$mask" || return 1
+ done
+}
+
+check_rejections() {
+ for section in xdp xdp/ xdp/0 xdp/32 xdp/0x1 xdp/+1 xdp/eth0 \
+ xdp/18446744073709551616 xdp.frags xdp/devmap xdp/cpumap; do
+ if build_xdp "$section"; then
+ return 1
+ fi
+ done
+}
+
+test_expect_success 'every class mask survives signing and parsing, and bit 4 fails' '
+ check_masks
+'
+
+test_expect_success 'an object input retains the signed XDP selection' '
+ build_xdp xdp/27 &&
+ (cd .. && "$SHB" "$WORK/xdp.o" -o "$WORK/object.upatch" \
+ --name xdp --key "$WORK/k.pem" --cert "$WORK/c.der") &&
+ "$CHECK" "$WORK/object.upatch" xdp 27
+'
+
+test_expect_success 'missing, malformed and unsupported masks and variants fail' '
+ check_rejections
+'
+
+test_done
diff --git a/testing/functional/upatch/t3111-xdp.sh b/testing/functional/upatch/t3111-xdp.sh
new file mode 100644
index 00000000..68ac638a
--- /dev/null
+++ b/testing/functional/upatch/t3111-xdp.sh
@@ -0,0 +1,134 @@
+#!/bin/sh
+# SPDX-License-Identifier: BSD-2-Clause
+# Copyright (c) 2026 Authors of shirudo
+
+cd "$(dirname "$0")/../.."
+. ./integration-lib.sh
+target_guard
+
+FIXTURES=${SHIRUDO_TEST_FIXTURES_DIR:?target fixture directory is not set}
+H=./helper/test-xdp
+B=/run/shirudo/bpffs/upatches
+NAME=shirudo-test-xdp-virtual
+CONFLICT=shirudo-test-xdp-conflict
+VM_PATCH=shirudo-test-xdp-vm
+[ -x "$H" ] || test_skip_all "XDP helper unavailable"
+command -v ip >/dev/null 2>&1 || test_skip_all "ip unavailable"
+for name in "$NAME" "$CONFLICT" "$VM_PATCH"; do
+ [ -s "$FIXTURES/$name.upatch" ] || test_skip_all "XDP fixture unavailable"
+done
+
+load() {
+ "$SHIRUDO_BIN" upatch load "$FIXTURES/$1.upatch" --no-precheck
+}
+
+unload() {
+ "$SHIRUDO_BIN" upatch unload "$FIXTURES/$1.unload.upatch" --no-precheck
+}
+
+objget_counter() {
+ "$SHIRUDO_BIN" status --json | python3 -c '
+import json, sys
+print(json.load(sys.stdin)["tamper_attempts"]["counters"]["ObjGet"])
+'
+}
+
+cleanup() {
+ for name in "$NAME" "$CONFLICT" "$VM_PATCH"; do
+ unload "$name" >/dev/null 2>&1 || true
+ done
+ for dev in xdph0 xdph1 xdpa xdpc xdpbr; do
+ ip link del "$dev" >/dev/null 2>&1 || true
+ done
+ for ns in xdp-test-a xdp-test-b; do
+ ip netns del "$ns" >/dev/null 2>&1 || true
+ done
+}
+trap cleanup EXIT
+
+test_xdp_success() {
+ cleanup
+ test_expect_success "$@"
+ cleanup
+}
+
+test_xdp_success 'a device without native XDP alone is no attachable target' '
+ ip link add xdpbr type bridge && ip link set xdpbr up &&
+ status=0 &&
+ report=$("$SHIRUDO_BIN" upatch load "$FIXTURES/$NAME.upatch" \
+ --no-precheck --report=- 2>/dev/null) || status=$?
+ [ "$status" = 1 ] &&
+ [ "$(printf "%s\n" "$report" | report_field category)" = attach_target_missing ] &&
+ [ ! -e "$B/$NAME" ]
+'
+
+test_xdp_success 'one endpoint of a host veth pair receives native XDP' '
+ ip link add xdph0 index 30001 type veth peer name xdph1 index 30000 &&
+ ip link set xdph0 up && ip link set xdph1 up &&
+ load "$NAME" &&
+ [ "$("$H" query xdph1)" -gt 0 ] &&
+ [ "$("$H" query xdph0)" = 0 ] &&
+ [ -e "$B/$NAME/link_0" ] && [ ! -e "$B/$NAME/link_1" ] &&
+ before=$(wc -l </var/lib/shirudo/eventlog) &&
+ "$SHIRUDO_BIN" init &&
+ [ "$(wc -l </var/lib/shirudo/eventlog)" = "$before" ] &&
+ [ "$("$H" query xdph1)" -gt 0 ] &&
+ unload "$NAME" &&
+ [ "$("$H" query xdph1)" = 0 ] &&
+ ip link del xdph0
+'
+
+test_xdp_success 'a device without native XDP is skipped beside supported ones' '
+ ip link add xdph0 index 30000 type veth peer name xdph1 index 30001 &&
+ ip link set xdph0 up && ip link set xdph1 up &&
+ ip link add xdpbr type bridge && ip link set xdpbr up &&
+ load "$NAME" &&
+ [ "$("$H" query xdph0)" -gt 0 ] && [ "$("$H" query xdpbr)" = 0 ] &&
+ unload "$NAME"
+'
+
+test_xdp_success 'the VM class selects the guest adapter' '
+ adapter=$(ip -o route show default | awk "{print \$5; exit}") &&
+ [ -n "$adapter" ] && load "$VM_PATCH" &&
+ [ "$("$H" query "$adapter")" -gt 0 ] &&
+ unload "$VM_PATCH" && [ "$("$H" query "$adapter")" = 0 ]
+'
+
+test_xdp_success 'both host endpoints of separate cross-namespace pairs attach' '
+ ip netns add xdp-test-a && ip netns add xdp-test-b &&
+ ip link add xdpa type veth peer name xdpa-peer netns xdp-test-a &&
+ ip link add xdpc type veth peer name xdpc-peer netns xdp-test-b &&
+ ip link set xdpa up && ip link set xdpc up &&
+ ip -n xdp-test-a link set xdpa-peer up &&
+ ip -n xdp-test-b link set xdpc-peer up &&
+ ip -n xdp-test-a link add internal0 type veth peer name internal1 &&
+ ip -n xdp-test-a link set internal0 up &&
+ ip -n xdp-test-a link set internal1 up &&
+ load "$NAME" &&
+ [ "$("$H" query xdpa)" -gt 0 ] && [ "$("$H" query xdpc)" -gt 0 ] &&
+ [ -e "$B/$NAME/link_0" ] && [ -e "$B/$NAME/link_1" ] &&
+ [ ! -e "$B/$NAME/link_2" ] &&
+ [ "$(ip netns exec xdp-test-a "$H" query internal0)" = 0 ] &&
+ [ "$(ip netns exec xdp-test-a "$H" query internal1)" = 0 ] &&
+ before=$(objget_counter) && "$H" denied xdpa &&
+ [ "$(objget_counter)" -gt "$before" ] &&
+ unload "$NAME" &&
+ [ "$("$H" query xdpa)" = 0 ] && [ "$("$H" query xdpc)" = 0 ] &&
+ ip link del xdpa && ip link del xdpc &&
+ ip netns del xdp-test-a && ip netns del xdp-test-b
+'
+
+test_xdp_success 'a later occupied device rolls back earlier successful links' '
+ ip link add xdph0 index 31000 type veth peer name xdph1 index 31001 &&
+ ip link set xdph0 up && ip link set xdph1 up &&
+ load "$CONFLICT" &&
+ ip link add xdpa index 30000 type veth peer name xdpc index 30001 &&
+ ip link set xdpa up && ip link set xdpc up &&
+ ! load "$NAME" &&
+ [ ! -e "$B/$NAME" ] &&
+ [ "$("$H" query xdpa)" = 0 ] &&
+ [ "$("$H" query xdph0)" -gt 0 ] &&
+ unload "$CONFLICT"
+'
+
+test_done
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-1 b/testing/fuzz/corpus/prog-metadata/xdp-1
new file mode 100644
index 00000000..2e8df35e
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-1 differ
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-16 b/testing/fuzz/corpus/prog-metadata/xdp-16
new file mode 100644
index 00000000..c18d69d1
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-16 differ
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-2 b/testing/fuzz/corpus/prog-metadata/xdp-2
new file mode 100644
index 00000000..0b84c924
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-2 differ
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-31 b/testing/fuzz/corpus/prog-metadata/xdp-31
new file mode 100644
index 00000000..6c80c65f
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-31 differ
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-4 b/testing/fuzz/corpus/prog-metadata/xdp-4
new file mode 100644
index 00000000..61382214
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-4 differ
diff --git a/testing/fuzz/corpus/prog-metadata/xdp-8 b/testing/fuzz/corpus/prog-metadata/xdp-8
new file mode 100644
index 00000000..0beabe4e
Binary files /dev/null and b/testing/fuzz/corpus/prog-metadata/xdp-8 differ
diff --git a/testing/fuzz/corpus/upatch/xdp-virtual b/testing/fuzz/corpus/upatch/xdp-virtual
new file mode 100644
index 00000000..1043595c
Binary files /dev/null and b/testing/fuzz/corpus/upatch/xdp-virtual differ
diff --git a/testing/fuzz/fuzz-prog-metadata.c b/testing/fuzz/fuzz-prog-metadata.c
index d5bc1b0a..4d9abc9a 100644
--- a/testing/fuzz/fuzz-prog-metadata.c
+++ b/testing/fuzz/fuzz-prog-metadata.c
@@ -2,8 +2,7 @@
/*
* Copyright (c) 2026 Authors of shirudo
*
- * prog_specs_parse() on a load upatch's program metadata, which
- * the loader signature does not cover.
+ * prog_specs_parse() on a load upatch's signed program metadata.
*/
#include <stdint.h>
diff --git a/testing/helper/test-upatch-prog-metadata.c b/testing/helper/test-upatch-prog-metadata.c
index 63c41a25..4f4bf95e 100644
--- a/testing/helper/test-upatch-prog-metadata.c
+++ b/testing/helper/test-upatch-prog-metadata.c
@@ -11,6 +11,7 @@
#include <string.h>
#include <shirudo/misc.h>
+#include <shirudo/string.h>
#include "upatch.h"
@@ -206,7 +207,7 @@ int main(int argc, char **argv)
const char *mode = "serializer";
int ret;
- if (argc != 2 && argc != 3 && argc != 6)
+ if (argc != 2 && argc != 3 && argc != 4 && argc != 6)
return fail("usage: test-upatch-prog-metadata <file.upatch> [mode [path pattern count]]");
if (argc >= 3)
mode = argv[2];
@@ -235,11 +236,27 @@ int main(int argc, char **argv)
ret = expect_attach(&u,
UPATCH_ATTACH_NETFILTER_IPV6_PRE_ROUTING,
NULL, 0);
+ } else if (strcmp(mode, "xdp") == 0 && argc == 4) {
+ struct prog_spec *specs = NULL;
+ const void *attach;
+ __u32 len;
+ __u64 mask;
+
+ attach = upatch_signed_attach(&u, &len);
+ ret = parse_u64(argv[3], strlen(argv[3]), UPATCH_XDP_ALL, &mask);
+ if (!ret)
+ ret = prog_specs_parse(attach, len, u.hdr.nr_maps,
+ u.hdr.nr_progs, &specs);
+ if (!ret) {
+ if (u.hdr.nr_progs != 1 || specs[0].kind != UPATCH_ATTACH_XDP ||
+ specs[0].device_classes != mask)
+ ret = fail("XDP metadata mismatch");
+ prog_specs_free(specs, u.hdr.nr_progs);
+ }
} else if (strcmp(mode, "uprobe-multi") == 0 && argc == 6) {
- char *end = NULL;
- __u64 count = strtoul(argv[5], &end, 10);
+ __u64 count;
- if (!end || *end || count > UINT32_MAX)
+ if (parse_u64(argv[5], strlen(argv[5]), UINT32_MAX, &count))
ret = fail("invalid expected uprobe offset count");
else
ret = expect_uprobe_multi(&u, argv[3], argv[4],
diff --git a/testing/helper/test-xdp.c b/testing/helper/test-xdp.c
new file mode 100644
index 00000000..6a419d60
--- /dev/null
+++ b/testing/helper/test-xdp.c
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <net/if.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <linux/if_link.h>
+#include <bpf/bpf.h>
+#include <bpf/libbpf.h>
+
+#include <shirudo/misc.h>
+
+int main(int argc, char **argv)
+{
+ LIBBPF_OPTS(bpf_link_create_opts, opts, .flags = XDP_FLAGS_DRV_MODE);
+ __u32 ifindex, id = 0, after = 0;
+ int fd, ret;
+
+ if (argc != 3)
+ return 2;
+ ifindex = if_nametoindex(argv[2]);
+ if (!ifindex)
+ return 2;
+ ret = bpf_xdp_query_id((int)ifindex, XDP_FLAGS_DRV_MODE, &id);
+ if (ret)
+ return 2;
+ if (!strcmp(argv[1], "query")) {
+ printf("%u\n", id);
+ return 0;
+ }
+ if (strcmp(argv[1], "denied") || !id)
+ return 2;
+ fd = bpf_prog_get_fd_by_id(id);
+ if (fd >= 0) {
+ close(fd);
+ fprintf(stderr, "XDP program descriptor acquisition was allowed\n");
+ return 1;
+ }
+ if (errno != EACCES ||
+ bpf_link_create(-1, (int)ifindex, BPF_XDP, &opts) != -EACCES ||
+ bpf_link_detach(-1) != -EACCES ||
+ bpf_xdp_detach((int)ifindex, XDP_FLAGS_DRV_MODE, NULL) != -EBUSY)
+ return 1;
+ if (bpf_xdp_query_id((int)ifindex, XDP_FLAGS_DRV_MODE, &after))
+ return 1;
+ return id == after ? 0 : 1;
+}
diff --git a/testing/unit/upatch.c b/testing/unit/upatch.c
index f21d3113..61f5fac3 100644
--- a/testing/unit/upatch.c
+++ b/testing/unit/upatch.c
@@ -125,6 +125,53 @@ static void name_fits_its_pin_directory(void)
EXPECT_FALSE(upatch_name_valid(name));
}
+static void xdp_masks_are_signed_and_bounded(void)
+{
+ struct upatch_prog_entry prog = {};
+ struct prog_spec *specs = NULL;
+ __u8 buf[ONE_PROG_LEN];
+ __u32 mask;
+
+ EXPECT_UEQ(sizeof(prog), 160);
+ for (mask = 1; mask <= 31; mask++) {
+ one_raw_tracepoint(buf, 0);
+ prog.kind = cpu_to_le32(UPATCH_ATTACH_XDP);
+ prog.xdp.device_classes = cpu_to_le32(mask);
+ memcpy(buf + sizeof(struct upatch_prog_metadata), &prog, sizeof(prog));
+ if (mask & ~(__u32)UPATCH_XDP_ALL) {
+ EXPECT_TRUE(prog_specs_parse(buf, sizeof(buf), 0, 1, &specs) < 0);
+ continue;
+ }
+ ASSERT_EQ(prog_specs_parse(buf, sizeof(buf), 0, 1, &specs), 0);
+ EXPECT_UEQ(specs[0].kind, UPATCH_ATTACH_XDP);
+ EXPECT_UEQ(specs[0].device_classes, mask);
+ EXPECT_UEQ(specs[0].offset, 0);
+ prog_specs_free(specs, 1);
+ }
+ for (mask = 0; mask < 7; mask++) {
+ memset(&prog, 0, sizeof(prog));
+ prog.kind = cpu_to_le32(UPATCH_ATTACH_XDP);
+ prog.xdp.device_classes = cpu_to_le32(UPATCH_XDP_ALL);
+ if (mask == 0)
+ prog.xdp.device_classes = 0;
+ else if (mask == 1)
+ prog.xdp.device_classes = cpu_to_le32(32);
+ else if (mask == 2)
+ prog.xdp.reserved = cpu_to_le32(1);
+ else if (mask == 3)
+ prog.target[0] = 'x';
+ else if (mask == 4)
+ prog.map[0] = 'x';
+ else if (mask == 5)
+ prog.target[sizeof(prog.target) - 1] = 'x';
+ else
+ prog.map[sizeof(prog.map) - 1] = 'x';
+ memcpy(buf + sizeof(struct upatch_prog_metadata), &prog, sizeof(prog));
+ EXPECT_EQ(prog_specs_parse(buf, sizeof(buf), 0, 1, &specs), -EINVAL);
+ EXPECT_FALSE(specs);
+ }
+}
+
static const struct unit_case cases[] = {
UNIT_CASE(prog_specs_take_the_signed_counts),
UNIT_CASE(prog_specs_refuse_another_header_count),
@@ -133,6 +180,7 @@ static const struct unit_case cases[] = {
UNIT_CASE(name_signed_is_the_header_name),
UNIT_CASE(member_is_a_name_and_a_payload),
UNIT_CASE(name_fits_its_pin_directory),
+ UNIT_CASE(xdp_masks_are_signed_and_bounded),
{}
};
diff --git a/testing/unit/xdp.c b/testing/unit/xdp.c
new file mode 100644
index 00000000..020a56d7
--- /dev/null
+++ b/testing/unit/xdp.c
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <net/if.h>
+#include <linux/devlink.h>
+#include <linux/rtnetlink.h>
+
+#include <shirudo/upatch.h>
+
+#include "unit.h"
+#include "malloc.h"
+#include "xdp.h"
+
+static void classes_are_exclusive(void)
+{
+ struct xdp_device dev = {};
+
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_UNKNOWN);
+ memcpy(dev.kind, "veth", sizeof("veth"));
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_VIRTUAL);
+ memcpy(dev.parent_bus, "pci", sizeof("pci"));
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_NETWORK);
+ dev.devlink_port = true;
+ dev.port_flavour = DEVLINK_PORT_FLAVOUR_PCI_VF;
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_VIRTUAL);
+ dev.port_flavour = DEVLINK_PORT_FLAVOUR_PHYSICAL;
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_NETWORK);
+ dev.port_flavour = 65535;
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_UNKNOWN);
+ memcpy(dev.driver, "virtio_net", sizeof("virtio_net"));
+ EXPECT_UEQ(xdp_device_class(&dev), UPATCH_XDP_VM);
+ dev.flags = IFF_LOOPBACK;
+ EXPECT_UEQ(xdp_device_class(&dev), 0);
+ EXPECT_FALSE(xdp_device_selected(&dev, 1, 0, UPATCH_XDP_ALL));
+}
+
+static void veth_peers_are_namespace_aware(void)
+{
+ struct xdp_device devs[4] = {};
+ size_t i;
+
+ for (i = 0; i < 4; i++) {
+ memcpy(devs[i].kind, "veth", sizeof("veth"));
+ devs[i].ifindex = (__u32)i + 10;
+ }
+ devs[0].peer_ifindex = 11;
+ devs[1].peer_ifindex = 10;
+ EXPECT_TRUE(xdp_device_selected(devs, 4, 0, UPATCH_XDP_VIRTUAL));
+ EXPECT_FALSE(xdp_device_selected(devs, 4, 1, UPATCH_XDP_ALL));
+ EXPECT_FALSE(xdp_device_selected(devs, 4, 0, UPATCH_XDP_UNKNOWN));
+ devs[2].peer_ifindex = 13;
+ devs[3].peer_ifindex = 12;
+ devs[2].peer_other_netns = true;
+ devs[3].peer_other_netns = true;
+ EXPECT_TRUE(xdp_device_selected(devs, 4, 2, UPATCH_XDP_VIRTUAL));
+ EXPECT_TRUE(xdp_device_selected(devs, 4, 3, UPATCH_XDP_VIRTUAL));
+ devs[0].peer_other_netns = true;
+ devs[1].peer_other_netns = true;
+ EXPECT_TRUE(xdp_device_selected(devs, 4, 0, UPATCH_XDP_VIRTUAL));
+ EXPECT_TRUE(xdp_device_selected(devs, 4, 1, UPATCH_XDP_VIRTUAL));
+}
+
+static size_t add_attr(__u8 *buf, size_t len, __u16 type,
+ const void *value, size_t size)
+{
+ struct nlattr attr = {
+ .nla_len = (__u16)(NLA_HDRLEN + size),
+ .nla_type = type,
+ };
+
+ memcpy(buf + len, &attr, sizeof(attr));
+ memcpy(buf + len + NLA_HDRLEN, value, size);
+ return len + NLA_ALIGN(attr.nla_len);
+}
+
+static void link_messages_are_checked(void)
+{
+ struct ifinfomsg info = { .ifi_index = 12 };
+ struct xdp_device dev;
+ __u8 buf[256] = {};
+ __u8 nested[32] = {};
+ __u32 peer = 13;
+ __s32 nsid = 4;
+ size_t len, n;
+
+ memcpy(buf, &info, sizeof(info));
+ len = add_attr(buf, sizeof(info), IFLA_IFNAME, "veth0", sizeof("veth0"));
+ len = add_attr(buf, len, IFLA_LINK, &peer, sizeof(peer));
+ len = add_attr(buf, len, IFLA_LINK_NETNSID, &nsid, sizeof(nsid));
+ n = add_attr(nested, 0, IFLA_INFO_KIND, "veth", sizeof("veth"));
+ len = add_attr(buf, len, IFLA_LINKINFO | NLA_F_NESTED, nested, n);
+ ASSERT_EQ(xdp_device_parse(buf, len, &dev), 0);
+ EXPECT_STREQ(dev.name, "veth0");
+ EXPECT_STREQ(dev.kind, "veth");
+ EXPECT_UEQ(dev.ifindex, 12);
+ EXPECT_UEQ(dev.peer_ifindex, 13);
+ EXPECT_TRUE(dev.peer_other_netns);
+ for (n = 0; n < sizeof(info) + NLA_HDRLEN + sizeof("veth0"); n++)
+ EXPECT_EQ(xdp_device_parse(buf, n, &dev), -EINVAL);
+ EXPECT_EQ(xdp_device_parse(buf, len - 1, &dev), -EINVAL);
+ len = add_attr(buf, len, IFLA_IFNAME, "other", sizeof("other"));
+ EXPECT_EQ(xdp_device_parse(buf, len, &dev), -EINVAL);
+ memset(buf, 0, sizeof(buf));
+ memcpy(buf, &info, sizeof(info));
+ len = add_attr(buf, sizeof(info), IFLA_IFNAME, "no-nul", 6);
+ EXPECT_EQ(xdp_device_parse(buf, len, &dev), -EINVAL);
+}
+
+static void kernel_discovery_revalidates_devices(void)
+{
+ struct xdp_device *devices = NULL;
+ size_t count = 0, i;
+ int ret;
+
+ ret = xdp_devices_read(&devices, &count);
+ if (ret == -EPERM || ret == -EACCES || ret == -EAFNOSUPPORT)
+ unit_skip("kernel network discovery unavailable");
+ ASSERT_EQ(ret, 0);
+ EXPECT_TRUE(count > 0);
+ for (i = 0; i < count; i++) {
+ EXPECT_EQ(xdp_device_verify(&devices[i]), 0);
+ if (i)
+ EXPECT_TRUE(devices[i - 1].ifindex < devices[i].ifindex);
+ }
+ xfree(devices, count * sizeof(*devices));
+}
+
+static const struct unit_case cases[] = {
+ UNIT_CASE(classes_are_exclusive),
+ UNIT_CASE(veth_peers_are_namespace_aware),
+ UNIT_CASE(link_messages_are_checked),
+ UNIT_CASE(kernel_discovery_revalidates_devices),
+ {}
+};
+
+UNIT_SUITE(xdp, cases);
diff --git a/testing/vm/build-bundle.sh b/testing/vm/build-bundle.sh
index 00225639..1afe0245 100755
--- a/testing/vm/build-bundle.sh
+++ b/testing/vm/build-bundle.sh
@@ -363,6 +363,7 @@ testing/helper/test-upatch-decode
testing/helper/test-upatch-serializer-pages
testing/helper/test-signed-load
testing/helper/test-upatch-link-lockdown
+testing/helper/test-xdp
testing/helper/test-exec-churn
testing/end2end/exec-paths
testing/end2end/policy-exec
@@ -743,6 +744,9 @@ queue_fixture build_fixture uprobe-multi.bpf.c shirudo-test-uprobe-multi "$FIXTU
queue_fixture build_fixture scope-netfilter.bpf.c shirudo-test-scope-netfilter "$FIXTURE_WORK/trusted"
queue_fixture build_fixture scope-cgroup.bpf.c shirudo-test-scope-cgroup "$FIXTURE_WORK/trusted"
queue_fixture build_fixture scope-kprobe.bpf.c shirudo-test-scope-kprobe "$FIXTURE_WORK/trusted"
+queue_fixture build_fixture xdp-virtual.bpf.c shirudo-test-xdp-virtual "$FIXTURE_WORK/trusted"
+queue_fixture build_fixture xdp-virtual.bpf.c shirudo-test-xdp-conflict "$FIXTURE_WORK/trusted"
+queue_fixture build_fixture xdp-vm.bpf.c shirudo-test-xdp-vm "$FIXTURE_WORK/trusted"
queue_fixture build_fixture basic.bpf.c shirudo-test-foreign "$FIXTURE_WORK/foreign"
queue_fixture build_fixture basic.bpf.c shirudo-test-own-keyring "$FIXTURE_WORK/own"
queue_fixture build_policy_labels_fixture
@@ -786,6 +790,18 @@ observability_payload="$($REPO_ROOT/shirudo upatch info \
observability_anomaly_payload="$($REPO_ROOT/shirudo upatch info \
"$TMP_DIR/fixtures/kernel-obs-cred-anomaly.upatch" --json |
python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"
+for xdp_kind in virtual conflict vm; do
+ xdp_name="shirudo-test-xdp-$xdp_kind"
+ xdp_payload="$($REPO_ROOT/shirudo upatch info \
+ "$TMP_DIR/fixtures/$xdp_name.upatch" --json | \
+ python3 -c 'import json,sys; print(json.load(sys.stdin)["payload_sha256"])')"
+ "$REPO_ROOT/tools/shirudo-build/shirudo-build" --unload "$xdp_name" \
+ --payload-sha256 "$xdp_payload" \
+ -o "$TMP_DIR/fixtures/$xdp_name.unload.upatch" \
+ --key "$FIXTURE_WORK/trusted/signing_key.pem" \
+ --cert "$FIXTURE_WORK/trusted/cert.der"
+done
+
for scope in netfilter cgroup kprobe; do
scope_payload="$($REPO_ROOT/shirudo upatch info \
"$TMP_DIR/fixtures/shirudo-test-scope-$scope.upatch" --json |
diff --git a/testing/vm/image-fixtures.sh b/testing/vm/image-fixtures.sh
index 688444ac..15a33a5f 100755
--- a/testing/vm/image-fixtures.sh
+++ b/testing/vm/image-fixtures.sh
@@ -175,6 +175,14 @@ done
--key "$output/private/live/signing_key.pem" \
--cert "$output/public/live.der"
+"$builder" "$source_dir/testing/fixtures/xdp-virtual.bpf.c" \
+ -o "$output/public/shirudo-test-revoked-xdp.upatch" \
+ --name shirudo-test-revoked-xdp \
+ --vmlinux "$source_dir/vendor/linux/vmlinux.h" \
+ --extra-cflags "-I$source_dir/vendor/libbpf" \
+ --key "$output/private/boot/signing_key.pem" \
+ --cert "$output/public/boot.der"
+
# These host checks validate the fixture graph before the real target test.
mkdir "$output/check-live" "$output/check-boot"
"$validator" "$keys_dir/cert.der" "$output/source/config-boot-keys" \
diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.c
index c6b1fe62..747fc47f 100644
--- a/tools/shirudo-build/package.c
+++ b/tools/shirudo-build/package.c
@@ -659,6 +659,10 @@ static __u32 attach_kind_from_section(const char *sec,
return UPATCH_ATTACH_FMOD_RET;
if (strcmp(sec, "netfilter") == 0)
return UPATCH_ATTACH_NETFILTER_IPV6_PRE_ROUTING;
+ if (strncmp(sec, "xdp/", 4) == 0 && sec[4]) {
+ *target = sec + 4;
+ return UPATCH_ATTACH_XDP;
+ }
return UPATCH_ATTACH_RAW_TRACEPOINT;
}
@@ -1310,7 +1314,7 @@ static int build_prog_metadata(struct bpf_object *obj, __u32 nr_maps,
kind = attach_kind_from_section(sec, &target);
if (kind == UPATCH_ATTACH_RAW_TRACEPOINT &&
!default_attach_section(sec)) {
- pr_err("unsupported section '%s'; supported are fentry, fexit, fmod_ret, lsm, tp_btf, kprobe, kretprobe, uprobe.multi, cgroup_skb and netfilter",
+ pr_err("unsupported section '%s'; supported are fentry, fexit, fmod_ret, lsm, tp_btf, kprobe, kretprobe, uprobe.multi, cgroup_skb, netfilter and xdp/<mask>",
sec);
err = -EOPNOTSUPP;
goto err_free;
@@ -1318,7 +1322,21 @@ static int build_prog_metadata(struct bpf_object *obj, __u32 nr_maps,
md->progs[i].role =
cpu_to_le32(UPATCH_PROG_ROLE_ATTACH);
md->progs[i].kind = cpu_to_le32(kind);
- if (kind == UPATCH_ATTACH_UPROBE_MULTI) {
+ if (kind == UPATCH_ATTACH_XDP) {
+ __u64 mask;
+
+ err = parse_u64(target, strlen(target), UPATCH_XDP_ALL,
+ &mask);
+ if (err || !mask || (mask & ~(__u64)UPATCH_XDP_ALL)) {
+ pr_err("invalid XDP device class mask in section '%s'; use xdp/<decimal-mask>, a sum of 1, 2, 8 and 16",
+ sec);
+ err = -EINVAL;
+ goto err_free;
+ }
+ md->progs[i].xdp.device_classes = cpu_to_le32((__u32)mask);
+ i++;
+ continue;
+ } else if (kind == UPATCH_ATTACH_UPROBE_MULTI) {
struct build_uprobe_target *ut =
&uprobe_targets[nr_uprobe_targets];
@@ -1474,6 +1492,8 @@ static int set_target_attach_types(struct bpf_object *obj)
type = BPF_CGROUP_INET_INGRESS;
else if (strcmp(sec, "cgroup_skb/egress") == 0)
type = BPF_CGROUP_INET_EGRESS;
+ else if (!strncmp(sec, "xdp/", 4))
+ type = BPF_XDP;
else
continue;
@@ -1486,7 +1506,7 @@ static int set_target_attach_types(struct bpf_object *obj)
return 0;
}
-static int register_target_attach_types(int handler_ids[2])
+static int register_target_attach_types(int handler_ids[3])
{
handler_ids[0] = libbpf_register_prog_handler("cgroup_skb/ingress",
BPF_PROG_TYPE_CGROUP_SKB,
@@ -1504,17 +1524,29 @@ static int register_target_attach_types(int handler_ids[2])
handler_ids[0] = -1;
return handler_ids[1];
}
+ handler_ids[2] = libbpf_register_prog_handler("xdp/", BPF_PROG_TYPE_XDP,
+ BPF_XDP, NULL);
+ if (handler_ids[2] < 0) {
+ libbpf_unregister_prog_handler(handler_ids[1]);
+ libbpf_unregister_prog_handler(handler_ids[0]);
+ handler_ids[1] = -1;
+ handler_ids[0] = -1;
+ return handler_ids[2];
+ }
return 0;
}
-static void unregister_target_attach_types(int handler_ids[2])
+static void unregister_target_attach_types(int handler_ids[3])
{
+ if (handler_ids[2] >= 0)
+ libbpf_unregister_prog_handler(handler_ids[2]);
if (handler_ids[1] >= 0)
libbpf_unregister_prog_handler(handler_ids[1]);
if (handler_ids[0] >= 0)
libbpf_unregister_prog_handler(handler_ids[0]);
handler_ids[0] = -1;
handler_ids[1] = -1;
+ handler_ids[2] = -1;
}
/*
@@ -1771,7 +1803,7 @@ int build_package_load(const char *bpf_o, const char *src_path,
__u32 label_len = 0, policy_map_idx = 0, socket_policy_map_idx = 0;
struct upatch_policy_label_header *label_blob = NULL;
struct bpf_map *map, *task_map, *sock_map;
- int handler_ids[2] = {-1, -1};
+ int handler_ids[3] = { -1, -1, -1 };
struct bpf_object *obj;
__u32 map_idx = 0;
int err;
@@ -1781,7 +1813,7 @@ int build_package_load(const char *bpf_o, const char *src_path,
return err;
err = register_target_attach_types(handler_ids);
if (err) {
- pr_err("register cgroup_skb section handlers: %d", err);
+ pr_err("register target section handlers: %d", err);
return err;
}
diff --git a/util/image_guards.c b/util/image_guards.c
index 2319f08d..7f5e787d 100644
--- a/util/image_guards.c
+++ b/util/image_guards.c
@@ -132,6 +132,9 @@ shirudo_gate_guards[GATE_HOOK_COUNT] = {
[GUARD_BPF_MAP] = {
"shirudo_lsm_bpf_map", LSM_BPF_MAP_LINK_PIN,
},
+ [GUARD_BPF_PROG] = {
+ "shirudo_lsm_bpf_prog", LSM_BPF_PROG_LINK_PIN,
+ },
[GUARD_PROG_LOAD] = {
"shirudo_lsm_bpf_prog_load", LSM_PROG_LOAD_LINK_PIN,
},
diff --git a/util/image_guards.h b/util/image_guards.h
index 26cb8b1a..91b90c16 100644
--- a/util/image_guards.h
+++ b/util/image_guards.h
@@ -26,6 +26,7 @@ enum gate_guard {
GUARD_KEY_PERMISSION,
GUARD_TPM_COMMAND,
GUARD_BPF_MAP,
+ GUARD_BPF_PROG,
GUARD_PROG_LOAD,
GUARD_BPF,
GATE_HOOK_COUNT,
diff --git a/util/paths.h b/util/paths.h
index 113a70bb..13b862fe 100644
--- a/util/paths.h
+++ b/util/paths.h
@@ -62,6 +62,7 @@
#define LSM_LINK_PIN BPFFS_DIR "/lsm_link"
#define LSM_PROG_LOAD_LINK_PIN BPFFS_DIR "/bpf2_bpf_prog_load_link"
#define LSM_BPF_MAP_LINK_PIN BPFFS_DIR "/bpf2_bpf_map_link"
+#define LSM_BPF_PROG_LINK_PIN BPFFS_DIR "/bpf2_bpf_prog_link"
#define SB_UMOUNT_LINK_PIN BPFFS_DIR "/bpf2_sb_umount_link"
#define MOVE_MOUNT_LINK_PIN BPFFS_DIR "/bpf2_move_mount_link"
#define SB_MOUNT_LINK_PIN BPFFS_DIR "/bpf2_sb_mount_link"
diff --git a/util/upatch.c b/util/upatch.c
index 6bbbd46d..bd5ed22b 100644
--- a/util/upatch.c
+++ b/util/upatch.c
@@ -593,12 +593,13 @@ void prog_specs_free(struct prog_spec *specs, __u32 nr_progs)
int prog_specs_parse(const void *metadata, __u32 metadata_len,
__u32 nr_maps, __u32 nr_progs, struct prog_spec **out)
{
+ __u32 magic, version, count, i, nr_uprobes = 0;
+ const struct upatch_prog_entry empty = {};
struct upatch_prog_metadata md;
struct prog_spec *specs = NULL;
const __u8 *cursor, *end;
- size_t base_len;
- __u32 magic, version, count, i, nr_uprobes = 0;
int ret = -EINVAL;
+ size_t base_len;
*out = NULL;
if (!metadata || metadata_len < sizeof(__u32))
@@ -686,6 +687,16 @@ int prog_specs_parse(const void *metadata, __u32 metadata_len,
goto out;
nr_uprobes++;
break;
+ case UPATCH_ATTACH_XDP:
+ spec->device_classes = le32_to_cpu(prog.xdp.device_classes);
+ if (!spec->device_classes ||
+ (spec->device_classes & ~UPATCH_XDP_ALL) ||
+ prog.xdp.reserved ||
+ memcmp(prog.target, empty.target, sizeof(prog.target)) ||
+ memcmp(prog.map, empty.map, sizeof(prog.map)))
+ goto out;
+ spec->kind = kind;
+ continue;
default:
goto out;
}
diff --git a/util/upatch.h b/util/upatch.h
index 3f25b585..49347f7c 100644
--- a/util/upatch.h
+++ b/util/upatch.h
@@ -148,6 +148,7 @@ int upatch_select(const struct dirent *e);
struct prog_spec {
__u32 role;
__u32 kind;
+ __u32 device_classes;
__u64 offset;
char target[UPATCH_ATTACH_TARGET_MAX];
char map[UPATCH_PROG_MAP_MAX];
@@ -178,9 +179,8 @@ int upatch_install(const char *path);
int upatch_remove(const char *path);
/*
- * upatch_install() when the signed payload is valid but its
- * kprobe target is not there, because the module that has it is not
- * loaded.
+ * A missing optional kprobe module permits tree projection advancement;
+ * an XDP selection without an attachable device must fail instead.
*/
#define UPATCH_INSTALL_TARGET_MISSING 2
diff --git a/util/upatch_resolve.c b/util/upatch_resolve.c
index 9fb647de..b9e2ecbf 100644
--- a/util/upatch_resolve.c
+++ b/util/upatch_resolve.c
@@ -7,6 +7,7 @@
#include <errno.h>
#include <limits.h>
+#include <net/if.h>
#include <linux/bpf.h>
#include <stdio.h>
#include <string.h>
@@ -139,6 +140,14 @@ int upatch_resolve_location(struct btf *vbtf, const char *name,
return ret;
}
close(link_fd);
+ if (linfo.type == BPF_LINK_TYPE_XDP) {
+ char device[IF_NAMESIZE];
+
+ if (linfo.xdp.ifindex && if_indextoname(linfo.xdp.ifindex, device))
+ return strsprintf(out, cap, "xdp/%s", device) < 0 ? -E2BIG : 0;
+ return strsprintf(out, cap, "xdp/ifindex:%u", linfo.xdp.ifindex) < 0 ?
+ -E2BIG : 0;
+ }
if (linfo.type == BPF_LINK_TYPE_TRACING)
attach_type = linfo.tracing.attach_type;
if (linfo.type == BPF_LINK_TYPE_NETFILTER &&
diff --git a/util/xdp.c b/util/xdp.c
new file mode 100644
index 00000000..48e4da6e
--- /dev/null
+++ b/util/xdp.c
@@ -0,0 +1,553 @@
+// SPDX-License-Identifier: BSD-2-Clause
+/* Copyright (c) 2026 Authors of shirudo */
+
+#include <errno.h>
+#include <limits.h>
+#include <net/if.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#include <linux/devlink.h>
+#include <linux/ethtool.h>
+#include <linux/genetlink.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <linux/sockios.h>
+
+#include <shirudo/overflow.h>
+#include <shirudo/string.h>
+#include <shirudo/upatch.h>
+
+#include "malloc.h"
+#include "xdp.h"
+
+#define NETLINK_BUFFER_SIZE 65536U
+
+struct nl_request {
+ struct nlmsghdr hdr;
+ __u8 data[512];
+};
+
+typedef int (*nl_receive_fn)(const void *data, size_t len, void *ctx);
+
+static int attr_find(const void *data, size_t len, __u16 type,
+ const struct nlattr **out)
+{
+ const __u8 *cursor = data;
+
+ *out = NULL;
+ while (len) {
+ const struct nlattr *attr = (const void *)cursor;
+ size_t step;
+
+ if (len < NLA_HDRLEN || attr->nla_len < NLA_HDRLEN ||
+ attr->nla_len > len)
+ return -EINVAL;
+ step = NLA_ALIGN(attr->nla_len);
+ if (step > len)
+ return -EINVAL;
+ if ((attr->nla_type & NLA_TYPE_MASK) == type) {
+ if (*out)
+ return -EINVAL;
+ *out = attr;
+ }
+ cursor += step;
+ len -= step;
+ }
+ return 0;
+}
+
+static int attr_string(const void *data, size_t len, __u16 type,
+ char *out, size_t cap)
+{
+ const struct nlattr *attr;
+ const char *value;
+ size_t size;
+ int ret;
+
+ ret = attr_find(data, len, type, &attr);
+ if (ret || !attr)
+ return ret;
+ size = attr->nla_len - NLA_HDRLEN;
+ value = (const char *)attr + NLA_HDRLEN;
+ if (!size || size > cap || value[size - 1] ||
+ memchr(value, '\0', size - 1))
+ return -EINVAL;
+ memcpy(out, value, size);
+ return 0;
+}
+
+static int attr_number(const void *data, size_t len, __u16 type,
+ void *out, size_t size, bool *present)
+{
+ const struct nlattr *attr;
+ int ret;
+
+ ret = attr_find(data, len, type, &attr);
+ if (ret || !attr)
+ return ret;
+ if (attr->nla_len != NLA_HDRLEN + size)
+ return -EINVAL;
+ memcpy(out, (const __u8 *)attr + NLA_HDRLEN, size);
+ if (present)
+ *present = true;
+ return 0;
+}
+
+static int attr_put(struct nl_request *req, __u16 type,
+ const void *data, size_t len)
+{
+ size_t size = size_add(NLA_HDRLEN, len);
+ size_t end = size_add(req->hdr.nlmsg_len, NLA_ALIGN(size));
+ struct nlattr *attr;
+
+ if (end > sizeof(*req))
+ return -E2BIG;
+ attr = (void *)((__u8 *)req + req->hdr.nlmsg_len);
+ attr->nla_type = type;
+ attr->nla_len = (__u16)size;
+ memcpy((__u8 *)attr + NLA_HDRLEN, data, len);
+ req->hdr.nlmsg_len = (__u32)end;
+ return 0;
+}
+
+static int nl_exchange(int protocol, struct nl_request *req,
+ nl_receive_fn receive, void *ctx)
+{
+ struct sockaddr_nl kernel = { .nl_family = AF_NETLINK };
+ struct timeval timeout = { .tv_sec = 5 };
+ __u8 *buf = NULL;
+ int fd, ret;
+
+ fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, protocol);
+ if (fd < 0)
+ return -errno;
+ ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
+ if (ret) {
+ ret = -errno;
+ goto out;
+ }
+ buf = xmalloc(NETLINK_BUFFER_SIZE);
+ if (!buf) {
+ ret = -ENOMEM;
+ goto out;
+ }
+ req->hdr.nlmsg_seq = 1;
+ if (sendto(fd, req, req->hdr.nlmsg_len, 0,
+ (const struct sockaddr *)&kernel, sizeof(kernel)) < 0) {
+ ret = -errno;
+ goto out;
+ }
+ for (;;) {
+ struct iovec iov = { .iov_base = buf, .iov_len = NETLINK_BUFFER_SIZE };
+ struct sockaddr_nl sender = {};
+ struct msghdr msg = {
+ .msg_name = &sender,
+ .msg_namelen = sizeof(sender),
+ .msg_iov = &iov,
+ .msg_iovlen = 1,
+ };
+ const __u8 *cursor = buf;
+ ssize_t n;
+
+ n = recvmsg(fd, &msg, 0);
+ if (n < 0) {
+ ret = -errno;
+ goto out;
+ }
+ if (!n || msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC) ||
+ msg.msg_namelen != sizeof(sender) || sender.nl_pid ||
+ sender.nl_family != AF_NETLINK) {
+ ret = -EBADMSG;
+ goto out;
+ }
+ while (n) {
+ const struct nlmsghdr *hdr = (const void *)cursor;
+ size_t len, step;
+
+ ret = -EBADMSG;
+ if ((size_t)n < sizeof(*hdr) ||
+ hdr->nlmsg_len < sizeof(*hdr) || hdr->nlmsg_len > (__u32)n)
+ goto out;
+ step = NLMSG_ALIGN(hdr->nlmsg_len);
+ if (step > (size_t)n || hdr->nlmsg_seq != 1)
+ goto out;
+ if (hdr->nlmsg_flags & NLM_F_DUMP_INTR) {
+ ret = -EAGAIN;
+ goto out;
+ }
+ len = hdr->nlmsg_len - sizeof(*hdr);
+ if (hdr->nlmsg_type == NLMSG_ERROR) {
+ struct nlmsgerr err;
+
+ if (len < sizeof(err))
+ goto out;
+ memcpy(&err, cursor + sizeof(*hdr), sizeof(err));
+ ret = err.error <= 0 ? err.error : -EBADMSG;
+ goto out;
+ }
+ if (hdr->nlmsg_type == NLMSG_DONE) {
+ int err = 0;
+
+ if (len && len < sizeof(err))
+ goto out;
+ if (len)
+ memcpy(&err, cursor + sizeof(*hdr), sizeof(err));
+ ret = err <= 0 ? err : -EBADMSG;
+ goto out;
+ }
+ ret = receive(cursor + sizeof(*hdr), len, ctx);
+ if (ret || !(hdr->nlmsg_flags & NLM_F_MULTI))
+ goto out;
+ cursor += step;
+ n -= (ssize_t)step;
+ }
+ }
+out:
+ xfree(buf, NETLINK_BUFFER_SIZE);
+ close(fd);
+ return ret;
+}
+
+int xdp_device_parse(const void *data, size_t len, struct xdp_device *out)
+{
+ const struct nlattr *linkinfo, *port;
+ bool port_present = false;
+ struct ifinfomsg info;
+ __s32 peer_netns = 0;
+ const __u8 *attrs;
+ int ret;
+
+ memset(out, 0, sizeof(*out));
+ out->port_flavour = UINT16_MAX;
+ if (len < sizeof(info))
+ return -EINVAL;
+ memcpy(&info, data, sizeof(info));
+ if (info.ifi_index <= 0)
+ return -EINVAL;
+ out->ifindex = (__u32)info.ifi_index;
+ out->flags = info.ifi_flags;
+ attrs = (const __u8 *)data + sizeof(info);
+ len -= sizeof(info);
+ ret = attr_string(attrs, len, IFLA_IFNAME, out->name, sizeof(out->name));
+ if (ret || !out->name[0])
+ return ret ? ret : -EINVAL;
+ ret = attr_number(attrs, len, IFLA_LINK, &out->peer_ifindex,
+ sizeof(out->peer_ifindex), NULL);
+ if (ret)
+ return ret;
+ ret = attr_number(attrs, len, IFLA_LINK_NETNSID, &peer_netns,
+ sizeof(peer_netns), &out->peer_other_netns);
+ if (ret)
+ return ret;
+ ret = attr_string(attrs, len, IFLA_PARENT_DEV_BUS_NAME, out->parent_bus,
+ sizeof(out->parent_bus));
+ if (ret)
+ return ret;
+ ret = attr_find(attrs, len, IFLA_LINKINFO, &linkinfo);
+ if (ret)
+ return ret;
+ if (linkinfo) {
+ ret = attr_string((const __u8 *)linkinfo + NLA_HDRLEN,
+ linkinfo->nla_len - NLA_HDRLEN, IFLA_INFO_KIND,
+ out->kind, sizeof(out->kind));
+ if (ret)
+ return ret;
+ }
+ ret = attr_find(attrs, len, IFLA_DEVLINK_PORT, &port);
+ if (ret || !port || port->nla_len == NLA_HDRLEN)
+ return ret;
+ attrs = (const __u8 *)port + NLA_HDRLEN;
+ len = port->nla_len - NLA_HDRLEN;
+ out->devlink_port = true;
+ ret = attr_string(attrs, len, DEVLINK_ATTR_BUS_NAME, out->devlink_bus,
+ sizeof(out->devlink_bus));
+ if (ret)
+ return ret;
+ ret = attr_string(attrs, len, DEVLINK_ATTR_DEV_NAME, out->devlink_device,
+ sizeof(out->devlink_device));
+ if (ret || !out->devlink_bus[0] || !out->devlink_device[0])
+ return ret ? ret : -EINVAL;
+ ret = attr_number(attrs, len, DEVLINK_ATTR_PORT_INDEX, &out->port_index,
+ sizeof(out->port_index), &port_present);
+ return ret ? ret : port_present ? 0 : -EINVAL;
+}
+
+__u32 xdp_device_class(const struct xdp_device *dev)
+{
+ static const char * const vm_drivers[] = {
+ "virtio_net", "vmxnet3", "hv_netvsc", "xen-netfront", "vif",
+ };
+ size_t i;
+
+ if (dev->flags & IFF_LOOPBACK)
+ return 0;
+ for (i = 0; i < ARRAY_SIZE(vm_drivers); i++)
+ if (!strcmp(dev->driver, vm_drivers[i]))
+ return UPATCH_XDP_VM;
+ if (dev->devlink_port) {
+ switch (dev->port_flavour) {
+ case DEVLINK_PORT_FLAVOUR_PHYSICAL:
+ return UPATCH_XDP_NETWORK;
+ case DEVLINK_PORT_FLAVOUR_CPU:
+ case DEVLINK_PORT_FLAVOUR_DSA:
+ case DEVLINK_PORT_FLAVOUR_PCI_PF:
+ case DEVLINK_PORT_FLAVOUR_PCI_VF:
+ case DEVLINK_PORT_FLAVOUR_VIRTUAL:
+ case DEVLINK_PORT_FLAVOUR_PCI_SF:
+ return UPATCH_XDP_VIRTUAL;
+ default:
+ return UPATCH_XDP_UNKNOWN;
+ }
+ }
+ if (!strcmp(dev->driver, "netdevsim"))
+ return UPATCH_XDP_VIRTUAL;
+ if (dev->parent_bus[0])
+ return UPATCH_XDP_NETWORK;
+ if (dev->kind[0])
+ return UPATCH_XDP_VIRTUAL;
+ return UPATCH_XDP_UNKNOWN;
+}
+
+bool xdp_device_selected(const struct xdp_device *devs, size_t count,
+ size_t index, __u32 mask)
+{
+ const struct xdp_device *dev = &devs[index];
+ size_t i;
+
+ if (!(xdp_device_class(dev) & mask))
+ return false;
+ if (strcmp(dev->kind, "veth") || dev->peer_other_netns)
+ return true;
+ for (i = 0; i < count; i++) {
+ const struct xdp_device *peer = &devs[i];
+
+ if (peer->ifindex == dev->peer_ifindex &&
+ peer->peer_ifindex == dev->ifindex &&
+ !peer->peer_other_netns && !strcmp(peer->kind, "veth"))
+ return dev->ifindex < peer->ifindex;
+ }
+ return false;
+}
+
+struct device_list {
+ struct xdp_device *devices;
+ size_t count;
+};
+
+static int receive_device(const void *data, size_t len, void *ctx)
+{
+ struct device_list *list = ctx;
+ struct xdp_device dev, *grown;
+ size_t count;
+ int ret;
+
+ ret = xdp_device_parse(data, len, &dev);
+ if (ret)
+ return ret;
+ if (check_add_overflow(list->count, 1, &count))
+ return -EOVERFLOW;
+ grown = xreallocarray(list->devices, list->count, count, sizeof(dev));
+ if (!grown)
+ return -ENOMEM;
+ list->devices = grown;
+ list->devices[list->count++] = dev;
+ return 0;
+}
+
+static int receive_family(const void *data, size_t len, void *ctx)
+{
+ if (len < GENL_HDRLEN)
+ return -EINVAL;
+ return attr_number((const __u8 *)data + GENL_HDRLEN, len - GENL_HDRLEN,
+ CTRL_ATTR_FAMILY_ID, ctx, sizeof(__u16), NULL);
+}
+
+static int devlink_family(__u16 *id)
+{
+ struct nl_request req = {
+ .hdr.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN),
+ .hdr.nlmsg_type = GENL_ID_CTRL,
+ .hdr.nlmsg_flags = NLM_F_REQUEST,
+ };
+ struct genlmsghdr genl = { .cmd = CTRL_CMD_GETFAMILY, .version = 1 };
+ int ret;
+
+ memcpy(req.data, &genl, sizeof(genl));
+ ret = attr_put(&req, CTRL_ATTR_FAMILY_NAME, DEVLINK_GENL_NAME,
+ sizeof(DEVLINK_GENL_NAME));
+ return ret ? ret : nl_exchange(NETLINK_GENERIC, &req, receive_family, id);
+}
+
+static int receive_port(const void *data, size_t len, void *ctx)
+{
+ struct xdp_device *dev = ctx;
+
+ if (len < GENL_HDRLEN)
+ return -EINVAL;
+ return attr_number((const __u8 *)data + GENL_HDRLEN, len - GENL_HDRLEN,
+ DEVLINK_ATTR_PORT_FLAVOUR, &dev->port_flavour,
+ sizeof(dev->port_flavour), NULL);
+}
+
+static int device_details(struct xdp_device *dev)
+{
+ struct ethtool_drvinfo driver = { .cmd = ETHTOOL_GDRVINFO };
+ struct ifreq identity = {};
+ struct ifreq ifr = {};
+ int fd, ret;
+
+ if (strscpy(ifr.ifr_name, dev->name, sizeof(ifr.ifr_name)) < 0)
+ return -EINVAL;
+ identity = ifr;
+ fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ if (fd < 0)
+ return -errno;
+ if (ioctl(fd, SIOCGIFINDEX, &identity) ||
+ identity.ifr_ifindex != (int)dev->ifindex) {
+ close(fd);
+ return -EXDEV;
+ }
+ ifr.ifr_data = (void *)&driver;
+ ret = ioctl(fd, SIOCETHTOOL, &ifr) ? -errno : 0;
+ if (ioctl(fd, SIOCGIFINDEX, &identity) ||
+ identity.ifr_ifindex != (int)dev->ifindex)
+ ret = -EXDEV;
+ close(fd);
+ if (ret && ret != -EOPNOTSUPP && ret != -ENOTTY)
+ return ret;
+ if (!ret) {
+ if (!memchr(driver.driver, '\0', sizeof(driver.driver)))
+ return -EINVAL;
+ memcpy(dev->driver, driver.driver, sizeof(dev->driver));
+ }
+ if (dev->devlink_port) {
+ struct nl_request req = {
+ .hdr.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN),
+ .hdr.nlmsg_flags = NLM_F_REQUEST,
+ };
+ struct genlmsghdr genl = {
+ .cmd = DEVLINK_CMD_PORT_GET,
+ .version = DEVLINK_GENL_VERSION,
+ };
+ __u16 family = 0;
+
+ ret = devlink_family(&family);
+ if (ret || !family)
+ return ret ? ret : -EINVAL;
+ req.hdr.nlmsg_type = family;
+ memcpy(req.data, &genl, sizeof(genl));
+ ret = attr_put(&req, DEVLINK_ATTR_BUS_NAME, dev->devlink_bus,
+ strlen(dev->devlink_bus) + 1);
+ if (!ret)
+ ret = attr_put(&req, DEVLINK_ATTR_DEV_NAME,
+ dev->devlink_device,
+ strlen(dev->devlink_device) + 1);
+ if (!ret)
+ ret = attr_put(&req, DEVLINK_ATTR_PORT_INDEX,
+ &dev->port_index, sizeof(dev->port_index));
+ if (ret)
+ return ret;
+ return nl_exchange(NETLINK_GENERIC, &req, receive_port, dev);
+ }
+ return 0;
+}
+
+static int device_compare(const void *a, const void *b)
+{
+ const struct xdp_device *left = a, *right = b;
+
+ return (left->ifindex > right->ifindex) -
+ (left->ifindex < right->ifindex);
+}
+
+int xdp_devices_read(struct xdp_device **out, size_t *count)
+{
+ struct nl_request req = {
+ .hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
+ .hdr.nlmsg_type = RTM_GETLINK,
+ .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
+ };
+ struct device_list list = {};
+ size_t i;
+ int ret;
+
+ *out = NULL;
+ *count = 0;
+ ret = nl_exchange(NETLINK_ROUTE, &req, receive_device, &list);
+ if (ret)
+ goto out;
+ qsort(list.devices, list.count, sizeof(*list.devices), device_compare);
+ for (i = 0; i < list.count; i++) {
+ const struct xdp_device *dev = &list.devices[i];
+ bool found = false;
+ size_t j;
+
+ if (i && list.devices[i - 1].ifindex == list.devices[i].ifindex) {
+ ret = -EXDEV;
+ goto out;
+ }
+ ret = device_details(&list.devices[i]);
+ if (ret)
+ goto out;
+ if (strcmp(dev->kind, "veth") || dev->peer_other_netns)
+ continue;
+ for (j = 0; j < list.count; j++) {
+ const struct xdp_device *peer = &list.devices[j];
+
+ if (peer->ifindex != dev->ifindex &&
+ peer->ifindex == dev->peer_ifindex &&
+ peer->peer_ifindex == dev->ifindex &&
+ !peer->peer_other_netns && !strcmp(peer->kind, "veth"))
+ found = true;
+ }
+ if (!found) {
+ ret = -EXDEV;
+ goto out;
+ }
+ }
+ *out = list.devices;
+ *count = list.count;
+ return 0;
+out:
+ xfree(list.devices, size_mul(list.count, sizeof(*list.devices)));
+ return ret;
+}
+
+int xdp_device_verify(const struct xdp_device *expected)
+{
+ struct nl_request req = {
+ .hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
+ .hdr.nlmsg_type = RTM_GETLINK,
+ .hdr.nlmsg_flags = NLM_F_REQUEST,
+ };
+ struct ifinfomsg info = { .ifi_index = (int)expected->ifindex };
+ struct device_list list = {};
+ struct xdp_device *dev;
+ int ret;
+
+ memcpy(req.data, &info, sizeof(info));
+ ret = nl_exchange(NETLINK_ROUTE, &req, receive_device, &list);
+ if (ret)
+ goto out;
+ if (list.count != 1) {
+ ret = -EXDEV;
+ goto out;
+ }
+ dev = list.devices;
+ ret = device_details(dev);
+ if (ret)
+ goto out;
+ if (dev->ifindex != expected->ifindex ||
+ dev->peer_ifindex != expected->peer_ifindex ||
+ dev->peer_other_netns != expected->peer_other_netns ||
+ strcmp(dev->kind, expected->kind) ||
+ xdp_device_class(dev) != xdp_device_class(expected))
+ ret = -EXDEV;
+out:
+ xfree(list.devices, size_mul(list.count, sizeof(*list.devices)));
+ return ret;
+}
diff --git a/util/xdp.h b/util/xdp.h
new file mode 100644
index 00000000..897873d5
--- /dev/null
+++ b/util/xdp.h
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: BSD-2-Clause */
+/* Copyright (c) 2026 Authors of shirudo */
+
+#ifndef SHIRUDO_XDP_H
+#define SHIRUDO_XDP_H
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#include <shirudo/misc.h>
+
+#define XDP_IFNAME_MAX 16
+
+struct xdp_device {
+ char devlink_device[128];
+ char devlink_bus[128];
+ char parent_bus[64];
+ char kind[64];
+ char driver[32];
+ char name[XDP_IFNAME_MAX];
+ __u32 ifindex;
+ __u32 peer_ifindex;
+ __u32 flags;
+ __u32 port_index;
+ __u16 port_flavour;
+ bool peer_other_netns;
+ bool devlink_port;
+};
+
+int xdp_device_parse(const void *data, size_t len, struct xdp_device *out);
+__u32 xdp_device_class(const struct xdp_device *dev);
+bool xdp_device_selected(const struct xdp_device *devs, size_t count,
+ size_t index, __u32 mask);
+int xdp_devices_read(struct xdp_device **out, size_t *count);
+int xdp_device_verify(const struct xdp_device *expected);
+
+#endif /* SHIRUDO_XDP_H */