File size: 6,769 Bytes
4bd7b12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3
"""Export the CVE proof corpus into certkit format.

Reads the internal specification manifest and its Farkas certificates, and emits
one self-contained JSONL record per vulnerability class. Each record carries the
safety relation, the shipped guard, the declared domain, and the multipliers that
prove the guard implies safety.

Two things make this corpus worth publishing rather than a toy:

1. The relations are the *real* ones. `openssl_heartbeat` is the CVE-2014-0160
   length relation, not a paraphrase of it. Six classes across six ecosystems.

2. Every record is independently checkable. The multipliers are the proof, and
   `verify.py` re-checks all of them with `certkit` -- which imports nothing from
   the tool that produced them. A corpus you cannot verify is a claim; this one
   is an artifact.

Field mapping from the internal manifest to the published schema:

    domain_full  ->  domain      constraints bounding the attacker's input
    guard        ->  guard       what the shipped fix checks
    in_bounds    ->  safety      the memory-safety relation that must hold

The obligation model is identical in both: one obligation per safety conjunct,
refuting `domain AND guard AND NOT safety[i]`.

Run from this directory:

    python export.py --repo-root ../../..
"""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any

SCHEMA = "cve-proof-corpus/v1"

# Public identifiers for each class. These are facts about the upstream CVEs, not
# anything derived from the internal pipeline.
CVE_METADATA = {
    "openssl_heartbeat": {
        "cve": "CVE-2014-0160",
        "common_name": "Heartbleed",
        "project": "OpenSSL",
        "cwe": "CWE-125",
        "weakness": "out-of-bounds read",
        "relation": "the heartbeat payload length must fit inside the record it arrived in",
    },
    "libxml2_len_overflow": {
        "cve": "CVE-2015-8317",
        "common_name": "libxml2 length overflow",
        "project": "libxml2",
        "cwe": "CWE-125",
        "weakness": "out-of-bounds read",
        "relation": "a declared length must not exceed the remaining input",
    },
    "zlib_inflate_extra": {
        "cve": "CVE-2022-37434",
        "common_name": "zlib inflate extra-field overflow",
        "project": "zlib",
        "cwe": "CWE-787",
        "weakness": "out-of-bounds write",
        "relation": "the extra-field copy must fit the destination state buffer",
    },
    "libpng_rfc1123": {
        "cve": "CVE-2015-7981",
        "common_name": "libpng time formatting overflow",
        "project": "libpng",
        "cwe": "CWE-125",
        "weakness": "out-of-bounds read",
        "relation": "the formatted output must fit the fixed destination buffer",
    },
    "sudo_set_cmnd": {
        "cve": "CVE-2021-3156",
        "common_name": "Baron Samedit",
        "project": "sudo",
        "cwe": "CWE-787",
        "weakness": "heap out-of-bounds write",
        "relation": "the concatenated argument length must fit the allocated buffer",
    },
    "curl_ntlm_type3": {
        "cve": "CVE-2019-3822",
        "common_name": "curl NTLM type-3 overflow",
        "project": "curl",
        "cwe": "CWE-787",
        "weakness": "stack out-of-bounds write",
        "relation": "the NTLM response length plus header must fit the output buffer",
    },
}


def fingerprint(body: dict[str, Any]) -> str:
    payload = json.dumps(body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def build_record(name: str, spec: dict[str, Any], certs: dict[str, Any] | None) -> dict[str, Any]:
    """Assemble one published record from the internal manifest entry."""
    meta = CVE_METADATA.get(name, {})

    body: dict[str, Any] = {
        "schema": "certkit/spec/v1",
        "name": name,
        "domain": spec["domain_full"],
        "guard": spec["guard"],
        "safety": spec["in_bounds"],
    }
    body["fingerprint"] = fingerprint(dict(body))

    # Map the internal certificate's per-obligation multipliers onto certkit's
    # obligation list, which is ordered by safety conjunct.
    obligations: list[dict[str, Any]] = []
    if certs:
        by_index = {}
        for ob in certs.get("obligations", []):
            idx = ob.get("in_bounds_atom_index")
            if idx is not None:
                by_index[int(idx)] = ob.get("farkas", {})
        for i in range(len(body["safety"])):
            obligations.append({"multipliers": by_index.get(i, {})})

    certificate = {
        "schema": "certkit/farkas/v1",
        "spec_fingerprint": body["fingerprint"],
        "obligations": obligations,
    }

    return {
        "schema": SCHEMA,
        "id": name,
        "cve": meta.get("cve"),
        "common_name": meta.get("common_name"),
        "project": meta.get("project"),
        "cwe": meta.get("cwe"),
        "weakness": meta.get("weakness"),
        "relation_in_words": meta.get("relation"),
        "variables": spec["vars"],
        "spec": body,
        "certificate": certificate,
        "n_safety_conjuncts": len(body["safety"]),
        "n_domain_atoms": len(body["domain"]),
        "n_guard_atoms": len(body["guard"]),
        "has_certificate": bool(obligations) and all(o["multipliers"] for o in obligations),
    }


def main(argv: Any = None) -> int:
    ap = argparse.ArgumentParser(description="Export the CVE proof corpus.")
    ap.add_argument("--repo-root", type=Path, required=True)
    ap.add_argument(
        "--out",
        type=Path,
        default=Path(__file__).resolve().parent / "cve-proof-corpus.jsonl",
    )
    args = ap.parse_args(argv)

    manifest_path = args.repo_root / "verifier" / "spec_manifest.json"
    cert_dir = args.repo_root / "artifacts" / "certs"

    if not manifest_path.is_file():
        print(f"error: manifest not found at {manifest_path}", file=sys.stderr)
        return 2

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    classes = manifest["classes"]

    records = []
    for name in sorted(classes):
        cert_file = cert_dir / f"{name}.certs.json"
        certs = json.loads(cert_file.read_text(encoding="utf-8")) if cert_file.is_file() else None
        records.append(build_record(name, classes[name], certs))

    with args.out.open("w", encoding="utf-8") as fh:
        for rec in records:
            fh.write(json.dumps(rec, sort_keys=True) + "\n")

    with_cert = sum(1 for r in records if r["has_certificate"])
    print(f"wrote {len(records)} records to {args.out}")
    print(f"  {with_cert} of {len(records)} carry a complete certificate")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())