pidsmaker 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. pidsmaker/__init__.py +1 -0
  2. pidsmaker/cli.py +81 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1824 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +323 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +287 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +168 -0
  33. pidsmaker/detection/training_methods/training_loop.py +383 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +66 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +478 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1427 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1434 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/config/anomal_e.yml +25 -0
  164. pidsmaker/resources/config/argus.yml +56 -0
  165. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  166. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  167. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  168. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  169. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  170. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  171. pidsmaker/resources/config/default.yml +315 -0
  172. pidsmaker/resources/config/egraphsage.yml +95 -0
  173. pidsmaker/resources/config/euler.yml +104 -0
  174. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  175. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  176. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  177. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  178. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  179. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  180. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  181. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  182. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  183. pidsmaker/resources/config/flash.yml +79 -0
  184. pidsmaker/resources/config/jbeil.yml +65 -0
  185. pidsmaker/resources/config/kairos.yml +121 -0
  186. pidsmaker/resources/config/lares.yml +115 -0
  187. pidsmaker/resources/config/magic.yml +86 -0
  188. pidsmaker/resources/config/nodlink.yml +79 -0
  189. pidsmaker/resources/config/ocrapt.yml +91 -0
  190. pidsmaker/resources/config/orthrus.yml +126 -0
  191. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  192. pidsmaker/resources/config/pretrained/README.md +101 -0
  193. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  194. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  195. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  196. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  197. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  198. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  199. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  200. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  201. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  202. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  203. pidsmaker/resources/config/prographer.yml +136 -0
  204. pidsmaker/resources/config/rcaid.yml +88 -0
  205. pidsmaker/resources/config/shadewatcher.yml +146 -0
  206. pidsmaker/resources/config/tests.yml +10 -0
  207. pidsmaker/resources/config/threatrace.yml +73 -0
  208. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  209. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  210. pidsmaker/resources/config/velox.yml +10 -0
  211. pidsmaker/resources/config/viz_config.yml +10 -0
  212. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  213. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  214. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  215. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  216. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  217. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  218. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  219. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  220. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  221. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  222. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  223. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  224. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  225. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  226. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  227. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  228. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  229. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  230. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  231. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  232. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  233. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  234. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  235. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  236. pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  237. pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  238. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  239. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  240. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  241. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  242. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  243. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  244. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  245. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  246. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  247. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  248. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  249. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  250. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  251. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  252. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  253. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  254. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  255. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  256. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  257. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  258. pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  259. pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
  260. pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
  261. pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
  262. pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
  263. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  264. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  265. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  266. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  267. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  268. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  269. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  270. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  271. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  272. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  273. pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  274. pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  275. pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  276. pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  277. pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
  278. pidsmaker/tasks/__init__.py +10 -0
  279. pidsmaker/tasks/batching.py +47 -0
  280. pidsmaker/tasks/construction.py +31 -0
  281. pidsmaker/tasks/evaluation.py +241 -0
  282. pidsmaker/tasks/feat_inference.py +413 -0
  283. pidsmaker/tasks/featurization.py +43 -0
  284. pidsmaker/tasks/training.py +17 -0
  285. pidsmaker/tasks/transformation.py +306 -0
  286. pidsmaker/tasks/triage.py +143 -0
  287. pidsmaker/tgn.py +635 -0
  288. pidsmaker/tokenization/__init__.py +112 -0
  289. pidsmaker/tokenization/base.py +58 -0
  290. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  291. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  292. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  293. pidsmaker/tokenization/label_tokenizer.py +24 -0
  294. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  295. pidsmaker/tokenization/substitution.py +295 -0
  296. pidsmaker/triage/__init__.py +0 -0
  297. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  298. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  299. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  300. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  301. pidsmaker/utils/__init__.py +0 -0
  302. pidsmaker/utils/cache_utils.py +256 -0
  303. pidsmaker/utils/console.py +282 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +150 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +570 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +445 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +712 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/backfill_manifests.py +100 -0
  315. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  316. pidsmaker/vizgen/embed_exporter.py +467 -0
  317. pidsmaker/vizgen/exporter.py +493 -0
  318. pidsmaker/vizgen/html_builder.py +936 -0
  319. pidsmaker/vizgen/web/__init__.py +1 -0
  320. pidsmaker/vizgen/web/export.py +62 -0
  321. pidsmaker/vizgen/web/static/css/app.css +250 -0
  322. pidsmaker/vizgen/web/static/index.html +182 -0
  323. pidsmaker/vizgen/web/static/js/app.js +627 -0
  324. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  325. pidsmaker/vizgen/web/static/js/data.js +119 -0
  326. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  327. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  328. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  329. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  330. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  331. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  332. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  333. pidsmaker/vizgen/web/viz_server.py +2176 -0
  334. pidsmaker-5.0.0.dist-info/METADATA +597 -0
  335. pidsmaker-5.0.0.dist-info/RECORD +339 -0
  336. pidsmaker-5.0.0.dist-info/WHEEL +5 -0
  337. pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
  338. pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
  339. pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1788 @@
1
+ import os
2
+ import time
3
+ from collections import defaultdict
4
+ from datetime import datetime
5
+ from time import mktime
6
+
7
+ import igraph as ig
8
+ import matplotlib.patches as mpatches
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+ import pytz
13
+ import torch
14
+ import wandb
15
+ from sklearn.cluster import KMeans
16
+ from sklearn.metrics import (
17
+ average_precision_score as ap_score,
18
+ )
19
+ from sklearn.metrics import (
20
+ balanced_accuracy_score,
21
+ confusion_matrix,
22
+ precision_recall_curve,
23
+ roc_auc_score,
24
+ )
25
+
26
+ import pidsmaker.utils.labelling as labelling
27
+ from pidsmaker.utils import console
28
+ from pidsmaker.utils.dataset_utils import (
29
+ get_node_to_path_and_type,
30
+ get_uuid_to_index_id,
31
+ )
32
+ from pidsmaker.utils.loss_files import read_losses, strip_loss_ext
33
+ from pidsmaker.utils.utils import (
34
+ get_all_graphs_for_dates,
35
+ listdir_sorted,
36
+ log,
37
+ mean,
38
+ percentile_90,
39
+ )
40
+
41
+ # Assign different colors for each attack type
42
+ # Source: Tailwind 4 colors (800 shade)
43
+ attack_colors = {
44
+ 0: "black",
45
+ 1: "red",
46
+ 2: "blue",
47
+ 3: "#006045",
48
+ 4: "#005f78",
49
+ 5: "#193cb8",
50
+ 6: "#5d0ec0",
51
+ 7: "#8a0194",
52
+ 8: "#a3004c",
53
+ 9: "#1d293d"
54
+ }
55
+
56
+ def compute_topk_metrics(y_test, scores, k_values=(10, 50, 100)):
57
+ """Compute AP@K, Precision@K, and Recall@K for given K values.
58
+
59
+ These metrics evaluate ranking quality within the top-K predictions,
60
+ which is more operationally meaningful than full AP in settings with
61
+ noisy labels or extreme class imbalance.
62
+ """
63
+ y_test = np.array(y_test)
64
+ scores = np.array(scores)
65
+ sorted_idx = np.argsort(-scores)
66
+ total_pos = y_test.sum()
67
+
68
+ stats = {}
69
+ for k in k_values:
70
+ if k > len(y_test):
71
+ continue
72
+ top_k_labels = y_test[sorted_idx[:k]]
73
+ n_pos_in_k = top_k_labels.sum()
74
+
75
+ # Precision@K
76
+ prec_k = float(n_pos_in_k / k)
77
+ stats[f"precision@{k}"] = round(prec_k, 5)
78
+
79
+ # Recall@K
80
+ recall_k = float(n_pos_in_k / total_pos) if total_pos > 0 else 0.0
81
+ stats[f"recall@{k}"] = round(recall_k, 5)
82
+
83
+ # AP@K: average of precision values at each relevant position in top-K
84
+ if n_pos_in_k == 0:
85
+ ap_k = 0.0
86
+ else:
87
+ cumsum = np.cumsum(top_k_labels)
88
+ precisions = cumsum / np.arange(1, k + 1)
89
+ ap_k = float((precisions * top_k_labels).sum() / min(total_pos, k))
90
+ stats[f"ap@{k}"] = round(ap_k, 5)
91
+
92
+ return stats
93
+
94
+
95
+ def classifier_evaluation(y_test, y_test_pred, scores):
96
+ # Arrays make the metrics much faster on large test sets than lists
97
+ y_test = np.asarray(y_test).astype(np.int64, copy=False)
98
+ y_test_pred = np.asarray(y_test_pred).astype(np.int64, copy=False)
99
+ scores = np.asarray(scores, dtype=np.float64)
100
+ labels_exist = y_test.sum() > 0
101
+ binary = labels_exist and bool(np.isin(y_test, (0, 1)).all() and np.isin(y_test_pred, (0, 1)).all())
102
+ if binary and (y_test == 0).any():
103
+ # Same as confusion_matrix(y_test, y_test_pred).ravel() for 0/1 labels with both classes
104
+ tp = int(np.count_nonzero((y_test == 1) & (y_test_pred == 1)))
105
+ fp = int(np.count_nonzero((y_test == 0) & (y_test_pred == 1)))
106
+ fn = int(np.count_nonzero((y_test == 1) & (y_test_pred == 0)))
107
+ tn = len(y_test) - tp - fp - fn
108
+ elif labels_exist:
109
+ # `labels` keeps the matrix 2x2 when a single class is present (e.g. all predicted malicious)
110
+ tn, fp, fn, tp = confusion_matrix(y_test, y_test_pred, labels=[0, 1]).ravel()
111
+ else:
112
+ log("WARNING: Computing confusion matrix failed.")
113
+ tn, fp, fn, tp = 1, 1, 1, 1 # only to not break tests
114
+
115
+ eps = 1e-12
116
+ fpr = fp / (fp + tn + eps)
117
+ precision = tp / (tp + fp + eps)
118
+ recall = tp / (tp + fn + eps)
119
+ accuracy = (tp + tn) / (tp + tn + fp + fn + eps)
120
+ fscore = 2 * (precision * recall) / (precision + recall + eps)
121
+
122
+ try:
123
+ auc_val = roc_auc_score(y_test, scores)
124
+ except ValueError as e:
125
+ log(f"WARNING: AUC calculation failed: {e}")
126
+ auc_val = float("nan")
127
+ try:
128
+ ap = ap_score(y_test, scores)
129
+ except ValueError as e:
130
+ log(f"WARNING: AP calculation failed: {e}")
131
+ ap = float("nan")
132
+ try:
133
+ if binary and (y_test == 0).any():
134
+ # Same as balanced_accuracy_score: mean recall of the two classes
135
+ balanced_acc = float(np.mean([tn / (tn + fp), tp / (tp + fn)]))
136
+ else:
137
+ balanced_acc = balanced_accuracy_score(y_test, y_test_pred)
138
+ except ValueError as e:
139
+ log(f"WARNING: Balanced ACC calculation failed: {e}")
140
+ balanced_acc = float("nan")
141
+
142
+ sensitivity = tp / (tp + fn + eps)
143
+ specificity = tn / (tn + fp + eps)
144
+ lr_plus = sensitivity / (1 - specificity + eps)
145
+ dor = (tp * tn) / (fp * fn + eps)
146
+ mcc = compute_mcc(tp, fp, tn, fn)
147
+
148
+ topk_stats = compute_topk_metrics(y_test, scores, k_values=(10, 50, 100))
149
+
150
+ stats = {
151
+ "precision": round(precision, 5),
152
+ "recall": round(recall, 5),
153
+ "fpr": round(fpr, 7),
154
+ "fscore": round(fscore, 5),
155
+ "ap": round(ap, 5),
156
+ "accuracy": round(accuracy, 5),
157
+ "balanced_acc": round(balanced_acc, 5),
158
+ "auc": round(auc_val, 5),
159
+ "lr(+)": round(lr_plus, 5),
160
+ "dor": round(dor, 5),
161
+ "mcc": round(mcc, 5),
162
+ "tp": tp,
163
+ "fp": fp,
164
+ "tn": tn,
165
+ "fn": fn,
166
+ **topk_stats,
167
+ }
168
+ return stats
169
+
170
+
171
+ def compute_mcc(tp, fp, tn, fn):
172
+ numerator = (tp * tn) - (fp * fn)
173
+ denominator = ((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5
174
+
175
+ if denominator == 0:
176
+ return 0
177
+
178
+ mcc = numerator / denominator
179
+ return mcc
180
+
181
+
182
+ def get_threshold(val_tw_path, threshold_method: str, alpha=1.0, contamination=0.05):
183
+ threshold_method = threshold_method.strip()
184
+ if threshold_method == "max_val_loss":
185
+ return calculate_threshold(val_tw_path, threshold_method, alpha)["max"]
186
+ elif threshold_method == "mean_val_loss":
187
+ return calculate_threshold(val_tw_path, threshold_method)["mean"]
188
+ elif threshold_method == "percentile":
189
+ return calculate_threshold(val_tw_path, threshold_method, alpha)["max"]
190
+ elif threshold_method == "threatrace":
191
+ # The ratio threshold is already applied in the score (see `threatrace_anomaly_score`)
192
+ return 0.0
193
+ elif threshold_method == "flash":
194
+ return 0.53
195
+ elif threshold_method == "nodlink":
196
+ return calculate_threshold(val_tw_path, threshold_method)["percentile_90"]
197
+ elif threshold_method == "magic":
198
+ return calculate_threshold(val_tw_path, threshold_method)["mean"]
199
+ elif threshold_method == "ocrapt":
200
+ # Contamination percentile: flag the top-`contamination` fraction of node scores.
201
+ losses = []
202
+ for file in listdir_sorted(val_tw_path):
203
+ losses.extend(read_losses(os.path.join(val_tw_path, file), usecols=["loss"])["loss"].tolist())
204
+ return float(np.percentile(losses, 100 * (1 - contamination)))
205
+ elif threshold_method == "fixed_zero":
206
+ return 0.0 # BCE decision boundary: logit > 0 <=> P(attack) > 0.5
207
+ raise ValueError(f"Invalid threshold method `{threshold_method}`")
208
+
209
+
210
+ def get_threshold_per_type(val_tw_path, cfg, min_contamination=0.001, max_contamination=0.05):
211
+ # per node type: contamination = own val malicious fraction, clamped to [min, max]
212
+ node_to_type = {nid: info["type"] for nid, info in get_node_to_path_and_type(cfg).items()}
213
+ gt_nids, _, _ = labelling.get_ground_truth(cfg)
214
+ gt_nids = set(int(n) for n in gt_nids)
215
+
216
+ losses_by_type = defaultdict(list)
217
+ malicious_by_type = defaultdict(int)
218
+ total_by_type = defaultdict(int)
219
+ for file in listdir_sorted(val_tw_path):
220
+ df = read_losses(os.path.join(val_tw_path, file), usecols=["node", "loss"])
221
+ for node, loss in zip(df["node"], df["loss"]):
222
+ nt = node_to_type.get(int(node))
223
+ if nt is None:
224
+ continue
225
+ losses_by_type[nt].append(loss)
226
+ total_by_type[nt] += 1
227
+ if int(node) in gt_nids:
228
+ malicious_by_type[nt] += 1
229
+
230
+ thresholds = {}
231
+ for nt, losses in losses_by_type.items():
232
+ frac = malicious_by_type[nt] / total_by_type[nt] if total_by_type[nt] > 0 else 0.0
233
+ contamination = min(max(frac, min_contamination), max_contamination)
234
+ thresholds[nt] = float(np.percentile(losses, 100 * (1 - contamination)))
235
+ return thresholds
236
+
237
+
238
+ def reduce_losses_to_score(losses: list[float], threshold_method: str):
239
+ threshold_method = threshold_method.strip()
240
+ if threshold_method == "mean_val_loss":
241
+ return np.mean(losses)
242
+ elif threshold_method == "percentile":
243
+ return np.percentile(losses, 95)
244
+ elif (
245
+ threshold_method == "max_val_loss"
246
+ or threshold_method == "threatrace"
247
+ or threshold_method == "flash"
248
+ or threshold_method == "nodlink"
249
+ or threshold_method == "ocrapt"
250
+ or threshold_method == "fixed_zero"
251
+ ):
252
+ return np.max(losses)
253
+ raise ValueError(f"Invalid threshold method {threshold_method}")
254
+
255
+
256
+ def calculate_threshold(val_tw_dir, threshold_method, alpha=1.0):
257
+ filelist = listdir_sorted(val_tw_dir)
258
+ col = "magic_score" if threshold_method == "magic" else "loss"
259
+
260
+ loss_list = []
261
+ for file in filelist:
262
+ f = os.path.join(val_tw_dir, file)
263
+ loss_list.extend(read_losses(f, usecols=[col])[col].tolist())
264
+
265
+ thr = {
266
+ "max": max(loss_list) * alpha,
267
+ "mean": mean(loss_list) * alpha,
268
+ "percentile_90": percentile_90(loss_list) * alpha,
269
+ }
270
+ return thr
271
+
272
+
273
+ def plot_precision_recall(scores, y_truth, out_file):
274
+ precision, recall, thresholds = precision_recall_curve(y_truth, scores)
275
+
276
+ plt.figure(figsize=(8, 6))
277
+ plt.plot(recall, precision, marker=".", label="Precision-Recall curve")
278
+ plt.xlabel("Recall")
279
+ plt.ylabel("Precision")
280
+ plt.title("Precision-Recall Curve")
281
+ plt.legend()
282
+ plt.grid(True)
283
+ precision_ticks = [i / 20 for i in range(7)] # Generates [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3]
284
+ plt.yticks(precision_ticks)
285
+
286
+ plt.savefig(out_file)
287
+
288
+
289
+ def plot_simple_scores(scores, y_truth, out_file):
290
+ scores_0 = [score for score, label in zip(scores, y_truth) if label == 0]
291
+ scores_1 = [score for score, label in zip(scores, y_truth) if label == 1]
292
+
293
+ # Positions on the y-axis for the scatter plot (can be zero or any other constant)
294
+ y_zeros = [0] * len(scores_0) # All zeros at y=0
295
+ y_ones = [1] * len(scores_1) # All ones at y=1, you can also keep them at y=0 if you prefer
296
+
297
+ plt.figure(figsize=(6, 2)) # Width, height in inches
298
+ plt.scatter(scores_0, y_zeros, color="green")
299
+ plt.scatter(scores_1, y_ones, color="red")
300
+
301
+ plt.xlabel("Node anomaly scores")
302
+ plt.yticks([0, 1], ["Benign", "Malicious"])
303
+ plt.ylim(-0.1, 1.1) # Adjust if necessary to bring them even closer
304
+
305
+ plt.tight_layout() # Ensures everything fits within the figure area
306
+ plt.savefig(out_file)
307
+
308
+
309
+ def plot_score_seen(scores, y_truth, out_file):
310
+ scores_0 = [score for score, label in zip(scores, y_truth) if label == 0]
311
+ scores_1 = [score for score, label in zip(scores, y_truth) if label == 1]
312
+
313
+ # Positions on the y-axis for the scatter plot (can be zero or any other constant)
314
+ y_zeros = [0] * len(scores_0) # All zeros at y=0
315
+ y_ones = [1] * len(scores_1) # All ones at y=1, you can also keep them at y=0 if you prefer
316
+
317
+ plt.figure(figsize=(6, 2)) # Width, height in inches
318
+ plt.scatter(scores_0, y_zeros, color="green")
319
+ plt.scatter(scores_1, y_ones, color="red")
320
+
321
+ plt.xlabel("Node anomaly scores")
322
+ plt.yticks([0, 1], ["Seen", "Unseen"])
323
+ plt.ylim(-0.1, 1.1) # Adjust if necessary to bring them even closer
324
+
325
+ plt.tight_layout() # Ensures everything fits within the figure area
326
+ plt.savefig(out_file)
327
+
328
+
329
+ def plot_scores_with_paths_node_level(
330
+ scores,
331
+ y_truth,
332
+ nodes,
333
+ max_val_loss_tw,
334
+ tw_to_malicious_nodes,
335
+ node2attacks,
336
+ out_file,
337
+ cfg,
338
+ threshold=None,
339
+ ):
340
+ node_to_path = get_node_to_path_and_type(cfg)
341
+ paths, types = [], []
342
+ # Prints the path if it exists, else tries to print the cmd line
343
+ for n in nodes:
344
+ types.append(node_to_path[n]["type"])
345
+ path = node_to_path[n]["path"]
346
+ if path == "None":
347
+ paths.append(node_to_path[n]["cmd"] if "cmd" in node_to_path[n] else path)
348
+ else:
349
+ paths.append(path)
350
+
351
+ # Convert data to numpy arrays for easy manipulation
352
+ scores = np.array(scores)
353
+ y_truth = np.array(y_truth)
354
+ types = np.array(types)
355
+ nodes = np.array(nodes)
356
+
357
+ # Define marker styles for each type
358
+ marker_styles = {
359
+ "subject": "s", # Square
360
+ "file": "o", # Circle
361
+ "netflow": "D", # Diamond
362
+ }
363
+ # Node types of other datasets (e.g. hosts of network datasets)
364
+ for t in sorted(set(types) - set(marker_styles)):
365
+ marker_styles[t] = "^"
366
+
367
+ # Separate the scores based on labels
368
+ scores_0 = scores[y_truth == 0]
369
+ scores_1 = scores[y_truth == 1]
370
+ types_0 = types[y_truth == 0]
371
+ types_1 = types[y_truth == 1]
372
+ paths_0 = [path for path, label in zip(paths, y_truth) if label == 0]
373
+ paths_1 = [path for path, label in zip(paths, y_truth) if label == 1]
374
+
375
+ plt.figure(figsize=(12, 6))
376
+
377
+ node2attack = np.array([list(node2attacks.get(node))[0] for node in nodes[y_truth == 1]])
378
+
379
+ # Plot each type with a different marker for Label 0
380
+ for t in marker_styles.keys():
381
+ plt.scatter(
382
+ scores_0[types_0 == t],
383
+ [0] * sum(types_0 == t),
384
+ marker=marker_styles[t],
385
+ color="green",
386
+ label=t,
387
+ )
388
+
389
+ # Plot each type with a different marker for Label 1
390
+ for t in marker_styles.keys():
391
+ mask = types_1 == t
392
+ if not mask.any():
393
+ continue
394
+ plt.scatter(
395
+ scores_1[mask],
396
+ [1] * sum(mask),
397
+ marker=marker_styles[t],
398
+ color=[attack_colors.get(c, "red") for c in node2attack[mask]],
399
+ )
400
+
401
+ # Adding labels and title
402
+ plt.xlabel("Scores")
403
+ plt.ylabel("Labels")
404
+ plt.yticks([0, 1], ["0", "1"]) # Set y-ticks to show label categories
405
+ plt.title("Scatter Plot of Scores by Label")
406
+ plt.legend()
407
+
408
+ # Add vertical line at threshold if provided
409
+ if threshold is not None:
410
+ plt.axvline(x=threshold, color="purple", linestyle="--", label="Threshold")
411
+ plt.legend()
412
+
413
+ # Combine scores and paths for easy handling
414
+ combined_scores = list(zip(scores, paths, y_truth, max_val_loss_tw, nodes))
415
+
416
+ # Sort combined list by scores in descending order
417
+ combined_scores_sorted = sorted(combined_scores, key=lambda x: x[0], reverse=True)
418
+
419
+ # Separate the top scores by their labels
420
+ keep_only = 14
421
+ top_0 = [item for item in combined_scores_sorted if item[2] == 0][:keep_only]
422
+ top_1 = [item for item in combined_scores_sorted if item[2] == 1][:keep_only]
423
+
424
+ x_axis = max(scores) + max(scores) * 0.05
425
+ # Annotate the top scores for label 0
426
+ for i, (score, path, _, max_tw_idx, node) in enumerate(top_0):
427
+ y_position = 0 - (i * 0.1) # Adjust y-position for each label to avoid overlap
428
+ plt.text(
429
+ x_axis,
430
+ y_position,
431
+ f"{str(path)[:30]} ({score:.2f}): TW {max_tw_idx}, Node: {node}",
432
+ fontsize=8,
433
+ va="center",
434
+ ha="left",
435
+ color="green",
436
+ )
437
+
438
+ # Annotate the top scores for label 1
439
+ for i, (score, path, _, max_tw_idx, node) in enumerate(top_1):
440
+ y_position = 1.4 - (
441
+ i * 0.1
442
+ ) # Adjust y-position for each label to avoid overlap and add space between groups
443
+ plt.text(
444
+ x_axis,
445
+ y_position,
446
+ f"{str(path)[:30]} ({score:.2f}): TW {max_tw_idx}, Node: {node}",
447
+ fontsize=8,
448
+ va="center",
449
+ ha="left",
450
+ color="red",
451
+ )
452
+
453
+ plt.text(
454
+ min(scores),
455
+ 1.6,
456
+ f"Dataset: {cfg.dataset.name}",
457
+ fontsize=8,
458
+ va="center",
459
+ ha="left",
460
+ color="black",
461
+ )
462
+ plt.text(
463
+ min(scores),
464
+ 1.5,
465
+ f"Malicious TW: {str(list(tw_to_malicious_nodes.keys()))}",
466
+ fontsize=8,
467
+ va="center",
468
+ ha="left",
469
+ color="black",
470
+ )
471
+
472
+ finite_scores = np.array(scores)[np.isfinite(scores)]
473
+ if len(finite_scores) == 0:
474
+ finite_scores = np.array([0.0, 1.0])
475
+ plt.xlim([np.min(finite_scores), max(np.max(finite_scores) * 1.5, 1e-6)]) # Adjust xlim to make space for text
476
+ plt.ylim([-1, 2]) # Adjust ylim to ensure the text is within the figure bounds
477
+ plt.savefig(out_file)
478
+ plt.close()
479
+
480
+
481
+ def plot_scores_with_paths_edge_level(
482
+ scores, y_truth, edges, tw_to_malicious_nodes, node2attacks, out_file, cfg, threshold=None
483
+ ):
484
+ node_to_path = get_node_to_path_and_type(cfg)
485
+ paths, types = [], []
486
+ # Prints the path if it exists, else tries to print the cmd line
487
+ for src, dst, *_ in edges:
488
+ src = int(src)
489
+ dst = int(dst)
490
+ src_type = node_to_path[src]["type"]
491
+ dst_type = node_to_path[dst]["type"]
492
+ types.append(src_type)
493
+
494
+ path_src = (
495
+ (node_to_path[src]["path"] + (", " + node_to_path[src]["cmd"]) if node_to_path[src]["cmd"] else "")
496
+ if src_type == "subject"
497
+ else node_to_path[src]["path"]
498
+ )
499
+ path_dst = (
500
+ (node_to_path[dst]["path"] + (", " + node_to_path[dst]["cmd"]) if node_to_path[dst]["cmd"] else "")
501
+ if dst_type == "subject"
502
+ else node_to_path[dst]["path"]
503
+ )
504
+ paths.append((path_src, path_dst))
505
+
506
+ # Convert data to numpy arrays for easy manipulation
507
+ scores = np.array(scores)
508
+ y_truth = np.array(y_truth)
509
+ types = np.array(types)
510
+
511
+ # Define marker styles for each type
512
+ marker_styles = {
513
+ "subject": "s", # Square
514
+ "file": "o", # Circle
515
+ "netflow": "D", # Diamond
516
+ }
517
+ # Node types of other datasets (e.g. hosts of network datasets)
518
+ for t in sorted(set(types) - set(marker_styles)):
519
+ marker_styles[t] = "^"
520
+
521
+ # Separate the scores based on labels
522
+ scores_0 = scores[y_truth == 0]
523
+ scores_1 = scores[y_truth == 1]
524
+ types_0 = types[y_truth == 0]
525
+ types_1 = types[y_truth == 1]
526
+
527
+ plt.figure(figsize=(14, 6))
528
+
529
+ malicious_elements = [n for y_true, n in zip(y_truth, edges) if y_true == 1]
530
+ node2attack = np.array([list(node2attacks.get(node))[0] for node in malicious_elements])
531
+
532
+ # Plot each type with a different marker for Label 0
533
+ for t in marker_styles.keys():
534
+ plt.scatter(
535
+ scores_0[types_0 == t],
536
+ [0] * sum(types_0 == t),
537
+ marker=marker_styles[t],
538
+ color="green",
539
+ label=t,
540
+ )
541
+
542
+ # Plot each type with a different marker for Label 1
543
+ for t in marker_styles.keys():
544
+ mask = types_1 == t
545
+ if not mask.any():
546
+ continue
547
+ plt.scatter(
548
+ scores_1[mask],
549
+ [1] * sum(mask),
550
+ marker=marker_styles[t],
551
+ color=[attack_colors.get(c, "red") for c in node2attack[mask]],
552
+ )
553
+
554
+ # Adding labels and title
555
+ plt.xlabel("Scores")
556
+ plt.ylabel("Labels")
557
+ plt.yticks([0, 1], ["0", "1"]) # Set y-ticks to show label categories
558
+ plt.title("Scatter Plot of Scores by Label")
559
+ plt.legend()
560
+
561
+ # Add vertical line at threshold if provided
562
+ if threshold is not None:
563
+ plt.axvline(x=threshold, color="purple", linestyle="--", label="Threshold")
564
+ plt.legend()
565
+
566
+ # Combine scores and paths for easy handling
567
+ combined_scores = list(zip(scores, paths, y_truth, edges))
568
+
569
+ # Sort combined list by scores in descending order
570
+ combined_scores_sorted = sorted(combined_scores, key=lambda x: x[0], reverse=True)
571
+
572
+ # Separate the top scores by their labels
573
+ keep_only = 14
574
+ top_0 = [item for item in combined_scores_sorted if item[2] == 0][:keep_only]
575
+ top_1 = [item for item in combined_scores_sorted if item[2] == 1][:keep_only]
576
+
577
+ x_axis = max(scores) + max(scores) * 0.02
578
+ # Annotate the top scores for label 0
579
+ for i, (score, path, _, (src, dst, _, edge_type)) in enumerate(top_0):
580
+ y_position = 0 - (i * 0.1) # Adjust y-position for each label to avoid overlap
581
+ edge_type = edge_type.replace("EVENT_", "")
582
+ plt.text(
583
+ x_axis,
584
+ y_position,
585
+ f"({src}, {dst} | {node_to_path[int(src)]['type']}, {edge_type}, {node_to_path[int(dst)]['type']}): {str(path[0])[:28]} => {str(path[1])[:28]} ({score:.2f})",
586
+ fontsize=6,
587
+ va="center",
588
+ ha="left",
589
+ color="green",
590
+ )
591
+
592
+ # Annotate the top scores for label 1
593
+ for i, (score, path, _, (src, dst, _, edge_type)) in enumerate(top_1):
594
+ y_position = 1.4 - (
595
+ i * 0.1
596
+ ) # Adjust y-position for each label to avoid overlap and add space between groups
597
+ edge_type = edge_type.replace("EVENT_", "")
598
+ plt.text(
599
+ x_axis,
600
+ y_position,
601
+ f"({src}, {dst} | {node_to_path[int(src)]['type']}, {edge_type}, {node_to_path[int(dst)]['type']}): {str(path[0])[:28]} => {str(path[1])[:28]} ({score:.2f})",
602
+ fontsize=6,
603
+ va="center",
604
+ ha="left",
605
+ color="red",
606
+ )
607
+ plt.text(
608
+ min(scores),
609
+ 1.6,
610
+ f"Dataset: {cfg.dataset.name}",
611
+ fontsize=8,
612
+ va="center",
613
+ ha="left",
614
+ color="black",
615
+ )
616
+ plt.text(
617
+ min(scores),
618
+ 1.5,
619
+ f"Malicious TW: {str(list(tw_to_malicious_nodes.keys()))}",
620
+ fontsize=8,
621
+ va="center",
622
+ ha="left",
623
+ color="black",
624
+ )
625
+
626
+ finite_scores = np.array(scores)[np.isfinite(scores)]
627
+ if len(finite_scores) == 0:
628
+ finite_scores = np.array([0.0, 1.0])
629
+ plt.xlim([np.min(finite_scores), max(np.max(finite_scores) * 1.5, 1e-6)]) # Adjust xlim to make space for text
630
+ plt.ylim([-1, 2]) # Adjust ylim to ensure the text is within the figure bounds
631
+ plt.savefig(out_file)
632
+
633
+
634
+ def plot_scores_neat(scores, y_truth, nodes, node2attacks, out_file, threshold=None):
635
+ # Separate scores based on labels
636
+ scores_0 = [
637
+ score
638
+ for i, (score, label) in enumerate(zip(scores, y_truth))
639
+ if label == 0 and (score > 0.9 or (score <= 0.9 and i % 500 == 1))
640
+ ]
641
+ scores_1 = [(score, node) for score, label, node in zip(scores, y_truth, nodes) if label == 1]
642
+
643
+ center_coef = 0.2 # to center the lines/dots
644
+
645
+ # Positions on the y-axis for the scatter plot
646
+ y_zeros = [center_coef] * len(scores_0) # All zeros at y=0
647
+ y_ones = [1 - center_coef] * len(scores_1) # All ones at y=1
648
+
649
+ plt.figure(figsize=(6, 1.5)) # Width, height in inches
650
+ plt.scatter(scores_0, y_zeros, color="green", label="Benign", rasterized=True)
651
+
652
+ # Plot each malicious node with its corresponding color based on its attack type
653
+ labels, colors, scores = [], [], []
654
+ for score, node in scores_1:
655
+ scores.append(score)
656
+ attack_type = list(node2attacks.get(node))[0]
657
+ labels.append(f"Attack {attack_type}")
658
+ colors.append(attack_colors.get(attack_type, "black"))
659
+ plt.scatter(scores, y_ones, color=colors, label=labels, rasterized=True)
660
+
661
+ if threshold is not None:
662
+ plt.axvline(
663
+ x=threshold, color="black", linestyle="-", linewidth=2, label=f"Threshold: {threshold}"
664
+ )
665
+
666
+ plt.xlabel("Node anomaly scores")
667
+ plt.yticks([center_coef, 1 - center_coef], ["Benign", "Malicious"])
668
+ plt.ylim(-0.1, 1.1) # Adjust if necessary to bring them even closer
669
+
670
+ plt.tight_layout() # Ensures everything fits within the figure area
671
+ plt.savefig(out_file, dpi=300)
672
+ plt.close()
673
+
674
+
675
+ def plot_false_positives(y_true, y_pred, out_file):
676
+ plt.figure(figsize=(10, 6))
677
+
678
+ plt.plot(y_pred, label="y_pred", color="blue")
679
+
680
+ # Adding green dots for true positives (y_true == 1)
681
+ label_indices = [i for i, true in enumerate(y_true) if true == 1]
682
+ plt.scatter(
683
+ label_indices, [y_pred[i] for i in label_indices], color="green", label="True Positive"
684
+ )
685
+
686
+ # Adding red dots for false positives (y_true == 0 and y_pred == 1)
687
+ false_positive_indices = [
688
+ i for i, (true, pred) in enumerate(zip(y_true, y_pred)) if true == 0 and pred == 1
689
+ ]
690
+ plt.scatter(
691
+ false_positive_indices,
692
+ [y_pred[i] for i in false_positive_indices],
693
+ color="red",
694
+ label="False Positive",
695
+ )
696
+
697
+ plt.xlabel("Index")
698
+ plt.ylabel("Prediction Value")
699
+ plt.title("True Positives and False Positives in Predictions")
700
+ plt.legend()
701
+ plt.savefig(out_file)
702
+
703
+
704
+ def plot_dor_recall_curve(scores, y_truth, out_file):
705
+ scores = np.array(scores)
706
+ y_truth = np.array(y_truth)
707
+ thresholds = np.linspace(scores.min(), scores.max(), 300)
708
+
709
+ sensitivity_list = []
710
+ dor_list = []
711
+
712
+ # Iterate over each threshold to calculate recall and DOR
713
+ for threshold in thresholds:
714
+ # Make predictions based on the threshold
715
+ predictions = (scores >= threshold).astype(int)
716
+
717
+ # Calculate TP, FP, TN, FN
718
+ TN, FP, FN, TP = confusion_matrix(y_truth, predictions, labels=[0, 1]).ravel()
719
+ recall = TP / (TP + FN) if (TP + FN) > 0 else 0
720
+
721
+ # Calculate Diagnostic Odds Ratio (DOR)
722
+ if (FP * FN) == 0:
723
+ dor = np.nan
724
+ else:
725
+ dor = (TP * TN) / (FP * FN)
726
+
727
+ sensitivity_list.append(recall)
728
+ dor_list.append(dor)
729
+
730
+ # Convert lists to numpy arrays for plotting
731
+ sensitivity_list = np.array(sensitivity_list)
732
+ dor_list = np.array(dor_list)
733
+
734
+ # Create the plot
735
+ plt.figure(figsize=(10, 6))
736
+ plt.plot(sensitivity_list, dor_list, label="DOR vs Sensitivity", color="blue", marker="o")
737
+ plt.xlabel("Sensitivity")
738
+ plt.ylabel("Diagnostic Odds Ratio (DOR)")
739
+ plt.title("Diagnostic Odds Ratio vs Sensitivity at Different Thresholds")
740
+ plt.grid(True)
741
+ plt.legend()
742
+ plt.savefig(out_file)
743
+
744
+
745
+ def attack_hits(nodes, node2attacks):
746
+ """(positions, attacks) of the items of `nodes` (nodes, or edge tuples) that belong to attacks:
747
+ `attacks[j]` is `node2attacks[nodes[positions[j]]]`.
748
+
749
+ `nodes` may be a lazy sequence with an `attack_hits(node2attacks)` method (e.g. the test
750
+ edges of the edge evaluation), which avoids building millions of Python items."""
751
+ if hasattr(nodes, "attack_hits"):
752
+ return nodes.attack_hits(node2attacks)
753
+ positions, attacks = [], []
754
+ for i, node in enumerate(nodes):
755
+ found = node2attacks.get(node)
756
+ if found is not None:
757
+ positions.append(i)
758
+ attacks.append(found)
759
+ return np.array(positions, dtype=np.int64), attacks
760
+
761
+
762
+ def take_items(nodes, idx):
763
+ """Items of `nodes` at the positions `idx` (`nodes.take(idx)` for lazy sequences)."""
764
+ if hasattr(nodes, "take"):
765
+ return nodes.take(idx)
766
+ return [nodes[i] for i in np.asarray(idx, dtype=np.int64).tolist()]
767
+
768
+
769
+ def _descending_order(scores):
770
+ # Same ranking (and order of ties) as `np.argsort(scores)[::-1]` on the original values
771
+ return np.argsort(np.asarray(scores))[::-1]
772
+
773
+
774
+ def detected_attacks_vs_precision(scores, nodes, node2attacks, labels):
775
+ """Curve of the percentage of detected attacks vs precision, when ranking the nodes by
776
+ descending score: (unique precisions, max percentage of detected attacks at each one).
777
+
778
+ Duplicate precisions keep the max percentage. The curve starts at (0, 0).
779
+ """
780
+ labels = np.asarray(labels)
781
+ order = _descending_order(scores)
782
+ total_attacks = len(set(attack for attacks in node2attacks.values() for attack in attacks))
783
+ if len(order) and total_attacks == 0:
784
+ raise ZeroDivisionError("No attack to detect")
785
+
786
+ sorted_labels = labels[order] == 1
787
+ tp = np.cumsum(sorted_labels)
788
+ fp = np.cumsum(~sorted_labels)
789
+ precisions = tp / (tp + fp)
790
+
791
+ # Rank at which each attack is first detected (by one of its nodes labelled malicious)
792
+ rank = np.empty(len(order), dtype=np.int64)
793
+ rank[order] = np.arange(len(order))
794
+ first_rank = {}
795
+ hit_pos, hit_attacks = attack_hits(nodes, node2attacks)
796
+ for i, attacks in zip(hit_pos.tolist(), hit_attacks):
797
+ if labels[i] == 1:
798
+ for attack in attacks:
799
+ first_rank[attack] = min(first_rank.get(attack, len(order)), int(rank[i]))
800
+ detected = np.searchsorted(np.sort(list(first_rank.values())), np.arange(len(order)), side="right")
801
+ percentages = (detected / max(total_attacks, 1)) * 100
802
+
803
+ x = np.concatenate(([0.0], precisions))
804
+ y = np.concatenate(([0.0], percentages))
805
+ by_x = np.argsort(x, kind="stable")
806
+ x, y = x[by_x], y[by_x]
807
+ starts = np.flatnonzero(np.r_[True, x[1:] != x[:-1]])
808
+ return x[starts], np.maximum.reduceat(y, starts)
809
+
810
+
811
+ def plot_detected_attacks_vs_precision(scores, nodes, node2attacks, labels, out_file):
812
+ """
813
+ Plot the percentage of detected attacks vs precision using anomaly scores, node IDs,
814
+ ground truth labels, and mapping of nodes to their respective attack numbers.
815
+
816
+ Precision is on the x-axis and the cumulative percentage of detected attacks on the y-axis
817
+ (see `detected_attacks_vs_precision`). Returns the area under the curve (ADP score); the
818
+ figure is not saved when `out_file` is None.
819
+ """
820
+ unique_precisions, max_detected_attacks_percentages = detected_attacks_vs_precision(
821
+ scores, nodes, node2attacks, labels
822
+ )
823
+
824
+ # Calculate area under the curve for % detected attacks vs precision
825
+ area_under_curve = np.trapz(max_detected_attacks_percentages, unique_precisions) / 100
826
+ if out_file is None:
827
+ return area_under_curve
828
+
829
+ # Plotting
830
+ try:
831
+ plt.figure(figsize=(10, 6))
832
+ plt.plot(
833
+ unique_precisions,
834
+ max_detected_attacks_percentages,
835
+ color="b",
836
+ label=f"Area under curve = {area_under_curve:.2f}",
837
+ )
838
+ plt.fill_between(
839
+ unique_precisions, max_detected_attacks_percentages, color="blue", alpha=0.2
840
+ )
841
+ plt.xlabel("Precision")
842
+ plt.ylabel("% of Detected Attacks")
843
+ plt.title("Percentage of Detected Attacks vs Precision")
844
+ plt.legend(loc="lower left")
845
+ plt.xlim(0, 1)
846
+ plt.ylim(0, 100.5)
847
+ plt.grid(True)
848
+ plt.savefig(out_file)
849
+ plt.close()
850
+ except:
851
+ print("Error while generating ADP plot")
852
+ return area_under_curve
853
+
854
+
855
+ def plot_recall_vs_precision(scores, nodes, node2attacks, labels, out_file):
856
+ """
857
+ Plot the recall vs precision using anomaly scores, node IDs, ground truth labels,
858
+ and a mapping of node IDs to their respective attack numbers.
859
+
860
+ This function calculates precision on the x-axis and recall on the y-axis, handles duplicate
861
+ x-values by taking the maximum y-value for each unique x-value, and then plots it with a
862
+ filled area under the curve.
863
+ Ensures that the plot starts at (0, 0).
864
+ """
865
+ # Sort nodes by descending anomaly scores
866
+ sorted_indices = np.argsort(scores)[::-1]
867
+ sorted_nodes = [nodes[i] for i in sorted_indices]
868
+ sorted_labels = [labels[i] for i in sorted_indices]
869
+
870
+ # Initialize variables for tracking true positives and recall
871
+ total_positives = np.sum(labels) # Total number of actual positives
872
+ tp = 0 # True positives
873
+ fp = 0 # False positives
874
+
875
+ recalls = [0] # Start at y=0
876
+ precisions = [0] # Start at x=0
877
+
878
+ # Count true positives and calculate precision and recall at each threshold
879
+ for i, node in enumerate(sorted_nodes):
880
+ # Update tp and fp based on the current label
881
+ if sorted_labels[i] == 1:
882
+ tp += 1
883
+ else:
884
+ fp += 1
885
+
886
+ # Calculate precision and recall
887
+ precision = tp / (tp + fp)
888
+ recall = tp / total_positives
889
+
890
+ precisions.append(precision)
891
+ recalls.append(recall)
892
+
893
+ # Use max recall for each unique precision
894
+ precision_to_recall = defaultdict(list)
895
+ for precision, recall in zip(precisions, recalls):
896
+ precision_to_recall[precision].append(recall)
897
+
898
+ unique_precisions = []
899
+ max_recalls = []
900
+ for precision, recall_list in sorted(precision_to_recall.items()):
901
+ unique_precisions.append(precision)
902
+ max_recalls.append(np.max(recall_list))
903
+
904
+ # Calculate area under the curve for recall vs precision
905
+ area_under_curve = np.trapz(max_recalls, unique_precisions) / 100
906
+
907
+ # Plotting
908
+ plt.figure(figsize=(10, 6))
909
+ plt.plot(
910
+ unique_precisions,
911
+ max_recalls,
912
+ color="b",
913
+ label=f"Area under curve = {area_under_curve:.2f}",
914
+ )
915
+ plt.fill_between(unique_precisions, max_recalls, color="blue", alpha=0.2)
916
+ plt.xlabel("Precision")
917
+ plt.ylabel("Recall")
918
+ plt.title("Recall vs Precision")
919
+ plt.legend(loc="lower left")
920
+ plt.xlim(0, 1)
921
+ plt.ylim(0, 1)
922
+ plt.grid(True)
923
+ plt.savefig(out_file)
924
+ return area_under_curve
925
+
926
+
927
+ def plot_discrimination_metric(scores, y_truth, out_file):
928
+ scores = np.array(scores)
929
+ y_truth = np.array(y_truth)
930
+ anomalous_scores = scores[y_truth == 1]
931
+ benign_scores = scores[y_truth == 0]
932
+
933
+ # Define the top K value
934
+ K = len(anomalous_scores)
935
+ if K == 0:
936
+ return 0.0
937
+
938
+ # Get top K scores for anomalies and benign samples
939
+ top_anomalous_scores = np.sort(anomalous_scores)[-K:][::-1]
940
+ top_benign_scores = np.sort(benign_scores)[-K:][::-1]
941
+
942
+ # Calculate the boolean mask where anomalies > benign
943
+ mask = top_anomalous_scores > top_benign_scores
944
+
945
+ # Compute the raw separation area
946
+ if mask.sum() > 0:
947
+ # Positive overlap exists
948
+ raw_area = np.trapz(top_anomalous_scores[mask] - top_benign_scores[mask], dx=1)
949
+ else:
950
+ # No positive overlap; compute negative area
951
+ raw_area = -np.trapz(top_benign_scores - top_anomalous_scores, dx=1)
952
+
953
+ # Calculate the range of scores (y-axis normalization)
954
+ max_score = max(top_anomalous_scores.max(), top_benign_scores.max())
955
+ min_score = min(top_anomalous_scores.min(), top_benign_scores.min())
956
+ score_range = max_score - min_score
957
+
958
+ # Normalize the area
959
+ total_plot_area = score_range * K
960
+ area = raw_area / total_plot_area
961
+
962
+ # Visualization
963
+ plt.figure(figsize=(8, 6))
964
+ plt.plot(range(K), top_anomalous_scores, label="Top Anomalies", color="red")
965
+ plt.plot(range(K), top_benign_scores, label="Top Benign", color="blue")
966
+
967
+ # Highlight the positive or negative area
968
+ if mask.sum() > 0:
969
+ # Positive overlap exists
970
+ plt.fill_between(
971
+ range(K),
972
+ top_anomalous_scores,
973
+ top_benign_scores,
974
+ where=(top_anomalous_scores > top_benign_scores),
975
+ interpolate=True,
976
+ color="purple",
977
+ alpha=0.2,
978
+ label=f"Positive Area {area:.2f}",
979
+ )
980
+ else:
981
+ # No positive overlap; negative area
982
+ plt.fill_between(
983
+ range(K),
984
+ top_anomalous_scores,
985
+ top_benign_scores,
986
+ where=(top_anomalous_scores < top_benign_scores),
987
+ interpolate=True,
988
+ color="orange",
989
+ alpha=0.2,
990
+ label=f"Negative Area {area:.2f}",
991
+ )
992
+
993
+ plt.xlabel("Rank")
994
+ plt.ylabel("Anomaly Score")
995
+ plt.title("Top K Anomalous vs Benign Scores")
996
+ plt.legend()
997
+ plt.grid(alpha=0.5)
998
+ plt.savefig(out_file)
999
+ plt.close()
1000
+ return area
1001
+
1002
+
1003
+ def _top_benign_mean(normalized, y_truth, k):
1004
+ """Mean of the `k` highest normalized scores of benign items."""
1005
+ benign = normalized[y_truth == 0]
1006
+ if len(benign) > k:
1007
+ benign = np.partition(benign, len(benign) - k)[-k:]
1008
+ return np.mean(np.sort(benign)[-k:][::-1])
1009
+
1010
+
1011
+ def _normalized_scores(pred_scores):
1012
+ pred_scores = np.array(pred_scores).astype(float)
1013
+ pred_scores /= pred_scores.max() + 1e-6
1014
+ return pred_scores
1015
+
1016
+
1017
+ def compute_discrimination_score(pred_scores, nodes, node2attacks, y_truth, k=10):
1018
+ pred_scores = _normalized_scores(pred_scores)
1019
+ y_truth = np.asarray(y_truth)
1020
+
1021
+ attack2max_score = defaultdict(float)
1022
+ hit_pos, hit_attacks = attack_hits(nodes, node2attacks)
1023
+ for i, attacks in zip(hit_pos.tolist(), hit_attacks):
1024
+ for attack in attacks:
1025
+ attack2max_score[attack] = max(attack2max_score[attack], pred_scores[i])
1026
+ attack2max_score = dict(sorted(attack2max_score.items(), key=lambda item: item[0]))
1027
+
1028
+ mean = _top_benign_mean(pred_scores, y_truth, k)
1029
+ att2score = {}
1030
+
1031
+ for att in set.union(*list(node2attacks.values())):
1032
+ att2score[f"discrim_score_att_{att}"] = 0
1033
+
1034
+ for k, v in attack2max_score.items():
1035
+ score = v - mean
1036
+ att2score[f"discrim_score_att_{k}"] = score
1037
+ att2score["discrimination"] = np.mean(list(att2score.values()))
1038
+
1039
+ return att2score
1040
+
1041
+
1042
+ def compute_discrimination_tp(pred_scores, nodes, node2attacks, y_truth, k=10):
1043
+ pred_scores = _normalized_scores(pred_scores)
1044
+ y_truth = np.asarray(y_truth)
1045
+
1046
+ mean = _top_benign_mean(pred_scores, y_truth, k)
1047
+ att2tp = defaultdict(int)
1048
+
1049
+ for att in set.union(*list(node2attacks.values())):
1050
+ att2tp[f"discrim_tp_att_{att}"] = 0
1051
+
1052
+ hit_pos, hit_attacks = attack_hits(nodes, node2attacks)
1053
+ for i, attacks in zip(hit_pos.tolist(), hit_attacks):
1054
+ if pred_scores[i] > mean:
1055
+ for attack in attacks:
1056
+ att2tp[f"discrim_tp_att_{attack}"] += 1
1057
+ att2tp["discrim_tp_att_sum"] = np.sum(list(att2tp.values()))
1058
+
1059
+ return att2tp
1060
+
1061
+
1062
+ def compute_tp_per_attack_thr(pred_scores, nodes, node2attacks, y_truth, thr):
1063
+ pred_scores = np.array(pred_scores).astype(float)
1064
+ y_truth = np.array(y_truth)
1065
+
1066
+ pred_scores /= pred_scores.max() + 1e-6
1067
+ att2tp = defaultdict(int)
1068
+
1069
+ for att in set.union(*list(node2attacks.values())):
1070
+ att2tp[f"tp_att_{att}"] = 0
1071
+
1072
+ for node, score in zip(nodes, pred_scores):
1073
+ if node in node2attacks:
1074
+ for attack in node2attacks[node]:
1075
+ if score > thr:
1076
+ att2tp[f"tp_att_{attack}"] += 1
1077
+
1078
+ return att2tp
1079
+
1080
+
1081
+ def get_detected_tps(scores, src_dst_t_type, edge2attack, y_truth, cfg):
1082
+ """
1083
+ Maps each attack to edges that are true positives based on scores.
1084
+
1085
+ Args:
1086
+ scores (np.ndarray or list): Confidence scores for each edge.
1087
+ src_dst_t_type (list of tuples): List of (src, dst, t, type) tuples representing edges.
1088
+ edge2attack (dict): Dictionary mapping edge indices to attack identifiers.
1089
+ y_truth (np.ndarray or list): Ground truth labels (1 for true, 0 for false).
1090
+
1091
+ Returns:
1092
+ dict: Dictionary mapping attack identifiers to lists of detected true positive edges (as tuples).
1093
+ """
1094
+ # Ranking by descending score; the top k edges are true positives ranked above the first FP
1095
+ indices = _descending_order(scores)
1096
+ sorted_labels = np.asarray(y_truth)[indices]
1097
+ false_positives = np.flatnonzero(sorted_labels == 0)
1098
+ k = int(false_positives[0]) if len(false_positives) else len(indices)
1099
+ true_positive_edges = take_items(src_dst_t_type, indices[:k])
1100
+
1101
+ node_to_path = get_node_to_path_and_type(cfg)
1102
+
1103
+ get_label = (
1104
+ lambda data: f"{data.get('path')}-{data.get('cmd')}".replace("None-", "")
1105
+ if data["type"] == "subject"
1106
+ else data.get("path")
1107
+ )
1108
+
1109
+ # Map true positive edges to their attacks
1110
+ attack_to_detected_edges = {}
1111
+ attacks = set.union(*list(edge2attack.values()))
1112
+ for att in attacks:
1113
+ attack_to_detected_edges[att] = []
1114
+ for edge in true_positive_edges:
1115
+ attack = list(edge2attack.get(edge))[0]
1116
+ if attack is not None: # Only include edges with a valid attack mapping
1117
+ src_node = node_to_path[int(edge[0])]
1118
+ dst_node = node_to_path[int(edge[1])]
1119
+ edge = (
1120
+ get_label(src_node),
1121
+ get_label(dst_node),
1122
+ src_node["type"],
1123
+ dst_node["type"],
1124
+ ) + edge
1125
+ attack_to_detected_edges[attack].append(edge)
1126
+
1127
+ return attack_to_detected_edges
1128
+
1129
+
1130
+ def get_detected_tps_node_level(scores, nodes, node2attack, y_truth, cfg):
1131
+ """
1132
+ Maps each attack to nodes that are true positives based on scores.
1133
+
1134
+ Args:
1135
+ scores (np.ndarray or list): Confidence scores for each node.
1136
+ nodes (list of tuples): List of nodes.
1137
+ node2attack (dict): Dictionary mapping node indices to attack identifiers.
1138
+ y_truth (np.ndarray or list): Ground truth labels (1 for true, 0 for false).
1139
+
1140
+ Returns:
1141
+ dict: Dictionary mapping attack identifiers to lists of detected true positive nodes (as tuples).
1142
+ """
1143
+ # Ensure inputs are numpy arrays for easier manipulation
1144
+ scores = np.array(scores)
1145
+ y_truth = np.array(y_truth)
1146
+
1147
+ # Create an array of indices to sort by scores
1148
+ indices = np.argsort(scores)[::-1] # Sort in descending order
1149
+
1150
+ # Sort scores, edges, and labels based on descending scores
1151
+ sorted_scores = scores[indices]
1152
+ sorted_nodes = [nodes[i] for i in indices]
1153
+ sorted_labels = y_truth[indices]
1154
+
1155
+ # Find the cutoff k where no false positives (label 0) are included
1156
+ k = 0
1157
+ for i, label in enumerate(sorted_labels):
1158
+ if label == 0: # Stop at the first false positive
1159
+ k = i
1160
+ break
1161
+ k = i + 1 # Include all true positives up to this point
1162
+
1163
+ # Select the top k nodes (true positives)
1164
+ true_positive_nodes = sorted_nodes[:k]
1165
+ true_positive_indices = indices[:k]
1166
+
1167
+ node_to_path = get_node_to_path_and_type(cfg)
1168
+
1169
+ get_label = (
1170
+ lambda data: f"{data.get('path')}-{data.get('cmd')}".replace("None-", "")
1171
+ if data["type"] == "subject"
1172
+ else data.get("path")
1173
+ )
1174
+
1175
+ # Map true positive nodes to their attacks
1176
+ attack_to_detected_nodes = defaultdict(list)
1177
+ for node in true_positive_nodes:
1178
+ attack = list(node2attack.get(node))[0]
1179
+ if attack is not None: # Only include nodes with a valid attack mapping
1180
+ node_msg = get_label(node_to_path[int(node)]) + str(node)
1181
+ attack_to_detected_nodes[attack].append(node_msg)
1182
+
1183
+ return dict(attack_to_detected_nodes)
1184
+
1185
+
1186
+ def get_ground_truth_nids(cfg):
1187
+ # ground_truth_nids, ground_truth_paths = [], {}
1188
+ # for file in cfg.dataset.ground_truth_relative_path:
1189
+ # with open(os.path.join(cfg._ground_truth_dir, file), 'r') as f:
1190
+ # reader = csv.reader(f)
1191
+ # for row in reader:
1192
+ # node_uuid, node_labels, node_id = row[0], row[1], row[2]
1193
+ # ground_truth_nids.append(int(node_id))
1194
+ # ground_truth_paths[int(node_id)] = node_labels
1195
+ ground_truth_nids, ground_truth_paths, uuid_to_node_id = labelling.get_ground_truth(cfg)
1196
+ return set(ground_truth_nids), ground_truth_paths
1197
+
1198
+
1199
+ def get_ground_truth_uuid_to_node_id(cfg):
1200
+ # uuid_to_node_id = {}
1201
+ # for file in cfg.dataset.ground_truth_relative_path:
1202
+ # with open(os.path.join(cfg._ground_truth_dir, file), 'r') as f:
1203
+ # reader = csv.reader(f)
1204
+ # for row in reader:
1205
+ # node_uuid, node_labels, node_id = row[0], row[1], row[2]
1206
+ # uuid_to_node_id[node_uuid] = node_id
1207
+ ground_truth_nids, ground_truth_paths, uuid_to_node_id = labelling.get_ground_truth(cfg)
1208
+ return uuid_to_node_id
1209
+
1210
+
1211
+ def compute_tw_labels(cfg, losses_dir=None, tw_names=None):
1212
+ """
1213
+ Gets the malcious node IDs present in each time window.
1214
+
1215
+ When losses_dir is provided, enumerates the CSV files from that directory
1216
+ instead of the raw graph files. This is important because intra-graph
1217
+ batching may split a single graph into multiple sub-batches, each producing
1218
+ its own CSV. Using the CSV file list ensures the TW indices here match
1219
+ those assigned in node_evaluation.
1220
+
1221
+ When tw_names is provided (list of "start~end" strings, e.g. returned by
1222
+ `load_losses_per_time_window`), TW indices follow that list instead.
1223
+ """
1224
+ out_path = cfg.construction._tw_labels
1225
+ out_file = os.path.join(out_path, "tw_to_malicious_nodes.pkl")
1226
+ uuid_to_node_id = get_ground_truth_uuid_to_node_id(cfg)
1227
+
1228
+ # Edge GT may reference nodes not in the node-level GT CSVs (e.g. dst
1229
+ # files in attack edges). Build a full uuid->index_id map as fallback.
1230
+ if labelling._has_edge_csvs(cfg):
1231
+ full_uuid2nid, _ = get_uuid_to_index_id(cfg)
1232
+ for uuid, nid in full_uuid2nid.items():
1233
+ if uuid not in uuid_to_node_id:
1234
+ uuid_to_node_id[uuid] = str(nid)
1235
+
1236
+ os.makedirs(out_path, exist_ok=True)
1237
+
1238
+ t_to_node = labelling.get_t2malicious_node(cfg)
1239
+
1240
+ # Use CSV loss files when available so TW indices match node_evaluation
1241
+ if tw_names is not None:
1242
+ test_tw_files = list(tw_names)
1243
+ elif losses_dir is not None and os.path.isdir(losses_dir):
1244
+ test_tw_files = listdir_sorted(losses_dir)
1245
+ else:
1246
+ graph_dir = cfg.transformation._graphs_dir
1247
+ test_tw_files = get_all_graphs_for_dates(graph_dir, cfg.dataset.test_dates)
1248
+
1249
+ num_found_event_labels = 0
1250
+ tw_to_malicious_nodes = defaultdict(list)
1251
+ for i, tw in enumerate(test_tw_files):
1252
+ date = tw.split("/")[-1]
1253
+ start, end = (
1254
+ datetime_to_ns_time_US_handle_nano(date.split("~")[0], timezone=cfg.dataset.timezone),
1255
+ datetime_to_ns_time_US_handle_nano(date.split("~")[1], timezone=cfg.dataset.timezone),
1256
+ )
1257
+
1258
+ for t, node_ids in t_to_node.items():
1259
+ if start < t < end:
1260
+ for node_id in node_ids: # src, dst, or [src, dst] malicious nodes
1261
+ tw_to_malicious_nodes[i].append(node_id)
1262
+ num_found_event_labels += 1
1263
+
1264
+ log(f"Matched {num_found_event_labels}/{len(t_to_node)} event timestamps to test time windows.")
1265
+ torch.save(tw_to_malicious_nodes, out_file)
1266
+
1267
+ # Used to retrieve node ID from node raw UUID
1268
+ # node_labels_path = os.path.join(cfg._ground_truth_dir, cfg.dataset.ground_truth_events_relative_path)
1269
+
1270
+ # uuid_to_node_id = get_ground_truth_uuid_to_node_id(cfg)
1271
+
1272
+ # Create a mapping TW number => malicious node IDs
1273
+ all_malicious_nodes = set()
1274
+ for tw, nodes in tw_to_malicious_nodes.items():
1275
+ unique_nodes, counts = np.unique(nodes, return_counts=True)
1276
+ node_to_count = {node: count for node, count in zip(unique_nodes, counts)}
1277
+
1278
+ node_to_count = {
1279
+ uuid_to_node_id[node_id]: count for node_id, count in node_to_count.items()
1280
+ }
1281
+ all_malicious_nodes.update(node_to_count.keys())
1282
+ # pprint(node_to_count, width=1)
1283
+ tw_to_malicious_nodes[tw] = node_to_count
1284
+
1285
+ log(
1286
+ f"Total distinct malicious nodes across time windows: "
1287
+ f"{len(all_malicious_nodes)} / {len(uuid_to_node_id)} ground-truth nodes"
1288
+ )
1289
+
1290
+ return tw_to_malicious_nodes
1291
+
1292
+
1293
+ def _tw_name_to_ns_range(name, timezone):
1294
+ name = strip_loss_ext(os.path.basename(name))
1295
+ start, end = name.split("~")
1296
+ return (
1297
+ datetime_to_ns_time_US_handle_nano(start, timezone=timezone),
1298
+ datetime_to_ns_time_US_handle_nano(end, timezone=timezone),
1299
+ )
1300
+
1301
+
1302
+ def load_losses_per_time_window(losses_dir, cfg, max_unmatched_ratio=0.01):
1303
+ """Loads the loss files of a split/epoch directory and groups their rows by time window.
1304
+
1305
+ The CSVs written during inference do not necessarily map 1:1 to the time
1306
+ windows (graphs) built during construction: intra-graph batching splits a
1307
+ graph into several CSVs, while global/inter-graph batching may merge several
1308
+ graphs into a single CSV. Time-window-level evaluations (tw, node_tw, queue)
1309
+ require the original windows, so edges are re-assigned to the test graph
1310
+ whose time range contains their timestamp.
1311
+
1312
+ If the CSVs have no `time` column (node-level objectives) or the timestamps
1313
+ cannot be matched with the test graphs, each CSV is considered as one window.
1314
+
1315
+ Returns:
1316
+ tuple: (tw_names, tw_to_df) where tw_names is the ordered list of
1317
+ "start~end" window names (indices match `compute_tw_labels(cfg, tw_names=tw_names)`)
1318
+ and tw_to_df maps a window index to the DataFrame of its rows. Windows
1319
+ without any row are absent from tw_to_df.
1320
+ """
1321
+ files = listdir_sorted(losses_dir)
1322
+ dfs = [read_losses(os.path.join(losses_dir, f)) for f in files]
1323
+ per_file_names = [strip_loss_ext(f) for f in files]
1324
+ per_file = (per_file_names, {i: df for i, df in enumerate(dfs)})
1325
+
1326
+ if len(dfs) == 0 or not all("time" in df.columns for df in dfs):
1327
+ return per_file
1328
+
1329
+ graph_files = get_all_graphs_for_dates(cfg.transformation._graphs_dir, cfg.dataset.test_dates)
1330
+ if len(graph_files) == 0:
1331
+ log("WARNING: no test graph found, using loss files as time windows.")
1332
+ return per_file
1333
+
1334
+ tw_names = [os.path.basename(f) for f in graph_files]
1335
+ ranges = np.array([_tw_name_to_ns_range(n, cfg.dataset.timezone) for n in tw_names])
1336
+ starts, ends = ranges[:, 0], ranges[:, 1]
1337
+
1338
+ df = pd.concat(dfs, ignore_index=True)
1339
+ times = df["time"].to_numpy(dtype=np.int64)
1340
+ tw_idx = np.searchsorted(starts, times, side="right") - 1
1341
+ unmatched = (tw_idx < 0) | (times > ends[np.clip(tw_idx, 0, None)])
1342
+ unmatched_ratio = unmatched.mean() if len(times) > 0 else 0.0
1343
+ if unmatched_ratio > max_unmatched_ratio:
1344
+ log(
1345
+ f"WARNING: {unmatched_ratio:.1%} of edges do not fall in any test graph time window, "
1346
+ "using loss files as time windows."
1347
+ )
1348
+ return per_file
1349
+
1350
+ df["_tw"] = np.clip(tw_idx, 0, len(tw_names) - 1)
1351
+ tw_to_df = {
1352
+ int(tw): group.drop(columns="_tw").reset_index(drop=True)
1353
+ for tw, group in df.groupby("_tw", sort=True)
1354
+ }
1355
+ console.log_once( # Same for each epoch
1356
+ f"Grouped {len(files)} loss files into {len(tw_to_df)}/{len(tw_names)} non-empty time windows."
1357
+ )
1358
+ return tw_names, tw_to_df
1359
+
1360
+
1361
+ def datetime_to_ns_time_US_handle_nano(nano_date_str, timezone="US/Eastern"):
1362
+ date = nano_date_str.split(".")[0]
1363
+ nanos = nano_date_str.split(".")[1]
1364
+
1365
+ tz = pytz.timezone(timezone)
1366
+ timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
1367
+ dt = datetime.fromtimestamp(mktime(timeArray))
1368
+ timestamp = tz.localize(dt)
1369
+ timestamp = timestamp.timestamp()
1370
+ timeStamp = str(timestamp).split(".")[0] + nanos
1371
+ return int(timeStamp)
1372
+
1373
+
1374
+ def viz_graph(
1375
+ edge_index,
1376
+ edge_scores,
1377
+ node_scores,
1378
+ node_to_correct_pred,
1379
+ malicious_nodes,
1380
+ node_to_path_and_type,
1381
+ anomaly_threshold,
1382
+ out_dir,
1383
+ tw,
1384
+ cfg,
1385
+ n_hop,
1386
+ fuse_nodes,
1387
+ ):
1388
+ # On OpTC, the degree is too high so we remove 90% of non-malicious nodes
1389
+ # for visualization.
1390
+ # if dataset == "OPTC":
1391
+ # OPTC_NODE_TO_VISUALIZE = 201 # Set the node viz manually
1392
+ # idx = edge_index[0, :] == OPTC_NODE_TO_VISUALIZE
1393
+
1394
+ # if 1 not in y[idx]:
1395
+ # return
1396
+
1397
+ # edge_index = edge_index[:, idx]
1398
+ # edge_scores = edge_scores[idx]
1399
+ # y = y[idx]
1400
+
1401
+ # indices_0 = np.where(y == 0)[0]
1402
+ # indices_1 = np.where(y == 1)[0]
1403
+
1404
+ # selected_indices_0 = np.random.choice(
1405
+ # indices_0, size=int(len(indices_0) * 0.1), replace=False
1406
+ # )
1407
+ # final_indices = np.concatenate((selected_indices_0, indices_1))
1408
+ # np.random.shuffle(final_indices)
1409
+
1410
+ # edge_index = edge_index[:, final_indices]
1411
+ # edge_scores = edge_scores[final_indices]
1412
+ # y = y[final_indices]
1413
+
1414
+ if edge_index.shape[0] != 2:
1415
+ edge_index = np.array([edge_index[:, 0], edge_index[:, 1]])
1416
+
1417
+ if fuse_nodes:
1418
+ idx = 0
1419
+ merged_nodes = defaultdict(lambda: defaultdict(int))
1420
+ merged_edges = defaultdict(lambda: defaultdict(list))
1421
+ old_node_to_merged_node = defaultdict(list)
1422
+ for i, (src, dst, score) in enumerate(zip(edge_index[0], edge_index[1], edge_scores)):
1423
+ edge_tuple = []
1424
+ for node in [src, dst]:
1425
+ path = node_to_path_and_type[node]["path"]
1426
+ typ = node_to_path_and_type[node]["type"]
1427
+
1428
+ if (path, typ) not in merged_nodes:
1429
+ merged_nodes[(path, typ)] = {"idx": idx, "label": 0, "predicted": 0}
1430
+ idx += 1
1431
+ edge_tuple.append(merged_nodes[(path, typ)]["idx"])
1432
+ old_node_to_merged_node[node] = merged_nodes[(path, typ)]["idx"]
1433
+
1434
+ # If only one malicious node is present in the merged node, it is malicious
1435
+ merged_nodes[(path, typ)]["label"] = max(
1436
+ merged_nodes[(path, typ)]["label"], int(node in malicious_nodes)
1437
+ )
1438
+ # I fonly one good prediction of the merged nodes is correct, we set predicted=1. If node not predicted, we set to -1
1439
+ merged_nodes[(path, typ)]["predicted"] = max(
1440
+ merged_nodes[(path, typ)]["predicted"], int(node_to_correct_pred.get(node, -1))
1441
+ )
1442
+
1443
+ merged_edges[tuple(edge_tuple)]["t"].append(i)
1444
+ merged_edges[tuple(edge_tuple)]["score"].append(score)
1445
+
1446
+ new_edge_index = np.array(list(merged_edges.keys())).T
1447
+ merged_edge_scores = [np.max(d["score"]) for _, d in merged_edges.items()]
1448
+ edge_t = [f"{np.min(d['t'])}-{np.max(d['t'])}" for _, d in merged_edges.items()]
1449
+
1450
+ # sorted_merged_nodes = dict(sorted(merged_nodes.items(), key=lambda item: item[1]))
1451
+ unique_nodes, unique_labels, unique_predicted, unique_paths, unique_types = (
1452
+ [],
1453
+ [],
1454
+ [],
1455
+ [],
1456
+ [],
1457
+ )
1458
+ for (path, typ), d in merged_nodes.items():
1459
+ unique_nodes.append(d["idx"])
1460
+ unique_labels.append(d["label"])
1461
+ unique_predicted.append(d["predicted"])
1462
+ unique_paths.append(path)
1463
+ unique_types.append(typ)
1464
+
1465
+ source_nodes = malicious_nodes
1466
+ new_source_nodes = {old_node_to_merged_node[n] for n in source_nodes}
1467
+
1468
+ else:
1469
+ # Flatten edge_index and map node IDs to a contiguous range starting from 0
1470
+ unique_nodes, new_edge_index = np.unique(edge_index.flatten(), return_inverse=True)
1471
+ new_edge_index = new_edge_index.reshape(edge_index.shape)
1472
+ unique_paths = [node_to_path_and_type[n]["path"] for n in unique_nodes]
1473
+ unique_types = [node_to_path_and_type[n]["type"] for n in unique_nodes]
1474
+ unique_labels = [n in malicious_nodes for n in unique_nodes]
1475
+ unique_predicted = [node_to_correct_pred.get(n, -1) for n in unique_nodes]
1476
+ edge_t = list(range(len(edge_index[0])))
1477
+
1478
+ source_nodes = malicious_nodes
1479
+ source_node_map = {old: new for new, old in enumerate(unique_nodes)}
1480
+ new_source_nodes = [source_node_map.get(node, -1) for node in source_nodes]
1481
+
1482
+ G = ig.Graph(edges=[tuple(e) for e in new_edge_index.T], directed=True)
1483
+
1484
+ # Node attributes
1485
+ G.vs["original_id"] = unique_nodes
1486
+ G.vs["path"] = unique_paths
1487
+ G.vs["type"] = unique_types
1488
+ G.vs["shape"] = [
1489
+ "rectangle" if typ == "file" else "circle" if typ == "subject" else "triangle"
1490
+ for typ in unique_types
1491
+ ]
1492
+
1493
+ G.vs["label"] = unique_labels
1494
+ G.vs["predicted"] = unique_predicted
1495
+ G.es["t"] = edge_t
1496
+
1497
+ # Edge attributes
1498
+ G.es["anomaly_score"] = edge_scores
1499
+
1500
+ # Find N-hop neighborhoods for the source nodes
1501
+ neighborhoods = set()
1502
+ for node in new_source_nodes:
1503
+ if node == -1:
1504
+ # Warning: one malicious node in {source_nodes} was not seen in the dataset ({new_source_nodes}).
1505
+ continue
1506
+ neighborhood = G.neighborhood(node, order=n_hop)
1507
+ neighborhoods.update(neighborhood)
1508
+
1509
+ # Create a subgraph with only the n-hop neighborhoods
1510
+ subgraph = G.subgraph(neighborhoods)
1511
+
1512
+ BENIGN = "#44BC"
1513
+ ATTACK = "#FF7E79"
1514
+ FAILURE = "red"
1515
+ SUCCESS = "green"
1516
+
1517
+ visual_style = {}
1518
+ visual_style["bbox"] = (700, 700)
1519
+ visual_style["margin"] = 40
1520
+ visual_style["layout"] = subgraph.layout("kk")
1521
+
1522
+ visual_style["vertex_size"] = 13
1523
+ visual_style["vertex_width"] = 13
1524
+ visual_style["vertex_label_dist"] = 1.3
1525
+ visual_style["vertex_label_size"] = 6
1526
+ visual_style["vertex_label_font"] = 1
1527
+ visual_style["vertex_color"] = [ATTACK if label else BENIGN for label in subgraph.vs["label"]]
1528
+ visual_style["vertex_label"] = subgraph.vs["path"]
1529
+ visual_style["vertex_frame_width"] = 2
1530
+ visual_style["vertex_frame_color"] = [
1531
+ "black" if predicted == -1 else SUCCESS if predicted else FAILURE
1532
+ for predicted in subgraph.vs["predicted"]
1533
+ ]
1534
+
1535
+ visual_style["edge_curved"] = 0.1
1536
+ visual_style["edge_width"] = 1 # [3 if label else 1 for label in y_hat]
1537
+ visual_style["edge_color"] = (
1538
+ "gray" # ["red" if label else "gray" for label in subgraph.es["y"]]
1539
+ )
1540
+ visual_style["edge_label"] = [
1541
+ f"s:{x:.2f}\nt:{t}" for x, t in zip(subgraph.es["anomaly_score"], subgraph.es["t"])
1542
+ ]
1543
+ visual_style["edge_label_size"] = 6
1544
+ visual_style["edge_label_color"] = "#888888"
1545
+ visual_style["edge_arrow_size"] = 8
1546
+ visual_style["edge_arrow_width"] = 8
1547
+
1548
+ # Create the plot
1549
+ fig, ax = plt.subplots(figsize=(12, 12))
1550
+
1551
+ # Plot the graph using igraph
1552
+ plot = ig.plot(subgraph, target=ax, **visual_style)
1553
+
1554
+ # Create legend handles
1555
+ legend_handles = [
1556
+ mpatches.Patch(color=BENIGN, label="Benign"),
1557
+ mpatches.Patch(color=ATTACK, label="Attack"),
1558
+ plt.Line2D(
1559
+ [0],
1560
+ [0],
1561
+ marker="o",
1562
+ color="w",
1563
+ markerfacecolor="k",
1564
+ markersize=10,
1565
+ label="Subject",
1566
+ markeredgewidth=1,
1567
+ ),
1568
+ plt.Line2D(
1569
+ [0],
1570
+ [0],
1571
+ marker="s",
1572
+ color="w",
1573
+ markerfacecolor="k",
1574
+ markersize=10,
1575
+ label="File",
1576
+ markeredgewidth=1,
1577
+ ),
1578
+ plt.Line2D(
1579
+ [0],
1580
+ [0],
1581
+ marker="^",
1582
+ color="w",
1583
+ markerfacecolor="k",
1584
+ markersize=10,
1585
+ label="IP",
1586
+ markeredgewidth=1,
1587
+ ),
1588
+ mpatches.Patch(edgecolor=FAILURE, label="False Pos/Neg", facecolor="none"),
1589
+ mpatches.Patch(edgecolor=SUCCESS, label="True Pos/Neg", facecolor="none"),
1590
+ ]
1591
+
1592
+ # Add legend to the plot
1593
+ ax.legend(handles=legend_handles, loc="upper right", fontsize="medium")
1594
+
1595
+ # Save the plot with legend
1596
+ out_file = f"{n_hop}-hop_attack_graph_tw_{tw}"
1597
+ svg = os.path.join(out_dir, f"{out_file}.png")
1598
+ plt.savefig(svg)
1599
+ plt.close(fig)
1600
+
1601
+ print(f"Graph {svg} saved, with attack nodes:\t {','.join([str(n) for n in source_nodes])}.")
1602
+ return {out_file: wandb.Image(svg)}
1603
+
1604
+
1605
+ def compute_kmeans_labels(results, topk_K):
1606
+ nodes_to_score = sorted(
1607
+ [(node_id, d["score"]) for node_id, d in results.items()], key=lambda x: x[1]
1608
+ )
1609
+ nodes_to_score = np.array(nodes_to_score, dtype=object)
1610
+ score_values = nodes_to_score[:, 1].astype(float)
1611
+
1612
+ last_N_scores = score_values[-topk_K:]
1613
+ last_N_nodes = nodes_to_score[-topk_K:]
1614
+
1615
+ # KMeans needs at least 2 samples: with a single node, it is the top anomaly
1616
+ if len(last_N_scores) < 2:
1617
+ for node_id in last_N_nodes[:, 0]:
1618
+ results[node_id]["y_hat"] = 1
1619
+ return results
1620
+
1621
+ kmeans = KMeans(n_clusters=2, random_state=0, n_init=10)
1622
+ kmeans.fit(last_N_scores.reshape(-1, 1))
1623
+
1624
+ centroids = kmeans.cluster_centers_.flatten()
1625
+ highest_cluster_index = np.argmax(centroids)
1626
+
1627
+ # Extract scores from the highest value cluster
1628
+ highest_value_cluster_indices = np.where(kmeans.labels_ == highest_cluster_index)[0]
1629
+ highest_value_cluster = last_N_nodes[highest_value_cluster_indices]
1630
+
1631
+ # Extract scores and nodes from the highest cluster
1632
+ cluster_scores = highest_value_cluster[:, 1].astype(float)
1633
+ anomaly_nodes = highest_value_cluster[:, 0]
1634
+
1635
+ for idx in highest_value_cluster_indices:
1636
+ global_idx = len(score_values) - len(last_N_scores) + idx
1637
+ node_id = nodes_to_score[global_idx, 0]
1638
+ results[node_id]["y_hat"] = 1
1639
+
1640
+ return results
1641
+
1642
+
1643
+ def transform_attack2nodes_to_node2attacks(attack2nodes):
1644
+ node2attacks = defaultdict(set)
1645
+ for attack, nodes in attack2nodes.items():
1646
+ for node in nodes:
1647
+ node2attacks[node].add(attack)
1648
+ return dict(node2attacks)
1649
+
1650
+
1651
+ def get_metrics_if_all_attacks_detected(pred_scores, nodes, attack_to_GPs):
1652
+ """FPs and TPs ranked above the item (node or edge) that makes all the attacks detected,
1653
+ items being ranked by descending (score, item)."""
1654
+ nodes_per_attack = [v["nids"] if isinstance(v, dict) else v for k, v in attack_to_GPs.items()]
1655
+ total_attack_nodes = sum(len(nodes_set) for nodes_set in nodes_per_attack)
1656
+ scores = np.asarray(pred_scores, dtype=np.float64)
1657
+
1658
+ # Attacks (indices in `nodes_per_attack`) of each item
1659
+ node2attack_ids = defaultdict(set)
1660
+ for i, nodes_set in enumerate(nodes_per_attack):
1661
+ for node in nodes_set:
1662
+ node2attack_ids[node].add(i)
1663
+ hit_pos, hit_attacks = attack_hits(nodes, dict(node2attack_ids))
1664
+ is_hit = np.zeros(len(scores), dtype=bool)
1665
+ is_hit[hit_pos] = True
1666
+
1667
+ # Best score of each attack: it is detected once this score is reached
1668
+ best = {}
1669
+ for i, attacks in zip(hit_pos.tolist(), hit_attacks):
1670
+ for attack in attacks:
1671
+ best[attack] = max(best.get(attack, -np.inf), scores[i])
1672
+ if not nodes_per_attack:
1673
+ tps = fps = 0
1674
+ elif len(best) < len(nodes_per_attack):
1675
+ # Some attacks are never detected: all the items are counted
1676
+ tps = int(is_hit.sum())
1677
+ fps = len(scores) - tps
1678
+ else:
1679
+ # All the attacks are detected among the items of the lowest best score, ordered by
1680
+ # descending item
1681
+ threshold = min(best.values())
1682
+ above = scores > threshold
1683
+ tps = int((is_hit & above).sum())
1684
+ fps = int(above.sum()) - tps
1685
+ detected = {attack for attack, score in best.items() if score > threshold}
1686
+ tie = np.flatnonzero(scores == threshold)
1687
+ attacks_of = dict(zip(hit_pos.tolist(), hit_attacks))
1688
+ for _, i in sorted(zip(take_items(nodes, tie), tie.tolist()), reverse=True):
1689
+ attacks = attacks_of.get(i)
1690
+ if attacks is not None:
1691
+ detected |= attacks
1692
+ if len(detected) == len(nodes_per_attack):
1693
+ break
1694
+ if attacks is not None:
1695
+ tps += 1
1696
+ else:
1697
+ fps += 1
1698
+
1699
+ precision = tps / (tps + fps + 1e-12)
1700
+ recall = tps / (total_attack_nodes + 1e-12)
1701
+
1702
+ return fps, tps, precision, recall
1703
+
1704
+
1705
+ def two_hop_relaxed_metrics(mp_mask, gp_mask, adjacency):
1706
+ def _khop(mask_bool, k):
1707
+ m = mask_bool.astype(np.float32)
1708
+ for _ in range(k):
1709
+ m = ((adjacency @ m) + m > 0).astype(np.float32)
1710
+ return m > 0
1711
+
1712
+ tp_m = mp_mask & gp_mask
1713
+ fp_m = mp_mask & ~gp_mask
1714
+ fn_m = gp_mask & ~mp_mask
1715
+ two_hop_gp = _khop(gp_mask, 2)
1716
+ two_hop_tp = _khop(tp_m, 2)
1717
+ fpl = fp_m & ~two_hop_gp # forgive FP within 2 hops of a GT node
1718
+ tpl = tp_m | (fn_m & two_hop_tp) # credit missed GT within 2 hops of a TP
1719
+ fn = fn_m & ~two_hop_tp
1720
+ tp, fp, fn = int(tpl.sum()), int(fpl.sum()), int(fn.sum())
1721
+ prec = tp / (tp + fp) if tp + fp else 0.0
1722
+ rec = tp / (tp + fn) if tp + fn else 0.0
1723
+ f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
1724
+ return {"precision": prec, "recall": rec, "fscore": f1, "tp": tp, "fp": fp, "fn": fn}
1725
+
1726
+
1727
+ # Metrics of the one-line summary of each epoch, when they are computed
1728
+ SUMMARY_METRICS = [
1729
+ "adp_score", "discrimination", "ap", "auc", "tp", "fp", "fn", "mcc", "precision", "recall",
1730
+ ] # fmt: skip
1731
+
1732
+ # First metrics of the best epoch (see `log_best_epoch`), followed by the others
1733
+ BEST_EPOCH_METRICS = [
1734
+ "adp_score", "ap", "auc", "mcc", "precision", "recall", "tp", "fp", "tn", "fn",
1735
+ ] # fmt: skip
1736
+
1737
+ # Key, in the stats of an epoch, of the lines of its detailed analysis (e.g. the score of each
1738
+ # malicious node), logged for the best epoch only and removed from the stats (see `pop_report`)
1739
+ REPORT_KEY = "_report"
1740
+
1741
+
1742
+ def detection_mark(detected):
1743
+ """Colored TP/FN mark of a malicious node or time window."""
1744
+ return console.style("TP", "green") if detected else console.style("FN", "red")
1745
+
1746
+
1747
+ def pop_report(stats):
1748
+ """Removes and returns the analysis lines of `stats` (see `REPORT_KEY`)."""
1749
+ return stats.pop(REPORT_KEY, None) or []
1750
+
1751
+
1752
+ def epoch_name(model_epoch_dir):
1753
+ """"model_epoch_13" -> "epoch 13"."""
1754
+ epoch = model_epoch_dir.rsplit("_", 1)[-1]
1755
+ return f"epoch {epoch}" if epoch.isdigit() else model_epoch_dir
1756
+
1757
+
1758
+ def log_epoch_summary(stats):
1759
+ parts = [
1760
+ f"{console.style(k, 'dim')} {console.format_value(stats[k])}"
1761
+ for k in SUMMARY_METRICS
1762
+ if k in stats and isinstance(stats[k], (int, float))
1763
+ ]
1764
+ log(" ".join(parts))
1765
+
1766
+
1767
+ def log_best_epoch(stats, cfg, report=(), selection=None):
1768
+ """Logs the detailed analysis (`report`, e.g. the score of each malicious node) and all the
1769
+ metrics of the best epoch, selected by `selection` (default: `evaluation.best_model_selection`)."""
1770
+ if stats is None:
1771
+ return
1772
+ selection = selection or cfg.evaluation.best_model_selection
1773
+ print(flush=True)
1774
+ log(
1775
+ console.style(f"Best epoch: {stats.get('epoch')}", "bold")
1776
+ + console.style(f" (selection: {selection})", "dim")
1777
+ )
1778
+ for i, line in enumerate(report):
1779
+ if line.startswith(" "):
1780
+ log(line)
1781
+ elif i + 1 < len(report) and report[i + 1].startswith(" "): # Title of a non-empty section
1782
+ log(console.style(line, "bold"))
1783
+ first = [k for k in BEST_EPOCH_METRICS if k in stats]
1784
+ others = [k for k in stats if k not in first and k != "epoch"]
1785
+ console.metrics({k: stats[k] for k in first + others})
1786
+ for name, key in [("scores", "scores_file"), ("model", "model_path")]:
1787
+ if stats.get(key):
1788
+ log(f"{console.style(name.ljust(7), 'dim')} {stats[key]}")