pidsmaker 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

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