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.
- pidsmaker/__init__.py +22 -0
- pidsmaker/cli.py +32 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1768 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +222 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +293 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +169 -0
- pidsmaker/detection/training_methods/training_loop.py +377 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +68 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +377 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1432 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1437 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +120 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +49 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +232 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +19 -0
- pidsmaker/tasks/transformation.py +308 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +204 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +1057 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +447 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +730 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-4.0.0.dist-info/METADATA +596 -0
- pidsmaker-4.0.0.dist-info/RECORD +338 -0
- pidsmaker-4.0.0.dist-info/WHEEL +5 -0
- pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import os.path
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
|
|
5
|
+
from pidsmaker.utils.database import events_order_sql
|
|
6
|
+
from pidsmaker.utils.utils import datetime_to_ns_time_US, init_database_connection, log
|
|
7
|
+
from pidsmaker.utils.dataset_utils import get_schema, get_uuid_to_index_id, get_time_and_end_node
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def has_event_labels(cfg):
|
|
11
|
+
"""Whether the dataset labels its events in the database (see `DatasetSchema.label_column`).
|
|
12
|
+
|
|
13
|
+
These datasets (e.g. network datasets like LANL) have event-level ground truth: the
|
|
14
|
+
malicious nodes are the endpoints of malicious events, and attacks are the groups of
|
|
15
|
+
malicious events in the time windows of `attack_to_time_window`.
|
|
16
|
+
"""
|
|
17
|
+
return get_schema(cfg).label_column is not None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Last result of `get_malicious_events` (read many times per evaluation)
|
|
21
|
+
_MALICIOUS_EVENTS_CACHE = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_malicious_events(cfg):
|
|
25
|
+
"""[(src_index_id, dst_index_id, timestamp, edge type)] of the events labelled malicious,
|
|
26
|
+
sorted by time. The edge type is the one of the graphs (see `construction.edge_type`)."""
|
|
27
|
+
schema = get_schema(cfg)
|
|
28
|
+
database = (
|
|
29
|
+
cfg.dataset.database_all_file if cfg.construction.use_all_files else cfg.dataset.database
|
|
30
|
+
)
|
|
31
|
+
key = (cfg.dataset.name, database, schema.name, schema.edge_type_attribute, schema.operations_sql())
|
|
32
|
+
if key not in _MALICIOUS_EVENTS_CACHE:
|
|
33
|
+
if schema.edge_type_attribute:
|
|
34
|
+
attr = schema.edge_attribute(schema.edge_type_attribute)
|
|
35
|
+
type_col, encode = attr.column, attr.encode
|
|
36
|
+
else:
|
|
37
|
+
type_col, encode = "operation", (lambda v: v)
|
|
38
|
+
cur, connect = init_database_connection(cfg)
|
|
39
|
+
try:
|
|
40
|
+
cur.execute(
|
|
41
|
+
f"SELECT src_index_id, dst_index_id, timestamp_rec, {type_col} "
|
|
42
|
+
f"FROM {schema.event_table} WHERE {schema.label_column} = 1{schema.operations_sql()} "
|
|
43
|
+
f"{events_order_sql(connect, 'timestamp_rec')};"
|
|
44
|
+
)
|
|
45
|
+
rows = cur.fetchall()
|
|
46
|
+
finally:
|
|
47
|
+
connect.close()
|
|
48
|
+
_MALICIOUS_EVENTS_CACHE.clear()
|
|
49
|
+
_MALICIOUS_EVENTS_CACHE[key] = [
|
|
50
|
+
(int(src), int(dst), int(t), encode(etype)) for src, dst, t, etype in rows
|
|
51
|
+
]
|
|
52
|
+
return _MALICIOUS_EVENTS_CACHE[key]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _malicious_events_of_attack(cfg, start, end):
|
|
56
|
+
return [e for e in get_malicious_events(cfg) if start <= e[2] <= end]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def is_threatrace(cfg):
|
|
60
|
+
"""True when the ThreaTrace ground truth is selected."""
|
|
61
|
+
return cfg.evaluation.ground_truth_version == "threatrace"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _threatrace_gt_file(cfg):
|
|
65
|
+
"""ThreaTrace ships one flat UUID list per dataset. Reuse the dataset's
|
|
66
|
+
ground-truth subfolder (e.g. 'E3-CADETS') from its configured paths."""
|
|
67
|
+
paths = cfg.dataset.ground_truth_relative_path
|
|
68
|
+
if not paths:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
"ThreaTrace ground truth needs the dataset's GT subfolder, but "
|
|
71
|
+
"`ground_truth_relative_path` is empty for this dataset."
|
|
72
|
+
)
|
|
73
|
+
return os.path.join(paths[0].split("/")[0], "ground_truth.txt")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def ensure_ground_truth_available(cfg):
|
|
77
|
+
"""Fail fast with a clear message when the selected ground truth has no file for
|
|
78
|
+
this dataset. ThreaTrace only covers CADETS, THEIA, TRACE, and FIVEDIRECTIONS (E3)."""
|
|
79
|
+
if has_event_labels(cfg):
|
|
80
|
+
return
|
|
81
|
+
if not is_threatrace(cfg):
|
|
82
|
+
missing = [
|
|
83
|
+
path
|
|
84
|
+
for path in cfg.dataset.ground_truth_relative_path
|
|
85
|
+
if not os.path.exists(os.path.join(cfg._ground_truth_dir, path))
|
|
86
|
+
]
|
|
87
|
+
if missing:
|
|
88
|
+
raise FileNotFoundError(
|
|
89
|
+
f"Ground truth `{cfg.evaluation.ground_truth_version}` not found for dataset "
|
|
90
|
+
f"'{cfg.dataset.name}': missing {missing} in {cfg._ground_truth_dir}. "
|
|
91
|
+
"Use another `evaluation.ground_truth_version`."
|
|
92
|
+
)
|
|
93
|
+
return
|
|
94
|
+
paths = cfg.dataset.ground_truth_relative_path
|
|
95
|
+
subdir = paths[0].split("/")[0] if paths else None
|
|
96
|
+
gt_path = os.path.join(cfg._ground_truth_dir, subdir, "ground_truth.txt") if subdir else None
|
|
97
|
+
if not gt_path or not os.path.exists(gt_path):
|
|
98
|
+
raise FileNotFoundError(
|
|
99
|
+
f"ThreaTrace ground truth not found for dataset '{cfg.dataset.name}'. "
|
|
100
|
+
f"ThreaTrace provides ground truth only for CADETS, THEIA, TRACE, and "
|
|
101
|
+
f"FIVEDIRECTIONS (E3)."
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _test_period_ns(cfg):
|
|
106
|
+
"""(start, end) of the dataset's test period in ns — the single combined
|
|
107
|
+
window used for the flat ThreaTrace ground truth."""
|
|
108
|
+
dates = sorted(cfg.dataset.test_dates)
|
|
109
|
+
return (
|
|
110
|
+
datetime_to_ns_time_US(dates[0] + " 00:00:00", timezone=cfg.dataset.timezone),
|
|
111
|
+
datetime_to_ns_time_US(dates[-1] + " 23:59:59", timezone=cfg.dataset.timezone),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def ground_truth_files(cfg):
|
|
116
|
+
"""GT file relative paths for the active version: one flat file for
|
|
117
|
+
ThreaTrace, the per-attack files otherwise."""
|
|
118
|
+
if is_threatrace(cfg):
|
|
119
|
+
return [_threatrace_gt_file(cfg)]
|
|
120
|
+
return list(cfg.dataset.ground_truth_relative_path)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def ground_truth_attacks(cfg):
|
|
124
|
+
"""(relative_path, start_ns, end_ns) per attack. ThreaTrace collapses to a
|
|
125
|
+
single combined window over the dataset's test period."""
|
|
126
|
+
if is_threatrace(cfg) or (has_event_labels(cfg) and not cfg.dataset.attack_to_time_window):
|
|
127
|
+
start, end = _test_period_ns(cfg)
|
|
128
|
+
name = "all_attacks" if has_event_labels(cfg) else _threatrace_gt_file(cfg)
|
|
129
|
+
return [(name, start, end)]
|
|
130
|
+
return [
|
|
131
|
+
(a[0], datetime_to_ns_time_US(a[1], timezone=cfg.dataset.timezone), datetime_to_ns_time_US(a[2], timezone=cfg.dataset.timezone))
|
|
132
|
+
for a in cfg.dataset.attack_to_time_window
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def read_ground_truth_uuids(cfg, relative_path):
|
|
137
|
+
"""Yield (uuid, label) from a GT file, handling both the 3-column
|
|
138
|
+
orthrus/reapr CSV and the UUID-only ThreaTrace txt."""
|
|
139
|
+
with open(os.path.join(cfg._ground_truth_dir, relative_path), "r") as f:
|
|
140
|
+
for row in csv.reader(f):
|
|
141
|
+
if not row or not row[0].strip():
|
|
142
|
+
continue
|
|
143
|
+
yield row[0].strip(), (row[1] if len(row) > 1 else "threatrace")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _mimicry_nodes(cfg, relative_path, uuid2nids):
|
|
147
|
+
"""Node ids injected by the mimicry attack generator for one ground-truth file.
|
|
148
|
+
Only applies to the per-attack (orthrus/reapr) ground truth."""
|
|
149
|
+
nodes = {}
|
|
150
|
+
path = os.path.join(cfg.construction._mimicry_dir, relative_path.split("/")[-1])
|
|
151
|
+
with open(path, "r") as f:
|
|
152
|
+
for row in csv.reader(f):
|
|
153
|
+
node_id = uuid2nids.get(row[0])
|
|
154
|
+
if node_id is not None:
|
|
155
|
+
nodes[int(node_id)] = row[1] if len(row) > 1 else ""
|
|
156
|
+
return nodes
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _get_ground_truth_from_event_labels(cfg):
|
|
160
|
+
"""Malicious nodes: the endpoints of malicious events, labelled by their attack."""
|
|
161
|
+
_, nid2uuid = get_uuid_to_index_id(cfg)
|
|
162
|
+
ground_truth_paths, uuid_to_node_id = {}, {}
|
|
163
|
+
for name, start, end in ground_truth_attacks(cfg):
|
|
164
|
+
for src, dst, _t, _etype in _malicious_events_of_attack(cfg, start, end):
|
|
165
|
+
for nid in (src, dst):
|
|
166
|
+
ground_truth_paths.setdefault(nid, name)
|
|
167
|
+
uuid_to_node_id[nid2uuid[nid]] = str(nid)
|
|
168
|
+
return set(ground_truth_paths), ground_truth_paths, uuid_to_node_id
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def get_ground_truth(cfg):
|
|
172
|
+
if has_event_labels(cfg):
|
|
173
|
+
return _get_ground_truth_from_event_labels(cfg)
|
|
174
|
+
uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
|
|
175
|
+
|
|
176
|
+
ground_truth_nids, ground_truth_paths = [], {}
|
|
177
|
+
uuid_to_node_id = {}
|
|
178
|
+
missing = 0
|
|
179
|
+
for file in ground_truth_files(cfg):
|
|
180
|
+
for node_uuid, node_labels in read_ground_truth_uuids(cfg, file):
|
|
181
|
+
node_id = uuid2nids.get(node_uuid)
|
|
182
|
+
if node_id is None:
|
|
183
|
+
missing += 1
|
|
184
|
+
continue
|
|
185
|
+
ground_truth_nids.append(int(node_id))
|
|
186
|
+
ground_truth_paths[int(node_id)] = node_labels
|
|
187
|
+
uuid_to_node_id[node_uuid] = str(node_id)
|
|
188
|
+
if missing:
|
|
189
|
+
log(f"{missing} ground-truth UUIDs not present in the graph (skipped)")
|
|
190
|
+
|
|
191
|
+
mimicry_edge_num = cfg.construction.mimicry_edge_num
|
|
192
|
+
if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
|
|
193
|
+
num_before = len(ground_truth_nids)
|
|
194
|
+
for file in cfg.dataset.ground_truth_relative_path:
|
|
195
|
+
for node_id, labels in _mimicry_nodes(cfg, file, uuid2nids).items():
|
|
196
|
+
ground_truth_nids.append(node_id)
|
|
197
|
+
ground_truth_paths[node_id] = labels
|
|
198
|
+
log(f"{len(ground_truth_nids) - num_before} mimicry ground truth nodes loaded")
|
|
199
|
+
|
|
200
|
+
return set(ground_truth_nids), ground_truth_paths, uuid_to_node_id
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def get_GP_of_each_attack(cfg):
|
|
204
|
+
if has_event_labels(cfg):
|
|
205
|
+
return {
|
|
206
|
+
i: {
|
|
207
|
+
"nids": {n for e in _malicious_events_of_attack(cfg, start, end) for n in e[:2]},
|
|
208
|
+
"time_range": [start, end],
|
|
209
|
+
}
|
|
210
|
+
for i, (_name, start, end) in enumerate(ground_truth_attacks(cfg))
|
|
211
|
+
}
|
|
212
|
+
uuid2nids, _ = get_uuid_to_index_id(cfg)
|
|
213
|
+
|
|
214
|
+
attack_to_nids = {}
|
|
215
|
+
for i, (path, start, end) in enumerate(ground_truth_attacks(cfg)):
|
|
216
|
+
nids = set()
|
|
217
|
+
for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
|
|
218
|
+
node_id = uuid2nids.get(node_uuid)
|
|
219
|
+
if node_id is not None:
|
|
220
|
+
nids.add(int(node_id))
|
|
221
|
+
|
|
222
|
+
mimicry_edge_num = cfg.construction.mimicry_edge_num
|
|
223
|
+
if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
|
|
224
|
+
mimicry = _mimicry_nodes(cfg, path, uuid2nids)
|
|
225
|
+
nids |= set(mimicry.keys())
|
|
226
|
+
log(f"{len(mimicry)} mimicry ground truth nodes loaded")
|
|
227
|
+
|
|
228
|
+
attack_to_nids[i] = {"nids": nids, "time_range": [start, end]}
|
|
229
|
+
return attack_to_nids
|
|
230
|
+
|
|
231
|
+
def get_t2malicious_node(cfg) -> dict[list]:
|
|
232
|
+
"""Map event timestamps to malicious node UUIDs.
|
|
233
|
+
|
|
234
|
+
When edge-level ground truth CSVs are available, only events
|
|
235
|
+
matching explicit attack edges are considered malicious. Otherwise falls back
|
|
236
|
+
to the DARPA TC approach: any event touching a GT node within the attack
|
|
237
|
+
window is malicious.
|
|
238
|
+
"""
|
|
239
|
+
if has_event_labels(cfg):
|
|
240
|
+
_, nid2uuid = get_uuid_to_index_id(cfg)
|
|
241
|
+
t_to_node = defaultdict(list)
|
|
242
|
+
for src, dst, t, _etype in get_malicious_events(cfg):
|
|
243
|
+
t_to_node[t].extend([nid2uuid[src], nid2uuid[dst]])
|
|
244
|
+
return t_to_node
|
|
245
|
+
if _has_edge_csvs(cfg):
|
|
246
|
+
return _get_t2malicious_node_from_edge_gt(cfg)
|
|
247
|
+
return _get_t2malicious_node_from_node_gt(cfg)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _get_t2malicious_node_from_edge_gt(cfg) -> dict[list]:
|
|
251
|
+
"""Use explicit edge-level ground truth to find malicious events.
|
|
252
|
+
|
|
253
|
+
For each attack edge (src, dst, event_type), query the DB for matching events
|
|
254
|
+
and record the timestamp -> node mapping.
|
|
255
|
+
"""
|
|
256
|
+
cur, connect = init_database_connection(cfg)
|
|
257
|
+
uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
|
|
258
|
+
|
|
259
|
+
t_to_node = defaultdict(list)
|
|
260
|
+
|
|
261
|
+
edge_paths = cfg.dataset.ground_truth_edges_relative_path
|
|
262
|
+
for path in edge_paths:
|
|
263
|
+
filepath = os.path.join(cfg._ground_truth_dir, path)
|
|
264
|
+
if not os.path.exists(filepath):
|
|
265
|
+
continue
|
|
266
|
+
|
|
267
|
+
# Collect all attack edges: (src_nid, dst_nid, event_type)
|
|
268
|
+
attack_edges = set()
|
|
269
|
+
with open(filepath, "r") as f:
|
|
270
|
+
reader = csv.DictReader(f)
|
|
271
|
+
for row in reader:
|
|
272
|
+
src_nid = uuid2nids.get(row["src_node_uuid"])
|
|
273
|
+
dst_nid = uuid2nids.get(row["dst_node_uuid"])
|
|
274
|
+
if src_nid is not None and dst_nid is not None:
|
|
275
|
+
attack_edges.add((str(src_nid), str(dst_nid), row["event_type"]))
|
|
276
|
+
|
|
277
|
+
if not attack_edges:
|
|
278
|
+
continue
|
|
279
|
+
|
|
280
|
+
# Query events for each attack edge
|
|
281
|
+
for src_nid, dst_nid, event_type in attack_edges:
|
|
282
|
+
sql = (
|
|
283
|
+
"SELECT src_index_id, dst_index_id, timestamp_rec "
|
|
284
|
+
"FROM event_table "
|
|
285
|
+
"WHERE src_index_id = %s AND dst_index_id = %s AND operation = %s;"
|
|
286
|
+
)
|
|
287
|
+
cur.execute(sql, (src_nid, dst_nid, event_type))
|
|
288
|
+
for row in cur.fetchall():
|
|
289
|
+
t = int(row[2])
|
|
290
|
+
t_to_node[t].append(nid2uuid[int(row[0])])
|
|
291
|
+
t_to_node[t].append(nid2uuid[int(row[1])])
|
|
292
|
+
|
|
293
|
+
log(f"Edge GT: found {len(t_to_node)} event timestamps with malicious activity")
|
|
294
|
+
return t_to_node
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _get_t2malicious_node_from_node_gt(cfg) -> dict[list]:
|
|
298
|
+
"""Original DARPA TC approach: any event touching a GT node in the attack window."""
|
|
299
|
+
cur, connect = init_database_connection(cfg)
|
|
300
|
+
uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
|
|
301
|
+
|
|
302
|
+
t_to_node = defaultdict(list)
|
|
303
|
+
|
|
304
|
+
for path, start_time, end_time in ground_truth_attacks(cfg):
|
|
305
|
+
ground_truth_nids = set()
|
|
306
|
+
for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
|
|
307
|
+
node_id = uuid2nids.get(node_uuid)
|
|
308
|
+
if node_id is not None:
|
|
309
|
+
ground_truth_nids.add(str(node_id))
|
|
310
|
+
|
|
311
|
+
mimicry_edge_num = cfg.construction.mimicry_edge_num
|
|
312
|
+
if mimicry_edge_num and mimicry_edge_num > 0 and not is_threatrace(cfg):
|
|
313
|
+
mimicry = _mimicry_nodes(cfg, path, uuid2nids)
|
|
314
|
+
ground_truth_nids |= {str(n) for n in mimicry}
|
|
315
|
+
log(f"{len(mimicry)} mimicry nodes loaded")
|
|
316
|
+
|
|
317
|
+
rows = get_time_and_end_node(cfg, start_time, end_time)
|
|
318
|
+
for row in rows:
|
|
319
|
+
src_id = str(row[0])
|
|
320
|
+
dst_id = str(row[1])
|
|
321
|
+
t = row[2]
|
|
322
|
+
if src_id in ground_truth_nids:
|
|
323
|
+
t_to_node[int(t)].append(nid2uuid[int(src_id)])
|
|
324
|
+
if dst_id in ground_truth_nids:
|
|
325
|
+
t_to_node[int(t)].append(nid2uuid[int(dst_id)])
|
|
326
|
+
|
|
327
|
+
log(f"Node GT: found {len(t_to_node)} event timestamps with malicious activity")
|
|
328
|
+
return t_to_node
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _has_edge_csvs(cfg):
|
|
332
|
+
"""Check if explicit edge-level ground truth CSVs are configured."""
|
|
333
|
+
paths = getattr(cfg.dataset, "ground_truth_edges_relative_path", None)
|
|
334
|
+
return paths is not None and len(paths) > 0
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def get_attack_to_mal_edges(cfg) -> dict[set]:
|
|
338
|
+
"""Load per-attack malicious edges.
|
|
339
|
+
|
|
340
|
+
If ground_truth_edges_relative_path is configured,
|
|
341
|
+
loads explicit attack edges from CSV files.
|
|
342
|
+
Otherwise falls back to the DB-query approach (DARPA TC datasets).
|
|
343
|
+
"""
|
|
344
|
+
if has_event_labels(cfg):
|
|
345
|
+
return {
|
|
346
|
+
i: {
|
|
347
|
+
(str(src), str(dst), t, etype)
|
|
348
|
+
for src, dst, t, etype in _malicious_events_of_attack(cfg, start, end)
|
|
349
|
+
}
|
|
350
|
+
for i, (_name, start, end) in enumerate(ground_truth_attacks(cfg))
|
|
351
|
+
}
|
|
352
|
+
if _has_edge_csvs(cfg):
|
|
353
|
+
return _get_attack_to_mal_edges_from_csv(cfg)
|
|
354
|
+
return _get_attack_to_mal_edges_from_db(cfg)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _get_attack_to_mal_edges_from_csv(cfg) -> dict[set]:
|
|
358
|
+
"""Load malicious edges from explicit CSV files.
|
|
359
|
+
|
|
360
|
+
CSV format: src_node_uuid,dst_node_uuid,event_type,attack_edge_type
|
|
361
|
+
Edges are matched by (src_index_id, dst_index_id, event_type) — no timestamp needed.
|
|
362
|
+
"""
|
|
363
|
+
uuid2nids, _ = get_uuid_to_index_id(cfg)
|
|
364
|
+
|
|
365
|
+
attack_to_mal_edges = defaultdict(set)
|
|
366
|
+
edge_paths = cfg.dataset.ground_truth_edges_relative_path
|
|
367
|
+
|
|
368
|
+
for i, path in enumerate(edge_paths):
|
|
369
|
+
filepath = os.path.join(cfg._ground_truth_dir, path)
|
|
370
|
+
if not os.path.exists(filepath):
|
|
371
|
+
log(f"Warning: edge ground truth file not found: {filepath}")
|
|
372
|
+
continue
|
|
373
|
+
with open(filepath, "r") as f:
|
|
374
|
+
reader = csv.DictReader(f)
|
|
375
|
+
for row in reader:
|
|
376
|
+
src_uuid = row["src_node_uuid"]
|
|
377
|
+
dst_uuid = row["dst_node_uuid"]
|
|
378
|
+
event_type = row["event_type"]
|
|
379
|
+
|
|
380
|
+
src_nid = uuid2nids.get(src_uuid)
|
|
381
|
+
dst_nid = uuid2nids.get(dst_uuid)
|
|
382
|
+
if src_nid is None or dst_nid is None:
|
|
383
|
+
continue
|
|
384
|
+
|
|
385
|
+
# Store as (src_index_id, dst_index_id, event_type) — no timestamp
|
|
386
|
+
attack_to_mal_edges[i].add((str(src_nid), str(dst_nid), event_type))
|
|
387
|
+
|
|
388
|
+
total = sum(len(s) for s in attack_to_mal_edges.values())
|
|
389
|
+
log(f"Loaded {total} malicious edges from {len(edge_paths)} CSV files")
|
|
390
|
+
return attack_to_mal_edges
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _get_attack_to_mal_edges_from_db(cfg) -> dict[set]:
|
|
394
|
+
"""Original DB-query approach: find all events involving GT nodes during attack windows."""
|
|
395
|
+
cur, connect = init_database_connection(cfg)
|
|
396
|
+
uuid2nids, nid2uuid = get_uuid_to_index_id(cfg)
|
|
397
|
+
|
|
398
|
+
malicious_edge_selection = cfg.evaluation.edge_evaluation.malicious_edge_selection
|
|
399
|
+
|
|
400
|
+
attack_to_mal_edges = defaultdict(set)
|
|
401
|
+
for i, (path, start_time, end_time) in enumerate(ground_truth_attacks(cfg)):
|
|
402
|
+
ground_truth_nids = set()
|
|
403
|
+
for node_uuid, _labels in read_ground_truth_uuids(cfg, path):
|
|
404
|
+
node_id = uuid2nids.get(node_uuid)
|
|
405
|
+
if node_id is not None:
|
|
406
|
+
ground_truth_nids.add(str(node_id))
|
|
407
|
+
|
|
408
|
+
rows = get_time_and_end_node(cfg, start_time, end_time)
|
|
409
|
+
for row in rows:
|
|
410
|
+
src_idx_id = str(row[0])
|
|
411
|
+
dst_idx_id = str(row[1])
|
|
412
|
+
timestamp_rec = row[2]
|
|
413
|
+
ope = row[3]
|
|
414
|
+
|
|
415
|
+
condition = None
|
|
416
|
+
if malicious_edge_selection == "src_node":
|
|
417
|
+
condition = src_idx_id in ground_truth_nids
|
|
418
|
+
elif malicious_edge_selection == "dst_node":
|
|
419
|
+
condition = dst_idx_id in ground_truth_nids
|
|
420
|
+
elif malicious_edge_selection == "both_nodes":
|
|
421
|
+
condition = src_idx_id in ground_truth_nids and dst_idx_id in ground_truth_nids
|
|
422
|
+
elif malicious_edge_selection == "either_node":
|
|
423
|
+
condition = src_idx_id in ground_truth_nids or dst_idx_id in ground_truth_nids
|
|
424
|
+
else:
|
|
425
|
+
raise ValueError(
|
|
426
|
+
"`malicious_edge_selection` must be one of 'src_node', 'dst_node', 'both_nodes', 'either_node"
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
if condition:
|
|
430
|
+
attack_to_mal_edges[i].add((src_idx_id, dst_idx_id, timestamp_rec, ope))
|
|
431
|
+
|
|
432
|
+
return attack_to_mal_edges
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def get_ground_truth_edges(cfg) -> set:
|
|
436
|
+
"""Return the set of all malicious edges across all attacks.
|
|
437
|
+
|
|
438
|
+
When using CSV-based edge labels, edges are (src_nid, dst_nid, event_type) tuples.
|
|
439
|
+
When using DB-based labels, edges are (src_nid, dst_nid, timestamp, event_type) tuples.
|
|
440
|
+
"""
|
|
441
|
+
attack_to_mal_edges = get_attack_to_mal_edges(cfg)
|
|
442
|
+
|
|
443
|
+
malicious_edges = set()
|
|
444
|
+
for attack, edges_set in attack_to_mal_edges.items():
|
|
445
|
+
malicious_edges |= edges_set
|
|
446
|
+
|
|
447
|
+
return malicious_edges
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Storage of the per-epoch inference outputs (edge/node losses per time window).
|
|
2
|
+
|
|
3
|
+
Inference writes one file per batch/time window in
|
|
4
|
+
``{edge_losses_dir}/{split}/model_epoch_{i}/{start}~{end}{ext}``, for every epoch.
|
|
5
|
+
These used to be CSV files, which made them the largest output of a run after the
|
|
6
|
+
edge features. They are now stored as compressed `.npz` archives of typed columns
|
|
7
|
+
(about 9x smaller than the CSVs):
|
|
8
|
+
|
|
9
|
+
- float64 columns holding float32 values (e.g. losses computed in float32) are stored
|
|
10
|
+
as float32, other floats as float64;
|
|
11
|
+
- integer columns are stored as int32 when the values fit, int64 otherwise.
|
|
12
|
+
|
|
13
|
+
`read_losses` always returns float64/int64 columns, i.e. the same DataFrame as
|
|
14
|
+
`pd.read_csv` on the former CSV files, so downstream code is unchanged. Legacy CSV
|
|
15
|
+
files remain readable.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
LOSS_EXT = ".npz"
|
|
24
|
+
_LEGACY_EXT = ".csv"
|
|
25
|
+
_EXTS = (LOSS_EXT, _LEGACY_EXT)
|
|
26
|
+
|
|
27
|
+
_I32 = np.iinfo(np.int32)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _compact_column(values):
|
|
31
|
+
a = np.asarray(values)
|
|
32
|
+
if a.dtype == np.bool_:
|
|
33
|
+
return a.astype(np.int8)
|
|
34
|
+
if np.issubdtype(a.dtype, np.floating):
|
|
35
|
+
if a.dtype == np.float64:
|
|
36
|
+
a32 = a.astype(np.float32)
|
|
37
|
+
# Only downcast when lossless (NaNs compare unequal, hence equal_nan)
|
|
38
|
+
if np.array_equal(a32.astype(np.float64), a, equal_nan=True):
|
|
39
|
+
return a32
|
|
40
|
+
return a
|
|
41
|
+
if np.issubdtype(a.dtype, np.integer):
|
|
42
|
+
if a.size == 0 or (a.min() >= _I32.min and a.max() <= _I32.max):
|
|
43
|
+
return a.astype(np.int32)
|
|
44
|
+
return a.astype(np.int64)
|
|
45
|
+
raise TypeError(f"Unsupported column dtype {a.dtype} in loss file")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _expand_column(a):
|
|
49
|
+
if np.issubdtype(a.dtype, np.floating):
|
|
50
|
+
return a.astype(np.float64, copy=False)
|
|
51
|
+
if np.issubdtype(a.dtype, np.integer):
|
|
52
|
+
return a.astype(np.int64, copy=False)
|
|
53
|
+
return a
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write_losses(out_dir, name, columns):
|
|
57
|
+
"""Writes the columns (dict name -> 1D array, or a DataFrame) of one loss file.
|
|
58
|
+
|
|
59
|
+
Returns the written path.
|
|
60
|
+
"""
|
|
61
|
+
if isinstance(columns, pd.DataFrame):
|
|
62
|
+
columns = {c: columns[c].to_numpy() for c in columns.columns}
|
|
63
|
+
path = os.path.join(out_dir, name + LOSS_EXT)
|
|
64
|
+
# A CSV of the same window left by a previous run with the former format would be
|
|
65
|
+
# read in addition to this file
|
|
66
|
+
legacy = os.path.join(out_dir, name + _LEGACY_EXT)
|
|
67
|
+
if os.path.exists(legacy):
|
|
68
|
+
os.remove(legacy)
|
|
69
|
+
np.savez_compressed(path, **{k: _compact_column(v) for k, v in columns.items()})
|
|
70
|
+
return path
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_losses(path, usecols=None):
|
|
74
|
+
"""Reads one loss file (.npz or legacy .csv) as a DataFrame of float64/int64 columns."""
|
|
75
|
+
if path.endswith(_LEGACY_EXT):
|
|
76
|
+
return pd.read_csv(path, usecols=usecols)
|
|
77
|
+
with np.load(path) as f:
|
|
78
|
+
names = f.files if usecols is None else [c for c in f.files if c in usecols]
|
|
79
|
+
missing = set(usecols or ()) - set(f.files)
|
|
80
|
+
if missing:
|
|
81
|
+
raise ValueError(f"Columns {sorted(missing)} not found in {path}")
|
|
82
|
+
return pd.DataFrame({c: _expand_column(f[c]) for c in names})
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_loss_file(fname):
|
|
86
|
+
return fname.endswith(_EXTS)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def strip_loss_ext(fname):
|
|
90
|
+
"""Returns the time window name ("start~end") of a loss file name."""
|
|
91
|
+
for ext in _EXTS:
|
|
92
|
+
if fname.endswith(ext):
|
|
93
|
+
return fname[: -len(ext)]
|
|
94
|
+
return fname
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def compact_int_columns(df):
|
|
98
|
+
"""Losslessly stores the int64 columns of a DataFrame as int32 when the values fit.
|
|
99
|
+
|
|
100
|
+
Used for the per-epoch `edge_scores_*.pkl` files, whose node IDs, types, time
|
|
101
|
+
window indices and labels all fit in 32 bits.
|
|
102
|
+
"""
|
|
103
|
+
df = df.copy(deep=False)
|
|
104
|
+
for c in df.columns:
|
|
105
|
+
if df[c].dtype == np.int64 and len(df) > 0:
|
|
106
|
+
if df[c].min() >= _I32.min and df[c].max() <= _I32.max:
|
|
107
|
+
df[c] = df[c].astype(np.int32)
|
|
108
|
+
return df
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
_EPOCH_FILE_PREFIXES = ("edge_scores_", "result_", "scores_")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _epochs_to_keep(cfg, metrics):
|
|
115
|
+
keep = set()
|
|
116
|
+
if not metrics or metrics.get("epoch") is None:
|
|
117
|
+
return keep # the evaluation's best epoch is unknown (e.g. cached): nothing is pruned
|
|
118
|
+
keep.add(f"model_epoch_{int(metrics['epoch'])}")
|
|
119
|
+
|
|
120
|
+
# Triage selects its own best epoch (highest MCC) from the per-epoch stats
|
|
121
|
+
import torch
|
|
122
|
+
|
|
123
|
+
pr_dir = cfg.evaluation._precision_recall_dir
|
|
124
|
+
best_mcc = None
|
|
125
|
+
if os.path.isdir(pr_dir):
|
|
126
|
+
for f in os.listdir(pr_dir):
|
|
127
|
+
if f.startswith("stats_model_epoch_") and f.endswith(".pth"):
|
|
128
|
+
stats = torch.load(os.path.join(pr_dir, f), weights_only=False)
|
|
129
|
+
mcc = stats.get("mcc") if isinstance(stats, dict) else None
|
|
130
|
+
if mcc is not None and (best_mcc is None or mcc > best_mcc[0]):
|
|
131
|
+
best_mcc = (mcc, f[len("stats_") : -len(".pth")])
|
|
132
|
+
if best_mcc is not None:
|
|
133
|
+
keep.add(best_mcc[1])
|
|
134
|
+
return keep
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def prune_non_best_epochs(cfg, metrics):
|
|
138
|
+
"""Deletes the large per-epoch outputs of all epochs except the best one(s).
|
|
139
|
+
|
|
140
|
+
Kept for every epoch: stats and plots. Deleted for the other epochs: the loss
|
|
141
|
+
files of all splits, the evaluation pickles (edge_scores_, result_, scores_) and
|
|
142
|
+
the saved model weights. The best epoch is the one selected by the evaluation,
|
|
143
|
+
plus the one selected by triage (best MCC) when it differs.
|
|
144
|
+
|
|
145
|
+
Re-running evaluation with another config afterwards only considers the kept epochs.
|
|
146
|
+
"""
|
|
147
|
+
import shutil
|
|
148
|
+
|
|
149
|
+
from pidsmaker.utils.utils import log
|
|
150
|
+
|
|
151
|
+
keep = _epochs_to_keep(cfg, metrics)
|
|
152
|
+
if not keep:
|
|
153
|
+
log("Epoch pruning skipped: the best epoch is unknown.")
|
|
154
|
+
return
|
|
155
|
+
|
|
156
|
+
freed = 0
|
|
157
|
+
|
|
158
|
+
def _rm(path):
|
|
159
|
+
nonlocal freed
|
|
160
|
+
if os.path.isdir(path):
|
|
161
|
+
for root, _, files in os.walk(path):
|
|
162
|
+
freed += sum(os.path.getsize(os.path.join(root, f)) for f in files)
|
|
163
|
+
shutil.rmtree(path)
|
|
164
|
+
elif os.path.isfile(path):
|
|
165
|
+
freed += os.path.getsize(path)
|
|
166
|
+
os.remove(path)
|
|
167
|
+
|
|
168
|
+
losses_dir = cfg.training._edge_losses_dir
|
|
169
|
+
if os.path.isdir(losses_dir):
|
|
170
|
+
for split in os.listdir(losses_dir):
|
|
171
|
+
split_dir = os.path.join(losses_dir, split)
|
|
172
|
+
if not os.path.isdir(split_dir):
|
|
173
|
+
continue
|
|
174
|
+
for epoch_dir in os.listdir(split_dir):
|
|
175
|
+
if epoch_dir.startswith("model_epoch_") and epoch_dir not in keep:
|
|
176
|
+
_rm(os.path.join(split_dir, epoch_dir))
|
|
177
|
+
|
|
178
|
+
models_dir = getattr(cfg.training, "_trained_models_dir", None)
|
|
179
|
+
if models_dir and os.path.isdir(models_dir):
|
|
180
|
+
for f in os.listdir(models_dir):
|
|
181
|
+
if f.startswith("model_epoch_") and f not in keep:
|
|
182
|
+
_rm(os.path.join(models_dir, f))
|
|
183
|
+
|
|
184
|
+
pr_dir = cfg.evaluation._precision_recall_dir
|
|
185
|
+
if os.path.isdir(pr_dir):
|
|
186
|
+
for f in os.listdir(pr_dir):
|
|
187
|
+
for prefix in _EPOCH_FILE_PREFIXES:
|
|
188
|
+
if f.startswith(prefix + "model_epoch_") and not f.endswith((".png", ".svg")):
|
|
189
|
+
epoch = os.path.splitext(f[len(prefix) :])[0]
|
|
190
|
+
if epoch not in keep:
|
|
191
|
+
_rm(os.path.join(pr_dir, f))
|
|
192
|
+
|
|
193
|
+
log(f"Pruned per-epoch outputs except {sorted(keep)}: freed {freed / 1e9:.2f} GB")
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Process tags of R-Caid (Goyal et al., IEEE S&P 2024, Section 4.3).
|
|
2
|
+
|
|
3
|
+
R-Caid annotates each process with a tag, "the process name" extracted from "the file path to
|
|
4
|
+
its binary executable", and trains its GNN to predict it. So that the tag does not appear in the
|
|
5
|
+
node features, the process name is truncated from the path of the process before computing its
|
|
6
|
+
features.
|
|
7
|
+
|
|
8
|
+
Process labels are made of the attributes of `construction.node_label_features.subject`
|
|
9
|
+
joined by spaces, starting with the path of the executable (e.g. `path, cmd_line`):
|
|
10
|
+
`/bin/dash /bin/sh -e script` (THEIA) or `None sleep` (CADETS, whose processes have no path).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
_NULL = ("", "None", "none", "null")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _path_and_rest(label):
|
|
19
|
+
label = (label or "").strip()
|
|
20
|
+
if not label:
|
|
21
|
+
return "", ""
|
|
22
|
+
path, _, rest = label.partition(" ")
|
|
23
|
+
return path, rest.strip()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def process_tag(label):
|
|
27
|
+
"""Name of the executable of a process: the basename of its path, or, without path, of the
|
|
28
|
+
first word of the rest of its label (e.g. its command line)."""
|
|
29
|
+
path, rest = _path_and_rest(label)
|
|
30
|
+
if path in _NULL:
|
|
31
|
+
path = rest.split(" ")[0] if rest else ""
|
|
32
|
+
if path in _NULL:
|
|
33
|
+
return ""
|
|
34
|
+
return os.path.basename(path.replace("\\", "/").rstrip("/")) or path
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def truncate_process_name(label):
|
|
38
|
+
"""Features label of a process: the directory of its executable, without its name nor the
|
|
39
|
+
rest of its label (which usually repeats the name, e.g. in the command line)."""
|
|
40
|
+
path, _ = _path_and_rest(label)
|
|
41
|
+
if path in _NULL:
|
|
42
|
+
return ""
|
|
43
|
+
path = path.replace("\\", "/").rstrip("/")
|
|
44
|
+
return path.rsplit("/", 1)[0] + "/" if "/" in path else ""
|