浏览代码

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`.
Michal Rostecki 3 周之前
父节点
当前提交
f48b5a4a84
共有 2 个文件被更改,包括 7 次插入3 次删除
  1. 2 3
      aya/src/sys/bpf.rs
  2. 5 0
      test/integration-ebpf/src/map_test.rs

+ 2 - 3
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
     // The map name was added as a parameter in kernel 4.15+ so we skip adding it on
     // older kernels for compatibility
     // older kernels for compatibility
     if KernelVersion::at_least(4, 15, 0) {
     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]
         u.map_name[..len]
             .copy_from_slice(unsafe { mem::transmute::<&[u8], &[c_char]>(&name_bytes[..len]) });
             .copy_from_slice(unsafe { mem::transmute::<&[u8], &[c_char]>(&name_bytes[..len]) });
     }
     }

+ 5 - 0
test/integration-ebpf/src/map_test.rs

@@ -18,6 +18,11 @@ static FOO: Array<u32> = Array::<u32>::with_max_entries(10, 0);
 #[map(name = "BAR")]
 #[map(name = "BAR")]
 static BAZ: HashMap<u32, u8> = HashMap::<u32, u8>::with_max_entries(8, 0);
 static BAZ: HashMap<u32, u8> = HashMap::<u32, u8>::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<u32, u8> = HashMap::<u32, u8>::with_max_entries(8, 0);
+
 // Introduced in kernel v3.19.
 // Introduced in kernel v3.19.
 #[socket_filter]
 #[socket_filter]
 pub fn simple_prog(_ctx: SkBuffContext) -> i64 {
 pub fn simple_prog(_ctx: SkBuffContext) -> i64 {