sealgate 0.1.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.
- sealgate/__init__.py +26 -0
- sealgate/__main__.py +8 -0
- sealgate/api.py +212 -0
- sealgate/attest.py +225 -0
- sealgate/canonical.py +21 -0
- sealgate/checks/__init__.py +1 -0
- sealgate/checks/fields.py +79 -0
- sealgate/checks/intake.py +34 -0
- sealgate/checks/objects.py +48 -0
- sealgate/checks/rawscan.py +95 -0
- sealgate/checks/revisions.py +51 -0
- sealgate/checks/similarity.py +93 -0
- sealgate/cli.py +610 -0
- sealgate/data/matchers.yaml +83 -0
- sealgate/data/signals.yaml +17 -0
- sealgate/hardening/__init__.py +7 -0
- sealgate/hardening/facts.py +614 -0
- sealgate/hardening/profile.py +585 -0
- sealgate/integrity.py +541 -0
- sealgate/inventory.py +179 -0
- sealgate/matchers.py +388 -0
- sealgate/observer.py +54 -0
- sealgate/pipeline.py +293 -0
- sealgate/py.typed +0 -0
- sealgate/sandbox.py +199 -0
- sealgate/settings.py +143 -0
- sealgate/signals.py +183 -0
- sealgate/templates/__init__.py +19 -0
- sealgate/templates/approval.py +121 -0
- sealgate/templates/induce.py +501 -0
- sealgate/templates/learn.py +114 -0
- sealgate/templates/store.py +264 -0
- sealgate/tools/__init__.py +2 -0
- sealgate/tools/evaluate.py +221 -0
- sealgate/tools/fixtures.py +470 -0
- sealgate/tools/mutate.py +723 -0
- sealgate/types.py +135 -0
- sealgate/worker.py +472 -0
- sealgate-0.1.0.dist-info/METADATA +92 -0
- sealgate-0.1.0.dist-info/RECORD +46 -0
- sealgate-0.1.0.dist-info/WHEEL +4 -0
- sealgate-0.1.0.dist-info/entry_points.txt +2 -0
- sealgate-0.1.0.dist-info/licenses/LICENSE +387 -0
- sealgate-0.1.0.dist-info/licenses/NOTICE +6 -0
- sealgate-0.1.0.dist-info/licenses/licenses/COMMONS-CLAUSE.txt +11 -0
- sealgate-0.1.0.dist-info/licenses/licenses/MPL-2.0.txt +373 -0
sealgate/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""sealgate: check PDFs against learned layouts and report findings."""
|
|
3
|
+
|
|
4
|
+
from importlib.metadata import version
|
|
5
|
+
|
|
6
|
+
from sealgate.api import Engine, VerifyResult, verify
|
|
7
|
+
from sealgate.observer import Observer
|
|
8
|
+
from sealgate.settings import SandboxLimits, Settings
|
|
9
|
+
from sealgate.types import Expected, Finding, Signal, Template, Verdict
|
|
10
|
+
|
|
11
|
+
__version__: str = version("sealgate")
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Engine",
|
|
15
|
+
"Expected",
|
|
16
|
+
"Finding",
|
|
17
|
+
"Observer",
|
|
18
|
+
"SandboxLimits",
|
|
19
|
+
"Settings",
|
|
20
|
+
"Signal",
|
|
21
|
+
"Template",
|
|
22
|
+
"Verdict",
|
|
23
|
+
"VerifyResult",
|
|
24
|
+
"__version__",
|
|
25
|
+
"verify",
|
|
26
|
+
]
|
sealgate/__main__.py
ADDED
sealgate/api.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Public API: the Engine and a one-call verify()."""
|
|
3
|
+
|
|
4
|
+
import datetime as dt
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from sealgate import pipeline
|
|
12
|
+
from sealgate.hardening import ProfileKeyError, load_key
|
|
13
|
+
from sealgate.inventory import build_inventory
|
|
14
|
+
from sealgate.matchers import load_library
|
|
15
|
+
from sealgate.observer import Observer
|
|
16
|
+
from sealgate.settings import Settings
|
|
17
|
+
from sealgate.signals import load_signal_config
|
|
18
|
+
from sealgate.templates import TemplateError, TemplateStore
|
|
19
|
+
from sealgate.templates.store import validate
|
|
20
|
+
from sealgate.types import Expected, RulesSource, Template, Verdict
|
|
21
|
+
|
|
22
|
+
DEFAULT_SETTINGS = Settings()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class VerifyResult:
|
|
27
|
+
"""A verdict with the rules snapshot the run used.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
verdict: The verdict.
|
|
31
|
+
template: The matched template (None without a match), taken from ``rules``.
|
|
32
|
+
rules: The templates the run considered; ``verdict["rulesDigest"]`` is their digest.
|
|
33
|
+
facts: Allow-listed structure facts of the parsed document (None when it could not be
|
|
34
|
+
parsed): counts, names, sizes and keyed (HMAC) hashes only, never plain inner hashes.
|
|
35
|
+
Input for ``Engine.build_inventory``; it holds no text or field values.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
verdict: Verdict
|
|
39
|
+
template: Template | None
|
|
40
|
+
rules: list[Template]
|
|
41
|
+
facts: dict[str, Any] | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Engine:
|
|
45
|
+
"""Verifies documents against the store's templates (or inline ones).
|
|
46
|
+
|
|
47
|
+
The profile key, matcher library and signal policy are loaded once here. Without
|
|
48
|
+
``matchers_path`` the store's own library is used. A profile key is required when an
|
|
49
|
+
approved version in the store carries a hardening profile; a missing key fails here.
|
|
50
|
+
The engine holds no mutable state besides the store, so ``verify`` is thread-safe.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
store: TemplateStore,
|
|
56
|
+
settings: Settings = DEFAULT_SETTINGS,
|
|
57
|
+
observers: Sequence[Observer] = (),
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Load the profile key, matcher library and signal policy.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
store: Template store holding the rules to verify against.
|
|
63
|
+
settings: Engine settings. Defaults use the packaged matcher library and signal policy.
|
|
64
|
+
observers: Called for every timed check and every verdict. Their failures are
|
|
65
|
+
logged once per type and never change a verdict.
|
|
66
|
+
|
|
67
|
+
Raises:
|
|
68
|
+
ProfileKeyError: An approved version carries a hardening profile and no readable
|
|
69
|
+
profile key is configured.
|
|
70
|
+
MatcherError: The matcher library cannot be loaded.
|
|
71
|
+
SignalConfigError: The signal policy cannot be loaded.
|
|
72
|
+
"""
|
|
73
|
+
self.store = store
|
|
74
|
+
self.settings = settings
|
|
75
|
+
lib = load_library(settings.matchers_path) if settings.matchers_path else store.lib
|
|
76
|
+
key = load_key(settings.profile_key_path) if settings.profile_key_path else None
|
|
77
|
+
if key is None and any(
|
|
78
|
+
v.get("status") == "approved" and v.get("hardening")
|
|
79
|
+
for t in store.list()
|
|
80
|
+
for v in t.get("versions", [])
|
|
81
|
+
):
|
|
82
|
+
raise ProfileKeyError("a profile key is required: approved versions carry hardening profiles")
|
|
83
|
+
self._cfg = pipeline.RunConfig(
|
|
84
|
+
lib=lib,
|
|
85
|
+
signals=load_signal_config(settings.signals_path),
|
|
86
|
+
limits=settings.sandbox,
|
|
87
|
+
max_bytes=settings.max_bytes,
|
|
88
|
+
key=key,
|
|
89
|
+
observers=tuple(observers),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def verify( # noqa: PLR0913 (keyword-only options of the public API)
|
|
93
|
+
self,
|
|
94
|
+
data: bytes,
|
|
95
|
+
*,
|
|
96
|
+
expected: Expected | None = None,
|
|
97
|
+
template_id: str | None = None,
|
|
98
|
+
templates: list[Template] | None = None,
|
|
99
|
+
today: dt.date | None = None,
|
|
100
|
+
cancel: threading.Event | None = None,
|
|
101
|
+
) -> Verdict:
|
|
102
|
+
"""Verify one document.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
data: The PDF bytes.
|
|
106
|
+
expected: What the caller expects: its request id and field values to cross-check.
|
|
107
|
+
template_id: Only consider this template id.
|
|
108
|
+
templates: Inline rules that replace the store for this call. They are validated like
|
|
109
|
+
stored ones. The verdict then has ``rulesSource`` ``"inline"``.
|
|
110
|
+
today: Date that anchors date rules. Defaults to the current date.
|
|
111
|
+
cancel: Set it from another thread to stop the parse worker; the run then ends
|
|
112
|
+
with a CHECK_ERROR finding (QUARANTINE).
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
The verdict. Errors inside a check become findings, never exceptions.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
TemplateError: Inline templates are invalid.
|
|
119
|
+
"""
|
|
120
|
+
return self.verify_detailed(
|
|
121
|
+
data, expected=expected, template_id=template_id, templates=templates, today=today, cancel=cancel
|
|
122
|
+
).verdict
|
|
123
|
+
|
|
124
|
+
def verify_detailed( # noqa: PLR0913 (keyword-only options of the public API)
|
|
125
|
+
self,
|
|
126
|
+
data: bytes,
|
|
127
|
+
*,
|
|
128
|
+
expected: Expected | None = None,
|
|
129
|
+
template_id: str | None = None,
|
|
130
|
+
templates: list[Template] | None = None,
|
|
131
|
+
today: dt.date | None = None,
|
|
132
|
+
cancel: threading.Event | None = None,
|
|
133
|
+
) -> VerifyResult:
|
|
134
|
+
"""Like ``verify``; also returns the matched template and the rules from the same snapshot.
|
|
135
|
+
|
|
136
|
+
Use it when something must be consistent with the verdict, such as an attestation:
|
|
137
|
+
the store may change while a run is in progress, so reading it again afterwards could
|
|
138
|
+
give another version.
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
TemplateError: Inline templates are invalid.
|
|
142
|
+
"""
|
|
143
|
+
source: RulesSource
|
|
144
|
+
if templates is None:
|
|
145
|
+
source, rules = "store", self.store.list()
|
|
146
|
+
else:
|
|
147
|
+
source, rules = "inline", [validate(t, self._cfg.lib) for t in templates]
|
|
148
|
+
considered = [t for t in rules if not template_id or t["id"] == template_id]
|
|
149
|
+
req = pipeline.Request(
|
|
150
|
+
templates=considered,
|
|
151
|
+
rules_source=source,
|
|
152
|
+
expected=expected or {},
|
|
153
|
+
template_id=template_id,
|
|
154
|
+
today=today,
|
|
155
|
+
cancel=cancel,
|
|
156
|
+
)
|
|
157
|
+
verdict, matched, facts = pipeline.run_detailed(data, self._cfg, req)
|
|
158
|
+
return VerifyResult(verdict=verdict, template=matched, rules=considered, facts=facts)
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def can_inventory(self) -> bool:
|
|
162
|
+
"""True when a profile key is loaded, so ``build_inventory`` works."""
|
|
163
|
+
return self._cfg.key is not None
|
|
164
|
+
|
|
165
|
+
def build_inventory(self, result: VerifyResult) -> dict[str, Any]:
|
|
166
|
+
"""The CycloneDX 1.6 inventory of a verified document (structure only, keyed hashes).
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
result: From ``verify_detailed``; no second parse is run.
|
|
170
|
+
|
|
171
|
+
Raises:
|
|
172
|
+
ProfileKeyError: The engine has no profile key (inner hashes are keyed with it).
|
|
173
|
+
"""
|
|
174
|
+
if self._cfg.key is None:
|
|
175
|
+
raise ProfileKeyError("an inventory needs a profile key")
|
|
176
|
+
return build_inventory(result.facts, result.verdict)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def verify( # noqa: PLR0913 (keyword-only options of the public API)
|
|
180
|
+
data: bytes,
|
|
181
|
+
templates_dir: Path | str,
|
|
182
|
+
*,
|
|
183
|
+
settings: Settings = DEFAULT_SETTINGS,
|
|
184
|
+
expected: Expected | None = None,
|
|
185
|
+
template_id: str | None = None,
|
|
186
|
+
today: dt.date | None = None,
|
|
187
|
+
) -> Verdict:
|
|
188
|
+
"""Verify one document against the templates in a directory.
|
|
189
|
+
|
|
190
|
+
Builds an Engine for the call. Use an Engine directly when verifying many documents.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
data: The PDF bytes.
|
|
194
|
+
templates_dir: Directory of template files.
|
|
195
|
+
settings: Engine settings.
|
|
196
|
+
expected: What the caller expects: its request id and field values to cross-check.
|
|
197
|
+
template_id: Only consider this template id.
|
|
198
|
+
today: Date that anchors date rules. Defaults to the current date.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
The verdict.
|
|
202
|
+
|
|
203
|
+
Raises:
|
|
204
|
+
TemplateError: The directory is missing or a template is invalid.
|
|
205
|
+
ProfileKeyError: A profile key is needed and not readable.
|
|
206
|
+
"""
|
|
207
|
+
root = Path(templates_dir)
|
|
208
|
+
if not root.is_dir():
|
|
209
|
+
raise TemplateError("templates directory not found")
|
|
210
|
+
lib = load_library(settings.matchers_path)
|
|
211
|
+
engine = Engine(TemplateStore(root, lib), settings)
|
|
212
|
+
return engine.verify(data, expected=expected, template_id=template_id, today=today)
|
sealgate/attest.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Verdict attestations: an in-toto Statement v1 in a DSSE envelope, signed with Ed25519.
|
|
3
|
+
|
|
4
|
+
An attestation says "this exact PDF (by sha256) was checked against this approved template
|
|
5
|
+
by this sealgate version, with this outcome". It is portable: it can be stored and passed on
|
|
6
|
+
without trusting the transport, and checked with standard tooling (cosign, in-toto).
|
|
7
|
+
|
|
8
|
+
The predicate carries the verdict without ``durationsMs``, ``verdictId``, ``requestId``, finding
|
|
9
|
+
``detail`` and the approver: codes, severities, hashes, ids and versions only. The subject name
|
|
10
|
+
is fixed (``document.pdf``), never the upload filename. Signing uses the same key and ``kid``
|
|
11
|
+
as response signing (``sealgate.integrity``); HMAC is refused, since third parties could not
|
|
12
|
+
verify it. ``cryptography`` is imported lazily (``sealgate[integrity]``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import base64
|
|
18
|
+
import binascii
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import json
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from typing import TYPE_CHECKING, Any
|
|
23
|
+
|
|
24
|
+
from sealgate.canonical import dumps, sha256_json
|
|
25
|
+
from sealgate.integrity import SigningKey, VerifyKey
|
|
26
|
+
from sealgate.types import Template, Verdict
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from sealgate.api import VerifyResult
|
|
30
|
+
|
|
31
|
+
PAYLOAD_TYPE = "application/vnd.in-toto+json"
|
|
32
|
+
STATEMENT_TYPE = "https://in-toto.io/Statement/v1"
|
|
33
|
+
PREDICATE_TYPE = "https://github.com/D3vl0per/sealgate/attestation/verification/v1"
|
|
34
|
+
SUBJECT_NAME = "document.pdf"
|
|
35
|
+
VERIFIER_ID = "sealgate"
|
|
36
|
+
_B64_ALPHABET = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/-_=")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AttestationError(Exception):
|
|
40
|
+
"""Verification failed. ``code`` is ``malformed``, ``bad_signature``, ``unknown_key``,
|
|
41
|
+
``payload_type``, ``predicate_type`` or ``subject_mismatch``."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, code: str) -> None:
|
|
44
|
+
super().__init__(code)
|
|
45
|
+
self.code = code
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pae(payload_type: str, body: bytes) -> bytes:
|
|
49
|
+
"""DSSE v1 pre-authentication encoding: ``DSSEv1 SP LEN(type) SP type SP LEN(body) SP body``.
|
|
50
|
+
|
|
51
|
+
Lengths are byte counts as ASCII decimal.
|
|
52
|
+
"""
|
|
53
|
+
t = payload_type.encode("utf-8")
|
|
54
|
+
return b"DSSEv1 %d %s %d %s" % (len(t), t, len(body), body)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _approval_digest(verdict: Verdict, template: Template | None) -> str | None:
|
|
58
|
+
if template is None or template.get("id") != verdict.get("templateId"):
|
|
59
|
+
return None
|
|
60
|
+
for version in template.get("versions", []):
|
|
61
|
+
if version.get("id") == verdict.get("templateVersion") and version.get("status") == "approved":
|
|
62
|
+
approval = version.get("approval")
|
|
63
|
+
return approval["digest"] if approval else None
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def build_statement(
|
|
68
|
+
verdict: Verdict,
|
|
69
|
+
template: Template | None,
|
|
70
|
+
*,
|
|
71
|
+
now: dt.datetime | None = None,
|
|
72
|
+
inventory_digest: str | None = None,
|
|
73
|
+
) -> dict:
|
|
74
|
+
"""The in-toto Statement for a verdict.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
verdict: The verdict.
|
|
78
|
+
template: The template the verdict matched (store or inline), for its approval digest.
|
|
79
|
+
None, or another template, gives ``approvalDigest: null``.
|
|
80
|
+
now: Time of verification (default: now, UTC). Written as RFC 3339 UTC, seconds.
|
|
81
|
+
inventory_digest: sha256 of the canonical JSON of the document inventory. Adds
|
|
82
|
+
``predicate.inventoryDigest``, so the inventory can be stored apart and still be checked.
|
|
83
|
+
"""
|
|
84
|
+
when = (now or dt.datetime.now(dt.UTC)).astimezone(dt.UTC).replace(microsecond=0)
|
|
85
|
+
predicate: dict[str, Any] = {
|
|
86
|
+
"status": verdict["status"],
|
|
87
|
+
"signal": verdict["signal"],
|
|
88
|
+
"findings": [
|
|
89
|
+
{"code": f["code"], "severity": f["severity"], "check": f["check"]} for f in verdict["findings"]
|
|
90
|
+
],
|
|
91
|
+
"templateId": verdict["templateId"],
|
|
92
|
+
"templateVersion": verdict["templateVersion"],
|
|
93
|
+
"approvalDigest": _approval_digest(verdict, template),
|
|
94
|
+
"rulesSource": verdict["rulesSource"],
|
|
95
|
+
"rulesDigest": verdict["rulesDigest"],
|
|
96
|
+
"skeletonSha256": verdict["skeletonSha256"],
|
|
97
|
+
"tlshDistance": verdict["tlshDistance"],
|
|
98
|
+
"verifier": {"id": VERIFIER_ID, "version": verdict["sealgateVersion"]},
|
|
99
|
+
"timeVerified": when.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
100
|
+
}
|
|
101
|
+
if inventory_digest is not None:
|
|
102
|
+
predicate["inventoryDigest"] = inventory_digest
|
|
103
|
+
return {
|
|
104
|
+
"_type": STATEMENT_TYPE,
|
|
105
|
+
"subject": [{"name": SUBJECT_NAME, "digest": {"sha256": verdict["sha256"]}}],
|
|
106
|
+
"predicateType": PREDICATE_TYPE,
|
|
107
|
+
"predicate": predicate,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def attest(
|
|
112
|
+
result: VerifyResult,
|
|
113
|
+
key: SigningKey,
|
|
114
|
+
*,
|
|
115
|
+
now: dt.datetime | None = None,
|
|
116
|
+
inventory: dict | None = None,
|
|
117
|
+
) -> dict:
|
|
118
|
+
"""Sign the statement for an ``Engine.verify_detailed`` result.
|
|
119
|
+
|
|
120
|
+
The approval digest comes from the template the run matched, never from a later read of
|
|
121
|
+
the store. With ``inventory`` the predicate carries its digest (``sha256_json``); the
|
|
122
|
+
inventory itself is not signed in. Fails closed when the rules snapshot does not match the
|
|
123
|
+
verdict's digest.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
ValueError: The rules do not match ``rulesDigest``, the matched template is not one of
|
|
127
|
+
them, or the key is not Ed25519.
|
|
128
|
+
"""
|
|
129
|
+
verdict, template = result.verdict, result.template
|
|
130
|
+
if sha256_json(result.rules) != verdict["rulesDigest"]:
|
|
131
|
+
raise ValueError("rules snapshot does not match the verdict's rulesDigest")
|
|
132
|
+
if template is not None and (template not in result.rules or template.get("id") != verdict["templateId"]):
|
|
133
|
+
raise ValueError("matched template is not part of the rules snapshot")
|
|
134
|
+
digest = sha256_json(inventory) if inventory is not None else None
|
|
135
|
+
return sign_envelope(build_statement(verdict, template, now=now, inventory_digest=digest), key)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def sign_envelope(statement: dict, key: SigningKey) -> dict:
|
|
139
|
+
"""A DSSE envelope over the statement (canonical JSON), signed with an Ed25519 key.
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
ValueError: The key is not Ed25519.
|
|
143
|
+
"""
|
|
144
|
+
if key.alg != "ed25519":
|
|
145
|
+
raise ValueError("attestations need an ed25519 key")
|
|
146
|
+
body = dumps(statement).encode("utf-8")
|
|
147
|
+
sig = key.sign(pae(PAYLOAD_TYPE, body))
|
|
148
|
+
return {
|
|
149
|
+
"payloadType": PAYLOAD_TYPE,
|
|
150
|
+
"payload": base64.b64encode(body).decode("ascii"),
|
|
151
|
+
"signatures": [{"keyid": key.kid, "sig": base64.b64encode(sig).decode("ascii")}],
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _b64(text: Any) -> bytes:
|
|
156
|
+
"""Standard or URL-safe base64, with or without padding (as the DSSE spec allows)."""
|
|
157
|
+
if not isinstance(text, str) or not set(text) <= _B64_ALPHABET:
|
|
158
|
+
raise AttestationError("malformed")
|
|
159
|
+
std = text.rstrip("=").replace("-", "+").replace("_", "/")
|
|
160
|
+
try:
|
|
161
|
+
return base64.b64decode(std + "=" * (-len(std) % 4), validate=True)
|
|
162
|
+
except (binascii.Error, ValueError):
|
|
163
|
+
raise AttestationError("malformed") from None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _parse(envelope: Any) -> tuple[str, bytes, list[tuple[str, bytes]]]:
|
|
167
|
+
if not isinstance(envelope, dict):
|
|
168
|
+
raise AttestationError("malformed")
|
|
169
|
+
ptype, sigs = envelope.get("payloadType"), envelope.get("signatures")
|
|
170
|
+
if not isinstance(ptype, str) or not isinstance(sigs, list) or not sigs:
|
|
171
|
+
raise AttestationError("malformed")
|
|
172
|
+
body = _b64(envelope.get("payload"))
|
|
173
|
+
out: list[tuple[str, bytes]] = []
|
|
174
|
+
for s in sigs:
|
|
175
|
+
if not isinstance(s, dict) or not isinstance(s.get("keyid", ""), str):
|
|
176
|
+
raise AttestationError("malformed")
|
|
177
|
+
out.append((s.get("keyid", ""), _b64(s.get("sig"))))
|
|
178
|
+
return ptype, body, out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _check_subject(statement: dict, pdf_sha256: str) -> None:
|
|
182
|
+
subject = statement.get("subject")
|
|
183
|
+
want = pdf_sha256.lower()
|
|
184
|
+
ok = (
|
|
185
|
+
isinstance(subject, list)
|
|
186
|
+
and len(subject) == 1
|
|
187
|
+
and isinstance(subject[0], dict)
|
|
188
|
+
and isinstance(subject[0].get("digest"), dict)
|
|
189
|
+
and subject[0]["digest"].get("sha256") == want
|
|
190
|
+
)
|
|
191
|
+
if not ok:
|
|
192
|
+
raise AttestationError("subject_mismatch")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def verify_envelope(envelope: dict, keys: Mapping[str, VerifyKey], *, pdf_sha256: str | None = None) -> dict:
|
|
196
|
+
"""Verify a DSSE envelope and return its statement.
|
|
197
|
+
|
|
198
|
+
The signature over the PAE is checked first, by a key picked by ``keyid`` (Ed25519 keys
|
|
199
|
+
only); then the payload type, statement and predicate type; then, with ``pdf_sha256``,
|
|
200
|
+
that the single subject is that document.
|
|
201
|
+
|
|
202
|
+
Raises:
|
|
203
|
+
AttestationError: ``malformed``, ``unknown_key``, ``bad_signature``, ``payload_type``,
|
|
204
|
+
``predicate_type`` or ``subject_mismatch``.
|
|
205
|
+
"""
|
|
206
|
+
ptype, body, sigs = _parse(envelope)
|
|
207
|
+
message = pae(ptype, body)
|
|
208
|
+
known = [(keys[kid], sig) for kid, sig in sigs if kid in keys and keys[kid].alg == "ed25519"]
|
|
209
|
+
if not known:
|
|
210
|
+
raise AttestationError("unknown_key")
|
|
211
|
+
if not any(key.verify(message, sig) for key, sig in known):
|
|
212
|
+
raise AttestationError("bad_signature")
|
|
213
|
+
if ptype != PAYLOAD_TYPE:
|
|
214
|
+
raise AttestationError("payload_type")
|
|
215
|
+
try:
|
|
216
|
+
statement = json.loads(body.decode("utf-8"))
|
|
217
|
+
except (UnicodeDecodeError, ValueError, RecursionError):
|
|
218
|
+
raise AttestationError("malformed") from None
|
|
219
|
+
if not isinstance(statement, dict):
|
|
220
|
+
raise AttestationError("malformed")
|
|
221
|
+
if statement.get("_type") != STATEMENT_TYPE or statement.get("predicateType") != PREDICATE_TYPE:
|
|
222
|
+
raise AttestationError("predicate_type")
|
|
223
|
+
if pdf_sha256 is not None:
|
|
224
|
+
_check_subject(statement, pdf_sha256)
|
|
225
|
+
return statement
|
sealgate/canonical.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Canonical JSON used for every hashed identity.
|
|
3
|
+
|
|
4
|
+
Keys sorted, no insignificant whitespace, non-ASCII emitted as-is.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def dumps(obj: Any) -> str:
|
|
13
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def sha256_text(text: str) -> str:
|
|
17
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sha256_json(obj: Any) -> str:
|
|
21
|
+
return sha256_text(dumps(obj))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Field rules, boilerplate and caller expectations.
|
|
3
|
+
|
|
4
|
+
Findings name the field only, never its value. Rules come from the matcher library and
|
|
5
|
+
the template (see sealgate.matchers).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import datetime as dt
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
from sealgate import matchers
|
|
12
|
+
from sealgate.canonical import sha256_text
|
|
13
|
+
from sealgate.matchers import MatcherLibrary
|
|
14
|
+
from sealgate.types import Expected, Finding, Template, Version, finding
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def collapse(text: str) -> str:
|
|
18
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _field_rules(
|
|
22
|
+
policy: Template, values: dict[str, str], lib: MatcherLibrary, today: dt.date | None
|
|
23
|
+
) -> tuple[dict[str, matchers.ResolvedRule], list[Finding]]:
|
|
24
|
+
out: list[Finding] = []
|
|
25
|
+
rules = {f["name"]: matchers.resolve(f, policy, lib) for f in policy.get("fields", [])}
|
|
26
|
+
for f in policy.get("fields", []):
|
|
27
|
+
name = f["name"]
|
|
28
|
+
v = collapse(values.get(name, "") or "")
|
|
29
|
+
if v == "":
|
|
30
|
+
if f.get("required"):
|
|
31
|
+
out.append(finding("FIELD_MISSING", "QUARANTINE", "fields", name))
|
|
32
|
+
continue
|
|
33
|
+
for reason in matchers.check(rules[name], v, today):
|
|
34
|
+
code, _, why = reason.partition(":")
|
|
35
|
+
out.append(finding(code, "QUARANTINE", "fields", f"{name} ({why})" if why else name))
|
|
36
|
+
return rules, out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _expectations(
|
|
40
|
+
policy: Template, values: dict[str, str], expected: Expected, rules: dict[str, matchers.ResolvedRule]
|
|
41
|
+
) -> list[Finding]:
|
|
42
|
+
out: list[Finding] = []
|
|
43
|
+
supplied = expected.get("fields") or {}
|
|
44
|
+
# mandatory for fields marked `expected`: without them a signer could put any
|
|
45
|
+
# pattern-conforming text into those fields
|
|
46
|
+
missing = [
|
|
47
|
+
f["name"]
|
|
48
|
+
for f in policy.get("fields", [])
|
|
49
|
+
if f.get("expected") and (supplied.get(f["name"]) is None or not str(supplied[f["name"]]).strip())
|
|
50
|
+
]
|
|
51
|
+
if missing:
|
|
52
|
+
out.append(finding("EXPECTED_MISSING", "QUARANTINE", "fields", ",".join(missing)))
|
|
53
|
+
for name, want in supplied.items():
|
|
54
|
+
if want is None:
|
|
55
|
+
continue # reported as EXPECTED_MISSING above when the field is cross-checked
|
|
56
|
+
rule = rules.get(name) or {"normalize": matchers.DEFAULT_NORMALIZE}
|
|
57
|
+
if not matchers.same(rule, values.get(name, ""), want):
|
|
58
|
+
out.append(finding("EXPECTED_MISMATCH", "QUARANTINE", "fields", name))
|
|
59
|
+
return out
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_fields( # noqa: PLR0913
|
|
63
|
+
policy: Template,
|
|
64
|
+
field_texts: dict[str, str],
|
|
65
|
+
boilerplate_text: str,
|
|
66
|
+
*,
|
|
67
|
+
expected: Expected,
|
|
68
|
+
candidates: list[Version],
|
|
69
|
+
lib: MatcherLibrary,
|
|
70
|
+
today: dt.date | None = None,
|
|
71
|
+
) -> list[Finding]:
|
|
72
|
+
"""Field rules, boilerplate against `candidates` (the matched version, else every
|
|
73
|
+
approved one) and caller expectations."""
|
|
74
|
+
rules, out = _field_rules(policy, field_texts, lib, today)
|
|
75
|
+
bp_sha = sha256_text(collapse(boilerplate_text))
|
|
76
|
+
if not any(v.get("boilerplateSha256") == bp_sha for v in candidates):
|
|
77
|
+
out.append(finding("BOILERPLATE_MISMATCH", "QUARANTINE", "fields"))
|
|
78
|
+
out += _expectations(policy, field_texts, expected, rules)
|
|
79
|
+
return out
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Intake: size, header, %%EOF and trailing data."""
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from sealgate.types import Finding, finding
|
|
7
|
+
|
|
8
|
+
MAX_TRAILING_JUNK = 2
|
|
9
|
+
WS = b" \t\r\n\x0c\x00"
|
|
10
|
+
EOF_MARKER = re.compile(rb"(?:^|(?<=[\r\n]))%%EOF")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def eof_positions(data: bytes) -> list[int]:
|
|
14
|
+
"""Offsets of real %%EOF markers: at the start of the file or of a line."""
|
|
15
|
+
return [m.start() for m in EOF_MARKER.finditer(data)]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def intake(data: bytes, *, max_bytes: int) -> list[Finding]:
|
|
19
|
+
if len(data) == 0:
|
|
20
|
+
return [finding("EMPTY", "REJECT", "intake")]
|
|
21
|
+
if len(data) > max_bytes:
|
|
22
|
+
return [finding("TOO_LARGE", "REJECT", "intake", f"size>{max_bytes}")]
|
|
23
|
+
if not data.startswith(b"%PDF-"):
|
|
24
|
+
return [finding("BAD_HEADER", "REJECT", "intake", "header not at offset 0")]
|
|
25
|
+
eofs = eof_positions(data)
|
|
26
|
+
if not eofs:
|
|
27
|
+
return [finding("NO_EOF", "REJECT", "intake")]
|
|
28
|
+
last = eofs[-1]
|
|
29
|
+
junk = sum(1 for b in data[last + 5 :] if b not in WS)
|
|
30
|
+
if junk > MAX_TRAILING_JUNK:
|
|
31
|
+
return [
|
|
32
|
+
finding("TRAILING_DATA", "QUARANTINE", "intake", f"{junk} non-whitespace bytes after last %%EOF")
|
|
33
|
+
]
|
|
34
|
+
return []
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LicenseRef-MPL-2.0-with-Commons-Clause
|
|
2
|
+
"""Structure findings from the sandboxed worker's facts (parse result, risky keys, objects).
|
|
3
|
+
|
|
4
|
+
Details carry fixed wording, key paths, token names and counts only: parser messages can
|
|
5
|
+
quote document bytes, so they never reach a finding.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Collection
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from sealgate.types import Finding, finding
|
|
12
|
+
|
|
13
|
+
REPAIR_MARKERS = ("damaged", "reconstruct", "xref not found", "recover", "invalid xref", "bad xref")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse_error(facts: dict[str, Any]) -> list[Finding]:
|
|
17
|
+
"""PARSE_ERROR when the worker could not parse the document (reason is an exception name)."""
|
|
18
|
+
if facts.get("ok"):
|
|
19
|
+
return []
|
|
20
|
+
return [finding("PARSE_ERROR", "QUARANTINE", "structure", str(facts.get("reason", "")))]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def structure(facts: dict[str, Any], allowed_risk: Collection[str], allow_encrypted: bool) -> list[Finding]:
|
|
24
|
+
out = [
|
|
25
|
+
finding("RISK_KEY", "QUARANTINE", "structure", r) for r in facts["riskPaths"] if r not in allowed_risk
|
|
26
|
+
]
|
|
27
|
+
if facts["encrypted"] and not allow_encrypted:
|
|
28
|
+
out.append(finding("ENCRYPTED", "QUARANTINE", "structure"))
|
|
29
|
+
warnings = facts.get("parserWarnings", [])
|
|
30
|
+
repairs = [w for w in warnings if any(k in w.lower() for k in REPAIR_MARKERS)]
|
|
31
|
+
if repairs:
|
|
32
|
+
out.append(
|
|
33
|
+
finding(
|
|
34
|
+
"PARSER_REPAIR",
|
|
35
|
+
"QUARANTINE",
|
|
36
|
+
"structure",
|
|
37
|
+
f"{len(repairs)} repair warning type(s) (xref/structure reconstructed)",
|
|
38
|
+
)
|
|
39
|
+
)
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def object_keywords(facts: dict[str, Any], allowed_raw: Collection[str]) -> list[Finding]:
|
|
44
|
+
"""Risky names found at object level (also inside object streams) by the worker."""
|
|
45
|
+
bad = [t for t in facts.get("objectTokens", []) if t not in allowed_raw]
|
|
46
|
+
if bad:
|
|
47
|
+
return [finding("OBJECT_KEYWORD", "QUARANTINE", "structure", "tokens=" + ",".join(bad))]
|
|
48
|
+
return []
|