use serde::Serialize;
use crate::parser::cfb_reader::{decompress_stream_limited, CfbReader};
use crate::parser::detect_format;
const STREAM_SCAN_CAP: usize = 32 * 1024 * 1024;
const MAX_RECORDS_SCANNED: usize = 500_000;
const MAX_FINDINGS: usize = 2_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Low,
Medium,
High,
}
impl Severity {
pub fn label(self) -> &'static str {
match self {
Severity::Low => "low",
Severity::Medium => "medium",
Severity::High => "high",
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ThreatFinding {
pub kind: &'static str,
pub severity: &'static str,
pub location: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
pub rationale: String,
}
#[derive(Debug, Clone)]
pub struct ThreatReport {
pub source: String,
pub format: &'static str,
pub scopes: Vec<&'static str>,
pub findings: Vec<ThreatFinding>,
pub notes: Vec<String>,
pub truncated: bool,
}
impl ThreatReport {
pub fn clean(&self) -> bool {
self.findings.is_empty()
}
pub fn highest_severity(&self) -> Option<&'static str> {
self.findings
.iter()
.min_by_key(|f| severity_rank_of(f.severity))
.map(|f| f.severity)
}
}
fn severity_rank_of(label: &str) -> u8 {
match label {
"high" => 0,
"medium" => 1,
_ => 2,
}
}
fn executable_magic(bytes: &[u8]) -> Option<&'static str> {
if bytes.len() < 4 {
return None;
}
if bytes[0] == 0x4D && bytes[1] == 0x5A {
return Some("PE(MZ)");
}
if bytes.starts_with(&[0x7F, 0x45, 0x4C, 0x46]) {
return Some("ELF");
}
if bytes.starts_with(&[0xFE, 0xED, 0xFA, 0xCE])
|| bytes.starts_with(&[0xFE, 0xED, 0xFA, 0xCF])
|| bytes.starts_with(&[0xCF, 0xFA, 0xED, 0xFE])
|| bytes.starts_with(&[0xCE, 0xFA, 0xED, 0xFE])
{
return Some("Mach-O");
}
None
}
fn is_ole_compound(bytes: &[u8]) -> bool {
bytes.len() >= 8 && bytes[..8] == [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]
}
fn looks_remote(target: &str) -> bool {
let t = target.trim();
if t.is_empty() {
return false;
}
let lower = t.to_ascii_lowercase();
lower.starts_with("http://")
|| lower.starts_with("https://")
|| lower.starts_with("ftp://")
|| lower.starts_with("ftps://")
|| lower.starts_with("smb://")
|| lower.starts_with("file://")
|| lower.starts_with("\\\\") || lower.starts_with("//") || lower.contains("://")
}
fn materialize_candidates(raw: Vec<u8>) -> Vec<Vec<u8>> {
let mut out = Vec::new();
let raw_looks_structured = executable_magic(&raw).is_some()
|| is_ole_compound(&raw)
|| raw.starts_with(b"BM")
|| raw.starts_with(&[0x89, 0x50, 0x4E, 0x47]); if !raw_looks_structured {
if let Ok(decoded) = decompress_stream_limited(&raw, STREAM_SCAN_CAP) {
if decoded != raw && !decoded.is_empty() {
out.push(decoded);
}
}
}
out.push(raw);
out
}
struct Collector {
findings: Vec<ThreatFinding>,
notes: Vec<String>,
truncated: bool,
}
impl Collector {
fn new() -> Self {
Collector {
findings: Vec::new(),
notes: Vec::new(),
truncated: false,
}
}
fn push(
&mut self,
kind: &'static str,
severity: Severity,
location: String,
detail: Option<String>,
rationale: String,
) {
if self.findings.len() >= MAX_FINDINGS {
self.truncated = true;
return;
}
self.findings.push(ThreatFinding {
kind,
severity: severity.label(),
location,
detail,
rationale,
});
}
fn note(&mut self, message: String) {
if self.notes.len() < 64 {
self.notes.push(message);
}
}
}
fn scan_embedded_bytes(location: &str, raw: Vec<u8>, col: &mut Collector) {
for bytes in materialize_candidates(raw) {
if let Some(kind) = executable_magic(&bytes) {
col.push(
"embedded_executable",
Severity::High,
location.to_string(),
None,
format!(
"내장 스트림이 실행 파일 매직({kind})으로 시작합니다 — 문서는 실행체를 \
정당하게 내장하지 않습니다. 무기화 첨부의 전형적 형태입니다."
),
);
return;
}
if is_ole_compound(&bytes) {
scan_nested_ole(location, &bytes, col);
return;
}
}
}
fn scan_nested_ole(location: &str, ole_bytes: &[u8], col: &mut Collector) {
let Some(streams) = crate::parser::ole_container::all_ole_streams(ole_bytes) else {
return;
};
let mut flagged_package = false;
let mut flagged_exec = false;
for (name, data) in &streams {
if !flagged_exec {
if let Some(kind) = executable_magic(data) {
col.push(
"embedded_executable",
Severity::High,
format!("{location}»{name}"),
None,
format!(
"내장 OLE 개체 안의 스트림이 실행 파일 매직({kind})을 담고 있습니다 — \
문서에 실행체가 포장돼 있습니다."
),
);
flagged_exec = true;
}
}
if !flagged_package && (name == "\u{0001}Ole10Native" || name.ends_with("Ole10Native")) {
let payload_exec =
ole10native_payload(data).and_then(|p| executable_magic(&p).map(|k| k.to_string()));
let sev = if payload_exec.is_some() {
Severity::High
} else {
Severity::Medium
};
let extra = match &payload_exec {
Some(k) => format!(" 감싼 payload 가 실행 파일 매직({k})입니다."),
None => String::new(),
};
col.push(
"ole_package",
sev,
format!("{location}»Ole10Native"),
None,
format!(
"내장 OLE 개체가 OLE 패키지(Ole10Native)입니다 — 임의 파일·스크립트·실행체를 \
문서에 감싸 넣는 고전적 통로입니다.{extra}"
),
);
flagged_package = true;
}
}
}
fn ole10native_payload(data: &[u8]) -> Option<Vec<u8>> {
if data.len() < 6 {
return None;
}
let mut pos = 6usize;
for _ in 0..3 {
let start = pos;
while pos < data.len() && data[pos] != 0 {
pos += 1;
}
if pos >= data.len() {
return None;
}
pos += 1; let _ = start;
}
if pos + 4 > data.len() {
return None;
}
pos += 4;
if pos >= data.len() {
return None;
}
Some(data[pos..].to_vec())
}
fn scan_records_for_overrun(stream_label: &str, data: &[u8], col: &mut Collector) {
let mut pos = 0usize;
let mut idx = 0usize;
while pos + 4 <= data.len() && idx < MAX_RECORDS_SCANNED {
let header = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
pos += 4;
let tag_id = (header & 0x3FF) as u16;
let mut size = (header >> 20) as u32;
if size == 0xFFF {
if pos + 4 > data.len() {
col.push(
"malformed_record",
Severity::High,
format!("{stream_label}/record[{idx}]"),
None,
format!(
"레코드(tag={tag_id})가 확장 크기 헤더를 선언했지만 스트림이 그 4바이트 \
전에 끝납니다 — 파서 경계를 노리는 잘린 헤더 모양입니다."
),
);
return;
}
size = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
pos += 4;
}
let available = data.len() - pos;
match pos.checked_add(size as usize) {
None => {
col.push(
"malformed_record",
Severity::High,
format!("{stream_label}/record[{idx}]"),
None,
format!(
"레코드(tag={tag_id})가 선언한 크기 {size}바이트가 usize 를 넘겨 오프셋 \
계산이 오버플로합니다 — wasm32 랩어라운드로 경계 검사를 무력화하려는 모양입니다."
),
);
return;
}
Some(end) if end > data.len() => {
col.push(
"malformed_record",
Severity::High,
format!("{stream_label}/record[{idx}]"),
None,
format!(
"레코드(tag={tag_id})가 {size}바이트를 선언했지만 스트림에는 {available}바이트만 \
남았습니다 — 선언 크기가 스트림 밖을 가리키는, 파서 메모리 안전을 노리는 모양입니다."
),
);
return;
}
Some(end) => {
pos = end;
}
}
idx += 1;
}
}
fn scan_hwp5(data: &[u8], col: &mut Collector) -> (&'static str, Vec<&'static str>) {
let scopes = vec![
"binDataStreams",
"oleObjects",
"docInfoRecords",
"bodyTextRecords",
"scriptFlag",
"externalLinks",
];
let mut cfb = match CfbReader::open(data) {
Ok(c) => c,
Err(e) => {
col.note(format!(
"CFB 컨테이너를 열 수 없어 HWP5 구조 스캔을 건너뜁니다: {e}"
));
return ("hwp5", scopes);
}
};
let (compressed, encrypted, distribution, script_flag) = match cfb.read_file_header() {
Ok(hdr) => match crate::parser::header::parse_file_header(&hdr) {
Ok(fh) => (
fh.flags.compressed,
fh.flags.encrypted,
fh.flags.distribution,
fh.flags.script,
),
Err(_) => (true, false, false, false),
},
Err(_) => (true, false, false, false),
};
if script_flag {
col.push(
"macro_script",
Severity::Medium,
"FileHeader.flags.script".to_string(),
None,
"FileHeader 가 스크립트 저장 플래그를 선언했습니다 — 문서가 실행 가능한 \
스크립트(매크로)를 실제로 담고 있다는 한글 자체의 표지입니다."
.to_string(),
);
}
for name in cfb.list_bin_data() {
match cfb.read_bin_data_limited(&name, STREAM_SCAN_CAP) {
Ok(bytes) => scan_embedded_bytes(&format!("BinData/{name}"), bytes, col),
Err(e) => col.note(format!("BinData/{name} 를 깊이 스캔할 수 없습니다: {e}")),
}
}
if encrypted || distribution {
col.note(
"암호화/배포용 문서라 DocInfo·BodyText 내부를 레코드로 읽지 않았습니다(암호문 오탐 방지)."
.to_string(),
);
}
match cfb.read_doc_info_limited(compressed, STREAM_SCAN_CAP) {
Ok(doc_info) => {
if !(encrypted || distribution) {
scan_records_for_overrun("DocInfo", &doc_info, col);
}
if let Ok((di, _)) = crate::parser::doc_info::parse_doc_info(&doc_info) {
for bd in &di.bin_data_list {
if bd.data_type != crate::model::bin_data::BinDataType::Link {
continue;
}
let target = bd
.abs_path
.as_deref()
.filter(|s| looks_remote(s))
.or_else(|| bd.rel_path.as_deref().filter(|s| looks_remote(s)));
if let Some(t) = target {
col.push(
"external_reference",
Severity::Medium,
"DocInfo/BinData[Link]".to_string(),
Some(t.to_string()),
"문서가 원격/UNC 위치의 외부 파일을 링크로 참조합니다 — 열람 시 \
자동으로 외부 자원을 불러오도록 유도하는 형태일 수 있습니다."
.to_string(),
);
}
}
}
}
Err(e) => col.note(format!(
"DocInfo 를 읽을 수 없어 레코드/링크 축을 건너뜁니다: {e}"
)),
}
if !(encrypted || distribution) {
let sections = cfb.section_count();
for i in 0..sections {
match cfb.read_body_text_section_limited(i, compressed, STREAM_SCAN_CAP) {
Ok(sec) => scan_records_for_overrun(&format!("BodyText/Section{i}"), &sec, col),
Err(e) => col.note(format!("BodyText/Section{i} 를 읽을 수 없습니다: {e}")),
}
}
}
("hwp5", scopes)
}
fn scan_hwpx(data: &[u8], col: &mut Collector) -> (&'static str, Vec<&'static str>) {
let scopes = vec![
"binDataEntries",
"oleObjects",
"scriptEntries",
"manifestExternalRefs",
];
let mut reader = match crate::parser::hwpx::reader::HwpxReader::open(data) {
Ok(r) => r,
Err(e) => {
col.note(format!("HWPX ZIP 을 열 수 없어 스캔을 건너뜁니다: {e}"));
return ("hwpx", scopes);
}
};
let names = reader.file_names();
for name in &names {
let norm = name.trim_start_matches('/');
if norm.starts_with("Scripts/") && !norm.ends_with('/') {
col.push(
"macro_script",
Severity::Medium,
name.clone(),
None,
"HWPX 스크립트 엔트리입니다 — 패키지에 스크립트/매크로가 들어 있습니다."
.to_string(),
);
}
}
for name in &names {
let norm = name.trim_start_matches('/');
if norm.starts_with("BinData/") && !norm.ends_with('/') {
match reader.read_file_bytes_limited(name, STREAM_SCAN_CAP) {
Ok(bytes) => scan_embedded_bytes(name, bytes, col),
Err(e) => col.note(format!("{name} 를 깊이 스캔할 수 없습니다: {e}")),
}
}
}
if let Ok(hpf) = reader.read_file("Contents/content.hpf") {
if let Ok(info) = crate::parser::hwpx::content::parse_content_hpf(&hpf) {
for item in &info.bin_data_items {
if looks_remote(&item.href) || (!item.is_embedded && item.href.contains("://")) {
col.push(
"external_reference",
Severity::Medium,
"Contents/content.hpf/manifest".to_string(),
Some(item.href.clone()),
"HWPX 매니페스트가 원격 위치의 외부 자원을 참조합니다 — 열람 시 \
자동으로 외부 자원을 불러오도록 유도하는 형태일 수 있습니다."
.to_string(),
);
}
}
}
}
("hwpx", scopes)
}
pub fn scan_bytes(source: &str, data: &[u8]) -> ThreatReport {
use crate::parser::FileFormat;
let mut col = Collector::new();
let (format, scopes) = match detect_format(data) {
FileFormat::Hwp => scan_hwp5(data, &mut col),
FileFormat::Hwpx => scan_hwpx(data, &mut col),
FileFormat::Hwp3 => {
col.note(
"HWP3(비 CFB) 형식은 이 구조 스캐너의 대상이 아닙니다 — 스캔하지 않았습니다."
.to_string(),
);
("unknown", Vec::new())
}
other => {
col.note(format!(
"HWP/HWPX 컨테이너가 아니라 구조 스캔 대상이 아닙니다(감지: {other:?})."
));
("unknown", Vec::new())
}
};
col.findings.sort_by(|a, b| {
severity_rank_of(a.severity)
.cmp(&severity_rank_of(b.severity))
.then_with(|| a.kind.cmp(b.kind))
.then_with(|| a.location.cmp(&b.location))
.then_with(|| a.detail.cmp(&b.detail))
});
ThreatReport {
source: source.to_string(),
format,
scopes,
findings: col.findings,
notes: col.notes,
truncated: col.truncated,
}
}
pub fn envelope(report: &ThreatReport) -> serde_json::Value {
serde_json::json!({
"schemaVersion": crate::schema_registry::ENVELOPE_SCHEMA_VERSION,
"source": report.source,
"format": report.format,
"scanScopes": report.scopes,
"findings": report.findings,
"findingCount": report.findings.len(),
"highestSeverity": report.highest_severity(),
"clean": report.clean(),
"truncated": report.truncated,
"notes": report.notes,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn executable_magic_detects_pe_elf_macho() {
assert_eq!(executable_magic(b"MZ\x90\x00"), Some("PE(MZ)"));
assert_eq!(executable_magic(&[0x7F, 0x45, 0x4C, 0x46]), Some("ELF"));
assert_eq!(executable_magic(&[0xFE, 0xED, 0xFA, 0xCE]), Some("Mach-O"));
assert_eq!(executable_magic(b"BM\x00\x00"), None);
assert_eq!(executable_magic(b"%PD"), None);
}
#[test]
fn looks_remote_flags_url_and_unc_only() {
assert!(looks_remote("http://evil.example/x.dll"));
assert!(looks_remote("https://evil.example/x"));
assert!(looks_remote("\\\\10.0.0.5\\share\\payload"));
assert!(looks_remote("smb://host/share"));
assert!(!looks_remote("images/logo.png"));
assert!(!looks_remote("..\\rel\\local.bmp"));
assert!(!looks_remote(""));
}
#[test]
fn record_overrun_is_flagged_and_clean_stream_is_not() {
let size: u32 = 2;
let header = 0x10u32 | (size << 20);
let mut clean = header.to_le_bytes().to_vec();
clean.extend_from_slice(&[0xAA, 0xBB]);
let mut col = Collector::new();
scan_records_for_overrun("DocInfo", &clean, &mut col);
assert!(col.findings.is_empty(), "정상 레코드는 신고되면 안 된다");
let header = 0x10u32 | (9999u32 << 20);
let mut bad = header.to_le_bytes().to_vec();
bad.extend_from_slice(&[0xAA, 0xBB]);
let mut col = Collector::new();
scan_records_for_overrun("DocInfo", &bad, &mut col);
assert_eq!(col.findings.len(), 1);
assert_eq!(col.findings[0].kind, "malformed_record");
assert_eq!(col.findings[0].severity, "high");
}
#[test]
fn unknown_format_scans_nothing() {
let report = scan_bytes("x.bin", b"not a document");
assert_eq!(report.format, "unknown");
assert!(report.scopes.is_empty());
assert!(report.clean());
}
}