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,825 @@
1
+ """Default graph construction from the events of a dataset.
2
+
3
+ Builds the graphs of a dataset (provenance or network events, see `pidsmaker/utils/database.py`).
4
+ Creates time-windowed graph snapshots with node features, edge types, and timestamps.
5
+ Supports attack mimicry generation for data augmentation.
6
+ """
7
+
8
+ import gc
9
+ import multiprocessing
10
+ import os
11
+ import queue
12
+ import re
13
+ import sys
14
+ import threading
15
+ from collections import Counter, defaultdict
16
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
17
+ from datetime import datetime, timedelta
18
+
19
+ import torch
20
+
21
+ import pidsmaker.mimicry as mimicry
22
+ from pidsmaker.config import get_dates_from_cfg, get_node_feats_from_cfg
23
+ from pidsmaker.config.schemas import benign_training
24
+ from pidsmaker.preprocessing.cleaning import Cleaner
25
+ from pidsmaker.utils.graph_store import save_edge_list
26
+ from pidsmaker.utils.dataset_utils import get_schema, iter_nodes
27
+ from pidsmaker.utils.utils import (
28
+ datetime_to_ns_time_US,
29
+ get_split_to_files,
30
+ init_database_connection,
31
+ log,
32
+ log_tqdm,
33
+ ns_time_to_datetime_US,
34
+ stringtomd5,
35
+ )
36
+
37
+
38
+ _cursor_id = 0
39
+
40
+
41
+ def _next_cursor_name():
42
+ global _cursor_id
43
+ _cursor_id += 1
44
+ return f"pids_cur_{_cursor_id}"
45
+
46
+
47
+ # Rows keep the shape of `select *` (src_node, src_index_id, operation, dst_node,
48
+ # dst_index_id, event_uuid, timestamp_rec, _id), but the columns that construction does
49
+ # not use are not transferred (NULL): fetching rows dominates the query time.
50
+ # The columns of the schema's edge attributes, then its label column, follow (see `events_sql`).
51
+ EVENT_TIME_IDX = 6
52
+ EVENT_EXTRA_IDX = 8
53
+
54
+
55
+ def events_sql(schema):
56
+ """Query of the events of a time range, in their stored order: by `timestamp_rec,
57
+ event_uuid` (see the row shape above and `pidsmaker/utils/database.py`)."""
58
+ extra = [attr.column for attr in schema.edge_attributes]
59
+ if schema.label_column:
60
+ extra.append(schema.label_column)
61
+ extra_sql = "".join(f", {col}" for col in extra)
62
+ return f"""
63
+ select NULL, src_index_id, operation, NULL, dst_index_id, event_uuid, timestamp_rec, NULL{extra_sql}
64
+ from {schema.event_table}
65
+ where
66
+ timestamp_rec > %s and timestamp_rec < %s{schema.operations_sql()};
67
+ """
68
+
69
+
70
+ class DayQueryPrefetcher:
71
+ """Runs the daily event queries ahead of their processing.
72
+
73
+ Each day is queried through its own connection and server-side cursor in a
74
+ background thread, so that the database scans and sorts the next days while the
75
+ current day is turned into graphs (daily queries dominate construction time).
76
+
77
+ Memory stays bounded: each day buffers at most `queue_size` chunks of `fetch_size`
78
+ rows, and at most `num_workers` days are fetched at the same time. Chunks are the
79
+ exact `fetchmany` results (the last one being shorter than `fetch_size`).
80
+ """
81
+
82
+ def __init__(self, cfg, params_list, fetch_size, num_workers=4, queue_size=1):
83
+ self.fetch_size = fetch_size
84
+ self._stop = threading.Event()
85
+ self._abandoned = [threading.Event() for _ in params_list]
86
+ self._queues = [queue.Queue(maxsize=queue_size) for _ in params_list]
87
+ self._pool = ThreadPoolExecutor(max_workers=max(1, num_workers))
88
+ # Days are submitted in order, so they are fetched in processing order
89
+ for i, params in enumerate(params_list):
90
+ self._pool.submit(self._produce, cfg, params, i)
91
+
92
+ def _put(self, i, item):
93
+ while not (self._stop.is_set() or self._abandoned[i].is_set()):
94
+ try:
95
+ self._queues[i].put(item, timeout=0.5)
96
+ return True
97
+ except queue.Full:
98
+ continue
99
+ return False
100
+
101
+ def _produce(self, cfg, params, i):
102
+ if self._stop.is_set() or self._abandoned[i].is_set():
103
+ return
104
+ connect = None
105
+ try:
106
+ _, connect = init_database_connection(cfg)
107
+ with connect.cursor(_next_cursor_name()) as cur:
108
+ cur.execute(events_sql(get_schema(cfg)), params)
109
+ while True:
110
+ chunk = cur.fetchmany(self.fetch_size)
111
+ if not self._put(i, chunk) or len(chunk) < self.fetch_size:
112
+ break
113
+ except Exception as e: # re-raised in the consumer thread
114
+ self._put(i, e)
115
+ finally:
116
+ if connect is not None:
117
+ connect.close()
118
+
119
+ def chunks(self, i):
120
+ """Yields the row chunks of the i-th day, in order."""
121
+ while True:
122
+ item = self._queues[i].get()
123
+ if isinstance(item, Exception):
124
+ raise item
125
+ yield item
126
+ if len(item) < self.fetch_size:
127
+ return
128
+
129
+ def abandon(self, i):
130
+ """Stops fetching the i-th day (e.g. when its remaining rows are not needed)."""
131
+ self._abandoned[i].set()
132
+ self._drain(i)
133
+
134
+ def _drain(self, i):
135
+ try:
136
+ while True:
137
+ self._queues[i].get_nowait()
138
+ except queue.Empty:
139
+ pass
140
+
141
+ def close(self):
142
+ self._stop.set()
143
+ for i in range(len(self._queues)):
144
+ self._drain(i)
145
+ self._pool.shutdown(wait=True)
146
+
147
+
148
+ def compute_indexid2msg(cfg, cleaner=None):
149
+ """Compute mapping from node index IDs to node types and feature labels.
150
+
151
+ Reads all nodes of the dataset (the tables of its schema's node types) and builds the
152
+ label of each node from its attributes, based on `construction.node_label_features`.
153
+
154
+ Args:
155
+ cfg: Configuration with database connection and feature settings
156
+ cleaner: Optional `Cleaner` applied to node attributes and labels. Nodes it
157
+ removes (noisy netflows) are absent from the mapping, so their events are skipped.
158
+
159
+ Returns:
160
+ dict: Mapping {index_id: [node_type, label_string]} where:
161
+ - index_id: Database node identifier (str)
162
+ - node_type: Name of the node type in the dataset's schema
163
+ - label_string: Feature label (hashed or plaintext depending on config)
164
+ """
165
+ _, connect = init_database_connection(cfg)
166
+ if cleaner is None:
167
+ cleaner = Cleaner(cfg)
168
+
169
+ schema = get_schema(cfg)
170
+ use_hashed_label = cfg.construction.use_hashed_label
171
+ null_label_tokens = cfg.construction.null_label_tokens
172
+ node_label_features = get_node_feats_from_cfg(cfg)
173
+ indexid2msg = {}
174
+
175
+ def get_label_str_from_features(attrs, node_type):
176
+ """Feature label of a node from its attributes and the configured features."""
177
+ feats = node_label_features[node_type]
178
+ if feats == ["auto"]:
179
+ label_str = schema.node_type(node_type).auto_label_str(attrs, null_label_tokens)
180
+ elif cleaner:
181
+ # Null attributes were emptied by the cleaning: they are skipped
182
+ label_str = " ".join([attrs[label_used] for label_used in feats if attrs[label_used]])
183
+ else:
184
+ label_str = " ".join([attrs[label_used] for label_used in feats])
185
+
186
+ label_str = cleaner.normalize_label(label_str)
187
+ if use_hashed_label:
188
+ label_str = stringtomd5(label_str)
189
+ # Keep only printable ASCII — labels are paths, cmds, IPs, host names, ...
190
+ label_str = re.sub(r"[^\x20-\x7e]+", "", label_str).strip()
191
+ return label_str
192
+
193
+ # Nodes of the same type and label share the same [node_type, label] list (values are
194
+ # never modified). Many nodes share their label (e.g. TRACE_E3 has 39M processes but 355
195
+ # distinct paths), so this divides the memory of the mapping, and avoids that forked
196
+ # graph-building workers copy the pages of millions of lists whose refcount they change.
197
+ shared_msgs = defaultdict(dict) # {node_type: {label: [node_type, label]}}
198
+ counts = Counter()
199
+ for node_type, _uuid, _hash_id, index_id, attrs in iter_nodes(cfg, connect):
200
+ if "remote_ip" in attrs and cleaner.is_noisy_netflow(attrs):
201
+ continue
202
+ attrs = cleaner.clean_attributes(node_type, attrs)
203
+ label_str = get_label_str_from_features(attrs, node_type)
204
+ msgs = shared_msgs[node_type]
205
+ msg = msgs.get(label_str)
206
+ if msg is None:
207
+ msg = msgs[label_str] = [node_type, label_str]
208
+ indexid2msg[str(index_id)] = msg
209
+ counts[node_type] += 1
210
+ del shared_msgs
211
+
212
+ for node_type, count in counts.items():
213
+ log(f"Number of {node_type} nodes: {count}")
214
+ connect.close()
215
+
216
+ return indexid2msg # {index_id: [node_type, msg]}
217
+
218
+
219
+ def save_indexid2msg(indexid2msg, split2nodes, cfg):
220
+ """Save filtered node index-to-feature mapping to disk.
221
+
222
+ Filters out nodes not used in any train/val/test graphs (due to excluded edge types)
223
+ before saving to avoid downstream errors during featurization.
224
+
225
+ Note: Must be called after graph construction to ensure only used nodes are saved.
226
+
227
+ Args:
228
+ indexid2msg: Full node mapping from compute_indexid2msg()
229
+ split2nodes: Mapping of splits to their node sets
230
+ cfg: Configuration with output directory path
231
+ """
232
+ empty_splits = [split for split in ["train", "val", "test"] if not split2nodes.get(split)]
233
+ if empty_splits:
234
+ raise ValueError(
235
+ f"No graph was built for the {empty_splits} split(s) of {cfg.dataset.name}. "
236
+ "Check that the database contains events for the dates of these splits."
237
+ )
238
+ all_nodes = set().union(*(split2nodes[split] for split in ["train", "val", "test"]))
239
+ indexid2msg = {k: v for k, v in indexid2msg.items() if k in all_nodes}
240
+
241
+ out_dir = cfg.construction._dicts_dir
242
+ os.makedirs(out_dir, exist_ok=True)
243
+ log("Saving indexid2msg to disk...")
244
+ torch.save(indexid2msg, os.path.join(out_dir, "indexid2msg.pkl"))
245
+
246
+
247
+ def compute_and_save_split2nodes(cfg, file2nodes=None):
248
+ """Compute and save mapping of dataset splits to their node sets.
249
+
250
+ Loads all graphs from train/val/test splits and collects unique node IDs
251
+ appearing in each split. Used to filter node features and track split membership.
252
+
253
+ Args:
254
+ cfg: Configuration with graph directory and split file paths
255
+ file2nodes: Optional {normalized graph path: node set} recorded while building
256
+ the graphs. Graphs found there are not reloaded from disk. The set of a graph may
257
+ be a superset of its nodes shared by graphs of the same splits (e.g. the nodes
258
+ of its day).
259
+
260
+ Returns:
261
+ dict: Mapping of split names to node sets:
262
+ {'train': {node_ids}, 'val': {node_ids}, 'test': {node_ids}}
263
+ """
264
+ split_to_files = get_split_to_files(cfg, cfg.construction._graphs_dir)
265
+ split2nodes = defaultdict(set)
266
+ file2nodes = file2nodes or {}
267
+
268
+ for split, files in split_to_files.items():
269
+ merged = set() # ids of the node sets already merged (graphs may share a set)
270
+ for path in log_tqdm(files, desc=f"Check nodes in {split} set"):
271
+ nodes = file2nodes.get(os.path.normpath(path))
272
+ if nodes is None:
273
+ nodes = torch.load(path).nodes()
274
+ elif id(nodes) in merged:
275
+ continue
276
+ else:
277
+ merged.add(id(nodes))
278
+ split2nodes[split].update(nodes)
279
+ split2nodes = dict(split2nodes)
280
+
281
+ out_dir = cfg.construction._dicts_dir
282
+ os.makedirs(out_dir, exist_ok=True)
283
+ log("Saving split2nodes to disk...")
284
+ torch.save(split2nodes, os.path.join(out_dir, "split2nodes.pkl"))
285
+
286
+ return split2nodes
287
+
288
+
289
+ def gen_edge_fused_tw(indexid2msg, cfg, cleaner=None, file2nodes=None):
290
+ """Generate time-windowed provenance graphs from database events.
291
+
292
+ Main graph construction function that:
293
+ 1. Queries database for events in time windows
294
+ 2. Optionally fuses consecutive edges of same type between node pairs
295
+ 3. Optionally adds attack mimicry events for data augmentation
296
+ 4. Builds NetworkX MultiDiGraphs with node attributes and edge metadata
297
+ 5. Saves graphs to disk organized by day and time window
298
+
299
+ Args:
300
+ indexid2msg: Node index to [type, label] mapping from compute_indexid2msg()
301
+ cfg: Configuration with:
302
+ - Database connection settings
303
+ - Time window parameters (size, dates)
304
+ - Edge type filtering (rel2id)
305
+ - Mimicry settings (mimicry_edge_num)
306
+ - Output directory paths
307
+ cleaner: Optional `Cleaner` removing events (self-loops, duplicates, ...)
308
+ file2nodes: Optional dict filled with {normalized graph path: node set}, so that
309
+ the nodes of each split can be retrieved without reloading the graphs from disk.
310
+ All the graphs of a day share the set of the nodes of the day.
311
+ """
312
+ if cleaner is None:
313
+ cleaner = Cleaner(cfg)
314
+ schema = get_schema(cfg)
315
+ # DB rows carry raw edge type strings (e.g. "START", "MESSAGE" for OpTC), which are
316
+ # filtered against the raw vocabulary when the schema translates edge types.
317
+ include_edge_type = schema.event_filter_rel2id
318
+
319
+ mimicry_edge_num = cfg.construction.mimicry_edge_num
320
+ if mimicry_edge_num is not None and mimicry_edge_num > 0:
321
+ attack_mimicry_events = mimicry.gen_mimicry_edges(cfg)
322
+ else:
323
+ attack_mimicry_events = defaultdict(list)
324
+
325
+ # In test mode, we ensure to get 1 TW in each set
326
+ dates = get_dates_from_cfg(cfg)
327
+
328
+ # Timezone-aware timestamp conversion: UTC for datasets with timezone=UTC, else US/Eastern
329
+ _tz = getattr(cfg.dataset, "timezone", None)
330
+ if _tz and _tz.upper() == "UTC":
331
+ import pytz as _pytz
332
+ _utc = _pytz.utc
333
+ def _to_ns(date_str):
334
+ dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
335
+ dt = _utc.localize(dt)
336
+ return int(dt.timestamp() * 1_000_000_000)
337
+ else:
338
+ _to_ns = datetime_to_ns_time_US
339
+
340
+ use_cleaner = bool(cleaner)
341
+ # Fetch large DB chunks to minimise round-trips; no per-row generator
342
+ # overhead — events are processed directly from list slices.
343
+ FETCH_SIZE = 500_000
344
+ day_params = []
345
+ for date in dates:
346
+ date_start = f"{date} 00:00:00"
347
+ date_stop = f"{(datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')} 00:00:00"
348
+ day_params.append((_to_ns(date_start), _to_ns(date_stop)))
349
+ common = dict(
350
+ cfg=cfg,
351
+ day_params=day_params,
352
+ fetch_size=FETCH_SIZE,
353
+ indexid2msg=indexid2msg,
354
+ cleaner=cleaner,
355
+ use_cleaner=use_cleaner,
356
+ include_edge_type=include_edge_type,
357
+ attack_mimicry_events=attack_mimicry_events,
358
+ mimicry_edge_num=mimicry_edge_num,
359
+ _to_ns=_to_ns,
360
+ )
361
+ if file2nodes is None:
362
+ file2nodes = {}
363
+
364
+ num_workers = min(get_num_workers(cfg), len(dates))
365
+ # The same date may appear in several splits (e.g. PROVENANCE_BENIGN): it is then built
366
+ # several times as before, which parallel workers would do concurrently on the same files
367
+ if num_workers > 1 and _can_fork() and len(set(dates)) == len(dates):
368
+ log(f"Building graphs ({num_workers} processes)...")
369
+ _build_days_in_parallel(dates, common, num_workers, file2nodes)
370
+ else:
371
+ log("Building graphs...")
372
+ # Days are processed sequentially, while the next ones are queried in the background
373
+ prefetcher = DayQueryPrefetcher(cfg, day_params, FETCH_SIZE)
374
+ try:
375
+ for day_idx, date in enumerate(dates):
376
+ try:
377
+ _build_day(
378
+ day_idx=day_idx,
379
+ date=date,
380
+ day_chunks=prefetcher.chunks(day_idx),
381
+ file2nodes=file2nodes,
382
+ **common,
383
+ )
384
+ finally:
385
+ prefetcher.abandon(day_idx)
386
+ finally:
387
+ prefetcher.close()
388
+
389
+
390
+ def get_num_workers(cfg):
391
+ """Number of processes for CPU-bound preprocessing (`--num_workers`, default: up to 8)."""
392
+ num_workers = getattr(cfg, "_num_workers", None)
393
+ if num_workers is None:
394
+ num_workers = min(8, os.cpu_count() or 1)
395
+ return max(1, int(num_workers))
396
+
397
+
398
+ def _can_fork():
399
+ """Workers are forked to share the (large) read-only state without pickling it.
400
+
401
+ Forking after CUDA initialization is unsafe, in which case days are built sequentially.
402
+ """
403
+ if sys.platform == "win32" or "fork" not in multiprocessing.get_all_start_methods():
404
+ return False
405
+ try:
406
+ import torch.cuda
407
+
408
+ return not torch.cuda.is_initialized()
409
+ except Exception:
410
+ return False
411
+
412
+
413
+ # State shared with the forked workers of `_build_days_in_parallel` (inherited, not pickled)
414
+ _DAY_WORKER_STATE = None
415
+
416
+
417
+ def _iter_day_chunks(cfg, params, fetch_size):
418
+ """Yields the `fetchmany` chunks of the events query of a day, on a new connection."""
419
+ _, connect = init_database_connection(cfg)
420
+ try:
421
+ with connect.cursor(_next_cursor_name()) as cur:
422
+ cur.execute(events_sql(get_schema(cfg)), params)
423
+ while True:
424
+ chunk = cur.fetchmany(fetch_size)
425
+ yield chunk
426
+ if len(chunk) < fetch_size:
427
+ return
428
+ finally:
429
+ connect.close()
430
+
431
+
432
+ def _day_worker(day_idx, date):
433
+ common = _DAY_WORKER_STATE
434
+ # Only the per-day cleaning state is collected, then merged by the parent. Days are
435
+ # independent: their events never share a timestamp (bounds are exclusive).
436
+ cleaner = common["cleaner"]
437
+ cleaner.stats = Counter()
438
+ cleaner._seen_nodes = set()
439
+ cleaner._graph_nodes = set()
440
+ cleaner._last_timestamp = None
441
+ cleaner._events_at_timestamp = set()
442
+
443
+ file2nodes = {}
444
+ day_chunks = _iter_day_chunks(common["cfg"], common["day_params"][day_idx], common["fetch_size"])
445
+ try:
446
+ _build_day(day_idx=day_idx, date=date, day_chunks=day_chunks, file2nodes=file2nodes, **common)
447
+ finally:
448
+ day_chunks.close()
449
+ return file2nodes, cleaner.stats, cleaner._seen_nodes, cleaner._graph_nodes
450
+
451
+
452
+ def _build_days_in_parallel(dates, common, num_workers, file2nodes):
453
+ """Builds the graphs of each day in a separate process (results are identical)."""
454
+ global _DAY_WORKER_STATE
455
+ _DAY_WORKER_STATE = common
456
+ cleaner = common["cleaner"]
457
+ try:
458
+ ctx = multiprocessing.get_context("fork")
459
+ with ProcessPoolExecutor(max_workers=num_workers, mp_context=ctx) as pool:
460
+ futures = [pool.submit(_day_worker, i, date) for i, date in enumerate(dates)]
461
+ for future in futures: # merged in day order
462
+ day_file2nodes, stats, seen_nodes, graph_nodes = future.result()
463
+ file2nodes.update(day_file2nodes)
464
+ cleaner.stats.update(stats)
465
+ cleaner._seen_nodes |= seen_nodes
466
+ cleaner._graph_nodes |= graph_nodes
467
+ finally:
468
+ _DAY_WORKER_STATE = None
469
+
470
+
471
+ class _EncodedValues(dict):
472
+ """{database value: `attr.encode(value)`}, filled on first access (few distinct values)."""
473
+
474
+ def __init__(self, attr):
475
+ super().__init__()
476
+ self.attr = attr
477
+
478
+ def __missing__(self, value):
479
+ encoded = self[value] = self.attr.encode(value)
480
+ return encoded
481
+
482
+
483
+ def _attributes_encoder(edge_attributes):
484
+ """Function of the extra columns of an event row returning the tuple of the encoded values
485
+ of `edge_attributes` (the first columns), as `tuple(attr.encode(v) for ...)`."""
486
+ encoders = [attr.encode for attr in edge_attributes]
487
+ # Categorical attributes have few distinct values: their encodings are memoized
488
+ getters = [
489
+ _EncodedValues(attr).__getitem__ if attr.kind == "categorical" else attr.encode
490
+ for attr in edge_attributes
491
+ ]
492
+
493
+ def encode_slow(extra):
494
+ return tuple(encode(v) for encode, v in zip(encoders, extra))
495
+
496
+ def encode_fast(extra):
497
+ # One dict lookup per value instead of a call to `encode`
498
+ return tuple([get(v) for get, v in zip(getters, extra)])
499
+
500
+ def encode(extra):
501
+ try:
502
+ return encode_fast(extra)
503
+ except TypeError: # unhashable values
504
+ return encode_slow(extra)
505
+
506
+ return encode
507
+
508
+
509
+ def _save_window_graph(path, node_info, edge_list, edge_attr_names):
510
+ """Saves the graph of a time window: nodes {node: [node_type, label]} and edges
511
+ (src, dst, time, label, event_uuid, attribute values, y), with the edge attributes
512
+ {"event_uuid", "time", "label", "y", **attributes} (attributes of the same name as the
513
+ first ones replace them, as in a dict).
514
+
515
+ The compact file is written from the edge list (`save_edge_list`), without building the
516
+ networkx graph, which is slow for the millions of edges of the windows of network datasets.
517
+ """
518
+ infos = list(node_info.values())
519
+ node_attrs = {"node_type": [i[0] for i in infos], "label": [i[1] for i in infos]}
520
+ srcs, dsts, times, labels, uuids, attrs, ys = zip(*edge_list) if edge_list else ((),) * 7
521
+ edge_attrs = {"event_uuid": uuids, "time": times, "label": labels, "y": ys}
522
+ attr_cols = list(zip(*attrs)) if attrs else [()] * len(edge_attr_names)
523
+ for name, col in zip(edge_attr_names, attr_cols):
524
+ edge_attrs[name] = col
525
+ save_edge_list(path, list(node_info), node_attrs, srcs, dsts, edge_attrs)
526
+
527
+
528
+ def _build_day(
529
+ cfg, day_idx, date, day_params, day_chunks, fetch_size, indexid2msg, cleaner, use_cleaner,
530
+ include_edge_type, attack_mimicry_events, mimicry_edge_num, _to_ns, file2nodes,
531
+ ):
532
+ """Builds and saves the time window graphs of a day (see `gen_edge_fused_tw`).
533
+
534
+ `day_chunks` yields the `fetchmany(fetch_size)` chunks of the day's events query.
535
+ """
536
+ # The millions of event tuples of a window trigger costly cyclic GC passes that cannot free
537
+ # anything (events hold no reference cycles)
538
+ gc_enabled = gc.isenabled()
539
+ gc.disable()
540
+ try:
541
+ _build_day_events(
542
+ cfg, day_idx, date, day_params, day_chunks, fetch_size, indexid2msg, cleaner,
543
+ use_cleaner, include_edge_type, attack_mimicry_events, mimicry_edge_num, _to_ns,
544
+ file2nodes,
545
+ )
546
+ finally:
547
+ if gc_enabled:
548
+ gc.enable()
549
+
550
+
551
+ def _build_day_events(
552
+ cfg, day_idx, date, day_params, day_chunks, fetch_size, indexid2msg, cleaner, use_cleaner,
553
+ include_edge_type, attack_mimicry_events, mimicry_edge_num, _to_ns, file2nodes,
554
+ ):
555
+ schema = get_schema(cfg)
556
+ edge_attributes = schema.edge_attributes
557
+ edge_attr_names = [attr.name for attr in edge_attributes]
558
+ num_extras = len(edge_attributes) + (1 if schema.label_column else 0)
559
+ has_extras = num_extras > 0
560
+ edge_type_idx = (
561
+ edge_attr_names.index(schema.edge_type_attribute) if schema.edge_type_attribute else None
562
+ )
563
+
564
+ encode_attrs = _attributes_encoder(edge_attributes)
565
+ has_label = bool(schema.label_column)
566
+
567
+ # With `benign_training`, the malicious events of train/val dates are dropped
568
+ train_val_dates = set(cfg.dataset.train_dates) | set(cfg.dataset.val_dates)
569
+ drop_malicious = (
570
+ has_label
571
+ and benign_training(cfg.construction)
572
+ and date in train_val_dates
573
+ and date not in set(cfg.dataset.test_dates)
574
+ )
575
+ label_idx = EVENT_EXTRA_IDX + len(edge_attributes)
576
+ num_dropped_malicious = 0
577
+
578
+ def read_extras(row):
579
+ """(edge attribute values, label) of an event row. Missing columns (e.g. in events
580
+ generated by mimicry) are null."""
581
+ extra = row[EVENT_EXTRA_IDX:]
582
+ if len(extra) < num_extras:
583
+ extra = tuple(extra) + (None,) * (num_extras - len(extra))
584
+ y = int(extra[-1] or 0) if has_label else 0
585
+ return encode_attrs(extra), y
586
+
587
+ date_start = f"{date} 00:00:00"
588
+ date_stop = f"{(datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')} 00:00:00"
589
+
590
+ timestamps = [date_start, date_stop]
591
+ test_mode_set_done = False
592
+ day_nodes = set()
593
+
594
+ for i in range(0, len(timestamps) - 1):
595
+ start = timestamps[i]
596
+ stop = timestamps[i + 1]
597
+ start_ns_timestamp = _to_ns(start)
598
+ end_ns_timestamp = _to_ns(stop)
599
+
600
+ attack_index = 0
601
+ mimicry_events = []
602
+ for attack_tuple in cfg.dataset.attack_to_time_window:
603
+ attack = attack_tuple[0]
604
+ attack_start_time = _to_ns(attack_tuple[1])
605
+ attack_end_time = _to_ns(attack_tuple[2])
606
+
607
+ if mimicry_edge_num > 0 and (
608
+ attack_start_time >= start_ns_timestamp and attack_end_time <= end_ns_timestamp
609
+ ):
610
+ log(
611
+ f"Insert mimicry events into attack {attack_index} when building graphs from {date_start} to {date_stop}"
612
+ )
613
+ mimicry_events.extend(attack_mimicry_events[attack_index])
614
+ attack_index += 1
615
+
616
+ assert (start_ns_timestamp, end_ns_timestamp) == day_params[day_idx]
617
+ FETCH_SIZE = fetch_size
618
+
619
+ BATCH = 1024
620
+ window_size_in_ns = cfg.construction.time_window_size * 60_000_000_000
621
+
622
+ start_time = None
623
+ temp_list = []
624
+ # Filtered events from the previous DB chunk that did not fill a
625
+ # complete BATCH; prepended to the next chunk's filtered events.
626
+ leftover = []
627
+
628
+ db_done = False
629
+ test_mode_stop = False
630
+ while not db_done and not test_mode_stop:
631
+ db_chunk = next(day_chunks)
632
+ db_done = len(db_chunk) < FETCH_SIZE
633
+
634
+ # Take ownership of leftover, then append newly filtered rows.
635
+ filtered = leftover
636
+ leftover = []
637
+ chunk = [row for row in db_chunk if row[2] in include_edge_type]
638
+ if drop_malicious:
639
+ benign = [row for row in chunk if not row[label_idx]]
640
+ num_dropped_malicious += len(chunk) - len(benign)
641
+ chunk = benign
642
+ filtered.extend(cleaner.filter_events(chunk) if use_cleaner else chunk)
643
+
644
+ # On the last DB chunk also append mimicry events, matching
645
+ # the original events_list ordering (real events then mimicry).
646
+ if db_done:
647
+ for event in mimicry_events:
648
+ if event[2] in include_edge_type and (
649
+ not cleaner
650
+ or cleaner.keep_event(event[1], event[2], event[4], event[6])
651
+ ):
652
+ filtered.append(event)
653
+
654
+ if not filtered:
655
+ continue
656
+
657
+ # Initialise start_time from the very first event seen.
658
+ if start_time is None:
659
+ start_time = filtered[0][EVENT_TIME_IDX]
660
+
661
+ # Slice filtered into BATCH-sized chunks. Any incomplete tail
662
+ # is saved as leftover for the next DB chunk (unless db_done).
663
+ n = len(filtered)
664
+ pos = 0
665
+ while pos < n:
666
+ batch_end = pos + BATCH
667
+ is_last_batch = db_done and batch_end >= n
668
+
669
+ if batch_end > n and not is_last_batch:
670
+ # Incomplete batch with more DB data coming; defer.
671
+ leftover = filtered[pos:]
672
+ break
673
+
674
+ batch_edges = filtered[pos : min(batch_end, n)]
675
+ pos = min(batch_end, n)
676
+
677
+ temp_list.extend(batch_edges)
678
+
679
+ if (batch_edges[-1][EVENT_TIME_IDX] > start_time + window_size_in_ns) or is_last_batch:
680
+ time_interval = (
681
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
682
+ + "~"
683
+ + ns_time_to_datetime_US(batch_edges[-1][EVENT_TIME_IDX], timezone=cfg.dataset.timezone)
684
+ )
685
+
686
+ # log(f"Start create edge fused time window graph for {time_interval}")
687
+
688
+ node_info = {}
689
+ # Edges as (src, dst, time, operation, event_uuid) tuples
690
+ edge_list = []
691
+ # (src_index_id, operation, dst_index_id) of each event
692
+ temp_list = cleaner.dedup_window(
693
+ temp_list, key_fn=lambda e: (e[1], e[2], e[4])
694
+ )
695
+ fuse_edge = cfg.construction.fuse_edge
696
+ edge_info = defaultdict(list)
697
+ for row in temp_list:
698
+ src_index_id = row[1]
699
+ operation = row[2]
700
+ dst_index_id = row[4]
701
+ event_uuid = row[5]
702
+ timestamp_rec = row[EVENT_TIME_IDX]
703
+ if src_index_id not in node_info or dst_index_id not in node_info:
704
+ src_msg = indexid2msg.get(src_index_id)
705
+ dst_msg = indexid2msg.get(dst_index_id)
706
+ # Skip edges referencing filtered-out nodes
707
+ if src_msg is None or dst_msg is None:
708
+ continue
709
+ # node_info values are [node_type, label]
710
+ node_info.setdefault(src_index_id, src_msg)
711
+ node_info.setdefault(dst_index_id, dst_msg)
712
+
713
+ # Edge attributes and label (empty for datasets without them)
714
+ if has_extras:
715
+ attrs, y = read_extras(row)
716
+ if edge_type_idx is not None:
717
+ operation = attrs[edge_type_idx]
718
+ else:
719
+ attrs, y = (), 0
720
+
721
+ if fuse_edge:
722
+ edge_info[(src_index_id, dst_index_id)].append(
723
+ (timestamp_rec, operation, event_uuid, attrs, y)
724
+ )
725
+ else:
726
+ edge_list.append(
727
+ (src_index_id, dst_index_id, timestamp_rec, operation, event_uuid, attrs, y)
728
+ )
729
+
730
+ # Fusion: among the time-sorted events between two nodes, only the
731
+ # first event of each run of consecutive identical events (same operation,
732
+ # attributes and label) is kept
733
+ for (src, dst), data in edge_info.items():
734
+ sorted_data = sorted(data, key=lambda x: x[0])
735
+ current_key = None
736
+ for timestamp_rec, operation, event_uuid, attrs, y in sorted_data:
737
+ key = (operation, attrs, y)
738
+ if key != current_key:
739
+ current_key = key
740
+ edge_list.append(
741
+ (src, dst, timestamp_rec, operation, event_uuid, attrs, y)
742
+ )
743
+
744
+ if cleaner:
745
+ cleaner.add_graph_nodes(node_info.keys())
746
+
747
+ # For unit tests, we only want few edges
748
+ NUM_TEST_EDGES = 2000
749
+ if cfg._test_mode:
750
+ edge_list = edge_list[: NUM_TEST_EDGES + 1]
751
+
752
+ # Translates edge types (e.g. OpTC to DARPA TC with consistent_edge_types)
753
+ if schema.edge_type_translation:
754
+ edge_list = [
755
+ (
756
+ src,
757
+ dst,
758
+ t,
759
+ schema.translate_edge_type(
760
+ label, node_info[src][0], node_info[dst][0]
761
+ ),
762
+ uuid,
763
+ attrs,
764
+ y,
765
+ )
766
+ for src, dst, t, label, uuid, attrs, y in edge_list
767
+ ]
768
+ date_dir = f"{cfg.construction._graphs_dir}/graph_{date}/"
769
+ os.makedirs(date_dir, exist_ok=True)
770
+ graph_name = f"{date_dir}/{time_interval}"
771
+
772
+ # log(f"Saving graph for {time_interval}")
773
+ _save_window_graph(graph_name, node_info, edge_list, edge_attr_names)
774
+ if file2nodes is not None:
775
+ # The graphs of a day share the set of the nodes of the day: a
776
+ # set per graph took tens of GB on large datasets, while only the
777
+ # nodes of each split are needed (a day belongs to the same splits)
778
+ day_nodes.update(node_info)
779
+ file2nodes[os.path.normpath(graph_name)] = day_nodes
780
+
781
+ # log(f"[{time_interval}] Num of edges: {len(edge_list)}")
782
+ # log(f"[{time_interval}] Num of events: {len(temp_list)}")
783
+ # log(f"[{time_interval}] Num of nodes: {len(node_info.keys())}")
784
+ start_time = batch_edges[-1][EVENT_TIME_IDX]
785
+ temp_list.clear()
786
+
787
+ # For unit tests, we only edges from the first graph
788
+ if cfg._test_mode:
789
+ test_mode_set_done = True
790
+ test_mode_stop = True
791
+ break
792
+
793
+ if num_dropped_malicious:
794
+ log(f"{date}: dropped {num_dropped_malicious} malicious events (benign training)")
795
+
796
+
797
+ def main(cfg):
798
+ """Main construction pipeline: build graphs from database and save metadata.
799
+
800
+ Execution flow:
801
+ 1. Extract node features from database (compute_indexid2msg)
802
+ 2. Build time-windowed graphs from events (gen_edge_fused_tw)
803
+ 3. Compute dataset split node memberships (compute_and_save_split2nodes)
804
+ 4. Save filtered node features (save_indexid2msg)
805
+ 5. With `construction.cleaning`, save the cleaning report
806
+
807
+ Args:
808
+ cfg: Configuration object with all construction parameters
809
+ """
810
+
811
+ cleaner = Cleaner(cfg)
812
+ if cleaner:
813
+ log(f"Cleaning methods: {', '.join(sorted(cleaner.methods))}")
814
+
815
+ indexid2msg = compute_indexid2msg(cfg=cfg, cleaner=cleaner)
816
+
817
+ file2nodes = {}
818
+ gen_edge_fused_tw(indexid2msg=indexid2msg, cfg=cfg, cleaner=cleaner, file2nodes=file2nodes)
819
+
820
+ split2nodes = compute_and_save_split2nodes(cfg, file2nodes=file2nodes)
821
+ del file2nodes
822
+ save_indexid2msg(indexid2msg, split2nodes, cfg)
823
+
824
+ if cleaner:
825
+ cleaner.save_report(cfg)