Download demo/src/features.py from AriaAICompany/cloudtrail-lab: direct link, hf CLI and curl.
- Browser
- Download file 8.18 kB
-
https://huggingface.co/datasets/AriaAICompany/cloudtrail-lab/resolve/main/demo/src/features.py
- Command line
-
hf download hf://datasets/AriaAICompany/cloudtrail-lab/demo/src/features.py
-
curl -L -o features.py https://huggingface.co/datasets/AriaAICompany/cloudtrail-lab/resolve/main/demo/src/features.py
8.18 kB
| from __future__ import annotations | |
| from typing import Any | |
| import numpy as np | |
| import pandas as pd | |
| from src.domain import ( | |
| BURST_WINDOW_MINUTES, | |
| FEATURE_COLUMNS, | |
| SENSITIVE_TYPES, | |
| Split, | |
| TEST_START_ISO, | |
| ) | |
| from src.mapper import normalize_event | |
| from src.parsers import parse_timestamp | |
| from src.ruleset import maintenance_match, severity_for | |
| def events_frame(rows: list[dict[str, Any]] | pd.DataFrame) -> pd.DataFrame: | |
| if isinstance(rows, pd.DataFrame): | |
| records = rows.to_dict(orient="records") | |
| else: | |
| records = list(rows) | |
| cleaned = [normalize_event(row) for row in records] | |
| frame = pd.DataFrame(cleaned) | |
| if frame.empty: | |
| return frame | |
| frame["ts"] = [parse_timestamp(value) for value in frame["timestamp"]] | |
| valid = frame["ts"].notna() & frame["event_name"].astype(str).ne("") | |
| frame = frame.loc[valid].copy().reset_index(drop=True) | |
| if frame.empty: | |
| return frame | |
| test_start = pd.Timestamp(TEST_START_ISO) | |
| existing = frame["split"].replace("", Split.DEVELOPMENT.value) | |
| frame["split"] = np.where(pd.to_datetime(frame["ts"], utc=True) >= test_start, Split.TEST.value, existing) | |
| frame["hour"] = pd.to_datetime(frame["ts"], utc=True).dt.hour | |
| frame["weekday"] = pd.to_datetime(frame["ts"], utc=True).dt.weekday | |
| frame["weekend"] = frame["weekday"].isin([5, 6]).astype(float) | |
| human = frame["actor_kind"].eq("human") | |
| unusual = human & ((frame["hour"] < 6) | (frame["hour"] >= 22) | frame["weekday"].eq(6)) | |
| frame["unusual_hour"] = unusual.astype(float) | |
| frame["in_window"] = frame["weekday"].eq(6) & frame["hour"].between(2, 5) | |
| flags = frame.apply( | |
| lambda row: { | |
| "cidr_open": bool(row.get("cidr_open")), | |
| "policy_public": bool(row.get("policy_public")), | |
| "admin_policy": bool(row.get("admin_policy")), | |
| "logging_off": bool(row.get("logging_off")), | |
| "detector_off": bool(row.get("detector_off")), | |
| "wildcard_trust": bool(row.get("wildcard_trust")), | |
| "is_root": row.get("actor_kind") == "root", | |
| "hardening": bool(row.get("hardening")), | |
| }, | |
| axis=1, | |
| ) | |
| frame["severity"] = [ | |
| severity_for(str(row.change_type), flags.iloc[idx]).value for idx, row in enumerate(frame.itertuples(index=False)) | |
| ] | |
| frame["in_maintenance"] = [ | |
| maintenance_match( | |
| str(row.account_alias), | |
| str(row.actor_alias), | |
| str(row.change_type), | |
| flags.iloc[idx], | |
| str(row.change_ticket or ""), | |
| bool(row.in_window), | |
| ) | |
| for idx, row in enumerate(frame.itertuples(index=False)) | |
| ] | |
| frame["approval_status"] = np.where(frame["in_maintenance"], "approved_window", "none") | |
| frame["approval_status"] = np.where( | |
| frame["change_ticket"].astype(str).ne("") & ~frame["in_maintenance"], | |
| "unknown", | |
| frame["approval_status"], | |
| ) | |
| frame = _pair_before_after(frame) | |
| frame = _burst_counts(frame) | |
| frame["is_root"] = frame["actor_kind"].eq("root").astype(float) | |
| frame["is_service"] = frame["actor_kind"].eq("service").astype(float) | |
| frame["is_human"] = frame["actor_kind"].eq("human").astype(float) | |
| frame["error_event"] = frame["error_code"].astype(str).ne("").astype(float) | |
| frame["sensitive"] = frame["change_type"].isin(SENSITIVE_TYPES) & ~frame["hardening"].astype(bool) | |
| return frame.sort_values(["ts", "event_id"]).reset_index(drop=True) | |
| def _pair_before_after(frame: pd.DataFrame) -> pd.DataFrame: | |
| work = frame.sort_values("ts").copy() | |
| before_ids: list[str] = [] | |
| before_known: list[bool] = [] | |
| after_known: list[bool] = [] | |
| for idx, row in work.iterrows(): | |
| if row["change_type"] not in SENSITIVE_TYPES or row["hardening"]: | |
| before_ids.append("") | |
| before_known.append(False) | |
| after_known.append(False) | |
| continue | |
| prior = work.loc[ | |
| (work["ts"] < row["ts"]) | |
| & (work["account_alias"] == row["account_alias"]) | |
| & (work["resource_alias"] == row["resource_alias"]) | |
| & (work["resource_alias"].astype(str).ne("res_unknown")) | |
| ] | |
| if prior.empty: | |
| before_ids.append("") | |
| before_known.append(False) | |
| after_known.append(not bool(row.get("incomplete"))) | |
| continue | |
| before_ids.append(str(prior.iloc[-1]["event_id"])) | |
| before_known.append(True) | |
| after_known.append(not bool(row.get("incomplete"))) | |
| work["before_event_id"] = before_ids | |
| work["after_event_id"] = np.where(work["event_id"].astype(str).ne(""), work["event_id"], "") | |
| work["has_before"] = np.array(before_known, dtype=float) | |
| work["has_after"] = np.array(after_known, dtype=float) | |
| work["before_state"] = np.where(work["has_before"] >= 1, "known", "unknown") | |
| work["after_state"] = np.where(work["has_after"] >= 1, "known", "unknown") | |
| return work | |
| def _burst_counts(frame: pd.DataFrame) -> pd.DataFrame: | |
| work = frame.sort_values("ts").copy() | |
| counts = [] | |
| window = pd.Timedelta(minutes=BURST_WINDOW_MINUTES) | |
| sensitive = work["change_type"].isin(SENSITIVE_TYPES) & ~work["hardening"].astype(bool) | |
| for _, row in work.iterrows(): | |
| if not bool(sensitive.loc[row.name] if row.name in sensitive.index else False): | |
| counts.append(0) | |
| continue | |
| mask = ( | |
| (work["actor_alias"] == row["actor_alias"]) | |
| & (work["ts"] <= row["ts"]) | |
| & (work["ts"] >= row["ts"] - window) | |
| & sensitive | |
| ) | |
| counts.append(int(mask.sum())) | |
| work["burst_count"] = counts | |
| return work | |
| def feature_matrix(frame: pd.DataFrame) -> pd.DataFrame: | |
| if frame.empty: | |
| return pd.DataFrame(columns=list(FEATURE_COLUMNS)) | |
| data = {} | |
| for column in FEATURE_COLUMNS: | |
| if column == "severity_weight": | |
| data[column] = frame["severity"].map({"high": 4.0, "medium": 3.2, "low": 1.8}).fillna(0.0) | |
| elif column in frame.columns: | |
| data[column] = pd.to_numeric(frame[column], errors="coerce").fillna(0.0) | |
| else: | |
| data[column] = 0.0 | |
| return pd.DataFrame(data, index=frame.index) | |
| def attach_gold(frame: pd.DataFrame, gold: pd.DataFrame | list[dict[str, Any]] | None) -> pd.DataFrame: | |
| out = frame.copy() | |
| out["gold_event_ids"] = "" | |
| out["gold_family"] = "" | |
| out["detect_delay_min"] = np.nan | |
| if gold is None: | |
| return out | |
| gold_frame = gold if isinstance(gold, pd.DataFrame) else pd.DataFrame(gold) | |
| if gold_frame.empty: | |
| return out | |
| gold_frame = gold_frame.copy() | |
| gold_frame["start_ts"] = [parse_timestamp(value) for value in gold_frame["start"]] | |
| gold_frame["end_ts"] = [parse_timestamp(value) for value in gold_frame["end"]] | |
| for event in gold_frame.itertuples(index=False): | |
| lab_id = str(event.event_id) | |
| direct = out["lab_event_id"].astype(str).eq(lab_id) | out["event_id"].astype(str).eq(lab_id) | |
| if event.start_ts and event.end_ts: | |
| overlap = (out["ts"] >= event.start_ts) & (out["ts"] <= event.end_ts) | |
| if getattr(event, "account_alias", ""): | |
| overlap = overlap & out["account_alias"].astype(str).eq(str(event.account_alias)) | |
| if getattr(event, "actor_alias", ""): | |
| overlap = overlap & out["actor_alias"].astype(str).eq(str(event.actor_alias)) | |
| else: | |
| overlap = pd.Series(False, index=out.index) | |
| hit = direct | overlap | |
| if not hit.any(): | |
| continue | |
| current = out.loc[hit, "gold_event_ids"].astype(str) | |
| out.loc[hit, "gold_event_ids"] = np.where(current.eq("") | current.eq("nan"), lab_id, current + "," + lab_id) | |
| out.loc[hit, "gold_family"] = str(event.family) | |
| delay = (pd.to_datetime(out.loc[hit, "ts"], utc=True) - pd.Timestamp(event.start_ts)).dt.total_seconds() / 60.0 | |
| out.loc[hit, "detect_delay_min"] = delay | |
| return out | |
| def change_view(frame: pd.DataFrame) -> pd.DataFrame: | |
| if frame.empty: | |
| return frame | |
| return frame.loc[frame["change_type"].isin(SENSITIVE_TYPES)].copy() | |