Skip to content

Commit a299f43

Browse files
danobikernel-patches-bot
authored andcommitted
lib/strncpy_from_user.c: Don't overcopy bytes after NUL terminator
do_strncpy_from_user() may copy some extra bytes after the NUL terminator into the destination buffer. This usually does not matter for normal string operations. However, when BPF programs key BPF maps with strings, this matters a lot. A BPF program may read strings from user memory by calling the bpf_probe_read_user_str() helper which eventually calls do_strncpy_from_user(). The program can then key a map with the resulting string. BPF map keys are fixed-width and string-agnostic, meaning that map keys are treated as a set of bytes. The issue is when do_strncpy_from_user() overcopies bytes after the NUL terminator, it can result in seemingly identical strings occupying multiple slots in a BPF map. This behavior is subtle and totally unexpected by the user. This commit uses the proper word-at-a-time APIs to avoid overcopying. Fixes: 6ae08ae ("bpf: Add probe_read_{user, kernel} and probe_read_{user, kernel}_str helpers") Signed-off-by: Daniel Xu <[email protected]>
1 parent 51c522b commit a299f43

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

lib/strncpy_from_user.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,21 @@ static inline long do_strncpy_from_user(char *dst, const char __user *src,
3535
goto byte_at_a_time;
3636

3737
while (max >= sizeof(unsigned long)) {
38-
unsigned long c, data;
38+
unsigned long c, data, mask;
3939

4040
/* Fall back to byte-at-a-time if we get a page fault */
4141
unsafe_get_user(c, (unsigned long __user *)(src+res), byte_at_a_time);
4242

43-
*(unsigned long *)(dst+res) = c;
4443
if (has_zero(c, &data, &constants)) {
4544
data = prep_zero_mask(c, data, &constants);
4645
data = create_zero_mask(data);
46+
mask = zero_bytemask(data);
47+
*(unsigned long *)(dst+res) = c & mask;
4748
return res + find_zero(data);
4849
}
50+
51+
*(unsigned long *)(dst+res) = c;
52+
4953
res += sizeof(unsigned long);
5054
max -= sizeof(unsigned long);
5155
}

0 commit comments

Comments
 (0)