File size: 1,884 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
#!/usr/bin/env python3
"""Loading helpers for the CVE proof corpus.

Plain Python, no dependencies:

    from loader import load_corpus
    for rec in load_corpus():
        print(rec["cve"], rec["relation_in_words"])

With `datasets` installed:

    from datasets import load_dataset
    ds = load_dataset("json", data_files="cve-proof-corpus.jsonl", split="train")
"""

from __future__ import annotations

import json
from collections.abc import Iterator
from pathlib import Path
from typing import Any

DEFAULT_PATH = Path(__file__).resolve().parent / "cve-proof-corpus.jsonl"


def load_corpus(path: Path | str = DEFAULT_PATH) -> list[dict[str, Any]]:
    """Read every record into a list."""
    p = Path(path)
    return [json.loads(line) for line in p.read_text(encoding="utf-8").splitlines() if line.strip()]


def iter_corpus(path: Path | str = DEFAULT_PATH) -> Iterator[dict[str, Any]]:
    """Stream records one at a time."""
    p = Path(path)
    with p.open(encoding="utf-8") as fh:
        for line in fh:
            if line.strip():
                yield json.loads(line)


def to_certkit(record: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
    """Split a record into the (spec, certificate) pair certkit expects."""
    return record["spec"], record["certificate"]


def by_cwe(path: Path | str = DEFAULT_PATH) -> dict[str, list[str]]:
    """Group record ids by weakness class."""
    out: dict[str, list[str]] = {}
    for rec in iter_corpus(path):
        out.setdefault(rec["cwe"], []).append(rec["id"])
    return out


if __name__ == "__main__":
    corpus = load_corpus()
    print(f"{len(corpus)} records")
    for rec in corpus:
        print(f"  {rec['id']:24s} {rec['cve']:16s} {rec['cwe']:9s} {rec['project']}")
    print()
    print("by weakness:")
    for cwe, ids in sorted(by_cwe().items()):
        print(f"  {cwe}: {', '.join(ids)}")