💾 Archived View for thrig.me › software › assembly › slab-of-code › pledge.c captured on 2023-12-28 at 17:28:16.

View Raw

More Information

-=-=-=-=-=-=-

#include <sys/mman.h>

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

typedef void (*fn)(void);

#define SLABSIZE 4096

int
main(int argc, char *argv[])
{
	int value = 41;

	unsigned char *slab = malloc(SLABSIZE);
	if (!slab) err(1, "malloc");

	memset(slab, 0xC3, SLABSIZE); // RET
	slab[0] = 0x90;               // how about a NOP sled to the RET?
	slab[1] = 0x90;
	slab[3] = 0x90;

	int fd = open("slab", O_WRONLY | O_CREAT, 0666);
	if (fd >= 0) {
		write(fd, slab, SLABSIZE);
		close(fd);
	}

	if (mprotect(slab, SLABSIZE, PROT_EXEC) != 0) err(1, "mprotect");
#ifdef __OpenBSD__
	if (pledge("stdio", NULL) == -1) err(1, "pledge");
#endif

	fn call = (fn) slab;
	call();

	printf("%d\n", value);
}