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,165 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
from sklearn.metrics import average_precision_score, roc_auc_score
|
|
5
|
+
|
|
6
|
+
NEG_SAMPLING_METHODS = ["shuffle_dst", "uniform", "uniform_dst", "tgn"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class EdgeContrastivePrediction(nn.Module):
|
|
10
|
+
"""Link prediction: edges of the graph (positives) are contrasted with random negative edges.
|
|
11
|
+
|
|
12
|
+
Negative sampling (`neg_sampling`):
|
|
13
|
+
- `shuffle_dst`: each source is paired with the destination of another edge, so negatives
|
|
14
|
+
keep the degree distribution of destinations. On graphs where most edges go to a few
|
|
15
|
+
hubs (e.g. authentications to domain controllers in LANL), negatives never contain
|
|
16
|
+
edges to other nodes, which the model then learns to consider likely.
|
|
17
|
+
- `uniform`: sources and destinations are drawn uniformly among the nodes embedded by the
|
|
18
|
+
encoder (all the nodes of the dataset when the encoder embeds them all, see
|
|
19
|
+
`node_id_embedding.all_nodes`), `neg_ratio` negatives per positive, as in Euler and Argus.
|
|
20
|
+
- `uniform_dst`: the source of each positive edge is paired with destinations drawn uniformly
|
|
21
|
+
among the embedded nodes (`neg_ratio` per positive).
|
|
22
|
+
- `tgn`: the source of each edge is paired with a destination drawn uniformly among the
|
|
23
|
+
destinations of the dataset and embedded by the TGN with the edges of the batch, as in TGN
|
|
24
|
+
and Jbeil (requires `tgn_last_neighbor.negative_destinations`).
|
|
25
|
+
|
|
26
|
+
Each negative edge is paired with a positive edge (that of its source, except with `uniform`),
|
|
27
|
+
which pairwise losses such as `bpr` (ShadeWatcher) compare it to.
|
|
28
|
+
|
|
29
|
+
At validation, the AUC and AP of validation edges against uniform negatives measure how well
|
|
30
|
+
the model predicts links (`get_val_score`, used by `best_model_selection: best_val_score`).
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, decoder, loss_fn, graph_reindexer, neg_sampling="shuffle_dst", neg_ratio=1.0):
|
|
34
|
+
super().__init__()
|
|
35
|
+
|
|
36
|
+
if neg_sampling not in NEG_SAMPLING_METHODS:
|
|
37
|
+
raise ValueError(f"Invalid neg_sampling {neg_sampling}, expected one of {NEG_SAMPLING_METHODS}")
|
|
38
|
+
self.decoder = decoder
|
|
39
|
+
self.loss_fn = loss_fn
|
|
40
|
+
self.graph_reindexer = graph_reindexer
|
|
41
|
+
self.neg_sampling = neg_sampling
|
|
42
|
+
self.neg_ratio = neg_ratio
|
|
43
|
+
self._val_pos, self._val_neg = [], []
|
|
44
|
+
|
|
45
|
+
def _node_tables(self, edge_index, h, h_src, h_dst):
|
|
46
|
+
"""Node embedding tables (src, dst) indexed by `edge_index`."""
|
|
47
|
+
if isinstance(h, torch.Tensor) and h.dim() == 2 and int(edge_index.max()) < h.size(0):
|
|
48
|
+
return h, h, edge_index
|
|
49
|
+
(h_src, h_dst), edge_index, _ = self.graph_reindexer._reindex_graph(
|
|
50
|
+
edge_index, h_src, h_dst, x_is_tuple=True
|
|
51
|
+
)
|
|
52
|
+
return h_src, h_dst, edge_index
|
|
53
|
+
|
|
54
|
+
def _uniform_negative_sampling(
|
|
55
|
+
self, edge_index, h, h_src, h_dst, ratio, keep_src=False, return_pos_index=False
|
|
56
|
+
):
|
|
57
|
+
table_src, table_dst, edge_index = self._node_tables(edge_index, h, h_src, h_dst)
|
|
58
|
+
num_nodes = table_src.size(0)
|
|
59
|
+
num_neg = max(1, int(round(edge_index.size(1) * ratio)))
|
|
60
|
+
if keep_src:
|
|
61
|
+
idx = torch.arange(num_neg, device=edge_index.device) % edge_index.size(1)
|
|
62
|
+
src = edge_index[0, idx].long()
|
|
63
|
+
else:
|
|
64
|
+
src = torch.randint(0, num_nodes, (num_neg,), device=edge_index.device)
|
|
65
|
+
dst = torch.randint(0, num_nodes, (num_neg,), device=edge_index.device)
|
|
66
|
+
pos_hash = edge_index[0].long() * num_nodes + edge_index[1].long()
|
|
67
|
+
keep = (src != dst) & ~torch.isin(src * num_nodes + dst, pos_hash)
|
|
68
|
+
if not keep.any(): # e.g. tiny graphs: keep the drawn edges rather than no negative
|
|
69
|
+
keep = torch.ones_like(keep)
|
|
70
|
+
neg_h_src, neg_h_dst = table_src[src[keep]], table_dst[dst[keep]]
|
|
71
|
+
if not return_pos_index:
|
|
72
|
+
return neg_h_src, neg_h_dst
|
|
73
|
+
# Positive edge paired with each negative (that of its source with `keep_src`)
|
|
74
|
+
pos_index = torch.arange(num_neg, device=edge_index.device) % edge_index.size(1)
|
|
75
|
+
return neg_h_src, neg_h_dst, pos_index[keep]
|
|
76
|
+
|
|
77
|
+
def _fast_negative_sampling(self, edge_index, h_src, h_dst, aug_coef=1.0, return_pos_index=False):
|
|
78
|
+
(h_src, h_dst), edge_index, _ = self.graph_reindexer._reindex_graph(
|
|
79
|
+
edge_index, h_src, h_dst, x_is_tuple=True
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
neg_dst_idx = torch.randperm(
|
|
83
|
+
len(edge_index[0])
|
|
84
|
+
) # TODO: we may want to try also putting source nodes in the neg dst nodes
|
|
85
|
+
neg_dst = edge_index[1, neg_dst_idx]
|
|
86
|
+
neg_ei = torch.stack([edge_index[0], neg_dst])
|
|
87
|
+
|
|
88
|
+
num_nodes = (edge_index.max() + 1).item()
|
|
89
|
+
el_hash = lambda x: x[0, :] + x[1, :] * num_nodes
|
|
90
|
+
el1d = el_hash(edge_index)
|
|
91
|
+
|
|
92
|
+
# Positive edge paired with each negative (that of its source)
|
|
93
|
+
pos_index = torch.arange(neg_ei.size(1), device=neg_ei.device)
|
|
94
|
+
no_loop = neg_ei[0] != neg_ei[1]
|
|
95
|
+
neg_ei, pos_index = neg_ei[:, no_loop], pos_index[no_loop] # remove self-loops
|
|
96
|
+
neg_hash = el_hash(neg_ei)
|
|
97
|
+
|
|
98
|
+
no_collision = ~torch.isin(neg_hash, el1d) # remove collision edges in positive edges
|
|
99
|
+
neg_samples, pos_index = neg_ei[:, no_collision], pos_index[no_collision]
|
|
100
|
+
|
|
101
|
+
neg_h_src = h_src[neg_samples[0]]
|
|
102
|
+
neg_h_dst = h_dst[neg_samples[1]]
|
|
103
|
+
|
|
104
|
+
if not return_pos_index:
|
|
105
|
+
return neg_h_src, neg_h_dst
|
|
106
|
+
return neg_h_src, neg_h_dst, pos_index
|
|
107
|
+
|
|
108
|
+
def forward(self, h_src, h_dst, edge_index, inference, h=None, validation=False, batch=None, **kwargs):
|
|
109
|
+
pos_scores = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
110
|
+
h_neg = getattr(batch, "h_neg_tgn", None) if batch is not None else None
|
|
111
|
+
if self.neg_sampling == "tgn" and h_neg is None:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
"neg_sampling=tgn requires the TGN negatives of "
|
|
114
|
+
"`batching.intra_graph_batching.tgn_last_neighbor.negative_destinations`."
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Positive edge paired with each negative edge (by default, the edge of the same index)
|
|
118
|
+
pos_index = None
|
|
119
|
+
if not inference:
|
|
120
|
+
if self.neg_sampling == "tgn":
|
|
121
|
+
neg_h_src, neg_h_dst = h_src, h_neg
|
|
122
|
+
elif self.neg_sampling in ("uniform", "uniform_dst"):
|
|
123
|
+
neg_h_src, neg_h_dst, pos_index = self._uniform_negative_sampling(
|
|
124
|
+
edge_index, h, h_src, h_dst, self.neg_ratio,
|
|
125
|
+
keep_src=self.neg_sampling == "uniform_dst",
|
|
126
|
+
return_pos_index=True,
|
|
127
|
+
)
|
|
128
|
+
else:
|
|
129
|
+
neg_h_src, neg_h_dst, pos_index = self._fast_negative_sampling(
|
|
130
|
+
edge_index, h_src, h_dst, return_pos_index=True
|
|
131
|
+
)
|
|
132
|
+
neg_scores = self.decoder(h_src=neg_h_src, h_dst=neg_h_dst)
|
|
133
|
+
else:
|
|
134
|
+
neg_scores = None
|
|
135
|
+
if validation:
|
|
136
|
+
# Link prediction quality: validation edges vs as many negatives
|
|
137
|
+
if self.neg_sampling == "tgn":
|
|
138
|
+
neg_h_src, neg_h_dst = h_src, h_neg
|
|
139
|
+
else:
|
|
140
|
+
neg_h_src, neg_h_dst = self._uniform_negative_sampling(edge_index, h, h_src, h_dst, 1.0)
|
|
141
|
+
self._val_pos.append(pos_scores.detach().reshape(-1).float().cpu())
|
|
142
|
+
self._val_neg.append(
|
|
143
|
+
self.decoder(h_src=neg_h_src, h_dst=neg_h_dst).detach().reshape(-1).float().cpu()
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# class_weights = compute_class_weights(node_type, num_classes=self.node_type_dim) \
|
|
147
|
+
# if self.balanced_loss else None
|
|
148
|
+
|
|
149
|
+
pairing = {} if pos_index is None else {"pos_index": pos_index}
|
|
150
|
+
loss = self.loss_fn(pos_scores, neg_scores, inference=inference, **pairing)
|
|
151
|
+
if inference:
|
|
152
|
+
# One loss per edge, also for batches of a single edge (`squeeze` would return a scalar)
|
|
153
|
+
loss = loss.reshape(pos_scores.shape[0], -1)
|
|
154
|
+
return {"loss": loss.squeeze(1) if loss.shape[1] == 1 else loss}
|
|
155
|
+
return {"loss": loss.squeeze()}
|
|
156
|
+
|
|
157
|
+
def get_val_score(self):
|
|
158
|
+
"""AUC + AP of the validation edges against uniform negatives (reset after each call)."""
|
|
159
|
+
if not self._val_pos:
|
|
160
|
+
return 0.0
|
|
161
|
+
pos, neg = torch.cat(self._val_pos).numpy(), torch.cat(self._val_neg).numpy()
|
|
162
|
+
self._val_pos, self._val_neg = [], []
|
|
163
|
+
labels = np.r_[np.ones(len(pos)), np.zeros(len(neg))]
|
|
164
|
+
scores = np.r_[pos, neg]
|
|
165
|
+
return float(roc_auc_score(labels, scores) + average_precision_score(labels, scores))
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PredictEdgeSupervised(nn.Module):
|
|
7
|
+
"""Binary supervised edge classification: benign (0) vs attack (1).
|
|
8
|
+
|
|
9
|
+
Input to the decoder per edge: [x_src | edge_type | x_dst | edge_type]
|
|
10
|
+
(edge_type one-hot appended to both node embeddings symmetrically).
|
|
11
|
+
|
|
12
|
+
Uses raw SPIDER node embeddings (batch.x_src, batch.x_dst) directly,
|
|
13
|
+
bypassing the GNN encoder, so that attack features extracted from val/test
|
|
14
|
+
graphs and benign features from training graphs share the same embedding
|
|
15
|
+
space.
|
|
16
|
+
|
|
17
|
+
During training, attack edges are oversampled 1:1 with replacement to match
|
|
18
|
+
the benign batch size. This counters the extreme class imbalance (typically
|
|
19
|
+
O(20) attacks vs O(millions) benign edges) without any modification to the
|
|
20
|
+
data loading pipeline.
|
|
21
|
+
|
|
22
|
+
At inference time, per-edge BCE losses are returned as anomaly scores.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
decoder: nn.Module,
|
|
28
|
+
atk_x_src: torch.Tensor,
|
|
29
|
+
atk_x_dst: torch.Tensor,
|
|
30
|
+
atk_edge_type: torch.Tensor,
|
|
31
|
+
pos_weight: float = 1.0,
|
|
32
|
+
):
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.decoder = decoder
|
|
35
|
+
self.register_buffer("atk_x_src", atk_x_src)
|
|
36
|
+
self.register_buffer("atk_x_dst", atk_x_dst)
|
|
37
|
+
self.register_buffer("atk_edge_type", atk_edge_type)
|
|
38
|
+
self.pos_weight_val = pos_weight
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def _augment(x_src, x_dst, edge_type):
|
|
42
|
+
"""Append edge_type one-hot to both node embeddings."""
|
|
43
|
+
return (
|
|
44
|
+
torch.cat([x_src, edge_type], dim=-1),
|
|
45
|
+
torch.cat([x_dst, edge_type], dim=-1),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def forward(self, edge_type, inference: bool, batch, **kwargs):
|
|
49
|
+
x_src, x_dst = self._augment(batch.x_src, batch.x_dst, batch.edge_type)
|
|
50
|
+
device = x_src.device
|
|
51
|
+
|
|
52
|
+
if inference:
|
|
53
|
+
logits = self.decoder(h_src=x_src, h_dst=x_dst).squeeze(-1)
|
|
54
|
+
scores = F.binary_cross_entropy_with_logits(
|
|
55
|
+
logits, batch.y.float(), reduction="none"
|
|
56
|
+
)
|
|
57
|
+
return {"loss": scores}
|
|
58
|
+
|
|
59
|
+
# Training: oversample attack edges 1:1 with replacement
|
|
60
|
+
n = x_src.shape[0]
|
|
61
|
+
n_atk = self.atk_x_src.shape[0]
|
|
62
|
+
idx = torch.randint(0, n_atk, (n,), device=device)
|
|
63
|
+
atk_src, atk_dst = self._augment(
|
|
64
|
+
self.atk_x_src[idx], self.atk_x_dst[idx], self.atk_edge_type[idx]
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
all_src = torch.cat([x_src, atk_src], dim=0)
|
|
68
|
+
all_dst = torch.cat([x_dst, atk_dst], dim=0)
|
|
69
|
+
labels = torch.cat([
|
|
70
|
+
torch.zeros(n, device=device),
|
|
71
|
+
torch.ones(n, device=device),
|
|
72
|
+
])
|
|
73
|
+
|
|
74
|
+
logits = self.decoder(h_src=all_src, h_dst=all_dst).squeeze(-1)
|
|
75
|
+
pw = torch.tensor([self.pos_weight_val], device=device)
|
|
76
|
+
loss = F.binary_cross_entropy_with_logits(logits, labels, pos_weight=pw)
|
|
77
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import torch.nn as nn
|
|
2
|
+
|
|
3
|
+
from pidsmaker.utils.utils import compute_class_weights
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class EdgeTypePrediction(nn.Module):
|
|
7
|
+
def __init__(self, decoder, loss_fn, balanced_loss, edge_type_dim, multi_edge):
|
|
8
|
+
super(EdgeTypePrediction, self).__init__()
|
|
9
|
+
self.decoder = decoder
|
|
10
|
+
self.loss_fn = loss_fn
|
|
11
|
+
self.balanced_loss = balanced_loss
|
|
12
|
+
self.edge_type_dim = edge_type_dim
|
|
13
|
+
self.multi_edge = multi_edge
|
|
14
|
+
|
|
15
|
+
def forward(self, h_src, h_dst, edge_type, inference, **kwargs):
|
|
16
|
+
h = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
17
|
+
|
|
18
|
+
class_weights = (
|
|
19
|
+
compute_class_weights(edge_type, num_classes=self.edge_type_dim)
|
|
20
|
+
if self.balanced_loss
|
|
21
|
+
else None
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if not self.multi_edge:
|
|
25
|
+
edge_type = edge_type.argmax(dim=1)
|
|
26
|
+
|
|
27
|
+
loss = self.loss_fn(h, edge_type, inference=inference, weight=class_weights)
|
|
28
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from torch_geometric.utils import negative_sampling
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GMAEStructPrediction(nn.Module):
|
|
7
|
+
"""MAGIC's structure reconstruction: an MLP predicts whether node pairs are linked.
|
|
8
|
+
|
|
9
|
+
As in MAGIC, `min(max_samples, num_nodes)` existing edges are sampled uniformly as positives,
|
|
10
|
+
with as many uniform negative pairs. `max_samples=None` (or 0) uses all the edges.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, decoder, loss_fn, max_samples=None):
|
|
14
|
+
super(GMAEStructPrediction, self).__init__()
|
|
15
|
+
self.edge_recon_fc = decoder
|
|
16
|
+
self.loss_fn = loss_fn
|
|
17
|
+
self.max_samples = max_samples
|
|
18
|
+
|
|
19
|
+
def sample_positive_edges(self, edge_index, num_nodes):
|
|
20
|
+
num_edges = edge_index.shape[1]
|
|
21
|
+
if not self.max_samples:
|
|
22
|
+
return edge_index
|
|
23
|
+
n = min(self.max_samples, num_nodes, num_edges)
|
|
24
|
+
if n == num_edges:
|
|
25
|
+
return edge_index
|
|
26
|
+
idx = torch.randperm(num_edges, device=edge_index.device)[:n]
|
|
27
|
+
return edge_index[:, idx]
|
|
28
|
+
|
|
29
|
+
def forward(self, h, edge_index, inference, **kwargs):
|
|
30
|
+
# The structure loss is a training signal only: it does not score nodes
|
|
31
|
+
if inference:
|
|
32
|
+
return {"loss": torch.zeros((h.shape[0],), device=h.device)}
|
|
33
|
+
|
|
34
|
+
pos_edge_index = self.sample_positive_edges(edge_index, h.shape[0])
|
|
35
|
+
neg_edge_index = negative_sampling(
|
|
36
|
+
edge_index, num_nodes=h.shape[0], num_neg_samples=pos_edge_index.shape[1]
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
pos_samples = torch.cat([h[pos_edge_index[0]], h[pos_edge_index[1]]], dim=-1)
|
|
40
|
+
neg_samples = torch.cat([h[neg_edge_index[0]], h[neg_edge_index[1]]], dim=-1)
|
|
41
|
+
|
|
42
|
+
y_pred_pos = self.edge_recon_fc(pos_samples).squeeze(-1)
|
|
43
|
+
y_pred_neg = self.edge_recon_fc(neg_samples).squeeze(-1)
|
|
44
|
+
|
|
45
|
+
y_true = torch.cat([torch.ones_like(y_pred_pos), torch.zeros_like(y_pred_neg)])
|
|
46
|
+
y_pred = torch.cat([y_pred_pos, y_pred_neg])
|
|
47
|
+
|
|
48
|
+
loss = self.loss_fn(y_pred, y_true, inference=inference)
|
|
49
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import torch.nn as nn
|
|
2
|
+
import torch.nn.functional as F
|
|
3
|
+
|
|
4
|
+
from pidsmaker.utils.utils import compute_class_weights
|
|
5
|
+
|
|
6
|
+
# Attribute of a batch holding the boolean mask of the nodes that contribute to the training loss
|
|
7
|
+
NODE_LOSS_MASK_KEY = "node_loss_mask"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NodeTypePrediction(nn.Module):
|
|
11
|
+
def __init__(self, decoder, loss_fn, balanced_loss, node_type_dim):
|
|
12
|
+
super(NodeTypePrediction, self).__init__()
|
|
13
|
+
self.decoder = decoder
|
|
14
|
+
self.loss_fn = loss_fn
|
|
15
|
+
self.balanced_loss = balanced_loss
|
|
16
|
+
self.node_type_dim = node_type_dim
|
|
17
|
+
|
|
18
|
+
def forward(self, h, node_type, inference, batch=None, **kwargs):
|
|
19
|
+
h_hat = self.decoder(h)
|
|
20
|
+
|
|
21
|
+
# During training, the loss can be restricted to some nodes: those that ThreaTrace's
|
|
22
|
+
# previous submodels do not explain yet, or that FLASH still misclassifies
|
|
23
|
+
node_loss_mask = getattr(batch, NODE_LOSS_MASK_KEY, None) if not inference else None
|
|
24
|
+
h_loss, node_type_loss = h_hat, node_type
|
|
25
|
+
if node_loss_mask is not None:
|
|
26
|
+
h_loss, node_type_loss = h_hat[node_loss_mask], node_type[node_loss_mask]
|
|
27
|
+
|
|
28
|
+
class_weights = (
|
|
29
|
+
compute_class_weights(node_type_loss, num_classes=self.node_type_dim)
|
|
30
|
+
if self.balanced_loss
|
|
31
|
+
else None
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
node_type_classes = node_type_loss.argmax(dim=1)
|
|
35
|
+
loss = self.loss_fn(h_loss, node_type_classes, inference=inference, weight=class_weights)
|
|
36
|
+
return {"loss": loss, "out": F.log_softmax(h_hat, dim=1)}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Process tag prediction, the self-supervised objective of R-Caid (IEEE S&P 2024, Section 4.3).
|
|
2
|
+
|
|
3
|
+
Each process is annotated with the name of its executable (see `pidsmaker.utils.process_tags`),
|
|
4
|
+
and the GNN learns to predict it from its neighborhood and its roots: processes with the same
|
|
5
|
+
binary name get close embeddings. Only process nodes are classified (the paper found that
|
|
6
|
+
classifying all the nodes is detrimental); other nodes get a score of 0.
|
|
7
|
+
|
|
8
|
+
The classes are the tags of the processes of the training split, plus an "unknown" class for
|
|
9
|
+
the tags never seen in training, which is never a training target. Processes are scored either
|
|
10
|
+
as in the paper (`detection: kmeans`, see `ProcessTagPrediction`), which does not use the tags,
|
|
11
|
+
or by the loss of their tag (`detection: loss`), where a process running an executable never
|
|
12
|
+
seen in training gets a high loss.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import torch
|
|
17
|
+
import torch.nn as nn
|
|
18
|
+
import torch.nn.functional as F
|
|
19
|
+
|
|
20
|
+
from pidsmaker.utils.process_tags import process_tag
|
|
21
|
+
from pidsmaker.utils.utils import compute_class_weights, get_indexid2msg, get_split2nodes, log
|
|
22
|
+
|
|
23
|
+
PROCESS_TYPE = "subject"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_process_tag_classes(indexid2msg, train_nodes, process_type=PROCESS_TYPE):
|
|
27
|
+
"""(node id -> class array, number of known tags). Classes are numbered in order of
|
|
28
|
+
first appearance in the training processes (sorted by node id); -1: not a process,
|
|
29
|
+
`num_known`: process with an unknown tag."""
|
|
30
|
+
ids = sorted(int(n) for n in indexid2msg)
|
|
31
|
+
max_id = ids[-1] if ids else -1
|
|
32
|
+
classes = np.full(max_id + 1, -1, dtype=np.int64)
|
|
33
|
+
tag2class = {}
|
|
34
|
+
train_nodes = {str(n) for n in train_nodes}
|
|
35
|
+
for n in ids:
|
|
36
|
+
node_type, label = indexid2msg[str(n)] if str(n) in indexid2msg else indexid2msg[n]
|
|
37
|
+
if node_type == process_type and str(n) in train_nodes:
|
|
38
|
+
tag2class.setdefault(process_tag(label), len(tag2class))
|
|
39
|
+
num_known = len(tag2class)
|
|
40
|
+
for n in ids:
|
|
41
|
+
node_type, label = indexid2msg[str(n)] if str(n) in indexid2msg else indexid2msg[n]
|
|
42
|
+
if node_type == process_type:
|
|
43
|
+
classes[n] = tag2class.get(process_tag(label), num_known)
|
|
44
|
+
return classes, num_known
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def process_tag_classes_from_cfg(cfg):
|
|
48
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
49
|
+
train_nodes = get_split2nodes(cfg)["train"]
|
|
50
|
+
classes, num_known = build_process_tag_classes(indexid2msg, train_nodes)
|
|
51
|
+
log(f"Process tags: {num_known} tags in training, {(classes >= 0).sum()} processes")
|
|
52
|
+
return classes, num_known
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def elbow_kmeans(x, k_values, seed=0, elbow_sample=5000):
|
|
56
|
+
"""K-Means of x with the K at the elbow of the inertia curve over `k_values` (the point the
|
|
57
|
+
furthest from the line joining the first and last points, with normalized axes). The curve
|
|
58
|
+
is computed on a random sample of `elbow_sample` points."""
|
|
59
|
+
from sklearn.cluster import KMeans
|
|
60
|
+
|
|
61
|
+
k_values = [k for k in k_values if k <= len(x)] or [1]
|
|
62
|
+
sample = x
|
|
63
|
+
if len(x) > elbow_sample:
|
|
64
|
+
sample = x[np.random.default_rng(seed).choice(len(x), elbow_sample, replace=False)]
|
|
65
|
+
inertia = np.array(
|
|
66
|
+
[KMeans(n_clusters=k, n_init=3, random_state=seed).fit(sample).inertia_ for k in k_values]
|
|
67
|
+
)
|
|
68
|
+
best = len(k_values) - 1
|
|
69
|
+
if len(k_values) >= 3:
|
|
70
|
+
ks = np.array(k_values, dtype=float)
|
|
71
|
+
ks = (ks - ks[0]) / (ks[-1] - ks[0])
|
|
72
|
+
span = inertia[0] - inertia[-1]
|
|
73
|
+
inertia = (inertia - inertia[-1]) / span if span > 0 else np.zeros_like(inertia)
|
|
74
|
+
# Distance to the line from (0, 1) to (1, 0)
|
|
75
|
+
best = int(np.argmax(np.abs(ks + inertia - 1)))
|
|
76
|
+
return KMeans(n_clusters=k_values[best], n_init=3, random_state=seed).fit(x)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ProcessTagPrediction(nn.Module):
|
|
80
|
+
"""Process tag prediction. Inference scores (`detection`):
|
|
81
|
+
|
|
82
|
+
- `loss`: the cross-entropy of the tag of each process;
|
|
83
|
+
- `kmeans`: as in the paper (Section 4.4), the distance of the embedding of each process to
|
|
84
|
+
the median of its nearest cluster, clustered by K-Means (K chosen with the elbow method)
|
|
85
|
+
on the embeddings of training processes. These are sampled during the last training epoch
|
|
86
|
+
(up to `max_train_embeddings`, with dropout).
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, decoder, node_classes, num_known, balanced_loss, detection="loss",
|
|
90
|
+
max_train_embeddings=20000, k_values=(2, 4, 6, 8, 10, 12, 16, 20, 25, 30)):
|
|
91
|
+
super(ProcessTagPrediction, self).__init__()
|
|
92
|
+
self.decoder = decoder
|
|
93
|
+
self.num_classes = num_known + 1 # + unknown
|
|
94
|
+
self.balanced_loss = balanced_loss
|
|
95
|
+
self.register_buffer("node_classes", torch.as_tensor(node_classes, dtype=torch.long), persistent=False)
|
|
96
|
+
if detection not in ("loss", "kmeans"):
|
|
97
|
+
raise ValueError(f"Invalid detection {detection}")
|
|
98
|
+
self.detection = detection
|
|
99
|
+
self.max_train_embeddings = max_train_embeddings
|
|
100
|
+
self.k_values = list(k_values)
|
|
101
|
+
self._generator = torch.Generator().manual_seed(0)
|
|
102
|
+
self.reset_state()
|
|
103
|
+
|
|
104
|
+
def reset_state(self):
|
|
105
|
+
"""Called before each training epoch: the embeddings of the epoch are sampled again."""
|
|
106
|
+
self._train_embs = []
|
|
107
|
+
self._num_seen = 0
|
|
108
|
+
self._medians = None
|
|
109
|
+
|
|
110
|
+
def _sample_train_embeddings(self, h):
|
|
111
|
+
"""Uniform sample of the embeddings seen in the epoch: each one gets a random key, and
|
|
112
|
+
those whose key is below `max_train_embeddings / number seen` are kept."""
|
|
113
|
+
h = h.detach().float().cpu()
|
|
114
|
+
keys = torch.rand(len(h), generator=self._generator)
|
|
115
|
+
self._num_seen += len(h)
|
|
116
|
+
ratio = min(1.0, self.max_train_embeddings / self._num_seen)
|
|
117
|
+
self._train_embs.append((h, keys))
|
|
118
|
+
self._train_embs = [(e[k < ratio], k[k < ratio]) for e, k in self._train_embs]
|
|
119
|
+
self._medians = None
|
|
120
|
+
|
|
121
|
+
def _cluster_medians(self, device):
|
|
122
|
+
if self._medians is None:
|
|
123
|
+
if not self._train_embs:
|
|
124
|
+
raise RuntimeError("`detection: kmeans` needs the embeddings of a training epoch")
|
|
125
|
+
x = torch.cat([e for e, _ in self._train_embs]).numpy()
|
|
126
|
+
km = elbow_kmeans(x, self.k_values)
|
|
127
|
+
medians = [np.median(x[km.labels_ == c], axis=0) for c in range(km.n_clusters)]
|
|
128
|
+
log(f"Process tags: K-Means with K={km.n_clusters} on {len(x)} training processes")
|
|
129
|
+
self._medians = torch.tensor(np.stack(medians), dtype=torch.float)
|
|
130
|
+
return self._medians.to(device)
|
|
131
|
+
|
|
132
|
+
def _classes(self, batch, num_nodes, device):
|
|
133
|
+
n_id = batch.original_n_id.to(device)
|
|
134
|
+
classes = torch.full((num_nodes,), -1, dtype=torch.long, device=device)
|
|
135
|
+
valid = n_id < self.node_classes.numel()
|
|
136
|
+
classes[valid] = self.node_classes[n_id[valid]]
|
|
137
|
+
return classes
|
|
138
|
+
|
|
139
|
+
def forward(self, h, inference, batch, **kwargs):
|
|
140
|
+
classes = self._classes(batch, h.shape[0], h.device)
|
|
141
|
+
is_process = classes >= 0
|
|
142
|
+
|
|
143
|
+
if not inference:
|
|
144
|
+
# Unknown tags (not in the training split) are never targets
|
|
145
|
+
known = is_process & (classes < self.num_classes - 1)
|
|
146
|
+
if not bool(known.any()):
|
|
147
|
+
return {"loss": h.sum() * 0.0}
|
|
148
|
+
if self.detection == "kmeans":
|
|
149
|
+
self._sample_train_embeddings(h[known])
|
|
150
|
+
logits = self.decoder(h[known])
|
|
151
|
+
target = classes[known]
|
|
152
|
+
weight = (
|
|
153
|
+
compute_class_weights(F.one_hot(target, self.num_classes), num_classes=self.num_classes)
|
|
154
|
+
if self.balanced_loss
|
|
155
|
+
else None
|
|
156
|
+
)
|
|
157
|
+
return {"loss": F.cross_entropy(logits, target, weight=weight)}
|
|
158
|
+
|
|
159
|
+
scores = torch.zeros(h.shape[0], dtype=torch.float, device=h.device)
|
|
160
|
+
out = None
|
|
161
|
+
if bool(is_process.any()):
|
|
162
|
+
logits = self.decoder(h[is_process])
|
|
163
|
+
out = F.log_softmax(logits, dim=1)
|
|
164
|
+
if self.detection == "kmeans":
|
|
165
|
+
dist = torch.cdist(h[is_process].float(), self._cluster_medians(h.device))
|
|
166
|
+
scores[is_process] = dist.min(dim=1).values
|
|
167
|
+
else:
|
|
168
|
+
scores[is_process] = F.cross_entropy(logits, classes[is_process], reduction="none")
|
|
169
|
+
return {"loss": scores, "out": out}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Prediction of the embedding of the next snapshot, and key indicators (ProGrapher).
|
|
2
|
+
|
|
3
|
+
The encoder (`textrcnn`) predicts the graph2vec embedding of the current snapshot from the
|
|
4
|
+
previous ones. The loss of a snapshot is the L2 distance between its actual and predicted
|
|
5
|
+
embeddings (Eq. 6 of ProGrapher): the anomaly score of the snapshot.
|
|
6
|
+
|
|
7
|
+
At inference, the objective returns one score per node of the snapshot, so that ProGrapher is
|
|
8
|
+
evaluated per time window (`tw_evaluation`, as the paper) or per node (`node_evaluation`):
|
|
9
|
+
|
|
10
|
+
1. Key indicators (Section 4.4). graph2vec predicts each rooted subgraph (RSG) r of a snapshot
|
|
11
|
+
from its embedding E with p(r | E) = softmax_r(w_r . E) over the RSGs of the snapshot (Eq. 1),
|
|
12
|
+
w_r being the output vector of r. The RSGs are ranked by the difference of their
|
|
13
|
+
log-likelihood under the actual and the predicted embeddings, log p(r | E) - log p(r | E'),
|
|
14
|
+
which reduces to w_r . (E - E') up to a constant of the snapshot: the RSGs best explained
|
|
15
|
+
by the actual snapshot, but not by its prediction, come first.
|
|
16
|
+
2. Each node is ranked by the best rank of the RSGs rooted at it (one per WL depth): nodes
|
|
17
|
+
matching the top RSGs are the key indicators.
|
|
18
|
+
3. The score of a node is `snapshot_score * (1 - rank / num_rsgs)`: the nodes of the top RSG
|
|
19
|
+
get the score of the snapshot, the others a fraction decreasing with the rank of their RSG.
|
|
20
|
+
With `top_k`, only the nodes matching the `top_k` first RSGs (the key indicators reported by
|
|
21
|
+
ProGrapher) keep a non-zero score.
|
|
22
|
+
|
|
23
|
+
The maximum node score of a snapshot is thus its own score: reduced with a max, as
|
|
24
|
+
`tw_evaluation` does with `max_val_loss`, node scores give the snapshot-level detection of the
|
|
25
|
+
paper.
|
|
26
|
+
|
|
27
|
+
RSGs unseen when training graph2vec are ignored, as when inferring the snapshot embedding.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import torch
|
|
31
|
+
import torch.nn as nn
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SnapshotEmbeddingPrediction(nn.Module):
|
|
35
|
+
def __init__(self, rsg_vectors, top_k=0):
|
|
36
|
+
"""
|
|
37
|
+
Args:
|
|
38
|
+
rsg_vectors: (V, d) output vectors of the RSGs of graph2vec (`syn1neg`)
|
|
39
|
+
top_k: if > 0, only the nodes matching the `top_k` first RSGs get a score
|
|
40
|
+
"""
|
|
41
|
+
super().__init__()
|
|
42
|
+
self.register_buffer("rsg_vectors", rsg_vectors.float(), persistent=False)
|
|
43
|
+
self.top_k = top_k
|
|
44
|
+
self.val_scores = []
|
|
45
|
+
|
|
46
|
+
def forward(self, h, inference, batch, validation=False, **kwargs):
|
|
47
|
+
target = batch.graph_emb.float().view(1, -1)
|
|
48
|
+
pred = h.view(1, -1)
|
|
49
|
+
score = torch.linalg.vector_norm(target - pred)
|
|
50
|
+
|
|
51
|
+
if not inference:
|
|
52
|
+
return {"loss": score}
|
|
53
|
+
|
|
54
|
+
if validation:
|
|
55
|
+
self.val_scores.append(score.item())
|
|
56
|
+
node_scores = score * self.key_indicator_weights(batch, (target - pred).view(-1))
|
|
57
|
+
return {"loss": node_scores}
|
|
58
|
+
|
|
59
|
+
@torch.no_grad()
|
|
60
|
+
def key_indicator_weights(self, batch, diff):
|
|
61
|
+
"""Weight in [0, 1] of each node of the batch (in the order of `batch.original_n_id`)
|
|
62
|
+
given by the rank of its best RSG, the RSGs being ranked by w_r . diff."""
|
|
63
|
+
table = batch.snapshot_rsg[0].long() # (n, D + 2): node ID, then RSG IDs
|
|
64
|
+
rsg_ids = table[:, 1:]
|
|
65
|
+
known = rsg_ids >= 0
|
|
66
|
+
|
|
67
|
+
# Rank of the unique RSGs of the snapshot
|
|
68
|
+
uniq, inverse = torch.unique(rsg_ids[known], return_inverse=True)
|
|
69
|
+
num_rsgs = uniq.numel()
|
|
70
|
+
order = torch.argsort(self.rsg_vectors[uniq] @ diff, descending=True)
|
|
71
|
+
rank = torch.empty_like(order)
|
|
72
|
+
rank[order] = torch.arange(num_rsgs, device=order.device)
|
|
73
|
+
|
|
74
|
+
# Best rank of the RSGs of each node (num_rsgs if none is known)
|
|
75
|
+
node_rank = torch.full_like(rsg_ids, num_rsgs)
|
|
76
|
+
node_rank[known] = rank[inverse]
|
|
77
|
+
best_rank = node_rank.min(dim=1).values
|
|
78
|
+
|
|
79
|
+
weights = 1.0 - best_rank.float() / max(num_rsgs, 1)
|
|
80
|
+
if self.top_k > 0:
|
|
81
|
+
weights[best_rank >= self.top_k] = 0.0
|
|
82
|
+
|
|
83
|
+
# Nodes of the batch, found by ID in the table (sorted by node ID)
|
|
84
|
+
n_id = batch.original_n_id.long()
|
|
85
|
+
rows = torch.searchsorted(table[:, 0].contiguous(), n_id)
|
|
86
|
+
rows = rows.clamp(max=table.size(0) - 1)
|
|
87
|
+
if not torch.equal(table[rows, 0], n_id):
|
|
88
|
+
raise ValueError("Nodes of the batch are missing from the RSGs of their snapshot.")
|
|
89
|
+
return weights[rows]
|
|
90
|
+
|
|
91
|
+
def get_val_score(self):
|
|
92
|
+
"""Validation score used by `best_model_selection=best_val_score`: the opposite of the
|
|
93
|
+
mean prediction error on the (benign) validation snapshots, as ProGrapher selects its
|
|
94
|
+
model on validation data."""
|
|
95
|
+
score = -sum(self.val_scores) / len(self.val_scores) if self.val_scores else 0.0
|
|
96
|
+
self.val_scores = []
|
|
97
|
+
return score
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class EdgeEmbReconstruction(nn.Module):
|
|
6
|
+
def __init__(self, decoder, loss_fn):
|
|
7
|
+
super(EdgeEmbReconstruction, self).__init__()
|
|
8
|
+
self.decoder = decoder
|
|
9
|
+
self.loss_fn = loss_fn
|
|
10
|
+
|
|
11
|
+
def forward(self, h_src, h_dst, inference, **kwargs):
|
|
12
|
+
h_edge_hat = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
13
|
+
|
|
14
|
+
h_edge = torch.cat([h_src, h_dst], dim=-1)
|
|
15
|
+
loss = self.loss_fn(h_edge_hat, h_edge, inference=inference)
|
|
16
|
+
return {"loss": loss}
|