Download impl/src/pipeline/common.py from pramodkachare/Cyber: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/common.py
- Command line
-
hf download hf://datasets/pramodkachare/Cyber/impl/src/pipeline/common.py
-
curl -L -o common.py https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/common.py
5.05 kB
| """Shared paths, config and helpers for the BigFlow-NIDS-V2 pipeline.""" | |
| import json, os, time, contextlib | |
| import duckdb | |
| IMPL = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| CYBER = os.path.dirname(IMPL) | |
| CSV = os.path.join(CYBER, "Dataset", "BigFlow-NIDS-V2.csv") | |
| DATA = os.path.join(IMPL, "data") | |
| ART = os.path.join(IMPL, "artifacts") | |
| PARQUET = os.path.join(DATA, "bigflow_v2.parquet") | |
| PARQUET_SRC = os.path.join(DATA, "bigflow_v2_src.parquet") # = PARQUET + `source` column (step 03) | |
| SOURCES = ["NF-UNSW-NB15-v3", "NF-ToN-IoT-v3", "NF-BoT-IoT-v3", "NF-CSE-CIC-IDS2018-v3"] | |
| SEED = 42 | |
| THREADS = int(os.environ.get("BF_THREADS", 24)) # machine is shared: keep modest | |
| MEM = os.environ.get("BF_MEM", "48GB") | |
| # Label spelling variants seen in the dataset paper (Table 2 vs text); canonical names used from step 02 on. | |
| # Filled/extended by step 02 after inspecting the real label values. | |
| LABEL_FIX = {"Infilteration": "Infiltration", "Inflteration": "Infiltration"} | |
| TIMESTAMPS = ["FLOW_START_MILLISECONDS", "FLOW_END_MILLISECONDS"] | |
| STRINGS = ["IPV4_SRC_ADDR", "IPV4_DST_ADDR", "Attack"] | |
| IDENTIFIERS = ["IPV4_SRC_ADDR", "IPV4_DST_ADDR", "L4_SRC_PORT", "L4_DST_PORT"] + TIMESTAMPS # leakage-prone (feature set B drops these) | |
| def connect(): | |
| con = duckdb.connect() | |
| con.execute(f"SET threads={THREADS}; SET memory_limit='{MEM}'; SET preserve_insertion_order=true;") | |
| con.execute(f"SET temp_directory='{os.path.join(DATA, 'tmp')}';") | |
| os.makedirs(DATA, exist_ok=True); os.makedirs(ART, exist_ok=True); os.makedirs(os.path.join(DATA, "tmp"), exist_ok=True) | |
| return con | |
| def step_dir(name): | |
| d = os.path.join(ART, name); os.makedirs(d, exist_ok=True); return d | |
| def save_json(obj, path): | |
| with open(path, "w") as f: | |
| json.dump(obj, f, indent=2, default=str) | |
| def timed(label): | |
| t = time.time(); print(f"[{label}] start", flush=True) | |
| yield | |
| print(f"[{label}] done in {time.time() - t:.0f}s", flush=True) | |
| # ---- feature sets (plan v4) ---- | |
| NON_FEATURES = ["row_id", "Label", "Attack", "source"] | |
| ALL_COLUMNS = None # resolved lazily from the parquet schema | |
| def all_columns(con): | |
| global ALL_COLUMNS | |
| if ALL_COLUMNS is None: | |
| ALL_COLUMNS = [r[0] for r in con.execute(f"DESCRIBE SELECT * FROM read_parquet('{PARQUET}')").fetchall()] | |
| return ALL_COLUMNS | |
| def features_A(con): | |
| return [c for c in all_columns(con) if c not in NON_FEATURES] # 53 | |
| def features_B(con): | |
| return [c for c in features_A(con) if c not in IDENTIFIERS] # 47 | |
| def qlist(cols): | |
| return ", ".join(f'"{c}"' for c in cols) | |
| def temp_dir(): | |
| d = os.path.join(DATA, "tmp"); os.makedirs(d, exist_ok=True); return d | |
| def features_C(con): | |
| """Feature set C (defined by step 06): B minus features that identify the source on their own.""" | |
| path = os.path.join(ART, "step06", "feature_set_C.json") | |
| with open(path) as f: | |
| return json.load(f)["features_C"] | |
| SRC_SHORT = {"NF-UNSW-NB15-v3": "unsw", "NF-ToN-IoT-v3": "ton", "NF-BoT-IoT-v3": "bot", "NF-CSE-CIC-IDS2018-v3": "cse"} | |
| # Taxonomy v0 (PROVISIONAL; to be grounded in MITRE ATT&CK and compared with an empirical grouping, plan Phase 4). | |
| # 31 attack classes -> 8 families. Benign is its own class. Deliberate choices vs the first plan draft: | |
| # Fuzzers -> EXPLOIT_FUZZ (vulnerability probing, not malware); Generic (UNSW cipher attack) -> EXPLOIT_FUZZ (not MITM); | |
| # Analysis (UNSW: port scan, spam, html penetration) -> RECON_SCAN; Brute_Force_-XSS (automated XSS attempts) -> WEB_INJECTION; | |
| # Worms -> MALWARE_C2 (self-propagating malware). | |
| TAXONOMY_V0 = { | |
| "FLOOD_DOS": ["DoS", "DDoS", "DDOS_attack-HOIC", "DDOS_attack-LOIC-UDP", "DDoS_attacks-LOIC-HTTP", "DoS_attacks-GoldenEye", | |
| "DoS_attacks-Hulk", "DoS_attacks-SlowHTTPTest", "DoS_attacks-Slowloris"], | |
| "BRUTE_FORCE": ["FTP-BruteForce", "SSH-Bruteforce", "Brute_Force_-Web", "password"], | |
| "RECON_SCAN": ["Reconnaissance", "scanning", "Analysis"], | |
| "WEB_INJECTION": ["xss", "injection", "SQL_Injection", "Brute_Force_-XSS"], | |
| "MALWARE_C2": ["Backdoor", "Bot", "ransomware", "Worms"], | |
| "EXPLOIT_FUZZ": ["Exploits", "Shellcode", "Fuzzers", "Generic"], | |
| "INFIL_EXFIL": ["Infilteration", "Theft"], | |
| "MITM": ["mitm"], | |
| } | |
| FAMILY_OF = {a: f for f, cl in TAXONOMY_V0.items() for a in cl} | |
| FAMILY_OF["Benign"] = "BENIGN" | |
| IP_COLUMNS = ["IPV4_SRC_ADDR", "IPV4_DST_ADDR"] | |
| def feat_select(cols, prefix=""): | |
| """SQL select list for modelling: IPv4 strings become 32-bit integers (trees can split on address ranges); other columns unchanged.""" | |
| out = [] | |
| for c in cols: | |
| if c in IP_COLUMNS: | |
| x = f'{prefix}"{c}"' | |
| out.append(f"((CAST(split_part({x},'.',1) AS BIGINT) << 24) + (CAST(split_part({x},'.',2) AS BIGINT) << 16) + " | |
| f"(CAST(split_part({x},'.',3) AS BIGINT) << 8) + CAST(split_part({x},'.',4) AS BIGINT)) AS \"{c}\"") | |
| else: | |
| out.append(f'{prefix}"{c}"') | |
| return ", ".join(out) | |