Download impl/src/pipeline/step03_source_attribution.py from pramodkachare/Cyber: direct link, hf CLI and curl.
- Browser
- Download file 4.85 kB
-
https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step03_source_attribution.py
- Command line
-
hf download hf://datasets/pramodkachare/Cyber/impl/src/pipeline/step03_source_attribution.py
-
curl -L -o step03_source_attribution.py https://huggingface.co/datasets/pramodkachare/Cyber/resolve/main/impl/src/pipeline/step03_source_attribution.py
4.85 kB
| """STEP 03: attribute every flow to its source sub-dataset and validate the rule. | |
| Finding that shaped this step: the four source CSVs are NOT stored as sequential blocks (row order is interleaved: | |
| ~296k start-year changes along 66.9M rows), so row order cannot identify the source. | |
| Rule used instead (capture date of FLOW_START_MILLISECONDS, UTC): | |
| year 2015 -> NF-UNSW-NB15-v3 | |
| year 2019 -> NF-ToN-IoT-v3 | |
| 2018-02, 2018-03 -> NF-CSE-CIC-IDS2018-v3 | |
| 2018-05, 2018-06 -> NF-BoT-IoT-v3 | |
| Validation is independent of the rule: IP address plan per source (BoT-IoT testbed 192.168.100.0/24, CSE-CIC-IDS2018 | |
| victim network 172.31.0.0/16), month coverage, cross-source IP overlap. | |
| Outputs: data/bigflow_v2_src.parquet (adds `source`), artifacts/step03/{source_summary,month_by_source,ip_prefixes,validation}.* | |
| """ | |
| import csv | |
| from .common import * | |
| NAME = "step03" | |
| PQ = f"read_parquet('{PARQUET}')" | |
| RULE = """CASE | |
| WHEN year(to_timestamp(FLOW_START_MILLISECONDS/1000)) = 2015 THEN 'NF-UNSW-NB15-v3' | |
| WHEN year(to_timestamp(FLOW_START_MILLISECONDS/1000)) = 2019 THEN 'NF-ToN-IoT-v3' | |
| WHEN strftime(to_timestamp(FLOW_START_MILLISECONDS/1000), '%Y-%m') IN ('2018-02','2018-03') THEN 'NF-CSE-CIC-IDS2018-v3' | |
| WHEN strftime(to_timestamp(FLOW_START_MILLISECONDS/1000), '%Y-%m') IN ('2018-05','2018-06') THEN 'NF-BoT-IoT-v3' | |
| ELSE 'UNASSIGNED' END""" | |
| def _wcsv(path, header, rows): | |
| with open(path, "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(header); w.writerows(rows) | |
| def run(force=False): | |
| out = step_dir(NAME); con = connect(); v = {} | |
| if force or not os.path.exists(PARQUET_SRC): | |
| with timed("write source-augmented parquet"): | |
| con.execute(f"COPY (SELECT *, {RULE} AS source FROM {PQ}) TO '{PARQUET_SRC}' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 1000000)") | |
| S = f"read_parquet('{PARQUET_SRC}')" | |
| v["unassigned_rows"] = con.execute(f"SELECT count(*) FROM {S} WHERE source='UNASSIGNED'").fetchone()[0] | |
| rows = con.execute(f"""SELECT source, count(*), min(FLOW_START_MILLISECONDS), max(FLOW_START_MILLISECONDS), | |
| round(avg((Label=0)::INT),4), count(DISTINCT Attack) FROM {S} GROUP BY 1 ORDER BY 2 DESC""").fetchall() | |
| import datetime | |
| h = lambda ms: datetime.datetime.fromtimestamp(ms/1000, datetime.timezone.utc).strftime("%Y-%m-%d") | |
| _wcsv(os.path.join(out, "source_summary.csv"), ["source", "rows", "first_flow_utc", "last_flow_utc", "benign_share", "n_labels_incl_benign"], | |
| [[r[0], r[1], h(r[2]), h(r[3]), r[4], r[5]] for r in rows]) | |
| v["source_rows"] = {r[0]: r[1] for r in rows} | |
| _wcsv(os.path.join(out, "month_by_source.csv"), ["source", "year_month", "rows"], | |
| con.execute(f"SELECT source, strftime(to_timestamp(FLOW_START_MILLISECONDS/1000),'%Y-%m'), count(*) FROM {S} GROUP BY ALL ORDER BY 1,2").fetchall()) | |
| # IP-plan validation: top /16 prefixes of src and dst per source, and purity of testbed prefixes | |
| pref = con.execute(f"""SELECT source, side, prefix, n FROM ( | |
| SELECT source, side, prefix, n, row_number() OVER (PARTITION BY source, side ORDER BY n DESC) rk FROM ( | |
| SELECT source, 'src' side, split_part(IPV4_SRC_ADDR,'.',1)||'.'||split_part(IPV4_SRC_ADDR,'.',2) prefix, count(*) n FROM {S} GROUP BY ALL | |
| UNION ALL | |
| SELECT source, 'dst', split_part(IPV4_DST_ADDR,'.',1)||'.'||split_part(IPV4_DST_ADDR,'.',2), count(*) FROM {S} GROUP BY ALL)) WHERE rk<=6 | |
| ORDER BY source, side, n DESC""").fetchall() | |
| _wcsv(os.path.join(out, "ip_prefixes.csv"), ["source", "side", "prefix_/16", "rows"], pref) | |
| pur = con.execute(f"""SELECT source, | |
| count(*) FILTER (WHERE IPV4_SRC_ADDR LIKE '192.168.100.%' OR IPV4_DST_ADDR LIKE '192.168.100.%') ip_192_168_100, | |
| count(*) FILTER (WHERE IPV4_SRC_ADDR LIKE '172.31.%' OR IPV4_DST_ADDR LIKE '172.31.%') ip_172_31 FROM {S} GROUP BY 1""").fetchall() | |
| v["testbed_prefix_rows"] = {r[0]: {"192.168.100.x": r[1], "172.31.x.x": r[2]} for r in pur} | |
| # cross-source IP overlap (leakage relevant for step 05/06) | |
| ov = con.execute(f"""WITH ips AS (SELECT DISTINCT source, ip FROM ( | |
| SELECT source, IPV4_SRC_ADDR ip FROM {S} UNION ALL SELECT source, IPV4_DST_ADDR FROM {S})) | |
| SELECT n_src, count(*) FROM (SELECT ip, count(DISTINCT source) n_src FROM ips GROUP BY ip) GROUP BY 1 ORDER BY 1""").fetchall() | |
| v["ip_in_n_sources"] = {int(a): int(b) for a, b in ov} | |
| # row-order interleaving | |
| v["row_order_year_changes"] = con.execute(f"""SELECT count(*) FILTER (WHERE yr <> prev) FROM ( | |
| SELECT yr, lag(yr) OVER (ORDER BY row_id) prev FROM ( | |
| SELECT row_id, year(to_timestamp(FLOW_START_MILLISECONDS/1000)) yr FROM {PQ}))""").fetchone()[0] | |
| save_json(v, os.path.join(out, "validation.json")) | |
| print(json.dumps(v, indent=1)) | |