From e283ee20022aa1a51bb6754c56115b7dbc5d484b 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 NUL terminated Limit of map names in eBPF is 16 bytes and they have to be NUL 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 NUL byte. This change fixes that by truncating the name to 15 bytes, ensuring that the 16th byte is NUL. `MAP_WITH_LOOOONG_NAAAAAAAAME` is truncated to `MAP_WITH_LOOOON\0`. --- aya/src/sys/bpf.rs | 4 ++-- test/integration-ebpf/src/map_test.rs | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/aya/src/sys/bpf.rs b/aya/src/sys/bpf.rs index 2332ac6f..ed26c1ac 100644 --- a/aya/src/sys/bpf.rs +++ b/aya/src/sys/bpf.rs @@ -93,9 +93,9 @@ 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) { + let name_bytes = name.to_bytes(); // 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 len = cmp::min(name_bytes.len(), u.map_name.len() - 1); 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 {