pidsmaker 4.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.

Potentially problematic release.


This version of pidsmaker might be problematic. Click here for more details.

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