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,445 @@
1
+ import csv
2
+ import os.path
3
+ from collections import defaultdict
4
+
5
+ from pidsmaker.utils.utils import datetime_to_ns_time_US, init_database_connection, log
6
+ from pidsmaker.utils.dataset_utils import get_schema, get_uuid_to_index_id, get_time_and_end_node
7
+
8
+
9
+ def has_event_labels(cfg):
10
+ """Whether the dataset labels its events in the database (see `DatasetSchema.label_column`).
11
+
12
+ These datasets (e.g. network datasets like LANL) have event-level ground truth: the
13
+ malicious nodes are the endpoints of malicious events, and attacks are the groups of
14
+ malicious events in the time windows of `attack_to_time_window`.
15
+ """
16
+ return get_schema(cfg).label_column is not None
17
+
18
+
19
+ # Last result of `get_malicious_events` (read many times per evaluation)
20
+ _MALICIOUS_EVENTS_CACHE = {}
21
+
22
+
23
+ def get_malicious_events(cfg):
24
+ """[(src_index_id, dst_index_id, timestamp, edge type)] of the events labelled malicious,
25
+ sorted by time. The edge type is the one of the graphs (see `construction.edge_type`)."""
26
+ schema = get_schema(cfg)
27
+ database = (
28
+ cfg.dataset.database_all_file if cfg.construction.use_all_files else cfg.dataset.database
29
+ )
30
+ key = (cfg.dataset.name, database, schema.name, schema.edge_type_attribute, schema.operations_sql())
31
+ if key not in _MALICIOUS_EVENTS_CACHE:
32
+ if schema.edge_type_attribute:
33
+ attr = schema.edge_attribute(schema.edge_type_attribute)
34
+ type_col, encode = attr.column, attr.encode
35
+ else:
36
+ type_col, encode = "operation", (lambda v: v)
37
+ cur, connect = init_database_connection(cfg)
38
+ try:
39
+ cur.execute(
40
+ f"SELECT src_index_id, dst_index_id, timestamp_rec, {type_col} "
41
+ f"FROM {schema.event_table} WHERE {schema.label_column} = 1{schema.operations_sql()};"
42
+ )
43
+ rows = cur.fetchall()
44
+ finally:
45
+ connect.close()
46
+ _MALICIOUS_EVENTS_CACHE.clear()
47
+ _MALICIOUS_EVENTS_CACHE[key] = [
48
+ (int(src), int(dst), int(t), encode(etype)) for src, dst, t, etype in rows
49
+ ]
50
+ return _MALICIOUS_EVENTS_CACHE[key]
51
+
52
+
53
+ def _malicious_events_of_attack(cfg, start, end):
54
+ return [e for e in get_malicious_events(cfg) if start <= e[2] <= end]
55
+
56
+
57
+ def is_threatrace(cfg):
58
+ """True when the ThreaTrace ground truth is selected."""
59
+ return cfg.evaluation.ground_truth_version == "threatrace"
60
+
61
+
62
+ def _threatrace_gt_file(cfg):
63
+ """ThreaTrace ships one flat UUID list per dataset. Reuse the dataset's
64
+ ground-truth subfolder (e.g. 'E3-CADETS') from its configured paths."""
65
+ paths = cfg.dataset.ground_truth_relative_path
66
+ if not paths:
67
+ raise ValueError(
68
+ "ThreaTrace ground truth needs the dataset's GT subfolder, but "
69
+ "`ground_truth_relative_path` is empty for this dataset."
70
+ )
71
+ return os.path.join(paths[0].split("/")[0], "ground_truth.txt")
72
+
73
+
74
+ def ensure_ground_truth_available(cfg):
75
+ """Fail fast with a clear message when the selected ground truth has no file for
76
+ this dataset. ThreaTrace only covers CADETS, THEIA, TRACE, and FIVEDIRECTIONS (E3)."""
77
+ if has_event_labels(cfg):
78
+ return
79
+ if not is_threatrace(cfg):
80
+ missing = [
81
+ path
82
+ for path in cfg.dataset.ground_truth_relative_path
83
+ if not os.path.exists(os.path.join(cfg._ground_truth_dir, path))
84
+ ]
85
+ if missing:
86
+ raise FileNotFoundError(
87
+ f"Ground truth `{cfg.evaluation.ground_truth_version}` not found for dataset "
88
+ f"'{cfg.dataset.name}': missing {missing} in {cfg._ground_truth_dir}. "
89
+ "Use another `evaluation.ground_truth_version`."
90
+ )
91
+ return
92
+ paths = cfg.dataset.ground_truth_relative_path
93
+ subdir = paths[0].split("/")[0] if paths else None
94
+ gt_path = os.path.join(cfg._ground_truth_dir, subdir, "ground_truth.txt") if subdir else None
95
+ if not gt_path or not os.path.exists(gt_path):
96
+ raise FileNotFoundError(
97
+ f"ThreaTrace ground truth not found for dataset '{cfg.dataset.name}'. "
98
+ f"ThreaTrace provides ground truth only for CADETS, THEIA, TRACE, and "
99
+ f"FIVEDIRECTIONS (E3)."
100
+ )
101
+
102
+
103
+ def _test_period_ns(cfg):
104
+ """(start, end) of the dataset's test period in ns — the single combined
105
+ window used for the flat ThreaTrace ground truth."""
106
+ dates = sorted(cfg.dataset.test_dates)
107
+ return (
108
+ datetime_to_ns_time_US(dates[0] + " 00:00:00", timezone=cfg.dataset.timezone),
109
+ datetime_to_ns_time_US(dates[-1] + " 23:59:59", timezone=cfg.dataset.timezone),
110
+ )
111
+
112
+
113
+ def ground_truth_files(cfg):
114
+ """GT file relative paths for the active version: one flat file for
115
+ ThreaTrace, the per-attack files otherwise."""
116
+ if is_threatrace(cfg):
117
+ return [_threatrace_gt_file(cfg)]
118
+ return list(cfg.dataset.ground_truth_relative_path)
119
+
120
+
121
+ def ground_truth_attacks(cfg):
122
+ """(relative_path, start_ns, end_ns) per attack. ThreaTrace collapses to a
123
+ single combined window over the dataset's test period."""
124
+ if is_threatrace(cfg) or (has_event_labels(cfg) and not cfg.dataset.attack_to_time_window):
125
+ start, end = _test_period_ns(cfg)
126
+ name = "all_attacks" if has_event_labels(cfg) else _threatrace_gt_file(cfg)
127
+ return [(name, start, end)]
128
+ return [
129
+ (a[0], datetime_to_ns_time_US(a[1], timezone=cfg.dataset.timezone), datetime_to_ns_time_US(a[2], timezone=cfg.dataset.timezone))
130
+ for a in cfg.dataset.attack_to_time_window
131
+ ]
132
+
133
+
134
+ def read_ground_truth_uuids(cfg, relative_path):
135
+ """Yield (uuid, label) from a GT file, handling both the 3-column
136
+ orthrus/reapr CSV and the UUID-only ThreaTrace txt."""
137
+ with open(os.path.join(cfg._ground_truth_dir, relative_path), "r") as f:
138
+ for row in csv.reader(f):
139
+ if not row or not row[0].strip():
140
+ continue
141
+ yield row[0].strip(), (row[1] if len(row) > 1 else "threatrace")
142
+
143
+
144
+ def _mimicry_nodes(cfg, relative_path, uuid2nids):
145
+ """Node ids injected by the mimicry attack generator for one ground-truth file.
146
+ Only applies to the per-attack (orthrus/reapr) ground truth."""
147
+ nodes = {}
148
+ path = os.path.join(cfg.construction._mimicry_dir, relative_path.split("/")[-1])
149
+ with open(path, "r") as f:
150
+ for row in csv.reader(f):
151
+ node_id = uuid2nids.get(row[0])
152
+ if node_id is not None:
153
+ nodes[int(node_id)] = row[1] if len(row) > 1 else ""
154
+ return nodes
155
+
156
+
157
+ def _get_ground_truth_from_event_labels(cfg):
158
+ """Malicious nodes: the endpoints of malicious events, labelled by their attack."""
159
+ _, nid2uuid = get_uuid_to_index_id(cfg)
160
+ ground_truth_paths, uuid_to_node_id = {}, {}
161
+ for name, start, end in ground_truth_attacks(cfg):
162
+ for src, dst, _t, _etype in _malicious_events_of_attack(cfg, start, end):
163
+ for nid in (src, dst):
164
+ ground_truth_paths.setdefault(nid, name)
165
+ uuid_to_node_id[nid2uuid[nid]] = str(nid)
166
+ return set(ground_truth_paths), ground_truth_paths, uuid_to_node_id
167
+
168
+
169
+ def get_ground_truth(cfg):
170
+ if has_event_labels(cfg):
171
+ return _get_ground_truth_from_event_labels(cfg)
172
+ uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
173
+
174
+ ground_truth_nids, ground_truth_paths = [], {}
175
+ uuid_to_node_id = {}
176
+ missing = 0
177
+ for file in ground_truth_files(cfg):
178
+ for node_uuid, node_labels in read_ground_truth_uuids(cfg, file):
179
+ node_id = uuid2nids.get(node_uuid)
180
+ if node_id is None:
181
+ missing += 1
182
+ continue
183
+ ground_truth_nids.append(int(node_id))
184
+ ground_truth_paths[int(node_id)] = node_labels
185
+ uuid_to_node_id[node_uuid] = str(node_id)
186
+ if missing:
187
+ log(f"{missing} ground-truth UUIDs not present in the graph (skipped)")
188
+
189
+ mimicry_edge_num = cfg.construction.mimicry_edge_num
190
+ if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
191
+ num_before = len(ground_truth_nids)
192
+ for file in cfg.dataset.ground_truth_relative_path:
193
+ for node_id, labels in _mimicry_nodes(cfg, file, uuid2nids).items():
194
+ ground_truth_nids.append(node_id)
195
+ ground_truth_paths[node_id] = labels
196
+ log(f"{len(ground_truth_nids) - num_before} mimicry ground truth nodes loaded")
197
+
198
+ return set(ground_truth_nids), ground_truth_paths, uuid_to_node_id
199
+
200
+
201
+ def get_GP_of_each_attack(cfg):
202
+ if has_event_labels(cfg):
203
+ return {
204
+ i: {
205
+ "nids": {n for e in _malicious_events_of_attack(cfg, start, end) for n in e[:2]},
206
+ "time_range": [start, end],
207
+ }
208
+ for i, (_name, start, end) in enumerate(ground_truth_attacks(cfg))
209
+ }
210
+ uuid2nids, _ = get_uuid_to_index_id(cfg)
211
+
212
+ attack_to_nids = {}
213
+ for i, (path, start, end) in enumerate(ground_truth_attacks(cfg)):
214
+ nids = set()
215
+ for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
216
+ node_id = uuid2nids.get(node_uuid)
217
+ if node_id is not None:
218
+ nids.add(int(node_id))
219
+
220
+ mimicry_edge_num = cfg.construction.mimicry_edge_num
221
+ if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
222
+ mimicry = _mimicry_nodes(cfg, path, uuid2nids)
223
+ nids |= set(mimicry.keys())
224
+ log(f"{len(mimicry)} mimicry ground truth nodes loaded")
225
+
226
+ attack_to_nids[i] = {"nids": nids, "time_range": [start, end]}
227
+ return attack_to_nids
228
+
229
+ def get_t2malicious_node(cfg) -> dict[list]:
230
+ """Map event timestamps to malicious node UUIDs.
231
+
232
+ When edge-level ground truth CSVs are available, only events
233
+ matching explicit attack edges are considered malicious. Otherwise falls back
234
+ to the DARPA TC approach: any event touching a GT node within the attack
235
+ window is malicious.
236
+ """
237
+ if has_event_labels(cfg):
238
+ _, nid2uuid = get_uuid_to_index_id(cfg)
239
+ t_to_node = defaultdict(list)
240
+ for src, dst, t, _etype in get_malicious_events(cfg):
241
+ t_to_node[t].extend([nid2uuid[src], nid2uuid[dst]])
242
+ return t_to_node
243
+ if _has_edge_csvs(cfg):
244
+ return _get_t2malicious_node_from_edge_gt(cfg)
245
+ return _get_t2malicious_node_from_node_gt(cfg)
246
+
247
+
248
+ def _get_t2malicious_node_from_edge_gt(cfg) -> dict[list]:
249
+ """Use explicit edge-level ground truth to find malicious events.
250
+
251
+ For each attack edge (src, dst, event_type), query the DB for matching events
252
+ and record the timestamp -> node mapping.
253
+ """
254
+ cur, connect = init_database_connection(cfg)
255
+ uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
256
+
257
+ t_to_node = defaultdict(list)
258
+
259
+ edge_paths = cfg.dataset.ground_truth_edges_relative_path
260
+ for path in edge_paths:
261
+ filepath = os.path.join(cfg._ground_truth_dir, path)
262
+ if not os.path.exists(filepath):
263
+ continue
264
+
265
+ # Collect all attack edges: (src_nid, dst_nid, event_type)
266
+ attack_edges = set()
267
+ with open(filepath, "r") as f:
268
+ reader = csv.DictReader(f)
269
+ for row in reader:
270
+ src_nid = uuid2nids.get(row["src_node_uuid"])
271
+ dst_nid = uuid2nids.get(row["dst_node_uuid"])
272
+ if src_nid is not None and dst_nid is not None:
273
+ attack_edges.add((str(src_nid), str(dst_nid), row["event_type"]))
274
+
275
+ if not attack_edges:
276
+ continue
277
+
278
+ # Query events for each attack edge
279
+ for src_nid, dst_nid, event_type in attack_edges:
280
+ sql = (
281
+ "SELECT src_index_id, dst_index_id, timestamp_rec "
282
+ "FROM event_table "
283
+ "WHERE src_index_id = %s AND dst_index_id = %s AND operation = %s;"
284
+ )
285
+ cur.execute(sql, (src_nid, dst_nid, event_type))
286
+ for row in cur.fetchall():
287
+ t = int(row[2])
288
+ t_to_node[t].append(nid2uuid[int(row[0])])
289
+ t_to_node[t].append(nid2uuid[int(row[1])])
290
+
291
+ log(f"Edge GT: found {len(t_to_node)} event timestamps with malicious activity")
292
+ return t_to_node
293
+
294
+
295
+ def _get_t2malicious_node_from_node_gt(cfg) -> dict[list]:
296
+ """Original DARPA TC approach: any event touching a GT node in the attack window."""
297
+ cur, connect = init_database_connection(cfg)
298
+ uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
299
+
300
+ t_to_node = defaultdict(list)
301
+
302
+ for path, start_time, end_time in ground_truth_attacks(cfg):
303
+ ground_truth_nids = set()
304
+ for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
305
+ node_id = uuid2nids.get(node_uuid)
306
+ if node_id is not None:
307
+ ground_truth_nids.add(str(node_id))
308
+
309
+ mimicry_edge_num = cfg.construction.mimicry_edge_num
310
+ if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
311
+ mimicry = _mimicry_nodes(cfg, path, uuid2nids)
312
+ ground_truth_nids |= {str(n) for n in mimicry}
313
+ log(f"{len(mimicry)} mimicry nodes loaded")
314
+
315
+ rows = get_time_and_end_node(cfg, start_time, end_time)
316
+ for row in rows:
317
+ src_id = str(row[0])
318
+ dst_id = str(row[1])
319
+ t = row[2]
320
+ if src_id in ground_truth_nids:
321
+ t_to_node[int(t)].append(nid2uuid[int(src_id)])
322
+ if dst_id in ground_truth_nids:
323
+ t_to_node[int(t)].append(nid2uuid[int(dst_id)])
324
+
325
+ log(f"Node GT: found {len(t_to_node)} event timestamps with malicious activity")
326
+ return t_to_node
327
+
328
+
329
+ def _has_edge_csvs(cfg):
330
+ """Check if explicit edge-level ground truth CSVs are configured."""
331
+ paths = getattr(cfg.dataset, "ground_truth_edges_relative_path", None)
332
+ return paths is not None and len(paths) > 0
333
+
334
+
335
+ def get_attack_to_mal_edges(cfg) -> dict[set]:
336
+ """Load per-attack malicious edges.
337
+
338
+ If ground_truth_edges_relative_path is configured,
339
+ loads explicit attack edges from CSV files.
340
+ Otherwise falls back to the DB-query approach (DARPA TC datasets).
341
+ """
342
+ if has_event_labels(cfg):
343
+ return {
344
+ i: {
345
+ (str(src), str(dst), t, etype)
346
+ for src, dst, t, etype in _malicious_events_of_attack(cfg, start, end)
347
+ }
348
+ for i, (_name, start, end) in enumerate(ground_truth_attacks(cfg))
349
+ }
350
+ if _has_edge_csvs(cfg):
351
+ return _get_attack_to_mal_edges_from_csv(cfg)
352
+ return _get_attack_to_mal_edges_from_db(cfg)
353
+
354
+
355
+ def _get_attack_to_mal_edges_from_csv(cfg) -> dict[set]:
356
+ """Load malicious edges from explicit CSV files.
357
+
358
+ CSV format: src_node_uuid,dst_node_uuid,event_type,attack_edge_type
359
+ Edges are matched by (src_index_id, dst_index_id, event_type) — no timestamp needed.
360
+ """
361
+ uuid2nids, _ = get_uuid_to_index_id(cfg)
362
+
363
+ attack_to_mal_edges = defaultdict(set)
364
+ edge_paths = cfg.dataset.ground_truth_edges_relative_path
365
+
366
+ for i, path in enumerate(edge_paths):
367
+ filepath = os.path.join(cfg._ground_truth_dir, path)
368
+ if not os.path.exists(filepath):
369
+ log(f"Warning: edge ground truth file not found: {filepath}")
370
+ continue
371
+ with open(filepath, "r") as f:
372
+ reader = csv.DictReader(f)
373
+ for row in reader:
374
+ src_uuid = row["src_node_uuid"]
375
+ dst_uuid = row["dst_node_uuid"]
376
+ event_type = row["event_type"]
377
+
378
+ src_nid = uuid2nids.get(src_uuid)
379
+ dst_nid = uuid2nids.get(dst_uuid)
380
+ if src_nid is None or dst_nid is None:
381
+ continue
382
+
383
+ # Store as (src_index_id, dst_index_id, event_type) — no timestamp
384
+ attack_to_mal_edges[i].add((str(src_nid), str(dst_nid), event_type))
385
+
386
+ total = sum(len(s) for s in attack_to_mal_edges.values())
387
+ log(f"Loaded {total} malicious edges from {len(edge_paths)} CSV files")
388
+ return attack_to_mal_edges
389
+
390
+
391
+ def _get_attack_to_mal_edges_from_db(cfg) -> dict[set]:
392
+ """Original DB-query approach: find all events involving GT nodes during attack windows."""
393
+ cur, connect = init_database_connection(cfg)
394
+ uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
395
+
396
+ malicious_edge_selection = cfg.evaluation.edge_evaluation.malicious_edge_selection
397
+
398
+ attack_to_mal_edges = defaultdict(set)
399
+ for i, (path, start_time, end_time) in enumerate(ground_truth_attacks(cfg)):
400
+ ground_truth_nids = set()
401
+ for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
402
+ node_id = uuid2nids.get(node_uuid)
403
+ if node_id is not None:
404
+ ground_truth_nids.add(str(node_id))
405
+
406
+ rows = get_time_and_end_node(cfg, start_time, end_time)
407
+ for row in rows:
408
+ src_idx_id = str(row[0])
409
+ dst_idx_id = str(row[1])
410
+ timestamp_rec = row[2]
411
+ ope = row[3]
412
+
413
+ condition = None
414
+ if malicious_edge_selection == "src_node":
415
+ condition = src_idx_id in ground_truth_nids
416
+ elif malicious_edge_selection == "dst_node":
417
+ condition = dst_idx_id in ground_truth_nids
418
+ elif malicious_edge_selection == "both_nodes":
419
+ condition = src_idx_id in ground_truth_nids and dst_idx_id in ground_truth_nids
420
+ elif malicious_edge_selection == "either_node":
421
+ condition = src_idx_id in ground_truth_nids or dst_idx_id in ground_truth_nids
422
+ else:
423
+ raise ValueError(
424
+ "`malicious_edge_selection` must be one of 'src_node', 'dst_node', 'both_nodes', 'either_node"
425
+ )
426
+
427
+ if condition:
428
+ attack_to_mal_edges[i].add((src_idx_id, dst_idx_id, timestamp_rec, ope))
429
+
430
+ return attack_to_mal_edges
431
+
432
+
433
+ def get_ground_truth_edges(cfg) -> set:
434
+ """Return the set of all malicious edges across all attacks.
435
+
436
+ When using CSV-based edge labels, edges are (src_nid, dst_nid, event_type) tuples.
437
+ When using DB-based labels, edges are (src_nid, dst_nid, timestamp, event_type) tuples.
438
+ """
439
+ attack_to_mal_edges = get_attack_to_mal_edges(cfg)
440
+
441
+ malicious_edges = set()
442
+ for attack, edges_set in attack_to_mal_edges.items():
443
+ malicious_edges |= edges_set
444
+
445
+ return malicious_edges
@@ -0,0 +1,193 @@
1
+ """Storage of the per-epoch inference outputs (edge/node losses per time window).
2
+
3
+ Inference writes one file per batch/time window in
4
+ ``{edge_losses_dir}/{split}/model_epoch_{i}/{start}~{end}{ext}``, for every epoch.
5
+ These used to be CSV files, which made them the largest output of a run after the
6
+ edge features. They are now stored as compressed `.npz` archives of typed columns
7
+ (about 9x smaller than the CSVs):
8
+
9
+ - float64 columns holding float32 values (e.g. losses computed in float32) are stored
10
+ as float32, other floats as float64;
11
+ - integer columns are stored as int32 when the values fit, int64 otherwise.
12
+
13
+ `read_losses` always returns float64/int64 columns, i.e. the same DataFrame as
14
+ `pd.read_csv` on the former CSV files, so downstream code is unchanged. Legacy CSV
15
+ files remain readable.
16
+ """
17
+
18
+ import os
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ LOSS_EXT = ".npz"
24
+ _LEGACY_EXT = ".csv"
25
+ _EXTS = (LOSS_EXT, _LEGACY_EXT)
26
+
27
+ _I32 = np.iinfo(np.int32)
28
+
29
+
30
+ def _compact_column(values):
31
+ a = np.asarray(values)
32
+ if a.dtype == np.bool_:
33
+ return a.astype(np.int8)
34
+ if np.issubdtype(a.dtype, np.floating):
35
+ if a.dtype == np.float64:
36
+ a32 = a.astype(np.float32)
37
+ # Only downcast when lossless (NaNs compare unequal, hence equal_nan)
38
+ if np.array_equal(a32.astype(np.float64), a, equal_nan=True):
39
+ return a32
40
+ return a
41
+ if np.issubdtype(a.dtype, np.integer):
42
+ if a.size == 0 or (a.min() >= _I32.min and a.max() <= _I32.max):
43
+ return a.astype(np.int32)
44
+ return a.astype(np.int64)
45
+ raise TypeError(f"Unsupported column dtype {a.dtype} in loss file")
46
+
47
+
48
+ def _expand_column(a):
49
+ if np.issubdtype(a.dtype, np.floating):
50
+ return a.astype(np.float64, copy=False)
51
+ if np.issubdtype(a.dtype, np.integer):
52
+ return a.astype(np.int64, copy=False)
53
+ return a
54
+
55
+
56
+ def write_losses(out_dir, name, columns):
57
+ """Writes the columns (dict name -> 1D array, or a DataFrame) of one loss file.
58
+
59
+ Returns the written path.
60
+ """
61
+ if isinstance(columns, pd.DataFrame):
62
+ columns = {c: columns[c].to_numpy() for c in columns.columns}
63
+ path = os.path.join(out_dir, name + LOSS_EXT)
64
+ # A CSV of the same window left by a previous run with the former format would be
65
+ # read in addition to this file
66
+ legacy = os.path.join(out_dir, name + _LEGACY_EXT)
67
+ if os.path.exists(legacy):
68
+ os.remove(legacy)
69
+ np.savez_compressed(path, **{k: _compact_column(v) for k, v in columns.items()})
70
+ return path
71
+
72
+
73
+ def read_losses(path, usecols=None):
74
+ """Reads one loss file (.npz or legacy .csv) as a DataFrame of float64/int64 columns."""
75
+ if path.endswith(_LEGACY_EXT):
76
+ return pd.read_csv(path, usecols=usecols)
77
+ with np.load(path) as f:
78
+ names = f.files if usecols is None else [c for c in f.files if c in usecols]
79
+ missing = set(usecols or ()) - set(f.files)
80
+ if missing:
81
+ raise ValueError(f"Columns {sorted(missing)} not found in {path}")
82
+ return pd.DataFrame({c: _expand_column(f[c]) for c in names})
83
+
84
+
85
+ def is_loss_file(fname):
86
+ return fname.endswith(_EXTS)
87
+
88
+
89
+ def strip_loss_ext(fname):
90
+ """Returns the time window name ("start~end") of a loss file name."""
91
+ for ext in _EXTS:
92
+ if fname.endswith(ext):
93
+ return fname[: -len(ext)]
94
+ return fname
95
+
96
+
97
+ def compact_int_columns(df):
98
+ """Losslessly stores the int64 columns of a DataFrame as int32 when the values fit.
99
+
100
+ Used for the per-epoch `edge_scores_*.pkl` files, whose node IDs, types, time
101
+ window indices and labels all fit in 32 bits.
102
+ """
103
+ df = df.copy(deep=False)
104
+ for c in df.columns:
105
+ if df[c].dtype == np.int64 and len(df) > 0:
106
+ if df[c].min() >= _I32.min and df[c].max() <= _I32.max:
107
+ df[c] = df[c].astype(np.int32)
108
+ return df
109
+
110
+
111
+ _EPOCH_FILE_PREFIXES = ("edge_scores_", "result_", "scores_")
112
+
113
+
114
+ def _epochs_to_keep(cfg, metrics):
115
+ keep = set()
116
+ if not metrics or metrics.get("epoch") is None:
117
+ return keep # the evaluation's best epoch is unknown (e.g. cached): nothing is pruned
118
+ keep.add(f"model_epoch_{int(metrics['epoch'])}")
119
+
120
+ # Triage selects its own best epoch (highest MCC) from the per-epoch stats
121
+ import torch
122
+
123
+ pr_dir = cfg.evaluation._precision_recall_dir
124
+ best_mcc = None
125
+ if os.path.isdir(pr_dir):
126
+ for f in os.listdir(pr_dir):
127
+ if f.startswith("stats_model_epoch_") and f.endswith(".pth"):
128
+ stats = torch.load(os.path.join(pr_dir, f), weights_only=False)
129
+ mcc = stats.get("mcc") if isinstance(stats, dict) else None
130
+ if mcc is not None and (best_mcc is None or mcc > best_mcc[0]):
131
+ best_mcc = (mcc, f[len("stats_") : -len(".pth")])
132
+ if best_mcc is not None:
133
+ keep.add(best_mcc[1])
134
+ return keep
135
+
136
+
137
+ def prune_non_best_epochs(cfg, metrics):
138
+ """Deletes the large per-epoch outputs of all epochs except the best one(s).
139
+
140
+ Kept for every epoch: stats and plots. Deleted for the other epochs: the loss
141
+ files of all splits, the evaluation pickles (edge_scores_, result_, scores_) and
142
+ the saved model weights. The best epoch is the one selected by the evaluation,
143
+ plus the one selected by triage (best MCC) when it differs.
144
+
145
+ Re-running evaluation with another config afterwards only considers the kept epochs.
146
+ """
147
+ import shutil
148
+
149
+ from pidsmaker.utils.utils import log
150
+
151
+ keep = _epochs_to_keep(cfg, metrics)
152
+ if not keep:
153
+ log("Epoch pruning skipped: the best epoch is unknown.")
154
+ return
155
+
156
+ freed = 0
157
+
158
+ def _rm(path):
159
+ nonlocal freed
160
+ if os.path.isdir(path):
161
+ for root, _, files in os.walk(path):
162
+ freed += sum(os.path.getsize(os.path.join(root, f)) for f in files)
163
+ shutil.rmtree(path)
164
+ elif os.path.isfile(path):
165
+ freed += os.path.getsize(path)
166
+ os.remove(path)
167
+
168
+ losses_dir = cfg.training._edge_losses_dir
169
+ if os.path.isdir(losses_dir):
170
+ for split in os.listdir(losses_dir):
171
+ split_dir = os.path.join(losses_dir, split)
172
+ if not os.path.isdir(split_dir):
173
+ continue
174
+ for epoch_dir in os.listdir(split_dir):
175
+ if epoch_dir.startswith("model_epoch_") and epoch_dir not in keep:
176
+ _rm(os.path.join(split_dir, epoch_dir))
177
+
178
+ models_dir = getattr(cfg.training, "_trained_models_dir", None)
179
+ if models_dir and os.path.isdir(models_dir):
180
+ for f in os.listdir(models_dir):
181
+ if f.startswith("model_epoch_") and f not in keep:
182
+ _rm(os.path.join(models_dir, f))
183
+
184
+ pr_dir = cfg.evaluation._precision_recall_dir
185
+ if os.path.isdir(pr_dir):
186
+ for f in os.listdir(pr_dir):
187
+ for prefix in _EPOCH_FILE_PREFIXES:
188
+ if f.startswith(prefix + "model_epoch_") and not f.endswith((".png", ".svg")):
189
+ epoch = os.path.splitext(f[len(prefix) :])[0]
190
+ if epoch not in keep:
191
+ _rm(os.path.join(pr_dir, f))
192
+
193
+ log(f"Pruned per-epoch outputs except {sorted(keep)}: freed {freed / 1e9:.2f} GB")
@@ -0,0 +1,44 @@
1
+ """Process tags of R-Caid (Goyal et al., IEEE S&P 2024, Section 4.3).
2
+
3
+ R-Caid annotates each process with a tag, "the process name" extracted from "the file path to
4
+ its binary executable", and trains its GNN to predict it. So that the tag does not appear in the
5
+ node features, the process name is truncated from the path of the process before computing its
6
+ features.
7
+
8
+ Process labels are made of the attributes of `construction.node_label_features.subject`
9
+ joined by spaces, starting with the path of the executable (e.g. `path, cmd_line`):
10
+ `/bin/dash /bin/sh -e script` (THEIA) or `None sleep` (CADETS, whose processes have no path).
11
+ """
12
+
13
+ import os
14
+
15
+ _NULL = ("", "None", "none", "null")
16
+
17
+
18
+ def _path_and_rest(label):
19
+ label = (label or "").strip()
20
+ if not label:
21
+ return "", ""
22
+ path, _, rest = label.partition(" ")
23
+ return path, rest.strip()
24
+
25
+
26
+ def process_tag(label):
27
+ """Name of the executable of a process: the basename of its path, or, without path, of the
28
+ first word of the rest of its label (e.g. its command line)."""
29
+ path, rest = _path_and_rest(label)
30
+ if path in _NULL:
31
+ path = rest.split(" ")[0] if rest else ""
32
+ if path in _NULL:
33
+ return ""
34
+ return os.path.basename(path.replace("\\", "/").rstrip("/")) or path
35
+
36
+
37
+ def truncate_process_name(label):
38
+ """Features label of a process: the directory of its executable, without its name nor the
39
+ rest of its label (which usually repeats the name, e.g. in the command line)."""
40
+ path, _ = _path_and_rest(label)
41
+ if path in _NULL:
42
+ return ""
43
+ path = path.replace("\\", "/").rstrip("/")
44
+ return path.rsplit("/", 1)[0] + "/" if "/" in path else ""