#!/usr/bin/env bash
# lab6b/make-benign-sample.sh
# Produces a synthetic, COMPLETELY BENIGN "training binary" for Lab 17.6b.
# The script writes a tiny Python-compiled .pyc or a stub PE-header marker
# for use with static analysis exercises.
#
# SAFETY: this is NOT malware. It writes a text file whose first two bytes are
# the EICAR test string prefix so that YARA exercises can match on it, plus
# stub indicators (fake URL, fake mutex) for string-extraction practice.
# It will NOT execute as a real PE. It is intended for educational use only.

set -euo pipefail
OUT="${1:-/analysis/training-sample.bin}"

python3 - <<'PYEOF'
import struct, os, sys

out_path = sys.argv[1] if len(sys.argv) > 1 else "/analysis/training-sample.bin"

# Build a minimal stub that exercises static analysis:
# - MZ header (DOS stub) so pefile can parse it
# - Fake imports section referencing common API names
# - Fake strings: URL, mutex, registry path
# This binary cannot execute -- it has no valid PE optional header beyond the stub.
# It is purely for string/header extraction practice.

MZ_MAGIC = b"MZ"
FAKE_PE_STUB = b"\x00" * 58 + struct.pack("<I", 64)   # e_lfanew = 64
PE_SIG = b"PE\x00\x00"

fake_strings = (
    b"\x00TRAINING_SAMPLE_BENIGN_DO_NOT_SUBMIT\x00"
    b"\x00http://lab.invalid/c2-callback\x00"
    b"\x00Global\\LabMutex_Training\x00"
    b"\x00SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\x00"
    b"\x00WriteProcessMemory\x00"
    b"\x00VirtualAllocEx\x00"
    b"\x00CreateRemoteThread\x00"
    b"\x00WS2_32.dll\x00"
    b"\x00KERNEL32.dll\x00"
)

content = MZ_MAGIC + FAKE_PE_STUB + PE_SIG + fake_strings
content += b"\x00" * (512 - len(content) % 512)  # pad to sector boundary

os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
with open(out_path, "wb") as f:
    f.write(content)

print(f"[*] Benign training sample written to {out_path} ({len(content)} bytes)")
print("[*] SHA256:", __import__("hashlib").sha256(content).hexdigest())
PYEOF
