drivers/misc/lkdtm/fortify.c

Source file repositories/reference/linux-study-clean/drivers/misc/lkdtm/fortify.c

File Facts

System
Linux kernel
Corpus path
drivers/misc/lkdtm/fortify.c
Extension
.c
Size
5251 bytes
Lines
200
Domain
Driver Families
Bucket
drivers/misc
Inferred role
Driver Families: implementation source
Status
source implementation candidate

Why This File Exists

Repeatable hardware-adapter layer. Deep compatibility for every driver is out of scope; this atlas records patterns, probe lifecycles, bus glue, IRQ/DMA usage, and links back to core abstractions.

Dependency Surface

Detected Declarations

Annotated Snippet

struct target {
		char a[10];
		char b[10];
	} target;
	volatile int size = 20;
	char *src;

	src = kmalloc(size, GFP_KERNEL);
	if (!src)
		return;

	/* 15 bytes: past end of a[] but not target. */
	strscpy(src, "over ten bytes", size);
	size = strlen(src) + 1;

	pr_info("trying to strscpy() past the end of a struct member...\n");

	/*
	 * strscpy(target.a, src, 15); will hit a compile error because the
	 * compiler knows at build time that target.a < 15 bytes. Use a
	 * volatile to force a runtime error.
	 */
	strscpy(target.a, src, size);

	/* Store result to global to prevent the code from being eliminated */
	fortify_scratch_space = target.a[3];

	pr_err("FAIL: fortify did not block a strscpy() struct member write overflow!\n");
	pr_expected_config(CONFIG_FORTIFY_SOURCE);

	kfree(src);
}

static void lkdtm_FORTIFY_MEM_OBJECT(void)
{
	int before[10];
	struct target {
		char a[10];
		int foo;
	} target = {};
	int after[10];
	/*
	 * Using volatile prevents the compiler from determining the value of
	 * 'size' at compile time. Without that, we would get a compile error
	 * rather than a runtime error.
	 */
	volatile int size = 20;

	memset(before, 0, sizeof(before));
	memset(after, 0, sizeof(after));
	fortify_scratch_space = before[5];
	fortify_scratch_space = after[5];

	pr_info("trying to memcpy() past the end of a struct\n");

	pr_info("0: %zu\n", __builtin_object_size(&target, 0));
	pr_info("1: %zu\n", __builtin_object_size(&target, 1));
	pr_info("s: %d\n", size);
	memcpy(&target, &before, size);

	/* Store result to global to prevent the code from being eliminated */
	fortify_scratch_space = target.a[3];

	pr_err("FAIL: fortify did not block a memcpy() object write overflow!\n");
	pr_expected_config(CONFIG_FORTIFY_SOURCE);
}

static void lkdtm_FORTIFY_MEM_MEMBER(void)
{
	struct target {
		char a[10];
		char b[10];
	} target;
	volatile int size = 20;
	char *src;

	src = kmalloc(size, GFP_KERNEL);
	if (!src)
		return;

	strscpy(src, "over ten bytes", size);
	size = strlen(src) + 1;

	pr_info("trying to memcpy() past the end of a struct member...\n");

	/*
	 * memcpy(target.a, src, 20); will hit a compile error because the
	 * compiler knows at build time that target.a < 20 bytes. Use a
	 * volatile to force a runtime error.
	 */

Annotation

Implementation Notes