litmus-cli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- litmus/__init__.py +27 -0
- litmus/artifact.py +179 -0
- litmus/cli.py +342 -0
- litmus/detectors/__init__.py +3 -0
- litmus/detectors/base.py +56 -0
- litmus/exif.py +158 -0
- litmus/inspectors/__init__.py +32 -0
- litmus/inspectors/base.py +36 -0
- litmus/inspectors/c2pa.py +159 -0
- litmus/inspectors/file_metadata.py +210 -0
- litmus/inspectors/office_metadata.py +54 -0
- litmus/inspectors/text_markers.py +75 -0
- litmus/inspectors/unicode_scan.py +308 -0
- litmus/io.py +54 -0
- litmus/model.py +173 -0
- litmus/office.py +198 -0
- litmus/pipeline.py +464 -0
- litmus/providers/__init__.py +17 -0
- litmus/providers/registry.py +239 -0
- litmus/reporting.py +150 -0
- litmus/server.py +176 -0
- litmus/transform/__init__.py +12 -0
- litmus/transform/base.py +30 -0
- litmus/transform/code_structural.py +119 -0
- litmus/transform/file_strip.py +148 -0
- litmus/transform/text_normalize.py +257 -0
- litmus/validate/__init__.py +3 -0
- litmus/validate/binary.py +75 -0
- litmus/validate/code.py +165 -0
- litmus/validate/office.py +73 -0
- litmus/validate/structural.py +136 -0
- litmus/validate/text.py +158 -0
- litmus/validate/treesitter_code.py +129 -0
- litmus/web_ui.py +728 -0
- litmus_cli-0.3.0.dist-info/METADATA +108 -0
- litmus_cli-0.3.0.dist-info/RECORD +39 -0
- litmus_cli-0.3.0.dist-info/WHEEL +4 -0
- litmus_cli-0.3.0.dist-info/entry_points.txt +2 -0
- litmus_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
litmus/exif.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Minimal EXIF reader for surfacing privacy-relevant fields (feature 2).
|
|
2
|
+
|
|
3
|
+
Purpose is narrow and honest: pull out the handful of tags people actually care
|
|
4
|
+
about when sharing a photo — GPS location, camera make/model, capture date, and
|
|
5
|
+
authoring software — so the inspector can name them plainly. It is not a full
|
|
6
|
+
EXIF library; unknown tags are ignored. Standard library only; no allocation
|
|
7
|
+
beyond the segment; bounded by the segment length.
|
|
8
|
+
|
|
9
|
+
The JPEG APP1 Exif payload is a TIFF stream: an 8-byte header giving byte order
|
|
10
|
+
and the offset of the first Image File Directory (IFD), then IFDs of 12-byte
|
|
11
|
+
entries. GPS data lives in a sub-IFD referenced by tag 0x8825.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import struct
|
|
17
|
+
|
|
18
|
+
EXIF_PREFIX = b"Exif\x00\x00"
|
|
19
|
+
|
|
20
|
+
# TIFF field type -> byte size, for the types we read.
|
|
21
|
+
_TYPE_SIZE = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8}
|
|
22
|
+
|
|
23
|
+
# Tags we care about, in the primary IFD.
|
|
24
|
+
_TAG_MAKE = 0x010F
|
|
25
|
+
_TAG_MODEL = 0x0110
|
|
26
|
+
_TAG_SOFTWARE = 0x0131
|
|
27
|
+
_TAG_DATETIME = 0x0132
|
|
28
|
+
_TAG_ARTIST = 0x013B
|
|
29
|
+
_TAG_GPS_IFD = 0x8825
|
|
30
|
+
_TAG_EXIF_IFD = 0x8769
|
|
31
|
+
_TAG_DATETIME_ORIG = 0x9003
|
|
32
|
+
|
|
33
|
+
_PRIMARY_LABELS = {
|
|
34
|
+
_TAG_MAKE: "camera make",
|
|
35
|
+
_TAG_MODEL: "camera model",
|
|
36
|
+
_TAG_SOFTWARE: "software",
|
|
37
|
+
_TAG_DATETIME: "date/time",
|
|
38
|
+
_TAG_ARTIST: "artist",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
# GPS sub-IFD tags.
|
|
42
|
+
_GPS_LAT_REF = 0x0001
|
|
43
|
+
_GPS_LAT = 0x0002
|
|
44
|
+
_GPS_LON_REF = 0x0003
|
|
45
|
+
_GPS_LON = 0x0004
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _read_header(buf: bytes) -> tuple[str, int] | None:
|
|
49
|
+
if len(buf) < 8:
|
|
50
|
+
return None
|
|
51
|
+
if buf[:2] == b"II":
|
|
52
|
+
endian = "<"
|
|
53
|
+
elif buf[:2] == b"MM":
|
|
54
|
+
endian = ">"
|
|
55
|
+
else:
|
|
56
|
+
return None
|
|
57
|
+
(first_ifd,) = struct.unpack(endian + "I", buf[4:8])
|
|
58
|
+
return endian, first_ifd
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _entries(buf: bytes, endian: str, offset: int) -> list[tuple[int, int, int, bytes]]:
|
|
62
|
+
"""Return (tag, type, count, value_or_offset_bytes) for one IFD."""
|
|
63
|
+
if offset + 2 > len(buf):
|
|
64
|
+
return []
|
|
65
|
+
(count,) = struct.unpack(endian + "H", buf[offset : offset + 2])
|
|
66
|
+
entries: list[tuple[int, int, int, bytes]] = []
|
|
67
|
+
pos = offset + 2
|
|
68
|
+
for _ in range(count):
|
|
69
|
+
if pos + 12 > len(buf):
|
|
70
|
+
break
|
|
71
|
+
tag, ftype, num = struct.unpack(endian + "HHI", buf[pos : pos + 8])
|
|
72
|
+
entries.append((tag, ftype, num, buf[pos + 8 : pos + 12]))
|
|
73
|
+
pos += 12
|
|
74
|
+
return entries
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _value_bytes(buf: bytes, endian: str, ftype: int, count: int, raw: bytes) -> bytes:
|
|
78
|
+
size = _TYPE_SIZE.get(ftype, 0) * count
|
|
79
|
+
if size == 0:
|
|
80
|
+
return b""
|
|
81
|
+
if size <= 4:
|
|
82
|
+
return raw[:size]
|
|
83
|
+
(off,) = struct.unpack(endian + "I", raw)
|
|
84
|
+
return buf[off : off + size] if off + size <= len(buf) else b""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _ascii(buf: bytes, endian: str, ftype: int, count: int, raw: bytes) -> str:
|
|
88
|
+
return (
|
|
89
|
+
_value_bytes(buf, endian, ftype, count, raw).split(b"\x00", 1)[0].decode("ascii", "replace")
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _rationals(buf: bytes, endian: str, count: int, raw: bytes) -> list[float]:
|
|
94
|
+
data = _value_bytes(buf, endian, 5, count, raw)
|
|
95
|
+
out: list[float] = []
|
|
96
|
+
for i in range(0, len(data) - 7, 8):
|
|
97
|
+
num, den = struct.unpack(endian + "II", data[i : i + 8])
|
|
98
|
+
out.append(num / den if den else 0.0)
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _gps_coord(values: list[float]) -> float | None:
|
|
103
|
+
if len(values) < 3:
|
|
104
|
+
return None
|
|
105
|
+
deg, minute, sec = values[0], values[1], values[2]
|
|
106
|
+
return deg + minute / 60 + sec / 3600
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def parse_exif_from_app1(payload: bytes) -> dict[str, object]:
|
|
110
|
+
"""Extract privacy-relevant fields from a JPEG APP1 Exif payload.
|
|
111
|
+
|
|
112
|
+
Returns a flat dict (possibly empty). Never raises: a malformed stream
|
|
113
|
+
yields whatever could be read.
|
|
114
|
+
"""
|
|
115
|
+
if not payload.startswith(EXIF_PREFIX):
|
|
116
|
+
return {}
|
|
117
|
+
tiff = payload[len(EXIF_PREFIX) :]
|
|
118
|
+
header = _read_header(tiff)
|
|
119
|
+
if header is None:
|
|
120
|
+
return {}
|
|
121
|
+
endian, first = header
|
|
122
|
+
result: dict[str, object] = {}
|
|
123
|
+
gps_offset = 0
|
|
124
|
+
for tag, ftype, count, raw in _entries(tiff, endian, first):
|
|
125
|
+
if tag in _PRIMARY_LABELS and ftype == 2:
|
|
126
|
+
text = _ascii(tiff, endian, ftype, count, raw)
|
|
127
|
+
if text:
|
|
128
|
+
result[_PRIMARY_LABELS[tag]] = text
|
|
129
|
+
elif tag == _TAG_GPS_IFD and ftype == 4:
|
|
130
|
+
(gps_offset,) = struct.unpack(endian + "I", raw)
|
|
131
|
+
elif tag == _TAG_EXIF_IFD and ftype == 4:
|
|
132
|
+
(exif_off,) = struct.unpack(endian + "I", raw)
|
|
133
|
+
for etag, eftype, ecount, eraw in _entries(tiff, endian, exif_off):
|
|
134
|
+
if etag == _TAG_DATETIME_ORIG and eftype == 2:
|
|
135
|
+
text = _ascii(tiff, endian, eftype, ecount, eraw)
|
|
136
|
+
if text:
|
|
137
|
+
result["date/time original"] = text
|
|
138
|
+
|
|
139
|
+
if gps_offset:
|
|
140
|
+
lat = lon = None
|
|
141
|
+
lat_ref = lon_ref = ""
|
|
142
|
+
for tag, ftype, count, raw in _entries(tiff, endian, gps_offset):
|
|
143
|
+
if tag == _GPS_LAT and ftype == 5:
|
|
144
|
+
lat = _gps_coord(_rationals(tiff, endian, count, raw))
|
|
145
|
+
elif tag == _GPS_LON and ftype == 5:
|
|
146
|
+
lon = _gps_coord(_rationals(tiff, endian, count, raw))
|
|
147
|
+
elif tag == _GPS_LAT_REF and ftype == 2:
|
|
148
|
+
lat_ref = _ascii(tiff, endian, ftype, count, raw)
|
|
149
|
+
elif tag == _GPS_LON_REF and ftype == 2:
|
|
150
|
+
lon_ref = _ascii(tiff, endian, ftype, count, raw)
|
|
151
|
+
if lat is not None and lon is not None:
|
|
152
|
+
if lat_ref.upper() == "S":
|
|
153
|
+
lat = -lat
|
|
154
|
+
if lon_ref.upper() == "W":
|
|
155
|
+
lon = -lon
|
|
156
|
+
result["gps_latitude"] = round(lat, 6)
|
|
157
|
+
result["gps_longitude"] = round(lon, 6)
|
|
158
|
+
return result
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Inspector registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .base import Inspector, InspectorOutcome
|
|
6
|
+
from .c2pa import C2paInspector
|
|
7
|
+
from .file_metadata import FileMetadataInspector
|
|
8
|
+
from .office_metadata import OfficeMetadataInspector
|
|
9
|
+
from .text_markers import TextMarkerInspector
|
|
10
|
+
from .unicode_scan import UnicodeInspector
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def default_inspectors() -> list[Inspector]:
|
|
14
|
+
return [
|
|
15
|
+
UnicodeInspector(),
|
|
16
|
+
TextMarkerInspector(),
|
|
17
|
+
FileMetadataInspector(),
|
|
18
|
+
OfficeMetadataInspector(),
|
|
19
|
+
C2paInspector(),
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"C2paInspector",
|
|
25
|
+
"FileMetadataInspector",
|
|
26
|
+
"Inspector",
|
|
27
|
+
"InspectorOutcome",
|
|
28
|
+
"OfficeMetadataInspector",
|
|
29
|
+
"TextMarkerInspector",
|
|
30
|
+
"UnicodeInspector",
|
|
31
|
+
"default_inspectors",
|
|
32
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Inspector protocol and registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
from ..artifact import Artifact
|
|
9
|
+
from ..model import Finding
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class InspectorOutcome:
|
|
14
|
+
findings: list[Finding] = field(default_factory=list)
|
|
15
|
+
ran: bool = True
|
|
16
|
+
reason: str | None = None
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def skipped(cls, reason: str) -> InspectorOutcome:
|
|
20
|
+
return cls(findings=[], ran=False, reason=reason)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@runtime_checkable
|
|
24
|
+
class Inspector(Protocol):
|
|
25
|
+
name: str
|
|
26
|
+
|
|
27
|
+
def applies_to(self, artifact: Artifact) -> bool: ...
|
|
28
|
+
|
|
29
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome: ...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def line_col(text: str, offset: int) -> tuple[int, int]:
|
|
33
|
+
"""1-based line, 1-based column for a character offset."""
|
|
34
|
+
line = text.count("\n", 0, offset) + 1
|
|
35
|
+
last_nl = text.rfind("\n", 0, offset)
|
|
36
|
+
return line, offset - last_nl
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""C2PA manifest inspection.
|
|
2
|
+
|
|
3
|
+
Two distinct capabilities, kept separate on purpose:
|
|
4
|
+
|
|
5
|
+
* **Presence** — detected structurally with the standard library. A C2PA
|
|
6
|
+
manifest store lives in a PNG ``caBX`` chunk, a JPEG APP11/JUMBF segment, or
|
|
7
|
+
SVG metadata. Presence is cheap and reliable.
|
|
8
|
+
* **Verification** — checking the signature chain, issuer, assertions and
|
|
9
|
+
timestamps. This requires the optional ``c2pa`` extra. Without it the finding
|
|
10
|
+
reports ``verification: not_performed`` rather than implying the manifest is
|
|
11
|
+
valid.
|
|
12
|
+
|
|
13
|
+
Presence of a manifest is *not* proof of provenance; only a verified signature
|
|
14
|
+
is, and even then it attests to the signer's claim, not to authorship.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import contextlib
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from ..artifact import Artifact
|
|
23
|
+
from ..model import EvidenceClass, EvidenceLabel, Finding, Severity
|
|
24
|
+
from .base import InspectorOutcome
|
|
25
|
+
from .file_metadata import (
|
|
26
|
+
JPEG_SIGNATURE,
|
|
27
|
+
PNG_SIGNATURE,
|
|
28
|
+
iter_jpeg_segments,
|
|
29
|
+
iter_png_chunks,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# JUMBF box type used by C2PA, and the C2PA namespace UUID prefix.
|
|
33
|
+
JUMBF_MAGIC = b"jumb"
|
|
34
|
+
C2PA_MARKERS = (b"c2pa", b"jumbf", b"urn:uuid:")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _guess_mime(data: bytes) -> str | None:
|
|
38
|
+
if data.startswith(PNG_SIGNATURE):
|
|
39
|
+
return "image/png"
|
|
40
|
+
if data.startswith(JPEG_SIGNATURE):
|
|
41
|
+
return "image/jpeg"
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _load_c2pa_module() -> Any | None:
|
|
46
|
+
try:
|
|
47
|
+
import c2pa
|
|
48
|
+
except ImportError:
|
|
49
|
+
return None
|
|
50
|
+
return c2pa
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class C2paInspector:
|
|
54
|
+
name = "c2pa"
|
|
55
|
+
|
|
56
|
+
def applies_to(self, artifact: Artifact) -> bool:
|
|
57
|
+
data = artifact.data
|
|
58
|
+
return (
|
|
59
|
+
data.startswith(PNG_SIGNATURE)
|
|
60
|
+
or data.startswith(JPEG_SIGNATURE)
|
|
61
|
+
or artifact.ref.media_type == "image/svg+xml"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome:
|
|
65
|
+
present, container, evidence = self._detect_presence(artifact)
|
|
66
|
+
if not present:
|
|
67
|
+
return InspectorOutcome(findings=[])
|
|
68
|
+
|
|
69
|
+
details: dict[str, object] = {
|
|
70
|
+
"container": container,
|
|
71
|
+
"located_in": evidence,
|
|
72
|
+
"verification": "not_performed",
|
|
73
|
+
"verification_reason": (
|
|
74
|
+
"the optional 'c2pa' extra is not installed; manifest presence was "
|
|
75
|
+
"detected structurally but the signature was not verified"
|
|
76
|
+
),
|
|
77
|
+
}
|
|
78
|
+
severity = Severity.INFO
|
|
79
|
+
label = EvidenceLabel.CONFIRMED
|
|
80
|
+
|
|
81
|
+
module = _load_c2pa_module()
|
|
82
|
+
if module is not None:
|
|
83
|
+
details.update(self._verify(module, artifact))
|
|
84
|
+
|
|
85
|
+
return InspectorOutcome(
|
|
86
|
+
findings=[
|
|
87
|
+
Finding(
|
|
88
|
+
detector=self.name,
|
|
89
|
+
category="c2pa_manifest",
|
|
90
|
+
# Presence alone is only *claimed* signed provenance. The
|
|
91
|
+
# class stays SIGNED_PROVENANCE because that is what the
|
|
92
|
+
# structure is; the verification field carries the caveat.
|
|
93
|
+
evidence_class=EvidenceClass.SIGNED_PROVENANCE,
|
|
94
|
+
severity=severity,
|
|
95
|
+
summary=f"C2PA manifest store present in {container} container",
|
|
96
|
+
label=label,
|
|
97
|
+
details=details,
|
|
98
|
+
removable_by=[],
|
|
99
|
+
)
|
|
100
|
+
]
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def _detect_presence(self, artifact: Artifact) -> tuple[bool, str, str]:
|
|
104
|
+
data = artifact.data
|
|
105
|
+
if data.startswith(PNG_SIGNATURE):
|
|
106
|
+
for ctype, _payload in iter_png_chunks(data):
|
|
107
|
+
if ctype == "caBX":
|
|
108
|
+
return True, "png", "caBX chunk"
|
|
109
|
+
return False, "png", ""
|
|
110
|
+
if data.startswith(JPEG_SIGNATURE):
|
|
111
|
+
for marker, payload in iter_jpeg_segments(data):
|
|
112
|
+
if marker == 0xEB and JUMBF_MAGIC in payload[:64]:
|
|
113
|
+
return True, "jpeg", "APP11 JUMBF segment"
|
|
114
|
+
return False, "jpeg", ""
|
|
115
|
+
if artifact.text is not None and artifact.ref.media_type == "image/svg+xml":
|
|
116
|
+
lowered = artifact.text.lower()
|
|
117
|
+
if "c2pa" in lowered:
|
|
118
|
+
return True, "svg", "c2pa reference in SVG markup"
|
|
119
|
+
return False, "svg", ""
|
|
120
|
+
return False, "unknown", ""
|
|
121
|
+
|
|
122
|
+
def _verify(self, module: Any, artifact: Artifact) -> dict[str, object]:
|
|
123
|
+
"""Verify with the optional c2pa library, reading from bytes in memory.
|
|
124
|
+
|
|
125
|
+
Reading from a stream (rather than a file path) means verification works
|
|
126
|
+
the same way for the in-memory web UI and the CLI. Any library error is
|
|
127
|
+
reported as a verification outcome, never raised: a broken or untrusted
|
|
128
|
+
manifest is a result, not a crash.
|
|
129
|
+
"""
|
|
130
|
+
import io
|
|
131
|
+
|
|
132
|
+
media = artifact.ref.media_type or _guess_mime(artifact.data)
|
|
133
|
+
if media is None:
|
|
134
|
+
return {
|
|
135
|
+
"verification": "not_performed",
|
|
136
|
+
"verification_reason": "could not determine the media type to verify",
|
|
137
|
+
}
|
|
138
|
+
reader = None
|
|
139
|
+
try:
|
|
140
|
+
reader = module.Reader(media, io.BytesIO(artifact.data))
|
|
141
|
+
manifest_json = reader.json()
|
|
142
|
+
validity: str | None = None
|
|
143
|
+
if hasattr(reader, "is_valid"):
|
|
144
|
+
validity = "valid" if reader.is_valid() else "invalid"
|
|
145
|
+
return {
|
|
146
|
+
"verification": "performed",
|
|
147
|
+
"verification_reason": None,
|
|
148
|
+
"validity": validity,
|
|
149
|
+
"manifest": manifest_json,
|
|
150
|
+
}
|
|
151
|
+
except Exception as exc: # noqa: BLE001 - any library error is a result
|
|
152
|
+
return {
|
|
153
|
+
"verification": "failed",
|
|
154
|
+
"verification_reason": f"{type(exc).__name__}: {exc}",
|
|
155
|
+
}
|
|
156
|
+
finally:
|
|
157
|
+
if reader is not None:
|
|
158
|
+
with contextlib.suppress(Exception):
|
|
159
|
+
reader.close()
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Embedded file-metadata inspection, standard library only.
|
|
2
|
+
|
|
3
|
+
Parsers are intentionally defensive: a malformed container yields a finding
|
|
4
|
+
that says the container is malformed, never an exception and never a silent
|
|
5
|
+
empty result (brief §19).
|
|
6
|
+
|
|
7
|
+
Everything reported here is ``EMBEDDED_METADATA``: unsigned, trivially forged,
|
|
8
|
+
and trivially stripped. Signed provenance is handled in ``c2pa.py``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import struct
|
|
14
|
+
|
|
15
|
+
from ..artifact import Artifact
|
|
16
|
+
from ..exif import parse_exif_from_app1
|
|
17
|
+
from ..model import EvidenceClass, EvidenceLabel, Finding, Severity
|
|
18
|
+
from .base import InspectorOutcome
|
|
19
|
+
|
|
20
|
+
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
21
|
+
JPEG_SIGNATURE = b"\xff\xd8"
|
|
22
|
+
MAX_VALUE_CHARS = 200
|
|
23
|
+
|
|
24
|
+
# PNG chunk types that carry metadata rather than image data.
|
|
25
|
+
PNG_METADATA_CHUNKS = {b"tEXt", b"iTXt", b"zTXt", b"eXIf", b"tIME", b"iCCP"}
|
|
26
|
+
|
|
27
|
+
JPEG_APP_NAMES = {
|
|
28
|
+
0xE0: "APP0 (JFIF)",
|
|
29
|
+
0xE1: "APP1 (Exif/XMP)",
|
|
30
|
+
0xE2: "APP2 (ICC/FlashPix)",
|
|
31
|
+
0xEB: "APP11 (JUMBF)",
|
|
32
|
+
0xED: "APP13 (Photoshop IRB/IPTC)",
|
|
33
|
+
0xEE: "APP14 (Adobe)",
|
|
34
|
+
0xFE: "COM (comment)",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _clean(value: bytes) -> str:
|
|
39
|
+
return value.decode("utf-8", errors="replace")[:MAX_VALUE_CHARS]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def iter_png_chunks(data: bytes) -> list[tuple[str, bytes]]:
|
|
43
|
+
"""Yield (chunk_type, chunk_data). Stops cleanly on truncation."""
|
|
44
|
+
chunks: list[tuple[str, bytes]] = []
|
|
45
|
+
offset = len(PNG_SIGNATURE)
|
|
46
|
+
while offset + 8 <= len(data):
|
|
47
|
+
(length,) = struct.unpack(">I", data[offset : offset + 4])
|
|
48
|
+
ctype = data[offset + 4 : offset + 8]
|
|
49
|
+
start = offset + 8
|
|
50
|
+
end = start + length
|
|
51
|
+
if length > len(data) or end > len(data):
|
|
52
|
+
break
|
|
53
|
+
chunks.append((ctype.decode("ascii", errors="replace"), data[start:end]))
|
|
54
|
+
if ctype == b"IEND":
|
|
55
|
+
break
|
|
56
|
+
offset = end + 4 # skip CRC
|
|
57
|
+
return chunks
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def iter_jpeg_segments(data: bytes) -> list[tuple[int, bytes]]:
|
|
61
|
+
"""Yield (marker_byte, payload) for JPEG APPn/COM segments before the scan."""
|
|
62
|
+
segments: list[tuple[int, bytes]] = []
|
|
63
|
+
offset = 2
|
|
64
|
+
while offset + 4 <= len(data):
|
|
65
|
+
if data[offset] != 0xFF:
|
|
66
|
+
break
|
|
67
|
+
marker = data[offset + 1]
|
|
68
|
+
if marker == 0xDA: # start of scan: metadata region is over
|
|
69
|
+
break
|
|
70
|
+
if marker in (0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
|
|
71
|
+
offset += 2
|
|
72
|
+
continue
|
|
73
|
+
(length,) = struct.unpack(">H", data[offset + 2 : offset + 4])
|
|
74
|
+
if length < 2:
|
|
75
|
+
break
|
|
76
|
+
start = offset + 4
|
|
77
|
+
end = offset + 2 + length
|
|
78
|
+
if end > len(data):
|
|
79
|
+
break
|
|
80
|
+
segments.append((marker, data[start:end]))
|
|
81
|
+
offset = end
|
|
82
|
+
return segments
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class FileMetadataInspector:
|
|
86
|
+
name = "file_metadata"
|
|
87
|
+
|
|
88
|
+
def applies_to(self, artifact: Artifact) -> bool:
|
|
89
|
+
data = artifact.data
|
|
90
|
+
if data.startswith(PNG_SIGNATURE) or data.startswith(JPEG_SIGNATURE):
|
|
91
|
+
return True
|
|
92
|
+
return artifact.ref.media_type == "image/svg+xml"
|
|
93
|
+
|
|
94
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome:
|
|
95
|
+
data = artifact.data
|
|
96
|
+
if data.startswith(PNG_SIGNATURE):
|
|
97
|
+
return InspectorOutcome(findings=self._png(data))
|
|
98
|
+
if data.startswith(JPEG_SIGNATURE):
|
|
99
|
+
return InspectorOutcome(findings=self._jpeg(data))
|
|
100
|
+
if artifact.text is not None:
|
|
101
|
+
return InspectorOutcome(findings=self._svg(artifact.text))
|
|
102
|
+
return InspectorOutcome.skipped("unsupported container for metadata inspection")
|
|
103
|
+
|
|
104
|
+
def _finding(self, category: str, summary: str, details: dict[str, object]) -> Finding:
|
|
105
|
+
return Finding(
|
|
106
|
+
detector=self.name,
|
|
107
|
+
category=category,
|
|
108
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
109
|
+
severity=Severity.INFO,
|
|
110
|
+
summary=summary,
|
|
111
|
+
label=EvidenceLabel.CONFIRMED,
|
|
112
|
+
details=details,
|
|
113
|
+
removable_by=[], # binary rewriting is out of scope for this milestone
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def _png(self, data: bytes) -> list[Finding]:
|
|
117
|
+
chunks = iter_png_chunks(data)
|
|
118
|
+
if not chunks:
|
|
119
|
+
return [
|
|
120
|
+
self._finding(
|
|
121
|
+
"malformed_container",
|
|
122
|
+
"PNG signature present but no readable chunks",
|
|
123
|
+
{"container": "png"},
|
|
124
|
+
)
|
|
125
|
+
]
|
|
126
|
+
findings: list[Finding] = []
|
|
127
|
+
entries: dict[str, str] = {}
|
|
128
|
+
present: list[str] = []
|
|
129
|
+
for ctype, payload in chunks:
|
|
130
|
+
if ctype.encode("ascii", "replace") not in PNG_METADATA_CHUNKS:
|
|
131
|
+
continue
|
|
132
|
+
present.append(ctype)
|
|
133
|
+
if ctype == "tEXt" and b"\x00" in payload:
|
|
134
|
+
key, _, value = payload.partition(b"\x00")
|
|
135
|
+
entries[_clean(key)] = _clean(value)
|
|
136
|
+
elif ctype == "iTXt" and b"\x00" in payload:
|
|
137
|
+
key, _, rest = payload.partition(b"\x00")
|
|
138
|
+
# compression flag, method, language tag, translated key, text
|
|
139
|
+
parts = rest.split(b"\x00")
|
|
140
|
+
entries[_clean(key)] = _clean(parts[-1]) if parts else ""
|
|
141
|
+
elif ctype == "zTXt":
|
|
142
|
+
key, _, _ = payload.partition(b"\x00")
|
|
143
|
+
entries[_clean(key)] = "<compressed>"
|
|
144
|
+
if present:
|
|
145
|
+
findings.append(
|
|
146
|
+
self._finding(
|
|
147
|
+
"png_metadata",
|
|
148
|
+
f"PNG carries {len(present)} metadata chunk(s)",
|
|
149
|
+
{"container": "png", "chunks": sorted(set(present)), "entries": entries},
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
return findings
|
|
153
|
+
|
|
154
|
+
def _jpeg(self, data: bytes) -> list[Finding]:
|
|
155
|
+
segments = iter_jpeg_segments(data)
|
|
156
|
+
if not segments:
|
|
157
|
+
return []
|
|
158
|
+
found: dict[str, int] = {}
|
|
159
|
+
exif: dict[str, object] = {}
|
|
160
|
+
for marker, payload in segments:
|
|
161
|
+
name = JPEG_APP_NAMES.get(marker, f"APP{marker - 0xE0}" if marker >= 0xE0 else "other")
|
|
162
|
+
if payload.startswith(b"http://ns.adobe.com/xap/1.0/"):
|
|
163
|
+
name = "APP1 (XMP)"
|
|
164
|
+
elif payload.startswith(b"Exif\x00\x00"):
|
|
165
|
+
name = "APP1 (Exif)"
|
|
166
|
+
exif = exif or parse_exif_from_app1(payload)
|
|
167
|
+
found[name] = found.get(name, 0) + 1
|
|
168
|
+
|
|
169
|
+
findings: list[Finding] = [
|
|
170
|
+
self._finding(
|
|
171
|
+
"jpeg_metadata",
|
|
172
|
+
f"JPEG carries {sum(found.values())} metadata segment(s)",
|
|
173
|
+
{"container": "jpeg", "segments": found},
|
|
174
|
+
)
|
|
175
|
+
]
|
|
176
|
+
has_gps = "gps_latitude" in exif and "gps_longitude" in exif
|
|
177
|
+
if exif:
|
|
178
|
+
summary = "Photo embeds GPS location" if has_gps else "Photo embeds camera/EXIF details"
|
|
179
|
+
findings.append(
|
|
180
|
+
Finding(
|
|
181
|
+
detector=self.name,
|
|
182
|
+
category="photo_location" if has_gps else "photo_exif",
|
|
183
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
184
|
+
# Location is the sharp privacy risk; flag it loudly.
|
|
185
|
+
severity=Severity.WARNING if has_gps else Severity.NOTICE,
|
|
186
|
+
summary=summary,
|
|
187
|
+
label=EvidenceLabel.CONFIRMED,
|
|
188
|
+
details=exif,
|
|
189
|
+
removable_by=["strip_image_metadata"],
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
return findings
|
|
193
|
+
|
|
194
|
+
def _svg(self, text: str) -> list[Finding]:
|
|
195
|
+
markers = {
|
|
196
|
+
"metadata_element": "<metadata" in text,
|
|
197
|
+
"xmp": "x:xmpmeta" in text or "adobe:ns:meta" in text,
|
|
198
|
+
"dublin_core": "dc:" in text or "purl.org/dc/" in text,
|
|
199
|
+
"rdf": "rdf:RDF" in text,
|
|
200
|
+
}
|
|
201
|
+
present = [k for k, v in markers.items() if v]
|
|
202
|
+
if not present:
|
|
203
|
+
return []
|
|
204
|
+
return [
|
|
205
|
+
self._finding(
|
|
206
|
+
"svg_metadata",
|
|
207
|
+
f"SVG carries metadata blocks: {', '.join(present)}",
|
|
208
|
+
{"container": "svg", "blocks": present},
|
|
209
|
+
)
|
|
210
|
+
]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Office Open XML metadata inspection (DOCX / XLSX / PPTX).
|
|
2
|
+
|
|
3
|
+
Surfaces the identifying properties these documents carry — author, company,
|
|
4
|
+
revision count, timestamps, custom properties — that ride along invisibly when
|
|
5
|
+
a file is shared. Everything here is ``EMBEDDED_METADATA``: unsigned and
|
|
6
|
+
trivially removable. Standard library only.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from ..artifact import Artifact
|
|
12
|
+
from ..model import EvidenceClass, EvidenceLabel, Finding, Severity
|
|
13
|
+
from ..office import is_ooxml, ooxml_kind, read_properties
|
|
14
|
+
from .base import InspectorOutcome
|
|
15
|
+
|
|
16
|
+
# Fields whose presence is a privacy concern rather than mere housekeeping.
|
|
17
|
+
_PERSONAL = {"author", "last modified by", "company", "manager"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OfficeMetadataInspector:
|
|
21
|
+
name = "office_metadata"
|
|
22
|
+
|
|
23
|
+
def applies_to(self, artifact: Artifact) -> bool:
|
|
24
|
+
return is_ooxml(artifact.data)
|
|
25
|
+
|
|
26
|
+
def inspect(self, artifact: Artifact) -> InspectorOutcome:
|
|
27
|
+
props = read_properties(artifact.data)
|
|
28
|
+
kind = ooxml_kind(artifact.data)
|
|
29
|
+
entries: dict[str, str] = {}
|
|
30
|
+
for bucket in ("core", "app", "custom"):
|
|
31
|
+
entries.update(props[bucket])
|
|
32
|
+
if not entries:
|
|
33
|
+
return InspectorOutcome(findings=[])
|
|
34
|
+
|
|
35
|
+
has_personal = any(k in _PERSONAL for k in entries) or bool(props["custom"])
|
|
36
|
+
finding = Finding(
|
|
37
|
+
detector=self.name,
|
|
38
|
+
category="office_metadata",
|
|
39
|
+
evidence_class=EvidenceClass.EMBEDDED_METADATA,
|
|
40
|
+
severity=Severity.WARNING if has_personal else Severity.NOTICE,
|
|
41
|
+
summary=(
|
|
42
|
+
f"{kind.upper()} document carries {len(entries)} metadata field(s)"
|
|
43
|
+
+ (" including author/company information" if has_personal else "")
|
|
44
|
+
),
|
|
45
|
+
label=EvidenceLabel.CONFIRMED,
|
|
46
|
+
details={
|
|
47
|
+
"container": kind,
|
|
48
|
+
"core": props["core"],
|
|
49
|
+
"app": props["app"],
|
|
50
|
+
"custom": props["custom"],
|
|
51
|
+
},
|
|
52
|
+
removable_by=["strip_office_metadata"],
|
|
53
|
+
)
|
|
54
|
+
return InspectorOutcome(findings=[finding])
|