Skip to content

perf: Harden perf.data parsing against crafted/corrupted files

Arnaldo Carvalho de Melo linux-perf-users lkml 1 version In review

Get series with b4
b4 am [email protected]

Versions newest first

  1. v1 Latest28 patches 3 repliesIn review

Patches in v1 No applies recorded yet

#Subject and filesSizeRepliesApplied
1/28perf session: Add minimum event size validation tabletools/perf/util/session.c+121 -01 reply
2/28perf tools: Fix event_contains() macro to verify full field extenttools/lib/perf/include/perf/event.h tools/perf/util/arm-spe.c tools/perf/util/cs-etm.c +2 more+7 -50 replies
3/28perf zstd: Fix compression error path in zstd_compress_stream_to_records()tools/perf/util/zstd.c+13 -20 replies
4/28perf zstd: Fix multi-iteration decompression and error handlingtools/perf/util/zstd.c+16 -40 replies
5/28perf session: Fix PERF_RECORD_READ swap and dump for variable-length eventstools/perf/util/session.c+43 -180 replies
6/28perf session: Align auxtrace_info priv size before byte-swappingtools/perf/util/session.c+11 -30 replies
7/28perf session: Add validated swap infrastructure with null-termination checkstools/perf/util/session.c+323 -880 replies
8/28perf session: Use bounded copy for PERF_RECORD_TIME_CONVtools/perf/util/session.c+8 -10 replies
9/28perf session: Validate HEADER_ATTR alignment and attr.size before swappingtools/perf/tests/parse-no-sample-id-all.c tools/perf/util/header.c tools/perf/util/session.c +1 more+149 -90 replies
10/28perf session: Validate nr fields against event size on both swap and common pathstools/perf/util/session.c+224 -190 replies
11/28perf header: Byte-swap build ID event pid and bounds check section entriestools/perf/util/header.c tools/perf/util/session.c+61 -50 replies
12/28perf cpumap: Reject RANGE_CPUS with start_cpu > end_cputools/perf/util/cpumap.c+19 -30 replies
13/28perf auxtrace: Harden auxtrace_error event handlingtools/perf/util/auxtrace.c tools/perf/util/scripting-engines/trace-event-python.c tools/perf/util/session.c+61 -90 replies
14/28perf session: Add byte-swap and bounds check for PERF_RECORD_BPF_METADATA eventstools/perf/util/session.c+82 -10 replies
15/28perf header: Validate null-termination in PERF_RECORD_EVENT_UPDATE string fieldstools/perf/util/header.c tools/perf/util/session.c+216 -90 replies
16/28perf tools: Bounds check perf_event_attr fields against attr.size before printingtools/perf/trace/beauty/perf_event_open.c tools/perf/util/perf_event_attr_fprintf.c+109 -500 replies
17/28perf header: Propagate feature section processing errorstools/perf/util/header.c+39 -130 replies
18/28perf header: Validate f_attr.ids section before use in perf_session__read_header()tools/perf/util/header.c+77 -10 replies
19/28perf header: Validate feature section size and add read path bounds checkingtools/perf/util/header.c+53 -90 replies
20/28perf header: Sanity check HEADER_EVENT_DESC attr.size before swaptools/perf/util/header.c+49 -10 replies
21/28perf header: Validate bitmap size before allocating in do_read_bitmap()tools/perf/util/header.c+26 -50 replies
22/28perf session: Add byte-swap for PERF_RECORD_COMPRESSED2 eventstools/perf/util/session.c+9 -00 replies
23/28perf tools: Harden compressed event processingtools/perf/util/header.c tools/perf/util/tool.c+54 -10 replies
24/28perf session: Check for decompression buffer size overflowtools/perf/util/tool.c+13 -00 replies
25/28perf session: Bound nr_cpus_avail and validate sample CPUtools/perf/builtin-timechart.c tools/perf/util/header.c tools/perf/util/session.c+118 -20 replies
26/28perf timechart: Bounds check cpu_id and fix topology_map allocationtools/perf/builtin-timechart.c tools/perf/util/svghelper.c+104 -172 replies
27/28perf kwork: Bounds check work->cpu before indexing cpus_runtime[]tools/perf/builtin-kwork.c tools/perf/util/kwork.h+44 -60 replies
28/28perf test: Add truncated perf.data robustness testtools/perf/tests/shell/data_validation.sh+59 -00 replies

Reviews trailers per patch

No Reviewed-by, Acked-by or Tested-by trailers for v1 yet.

Read the v1 thread

Cover letter [PATCH 00/28] perf: Harden perf.data parsing against crafted/corrupted files

From: Arnaldo Carvalho de Melo <[email protected]>

Hi,

Here is a series experimenting with AI assistance, I did several
experiments that resulted in improvements to sashiko: a response cache, support for IPv6, ways to better communicate agents, etc.

Please take a look, I took more time than I expected to submit
this, and I'm not sure it is in the right shape, but at some point we need to just submit to get things going.

- Arnaldo

AI-assisted development notice
==============================

This series was developed with AI assistance (Claude, tagged with Assisted-by) and reviewed iteratively by sashiko, an AI code reviewer (tagged with Reported-by for issues it found). This is a first attempt at using AI tools to help improve the perf tools from a maintainer's perspective, and the workflow is still being refined.

The human (Arnaldo) read every diff, verified every fix, ran perf test at multiple points in the series, and built with both gcc and clang. Every design decision, architectural choice, and commit message was reviewed and approved by the maintainer. The AI helped with exploration, code generation, and iterative review analysis, but the Signed-off-by represents the maintainer's judgment that the code is correct and appropriate for upstream.

That said, this is new territory. The series may have issues that a more traditional development process would have caught differently, or patterns that experienced reviewers find unusual. Constructive feedback on both the code and the process is welcome.

What this series does
=====================

Defense-in-depth validation for perf.data file parsing. A crafted or corrupted perf.data file can currently cause out-of-bounds reads/writes, infinite loops, heap overflows, and segfaults in perf report, perf script, perf inject, perf timechart, and perf kwork.

The series adds:

- A per-event-type minimum size table, enforced before swap and processing on both native and cross-endian paths.
- Swap handler return values (void → int) so handlers can propagate errors instead of silently corrupting adjacent memory.
- Bounds checking for string fields (null-termination), array counts (nr vs payload size), feature section sizes (vs file size), and CPU indices (vs nr_cpus_avail / array allocation).
- ABI0 handling for perf_event_attr.size == 0 across all code paths (swap, native, synthesize, read_event_desc), with consistent behavior regardless of file endianness.
- Backtrace ownership transfer in timechart (const char ** pattern) to fix a pre-existing memory leak.
- A shell test that truncates perf.data at various offsets and verifies perf report doesn't crash.

Design decisions reviewers may question
=======================================

1. Why not copy events to local buffers?

Native-endian files are MAP_SHARED+PROT_READ. Copying each event would eliminate TOCTOU but adds overhead for the common case. Instead, we validate once and accept the theoretical TOCTOU risk. A follow-up could switch to MAP_PRIVATE for both paths — zero overhead when no writes occur (COW is lazy).

2. Why warn+clamp instead of abort on invalid CPU?

Synthesized events (MMAP, COMM) lack sample_id_all data, so evsel__parse_sample reads garbage from the event payload. Aborting would kill perf report on perfectly normal perf.data files. Clamping to 0 protects downstream array indexing. The (u32)-1 sentinel is preserved for perf script and perf inject.

3. Why per-handler nr validation AND a central min_size table?

The min_size table catches undersized events before the swap handler runs. But variable-length events (namespaces, thread_map, cpu_map, stat_config) have array counts that must be validated against the payload — that's per-handler because each layout differs.

4. Why not validate on the native path by clamping in place?

Native-endian events are on a read-only mmap. Writing to them would SIGSEGV. The swap path uses MAP_PRIVATE and can clamp in place. The native path must skip or reject instead.

5. Why read attr.size into a local variable?

The event may be on a shared mmap. Re-reading could yield a different value if another process modifies the file. Reading once eliminates this class of concern.

FIXME items left for follow-up
==============================

- perf.data should record the recording system's page size. Currently comp_mmap_len validation assumes 4K alignment.

- Block device input should be rejected or handled explicitly. All file-size validation is skipped for non-regular files.

- MAP_PRIVATE for both native and swap paths would eliminate ABI0 write-back workarounds and reduce TOCTOU surface.

Pre-existing bugs fixed opportunistically
==========================================

- event_contains() macro off-by-one (checked start, not full extent)
- zstd_decompress_stream multi-iteration output.pos bug
- zstd_compress_stream_to_records: broken memcpy fallback
- PERF_RECORD_SWITCH sample_id_all offset wrong for non-CPU_WIDE
- cpu_map__from_range any_cpu used as count instead of boolean
- cpu_map__from_mask double-fetch heap overflow
- kwork cpus_runtime BUG_ON with signed comparison
- perf_header__getbuffer64 EOF without errno
- timechart backtrace memory leak
- read_event_desc ABI0 sentinel corruption

Testing
=======

- perf test at baseline and at patches 1, 7, 10, 16, 20, 25, 27 with 300s timeout — no regressions detected.
- Build with both gcc and clang at every patch.
- checkpatch.pl on all 28 patches.
- 34 sashiko review rounds, all genuine findings addressed.
- Patch 28 adds a truncated perf.data test that exercises the hardening code.

Arnaldo Carvalho de Melo (28):
perf session: Add minimum event size validation table
perf tools: Fix event_contains() macro to verify full field extent perf zstd: Fix compression error path in
zstd_compress_stream_to_records()
perf zstd: Fix multi-iteration decompression and error handling perf session: Fix PERF_RECORD_READ swap and dump for variable-length
events
perf session: Align auxtrace_info priv size before byte-swapping perf session: Add validated swap infrastructure with null-termination
checks
perf session: Use bounded copy for PERF_RECORD_TIME_CONV perf session: Validate HEADER_ATTR alignment and attr.size before
swapping
perf session: Validate nr fields against event size on both swap and
common paths
perf header: Byte-swap build ID event pid and bounds check section
entries
perf cpumap: Reject RANGE_CPUS with start_cpu > end_cpu perf auxtrace: Harden auxtrace_error event handling
perf session: Add byte-swap and bounds check for
PERF_RECORD_BPF_METADATA events
perf header: Validate null-termination in PERF_RECORD_EVENT_UPDATE
string fields
perf tools: Bounds check perf_event_attr fields against attr.size
before printing
perf header: Propagate feature section processing errors perf header: Validate f_attr.ids section before use in
perf_session__read_header()
perf header: Validate feature section size and add read path bounds
checking
perf header: Sanity check HEADER_EVENT_DESC attr.size before swap perf header: Validate bitmap size before allocating in
do_read_bitmap()
perf session: Add byte-swap for PERF_RECORD_COMPRESSED2 events perf tools: Harden compressed event processing
perf session: Check for decompression buffer size overflow perf session: Bound nr_cpus_avail and validate sample CPU perf timechart: Bounds check cpu_id and fix topology_map allocation perf kwork: Bounds check work->cpu before indexing cpus_runtime[] perf test: Add truncated perf.data robustness test

 tools/lib/perf/include/perf/event.h           |    4 +-
 tools/perf/builtin-kwork.c                    |   49 +-
 tools/perf/builtin-timechart.c                |  117 +-
 tools/perf/tests/parse-no-sample-id-all.c     |    6 +
 tools/perf/tests/shell/data_validation.sh     |   59 +
 tools/perf/trace/beauty/perf_event_open.c     |   19 +-
 tools/perf/util/arm-spe.c                     |    2 +-
 tools/perf/util/auxtrace.c                    |   24 +-
 tools/perf/util/cpumap.c                      |   22 +-
 tools/perf/util/cs-etm.c                      |    2 +-
 tools/perf/util/header.c                      |  601 ++++++++-
 tools/perf/util/jitdump.c                     |    2 +-
 tools/perf/util/kwork.h                       |    1 +
 tools/perf/util/perf_event_attr_fprintf.c     |  140 +-
 .../scripting-engines/trace-event-python.c    |   28 +-
 tools/perf/util/session.c                     | 1154 +++++++++++++++--
 tools/perf/util/svghelper.c                   |    6 +-
 tools/perf/util/synthetic-events.c            |   25 +-
 tools/perf/util/tool.c                        |   51 +-
 tools/perf/util/tsc.c                         |    2 +-
 tools/perf/util/zstd.c                        |   35 +-
 21 files changed, 2088 insertions(+), 261 deletions(-)
 create mode 100755 tools/perf/tests/shell/data_validation.sh
Signature · 1 line
2.54.0