From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wr1-f41.google.com (mail-wr1-f41.google.com [209.85.221.41]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 960A42EA483 for ; Wed, 13 Aug 2025 13:38:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.41 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092323; cv=none; b=MerCEZJjT0NHTkX5Tq9PB63qXFwoitqqDIJuTgXaaO4+stV8cbiTL/B9NJr2ugawAhCVuf7krtXx77lWcXatTXIV8AI8Zg2wKgw8b5rtKQ/qBh0DT7tDLbHMmSnUl9S5vG8pLuFZn1ZfeUrdcDbG3i2hKFztzeJ4IQJswvPEWVw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092323; c=relaxed/simple; bh=JQkfk7058DpeupZ5iLpC21qDgS8vcgz+bZhgajNmMTA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dInJB9DV2IaeJ7+q2LTOg112X4i1SrlokYHCg1Dtg75g5u/t9bUSETovMgd/1zvCPwBzXzxt5G6S/gO1S+CXisKtbpQyy+eeVhCMqWnBWIzgTb6rI3l/0YQaUNHjmZBQgCSykM1CkjTtc//C/DIkSAwE9ktPGzTpWFmx3Suj+5U= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=ab/9eGle; arc=none smtp.client-ip=209.85.221.41 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="ab/9eGle" Received: by mail-wr1-f41.google.com with SMTP id ffacd0b85a97d-3b914186705so1062283f8f.0 for ; Wed, 13 Aug 2025 06:38:41 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092320; x=1755697120; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=7I1CLCGLbU0y9mn/lwEJ1bdLkYwEZFUd6f7/dKgAqBc=; b=ab/9eGle7QRrn0xj7w49h7I5BmOQKgAxEetjCQVYR300pxDAnpN5jI5P//kz4IXCqz WBw1ROKNDj7Vm+EB2gusSWwpOoLb+u2NABsMvfDRczVyJlgU6KIXHFN8rPRxu9R3sIT5 9c0UAcuL0GE1U8ZpcUBnWZngQiOk0tEd1DlzgH3UGs9k+dTXFjSKzU5oEoiv8ipErWm8 4Guz9w8NTbUBSYb7dwJRypWTBQTAW3Zg8bMWxGIsOkkdb4b6Q/9jFqfRMdJID7Hvthcu IHXlAOm78nfpDYuLi7U75NxlUckWEs/6aYGPe5bybRieRvTtzPDrGuv394+2zVoWqASM ErEg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092320; x=1755697120; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=7I1CLCGLbU0y9mn/lwEJ1bdLkYwEZFUd6f7/dKgAqBc=; b=JqtinZHQ/cpgIFvq1R4fOcYQEO/SjgF1np+pIDMAk/WJjHdFW7YISF10GQemH2T85c tO+J5HtfG+PXJQeWrwNL4lTeEodKl12Q3mIrdzh1o0kxooMDZpbVufYiOkhuLw0noH02 cUBHIA6X8vRoKQzSrJdxaXTq1uJi1ZJLmeCwciL8FR7MStLnRJpnsRuC9wzoOnlXG2sv 4G+LdEITIkIyNiesRCVNlzD8EANeGZx08sn46JX2APZj3cqv33vYoxiFRhC2j+IO1Bum 0cfn7Bn/aqYTdX0oWd6PM8g7k00cs7jlBivf+gJSKz7KPOpfp8obiuoJlc2oh2nRXfg1 1dwg== X-Forwarded-Encrypted: i=1; AJvYcCWl6Wi5KT7KulLdfuC/IwBmmv8CBwbP5QVqAbQrxhwhoTnr6wlv4YG+3G+xVZJztAh15yUD0mmpCMs7GCY=@vger.kernel.org X-Gm-Message-State: AOJu0Yxo4wLVTHh6GlETDZx0nYe5aNIROFGcI8ypWvK23kDG+PFojiGP NO+/CF2/Ucp/CI0R7SDOgqhUCC4YKrRmBVdzHMnc9Gbub73243xBBuVl X-Gm-Gg: ASbGncsQNZp08bL7roBEUHcxgCj000TByEGi1Xo2GwmxEuGVGFM2aQRIV4fUy8Ngu8C d/psdLmXBF9Q2+l0uLMKW2eKWKF0VS/SHXSWEABENfMv0Nj2D1o9/cGKwM/AKlEdYL0tzaQG6la lvxDgoSsh7FDma7nFBjA9bbnZCsTjrj4Lfm8gC0aRO9hIbQ8dBql3ZX0DPfujdV/qNQq32ZP0Fp wTemuWTAnFMsPhLdrDjGx+rxNsC/LevIomhoKvWlNhjjYsxwtR4JqMh0yaon85t3yZdsmLCmDBA lfYuaN8xXxIjM9lcVZdI4s9G1uisemk/HQs4B1wWHskfT70Nq7BSixff8n9aKdubYU2Eqd/NMl+ RIjb6QybJtMn0jLF3kHidkpHqPUrrQXoX7UKr9Pfio1EcA6nONfLWeVUIgUqLz/25cbZbPQSwVv L5O0eaYxpvYhHppm6SUeXhQhtHQg== X-Google-Smtp-Source: AGHT+IHZNOhAgTvsuvPk892oDXRewzcTY9/3o1skRWreIGXIT2NRj0SynSZXlXoBlZtHMuIDZekDXA== X-Received: by 2002:a05:6000:258a:b0:3b7:974d:5359 with SMTP id ffacd0b85a97d-3b917eacf60mr2328459f8f.32.1755092319463; Wed, 13 Aug 2025 06:38:39 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:39 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 1/6] mm/kasan: implement kasan_poison_range Date: Wed, 13 Aug 2025 13:38:07 +0000 Message-ID: <20250813133812.926145-2-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Introduce a new helper function, kasan_poison_range(), to encapsulate the logic for poisoning an arbitrary memory range of a given size, and expose it publically in . This is a preparatory change for the upcoming KFuzzTest patches, which requires the ability to poison the inter-region padding in its input buffers. No functional change to any other subsystem is intended by this commit. Signed-off-by: Ethan Graham --- include/linux/kasan.h | 16 ++++++++++++++++ mm/kasan/shadow.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/include/linux/kasan.h b/include/linux/kasan.h index 890011071f2b..09baeb6c9f4d 100644 --- a/include/linux/kasan.h +++ b/include/linux/kasan.h @@ -102,6 +102,21 @@ static inline bool kasan_has_integrated_init(void) } =20 #ifdef CONFIG_KASAN + +/** + * kasan_poison_range - poison the memory range [start, start + size) + * + * The exact behavior is subject to alignment with KASAN_GRANULE_SIZE, def= ined + * in . + * + * - If @start is unaligned, the initial partial granule at the beginning + * of the range is only poisoned if CONFIG_KASAN_GENERIC is enabled. + * - The poisoning of the range only extends up to the last full granule b= efore + * the end of the range. Any remaining bytes in a final partial granule are + * ignored. + */ +void kasan_poison_range(const void *start, size_t size); + void __kasan_unpoison_range(const void *addr, size_t size); static __always_inline void kasan_unpoison_range(const void *addr, size_t = size) { @@ -402,6 +417,7 @@ static __always_inline bool kasan_check_byte(const void= *addr) =20 #else /* CONFIG_KASAN */ =20 +static inline void kasan_poison_range(const void *start, size_t size) {} static inline void kasan_unpoison_range(const void *address, size_t size) = {} static inline void kasan_poison_pages(struct page *page, unsigned int orde= r, bool init) {} diff --git a/mm/kasan/shadow.c b/mm/kasan/shadow.c index d2c70cd2afb1..a1b6bfb35f07 100644 --- a/mm/kasan/shadow.c +++ b/mm/kasan/shadow.c @@ -147,6 +147,37 @@ void kasan_poison(const void *addr, size_t size, u8 va= lue, bool init) } EXPORT_SYMBOL_GPL(kasan_poison); =20 +void kasan_poison_range(const void *start, size_t size) +{ + void *end =3D (char *)start + size; + uintptr_t start_addr =3D (uintptr_t)start; + uintptr_t head_granule_start; + uintptr_t poison_body_start; + uintptr_t poison_body_end; + size_t head_prefix_size; + uintptr_t end_addr; + + end_addr =3D ALIGN_DOWN((uintptr_t)end, KASAN_GRANULE_SIZE); + if (start_addr >=3D end_addr) + return; + + head_granule_start =3D ALIGN_DOWN(start_addr, KASAN_GRANULE_SIZE); + head_prefix_size =3D start_addr - head_granule_start; + + if (IS_ENABLED(CONFIG_KASAN_GENERIC) && head_prefix_size > 0) + kasan_poison_last_granule((void *)head_granule_start, + head_prefix_size); + + poison_body_start =3D ALIGN(start_addr, KASAN_GRANULE_SIZE); + poison_body_end =3D ALIGN_DOWN(end_addr, KASAN_GRANULE_SIZE); + + if (poison_body_start < poison_body_end) + kasan_poison((void *)poison_body_start, + poison_body_end - poison_body_start, + KASAN_SLAB_REDZONE, false); +} +EXPORT_SYMBOL(kasan_poison_range); + #ifdef CONFIG_KASAN_GENERIC void kasan_poison_last_granule(const void *addr, size_t size) { --=20 2.51.0.rc0.205.g4a044479a3-goog From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wr1-f47.google.com (mail-wr1-f47.google.com [209.85.221.47]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9EB5B2EA499 for ; Wed, 13 Aug 2025 13:38:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092325; cv=none; b=KTehWVh2mm+HeiHfcLKdW86K8nJF6FYh85Ir+/y6X5IWVOiTn5S2cKTHJ2R2q8QEmDZAVPPvQV8HokreNC23N3L7W81Qhda//C7rIVmjfQnIADxTjMVmX3S8HkYOmhgKFumMQ8ft8E/O2eUpAdu9vH+rzJYzIr0eNgNOkJYlJlk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092325; c=relaxed/simple; bh=nzlCCGRJX9Ej/NXqDlQxavg1N5HrG4FxUQ2wdNzxwT0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=D+sqc3e3eNqd4WUQerA4i4YqT42mjE7lSJa097Am9oHQcZ4eMI6kKcSeYa3Fns5fF0XHFgtx05dKUPoqD6UPpPnnirJkDp5w29Pfz/5H6grgv/zzLpOplv+4JYh8JygrO55G2ibgxEUvCiIF0b7gBua173fo4QRJmLQCz/qWvU4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=RB79V1XF; arc=none smtp.client-ip=209.85.221.47 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="RB79V1XF" Received: by mail-wr1-f47.google.com with SMTP id ffacd0b85a97d-3b792b0b829so6613105f8f.3 for ; Wed, 13 Aug 2025 06:38:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092321; x=1755697121; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=JExl73RPYAos6cnZfl//XMbBahCTNDsylfHPobCls2o=; b=RB79V1XF0trOQ36EKIFszN5KYfZdaRESYF0XnaWoJevwLJPgduk/yZt+csctMySOav yHgnyhqRpUN3G/piLQFVjgrNmxykkEQXSXkHL6ypbOD2SWpo6i7+1fLJSZZM1a5ZLQT8 AWka0Gzmkr3N5T4WZQWJC6kqhGECJuxmath0Cxr8Ogd3DQvjQbOFbydDUlKgz6ohQZVz dkKmGwBWuO3f5vLwN5yTwJmcoZtgirc1qmB/BlYwSKcpgDFxSRDrfmjyGmOEuyPsKWGe XM8f2IDsjR4X/RaClWRZ+ycnRGMsRrRIYBvM4Ppqn+d/g57Jj19cmBB+L+IMukdg2i3Q FD0A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092321; x=1755697121; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=JExl73RPYAos6cnZfl//XMbBahCTNDsylfHPobCls2o=; b=KBa0rv0APA90o1WRmKBYBMyQy6c5UaUlveIJk8niNaWq9jhndpvxwFEsQL9uBrDAcv vHgmErXO8rk1TeyOGPE0XqiN6axo66t2EHdt5OQF9k8tygqET9tV1GlZdDo/FuGcAPIE +cFwsR9kgIXtMCjPVNmYuD/Y6jBOF5vA7XLHg/1tCOOsK1dIirx5E9TqRRPFRvqnBv8S 8+yjYPAGhp5VHN+p/dsrqM0waXxJwlxW6QUOMXppFmiysA31ifKSMF6yod61bLQw3/Mi 06aUtGzOwM3L3u9SegupfYwv+jXwRpaw7DSYBzZvdvTEtyStJebpCwy2BQfg2KqJfC9f CpCw== X-Forwarded-Encrypted: i=1; AJvYcCX5eq4vl09vCGlV2srhGL8osaDIme+LF8n9lXjkKKdR4naUYfQobuekeJ8WpoD+okQQsntA97nMKWRcmXM=@vger.kernel.org X-Gm-Message-State: AOJu0YzntfWOdMq8/VnlZPC7RfJUTOJ6QoKXFPP9nvxBywpa3xRUrlfy 2YC8PqS7oG8irCCsZdeMHSnl+lQeN+pBoBwmasgzxdnkNNWhLun7lE2/ X-Gm-Gg: ASbGncs9dQ923WQRE+jETp/yZy2cxbvlPtL0Uplylpslk3ytU5mRCWkndVBGpQn7a93 NvDxDgengMpFqcR4jHKJuZmVIDqI6soAamIxb9B/MvV2rNZjN+J7ULeqIFdqD/GEvEfRxvzVc1K EIL3/+v/HSf89EFS9aqimS+ig+xR+Yatr4z17KscrtXw0zzp4B2/ogK9ib8VBHctXj5PiUwjjhz lxLSYO6/SI2xVC6xXfQ+htxdqxYXeJJe6JjiMCSnRFVnDWJtdXe31LHek4jKs7/dgvIbvn4Q5Am b6eeFwmAsvBdtG35u6u89btIZDpbcMCyEbkkwB0AxzKM6FKNsAM1R0es7slQGELHITgXeY7qoeO AZx5LY++tUNouD6VE0r1EGfxjBMXvvp1/1mXXn2JtgC19M4EQyx0wpctCcT68gq4zsiY8cLN5ue Q5dvkuj48ObvGRzzOmpDT/eDF94A== X-Google-Smtp-Source: AGHT+IGJwkKDbGpMWQMiOKMltg00rXXiYABXq4gACAbBRvEZ1E2AKRdOicYy65GkIAL55+xxn3c6zw== X-Received: by 2002:a05:6000:2087:b0:3b7:9546:a0e8 with SMTP id ffacd0b85a97d-3b917f15122mr2306669f8f.41.1755092320576; Wed, 13 Aug 2025 06:38:40 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.39 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:39 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 2/6] kfuzztest: add user-facing API and data structures Date: Wed, 13 Aug 2025 13:38:08 +0000 Message-ID: <20250813133812.926145-3-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Add the foundational user-facing components for the KFuzzTest framework. This includes the main API header , the Kconfig option to enable the feature, and the required linker script changes which introduce three new ELF sections in vmlinux. Note that KFuzzTest is intended strictly for debug builds only, and should never be enabled in a production build. The fact that it exposes internal kernel functions and state directly to userspace may constitute a serious security vulnerability if used for any reason other than testing. The header defines: - The FUZZ_TEST() macro for creating test targets. - The data structures required for the binary serialization format, which allows passing complex inputs from userspace. - The metadata structures for test targets, constraints and annotations, which are placed in dedicated ELF sections (.kfuzztest_*) for discovery. This patch only adds the public interface and build integration; no runtime logic is included. Signed-off-by: Ethan Graham --- arch/x86/kernel/vmlinux.lds.S | 22 ++ include/linux/kfuzztest.h | 508 ++++++++++++++++++++++++++++++++++ lib/Kconfig.debug | 1 + lib/kfuzztest/Kconfig | 20 ++ 4 files changed, 551 insertions(+) create mode 100644 include/linux/kfuzztest.h create mode 100644 lib/kfuzztest/Kconfig diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S index 4fa0be732af1..484e3e1ffb9f 100644 --- a/arch/x86/kernel/vmlinux.lds.S +++ b/arch/x86/kernel/vmlinux.lds.S @@ -112,6 +112,26 @@ ASSERT(__relocate_kernel_end - __relocate_kernel_start= <=3D KEXEC_CONTROL_CODE_MAX #else #define KEXEC_RELOCATE_KERNEL #endif + +#ifdef CONFIG_KFUZZTEST +#define KFUZZTEST_TABLE \ + . =3D ALIGN(PAGE_SIZE); \ + __kfuzztest_targets_start =3D .; \ + KEEP(*(.kfuzztest_target)); \ + __kfuzztest_targets_end =3D .; \ + . =3D ALIGN(PAGE_SIZE); \ + __kfuzztest_constraints_start =3D .; \ + KEEP(*(.kfuzztest_constraint)); \ + __kfuzztest_constraints_end =3D .; \ + . =3D ALIGN(PAGE_SIZE); \ + __kfuzztest_annotations_start =3D .; \ + KEEP(*(.kfuzztest_annotation)); \ + __kfuzztest_annotations_end =3D .; + +#else /* CONFIG_KFUZZTEST */ +#define KFUZZTEST_TABLE +#endif /* CONFIG_KFUZZTEST */ + PHDRS { text PT_LOAD FLAGS(5); /* R_E */ data PT_LOAD FLAGS(6); /* RW_ */ @@ -199,6 +219,8 @@ SECTIONS CONSTRUCTORS KEXEC_RELOCATE_KERNEL =20 + KFUZZTEST_TABLE + /* rarely changed data like cpu maps */ READ_MOSTLY_DATA(INTERNODE_CACHE_BYTES) =20 diff --git a/include/linux/kfuzztest.h b/include/linux/kfuzztest.h new file mode 100644 index 000000000000..11a647c1d925 --- /dev/null +++ b/include/linux/kfuzztest.h @@ -0,0 +1,508 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * The Kernel Fuzz Testing Framework (KFuzzTest) API for defining fuzz tar= gets + * for internal kernel functions. + * + * For more information please see Documentation/dev-tools/kfuzztest.rst. + * + * Copyright 2025 Google LLC + */ +#ifndef KFUZZTEST_H +#define KFUZZTEST_H + +#include +#include +#include + +#define KFUZZTEST_HEADER_MAGIC (0xBFACE) +#define KFUZZTEST_V0 (0) + +/** + * @brief The KFuzzTest Input Serialization Format + * + * KFuzzTest receives its input from userspace as a single binary blob. Th= is + * format allows for the serialization of complex, pointer-rich C structur= es + * into a flat buffer that can be safely passed into the kernel. This form= at + * requires only a single copy from userspace into a kenrel buffer, and no + * further kernel allocations. Pointers are patched internally using a "re= gion" + * system where each region corresponds to some pointed-to data. + * + * Regions should be padded to respect alignment constraints of their unde= rlying + * types, and should be followed by at least 8 bytes of padding. These pad= ded + * regions are poisoned by KFuzzTest to ensure that KASAN catches OOB acce= sses. + * + * The format consists of a prefix and three main components: + * 1. An 8-byte header: Contains KFUZZTEST_MAGIC in the first 4 bytes, and= the + * version number in the subsequent 4 bytes. This ensures backwards + * compatibility in the event of future format changes. + * 2. A reloc_region_array: Defines the memory layout of the target struct= ure + * by partitioning the payload into logical regions. Each logical region + * should contain the byte representation of the type that it represents, + * including any necessary padding. The region descriptors should be + * ordered by offset ascending. + * 3. A reloc_table: Provides "linking" instructions that tell the kernel = how + * to patch pointer fields to point to the correct regions. By design, + * the first region (index 0) is passed as input into a FUZZ_TEST. + * 4. A Payload: The raw binary data for the structure and its associated + * buffers. This should be aligned to the maximum alignment of all + * regions to satisfy alignment requirements of the input types, but this + * isn't checked by the parser. + * + * For a detailed specification of the binary layout see the full document= ation + * at: Documentation/dev-tools/kfuzztest.rst + */ + +/** + * struct reloc_region - single contiguous memory region in the payload + * + * @offset: The byte offset of this region from the start of the payload, = which + * should be aligned to the alignment requirements of the region's + * underlying type. + * @size: The size of this region in bytes. + */ +struct reloc_region { + uint32_t offset; + uint32_t size; +}; + +/** + * struct reloc_region_array - array of regions in an input + * @num_regions: The total number of regions defined. + * @regions: A flexible array of `num_regions` region descriptors. + */ +struct reloc_region_array { + uint32_t num_regions; + struct reloc_region regions[]; +}; + +/** + * struct reloc_entry - a single pointer to be patched in an input + * + * @region_id: The index of the region in the `reloc_region_array` that + * contains the pointer. + * @region_offset: The start offset of the pointer inside of the region. + * @value: contains the index of the pointee region, or KFUZZTEST_REGIONID= _NULL + * if the pointer is NULL. + */ +struct reloc_entry { + uint32_t region_id; + uint32_t region_offset; + uint32_t value; +}; + +/** + * struct reloc_entry - array of relocations required by an input + * + * @num_entries: the number of pointer relocations. + * @padding_size: the number of padded bytes between the last relocation in + * entries, and the start of the payload data. This should be at least + * 8 bytes, as it is used for poisoning. + * @entries: array of relocations. + */ +struct reloc_table { + uint32_t num_entries; + uint32_t padding_size; + struct reloc_entry entries[]; +}; + +/** + * kfuzztest_parse_and_relocate - validate and relocate a KFuzzTest input + * + * @input: A buffer containing the serialized input for a fuzz target. + * @input_size: the size in bytes of the @input buffer. + * @arg_ret: return pointer for the test case's input structure. + */ +int kfuzztest_parse_and_relocate(void *input, size_t input_size, void **ar= g_ret); + +/* + * Dump some information on the parsed headers and payload. Can be useful = for + * debugging inputs when writing an encoder for the KFuzzTest input format. + */ +__attribute__((unused)) static inline void kfuzztest_debug_header(struct r= eloc_region_array *regions, + struct reloc_table *rt, void *payload_start, + void *payload_end) +{ + uint32_t i; + + pr_info("regions: { num_regions =3D %u } @ %px", regions->num_regions, re= gions); + for (i =3D 0; i < regions->num_regions; i++) { + pr_info(" region_%u: { start: 0x%x, size: 0x%x }", i, regions->regions[= i].offset, + regions->regions[i].size); + } + + pr_info("reloc_table: { num_entries =3D %u, padding =3D %u } @ offset 0x%= lx", rt->num_entries, rt->padding_size, + (char *)rt - (char *)regions); + for (i =3D 0; i < rt->num_entries; i++) { + pr_info(" reloc_%u: { src: %u, offset: 0x%x, dst: %u }", i, rt->entries= [i].region_id, + rt->entries[i].region_offset, rt->entries[i].value); + } + + pr_info("payload: [0x%lx, 0x%lx)", (char *)payload_start - (char *)region= s, + (char *)payload_end - (char *)regions); +} + +struct kfuzztest_target { + const char *name; + const char *arg_type_name; + ssize_t (*write_input_cb)(struct file *filp, const char __user *buf, size= _t len, loff_t *off); +} __aligned(32); + +/** + * FUZZ_TEST - defines a KFuzzTest target + * + * @test_name: The unique identifier for the fuzz test, which is used to n= ame + * the debugfs entry, e.g., /sys/kernel/debug/kfuzztest/@test_name. + * @test_arg_type: The struct type that defines the inputs for the test. T= his + * must be the full struct type (e.g., "struct my_inputs"), not a typedef. + * + * Context: + * This macro is the primary entry point for the KFuzzTest framework. It + * generates all the necessary boilerplate for a fuzz test, including: + * - A static `struct kfuzztest_target` instance that is placed in a + * dedicated ELF section for discovery by userspace tools. + * - A `debugfs` write callback that handles receiving serialized data f= rom + * a fuzzer, parsing it, and "hydrating" it into a valid C struct. + * - A function stub where the developer places the test logic. + * + * User-Provided Logic: + * The developer must provide the body of the fuzz test logic within the c= urly + * braces following the macro invocation. Within this scope, the framework + * provides the following variables: + * + * - `arg`: A pointer of type `@test_arg_type *` to the fully hydrated inp= ut + * structure. All pointer fields within this struct have been relocated + * and are valid kernel pointers. This is the primary variable to use + * for accessing fuzzing inputs. + * + * - `regions`: A pointer of type `struct reloc_region_array *`. This is an + * advanced feature that allows access to the raw region metadata, which + * can be useful for checking the actual allocated size of a buffer via + * `KFUZZTEST_REGION_SIZE(n)`. + * + * Example Usage: + * + * // 1. The kernel function we want to fuzz. + * int process_data(const char *data, size_t len); + * + * // 2. Define a struct to hold all inputs for the function. + * struct process_data_inputs { + * const char *data; + * size_t len; + * }; + * + * // 3. Define the fuzz test using the FUZZ_TEST macro. + * FUZZ_TEST(process_data_fuzzer, struct process_data_inputs) + * { + * int ret; + * // Use KFUZZTEST_EXPECT_* to enforce preconditions. + * // The test will exit early if data is NULL. + * KFUZZTEST_EXPECT_NOT_NULL(process_data_inputs, data); + * + * // Use KFUZZTEST_ANNOTATE_* to provide hints to the fuzzer. + * // This links the 'len' field to the 'data' buffer. + * KFUZZTEST_ANNOTATE_LEN(process_data_inputs, len, data); + * + * // Call the function under test using the 'arg' variable. OOB memory + * // accesses will be caught by KASAN, but the user can also choose to + * // validate the return value and log any failures. + * ret =3D process_data(arg->data, arg->len); + * } + */ +#define FUZZ_TEST(test_name, test_arg_type) = \ + static ssize_t kfuzztest_write_cb_##test_name(struct file *filp, const ch= ar __user *buf, size_t len, \ + loff_t *off); \ + static void kfuzztest_logic_##test_name(test_arg_type *arg); = \ + const struct kfuzztest_target __fuzz_test__##test_name __section(".kfuzzt= est_target") __used =3D { \ + .name =3D #test_name, = \ + .arg_type_name =3D #test_arg_type, = \ + .write_input_cb =3D kfuzztest_write_cb_##test_name, = \ + }; = \ + static ssize_t kfuzztest_write_cb_##test_name(struct file *filp, const ch= ar __user *buf, size_t len, \ + loff_t *off) \ + { = \ + test_arg_type *arg; = \ + void *buffer; = \ + int ret; = \ + = \ + buffer =3D kmalloc(len, GFP_KERNEL); = \ + if (!buffer) = \ + return -ENOMEM; = \ + ret =3D simple_write_to_buffer(buffer, len, off, buf, len); = \ + if (ret < 0) = \ + goto out; = \ + ret =3D kfuzztest_parse_and_relocate(buffer, len, (void **)&arg); = \ + if (ret < 0) = \ + goto out; = \ + kfuzztest_logic_##test_name(arg); = \ + ret =3D len; = \ +out: = \ + kfree(buffer); = \ + return ret; = \ + } = \ + static void kfuzztest_logic_##test_name(test_arg_type *arg) + +enum kfuzztest_constraint_type { + EXPECT_EQ, + EXPECT_NE, + EXPECT_LT, + EXPECT_LE, + EXPECT_GT, + EXPECT_GE, + EXPECT_IN_RANGE, +}; + +/** + * struct kfuzztest_constraint - a metadata record for a domain constraint + * + * Domain constraints are rules about the input data that must be satisfie= d for + * a fuzz test to proceed. While they are enforced in the kernel with a ru= ntime + * check, they are primarily intended as a discoverable contract for users= pace + * fuzzers. + * + * Instances of this struct are generated by the KFUZZTEST_EXPECT_* macros + * and placed into the read-only ".kfuzztest_constraint" ELF section of the + * vmlinux binary. A fuzzer can parse this section to learn about the + * constraints and generate valid inputs more intelligently. + * + * For an example of how these constraints are used within a fuzz test, se= e the + * documentation for the FUZZ_TEST() macro. + * + * @input_type: The name of the input struct type, without the leading + * "struct ". + * @field_name: The name of the field within the struct that this constrai= nt + * applies to. + * @value1: The primary value used in the comparison (e.g., the upper + * bound for EXPECT_LE). + * @value2: The secondary value, used only for multi-value comparisons + * (e.g., the upper bound for EXPECT_IN_RANGE). + * @type: The type of the constraint. + */ +struct kfuzztest_constraint { + const char *input_type; + const char *field_name; + uintptr_t value1; + uintptr_t value2; + enum kfuzztest_constraint_type type; +} __aligned(64); + +#define __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val1, val2, tpe) = \ + static struct kfuzztest_constraint __constraint_##arg_type##_##field __se= ction(".kfuzztest_constraint") \ + __used =3D { = \ + .input_type =3D "struct " #arg_type, = \ + .field_name =3D #field, = \ + .value1 =3D (uintptr_t)val1, = \ + .value2 =3D (uintptr_t)val2, = \ + .type =3D tpe, = \ + } + +/** + * KFUZZTEST_EXPECT_EQ - constrain a field to be equal to a value + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable + * @val: a value of the same type as @arg_type.@field + */ +#define KFUZZTEST_EXPECT_EQ(arg_type, field, val) = \ + do { = \ + if (arg->field !=3D val) \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_EQ); \ + } while (0) + +/** + * KFUZZTEST_EXPECT_NE - constrain a field to be not equal to a value + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_NE(arg_type, field, val) = \ + do { = \ + if (arg->field =3D=3D val) = \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_NE); \ + } while (0) + +/** + * KFUZZTEST_EXPECT_LT - constrain a field to be less than a value + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_LT(arg_type, field, val) = \ + do { = \ + if (arg->field >=3D val) \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_LT); \ + } while (0) + +/** + * KFUZZTEST_EXPECT_LE - constrain a field to be less than or equal to a v= alue + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_LE(arg_type, field, val) = \ + do { = \ + if (arg->field > val) \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_LE); \ + } while (0) + +/** + * KFUZZTEST_EXPECT_GT - constrain a field to be greater than a value + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_GT(arg_type, field, val) = \ + do { = \ + if (arg->field <=3D val) \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_GT) \ + } while (0) + +/** + * KFUZZTEST_EXPECT_GE - constrain a field to be greater than or equal to = a value + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_GE(arg_type, field, val) = \ + do { = \ + if (arg->field < val) \ + return; \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, val, 0x0, EXPECT_GE)` \ + } while (0) + +/** + * KFUZZTEST_EXPECT_GE - constrain a pointer field to be non-NULL + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @val: a value of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_NOT_NULL(arg_type, field) KFUZZTEST_EXPECT_NE(arg= _type, field, NULL) + +/** + * KFUZZTEST_EXPECT_IN_RANGE - constrain a field to be within a range + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: some field that is comparable. + * @lower_bound: a lower bound of the same type as @arg_type.@field. + * @upper_bound: an upper bound of the same type as @arg_type.@field. + */ +#define KFUZZTEST_EXPECT_IN_RANGE(arg_type, field, lower_bound, upper_boun= d) \ + do { = \ + if (arg->field < lower_bound || arg->field > upper_bound) = \ + return; = \ + __KFUZZTEST_DEFINE_CONSTRAINT(arg_type, field, lower_bound, upper_bound,= EXPECT_IN_RANGE) \ + } while (0) + +/** + * Annotations express attributes about structure fields that can't be eas= ily + * or safely verified at runtime. They are intended as hints to the fuzzing + * engine to help it generate more semantically correct and effective inpu= ts. + * Unlike constraints, annotations do not add any runtime checks and do not + * cause a test to exit early. + * + * For example, a `char *` field could be a raw byte buffer or a C-style + * null-terminated string. A fuzzer that is aware of this distinction can = avoid + * creating inputs that would cause trivial, uninteresting crashes from re= ading + * past the end of a non-null-terminated buffer. + */ +enum kfuzztest_annotation_attribute : uint8_t { + ATTRIBUTE_LEN, + ATTRIBUTE_STRING, + ATTRIBUTE_ARRAY, +}; + +/** + * struct kfuzztest_annotation - a metadata record for a fuzzer hint + * + * This struct captures a single hint about a field in the input structure. + * Instances are generated by the KFUZZTEST_ANNOTATE_* macros and are plac= ed + * into the read-only ".kfuzztest_annotation" ELF section of the vmlinux b= inary. + * + * A userspace fuzzer can parse this section to understand the semantic + * relationships between fields (e.g., which field is a length for which + * buffer) and the expected format of the data (e.g., a null-terminated + * string). This allows the fuzzer to be much more intelligent during input + * generation and mutation. + * + * For an example of how annotations are used within a fuzz test, see the + * documentation for the FUZZ_TEST() macro. + * + * @input_type: The name of the input struct type. + * @field_name: The name of the field being annotated (e.g., the data + * buffer field). + * @linked_field_name: For annotations that link two fields (like + * ATTRIBUTE_LEN), this is the name of the related field (e.g., the + * length field). For others, this may be unused. + * @attrib: The type of the annotation hint. + */ +struct kfuzztest_annotation { + const char *input_type; + const char *field_name; + const char *linked_field_name; + enum kfuzztest_annotation_attribute attrib; +} __aligned(32); + +#define __KFUZZTEST_ANNOTATE(arg_type, field, linked_field, attribute) = \ + static struct kfuzztest_annotation __annotation_##arg_type##_##field __se= ction(".kfuzztest_annotation") \ + __used =3D { = \ + .input_type =3D "struct " #arg_type, = \ + .field_name =3D #field, = \ + .linked_field_name =3D #linked_field, = \ + .attrib =3D attribute, = \ + } + +/** + * KFUZZTEST_ANNOTATE_STRING - annotate a char* field as a C string + * + * We define a C string as a sequence of non-zero characters followed by e= xactly + * one null terminator. + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: the name of the field to annotate. + */ +#define KFUZZTEST_ANNOTATE_STRING(arg_type, field) __KFUZZTEST_ANNOTATE(ar= g_type, field, NULL, ATTRIBUTE_STRING) + +/** + * KFUZZTEST_ANNOTATE_ARRAY - annotate a pointer as an array + * + * We define an array as a contiguous memory region containing zero or more + * elements of the same type. + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: the name of the field to annotate. + */ +#define KFUZZTEST_ANNOTATE_ARRAY(arg_type, field) __KFUZZTEST_ANNOTATE(arg= _type, field, NULL, ATTRIBUTE_ARRAY) + +/** + * KFUZZTEST_ANNOTATE_LEN - annotate a field as the length of another + * + * This expresses the relationship `arg_type.field =3D=3D len(linked_field= )`, where + * `linked_field` is an array. + * + * @arg_type: name of the input structure, without the leading "struct ". + * @field: the name of the field to annotate. + * @linked_field: the name of an array field with length @field. + */ +#define KFUZZTEST_ANNOTATE_LEN(arg_type, field, linked_field) \ + __KFUZZTEST_ANNOTATE(arg_type, field, linked_field, ATTRIBUTE_LEN) + +#define KFUZZTEST_REGIONID_NULL U32_MAX + +/** + * The end of the input should be padded by at least this number of bytes = as + * it is poisoned to detect out of bounds accesses at the end of the last + * region. + */ +#define KFUZZTEST_POISON_SIZE 0x8 + +#endif /* KFUZZTEST_H */ diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index ebe33181b6e6..3542e94204c8 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -1947,6 +1947,7 @@ endmenu menu "Kernel Testing and Coverage" =20 source "lib/kunit/Kconfig" +source "lib/kfuzztest/Kconfig" =20 config NOTIFIER_ERROR_INJECTION tristate "Notifier error injection" diff --git a/lib/kfuzztest/Kconfig b/lib/kfuzztest/Kconfig new file mode 100644 index 000000000000..f9fb5abf8d27 --- /dev/null +++ b/lib/kfuzztest/Kconfig @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config KFUZZTEST + bool "KFuzzTest - enable support for internal fuzz targets" + depends on DEBUG_FS && DEBUG_KERNEL + help + Enables support for the kernel fuzz testing framework (KFuzzTest), an + interface for exposing internal kernel functions to a userspace fuzzing + engine. KFuzzTest targets are exposed via a debugfs interface that + accepts serialized userspace inputs, and is designed to make it easier + to fuzz deeply nested kernel code that is hard to reach from the system + call boundary. Using a simple macro-based API, developers can add a new + fuzz target with minimal boilerplate code. + + It is strongly recommended to also enable CONFIG_KASAN for byte-accurate + out-of-bounds detection, as KFuzzTest was designed with this in mind. It + is also recommended to enable CONFIG_KCOV for coverage guided fuzzing. + + WARNING: This exposes internal kernel functions directly to userspace + and must NEVER be enabled in production builds. --=20 2.51.0.rc0.205.g4a044479a3-goog From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wr1-f47.google.com (mail-wr1-f47.google.com [209.85.221.47]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9105E2EA739 for ; Wed, 13 Aug 2025 13:38:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092325; cv=none; b=B82o3lf7eK5iGIMg8OFohs64WqBORdJ/RrTR82FHXmfDw44r7O1HJLnK4lB4oazG8FLb1/ptpHhH6g+8x2+QLipZNLa65YXheNsp4O7AOIIraKbVHKyasm+njLml/wZri9H47PVnTQVLSMcPD830GjUAk+LPhD9EfxWkUMqavdo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092325; c=relaxed/simple; bh=WVMr1+sQbLm0NhlHOMNsq2uOefeZI8p0ST+TTTcPmeM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NymrF50c93benoumZwj251sPgDXa6owChqReJAB+DRAbh5aN52dgLcL17lFm8+Rpj/9SWMZOaXlxjHZzAx2PwLci6Nzk6L4diDBQVHrA/vZXxfRLZwu0KsAsK/pP8bsdBZZB87JAUViXgwTjsyyQFoqfG7JxuK87QKvkuqT30Lc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=N6WHttjp; arc=none smtp.client-ip=209.85.221.47 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="N6WHttjp" Received: by mail-wr1-f47.google.com with SMTP id ffacd0b85a97d-3b91325d79fso872264f8f.3 for ; Wed, 13 Aug 2025 06:38:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092322; x=1755697122; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=NqDz/RTemVf8hk/fnHnI91a5xRvLZSkfIpeLZw9SlZs=; b=N6WHttjp6c2d/shq/Iv5hNKwGDvL+ts3bOQLKb42HrUQzIta0AiW0UGbdLhKaRDTiv F99TghVXa0Sec1MdkCn2yqvEJeI7+v7YxJ/tMAyfUyI/jPIGI83GIdUDmmB134xD/nye tBbv/xSGrxeDpvg+K3fLVr2lgJ7QyjXsSNiKRSktX888F7Lc3xxlr3WbFCcHlcdgRUqC 4Qnnm0wACO+oicG7whOHEQn8YABls2FUMEqbQKDnF8I8HgIdlaYAQmhbCT3Y19aO2Jyi CwhIup0WEVS/HDSOdbk/GYshADzf/YjdXQujngfL8PM7nM4f6qNXO+opehQqk5OGT9H1 CMnw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092322; x=1755697122; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=NqDz/RTemVf8hk/fnHnI91a5xRvLZSkfIpeLZw9SlZs=; b=G6aMYZzwb4fWy6ZiJ9kNgOd31aHXgwtk9reLEo6kSlLHuemOoF0Uhgrkxu6h3mXjL0 ZhrUcIhyxojep+Mib2ke1p/aI+IdFfIWRmjrLWnNXW1avLh02tKiiYampnufR0wswcYv WMTZND3bTPvkmJ8ADBU25T6N5hhZpqEVhZU4O2WEe6GNIvi1zL60Kq6eVSGJCSxw1O2B TTa3GmMf18qKYZIY5WSRKEA2VnelWxOkuXj59V/4lygoEYro+UslNHNgQ5snRHxMeBGC M+6S5MdPwKF3HMFKbmaUKYzU0+QjqddslV1NlT+8CEh1YKoUqzyCvmkN4pWT2T04bZGF VRzQ== X-Forwarded-Encrypted: i=1; AJvYcCWQ4r5nN6iUrWXlYAQiiGan8ijKAy2teVIzJ/QMB8VgRuV3Skmz8RCO1pjpqVkkwkzdujTE86cyJMsWrCQ=@vger.kernel.org X-Gm-Message-State: AOJu0Yz+uMvnqH4BEDBhN3SVnVTfiGbJeLEviVD2kwHC3Z1/Il2r+1Mk JS0jvfuOUSjqF/JBsm8Lbaf0lQxD/V0KeNx8ZQ8dK98ETaqU5YXbXfYs X-Gm-Gg: ASbGncvuXPRnDpLUnVK36oDPjz6SadMF2qBgB6PmxGEIybF+xvVD414yhi3TQeOYIWw pmYDLKcoBU5RlvzLKZ4lRH77s5Fi4LHgLOjVAAGiHWo+1MTHBiSAy02kYHg6mvMZd6dwFQZSf56 upNvyyK1ju0qh/11diVv1k0bKS32PHnlIlFRkT5ZUYg2UOmXnqQw8z+PrsQXz1fJE+JED2O0k6B UmNTLR9j5giYDR5Omd2lJNTgvQs2udrw4hAwYzbk9xkPdYcM5ju7X4wneQXt5QXxjZLQrrVaoMp agZy/u5WTAsK8gzAZWV4iEIBa5U1qaixVKsOHyL1cU/y1vMH4xk878nnTgCHn+xQ3CG8AJU+u37 mlE1TExyc12xD9X/tAdTQeD5zkm6JQGsGEVdEv+lU3fjwVOGK8R8dxzptprig4G4JI3RFUaYrkl K37448L0UgdSTg2+E= X-Google-Smtp-Source: AGHT+IGKke6LjQNxg3psbIRPw8246iMbv8THZ+fYA644g5YUiVc5QrmNXJbLKniBxb8JhdUcLxhU0g== X-Received: by 2002:a05:6000:240b:b0:3b8:d08c:cde5 with SMTP id ffacd0b85a97d-3b917eb47ebmr2500162f8f.43.1755092321515; Wed, 13 Aug 2025 06:38:41 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.40 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:40 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 3/6] kfuzztest: implement core module and input processing Date: Wed, 13 Aug 2025 13:38:09 +0000 Message-ID: <20250813133812.926145-4-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Add the core runtime implementation for KFuzzTest. This includes the module initialization, and the logic for receiving and processing user-provided inputs through debugfs. On module load, the framework discovers all test targets by iterating over the .kfuzztest_target section, creating a corresponding debugfs directory with a write-only 'input' file for each of them. Writing to an 'input' file triggers the main fuzzing sequence: 1. The serialized input is copied from userspace into a kernel buffer. 2. The buffer is parsed to validate the region array and relocation table. 3. Pointers are patched based on the relocation entries, and in KASAN builds the inter-region padding is poisoned. 4. The resulting struct is passed to the user-defined test logic. Signed-off-by: Ethan Graham --- lib/Makefile | 2 + lib/kfuzztest/Makefile | 4 + lib/kfuzztest/main.c | 161 +++++++++++++++++++++++++++++++ lib/kfuzztest/parse.c | 208 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 375 insertions(+) create mode 100644 lib/kfuzztest/Makefile create mode 100644 lib/kfuzztest/main.c create mode 100644 lib/kfuzztest/parse.c diff --git a/lib/Makefile b/lib/Makefile index c38582f187dd..511c44ef4b19 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -354,6 +354,8 @@ obj-$(CONFIG_GENERIC_LIB_CMPDI2) +=3D cmpdi2.o obj-$(CONFIG_GENERIC_LIB_UCMPDI2) +=3D ucmpdi2.o obj-$(CONFIG_OBJAGG) +=3D objagg.o =20 +obj-$(CONFIG_KFUZZTEST) +=3D kfuzztest/ + # pldmfw library obj-$(CONFIG_PLDMFW) +=3D pldmfw/ =20 diff --git a/lib/kfuzztest/Makefile b/lib/kfuzztest/Makefile new file mode 100644 index 000000000000..142d16007eea --- /dev/null +++ b/lib/kfuzztest/Makefile @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_KFUZZTEST) +=3D kfuzztest.o +kfuzztest-objs :=3D main.o parse.o diff --git a/lib/kfuzztest/main.c b/lib/kfuzztest/main.c new file mode 100644 index 000000000000..fccda1319fb0 --- /dev/null +++ b/lib/kfuzztest/main.c @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KFuzzTest core module initialization and debugfs interface. + * + * Copyright 2025 Google LLC + */ +#include +#include +#include +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Ethan Graham "); +MODULE_DESCRIPTION("Kernel Fuzz Testing Framework (KFuzzTest)"); + +extern const struct kfuzztest_target __kfuzztest_targets_start[]; +extern const struct kfuzztest_target __kfuzztest_targets_end[]; + +/** + * struct kfuzztest_dentry - A container for a debugfs dentry and its fops. + * @dentry: Pointer to the created debugfs dentry. + * @fops: The file_operations struct associated with this dentry. + * + * This simplifies state management by keeping a file's dentry and its + * operations bundled together. + */ +struct kfuzztest_dentry { + struct dentry *dentry; + struct file_operations fops; +}; + +/** + * struct kfuzztest_debugfs_state - Per-test-case debugfs state. + * @test_dir: The top-level debugfs directory for a single test case, e.g., + * /sys/kernel/debug/kfuzztest//. + * @input_dentry: The state for the "input" file, which is write-only. + * + * Wraps all debugfs components created for a single test case. + */ +struct kfuzztest_debugfs_state { + struct dentry *target_dir; + struct kfuzztest_dentry input_dentry; +}; + +/** + * struct kfuzztest_simple_fuzzer_state - Global state for the KFTF module. + * @kfuzztest_dir: The root debugfs directory, /sys/kernel/debug/kfuzztest= /. + * @debugfs_state: A statically sized array holding the state for each + * registered test case. + */ +struct kfuzztest_state { + struct file_operations fops; + struct dentry *kfuzztest_dir; + struct kfuzztest_debugfs_state *debugfs_state; +}; + +/* Global static variable to hold all state for the module. */ +static struct kfuzztest_state state; + +const umode_t KFUZZTEST_INPUT_PERMS =3D 0222; + +/** + * kfuzztest_init - Initializes the debug filesystem for KFuzzTest. + * + * Each registered test in the ".kfuzztest" section gets its own subdirect= ory + * under "/sys/kernel/debug/kfuzztest/" with one files: + * - input: write-only file to send input to the fuzz driver + * + * Returns: + * 0 on success. + * -ENODEV or other error codes if debugfs creation fails. + */ +static int __init kfuzztest_init(void) +{ + const struct kfuzztest_target *targ; + int ret =3D 0; + int i =3D 0; + size_t num_test_cases; + + num_test_cases =3D __kfuzztest_targets_end - __kfuzztest_targets_start; + + state.debugfs_state =3D + kzalloc(num_test_cases * sizeof(struct kfuzztest_debugfs_state), + GFP_KERNEL); + if (!state.debugfs_state) + return -ENOMEM; + + /* Create the main "kfuzztest" directory in /sys/kernel/debug. */ + state.kfuzztest_dir =3D debugfs_create_dir("kfuzztest", NULL); + if (!state.kfuzztest_dir) { + pr_warn("KFuzzTest: could not create debugfs"); + return -ENODEV; + } + + if (IS_ERR(state.kfuzztest_dir)) { + state.kfuzztest_dir =3D NULL; + return PTR_ERR(state.kfuzztest_dir); + } + + for (targ =3D __kfuzztest_targets_start; targ < __kfuzztest_targets_end; + targ++, i++) { + /* Create debugfs directory for the target. */ + state.debugfs_state[i].target_dir =3D + debugfs_create_dir(targ->name, state.kfuzztest_dir); + + if (!state.debugfs_state[i].target_dir) { + ret =3D -ENOMEM; + goto cleanup_failure; + } else if (IS_ERR(state.debugfs_state[i].target_dir)) { + ret =3D PTR_ERR(state.debugfs_state[i].target_dir); + goto cleanup_failure; + } + + /* Create an input file under the target's directory. */ + state.debugfs_state[i].input_dentry.fops =3D + (struct file_operations){ + .owner =3D THIS_MODULE, + .write =3D targ->write_input_cb, + }; + state.debugfs_state[i].input_dentry.dentry =3D + debugfs_create_file( + "input", KFUZZTEST_INPUT_PERMS, + state.debugfs_state[i].target_dir, NULL, + &state.debugfs_state[i].input_dentry.fops); + if (!state.debugfs_state[i].input_dentry.dentry) { + ret =3D -ENOMEM; + goto cleanup_failure; + } else if (IS_ERR(state.debugfs_state[i].input_dentry.dentry)) { + ret =3D PTR_ERR( + state.debugfs_state[i].input_dentry.dentry); + goto cleanup_failure; + } + + pr_info("KFuzzTest: registered target %s", targ->name); + } + + return 0; + +cleanup_failure: + debugfs_remove_recursive(state.kfuzztest_dir); + return ret; +} + +static void __exit kfuzztest_exit(void) +{ + pr_info("KFuzzTest: exiting"); + if (!state.kfuzztest_dir) + return; + + debugfs_remove_recursive(state.kfuzztest_dir); + state.kfuzztest_dir =3D NULL; + + if (state.debugfs_state) { + kfree(state.debugfs_state); + state.debugfs_state =3D NULL; + } +} + +module_init(kfuzztest_init); +module_exit(kfuzztest_exit); diff --git a/lib/kfuzztest/parse.c b/lib/kfuzztest/parse.c new file mode 100644 index 000000000000..6010171190ad --- /dev/null +++ b/lib/kfuzztest/parse.c @@ -0,0 +1,208 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * KFuzzTest input parsing and validation. + * + * Copyright 2025 Google LLC + */ +#include +#include + +/* + * Enforce a fixed struct size to ensure a consistent stride when iteratin= g over + * the array of these structs in the dedicated ELF section. + */ +static_assert(sizeof(struct kfuzztest_target) =3D=3D 32, "struct kfuzztest= _target should have size 32"); +static_assert(sizeof(struct kfuzztest_constraint) =3D=3D 64, "struct kfuzz= test_constraint should have size 64"); +static_assert(sizeof(struct kfuzztest_annotation) =3D=3D 32, "struct kfuzz= test_annotation should have size 32"); + +static int kfuzztest_relocate_v0(struct reloc_region_array *regions, struc= t reloc_table *rt, void *payload_start, + void *payload_end) +{ + struct reloc_region reg, src, dst; + void *poison_start, *poison_end; + uintptr_t *ptr_location; + struct reloc_entry re; + size_t i; + + /* Patch pointers. */ + for (i =3D 0; i < rt->num_entries; i++) { + re =3D rt->entries[i]; + src =3D regions->regions[re.region_id]; + ptr_location =3D (uintptr_t *)((char *)payload_start + src.offset + re.r= egion_offset); + if (re.value =3D=3D KFUZZTEST_REGIONID_NULL) + *ptr_location =3D (uintptr_t)NULL; + else if (re.value < regions->num_regions) { + dst =3D regions->regions[re.value]; + *ptr_location =3D (uintptr_t)((char *)payload_start + dst.offset); + } else + return -EINVAL; + } + + /* Poison the padding between regions. */ + for (i =3D 0; i < regions->num_regions; i++) { + reg =3D regions->regions[i]; + + /* Points to the beginning of the inter-region padding */ + poison_start =3D payload_start + reg.offset + reg.size; + if (i < regions->num_regions - 1) + poison_end =3D payload_start + regions->regions[i + 1].offset; + else + poison_end =3D payload_end; + + if ((char *)poison_end > (char *)payload_end) + return -EINVAL; + + kasan_poison_range(poison_start, poison_end - poison_start); + } + + /* Poison the padded area preceding the payload. */ + kasan_poison_range((char *)payload_start - rt->padding_size, rt->padding_= size); + return 0; +} + +static bool kfuzztest_input_is_valid(struct reloc_region_array *regions, s= truct reloc_table *rt, void *payload_start, + void *payload_end) +{ + size_t payload_size =3D (char *)payload_end - (char *)payload_start; + struct reloc_region reg, next_reg; + size_t usable_payload_size; + uint32_t region_end_offset; + struct reloc_entry reloc; + uint32_t i; + + if ((char *)payload_start > (char *)payload_end) + return false; + if (payload_size < KFUZZTEST_POISON_SIZE) + return false; + usable_payload_size =3D payload_size - KFUZZTEST_POISON_SIZE; + + for (i =3D 0; i < regions->num_regions; i++) { + reg =3D regions->regions[i]; + if (check_add_overflow(reg.offset, reg.size, ®ion_end_offset)) + return false; + if ((size_t)region_end_offset > usable_payload_size) + return false; + + if (i < regions->num_regions - 1) { + next_reg =3D regions->regions[i + 1]; + if (reg.offset > next_reg.offset) + return false; + /* + * Enforce the minimum poisonable gap between + * consecutive regions. + */ + if (reg.offset + reg.size + KFUZZTEST_POISON_SIZE > next_reg.offset) + return false; + } + } + + if (rt->padding_size < KFUZZTEST_POISON_SIZE) { + pr_info("validation failed because rt->padding_size =3D %u", rt->padding= _size); + return false; + } + + for (i =3D 0; i < rt->num_entries; i++) { + reloc =3D rt->entries[i]; + if (reloc.region_id >=3D regions->num_regions) + return false; + if (reloc.value !=3D KFUZZTEST_REGIONID_NULL && reloc.value >=3D regions= ->num_regions) + return false; + + reg =3D regions->regions[reloc.region_id]; + if (reloc.region_offset % (sizeof(uintptr_t)) || reloc.region_offset + s= izeof(uintptr_t) > reg.size) + return false; + } + + return true; +} + +static int kfuzztest_parse_input_v0(void *input, size_t input_size, struct= reloc_region_array **ret_regions, + struct reloc_table **ret_reloc_table, void **ret_payload_start, + void **ret_payload_end) +{ + size_t reloc_entries_size, reloc_regions_size; + size_t reloc_table_size, regions_size; + struct reloc_region_array *regions; + void *payload_end, *payload_start; + struct reloc_table *rt; + size_t curr_offset =3D 0; + + if (input_size < sizeof(struct reloc_region_array) + sizeof(struct reloc_= table)) + return -EINVAL; + + regions =3D input; + if (check_mul_overflow(regions->num_regions, sizeof(struct reloc_region),= &reloc_regions_size)) + return -EINVAL; + if (check_add_overflow(sizeof(*regions), reloc_regions_size, ®ions_siz= e)) + return -EINVAL; + + curr_offset =3D regions_size; + if (curr_offset > input_size) + return -EINVAL; + if (input_size - curr_offset < sizeof(struct reloc_table)) + return -EINVAL; + + rt =3D (struct reloc_table *)((char *)input + curr_offset); + + if (check_mul_overflow((size_t)rt->num_entries, sizeof(struct reloc_entry= ), &reloc_entries_size)) + return -EINVAL; + if (check_add_overflow(sizeof(*rt), reloc_entries_size, &reloc_table_size= )) + return -EINVAL; + if (check_add_overflow(reloc_table_size, rt->padding_size, &reloc_table_s= ize)) + return -EINVAL; + + if (check_add_overflow(curr_offset, reloc_table_size, &curr_offset)) + return -EINVAL; + if (curr_offset > input_size) + return -EINVAL; + + payload_start =3D (char *)input + curr_offset; + payload_end =3D (char *)input + input_size; + + if (!kfuzztest_input_is_valid(regions, rt, payload_start, payload_end)) + return -EINVAL; + + *ret_regions =3D regions; + *ret_reloc_table =3D rt; + *ret_payload_start =3D payload_start; + *ret_payload_end =3D payload_end; + return 0; +} + +static int kfuzztest_parse_and_relocate_v0(void *input, size_t input_size,= void **arg_ret) +{ + struct reloc_region_array *regions; + void *payload_start, *payload_end; + struct reloc_table *reloc_table; + int ret; + + ret =3D kfuzztest_parse_input_v0(input, input_size, ®ions, &reloc_tabl= e, &payload_start, &payload_end); + if (ret < 0) + return ret; + + ret =3D kfuzztest_relocate_v0(regions, reloc_table, payload_start, payloa= d_end); + if (ret < 0) + return ret; + *arg_ret =3D payload_start; + return 0; +} + +int kfuzztest_parse_and_relocate(void *input, size_t input_size, void **ar= g_ret) +{ + u32 version, magic; + + if (input_size < sizeof(u32) + sizeof(u32)) + return -EINVAL; + + magic =3D *(u32 *)input; + if (magic !=3D KFUZZTEST_HEADER_MAGIC) + return -EINVAL; + + version =3D *(u32 *)((char *)input + sizeof(u32)); + switch (version) { + case KFUZZTEST_V0: + return kfuzztest_parse_and_relocate_v0(input + sizeof(u64), input_size -= sizeof(u64), arg_ret); + } + + return -EINVAL; +} --=20 2.51.0.rc0.205.g4a044479a3-goog From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wr1-f42.google.com (mail-wr1-f42.google.com [209.85.221.42]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4778E2EAB6A for ; Wed, 13 Aug 2025 13:38:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092326; cv=none; b=bw9n+Pjbv5/Hqj+at4eXfjBKRQEyGYSV0/kTOrphHylMyMuHee8ucGR7nBS1Ly3KyBqJ6q+wGXe28gELaNCUgpUsmfjJNgBNkq3wOa+zmsnTA7XQizKp32igY435Sj+bA3emFLCHY/BvZT0vOaYVYfSA/oSLECV87YeIZDlkxLk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092326; c=relaxed/simple; bh=v5Q3Xn8pa41ckJim5ITQm4P5k3uWaLJtrBCtN7c4kUA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=GpirHLNjNFoi9v1eUEk9u18mrtwlO0qY+O0KU1jHyMTUlIU5K/YMxjjM0d2kw2Uv6yj3+k48wsRuvG+teE2fLZNtWddbmwyPdXwEb3jgIjuxurtzftMODjkVBmOpjvE9qo2+n+HU0E3918nd0vhatiau/gAlzMXoscXbFjCPIMY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=AgTspBk3; arc=none smtp.client-ip=209.85.221.42 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="AgTspBk3" Received: by mail-wr1-f42.google.com with SMTP id ffacd0b85a97d-3b913a76ba9so1672600f8f.3 for ; Wed, 13 Aug 2025 06:38:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092322; x=1755697122; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=fT8XtIdCS6vk3GGdGM60wvLV9ckvUvGKm1mza8YtIpw=; b=AgTspBk3uzRr+uK++jjJfZYF2S6sX6MKGnAQfcwkYxr/3RZlp7KV7RVuQCLXsjZbow i4QuvnHA1WPAOT2pGrsDPRCWoVz4M+w3cgIqrPRZhxaqKmnMUGli3hnlWtU1Ahy+HpV0 VAmO1boZjSXwhy1/WGBQXsO/lSkTA5NwRkT0SOvPuCH5Pa7VoJA/PG7ip4rzcjHur17k qbj3YG98FTJAbnY1BqeHkhpRXrcNBA0c67HM6NtiU8/8QsG7xc/U49WPbnkhqcvMAqzc VGCHCgyuaqJF+2VuyJ4Si87sX8kDkAYd60GBN0btUFDroqzt4I1VOZPFwDxQIeIUterj vMpg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092322; x=1755697122; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=fT8XtIdCS6vk3GGdGM60wvLV9ckvUvGKm1mza8YtIpw=; b=gsqJY10cqhHx7z+uICtJz1at0uJypvQGbMjwIKX7zw4zxglrEObVCFhnIs+D+q2JJa AyPO2jrT8VxvmDnosxc8XyLrMR3/oL2pZs7p7C+Ok5HCayCyx1Ez2Ql3M3RlC6gs2Z8q mfPZdaHZNVOa8dhNpav9+2Y+htE0ZGwqlFgUSTN0c9ZlLm0cyXXlQcoh6LrQO8hZnc4p Chei/AN8d8AWhlSwfFawE+zVfu4yzI7F0D0H0QbXwz0hm1mxBJL+UpYKXS/Cduie9tdt sINYW+FL0UuLni6LShgIWUr4H6w4hTZG3YaNiHDJygzIJlZtKQiU3oqyGm9WQB/C2Rs4 qoOA== X-Forwarded-Encrypted: i=1; AJvYcCUNLGwXP3b6manGkHBdHgXpJFl/nq7wQwCs5MMjww1HpNn/p+QJyRMfPvRtSVbZC3MZjiMygwe+MSVVjRM=@vger.kernel.org X-Gm-Message-State: AOJu0YxwVT5tXgmcof+k8sWc/dTkdAp3DhbsRCAdjFJMjm9k7YmPkpeM U34F1OHPQ63vB3geADJSd1iDwiv793D1/ccJbZy3wldu8yW6UiolmFqX X-Gm-Gg: ASbGncs91Q5jTuIDlaYZVYqh85LMErCXBhmkkc0Nk5L3eQZSPKmWmjxkoTHgMUqosb4 rFQCo4eH9kSimryR7OA83P67zAaJrkClik9rSPIb4tIM7pPdnfRwNf3jsh9VITwUF+uvItFqs5f yPOAUfySa766bZZ6gLEusx44Srg7hhfdKOyODs1lwr5AJcq0wa12DnZFY6roISni8jkcqyERBUG 7ryhAzAYRgtM+a0W5UAfoG/E1unbtG78bJ9srycASF+UTCWT06Kr0gdgmuvn+lvgyogYIHBS/EY uYZrezGeefrCmDuAyfAu1sN7rzMnRLJEM0cNXTtloHe8Gpd9OECA93+ztMGR8shRsqEz1ZSsgqq PLJPFPjiRAwVguFFu7CJP6tcid3dBoBXozxW6p6Wy8Epvl1BwS4hoCtK0gl3t4rkQkHccmo+keA 9ZpwAz5xFYuMG1Z6w= X-Google-Smtp-Source: AGHT+IG3CJoU5aNy+ncGbe3vgt9XmR0hiIDWH1GBUd5ER+QfQEnq5bQhyK7xzwpgftq1Sivqu1Fxdw== X-Received: by 2002:a05:6000:26c9:b0:3b8:d6ae:6705 with SMTP id ffacd0b85a97d-3b917ea1577mr2096491f8f.30.1755092322216; Wed, 13 Aug 2025 06:38:42 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:41 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 4/6] kfuzztest: add ReST documentation Date: Wed, 13 Aug 2025 13:38:10 +0000 Message-ID: <20250813133812.926145-5-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Add Documentation/dev-tools/kfuzztest.rst and reference it in the dev-tools index. Signed-off-by: Ethan Graham --- Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/kfuzztest.rst | 279 ++++++++++++++++++++++++++ 2 files changed, 280 insertions(+) create mode 100644 Documentation/dev-tools/kfuzztest.rst diff --git a/Documentation/dev-tools/index.rst b/Documentation/dev-tools/in= dex.rst index 65c54b27a60b..00ccc4da003b 100644 --- a/Documentation/dev-tools/index.rst +++ b/Documentation/dev-tools/index.rst @@ -32,6 +32,7 @@ Documentation/process/debugging/index.rst kfence kselftest kunit/index + kfuzztest ktap checkuapi gpio-sloppy-logic-analyzer diff --git a/Documentation/dev-tools/kfuzztest.rst b/Documentation/dev-tool= s/kfuzztest.rst new file mode 100644 index 000000000000..7fdc4914b966 --- /dev/null +++ b/Documentation/dev-tools/kfuzztest.rst @@ -0,0 +1,279 @@ +.. SPDX-License-Identifier: GPL-2.0 +.. Copyright 2025 Google LLC + +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D +Kernel Fuzz Testing Framework (KFuzzTest) +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +Overview +=3D=3D=3D=3D=3D=3D=3D=3D + +The Kernel Fuzz Testing Framework (KFuzzTest) is a framework designed to e= xpose +internal kernel functions to a userspace fuzzing engine. + +It is intended for testing stateless or low-state functions that are diffi= cult +to reach from the system call interface, such as routines involved in file +format parsing or complex data transformations. This provides a method for +in-situ fuzzing of kernel code without requiring that it be built as a sep= arate +userspace library or that its dependencies be stubbed out. + +The framework consists of four main components: + +1. An API, based on the ``FUZZ_TEST`` macro, for defining test targets + directly in the kernel tree. +2. A binary serialization format for passing complex, pointer-rich data + structures from userspace to the kernel. +3. A ``debugfs`` interface through which a userspace fuzzer submits + serialized test inputs. +4. Metadata embedded in dedicated ELF sections of the ``vmlinux`` binary = to + allow for the discovery of available fuzz targets by external tooling. + +.. warning:: + KFuzzTest is a debugging and testing tool. It exposes internal kernel + functions to userspace with minimal sanitization and is designed for + use in controlled test environments only. It must **NEVER** be enabled + in production kernels. + +Supported Architectures +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +KFuzzTest is currently only supported for x86_64. + +Usage +=3D=3D=3D=3D=3D + +To enable KFuzzTest, configure the kernel with:: + + CONFIG_KFUZZTEST=3Dy + +which depends on ``CONFIG_DEBUGFS`` for receiving userspace inputs, and +``CONFIG_DEBUG_KERNEL`` as an additional guardrail for preventing KFuzzTest +from finding its way into a production build accidentally. + +The KFuzzTest sample fuzz targets can be built in with +``CONFIG_SAMPLE_KFUZZTEST``. + +KFuzzTest currently only supports code that is built into the kernel, as t= he +core module's startup process discovers fuzz targets, constraints, and +annotations from a dedicated ELF section during startup. + +Declaring a KFuzzTest target +---------------------------- + +A fuzz target is defined directly in a .c file, typically alongside the fu= nction +being tested. This process involves three main parts: defining an input +structure, writing the test body using the ``FUZZ_TEST`` macro, and option= ally +adding metadata for the fuzzer. + +The following example illustrates how to create a fuzz target for a functi= on +``int process_data(const char *data, size_t len)``. + +.. code-block:: c + + /* + * 1. Define a struct to model the inputs for the function under test. + * Each field corresponds to an argument needed by the function. + */ + struct process_data_inputs { + const char *data; + size_t len; + }; + + /* + * 2. Define the fuzz target using the FUZZ_TEST macro. + * The first parameter is a unique name for the target. + * The second parameter is the input struct defined above. + */ + FUZZ_TEST(test_process_data, struct process_data_inputs) + { + /* + * Within this body, the 'arg' variable is a pointer to a + * fully initialized 'struct process_data_inputs'. + */ + + /* + * 3. (Optional) Add constraints to define preconditions. + * This check ensures 'arg->data' is not NULL. If the condition + * is not met, the test exits early. This also creates metadata + * to inform the fuzzer. + */ + KFUZZTEST_EXPECT_NOT_NULL(process_data_inputs, data); + + /* + * 4. (Optional) Add annotations to provide semantic hints. + * This annotation informs the fuzzer that the 'len' field + * is the length of the buffer pointed to by 'data'. + * Annotations do not add any runtime checks. + */ + KFUZZTEST_ANNOTATE_LEN(process_data_inputs, len, data); + + /* + * 5. Call the kernel function with the provided inputs. + * Memory errors like out-of-bounds accesses on 'arg->data' will + * be detected by KASAN or other memory error detection tools. + */ + process_data(arg->data, arg->len); + } + +KFuzzTest provides two families of macros to improve the quality of fuzzin= g: + +- ``KFUZZTEST_EXPECT_*``: These macros define constraints, which are + preconditions that must be true for the test to proceed. They are enforc= ed + with a runtime check in the kernel. If a check fails, the current test r= un is + aborted. This metadata helps the userspace fuzzer avoid generating inval= id + inputs. + +- ``KFUZZTEST_ANNOTATE_*``: These macros define annotations, which are pur= ely + semantic hints for the fuzzer. They do not add any runtime checks and ex= ist + only to help the fuzzer generate more intelligent and structurally corre= ct + inputs. For example, KFUZZTEST_ANNOTATE_LEN links a size field to a poin= ter + field, which is a common pattern in C APIs. + +Metadata +-------- + +Macros ``FUZZ_TEST``, `KFUZZTEST_EXPECT_*`` and ``KFUZZTEST_ANNOTATE_*`` e= mbed +metadata into several sections within the main ``.data`` section of the fi= nal +``vmlinux`` binary; ``.kfuzztest_target``, ``.kfuzztest_constraint`` and +``.kfuzztest_annotation`` respectively. + +This serves two purposes: + +1. The core module uses the ``.kfuzztest_target`` section at boot to disco= ver + every ``FUZZ_TEST`` instance and create its ``debugfs`` directory and + ``input`` file. +2. Userspace fuzzers can read this metadata from the ``vmlinux`` binary to + discover targets and learn about their rules and structure in order to + generate correct and effective inputs. + +The metadata in the ``.kfuzztest_*`` sections consists of arrays of fixed-= size C +structs (e.g., ``struct kfuzztest_target``). Fields within these structs t= hat +are pointers, such as ``name`` or ``arg_type_name``, contain addresses that +point to other locations in the ``vmlinux`` binary. A userspace tool that +parsing the ELF file must resolve these pointers to read the data that they +reference. For example, to get a target's name, a tool must: + +1. Read the ``struct kfuzztest_target`` from the ``.kfuzztest_target`` sec= tion. +2. Read the address in the ``.name`` field. +3. Use that address to locate and read null-terminated string from its pos= ition + elsewhere in the binary (e.g., ``.rodata``). + +Tooling Dependencies +-------------------- + +For userspace tools to parse the ``vmlinux`` binary and make use of emitted +KFuzzTest metadata, the kernel must be compiled with DWARF debug informati= on. +This is required for tools to understand the layout of C structs, resolve = type +information, and correctly interpret constraints and annotations. + +When using KFuzzTest with automated fuzzing tools, either +``CONFIG_DEBUG_INFO_DWARF4`` or ``CONFIG_DEBUG_INFO_DWARF5`` should be ena= bled. + +Input Format +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +KFuzzTest targets receive their inputs from userspace via a write to a ded= icated +debugfs ``/sys/kernel/debug/kfuzztest//input``. + +The data written to this file must be a single binary blob that follows a +specific serialization format. This format is designed to allow complex, +pointer-rich C structures to be represented in a flat buffer, requiring on= ly a +single kernel allocation and copy from userspace. + +An input is first prefixed by an 8-byte header containing a magic value in= the +first four bytes, defined as ``KFUZZTEST_HEADER_MAGIC`` in +```, and a version number in the subsequent four +bytes. + +Version 0 +--------- + +In version 0 (i.e., when the version number in the 8-byte header is equal = to 0), +the input format consists of three main parts laid out sequentially: a reg= ion +array, a relocation table, and the payload.:: + + +----------------+---------------------+-----------+----------------+ + | region array | relocation table | padding | payload | + +----------------+---------------------+-----------+----------------+ + +Region Array +^^^^^^^^^^^^ + +This component is a header that describes how the raw data in the Payload = is +partitioned into logical memory regions. It consists of a count of regions +followed by an array of ``struct reloc_region``, where each entry defines a +single region with its size and offset from the start of the payload. + +.. code-block:: c + + struct reloc_region { + uint32_t offset; + uint32_t size; + }; + + struct reloc_region_array { + uint32_t num_regions; + struct reloc_region regions[]; + }; + +By convention, region 0 represents the top-level input struct that is pass= ed +as the arg variable to the FUZZ_TEST body. Subsequent regions typically +represent data buffers pointed to by fields within that struct. Region arr= ay +entries must be ordered by offset ascending, and must not overlap with one +another. + +To satisfy C language alignment requirements and prevent potential hardware +faults, the memory address of each region's data must be correctly aligned= for +the type it represents. The framework allocates a base buffer that is suit= ably +aligned for any C type. Therefore, the userspace tool that generates the i= nput +is responsible for calculating each region's offset within the payload to = ensure +this alignment is maintained. + +Relocation Table +^^^^^^^^^^^^^^^^ + +The relocation table provides the instructions for the kernel to "hydrate"= the +payload by patching pointer fields. It contains an array of +``struct reloc_entry`` items. Each entry acts as a linking instruction, +specifying: + +- The location of a pointer that needs to be patched (identified by a regi= on + ID and an offset within that region). + +- The target region that the pointer should point to (identified by the + target's region ID) or ``KFUZZTEST_REGIONID_NULL`` if the pointer is ``N= ULL``. + +This table also specifies the amount of padding between its end and the st= art +of the payload, which should be at least 8 bytes. + +.. code-block:: c + + struct reloc_entry { + uint32_t region_id; + uint32_t region_offset; + uint32_t value; + }; + + struct reloc_table { + uint32_t num_entries; + uint32_t padding_size; + struct reloc_entry entries[]; + }; + +Payload +^^^^^^^ + +The payload contains the raw binary data for all regions, concatenated tog= ether +according to their specified offsets. + +- Alignment: The start of the payload must be aligned to the most restrict= ive + alignment requirement of all its constituent regions. The framework ensu= res + that each region within the payload is then placed at an offset that res= pects + its own type's alignment. + +- Padding and Poisoning: The space between the end of one region's data an= d the + beginning of the next must be sufficient for padding. In KASAN builds, + KFuzzTest poisons this unused padding, allowing for precise detection of + out-of-bounds memory accesses between adjacent buffers. This padding sho= uld + be at least ``KFUZZTEST_POISON_SIZE`` bytes as defined in + `include/linux/kfuzztest.h``. --=20 2.51.0.rc0.205.g4a044479a3-goog From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wm1-f48.google.com (mail-wm1-f48.google.com [209.85.128.48]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 03AE72EAB88 for ; Wed, 13 Aug 2025 13:38:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092326; cv=none; b=EnHZmZJakVnlQrOIIwfpZIRqFVqfvx0VMlGaHk9RfM9USgBNfoHugz9ef9jkqtcIwnqG///8RN9EH6s8Kf4RswYtjdA7EECbiGA4/ty3P48BaDKBkzGUFfvV4tmIkMZgrygG9EOwraqIvfHbeHtXWItv3mQBvAAtSxcOvVH4jdE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092326; c=relaxed/simple; bh=UZMHOj4dcWuDePMWBKn/lmZBU3O7jroj1pLSG5PDHcg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=SaccTnzEqZXopNCn9NOndHPizU4OasfezcrveE+H8VcIQC28Pd+EU/b1JMynYAYsGFTQwbbZbYjzV3VpECH0P3QgfkdAJ+NJ562rJRKW3GXtPaGWXq5OaMTTSwwoYwPuMvFcwkxHk/bVhnJhf+okVdWPwPddoP1PwQw9Uy8+ink= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=azPFY3uC; arc=none smtp.client-ip=209.85.128.48 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="azPFY3uC" Received: by mail-wm1-f48.google.com with SMTP id 5b1f17b1804b1-459fdc391c6so38002095e9.3 for ; Wed, 13 Aug 2025 06:38:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092323; x=1755697123; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=08hbUSvRcagfemg83g47pFkXwfN5ra3fR8Zxn3xb4d4=; b=azPFY3uClkmv+vjB4u6lXP8SdRd5SCDegOOP7PqndU2pMUJKRJWhI9T/fpkbCqwXiY CxIHOGoqzmX/W5HbuswMP307woPgigrlIdsJqGIlCDqAyiJXnjlT9IxMYEChFfqd4Ja1 jdPL2yTAROph4P3sHyJsY769+zAIWZAzMHCkDgKrW+v4OQgQuWYZkmgaGHUaf738wTLo NVRqibQWBBObqOJUYtQezcEPPU9n2AHuM0L60WM02vb2CluzHGVeRJ9mxQD3JoYs7HRY qhj2OWCZZR9RXy+jSC5td8RtnQdg4sDRwnwDk8Kp5zmxxkudXQ9E1Ibo6HJ/tARodklX z2ng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092323; x=1755697123; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=08hbUSvRcagfemg83g47pFkXwfN5ra3fR8Zxn3xb4d4=; b=iQPHVRy2ibeILmv9jg8N/Qe652WXqNQG0FfrKqn6lPb3ktJwM3T6ni/K/bfv7J7gwP g0RhHpg4bg5NDuJgD7UhhwxHVX8LQZ0LKF2VtBG/CJWZxnOEJkZG0uBUJrxfWkOf7+oD xmu9ZCZUsCXGZ4lefVsJR1NTLkYn+tGyRlXOnG2byITv2X2s8Remrc7QelKdnLjo/bfE LnJQOuyRauN9KVoJwFEc0961N39gP3n0bgwbyM6+VVFibqxmw4ueyLK2UZ6TlXU/szPn LbAW07Ap5yVEcWovAVE/etF6CMRMWbZjwW3q0nZBnd4Nsez6lzxgAaboFAkxOZOd8ozz qZqw== X-Forwarded-Encrypted: i=1; AJvYcCW7Afx7YfCzqltzYL/e2jaRMgpTSxUaGXBPX5q6oXA8q/O6gx/fUQzYYRfcQneOIO3ffoDHdXWlP8s2KiI=@vger.kernel.org X-Gm-Message-State: AOJu0YxbZh8GS9nx073t5lLFCM2Gz8H1evxj/kYDq67K/GR1barjaWXa +FRM+vLZS0mILwPBflLoXx9OsPUXxBj4sz4HCoGPp8LZ8DLSkeQN2rbD X-Gm-Gg: ASbGncvkUAOoZnmR+NcuYgPL5/vXJPsm8gj9APaW7DTZP7R9OKexZ3hVf7b0kbnBlbk vut744XvgvqOHQ94tWdTrMLgoqNx42YEA/wBdi8KdH2vdC7QrVA+9dvez+RyQVZP4g+/OFdhZoN un4/ss4mEQIAqgmND/BF1lFbR5dYHZoyrkINRKTuEYzMrHB/aRXQ+qC/TXh5xy9a5+aK99pgvH0 veE1lQVFd1mcRlCvEEs6ttl2laIgnNFlv9fyV0Qgdh9oU1oWZnnNzmwhHJzrx6HvKur4XzwMv3b Tf+WOmZpmnScps/kEvhh0vXgZaQ34S4YqbfQWQHy3LRSI27zwT5T0bsG97tpSZh5/6jmDp06BjM aIWq52OuQiH9u2u94a0tJhcLxS6ZL+oObolqwPhxnOk/GzNgeMz5fbFbsmUClGmFGEZ24y2STA3 QVnWq8CotjiyouePMn+pecJJkFWw== X-Google-Smtp-Source: AGHT+IH/vHQLEUqCTkHELdcv4FlcQ/pK5AuwNwJHyQdHRE3adkmaZLxp5+wlXgNH0eI9cVeElhHRKg== X-Received: by 2002:a05:600c:1c86:b0:458:b01c:8f with SMTP id 5b1f17b1804b1-45a1a80e6femr1190105e9.8.1755092323030; Wed, 13 Aug 2025 06:38:43 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:42 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 5/6] kfuzztest: add KFuzzTest sample fuzz targets Date: Wed, 13 Aug 2025 13:38:11 +0000 Message-ID: <20250813133812.926145-6-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Add two simple fuzz target samples to demonstrate the KFuzzTest API and provide basic self-tests for the framework. These examples showcase how a developer can define a fuzz target using the FUZZ_TEST(), constraint, and annotation macros, and serve as runtime sanity checks for the core logic. For example, they test that out-of-bounds memory accesses into poisoned padding regions are correctly detected in a KASAN build. These have been tested by writing syzkaller-generated inputs into their debugfs 'input' files and verifying that the correct KASAN reports were triggered. Signed-off-by: Ethan Graham --- samples/Kconfig | 7 +++ samples/Makefile | 1 + samples/kfuzztest/Makefile | 3 ++ samples/kfuzztest/overflow_on_nested_buffer.c | 52 +++++++++++++++++++ samples/kfuzztest/underflow_on_buffer.c | 41 +++++++++++++++ 5 files changed, 104 insertions(+) create mode 100644 samples/kfuzztest/Makefile create mode 100644 samples/kfuzztest/overflow_on_nested_buffer.c create mode 100644 samples/kfuzztest/underflow_on_buffer.c diff --git a/samples/Kconfig b/samples/Kconfig index ffef99950206..4be51a21d010 100644 --- a/samples/Kconfig +++ b/samples/Kconfig @@ -321,6 +321,13 @@ config SAMPLE_HUNG_TASK if 2 or more processes read the same file concurrently, it will be detected by the hung_task watchdog. =20 +config SAMPLE_KFUZZTEST + bool "Build KFuzzTest sample targets" + depends on KFUZZTEST + help + Build KFuzzTest sample targets that serve as selftests for input + deserialization and inter-region redzone poisoning logic. + source "samples/rust/Kconfig" =20 source "samples/damon/Kconfig" diff --git a/samples/Makefile b/samples/Makefile index 07641e177bd8..3a0e7f744f44 100644 --- a/samples/Makefile +++ b/samples/Makefile @@ -44,4 +44,5 @@ obj-$(CONFIG_SAMPLE_DAMON_WSSE) +=3D damon/ obj-$(CONFIG_SAMPLE_DAMON_PRCL) +=3D damon/ obj-$(CONFIG_SAMPLE_DAMON_MTIER) +=3D damon/ obj-$(CONFIG_SAMPLE_HUNG_TASK) +=3D hung_task/ +obj-$(CONFIG_SAMPLE_KFUZZTEST) +=3D kfuzztest/ obj-$(CONFIG_SAMPLE_TSM_MR) +=3D tsm-mr/ diff --git a/samples/kfuzztest/Makefile b/samples/kfuzztest/Makefile new file mode 100644 index 000000000000..4f8709876c9e --- /dev/null +++ b/samples/kfuzztest/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0-only + +obj-$(CONFIG_SAMPLE_KFUZZTEST) +=3D overflow_on_nested_buffer.o underflow_= on_buffer.o diff --git a/samples/kfuzztest/overflow_on_nested_buffer.c b/samples/kfuzzt= est/overflow_on_nested_buffer.c new file mode 100644 index 000000000000..8b4bab1d6d4a --- /dev/null +++ b/samples/kfuzztest/overflow_on_nested_buffer.c @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * This file contains a KFuzzTest example target that ensures that a buffer + * overflow on a nested region triggers a KASAN OOB access report. + * + * Copyright 2025 Google LLC + */ +#include + +static void overflow_on_nested_buffer(const char *a, size_t a_len, const c= har *b, size_t b_len) +{ + size_t i; + pr_info("a =3D [%px, %px)", a, a + a_len); + pr_info("b =3D [%px, %px)", b, b + b_len); + + /* Ensure that all bytes in arg->b are accessible. */ + for (i =3D 0; i < b_len; i++) + READ_ONCE(b[i]); + /* + * Check that all bytes in arg->a are accessible, and provoke an OOB on + * the first byte to the right of the buffer which will trigger a KASAN + * report. + */ + for (i =3D 0; i <=3D a_len; i++) + READ_ONCE(a[i]); +} + +struct nested_buffers { + const char *a; + size_t a_len; + const char *b; + size_t b_len; +}; + +/** + * The KFuzzTest input format specifies that struct nested buffers should + * be expanded as: + * + * | a | b | pad[8] | *a | pad[8] | *b | + * + * where the padded regions are poisoned. We expect to trigger a KASAN rep= ort by + * overflowing one byte into the `a` buffer. + */ +FUZZ_TEST(test_overflow_on_nested_buffer, struct nested_buffers) +{ + KFUZZTEST_EXPECT_NOT_NULL(nested_buffers, a); + KFUZZTEST_EXPECT_NOT_NULL(nested_buffers, b); + KFUZZTEST_ANNOTATE_LEN(nested_buffers, a_len, a); + KFUZZTEST_ANNOTATE_LEN(nested_buffers, b_len, b); + + overflow_on_nested_buffer(arg->a, arg->a_len, arg->b, arg->b_len); +} diff --git a/samples/kfuzztest/underflow_on_buffer.c b/samples/kfuzztest/un= derflow_on_buffer.c new file mode 100644 index 000000000000..fbe214274037 --- /dev/null +++ b/samples/kfuzztest/underflow_on_buffer.c @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * This file contains a KFuzzTest example target that ensures that a buffer + * underflow on a region triggers a KASAN OOB access report. + * + * Copyright 2025 Google LLC + */ +#include + +static void underflow_on_buffer(char *buf, size_t buflen) +{ + size_t i; + + pr_info("buf =3D [%px, %px)", buf, buf + buflen); + + /* First ensure that all bytes in arg->b are accessible. */ + for (i =3D 0; i < buflen; i++) + READ_ONCE(buf[i]); + /* + * Provoke a buffer overflow on the first byte preceding b, triggering + * a KASAN report. + */ + READ_ONCE(*((char *)buf - 1)); +} + +struct some_buffer { + char *buf; + size_t buflen; +}; + +/** + * Tests that the region between struct some_buffer and the expanded *buf = field + * is correctly poisoned by accessing the first byte before *buf. + */ +FUZZ_TEST(test_underflow_on_buffer, struct some_buffer) +{ + KFUZZTEST_EXPECT_NOT_NULL(some_buffer, buf); + KFUZZTEST_ANNOTATE_LEN(some_buffer, buflen, buf); + + underflow_on_buffer(arg->buf, arg->buflen); +} --=20 2.51.0.rc0.205.g4a044479a3-goog From nobody Sat Oct 4 19:16:46 2025 Received: from mail-wr1-f41.google.com (mail-wr1-f41.google.com [209.85.221.41]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 72A202EAB94 for ; Wed, 13 Aug 2025 13:38:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.41 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092327; cv=none; b=GCEpqswPMSLlQbe03zzmqjoE/RL7wM26xVmjRdJUZJmZHjSDkvauwvOl7UtVOnEZeJ+9AYwal95SKZ6OR6uMKXo1YqTo1Goaw+oFW6VtPs+gDG99CvVAOffbIKCGusDwVu7XwK6yc2F1kju+QbeTyuSBEgHGmIkVE0TMhtjZk4M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755092327; c=relaxed/simple; bh=ATCeCXY9ExH+Cvg4r15EUaOEE6ibGwuLUwDitn12MTQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RE0bgK6o7wiCG436EtK9kV+m1PgHpS5aFwva02qiY88L0gELyRIcLNXk/1swr6IQIMJ8lNOZ/sYkde1gdFv4hJV95ufA5v1psDkdo0EAkmZKoBpHS5SS0hwzsWeFhVjpfEYlADYIykfTlgHRLNTLFj9+TqjtdiwxdfBm6YqbXmQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=YUKwEYU2; arc=none smtp.client-ip=209.85.221.41 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="YUKwEYU2" Received: by mail-wr1-f41.google.com with SMTP id ffacd0b85a97d-3b8de193b60so3761880f8f.0 for ; Wed, 13 Aug 2025 06:38:45 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755092324; x=1755697124; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=WCmoTAq+24iKRI4CSHEBG8UaeJTBmRNFmOmZvFaISJE=; b=YUKwEYU2bWSnjxDaEz1aMAlUu8zoOnjXj30O2SYSndjx2luwz/SE6LlhbUv4zRi0q0 u61l8KCbDfl8hwIOztdOHXLUzd5L6/xRfUk1TqdTjKM6CGSe7MEofL/XPZoZCVu9TOxR 4syxXtlkpOPNgN2zOCz0MU1FZaKjEf62ntp9c1cKBk6R9qmArWzan9KYKmWkw8B34Fcd J/DfTtQ8WRBwm6h7hEn1nY6DLJxj80NGqb43zMtxc4HrPkUHhXKtW/zkQVJQKS+Mciho CRdmbiqWdSOVSqEMZZ1XXWLqp+aZj0Ido85HDti5hURqhwvH95LBMhv1jmKCCkSP6AQW iH4A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755092324; x=1755697124; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=WCmoTAq+24iKRI4CSHEBG8UaeJTBmRNFmOmZvFaISJE=; b=qdecpOWnTFfpmxA0aE2mUzP0m2YD6pFOm9hRQ5hopgAEQkO3QTSt5yV9cTx2VLY2Bk cld2vqr18+4kjxgeixqS0pEa6W9n01lzpM8Vw+Rmen4GS+NWZSAOG+2YMlgs5FbsRIh8 8DNkVizhT2vtBLxBSoDroYEeFq7MUYu55/qDKWiEpGVq4Zcg3IMYWg4WZBzA9aIiF3XU qudQ0z5ejPjy9eF42DjQFrcMY5Zr2RHG8U40Vgkt4hCdlt3CGoXfQ0mEExBJAEjjQN// z5yns/5C/0AAkDJF2FmvPJnw8ufLmkdKDCMJy/atyCQXkOdPOWlddPie737N2hcCiOVP 7Sxg== X-Forwarded-Encrypted: i=1; AJvYcCV5OspCam+2hTzYm9ALcT1bgAT5dMtpR4/KvRqw9pjO69u64mQG4DoqzNicUIpLd/adWOOf0dKQJDh/kPU=@vger.kernel.org X-Gm-Message-State: AOJu0YwXE41IdysLY5uq6Da2XMKNxjyA7mDWp3AlObIg+9X5YeHWBXok BAaTotlcYMk3YG0jhChl/Nd8ZHBZ51j/2nyOn1OgtMjXVaoN1FwXODTS X-Gm-Gg: ASbGncuHL3uPShJKm3hiR8Fmp/2XktVLK+vECHcgk6QOW8xerHnHHUXqAW1sdLFA/Ru Yxa3AazGLCdyvztRWqvU1985Es17k7zv4dCSxa4sm6L0SNArN1uIVFqvTvfFjSIQmPTMZASlrVz GrH4pfK4v4jls9TLNQDL2vjXtLyrlwV9zWccHaODBYU7+evRoXzAqx7TngeyV+x2zmKcbWpsZIr LkyaLMyZ7fmodzVZuqzDUmp9vIr03G8PrMNXRn/0X0IIJsf18MD2oaFYbdsJqE/74QWBgnUM4BM Ol32ugEdb8A6ktxTZ6M8Hfp735fQM/WpxOWGh9piPOJI+13swbWf7DQL5K+9OSLZD79GwhxjNyD 8aUR/WgNDJPiWOKNtBD0GEHtDd+2Qh0e2OI1qG9yKFDaMB7PZ/0+Weyr8sx4iLYJwtEqX2equ/m m+SzrWokcDCDfvwQcQD/SaeXcjPA== X-Google-Smtp-Source: AGHT+IHW7Qd1SAbOSY879BbiErQpR32SX8ht+p3w2HKrir466M04lOt+huUQxcKj+6by6JWF/cRHzQ== X-Received: by 2002:a05:6000:4308:b0:3b7:84fc:ef4c with SMTP id ffacd0b85a97d-3b917d2d303mr2420863f8f.6.1755092323832; Wed, 13 Aug 2025 06:38:43 -0700 (PDT) Received: from xl-nested.c.googlers.com.com (87.220.76.34.bc.googleusercontent.com. [34.76.220.87]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3b8f8b1bc81sm25677444f8f.69.2025.08.13.06.38.43 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 13 Aug 2025 06:38:43 -0700 (PDT) From: Ethan Graham To: ethangraham@google.com, glider@google.com Cc: andreyknvl@gmail.com, brendan.higgins@linux.dev, davidgow@google.com, dvyukov@google.com, jannh@google.com, elver@google.com, rmoar@google.com, shuah@kernel.org, tarasmadan@google.com, kasan-dev@googlegroups.com, kunit-dev@googlegroups.com, linux-kernel@vger.kernel.org, linux-mm@kvack.org Subject: [PATCH v1 RFC 6/6] crypto: implement KFuzzTest targets for PKCS7 and RSA parsing Date: Wed, 13 Aug 2025 13:38:12 +0000 Message-ID: <20250813133812.926145-7-ethan.w.s.graham@gmail.com> X-Mailer: git-send-email 2.51.0.rc0.205.g4a044479a3-goog In-Reply-To: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> References: <20250813133812.926145-1-ethan.w.s.graham@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Ethan Graham Add KFuzzTest targets for pkcs7_parse_message, rsa_parse_pub_key, and rsa_parse_priv_key to serve as real-world examples of how the framework is = used. These functions are ideal candidates for KFuzzTest as they perform complex parsing of user-controlled data but are not directly exposed at the syscall boundary. This makes them difficult to exercise with traditional fuzzing to= ols and showcases the primary strength of the KFuzzTest framework: providing an interface to fuzz internal, non-exported kernel functions. The targets are defined directly within the source files of the functions t= hey test, demonstrating how to colocate fuzz tests with the code under test. Signed-off-by: Ethan Graham --- crypto/asymmetric_keys/pkcs7_parser.c | 15 ++++++++++++++ crypto/rsa_helper.c | 29 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys= /pkcs7_parser.c index 423d13c47545..e8477f8b0eaf 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -13,6 +13,7 @@ #include #include #include +#include #include "pkcs7_parser.h" #include "pkcs7.asn1.h" =20 @@ -169,6 +170,20 @@ struct pkcs7_message *pkcs7_parse_message(const void *= data, size_t datalen) } EXPORT_SYMBOL_GPL(pkcs7_parse_message); =20 +struct pkcs7_parse_message_arg { + const void *data; + size_t datalen; +}; + +FUZZ_TEST(test_pkcs7_parse_message, struct pkcs7_parse_message_arg) +{ + KFUZZTEST_EXPECT_NOT_NULL(pkcs7_parse_message_arg, data); + KFUZZTEST_ANNOTATE_LEN(pkcs7_parse_message_arg, datalen, data); + KFUZZTEST_EXPECT_LE(pkcs7_parse_message_arg, datalen, 16 * PAGE_SIZE); + + pkcs7_parse_message(arg->data, arg->datalen); +} + /** * pkcs7_get_content_data - Get access to the PKCS#7 content * @pkcs7: The preparsed PKCS#7 message to access diff --git a/crypto/rsa_helper.c b/crypto/rsa_helper.c index 94266f29049c..79b7ddc7c48d 100644 --- a/crypto/rsa_helper.c +++ b/crypto/rsa_helper.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "rsapubkey.asn1.h" #include "rsaprivkey.asn1.h" @@ -166,6 +167,20 @@ int rsa_parse_pub_key(struct rsa_key *rsa_key, const v= oid *key, } EXPORT_SYMBOL_GPL(rsa_parse_pub_key); =20 +struct rsa_parse_pub_key_arg { + const void *key; + size_t key_len; +}; + +FUZZ_TEST(test_rsa_parse_pub_key, struct rsa_parse_pub_key_arg) +{ + KFUZZTEST_EXPECT_NOT_NULL(rsa_parse_pub_key_arg, key); + KFUZZTEST_EXPECT_LE(rsa_parse_pub_key_arg, key_len, 16 * PAGE_SIZE); + + struct rsa_key out; + rsa_parse_pub_key(&out, arg->key, arg->key_len); +} + /** * rsa_parse_priv_key() - decodes the BER encoded buffer and stores in the * provided struct rsa_key, pointers to the raw key @@ -184,3 +199,17 @@ int rsa_parse_priv_key(struct rsa_key *rsa_key, const = void *key, return asn1_ber_decoder(&rsaprivkey_decoder, rsa_key, key, key_len); } EXPORT_SYMBOL_GPL(rsa_parse_priv_key); + +struct rsa_parse_priv_key_arg { + const void *key; + size_t key_len; +}; + +FUZZ_TEST(test_rsa_parse_priv_key, struct rsa_parse_priv_key_arg) +{ + KFUZZTEST_EXPECT_NOT_NULL(rsa_parse_priv_key_arg, key); + KFUZZTEST_EXPECT_LE(rsa_parse_priv_key_arg, key_len, 16 * PAGE_SIZE); + + struct rsa_key out; + rsa_parse_priv_key(&out, arg->key, arg->key_len); +} --=20 2.51.0.rc0.205.g4a044479a3-goog