GrepBoard/매뉴얼
605 편 ·

GGUF 파일 점검: chat template 과 파일 끝 숨은 데이터

·시험 환경 Docker python:3.12-slim · Python 3.12.16 · gguf 0.19.0·시험 범위 ↓·4 단계

받은 GGUF 를 실행하기 전에 chat template 전체를 이스케이프한 글자로 읽습니다. 마지막 텐서 끝과 파일 크기를 대조해 정렬 여백을 제외한 추가 바이트를 셉니다.

11월 27일 연구자는 Hugging Face 공개 모델 저장소에서 악성 GGUF 모델 5개를 찾아 다운로드 합계 2,428회를 집계했다고 발표했습니다. 한 묶음은 파일 끝에 데이터를 숨기고 chat template 으로 답변 첫머리에 명령을 내보내도록 유도했습니다. 다른 묶음은 정상 템플릿 끝부분에 한 줄을 더해 코딩 에이전트의 도구 호출을 노렸습니다. 연구자 원문

[1] Bash 에서 점검 폴더를 만듭니다. 설치 컨테이너에는 패키지 폴더만 연결합니다.

bash
mkdir gguf-check && cd gguf-check && mkdir deps && \timeout 180 docker run --rm --name gguf-file-hidden-data-chat-template-check-deps \  --memory 1g --cpus 2 --user "$(id -u):$(id -g)" \  --mount "type=bind,\"source=${PWD//\"/\"\"}/deps\",target=/deps" python:3.12-slim \  python -m pip install --disable-pip-version-check --no-cache-dir --no-compile \  --index-url https://pypi.org/simple --target /deps gguf==0.19.0

[2] 아래를 check_gguf.py 로 저장합니다. tokenizer.chat_template 로 시작하는 모든 키의 문자열을 이스케이프해 전부 표시합니다. 각 텐서의 파일 기준 오프셋에 텐서 바이트 수를 더한 최댓값이 tensor_end 입니다. 판독기가 데이터 시작점을 구할 때 정렬을 반영합니다. GGUF 명세 · gguf 0.19.0

check_gguf.py
import loggingimport sysimport unicodedata from gguf import GGUFReader, GGUFValueType  def show_template(reader):    prefix = "tokenizer.chat_template"    fields = [(key, field) for key, field in reader.fields.items() if key.startswith(prefix)]    if not fields:        print(f"{prefix}: absent")    for key, field in fields:        if field.types != [GGUFValueType.STRING]:            raise ValueError(f"Unexpected type for {ascii(key)}")        show_text(key, field.contents())  def show_text(key, template):    lines = template.split("\n")    print(f"{ascii(key)}: lines={len(lines)} chars={len(template)} (LF separates lines)")    width = 160    for number, line in enumerate(lines, 1):        parts = max(1, (len(line) + width - 1) // width)        control = any(unicodedata.category(ch) in {"Cc", "Cf"} for ch in line)        for part in range(parts):            flags = [f"long; part {part + 1}/{parts}"] if parts > 1 else []            if control:                flags.append("control/format")            label = f" [{', '.join(flags)}]" if flags else ""            chunk = line[part * width:(part + 1) * width]            print(f"  {number}{label}: {ascii(chunk)}")  def inspect(path):    reader = GGUFReader(path, mode="r")    if not reader.tensors:        print("No tensors; EOF comparison unavailable")        show_template(reader)        return     size = reader.data.size    alignment = int(reader.alignment)    if alignment < 8 or alignment % 8:        raise ValueError("invalid alignment")    data_start = int(reader.data_offset)    ends = []    for tensor in reader.tensors:        start = tensor.data_offset        end = start + tensor.n_bytes        if start < data_start or (start - data_start) % alignment or end > size:            raise ValueError("invalid tensor extent")        ends.append(end)    end = max(ends)    aligned_end = end + (-end % alignment)    padding = 0    if aligned_end <= size and not reader.data[end:aligned_end].any():        padding = aligned_end - end     print(f"alignment={alignment} tensor_end={end} aligned_end={aligned_end}")    print(f"file_bytes={size} zero_eof_padding={padding} extra_bytes={size - end - padding}")    show_template(reader)  if __name__ == "__main__":    if len(sys.argv) != 2:        sys.exit("Usage: check_gguf.py FILE.gguf")    logging.disable(logging.CRITICAL)    try:        inspect(sys.argv[1])    except KeyError as error:        if str(error.args[0]).startswith("Duplicate "):            print("Duplicate GGUF key; templates unavailable", file=sys.stderr)        sys.exit("Inspection failed; no reliable result")    except Exception:        sys.exit("Inspection failed; no reliable result")

[3] 네트워크를 차단한 컨테이너에서 점검합니다. 이미 받은 모델 파일을 원래 위치에서 읽기 전용으로 연결합니다. 파일명에 공백이나 쉼표가 있으면 아래처럼 경로 전체를 따옴표로 감쌉니다.

bash
scan() {  local model code=0  IFS= read -r -d '' model < <(realpath -ez -- "$1") || return  timeout 600 docker run --rm --init --pull never --name gguf-file-hidden-data-chat-template-check-scan \    --network none --memory 4g --cpus 2 --read-only --cap-drop ALL \    --security-opt no-new-privileges --user "$(id -u):$(id -g)" \    --mount "type=bind,\"source=${PWD//\"/\"\"}\",target=/work,readonly" \    --mount "type=bind,\"source=${model//\"/\"\"}\",target=/input.gguf,readonly" \    -e PYTHONPATH=/work/deps python:3.12-slim python -B /work/check_gguf.py /input.gguf || code=$?  if ((code)); then    printf 'No result (exit %s); file safety was not established.\n' "$code" >&2  fi  return "$code"}
console
$ scan '/path/to/model name, quant.gguf'

출력이 길면 scan '/path/to/model name, quant.gguf' > scan.txt 2>&1 로 저장해 텍스트 편집기에서 읽습니다.

[4] extra_bytes 와 템플릿을 함께 봅니다. 기본 정렬은 32바이트이고 general.alignment 가 있으면 그 값을 씁니다. 텐서 끝부터 다음 정렬 경계까지 모두 영 바이트로 채워져 있을 때만 그 구간을 zero_eof_padding 으로 셉니다. 경계에 못 미치는 짧은 꼬리나 다른 값이 섞인 여백은 extra_bytes 에 포함합니다.

직접 만든 시험 파일은 텐서 2개와 평범한 chat template 을 담았습니다.

console
$ scan clean.gguf
output
alignment=32 tensor_end=308 aligned_end=320file_bytes=320 zero_eof_padding=12 extra_bytes=0'tokenizer.chat_template': lines=3 chars=55 (LF separates lines)  1: '{% for m in messages %}'  2: "{{ m['content'] }}"  3: '{% endfor %}'

같은 파일 끝에 무해한 글자와 줄바꿈을 10바이트 덧붙인 사본입니다. 출력 앞 두 줄에서 텐서 끝과 0 여백은 그대로이고 extra_bytes 만 10입니다.

console
$ scan appended.gguf
output
alignment=32 tensor_end=308 aligned_end=320file_bytes=330 zero_eof_padding=12 extra_bytes=10…

64바이트 정렬을 지정한 별도 파일에는 92번째 줄과 4,000자가 넘는 줄의 끝에 무해한 표식을 넣었습니다. 키마다 줄 수와 글자 수를 먼저 표시하고, 긴 줄은 part 번호를 붙여 160자씩 모두 보여 줍니다. 출력에서 가운데를 줄였습니다.

console
$ scan 'display case, sample.gguf'
output
…'tokenizer.chat_template': lines=93 chars=5674 (LF separates lines)…  4 [control/format]: '{#\t\u202e #}'…  92: '{# LATE-LINE-92 #}'…  93 [long; part 26/26]: 'AAAAAAAA LONG-LINE-END #}''tokenizer.chat_template.review': lines=1 chars=20 (LF separates lines)  1: '{# NAMED-TEMPLATE #}'

확인할 때 헷갈리는 곳

  • extra_bytes=0 이어도 안전은 보장되지 않습니다. 텐서 데이터 앞 정렬 여백, 가중치 내부, 텐서 사이 여백은 검사 범위 밖입니다. 분할 모델은 파일마다 점검합니다. 조각의 누락·조합과 별도 파일의 템플릿은 확인하지 않습니다. 텐서가 없는 파일은 템플릿만 표시합니다. 연구자 원문 4절
  • gguf 0.19.0 판독기는 중복 키에서 멈춥니다. 시험 파일에서도 Duplicate GGUF key; templates unavailable 뒤에 No result 가 나왔습니다. 이 경우 중복 항목의 값은 볼 수 없습니다. 명시된 정렬값도 2 의 거듭제곱이어야 판독기가 읽습니다. gguf 0.19.0 배포 소스
  • Hugging Face 의 Ollama 문서에 따르면 내장 chat template 은 실행 시 템플릿 선택에 쓰입니다. 모델을 이미 불러왔거나 명령을 따라 쳤다면 모델이 제안하는 명령을 더 실행하지 않습니다. 지표를 대조할 때는 연구자 원문의 「7.2 Indicators of Compromise」 절을 봅니다. Hugging Face Ollama 문서 · 연구자 권고

Ollama 에서 받은 파일의 위치를 모르면 Ollama 모델 저장 위치의 기본 경로를 확인합니다.

#gguf#chat-template#model-security#hugging-face#ollama