On Fri, Oct 30, 2020 at 5:08 AM Kevin Sheldrake <Kevin.Sheldrake@xxxxxxxxxxxxx> wrote: > > As discussed, bpf_perf_event_output() takes a u64 for the sample size parameter but the perf ring buffer uses a u16 internally. This results in overlapping samples where the total sample size (including header/padding) exceeds 64K, and prevents samples from being submitted when the total sample size == 64K. > > This patch adds a check to the verifier to force the total sample size to be less than 64K. I'm not convinced it is in the right place stylistically, but it does work. > This is the first patch I've submitted to this list so please forgive me if I'm doing this wrong, and let me know what I should have done. See [0] for some guidelines. I use git format-patch and git send-email for my patch workflow. And please make sure your email client/editor wraps the lines, it's hard to reply if the entire paragraph is one long line. [0] https://kernelnewbies.org/FirstKernelPatch >Also I don't know what the size reduction of -24 relates to (it doesn't match any header struct I've found) but it was found through experimentation. So -24 should have been a clue that something fishy is going on. Look at perf_prepare_sample() in kernel/events/core.c. header->size (which is u16) contains the entire size of the data in the perf event. This includes raw data that you send with bpf_perf_event_output(), but it can also have tons of other stuff (e.g., call stacks, LBR data, etc). What gets added to the perf sample depends on how the perf event was configured in the first place. And it happens automatically on each perf event output. So, all that means that there could be no reliable static check in the verifier which would prevent the corruption. It has to be checked by perf_prepare_sample() in runtime based on the actual size of the sample. We can do an extra check in verifier, but I wouldn't bother because it's never going to be 100% correct. > > Thanks > > Kevin Sheldrake > > diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h > index e83ef6f..0941731 100644 > --- a/include/linux/bpf_verifier.h > +++ b/include/linux/bpf_verifier.h > @@ -18,6 +18,13 @@ > */ > #define BPF_MAX_VAR_SIZ (1 << 29) > > +/* Maximum variable size permitted for size param to bpf_perf_event_output(). > + * This ensures the samples sent into the perf ring buffer do not overflow the > + * size parameter in the perf event header. > + */ > +#define BPF_PERF_RAW_SIZ_BITS sizeof(((struct perf_event_header *)0)->size) > +#define BPF_MAX_PERF_SAMP_SIZ ((1 << (BPF_PERF_RAW_SIZ_BITS * 8)) - 24) > + [...]