libbpf: Fix potential misaligned memory access in btf_ext__new()
authorAndrii Nakryiko <andrii@kernel.org>
Wed, 24 Nov 2021 00:23:14 +0000 (16:23 -0800)
committerDaniel Borkmann <daniel@iogearbox.net>
Thu, 25 Nov 2021 23:14:06 +0000 (00:14 +0100)
Perform a memory copy before we do the sanity checks of btf_ext_hdr.
This prevents misaligned memory access if raw btf_ext data is not 4-byte
aligned ([0]).

While at it, also add missing const qualifier.

  [0] Closes: https://github.com/libbpf/libbpf/issues/391

Fixes: 2993e0515bb4 ("tools/bpf: add support to read .BTF.ext sections")
Reported-by: Evgeny Vereshchagin <evvers@ya.ru>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20211124002325.1737739-3-andrii@kernel.org
tools/lib/bpf/btf.c
tools/lib/bpf/btf.h

index e97217a771966aa7f5fada797ae9a0c00269ed3e..8024fe355ca866f34d51cc8cc036164043fa2d34 100644 (file)
@@ -2731,15 +2731,11 @@ void btf_ext__free(struct btf_ext *btf_ext)
        free(btf_ext);
 }
 
-struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
+struct btf_ext *btf_ext__new(const __u8 *data, __u32 size)
 {
        struct btf_ext *btf_ext;
        int err;
 
-       err = btf_ext_parse_hdr(data, size);
-       if (err)
-               return libbpf_err_ptr(err);
-
        btf_ext = calloc(1, sizeof(struct btf_ext));
        if (!btf_ext)
                return libbpf_err_ptr(-ENOMEM);
@@ -2752,6 +2748,10 @@ struct btf_ext *btf_ext__new(__u8 *data, __u32 size)
        }
        memcpy(btf_ext->data, data, size);
 
+       err = btf_ext_parse_hdr(btf_ext->data, size);
+       if (err)
+               goto done;
+
        if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, line_info_len)) {
                err = -EINVAL;
                goto done;
index 5c73a5b0a044f589f55ff79b7881368a30a87f66..742a2bf71c5eef52fd441f50747c8bc8487c947d 100644 (file)
@@ -157,7 +157,7 @@ LIBBPF_API int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
                                    __u32 expected_value_size,
                                    __u32 *key_type_id, __u32 *value_type_id);
 
-LIBBPF_API struct btf_ext *btf_ext__new(__u8 *data, __u32 size);
+LIBBPF_API struct btf_ext *btf_ext__new(const __u8 *data, __u32 size);
 LIBBPF_API void btf_ext__free(struct btf_ext *btf_ext);
 LIBBPF_API const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext,
                                             __u32 *size);