File size: 7,221 Bytes
a56b6dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score every model on the test split and the shifted challenge set; write the leaderboard.

Usage: python src/evaluate.py --data ../incident-logs-dataset/data --challenge data/challenge.parquet --out eval

Writes eval/metrics.json, eval/leaderboard.md, eval/confusion_matrix.png and eval/test_scores.parquet
(Python reference scores for the JavaScript parity test).
"""
import argparse
import json
import os

import matplotlib
import numpy as np
import pandas as pd
from skops.io import get_untrusted_types, load
from sklearn.metrics import (average_precision_score, confusion_matrix, f1_score, precision_score, recall_score,
                             roc_auc_score)

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

from common import featurize_df, load_events, mask_line, token_matrix  # noqa: E402
from rules import rule_score  # noqa: E402
from train import ours_matrix  # noqa: E402

DISPLAY = [
    ("rules", "Signature rules (16 regexes)", "none"),
    ("isoforest", "Isolation Forest, benign-only (unsupervised)", "streaming context"),
    ("line_tfidf", "TF-IDF char 3-5-grams + LR", "one line"),
    ("tokens_only", "Line tokens + LR (ablation, no context)", "one line"),
    ("hgb", "Gradient-boosted trees, same features as ours", "streaming context"),
    ("ours", "**Ours: context-aware LR**", "streaming context"),
]


def sload(path):
    return load(path, trusted=get_untrusted_types(file=path))


def score_all(df, ours, base):
    toks, nums = featurize_df(df)
    vocab = ours["vocab"]
    X = ours_matrix(toks, nums, vocab, ours["token_scale"])
    b = base["models"]
    out = {"rules": (np.array([rule_score(l) for l in df.raw_log]), 0.5),
           "ours": (ours["clf"].predict_proba(X)[:, 1], ours["threshold"]),
           "tokens_only": (b["tokens_only"]["clf"].predict_proba(token_matrix(toks, vocab))[:, 1], b["tokens_only"]["threshold"]),
           "hgb": (b["hgb"]["clf"].predict_proba(X.toarray())[:, 1], b["hgb"]["threshold"]),
           "line_tfidf": (b["line_tfidf"]["clf"].predict_proba(
               b["line_tfidf"]["vec"].transform([mask_line(l) for l in df.raw_log]))[:, 1], b["line_tfidf"]["threshold"]),
           "isoforest": (-b["isoforest"]["clf"].score_samples(X.toarray()), b["isoforest"]["threshold"])}
    return out


def metrics(y, s, thr, sessions, scen):
    p = s >= thr
    tn, fp, fn, tp = confusion_matrix(y, p, labels=[0, 1]).ravel()
    sess = pd.DataFrame({"sid": sessions, "y": y, "p": p}).groupby("sid").agg(y=("y", "max"), p=("p", "max"))
    sp = sess.p.values
    per = pd.DataFrame({"scen": scen, "y": y, "p": p})
    per_scen = {k: round(float((g.p == g.y).mean()), 4) for k, g in per.groupby("scen")}
    return {"threshold": round(float(thr), 4),
            "event": {"average_precision": round(float(average_precision_score(y, s)), 4),
                      "roc_auc": round(float(roc_auc_score(y, s)), 4),
                      "f1": round(float(f1_score(y, p)), 4), "precision": round(float(precision_score(y, p, zero_division=0)), 4),
                      "recall": round(float(recall_score(y, p)), 4), "false_positive_rate": round(float(fp / (fp + tn)), 4),
                      "tp": int(tp), "fp": int(fp), "tn": int(tn), "fn": int(fn)},
            "session": {"detection_rate": round(float(sp[sess.y.values == 1].mean()), 4),
                        "false_alarm_rate": round(float(sp[sess.y.values == 0].mean()), 4),
                        "accuracy": round(float((sp == sess.y.values).mean()), 4)},
            "per_scenario_event_accuracy": per_scen}


def per_technique_recall(df, s, thr):
    m = df[df.is_malicious].assign(hit=(s >= thr)[df.is_malicious.values])
    return {k: [round(float(g.hit.mean()), 4), int(len(g))] for k, g in m.groupby("mitre_technique_id")}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", default=None)
    ap.add_argument("--challenge", default="data/challenge.parquet")
    ap.add_argument("--models", default="outputs")
    ap.add_argument("--out", default="eval")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)
    ours = sload(f"{args.models}/model/model.skops")
    base = sload(f"{args.models}/baselines/baselines.skops")
    sets = {"test": load_events(args.data, "test"),
            "challenge": pd.read_parquet(args.challenge).sort_values(["session_id", "seq"]).reset_index(drop=True)}
    res, scored = {}, {}
    for name, df in sets.items():
        y = df.is_malicious.values.astype(int)
        sc = score_all(df, ours, base)
        scored[name] = sc
        res[name] = {"events": int(len(df)), "sessions": int(df.session_id.nunique()),
                     "malicious_share": round(float(y.mean()), 4),
                     "models": {k: metrics(y, s, t, df.session_id.values, df.scenario.values) for k, (s, t) in sc.items()}}
        res[name]["ours_per_technique_recall"] = per_technique_recall(df, *sc["ours"])
        print(f"== {name}")
        for k, _, _ in DISPLAY:
            e = res[name]["models"][k]["event"]
            print(f"  {k:12s} AP={e['average_precision']:.4f} F1={e['f1']:.4f} P={e['precision']:.4f} "
                  f"R={e['recall']:.4f} FPR={e['false_positive_rate']:.4f}")
    with open(f"{args.out}/metrics.json", "w") as fh:
        json.dump(res, fh, indent=2)

    # Python reference scores for tests/parity.mjs
    t = sets["test"]
    pd.DataFrame({"session_id": t.session_id, "seq": t.seq, "p": scored["test"]["ours"][0]}).to_parquet(
        f"{args.out}/test_scores.parquet", index=False)

    # leaderboard
    lines = ["| model | context | challenge F1 | challenge AP | challenge precision | challenge recall | challenge FPR "
             "| test F1 | test AP | test FPR |", "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|"]
    for k, label, ctx in DISPLAY:
        c, te = res["challenge"]["models"][k]["event"], res["test"]["models"][k]["event"]
        b = (lambda v: f"**{v:.3f}**") if k == "ours" else (lambda v: f"{v:.3f}")
        lines.append(f"| {label} | {ctx} | {b(c['f1'])} | {b(c['average_precision'])} | {b(c['precision'])} | "
                     f"{b(c['recall'])} | {b(c['false_positive_rate'])} | {b(te['f1'])} | {b(te['average_precision'])} | "
                     f"{b(te['false_positive_rate'])} |")
    with open(f"{args.out}/leaderboard.md", "w") as fh:
        fh.write("\n".join(lines) + "\n")
    print("\n".join(lines))

    # confusion matrices for ours
    fig, axes = plt.subplots(1, 2, figsize=(9, 4))
    for ax, name in zip(axes, ["test", "challenge"]):
        e = res[name]["models"]["ours"]["event"]
        cm = np.array([[e["tn"], e["fp"]], [e["fn"], e["tp"]]])
        ax.imshow(cm, cmap="Blues")
        for (i, j), v in np.ndenumerate(cm):
            ax.text(j, i, f"{v:,}", ha="center", va="center", color="white" if v > cm.max() / 2 else "black")
        ax.set_xticks([0, 1], ["normal", "anomalous"])
        ax.set_yticks([0, 1], ["normal", "anomalous"])
        ax.set_xlabel("predicted")
        ax.set_ylabel("actual")
        ax.set_title(f"{name} ({res[name]['events']:,} events)")
    fig.tight_layout()
    fig.savefig(f"{args.out}/confusion_matrix.png", dpi=120)


if __name__ == "__main__":
    main()