Extract embedded files from Word docs with original names, selectable output, and a Windows exe build script. Co-authored-by: Cursor <cursoragent@cursor.com>
1047 lines
35 KiB
Python
1047 lines
35 KiB
Python
"""Extract embedded / attached files from Word (.docx, .docm) documents."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import re
|
|
import zipfile
|
|
import xml.etree.ElementTree as ET
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
import olefile
|
|
|
|
WORD_EXTENSIONS = {".docx", ".docm"}
|
|
EMBEDDINGS_PREFIX = "word/embeddings/"
|
|
MEDIA_PREFIX = "word/media/"
|
|
|
|
REL_NS = {"r": "http://schemas.openxmlformats.org/package/2006/relationships"}
|
|
OLE_OBJECT_TYPES = {
|
|
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject",
|
|
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/package",
|
|
}
|
|
|
|
# Names Word/OLE invent that are never the user's original filename.
|
|
_JUNK_NAMES = {
|
|
"attachment",
|
|
"embedded",
|
|
"embedded.bin",
|
|
"embedded.pdf",
|
|
"embedded.doc",
|
|
"embedded.docx",
|
|
"embedded.xls",
|
|
"embedded.xlsx",
|
|
"oleobject.bin",
|
|
"ole package",
|
|
"package",
|
|
"acrobat document",
|
|
"adobe acrobat document",
|
|
"contents",
|
|
"microsoft excel worksheet",
|
|
"microsoft excel worksheet.xlsx",
|
|
"microsoft excel worksheet.xls",
|
|
"microsoft_excel_worksheet",
|
|
"microsoft_excel_worksheet.xlsx",
|
|
"microsoft_excel_worksheet.xls",
|
|
"worksheet",
|
|
"workbook",
|
|
}
|
|
|
|
_FILE_EXT_RE = re.compile(
|
|
r"(?i)\.(pdf|docx?|xlsx?|pptx?|zip|txt|csv|rtf|msg|png|jpe?g|gif|tif{1,2}|bin)$"
|
|
)
|
|
|
|
# ASCII-only filenames scraped from icon images (avoid UTF-16 binary noise).
|
|
_ICON_NAME_RE = re.compile(
|
|
rb"[A-Za-z0-9 ._+()\-,&'[\]]{3,200}\.(?:pdf|docx?|xlsx?|xlsm?|pptx?|zip|txt|csv|rtf|msg)",
|
|
flags=re.IGNORECASE,
|
|
)
|
|
|
|
OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
|
|
|
|
|
@dataclass
|
|
class DiscoveredAttachment:
|
|
"""One extractable attachment found inside a Word document."""
|
|
|
|
id: str
|
|
source_doc: Path
|
|
display_name: str
|
|
zip_path: str
|
|
kind: str # embedding | media | ole
|
|
size_bytes: int
|
|
payload: bytes = field(repr=False)
|
|
note: str = ""
|
|
|
|
|
|
@dataclass
|
|
class ExtractedFile:
|
|
source_doc: Path
|
|
original_name: str
|
|
output_path: Path
|
|
size_bytes: int
|
|
|
|
|
|
@dataclass
|
|
class ExtractResult:
|
|
source_doc: Path
|
|
extracted: list[ExtractedFile]
|
|
skipped: list[str]
|
|
errors: list[str]
|
|
|
|
|
|
def _safe_filename(name: str) -> str:
|
|
name = (name or "").strip().replace("\\", "/").split("/")[-1]
|
|
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", name)
|
|
name = name.strip(". ")
|
|
return name or "attachment"
|
|
|
|
|
|
def _is_junk_name(name: str | None) -> bool:
|
|
if not name:
|
|
return True
|
|
cleaned = _safe_filename(name)
|
|
lower = cleaned.lower()
|
|
if lower in _JUNK_NAMES:
|
|
return True
|
|
# word/embeddings part names like oleObject1.bin / oleObject12.bin
|
|
if re.fullmatch(r"oleobject\d*\.bin", lower):
|
|
return True
|
|
if re.fullmatch(r"image\d+\.(emf|wmf|png|jpe?g|bin)", lower):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _unique_path(directory: Path, filename: str) -> Path:
|
|
path = directory / filename
|
|
if not path.exists():
|
|
return path
|
|
stem = path.stem
|
|
suffix = path.suffix
|
|
counter = 1
|
|
while True:
|
|
candidate = directory / f"{stem}_{counter}{suffix}"
|
|
if not candidate.exists():
|
|
return candidate
|
|
counter += 1
|
|
|
|
|
|
def _carve_pdf(data: bytes) -> bytes | None:
|
|
"""Find a PDF payload inside raw bytes (Acrobat OLE often wraps it)."""
|
|
start = data.find(b"%PDF")
|
|
if start < 0:
|
|
return None
|
|
end = data.rfind(b"%%EOF")
|
|
if end < start:
|
|
return data[start:]
|
|
end = end + 5
|
|
while end < len(data) and data[end] in (0x0A, 0x0D, 0x00, 0x20):
|
|
end += 1
|
|
return data[start:end]
|
|
|
|
|
|
def _carve_zip(data: bytes) -> bytes | None:
|
|
"""Find a ZIP/OOXML payload that may be nested inside an OLE stream."""
|
|
start = data.find(b"PK\x03\x04")
|
|
if start < 0:
|
|
return None
|
|
candidate = data[start:]
|
|
if zipfile.is_zipfile(io.BytesIO(candidate)):
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def _ooxml_extension(data: bytes) -> str | None:
|
|
"""If data is an Office Open XML zip, return .xlsx / .docx / .pptx / etc."""
|
|
if data[:4] != b"PK\x03\x04" and not zipfile.is_zipfile(io.BytesIO(data)):
|
|
carved = _carve_zip(data)
|
|
if not carved:
|
|
return None
|
|
data = carved
|
|
try:
|
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
|
names = {n.lower() for n in zf.namelist()}
|
|
if any(n.startswith("xl/") for n in names):
|
|
if any("vbaproject" in n for n in names):
|
|
return ".xlsm"
|
|
return ".xlsx"
|
|
if any(n.startswith("word/") for n in names):
|
|
return ".docx"
|
|
if any(n.startswith("ppt/") for n in names):
|
|
return ".pptx"
|
|
# content types fallback
|
|
if "[content_types].xml" in names:
|
|
try:
|
|
ct = zf.read("[Content_Types].xml").decode("utf-8", errors="ignore").lower()
|
|
except Exception:
|
|
ct = ""
|
|
if "spreadsheetml" in ct:
|
|
return ".xlsx"
|
|
if "wordprocessingml" in ct:
|
|
return ".docx"
|
|
if "presentationml" in ct:
|
|
return ".pptx"
|
|
except zipfile.BadZipFile:
|
|
return None
|
|
return None
|
|
|
|
|
|
def _ole_stream_names(ole: olefile.OleFileIO) -> set[str]:
|
|
names: set[str] = set()
|
|
for entry in ole.listdir():
|
|
names.add(entry[-1].lstrip("\x01").lower())
|
|
return names
|
|
|
|
|
|
def _detect_kind(data: bytes) -> str:
|
|
"""Return a short kind / extension hint from magic bytes / structure."""
|
|
if not data:
|
|
return "bin"
|
|
if data.startswith(b"%PDF") or 0 <= data.find(b"%PDF") < 2048:
|
|
return "pdf"
|
|
|
|
# OLE before zip checks — Excel .xls files are OLE and can contain stray PK bytes.
|
|
if data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(data)):
|
|
try:
|
|
ole = olefile.OleFileIO(io.BytesIO(data))
|
|
try:
|
|
streams = _ole_stream_names(ole)
|
|
if "workbook" in streams or "book" in streams:
|
|
return "xls"
|
|
if "worddocument" in streams:
|
|
return "doc"
|
|
if "powerpoint document" in streams:
|
|
return "ppt"
|
|
finally:
|
|
ole.close()
|
|
except Exception:
|
|
pass
|
|
return "ole"
|
|
|
|
if data[:4] == b"PK\x03\x04" or zipfile.is_zipfile(io.BytesIO(data)):
|
|
ooxml = _ooxml_extension(data)
|
|
if ooxml:
|
|
return ooxml.lstrip(".")
|
|
return "zip"
|
|
|
|
if data[:2] == b"BM":
|
|
return "bmp"
|
|
if data[:3] == b"\xff\xd8\xff":
|
|
return "jpg"
|
|
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
|
return "png"
|
|
return "bin"
|
|
|
|
|
|
def _extension_for(data: bytes, hint_name: str | None = None) -> str:
|
|
kind = _detect_kind(data)
|
|
kind_to_ext = {
|
|
"pdf": ".pdf",
|
|
"png": ".png",
|
|
"jpg": ".jpg",
|
|
"bmp": ".bmp",
|
|
"xlsx": ".xlsx",
|
|
"xlsm": ".xlsm",
|
|
"docx": ".docx",
|
|
"pptx": ".pptx",
|
|
"xls": ".xls",
|
|
"doc": ".doc",
|
|
"ppt": ".ppt",
|
|
"zip": ".zip",
|
|
}
|
|
if kind in kind_to_ext:
|
|
return kind_to_ext[kind]
|
|
|
|
hint_suffix = ""
|
|
if hint_name:
|
|
hint_suffix = Path(_safe_filename(hint_name)).suffix.lower()
|
|
|
|
if kind == "ole":
|
|
# Never trust an OOXML extension for a raw OLE container.
|
|
if hint_suffix in {".xls", ".doc", ".ppt", ".msg"}:
|
|
return hint_suffix
|
|
return ".bin"
|
|
|
|
if hint_suffix and hint_suffix != ".bin":
|
|
return hint_suffix
|
|
return ".bin"
|
|
|
|
|
|
def _repair_xlsx_for_standalone(data: bytes) -> bytes:
|
|
"""
|
|
Word embeds Excel with workbookView visibility=\"hidden\".
|
|
That still previews in Explorer, but double-click opens a blank/black Excel window.
|
|
Make the workbook viewable when opened on its own.
|
|
"""
|
|
if not zipfile.is_zipfile(io.BytesIO(data)):
|
|
return data
|
|
try:
|
|
source = zipfile.ZipFile(io.BytesIO(data), "r")
|
|
except zipfile.BadZipFile:
|
|
return data
|
|
|
|
try:
|
|
if "xl/workbook.xml" not in source.namelist():
|
|
return data
|
|
workbook_xml = source.read("xl/workbook.xml").decode("utf-8", errors="replace")
|
|
original = workbook_xml
|
|
workbook_xml = re.sub(
|
|
r'\bvisibility="(?:hidden|veryHidden)"',
|
|
'visibility="visible"',
|
|
workbook_xml,
|
|
flags=re.IGNORECASE,
|
|
)
|
|
# If every sheet is hidden, unhide them so Excel has something to show
|
|
sheet_states = re.findall(r'<sheet\b[^>]*>', workbook_xml, flags=re.IGNORECASE)
|
|
if sheet_states and all(re.search(r'\bstate="(?:hidden|veryHidden)"', s, re.I) for s in sheet_states):
|
|
workbook_xml = re.sub(
|
|
r'(<sheet\b[^>]*?)\sstate="(?:hidden|veryHidden)"',
|
|
r"\1",
|
|
workbook_xml,
|
|
flags=re.IGNORECASE,
|
|
)
|
|
if workbook_xml == original:
|
|
return data
|
|
|
|
out = io.BytesIO()
|
|
with zipfile.ZipFile(out, "w") as target:
|
|
for info in source.infolist():
|
|
payload = source.read(info.filename)
|
|
if info.filename == "xl/workbook.xml":
|
|
payload = workbook_xml.encode("utf-8")
|
|
# Keep entries compressible; Excel accepts standard deflate packages
|
|
compress = (
|
|
zipfile.ZIP_STORED
|
|
if info.compress_type == zipfile.ZIP_STORED
|
|
else zipfile.ZIP_DEFLATED
|
|
)
|
|
target.writestr(info.filename, payload, compress_type=compress)
|
|
return out.getvalue()
|
|
except Exception:
|
|
return data
|
|
finally:
|
|
source.close()
|
|
|
|
|
|
def _normalize_payload(data: bytes) -> tuple[bytes, str]:
|
|
"""Return (payload, kind), unwrapping PDFs / OOXML buried in containers."""
|
|
if not data:
|
|
return data, "bin"
|
|
|
|
# Whole OLE compound files must stay intact (.xls/.doc). Nested OOXML is
|
|
# extracted from Package/CONTENTS streams by the OLE walker instead.
|
|
if data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(data)):
|
|
return data, _detect_kind(data)
|
|
|
|
# PDF directly or lightly wrapped
|
|
if data.startswith(b"%PDF") or 0 <= data.find(b"%PDF") < 4096:
|
|
carved_pdf = _carve_pdf(data)
|
|
if carved_pdf:
|
|
return carved_pdf, "pdf"
|
|
|
|
# OOXML / zip
|
|
if data[:4] == b"PK\x03\x04" or zipfile.is_zipfile(io.BytesIO(data)):
|
|
ext = _ooxml_extension(data)
|
|
if ext in {".xlsx", ".xlsm"}:
|
|
return _repair_xlsx_for_standalone(data), ext.lstrip(".")
|
|
if ext:
|
|
return data, ext.lstrip(".")
|
|
return data, "zip"
|
|
|
|
carved_zip = _carve_zip(data)
|
|
if carved_zip:
|
|
ext = _ooxml_extension(carved_zip)
|
|
if ext in {".xlsx", ".xlsm"}:
|
|
return _repair_xlsx_for_standalone(carved_zip), ext.lstrip(".")
|
|
if ext:
|
|
return carved_zip, ext.lstrip(".")
|
|
return carved_zip, "zip"
|
|
|
|
return data, _detect_kind(data)
|
|
|
|
|
|
def _best_name(*candidates: str | None, data: bytes | None = None) -> str:
|
|
ranked: list[str] = []
|
|
for c in candidates:
|
|
if _is_junk_name(c):
|
|
continue
|
|
cleaned = _safe_filename(c) # type: ignore[arg-type]
|
|
# Reject mostly-non-ascii garbage scraped from EMF binaries
|
|
ascii_ratio = sum(1 for ch in cleaned if ord(ch) < 128) / max(len(cleaned), 1)
|
|
if ascii_ratio < 0.8:
|
|
continue
|
|
ranked.append(cleaned)
|
|
|
|
chosen: str | None = None
|
|
if ranked:
|
|
with_ext = [n for n in ranked if _FILE_EXT_RE.search(n)]
|
|
chosen = with_ext[0] if with_ext else ranked[0]
|
|
|
|
if not chosen:
|
|
chosen = "attachment"
|
|
|
|
# Always force extension to match actual payload bytes
|
|
if data is not None:
|
|
ext = _extension_for(data, chosen)
|
|
stem = Path(chosen).stem or "attachment"
|
|
chosen = f"{stem}{ext}"
|
|
|
|
return _safe_filename(chosen)
|
|
|
|
|
|
def _read_cstring(buf: bytes, start: int) -> tuple[str, int] | None:
|
|
end = buf.find(b"\x00", start)
|
|
if end < 0:
|
|
return None
|
|
text = buf[start:end].decode("latin-1", errors="replace")
|
|
return text, end + 1
|
|
|
|
|
|
def _read_len_prefixed_ansi(buf: bytes, start: int) -> tuple[str, int] | None:
|
|
if start + 4 > len(buf):
|
|
return None
|
|
length = int.from_bytes(buf[start : start + 4], "little")
|
|
start += 4
|
|
if length < 0 or start + length > len(buf):
|
|
return None
|
|
raw = buf[start : start + length]
|
|
if raw.endswith(b"\x00"):
|
|
raw = raw[:-1]
|
|
return raw.decode("latin-1", errors="replace"), start + length
|
|
|
|
|
|
def _read_len_prefixed_utf16(buf: bytes, start: int) -> tuple[str, int] | None:
|
|
if start + 4 > len(buf):
|
|
return None
|
|
length = int.from_bytes(buf[start : start + 4], "little")
|
|
start += 4
|
|
if length < 0 or start + length > len(buf):
|
|
return None
|
|
raw = buf[start : start + length]
|
|
if len(raw) >= 2 and raw.endswith(b"\x00\x00"):
|
|
raw = raw[:-2]
|
|
try:
|
|
text = raw.decode("utf-16-le", errors="replace")
|
|
except Exception:
|
|
return None
|
|
return text, start + length
|
|
|
|
|
|
def _parse_ole10_native(data: bytes) -> tuple[str, bytes] | None:
|
|
"""Parse Ole10Native / OLE Package stream into (original_filename, file_bytes)."""
|
|
if len(data) < 10:
|
|
return None
|
|
|
|
offset = 0
|
|
_ = int.from_bytes(data[offset : offset + 4], "little")
|
|
offset += 4
|
|
|
|
if offset + 2 <= len(data):
|
|
sig = int.from_bytes(data[offset : offset + 2], "little")
|
|
if sig == 0x0002:
|
|
offset += 2
|
|
|
|
while offset < len(data) and data[offset] == 0:
|
|
offset += 1
|
|
|
|
label_result = _read_cstring(data, offset)
|
|
if not label_result:
|
|
return None
|
|
label, offset = label_result
|
|
|
|
path_result = _read_cstring(data, offset)
|
|
if not path_result:
|
|
return None
|
|
src_path, offset = path_result
|
|
|
|
unicode_name: str | None = None
|
|
file_bytes: bytes | None = None
|
|
|
|
if offset + 8 <= len(data):
|
|
unused = data[offset : offset + 2]
|
|
fmt = int.from_bytes(data[offset + 2 : offset + 4], "little")
|
|
probe = offset + 4
|
|
temp = _read_len_prefixed_ansi(data, probe)
|
|
if temp is not None and unused == b"\x00\x00" and fmt in (0x0001, 0x0003):
|
|
_temp_path, probe = temp
|
|
if fmt == 0x0003 and probe + 4 <= len(data):
|
|
size = int.from_bytes(data[probe : probe + 4], "little")
|
|
probe += 4
|
|
if 0 <= size <= len(data) - probe:
|
|
file_bytes = data[probe : probe + size]
|
|
probe += size
|
|
u_name = _read_len_prefixed_utf16(data, probe)
|
|
if u_name:
|
|
unicode_name, probe = u_name
|
|
u_path = _read_len_prefixed_utf16(data, probe)
|
|
if u_path and not unicode_name:
|
|
unicode_name = u_path[0]
|
|
|
|
if file_bytes is None:
|
|
classic_off = offset
|
|
if classic_off + 6 > len(data):
|
|
return None
|
|
classic_off += 2
|
|
if classic_off + 4 > len(data):
|
|
return None
|
|
temp_len = int.from_bytes(data[classic_off : classic_off + 4], "little")
|
|
classic_off += 4
|
|
if temp_len < 0 or classic_off + temp_len + 4 > len(data):
|
|
return None
|
|
classic_off += temp_len
|
|
size = int.from_bytes(data[classic_off : classic_off + 4], "little")
|
|
classic_off += 4
|
|
if size < 0 or classic_off + size > len(data):
|
|
return None
|
|
file_bytes = data[classic_off : classic_off + size]
|
|
classic_off += size
|
|
u_name = _read_len_prefixed_utf16(data, classic_off)
|
|
if u_name:
|
|
unicode_name = u_name[0]
|
|
|
|
if not file_bytes:
|
|
return None
|
|
|
|
file_bytes, _kind = _normalize_payload(file_bytes)
|
|
filename = _best_name(unicode_name, label, src_path, data=file_bytes)
|
|
return filename, file_bytes
|
|
|
|
|
|
def _compobj_user_type(ole: olefile.OleFileIO) -> str | None:
|
|
for entry in ole.listdir():
|
|
if entry[-1].lstrip("\x01") == "CompObj":
|
|
try:
|
|
data = ole.openstream(entry).read()
|
|
except Exception:
|
|
return None
|
|
text = data.decode("latin-1", errors="ignore")
|
|
for marker in ("OLE Package", "Package", "Acrobat Document", "Adobe Acrobat Document"):
|
|
if marker in text:
|
|
return marker
|
|
chunk = data[28:]
|
|
end = chunk.find(b"\x00")
|
|
if end > 0:
|
|
return chunk[:end].decode("latin-1", errors="ignore")
|
|
return None
|
|
|
|
|
|
def _filenames_from_icon_bytes(data: bytes) -> list[str]:
|
|
"""
|
|
Pull filename-like strings from EMF/WMF icon images.
|
|
Word often only stores the attachment caption inside these icons.
|
|
"""
|
|
found: list[str] = []
|
|
|
|
# UTF-16LE as ASCII code units only (high bytes zero) — avoids binary noise
|
|
chars: list[str] = []
|
|
for i in range(0, len(data) - 1, 2):
|
|
lo, hi = data[i], data[i + 1]
|
|
if hi == 0 and 32 <= lo < 127:
|
|
chars.append(chr(lo))
|
|
else:
|
|
chars.append("\n")
|
|
utf16_ascii = "".join(chars)
|
|
for match in re.finditer(
|
|
r"[A-Za-z0-9 ._+()\-,&'[\]]{3,200}\.(?:pdf|docx?|xlsx?|xlsm?|pptx?|zip|txt|csv|rtf|msg)",
|
|
utf16_ascii,
|
|
flags=re.IGNORECASE,
|
|
):
|
|
found.append(match.group(0).strip())
|
|
|
|
for match in _ICON_NAME_RE.finditer(data):
|
|
found.append(match.group(0).decode("ascii", errors="ignore").strip())
|
|
|
|
unique: list[str] = []
|
|
for name in sorted({_safe_filename(n) for n in found}, key=len, reverse=True):
|
|
if _is_junk_name(name):
|
|
continue
|
|
if any(u.endswith(name) and u != name for u in unique):
|
|
continue
|
|
unique.append(name)
|
|
return unique
|
|
|
|
|
|
def _extract_from_ole_bin(
|
|
ole_bytes: bytes,
|
|
preferred_name: str | None = None,
|
|
) -> list[tuple[str, bytes, str]]:
|
|
"""Pull packaged files out of an OLE compound document."""
|
|
results: list[tuple[str, bytes, str]] = []
|
|
|
|
def add(fname: str | None, payload: bytes, note: str) -> None:
|
|
payload, _kind = _normalize_payload(payload)
|
|
name = _best_name(preferred_name, fname, data=payload)
|
|
results.append((name, payload, note))
|
|
|
|
# Non-OLE container: still try to carve useful payloads
|
|
if not olefile.isOleFile(io.BytesIO(ole_bytes)):
|
|
payload, kind = _normalize_payload(ole_bytes)
|
|
if kind != "bin":
|
|
add(preferred_name, payload, f"raw {kind}")
|
|
return results
|
|
|
|
try:
|
|
ole = olefile.OleFileIO(io.BytesIO(ole_bytes))
|
|
except Exception:
|
|
payload, kind = _normalize_payload(ole_bytes)
|
|
if kind != "bin":
|
|
add(preferred_name, payload, f"carved {kind}")
|
|
return results
|
|
|
|
try:
|
|
user_type = _compobj_user_type(ole) or ""
|
|
streams = _ole_stream_names(ole)
|
|
|
|
# Classic Excel workbook: the OLE file itself is a valid .xls
|
|
if "workbook" in streams or "book" in streams:
|
|
if "ole10native" not in streams and "package" not in streams:
|
|
add(preferred_name, ole_bytes, "Excel workbook OLE (.xls)")
|
|
return results
|
|
|
|
# Classic Word: whole OLE is a valid .doc
|
|
if "worddocument" in streams and "ole10native" not in streams and "package" not in streams:
|
|
if "contents" not in streams:
|
|
add(preferred_name, ole_bytes, "Word document OLE (.doc)")
|
|
return results
|
|
|
|
for entry in ole.listdir():
|
|
leaf = entry[-1]
|
|
lower_leaf = leaf.lower().lstrip("\x01")
|
|
is_ole10 = "ole10native" in lower_leaf
|
|
is_package = leaf in ("CONTENTS", "Package") or lower_leaf == "package"
|
|
if not is_ole10 and not is_package:
|
|
continue
|
|
|
|
try:
|
|
stream_data = ole.openstream(entry).read()
|
|
except Exception:
|
|
continue
|
|
|
|
if is_ole10:
|
|
parsed = _parse_ole10_native(stream_data)
|
|
if parsed:
|
|
fname, fbytes = parsed
|
|
add(fname, fbytes, "OLE Package")
|
|
else:
|
|
payload, kind = _normalize_payload(stream_data)
|
|
if kind != "bin":
|
|
add(preferred_name, payload, f"carved {kind} from Ole10Native")
|
|
continue
|
|
|
|
# CONTENTS / Package may be OOXML, PDF, or nested OLE
|
|
if stream_data[:8] == OLE_MAGIC or olefile.isOleFile(io.BytesIO(stream_data)):
|
|
nested = _extract_from_ole_bin(stream_data, preferred_name=preferred_name)
|
|
if nested:
|
|
results.extend(nested)
|
|
continue
|
|
|
|
payload, kind = _normalize_payload(stream_data)
|
|
note = user_type or "OLE CONTENTS"
|
|
if kind == "pdf":
|
|
note = "Acrobat / PDF OLE"
|
|
elif kind in {"xlsx", "xlsm"}:
|
|
note = "Excel workbook"
|
|
elif kind == "xls":
|
|
note = "Excel workbook OLE (.xls)"
|
|
elif kind == "docx":
|
|
note = "Word document"
|
|
add(preferred_name, payload, note)
|
|
|
|
if not results:
|
|
# Carve from any stream / whole file
|
|
for entry in ole.listdir():
|
|
try:
|
|
stream_data = ole.openstream(entry).read()
|
|
except Exception:
|
|
continue
|
|
payload, kind = _normalize_payload(stream_data)
|
|
if kind in {"pdf", "xlsx", "xlsm", "docx", "pptx", "zip"}:
|
|
add(preferred_name, payload, f"carved {kind}")
|
|
break
|
|
if not results:
|
|
payload, kind = _normalize_payload(ole_bytes)
|
|
if kind in {"pdf", "xlsx", "xlsm", "docx", "pptx", "xls", "doc"}:
|
|
add(preferred_name, payload, f"carved {kind}")
|
|
elif "excel" in user_type.lower():
|
|
# Excel-tagged OLE with no Package stream: treat as .xls
|
|
add(preferred_name, ole_bytes, "Excel OLE (.xls)")
|
|
finally:
|
|
ole.close()
|
|
|
|
return results
|
|
|
|
|
|
def _is_word_package(path: Path) -> bool:
|
|
return path.suffix.lower() in WORD_EXTENSIONS and zipfile.is_zipfile(path)
|
|
|
|
|
|
def list_word_files(paths: list[Path], recurse: bool = True) -> list[Path]:
|
|
files: list[Path] = []
|
|
for path in paths:
|
|
if path.is_file() and path.suffix.lower() in WORD_EXTENSIONS:
|
|
files.append(path)
|
|
elif path.is_dir():
|
|
pattern = "**/*" if recurse else "*"
|
|
for child in path.glob(pattern):
|
|
if child.is_file() and child.suffix.lower() in WORD_EXTENSIONS:
|
|
files.append(child)
|
|
seen: set[Path] = set()
|
|
unique: list[Path] = []
|
|
for f in sorted(files, key=lambda p: str(p).lower()):
|
|
resolved = f.resolve()
|
|
if resolved not in seen:
|
|
seen.add(resolved)
|
|
unique.append(f)
|
|
return unique
|
|
|
|
|
|
def _local_name(tag: str) -> str:
|
|
if "}" in tag:
|
|
return tag.rsplit("}", 1)[-1]
|
|
return tag
|
|
|
|
|
|
def _normalize_zip_target(target: str) -> str:
|
|
target = target.replace("\\", "/").split("?")[0]
|
|
if target.startswith("/"):
|
|
target = target.lstrip("/")
|
|
if not target.startswith("word/"):
|
|
target = f"word/{target.lstrip('./')}"
|
|
return target
|
|
|
|
|
|
def _relationship_map(zf: zipfile.ZipFile) -> dict[str, tuple[str, str]]:
|
|
"""Map rId -> (zip_target, type) from document relationships."""
|
|
mapping: dict[str, tuple[str, str]] = {}
|
|
rels_path = "word/_rels/document.xml.rels"
|
|
if rels_path not in zf.namelist():
|
|
return mapping
|
|
try:
|
|
root = ET.fromstring(zf.read(rels_path))
|
|
except Exception:
|
|
return mapping
|
|
for rel in root.findall("r:Relationship", REL_NS):
|
|
rid = rel.attrib.get("Id", "")
|
|
target = rel.attrib.get("Target", "")
|
|
rtype = rel.attrib.get("Type", "")
|
|
if rid and target:
|
|
mapping[rid] = (_normalize_zip_target(target), rtype)
|
|
return mapping
|
|
|
|
|
|
def _rid_from_attrs(attrib: dict[str, str]) -> str:
|
|
attrs = {_local_name(k): v for k, v in attrib.items()}
|
|
for key in ("id", "embed", "link"):
|
|
val = attrs.get(key, "")
|
|
if val:
|
|
return val
|
|
for k, v in attrib.items():
|
|
if _local_name(k) in {"id", "embed", "link"} and str(v).startswith("rId"):
|
|
return v
|
|
return ""
|
|
|
|
|
|
def _icon_and_display_names(zf: zipfile.ZipFile) -> dict[str, str]:
|
|
"""
|
|
Map embedding zip path -> best display name.
|
|
Uses OLEObject Name, then the caption text inside the linked icon EMF/WMF.
|
|
"""
|
|
names: dict[str, str] = {}
|
|
rels = _relationship_map(zf)
|
|
if "word/document.xml" not in zf.namelist():
|
|
return names
|
|
|
|
try:
|
|
root = ET.fromstring(zf.read("word/document.xml"))
|
|
except Exception:
|
|
return names
|
|
|
|
# shape id -> image zip path (icon)
|
|
shape_icons: dict[str, str] = {}
|
|
# Collect shapes with imagedata
|
|
for elem in root.iter():
|
|
if _local_name(elem.tag) != "shape":
|
|
continue
|
|
shape_id = ""
|
|
for k, v in elem.attrib.items():
|
|
if _local_name(k) == "id":
|
|
shape_id = v
|
|
break
|
|
if not shape_id:
|
|
continue
|
|
for child in elem.iter():
|
|
if _local_name(child.tag) != "imagedata":
|
|
continue
|
|
rid = _rid_from_attrs(child.attrib)
|
|
if rid in rels:
|
|
shape_icons[shape_id] = rels[rid][0]
|
|
# o:title sometimes has a caption
|
|
for k, v in child.attrib.items():
|
|
if _local_name(k) == "title" and v and not _is_junk_name(v):
|
|
# Title alone isn't tied to ole yet; store on shape via side map later
|
|
shape_icons.setdefault(f"title:{shape_id}", v)
|
|
|
|
# Walk OLEObject elements and pair with their shape icon
|
|
for elem in root.iter():
|
|
if _local_name(elem.tag) not in {"OLEObject", "oleObject"}:
|
|
continue
|
|
|
|
attrs = {_local_name(k): v for k, v in elem.attrib.items()}
|
|
display = attrs.get("Name") or attrs.get("name") or ""
|
|
shape_id = attrs.get("ShapeID") or attrs.get("shapeId") or ""
|
|
rid = _rid_from_attrs(elem.attrib)
|
|
if not rid or rid not in rels:
|
|
continue
|
|
|
|
zip_path = rels[rid][0]
|
|
candidates: list[str] = []
|
|
if display and not _is_junk_name(display):
|
|
candidates.append(display)
|
|
|
|
title_key = f"title:{shape_id}"
|
|
if title_key in shape_icons and not shape_icons[title_key].startswith("word/"):
|
|
candidates.append(shape_icons[title_key])
|
|
|
|
icon_path = shape_icons.get(shape_id)
|
|
if icon_path and icon_path in zf.namelist():
|
|
try:
|
|
icon_bytes = zf.read(icon_path)
|
|
candidates.extend(_filenames_from_icon_bytes(icon_bytes))
|
|
except Exception:
|
|
pass
|
|
|
|
# Pick best candidate (longest real filename wins)
|
|
best = ""
|
|
for c in sorted(candidates, key=lambda s: len(s), reverse=True):
|
|
if not _is_junk_name(c):
|
|
best = _safe_filename(c)
|
|
break
|
|
if best:
|
|
names[zip_path] = best
|
|
|
|
return names
|
|
|
|
|
|
def discover_attachments_in_docx(
|
|
docx_path: Path,
|
|
*,
|
|
include_media: bool = False,
|
|
) -> tuple[list[DiscoveredAttachment], list[str]]:
|
|
"""Scan a Word file and return discoverable attachments (payload kept in memory)."""
|
|
found: list[DiscoveredAttachment] = []
|
|
errors: list[str] = []
|
|
|
|
if not _is_word_package(docx_path):
|
|
return [], [f"Not a valid .docx/.docm file: {docx_path.name}"]
|
|
|
|
try:
|
|
with zipfile.ZipFile(docx_path, "r") as zf:
|
|
names = zf.namelist()
|
|
display_map = _icon_and_display_names(zf)
|
|
embed_names = [
|
|
n for n in names if n.startswith(EMBEDDINGS_PREFIX) and not n.endswith("/")
|
|
]
|
|
media_names = (
|
|
[n for n in names if n.startswith(MEDIA_PREFIX) and not n.endswith("/")]
|
|
if include_media
|
|
else []
|
|
)
|
|
|
|
for zip_path in embed_names:
|
|
try:
|
|
raw = zf.read(zip_path)
|
|
except Exception as exc:
|
|
errors.append(f"{docx_path.name}: failed to read {zip_path}: {exc}")
|
|
continue
|
|
|
|
preferred = display_map.get(zip_path)
|
|
base = Path(zip_path).name
|
|
|
|
if not base.lower().endswith(".bin") and not olefile.isOleFile(io.BytesIO(raw)):
|
|
payload, _kind = _normalize_payload(raw)
|
|
display = _best_name(preferred, base, data=payload)
|
|
found.append(
|
|
DiscoveredAttachment(
|
|
id=f"{docx_path.resolve()}::{zip_path}::0",
|
|
source_doc=docx_path,
|
|
display_name=display,
|
|
zip_path=zip_path,
|
|
kind="embedding",
|
|
size_bytes=len(payload),
|
|
payload=payload,
|
|
)
|
|
)
|
|
continue
|
|
|
|
ole_files = _extract_from_ole_bin(raw, preferred_name=preferred)
|
|
if ole_files:
|
|
for idx, (fname, fbytes, note) in enumerate(ole_files):
|
|
display = _best_name(preferred, fname, data=fbytes)
|
|
found.append(
|
|
DiscoveredAttachment(
|
|
id=f"{docx_path.resolve()}::{zip_path}::{idx}",
|
|
source_doc=docx_path,
|
|
display_name=display,
|
|
zip_path=zip_path,
|
|
kind="ole",
|
|
size_bytes=len(fbytes),
|
|
payload=fbytes,
|
|
note=note,
|
|
)
|
|
)
|
|
else:
|
|
payload, kind = _normalize_payload(raw)
|
|
display = _best_name(preferred, data=payload)
|
|
found.append(
|
|
DiscoveredAttachment(
|
|
id=f"{docx_path.resolve()}::{zip_path}::0",
|
|
source_doc=docx_path,
|
|
display_name=display,
|
|
zip_path=zip_path,
|
|
kind="ole",
|
|
size_bytes=len(payload),
|
|
payload=payload,
|
|
note="Opaque OLE object"
|
|
if kind != "pdf"
|
|
else "PDF carved from OLE container",
|
|
)
|
|
)
|
|
|
|
for zip_path in media_names:
|
|
# Skip EMF/WMF icons that belong to OLE objects — they aren't attachments
|
|
lower = zip_path.lower()
|
|
if lower.endswith((".emf", ".wmf")):
|
|
continue
|
|
try:
|
|
raw = zf.read(zip_path)
|
|
except Exception as exc:
|
|
errors.append(f"{docx_path.name}: failed to read {zip_path}: {exc}")
|
|
continue
|
|
found.append(
|
|
DiscoveredAttachment(
|
|
id=f"{docx_path.resolve()}::{zip_path}::0",
|
|
source_doc=docx_path,
|
|
display_name=_safe_filename(Path(zip_path).name),
|
|
zip_path=zip_path,
|
|
kind="media",
|
|
size_bytes=len(raw),
|
|
payload=raw,
|
|
note="media",
|
|
)
|
|
)
|
|
except zipfile.BadZipFile:
|
|
errors.append(f"Corrupt or unreadable Word file: {docx_path.name}")
|
|
except Exception as exc:
|
|
errors.append(f"Unexpected error on {docx_path.name}: {exc}")
|
|
|
|
return found, errors
|
|
|
|
|
|
def discover_attachments(
|
|
paths: list[Path],
|
|
*,
|
|
include_media: bool = False,
|
|
recurse: bool = True,
|
|
) -> tuple[list[DiscoveredAttachment], list[str]]:
|
|
attachments: list[DiscoveredAttachment] = []
|
|
errors: list[str] = []
|
|
for doc in list_word_files(paths, recurse=recurse):
|
|
found, errs = discover_attachments_in_docx(doc, include_media=include_media)
|
|
attachments.extend(found)
|
|
errors.extend(errs)
|
|
return attachments, errors
|
|
|
|
|
|
def extract_attachments(
|
|
attachments: list[DiscoveredAttachment],
|
|
output_root: Path | None = None,
|
|
*,
|
|
per_document_subfolder: bool = True,
|
|
) -> list[ExtractResult]:
|
|
"""Write selected discovered attachments to disk."""
|
|
by_doc: dict[Path, list[DiscoveredAttachment]] = {}
|
|
for item in attachments:
|
|
by_doc.setdefault(item.source_doc, []).append(item)
|
|
|
|
multi = len(by_doc) > 1
|
|
results: list[ExtractResult] = []
|
|
|
|
for doc, items in by_doc.items():
|
|
extracted: list[ExtractedFile] = []
|
|
errors: list[str] = []
|
|
|
|
if output_root is None:
|
|
dest = doc.parent / f"{doc.stem}_attachments"
|
|
elif per_document_subfolder and multi:
|
|
dest = output_root / _safe_filename(doc.stem)
|
|
else:
|
|
dest = output_root
|
|
|
|
try:
|
|
dest.mkdir(parents=True, exist_ok=True)
|
|
except Exception as exc:
|
|
results.append(
|
|
ExtractResult(doc, [], [], [f"Cannot create output folder: {exc}"])
|
|
)
|
|
continue
|
|
|
|
for item in items:
|
|
try:
|
|
# Final safety: never write a PDF payload as .bin
|
|
name = _best_name(item.display_name, data=item.payload)
|
|
out = _unique_path(dest, name)
|
|
out.write_bytes(item.payload)
|
|
extracted.append(
|
|
ExtractedFile(doc, name, out, len(item.payload))
|
|
)
|
|
except Exception as exc:
|
|
errors.append(f"Failed to save {item.display_name}: {exc}")
|
|
|
|
results.append(ExtractResult(doc, extracted, [], errors))
|
|
|
|
return results
|
|
|
|
|
|
def extract_from_docx(
|
|
docx_path: Path,
|
|
output_dir: Path,
|
|
*,
|
|
include_media: bool = False,
|
|
) -> ExtractResult:
|
|
found, scan_errors = discover_attachments_in_docx(
|
|
docx_path, include_media=include_media
|
|
)
|
|
if not found and scan_errors:
|
|
return ExtractResult(docx_path, [], [], scan_errors)
|
|
if not found:
|
|
return ExtractResult(docx_path, [], ["No embedded attachments found"], [])
|
|
result = extract_attachments(found, output_root=output_dir, per_document_subfolder=False)[0]
|
|
result.errors = scan_errors + result.errors
|
|
return result
|
|
|
|
|
|
def extract_from_paths(
|
|
paths: list[Path],
|
|
output_root: Path | None = None,
|
|
*,
|
|
include_media: bool = False,
|
|
recurse: bool = True,
|
|
per_document_subfolder: bool = True,
|
|
) -> list[ExtractResult]:
|
|
found, errors = discover_attachments(
|
|
paths, include_media=include_media, recurse=recurse
|
|
)
|
|
results = extract_attachments(
|
|
found,
|
|
output_root=output_root,
|
|
per_document_subfolder=per_document_subfolder,
|
|
)
|
|
if errors and results:
|
|
results[0].errors = errors + results[0].errors
|
|
elif errors:
|
|
for path in list_word_files(paths, recurse=recurse):
|
|
doc_errs = [e for e in errors if path.name in e]
|
|
results.append(ExtractResult(path, [], [], doc_errs or errors))
|
|
break
|
|
return results
|