audit_pptx.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. #!/usr/bin/env python3
  2. """Audit PPTX format metadata: layouts, themes, fonts, colors, hyperlinks, embedded objects, and security labels.
  3. Outputs structured JSON covering:
  4. - Document properties (docProps/core.xml, docProps/app.xml)
  5. - Slide master and layout inventory with usage counts
  6. - Theme colors and fonts
  7. - Per-slide shape inventory with position/size/font/color details
  8. - Hyperlinks across all slides
  9. - Embedded objects and OLE items
  10. - MSIP / sensitivity labels (if present)
  11. Usage:
  12. python audit_pptx.py <path_to_pptx>
  13. python audit_pptx.py <path_to_pptx> --sections all
  14. python audit_pptx.py <path_to_pptx> --sections metadata,themes,hyperlinks
  15. python audit_pptx.py <path_to_pptx> --slides 1,3,5
  16. python audit_pptx.py <path_to_pptx> --format text
  17. Sections: metadata, masters, themes, shapes, hyperlinks, embedded, security
  18. Default: all sections.
  19. Requires: python-pptx (pip install python-pptx)
  20. """
  21. from __future__ import annotations
  22. import argparse
  23. import json
  24. import os
  25. import re
  26. import sys
  27. import zipfile
  28. from collections import Counter, defaultdict
  29. from dataclasses import asdict, dataclass, field
  30. from typing import Any
  31. from xml.etree import ElementTree as ET
  32. # ---------------------------------------------------------------------------
  33. # Namespace helpers
  34. # ---------------------------------------------------------------------------
  35. NS = {
  36. "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
  37. "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
  38. "p": "http://schemas.openxmlformats.org/presentationml/2006/main",
  39. "cp": "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
  40. "dc": "http://purl.org/dc/elements/1.1/",
  41. "dcterms": "http://purl.org/dc/terms/",
  42. "ep": "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
  43. "ct": "http://schemas.openxmlformats.org/package/2006/content-types",
  44. "rel": "http://schemas.openxmlformats.org/package/2006/relationships",
  45. "msip": "http://schemas.microsoft.com/office/2020/02/relationships/classificationlabel",
  46. }
  47. def _text(el: ET.Element | None) -> str | None:
  48. if el is None:
  49. return None
  50. return el.text
  51. def _emu_to_inches(emu: int | str | None) -> float | None:
  52. if emu is None:
  53. return None
  54. return round(int(emu) / 914400, 4)
  55. # ---------------------------------------------------------------------------
  56. # Section extractors
  57. # ---------------------------------------------------------------------------
  58. def extract_metadata(zf: zipfile.ZipFile) -> dict[str, Any]:
  59. """Extract document properties from docProps/core.xml and docProps/app.xml."""
  60. result: dict[str, Any] = {}
  61. if "docProps/core.xml" in zf.namelist():
  62. try:
  63. tree = ET.fromstring(zf.read("docProps/core.xml"))
  64. result["title"] = _text(tree.find("dc:title", NS))
  65. result["subject"] = _text(tree.find("dc:subject", NS))
  66. result["creator"] = _text(tree.find("dc:creator", NS))
  67. result["description"] = _text(tree.find("dc:description", NS))
  68. result["lastModifiedBy"] = _text(tree.find("cp:lastModifiedBy", NS))
  69. result["created"] = _text(tree.find("dcterms:created", NS))
  70. result["modified"] = _text(tree.find("dcterms:modified", NS))
  71. result["category"] = _text(tree.find("cp:category", NS))
  72. result["keywords"] = _text(tree.find("cp:keywords", NS))
  73. except Exception:
  74. result["_error_core"] = "Failed to parse docProps/core.xml"
  75. if "docProps/app.xml" in zf.namelist():
  76. try:
  77. tree = ET.fromstring(zf.read("docProps/app.xml"))
  78. result["application"] = _text(tree.find("ep:Application", NS))
  79. result["presentationFormat"] = _text(tree.find("ep:PresentationFormat", NS))
  80. result["totalSlides"] = _text(tree.find("ep:Slides", NS))
  81. result["hiddenSlides"] = _text(tree.find("ep:HiddenSlides", NS))
  82. result["company"] = _text(tree.find("ep:Company", NS))
  83. except Exception:
  84. result["_error_app"] = "Failed to parse docProps/app.xml"
  85. # Remove None values for cleaner output
  86. return {k: v for k, v in result.items() if v is not None}
  87. def extract_masters_and_layouts(zf: zipfile.ZipFile) -> dict[str, Any]:
  88. """Extract slide master and layout inventory with per-slide usage counts."""
  89. result: dict[str, Any] = {"masters": [], "layoutUsage": {}}
  90. # Parse presentation.xml for slide master references
  91. if "ppt/presentation.xml" not in zf.namelist():
  92. return result
  93. pres_tree = ET.fromstring(zf.read("ppt/presentation.xml"))
  94. # Enumerate slide masters
  95. master_files = sorted(
  96. [
  97. n
  98. for n in zf.namelist()
  99. if re.match(r"ppt/slideMasters/slideMaster\d+\.xml", n)
  100. ]
  101. )
  102. for mf in master_files:
  103. master_name = os.path.basename(mf)
  104. master_info: dict[str, Any] = {"file": master_name, "layouts": []}
  105. # Find layouts referenced by this master
  106. rels_path = mf.replace("ppt/slideMasters/", "ppt/slideMasters/_rels/") + ".rels"
  107. if rels_path in zf.namelist():
  108. try:
  109. rels_tree = ET.fromstring(zf.read(rels_path))
  110. except Exception:
  111. result["masters"].append(master_info)
  112. continue
  113. for rel in rels_tree.findall("rel:Relationship", NS):
  114. target = rel.get("Target", "")
  115. if "slideLayout" in target:
  116. layout_file = os.path.basename(target)
  117. layout_path = f"ppt/slideLayouts/{layout_file}"
  118. layout_name = layout_file
  119. if layout_path in zf.namelist():
  120. try:
  121. layout_tree = ET.fromstring(zf.read(layout_path))
  122. cSld = layout_tree.find("p:cSld", NS)
  123. if cSld is not None and cSld.get("name"):
  124. layout_name = cSld.get("name", layout_file)
  125. except Exception:
  126. pass
  127. master_info["layouts"].append(
  128. {
  129. "file": layout_file,
  130. "name": layout_name,
  131. }
  132. )
  133. result["masters"].append(master_info)
  134. # Count layout usage per slide
  135. layout_counter: Counter[str] = Counter()
  136. slide_files = sorted(
  137. [n for n in zf.namelist() if re.match(r"ppt/slides/slide\d+\.xml$", n)]
  138. )
  139. for sf in slide_files:
  140. rels_path = sf.replace("ppt/slides/", "ppt/slides/_rels/") + ".rels"
  141. if rels_path in zf.namelist():
  142. try:
  143. rels_tree = ET.fromstring(zf.read(rels_path))
  144. for rel in rels_tree.findall("rel:Relationship", NS):
  145. target = rel.get("Target", "")
  146. if "slideLayout" in target:
  147. layout_counter[os.path.basename(target)] += 1
  148. except Exception:
  149. pass
  150. result["layoutUsage"] = dict(layout_counter.most_common())
  151. return result
  152. def extract_themes(zf: zipfile.ZipFile) -> dict[str, Any]:
  153. """Extract theme colors and fonts."""
  154. result: dict[str, Any] = {"themes": []}
  155. theme_files = sorted(
  156. [n for n in zf.namelist() if re.match(r"ppt/theme/theme\d+\.xml", n)]
  157. )
  158. for tf in theme_files:
  159. try:
  160. tree = ET.fromstring(zf.read(tf))
  161. except Exception:
  162. result["themes"].append({"file": os.path.basename(tf), "_error": "Failed to parse"})
  163. continue
  164. theme_info: dict[str, Any] = {"file": os.path.basename(tf)}
  165. # Theme name
  166. theme_el = tree.find("a:themeElements", NS)
  167. theme_info["name"] = tree.get("name", "")
  168. # Color scheme
  169. clrScheme = tree.find(".//a:clrScheme", NS)
  170. if clrScheme is not None:
  171. theme_info["colorSchemeName"] = clrScheme.get("name", "")
  172. colors: dict[str, str] = {}
  173. for child in clrScheme:
  174. tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag
  175. # Get the color value from srgbClr or sysClr
  176. srgb = child.find("a:srgbClr", NS)
  177. sysclr = child.find("a:sysClr", NS)
  178. if srgb is not None:
  179. colors[tag] = srgb.get("val", "")
  180. elif sysclr is not None:
  181. colors[tag] = sysclr.get("lastClr", sysclr.get("val", ""))
  182. theme_info["colors"] = colors
  183. # Font scheme
  184. fontScheme = tree.find(".//a:fontScheme", NS)
  185. if fontScheme is not None:
  186. theme_info["fontSchemeName"] = fontScheme.get("name", "")
  187. fonts: dict[str, Any] = {}
  188. majorFont = fontScheme.find("a:majorFont", NS)
  189. if majorFont is not None:
  190. latin = majorFont.find("a:latin", NS)
  191. ea = majorFont.find("a:ea", NS)
  192. fonts["majorLatin"] = (
  193. latin.get("typeface", "") if latin is not None else ""
  194. )
  195. fonts["majorEastAsian"] = (
  196. ea.get("typeface", "") if ea is not None else ""
  197. )
  198. minorFont = fontScheme.find("a:minorFont", NS)
  199. if minorFont is not None:
  200. latin = minorFont.find("a:latin", NS)
  201. ea = minorFont.find("a:ea", NS)
  202. fonts["minorLatin"] = (
  203. latin.get("typeface", "") if latin is not None else ""
  204. )
  205. fonts["minorEastAsian"] = (
  206. ea.get("typeface", "") if ea is not None else ""
  207. )
  208. theme_info["fonts"] = fonts
  209. result["themes"].append(theme_info)
  210. return result
  211. def extract_shapes(
  212. zf: zipfile.ZipFile, slide_filter: set[int] | None = None
  213. ) -> dict[str, Any]:
  214. """Extract per-slide shape inventory with position, size, font, and color details."""
  215. result: dict[str, list[dict[str, Any]]] = {}
  216. slide_files = sorted(
  217. [n for n in zf.namelist() if re.match(r"ppt/slides/slide\d+\.xml$", n)],
  218. key=lambda x: int(re.search(r"(\d+)", x).group(1)), # type: ignore
  219. )
  220. for sf in slide_files:
  221. slide_num = int(re.search(r"(\d+)", sf).group(1)) # type: ignore
  222. if slide_filter and slide_num not in slide_filter:
  223. continue
  224. try:
  225. tree = ET.fromstring(zf.read(sf))
  226. except Exception:
  227. result[f"slide{slide_num}"] = [{"_error": "Failed to parse slide XML"}]
  228. continue
  229. shapes: list[dict[str, Any]] = []
  230. for sp in tree.iter("{%s}sp" % NS["p"]):
  231. shape_info: dict[str, Any] = {}
  232. # Name
  233. nvSpPr = sp.find("p:nvSpPr/p:cNvPr", NS)
  234. if nvSpPr is not None:
  235. shape_info["name"] = nvSpPr.get("name", "")
  236. shape_info["id"] = nvSpPr.get("id", "")
  237. # Position and size
  238. spPr = sp.find("p:spPr", NS)
  239. if spPr is not None:
  240. off = spPr.find("a:xfrm/a:off", NS)
  241. ext = spPr.find("a:xfrm/a:ext", NS)
  242. if off is not None:
  243. shape_info["x"] = _emu_to_inches(off.get("x"))
  244. shape_info["y"] = _emu_to_inches(off.get("y"))
  245. if ext is not None:
  246. shape_info["w"] = _emu_to_inches(ext.get("cx"))
  247. shape_info["h"] = _emu_to_inches(ext.get("cy"))
  248. # Shape type
  249. prstGeom = spPr.find("a:prstGeom", NS)
  250. if prstGeom is not None:
  251. shape_info["shapeType"] = prstGeom.get("prst", "")
  252. # Text content and font info
  253. txBody = sp.find("p:txBody", NS)
  254. if txBody is not None:
  255. text_runs: list[str] = []
  256. font_info: list[dict[str, Any]] = []
  257. for para in txBody.findall("a:p", NS):
  258. for run in para.findall("a:r", NS):
  259. t = run.find("a:t", NS)
  260. if t is not None and t.text:
  261. text_runs.append(t.text)
  262. rPr = run.find("a:rPr", NS)
  263. if rPr is not None:
  264. fi: dict[str, Any] = {}
  265. if rPr.get("sz"):
  266. fi["fontSize"] = int(rPr.get("sz", "0")) / 100
  267. if rPr.get("b") == "1":
  268. fi["bold"] = True
  269. if rPr.get("i") == "1":
  270. fi["italic"] = True
  271. latin = rPr.find("a:latin", NS)
  272. if latin is not None:
  273. fi["fontFace"] = latin.get("typeface", "")
  274. ea = rPr.find("a:ea", NS)
  275. if ea is not None:
  276. fi["fontFaceEA"] = ea.get("typeface", "")
  277. solidFill = rPr.find("a:solidFill/a:srgbClr", NS)
  278. if solidFill is not None:
  279. fi["color"] = solidFill.get("val", "")
  280. if fi:
  281. font_info.append(fi)
  282. if text_runs:
  283. shape_info["text"] = " ".join(text_runs)[:200] # truncate long text
  284. if font_info:
  285. shape_info["fonts"] = font_info
  286. if shape_info:
  287. shapes.append(shape_info)
  288. # Also collect picture shapes
  289. for pic in tree.iter("{%s}pic" % NS["p"]):
  290. pic_info: dict[str, Any] = {"type": "picture"}
  291. nvPicPr = pic.find("p:nvPicPr/p:cNvPr", NS)
  292. if nvPicPr is not None:
  293. pic_info["name"] = nvPicPr.get("name", "")
  294. spPr = pic.find("p:spPr", NS)
  295. if spPr is not None:
  296. off = spPr.find("a:xfrm/a:off", NS)
  297. ext = spPr.find("a:xfrm/a:ext", NS)
  298. if off is not None:
  299. pic_info["x"] = _emu_to_inches(off.get("x"))
  300. pic_info["y"] = _emu_to_inches(off.get("y"))
  301. if ext is not None:
  302. pic_info["w"] = _emu_to_inches(ext.get("cx"))
  303. pic_info["h"] = _emu_to_inches(ext.get("cy"))
  304. shapes.append(pic_info)
  305. result[f"slide{slide_num}"] = shapes
  306. return {"slides": result}
  307. def extract_hyperlinks(
  308. zf: zipfile.ZipFile, slide_filter: set[int] | None = None
  309. ) -> dict[str, Any]:
  310. """Extract hyperlinks from all slides."""
  311. hyperlinks: list[dict[str, Any]] = []
  312. slide_files = sorted(
  313. [n for n in zf.namelist() if re.match(r"ppt/slides/slide\d+\.xml$", n)],
  314. key=lambda x: int(re.search(r"(\d+)", x).group(1)), # type: ignore
  315. )
  316. for sf in slide_files:
  317. slide_num = int(re.search(r"(\d+)", sf).group(1)) # type: ignore
  318. if slide_filter and slide_num not in slide_filter:
  319. continue
  320. # Build rId -> target map from rels
  321. rels_path = sf.replace("ppt/slides/", "ppt/slides/_rels/") + ".rels"
  322. rid_map: dict[str, str] = {}
  323. if rels_path in zf.namelist():
  324. try:
  325. rels_tree = ET.fromstring(zf.read(rels_path))
  326. for rel in rels_tree.findall("rel:Relationship", NS):
  327. rid = rel.get("Id", "")
  328. target = rel.get("Target", "")
  329. target_mode = rel.get("TargetMode", "")
  330. if target_mode == "External" or "http" in target:
  331. rid_map[rid] = target
  332. except Exception:
  333. pass
  334. # Find hyperlinks in slide XML
  335. try:
  336. tree = ET.fromstring(zf.read(sf))
  337. except Exception:
  338. continue
  339. for hlinkClick in tree.iter("{%s}hlinkClick" % NS["a"]):
  340. rid = hlinkClick.get("{%s}id" % NS["r"], "")
  341. url = rid_map.get(rid, "")
  342. action = hlinkClick.get("action", "")
  343. tooltip = hlinkClick.get("tooltip", "")
  344. link_info: dict[str, Any] = {"slide": slide_num}
  345. if url:
  346. link_info["url"] = url
  347. if action:
  348. link_info["action"] = action
  349. if tooltip:
  350. link_info["tooltip"] = tooltip
  351. if rid and not url:
  352. link_info["rId"] = rid
  353. link_info["note"] = "internal or missing target"
  354. hyperlinks.append(link_info)
  355. return {"hyperlinks": hyperlinks, "totalCount": len(hyperlinks)}
  356. def extract_embedded(zf: zipfile.ZipFile) -> dict[str, Any]:
  357. """Extract embedded objects and OLE items."""
  358. embedded: list[dict[str, str]] = []
  359. for name in zf.namelist():
  360. if name.startswith("ppt/embeddings/"):
  361. ext = os.path.splitext(name)[1]
  362. embedded.append({"path": name, "extension": ext})
  363. # Check for OLE objects in content types
  364. ole_items: list[str] = []
  365. if "[Content_Types].xml" in zf.namelist():
  366. try:
  367. ct_tree = ET.fromstring(zf.read("[Content_Types].xml"))
  368. for override in ct_tree.findall("ct:Override", NS):
  369. content_type = override.get("ContentType", "")
  370. part_name = override.get("PartName", "")
  371. if "oleObject" in content_type.lower() or "oleObject" in part_name.lower():
  372. ole_items.append(part_name)
  373. except Exception:
  374. pass
  375. return {
  376. "embeddedFiles": embedded,
  377. "oleObjects": ole_items,
  378. "totalEmbedded": len(embedded),
  379. "totalOLE": len(ole_items),
  380. }
  381. def extract_security(zf: zipfile.ZipFile) -> dict[str, Any]:
  382. """Extract MSIP sensitivity labels and security metadata."""
  383. result: dict[str, Any] = {"msipLabels": [], "customXmlParts": []}
  384. # Check for MSIP labels in custom XML parts
  385. for name in zf.namelist():
  386. if name.startswith("customXml/") and name.endswith(".xml"):
  387. try:
  388. content = zf.read(name).decode("utf-8", errors="replace")
  389. if (
  390. "MSIP" in content
  391. or "MicrosoftInformationProtection" in content
  392. or "sensitivity" in content.lower()
  393. ):
  394. result["msipLabels"].append(
  395. {
  396. "path": name,
  397. "snippet": content[:500],
  398. }
  399. )
  400. result["customXmlParts"].append(name)
  401. except Exception:
  402. result["customXmlParts"].append(name)
  403. # Check for label info in docProps/custom.xml
  404. if "docProps/custom.xml" in zf.namelist():
  405. try:
  406. content = zf.read("docProps/custom.xml").decode("utf-8", errors="replace")
  407. tree = ET.fromstring(zf.read("docProps/custom.xml"))
  408. for prop in tree:
  409. name_attr = prop.get("name", "")
  410. if (
  411. "MSIP" in name_attr
  412. or "Sensitivity" in name_attr
  413. or "Classification" in name_attr
  414. ):
  415. val = prop.text or ""
  416. # Try to get value from child elements
  417. for child in prop:
  418. if child.text:
  419. val = child.text
  420. result["msipLabels"].append(
  421. {
  422. "property": name_attr,
  423. "value": val,
  424. }
  425. )
  426. except Exception:
  427. pass
  428. return result
  429. # ---------------------------------------------------------------------------
  430. # Output formatters
  431. # ---------------------------------------------------------------------------
  432. def format_text(data: dict[str, Any]) -> str:
  433. """Format audit result as human-readable text."""
  434. lines: list[str] = []
  435. if "metadata" in data:
  436. lines.append("=== Document Metadata ===")
  437. for k, v in data["metadata"].items():
  438. lines.append(f" {k}: {v}")
  439. lines.append("")
  440. if "masters" in data:
  441. lines.append("=== Slide Masters & Layouts ===")
  442. for master in data["masters"].get("masters", []):
  443. lines.append(f" Master: {master['file']}")
  444. for layout in master.get("layouts", []):
  445. lines.append(f" Layout: {layout['name']} ({layout['file']})")
  446. lines.append(" Layout Usage:")
  447. for layout, count in data["masters"].get("layoutUsage", {}).items():
  448. lines.append(f" {layout}: {count} slide(s)")
  449. lines.append("")
  450. if "themes" in data:
  451. lines.append("=== Themes ===")
  452. for theme in data["themes"].get("themes", []):
  453. lines.append(f" Theme: {theme.get('name', 'unnamed')} ({theme['file']})")
  454. if "colors" in theme:
  455. lines.append(" Colors:")
  456. for name, val in theme["colors"].items():
  457. lines.append(f" {name}: #{val}")
  458. if "fonts" in theme:
  459. lines.append(" Fonts:")
  460. for name, val in theme["fonts"].items():
  461. lines.append(f" {name}: {val}")
  462. lines.append("")
  463. if "shapes" in data:
  464. lines.append("=== Shape Inventory ===")
  465. for slide_key, shapes in data["shapes"].get("slides", {}).items():
  466. lines.append(f" {slide_key}: {len(shapes)} shape(s)")
  467. for s in shapes:
  468. desc = s.get("name", s.get("type", "shape"))
  469. pos = ""
  470. if "x" in s and "y" in s:
  471. pos = f' @ ({s["x"]}", {s["y"]}")'
  472. size = ""
  473. if "w" in s and "h" in s:
  474. size = f' [{s["w"]}" x {s["h"]}"]'
  475. text_preview = ""
  476. if "text" in s:
  477. text_preview = (
  478. f' "{s["text"][:60]}..."'
  479. if len(s.get("text", "")) > 60
  480. else f' "{s["text"]}"'
  481. )
  482. lines.append(f" - {desc}{pos}{size}{text_preview}")
  483. lines.append("")
  484. if "hyperlinks" in data:
  485. lines.append(f"=== Hyperlinks ({data['hyperlinks']['totalCount']}) ===")
  486. for link in data["hyperlinks"].get("hyperlinks", []):
  487. url = link.get("url", link.get("action", link.get("rId", "unknown")))
  488. lines.append(f" Slide {link['slide']}: {url}")
  489. lines.append("")
  490. if "embedded" in data:
  491. lines.append(f"=== Embedded Objects ({data['embedded']['totalEmbedded']}) ===")
  492. for item in data["embedded"].get("embeddedFiles", []):
  493. lines.append(f" {item['path']} ({item['extension']})")
  494. if data["embedded"].get("oleObjects"):
  495. lines.append(" OLE Objects:")
  496. for ole in data["embedded"]["oleObjects"]:
  497. lines.append(f" {ole}")
  498. lines.append("")
  499. if "security" in data:
  500. lines.append("=== Security / MSIP Labels ===")
  501. if data["security"].get("msipLabels"):
  502. for label in data["security"]["msipLabels"]:
  503. if "property" in label:
  504. lines.append(f" {label['property']}: {label['value']}")
  505. elif "path" in label:
  506. lines.append(f" Found in: {label['path']}")
  507. else:
  508. lines.append(" No MSIP/sensitivity labels detected.")
  509. lines.append("")
  510. return "\n".join(lines)
  511. # ---------------------------------------------------------------------------
  512. # Main
  513. # ---------------------------------------------------------------------------
  514. ALL_SECTIONS = [
  515. "metadata",
  516. "masters",
  517. "themes",
  518. "shapes",
  519. "hyperlinks",
  520. "embedded",
  521. "security",
  522. ]
  523. def parse_args() -> argparse.Namespace:
  524. parser = argparse.ArgumentParser(
  525. description="Audit PPTX format metadata: layouts, themes, fonts, colors, hyperlinks, embedded objects, security labels."
  526. )
  527. parser.add_argument("pptx_path", help="Path to the PPTX file to audit.")
  528. parser.add_argument(
  529. "--sections",
  530. default="all",
  531. help="Comma-separated sections to include: metadata,masters,themes,shapes,hyperlinks,embedded,security. Default: all",
  532. )
  533. parser.add_argument(
  534. "--slides",
  535. help='Only audit these slide numbers for shape/hyperlink sections, e.g. "1,3,5".',
  536. )
  537. parser.add_argument(
  538. "--format",
  539. choices=["json", "text"],
  540. default="json",
  541. help="Output format: json (default) or text.",
  542. )
  543. return parser.parse_args()
  544. def main() -> int:
  545. args = parse_args()
  546. if not os.path.isfile(args.pptx_path):
  547. print(f"File not found: {args.pptx_path}", file=sys.stderr)
  548. return 1
  549. sections = (
  550. ALL_SECTIONS
  551. if args.sections == "all"
  552. else [s.strip() for s in args.sections.split(",")]
  553. )
  554. slide_filter: set[int] | None = None
  555. if args.slides:
  556. try:
  557. slide_filter = {int(s.strip()) for s in args.slides.split(",")}
  558. except ValueError:
  559. print(
  560. "Invalid --slides format. Use comma-separated integers.",
  561. file=sys.stderr,
  562. )
  563. return 1
  564. try:
  565. zf = zipfile.ZipFile(args.pptx_path, "r")
  566. except (zipfile.BadZipFile, Exception) as e:
  567. print(f"Cannot open PPTX: {e}", file=sys.stderr)
  568. return 1
  569. result: dict[str, Any] = {"file": os.path.basename(args.pptx_path)}
  570. with zf:
  571. if "metadata" in sections:
  572. result["metadata"] = extract_metadata(zf)
  573. if "masters" in sections:
  574. result["masters"] = extract_masters_and_layouts(zf)
  575. if "themes" in sections:
  576. result["themes"] = extract_themes(zf)
  577. if "shapes" in sections:
  578. result["shapes"] = extract_shapes(zf, slide_filter)
  579. if "hyperlinks" in sections:
  580. result["hyperlinks"] = extract_hyperlinks(zf, slide_filter)
  581. if "embedded" in sections:
  582. result["embedded"] = extract_embedded(zf)
  583. if "security" in sections:
  584. result["security"] = extract_security(zf)
  585. if args.format == "json":
  586. print(json.dumps(result, indent=2, ensure_ascii=False))
  587. else:
  588. print(format_text(result))
  589. return 0
  590. if __name__ == "__main__":
  591. raise SystemExit(main())