libbpf: fix UAF in strset__add_str()
PATCH 1/1 libbpf: fix UAF in strset__add_str()
strset_add_str_mem() might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting to memcpy() the string into the new buffer.
One scenario that triggers this problematic path is when resolve_btfids attempts to patch kfunc prototypes using existing BTF parameter names:
| resolve_btfids: function bpf_list_push_back_impl already exists in BTF | Segmentation fault (core dumped)
Compiling resolve_btfids with fsanitize=address generates a detailed report of the UAF:
| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20
While resolve_btfids could be refactored to avoid this call path, let's instead fix this issue at the source in strset__add_str() and avoid similar scenarios. Let's simply check whether 's' is already within the strset data buffer boundaries, and return the offset directly if so.
--- tools/lib/bpf/strset.c | 5 +++++ 1 file changed, 5 insertions(+)
tools/lib/bpf/strset.c +5 -0
@@ -141,10 +141,15 @@ int strset__find_str(struct strset *set, const char *s)*/ int strset__add_str (struct strset *set,const char *s) { +const char *strs =strset__data (set);long old_off, new_off, len;void *p;int err; +/* Check whether 's' is already in the strset data buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) +return s - strs; +/* Hashmap keys are always offsets within set->strs_data, so to even * look up some string from the "outside", we need to first append it * at the end, so that it can be addressed with an offset. Luckily,
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
[email protected]
AI reviewThe existing Fixes: tag points to commit 919d2b1dbb07, but the bug is actually in strset__add_str() which was introduced by commit 90d76d3ececc ("libbpf: Extract internal set-of-strings…
Quoted 40 lines
strset_add_str_mem()might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting tomemcpy()the string into the new buffer.One scenario that triggers this problematic path is when
resolve_btfidsattempts to patch kfunc prototypes using existing BTF parameter names:|
resolve_btfids: functionbpf_list_push_back_implalready exists in BTF | Segmentation fault (core dumped)Compiling
resolve_btfidswith fsanitize=address generates a detailed report of the UAF:| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20
Quoted 7 lines
While
resolve_btfidscould be refactored to avoid this call path, let's instead fix this issue at the source instrset__add_str()and avoid similar scenarios. Let's simply check whether 's' is already within the strset data buffer boundaries, and return the offset directly if so.Fixes 919d2b1dbb07 ("libbpf: Allow modification of BTF and add btf__add_str API")Signed-off-by Carlos Llamas <[email protected]>
The existing Fixes: tag points to commit 919d2b1dbb07, but the bug is actually in strset__add_str() which was introduced by commit 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs").
While the vulnerable pattern originated in btf__add_str() from 919d2b1dbb07, the code being fixed resides in tools/lib/bpf/strset.c which was created by 90d76d3ececc when the string set functionality was extracted into a separate module.
Should this use:
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/25832614669
Quoted 7 lines · On Wed, May 13, 2026 at 11:55:53PM +0000, [email protected] wrote:
Quoted 3 lines
Fixes 919d2b1dbb07 ("libbpf: Allow modification of BTF and add btf__add_str API")Signed-off-by Carlos Llamas <[email protected]>The existing Fixes: tag points to commit
919d2b1dbb07, but the bug is actually instrset__add_str()which was introduced by commit90d76d3ececc("libbpf: Extract internal set-of-strings datastructure APIs").
Yes, the bug is currently in strset__add_str(). But it used to be in btf__add_str() before the problematic code got migrated into a separate file.
Quoted 4 lines
While the vulnerable pattern originated in
btf__add_str()from919d2b1dbb07, the code being fixed resides intools/lib/bpf/strset.cwhich was created by90d76d3ececcwhen the string set functionality was extracted into a separate module.
Right, you are making my point here.
Quoted 3 lines
Should this use:
Fixes 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs")
I would think the commit tagged as "Fixes:" should be the one that introduced the issue and not the one that better fits the file name or function no?
Another idea would be to tag instead the commit that introduced the specific pattern that I ran into, which would be commit 9d199965990c ("resolve_btfids: Support for KF_IMPLICIT_ARGS").
Anyway, I'm happy to use any of these. It would be nice if a human can confirm a preference though lol.
Regards,
--
Carlos Llamas
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Unpatched Use-After-Free in strset__find_str() - [High] Use-After-Free in BTF add APIs due to…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Unpatched Use-After-Free in strset__find_str()
- [High] Use-After-Free in BTF add APIs due to btf_ensure_modifiable() freeing raw_data
- [Medium] Early return in strset__add_str() breaks hash map deduplication invariants --
commit 2a7bfcb093726b849608e340f9bda7c5e3f56ac2
Author: Carlos Llamas <[email protected]>
libbpf: fix UAF in strset__add_str()
This commit addresses a heap-use-after-free in strset__add_str() that occurs when the provided string points into the internal strset data buffer. It adds a boundary check to return the offset directly if the string is already within the buffer, avoiding a dangling pointer during reallocation.
[ ... ]
Quoted 4 lines
| #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14
[ ... ]
Does btf__add_str() have another use-after-free when operating on a non-modifiable BTF object?
If a user calls btf__add_str(btf, s) where s is a pointer returned by btf__name_by_offset() (which points into btf->raw_data), btf_ensure_modifiable(btf) is called.
btf_ensure_modifiable() allocates new buffers and calls btf_invalidate_raw_data(btf), which frees btf->raw_data.
At this point, the argument s becomes a dangling pointer before strset__add_str() is even called, making the boundary check added by this patch evaluate against the freed raw_data.
tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s)
Quoted 5 lines
tools/lib/bpf/strset.c +0
-0@@ -141,10 +141,15 @@ int strset__find_str(struct strset *set, const char *s)
Does strset__find_str() suffer from the same vulnerability being fixed here?
It follows the exact same pattern as strset__add_str(): it temporarily appends s by calling strset_add_str_mem(set, len), which may realloc() the internal buffer.
If s points into the internal buffer, the realloc() frees the old memory, leaving s dangling before the memcpy() occurs.
tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s) · line 151
Quoted 11 lines
tools/lib/bpf/strset.c +4
-0*/ int strset__add_str (struct strset *set,const char *s) { +const char *strs =strset__data (set);long old_off, new_off, len;void *p;int err; +/* Check whether 's' is already in the strset data buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) +return s - strs;
Can this early return break hash map deduplication invariants if s is a substring?
If a caller passes a pointer to a substring of an existing string, the function returns the substring's offset but skips inserting it into set->strs_hash.
Because the substring is never added to the hash map, subsequent lookups for it via strset__find_str() will fail, and future additions from an external pointer will duplicate the string.
Would it be safer to calculate the offset, perform the realloc(), and then re-calculate the s pointer instead of returning early?
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Quoted 71 lines · On 5/14/26 12:57 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Unpatched Use-After-Free instrset__find_str()
- [High] Use-After-Free in BTF add APIs due tobtf_ensure_modifiable()freeingraw_data
- [Medium] Early return instrset__add_str()breaks hash map deduplication invariants --commit
2a7bfcb093726b849608e340f9bda7c5e3f56ac2
Author: Carlos Llamas <[email protected]>libbpf: fix UAF in
strset__add_str()This commit addresses a heap-use-after-free in
strset__add_str()that occurs when the provided string points into the internal strset data buffer. It adds a boundary check to return the offset directly if the string is already within the buffer, avoiding a dangling pointer during reallocation.[ ... ]
Quoted 4 lines
| #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14[ ... ]
Does
btf__add_str()have another use-after-free when operating on a non-modifiable BTF object?If a user calls
btf__add_str(btf, s)where s is a pointer returned bybtf__name_by_offset()(which points intobtf->raw_data),btf_ensure_modifiable(btf)is called.
btf_ensure_modifiable()allocates new buffers and callsbtf_invalidate_raw_data(btf), which freesbtf->raw_data.At this point, the argument s becomes a dangling pointer before
strset__add_str()is even called, making the boundary check added by this patch evaluate against the freedraw_data.tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s)
Quoted 5 lines
tools/lib/bpf/strset.c +0
-0@@ -141,10 +141,15 @@ int strset__find_str(struct strset *set, const char *s)Does
strset__find_str()suffer from the same vulnerability being fixed here?It follows the exact same pattern as
strset__add_str(): it temporarily appends s by callingstrset_add_str_mem(set, len), which mayrealloc()the internal buffer.If s points into the internal buffer, the
realloc()frees the old memory, leaving s dangling before thememcpy()occurs.tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s) · line 151
Quoted 11 lines
tools/lib/bpf/strset.c +4
-0*/ int strset__add_str (struct strset *set,const char *s) { +const char *strs =strset__data (set);long old_off, new_off, len;void *p;int err; +/* Check whether 's' is already in the strset data buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) +return s - strs;Can this early return break hash map deduplication invariants if s is a substring?
If a caller passes a pointer to a substring of an existing string, the function returns the substring's offset but skips inserting it into
set->strs_hash.
Quoted 7 lines
Because the substring is never added to the hash map, subsequent lookups for it via
strset__find_str()will fail, and future additions from an external pointer will duplicate the string.Would it be safer to calculate the offset, perform the
realloc(), and then re-calculate the s pointer instead of returning early?
It looks like sashiko is right, addressing the same issue in strset__find_str() and handling substring case could be useful.
maybe adding a helper like this:
/*
* Returns the offset of the string in set and length which set needs to
* grow by to include the string.
*/
int strset__offset(struct strset *set, const char *s, long *off, long *grow)
{
long len;
const char *strs = strset__data(set);
void *p;
if (s >= strs && s < strs + set->strs_data_len) {
*off = s - strs;
*grow = 0;
return 0;
}
len = strlen(s) + 1;
p = strset_add_str_mem(set, len);
if (!p)
return -ENOMEM;
memcpy(p, s, len);
*off = set->strs_data_len;
*grow = len;
return 0;
} Quoted 2 lines
[ ... ]
Quoted 78 lines · Mykyta Yatsenko
Quoted 75 lines · On 5/14/26 12:57 PM, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Unpatched Use-After-Free instrset__find_str()
- [High] Use-After-Free in BTF add APIs due tobtf_ensure_modifiable()freeingraw_data
- [Medium] Early return instrset__add_str()breaks hash map deduplication invariants --commit
2a7bfcb093726b849608e340f9bda7c5e3f56ac2
Author: Carlos Llamas <[email protected]>libbpf: fix UAF in
strset__add_str()This commit addresses a heap-use-after-free in
strset__add_str()that occurs when the provided string points into the internal strset data buffer. It adds a boundary check to return the offset directly if the string is already within the buffer, avoiding a dangling pointer during reallocation.[ ... ]
Quoted 4 lines
| #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14[ ... ]
Does
btf__add_str()have another use-after-free when operating on a non-modifiable BTF object?If a user calls
btf__add_str(btf, s)where s is a pointer returned bybtf__name_by_offset()(which points intobtf->raw_data),btf_ensure_modifiable(btf)is called.
btf_ensure_modifiable()allocates new buffers and callsbtf_invalidate_raw_data(btf), which freesbtf->raw_data.At this point, the argument s becomes a dangling pointer before
strset__add_str()is even called, making the boundary check added by this patch evaluate against the freedraw_data.tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s)
Quoted 5 lines
tools/lib/bpf/strset.c +0
-0@@ -141,10 +141,15 @@ int strset__find_str(struct strset *set, const char *s)Does
strset__find_str()suffer from the same vulnerability being fixed here?It follows the exact same pattern as
strset__add_str(): it temporarily appends s by callingstrset_add_str_mem(set, len), which mayrealloc()the internal buffer.If s points into the internal buffer, the
realloc()frees the old memory, leaving s dangling before thememcpy()occurs.tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s) · line 151
Quoted 11 lines
tools/lib/bpf/strset.c +4
-0*/ int strset__add_str (struct strset *set,const char *s) { +const char *strs =strset__data (set);long old_off, new_off, len;void *p;int err; +/* Check whether 's' is already in the strset data buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) +return s - strs;Can this early return break hash map deduplication invariants if s is a substring?
If a caller passes a pointer to a substring of an existing string, the function returns the substring's offset but skips inserting it into
set->strs_hash.Because the substring is never added to the hash map, subsequent lookups for it via
strset__find_str()will fail, and future additions from an external pointer will duplicate the string.
Quoted 6 lines
Quoted 3 lines
Would it be safer to calculate the offset, perform the
realloc(), and then re-calculate the s pointer instead of returning early?It looks like sashiko is right, addressing the same issue in
strset__find_str()and handling substring case could be useful.
The substring case is interesting, it can save memory space I suppose. Although it sounds like a brand new use-case, since users would need to perform some pointer manipulation on 's' first e.g. strstr(). Also, per the current logic doing so would still trigger the same UAF.
It does seem like more than just fixing the bug though. Would adding the support for substrings still get backported to stable without a user?
Yeah, it seems strset__find_str() suffers from the same issue. In general, it feels wrong to call these two APIs with a string that is already present in the buffer.
Anyway, thanks for the feedback and the example. I'll send a v2 with the suggestions.
--
Carlos Llamas
PATCH v2 1/1 libbpf: fix UAF in strset__add_str()
In reply to Mykyta Yatsenkostrset_add_str_mem() might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting to memcpy() the string into the new buffer.
One scenario that triggers this problematic path is when resolve_btfids attempts to patch kfunc prototypes using existing BTF parameter names:
| resolve_btfids: function bpf_list_push_back_impl already exists in BTF | Segmentation fault (core dumped)
Compiling resolve_btfids with fsanitize=address generates a detailed report of the UAF:
| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20
While resolve_btfids could be refactored to avoid this call path, let's instead fix this issue at the source in strset__add_str() and avoid similar scenarios. Let's simply check whether 's' is already within the strset data buffer boundaries, and skip appending it at the end of the buffer again.
While already here, also fix strset__find_str() which suffers from the same problem by factoring out the common operations into a new helper function strset__offset() as suggested by Mykyta.
---
v2:
Implemented the fix in strset__offset() helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used 90d76d3ececc as Fixes tag as suggested by Sashiko.
v1:
https://lore.kernel.org/all/[email protected]/
tools/lib/bpf/strset.c | 70 ++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 27 deletions(-)
tools/lib/bpf/strset.c +43 -27
@@ -107,25 +107,53 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } -/* Find string offset that corresponds to a given string *s*. -* Returns: -* - >0 offset into string data, if string is found; -* - -ENOENT, if string is not in the string data; -* - <0, on any other error. +/* Returns the offset of the string in set, and populates *grow* with the +* length which set needs to grow by to include *s*. */ -int strset__find_str (struct strset *set,const char *s) +static long strset__offset (struct strset *set,const char *s,long *grow) { -long old_off, new_off, len; +const char *strs =strset__data (set); +long len;void *p; -/* see strset__add_str() for why we do this */ +/* Check whether 's' is already within the buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) { + *grow =0 ; +return s - strs; + } + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ len =strlen (s) +1 ; p =strset_add_str_mem (set, len);if (!p)return -ENOMEM ; - new_off = set->strs_data_len;memcpy (p, s, len); + *grow = len; + +return set->strs_data_len; +} + +/* Find string offset that corresponds to a given string *s*. +* Returns: +* - >0 offset into string data, if string is found; +* - -ENOENT, if string is not in the string data; +* - <0, on any other error. +*/ +int strset__find_str (struct strset *set,const char *s) +{ +long old_off, new_off, grow; + + new_off =strset__offset (set, s, &grow); +if (new_off <0 ) +return new_off;if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;
@@ -141,25 +169,12 @@ int strset__find_str(struct strset *set, const char *s)*/ int strset__add_str (struct strset *set,const char *s) { -long old_off, new_off, len; -void *p; +long old_off, new_off, grow;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; - - new_off = set->strs_data_len; -memcpy (p, s, len); + new_off =strset__offset (set, s, &grow); +if (new_off <0 ) +return new_off;/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such
@@ -172,6 +187,7 @@ int strset__add_str(struct strset *set, const char *s)if (err)return err; - set->strs_data_len += len;/* new unique string, adjust data length */ + set->strs_data_len += grow;/* new unique string, adjust data length */ +return new_off; }
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
Quoted 74 lines · Carlos Llamas
strset_add_str_mem()might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting tomemcpy()the string into the new buffer.One scenario that triggers this problematic path is when
resolve_btfidsattempts to patch kfunc prototypes using existing BTF parameter names:|
resolve_btfids: functionbpf_list_push_back_implalready exists in BTF | Segmentation fault (core dumped)Compiling
resolve_btfidswith fsanitize=address generates a detailed report of the UAF:| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20While
resolve_btfidscould be refactored to avoid this call path, let's instead fix this issue at the source instrset__add_str()and avoid similar scenarios. Let's simply check whether 's' is already within the strset data buffer boundaries, and skip appending it at the end of the buffer again.While already here, also fix
strset__find_str()which suffers from the same problem by factoring out the common operations into a new helper functionstrset__offset()as suggested by Mykyta.Fixes 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs")Suggested-by Mykyta Yatsenko <[email protected]>Signed-off-by Carlos Llamas <[email protected]>---
v2:
Implemented the fix instrset__offset()helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used90d76d3ececcas Fixes tag as suggested by Sashiko.v1:
https://lore.kernel.org/all/[email protected]/tools/lib/bpf/strset.c | 70 ++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 27 deletions(-)tools/lib/bpf/strset.c +0
-0@@ -107,25 +107,53 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); }
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 113
Quoted 10 lines
tools/lib/bpf/strset.c +3
-6-/* Find string offset that corresponds to a given string *s*. -* Returns: -* - >0 offset into string data, if string is found; -* - -ENOENT, if string is not in the string data; -* - <0, on any other error. +/* Returns the offset of the string in set, and populates *grow* with the +* length which set needs to grow by to include *s*. */ -int strset__find_str (struct strset *set,const char *s) +static long strset__offset (struct strset *set,const char *s,long *grow)
tbh, it seems like
Quoted 37 lines
tools/lib/bpf/strset.c +25
-3{ -long old_off, new_off, len; +const char *strs =strset__data (set); +long len;void *p; -/* see strset__add_str() for why we do this */ +/* Check whether 's' is already within the buffer */ +if (strs && s >= strs && s < strs + set->strs_data_len) { + *grow =0 ; +return s - strs; + } + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ len =strlen (s) +1 ; p =strset_add_str_mem (set, len);if (!p)return -ENOMEM ; - new_off = set->strs_data_len;memcpy (p, s, len); + *grow = len; + +return set->strs_data_len; +} + +/* Find string offset that corresponds to a given string *s*. +* Returns: +* - >0 offset into string data, if string is found; +* - -ENOENT, if string is not in the string data;
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 157
Quoted 10 lines
tools/lib/bpf/strset.c +9
-0+* - <0, on any other error. +*/ +int strset__find_str (struct strset *set,const char *s) +{ +long old_off, new_off, grow; + + new_off =strset__offset (set, s, &grow); +if (new_off <0 ) +return new_off;
I'm not a fan of bypassing strs_hash, tbh... see below
Quoted 19 lines
tools/lib/bpf/strset.c +1
-10if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;@@ -141,25 +169,12 @@ int strset__find_str(struct strset *set, const char *s)*/ int strset__add_str (struct strset *set,const char *s) { -long old_off, new_off, len; -void *p; +long old_off, new_off, grow;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/
tools/lib/bpf/strset.c int strset__find_str(struct strset *set, const char *s) · line 177
Quoted 10 lines
tools/lib/bpf/strset.c +3
-7- len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; - - new_off = set->strs_data_len; -memcpy (p, s, len); + new_off =strset__offset (set, s, &grow); +if (new_off <0 ) +return new_off;
I agree that this is a usability problem, but I'd handle it by recalculating s pointer to correct one if it happens to be coming from invalidated strs_data. Something along the lines of:
const char *old_data = set->strs_data;size_t old_data_len = set->strs_data_len;
p = strset_add_str_mem(...);
if (!p)
return -ENOMEM;
if (p != old_data && s >= old_data && s < old_data + old_data_len)
s = p + (s - old_data);
At this point s will be correct even if it was invalidated.
pw-bot: cr
Quoted 15 lines
tools/lib/bpf/strset.c +2
-2/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such @@ -172,6 +187,7 @@ int strset__add_str(struct strset *set, const char *s)if (err)return err; - set->strs_data_len += len;/* new unique string, adjust data length */ + set->strs_data_len += grow;/* new unique string, adjust data length */ +return new_off; } --2.54.0.563.g4f69b47b94-goog
Quoted 11 lines · Andrii Nakryiko
I agree that this is a usability problem, but I'd handle it by recalculating s pointer to correct one if it happens to be coming from invalidated
strs_data. Something along the lines of:const char
*old_data=set->strs_data;size_told_data_len=set->strs_data_len;p =
strset_add_str_mem(...);
if (!p)return -ENOMEM;
Quoted 7 lines
if (p !=
old_data&& s >=old_data&& s <old_data+old_data_len)s = p + (s - old_data);At this point s will be correct even if it was invalidated.
pw-bot: cr
Oh right, that totally works. I've tested the changes and will send a new patch. Obviously 'p' was meant to be 'set->strs_data' in the check.
Thanks,
--
Carlos Llamas
PATCH v3 1/1 libbpf: fix UAF in strset__add_str()
In reply to Andrii Nakryikostrset_add_str_mem() might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting to memcpy() the string into the new buffer.
One scenario that triggers this problematic path is when resolve_btfids attempts to patch kfunc prototypes using existing BTF parameter names:
| resolve_btfids: function bpf_list_push_back_impl already exists in BTF | Segmentation fault (core dumped)
Compiling resolve_btfids with fsanitize=address generates a detailed report of the UAF:
| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20
While resolve_btfids could be refactored to avoid this call path, let's instead fix this issue at the source in strset__add_str() and avoid similar scenarios.
Let's check if set->strs_data was reallocated and whether 's' points to an internal string within the old strset buffer. In such case, 's' is reconstructed to point to the new buffer.
While already here, also fix strset__find_str() which suffers from the same problem by factoring out the common operations into a new helper function strset_str_append().
---
v3:
Switch to 's' reconstruction approach suggested by Andrii. Adjusted names and commit log accordingly.
v2:
Implemented the fix in strset__offset() helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used 90d76d3ececc as Fixes tag as suggested by Sashiko.
https://lore.kernel.org/all/[email protected]/
v1:
https://lore.kernel.org/all/[email protected]/
tools/lib/bpf/strset.c | 58 +++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-)
tools/lib/bpf/strset.c +37 -21
@@ -107,6 +107,37 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +const char *old_data =strset__data (set); +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data !=strset__data (set) && + s >= old_data && s < old_data + set->strs_data_len) + s =strset__data (set) + (s - old_data); + +memcpy (p, s, len); + +return len; +} +/* Find string offset that corresponds to a given string *s*. * Returns: * - >0 offset into string data, if string is found;
@@ -116,16 +147,12 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz)int strset__find_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p; -/* see strset__add_str() for why we do this */ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;
@@ -142,24 +169,13 @@ int strset__find_str(struct strset *set, const char *s)int strset__add_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Use-After-Free in btf__add_* APIs when called with strings from btf__name_by_offset on an…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Use-After-Free in btf__add_* APIs when called with strings from btf__name_by_offset on an unmodifiable BTF.
- [Medium] Undefined Behavior in pointer comparison and arithmetic potentially re-introducing UAF. --
commit c0c79bff673db7048c82410ff03ad09f2f25dbab
Author: Carlos Llamas <[email protected]>
libbpf: fix UAF in strset__add_str()
strset_add_str_mem() might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc.
Quoted 4 lines
tools/lib/bpf/strset.c +0
-0
[ ... ]
Quoted 18 lines
tools/lib/bpf/strset.c +14
-0@@ -107,6 +107,37 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +const char *old_data =strset__data (set); +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 133
Quoted 10 lines
tools/lib/bpf/strset.c +10
-0+ p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data !=strset__data (set) && + s >= old_data && s < old_data + set->strs_data_len)
Does this comparison invoke undefined behavior if old_data was freed by realloc() inside strset_add_str_mem() or if s is an unrelated pointer?
According to the C standard, comparing or subtracting freed or unrelated pointers using relational operators can invoke undefined behavior. Compilers tracking pointer provenance might deduce the pointer was freed and optimize away the bounds check entirely, bypassing the safety check.
Could these pointers be cast to uintptr_t before comparison to safely check the bounds?
Does a similar use-after-free still exist in the btf__add_* APIs (e.g. btf__add_str) when called with strings from btf__name_by_offset() on an unmodifiable BTF?
If a user passes a string retrieved via btf__name_by_offset(), the string pointer points directly into btf->raw_data.
Inside the btf__add_* APIs, btf_ensure_modifiable(btf) is called first, which calls btf_invalidate_raw_data() and frees btf->raw_data.
Could this leave the s pointer dangling before it even reaches this check? The check added here uses old_data which corresponds to btf->strs_set, not the freed btf->raw_data, so it wouldn't rescue the pointer.
Quoted 6 lines
tools/lib/bpf/strset.c +6
-0+ s =strset__data (set) + (s - old_data); + +memcpy (p, s, len); + +return len; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Quoted 78 lines · Carlos Llamas
strset_add_str_mem()might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting tomemcpy()the string into the new buffer.One scenario that triggers this problematic path is when
resolve_btfidsattempts to patch kfunc prototypes using existing BTF parameter names:|
resolve_btfids: functionbpf_list_push_back_implalready exists in BTF | Segmentation fault (core dumped)Compiling
resolve_btfidswith fsanitize=address generates a detailed report of the UAF:| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20While
resolve_btfidscould be refactored to avoid this call path, let's instead fix this issue at the source instrset__add_str()and avoid similar scenarios.Let's check if
set->strs_datawas reallocated and whether 's' points to an internal string within the old strset buffer. In such case, 's' is reconstructed to point to the new buffer.While already here, also fix
strset__find_str()which suffers from the same problem by factoring out the common operations into a new helper functionstrset_str_append().Fixes 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs")Suggested-by Andrii Nakryiko <[email protected]>Suggested-by Mykyta Yatsenko <[email protected]>Signed-off-by Carlos Llamas <[email protected]>---
v3:
Switch to 's' reconstruction approach suggested by Andrii. Adjusted names and commit log accordingly.v2:
Implemented the fix instrset__offset()helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used90d76d3ececcas Fixes tag as suggested by Sashiko.
https://lore.kernel.org/all/[email protected]/v1:
https://lore.kernel.org/all/[email protected]/tools/lib/bpf/strset.c | 58 +++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-)tools/lib/bpf/strset.c +0
-0
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 112
Quoted 6 lines
tools/lib/bpf/strset.c +3
-0@@ -107,6 +107,37 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +const char *old_data =strset__data (set);
sashiko suggests to use uintptr_t for this detection to avoid undefined behavior, let's do that then)?
but other than that and a nit below, looks good, thanks!
pw-bot: cr
Quoted 12 lines
tools/lib/bpf/strset.c +12
-0+long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len);
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 134
Quoted 10 lines
tools/lib/bpf/strset.c +10
-0+if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data !=strset__data (set) && + s >= old_data && s < old_data + set->strs_data_len) + s =strset__data (set) + (s - old_data);
nit: strset__data() is more of an "external api", note how we access strs_data_len directly through field. So let's use s->strs_data access consistently.
Quoted 60 lines
tools/lib/bpf/strset.c +12
-22+ +memcpy (p, s, len); + +return len; +} +/* Find string offset that corresponds to a given string *s*. * Returns: * - >0 offset into string data, if string is found; @@ -116,16 +147,12 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz)int strset__find_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p; -/* see strset__add_str() for why we do this */ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;@@ -142,24 +169,13 @@ int strset__find_str(struct strset *set, const char *s)int strset__add_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such -- 2.54.0.563.g4f69b47b94-goog
Quoted 90 lines · Andrii Nakryiko
Quoted 78 lines · Carlos Llamas
strset_add_str_mem()might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting tomemcpy()the string into the new buffer.One scenario that triggers this problematic path is when
resolve_btfidsattempts to patch kfunc prototypes using existing BTF parameter names:|
resolve_btfids: functionbpf_list_push_back_implalready exists in BTF | Segmentation fault (core dumped)Compiling
resolve_btfidswith fsanitize=address generates a detailed report of the UAF:| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20While
resolve_btfidscould be refactored to avoid this call path, let's instead fix this issue at the source instrset__add_str()and avoid similar scenarios.Let's check if
set->strs_datawas reallocated and whether 's' points to an internal string within the old strset buffer. In such case, 's' is reconstructed to point to the new buffer.While already here, also fix
strset__find_str()which suffers from the same problem by factoring out the common operations into a new helper functionstrset_str_append().Fixes 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs")Suggested-by Andrii Nakryiko <[email protected]>Suggested-by Mykyta Yatsenko <[email protected]>Signed-off-by Carlos Llamas <[email protected]>---
v3:
Switch to 's' reconstruction approach suggested by Andrii. Adjusted names and commit log accordingly.v2:
Implemented the fix instrset__offset()helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used90d76d3ececcas Fixes tag as suggested by Sashiko.
https://lore.kernel.org/all/[email protected]/v1:
https://lore.kernel.org/all/[email protected]/tools/lib/bpf/strset.c | 58 +++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-)tools/lib/bpf/strset.c +0
-0tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 112
Quoted 6 lines
tools/lib/bpf/strset.c +3
-0@@ -107,6 +107,37 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +const char *old_data =strset__data (set);sashiko suggests to use
uintptr_tfor this detection to avoid undefined behavior, let's do that then)?
Quoted 3 lines
but other than that and a nit below, looks good, thanks!
pw-bot: cr
Ping. Carlos, are you planning to send a follow up?
Quoted 88 lines
Quoted 13 lines
tools/lib/bpf/strset.c +12
-0+long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len);tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 134
Quoted 10 lines
tools/lib/bpf/strset.c +10
-0+if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data !=strset__data (set) && + s >= old_data && s < old_data + set->strs_data_len) + s =strset__data (set) + (s - old_data);nit:
strset__data()is more of an "external api", note how we accessstrs_data_lendirectly through field. So let's uses->strs_dataaccess consistently.Quoted 60 lines
tools/lib/bpf/strset.c +12
-22+ +memcpy (p, s, len); + +return len; +} +/* Find string offset that corresponds to a given string *s*. * Returns: * - >0 offset into string data, if string is found; @@ -116,16 +147,12 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz)int strset__find_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p; -/* see strset__add_str() for why we do this */ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;@@ -142,24 +169,13 @@ int strset__find_str(struct strset *set, const char *s)int strset__add_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such -- 2.54.0.563.g4f69b47b94-goog
Quoted 9 lines · Andrii Nakryiko
Quoted 7 lines
sashiko suggests to use
uintptr_tfor this detection to avoid undefined behavior, let's do that then)?but other than that and a nit below, looks good, thanks!
pw-bot: cr
Ping. Carlos, are you planning to send a follow up?
Hey Andrii sorry about the delay I got caught up with something else here. I'll send a new version in a bit with the uintptr_t casting and your suggestion. I would just say that it is a bit unfortunate that we'll have to clutter the code with this kind of parsing to avoid the compiler behavior that was mentioned. :(
Thanks,
Carlos Llamas
PATCH v4 1/1 libbpf: fix UAF in strset__add_str()
In reply to Andrii Nakryikostrset_add_str_mem() might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting to memcpy() the string into the new buffer.
One scenario that triggers this problematic path is when resolve_btfids attempts to patch kfunc prototypes using existing BTF parameter names:
| resolve_btfids: function bpf_list_push_back_impl already exists in BTF | Segmentation fault (core dumped)
Compiling resolve_btfids with fsanitize=address generates a detailed report of the UAF:
| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20
While resolve_btfids could be refactored to avoid this call path, let's instead fix this issue at the source in strset__add_str() and avoid similar scenarios.
Let's check if set->strs_data was reallocated and whether 's' points to an internal string within the old strset buffer. In such case, 's' is reconstructed to point to the new buffer.
While already here, also fix strset__find_str() which suffers from the same problem by factoring out the common operations into a new helper function strset_str_append().
---
v4:
Store pointers as integers in advance before realloc to prevent UB. Access set->strs_data directly, not through external API.
v3:
Switch to 's' reconstruction approach suggested by Andrii. Adjusted names and commit log accordingly.
https://lore.kernel.org/all/[email protected]/
v2:
Implemented the fix in strset__offset() helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used 90d76d3ececc as Fixes tag as suggested by Sashiko.
https://lore.kernel.org/all/[email protected]/
v1:
https://lore.kernel.org/all/[email protected]/
tools/lib/bpf/strset.c | 59 +++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 21 deletions(-)
tools/lib/bpf/strset.c +38 -21
@@ -107,6 +107,38 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +uintptr_t old_data = (uintptr_t )set->strs_data; +uintptr_t old_s = (uintptr_t )s; +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data != (uintptr_t )set->strs_data && + old_s >= old_data && old_s < old_data + set->strs_data_len) + s = set->strs_data + (old_s - old_data); + +memcpy (p, s, len); + +return len; +} +/* Find string offset that corresponds to a given string *s*. * Returns: * - >0 offset into string data, if string is found;
@@ -116,16 +148,12 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz)int strset__find_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p; -/* see strset__add_str() for why we do this */ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);if (hashmap__find (set->strs_hash, new_off, &old_off))return old_off;
@@ -142,24 +170,13 @@ int strset__find_str(struct strset *set, const char *s)int strset__add_str (struct strset *set,const char *s) {long old_off, new_off, len; -void *p;int err; -/* Hashmap keys are always offsets within set->strs_data, so to even -* look up some string from the "outside", we need to first append it -* at the end, so that it can be addressed with an offset. Luckily, -* until set->strs_data_len is incremented, that string is just a piece -* of garbage for the rest of the code, so no harm, no foul. On the -* other hand, if the string is unique, it's already appended and -* ready to be used, only a simple set->strs_data_len increment away. -*/ - len =strlen (s) +1 ; - p =strset_add_str_mem (set, len); -if (!p) -return -ENOMEM ; + len =strset_str_append (set, s); +if (len <0 ) +return len; new_off = set->strs_data_len; -memcpy (p, s, len);/* Now attempt to add the string, but only if the string with the same * contents doesn't exist already (HASHMAP_ADD strategy). If such
Signature · 1 line
2.54.0.746.g67dd491aae-goog
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Multi-line comments do not follow the BPF subsystem kernel style guidelines. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Multi-line comments do not follow the BPF subsystem kernel style guidelines. --
commit 85499e76a5baa5992df9be7379523577757796bf
Author: Carlos Llamas <[email protected]>
libbpf: fix UAF in strset__add_str()
This commit fixes a use-after-free issue where strset_add_str_mem() reallocation could cause the string pointer to become dangling if it pointed into the old buffer. It refactors the logic into a new helper function strset_str_append() that reconstructs the pointer when necessary.
Quoted 5 lines
tools/lib/bpf/strset.c +0
-0@@ -107,6 +107,38 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz)
[ ... ]
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 117
Quoted 8 lines
tools/lib/bpf/strset.c +8
-0+static long strset_str_append (struct strset *set,const char *s) +{ +uintptr_t old_data = (uintptr_t )set->strs_data; +uintptr_t old_s = (uintptr_t )s; +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even
[Severity: Low]
This isn't a bug, but the BPF subsystem prefers the modern kernel multi-line comment style which requires the opening /* to be on its own line. Could this be updated to match the BPF style guidelines?
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 129
Quoted 12 lines
tools/lib/bpf/strset.c +12
-0+* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed
[Severity: Low]
This isn't a bug either, but this comment also doesn't follow the preferred BPF subsystem multi-line comment style with the opening /* on its own line.
Quoted 8 lines
tools/lib/bpf/strset.c +8
-0+* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data != (uintptr_t )set->strs_data && + old_s >= old_data && old_s < old_data + set->strs_data_len) + s = set->strs_data + (old_s - old_data); + +memcpy (p, s, len);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewDoes a similar use-after-free still exist in the btf__add_* APIs (e.g. btf__add_str) when called with strings from btf__name_by_offset() on an unmodifiable BTF?
Quoted 29 lines
tools/lib/bpf/strset.c +21
-0@@ -107,6 +107,38 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +uintptr_t old_data = (uintptr_t )set->strs_data; +uintptr_t old_s = (uintptr_t )s; +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/ + p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 140
Quoted 10 lines
tools/lib/bpf/strset.c +10
-0+* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data != (uintptr_t )set->strs_data && + old_s >= old_data && old_s < old_data + set->strs_data_len) + s = set->strs_data + (old_s - old_data); + +memcpy (p, s, len); + +return len; +}
Does a similar use-after-free still exist in the btf__add_* APIs (e.g. btf__add_str) when called with strings from btf__name_by_offset() on an unmodifiable BTF?
If a user passes a string retrieved via btf__name_by_offset(), the string pointer points directly into btf->raw_data. Inside the btf__add_* APIs, btf_ensure_modifiable(btf) is called first, which calls btf_invalidate_raw_data() and frees btf->raw_data.
Could this leave the s pointer dangling before it even reaches this check? The check added here uses old_data which corresponds to btf->strs_set, not the freed btf->raw_data, so it wouldn't rescue the pointer.
This concern was raised by [email protected] on lore but was not addressed in subsequent patch versions.
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 144
Quoted 4 lines
tools/lib/bpf/strset.c +1
-0+/* Find string offset that corresponds to a given string *s*. * Returns: * - >0 offset into string data, if string is found;
[ ... ]
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26338132147
Andrii Nakryiko
AppliedQuoted 102 lines · Carlos Llamas
strset_add_str_mem()might reallocate the strset data buffer in order to accommodate the provided string 's'. However, if 's' points to a string already present in the buffer, it becomes dangling after the realloc. This leads to a use-after-free when attempting tomemcpy()the string into the new buffer.One scenario that triggers this problematic path is when
resolve_btfidsattempts to patch kfunc prototypes using existing BTF parameter names:|
resolve_btfids: functionbpf_list_push_back_implalready exists in BTF | Segmentation fault (core dumped)Compiling
resolve_btfidswith fsanitize=address generates a detailed report of the UAF:| ================================================================= | ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 | ==1507892==ERROR: AddressSanitizer: heap-use-after-free on address 0x7f4c4a500bd4 at pc 0x55d25155a2a8 bp 0x7ffcef879060 sp 0x7ffcef878818 | READ of size 5 at 0x7f4c4a500bd4 thread T0 | #0 0x55d25155a2a7 in memcpy (tools/bpf/resolve_btfids/resolve_btfids+0xcf2a7) | #1 0x55d2515d708e in strset__add_str tools/lib/bpf/strset.c:162:2 | #2 0x55d2515c730b in btf__add_str tools/lib/bpf/btf.c:2109:8 | #3 0x55d2515c9020 in btf__add_func_param tools/lib/bpf/btf.c:3108:14 | #4 0x55d25159f0b5 in process_kfunc_with_implicit_args tools/bpf/resolve_btfids/main.c:1196:9 | #5 0x55d25159e004 in btf2btf tools/bpf/resolve_btfids/main.c:1229:9 | #6 0x55d25159cee7 in main tools/bpf/resolve_btfids/main.c:1535:6 | #7 0x7f4c78e29f76 in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16 | #8 0x7f4c78e2a026 in __libc_start_main csu/../csu/libc-start.c:360:3 | #9 0x55d2514bb860 in _start (tools/bpf/resolve_btfids/resolve_btfids+0x30860) | | 0x7f4c4a500bd4 is located 13268 bytes inside of 2829000-byte region [0x7f4c4a4fd800,0x7f4c4a7b02c8) | freed by thread T0 here: | #0 0x55d25155b700 in realloc (tools/bpf/resolve_btfids/resolve_btfids+0xd0700) | #1 0x55d2515c426c in libbpf_reallocarray tools/lib/bpf/./libbpf_internal.h:220:9 | #2 0x55d2515c426c in libbpf_add_mem tools/lib/bpf/btf.c:224:13 | | previously allocated by thread T0 here: | #0 0x55d25155b2e3 in malloc (tools/bpf/resolve_btfids/resolve_btfids+0xd02e3) | #1 0x55d2515d6e7d in strset__new tools/lib/bpf/strset.c:58:20While
resolve_btfidscould be refactored to avoid this call path, let's instead fix this issue at the source instrset__add_str()and avoid similar scenarios.Let's check if
set->strs_datawas reallocated and whether 's' points to an internal string within the old strset buffer. In such case, 's' is reconstructed to point to the new buffer.While already here, also fix
strset__find_str()which suffers from the same problem by factoring out the common operations into a new helper functionstrset_str_append().Fixes 90d76d3ececc ("libbpf: Extract internal set-of-strings datastructure APIs")Suggested-by Andrii Nakryiko <[email protected]>Suggested-by Mykyta Yatsenko <[email protected]>Signed-off-by Carlos Llamas <[email protected]>---
v4:
Store pointers as integers in advance before realloc to prevent UB. Accessset->strs_datadirectly, not through external API.v3:
Switch to 's' reconstruction approach suggested by Andrii. Adjusted names and commit log accordingly.
https://lore.kernel.org/all/[email protected]/v2:
Implemented the fix instrset__offset()helper as suggested by Mykyta. Added support to handle "substrings" of existing ones. Used90d76d3ececcas Fixes tag as suggested by Sashiko.
https://lore.kernel.org/all/[email protected]/v1:
https://lore.kernel.org/all/[email protected]/tools/lib/bpf/strset.c | 59 +++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 21 deletions(-)tools/lib/bpf/strset.c +15
-0@@ -107,6 +107,38 @@ static void *strset_add_str_mem(struct strset *set, size_t add_sz) set->strs_data_len, set->strs_data_max_len, add_sz); } +static long strset_str_append (struct strset *set,const char *s) +{ +uintptr_t old_data = (uintptr_t )set->strs_data; +uintptr_t old_s = (uintptr_t )s; +long len =strlen (s) +1 ; +void *p; + +/* Hashmap keys are always offsets within set->strs_data, so to even +* look up some string from the "outside", we need to first append it +* at the end, so that it can be addressed with an offset. Luckily, +* until set->strs_data_len is incremented, that string is just a piece +* of garbage for the rest of the code, so no harm, no foul. On the +* other hand, if the string is unique, it's already appended and +* ready to be used, only a simple set->strs_data_len increment away. +*/
tools/lib/bpf/strset.c static void *strset_add_str_mem(struct strset *set, size_t add_sz) · line 134
Quoted 10 lines
tools/lib/bpf/strset.c +10
-0+ p =strset_add_str_mem (set, len); +if (!p) +return -ENOMEM ; + +/* The set->strs_data might have reallocated and if 's' pointed +* to an internal string within the old buffer, then it became +* dangling and needs to be reconstructed before the copy. +*/ +if (old_data && old_data != (uintptr_t )set->strs_data && + old_s >= old_data && old_s < old_data + set->strs_data_len)
we should use ols strs_data_len here, I fixed it up (and comment style issues pointed out by AI) like so:
$ git diff
tools/lib/bpf/strset.c +0 -0
@@ -110,11 +110,13 @@ static void *strset_add_str_mem(struct strset
*set, size_t add_sz)
static long strset_str_append(struct strset *set, const char *s)
{
uintptr_t old_data = (uintptr_t)set->strs_data;
+ size_t old_data_len = set->strs_data_len;
uintptr_t old_s = (uintptr_t)s;
long len = strlen(s) + 1;
void *p;- /* Hashmap keys are always offsets within set->strs_data, so to even
+ /*
+ * Hashmap keys are always offsets within set->strs_data, so to even
* look up some string from the "outside", we need to first append it
* at the end, so that it can be addressed with an offset. Luckily,
* until set->strs_data_len is incremented, that string is just a piece
@@ -126,12 +128,13 @@ static long strset_str_append(struct strset *set, const char *s)
if (!p)
return -ENOMEM;- /* The set->strs_data might have reallocated and if 's' pointed
+ /*
+ * The set->strs_data might have reallocated and if 's' pointed
* to an internal string within the old buffer, then it became
* dangling and needs to be reconstructed before the copy. */
if (old_data && old_data != (uintptr_t)set->strs_data &&
- old_s >= old_data && old_s < old_data + set->strs_data_len)
+ old_s >= old_data && old_s < old_data + old_data_len)
s = set->strs_data + (old_s - old_data);
memcpy(p, s, len);applied to bpf-next, thanks!
Quoted 7 lines
tools/lib/bpf/strset.c +7
-0+ s = set->strs_data + (old_s - old_data); + +memcpy (p, s, len); + +return len; +} +
[...]