/*
 * acfg-vulnerable.c -- the ACFG parser, with one deliberately planted
 *                      memory-safety bug.
 *
 * Chapter 70 -- Vulnerability Research, examples/
 *
 * BUILD (host, WSL / Linux / macOS):
 *   gcc -std=c11 -Wall -Wextra -g -O1 -fsanitize=address,undefined \
 *       -fno-omit-frame-pointer -c acfg-vulnerable.c -o acfg-vulnerable.o
 *
 * BUILD (host, Android cross-compile with the NDK, for an emulator or a
 *        device you own -- see ../README.md section 7.6 before you do this):
 *   $NDK/bin/x86_64-linux-android24-clang -std=c11 -Wall -Wextra -g -O1 \
 *       -fsanitize=fuzzer-no-link,address -c acfg-vulnerable.c
 *
 * Or just run ./build.sh, which does every variant and reports which ones the
 * toolchain on this machine can actually produce.
 *
 * THE PLANTED BUG
 *   Search for the comment banner "PLANTED BUG" below. It is a missing
 *   destination-size check on a memcpy: the parser correctly verifies that the
 *   name bytes are PRESENT in the input, and then copies them into a fixed
 *   32-byte destination without verifying that they FIT.
 *
 *   That distinction -- "are the bytes there?" versus "do the bytes fit?" -- is
 *   the single most common shape of a real parser memory-safety bug. The
 *   truncation check is the one a developer remembers to write, because
 *   forgetting it produces an immediate out-of-bounds READ of the input and
 *   therefore obvious garbage. The destination check is the one that gets
 *   forgotten, because forgetting it produces a WRITE that usually appears to
 *   work.
 *
 * WHY THIS FILE EXISTS
 *   You cannot practise triage on a bug whose ground truth you do not know.
 *   Every crash you get from this file has a known cause, so when your triage
 *   verdict disagrees with the plant, the verdict is wrong -- and finding out
 *   why is the lesson. Real targets do not offer that feedback.
 *
 * WHAT THIS WILL NOT TELL YOU
 *   Nothing about this bug's severity transfers to a real target. It is planted
 *   at the top of the parse loop, reachable from the first byte of input, with
 *   no state machine in front of it. Real bugs sit behind four state
 *   transitions and a checksum. See section 11.2.
 */

#include "acfg.h"

#include <stdlib.h>
#include <string.h>

/* Little-endian 16-bit read. Written byte-wise rather than as a cast through
 * `uint16_t *` on purpose: the cast version is both an alignment bug on some
 * targets and an endianness bug on others, and UBSan's `alignment` check will
 * flag it. Parsers that do this are extremely common in the wild. */
static uint16_t rd16le(const uint8_t *p)
{
    return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8));
}

static int type_is_known(uint8_t t)
{
    return t == ACFG_T_STRING || t == ACFG_T_INT ||
           t == ACFG_T_BOOL   || t == ACFG_T_BLOB;
}

const char *acfg_strerror(int rc)
{
    switch (rc) {
    case ACFG_OK:         return "ok";
    case ACFG_E_ARG:      return "null argument";
    case ACFG_E_SHORT:    return "input shorter than header";
    case ACFG_E_MAGIC:    return "bad magic";
    case ACFG_E_VERSION:  return "unsupported version";
    case ACFG_E_TRUNC:    return "record truncated";
    case ACFG_E_TYPE:     return "unknown record type";
    case ACFG_E_VALUE:    return "value too large";
    case ACFG_E_NAME:     return "name too long";
    case ACFG_E_NOMEM:    return "out of memory";
    default:              return "unknown";
    }
}

void acfg_free(acfg_blob *out)
{
    uint16_t i;

    if (out == NULL || out->records == NULL) {
        if (out != NULL) {
            out->records = NULL;
            out->count = 0;
            out->built = 0;
        }
        return;
    }

    /* Free only what was actually built. Using `count` here instead of `built`
     * would be a second bug in its own right on the error path -- calloc gives
     * NULL pointers so free(NULL) is harmless, but the moment anyone switches
     * calloc to malloc it becomes an uninitialised free. Section 5.4. */
    for (i = 0; i < out->built; i++) {
        free(out->records[i].value);
        out->records[i].value = NULL;
    }

    free(out->records);
    out->records = NULL;
    out->count = 0;
    out->built = 0;
}

int acfg_parse(const uint8_t *buf, size_t len, acfg_blob *out)
{
    size_t   off;
    uint16_t i;
    uint16_t version, count;

    if (buf == NULL || out == NULL)
        return ACFG_E_ARG;

    memset(out, 0, sizeof(*out));

    /* --- file header ------------------------------------------------- */

    if (len < ACFG_HEADER_SIZE)
        return ACFG_E_SHORT;

    if (memcmp(buf, "ACFG", 4) != 0)
        return ACFG_E_MAGIC;

    version = rd16le(buf + 4);
    count   = rd16le(buf + 6);

    if (version != 1)
        return ACFG_E_VERSION;

    out->version = version;
    out->count   = count;
    out->built   = 0;

    if (count == 0)
        return ACFG_OK;

    /* An allocation whose size is a 16-bit attacker-controlled count times a
     * fixed struct size cannot overflow, because 65535 * sizeof(acfg_record)
     * is about 3 MB. If `count` were 32-bit this multiplication would itself
     * be the bug -- that is the classic calloc-overflow shape, and it is why
     * calloc's two-argument form exists at all. Section 5.2. */
    out->records = (acfg_record *)calloc(count, sizeof(acfg_record));
    if (out->records == NULL)
        return ACFG_E_NOMEM;

    /* --- records ----------------------------------------------------- */

    off = ACFG_HEADER_SIZE;

    for (i = 0; i < count; i++) {
        acfg_record *rec = &out->records[i];
        uint8_t  type, nlen;
        uint16_t vlen;

        /* Record header must be present. `off` is size_t and both operands are
         * small, so this addition cannot wrap on any target with a 64-bit
         * size_t. On a 32-bit target with a 4 GB input it could -- which is
         * why real audits ask what the widths are before trusting a check. */
        if (off + ACFG_REC_HEADER_SIZE > len) {
            acfg_free(out);
            return ACFG_E_TRUNC;
        }

        type = buf[off + 0];
        nlen = buf[off + 1];
        vlen = rd16le(buf + off + 2);
        off += ACFG_REC_HEADER_SIZE;

        if (!type_is_known(type)) {
            acfg_free(out);
            return ACFG_E_TYPE;
        }

        if (vlen > ACFG_MAX_VALUE) {
            acfg_free(out);
            return ACFG_E_VALUE;
        }

        /* Truncation check: are the name and value bytes actually present in
         * the input? This one is CORRECT. Both lengths are widened to size_t
         * before the addition, so nothing wraps. */
        if (off + (size_t)nlen + (size_t)vlen > len) {
            acfg_free(out);
            return ACFG_E_TRUNC;
        }

        rec->type = type;

        /* ================================================================
         *                          PLANTED BUG
         * ================================================================
         * `nlen` is an attacker-controlled byte with range 0..255.
         * `rec->name` is ACFG_NAME_MAX == 32 bytes.
         *
         * The check that is MISSING here is:
         *
         *     if (nlen >= ACFG_NAME_MAX) { acfg_free(out); return ACFG_E_NAME; }
         *
         * Without it, memcpy writes up to 255 bytes into a 32-byte field, and
         * the following store of the terminator writes one byte further still.
         *
         * Note what the check above DID validate. It proved the source bytes
         * exist. It said nothing whatsoever about the destination. A reviewer
         * skimming for "is there a bounds check?" sees one, three lines up,
         * and moves on. That is precisely how this bug class survives review.
         *
         * MEASURED, not assumed. Built with gcc 11.4.0,
         * `-fsanitize=address,undefined -O1`, and run. One defect produces
         * three completely different outcomes depending on `count` and `nlen`:
         *
         *   count == 1, nlen > 32
         *               The overflow runs off the end of the calloc block.
         *               ASan reports a clean heap-buffer-overflow WRITE.
         *               Process dies, exit code 1. This is the loud case.
         *
         *   count == 1, nlen == 32
         *               The 32 name bytes fit; only the terminator at
         *               name[32] is out of bounds -- and it lands at struct
         *               offset 33, still INSIDE the 56-byte allocation.
         *               ASan is silent. UBSan's array-bounds check reports
         *               "index 32 out of bounds for type 'char [32]'" and,
         *               being non-fatal by default, LETS THE PROCESS CONTINUE.
         *               Exit code 0. A campaign that only watches exit codes
         *               records this as a clean run.
         *
         *   count >= 2, 32 < nlen < 56ish
         *               The overflow lands inside the same calloc block, on
         *               top of record[0].value and record[0].value_len.
         *               ASan says NOTHING -- it places no redzone between two
         *               structs inside one allocation. And the corrupted
         *               fields are then OVERWRITTEN a few lines below by this
         *               same iteration's own assignments, so there is no
         *               functional consequence either. Measured with
         *               count == 4, nlen == 40: exit code 0, one UBSan line,
         *               no ASan report, correct output.
         *
         * The third case is the one worth sitting with. It is the identical
         * out-of-bounds write, it is genuinely undefined behaviour, and on a
         * different compiler, a different struct layout, or a `count` chosen
         * to place a live pointer under the write, it would be a serious bug.
         * Here it is invisible. If the corpus that found this bug had happened
         * to carry count == 4 rather than count == 1, the campaign would have
         * returned "no findings".
         *
         * One bug, three outcomes, two of them silent under the sanitizer most
         * people run alone. Chapter 70 section 3.7 and lab 03 are built on
         * this: it is why crash count is not bug count in either direction,
         * and why "we fuzzed it and it was clean" is a statement about the
         * corpus, not about the code.
         * ================================================================
         */
        memcpy(rec->name, buf + off, nlen);
        rec->name[nlen] = '\0';

        off += nlen;

        /* Value. malloc(0) is allowed to return either NULL or a unique
         * pointer; treating a NULL return as failure here would be a bug on
         * the platforms that return NULL for zero. Hence the length guard. */
        if (vlen > 0) {
            rec->value = (uint8_t *)malloc(vlen);
            if (rec->value == NULL) {
                acfg_free(out);
                return ACFG_E_NOMEM;
            }
            memcpy(rec->value, buf + off, vlen);
        } else {
            rec->value = NULL;
        }
        rec->value_len = vlen;

        off += vlen;

        /* Record i is now fully initialised, so acfg_free may release it. This
         * counter is incremented AFTER the last allocation in the iteration,
         * never before. Getting that order wrong is how "free of an
         * uninitialised pointer" bugs are written. */
        out->built = (uint16_t)(i + 1);
    }

    return ACFG_OK;
}
