From f48b5a4a84a858dd3a24101a83a3b03c314f1c5c Mon Sep 17 00:00:00 2001 From: Michal Rostecki Date: Wed, 12 Mar 2025 09:11:53 +0100 Subject: [PATCH] aya: Ensure that truncated map names are NULL terminated Limit of map names in eBPF is 16 bytes and they have to be NULL terminated. Before this change, long names were truncated to 16 bytes. `MAP_WITH_LOOOONG_NAAAAAAAAME` would become `MAP_WITH_LOOOONG`, which doesn't contain the NULL byte. This change fixes that by truncating the name to 15 bytes, ensuring that the 16th byte is NULL. `MAP_WITH_LOOOONG_NAAAAAAAAME` is truncated to `MAP_WITH_LOOOON\0`. --- aya/src/sys/bpf.rs | 5 ++--- test/integration-ebpf/src/map_test.rs | 5 +++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/aya/src/sys/bpf.rs b/aya/src/sys/bpf.rs index 2332ac6f..3d6d419f 100644 --- a/aya/src/sys/bpf.rs +++ b/aya/src/sys/bpf.rs @@ -93,9 +93,8 @@ pub(crate) fn bpf_create_map( // The map name was added as a parameter in kernel 4.15+ so we skip adding it on // older kernels for compatibility if KernelVersion::at_least(4, 15, 0) { - // u.map_name is 16 bytes max and must be NULL terminated - let name_bytes = name.to_bytes_with_nul(); - let len = cmp::min(name_bytes.len(), u.map_name.len()); + let name_bytes = name.to_bytes(); + let len = cmp::min(name_bytes.len(), u.map_name.len() - 1); // Ensure NULL termination. u.map_name[..len] .copy_from_slice(unsafe { mem::transmute::<&[u8], &[c_char]>(&name_bytes[..len]) }); } diff --git a/test/integration-ebpf/src/map_test.rs b/test/integration-ebpf/src/map_test.rs index e3fc28bc..e53b2f85 100644 --- a/test/integration-ebpf/src/map_test.rs +++ b/test/integration-ebpf/src/map_test.rs @@ -18,6 +18,11 @@ static FOO: Array = Array::::with_max_entries(10, 0); #[map(name = "BAR")] static BAZ: HashMap = HashMap::::with_max_entries(8, 0); +// The limit of map names is 16 (including a NUL byte). Ensure that we are +// able to create maps with names exceeding that limit by truncating them. +#[map(name = "MAP_WITH_LOOOONG_NAAAAAAAAME")] +static MAP_WITH_LOOOONG_NAAAAAAAAME: HashMap = HashMap::::with_max_entries(8, 0); + // Introduced in kernel v3.19. #[socket_filter] pub fn simple_prog(_ctx: SkBuffContext) -> i64 {