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,2176 @@
|
|
|
1
|
+
"""Standalone web visualizer server for PIDSMaker embeddings.
|
|
2
|
+
|
|
3
|
+
Flask app that serves the 3D UMAP embedding viewer over localhost. It is
|
|
4
|
+
*independent of the pipeline*: it only reads pre-computed artifacts from the
|
|
5
|
+
artifacts folder (``embedding_viz_*_points.json`` / ``*_adj.json`` and the
|
|
6
|
+
sibling ``viz_manifest.json``). The user picks a run in the browser.
|
|
7
|
+
|
|
8
|
+
Endpoints
|
|
9
|
+
---------
|
|
10
|
+
GET / -> single-page app (run browser + 3D viewer)
|
|
11
|
+
GET /api/runs -> list of discovered runs (artifacts scan)
|
|
12
|
+
GET /api/run?file=<points> -> run descriptor: n, hops, embeddings, epochs,
|
|
13
|
+
stats, detection_cost, adj availability
|
|
14
|
+
GET /api/buffer?file=<pts> -> packed binary buffer for GPU upload (cached,
|
|
15
|
+
Range-serveable so the client streams it in chunks)
|
|
16
|
+
GET /api/node?file=&idxs= -> full metadata for a few buffer rows (on selection)
|
|
17
|
+
GET /api/search?file=&q= -> buffer rows matching a query (id / path / cmd)
|
|
18
|
+
POST /api/filter {file,terms} -> buffer rows matching any of many terms (CSV filter)
|
|
19
|
+
GET /api/neighbors?file=&node= -> one node's incident edges (See Edges)
|
|
20
|
+
GET /api/causal?file=&node= -> causal subgraph (server-side trace)
|
|
21
|
+
GET /api/attack_pairs?file= -> malicious<->malicious edge pairs
|
|
22
|
+
GET /api/campaign?file= -> campaign attack graph
|
|
23
|
+
(Adjacency is served from a persisted CSR index, not the raw adj.json, and is
|
|
24
|
+
warmed in the background when a run is opened.)
|
|
25
|
+
|
|
26
|
+
Binary buffer layout (little-endian), with n points and H hops, in order:
|
|
27
|
+
1. positions : float16[H * n * 3] (hop-major, then point, then x,y,z)
|
|
28
|
+
2. attrs : uint16[n * 4] (tw_idx, tw_start, tw_end, score-as-float16)
|
|
29
|
+
3. ids : uint32[n] (node_id)
|
|
30
|
+
4. meta : uint8[n] (bit-packed: label<<0 | det<<1 | type<<3)
|
|
31
|
+
(no colour column, and no size — the client derives both from the packed flags)
|
|
32
|
+
|
|
33
|
+
Run:: python -m pidsmaker.vizgen.web.viz_server [--host H] [--port P]
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import argparse
|
|
37
|
+
import glob
|
|
38
|
+
import json
|
|
39
|
+
import math
|
|
40
|
+
import os
|
|
41
|
+
import queue
|
|
42
|
+
import re
|
|
43
|
+
import shutil
|
|
44
|
+
import signal
|
|
45
|
+
import subprocess
|
|
46
|
+
import sys
|
|
47
|
+
import threading
|
|
48
|
+
import time
|
|
49
|
+
import uuid
|
|
50
|
+
from collections import deque
|
|
51
|
+
|
|
52
|
+
import numpy as np
|
|
53
|
+
from flask import (
|
|
54
|
+
Flask,
|
|
55
|
+
Response,
|
|
56
|
+
abort,
|
|
57
|
+
jsonify,
|
|
58
|
+
request,
|
|
59
|
+
send_from_directory,
|
|
60
|
+
stream_with_context,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# --------------------------------------------------------------------------- #
|
|
64
|
+
# Paths / config
|
|
65
|
+
# --------------------------------------------------------------------------- #
|
|
66
|
+
|
|
67
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
68
|
+
STATIC_DIR = os.path.join(HERE, "static")
|
|
69
|
+
PIDSMAKER_ROOT = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get_artifacts_root():
|
|
73
|
+
"""$PIDS_ARTIFACTS_DIR, else the default of --artifact_dir (as the exporter)."""
|
|
74
|
+
from pidsmaker.config.pipeline import default_artifact_dir
|
|
75
|
+
|
|
76
|
+
return os.environ.get("PIDS_ARTIFACTS_DIR") or default_artifact_dir()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
ARTIFACTS_ROOT = get_artifacts_root()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _type_enum(t):
|
|
83
|
+
t = (t or "").lower()
|
|
84
|
+
if "process" in t or "subject" in t:
|
|
85
|
+
return 0
|
|
86
|
+
if "file" in t:
|
|
87
|
+
return 1
|
|
88
|
+
if "netflow" in t:
|
|
89
|
+
return 2
|
|
90
|
+
return 3
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# --------------------------------------------------------------------------- #
|
|
94
|
+
# Security: only allow files inside the artifacts root
|
|
95
|
+
# --------------------------------------------------------------------------- #
|
|
96
|
+
|
|
97
|
+
def safe_path(p, kind="file"):
|
|
98
|
+
"""Resolve *p* and ensure it lives under ARTIFACTS_ROOT. Abort otherwise.
|
|
99
|
+
|
|
100
|
+
kind="file" requires an existing file; kind="dir" an existing directory.
|
|
101
|
+
"""
|
|
102
|
+
if not p:
|
|
103
|
+
abort(400, "missing path param")
|
|
104
|
+
real = os.path.realpath(p)
|
|
105
|
+
root = os.path.realpath(ARTIFACTS_ROOT)
|
|
106
|
+
if not (real == root or real.startswith(root + os.sep)):
|
|
107
|
+
abort(403, "path outside artifacts root")
|
|
108
|
+
if kind == "dir":
|
|
109
|
+
if not os.path.isdir(real):
|
|
110
|
+
abort(404, "directory not found")
|
|
111
|
+
elif not os.path.isfile(real):
|
|
112
|
+
abort(404, "file not found")
|
|
113
|
+
return real
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# --------------------------------------------------------------------------- #
|
|
117
|
+
# Run discovery (replicates run_browser.py scan)
|
|
118
|
+
# --------------------------------------------------------------------------- #
|
|
119
|
+
|
|
120
|
+
def _read_model_name(config_path, viz_dir):
|
|
121
|
+
model = "Unknown"
|
|
122
|
+
try:
|
|
123
|
+
if config_path and os.path.exists(config_path):
|
|
124
|
+
import yaml
|
|
125
|
+
|
|
126
|
+
with open(config_path) as f:
|
|
127
|
+
cfg = yaml.safe_load(f) or {}
|
|
128
|
+
model = cfg.get("_model", "Unknown") or "Unknown"
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
if model == "Unknown" and viz_dir and os.path.isdir(viz_dir):
|
|
132
|
+
files = os.listdir(viz_dir)
|
|
133
|
+
if any("word2vec" in f for f in files):
|
|
134
|
+
model = "Velox (Word2Vec)"
|
|
135
|
+
elif any("encoder" in f for f in files):
|
|
136
|
+
model = "Orthrus (GNN)"
|
|
137
|
+
return model
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _raw_model(cfg_path):
|
|
141
|
+
"""Read the raw `_model` key from a run_config.yml (lowercased), or ''."""
|
|
142
|
+
try:
|
|
143
|
+
if cfg_path and os.path.exists(cfg_path):
|
|
144
|
+
import yaml
|
|
145
|
+
|
|
146
|
+
with open(cfg_path) as f:
|
|
147
|
+
cfg = yaml.safe_load(f) or {}
|
|
148
|
+
return str(cfg.get("_model", "") or "").lower()
|
|
149
|
+
except Exception:
|
|
150
|
+
pass
|
|
151
|
+
return ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _featurization_method(cfg_path):
|
|
155
|
+
"""The run's node featurization method (e.g. word2vec, doc2vec, flash, fasttext).
|
|
156
|
+
|
|
157
|
+
The base ("non-encoder") embedding space is whatever featurization the run
|
|
158
|
+
used — not necessarily word2vec — so the UI labels it with this instead of a
|
|
159
|
+
hardcoded "Word2Vec". Returns '' if it can't be determined.
|
|
160
|
+
"""
|
|
161
|
+
try:
|
|
162
|
+
if cfg_path and os.path.exists(cfg_path):
|
|
163
|
+
import yaml
|
|
164
|
+
|
|
165
|
+
with open(cfg_path) as f:
|
|
166
|
+
cfg = yaml.safe_load(f) or {}
|
|
167
|
+
feat = cfg.get("featurization")
|
|
168
|
+
if isinstance(feat, dict):
|
|
169
|
+
m = feat.get("used_method") or feat.get("used_methods")
|
|
170
|
+
if isinstance(m, str) and m:
|
|
171
|
+
return m
|
|
172
|
+
except Exception:
|
|
173
|
+
pass
|
|
174
|
+
return ""
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def discover_runs():
|
|
178
|
+
"""Scan artifacts for evaluation runs.
|
|
179
|
+
|
|
180
|
+
A run is listed if it has a viz_manifest.json (evaluated) and/or already has
|
|
181
|
+
viz/*_points.json. Each entry carries a status so the UI can offer
|
|
182
|
+
generation: ``ready`` (expected embeddings present), ``partial`` (some
|
|
183
|
+
present), or ``needs_viz`` (manifest only, nothing generated yet).
|
|
184
|
+
"""
|
|
185
|
+
runs = []
|
|
186
|
+
seen = set()
|
|
187
|
+
patterns = [
|
|
188
|
+
os.path.join(ARTIFACTS_ROOT, "evaluation/evaluation/*/*"),
|
|
189
|
+
os.path.join(ARTIFACTS_ROOT, "detection/evaluation/*/*"),
|
|
190
|
+
]
|
|
191
|
+
for pat in patterns:
|
|
192
|
+
for d_path in glob.glob(pat):
|
|
193
|
+
if not os.path.isdir(d_path) or d_path in seen:
|
|
194
|
+
continue
|
|
195
|
+
viz_dir = os.path.join(d_path, "viz")
|
|
196
|
+
manifest_path = os.path.join(d_path, "viz_manifest.json")
|
|
197
|
+
points = sorted(glob.glob(os.path.join(viz_dir, "*_points.json"))) \
|
|
198
|
+
if os.path.isdir(viz_dir) else []
|
|
199
|
+
has_manifest = os.path.exists(manifest_path)
|
|
200
|
+
if not points and not has_manifest:
|
|
201
|
+
continue
|
|
202
|
+
seen.add(d_path)
|
|
203
|
+
|
|
204
|
+
dataset = os.path.basename(d_path)
|
|
205
|
+
full_hash = os.path.basename(os.path.dirname(d_path))
|
|
206
|
+
cfg_path = os.path.join(d_path, "run_config.yml")
|
|
207
|
+
if not os.path.exists(cfg_path):
|
|
208
|
+
cfg_path = os.path.join(os.path.dirname(d_path), "run_config.yml")
|
|
209
|
+
|
|
210
|
+
manifest = load_manifest(viz_dir)
|
|
211
|
+
best_epoch = None
|
|
212
|
+
epochs = []
|
|
213
|
+
if manifest and manifest.get("epochs"):
|
|
214
|
+
eps = manifest["epochs"]
|
|
215
|
+
best_epoch = sorted(eps, key=lambda e: e.get("adp", 0), reverse=True)[0].get("epoch")
|
|
216
|
+
epochs = [e.get("epoch") for e in eps]
|
|
217
|
+
|
|
218
|
+
basenames = [os.path.basename(p) for p in points]
|
|
219
|
+
present_w2v = any("word2vec" in b for b in basenames)
|
|
220
|
+
present_enc = any("encoder" in b for b in basenames)
|
|
221
|
+
|
|
222
|
+
# expected embeddings from the model type
|
|
223
|
+
model_lc = _raw_model(cfg_path)
|
|
224
|
+
if "velox" in model_lc:
|
|
225
|
+
expected = {"w2v"}
|
|
226
|
+
elif any(k in model_lc for k in ("orthrus", "rcaid", "gnn")):
|
|
227
|
+
expected = {"enc"}
|
|
228
|
+
else:
|
|
229
|
+
expected = set()
|
|
230
|
+
present = set()
|
|
231
|
+
if present_w2v:
|
|
232
|
+
present.add("w2v")
|
|
233
|
+
if present_enc:
|
|
234
|
+
present.add("enc")
|
|
235
|
+
if not present:
|
|
236
|
+
status = "needs_viz"
|
|
237
|
+
elif expected and not expected.issubset(present):
|
|
238
|
+
status = "partial"
|
|
239
|
+
else:
|
|
240
|
+
status = "ready"
|
|
241
|
+
|
|
242
|
+
# default file to open: bare encoder > best-epoch encoder > word2vec > first
|
|
243
|
+
default_file = None
|
|
244
|
+
for fp in points:
|
|
245
|
+
b = os.path.basename(fp)
|
|
246
|
+
if "encoder" in b and "epoch" not in b:
|
|
247
|
+
default_file = fp
|
|
248
|
+
break
|
|
249
|
+
if default_file is None and best_epoch is not None:
|
|
250
|
+
for fp in points:
|
|
251
|
+
if f"encoder_epoch_{best_epoch}_" in os.path.basename(fp):
|
|
252
|
+
default_file = fp
|
|
253
|
+
break
|
|
254
|
+
if default_file is None and points:
|
|
255
|
+
w2v = [fp for fp in points if "word2vec" in os.path.basename(fp)]
|
|
256
|
+
default_file = w2v[0] if w2v else points[0]
|
|
257
|
+
|
|
258
|
+
adp, disc = 0.0, 0.0
|
|
259
|
+
if manifest and manifest.get("epochs"):
|
|
260
|
+
best = sorted(manifest["epochs"], key=lambda e: e.get("adp", 0), reverse=True)[0]
|
|
261
|
+
adp, disc = best.get("adp", 0.0), best.get("disc_score", 0.0)
|
|
262
|
+
|
|
263
|
+
mtime = os.path.getmtime(d_path)
|
|
264
|
+
runs.append(
|
|
265
|
+
{
|
|
266
|
+
"dataset": dataset,
|
|
267
|
+
"hash": full_hash[:8],
|
|
268
|
+
"full_hash": full_hash,
|
|
269
|
+
"model": _read_model_name(cfg_path, viz_dir),
|
|
270
|
+
"date": time.strftime("%Y-%m-%d %H:%M", time.localtime(mtime)),
|
|
271
|
+
"mtime": mtime,
|
|
272
|
+
"viz_dir": viz_dir,
|
|
273
|
+
"eval_dir": d_path,
|
|
274
|
+
"n_files": len(points),
|
|
275
|
+
"default_file": default_file,
|
|
276
|
+
"status": status,
|
|
277
|
+
"present": {"word2vec": present_w2v, "encoder": present_enc},
|
|
278
|
+
"epochs": epochs,
|
|
279
|
+
"adp": adp,
|
|
280
|
+
"disc_score": disc,
|
|
281
|
+
"has_manifest": has_manifest,
|
|
282
|
+
}
|
|
283
|
+
)
|
|
284
|
+
runs.sort(key=lambda r: r["mtime"], reverse=True)
|
|
285
|
+
return runs
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _label_for_file(basename, best_epoch=None, featurization=None):
|
|
289
|
+
if "word2vec" in basename:
|
|
290
|
+
return f"Featurization ({featurization})" if featurization else "Featurization Embedding"
|
|
291
|
+
if "encoder_epoch_" in basename:
|
|
292
|
+
ep = basename.split("encoder_epoch_")[1].split("_")[0]
|
|
293
|
+
return f"GNN Encoder (Epoch {ep})"
|
|
294
|
+
if "encoder" in basename:
|
|
295
|
+
return (
|
|
296
|
+
f"GNN Encoder (Best: Epoch {best_epoch})"
|
|
297
|
+
if best_epoch is not None
|
|
298
|
+
else "GNN Encoder (Best)"
|
|
299
|
+
)
|
|
300
|
+
return basename
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _epoch_of(basename):
|
|
304
|
+
if "encoder_epoch_" in basename:
|
|
305
|
+
try:
|
|
306
|
+
return int(basename.split("encoder_epoch_")[1].split("_")[0])
|
|
307
|
+
except Exception:
|
|
308
|
+
return None
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
# --------------------------------------------------------------------------- #
|
|
313
|
+
# run_config.yml cleaning (parity with loader.load_data)
|
|
314
|
+
# --------------------------------------------------------------------------- #
|
|
315
|
+
|
|
316
|
+
KNOWN_METHODS = {
|
|
317
|
+
"alacarte", "doc2vec", "fasttext", "flash", "temporal_rw", "word2vec",
|
|
318
|
+
"custom_mlp", "gat", "gin", "graph_attention", "magic_gat", "sage", "tgn",
|
|
319
|
+
"none", "rcaid_gat", "sum_aggregation", "glstm", "few_shot",
|
|
320
|
+
"predict_edge_contrastive", "predict_edge_type", "predict_node_type",
|
|
321
|
+
"reconstruct_edge_embeddings", "reconstruct_node_embeddings",
|
|
322
|
+
"reconstruct_node_features", "reconstruct_masked_features",
|
|
323
|
+
"predict_masked_struct", "detect_edge_few_shot", "global_batching",
|
|
324
|
+
"inter_graph_batching", "intra_graph_batching", "edges",
|
|
325
|
+
"tgn_last_neighbor", "depimpact", "synthetic_attack_naive",
|
|
326
|
+
"rcaid_pseudo_graph", "kairos_idf_queue", "provnet_lof_queue",
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _clean_cfg(d):
|
|
331
|
+
if not isinstance(d, dict):
|
|
332
|
+
return d
|
|
333
|
+
active = None
|
|
334
|
+
if isinstance(d.get("used_method"), str):
|
|
335
|
+
active = d["used_method"]
|
|
336
|
+
elif isinstance(d.get("used_methods"), str):
|
|
337
|
+
active = d["used_methods"]
|
|
338
|
+
out = {}
|
|
339
|
+
for k, v in d.items():
|
|
340
|
+
if isinstance(k, str) and k.startswith("_"):
|
|
341
|
+
continue
|
|
342
|
+
if v is None or v == "" or v == [] or v == {}:
|
|
343
|
+
continue
|
|
344
|
+
if k in {
|
|
345
|
+
"attack_to_time_window", "ground_truth_relative_path", "train_dates",
|
|
346
|
+
"test_dates", "val_dates", "unused_dates", "database",
|
|
347
|
+
"database_all_file", "host", "password", "port", "user",
|
|
348
|
+
"node_label_features",
|
|
349
|
+
}:
|
|
350
|
+
continue
|
|
351
|
+
if active and isinstance(v, dict) and k in KNOWN_METHODS and k != active:
|
|
352
|
+
continue
|
|
353
|
+
if isinstance(v, dict):
|
|
354
|
+
vc = _clean_cfg(v)
|
|
355
|
+
if vc:
|
|
356
|
+
if (
|
|
357
|
+
len(vc) == 1
|
|
358
|
+
and list(vc.keys())[0] in ("used_method", "used_methods")
|
|
359
|
+
and vc[list(vc.keys())[0]] == "none"
|
|
360
|
+
):
|
|
361
|
+
continue
|
|
362
|
+
out[k] = vc
|
|
363
|
+
else:
|
|
364
|
+
out[k] = v
|
|
365
|
+
return out
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def load_run_config_text(viz_dir):
|
|
369
|
+
eval_dir = os.path.dirname(viz_dir)
|
|
370
|
+
for cand in (
|
|
371
|
+
os.path.join(eval_dir, "run_config.yml"),
|
|
372
|
+
os.path.join(os.path.dirname(eval_dir), "run_config.yml"),
|
|
373
|
+
):
|
|
374
|
+
if os.path.exists(cand):
|
|
375
|
+
try:
|
|
376
|
+
import yaml
|
|
377
|
+
|
|
378
|
+
with open(cand) as f:
|
|
379
|
+
cfg = yaml.safe_load(f)
|
|
380
|
+
return yaml.dump(_clean_cfg(cfg), default_flow_style=False, sort_keys=True)
|
|
381
|
+
except Exception:
|
|
382
|
+
return ""
|
|
383
|
+
return ""
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# --------------------------------------------------------------------------- #
|
|
387
|
+
# Manifest helpers (adp / disc_score)
|
|
388
|
+
# --------------------------------------------------------------------------- #
|
|
389
|
+
|
|
390
|
+
def load_manifest(viz_dir):
|
|
391
|
+
mf = os.path.join(os.path.dirname(viz_dir), "viz_manifest.json")
|
|
392
|
+
if os.path.exists(mf):
|
|
393
|
+
try:
|
|
394
|
+
with open(mf) as f:
|
|
395
|
+
return json.load(f)
|
|
396
|
+
except Exception:
|
|
397
|
+
return None
|
|
398
|
+
return None
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def metrics_for_file(basename, manifest):
|
|
402
|
+
"""Return (adp, disc_score, best_epoch) for a points file."""
|
|
403
|
+
if manifest is None or "word2vec" in basename:
|
|
404
|
+
return 0.0, 0.0, None
|
|
405
|
+
epochs = manifest.get("epochs", [])
|
|
406
|
+
if not epochs:
|
|
407
|
+
return 0.0, 0.0, None
|
|
408
|
+
best = sorted(epochs, key=lambda e: e.get("adp", 0), reverse=True)[0]
|
|
409
|
+
best_ep = best.get("epoch")
|
|
410
|
+
ep = _epoch_of(basename)
|
|
411
|
+
if ep is not None:
|
|
412
|
+
for e in epochs:
|
|
413
|
+
if str(e.get("epoch")) == str(ep):
|
|
414
|
+
return e.get("adp", 0.0), e.get("disc_score", 0.0), best_ep
|
|
415
|
+
return best.get("adp", 0.0), best.get("disc_score", 0.0), best_ep
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# --------------------------------------------------------------------------- #
|
|
419
|
+
# Core: parse points.json -> numpy arrays (with disk cache)
|
|
420
|
+
# --------------------------------------------------------------------------- #
|
|
421
|
+
|
|
422
|
+
CACHE_VERSION = 4 # v4: v3 + attrs packed (tw uint16 ×3 + score float16, size dropped)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _cache_paths(points_path):
|
|
426
|
+
base = points_path + f".webcache_v{CACHE_VERSION}"
|
|
427
|
+
return base + ".bin", base + ".meta.json", base + ".info.json"
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _pack_attrs(attrs):
|
|
431
|
+
"""attrs f32[n,5] (tw_idx, tw_start, tw_end, score, size) -> uint16[n,4]
|
|
432
|
+
(tw_idx, tw_start, tw_end, score-as-float16). `size` is dropped (the client
|
|
433
|
+
derives it from the label); the temporal 'never ends' sentinel (1e30) clips
|
|
434
|
+
to 65535, which the client reads back as +inf."""
|
|
435
|
+
attrs = np.asarray(attrs, dtype=np.float32)
|
|
436
|
+
n = len(attrs)
|
|
437
|
+
packed = np.empty((n, 4), np.uint16)
|
|
438
|
+
packed[:, 0] = np.clip(attrs[:, 0], 0, 65535).astype(np.uint16)
|
|
439
|
+
packed[:, 1] = np.clip(attrs[:, 1], 0, 65535).astype(np.uint16)
|
|
440
|
+
packed[:, 2] = np.clip(attrs[:, 2], 0, 65535).astype(np.uint16)
|
|
441
|
+
packed[:, 3] = attrs[:, 3].astype(np.float16).view(np.uint16)
|
|
442
|
+
return packed
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _cache_fresh(points_path):
|
|
446
|
+
bin_p, meta_p, info_p = _cache_paths(points_path)
|
|
447
|
+
if not (os.path.exists(bin_p) and os.path.exists(meta_p) and os.path.exists(info_p)):
|
|
448
|
+
return False
|
|
449
|
+
src_m = os.path.getmtime(points_path)
|
|
450
|
+
return all(os.path.getmtime(p) >= src_m for p in (bin_p, meta_p, info_p))
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def build_cache(points_path):
|
|
454
|
+
"""Parse points.json and build the binary cache from it (server path)."""
|
|
455
|
+
try:
|
|
456
|
+
with open(points_path) as f:
|
|
457
|
+
pts = json.load(f)
|
|
458
|
+
except (json.JSONDecodeError, ValueError):
|
|
459
|
+
abort(422, "points file is corrupt or incomplete; regenerate this run")
|
|
460
|
+
if not pts:
|
|
461
|
+
abort(422, "empty points file")
|
|
462
|
+
return build_point_cache(pts, points_path)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def build_point_cache(pts, points_path):
|
|
466
|
+
"""Build the .bin/.meta/.info cache from in-memory point records (the same
|
|
467
|
+
shape as points.json). Shared by the server (which parses points.json) and
|
|
468
|
+
the exporter (which passes its records directly), so both produce identical
|
|
469
|
+
caches and the exporter's output needs no server-side JSON re-parse."""
|
|
470
|
+
t0 = time.time()
|
|
471
|
+
n = len(pts)
|
|
472
|
+
|
|
473
|
+
first = pts[0]
|
|
474
|
+
H = len(first["coords_hops"]) if "coords_hops" in first else 1
|
|
475
|
+
|
|
476
|
+
pos = np.zeros((H, n, 3), dtype=np.float32)
|
|
477
|
+
attrs = np.zeros((n, 5), dtype=np.float32) # tw_idx, tw_start, tw_end, score, size
|
|
478
|
+
flags = np.zeros((n, 4), dtype=np.uint32) # node_id, label, det, type_enum
|
|
479
|
+
# NOTE: no colour column. The client derives every node's colour from the flags
|
|
480
|
+
# (label/detection/type) via nodeRgba, so shipping colours was ~25% of the
|
|
481
|
+
# buffer wasted — dropped from the v2 cache.
|
|
482
|
+
|
|
483
|
+
# metadata (columnar) for inspector / search / tables
|
|
484
|
+
ids = [0] * n
|
|
485
|
+
paths = [""] * n
|
|
486
|
+
types = [""] * n
|
|
487
|
+
scores = [0.0] * n
|
|
488
|
+
tw_labels = [""] * n
|
|
489
|
+
cmds = [""] * n
|
|
490
|
+
top_edges = [""] * n
|
|
491
|
+
|
|
492
|
+
node_tws = {} # node_id -> list of (tw_idx, array_index)
|
|
493
|
+
|
|
494
|
+
stats = {
|
|
495
|
+
"total": n, "benign": 0, "malicious": 0,
|
|
496
|
+
"mal_proc": 0, "mal_file": 0, "mal_net": 0,
|
|
497
|
+
"attack_start_tw": math.inf, "attack_start_time": "",
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
for i, p in enumerate(pts):
|
|
501
|
+
if "coords_hops" in p:
|
|
502
|
+
ch = p["coords_hops"]
|
|
503
|
+
for h in range(H):
|
|
504
|
+
c = ch[h] if h < len(ch) else ch[-1]
|
|
505
|
+
pos[h, i, 0] = c[0]
|
|
506
|
+
pos[h, i, 1] = c[1]
|
|
507
|
+
pos[h, i, 2] = c[2]
|
|
508
|
+
else:
|
|
509
|
+
pos[0, i] = [p.get("x", 0.0), p.get("y", 0.0), p.get("z", 0.0)]
|
|
510
|
+
|
|
511
|
+
lbl = int(p.get("label", 0) or 0)
|
|
512
|
+
det = int(p.get("detection_status", 0) or 0)
|
|
513
|
+
tw_idx = float(p.get("tw_idx", 0) or 0)
|
|
514
|
+
score = float(p.get("anomaly_score", 0.0) or 0.0)
|
|
515
|
+
ptype = p.get("type") or ""
|
|
516
|
+
nid = int(p.get("node_id", 0) or 0)
|
|
517
|
+
|
|
518
|
+
attrs[i, 0] = tw_idx
|
|
519
|
+
attrs[i, 3] = score
|
|
520
|
+
if lbl == 0:
|
|
521
|
+
stats["benign"] += 1
|
|
522
|
+
attrs[i, 4] = 3.0
|
|
523
|
+
else:
|
|
524
|
+
stats["malicious"] += 1
|
|
525
|
+
attrs[i, 4] = 5.0
|
|
526
|
+
if tw_idx < stats["attack_start_tw"]:
|
|
527
|
+
stats["attack_start_tw"] = tw_idx
|
|
528
|
+
stats["attack_start_time"] = p.get("tw_label", "")
|
|
529
|
+
te = _type_enum(ptype)
|
|
530
|
+
if te == 0:
|
|
531
|
+
stats["mal_proc"] += 1
|
|
532
|
+
elif te == 1:
|
|
533
|
+
stats["mal_file"] += 1
|
|
534
|
+
elif te == 2:
|
|
535
|
+
stats["mal_net"] += 1
|
|
536
|
+
|
|
537
|
+
flags[i] = [nid, lbl, det, _type_enum(ptype)]
|
|
538
|
+
|
|
539
|
+
ids[i] = nid
|
|
540
|
+
paths[i] = p.get("path", "")
|
|
541
|
+
types[i] = ptype
|
|
542
|
+
scores[i] = score
|
|
543
|
+
tw_labels[i] = p.get("tw_label", "")
|
|
544
|
+
cmds[i] = p.get("cmd", "")
|
|
545
|
+
top_edges[i] = p.get("top_edge", "")
|
|
546
|
+
|
|
547
|
+
node_tws.setdefault(nid, []).append((tw_idx, i))
|
|
548
|
+
|
|
549
|
+
# temporal lifespan: tw_start = tw_idx ; tw_end = next occurrence of same id
|
|
550
|
+
attrs[:, 1] = attrs[:, 0]
|
|
551
|
+
attrs[:, 2] = np.inf
|
|
552
|
+
for lst in node_tws.values():
|
|
553
|
+
if len(lst) < 2:
|
|
554
|
+
continue
|
|
555
|
+
lst.sort(key=lambda x: x[0])
|
|
556
|
+
for k in range(len(lst) - 1):
|
|
557
|
+
attrs[lst[k][1], 2] = lst[k + 1][0]
|
|
558
|
+
# encode inf -> very large finite (shader compares u_time >= a_tw_end)
|
|
559
|
+
attrs[np.isinf(attrs[:, 2]), 2] = 1e30
|
|
560
|
+
|
|
561
|
+
max_tw = int(np.max(attrs[:, 0])) if n else 0
|
|
562
|
+
if math.isinf(stats["attack_start_tw"]):
|
|
563
|
+
stats["attack_start_tw"] = -1
|
|
564
|
+
|
|
565
|
+
# No index reordering: the exporter's natural node order is kept, so the
|
|
566
|
+
# painter's draw order matches the original (depth-correct-looking) layout.
|
|
567
|
+
# The client renders from the binary buffer and loads the string metadata
|
|
568
|
+
# lazily, so an "attacks-first" prefix is no longer needed.
|
|
569
|
+
|
|
570
|
+
# --- write binary buffer (atomically: temp file + rename) ---
|
|
571
|
+
bin_p, meta_p, info_p = _cache_paths(points_path)
|
|
572
|
+
bin_tmp = bin_p + ".tmp"
|
|
573
|
+
# Pack the buffer to cut wire transfer: positions as float16 (UMAP coords need
|
|
574
|
+
# nowhere near f32 precision), flags as node_id(u32) + one meta byte holding
|
|
575
|
+
# label(1b) | det(2b) | type(2b). Colour is already gone (derived from flags).
|
|
576
|
+
node_ids = flags[:, 0].astype(np.uint32)
|
|
577
|
+
meta_byte = (flags[:, 1] | (flags[:, 2] << 1) | (flags[:, 3] << 3)).astype(np.uint8)
|
|
578
|
+
with open(bin_tmp, "wb") as f:
|
|
579
|
+
f.write(np.ascontiguousarray(pos.astype(np.float16)).tobytes()) # H*n*3 f16
|
|
580
|
+
f.write(np.ascontiguousarray(_pack_attrs(attrs)).tobytes()) # n*4 u16
|
|
581
|
+
f.write(np.ascontiguousarray(node_ids).tobytes()) # n u32
|
|
582
|
+
f.write(np.ascontiguousarray(meta_byte).tobytes()) # n u8
|
|
583
|
+
os.replace(bin_tmp, bin_p)
|
|
584
|
+
|
|
585
|
+
# --- campaign mapping (optional) ---
|
|
586
|
+
campaign_ids = None
|
|
587
|
+
num_campaigns = 0
|
|
588
|
+
camp_path = os.path.join(os.path.dirname(points_path), "campaign_mapping.json")
|
|
589
|
+
if os.path.exists(camp_path):
|
|
590
|
+
try:
|
|
591
|
+
with open(camp_path) as f:
|
|
592
|
+
cm = json.load(f)
|
|
593
|
+
n2a = cm.get("node2attacks", {})
|
|
594
|
+
campaign_ids = [n2a.get(str(ids[i]), []) for i in range(n)]
|
|
595
|
+
num_campaigns = cm.get("num_campaigns", 0)
|
|
596
|
+
except Exception:
|
|
597
|
+
campaign_ids = None
|
|
598
|
+
|
|
599
|
+
meta = {
|
|
600
|
+
"ids": ids, "paths": paths, "types": types, "scores": scores,
|
|
601
|
+
"tw_idx": attrs[:, 0].astype(int).tolist(), "tw_labels": tw_labels,
|
|
602
|
+
"cmds": cmds, "top_edges": top_edges,
|
|
603
|
+
"labels": flags[:, 1].astype(int).tolist(),
|
|
604
|
+
"det": flags[:, 2].astype(int).tolist(),
|
|
605
|
+
}
|
|
606
|
+
if campaign_ids is not None:
|
|
607
|
+
meta["campaigns"] = campaign_ids
|
|
608
|
+
meta_tmp = meta_p + ".tmp"
|
|
609
|
+
with open(meta_tmp, "w") as f:
|
|
610
|
+
json.dump(meta, f, separators=(",", ":"))
|
|
611
|
+
os.replace(meta_tmp, meta_p)
|
|
612
|
+
build_meta_store(meta, meta_p + ".store.npz") # binary store -> instant metadata
|
|
613
|
+
|
|
614
|
+
info = {
|
|
615
|
+
"n": n, "hops": H, "max_tw": max_tw,
|
|
616
|
+
"stats": stats, "num_campaigns": num_campaigns,
|
|
617
|
+
"byte_offsets": { # layout: positions(f16) | attrs(u16×4) | ids(u32) | meta(u8)
|
|
618
|
+
"positions": 0,
|
|
619
|
+
"attrs": H * n * 3 * 2,
|
|
620
|
+
"ids": H * n * 3 * 2 + n * 4 * 2,
|
|
621
|
+
"meta": H * n * 3 * 2 + n * 4 * 2 + n * 4,
|
|
622
|
+
},
|
|
623
|
+
}
|
|
624
|
+
# detection cost needs scores + labels + det + campaigns
|
|
625
|
+
info["detection_cost"] = compute_detection_cost(
|
|
626
|
+
np.array(scores), np.array(meta["labels"]), np.array(meta["det"]),
|
|
627
|
+
np.array(ids), meta.get("campaigns"), num_campaigns,
|
|
628
|
+
)
|
|
629
|
+
info_tmp = info_p + ".tmp"
|
|
630
|
+
with open(info_tmp, "w") as f:
|
|
631
|
+
json.dump(info, f)
|
|
632
|
+
os.replace(info_tmp, info_p)
|
|
633
|
+
|
|
634
|
+
print(f"[viz_server] cached {os.path.basename(points_path)} "
|
|
635
|
+
f"({n} pts, {H} hops) in {time.time()-t0:.1f}s")
|
|
636
|
+
return info
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
# --------------------------------------------------------------------------- #
|
|
640
|
+
# Detection cost sweep (parity with main_window.precompute_detection_cost)
|
|
641
|
+
# --------------------------------------------------------------------------- #
|
|
642
|
+
|
|
643
|
+
def compute_detection_cost(scores, labels, det, ids, campaigns, num_campaigns):
|
|
644
|
+
n = len(scores)
|
|
645
|
+
if n == 0:
|
|
646
|
+
return None
|
|
647
|
+
benign = labels == 0
|
|
648
|
+
mal = labels == 1
|
|
649
|
+
|
|
650
|
+
total_gt = len(np.unique(ids[mal])) if mal.any() else 0
|
|
651
|
+
detected_ids = np.unique(ids[(mal) & (det == 1)]) if mal.any() else np.array([])
|
|
652
|
+
detected = len(detected_ids)
|
|
653
|
+
|
|
654
|
+
out = {
|
|
655
|
+
"total_gt": int(total_gt),
|
|
656
|
+
"detected": int(detected),
|
|
657
|
+
"current_fp": None, "current_threshold": None,
|
|
658
|
+
"fp_full_recall": None, "thresh_full_recall": None,
|
|
659
|
+
"fp_full_campaign": None, "thresh_full_campaign": None,
|
|
660
|
+
"campaign_coverage_det": None, "num_campaigns": int(num_campaigns or 0),
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
det_scores = scores[(mal) & (det == 1)]
|
|
664
|
+
if det_scores.size:
|
|
665
|
+
cur_thr = float(np.min(det_scores))
|
|
666
|
+
out["current_threshold"] = cur_thr
|
|
667
|
+
out["current_fp"] = int(np.sum(benign & (scores >= cur_thr)))
|
|
668
|
+
|
|
669
|
+
# FP for 100% recall: lowest mal score must pass
|
|
670
|
+
if mal.any():
|
|
671
|
+
thr_recall = float(np.min(scores[mal]))
|
|
672
|
+
out["thresh_full_recall"] = thr_recall
|
|
673
|
+
out["fp_full_recall"] = int(np.sum(benign & (scores >= thr_recall)))
|
|
674
|
+
|
|
675
|
+
# campaign coverage
|
|
676
|
+
if campaigns and num_campaigns:
|
|
677
|
+
det_camps = set()
|
|
678
|
+
for i in np.where((mal) & (det == 1))[0]:
|
|
679
|
+
for c in campaigns[i]:
|
|
680
|
+
det_camps.add(c)
|
|
681
|
+
out["campaign_coverage_det"] = len(det_camps)
|
|
682
|
+
# threshold so at least one node per campaign passes
|
|
683
|
+
camp_best = {}
|
|
684
|
+
for i in np.where(mal)[0]:
|
|
685
|
+
for c in campaigns[i]:
|
|
686
|
+
camp_best[c] = max(camp_best.get(c, -1e30), scores[i])
|
|
687
|
+
if camp_best:
|
|
688
|
+
thr_camp = float(min(camp_best.values()))
|
|
689
|
+
out["thresh_full_campaign"] = thr_camp
|
|
690
|
+
out["fp_full_campaign"] = int(np.sum(benign & (scores >= thr_camp)))
|
|
691
|
+
return out
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
_build_locks = {}
|
|
695
|
+
_build_locks_guard = threading.Lock()
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _build_lock(path):
|
|
699
|
+
with _build_locks_guard:
|
|
700
|
+
lk = _build_locks.get(path)
|
|
701
|
+
if lk is None:
|
|
702
|
+
lk = _build_locks[path] = threading.Lock()
|
|
703
|
+
return lk
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _read_info(points_path):
|
|
707
|
+
_, _, info_p = _cache_paths(points_path)
|
|
708
|
+
with open(info_p) as f:
|
|
709
|
+
return json.load(f)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _migrate_old_cache(points_path):
|
|
713
|
+
"""Upgrade an existing v1/v2/v3 cache to the current buffer format by
|
|
714
|
+
transforming the binary directly (float16 positions, dropped colour, packed
|
|
715
|
+
flags, packed attrs) instead of re-parsing the 100s-of-MB points.json — ~1 s
|
|
716
|
+
vs ~30 s+. The metadata store is format-unchanged, so it is just copied.
|
|
717
|
+
Returns the v4 info dict, or None if there is no usable old cache to migrate."""
|
|
718
|
+
src_m = os.path.getmtime(points_path) if os.path.exists(points_path) else 0
|
|
719
|
+
bin_p, meta_p, info_p = _cache_paths(points_path) # v4 targets
|
|
720
|
+
for old_v in (3, 2, 1):
|
|
721
|
+
base = points_path + f".webcache_v{old_v}"
|
|
722
|
+
o_bin, o_meta, o_info, o_store = base + ".bin", base + ".meta.json", \
|
|
723
|
+
base + ".info.json", base + ".meta.json.store.npz"
|
|
724
|
+
if not all(os.path.exists(p) for p in (o_bin, o_meta, o_info, o_store)):
|
|
725
|
+
continue
|
|
726
|
+
if os.path.getmtime(o_bin) < src_m: # stale vs source -> real rebuild
|
|
727
|
+
continue
|
|
728
|
+
try:
|
|
729
|
+
with open(o_info) as f:
|
|
730
|
+
info = json.load(f)
|
|
731
|
+
n, H, bo = info["n"], info["hops"], info["byte_offsets"]
|
|
732
|
+
raw = np.fromfile(o_bin, dtype=np.uint8)
|
|
733
|
+
attrs = raw[bo["attrs"]:bo["attrs"] + n * 5 * 4].view(np.float32).reshape(n, 5)
|
|
734
|
+
if old_v == 3: # already f16 pos + u32 ids + u8 meta; only attrs repack
|
|
735
|
+
pos_bytes = raw[bo["positions"]:bo["positions"] + H * n * 3 * 2].tobytes()
|
|
736
|
+
ids_bytes = raw[bo["ids"]:bo["ids"] + n * 4].tobytes()
|
|
737
|
+
meta_bytes = raw[bo["meta"]:bo["meta"] + n].tobytes()
|
|
738
|
+
else: # v1/v2: f32 pos, u32×4 flags -> f16 pos, id + meta byte
|
|
739
|
+
pos = raw[bo["positions"]:bo["positions"] + H * n * 3 * 4].view(np.float32)
|
|
740
|
+
flags = raw[bo["flags"]:bo["flags"] + n * 4 * 4].view(np.uint32).reshape(n, 4)
|
|
741
|
+
pos_bytes = pos.astype(np.float16).tobytes()
|
|
742
|
+
ids_bytes = flags[:, 0].astype(np.uint32).tobytes()
|
|
743
|
+
meta_bytes = (flags[:, 1] | (flags[:, 2] << 1) | (flags[:, 3] << 3)).astype(np.uint8).tobytes()
|
|
744
|
+
tmp = bin_p + ".tmp"
|
|
745
|
+
with open(tmp, "wb") as f:
|
|
746
|
+
f.write(pos_bytes)
|
|
747
|
+
f.write(np.ascontiguousarray(_pack_attrs(attrs)).tobytes())
|
|
748
|
+
f.write(ids_bytes)
|
|
749
|
+
f.write(meta_bytes)
|
|
750
|
+
os.replace(tmp, bin_p)
|
|
751
|
+
shutil.copyfile(o_store, meta_p + ".store.npz")
|
|
752
|
+
shutil.copyfile(o_meta, meta_p)
|
|
753
|
+
info["byte_offsets"] = {"positions": 0, "attrs": H * n * 3 * 2,
|
|
754
|
+
"ids": H * n * 3 * 2 + n * 4 * 2,
|
|
755
|
+
"meta": H * n * 3 * 2 + n * 4 * 2 + n * 4}
|
|
756
|
+
with open(info_p + ".tmp", "w") as f:
|
|
757
|
+
json.dump(info, f)
|
|
758
|
+
os.replace(info_p + ".tmp", info_p)
|
|
759
|
+
print(f"[viz_server] migrated {os.path.basename(points_path)} v{old_v}->v{CACHE_VERSION} (binary, no reparse)")
|
|
760
|
+
return info
|
|
761
|
+
except Exception as e:
|
|
762
|
+
print(f"[viz_server] cache migration failed ({type(e).__name__}: {e}); full rebuild")
|
|
763
|
+
return None
|
|
764
|
+
return None
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def get_info(points_path):
|
|
768
|
+
"""Return cached run info, building the cache once if stale.
|
|
769
|
+
|
|
770
|
+
A per-file lock makes the build single-flight: concurrent requests for the
|
|
771
|
+
same cold run wait for one build instead of racing (which could publish a
|
|
772
|
+
half-written cache). build_cache writes atomically, so a fresh cache is
|
|
773
|
+
always complete. If only an older-version cache exists, migrate its binary
|
|
774
|
+
in place (fast) rather than re-parsing points.json.
|
|
775
|
+
"""
|
|
776
|
+
if _cache_fresh(points_path):
|
|
777
|
+
return _read_info(points_path)
|
|
778
|
+
with _build_lock(points_path):
|
|
779
|
+
if _cache_fresh(points_path): # built while we waited on the lock
|
|
780
|
+
return _read_info(points_path)
|
|
781
|
+
migrated = _migrate_old_cache(points_path) # fast v1/v2 -> v3 binary upgrade
|
|
782
|
+
if migrated is not None:
|
|
783
|
+
return migrated
|
|
784
|
+
return build_cache(points_path)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
# --------------------------------------------------------------------------- #
|
|
788
|
+
# Adjacency index (server-side).
|
|
789
|
+
#
|
|
790
|
+
# The adjacency (``*_adj.json``) is large (tens to hundreds of MB) and re-parsing
|
|
791
|
+
# it on every "See Edges" / causal-trace / attack-overlay action does not scale.
|
|
792
|
+
# Instead we build a compact CSR index once and persist it next to the run as a
|
|
793
|
+
# binary ``.npz``: parsing 75 MB of JSON takes ~2.4 s, but the CSR reloads in
|
|
794
|
+
# ~0.02 s and is half the size — so the cost is paid once, ever (it survives
|
|
795
|
+
# server restarts), and every later query is a small array slice. The index is
|
|
796
|
+
# also warmed in a background thread when a run is opened (see api_run), so the
|
|
797
|
+
# first click is instant. Single-entry in-memory cache bounds RAM to one run.
|
|
798
|
+
# --------------------------------------------------------------------------- #
|
|
799
|
+
|
|
800
|
+
ADJ_INDEX_VERSION = 1
|
|
801
|
+
_META_CACHE = {}
|
|
802
|
+
_ADJ_INDEX = {}
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
class AdjIndex:
|
|
806
|
+
"""CSR adjacency: ``ids[K]`` sorted node ids, ``indptr[K+1]`` offsets, and
|
|
807
|
+
one entry per directed edge — ``nb[M]`` neighbour, ``t[M]`` time,
|
|
808
|
+
``dir[M]`` (1=out, 0=in), ``et[M]`` code into ``vocab`` (relation names)."""
|
|
809
|
+
|
|
810
|
+
def __init__(self, ids, indptr, nb, t, dr, et, vocab):
|
|
811
|
+
self.ids, self.indptr = ids, indptr
|
|
812
|
+
self.nb, self.t, self.dir, self.et = nb, t, dr, et
|
|
813
|
+
self.vocab = vocab
|
|
814
|
+
|
|
815
|
+
def _row(self, node):
|
|
816
|
+
i = int(np.searchsorted(self.ids, node))
|
|
817
|
+
if 0 <= i < len(self.ids) and int(self.ids[i]) == int(node):
|
|
818
|
+
return i
|
|
819
|
+
return -1
|
|
820
|
+
|
|
821
|
+
def neighbors(self, node):
|
|
822
|
+
"""This node's incident edges as ``[{nb, t, dir, et?}]`` — the same shape
|
|
823
|
+
the old per-node adjacency slice returned."""
|
|
824
|
+
i = self._row(node)
|
|
825
|
+
if i < 0:
|
|
826
|
+
return []
|
|
827
|
+
s, e = int(self.indptr[i]), int(self.indptr[i + 1])
|
|
828
|
+
out = []
|
|
829
|
+
for j in range(s, e):
|
|
830
|
+
d = {"nb": int(self.nb[j]), "t": int(self.t[j]),
|
|
831
|
+
"dir": "out" if self.dir[j] else "in"}
|
|
832
|
+
c = int(self.et[j])
|
|
833
|
+
if 0 <= c < len(self.vocab) and self.vocab[c]:
|
|
834
|
+
d["et"] = self.vocab[c]
|
|
835
|
+
out.append(d)
|
|
836
|
+
return out
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def _adj_index_paths(points_path):
|
|
840
|
+
adj_path = points_path.replace("_points.json", "_adj.json")
|
|
841
|
+
base = f"{adj_path}.idxcache_v{ADJ_INDEX_VERSION}"
|
|
842
|
+
return adj_path, base + ".npz", base + ".vocab.json"
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _adj_index_fresh(adj_path, npz_path, vocab_path):
|
|
846
|
+
if not (os.path.exists(npz_path) and os.path.exists(vocab_path)):
|
|
847
|
+
return False
|
|
848
|
+
src = os.path.getmtime(adj_path)
|
|
849
|
+
return all(os.path.getmtime(p) >= src for p in (npz_path, vocab_path))
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def _build_adj_index(adj_path, npz_path, vocab_path):
|
|
853
|
+
"""Parse adj.json once and build the CSR index from it (server path)."""
|
|
854
|
+
with open(adj_path) as f:
|
|
855
|
+
adj = json.load(f)
|
|
856
|
+
return build_adj_index_from_dict(adj, adj_path, npz_path, vocab_path)
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def build_adj_index_from_dict(adj, adj_path, npz_path, vocab_path):
|
|
860
|
+
"""Write the CSR ``.npz`` + relation vocab from an in-memory adjacency dict
|
|
861
|
+
({node_id -> [{nb, t, dir, et?}]}). Shared by the server (parses adj.json)
|
|
862
|
+
and the exporter (passes its dict directly), so no server-side re-parse."""
|
|
863
|
+
t0 = time.time()
|
|
864
|
+
keys = list(adj.keys())
|
|
865
|
+
ids = np.fromiter((int(k) for k in keys), dtype=np.int64, count=len(keys))
|
|
866
|
+
order = np.argsort(ids)
|
|
867
|
+
deg = np.fromiter((len(adj[keys[o]]) for o in order), dtype=np.int64, count=len(keys))
|
|
868
|
+
M = int(deg.sum())
|
|
869
|
+
indptr = np.zeros(len(keys) + 1, dtype=np.int64)
|
|
870
|
+
np.cumsum(deg, out=indptr[1:])
|
|
871
|
+
nb = np.empty(M, np.int64)
|
|
872
|
+
t = np.empty(M, np.int32)
|
|
873
|
+
dr = np.empty(M, np.uint8)
|
|
874
|
+
et = np.empty(M, np.int32)
|
|
875
|
+
vocab, vidx = [""], {"": 0}
|
|
876
|
+
p = 0
|
|
877
|
+
for o in order:
|
|
878
|
+
for e in adj[keys[o]]:
|
|
879
|
+
nb[p] = e["nb"]
|
|
880
|
+
t[p] = e.get("t", 0)
|
|
881
|
+
dr[p] = 1 if e.get("dir") == "out" else 0
|
|
882
|
+
s = e.get("et") or ""
|
|
883
|
+
c = vidx.get(s)
|
|
884
|
+
if c is None:
|
|
885
|
+
c = vidx[s] = len(vocab)
|
|
886
|
+
vocab.append(s)
|
|
887
|
+
et[p] = c
|
|
888
|
+
p += 1
|
|
889
|
+
ids_sorted = ids[order]
|
|
890
|
+
tmp = npz_path + ".tmp.npz"
|
|
891
|
+
np.savez(tmp, ids=ids_sorted, indptr=indptr, nb=nb, t=t, dir=dr, et=et)
|
|
892
|
+
os.replace(tmp if os.path.exists(tmp) else tmp + ".npz", npz_path)
|
|
893
|
+
vtmp = vocab_path + ".tmp"
|
|
894
|
+
with open(vtmp, "w") as f:
|
|
895
|
+
json.dump(vocab, f)
|
|
896
|
+
os.replace(vtmp, vocab_path)
|
|
897
|
+
print(f"[viz_server] built adjacency index for {os.path.basename(adj_path)} "
|
|
898
|
+
f"({len(keys)} nodes, {M} edges) in {time.time()-t0:.1f}s")
|
|
899
|
+
return AdjIndex(ids_sorted, indptr, nb, t, dr, et, vocab)
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def _load_adj_index(npz_path, vocab_path):
|
|
903
|
+
z = np.load(npz_path)
|
|
904
|
+
with open(vocab_path) as f:
|
|
905
|
+
vocab = json.load(f)
|
|
906
|
+
return AdjIndex(z["ids"], z["indptr"], z["nb"], z["t"], z["dir"], z["et"], vocab)
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def get_adj_index(points_path):
|
|
910
|
+
"""Return the run's :class:`AdjIndex`, building+persisting it on first use.
|
|
911
|
+
|
|
912
|
+
Single-flight (per-file lock) and cached in memory; returns None if the run
|
|
913
|
+
has no adjacency file.
|
|
914
|
+
"""
|
|
915
|
+
adj_path, npz_path, vocab_path = _adj_index_paths(points_path)
|
|
916
|
+
if not os.path.exists(adj_path):
|
|
917
|
+
return None
|
|
918
|
+
key = (adj_path, os.path.getmtime(adj_path))
|
|
919
|
+
if _ADJ_INDEX.get("key") == key:
|
|
920
|
+
return _ADJ_INDEX["index"]
|
|
921
|
+
with _build_lock(adj_path):
|
|
922
|
+
if _ADJ_INDEX.get("key") == key: # built while we waited
|
|
923
|
+
return _ADJ_INDEX["index"]
|
|
924
|
+
idx = None
|
|
925
|
+
if _adj_index_fresh(adj_path, npz_path, vocab_path):
|
|
926
|
+
try:
|
|
927
|
+
idx = _load_adj_index(npz_path, vocab_path)
|
|
928
|
+
except Exception as e: # corrupt/partial/version-skewed cache -> rebuild
|
|
929
|
+
print(f"[viz_server] adj index reload failed ({e}); rebuilding")
|
|
930
|
+
if idx is None:
|
|
931
|
+
idx = _build_adj_index(adj_path, npz_path, vocab_path)
|
|
932
|
+
_ADJ_INDEX.clear()
|
|
933
|
+
_ADJ_INDEX["key"] = key
|
|
934
|
+
_ADJ_INDEX["index"] = idx
|
|
935
|
+
return idx
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
# Heavy background cache builds are serialized through this semaphore so warming
|
|
939
|
+
# a run's many sibling epoch caches uses ~one core instead of thrashing all of
|
|
940
|
+
# them at once (and competing with whatever the user is actively viewing).
|
|
941
|
+
_WARM_SEMA = threading.Semaphore(1)
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def warm_run(points_path):
|
|
945
|
+
"""Warm everything needed to make a freshly-opened run feel instant.
|
|
946
|
+
|
|
947
|
+
First the opened file's graph tools (adjacency index, derived id-maps), then
|
|
948
|
+
— low priority, one at a time — the point caches of the sibling embedding /
|
|
949
|
+
epoch files, so switching embedding space or epoch does not pay a cold
|
|
950
|
+
``build_cache`` parse of a 100-600 MB points file. Best-effort.
|
|
951
|
+
|
|
952
|
+
NOT the campaign graph: it is a pure-Python build that, on a large run, holds
|
|
953
|
+
the GIL long enough to starve the buffer/meta requests the user is actively
|
|
954
|
+
waiting on. It is cached on first click of "Campaign Attack Graph" instead.
|
|
955
|
+
"""
|
|
956
|
+
try:
|
|
957
|
+
get_adj_index(points_path)
|
|
958
|
+
load_meta(points_path) # builds/loads the binary metadata store
|
|
959
|
+
except Exception as e:
|
|
960
|
+
print(f"[viz_server] warm_run(graph) failed for {os.path.basename(points_path)}: {e}")
|
|
961
|
+
|
|
962
|
+
try:
|
|
963
|
+
viz_dir = os.path.dirname(points_path)
|
|
964
|
+
siblings = [s for s in sorted(glob.glob(os.path.join(viz_dir, "*_points.json")))
|
|
965
|
+
if s != points_path]
|
|
966
|
+
except Exception:
|
|
967
|
+
siblings = []
|
|
968
|
+
for sib in siblings:
|
|
969
|
+
if _cache_fresh(sib):
|
|
970
|
+
continue
|
|
971
|
+
with _WARM_SEMA: # one heavy build at a time, globally
|
|
972
|
+
try:
|
|
973
|
+
if not _cache_fresh(sib):
|
|
974
|
+
get_info(sib) # single-flight build; a concurrent switch shares it
|
|
975
|
+
print(f"[viz_server] warmed switch cache: {os.path.basename(sib)}")
|
|
976
|
+
except Exception as e:
|
|
977
|
+
print(f"[viz_server] warm sibling cache failed for {os.path.basename(sib)}: {e}")
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
# --------------------------------------------------------------------------- #
|
|
981
|
+
# Binary metadata store.
|
|
982
|
+
#
|
|
983
|
+
# The columnar metadata is mostly strings (paths); parsing the JSON and
|
|
984
|
+
# materialising millions of Python strings is the dominant open cost at scale
|
|
985
|
+
# (~10 s for THEIA's 2.1 M rows, worse for E5). Instead we persist a binary
|
|
986
|
+
# store: numeric columns are plain arrays (instant load), string columns are one
|
|
987
|
+
# byte-blob + offsets (decode only the rows actually requested), and a sorted
|
|
988
|
+
# unique-id index gives O(log n) id->row lookup with no per-request scan. Built
|
|
989
|
+
# once (at export, or lazily from meta.json for older runs) and reused forever.
|
|
990
|
+
# --------------------------------------------------------------------------- #
|
|
991
|
+
|
|
992
|
+
_meta_lock = threading.Lock()
|
|
993
|
+
_META_STRCOLS = ("paths", "types", "cmds", "tw_labels", "top_edges")
|
|
994
|
+
|
|
995
|
+
_OFF_GRAPH = {"tw": "—", "type": "Filtered/Off-Graph", "score": 0,
|
|
996
|
+
"path": "", "cmd": "", "label": 0, "twi": None}
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
class StrCol:
|
|
1000
|
+
"""A string column stored as a UTF-8 blob + int64 offsets. Decodes lazily,
|
|
1001
|
+
so a slice/lookup costs only the strings it touches, not the whole column."""
|
|
1002
|
+
|
|
1003
|
+
def __init__(self, blob, off):
|
|
1004
|
+
self.blob, self.off = blob, off
|
|
1005
|
+
self._raw = None
|
|
1006
|
+
|
|
1007
|
+
def raw_bytes(self):
|
|
1008
|
+
"""The whole column as one bytes object (cached) — for a full-text scan
|
|
1009
|
+
that never decodes individual rows."""
|
|
1010
|
+
if self._raw is None:
|
|
1011
|
+
self._raw = self.blob.tobytes()
|
|
1012
|
+
return self._raw
|
|
1013
|
+
|
|
1014
|
+
def __getitem__(self, i):
|
|
1015
|
+
"""Decode a single row (used by the per-node inspector / See-Edges rows)."""
|
|
1016
|
+
a, b = int(self.off[i]), int(self.off[i + 1])
|
|
1017
|
+
return self.blob[a:b].tobytes().decode("utf-8", "replace") if b > a else ""
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
class MetaStore:
|
|
1021
|
+
"""Columnar metadata backed by binary arrays; dict-style access for numeric
|
|
1022
|
+
columns returns numpy arrays, string columns return lazy :class:`StrCol`."""
|
|
1023
|
+
|
|
1024
|
+
def __init__(self, z):
|
|
1025
|
+
self._num = {k: z[k] for k in ("ids", "scores", "labels", "det", "tw_idx", "type_enum")}
|
|
1026
|
+
self._str = {c: StrCol(z[c + "_blob"], z[c + "_off"]) for c in _META_STRCOLS}
|
|
1027
|
+
self.n = len(self._num["ids"])
|
|
1028
|
+
self.uniq_ids = z["uniq_ids"] # sorted unique node ids
|
|
1029
|
+
self.first_idx = z["first_idx"] # first row index per unique id
|
|
1030
|
+
self.first_tw = self._num["tw_idx"][self.first_idx]
|
|
1031
|
+
self.first_label = self._num["labels"][self.first_idx]
|
|
1032
|
+
self._camp = (z["camp_data"], z["camp_off"]) if "camp_data" in z.files else None
|
|
1033
|
+
|
|
1034
|
+
def __contains__(self, k):
|
|
1035
|
+
return k in self._num or k in self._str or (k == "campaigns" and self._camp is not None)
|
|
1036
|
+
|
|
1037
|
+
def __getitem__(self, k):
|
|
1038
|
+
if k in self._num:
|
|
1039
|
+
return self._num[k]
|
|
1040
|
+
if k in self._str:
|
|
1041
|
+
return self._str[k]
|
|
1042
|
+
if k == "campaigns" and self._camp is not None:
|
|
1043
|
+
return self._camp_rows(0, self.n)
|
|
1044
|
+
raise KeyError(k)
|
|
1045
|
+
|
|
1046
|
+
def get(self, k, default=None):
|
|
1047
|
+
try:
|
|
1048
|
+
return self[k]
|
|
1049
|
+
except KeyError:
|
|
1050
|
+
return default
|
|
1051
|
+
|
|
1052
|
+
def _pos(self, node_id):
|
|
1053
|
+
i = int(np.searchsorted(self.uniq_ids, node_id))
|
|
1054
|
+
if 0 <= i < len(self.uniq_ids) and int(self.uniq_ids[i]) == int(node_id):
|
|
1055
|
+
return i
|
|
1056
|
+
return -1
|
|
1057
|
+
|
|
1058
|
+
def first_index(self, node_id):
|
|
1059
|
+
p = self._pos(node_id)
|
|
1060
|
+
return int(self.first_idx[p]) if p >= 0 else -1
|
|
1061
|
+
|
|
1062
|
+
def first_tw_of(self, node_id):
|
|
1063
|
+
p = self._pos(node_id)
|
|
1064
|
+
return int(self.first_tw[p]) if p >= 0 else 0
|
|
1065
|
+
|
|
1066
|
+
def label_of(self, node_id):
|
|
1067
|
+
p = self._pos(node_id)
|
|
1068
|
+
return int(self.first_label[p]) if p >= 0 else 0
|
|
1069
|
+
|
|
1070
|
+
def malicious_ids(self):
|
|
1071
|
+
return set(self.uniq_ids[self.first_label != 0].tolist())
|
|
1072
|
+
|
|
1073
|
+
def row(self, i):
|
|
1074
|
+
"""The per-node fields the inspector tables show (mirrors client rowMeta)."""
|
|
1075
|
+
if i < 0:
|
|
1076
|
+
return dict(_OFF_GRAPH)
|
|
1077
|
+
return {
|
|
1078
|
+
"tw": self._str["tw_labels"][i] or int(self._num["tw_idx"][i]),
|
|
1079
|
+
"type": self._str["types"][i], "score": float(self._num["scores"][i]),
|
|
1080
|
+
"path": self._str["paths"][i], "cmd": self._str["cmds"][i],
|
|
1081
|
+
"label": int(self._num["labels"][i]), "twi": int(self._num["tw_idx"][i]),
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
def node_at(self, i):
|
|
1085
|
+
"""Full metadata for buffer row i (== store row i). Used by index-based
|
|
1086
|
+
selection so the client needn't hold the node-id column up front. O(1)."""
|
|
1087
|
+
if not (0 <= i < self.n):
|
|
1088
|
+
return None
|
|
1089
|
+
r = self.row(i)
|
|
1090
|
+
r["top_edge"] = self._str["top_edges"][i]
|
|
1091
|
+
r["id"] = int(self._num["ids"][i])
|
|
1092
|
+
return r
|
|
1093
|
+
|
|
1094
|
+
def search(self, terms, limit=20000):
|
|
1095
|
+
"""Buffer ROWS whose path or command matches any term, plus exact id hits.
|
|
1096
|
+
Scans the raw UTF-8 blobs with one alternation regex (no per-row decode),
|
|
1097
|
+
maps match byte-offsets back to rows — fast even at 20M+ nodes. Returns
|
|
1098
|
+
rows (== buffer indices) so the client filters by index without the ids."""
|
|
1099
|
+
if isinstance(terms, str):
|
|
1100
|
+
terms = [terms]
|
|
1101
|
+
terms = [t.strip().lower() for t in terms if t and t.strip()]
|
|
1102
|
+
if not terms:
|
|
1103
|
+
return []
|
|
1104
|
+
pat = re.compile(b"|".join(re.escape(t.encode("utf-8")) for t in terms), re.IGNORECASE)
|
|
1105
|
+
out, seen = [], set()
|
|
1106
|
+
for col in (self._str["paths"], self._str["cmds"]):
|
|
1107
|
+
blob, off = col.raw_bytes(), col.off
|
|
1108
|
+
for m in pat.finditer(blob):
|
|
1109
|
+
row = int(np.searchsorted(off, m.start(), side="right")) - 1
|
|
1110
|
+
# ignore a match that straddles two concatenated strings
|
|
1111
|
+
if 0 <= row < self.n and int(off[row + 1]) >= m.end() and row not in seen:
|
|
1112
|
+
seen.add(row)
|
|
1113
|
+
out.append(row)
|
|
1114
|
+
if len(out) >= limit:
|
|
1115
|
+
return out
|
|
1116
|
+
for t in terms: # exact node-id match -> all its rows
|
|
1117
|
+
if t.isdigit():
|
|
1118
|
+
for row in np.nonzero(self._num["ids"] == int(t))[0].tolist():
|
|
1119
|
+
if row not in seen:
|
|
1120
|
+
seen.add(row)
|
|
1121
|
+
out.append(row)
|
|
1122
|
+
if len(out) >= limit:
|
|
1123
|
+
return out
|
|
1124
|
+
return out
|
|
1125
|
+
|
|
1126
|
+
def _camp_rows(self, start, end):
|
|
1127
|
+
d, o = self._camp
|
|
1128
|
+
return [d[int(o[i]):int(o[i + 1])].tolist() for i in range(start, min(end, self.n))]
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _pack_strings(lst):
|
|
1132
|
+
enc = [(s.encode("utf-8") if s else b"") for s in lst]
|
|
1133
|
+
off = np.zeros(len(enc) + 1, dtype=np.int64)
|
|
1134
|
+
np.cumsum(np.fromiter((len(e) for e in enc), dtype=np.int64, count=len(enc)), out=off[1:])
|
|
1135
|
+
blob = np.frombuffer(b"".join(enc), dtype=np.uint8) if off[-1] else np.zeros(0, np.uint8)
|
|
1136
|
+
return blob, off
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _meta_store_path(points_path):
|
|
1140
|
+
_, meta_p, _ = _cache_paths(points_path)
|
|
1141
|
+
return meta_p, meta_p + ".store.npz"
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
def build_meta_store(meta, store_path):
|
|
1145
|
+
"""Write the binary metadata store from an in-memory columnar meta dict
|
|
1146
|
+
(called at export, and lazily from a parsed meta.json for older runs)."""
|
|
1147
|
+
ids = np.asarray(meta["ids"], dtype=np.int64)
|
|
1148
|
+
arrays = {
|
|
1149
|
+
"ids": ids,
|
|
1150
|
+
"scores": np.asarray(meta["scores"], dtype=np.float32),
|
|
1151
|
+
"labels": np.asarray(meta["labels"], dtype=np.int8),
|
|
1152
|
+
"det": np.asarray(meta["det"], dtype=np.int8),
|
|
1153
|
+
"tw_idx": np.asarray(meta["tw_idx"], dtype=np.int32),
|
|
1154
|
+
"type_enum": np.fromiter((_type_enum(t) for t in meta["types"]), dtype=np.int8, count=len(ids)),
|
|
1155
|
+
}
|
|
1156
|
+
for c in _META_STRCOLS:
|
|
1157
|
+
arrays[c + "_blob"], arrays[c + "_off"] = _pack_strings(meta[c])
|
|
1158
|
+
uniq, first = np.unique(ids, return_index=True)
|
|
1159
|
+
arrays["uniq_ids"] = uniq
|
|
1160
|
+
arrays["first_idx"] = first.astype(np.int64)
|
|
1161
|
+
camp = meta.get("campaigns")
|
|
1162
|
+
if camp is not None:
|
|
1163
|
+
off = np.zeros(len(camp) + 1, dtype=np.int64)
|
|
1164
|
+
np.cumsum(np.fromiter((len(c) for c in camp), dtype=np.int64, count=len(camp)), out=off[1:])
|
|
1165
|
+
data = np.fromiter((x for c in camp for x in c), dtype=np.int64, count=int(off[-1]))
|
|
1166
|
+
arrays["camp_data"], arrays["camp_off"] = data, off
|
|
1167
|
+
tmp = store_path + ".tmp.npz"
|
|
1168
|
+
np.savez(tmp, **arrays)
|
|
1169
|
+
os.replace(tmp if os.path.exists(tmp) else tmp + ".npz", store_path)
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
def load_meta(points_path):
|
|
1173
|
+
"""Return the run's :class:`MetaStore` (cached, single-flight). Builds the
|
|
1174
|
+
binary store once from meta.json if it doesn't exist yet."""
|
|
1175
|
+
meta_p, store_p = _meta_store_path(points_path)
|
|
1176
|
+
src_m = os.path.getmtime(meta_p) if os.path.exists(meta_p) else 0
|
|
1177
|
+
fresh = os.path.exists(store_p) and os.path.getmtime(store_p) >= src_m
|
|
1178
|
+
if fresh and _META_CACHE.get("key") == store_p:
|
|
1179
|
+
return _META_CACHE["store"]
|
|
1180
|
+
with _meta_lock:
|
|
1181
|
+
if os.path.exists(store_p) and os.path.getmtime(store_p) >= src_m \
|
|
1182
|
+
and _META_CACHE.get("key") == store_p:
|
|
1183
|
+
return _META_CACHE["store"]
|
|
1184
|
+
if not (os.path.exists(store_p) and os.path.getmtime(store_p) >= src_m):
|
|
1185
|
+
with open(meta_p) as f: # one-time parse for pre-store runs
|
|
1186
|
+
build_meta_store(json.load(f), store_p)
|
|
1187
|
+
store = MetaStore(np.load(store_p))
|
|
1188
|
+
_META_CACHE.clear()
|
|
1189
|
+
_META_CACHE["store"] = store
|
|
1190
|
+
_META_CACHE["key"] = store_p
|
|
1191
|
+
return store
|
|
1192
|
+
|
|
1193
|
+
|
|
1194
|
+
def causal_trace(index, start, start_tw, limit=10000):
|
|
1195
|
+
"""Time-respecting causal traversal from *start* (mirrors the client BFS).
|
|
1196
|
+
|
|
1197
|
+
Follows out-edges forward in time (t_edge >= t) and in-edges backward
|
|
1198
|
+
(t_edge <= t). Returns the ordered list of reached node ids (<= limit).
|
|
1199
|
+
"""
|
|
1200
|
+
visited, result, order = set(), set(), []
|
|
1201
|
+
stack = [(start, start_tw)]
|
|
1202
|
+
while stack and len(result) < limit:
|
|
1203
|
+
node, t = stack.pop()
|
|
1204
|
+
k = (node, t)
|
|
1205
|
+
if k in visited:
|
|
1206
|
+
continue
|
|
1207
|
+
visited.add(k)
|
|
1208
|
+
if node not in result:
|
|
1209
|
+
result.add(node)
|
|
1210
|
+
order.append(node)
|
|
1211
|
+
for e in index.neighbors(node):
|
|
1212
|
+
te = e["t"]
|
|
1213
|
+
if e["dir"] == "out" and te >= t:
|
|
1214
|
+
stack.append((e["nb"], te))
|
|
1215
|
+
elif e["dir"] == "in" and te <= t:
|
|
1216
|
+
stack.append((e["nb"], te))
|
|
1217
|
+
return order
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
# --------------------------------------------------------------------------- #
|
|
1221
|
+
# Export job manager (single concurrent job)
|
|
1222
|
+
#
|
|
1223
|
+
# Runs the standalone viz exporter (pidsmaker.vizgen.web.export) as a
|
|
1224
|
+
# subprocess and streams its stdout to the browser over SSE, so the user can
|
|
1225
|
+
# generate viz data for a run from the browser and watch the logs live. Spawned
|
|
1226
|
+
# with PYTHONUNBUFFERED=1 because the exporter's log() uses unflushed print(),
|
|
1227
|
+
# which would otherwise block-buffer over a pipe.
|
|
1228
|
+
# --------------------------------------------------------------------------- #
|
|
1229
|
+
|
|
1230
|
+
ALLOW_EXPORT = os.environ.get("PIDS_VIZ_ALLOW_EXPORT", "1") not in ("0", "false", "False")
|
|
1231
|
+
|
|
1232
|
+
# (key, label, [stdout substrings that mark entering this phase]) — ordered
|
|
1233
|
+
_PHASES = [
|
|
1234
|
+
("start", "Start", ["embedding extraction..."]),
|
|
1235
|
+
("graphs", "Load graphs", ["Loading preprocessed", "No cached graphs found"]),
|
|
1236
|
+
("model", "Model", ["Loaded model weights", "Evaluation Stats: Found"]),
|
|
1237
|
+
("embeddings", "Embeddings", ["[embed_exporter] Extracted", "Computed ", "Sampled:"]),
|
|
1238
|
+
("umap", "UMAP", ["Running UMAP for Hop", "[dim_reduction] Reducing"]),
|
|
1239
|
+
("write", "Write", ["Building interactive HTML", "Saved visualization to:"]),
|
|
1240
|
+
]
|
|
1241
|
+
PHASE_KEYS = [p[0] for p in _PHASES]
|
|
1242
|
+
PHASE_LABELS = {p[0]: p[1] for p in _PHASES}
|
|
1243
|
+
|
|
1244
|
+
_job_lock = threading.Lock()
|
|
1245
|
+
CURRENT_JOB = None
|
|
1246
|
+
STARTUP_STALL_LIMIT = 120 # s of silence at the "start" phase before aborting a wedged job
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def _classify_phase(line):
|
|
1250
|
+
for key, _label, markers in _PHASES:
|
|
1251
|
+
if any(m in line for m in markers):
|
|
1252
|
+
return key
|
|
1253
|
+
return None
|
|
1254
|
+
|
|
1255
|
+
|
|
1256
|
+
def _resolve_model(run_dir, embeddings):
|
|
1257
|
+
cfg_path = os.path.join(run_dir, "run_config.yml")
|
|
1258
|
+
if not os.path.exists(cfg_path):
|
|
1259
|
+
cfg_path = os.path.join(os.path.dirname(run_dir), "run_config.yml")
|
|
1260
|
+
m = _raw_model(cfg_path)
|
|
1261
|
+
if m:
|
|
1262
|
+
return m
|
|
1263
|
+
return "velox" if embeddings == "word2vec" else "orthrus"
|
|
1264
|
+
|
|
1265
|
+
|
|
1266
|
+
def _broadcast(job, msg):
|
|
1267
|
+
for q in list(job["subscribers"]):
|
|
1268
|
+
try:
|
|
1269
|
+
q.put_nowait(msg)
|
|
1270
|
+
except Exception:
|
|
1271
|
+
pass
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _append_line(job, line):
|
|
1275
|
+
"""Append a log line with a monotonic index and broadcast it. Shared by the
|
|
1276
|
+
subprocess reader and the startup watchdog (the client dedupes by index, so
|
|
1277
|
+
the two threads must not reuse an index)."""
|
|
1278
|
+
with job["ilock"]:
|
|
1279
|
+
idx = (job["lines"][-1][0] + 1) if job["lines"] else 1
|
|
1280
|
+
job["lines"].append((idx, line))
|
|
1281
|
+
_broadcast(job, {"type": "log", "i": idx, "line": line})
|
|
1282
|
+
return idx
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
def _reader_thread(job, proc):
|
|
1286
|
+
for raw in iter(proc.stdout.readline, ""):
|
|
1287
|
+
line = raw.rstrip("\n")
|
|
1288
|
+
if not line:
|
|
1289
|
+
continue
|
|
1290
|
+
job["last_out"] = time.time()
|
|
1291
|
+
ph = _classify_phase(line)
|
|
1292
|
+
if ph and ph != job["phase"]:
|
|
1293
|
+
job["phase"] = ph
|
|
1294
|
+
_broadcast(job, {"type": "phase", "phase": ph})
|
|
1295
|
+
_append_line(job, line)
|
|
1296
|
+
try:
|
|
1297
|
+
proc.stdout.close()
|
|
1298
|
+
except Exception:
|
|
1299
|
+
pass
|
|
1300
|
+
rc = proc.wait()
|
|
1301
|
+
job["returncode"] = rc
|
|
1302
|
+
job["ended"] = time.time()
|
|
1303
|
+
if job["status"] != "canceled":
|
|
1304
|
+
job["status"] = "done" if rc == 0 else "failed"
|
|
1305
|
+
# rc < 0 means killed by signal (-9 = SIGKILL); surface it in the console so a
|
|
1306
|
+
# silent death isn't mistaken for "nothing happened".
|
|
1307
|
+
print(f"[viz_server] export job {job['id']} ended: status={job['status']} rc={rc}")
|
|
1308
|
+
if rc and rc < 0:
|
|
1309
|
+
_append_line(job, f"[server] process was killed by signal {-rc}")
|
|
1310
|
+
if rc == 0:
|
|
1311
|
+
try:
|
|
1312
|
+
_refresh_runs() # newly-generated run must show up in the browser now
|
|
1313
|
+
except Exception:
|
|
1314
|
+
pass
|
|
1315
|
+
_broadcast(job, {"type": "status", "status": job["status"], "returncode": rc})
|
|
1316
|
+
_broadcast(job, None) # sentinel: terminate open streams
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
def start_export(opts):
|
|
1320
|
+
global CURRENT_JOB
|
|
1321
|
+
with _job_lock:
|
|
1322
|
+
# Busy only if the previous job's process is genuinely still alive. If it
|
|
1323
|
+
# died hard (e.g. OOM-killed) before the reader updated status, poll() is
|
|
1324
|
+
# not None — reap it so a new generation isn't wedged behind a dead job.
|
|
1325
|
+
if CURRENT_JOB and CURRENT_JOB["status"] == "running":
|
|
1326
|
+
if CURRENT_JOB["proc"].poll() is None:
|
|
1327
|
+
return None, CURRENT_JOB["id"]
|
|
1328
|
+
CURRENT_JOB["status"] = "failed"
|
|
1329
|
+
print(f"[viz_server] reaped dead export job {CURRENT_JOB['id']} "
|
|
1330
|
+
f"(rc={CURRENT_JOB['proc'].returncode})")
|
|
1331
|
+
run_dir = opts["run_dir"]
|
|
1332
|
+
dataset = os.path.basename(run_dir)
|
|
1333
|
+
embeddings = opts.get("embeddings", "both")
|
|
1334
|
+
model = _resolve_model(run_dir, embeddings)
|
|
1335
|
+
cmd = [sys.executable, "-u", "-m", "pidsmaker.vizgen.web.export",
|
|
1336
|
+
model, dataset, "--run", run_dir, "--embeddings", embeddings]
|
|
1337
|
+
if opts.get("all_epochs"):
|
|
1338
|
+
cmd.append("--all_epochs")
|
|
1339
|
+
if opts.get("method"):
|
|
1340
|
+
cmd += ["--method", str(opts["method"])]
|
|
1341
|
+
if opts.get("max_benign"):
|
|
1342
|
+
cmd += ["--max_benign", str(opts["max_benign"])]
|
|
1343
|
+
if opts.get("max_attack"):
|
|
1344
|
+
cmd += ["--max_attack", str(opts["max_attack"])]
|
|
1345
|
+
|
|
1346
|
+
env = {**os.environ, "PYTHONUNBUFFERED": "1"}
|
|
1347
|
+
print(f"[viz_server] starting export: {' '.join(cmd)}")
|
|
1348
|
+
proc = subprocess.Popen(
|
|
1349
|
+
cmd, cwd=PIDSMAKER_ROOT, env=env,
|
|
1350
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
1351
|
+
text=True, bufsize=1,
|
|
1352
|
+
start_new_session=True, # own process group, so cancel kills children too
|
|
1353
|
+
)
|
|
1354
|
+
job = {
|
|
1355
|
+
"id": uuid.uuid4().hex[:12],
|
|
1356
|
+
"run_dir": run_dir, "dataset": dataset, "model": model,
|
|
1357
|
+
"cmd": " ".join(cmd), "status": "running", "phase": "start",
|
|
1358
|
+
"started": time.time(), "ended": None, "returncode": None,
|
|
1359
|
+
"last_out": time.time(), "ilock": threading.Lock(),
|
|
1360
|
+
"lines": deque(maxlen=5000), "subscribers": [], "proc": proc,
|
|
1361
|
+
}
|
|
1362
|
+
job["lines"].append((0, "[server] launching generation…"))
|
|
1363
|
+
CURRENT_JOB = job
|
|
1364
|
+
threading.Thread(target=_reader_thread, args=(job, proc), daemon=True).start()
|
|
1365
|
+
threading.Thread(target=_watchdog_thread, args=(job,), daemon=True).start()
|
|
1366
|
+
return job, None
|
|
1367
|
+
|
|
1368
|
+
|
|
1369
|
+
def _watchdog_thread(job):
|
|
1370
|
+
"""Abort a job wedged in startup so it can't block the next generation forever.
|
|
1371
|
+
Phase still "start" means it never reached any real work; if it's also been
|
|
1372
|
+
silent past STARTUP_STALL_LIMIT the process is hung (e.g. a busy GPU during CUDA
|
|
1373
|
+
init) rather than merely slow. Only the "start" phase is guarded — real work may
|
|
1374
|
+
legitimately be quiet for a while."""
|
|
1375
|
+
while job["status"] == "running":
|
|
1376
|
+
time.sleep(5)
|
|
1377
|
+
if job["status"] != "running":
|
|
1378
|
+
return
|
|
1379
|
+
if job["phase"] == "start" and time.time() - job["last_out"] >= STARTUP_STALL_LIMIT:
|
|
1380
|
+
_append_line(job, f"[server] aborting — no progress for {STARTUP_STALL_LIMIT}s during "
|
|
1381
|
+
f"startup; the GPU may be busy (check nvidia-smi). Try again.")
|
|
1382
|
+
job["status"] = "failed"
|
|
1383
|
+
try:
|
|
1384
|
+
os.killpg(os.getpgid(job["proc"].pid), signal.SIGKILL)
|
|
1385
|
+
except Exception:
|
|
1386
|
+
try:
|
|
1387
|
+
job["proc"].kill()
|
|
1388
|
+
except Exception:
|
|
1389
|
+
pass
|
|
1390
|
+
return
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
def cancel_export():
|
|
1394
|
+
job = CURRENT_JOB
|
|
1395
|
+
if job and job["status"] == "running":
|
|
1396
|
+
job["status"] = "canceled"
|
|
1397
|
+
proc = job["proc"]
|
|
1398
|
+
|
|
1399
|
+
def _kill(): # escalate SIGTERM -> SIGKILL so a canceled job can't linger
|
|
1400
|
+
for sig, wait in ((signal.SIGTERM, 8), (signal.SIGKILL, 3)):
|
|
1401
|
+
if proc.poll() is not None:
|
|
1402
|
+
return
|
|
1403
|
+
try:
|
|
1404
|
+
os.killpg(os.getpgid(proc.pid), sig)
|
|
1405
|
+
except Exception:
|
|
1406
|
+
try:
|
|
1407
|
+
proc.terminate() if sig == signal.SIGTERM else proc.kill()
|
|
1408
|
+
except Exception:
|
|
1409
|
+
pass
|
|
1410
|
+
try:
|
|
1411
|
+
proc.wait(timeout=wait)
|
|
1412
|
+
except Exception:
|
|
1413
|
+
pass
|
|
1414
|
+
threading.Thread(target=_kill, daemon=True).start()
|
|
1415
|
+
return True
|
|
1416
|
+
return False
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def job_snapshot(job, tail=400):
|
|
1420
|
+
return {
|
|
1421
|
+
"id": job["id"], "status": job["status"], "phase": job["phase"],
|
|
1422
|
+
"model": job["model"], "dataset": job["dataset"], "run_dir": job["run_dir"],
|
|
1423
|
+
"cmd": job["cmd"], "started": job["started"],
|
|
1424
|
+
"elapsed": round((job["ended"] or time.time()) - job["started"], 1),
|
|
1425
|
+
"returncode": job["returncode"],
|
|
1426
|
+
"tail": [{"i": i, "line": l} for i, l in list(job["lines"])[-tail:]],
|
|
1427
|
+
"phases": PHASE_KEYS, "phase_labels": PHASE_LABELS,
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
def _sse(obj):
|
|
1432
|
+
return f"data: {json.dumps(obj)}\n\n"
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
# --------------------------------------------------------------------------- #
|
|
1436
|
+
# Score distribution — rendered server-side with the exact native matplotlib
|
|
1437
|
+
# figure (so it is pixel-identical to the desktop viewer), returned as PNG.
|
|
1438
|
+
# --------------------------------------------------------------------------- #
|
|
1439
|
+
|
|
1440
|
+
_SCOREDIST_CACHE = {}
|
|
1441
|
+
|
|
1442
|
+
|
|
1443
|
+
def render_score_distribution(points_path):
|
|
1444
|
+
import io
|
|
1445
|
+
|
|
1446
|
+
import matplotlib
|
|
1447
|
+
matplotlib.use("Agg")
|
|
1448
|
+
import matplotlib.pyplot as plt
|
|
1449
|
+
from matplotlib.patches import Patch
|
|
1450
|
+
|
|
1451
|
+
get_info(points_path) # ensure cache
|
|
1452
|
+
_, meta_p, info_p = _cache_paths(points_path)
|
|
1453
|
+
# the plot is deterministic per run — cache the rendered PNG so re-opening the
|
|
1454
|
+
# dialog is instant instead of re-rendering (matplotlib over millions of scores).
|
|
1455
|
+
store_npz = meta_p + ".store.npz"
|
|
1456
|
+
ck = (points_path, os.path.getmtime(store_npz) if os.path.exists(store_npz) else 0)
|
|
1457
|
+
if ck in _SCOREDIST_CACHE:
|
|
1458
|
+
return _SCOREDIST_CACHE[ck]
|
|
1459
|
+
store = load_meta(points_path)
|
|
1460
|
+
with open(info_p) as f:
|
|
1461
|
+
info = json.load(f)
|
|
1462
|
+
|
|
1463
|
+
raw_scores = np.asarray(store["scores"], dtype=float)
|
|
1464
|
+
labels = np.asarray(store["labels"], dtype=int)
|
|
1465
|
+
type_enum = np.asarray(store["type_enum"], dtype=int) # 0 proc,1 file,2 netflow,3 other
|
|
1466
|
+
campaigns = store.get("campaigns")
|
|
1467
|
+
num_campaigns = info.get("num_campaigns", 0)
|
|
1468
|
+
cur_thr = (info.get("detection_cost") or {}).get("current_threshold")
|
|
1469
|
+
|
|
1470
|
+
raw_min, raw_max = float(np.min(raw_scores)), float(np.max(raw_scores))
|
|
1471
|
+
span = (raw_max - raw_min) if raw_max > raw_min else 1.0
|
|
1472
|
+
norm_scores = (raw_scores - raw_min) / span
|
|
1473
|
+
|
|
1474
|
+
benign_type_colors = {"subject": "#1b5e20", "file": "#bbbbbb", "netflow": "#a5d6a7"}
|
|
1475
|
+
alpha_val = 0.7
|
|
1476
|
+
attack_colors = {0: "black", 1: "red", 2: "#377eb8"}
|
|
1477
|
+
|
|
1478
|
+
# Split benign scores by node type with vectorised numpy masks instead of a
|
|
1479
|
+
# Python loop over every node — the loop was O(N) in the interpreter (~27s at
|
|
1480
|
+
# 10M). Only the (few) attack nodes still need a per-node loop for campaign id.
|
|
1481
|
+
benign = labels == 0
|
|
1482
|
+
benign_by_type = {
|
|
1483
|
+
"subject": norm_scores[benign & (type_enum == 0)],
|
|
1484
|
+
"netflow": norm_scores[benign & (type_enum == 2)],
|
|
1485
|
+
"file": norm_scores[benign & ((type_enum == 1) | (type_enum == 3))],
|
|
1486
|
+
}
|
|
1487
|
+
attack_scores = {}
|
|
1488
|
+
for i in np.nonzero(labels != 0)[0]:
|
|
1489
|
+
cids = campaigns[i] if campaigns else [0]
|
|
1490
|
+
raw_at = cids[0] if cids else 0
|
|
1491
|
+
try:
|
|
1492
|
+
attack_type = int(raw_at)
|
|
1493
|
+
except (ValueError, TypeError):
|
|
1494
|
+
attack_type = raw_at
|
|
1495
|
+
attack_scores.setdefault(attack_type, []).append(norm_scores[i])
|
|
1496
|
+
|
|
1497
|
+
bins = np.linspace(0, 1, 75)
|
|
1498
|
+
try:
|
|
1499
|
+
plt.style.use("seaborn-v0_8-whitegrid")
|
|
1500
|
+
except Exception:
|
|
1501
|
+
pass
|
|
1502
|
+
fig, ax = plt.subplots(figsize=(9, 6))
|
|
1503
|
+
ax.grid(axis="x", visible=False)
|
|
1504
|
+
ax.grid(axis="y", linestyle="--", linewidth=0.5, alpha=0.7)
|
|
1505
|
+
|
|
1506
|
+
legend_patches = []
|
|
1507
|
+
for ntype in ("subject", "file", "netflow"):
|
|
1508
|
+
vals = benign_by_type.get(ntype, [])
|
|
1509
|
+
if len(vals) == 0:
|
|
1510
|
+
continue
|
|
1511
|
+
color = benign_type_colors[ntype]
|
|
1512
|
+
label = f"Benign ({ntype})"
|
|
1513
|
+
ax.hist(vals, bins=bins, alpha=alpha_val, label=label, color=color,
|
|
1514
|
+
edgecolor="black", linewidth=0.5, log=True)
|
|
1515
|
+
legend_patches.append(Patch(facecolor=color, edgecolor="black", alpha=alpha_val, label=label))
|
|
1516
|
+
|
|
1517
|
+
def _atk_label(at):
|
|
1518
|
+
return f"Attack #{at + 1}" if isinstance(at, int) else f"Attack {at}"
|
|
1519
|
+
|
|
1520
|
+
for attack_type, values in attack_scores.items():
|
|
1521
|
+
ax.hist(values, bins=bins, alpha=alpha_val, label=_atk_label(attack_type),
|
|
1522
|
+
color=attack_colors.get(attack_type, "black"), edgecolor="black",
|
|
1523
|
+
linewidth=0.5, log=True)
|
|
1524
|
+
for atype in sorted(attack_scores.keys(), key=lambda x: (isinstance(x, str), x)):
|
|
1525
|
+
legend_patches.append(Patch(facecolor=attack_colors.get(atype, "black"), edgecolor="black",
|
|
1526
|
+
alpha=alpha_val, label=_atk_label(atype)))
|
|
1527
|
+
|
|
1528
|
+
# Good Zone: precision >= 50% AND all campaigns detected (200-point sweep)
|
|
1529
|
+
n_curve_points = 200
|
|
1530
|
+
precision_cut = 0.5
|
|
1531
|
+
thresholds_norm = np.linspace(0, 1, n_curve_points)
|
|
1532
|
+
thresholds_raw = raw_min + thresholds_norm * span
|
|
1533
|
+
precision_curve = np.zeros(n_curve_points)
|
|
1534
|
+
det_curve = np.zeros(n_curve_points)
|
|
1535
|
+
|
|
1536
|
+
mal_scores_sorted = np.sort(raw_scores[labels == 1])
|
|
1537
|
+
ben_scores_sorted = np.sort(raw_scores[labels == 0])
|
|
1538
|
+
mal_campaign_ids = [campaigns[i] if campaigns else [] for i in np.where(labels == 1)[0]]
|
|
1539
|
+
mal_order = np.argsort(raw_scores[labels == 1])
|
|
1540
|
+
mal_campaigns_sorted = [mal_campaign_ids[i] for i in mal_order]
|
|
1541
|
+
|
|
1542
|
+
for ti, thr in enumerate(thresholds_raw):
|
|
1543
|
+
tp = len(mal_scores_sorted) - np.searchsorted(mal_scores_sorted, thr, side="left")
|
|
1544
|
+
fp = len(ben_scores_sorted) - np.searchsorted(ben_scores_sorted, thr, side="left")
|
|
1545
|
+
precision_curve[ti] = tp / (tp + fp + 1e-12)
|
|
1546
|
+
above_idx = np.searchsorted(mal_scores_sorted, thr, side="left")
|
|
1547
|
+
detected_camps = set()
|
|
1548
|
+
for cids in mal_campaigns_sorted[above_idx:]:
|
|
1549
|
+
detected_camps.update(cids)
|
|
1550
|
+
det_curve[ti] = len(detected_camps) / max(num_campaigns, 1)
|
|
1551
|
+
|
|
1552
|
+
mask = (precision_curve >= precision_cut) & (det_curve >= 1.0 - 1e-12)
|
|
1553
|
+
if np.any(mask):
|
|
1554
|
+
idx = np.where(mask)[0]
|
|
1555
|
+
runs = np.split(idx, np.where(np.diff(idx) > 1)[0] + 1)
|
|
1556
|
+
shaded = False
|
|
1557
|
+
for run in runs:
|
|
1558
|
+
lbl = "Good Zone (P≥50% & All Attacks)" if not shaded else None
|
|
1559
|
+
ax.axvspan(thresholds_norm[run[0]], thresholds_norm[run[-1]], color="gray", alpha=0.2, label=lbl)
|
|
1560
|
+
shaded = True
|
|
1561
|
+
|
|
1562
|
+
if cur_thr is not None:
|
|
1563
|
+
norm_thresh = (cur_thr - raw_min) / span
|
|
1564
|
+
if 0.0 <= norm_thresh <= 1.0:
|
|
1565
|
+
ax.axvline(x=norm_thresh, color="black", linestyle="--", linewidth=1.5,
|
|
1566
|
+
label=f"Threshold: {norm_thresh:.2f}")
|
|
1567
|
+
|
|
1568
|
+
ax.set_xlabel("Node anomaly scores", fontsize=12)
|
|
1569
|
+
ax.set_xlim(0, 1)
|
|
1570
|
+
ax.tick_params(labelsize=12)
|
|
1571
|
+
ax.legend(handles=legend_patches, loc="upper right", fontsize=9, frameon=True, fancybox=True)
|
|
1572
|
+
fig.tight_layout()
|
|
1573
|
+
|
|
1574
|
+
buf = io.BytesIO()
|
|
1575
|
+
fig.savefig(buf, format="png", dpi=110)
|
|
1576
|
+
plt.close(fig)
|
|
1577
|
+
buf.seek(0)
|
|
1578
|
+
png = buf.read()
|
|
1579
|
+
if len(_SCOREDIST_CACHE) > 8:
|
|
1580
|
+
_SCOREDIST_CACHE.clear()
|
|
1581
|
+
_SCOREDIST_CACHE[ck] = png
|
|
1582
|
+
return png
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
# --------------------------------------------------------------------------- #
|
|
1586
|
+
# Flask app
|
|
1587
|
+
# --------------------------------------------------------------------------- #
|
|
1588
|
+
|
|
1589
|
+
app = Flask(__name__, static_folder=None)
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
@app.route("/")
|
|
1593
|
+
def index():
|
|
1594
|
+
return send_from_directory(STATIC_DIR, "index.html")
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
@app.route("/static/<path:fn>")
|
|
1598
|
+
def static_files(fn):
|
|
1599
|
+
return send_from_directory(STATIC_DIR, fn)
|
|
1600
|
+
|
|
1601
|
+
|
|
1602
|
+
@app.route("/favicon.ico")
|
|
1603
|
+
def favicon():
|
|
1604
|
+
return Response(b"", mimetype="image/x-icon")
|
|
1605
|
+
|
|
1606
|
+
|
|
1607
|
+
# Run-browser discovery scans the whole artifacts tree (~2 s), and the browser
|
|
1608
|
+
# hits it on every page load / Run Browser open. Cache it and serve instantly,
|
|
1609
|
+
# refreshing in the background when stale (stale-while-revalidate). A finished
|
|
1610
|
+
# generation refreshes it synchronously so the new run shows up immediately.
|
|
1611
|
+
_RUNS_CACHE = {"ts": 0.0, "data": None, "refreshing": False}
|
|
1612
|
+
_RUNS_TTL = 30.0
|
|
1613
|
+
_runs_lock = threading.Lock()
|
|
1614
|
+
|
|
1615
|
+
|
|
1616
|
+
def _refresh_runs():
|
|
1617
|
+
data = discover_runs()
|
|
1618
|
+
with _runs_lock:
|
|
1619
|
+
_RUNS_CACHE["data"] = data
|
|
1620
|
+
_RUNS_CACHE["ts"] = time.time()
|
|
1621
|
+
_RUNS_CACHE["refreshing"] = False
|
|
1622
|
+
return data
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
def get_runs_cached(force=False):
|
|
1626
|
+
with _runs_lock:
|
|
1627
|
+
data = _RUNS_CACHE["data"]
|
|
1628
|
+
age = time.time() - _RUNS_CACHE["ts"]
|
|
1629
|
+
refreshing = _RUNS_CACHE["refreshing"]
|
|
1630
|
+
if force or data is None:
|
|
1631
|
+
return _refresh_runs() # first call / explicit refresh: scan synchronously
|
|
1632
|
+
if age >= _RUNS_TTL and not refreshing:
|
|
1633
|
+
with _runs_lock:
|
|
1634
|
+
_RUNS_CACHE["refreshing"] = True
|
|
1635
|
+
threading.Thread(target=_refresh_runs, daemon=True).start()
|
|
1636
|
+
return data # serve cached (possibly slightly stale) instantly
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
@app.route("/api/runs")
|
|
1640
|
+
def api_runs():
|
|
1641
|
+
force = request.args.get("refresh") in ("1", "true")
|
|
1642
|
+
return jsonify({"artifacts_root": ARTIFACTS_ROOT, "runs": get_runs_cached(force)})
|
|
1643
|
+
|
|
1644
|
+
|
|
1645
|
+
@app.route("/api/run")
|
|
1646
|
+
def api_run():
|
|
1647
|
+
points = safe_path(request.args.get("file"))
|
|
1648
|
+
viz_dir = os.path.dirname(points)
|
|
1649
|
+
basename = os.path.basename(points)
|
|
1650
|
+
manifest = load_manifest(viz_dir)
|
|
1651
|
+
|
|
1652
|
+
eval_dir = os.path.dirname(viz_dir)
|
|
1653
|
+
cfg_path = os.path.join(eval_dir, "run_config.yml")
|
|
1654
|
+
if not os.path.exists(cfg_path):
|
|
1655
|
+
cfg_path = os.path.join(os.path.dirname(eval_dir), "run_config.yml")
|
|
1656
|
+
featurization = _featurization_method(cfg_path)
|
|
1657
|
+
|
|
1658
|
+
# embeddings available in this viz dir
|
|
1659
|
+
files = sorted(glob.glob(os.path.join(viz_dir, "*_points.json")))
|
|
1660
|
+
best_epoch = None
|
|
1661
|
+
if manifest and manifest.get("epochs"):
|
|
1662
|
+
best_epoch = sorted(
|
|
1663
|
+
manifest["epochs"], key=lambda e: e.get("adp", 0), reverse=True
|
|
1664
|
+
)[0].get("epoch")
|
|
1665
|
+
|
|
1666
|
+
# per-epoch metrics from the manifest, keyed by epoch string
|
|
1667
|
+
ep_metrics = {}
|
|
1668
|
+
if manifest and manifest.get("epochs"):
|
|
1669
|
+
for e in manifest["epochs"]:
|
|
1670
|
+
ep_metrics[str(e.get("epoch"))] = (e.get("adp", 0.0), e.get("disc_score", 0.0))
|
|
1671
|
+
best_ep_int = None
|
|
1672
|
+
try:
|
|
1673
|
+
best_ep_int = int(best_epoch) if best_epoch is not None else None
|
|
1674
|
+
except (TypeError, ValueError):
|
|
1675
|
+
best_ep_int = best_epoch
|
|
1676
|
+
|
|
1677
|
+
embeddings, epochs = [], []
|
|
1678
|
+
w2v_path = enc_path = None
|
|
1679
|
+
for fp in files:
|
|
1680
|
+
b = os.path.basename(fp)
|
|
1681
|
+
entry = {"file": fp, "label": _label_for_file(b, best_epoch, featurization), "basename": b}
|
|
1682
|
+
embeddings.append(entry)
|
|
1683
|
+
if "word2vec" in b:
|
|
1684
|
+
w2v_path = fp
|
|
1685
|
+
if "encoder" in b and "epoch" not in b:
|
|
1686
|
+
# the bare "encoder" file == the best epoch; surface it in the selector
|
|
1687
|
+
if enc_path is None:
|
|
1688
|
+
enc_path = fp
|
|
1689
|
+
ad, di = ep_metrics.get(str(best_epoch), (0.0, 0.0))
|
|
1690
|
+
epochs.append({"epoch": best_ep_int, "file": fp, "adp": ad, "disc": di, "is_best": True})
|
|
1691
|
+
ep = _epoch_of(b)
|
|
1692
|
+
if ep is not None:
|
|
1693
|
+
ad, di = ep_metrics.get(str(ep), (0.0, 0.0))
|
|
1694
|
+
epochs.append({"epoch": ep, "file": fp, "adp": ad, "disc": di,
|
|
1695
|
+
"is_best": (str(ep) == str(best_epoch))})
|
|
1696
|
+
epochs.sort(key=lambda e: (e["epoch"] is None, e["epoch"]))
|
|
1697
|
+
# pick a representative encoder for hot-swap if no bare encoder file
|
|
1698
|
+
if enc_path is None and epochs:
|
|
1699
|
+
if best_epoch is not None:
|
|
1700
|
+
match = [e for e in epochs if str(e["epoch"]) == str(best_epoch)]
|
|
1701
|
+
enc_path = (match or epochs)[-1]["file"]
|
|
1702
|
+
else:
|
|
1703
|
+
enc_path = epochs[-1]["file"]
|
|
1704
|
+
|
|
1705
|
+
info = get_info(points)
|
|
1706
|
+
adp, disc, _ = metrics_for_file(basename, manifest)
|
|
1707
|
+
dataset = os.path.basename(os.path.dirname(viz_dir))
|
|
1708
|
+
adj = points.replace("_points.json", "_adj.json")
|
|
1709
|
+
|
|
1710
|
+
# Warm the adjacency index in the background so the first "See Edges" /
|
|
1711
|
+
# causal / attack action after opening the run is instant instead of paying
|
|
1712
|
+
# a one-time parse. The build is single-flight, so a duplicate warm is cheap.
|
|
1713
|
+
if os.path.exists(adj) and _ADJ_INDEX.get("key", (None,))[0] != adj:
|
|
1714
|
+
threading.Thread(target=warm_run, args=(points,), daemon=True).start()
|
|
1715
|
+
|
|
1716
|
+
return jsonify({
|
|
1717
|
+
"file": points,
|
|
1718
|
+
"dataset": dataset,
|
|
1719
|
+
"model": _label_for_file(basename, best_epoch, featurization),
|
|
1720
|
+
"featurization": featurization,
|
|
1721
|
+
"n": info["n"], "hops": info["hops"], "max_tw": info["max_tw"],
|
|
1722
|
+
"byte_offsets": info["byte_offsets"],
|
|
1723
|
+
"stats": dict(info["stats"], adp=adp, disc_score=disc,
|
|
1724
|
+
num_campaigns=info.get("num_campaigns", 0)),
|
|
1725
|
+
"detection_cost": info.get("detection_cost"),
|
|
1726
|
+
"run_config": load_run_config_text(viz_dir),
|
|
1727
|
+
"embeddings": embeddings, "epochs": epochs,
|
|
1728
|
+
"word2vec_file": w2v_path, "encoder_file": enc_path,
|
|
1729
|
+
"current_epoch": (best_ep_int if (_epoch_of(basename) is None
|
|
1730
|
+
and "encoder" in basename and "epoch" not in basename)
|
|
1731
|
+
else _epoch_of(basename)),
|
|
1732
|
+
"best_epoch": best_epoch,
|
|
1733
|
+
"has_adj": os.path.exists(adj), "adj_file": adj if os.path.exists(adj) else None,
|
|
1734
|
+
})
|
|
1735
|
+
|
|
1736
|
+
|
|
1737
|
+
@app.route("/api/buffer")
|
|
1738
|
+
def api_buffer():
|
|
1739
|
+
points = safe_path(request.args.get("file"))
|
|
1740
|
+
get_info(points) # ensure cache built
|
|
1741
|
+
bin_p, _, _ = _cache_paths(points)
|
|
1742
|
+
# stream from disk (these are tens-to-hundreds of MB) instead of buffering
|
|
1743
|
+
return send_from_directory(*os.path.split(bin_p), mimetype="application/octet-stream")
|
|
1744
|
+
|
|
1745
|
+
|
|
1746
|
+
@app.route("/api/neighbors")
|
|
1747
|
+
def api_neighbors():
|
|
1748
|
+
"""Edges incident to a single node — for the 'See Edges' dialog.
|
|
1749
|
+
|
|
1750
|
+
Returns just this node's adjacency slice instead of the whole graph, so the
|
|
1751
|
+
browser no longer downloads the entire (tens-to-hundreds of MB) adj file.
|
|
1752
|
+
"""
|
|
1753
|
+
points = safe_path(request.args.get("file"))
|
|
1754
|
+
try:
|
|
1755
|
+
node = int(request.args.get("node"))
|
|
1756
|
+
except (TypeError, ValueError):
|
|
1757
|
+
abort(400, "bad node id")
|
|
1758
|
+
index = get_adj_index(points)
|
|
1759
|
+
if index is None:
|
|
1760
|
+
abort(404, "no adjacency data for this run; generate viz data first")
|
|
1761
|
+
store = load_meta(points)
|
|
1762
|
+
edges = index.neighbors(node)
|
|
1763
|
+
# Enrich each edge with its neighbour's metadata (the client only holds a
|
|
1764
|
+
# prefix). A hub node can have thousands of edges, so resolve every neighbour
|
|
1765
|
+
# id → store row in ONE vectorised searchsorted rather than one per edge; only
|
|
1766
|
+
# the per-row string decode (unavoidable) stays in the loop.
|
|
1767
|
+
if edges and len(store.uniq_ids):
|
|
1768
|
+
nb = np.fromiter((e["nb"] for e in edges), dtype=np.int64, count=len(edges))
|
|
1769
|
+
pos = np.clip(np.searchsorted(store.uniq_ids, nb), 0, len(store.uniq_ids) - 1)
|
|
1770
|
+
match = store.uniq_ids[pos] == nb
|
|
1771
|
+
first = store.first_idx[pos]
|
|
1772
|
+
# A hub node can have tens of thousands of edge instances but only a few
|
|
1773
|
+
# hundred distinct neighbours, all carrying the same metadata — decode each
|
|
1774
|
+
# neighbour's row ONCE and reuse it, instead of re-slicing the same strings
|
|
1775
|
+
# per edge (the dominant cost when "See Edges" is slow on a hub node).
|
|
1776
|
+
row_cache = {}
|
|
1777
|
+
for e, ok, fi in zip(edges, match, first):
|
|
1778
|
+
if ok:
|
|
1779
|
+
fi = int(fi)
|
|
1780
|
+
r = row_cache.get(fi)
|
|
1781
|
+
if r is None:
|
|
1782
|
+
r = row_cache[fi] = store.row(fi)
|
|
1783
|
+
e.update(r)
|
|
1784
|
+
else:
|
|
1785
|
+
e.update(_OFF_GRAPH)
|
|
1786
|
+
elif edges:
|
|
1787
|
+
for e in edges:
|
|
1788
|
+
e.update(_OFF_GRAPH)
|
|
1789
|
+
return jsonify({"center": node, "edges": edges})
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
@app.route("/api/node")
|
|
1793
|
+
def api_node():
|
|
1794
|
+
"""Full metadata for a small set of nodes, fetched on demand when a node is
|
|
1795
|
+
selected. Keyed by buffer ROW index (`idxs`), so the client needn't hold the
|
|
1796
|
+
node-id column up front. Each lookup is O(1), so selecting a node is instant
|
|
1797
|
+
even at 20M."""
|
|
1798
|
+
points = safe_path(request.args.get("file"))
|
|
1799
|
+
store = load_meta(points)
|
|
1800
|
+
rows = {}
|
|
1801
|
+
for s in (request.args.get("idxs") or "").split(","):
|
|
1802
|
+
s = s.strip()
|
|
1803
|
+
try:
|
|
1804
|
+
r = store.node_at(int(s)) if s else None
|
|
1805
|
+
except ValueError:
|
|
1806
|
+
r = None
|
|
1807
|
+
if r is not None:
|
|
1808
|
+
rows[s] = r
|
|
1809
|
+
return jsonify({"rows": rows})
|
|
1810
|
+
|
|
1811
|
+
|
|
1812
|
+
@app.route("/api/search")
|
|
1813
|
+
def api_search():
|
|
1814
|
+
"""Buffer rows matching a single query (id or path/cmd substring), server-side
|
|
1815
|
+
so the client never downloads the metadata to search it. Rows == buffer
|
|
1816
|
+
indices, so the client filters the cloud by index."""
|
|
1817
|
+
points = safe_path(request.args.get("file"))
|
|
1818
|
+
q = request.args.get("q") or ""
|
|
1819
|
+
try:
|
|
1820
|
+
limit = min(int(request.args.get("limit", 200000)), 500000)
|
|
1821
|
+
except (TypeError, ValueError):
|
|
1822
|
+
limit = 200000
|
|
1823
|
+
store = load_meta(points)
|
|
1824
|
+
rows = store.search([q], limit)
|
|
1825
|
+
return jsonify({"rows": rows, "capped": len(rows) >= limit})
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
@app.route("/api/filter", methods=["POST"])
|
|
1829
|
+
def api_filter():
|
|
1830
|
+
"""Buffer rows matching ANY of many terms (the CSV filter) — same server-side
|
|
1831
|
+
blob scan as /api/search, batched."""
|
|
1832
|
+
body = request.get_json(force=True, silent=True) or {}
|
|
1833
|
+
points = safe_path(body.get("file"))
|
|
1834
|
+
terms = body.get("terms") or []
|
|
1835
|
+
if not isinstance(terms, list):
|
|
1836
|
+
terms = []
|
|
1837
|
+
store = load_meta(points)
|
|
1838
|
+
rows = store.search(terms, 500000)
|
|
1839
|
+
return jsonify({"rows": rows, "capped": len(rows) >= 500000})
|
|
1840
|
+
|
|
1841
|
+
|
|
1842
|
+
@app.route("/api/causal")
|
|
1843
|
+
def api_causal():
|
|
1844
|
+
"""Server-side causal subgraph from a node (time-respecting traversal).
|
|
1845
|
+
|
|
1846
|
+
Returns the reached node ids for the chronological table, plus a small
|
|
1847
|
+
induced subgraph (origin + malicious nodes, capped) for the directed-graph
|
|
1848
|
+
view — so the client renders both without holding the full adjacency.
|
|
1849
|
+
"""
|
|
1850
|
+
points = safe_path(request.args.get("file"))
|
|
1851
|
+
try:
|
|
1852
|
+
start = int(request.args.get("node"))
|
|
1853
|
+
except (TypeError, ValueError):
|
|
1854
|
+
abort(400, "bad node id")
|
|
1855
|
+
index = get_adj_index(points)
|
|
1856
|
+
if index is None:
|
|
1857
|
+
abort(404, "no adjacency data for this run; generate viz data first")
|
|
1858
|
+
|
|
1859
|
+
store = load_meta(points)
|
|
1860
|
+
start_tw = store.first_tw_of(start)
|
|
1861
|
+
ids = causal_trace(index, start, start_tw)
|
|
1862
|
+
|
|
1863
|
+
# rows enriched from full metadata (the table works even for nodes outside
|
|
1864
|
+
# the client's loaded prefix)
|
|
1865
|
+
rows = [{"id": nid, **store.row(store.first_index(nid))} for nid in ids]
|
|
1866
|
+
|
|
1867
|
+
# graph view: origin + malicious nodes only, capped for readability
|
|
1868
|
+
graph_nodes = [n for n in ids if n == start or store.label_of(n) != 0][:200]
|
|
1869
|
+
nset = set(graph_nodes)
|
|
1870
|
+
graph_edges = []
|
|
1871
|
+
for u in graph_nodes:
|
|
1872
|
+
for e in index.neighbors(u):
|
|
1873
|
+
if e["dir"] == "out" and e["nb"] in nset:
|
|
1874
|
+
graph_edges.append([u, e["nb"]])
|
|
1875
|
+
return jsonify({
|
|
1876
|
+
"count": len(ids), "rows": rows,
|
|
1877
|
+
"graph_nodes": graph_nodes, "graph_edges": graph_edges,
|
|
1878
|
+
})
|
|
1879
|
+
|
|
1880
|
+
|
|
1881
|
+
@app.route("/api/attack_pairs")
|
|
1882
|
+
def api_attack_pairs():
|
|
1883
|
+
"""Unique malicious<->malicious edges (as [u, v] id pairs) for the 3D attack
|
|
1884
|
+
overlay. Small (bounded by the attack subgraph); computed from the cached
|
|
1885
|
+
adjacency + labels so the client needn't load the whole graph."""
|
|
1886
|
+
points = safe_path(request.args.get("file"))
|
|
1887
|
+
index = get_adj_index(points)
|
|
1888
|
+
if index is None:
|
|
1889
|
+
abort(404, "no adjacency data for this run; generate viz data first")
|
|
1890
|
+
mal = load_meta(points).malicious_ids()
|
|
1891
|
+
pairs, seen = [], set()
|
|
1892
|
+
for u in mal:
|
|
1893
|
+
for e in index.neighbors(u):
|
|
1894
|
+
v = e["nb"]
|
|
1895
|
+
if v not in mal:
|
|
1896
|
+
continue
|
|
1897
|
+
k = (u, v) if u < v else (v, u)
|
|
1898
|
+
if k in seen:
|
|
1899
|
+
continue
|
|
1900
|
+
seen.add(k)
|
|
1901
|
+
pairs.append([u, v])
|
|
1902
|
+
return jsonify({"pairs": pairs})
|
|
1903
|
+
|
|
1904
|
+
|
|
1905
|
+
# ----- viz generation (export subprocess) ----- #
|
|
1906
|
+
|
|
1907
|
+
# --------------------------------------------------------------------------- #
|
|
1908
|
+
# Campaign attack graph — built from the run's own viz data: the adjacency
|
|
1909
|
+
# (edges, with relation type `et` and direction `dir`) and the ground-truth
|
|
1910
|
+
# node labels and paths. No edge_scores / indexid2msg needed, so it works for
|
|
1911
|
+
# any run that has viz data. Hop 0 = malicious<->malicious edges; hops 1/2/3
|
|
1912
|
+
# add neighbour context via edge sampling (300/200/100). DAG-enforced.
|
|
1913
|
+
# --------------------------------------------------------------------------- #
|
|
1914
|
+
|
|
1915
|
+
_CAMPAIGN_CACHE = {}
|
|
1916
|
+
HOP_EDGE_COLOR = ["#ff4d4d", "#ffb3b3", "#cccccc", "#666666"]
|
|
1917
|
+
|
|
1918
|
+
|
|
1919
|
+
def _campaign_node_color(ntype, is_mal):
|
|
1920
|
+
if not is_mal:
|
|
1921
|
+
return "#808080"
|
|
1922
|
+
if "process" in ntype:
|
|
1923
|
+
return "#ff4d4d"
|
|
1924
|
+
if "netflow" in ntype or "network" in ntype or "socket" in ntype:
|
|
1925
|
+
return "#4da6ff"
|
|
1926
|
+
if "file" in ntype:
|
|
1927
|
+
return "#4dff4d"
|
|
1928
|
+
return "#ffcc00"
|
|
1929
|
+
|
|
1930
|
+
|
|
1931
|
+
def build_campaign_graph(points_path):
|
|
1932
|
+
"""Cached, single-flight campaign graph. The lock stops a background warm and
|
|
1933
|
+
a user click from building it twice at once (which doubled the wall time)."""
|
|
1934
|
+
index = get_adj_index(points_path)
|
|
1935
|
+
if index is None:
|
|
1936
|
+
return None
|
|
1937
|
+
adj_path, _, _ = _adj_index_paths(points_path)
|
|
1938
|
+
_, meta_p, _ = _cache_paths(points_path)
|
|
1939
|
+
key = (adj_path, os.path.getmtime(adj_path), os.path.getmtime(meta_p))
|
|
1940
|
+
if _CAMPAIGN_CACHE.get("key") == key:
|
|
1941
|
+
return _CAMPAIGN_CACHE["data"]
|
|
1942
|
+
with _build_lock("campaign:" + adj_path):
|
|
1943
|
+
if _CAMPAIGN_CACHE.get("key") == key: # built while we waited
|
|
1944
|
+
return _CAMPAIGN_CACHE["data"]
|
|
1945
|
+
data = _compute_campaign(points_path, index)
|
|
1946
|
+
_CAMPAIGN_CACHE["key"] = key
|
|
1947
|
+
_CAMPAIGN_CACHE["data"] = data
|
|
1948
|
+
return data
|
|
1949
|
+
|
|
1950
|
+
|
|
1951
|
+
def _compute_campaign(points_path, index):
|
|
1952
|
+
import random
|
|
1953
|
+
|
|
1954
|
+
store = load_meta(points_path)
|
|
1955
|
+
types, paths = store["types"], store["paths"]
|
|
1956
|
+
malicious = store.malicious_ids()
|
|
1957
|
+
if not malicious:
|
|
1958
|
+
return {"nodes": [], "links": []}
|
|
1959
|
+
|
|
1960
|
+
def info(nid):
|
|
1961
|
+
i = store.first_index(nid)
|
|
1962
|
+
if i < 0:
|
|
1963
|
+
return "node", f"node: {nid}"
|
|
1964
|
+
t = (types[i] or "node").lower()
|
|
1965
|
+
name = paths[i] or str(nid)
|
|
1966
|
+
if "netflow" not in t:
|
|
1967
|
+
name = name.split("/")[-1] or name
|
|
1968
|
+
if len(name) > 40:
|
|
1969
|
+
name = "..." + name[-37:]
|
|
1970
|
+
return t, f"{t}: {name}"
|
|
1971
|
+
|
|
1972
|
+
def directed(u, e):
|
|
1973
|
+
return (e["nb"], u) if e.get("dir") == "in" else (u, e["nb"])
|
|
1974
|
+
|
|
1975
|
+
random.seed(42)
|
|
1976
|
+
|
|
1977
|
+
# hop 0: malicious <-> malicious edges
|
|
1978
|
+
hop = {}
|
|
1979
|
+
hop0_edges, eseen = [], set()
|
|
1980
|
+
for u in malicious:
|
|
1981
|
+
for e in index.neighbors(u):
|
|
1982
|
+
if e["nb"] not in malicious:
|
|
1983
|
+
continue
|
|
1984
|
+
s, t = directed(u, e)
|
|
1985
|
+
k = (s, t, e.get("et", ""))
|
|
1986
|
+
if k in eseen:
|
|
1987
|
+
continue
|
|
1988
|
+
eseen.add(k)
|
|
1989
|
+
hop0_edges.append((s, t, e.get("et", "")))
|
|
1990
|
+
hop[s] = 0
|
|
1991
|
+
hop[t] = 0
|
|
1992
|
+
# Cap hop-0 like the other hops. add_edge() runs an O(V+E) nx.find_cycle per
|
|
1993
|
+
# edge, so an uncapped hop-0 (many interconnected malicious nodes) makes the
|
|
1994
|
+
# whole build O(E²) and can wedge for minutes. 500 edges keeps it bounded and
|
|
1995
|
+
# is plenty for a readable graph.
|
|
1996
|
+
HOP0_CAP = 500
|
|
1997
|
+
if len(hop0_edges) > HOP0_CAP:
|
|
1998
|
+
hop0_edges = random.sample(hop0_edges, HOP0_CAP)
|
|
1999
|
+
hop = {}
|
|
2000
|
+
for s, t, _et in hop0_edges:
|
|
2001
|
+
hop[s] = 0
|
|
2002
|
+
hop[t] = 0
|
|
2003
|
+
if not hop:
|
|
2004
|
+
for nid in malicious:
|
|
2005
|
+
hop[nid] = 0
|
|
2006
|
+
|
|
2007
|
+
def boundary(inside, exclude, cap):
|
|
2008
|
+
out, s2 = [], set()
|
|
2009
|
+
for u in inside:
|
|
2010
|
+
for e in index.neighbors(u):
|
|
2011
|
+
if e["nb"] in exclude:
|
|
2012
|
+
continue
|
|
2013
|
+
s, t = directed(u, e)
|
|
2014
|
+
k = (s, t, e.get("et", ""))
|
|
2015
|
+
if k in s2:
|
|
2016
|
+
continue
|
|
2017
|
+
s2.add(k)
|
|
2018
|
+
out.append((s, t, e.get("et", "")))
|
|
2019
|
+
return random.sample(out, cap) if len(out) > cap else out
|
|
2020
|
+
|
|
2021
|
+
seen = set(hop)
|
|
2022
|
+
frontier = set(hop)
|
|
2023
|
+
hop_edges = {0: hop0_edges}
|
|
2024
|
+
for h, cap in ((1, 300), (2, 200), (3, 100)):
|
|
2025
|
+
edges = boundary(frontier, seen, cap)
|
|
2026
|
+
hop_edges[h] = edges
|
|
2027
|
+
new = set()
|
|
2028
|
+
for s, t, _et in edges:
|
|
2029
|
+
for nid in (s, t):
|
|
2030
|
+
if nid not in seen:
|
|
2031
|
+
hop[nid] = h
|
|
2032
|
+
new.add(nid)
|
|
2033
|
+
seen |= new
|
|
2034
|
+
frontier = new
|
|
2035
|
+
if not new:
|
|
2036
|
+
break
|
|
2037
|
+
|
|
2038
|
+
nodes, links = {}, []
|
|
2039
|
+
seen_links = set()
|
|
2040
|
+
|
|
2041
|
+
def add_node(nid, h):
|
|
2042
|
+
if nid in nodes:
|
|
2043
|
+
return
|
|
2044
|
+
t, lbl = info(nid)
|
|
2045
|
+
nodes[nid] = {"id": str(nid), "label": lbl, "hop": h, "color": _campaign_node_color(t, h == 0)}
|
|
2046
|
+
|
|
2047
|
+
def add_edge(s, t, et, h):
|
|
2048
|
+
# Orient each edge forward in (hop, id) order instead of dropping backward
|
|
2049
|
+
# ones: a strict endpoint order keeps the graph acyclic without discarding
|
|
2050
|
+
# edges, so a connected subgraph stays connected.
|
|
2051
|
+
ks, kt = (hop.get(s, 1 << 30), s), (hop.get(t, 1 << 30), t)
|
|
2052
|
+
if ks == kt:
|
|
2053
|
+
return
|
|
2054
|
+
if ks > kt:
|
|
2055
|
+
s, t = t, s
|
|
2056
|
+
if (s, t) in seen_links:
|
|
2057
|
+
return
|
|
2058
|
+
seen_links.add((s, t))
|
|
2059
|
+
links.append({"source": str(s), "target": str(t), "label": et, "hop": h, "color": HOP_EDGE_COLOR[h]})
|
|
2060
|
+
|
|
2061
|
+
for h in (0, 1, 2, 3):
|
|
2062
|
+
for nid, hh in list(hop.items()):
|
|
2063
|
+
if hh == h:
|
|
2064
|
+
add_node(nid, h)
|
|
2065
|
+
for s, t, et in hop_edges.get(h, []):
|
|
2066
|
+
add_edge(s, t, et, h)
|
|
2067
|
+
|
|
2068
|
+
return {"nodes": list(nodes.values()), "links": links}
|
|
2069
|
+
|
|
2070
|
+
|
|
2071
|
+
@app.route("/api/campaign")
|
|
2072
|
+
def api_campaign():
|
|
2073
|
+
points = safe_path(request.args.get("file"))
|
|
2074
|
+
try:
|
|
2075
|
+
data = build_campaign_graph(points)
|
|
2076
|
+
except Exception as e:
|
|
2077
|
+
abort(500, f"campaign graph build failed: {type(e).__name__}: {e}")
|
|
2078
|
+
if data is None:
|
|
2079
|
+
abort(404, "no adjacency data for this run; generate viz data first")
|
|
2080
|
+
return jsonify(data)
|
|
2081
|
+
|
|
2082
|
+
|
|
2083
|
+
@app.route("/api/scoredist")
|
|
2084
|
+
def api_scoredist():
|
|
2085
|
+
points = safe_path(request.args.get("file"))
|
|
2086
|
+
png = render_score_distribution(points)
|
|
2087
|
+
return Response(png, mimetype="image/png")
|
|
2088
|
+
|
|
2089
|
+
|
|
2090
|
+
@app.route("/api/export", methods=["POST"])
|
|
2091
|
+
def api_export():
|
|
2092
|
+
if not ALLOW_EXPORT:
|
|
2093
|
+
abort(403, "viz generation disabled (set PIDS_VIZ_ALLOW_EXPORT=1)")
|
|
2094
|
+
body = request.get_json(force=True, silent=True) or {}
|
|
2095
|
+
run_dir = safe_path(body.get("run_dir"), kind="dir")
|
|
2096
|
+
opts = {
|
|
2097
|
+
"run_dir": run_dir,
|
|
2098
|
+
"embeddings": body.get("embeddings", "both"),
|
|
2099
|
+
"all_epochs": bool(body.get("all_epochs")),
|
|
2100
|
+
"method": body.get("method") or "umap",
|
|
2101
|
+
"max_benign": body.get("max_benign"),
|
|
2102
|
+
"max_attack": body.get("max_attack"),
|
|
2103
|
+
}
|
|
2104
|
+
job, busy_id = start_export(opts)
|
|
2105
|
+
if job is None:
|
|
2106
|
+
return jsonify({"error": "an export is already running", "job_id": busy_id}), 409
|
|
2107
|
+
return jsonify({"job_id": job["id"]})
|
|
2108
|
+
|
|
2109
|
+
|
|
2110
|
+
@app.route("/api/export/status")
|
|
2111
|
+
def api_export_status():
|
|
2112
|
+
if CURRENT_JOB is None:
|
|
2113
|
+
return jsonify({"job": None, "allowed": ALLOW_EXPORT})
|
|
2114
|
+
return jsonify({"job": job_snapshot(CURRENT_JOB), "allowed": ALLOW_EXPORT})
|
|
2115
|
+
|
|
2116
|
+
|
|
2117
|
+
@app.route("/api/export/cancel", methods=["POST"])
|
|
2118
|
+
def api_export_cancel():
|
|
2119
|
+
return jsonify({"canceled": cancel_export()})
|
|
2120
|
+
|
|
2121
|
+
|
|
2122
|
+
@app.route("/api/export/stream")
|
|
2123
|
+
def api_export_stream():
|
|
2124
|
+
job = CURRENT_JOB
|
|
2125
|
+
if job is None:
|
|
2126
|
+
abort(404, "no export job")
|
|
2127
|
+
q = queue.Queue()
|
|
2128
|
+
job["subscribers"].append(q)
|
|
2129
|
+
|
|
2130
|
+
@stream_with_context
|
|
2131
|
+
def gen():
|
|
2132
|
+
yield _sse({"type": "snapshot", **job_snapshot(job)})
|
|
2133
|
+
if job["status"] != "running":
|
|
2134
|
+
try:
|
|
2135
|
+
job["subscribers"].remove(q)
|
|
2136
|
+
except ValueError:
|
|
2137
|
+
pass
|
|
2138
|
+
return
|
|
2139
|
+
try:
|
|
2140
|
+
while True:
|
|
2141
|
+
# Heartbeat: if no log arrives for 15s (e.g. a big torch.load or a
|
|
2142
|
+
# long silent edge scan), emit an SSE comment so the tunnel/browser
|
|
2143
|
+
# keeps the stream open instead of dropping it as idle.
|
|
2144
|
+
try:
|
|
2145
|
+
msg = q.get(timeout=15)
|
|
2146
|
+
except queue.Empty:
|
|
2147
|
+
yield ": keepalive\n\n"
|
|
2148
|
+
continue
|
|
2149
|
+
if msg is None:
|
|
2150
|
+
break
|
|
2151
|
+
yield _sse(msg)
|
|
2152
|
+
finally:
|
|
2153
|
+
try:
|
|
2154
|
+
job["subscribers"].remove(q)
|
|
2155
|
+
except ValueError:
|
|
2156
|
+
pass
|
|
2157
|
+
|
|
2158
|
+
return Response(gen(), mimetype="text/event-stream",
|
|
2159
|
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
|
2160
|
+
|
|
2161
|
+
|
|
2162
|
+
def main():
|
|
2163
|
+
ap = argparse.ArgumentParser(description="PIDSMaker web visualizer")
|
|
2164
|
+
ap.add_argument("--host", default="127.0.0.1")
|
|
2165
|
+
ap.add_argument("--port", type=int, default=5000)
|
|
2166
|
+
ap.add_argument("--debug", action="store_true")
|
|
2167
|
+
args = ap.parse_args()
|
|
2168
|
+
print(f"[viz_server] artifacts root: {ARTIFACTS_ROOT}")
|
|
2169
|
+
print(f"[viz_server] open http://{args.host}:{args.port}/")
|
|
2170
|
+
# prime the run-browser cache so the first page load is instant
|
|
2171
|
+
threading.Thread(target=lambda: get_runs_cached(force=True), daemon=True).start()
|
|
2172
|
+
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
|
|
2173
|
+
|
|
2174
|
+
|
|
2175
|
+
if __name__ == "__main__":
|
|
2176
|
+
main()
|