pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -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 +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -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 +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -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 +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -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 +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -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 +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -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 +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -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 +275 -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/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 +126 -0
- pidsmaker/resources/config/orthrus_fixed.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/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/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -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/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -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-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Detection rule of FLASH (Rehman et al., IEEE S&P 2024).
|
|
2
|
+
|
|
3
|
+
In the original code (Flash-IDS, E3 notebooks), the GNN outputs softmax probabilities over the
|
|
4
|
+
node types, and the confidence of a node is the relative gap between its two highest
|
|
5
|
+
probabilities, min-max normalized over the batch:
|
|
6
|
+
|
|
7
|
+
conf = (p1 - p2) / p1; conf = (conf - conf.min()) / conf.max()
|
|
8
|
+
|
|
9
|
+
A node is benign if the GNN predicts its type correctly with a confidence above a threshold
|
|
10
|
+
(0.53 on THEIA), and is flagged otherwise.
|
|
11
|
+
|
|
12
|
+
PIDSMaker ranks nodes by a score, so the rule is turned into an anomaly score that increases
|
|
13
|
+
when the node looks less benign: `1 - conf` for a correct prediction and `1 + conf` for a wrong
|
|
14
|
+
one (a confidently wrong prediction is the most anomalous). A node is flagged by the original
|
|
15
|
+
rule iff its score is at least `1 - threshold`.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import torch
|
|
20
|
+
|
|
21
|
+
from pidsmaker.detection.node_scoring import NodeScorer
|
|
22
|
+
from pidsmaker.objectives.predict_node_type import NODE_LOSS_MASK_KEY
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def flash_confidence(probs, eps=1e-6):
|
|
26
|
+
"""Normalized confidence of each row of `probs` (N, C) and the predicted classes."""
|
|
27
|
+
top2, indices = probs.topk(2, dim=1)
|
|
28
|
+
conf = (top2[:, 0] - top2[:, 1]) / (top2[:, 0] + eps)
|
|
29
|
+
conf_max = conf.max() if conf.numel() else conf.new_zeros(())
|
|
30
|
+
if conf_max > 0:
|
|
31
|
+
conf = (conf - conf.min()) / conf_max
|
|
32
|
+
return conf.clamp(min=0), indices[:, 0]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def flash_anomaly_score(probs, node_type_idx):
|
|
36
|
+
"""Anomaly score of each node (see the module docstring) and whether its type is predicted
|
|
37
|
+
correctly."""
|
|
38
|
+
conf, pred = flash_confidence(probs)
|
|
39
|
+
correct = pred == node_type_idx
|
|
40
|
+
score = torch.where(correct, 1 - conf, 1 + conf)
|
|
41
|
+
return score, correct
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def flash_flags(score, threshold):
|
|
45
|
+
"""Original rule: a node is flagged unless it is correctly predicted with conf > threshold."""
|
|
46
|
+
return score >= 1 - threshold
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def flash_drop_learned(probs, node_type_idx, drop_conf):
|
|
50
|
+
"""Training nodes that FLASH removes after an epoch: those whose type is predicted correctly,
|
|
51
|
+
or predicted with a confidence of at least `drop_conf` (`(pred == y) | (conf >= 0.9)` in the
|
|
52
|
+
CADETS and THEIA notebooks)."""
|
|
53
|
+
conf, pred = flash_confidence(probs)
|
|
54
|
+
return (pred == node_type_idx) | (conf >= drop_conf)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class FlashSnapshotEnsemble:
|
|
58
|
+
"""The sequence of GNN snapshots of FLASH.
|
|
59
|
+
|
|
60
|
+
In the original code, the GNN is trained for N rounds (22 on CADETS, 20 on THEIA). Each
|
|
61
|
+
round trains on the training nodes that are still misclassified, then removes the nodes it
|
|
62
|
+
learned (see `flash_drop_learned`), and saves the model. At test time, a node is benign if
|
|
63
|
+
any of the N snapshots predicts its type correctly with a confidence above the threshold.
|
|
64
|
+
|
|
65
|
+
Here, a round is an epoch over the training graphs: the remaining nodes of each graph are
|
|
66
|
+
stored in the CPU graph (`NODE_LOSS_MASK_KEY`) and only them contribute to the loss, and the
|
|
67
|
+
score of a node at inference is the minimum of its `flash_anomaly_score` over the snapshots
|
|
68
|
+
of the epochs trained so far (so it is flagged iff no snapshot is confidently correct).
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, drop_conf):
|
|
72
|
+
self.drop_conf = drop_conf
|
|
73
|
+
self.states = []
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _state(model):
|
|
77
|
+
return {k: v.detach().clone() for k, v in model.state_dict().items()}
|
|
78
|
+
|
|
79
|
+
@torch.no_grad()
|
|
80
|
+
def after_epoch(self, model, train_data, device):
|
|
81
|
+
from pidsmaker.utils.data_utils import batch_to_device
|
|
82
|
+
from pidsmaker.utils.utils import log
|
|
83
|
+
|
|
84
|
+
self.states.append(self._state(model))
|
|
85
|
+
was_training = model.training
|
|
86
|
+
model.eval()
|
|
87
|
+
remaining, total = 0, 0
|
|
88
|
+
for dataset in train_data:
|
|
89
|
+
for g in dataset:
|
|
90
|
+
mask = getattr(g, NODE_LOSS_MASK_KEY, None)
|
|
91
|
+
if mask is None or mask.any():
|
|
92
|
+
# The node features and types may only be built on the device copy
|
|
93
|
+
batch = batch_to_device(g, device)
|
|
94
|
+
out = model(batch, inference=True)["out"]
|
|
95
|
+
drop = flash_drop_learned(out.exp(), batch.node_type.argmax(1), self.drop_conf)
|
|
96
|
+
mask = ~drop.cpu() if mask is None else mask & ~drop.cpu()
|
|
97
|
+
setattr(g, NODE_LOSS_MASK_KEY, mask)
|
|
98
|
+
remaining += int(mask.sum())
|
|
99
|
+
total += mask.numel()
|
|
100
|
+
model.train(was_training)
|
|
101
|
+
log(f"FLASH round {len(self.states) - 1}: {remaining}/{total} training nodes still misclassified")
|
|
102
|
+
|
|
103
|
+
@torch.no_grad()
|
|
104
|
+
def score(self, model, data, current_score):
|
|
105
|
+
"""Minimum anomaly score over the snapshots. `current_score` is the score given by the
|
|
106
|
+
current weights of `model`, which are restored."""
|
|
107
|
+
if len(self.states) <= 1:
|
|
108
|
+
return current_score
|
|
109
|
+
current = self._state(model)
|
|
110
|
+
node_type_idx = data.node_type.argmax(1)
|
|
111
|
+
best = current_score
|
|
112
|
+
for state in self.states[:-1]: # the last snapshot holds the current weights
|
|
113
|
+
model.load_state_dict(state)
|
|
114
|
+
out = model(data, inference=True)["out"]
|
|
115
|
+
best = torch.minimum(best, flash_anomaly_score(out.exp(), node_type_idx)[0])
|
|
116
|
+
model.load_state_dict(current)
|
|
117
|
+
return best
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def flash_snapshot_ensemble(cfg):
|
|
121
|
+
"""The `FlashSnapshotEnsemble` trained by the training loop, or None when the model is not
|
|
122
|
+
FLASH's with snapshots (`predict_node_type.flash_snapshots` and `threshold_method: flash`)."""
|
|
123
|
+
node_type_cfg = getattr(cfg.training.decoder, "predict_node_type", None)
|
|
124
|
+
if (
|
|
125
|
+
cfg._is_node_level
|
|
126
|
+
and cfg.evaluation.node_evaluation.threshold_method == "flash"
|
|
127
|
+
and node_type_cfg is not None
|
|
128
|
+
and node_type_cfg.flash_snapshots
|
|
129
|
+
):
|
|
130
|
+
return FlashSnapshotEnsemble(drop_conf=node_type_cfg.flash_drop_conf)
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class FlashScorer(NodeScorer):
|
|
135
|
+
"""Writes the `flash_score` of the nodes, thresholded by `threshold_method: flash`, and
|
|
136
|
+
whether their type is predicted correctly. With snapshots, the score is the minimum over
|
|
137
|
+
the snapshots of the model's `flash_ensemble`."""
|
|
138
|
+
|
|
139
|
+
score_column = "flash_score"
|
|
140
|
+
|
|
141
|
+
def columns(self, model, data, results, split, node, loss):
|
|
142
|
+
# `out` holds log-probabilities: the confidence of FLASH is computed on probabilities
|
|
143
|
+
score, correct = flash_anomaly_score(results["out"].exp(), data.node_type.argmax(1))
|
|
144
|
+
ensemble = getattr(model, "flash_ensemble", None)
|
|
145
|
+
if ensemble is not None:
|
|
146
|
+
score = ensemble.score(model, data, score)
|
|
147
|
+
return {
|
|
148
|
+
"node": node,
|
|
149
|
+
"loss": loss,
|
|
150
|
+
"flash_score": score.cpu().numpy().astype(float),
|
|
151
|
+
"correct_pred": correct.long().cpu().numpy(),
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
def node_prediction(self, values, thr):
|
|
155
|
+
# The node is flagged if, in one of its time windows, it is not predicted correctly
|
|
156
|
+
# with a confidence above the threshold
|
|
157
|
+
scores = values["flash_score"]
|
|
158
|
+
tw_max = int(np.argmax(scores))
|
|
159
|
+
pred_score = scores[tw_max]
|
|
160
|
+
if flash_flags(np.float64(pred_score), thr):
|
|
161
|
+
return pred_score, True, values["tw"][tw_max]
|
|
162
|
+
return pred_score, False, None
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""MAGIC's detection module: k-nearest-neighbour outlier detection on node embeddings.
|
|
2
|
+
|
|
3
|
+
As in the original MAGIC (Jia et al., USENIX Security 2024, `model/eval.py`), the embeddings of
|
|
4
|
+
the benign training graphs form the reference set. Embeddings are standardized with the mean and
|
|
5
|
+
standard deviation of the reference set, and the anomaly score of a node is its mean Euclidean
|
|
6
|
+
distance to its k nearest benign neighbours divided by the mean k-NN distance of benign nodes.
|
|
7
|
+
A score of ~1 is as typical as a training node; outliers score well above 1.
|
|
8
|
+
|
|
9
|
+
The search is an exact brute-force search on the device of the reference set, by chunks. Many
|
|
10
|
+
training nodes share the exact same embedding (same type, same neighbourhood), so the reference
|
|
11
|
+
set is stored once per distinct embedding with its multiplicity: the k nearest distinct
|
|
12
|
+
embeddings always hold the k nearest nodes, and the k-NN distances are recovered exactly.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
|
|
19
|
+
from pidsmaker.detection.node_scoring import NodeScorer
|
|
20
|
+
from pidsmaker.utils.utils import log
|
|
21
|
+
|
|
22
|
+
# MAGIC estimates the mean k-NN distance of the reference set on at most 50,000 of its nodes
|
|
23
|
+
MEAN_DISTANCE_SAMPLE = 50_000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MagicKNNDetector:
|
|
27
|
+
def __init__(self, k=10, max_reference_size=None, chunk_elems=2**28, seed=0):
|
|
28
|
+
"""
|
|
29
|
+
Args:
|
|
30
|
+
k: number of nearest neighbours (10 in the MAGIC paper).
|
|
31
|
+
max_reference_size: if set, the reference set is a uniform random sample of at most
|
|
32
|
+
this many training embeddings, to bound the cost of the search.
|
|
33
|
+
chunk_elems: max number of query-reference distances computed at once.
|
|
34
|
+
seed: seed of the sampling of the reference set.
|
|
35
|
+
"""
|
|
36
|
+
self.k = k
|
|
37
|
+
self.max_reference_size = max_reference_size
|
|
38
|
+
self.chunk_elems = chunk_elems
|
|
39
|
+
self.seed = seed
|
|
40
|
+
self.reference = None # distinct standardized embeddings (U, d)
|
|
41
|
+
self.counts = None # multiplicity of each distinct embedding (U,)
|
|
42
|
+
self.num_reference_nodes = 0
|
|
43
|
+
self.mean = None
|
|
44
|
+
self.std = None
|
|
45
|
+
self.mean_distance = None
|
|
46
|
+
|
|
47
|
+
def fit(self, x_train: torch.Tensor):
|
|
48
|
+
"""Fits the detector on the embeddings of benign training nodes (N, d)."""
|
|
49
|
+
x_train = x_train.float()
|
|
50
|
+
gen = torch.Generator(device="cpu").manual_seed(self.seed)
|
|
51
|
+
if self.max_reference_size and x_train.shape[0] > self.max_reference_size:
|
|
52
|
+
idx = torch.randperm(x_train.shape[0], generator=gen)[: self.max_reference_size]
|
|
53
|
+
x_train = x_train[idx.to(x_train.device)]
|
|
54
|
+
|
|
55
|
+
self.mean = x_train.mean(dim=0)
|
|
56
|
+
# Constant dimensions (e.g. dead units) would divide by zero
|
|
57
|
+
self.std = x_train.std(dim=0, unbiased=False).clamp_min(1e-6)
|
|
58
|
+
x_train = (x_train - self.mean) / self.std
|
|
59
|
+
self.num_reference_nodes = x_train.shape[0]
|
|
60
|
+
|
|
61
|
+
self.reference, inverse, self.counts = torch.unique(
|
|
62
|
+
x_train, dim=0, return_inverse=True, return_counts=True
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
n = x_train.shape[0]
|
|
66
|
+
sample = torch.randperm(n, generator=gen)[: min(MEAN_DISTANCE_SAMPLE, n)]
|
|
67
|
+
# As in MAGIC, the sampled training nodes are part of the reference set: their nearest
|
|
68
|
+
# neighbour is themselves, at distance 0
|
|
69
|
+
dists = self._knn_mean_distance(self.reference[inverse[sample.to(inverse.device)]])
|
|
70
|
+
mean_distance = dists.mean().item()
|
|
71
|
+
self.mean_distance = mean_distance if mean_distance > 0 else 1e-9
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
@torch.no_grad()
|
|
75
|
+
def _knn_mean_distance(self, queries: torch.Tensor) -> torch.Tensor:
|
|
76
|
+
"""Mean distance of each (standardized) query to its k nearest reference nodes."""
|
|
77
|
+
ref, counts = self.reference, self.counts
|
|
78
|
+
k = min(self.k, self.num_reference_nodes)
|
|
79
|
+
k_distinct = min(k, ref.shape[0])
|
|
80
|
+
chunk = max(1, self.chunk_elems // max(1, ref.shape[0]))
|
|
81
|
+
ref_sq = (ref * ref).sum(dim=1)
|
|
82
|
+
out = []
|
|
83
|
+
for i in range(0, queries.shape[0], chunk):
|
|
84
|
+
q = queries[i : i + chunk]
|
|
85
|
+
# ||q - r||^2 = ||q||^2 - 2 q.r + ||r||^2, clamped against negative rounding errors
|
|
86
|
+
d2 = torch.addmm(ref_sq.unsqueeze(0), q, ref.T, alpha=-2)
|
|
87
|
+
d2 += (q * q).sum(dim=1, keepdim=True)
|
|
88
|
+
top = torch.topk(d2, k_distinct, dim=1, largest=False, sorted=True)
|
|
89
|
+
del d2
|
|
90
|
+
dist = top.values.clamp_min(0).sqrt()
|
|
91
|
+
# Expands the distinct neighbours by their multiplicity, up to k nodes
|
|
92
|
+
c = counts[top.indices]
|
|
93
|
+
before = c.cumsum(dim=1) - c
|
|
94
|
+
take = (k - before).clamp(min=0) - (k - before - c).clamp(min=0)
|
|
95
|
+
out.append((dist * take).sum(dim=1) / k)
|
|
96
|
+
if not out:
|
|
97
|
+
return torch.zeros(0, device=ref.device)
|
|
98
|
+
return torch.cat(out)
|
|
99
|
+
|
|
100
|
+
@torch.no_grad()
|
|
101
|
+
def score(self, x: torch.Tensor) -> torch.Tensor:
|
|
102
|
+
"""Anomaly score of each node embedding (N, d) -> (N,)."""
|
|
103
|
+
if self.reference is None:
|
|
104
|
+
raise RuntimeError("MagicKNNDetector must be fitted on benign embeddings first.")
|
|
105
|
+
x = x.float().to(self.reference.device)
|
|
106
|
+
# Identical test embeddings get the same score: each one is searched once
|
|
107
|
+
x, inverse = torch.unique(x, dim=0, return_inverse=True)
|
|
108
|
+
x = (x - self.mean) / self.std
|
|
109
|
+
return (self._knn_mean_distance(x) / self.mean_distance)[inverse]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def magic_detection_embedding(model, h, cfg=None):
|
|
113
|
+
"""Node embedding scored by MAGIC's k-NN detector: the last encoder layer (`last`, the
|
|
114
|
+
original code) or all the concatenated layers (`concat`, the paper)."""
|
|
115
|
+
mode = (cfg.evaluation.node_evaluation.magic_embedding if cfg is not None else None) or "last"
|
|
116
|
+
if mode == "last" and hasattr(model.encoder, "detection_embedding"):
|
|
117
|
+
return model.encoder.detection_embedding(h)
|
|
118
|
+
return h
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@torch.no_grad()
|
|
122
|
+
def fit_magic_detector(cfg, model, train_data, device):
|
|
123
|
+
"""Fits MAGIC's k-NN detector on the embeddings of the benign training nodes."""
|
|
124
|
+
from pidsmaker.detection.training_methods.training_loop import to_device_without_attacks
|
|
125
|
+
|
|
126
|
+
model.eval()
|
|
127
|
+
s = time.time()
|
|
128
|
+
embs = []
|
|
129
|
+
for dataset in train_data:
|
|
130
|
+
for g in dataset:
|
|
131
|
+
g = to_device_without_attacks(g, cfg, device)
|
|
132
|
+
h, *_ = model.embed(g, inference=True)
|
|
133
|
+
embs.append(magic_detection_embedding(model, h, cfg).float())
|
|
134
|
+
del g
|
|
135
|
+
x_train = torch.cat(embs)
|
|
136
|
+
del embs
|
|
137
|
+
node_eval = cfg.evaluation.node_evaluation
|
|
138
|
+
detector = MagicKNNDetector(
|
|
139
|
+
k=node_eval.magic_knn_k or 10,
|
|
140
|
+
max_reference_size=node_eval.magic_max_reference_size or None,
|
|
141
|
+
seed=cfg.training.seed or 0,
|
|
142
|
+
).fit(x_train)
|
|
143
|
+
log(
|
|
144
|
+
f"MAGIC k-NN detector fitted on {detector.num_reference_nodes:,} of {x_train.shape[0]:,} "
|
|
145
|
+
f"benign training node embeddings ({detector.reference.shape[0]:,} distinct, "
|
|
146
|
+
f"k={detector.k}, mean distance "
|
|
147
|
+
f"{detector.mean_distance:.4f}) in {time.time() - s:.1f}s"
|
|
148
|
+
)
|
|
149
|
+
return detector
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class MagicScorer(NodeScorer):
|
|
153
|
+
"""Writes the `magic_score` of the test nodes, thresholded by `threshold_method: magic`: the
|
|
154
|
+
k-NN distance of their embeddings to those of the benign training nodes."""
|
|
155
|
+
|
|
156
|
+
score_column = "magic_score"
|
|
157
|
+
|
|
158
|
+
def __init__(self, cfg):
|
|
159
|
+
super().__init__(cfg)
|
|
160
|
+
self.detector = None
|
|
161
|
+
|
|
162
|
+
def prepare(self, model, train_data, split_names, device):
|
|
163
|
+
if "test" in split_names:
|
|
164
|
+
if train_data is None:
|
|
165
|
+
raise ValueError("MAGIC detection requires the train split as k-NN reference set.")
|
|
166
|
+
self.detector = fit_magic_detector(self.cfg, model, train_data, device)
|
|
167
|
+
|
|
168
|
+
def columns(self, model, data, results, split, node, loss):
|
|
169
|
+
if split != "test":
|
|
170
|
+
return {"node": node, "loss": loss}
|
|
171
|
+
if self.detector is None:
|
|
172
|
+
raise ValueError("MAGIC detection requires a detector fitted on the train split.")
|
|
173
|
+
x_test, *_ = model.embed(data, inference=True)
|
|
174
|
+
score = self.detector.score(magic_detection_embedding(model, x_test, self.cfg))
|
|
175
|
+
return {
|
|
176
|
+
"node": node,
|
|
177
|
+
"magic_score": score.cpu().numpy().astype(float),
|
|
178
|
+
"loss": loss,
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
def node_prediction(self, values, thr):
|
|
182
|
+
# Detected in the first time window of max score, if above the threshold
|
|
183
|
+
max_score = 0
|
|
184
|
+
pred_score = max(values["magic_score"])
|
|
185
|
+
detected_tw = None
|
|
186
|
+
for score, tw in zip(values["magic_score"], values["tw"]):
|
|
187
|
+
if score > thr and score > max_score:
|
|
188
|
+
max_score = score
|
|
189
|
+
detected_tw = tw
|
|
190
|
+
return pred_score, pred_score > thr, detected_tw
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Node scores of node-level objectives, written at inference and thresholded at evaluation.
|
|
2
|
+
|
|
3
|
+
The inference loop (`training_methods.inference_loop.test_node_level`) writes one loss file per
|
|
4
|
+
batch, with the columns given by a `NodeScorer`, and the node evaluation
|
|
5
|
+
(`evaluation_methods.node_evaluation`) flags each node from its values in these files. The default
|
|
6
|
+
scorer writes the node losses, reduced to a score per node by `reduce_losses_to_score`. The
|
|
7
|
+
threshold methods of ThreaTrace, FLASH and MAGIC rank the nodes by scores of their own, computed
|
|
8
|
+
by their subclass in their module (see `node_scorer_factory` in `pidsmaker.factory`).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NodeScorer:
|
|
13
|
+
# Column of the loss files holding the scores of the nodes (None: the node losses)
|
|
14
|
+
score_column = None
|
|
15
|
+
|
|
16
|
+
def __init__(self, cfg):
|
|
17
|
+
self.cfg = cfg
|
|
18
|
+
|
|
19
|
+
def prepare(self, model, train_data, split_names, device):
|
|
20
|
+
"""Called once before the inference of the splits `split_names` (e.g. to fit a
|
|
21
|
+
detector on the training data)."""
|
|
22
|
+
|
|
23
|
+
def columns(self, model, data, results, split, node, loss):
|
|
24
|
+
"""The columns of the loss file of the batch `data`.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
model: the model, in eval mode.
|
|
28
|
+
data: the batch, on the device.
|
|
29
|
+
results: the output of `model(data, inference=True)`.
|
|
30
|
+
split: the name of the split of the batch.
|
|
31
|
+
node: the original node IDs of the batch (NumPy).
|
|
32
|
+
loss: the node losses (NumPy, float64).
|
|
33
|
+
"""
|
|
34
|
+
return {"node": node, "loss": loss}
|
|
35
|
+
|
|
36
|
+
def node_prediction(self, values, thr):
|
|
37
|
+
"""The score of a node, whether it is flagged with the threshold `thr`, and the index of
|
|
38
|
+
the time window in which it is detected (None: that of its max loss).
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
values: the values of the node in each column of the loss files of the test split,
|
|
42
|
+
over its time windows, whose indices are in `tw`.
|
|
43
|
+
thr: the threshold of the threshold method.
|
|
44
|
+
"""
|
|
45
|
+
# Imported here: `evaluation_methods` imports the factory, which imports the scorers
|
|
46
|
+
from pidsmaker.detection.evaluation_methods.evaluation_utils import reduce_losses_to_score
|
|
47
|
+
|
|
48
|
+
pred_score = reduce_losses_to_score(
|
|
49
|
+
values["loss"],
|
|
50
|
+
self.cfg.evaluation.node_evaluation.threshold_method,
|
|
51
|
+
)
|
|
52
|
+
return pred_score, pred_score > thr, None
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Detection rule of ThreaTrace (Wang et al., TIFS 2022, `test_darpatc.py`).
|
|
2
|
+
|
|
3
|
+
A node is anomalous when no submodel predicts its type with a top-1 / top-2 probability ratio of
|
|
4
|
+
at least `ratio_threshold`. The submodels are trained by
|
|
5
|
+
`training_methods.threatrace_training`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from pidsmaker.detection.node_scoring import NodeScorer
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def threatrace_log_ratio(log_probs, node_type):
|
|
17
|
+
"""log(p_true / max_{c != true} p_c) per node, from log-probabilities (N, C).
|
|
18
|
+
|
|
19
|
+
ThreaTrace explains a node when its type is predicted with a top-1 / top-2 probability
|
|
20
|
+
ratio of at least `thre`. This is equivalent to `ratio >= thre` with the ratio above: when
|
|
21
|
+
the prediction is right it is the top-1 / top-2 ratio, and when it is wrong it is <= 1.
|
|
22
|
+
"""
|
|
23
|
+
log_p_true = log_probs.gather(1, node_type.unsqueeze(1)).squeeze(1)
|
|
24
|
+
others = log_probs.scatter(1, node_type.unsqueeze(1), float("-inf"))
|
|
25
|
+
return log_p_true - others.max(dim=1).values
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def threatrace_anomaly_score(outs, node_type, ratio_threshold):
|
|
29
|
+
"""ThreaTrace's anomaly score, positive iff the node is anomalous.
|
|
30
|
+
|
|
31
|
+
A node is anomalous when no submodel predicts its type with a probability ratio of at least
|
|
32
|
+
`ratio_threshold` (test_darpatc.py). The score is
|
|
33
|
+
`log(ratio_threshold) - max_k log(p_true / max_{c != true} p_c)` over the submodels `outs`
|
|
34
|
+
(log-probabilities), so that anomalous nodes are exactly those with a score > 0, and nodes
|
|
35
|
+
whose type is the least well predicted rank first.
|
|
36
|
+
"""
|
|
37
|
+
best = torch.stack([threatrace_log_ratio(out, node_type) for out in outs]).max(dim=0).values
|
|
38
|
+
return math.log(ratio_threshold) - best
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ThreaTraceScorer(NodeScorer):
|
|
42
|
+
"""Writes the `threatrace_score` of the nodes, thresholded by `threshold_method: threatrace`."""
|
|
43
|
+
|
|
44
|
+
score_column = "threatrace_score"
|
|
45
|
+
|
|
46
|
+
def columns(self, model, data, results, split, node, loss):
|
|
47
|
+
# One output per submodel (ThreaTrace's multi-model scheme), or the single model's
|
|
48
|
+
outs = results.get("outs", [results["out"]])
|
|
49
|
+
score = threatrace_anomaly_score(
|
|
50
|
+
outs, data.node_type.argmax(1), self.cfg.training.threatrace.ratio_threshold
|
|
51
|
+
)
|
|
52
|
+
return {
|
|
53
|
+
"node": node,
|
|
54
|
+
"loss": loss,
|
|
55
|
+
"threatrace_score": score.cpu().numpy().astype(float),
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
def node_prediction(self, values, thr):
|
|
59
|
+
# The score is positive iff no submodel explains the node's type in that
|
|
60
|
+
# time window (see `threatrace_anomaly_score`): a node is detected if it is
|
|
61
|
+
# anomalous in any time window, the one with the highest score being kept.
|
|
62
|
+
scores = values["threatrace_score"]
|
|
63
|
+
best = int(np.argmax(scores))
|
|
64
|
+
pred_score = scores[best]
|
|
65
|
+
return pred_score, pred_score > thr, values["tw"][best]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import inference_loop, training_loop
|