// SPDX-License-Identifier: GPL-2.0
/*
 * rootme.c - stand-in for the "root-owned setuid binary the attacker can read
 * but not write" used by the ZDI-CAN-33367 escalation proof.
 *
 * Installed root:root mode 4755.  It grants a root shell only when argv[1]
 * matches the 8-byte gate that lives in its read-only .rodata ("ZDI-OK!").
 *
 * The gate is read through a volatile pointer on purpose: without it the
 * compiler constant-folds the comparison and never touches .rodata, which
 * would make a page-cache patch of that array unobservable.  With the volatile
 * load the byte array really is read at run time from the mapped file page,
 * which is exactly the storage the page-cache corruption primitive rewrites.
 *
 * After gaining real uid 0 it writes a target-local marker file containing the
 * per-attempt token passed as argv[2] (from the kernel command line), so the
 * root command execution is provable from outside the process.
 */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MARKER_PATH "/root/zdi33367_root_marker.txt"

static const char GATE[8] __attribute__((used)) = {
	'Z', 'D', 'I', '-', 'O', 'K', '!', 0
};

static int gate_ok(const char *arg)
{
	const volatile char *gate = GATE;
	int i;

	if (strlen(arg) < 7)
		return 0;
	for (i = 0; i < 7; i++)
		if (arg[i] != gate[i])
			return 0;
	return 1;
}

int main(int argc, char **argv)
{
	if (argc < 2) {
		printf("ROOTME_USAGE uid=%d euid=%d\n", getuid(), geteuid());
		return 1;
	}
	if (!gate_ok(argv[1])) {
		printf("ROOTME_DENIED uid=%d euid=%d\n", getuid(), geteuid());
		return 1;
	}
	if (setgid(0) || setuid(0)) {
		printf("ROOTME_SETUID_FAIL uid=%d\n", getuid());
		return 1;
	}
	printf("ROOTME_GRANTED uid=%d euid=%d\n", getuid(), geteuid());
	{
		const char *token = argc > 2 ? argv[2] : "unset";
		char marker[256];
		int n = snprintf(marker, sizeof(marker), "ZDI33367_ROOT_MARKER_%s", token);
		int fd = open(MARKER_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0600);

		if (fd >= 0 && n > 0 && write(fd, marker, (size_t)n) == n) {
			printf("ROOTME_MARKER_WRITTEN %s %s\n", MARKER_PATH, marker);
			close(fd);
		} else {
			printf("ROOTME_MARKER_FAILED errno=%d\n", errno);
			if (fd >= 0)
				close(fd);
		}
	}
	execl("/bin/sh", "sh", "-c", "id; head -1 /etc/shadow", NULL);
	return 0;
}
