bugx-cli 0.0.0-stage → 0.1.0
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.
- package/LICENSE +55 -0
- package/README.md +280 -2
- package/core/CATALOG.json +141 -0
- package/core/README.md +254 -0
- package/core/adapters/README.md +35 -0
- package/core/adapters/android-interaction.json +81 -0
- package/core/adapters/android.json +24 -0
- package/core/adapters/desktop-macos.json +20 -0
- package/core/adapters/ios-interaction.json +34 -0
- package/core/adapters/ios.json +23 -0
- package/core/adapters/memory-macos.json +24 -0
- package/core/agent/README.md +50 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +764 -0
- package/core/agent/agent_eval.py +1073 -0
- package/core/agent/agent_execution.py +552 -0
- package/core/agent/agent_orchestrator.py +1345 -0
- package/core/agent/agent_targets.py +871 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/assets/README.md +24 -0
- package/core/assets/bugx-avatar-1024.png +0 -0
- package/core/assets/bugx-avatar-512.png +0 -0
- package/core/assets/bugx-avatar-tight.svg +23 -0
- package/core/assets/bugx-avatar.svg +28 -0
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/assets/project-layout.md +42 -0
- package/core/audit_packs/README.md +37 -0
- package/core/audit_packs/data-audit/manifest.json +94 -0
- package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
- package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
- package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/desktop-audit/manifest.json +123 -0
- package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
- package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
- package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
- package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
- package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
- package/core/audit_packs/memory-testing.md +227 -0
- package/core/audit_packs/mobile-audit/manifest.json +155 -0
- package/core/audit_packs/mobile-audit/modules/android.md +19 -0
- package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
- package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
- package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
- package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
- package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
- package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
- package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
- package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
- package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
- package/core/audit_packs/native-audit/manifest.json +127 -0
- package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
- package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
- package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
- package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/platform-testing.md +174 -0
- package/core/audit_packs/web-audit/manifest.json +191 -0
- package/core/audit_packs/web-audit/modules/graphql.md +5 -0
- package/core/audit_packs/web-audit/modules/h5.md +18 -0
- package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
- package/core/audit_packs/web-audit/modules/oauth.md +4 -0
- package/core/audit_packs/web-audit/modules/upload.md +4 -0
- package/core/audit_packs/web-audit/modules/websocket.md +4 -0
- package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
- package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
- package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
- package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
- package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
- package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
- package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
- package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
- package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
- package/core/autonomous_cve/INTERFACE.md +61 -0
- package/core/autonomous_cve/README.md +58 -0
- package/core/autonomous_cve/SPEC.md +25 -0
- package/core/autonomous_cve/__init__.py +109 -0
- package/core/autonomous_cve/attack_graph.py +1096 -0
- package/core/autonomous_cve/attack_graph_store.py +1822 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +459 -0
- package/core/autonomous_cve/ghsa_advisories.py +174 -0
- package/core/autonomous_cve/models.py +93 -0
- package/core/autonomous_cve/mutator.py +87 -0
- package/core/autonomous_cve/patcher.py +126 -0
- package/core/autonomous_cve/scout.py +278 -0
- package/core/autonomous_cve/synthesizer.py +207 -0
- package/core/autonomous_cve/verifier.py +100 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1846 -0
- package/core/cloud_sync/INTERFACE.md +32 -0
- package/core/cloud_sync/README.md +62 -0
- package/core/cloud_sync/SPEC.md +25 -0
- package/core/cloud_sync/__init__.py +23 -0
- package/core/cloud_sync/auto_sync.py +398 -0
- package/core/cloud_sync/cloud_client.py +1199 -0
- package/core/cloud_sync/cloud_onboard.py +702 -0
- package/core/cloud_sync/cloud_schema.py +648 -0
- package/core/cloud_sync/consent.py +81 -0
- package/core/cloud_sync/device_identity.py +307 -0
- package/core/cloud_sync/endpoint_router.py +415 -0
- package/core/cloud_sync/flywheel_client.py +760 -0
- package/core/cloud_sync/network_transport.py +275 -0
- package/core/cloud_sync/onboard_wizard.py +493 -0
- package/core/cloud_sync/sensitive_filter.py +285 -0
- package/core/cloud_sync/sync_pull.py +695 -0
- package/core/cloud_sync/sync_push.py +721 -0
- package/core/contracts/AGENT_GUIDE.md +362 -0
- package/core/contracts/README.md +34 -0
- package/core/contracts/bugx-blackbox.md +541 -0
- package/core/contracts/bugx-opencode.md +469 -0
- package/core/contracts/bugx-quick.md +44 -0
- package/core/contracts/bugx-runtime-contract.md +353 -0
- package/core/contracts/bugx-worker.md +470 -0
- package/core/contracts/engine_gap_contracts.py +390 -0
- package/core/coverage/README.md +70 -0
- package/core/coverage/__init__.py +106 -0
- package/core/coverage/coverage_ai_review.py +185 -0
- package/core/coverage/coverage_backfill.py +54 -0
- package/core/coverage/coverage_bootstrap.py +713 -0
- package/core/coverage/coverage_business.py +36 -0
- package/core/coverage/coverage_cli.py +715 -0
- package/core/coverage/coverage_discovery.py +859 -0
- package/core/coverage/coverage_evidence.py +977 -0
- package/core/coverage/coverage_forensics.py +115 -0
- package/core/coverage/coverage_gate.py +277 -0
- package/core/coverage/coverage_intelligence.py +734 -0
- package/core/coverage/coverage_manifest.py +396 -0
- package/core/coverage/coverage_platform.py +77 -0
- package/core/coverage/coverage_validate.py +236 -0
- package/core/coverage/module_coverage.py +157 -0
- package/core/dev_harness/INTERFACE.md +20 -0
- package/core/dev_harness/README.md +21 -0
- package/core/dev_harness/SPEC.md +25 -0
- package/core/dev_harness/__init__.py +5 -0
- package/core/dev_harness/interaction_preset.py +408 -0
- package/core/engine-integrity.json +2625 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +382 -0
- package/core/fuzzing/differential_oracle.py +629 -0
- package/core/fuzzing/fuzz_input.py +1188 -0
- package/core/fuzzing/stateful_fuzzer.py +332 -0
- package/core/governance/README.md +61 -0
- package/core/governance/__init__.py +130 -0
- package/core/governance/capacity_planner.py +124 -0
- package/core/governance/dependency_lock.py +317 -0
- package/core/governance/goal_governor.py +754 -0
- package/core/governance/guide_budget.py +458 -0
- package/core/governance/lockdown.sh +50 -0
- package/core/governance/readonly_enforcer.py +154 -0
- package/core/governance/runtime_tool_gate.py +373 -0
- package/core/governance/secret_redactor.py +772 -0
- package/core/governance/token_budget.py +38 -0
- package/core/host_acp/INTERFACE.md +36 -0
- package/core/host_acp/README.md +51 -0
- package/core/host_acp/SPEC.md +25 -0
- package/core/host_acp/__init__.py +121 -0
- package/core/host_acp/base.py +111 -0
- package/core/host_acp/claude.py +41 -0
- package/core/host_acp/cline.py +235 -0
- package/core/host_acp/codex.py +245 -0
- package/core/host_acp/dsh.py +48 -0
- package/core/host_acp/opencode.py +154 -0
- package/core/host_acp/pi.py +36 -0
- package/core/host_acp/zcode.py +41 -0
- package/core/host_runtime/INTERFACE.md +24 -0
- package/core/host_runtime/README.md +62 -0
- package/core/host_runtime/SPEC.md +25 -0
- package/core/host_runtime/__init__.py +21 -0
- package/core/host_runtime/adapters.py +412 -0
- package/core/host_runtime/autonomous_runner.py +1152 -0
- package/core/host_runtime/cline.py +435 -0
- package/core/host_runtime/common.py +103 -0
- package/core/host_runtime/free_models.py +786 -0
- package/core/host_runtime/host_bootstrap.py +389 -0
- package/core/host_runtime/host_evaluators.py +721 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +777 -0
- package/core/host_runtime/host_registry.py +655 -0
- package/core/host_runtime/host_usage.py +127 -0
- package/core/host_runtime/mcp_process_tracker.py +509 -0
- package/core/host_runtime/mcp_registry_gate.py +368 -0
- package/core/hosts/INTERFACE.md +51 -0
- package/core/hosts/README.md +67 -0
- package/core/hosts/SPEC.md +25 -0
- package/core/hosts/__init__.py +136 -0
- package/core/hosts/_base_usage.py +152 -0
- package/core/hosts/_codex_usage.py +297 -0
- package/core/hosts/_dsh_usage.py +184 -0
- package/core/hosts/_mcp_toml.py +365 -0
- package/core/hosts/_zcode_usage.py +269 -0
- package/core/hosts/base.py +451 -0
- package/core/hosts/claude.py +157 -0
- package/core/hosts/cline.py +225 -0
- package/core/hosts/codex.py +948 -0
- package/core/hosts/dsh.py +518 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +151 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +39 -0
- package/core/infra/__init__.py +15 -0
- package/core/infra/build_info.py +86 -0
- package/core/infra/client_metadata.py +185 -0
- package/core/infra/python_runtime.py +540 -0
- package/core/infra/safe_xml.py +221 -0
- package/core/launch_bugx.py +118 -0
- package/core/launch_phases/INTERFACE.md +31 -0
- package/core/launch_phases/README.md +106 -0
- package/core/launch_phases/SPEC.md +25 -0
- package/core/launch_phases/__init__.py +29 -0
- package/core/launch_phases/candidate_revalidation.py +484 -0
- package/core/launch_phases/common.py +1041 -0
- package/core/launch_phases/finding_confirm_phase.py +387 -0
- package/core/launch_phases/finding_settlement.py +1245 -0
- package/core/launch_phases/findings_adjudication.py +666 -0
- package/core/launch_phases/findings_snapshot.py +357 -0
- package/core/launch_phases/judge_phase.py +791 -0
- package/core/launch_phases/lesson_context.py +536 -0
- package/core/launch_phases/lifecycle_reporter.py +627 -0
- package/core/launch_phases/orchestrator_controls.py +682 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +591 -0
- package/core/launch_phases/post_dry_run.py +817 -0
- package/core/launch_phases/post_observability.py +367 -0
- package/core/launch_phases/post_phase.py +1087 -0
- package/core/launch_phases/post_receipt.py +362 -0
- package/core/launch_phases/post_round_lifecycle.py +786 -0
- package/core/launch_phases/pre_phase.py +1029 -0
- package/core/launch_phases/pre_recon_scout.py +862 -0
- package/core/launch_phases/pre_state_builder.py +1286 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1133 -0
- package/core/launch_phases/session_runtime.py +1623 -0
- package/core/launch_phases/startup_gates.py +1022 -0
- package/core/launch_phases/startup_interaction.py +947 -0
- package/core/launch_phases/startup_version_gate.py +873 -0
- package/core/launch_phases/supervisor_bridge.py +1224 -0
- package/core/launch_phases/supervisor_coverage.py +417 -0
- package/core/launch_phases/supervisor_degraded.py +1219 -0
- package/core/launch_phases/worker_barriers.py +414 -0
- package/core/launch_phases/worker_orchestrator.py +1166 -0
- package/core/launch_phases/worker_prior.py +749 -0
- package/core/ledger/INTERFACE.md +35 -0
- package/core/ledger/README.md +160 -0
- package/core/ledger/SPEC.md +25 -0
- package/core/ledger/__init__.py +67 -0
- package/core/ledger/_facade.py +226 -0
- package/core/ledger/archive_ops.py +572 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +270 -0
- package/core/ledger/export_ops.py +549 -0
- package/core/ledger/finding_confirmation.py +1274 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +307 -0
- package/core/ledger/finding_verification.py +369 -0
- package/core/ledger/incidents.py +999 -0
- package/core/ledger/lesson-replay-cases.json +20 -0
- package/core/ledger/lesson_ledger.py +241 -0
- package/core/ledger/lesson_replay.py +272 -0
- package/core/ledger/life_ledger.py +668 -0
- package/core/ledger/mistake-book.md +130 -0
- package/core/ledger/patterns.py +681 -0
- package/core/ledger/receipt_contract.py +253 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +935 -0
- package/core/ledger/tool_experience.py +682 -0
- package/core/ledger/verify_life.py +1526 -0
- package/core/lesson-ledger.json +275 -0
- package/core/locales/README.md +19 -0
- package/core/locales/en-US.json +462 -0
- package/core/locales/zh-CN.json +462 -0
- package/core/mcp_handlers/INTERFACE.md +75 -0
- package/core/mcp_handlers/README.md +62 -0
- package/core/mcp_handlers/SPEC.md +25 -0
- package/core/mcp_handlers/__init__.py +128 -0
- package/core/mcp_handlers/base.py +697 -0
- package/core/mcp_handlers/channel_lifecycle.py +696 -0
- package/core/mcp_handlers/graph_handlers.py +222 -0
- package/core/mcp_handlers/knowledge_handlers.py +536 -0
- package/core/mcp_handlers/mining_handlers.py +586 -0
- package/core/mcp_handlers/resource_prompt_table.py +116 -0
- package/core/mcp_handlers/retrieval_handlers.py +239 -0
- package/core/mcp_handlers/rpc_server.py +465 -0
- package/core/mcp_handlers/supervisor_handlers.py +1435 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1015 -0
- package/core/mcp_runtime_support/README.md +21 -0
- package/core/mcp_runtime_support/__init__.py +1 -0
- package/core/mcp_runtime_support/common.py +363 -0
- package/core/mcp_runtime_support/environment.py +605 -0
- package/core/mcp_runtime_support/verifier.py +810 -0
- package/core/metadata.txt +5 -0
- package/core/planning/README.md +157 -0
- package/core/planning/__init__.py +242 -0
- package/core/planning/capability_plan.py +187 -0
- package/core/planning/capability_planner.py +195 -0
- package/core/planning/domain_archetype.py +542 -0
- package/core/planning/domain_router.py +267 -0
- package/core/planning/dynamic_flow_analyzer.py +328 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1163 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1702 -0
- package/core/planning/source_inspector.py +267 -0
- package/core/planning/spec_harvester.py +449 -0
- package/core/planning/target_sandbox_manager.py +573 -0
- package/core/planning/test_capability_verifier.py +1364 -0
- package/core/planning/tools-kb.md +38 -0
- package/core/planning/unit_kind.py +122 -0
- package/core/probes/INTERFACE.md +73 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +26 -0
- package/core/probes/__init__.py +70 -0
- package/core/probes/android_probe.py +384 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +590 -0
- package/core/probes/desktop_probe.py +238 -0
- package/core/probes/differential_probe.py +356 -0
- package/core/probes/efficiency_probe.py +168 -0
- package/core/probes/ios_binary_probe.py +368 -0
- package/core/probes/memory_probe.py +326 -0
- package/core/probes/miniprogram_probe.py +323 -0
- package/core/probes/mobile_probe.py +281 -0
- package/core/probes/native_probe.py +214 -0
- package/core/probes/openwiki_probe.py +193 -0
- package/core/probes/pattern_probe.py +347 -0
- package/core/probes/platform_probe.py +343 -0
- package/core/probes/probe_registry.py +1669 -0
- package/core/probes/sast_probe.py +1009 -0
- package/core/probes/sast_rules.py +841 -0
- package/core/probes/sca_scanner.py +731 -0
- package/core/probes/web_probe.py +359 -0
- package/core/project_profiler/INTERFACE.md +62 -0
- package/core/project_profiler/README.md +53 -0
- package/core/project_profiler/SPEC.md +28 -0
- package/core/project_profiler/__init__.py +201 -0
- package/core/project_profiler/arbitrator.py +311 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +392 -0
- package/core/project_profiler/extractors.py +836 -0
- package/core/project_profiler/fingerprint.py +116 -0
- package/core/project_profiler/storage.py +258 -0
- package/core/project_profiler/strategy.py +265 -0
- package/core/prompts/README.md +35 -0
- package/core/prompts/codex_dialog_dispatch.md +9 -0
- package/core/prompts/command_routing_en.md +42 -0
- package/core/prompts/command_routing_zh.md +42 -0
- package/core/prompts/l0_router.md +47 -0
- package/core/prompts/rules/anti_patterns.md +16 -0
- package/core/prompts/rules/concurrency_rules.md +14 -0
- package/core/prompts/rules/memory_leak_rules.md +13 -0
- package/core/prompts/rules/prompt_injection_defense.md +13 -0
- package/core/prompts/stages/stage_explore.md +31 -0
- package/core/prompts/stages/stage_gate.md +43 -0
- package/core/prompts/stages/stage_mutate.md +42 -0
- package/core/prompts/stages/stage_repair.md +85 -0
- package/core/repair/README.md +74 -0
- package/core/repair/__init__.py +169 -0
- package/core/repair/fix_watchlist.py +391 -0
- package/core/repair/l7_dynamic.py +418 -0
- package/core/repair/l7_repair_loop.py +465 -0
- package/core/repair/l7_selfcheck.py +862 -0
- package/core/repair/minimize_repro.py +466 -0
- package/core/repair/patch_synthesizer.py +617 -0
- package/core/repair/regression_pack.py +379 -0
- package/core/repair/rsi_fixer.py +910 -0
- package/core/repair/rsi_loop.py +313 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +262 -0
- package/core/repair/self_heal.py +604 -0
- package/core/repair/test_generator.py +1108 -0
- package/core/repair/test_quality_auditor.py +410 -0
- package/core/repair/test_strategy.py +511 -0
- package/core/report_engine/INTERFACE.md +59 -0
- package/core/report_engine/README.md +69 -0
- package/core/report_engine/SPEC.md +28 -0
- package/core/report_engine/__init__.py +47 -0
- package/core/report_engine/attestation.py +224 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +417 -0
- package/core/report_engine/formal_report_builder.py +924 -0
- package/core/report_engine/html_renderers.py +696 -0
- package/core/report_engine/models.py +761 -0
- package/core/report_engine/pdf_exporter.py +231 -0
- package/core/report_engine/projects_assets.py +730 -0
- package/core/report_engine/report_client.py +743 -0
- package/core/report_engine/report_data_builder.py +388 -0
- package/core/report_engine/report_share.py +459 -0
- package/core/report_engine/sast_bridge.py +116 -0
- package/core/report_engine/server.py +822 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +63 -0
- package/core/report_engine/web_conformance.py +459 -0
- package/core/report_engine/workbench_assets.py +484 -0
- package/core/retrieval/INTERFACE.md +20 -0
- package/core/retrieval/README.md +161 -0
- package/core/retrieval/SPEC.md +25 -0
- package/core/retrieval/__init__.py +3 -0
- package/core/retrieval/code_analyzer.py +1684 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +234 -0
- package/core/retrieval/corpus_fetch.py +369 -0
- package/core/retrieval/graph_ego.py +597 -0
- package/core/retrieval/knowledge_auto.py +662 -0
- package/core/retrieval/knowledge_sources.py +168 -0
- package/core/retrieval/knowledge_sync.py +909 -0
- package/core/retrieval/memory_store.py +480 -0
- package/core/retrieval/query_planner.py +1020 -0
- package/core/retrieval/rrf_engine.py +137 -0
- package/core/retrieval/slice_extractor.py +1209 -0
- package/core/retrieval/slice_normalizer.py +373 -0
- package/core/retrieval/slice_spec.py +357 -0
- package/core/retrieval/symbol_index.py +1132 -0
- package/core/retrieval/universal_code_matcher.py +437 -0
- package/core/retrieval/xerj_bridge.py +476 -0
- package/core/retrieval/xerj_supervisor.py +362 -0
- package/core/rules/README.md +33 -0
- package/core/rules/ios/PROVENANCE.json +30 -0
- package/core/rules/ios/crypto.yaml +36 -0
- package/core/rules/ios/network.yaml +20 -0
- package/core/rules/ios/resilience.yaml +47 -0
- package/core/rules/ios/storage.yaml +48 -0
- package/core/rules/mastg/LICENSE +173 -0
- package/core/rules/mastg/PROVENANCE.json +270 -0
- package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
- package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
- package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
- package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
- package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
- package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
- package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
- package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
- package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
- package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
- package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
- package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
- package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
- package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
- package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
- package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
- package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
- package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
- package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
- package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
- package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
- package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
- package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
- package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
- package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
- package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
- package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
- package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
- package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
- package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
- package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
- package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
- package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
- package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
- package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
- package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
- package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
- package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
- package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
- package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
- package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
- package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
- package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
- package/core/rules/miniprogram/PROVENANCE.json +26 -0
- package/core/rules/miniprogram/network.yaml +37 -0
- package/core/rules/miniprogram/platform.yaml +36 -0
- package/core/rules/miniprogram/storage.yaml +48 -0
- package/core/rules/mobsfscan-swift/LICENSE +165 -0
- package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
- package/core/rules/mobsfscan-swift/auth.yaml +59 -0
- package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
- package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
- package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
- package/core/rules/mobsfscan-swift/logging.yaml +23 -0
- package/core/rules/mobsfscan-swift/network.yaml +55 -0
- package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
- package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
- package/core/rules/mobsfscan-swift/storage.yaml +29 -0
- package/core/rules/mobsfscan-swift/webview.yaml +32 -0
- package/core/runtime/README.md +198 -0
- package/core/runtime/__init__.py +3 -0
- package/core/runtime/bugx_logging.py +1393 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +449 -0
- package/core/runtime/global_telemetry.py +549 -0
- package/core/runtime/incident_eval.py +148 -0
- package/core/runtime/interaction.py +605 -0
- package/core/runtime/interaction_store.py +435 -0
- package/core/runtime/interactive_menu.py +95 -0
- package/core/runtime/log_analytics.py +922 -0
- package/core/runtime/mining_quality_framework.py +1387 -0
- package/core/runtime/model_runner.py +769 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +476 -0
- package/core/runtime/project_graph.py +827 -0
- package/core/runtime/project_init.py +481 -0
- package/core/runtime/project_profile.py +224 -0
- package/core/runtime/project_settings.py +963 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +814 -0
- package/core/runtime/seed_drill.py +549 -0
- package/core/runtime/self_audit.py +550 -0
- package/core/runtime/session_profile.py +205 -0
- package/core/runtime/setup_ui_env.py +229 -0
- package/core/runtime/startup_environment.py +859 -0
- package/core/runtime/sync_store.py +1421 -0
- package/core/runtime/tool_install_targets.py +18 -0
- package/core/schemas/README.md +35 -0
- package/core/schemas/agent-graph.schema.json +368 -0
- package/core/schemas/attack-graph.schema.json +88 -0
- package/core/schemas/evidence-bundle.schema.json +33 -0
- package/core/schemas/skill-pack.schema.json +230 -0
- package/core/schemas/worker-checkpoint.schema.json +119 -0
- package/core/secure_atomic.py +289 -0
- package/core/seed_corpus/README.md +55 -0
- package/core/seed_corpus/c.txt +29 -0
- package/core/seed_corpus/cpp.txt +32 -0
- package/core/seed_corpus/css.txt +70 -0
- package/core/seed_corpus/go.txt +46 -0
- package/core/seed_corpus/java.txt +30 -0
- package/core/seed_corpus/javascript.txt +55 -0
- package/core/seed_corpus/kotlin.txt +28 -0
- package/core/seed_corpus/python.txt +71 -0
- package/core/seed_corpus/rust.txt +53 -0
- package/core/seed_corpus/swift.txt +29 -0
- package/core/seed_corpus/typescript.txt +29 -0
- package/core/skills/README.md +53 -0
- package/core/skills/__init__.py +189 -0
- package/core/skills/bugx_docs_mcp_server.py +416 -0
- package/core/skills/bugx_mcp_server.py +1134 -0
- package/core/skills/mcp_runtime.py +968 -0
- package/core/skills/mcp_session_proof.py +605 -0
- package/core/skills/mobile_ui_inspector.py +405 -0
- package/core/skills/skill_pack.py +1214 -0
- package/core/skills/skill_synthesizer.py +1153 -0
- package/core/skills/tools_kb.py +313 -0
- package/core/supervisor/INTERFACE.md +121 -0
- package/core/supervisor/README.md +209 -0
- package/core/supervisor/SPEC.md +25 -0
- package/core/supervisor/__init__.py +175 -0
- package/core/supervisor/audit_supervisor.py +1015 -0
- package/core/supervisor/budget_governor.py +760 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1322 -0
- package/core/supervisor/checkpoint_sync.py +640 -0
- package/core/supervisor/claim_events.py +74 -0
- package/core/supervisor/claim_sync.py +590 -0
- package/core/supervisor/cli.py +812 -0
- package/core/supervisor/context_sync.py +55 -0
- package/core/supervisor/coverage_sync.py +115 -0
- package/core/supervisor/finding_commit.py +470 -0
- package/core/supervisor/finding_sync.py +688 -0
- package/core/supervisor/finding_workflow.py +659 -0
- package/core/supervisor/finish_policy.py +224 -0
- package/core/supervisor/finish_sync.py +185 -0
- package/core/supervisor/graph_sync.py +669 -0
- package/core/supervisor/lease_manager.py +788 -0
- package/core/supervisor/lifecycle_blocks.py +124 -0
- package/core/supervisor/next_round_sync.py +126 -0
- package/core/supervisor/observability.py +140 -0
- package/core/supervisor/recovery_sync.py +165 -0
- package/core/supervisor/rejection_remedies.py +308 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +500 -0
- package/core/supervisor/start_sync.py +87 -0
- package/core/supervisor/state_store.py +249 -0
- package/core/supervisor/supervisor_host.py +511 -0
- package/core/supervisor/supervisor_models.py +1143 -0
- package/core/supervisor/systemic_failure.py +104 -0
- package/core/supervisor/task_scheduler.py +1640 -0
- package/core/supervisor/worker_checkpoint.py +223 -0
- package/core/supervisor/worker_execution.py +265 -0
- package/core/supervisor/worker_handoff.py +192 -0
- package/core/supervisor/worker_lifecycle.py +396 -0
- package/core/supervisor/worker_runtime.py +999 -0
- package/core/supervisor/worker_sync.py +89 -0
- package/core/supervisor_types/README.md +36 -0
- package/core/supervisor_types/__init__.py +0 -0
- package/core/supervisor_types/exceptions.py +52 -0
- package/core/supervisor_types/graph_models.py +357 -0
- package/core/supervisor_types/path_containment.py +151 -0
- package/core/supervisor_types/target_fingerprint.py +310 -0
- package/core/supervisor_types/worker_claim.py +402 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +25 -0
- package/core/webui/__init__.py +11 -0
- package/core/webui/adapters/__init__.py +27 -0
- package/core/webui/adapters/base.py +87 -0
- package/core/webui/adapters/bugx.py +102 -0
- package/core/webui/adapters/claude.py +218 -0
- package/core/webui/adapters/cline.py +399 -0
- package/core/webui/adapters/codex.py +256 -0
- package/core/webui/adapters/dsh.py +173 -0
- package/core/webui/adapters/opencode.py +218 -0
- package/core/webui/adapters/pi.py +272 -0
- package/core/webui/adapters/registry.py +100 -0
- package/core/webui/adapters/zcode.py +312 -0
- package/core/webui/api_routes_post.py +668 -0
- package/core/webui/dispatcher.py +1376 -0
- package/core/webui/docs_session_service.py +473 -0
- package/core/webui/handler.py +674 -0
- package/core/webui/ide_cloud_service.py +526 -0
- package/core/webui/mcp_inspector.py +1743 -0
- package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
- package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
- package/core/webui/static/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +42 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.css +6458 -0
- package/core/webui/static/project-settings.js +9602 -0
- package/core/webui/static/sw.js +8 -0
- package/core/webui/workspace_service.py +218 -0
- package/docs/07_distribution/01_README_NPM.md +281 -0
- package/docs/07_distribution/README.md +16 -0
- package/docs/README.md +121 -0
- package/ecosystem/README.md +129 -0
- package/ecosystem/integrations/README.md +38 -0
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
- package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
- package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/mcp/index.js +219 -0
- package/ecosystem/integrations/dsh/mcp/package.json +28 -0
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/integrations/dsh/ui/client.js +87 -0
- package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/ui/index.js +7 -0
- package/ecosystem/integrations/dsh/ui/package.json +27 -0
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
- package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
- package/ecosystem/integrations/opencode/opencode.json +118 -0
- package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
- package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
- package/ecosystem/integrations/qoder/connector-meta.json +21 -0
- package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
- package/ecosystem/integrations/workbuddy/icon.png +0 -0
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
- package/ecosystem/plugins/README.md +37 -0
- package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
- package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
- package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
- package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
- package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
- package/interfaces/README.md +143 -0
- package/interfaces/bin/README.md +35 -0
- package/interfaces/bin/bugx.js +80 -0
- package/interfaces/cli/README.md +90 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/cli.py +1678 -0
- package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
- package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
- package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
- package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
- package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
- package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
- package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
- package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
- package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
- package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
- package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
- package/interfaces/cli/bugx_cli/commands/project.py +670 -0
- package/interfaces/cli/bugx_cli/commands/report.py +260 -0
- package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
- package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
- package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
- package/interfaces/cli/bugx_cli/common.py +898 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
- package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
- package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
- package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
- package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
- package/interfaces/cli/bugx_cli/infra/security.py +332 -0
- package/package.json +98 -4
- package/pyproject.toml +246 -0
- package/scripts/README.md +118 -0
- package/scripts/ensure-python.mjs +97 -0
- package/scripts/isolate-npm-readme.mjs +40 -0
- package/scripts/runtime.lock.json +31 -0
- package/scripts/sync-version.mjs +37 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,1009 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""探测并执行 SAST 静态分析与轻量 SCA 依赖安全扫描 (DOC-061)。
|
|
3
|
+
|
|
4
|
+
SAST 层定位:
|
|
5
|
+
1. 规则驱动的已知漏洞模式扫描(SQLi/XSS/SSRF/RCE/SCA/反模式/反序列化/机密泄漏);
|
|
6
|
+
2. 零外部依赖多语言支持:内置通用结构化分词与括号平衡树引擎,
|
|
7
|
+
原生覆盖 Go、Java、TypeScript/JavaScript、Rust、C/C++、Python、PHP 等主流语言;
|
|
8
|
+
3. 供应链安全 (SCA):内置轻量离线依赖漏洞匹配器 (pom.xml/package.json/go.mod/requirements.txt/Cargo.lock);
|
|
9
|
+
4. 企业级工程治理:支持跨语言行级抑制 (// bugx-ignore)、基线快照 (--baseline) 与 OASIS SARIF v2.1.0 标准导出;
|
|
10
|
+
5. 非侵入容灾原则:严禁强制外部工具安装,无外部工具时 100% 自动无缝降级至内置多语言引擎。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
from typing import Any
|
|
15
|
+
# --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
|
|
16
|
+
import sys as _sys
|
|
17
|
+
from pathlib import Path as _Path
|
|
18
|
+
|
|
19
|
+
for _p in _Path(__file__).resolve().parents:
|
|
20
|
+
if (_p / "core" / "bugx.md").is_file():
|
|
21
|
+
if str(_p) not in _sys.path:
|
|
22
|
+
_sys.path.insert(0, str(_p))
|
|
23
|
+
break
|
|
24
|
+
del _p
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import ast
|
|
28
|
+
import collections
|
|
29
|
+
import hashlib
|
|
30
|
+
import json
|
|
31
|
+
import math
|
|
32
|
+
import os
|
|
33
|
+
import re
|
|
34
|
+
import shutil
|
|
35
|
+
import subprocess
|
|
36
|
+
import time
|
|
37
|
+
import sys
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
_CURRENT_DIR = Path(__file__).resolve().parent
|
|
41
|
+
_CORE_DIR = _CURRENT_DIR.parent
|
|
42
|
+
_REPO_ROOT = _CORE_DIR.parent
|
|
43
|
+
for _p in (str(_REPO_ROOT), str(_CORE_DIR), str(_CURRENT_DIR)):
|
|
44
|
+
if _p not in sys.path:
|
|
45
|
+
sys.path.insert(0, _p)
|
|
46
|
+
|
|
47
|
+
from core.probes.sast_rules import BUILTIN_RULES, SASTRuleMatcher
|
|
48
|
+
from core.probes.sca_scanner import SCAScanner
|
|
49
|
+
|
|
50
|
+
from core.planning.dynamic_flow_analyzer import DynamicFlowAnalyzer
|
|
51
|
+
|
|
52
|
+
from core.runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
|
|
53
|
+
from core.retrieval.universal_code_matcher import EXT_TO_LANG, ParsedSource, UniversalCodeMatcher
|
|
54
|
+
|
|
55
|
+
VALIDATED = {
|
|
56
|
+
"semgrep": "1.80.0",
|
|
57
|
+
"codeql": "2.18.0",
|
|
58
|
+
"trivy": "0.54.0",
|
|
59
|
+
"bandit": "1.8.6",
|
|
60
|
+
}
|
|
61
|
+
# Exact package pins remain separate from VALIDATED: an install target is not
|
|
62
|
+
# evidence that this checkout exercised the corresponding runtime.
|
|
63
|
+
MINIMUM = {
|
|
64
|
+
"semgrep": "1.50.0",
|
|
65
|
+
"codeql": "2.15.0",
|
|
66
|
+
"trivy": "0.40.0",
|
|
67
|
+
"bandit": "1.7.0",
|
|
68
|
+
}
|
|
69
|
+
VERSION_FLAG = {"codeql": "version"}
|
|
70
|
+
|
|
71
|
+
SKIP_DIRS = {
|
|
72
|
+
".git", ".bugx", ".venv", "venv", "node_modules", "__pycache__",
|
|
73
|
+
"dist", "build", "target", ".tox", ".mypy_cache", ".pytest_cache",
|
|
74
|
+
"vendor", "Pods", ".gradle", ".idea",
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _skipped(relative: Path) -> bool:
|
|
79
|
+
"""SAST 也要排除引擎/宿主的 ``.bugx*`` 运行态命名空间。
|
|
80
|
+
|
|
81
|
+
此前只按 ``SKIP_DIRS`` 的字面名排除 ``.bugx``,``.bugx-audit-artifacts``
|
|
82
|
+
这类兄弟目录会被当源码扫描——实测靶场里宿主写的 ``repro.py`` 就产生了
|
|
83
|
+
两条 ``SEC-006-SILENT-EXCEPTION``,被报告当成被测产品的缺陷。
|
|
84
|
+
判定与覆盖枚举同源(``core.retrieval.symbol_index``),避免两份名单漂移。
|
|
85
|
+
"""
|
|
86
|
+
from core.retrieval.symbol_index import _is_engine_namespace_segment
|
|
87
|
+
|
|
88
|
+
return any(
|
|
89
|
+
part in SKIP_DIRS or _is_engine_namespace_segment(part)
|
|
90
|
+
for part in relative.parts
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _probe_environment() -> dict[str, str]:
|
|
95
|
+
try:
|
|
96
|
+
try:
|
|
97
|
+
from .probe_registry import normalized_tool_environment
|
|
98
|
+
except (ImportError, ValueError):
|
|
99
|
+
try:
|
|
100
|
+
from .probe_registry import normalized_tool_environment
|
|
101
|
+
except ImportError:
|
|
102
|
+
from core.probes.probe_registry import normalized_tool_environment
|
|
103
|
+
return normalized_tool_environment()
|
|
104
|
+
except ImportError:
|
|
105
|
+
return dict(os.environ)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def version_tuple(value: str) -> tuple[int, ...]:
|
|
109
|
+
match = re.search(r"(\d+(?:\.\d+){1,3})", value)
|
|
110
|
+
return tuple(int(part) for part in match.group(1).split(".")) if match else ()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_TOOL_PROBE_CACHE: dict[str, dict] = {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def clear_tool_probe_cache() -> None:
|
|
117
|
+
_TOOL_PROBE_CACHE.clear()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _tool_candidates(names: tuple[str, ...], search_path: str) -> list[str]:
|
|
121
|
+
"""Return deduplicated executables in PATH order for the requested aliases."""
|
|
122
|
+
directories = [entry for entry in search_path.split(os.pathsep) if entry]
|
|
123
|
+
candidates: list[str] = []
|
|
124
|
+
seen: set[str] = set()
|
|
125
|
+
for name in names:
|
|
126
|
+
for directory in directories:
|
|
127
|
+
candidate = shutil.which(name, path=directory)
|
|
128
|
+
if not candidate:
|
|
129
|
+
continue
|
|
130
|
+
identity = os.path.normcase(os.path.realpath(candidate))
|
|
131
|
+
if identity in seen:
|
|
132
|
+
continue
|
|
133
|
+
seen.add(identity)
|
|
134
|
+
candidates.append(candidate)
|
|
135
|
+
return candidates
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _candidate_signature(candidates: list[str], search_path: str) -> tuple:
|
|
139
|
+
"""Invalidate cached versions when PATH candidates or their files change."""
|
|
140
|
+
signatures = []
|
|
141
|
+
for candidate in candidates:
|
|
142
|
+
try:
|
|
143
|
+
stat = Path(candidate).stat()
|
|
144
|
+
file_signature = (stat.st_mtime_ns, stat.st_size)
|
|
145
|
+
except OSError:
|
|
146
|
+
file_signature = None
|
|
147
|
+
signatures.append((candidate, os.path.realpath(candidate), file_signature))
|
|
148
|
+
return search_path, tuple(signatures)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _version_at_least(actual: tuple[int, ...], minimum: tuple[int, ...]) -> bool:
|
|
152
|
+
width = max(len(actual), len(minimum))
|
|
153
|
+
return actual + (0,) * (width - len(actual)) >= minimum + (0,) * (width - len(minimum))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _command(names: tuple[str, ...], expected: str) -> dict:
|
|
157
|
+
environment = _probe_environment()
|
|
158
|
+
search_path = environment.get("PATH", "")
|
|
159
|
+
candidates = _tool_candidates(names, search_path)
|
|
160
|
+
if not candidates:
|
|
161
|
+
return {"name": expected, "ok": False, "path": None, "version": None,
|
|
162
|
+
"detail": "未安装"}
|
|
163
|
+
|
|
164
|
+
signature = _candidate_signature(candidates, search_path)
|
|
165
|
+
cached = _TOOL_PROBE_CACHE.get(expected)
|
|
166
|
+
if cached and cached.get("_signature") == signature:
|
|
167
|
+
return {key: value for key, value in cached.items() if key != "_signature"}
|
|
168
|
+
|
|
169
|
+
flag = VERSION_FLAG.get(expected, "--version")
|
|
170
|
+
minimum = version_tuple(MINIMUM[expected])
|
|
171
|
+
observations: list[dict] = []
|
|
172
|
+
transient_failure = False
|
|
173
|
+
for path in candidates:
|
|
174
|
+
try:
|
|
175
|
+
result = subprocess.run(
|
|
176
|
+
[path, flag], capture_output=True, text=True,
|
|
177
|
+
check=False, timeout=10, env=environment,
|
|
178
|
+
)
|
|
179
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
180
|
+
transient_failure = True
|
|
181
|
+
observations.append({
|
|
182
|
+
"path": path, "version": None, "detail": type(exc).__name__,
|
|
183
|
+
})
|
|
184
|
+
continue
|
|
185
|
+
output = f"{result.stdout or ''}\n{result.stderr or ''}"
|
|
186
|
+
version_text = next(
|
|
187
|
+
(line.strip() for line in output.splitlines() if version_tuple(line)), "",
|
|
188
|
+
)
|
|
189
|
+
actual = version_tuple(version_text)
|
|
190
|
+
if result.returncode == 0 and actual and _version_at_least(actual, minimum):
|
|
191
|
+
info = {
|
|
192
|
+
"name": expected,
|
|
193
|
+
"ok": True,
|
|
194
|
+
"path": path,
|
|
195
|
+
"version": version_text,
|
|
196
|
+
"minimum": MINIMUM[expected],
|
|
197
|
+
"validated": VALIDATED[expected],
|
|
198
|
+
"detail": version_text,
|
|
199
|
+
"rejected_candidates": observations,
|
|
200
|
+
}
|
|
201
|
+
_TOOL_PROBE_CACHE[expected] = {**info, "_signature": signature}
|
|
202
|
+
return info
|
|
203
|
+
observations.append({
|
|
204
|
+
"path": path,
|
|
205
|
+
"version": version_text or None,
|
|
206
|
+
"detail": version_text or f"--version exited {result.returncode}",
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
first = observations[0] if observations else {}
|
|
210
|
+
info = {
|
|
211
|
+
"name": expected,
|
|
212
|
+
"ok": False,
|
|
213
|
+
"path": first.get("path", candidates[0]),
|
|
214
|
+
"version": first.get("version"),
|
|
215
|
+
"minimum": MINIMUM[expected],
|
|
216
|
+
"validated": VALIDATED[expected],
|
|
217
|
+
"detail": f"未找到满足最低版本 {MINIMUM[expected]} 的 PATH 候选",
|
|
218
|
+
"rejected_candidates": observations,
|
|
219
|
+
}
|
|
220
|
+
if not transient_failure:
|
|
221
|
+
_TOOL_PROBE_CACHE[expected] = {**info, "_signature": signature}
|
|
222
|
+
return info
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def check_tool(name: str) -> dict:
|
|
226
|
+
"""Check one registered SAST executable using the same PATH/version policy."""
|
|
227
|
+
if name not in MINIMUM:
|
|
228
|
+
raise ValueError(f"不支持的 SAST 工具: {name}")
|
|
229
|
+
return _command((name,), name)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def inspect(root: Path) -> dict:
|
|
233
|
+
root = root.resolve()
|
|
234
|
+
base = [
|
|
235
|
+
_command(("semgrep",), "semgrep"),
|
|
236
|
+
_command(("codeql",), "codeql"),
|
|
237
|
+
_command(("trivy",), "trivy"),
|
|
238
|
+
_command(("bandit",), "bandit"),
|
|
239
|
+
]
|
|
240
|
+
ready = any(item["ok"] for item in base)
|
|
241
|
+
return {
|
|
242
|
+
"status": "READY" if ready else "DEGRADED",
|
|
243
|
+
"required": False,
|
|
244
|
+
"recommended": True,
|
|
245
|
+
"root": str(root),
|
|
246
|
+
"base_tools": base,
|
|
247
|
+
"install": {
|
|
248
|
+
"semgrep": f"pipx install {OPTIONAL_TOOL_PACKAGE_SPECS['semgrep']}",
|
|
249
|
+
"codeql": "https://github.com/github/codeql-cli-binaries/releases",
|
|
250
|
+
"trivy": "brew install trivy",
|
|
251
|
+
"bandit": f"pipx install {OPTIONAL_TOOL_PACKAGE_SPECS['bandit']}",
|
|
252
|
+
},
|
|
253
|
+
"fallback": "pattern_probe.py scan + ast-grep 有界静态扫描",
|
|
254
|
+
"workflow": "SAST 扫描出候选点 → codebase-memory trace_path 验 Source→Sink → PostMCP/Playwright 发 PoC 复现",
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def print_report(report: dict, as_json: bool = False) -> None:
|
|
259
|
+
if as_json:
|
|
260
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
261
|
+
return
|
|
262
|
+
print(f"[{report['status']}] SAST 静态分析工具链(推荐,非硬依赖,支持多语言自动降级)")
|
|
263
|
+
for item in report["base_tools"]:
|
|
264
|
+
print(f" {'✓' if item['ok'] else '!'} {item['name']}: {item['detail']}")
|
|
265
|
+
if report["status"] != "READY":
|
|
266
|
+
print(f" → 回退:{report['fallback']}")
|
|
267
|
+
print(" → 架构契约:非侵入式零依赖,未安装外部工具时直接使用内置多语言分析引擎,无需配置或编译环境。")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
#: 常见的「占位符」值片段:命中即说明是文档/测试假凭证而非真实机密。
|
|
271
|
+
_SECRET_PLACEHOLDER_HINTS = (
|
|
272
|
+
"example", "placeholder", "changeme", "dummy", "sample", "redacted",
|
|
273
|
+
"your_", "xxxxx", "todo", "fixme", "fake",
|
|
274
|
+
)
|
|
275
|
+
_SECRET_CHAR_CLASSES = (r"[a-z]", r"[A-Z]", r"\d", r"[^A-Za-z0-9]")
|
|
276
|
+
#: 行级抑制注释,语义与多语言引擎的 ``// bugx-ignore`` / ``# nosec`` 保持一致。
|
|
277
|
+
_SUPPRESSION_RE = re.compile(r"(?:#|//)\s*(?:bugx-ignore(?::[^\n]*)?|nosec\b)", re.IGNORECASE)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _shannon_entropy(value: str) -> float:
|
|
281
|
+
"""字符级 Shannon 熵(bits/char),用于区分随机密钥与可读占位串。"""
|
|
282
|
+
if not value:
|
|
283
|
+
return 0.0
|
|
284
|
+
length = len(value)
|
|
285
|
+
return -sum(
|
|
286
|
+
(count / length) * math.log2(count / length)
|
|
287
|
+
for count in collections.Counter(value).values()
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _looks_like_hardcoded_secret(value: str) -> bool:
|
|
292
|
+
"""判断字面量本身是否具备「硬编码机密」的值特征(QUA-08)。
|
|
293
|
+
|
|
294
|
+
仅按变量名(含 ``api_key``/``token``)判定会把中文提示文案、状态哨兵与
|
|
295
|
+
测试假 token 全部报成 high,真实机密告警被误报淹没。这里要求值同时满足:
|
|
296
|
+
长度 ≥ 16、纯 ASCII 无空白、非 SCREAMING_SNAKE_CASE 常量、非占位符,
|
|
297
|
+
且字符级熵达标(两类字符时阈值更高)。
|
|
298
|
+
"""
|
|
299
|
+
if len(value) < 16 or not value.isascii():
|
|
300
|
+
return False
|
|
301
|
+
if any(character.isspace() for character in value):
|
|
302
|
+
return False
|
|
303
|
+
if value.startswith(("http://", "https://", "ENV_")):
|
|
304
|
+
return False
|
|
305
|
+
if re.fullmatch(r"[A-Z0-9_]+", value): # 常量名 / 状态哨兵,不是机密
|
|
306
|
+
return False
|
|
307
|
+
lowered = value.lower()
|
|
308
|
+
if any(hint in lowered for hint in _SECRET_PLACEHOLDER_HINTS):
|
|
309
|
+
return False
|
|
310
|
+
classes = sum(1 for pattern in _SECRET_CHAR_CLASSES if re.search(pattern, value))
|
|
311
|
+
if classes < 2:
|
|
312
|
+
return False
|
|
313
|
+
return _shannon_entropy(value) >= (3.5 if classes == 2 else 3.0)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
class BuiltinAstScanner(ast.NodeVisitor):
|
|
317
|
+
"""基于 Python 标准库 AST 的确定性安全与风险反模式检测器(保持向前兼容)。"""
|
|
318
|
+
|
|
319
|
+
def __init__(self, filepath: Path, rel_path: str, source_lines: list[str]) -> None:
|
|
320
|
+
self.filepath = filepath
|
|
321
|
+
self.rel_path = rel_path
|
|
322
|
+
self.source_lines = source_lines
|
|
323
|
+
self.findings: list[dict[str, Any]] = []
|
|
324
|
+
self.dynamic_analyzer = DynamicFlowAnalyzer(language="python")
|
|
325
|
+
self.var_env: dict[str, Any] = {}
|
|
326
|
+
|
|
327
|
+
def _get_snippet(self, lineno: int) -> str:
|
|
328
|
+
if 1 <= lineno <= len(self.source_lines):
|
|
329
|
+
return self.source_lines[lineno - 1].strip()
|
|
330
|
+
return ""
|
|
331
|
+
|
|
332
|
+
def _is_suppressed(self, lineno: int) -> bool:
|
|
333
|
+
"""行级抑制:``# bugx-ignore`` / ``# nosec``(与多语言引擎语义一致)。"""
|
|
334
|
+
return bool(_SUPPRESSION_RE.search(self._get_snippet(lineno)))
|
|
335
|
+
|
|
336
|
+
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
|
|
337
|
+
self.var_env.update(self.dynamic_analyzer.fold_python_function_scope(node))
|
|
338
|
+
self.generic_visit(node)
|
|
339
|
+
|
|
340
|
+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
|
|
341
|
+
self.var_env.update(self.dynamic_analyzer.fold_python_function_scope(node))
|
|
342
|
+
self.generic_visit(node)
|
|
343
|
+
|
|
344
|
+
def visit_Call(self, node: ast.Call) -> None:
|
|
345
|
+
func_name = ""
|
|
346
|
+
if isinstance(node.func, ast.Name):
|
|
347
|
+
func_name = node.func.id
|
|
348
|
+
elif isinstance(node.func, ast.Attribute):
|
|
349
|
+
func_name = node.func.attr
|
|
350
|
+
|
|
351
|
+
# os.system / os.popen 与 tempfile.mktemp,支持直接和 getattr 调用。
|
|
352
|
+
mod = ""
|
|
353
|
+
attr = ""
|
|
354
|
+
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
|
|
355
|
+
mod = node.func.value.id
|
|
356
|
+
attr = node.func.attr
|
|
357
|
+
elif (
|
|
358
|
+
isinstance(node.func, ast.Call)
|
|
359
|
+
and isinstance(node.func.func, ast.Name)
|
|
360
|
+
and node.func.func.id == "getattr"
|
|
361
|
+
and len(node.func.args) >= 2
|
|
362
|
+
):
|
|
363
|
+
target, attr_value = node.func.args[:2]
|
|
364
|
+
if isinstance(target, ast.Name):
|
|
365
|
+
mod = target.id
|
|
366
|
+
if isinstance(attr_value, ast.Constant) and isinstance(attr_value.value, str):
|
|
367
|
+
attr = attr_value.value
|
|
368
|
+
elif isinstance(attr_value, ast.Name) and attr_value.id in self.var_env:
|
|
369
|
+
value = self.var_env[attr_value.id].value
|
|
370
|
+
attr = value if isinstance(value, str) else ""
|
|
371
|
+
if mod == "os" and attr in {"system", "popen"}:
|
|
372
|
+
self.findings.append({
|
|
373
|
+
"rule_id": "SEC-001-OS-SYSTEM",
|
|
374
|
+
"name": "OS Command Injection via os.system",
|
|
375
|
+
"category": "command-injection",
|
|
376
|
+
"severity": "high",
|
|
377
|
+
"confidence": "high",
|
|
378
|
+
"cwe": "CWE-78",
|
|
379
|
+
"message": f"调用 {mod}.{attr} 执行外部命令,存在命令注入风险",
|
|
380
|
+
"file": self.rel_path,
|
|
381
|
+
"line": node.lineno,
|
|
382
|
+
"col": node.col_offset,
|
|
383
|
+
"evidence": self._get_snippet(node.lineno),
|
|
384
|
+
"remediation": "建议使用 subprocess.run 并传入数组形式的 argv,避免 shell 解析",
|
|
385
|
+
})
|
|
386
|
+
elif mod == "tempfile" and attr == "mktemp":
|
|
387
|
+
self.findings.append({
|
|
388
|
+
"rule_id": "SEC-007-INSECURE-TEMPFILE",
|
|
389
|
+
"name": "Insecure Temporary File",
|
|
390
|
+
"category": "race-condition",
|
|
391
|
+
"severity": "medium",
|
|
392
|
+
"confidence": "high",
|
|
393
|
+
"cwe": "CWE-377",
|
|
394
|
+
"message": "使用不安全的 tempfile.mktemp 创建临时文件,存在 TOCTOU 竞态漏洞",
|
|
395
|
+
"file": self.rel_path,
|
|
396
|
+
"line": node.lineno,
|
|
397
|
+
"col": node.col_offset,
|
|
398
|
+
"evidence": self._get_snippet(node.lineno),
|
|
399
|
+
"remediation": "改用 tempfile.NamedTemporaryFile 或 tempfile.mkstemp",
|
|
400
|
+
})
|
|
401
|
+
|
|
402
|
+
# subprocess(..., shell=True)
|
|
403
|
+
for kw in node.keywords:
|
|
404
|
+
if kw.arg == "shell":
|
|
405
|
+
is_true = False
|
|
406
|
+
if isinstance(kw.value, ast.Constant) and kw.value.value is True:
|
|
407
|
+
is_true = True
|
|
408
|
+
if is_true:
|
|
409
|
+
self.findings.append({
|
|
410
|
+
"rule_id": "SEC-001-SUBPROCESS-SHELL",
|
|
411
|
+
"name": "Subprocess shell=True Injection",
|
|
412
|
+
"category": "command-injection",
|
|
413
|
+
"severity": "high",
|
|
414
|
+
"confidence": "high",
|
|
415
|
+
"cwe": "CWE-78",
|
|
416
|
+
"message": "subprocess 执行携带 shell=True,可能导致未转义命令注入",
|
|
417
|
+
"file": self.rel_path,
|
|
418
|
+
"line": node.lineno,
|
|
419
|
+
"col": node.col_offset,
|
|
420
|
+
"evidence": self._get_snippet(node.lineno),
|
|
421
|
+
"remediation": "移除 shell=True,将命令拆分为参数列表传入",
|
|
422
|
+
})
|
|
423
|
+
|
|
424
|
+
# SEC-002: 危险执行 eval / exec
|
|
425
|
+
if func_name in {"eval", "exec"}:
|
|
426
|
+
self.findings.append({
|
|
427
|
+
"rule_id": "SEC-002-DANGEROUS-EVAL",
|
|
428
|
+
"name": "Dangerous Dynamic Code Execution",
|
|
429
|
+
"category": "code-injection",
|
|
430
|
+
"severity": "critical",
|
|
431
|
+
"confidence": "medium",
|
|
432
|
+
"cwe": "CWE-95",
|
|
433
|
+
"message": f"直接调用动态代码执行函数 {func_name}()",
|
|
434
|
+
"file": self.rel_path,
|
|
435
|
+
"line": node.lineno,
|
|
436
|
+
"col": node.col_offset,
|
|
437
|
+
"evidence": self._get_snippet(node.lineno),
|
|
438
|
+
"remediation": "避免使用 eval/exec;如需解析字面量使用 ast.literal_eval",
|
|
439
|
+
})
|
|
440
|
+
|
|
441
|
+
# SEC-003: 不安全反序列化 pickle.loads / marshal.loads
|
|
442
|
+
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
|
|
443
|
+
if node.func.value.id in {"pickle", "_pickle", "cPickle", "marshal"} and node.func.attr in {"load", "loads"}:
|
|
444
|
+
self.findings.append({
|
|
445
|
+
"rule_id": "SEC-003-INSECURE-DESERIALIZATION",
|
|
446
|
+
"name": "Insecure Deserialization",
|
|
447
|
+
"category": "deserialization",
|
|
448
|
+
"severity": "critical",
|
|
449
|
+
"confidence": "high",
|
|
450
|
+
"cwe": "CWE-502",
|
|
451
|
+
"message": f"使用未受信任的 {node.func.value.id}.{node.func.attr} 反序列化,可导致任意代码执行",
|
|
452
|
+
"file": self.rel_path,
|
|
453
|
+
"line": node.lineno,
|
|
454
|
+
"col": node.col_offset,
|
|
455
|
+
"evidence": self._get_snippet(node.lineno),
|
|
456
|
+
"remediation": "改用安全的结构化格式(如 json / protobuf / hmac 签名)",
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
# SEC-SSTI-001: Python SSTI (render_template_string, jinja2.Template)
|
|
460
|
+
if func_name == "render_template_string" or (
|
|
461
|
+
isinstance(node.func, ast.Attribute) and node.func.attr in {"render_template_string", "from_string"}
|
|
462
|
+
):
|
|
463
|
+
is_vuln = True
|
|
464
|
+
if node.args:
|
|
465
|
+
first_arg = node.args[0]
|
|
466
|
+
if isinstance(first_arg, ast.Constant) and isinstance(first_arg.value, str):
|
|
467
|
+
# 纯静态字面量视为安全
|
|
468
|
+
is_vuln = False
|
|
469
|
+
elif isinstance(first_arg, ast.Name) and first_arg.id in self.var_env:
|
|
470
|
+
var_obj = self.var_env[first_arg.id]
|
|
471
|
+
if var_obj.is_constant:
|
|
472
|
+
is_vuln = False
|
|
473
|
+
if is_vuln:
|
|
474
|
+
self.findings.append({
|
|
475
|
+
"rule_id": "SEC-SSTI-001",
|
|
476
|
+
"name": "Server-Side Template Injection (SSTI)",
|
|
477
|
+
"category": "template-injection",
|
|
478
|
+
"severity": "critical",
|
|
479
|
+
"confidence": "high",
|
|
480
|
+
"cwe": "CWE-1336",
|
|
481
|
+
"message": "动态渲染外部可控的模版字符串,可能导致服务端模版注入与远程代码执行",
|
|
482
|
+
"file": self.rel_path,
|
|
483
|
+
"line": node.lineno,
|
|
484
|
+
"col": node.col_offset,
|
|
485
|
+
"evidence": self._get_snippet(node.lineno),
|
|
486
|
+
"remediation": "改用静态模版文件并传递参数字典(如 render_template),严禁直接动态编译外部字符串为模版。",
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
self.generic_visit(node)
|
|
490
|
+
|
|
491
|
+
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
|
|
492
|
+
if len(node.body) == 1 and isinstance(node.body[0], ast.Pass):
|
|
493
|
+
is_broad = node.type is None
|
|
494
|
+
if isinstance(node.type, ast.Name) and node.type.id in {"Exception", "BaseException"}:
|
|
495
|
+
is_broad = True
|
|
496
|
+
if is_broad:
|
|
497
|
+
self.findings.append({
|
|
498
|
+
"rule_id": "SEC-006-SILENT-EXCEPTION",
|
|
499
|
+
"name": "Silent Generic Exception Swallowing",
|
|
500
|
+
"category": "error-handling",
|
|
501
|
+
"severity": "low",
|
|
502
|
+
"confidence": "high",
|
|
503
|
+
"cwe": "CWE-391",
|
|
504
|
+
"message": "静默捕获并吞没通用异常(except: pass),掩盖运行时致命故障",
|
|
505
|
+
"file": self.rel_path,
|
|
506
|
+
"line": node.lineno,
|
|
507
|
+
"col": node.col_offset,
|
|
508
|
+
"evidence": self._get_snippet(node.lineno),
|
|
509
|
+
"remediation": "指定具体异常类型,并在 except 块中记录日志或妥善恢复",
|
|
510
|
+
})
|
|
511
|
+
self.generic_visit(node)
|
|
512
|
+
|
|
513
|
+
def visit_Assign(self, node: ast.Assign) -> None:
|
|
514
|
+
sensitive_kw = {"password", "secret", "api_key", "apikey", "token", "private_key"}
|
|
515
|
+
for target in node.targets:
|
|
516
|
+
target_name = ""
|
|
517
|
+
if isinstance(target, ast.Name):
|
|
518
|
+
target_name = target.id.lower()
|
|
519
|
+
elif isinstance(target, ast.Attribute):
|
|
520
|
+
target_name = target.attr.lower()
|
|
521
|
+
|
|
522
|
+
if any(kw in target_name for kw in sensitive_kw):
|
|
523
|
+
if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
|
|
524
|
+
val = node.value.value
|
|
525
|
+
# QUA-08:变量名匹配只是必要条件;值本身还必须像机密。
|
|
526
|
+
if _looks_like_hardcoded_secret(val) and not self._is_suppressed(node.lineno):
|
|
527
|
+
self.findings.append({
|
|
528
|
+
"rule_id": "SEC-004-HARDCODED-SECRET",
|
|
529
|
+
"name": "Hardcoded Secret",
|
|
530
|
+
"category": "secrets",
|
|
531
|
+
"severity": "high",
|
|
532
|
+
"confidence": "medium",
|
|
533
|
+
"cwe": "CWE-798",
|
|
534
|
+
"message": f"疑似在变量 {target_name} 中硬编码静态机密凭证",
|
|
535
|
+
"file": self.rel_path,
|
|
536
|
+
"line": node.lineno,
|
|
537
|
+
"col": node.col_offset,
|
|
538
|
+
"evidence": self._get_snippet(node.lineno),
|
|
539
|
+
"remediation": "从安全环境变量或凭据保险箱动态获取,切勿写入代码",
|
|
540
|
+
})
|
|
541
|
+
self.generic_visit(node)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def scan_source_ast(
|
|
545
|
+
root: Path, max_files: int = 1000, stats: dict[str, int] | None = None,
|
|
546
|
+
) -> list[dict[str, Any]]:
|
|
547
|
+
"""扫描 Python 源码(BuiltinAstScanner,保持向前兼容)。
|
|
548
|
+
|
|
549
|
+
``stats`` 若给出,会填入 ``files``(成功解析的文件数)。报告层需要这个
|
|
550
|
+
数字才能说清覆盖范围:没有它,调用方只能拿「命中数」冒充「暴露面总量」。
|
|
551
|
+
"""
|
|
552
|
+
findings: list[dict[str, Any]] = []
|
|
553
|
+
scanned = 0
|
|
554
|
+
for path in sorted(root.rglob("*.py")):
|
|
555
|
+
if scanned >= max_files:
|
|
556
|
+
break
|
|
557
|
+
if path.is_symlink() or not path.is_file():
|
|
558
|
+
continue
|
|
559
|
+
try:
|
|
560
|
+
rel = path.relative_to(root).as_posix()
|
|
561
|
+
except ValueError:
|
|
562
|
+
rel = str(path)
|
|
563
|
+
if _skipped(Path(rel)):
|
|
564
|
+
continue
|
|
565
|
+
try:
|
|
566
|
+
content = path.read_text(encoding="utf-8", errors="replace")
|
|
567
|
+
source_lines = content.splitlines()
|
|
568
|
+
tree = ast.parse(content, filename=str(path))
|
|
569
|
+
scanner = BuiltinAstScanner(path, rel, source_lines)
|
|
570
|
+
scanner.visit(tree)
|
|
571
|
+
findings.extend(scanner.findings)
|
|
572
|
+
scanned += 1
|
|
573
|
+
except (SyntaxError, OSError):
|
|
574
|
+
continue
|
|
575
|
+
if stats is not None:
|
|
576
|
+
stats["files"] = stats.get("files", 0) + scanned
|
|
577
|
+
return findings
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def scan_multilang_sources(
|
|
581
|
+
root: Path, max_files: int = 2000, stats: dict[str, int] | None = None,
|
|
582
|
+
) -> list[dict[str, Any]]:
|
|
583
|
+
"""使用 UniversalCodeMatcher 与 SASTRuleMatcher 对非 Python 及多语言源码执行扫描。"""
|
|
584
|
+
matcher = SASTRuleMatcher(BUILTIN_RULES)
|
|
585
|
+
findings: list[dict[str, Any]] = []
|
|
586
|
+
scanned = 0
|
|
587
|
+
|
|
588
|
+
# 重点扫描非 Python 多语言文件(Python 已由 BuiltinAstScanner 深度处理,亦可补充)
|
|
589
|
+
for ext, lang in EXT_TO_LANG.items():
|
|
590
|
+
if ext == ".py":
|
|
591
|
+
continue
|
|
592
|
+
for path in root.rglob(f"*{ext}"):
|
|
593
|
+
if scanned >= max_files:
|
|
594
|
+
break
|
|
595
|
+
if path.is_symlink() or not path.is_file():
|
|
596
|
+
continue
|
|
597
|
+
try:
|
|
598
|
+
rel = path.relative_to(root).as_posix()
|
|
599
|
+
except ValueError:
|
|
600
|
+
rel = str(path)
|
|
601
|
+
if _skipped(Path(rel)):
|
|
602
|
+
continue
|
|
603
|
+
|
|
604
|
+
try:
|
|
605
|
+
content = path.read_text(encoding="utf-8", errors="replace")
|
|
606
|
+
parsed = UniversalCodeMatcher.parse_file(path, rel_path=rel, content=content)
|
|
607
|
+
file_findings = matcher.match_file(parsed)
|
|
608
|
+
findings.extend(file_findings)
|
|
609
|
+
scanned += 1
|
|
610
|
+
except Exception:
|
|
611
|
+
continue
|
|
612
|
+
|
|
613
|
+
if stats is not None:
|
|
614
|
+
stats["files"] = stats.get("files", 0) + scanned
|
|
615
|
+
return findings
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def scan_external_bandit(root: Path, timeout: float = 60.0) -> list[dict[str, Any]]:
|
|
619
|
+
"""调用外部 Native Bandit 对 Python 源码进行深度安全扫描。
|
|
620
|
+
|
|
621
|
+
``timeout`` 由调用方按**剩余总预算**下发(``run_scan(deadline_seconds=...)``),
|
|
622
|
+
使外部工具无法把整轮扫描拖过调用方的墙钟上限。
|
|
623
|
+
"""
|
|
624
|
+
environment = _probe_environment()
|
|
625
|
+
exe = shutil.which("bandit", path=environment.get("PATH"))
|
|
626
|
+
if not exe:
|
|
627
|
+
return []
|
|
628
|
+
try:
|
|
629
|
+
cmd = [exe, "-r", str(root), "-f", "json", "-q", "-x", ",".join(SKIP_DIRS)]
|
|
630
|
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
|
|
631
|
+
check=False, env=environment)
|
|
632
|
+
if res.returncode not in (0, 1):
|
|
633
|
+
return []
|
|
634
|
+
if not res.stdout.strip():
|
|
635
|
+
return []
|
|
636
|
+
try:
|
|
637
|
+
data = json.loads(res.stdout)
|
|
638
|
+
except json.JSONDecodeError:
|
|
639
|
+
return []
|
|
640
|
+
results = []
|
|
641
|
+
for item in data.get("results", []):
|
|
642
|
+
path_str = item.get("filename", "")
|
|
643
|
+
try:
|
|
644
|
+
rel = Path(path_str).relative_to(root).as_posix()
|
|
645
|
+
except Exception:
|
|
646
|
+
rel = path_str
|
|
647
|
+
cwe_id = "CWE-General"
|
|
648
|
+
issue_cwe = item.get("issue_cwe")
|
|
649
|
+
if isinstance(issue_cwe, dict) and issue_cwe.get("id"):
|
|
650
|
+
cwe_id = f"CWE-{issue_cwe.get('id')}"
|
|
651
|
+
results.append({
|
|
652
|
+
"rule_id": item.get("test_id", "bandit-rule"),
|
|
653
|
+
"name": item.get("test_name", "Bandit Finding"),
|
|
654
|
+
"category": "sast-bandit",
|
|
655
|
+
"severity": str(item.get("issue_severity", "medium")).lower(),
|
|
656
|
+
"confidence": str(item.get("issue_confidence", "medium")).lower(),
|
|
657
|
+
"cwe": cwe_id,
|
|
658
|
+
"message": item.get("issue_text", "Bandit 安全规则触发"),
|
|
659
|
+
"file": rel,
|
|
660
|
+
"line": item.get("line_number", 1),
|
|
661
|
+
"col": item.get("col_offset", 1),
|
|
662
|
+
"evidence": str(item.get("code", "")).strip(),
|
|
663
|
+
"remediation": f"参考 Bandit 规则文档修复: {item.get('more_info', '')}",
|
|
664
|
+
})
|
|
665
|
+
return results
|
|
666
|
+
except Exception:
|
|
667
|
+
return []
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def scan_external_semgrep(root: Path, timeout: float = 60.0) -> list[dict[str, Any]]:
|
|
671
|
+
"""调用外部 Semgrep 做深度规则扫描;``timeout`` 由调用方的剩余预算下发。"""
|
|
672
|
+
environment = _probe_environment()
|
|
673
|
+
exe = shutil.which("semgrep", path=environment.get("PATH"))
|
|
674
|
+
if not exe:
|
|
675
|
+
return []
|
|
676
|
+
try:
|
|
677
|
+
cmd = [exe, "scan", "--json", "--quiet", "--config", "p/security-audit", str(root)]
|
|
678
|
+
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
|
|
679
|
+
check=False, env=environment)
|
|
680
|
+
if res.returncode not in (0, 1):
|
|
681
|
+
return []
|
|
682
|
+
data = json.loads(res.stdout)
|
|
683
|
+
results = []
|
|
684
|
+
for item in data.get("results", []):
|
|
685
|
+
path_str = item.get("path", "")
|
|
686
|
+
try:
|
|
687
|
+
rel = Path(path_str).relative_to(root).as_posix()
|
|
688
|
+
except Exception:
|
|
689
|
+
rel = path_str
|
|
690
|
+
start = item.get("start", {})
|
|
691
|
+
extra = item.get("extra", {})
|
|
692
|
+
results.append({
|
|
693
|
+
"rule_id": item.get("check_id", "semgrep-rule"),
|
|
694
|
+
"name": item.get("check_id", "Semgrep Finding"),
|
|
695
|
+
"category": "sast-semgrep",
|
|
696
|
+
"severity": extra.get("severity", "medium").lower(),
|
|
697
|
+
"confidence": "high",
|
|
698
|
+
"cwe": (extra.get("metadata", {}).get("cwe") or ["CWE-General"])[0],
|
|
699
|
+
"message": extra.get("message", "Semgrep 规则触发"),
|
|
700
|
+
"file": rel,
|
|
701
|
+
"line": start.get("line", 1),
|
|
702
|
+
"col": start.get("col", 1),
|
|
703
|
+
"evidence": extra.get("lines", "").strip(),
|
|
704
|
+
"remediation": "根据 Semgrep 安全最佳实践修复代码逻辑",
|
|
705
|
+
})
|
|
706
|
+
return results
|
|
707
|
+
except Exception:
|
|
708
|
+
return []
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def compute_finding_fingerprint(finding: dict[str, Any]) -> str:
|
|
712
|
+
"""计算用于基线快照匹配的确定性指纹"""
|
|
713
|
+
raw = f"{finding.get('rule_id')}:{finding.get('file')}:{finding.get('evidence', '').strip()}"
|
|
714
|
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def apply_baseline_filter(findings: list[dict[str, Any]], baseline_path: Path) -> tuple[list[dict[str, Any]], int]:
|
|
718
|
+
"""过滤掉已存在于基线快照中的历史 Finding"""
|
|
719
|
+
if not baseline_path.exists():
|
|
720
|
+
return findings, 0
|
|
721
|
+
try:
|
|
722
|
+
data = json.loads(baseline_path.read_text(encoding="utf-8"))
|
|
723
|
+
baseline_hashes = set(data.get("fingerprints", []))
|
|
724
|
+
except Exception:
|
|
725
|
+
return findings, 0
|
|
726
|
+
|
|
727
|
+
filtered = []
|
|
728
|
+
suppressed_count = 0
|
|
729
|
+
for item in findings:
|
|
730
|
+
fp = compute_finding_fingerprint(item)
|
|
731
|
+
if fp in baseline_hashes:
|
|
732
|
+
suppressed_count += 1
|
|
733
|
+
else:
|
|
734
|
+
filtered.append(item)
|
|
735
|
+
return filtered, suppressed_count
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def save_baseline(findings: list[dict[str, Any]], baseline_path: Path) -> None:
|
|
739
|
+
fingerprints = sorted(list({compute_finding_fingerprint(f) for f in findings}))
|
|
740
|
+
payload = {
|
|
741
|
+
"version": 1,
|
|
742
|
+
"total": len(fingerprints),
|
|
743
|
+
"fingerprints": fingerprints,
|
|
744
|
+
}
|
|
745
|
+
baseline_path.parent.mkdir(parents=True, exist_ok=True)
|
|
746
|
+
baseline_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def export_to_sarif(scan_res: dict[str, Any]) -> dict[str, Any]:
|
|
750
|
+
"""将扫描结果导出为标准 OASIS SARIF v2.1.0 格式"""
|
|
751
|
+
results = []
|
|
752
|
+
rules_map: dict[str, dict[str, Any]] = {}
|
|
753
|
+
|
|
754
|
+
for f in scan_res.get("findings", []):
|
|
755
|
+
rule_id = f.get("rule_id", "BUGX-RULE")
|
|
756
|
+
if rule_id not in rules_map:
|
|
757
|
+
rules_map[rule_id] = {
|
|
758
|
+
"id": rule_id,
|
|
759
|
+
"name": f.get("name", rule_id),
|
|
760
|
+
"shortDescription": {"text": f.get("name", rule_id)},
|
|
761
|
+
"fullDescription": {"text": f.get("message", "")},
|
|
762
|
+
"help": {"text": f.get("remediation", f.get("recommendation", ""))},
|
|
763
|
+
"properties": {
|
|
764
|
+
"cwe": f.get("cwe", "CWE-Unknown"),
|
|
765
|
+
"category": f.get("category", "security"),
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
level = "warning"
|
|
770
|
+
sev = f.get("severity", "medium").lower()
|
|
771
|
+
if sev in {"critical", "high"}:
|
|
772
|
+
level = "error"
|
|
773
|
+
elif sev == "low":
|
|
774
|
+
level = "note"
|
|
775
|
+
|
|
776
|
+
results.append({
|
|
777
|
+
"ruleId": rule_id,
|
|
778
|
+
"level": level,
|
|
779
|
+
"message": {"text": f.get("message", "")},
|
|
780
|
+
"locations": [{
|
|
781
|
+
"physicalLocation": {
|
|
782
|
+
"artifactLocation": {"uri": f.get("file", "")},
|
|
783
|
+
"region": {
|
|
784
|
+
"startLine": f.get("line", 1),
|
|
785
|
+
"startColumn": f.get("col", 1) + 1,
|
|
786
|
+
"snippet": {"text": f.get("evidence", "")}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}]
|
|
790
|
+
})
|
|
791
|
+
|
|
792
|
+
return {
|
|
793
|
+
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
|
794
|
+
"version": "2.1.0",
|
|
795
|
+
"runs": [{
|
|
796
|
+
"tool": {
|
|
797
|
+
"driver": {
|
|
798
|
+
"name": "BugX-SAST",
|
|
799
|
+
"informationUri": "https://bugx.dev",
|
|
800
|
+
"rules": list(rules_map.values()),
|
|
801
|
+
}
|
|
802
|
+
},
|
|
803
|
+
"results": results,
|
|
804
|
+
}]
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def _cwe_head(value: Any) -> str:
|
|
809
|
+
"""取 CWE 编号本体:semgrep 会给出 ``CWE-78: Improper Neutralization...``。"""
|
|
810
|
+
return str(value or "").strip().upper().split(":", 1)[0].strip()
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def _dedupe_cross_tool(findings: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
814
|
+
"""合并不同扫描器对同一处缺陷的重复命中(同文件 + 同 CWE + 行号相近)。"""
|
|
815
|
+
kept: list[dict[str, Any]] = []
|
|
816
|
+
seen: list[tuple[str, str, str, int]] = []
|
|
817
|
+
for item in findings:
|
|
818
|
+
path = str(item.get("file") or "")
|
|
819
|
+
cwe = _cwe_head(item.get("cwe"))
|
|
820
|
+
rule = str(item.get("rule_id") or "")
|
|
821
|
+
try:
|
|
822
|
+
line = int(item.get("line") or 0)
|
|
823
|
+
except (TypeError, ValueError):
|
|
824
|
+
line = 0
|
|
825
|
+
duplicate = False
|
|
826
|
+
if path and cwe:
|
|
827
|
+
for seen_path, seen_cwe, seen_rule, seen_line in seen:
|
|
828
|
+
# 只有**不同规则**命中同一处才算跨工具重复:同一条规则在相邻
|
|
829
|
+
# 两行命中是两处真实缺陷(实测 src/config.py:5 与 :6 是两个
|
|
830
|
+
# 独立的硬编码凭据),不能被合并掉。
|
|
831
|
+
if (seen_path == path and seen_cwe == cwe
|
|
832
|
+
and seen_rule != rule and abs(seen_line - line) <= 3):
|
|
833
|
+
duplicate = True
|
|
834
|
+
break
|
|
835
|
+
if duplicate:
|
|
836
|
+
continue
|
|
837
|
+
seen.append((path, cwe, rule, line))
|
|
838
|
+
kept.append(item)
|
|
839
|
+
return kept
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def run_scan(
|
|
843
|
+
root: Path,
|
|
844
|
+
tools: str = "auto",
|
|
845
|
+
baseline: Path | None = None,
|
|
846
|
+
write_baseline: Path | None = None,
|
|
847
|
+
include_sca: bool = True,
|
|
848
|
+
deadline_seconds: float | None = None,
|
|
849
|
+
) -> dict[str, Any]:
|
|
850
|
+
"""执行一次 SAST 扫描。
|
|
851
|
+
|
|
852
|
+
``deadline_seconds`` 给出**整轮扫描的总墙钟预算**(None = 不限)。预算只约束
|
|
853
|
+
「是否还允许启动下一个外部工具」以及每个外部子进程的 ``timeout``:内建
|
|
854
|
+
AST/multilang/SCA 阶段是纯进程内计算,不设预算;外部 semgrep/bandit 一旦
|
|
855
|
+
剩余预算不足(<=0.5s)就跳过并标记 ``status=DEGRADED`` +
|
|
856
|
+
``budget_exhausted=True``,绝不静默返回 ``COMPLETED`` 冒充完整扫描。
|
|
857
|
+
"""
|
|
858
|
+
root = root.resolve()
|
|
859
|
+
findings: list[dict[str, Any]] = []
|
|
860
|
+
file_stats: dict[str, int] = {}
|
|
861
|
+
used_tools: list[str] = []
|
|
862
|
+
started_at = time.monotonic()
|
|
863
|
+
deadline = (
|
|
864
|
+
None if deadline_seconds is None else started_at + max(0.0, float(deadline_seconds))
|
|
865
|
+
)
|
|
866
|
+
budget_exhausted = False
|
|
867
|
+
|
|
868
|
+
def _remaining() -> float | None:
|
|
869
|
+
if deadline is None:
|
|
870
|
+
return None
|
|
871
|
+
return deadline - time.monotonic()
|
|
872
|
+
|
|
873
|
+
# 1. 执行 Python 原生 AST 扫描 (保持向前兼容)
|
|
874
|
+
builtin_py_results = scan_source_ast(root, stats=file_stats)
|
|
875
|
+
findings.extend(builtin_py_results)
|
|
876
|
+
used_tools.append("builtin-ast")
|
|
877
|
+
|
|
878
|
+
# 2. 执行多语言通用结构化模式扫描 (Go, Java, JS/TS, Rust, C/C++, PHP 等)
|
|
879
|
+
multilang_results = scan_multilang_sources(root, stats=file_stats)
|
|
880
|
+
if multilang_results:
|
|
881
|
+
findings.extend(multilang_results)
|
|
882
|
+
used_tools.append("builtin-multilang-sast")
|
|
883
|
+
|
|
884
|
+
# 3. 执行多语言依赖供应链分析 (SCA)
|
|
885
|
+
if include_sca:
|
|
886
|
+
sca = SCAScanner()
|
|
887
|
+
sca_results = sca.scan_project(root)
|
|
888
|
+
if sca_results:
|
|
889
|
+
findings.extend(sca_results)
|
|
890
|
+
used_tools.append("builtin-sca")
|
|
891
|
+
|
|
892
|
+
# 4. 外部 Native 工具加速通道(若存在且被允许)
|
|
893
|
+
allow_external = os.environ.get("BUGX_DISABLE_EXTERNAL_SAST") != "1"
|
|
894
|
+
if allow_external and tools in {"auto", "semgrep"} and shutil.which(
|
|
895
|
+
"semgrep", path=_probe_environment().get("PATH")
|
|
896
|
+
):
|
|
897
|
+
remaining = _remaining()
|
|
898
|
+
if remaining is not None and remaining <= 0.5:
|
|
899
|
+
budget_exhausted = True
|
|
900
|
+
else:
|
|
901
|
+
semgrep_results = scan_external_semgrep(
|
|
902
|
+
root, timeout=60.0 if remaining is None else min(60.0, remaining),
|
|
903
|
+
)
|
|
904
|
+
if semgrep_results:
|
|
905
|
+
findings.extend(semgrep_results)
|
|
906
|
+
used_tools.append("semgrep")
|
|
907
|
+
|
|
908
|
+
if allow_external and tools in {"auto", "bandit"} and shutil.which(
|
|
909
|
+
"bandit", path=_probe_environment().get("PATH")
|
|
910
|
+
):
|
|
911
|
+
remaining = _remaining()
|
|
912
|
+
if remaining is not None and remaining <= 0.5:
|
|
913
|
+
budget_exhausted = True
|
|
914
|
+
else:
|
|
915
|
+
bandit_results = scan_external_bandit(
|
|
916
|
+
root, timeout=60.0 if remaining is None else min(60.0, remaining),
|
|
917
|
+
)
|
|
918
|
+
if bandit_results:
|
|
919
|
+
findings.extend(bandit_results)
|
|
920
|
+
used_tools.append("bandit")
|
|
921
|
+
|
|
922
|
+
# 跨工具去重:内建 AST 与 semgrep/bandit 会独立命中同一处缺陷(实测
|
|
923
|
+
# ``eval`` 在 src/evals.py:11 被内建与 semgrep 各报一次,``shell=True``
|
|
924
|
+
# 被内建报在 11 行、semgrep 报在 12 行)。不去重时报告会把一个漏洞
|
|
925
|
+
# 计入两条发现、双倍抬升严重度计数。判据是「同一文件 + 同一 CWE +
|
|
926
|
+
# 行号相近(<=3 行)」,保留首个(内建优先,字段最全)。
|
|
927
|
+
findings = _dedupe_cross_tool(findings)
|
|
928
|
+
|
|
929
|
+
# 排序:按严重度及路径排序
|
|
930
|
+
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
931
|
+
findings.sort(key=lambda x: (severity_order.get(x.get("severity", "medium"), 2), x.get("file", ""), x.get("line", 0)))
|
|
932
|
+
|
|
933
|
+
# 保存基线
|
|
934
|
+
if write_baseline:
|
|
935
|
+
save_baseline(findings, write_baseline)
|
|
936
|
+
|
|
937
|
+
# 过滤基线
|
|
938
|
+
suppressed_baseline = 0
|
|
939
|
+
if baseline:
|
|
940
|
+
findings, suppressed_baseline = apply_baseline_filter(findings, baseline)
|
|
941
|
+
|
|
942
|
+
return {
|
|
943
|
+
"schema_version": 2,
|
|
944
|
+
"status": "DEGRADED" if budget_exhausted else "COMPLETED",
|
|
945
|
+
"root": str(root),
|
|
946
|
+
# 报告层需要「扫了多少文件」才能说清楚覆盖范围。此前收据不报这个数,
|
|
947
|
+
# 调用方只能用命中数顶替,把「命中数」当成「暴露面总量」呈现。
|
|
948
|
+
"scanned_files": int(file_stats.get("files", 0)),
|
|
949
|
+
"tools_executed": used_tools,
|
|
950
|
+
"total_findings": len(findings),
|
|
951
|
+
"suppressed_by_baseline": suppressed_baseline,
|
|
952
|
+
"budget_exhausted": budget_exhausted,
|
|
953
|
+
"elapsed_seconds": round(time.monotonic() - started_at, 3),
|
|
954
|
+
"findings": findings,
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def main(argv: list[str] | None = None) -> int:
|
|
959
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
960
|
+
parser.add_argument("command", choices=("check", "status", "scan"), nargs="?", default="check")
|
|
961
|
+
parser.add_argument("--root", type=Path, default=Path.cwd())
|
|
962
|
+
parser.add_argument("--json", action="store_true")
|
|
963
|
+
parser.add_argument("--sarif", action="store_true", help="输出 OASIS SARIF v2.1.0 格式")
|
|
964
|
+
parser.add_argument("--strict", action="store_true")
|
|
965
|
+
parser.add_argument(
|
|
966
|
+
"--allow-degraded", action="store_true",
|
|
967
|
+
help="明确允许使用回退方案;否则 DEGRADED 返回 2,要求调用方先取得用户决策",
|
|
968
|
+
)
|
|
969
|
+
parser.add_argument("--tools", choices=("auto", "builtin", "semgrep"), default="auto", help="指定扫描使用的工具")
|
|
970
|
+
parser.add_argument("--baseline", type=Path, default=None, help="从已有基线快照过滤已知历史问题")
|
|
971
|
+
parser.add_argument("--write-baseline", type=Path, default=None, help="将当前扫描结果持久化为基线快照")
|
|
972
|
+
args = parser.parse_args(argv)
|
|
973
|
+
|
|
974
|
+
if args.command == "scan":
|
|
975
|
+
scan_res = run_scan(
|
|
976
|
+
args.root,
|
|
977
|
+
tools=args.tools,
|
|
978
|
+
baseline=args.baseline,
|
|
979
|
+
write_baseline=args.write_baseline,
|
|
980
|
+
)
|
|
981
|
+
if args.sarif:
|
|
982
|
+
sarif_doc = export_to_sarif(scan_res)
|
|
983
|
+
print(json.dumps(sarif_doc, ensure_ascii=False, indent=2))
|
|
984
|
+
elif args.json:
|
|
985
|
+
print(json.dumps(scan_res, ensure_ascii=False, indent=2))
|
|
986
|
+
else:
|
|
987
|
+
print(f"[SAST Scan] 执行完成(工具链: {', '.join(scan_res['tools_executed'])}),发现 {scan_res['total_findings']} 个候选漏洞:")
|
|
988
|
+
if scan_res.get("suppressed_by_baseline", 0) > 0:
|
|
989
|
+
print(f" ℹ️ 已基于 Baseline 过滤 {scan_res['suppressed_by_baseline']} 个已知历史问题")
|
|
990
|
+
for idx, item in enumerate(scan_res["findings"][:25], 1):
|
|
991
|
+
cwe_tag = f"[{item.get('cwe', '')}] " if item.get('cwe') else ""
|
|
992
|
+
print(f" #{idx} [{item['severity'].upper()}] {item['file']}:{item['line']} - {cwe_tag}{item['rule_id']}: {item['message']}")
|
|
993
|
+
if scan_res['total_findings'] > 25:
|
|
994
|
+
print(f" ... 以及另外 {scan_res['total_findings'] - 25} 项(使用 --json 或 --sarif 查看全量)")
|
|
995
|
+
return 0
|
|
996
|
+
|
|
997
|
+
report = inspect(args.root)
|
|
998
|
+
print_report(report, args.json)
|
|
999
|
+
if report["status"] == "READY":
|
|
1000
|
+
return 0
|
|
1001
|
+
if not args.json and not args.allow_degraded and not args.strict:
|
|
1002
|
+
print(" ⏸ 当前仅完成探测,等待用户明确允许回退或配置工具;不会自动进入下一步。")
|
|
1003
|
+
if args.strict:
|
|
1004
|
+
return 1
|
|
1005
|
+
return 0 if args.allow_degraded else 2
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
if __name__ == "__main__":
|
|
1009
|
+
raise SystemExit(main())
|