ai-agent-security 0.22.2__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.
Files changed (618) hide show
  1. agentsec/__init__.py +44 -0
  2. agentsec/__main__.py +13 -0
  3. agentsec/advisor.py +334 -0
  4. agentsec/ai/__init__.py +13 -0
  5. agentsec/ai/lethal_trifecta.py +302 -0
  6. agentsec/ai/semgrep-rules/python-llm.yaml +96 -0
  7. agentsec/ai_bom.py +440 -0
  8. agentsec/arm.py +126 -0
  9. agentsec/astutil.py +290 -0
  10. agentsec/audit.py +643 -0
  11. agentsec/bicep.py +323 -0
  12. agentsec/canary.py +1244 -0
  13. agentsec/cfn.py +357 -0
  14. agentsec/checklist/__init__.py +203 -0
  15. agentsec/checklist/checklist.json +11124 -0
  16. agentsec/checkmeta.py +84 -0
  17. agentsec/ci/__init__.py +9 -0
  18. agentsec/ci/components/container-cve/component.json +14 -0
  19. agentsec/ci/components/container-cve/files/.github/workflows/container-cve.yml.tmpl +83 -0
  20. agentsec/ci/components/container-cve/files/.trivy-images.txt +9 -0
  21. agentsec/ci/components/dast/component.json +14 -0
  22. agentsec/ci/components/dast/files/.github/workflows/dast.yml.tmpl +90 -0
  23. agentsec/ci/components/db-lint/component.json +14 -0
  24. agentsec/ci/components/db-lint/files/.github/workflows/db-lint.yml.tmpl +65 -0
  25. agentsec/ci/components/dockerfile-lint/component.json +11 -0
  26. agentsec/ci/components/dockerfile-lint/files/.github/workflows/dockerfile-lint.yml.tmpl +34 -0
  27. agentsec/ci/components/dockerfile-lint/files/.hadolint.yaml +28 -0
  28. agentsec/ci/components/frontend-sec/component.json +14 -0
  29. agentsec/ci/components/frontend-sec/files/.github/workflows/frontend-security.yml.tmpl +40 -0
  30. agentsec/ci/components/garak/component.json +14 -0
  31. agentsec/ci/components/garak/files/.github/workflows/llm-redteam-garak.yml.tmpl +79 -0
  32. agentsec/ci/components/garak/files/scripts/redteam-shim.py +221 -0
  33. agentsec/ci/components/promptfoo/component.json +15 -0
  34. agentsec/ci/components/promptfoo/files/.github/workflows/llm-redteam-promptfoo.yml.tmpl +64 -0
  35. agentsec/ci/components/promptfoo/files/promptfooconfig.yaml +205 -0
  36. agentsec/ci/components/promptfoo/files/scripts/redteam-shim.py +221 -0
  37. agentsec/ci/components/python-sec/component.json +14 -0
  38. agentsec/ci/components/python-sec/files/.github/workflows/python-security.yml.tmpl +45 -0
  39. agentsec/ci/components/react-doctor/component.json +16 -0
  40. agentsec/ci/components/react-doctor/files/.github/workflows/frontend-health.yml.tmpl +84 -0
  41. agentsec/ci/components/react-doctor/files/@@FRONTEND_DIR@@/react-doctor.config.json +13 -0
  42. agentsec/ci/components/scorecard/component.json +13 -0
  43. agentsec/ci/components/scorecard/files/.github/workflows/scorecard.yml.tmpl +78 -0
  44. agentsec/ci/components/secret-scan/component.json +14 -0
  45. agentsec/ci/components/secret-scan/files/.github/workflows/secret-scan.yml.tmpl +70 -0
  46. agentsec/ci/components/secret-scan/files/.gitleaks.toml +34 -0
  47. agentsec/ci/components/secret-scan/files/.gitleaksignore +6 -0
  48. agentsec/ci/components/self-audit/component.json +16 -0
  49. agentsec/ci/components/self-audit/files/.github/workflows/agentsec-audit.yml.tmpl +44 -0
  50. agentsec/ci/components/type-check/component.json +14 -0
  51. agentsec/ci/components/type-check/files/.github/workflows/type-check.yml.tmpl +44 -0
  52. agentsec/ci/doctor.py +479 -0
  53. agentsec/ci/library.py +548 -0
  54. agentsec/ci/render.py +31 -0
  55. agentsec/clean_canary.py +171 -0
  56. agentsec/clean_canary_fixtures.py +533 -0
  57. agentsec/cli.py +3140 -0
  58. agentsec/compounding_risk.py +246 -0
  59. agentsec/config.py +186 -0
  60. agentsec/console.py +32 -0
  61. agentsec/corpus.py +1437 -0
  62. agentsec/coverage.py +365 -0
  63. agentsec/crosscheck.py +152 -0
  64. agentsec/deps_apply.py +962 -0
  65. agentsec/deps_monitor.py +912 -0
  66. agentsec/detect.py +1221 -0
  67. agentsec/drift.py +309 -0
  68. agentsec/epss.py +148 -0
  69. agentsec/exceptions.py +539 -0
  70. agentsec/findings.py +945 -0
  71. agentsec/fix.py +293 -0
  72. agentsec/gap_report.py +101 -0
  73. agentsec/guard_sandbox.py +248 -0
  74. agentsec/guard_worker.py +559 -0
  75. agentsec/guards/__init__.py +7 -0
  76. agentsec/guards/acp_vulnerabilities.py +385 -0
  77. agentsec/guards/actions_script_injection.py +261 -0
  78. agentsec/guards/actions_sha_pin.py +105 -0
  79. agentsec/guards/agent_headless_trust_surface.py +295 -0
  80. agentsec/guards/agent_iam_control_plane_exposure.py +213 -0
  81. agentsec/guards/agent_iam_killchain_combination.py +294 -0
  82. agentsec/guards/agent_iam_tool_resource_unscoped.py +307 -0
  83. agentsec/guards/agent_loop_circuit_breaker.py +828 -0
  84. agentsec/guards/agent_memory_retention.py +162 -0
  85. agentsec/guards/agent_memory_security.py +403 -0
  86. agentsec/guards/agent_memory_user_scope.py +328 -0
  87. agentsec/guards/agent_resume_unverified_trigger.py +279 -0
  88. agentsec/guards/agent_tool_audit_log.py +181 -0
  89. agentsec/guards/agent_tool_overpermission.py +352 -0
  90. agentsec/guards/agent_tool_url_fetch_ssrf.py +414 -0
  91. agentsec/guards/agentic_skills_ast.py +249 -0
  92. agentsec/guards/ai_docker.py +458 -0
  93. agentsec/guards/ai_instruction_poisoning.py +435 -0
  94. agentsec/guards/alb_listener_http_protocol.py +164 -0
  95. agentsec/guards/ansi_escape_llm_output.py +235 -0
  96. agentsec/guards/ansible_debug_echoes_auth_variable.py +134 -0
  97. agentsec/guards/ansible_host_key_checking_disabled.py +114 -0
  98. agentsec/guards/ansible_ignore_errors_on_security_task.py +124 -0
  99. agentsec/guards/ansible_no_log_disabled_on_secret_task.py +138 -0
  100. agentsec/guards/ansible_setuid_binary_creation.py +101 -0
  101. agentsec/guards/ansible_sudo_nopasswd.py +103 -0
  102. agentsec/guards/ansible_unsafe_lookups_enabled.py +104 -0
  103. agentsec/guards/api_docs_exposed.py +124 -0
  104. agentsec/guards/approval_parser_shell_desync.py +241 -0
  105. agentsec/guards/argv_toctou.py +270 -0
  106. agentsec/guards/arm_aks_rbac_disabled.py +133 -0
  107. agentsec/guards/arm_apim_backend_unauthenticated.py +169 -0
  108. agentsec/guards/arm_appservice_https_only_disabled.py +143 -0
  109. agentsec/guards/arm_redis_ssl_disabled.py +116 -0
  110. agentsec/guards/arm_sql_tde_disabled.py +143 -0
  111. agentsec/guards/async_blocking_io.py +196 -0
  112. agentsec/guards/auth_dependency_not_applied.py +682 -0
  113. agentsec/guards/auth_disabled_by_default.py +149 -0
  114. agentsec/guards/auth_rate_limit_absent.py +208 -0
  115. agentsec/guards/auth_users_exposed_view.py +91 -0
  116. agentsec/guards/auto_updates_absent.py +231 -0
  117. agentsec/guards/autostart_persistence_mechanism.py +155 -0
  118. agentsec/guards/aws_observability_hygiene.py +336 -0
  119. agentsec/guards/aws_weak_tls_policy.py +362 -0
  120. agentsec/guards/azure_keyvault_key_no_expiration.py +131 -0
  121. agentsec/guards/azure_keyvault_purge_protection_disabled.py +130 -0
  122. agentsec/guards/azure_mssql_publicly_accessible.py +135 -0
  123. agentsec/guards/azure_storage_account_https_only.py +137 -0
  124. agentsec/guards/azure_storage_account_public_blob_access.py +135 -0
  125. agentsec/guards/background_tasks.py +72 -0
  126. agentsec/guards/base.py +7216 -0
  127. agentsec/guards/bicep_admin_username_literal.py +103 -0
  128. agentsec/guards/bicep_commandtoexecute_plaintext_settings.py +190 -0
  129. agentsec/guards/bicep_output_secret_not_secure.py +115 -0
  130. agentsec/guards/bicep_param_file_insecure_secret_value.py +112 -0
  131. agentsec/guards/bicep_secret_param_not_secure.py +106 -0
  132. agentsec/guards/bicep_secure_param_in_nested_deployment.py +229 -0
  133. agentsec/guards/bicep_secure_parameter_default.py +151 -0
  134. agentsec/guards/bola.py +156 -0
  135. agentsec/guards/browser_credential_store_access.py +217 -0
  136. agentsec/guards/build_secret.py +518 -0
  137. agentsec/guards/bulk_env_var_harvesting.py +162 -0
  138. agentsec/guards/cfn_authentication_password.py +181 -0
  139. agentsec/guards/cfn_batch_privileged_container.py +117 -0
  140. agentsec/guards/cfn_cognito_mfa_off.py +114 -0
  141. agentsec/guards/cfn_cognito_unauth_identities.py +117 -0
  142. agentsec/guards/cfn_ec2_subnet_public_ip.py +114 -0
  143. agentsec/guards/cfn_ecr_scan_on_push.py +108 -0
  144. agentsec/guards/cfn_iam_escalation_action_no_condition.py +218 -0
  145. agentsec/guards/cfn_iam_notaction_with_allow.py +156 -0
  146. agentsec/guards/cfn_iam_user_direct_policy.py +146 -0
  147. agentsec/guards/cfn_kms_key_rotation_not_enabled.py +118 -0
  148. agentsec/guards/cfn_nacl_ineffective_deny.py +145 -0
  149. agentsec/guards/cfn_rds_hardcoded_password_no_echo.py +277 -0
  150. agentsec/guards/cfn_rds_publicly_accessible.py +116 -0
  151. agentsec/guards/cfn_s3_public_access_canned_acl.py +125 -0
  152. agentsec/guards/cfn_s3_versioning_missing.py +134 -0
  153. agentsec/guards/cfn_vpc_flow_log_missing.py +123 -0
  154. agentsec/guards/cfn_waf_default_allow.py +131 -0
  155. agentsec/guards/cfn_wildcard_principal.py +148 -0
  156. agentsec/guards/checkout_price_from_server.py +91 -0
  157. agentsec/guards/ci_image_build_no_sbom_provenance.py +170 -0
  158. agentsec/guards/ci_secret_env_unscoped.py +378 -0
  159. agentsec/guards/claude_code_compromise.py +567 -0
  160. agentsec/guards/claude_hook_rce.py +210 -0
  161. agentsec/guards/claude_routines_security.py +167 -0
  162. agentsec/guards/cleartext_secret_storage.py +200 -0
  163. agentsec/guards/client_side_auth_decision.py +370 -0
  164. agentsec/guards/client_side_secret_literal.py +659 -0
  165. agentsec/guards/cloud_metadata_endpoint_literal.py +138 -0
  166. agentsec/guards/cloudtrail_logging_disabled.py +193 -0
  167. agentsec/guards/cloudwatch_log_group_not_kms_encrypted.py +112 -0
  168. agentsec/guards/code_injection_eval_exec.py +271 -0
  169. agentsec/guards/command_injection.py +321 -0
  170. agentsec/guards/compose_connection_string_credential.py +182 -0
  171. agentsec/guards/compose_credential_env_literal.py +231 -0
  172. agentsec/guards/compose_db_port_exposed.py +289 -0
  173. agentsec/guards/compose_dns_bypass.py +277 -0
  174. agentsec/guards/compose_image_digest_missing.py +132 -0
  175. agentsec/guards/compose_logging_disabled.py +120 -0
  176. agentsec/guards/compose_no_network_segmentation.py +173 -0
  177. agentsec/guards/compose_no_new_privileges.py +158 -0
  178. agentsec/guards/compose_resource_limits_absent.py +135 -0
  179. agentsec/guards/compose_sensitive_host_mount.py +188 -0
  180. agentsec/guards/compose_shared_mount_propagation.py +144 -0
  181. agentsec/guards/compose_tmpfs_insecure_options.py +150 -0
  182. agentsec/guards/compose_user_directive_missing.py +251 -0
  183. agentsec/guards/compose_writable_host_root_mount.py +203 -0
  184. agentsec/guards/compose_writable_root_filesystem.py +138 -0
  185. agentsec/guards/content_type_magic_bytes.py +119 -0
  186. agentsec/guards/cors_wildcard.py +166 -0
  187. agentsec/guards/credential_file_path_reference.py +217 -0
  188. agentsec/guards/crewai_rce_chain.py +290 -0
  189. agentsec/guards/cron_systemd_persistence_write.py +248 -0
  190. agentsec/guards/csv_injection.py +212 -0
  191. agentsec/guards/ctypes_load_downloaded_library.py +263 -0
  192. agentsec/guards/curl_pipe_to_shell.py +250 -0
  193. agentsec/guards/dataset_injection.py +374 -0
  194. agentsec/guards/datastore_auth_absent.py +308 -0
  195. agentsec/guards/db_role_privilege_excessive.py +363 -0
  196. agentsec/guards/debug_default_off.py +98 -0
  197. agentsec/guards/debug_route_exposed.py +232 -0
  198. agentsec/guards/default_service_credential.py +484 -0
  199. agentsec/guards/definer_dynamic_sql.py +246 -0
  200. agentsec/guards/definer_function_grants.py +381 -0
  201. agentsec/guards/dependency_version_floor.py +889 -0
  202. agentsec/guards/destructive_filesystem_command.py +145 -0
  203. agentsec/guards/dns_egress_allowlist.py +115 -0
  204. agentsec/guards/dns_exfiltration_pattern.py +184 -0
  205. agentsec/guards/docker_add_misuse.py +149 -0
  206. agentsec/guards/docker_apt_update_not_alone.py +140 -0
  207. agentsec/guards/docker_expose_ssh.py +123 -0
  208. agentsec/guards/docker_latest_base_tag.py +180 -0
  209. agentsec/guards/docker_nonroot_user.py +150 -0
  210. agentsec/guards/docker_privileged_flags.py +318 -0
  211. agentsec/guards/docker_run_sudo.py +127 -0
  212. agentsec/guards/docker_socket_access.py +133 -0
  213. agentsec/guards/dockerfile_credential_in_instruction.py +189 -0
  214. agentsec/guards/dockerfile_run_isolation_weakening.py +196 -0
  215. agentsec/guards/dockerfile_workdir_sensitive_path.py +105 -0
  216. agentsec/guards/dom_xss_sinks.py +974 -0
  217. agentsec/guards/download_execute_chain.py +310 -0
  218. agentsec/guards/dynamic_import_non_literal.py +155 -0
  219. agentsec/guards/dynamodb_table_not_encrypted.py +134 -0
  220. agentsec/guards/ebs_volume_not_encrypted.py +115 -0
  221. agentsec/guards/ecr_repository_hygiene.py +232 -0
  222. agentsec/guards/ecr_repository_not_kms_encrypted.py +123 -0
  223. agentsec/guards/ecs_efs_volume_transit_encryption_disabled.py +164 -0
  224. agentsec/guards/efs_file_system_not_encrypted.py +118 -0
  225. agentsec/guards/elasticache_transit_encryption_disabled.py +132 -0
  226. agentsec/guards/electron_security_misconfig.py +209 -0
  227. agentsec/guards/empty_password_in_config.py +240 -0
  228. agentsec/guards/env_file_not_gitignored.py +155 -0
  229. agentsec/guards/env_secret_console_log.py +188 -0
  230. agentsec/guards/env_secret_in_prompt.py +177 -0
  231. agentsec/guards/env_secret_logged.py +234 -0
  232. agentsec/guards/environ_dump_to_network.py +437 -0
  233. agentsec/guards/error_response_info_leak.py +779 -0
  234. agentsec/guards/fail2ban_absent.py +107 -0
  235. agentsec/guards/fail_safe_exception.py +203 -0
  236. agentsec/guards/file_system_race.py +159 -0
  237. agentsec/guards/forwarded_header_blind_trust.py +484 -0
  238. agentsec/guards/frontend_xss.py +166 -0
  239. agentsec/guards/fulfill_on_completed_not_created.py +91 -0
  240. agentsec/guards/gcp_kms_key_public.py +195 -0
  241. agentsec/guards/gcp_kms_rotation_period_not_set.py +126 -0
  242. agentsec/guards/gcp_sql_publicly_accessible.py +242 -0
  243. agentsec/guards/git_in_docker.py +188 -0
  244. agentsec/guards/go_build_supply_chain_footgun.py +183 -0
  245. agentsec/guards/go_pprof_exposed.py +200 -0
  246. agentsec/guards/go_sql_injection.py +288 -0
  247. agentsec/guards/go_ssh_host_key_trust.py +146 -0
  248. agentsec/guards/go_template_html_escaping.py +346 -0
  249. agentsec/guards/go_tls_verify_disabled.py +160 -0
  250. agentsec/guards/graphql_mutation_idor.py +223 -0
  251. agentsec/guards/guardrail_architecture.py +963 -0
  252. agentsec/guards/hardcoded_llm_provider_key.py +301 -0
  253. agentsec/guards/hardcoded_password_default_arg.py +125 -0
  254. agentsec/guards/hardcoded_private_key_in_source.py +291 -0
  255. agentsec/guards/header_injection.py +153 -0
  256. agentsec/guards/hidden_executable_dotfile.py +98 -0
  257. agentsec/guards/homoglyph_source_chars.py +366 -0
  258. agentsec/guards/hostname_regex_unsafe.py +198 -0
  259. agentsec/guards/iac_open_ingress.py +111 -0
  260. agentsec/guards/iam_escalation_action_no_condition.py +285 -0
  261. agentsec/guards/iam_managed_admin_policy_attached.py +189 -0
  262. agentsec/guards/iam_notaction_with_allow.py +166 -0
  263. agentsec/guards/iam_policy_attached_to_user_directly.py +144 -0
  264. agentsec/guards/iam_resource_scopable_wildcard.py +181 -0
  265. agentsec/guards/iam_role_public_assume.py +529 -0
  266. agentsec/guards/iam_service_wildcard.py +156 -0
  267. agentsec/guards/iam_wildcard.py +241 -0
  268. agentsec/guards/incomplete_url_scheme_check.py +143 -0
  269. agentsec/guards/incomplete_url_substring_sanitization.py +189 -0
  270. agentsec/guards/incorrect_suffix_check.py +135 -0
  271. agentsec/guards/input_delimiters.py +180 -0
  272. agentsec/guards/insecure_cookies.py +309 -0
  273. agentsec/guards/insecure_file_permissions.py +151 -0
  274. agentsec/guards/insecure_tempfile_mktemp.py +99 -0
  275. agentsec/guards/invisible_unicode.py +202 -0
  276. agentsec/guards/java_command_injection.py +187 -0
  277. agentsec/guards/java_hardcoded_password_key.py +214 -0
  278. agentsec/guards/java_ldap_injection.py +157 -0
  279. agentsec/guards/java_path_traversal.py +231 -0
  280. agentsec/guards/java_sql_injection.py +249 -0
  281. agentsec/guards/java_ssrf.py +177 -0
  282. agentsec/guards/java_tls_verify_disabled.py +228 -0
  283. agentsec/guards/java_unsafe_deserialization.py +196 -0
  284. agentsec/guards/java_weak_crypto.py +169 -0
  285. agentsec/guards/java_xxe_unsafe_parsing.py +191 -0
  286. agentsec/guards/js_buffer_noassert.py +114 -0
  287. agentsec/guards/js_client_side_open_redirect.py +279 -0
  288. agentsec/guards/js_code_injection.py +346 -0
  289. agentsec/guards/js_command_injection.py +774 -0
  290. agentsec/guards/js_cors_wildcard.py +324 -0
  291. agentsec/guards/js_helmet_header_disabled.py +127 -0
  292. agentsec/guards/js_host_header_email_link.py +139 -0
  293. agentsec/guards/js_http_to_file_access.py +135 -0
  294. agentsec/guards/js_insecure_download_sensitive_file.py +110 -0
  295. agentsec/guards/js_loop_bound_injection.py +129 -0
  296. agentsec/guards/js_path_traversal.py +328 -0
  297. agentsec/guards/js_private_file_exposure.py +258 -0
  298. agentsec/guards/js_prototype_pollution.py +153 -0
  299. agentsec/guards/js_regex_injection_dos.py +137 -0
  300. agentsec/guards/js_secure_cookies.py +237 -0
  301. agentsec/guards/js_security_headers_absent.py +198 -0
  302. agentsec/guards/js_server_side_open_redirect.py +223 -0
  303. agentsec/guards/js_sql_injection.py +201 -0
  304. agentsec/guards/js_ssrf.py +149 -0
  305. agentsec/guards/js_supply_chain.py +800 -0
  306. agentsec/guards/js_system_prompt_injection.py +229 -0
  307. agentsec/guards/js_weak_crypto.py +205 -0
  308. agentsec/guards/js_xxe_unsafe_parsing.py +179 -0
  309. agentsec/guards/jsx_href_scheme.py +445 -0
  310. agentsec/guards/jwt_alg.py +239 -0
  311. agentsec/guards/jwt_claims_validated.py +163 -0
  312. agentsec/guards/jwt_exp_too_long.py +251 -0
  313. agentsec/guards/jwt_key_source_allowlist.py +262 -0
  314. agentsec/guards/k8s_allow_privilege_escalation.py +190 -0
  315. agentsec/guards/k8s_automount_serviceaccount_token.py +85 -0
  316. agentsec/guards/k8s_default_namespace.py +131 -0
  317. agentsec/guards/k8s_docker_sock_mount.py +79 -0
  318. agentsec/guards/k8s_host_namespace_sharing.py +90 -0
  319. agentsec/guards/k8s_hostpath_writable_mount.py +215 -0
  320. agentsec/guards/k8s_privileged_capabilities.py +136 -0
  321. agentsec/guards/k8s_privileged_container.py +79 -0
  322. agentsec/guards/k8s_rbac_anonymous_binding.py +106 -0
  323. agentsec/guards/k8s_rbac_cluster_admin_binding.py +145 -0
  324. agentsec/guards/k8s_rbac_dangerous_verb.py +426 -0
  325. agentsec/guards/k8s_rbac_wildcard_rule.py +151 -0
  326. agentsec/guards/k8s_readonly_root_filesystem.py +82 -0
  327. agentsec/guards/k8s_resource_limits_absent.py +128 -0
  328. agentsec/guards/k8s_run_as_non_root.py +91 -0
  329. agentsec/guards/k8s_seccomp_apparmor_unconfined.py +112 -0
  330. agentsec/guards/k8s_unmasked_proc_mount.py +96 -0
  331. agentsec/guards/k8s_unsafe_sysctl.py +159 -0
  332. agentsec/guards/keylogging_pattern.py +165 -0
  333. agentsec/guards/kinesis_stream_not_encrypted.py +129 -0
  334. agentsec/guards/kms_key_disabled.py +108 -0
  335. agentsec/guards/kms_key_rotation_not_enabled.py +145 -0
  336. agentsec/guards/langchain_load_prompt.py +187 -0
  337. agentsec/guards/langchain_prompt_template_injection.py +202 -0
  338. agentsec/guards/langchain_serialization.py +149 -0
  339. agentsec/guards/langchain_unsafe_chain.py +193 -0
  340. agentsec/guards/ldap_injection.py +142 -0
  341. agentsec/guards/lethal_trifecta_guard.py +31 -0
  342. agentsec/guards/llm_input_size_cap.py +266 -0
  343. agentsec/guards/llm_json_output_unvalidated.py +445 -0
  344. agentsec/guards/llm_output_html_sink.py +288 -0
  345. agentsec/guards/llm_output_secrets_unscanned.py +322 -0
  346. agentsec/guards/llm_output_to_sink.py +301 -0
  347. agentsec/guards/llm_query_engine_execution.py +412 -0
  348. agentsec/guards/llm_rate_limit_absent.py +277 -0
  349. agentsec/guards/llm_response_logged.py +158 -0
  350. agentsec/guards/llm_tool_dynamic_dispatch.py +300 -0
  351. agentsec/guards/llm_tool_result_leak.py +546 -0
  352. agentsec/guards/log_injection.py +347 -0
  353. agentsec/guards/markdown_render_xss.py +276 -0
  354. agentsec/guards/mass_assignment.py +207 -0
  355. agentsec/guards/matview_exposed.py +266 -0
  356. agentsec/guards/mcp_apps_ui_isolation.py +185 -0
  357. agentsec/guards/mcp_config_security.py +1578 -0
  358. agentsec/guards/mcp_env_placeholder_exfil.py +441 -0
  359. agentsec/guards/mcp_hardcoded_credential.py +314 -0
  360. agentsec/guards/mcp_marketplace_fetch_stdio_spawn.py +296 -0
  361. agentsec/guards/mcp_noauth_default.py +405 -0
  362. agentsec/guards/mcp_oauth_flow_hardening.py +799 -0
  363. agentsec/guards/mcp_oauth_scope_creep.py +197 -0
  364. agentsec/guards/mcp_overprivileged_scope.py +157 -0
  365. agentsec/guards/mcp_raw_execution_tool_name.py +201 -0
  366. agentsec/guards/mcp_routing_desync.py +288 -0
  367. agentsec/guards/mcp_sampling_no_consent.py +289 -0
  368. agentsec/guards/mcp_sandbox_self_disable.py +262 -0
  369. agentsec/guards/mcp_server_card_integrity.py +240 -0
  370. agentsec/guards/mcp_session_id_security.py +207 -0
  371. agentsec/guards/mcp_ssrf_unvalidated_destination.py +366 -0
  372. agentsec/guards/mcp_stateless_migration.py +290 -0
  373. agentsec/guards/mcp_stdio_no_sanitizer.py +326 -0
  374. agentsec/guards/mcp_tasks_lifecycle.py +278 -0
  375. agentsec/guards/mcp_tool_description_injection.py +1811 -0
  376. agentsec/guards/mcp_tool_env_inheritance.py +165 -0
  377. agentsec/guards/mcp_tool_path_traversal.py +530 -0
  378. agentsec/guards/mcp_tool_unverified.py +485 -0
  379. agentsec/guards/mcp_toolgate_asymmetry.py +398 -0
  380. agentsec/guards/mcp_tools_list_unbounded.py +376 -0
  381. agentsec/guards/mcp_transport_dns_rebinding.py +256 -0
  382. agentsec/guards/mcp_transport_flip.py +175 -0
  383. agentsec/guards/mcp_transport_no_auth.py +371 -0
  384. agentsec/guards/mcp_transport_session_unauth.py +263 -0
  385. agentsec/guards/mcp_tunnel_config_security.py +553 -0
  386. agentsec/guards/mcp_twin_route_auth_asymmetry.py +324 -0
  387. agentsec/guards/mcp_unsafe_auth_url_launch.py +248 -0
  388. agentsec/guards/ml_artifact_committed.py +104 -0
  389. agentsec/guards/ml_gguf_template_injection.py +471 -0
  390. agentsec/guards/ml_keras_lambda_rce.py +589 -0
  391. agentsec/guards/ml_model_provenance.py +305 -0
  392. agentsec/guards/ml_onnx_external_data.py +534 -0
  393. agentsec/guards/ml_pickle_dangerous_global.py +510 -0
  394. agentsec/guards/msk_cluster_transit_encryption_disabled.py +210 -0
  395. agentsec/guards/multi_agent_prompt_origin.py +405 -0
  396. agentsec/guards/next_api_route_auth_missing.py +249 -0
  397. agentsec/guards/next_public_client_secret.py +145 -0
  398. agentsec/guards/next_server_action_no_auth.py +172 -0
  399. agentsec/guards/no_cache_on_sensitive.py +765 -0
  400. agentsec/guards/no_pan_stored.py +151 -0
  401. agentsec/guards/nosql_injection_js.py +217 -0
  402. agentsec/guards/nosql_metadata_injection.py +156 -0
  403. agentsec/guards/npm_ignore_scripts.py +308 -0
  404. agentsec/guards/npm_install_script_network.py +221 -0
  405. agentsec/guards/obfuscated_payload_execution.py +413 -0
  406. agentsec/guards/open_redirect.py +512 -0
  407. agentsec/guards/opensearch_domain_encryption_disabled.py +209 -0
  408. agentsec/guards/overly_large_regex_range.py +151 -0
  409. agentsec/guards/paramiko_host_key_trust.py +121 -0
  410. agentsec/guards/path_prefix_authz_bypass.py +168 -0
  411. agentsec/guards/path_traversal.py +609 -0
  412. agentsec/guards/payments_user_scope.py +163 -0
  413. agentsec/guards/pdf_embedded_javascript.py +163 -0
  414. agentsec/guards/pg_anon_grant.py +278 -0
  415. agentsec/guards/pg_default_privileges_public.py +153 -0
  416. agentsec/guards/pg_extension_in_public.py +174 -0
  417. agentsec/guards/pg_foreign_table_exposed.py +161 -0
  418. agentsec/guards/pg_function_immutable_reads_session.py +229 -0
  419. agentsec/guards/pg_function_leakproof.py +137 -0
  420. agentsec/guards/pg_function_search_path.py +216 -0
  421. agentsec/guards/pg_graphql_table_exposed.py +182 -0
  422. agentsec/guards/pg_rls_no_policy.py +307 -0
  423. agentsec/guards/pg_rls_not_forced.py +137 -0
  424. agentsec/guards/pg_role_bypassrls.py +126 -0
  425. agentsec/guards/pg_role_bypassrls_membership.py +181 -0
  426. agentsec/guards/pg_security_definer_view.py +287 -0
  427. agentsec/guards/pg_ssl_required.py +207 -0
  428. agentsec/guards/pgmq_queue_exposed_in_api.py +113 -0
  429. agentsec/guards/php_code_injection.py +401 -0
  430. agentsec/guards/php_command_injection.py +246 -0
  431. agentsec/guards/php_extract_superglobal_overwrite.py +124 -0
  432. agentsec/guards/php_file_inclusion.py +182 -0
  433. agentsec/guards/php_preg_replace_eval_modifier.py +122 -0
  434. agentsec/guards/php_reflected_xss.py +141 -0
  435. agentsec/guards/php_sql_injection.py +182 -0
  436. agentsec/guards/php_tls_verify_disabled.py +167 -0
  437. agentsec/guards/php_unsafe_deserialization.py +177 -0
  438. agentsec/guards/pii_llm_roundtrip.py +218 -0
  439. agentsec/guards/plugin_security.py +738 -0
  440. agentsec/guards/policy_exists_rls_disabled.py +216 -0
  441. agentsec/guards/policy_no_role_scope.py +457 -0
  442. agentsec/guards/policy_truncation.py +242 -0
  443. agentsec/guards/postmessage_origin.py +244 -0
  444. agentsec/guards/privileged_field_assignment.py +205 -0
  445. agentsec/guards/prompt_string_interp.py +556 -0
  446. agentsec/guards/proxy_tls_hardening.py +212 -0
  447. agentsec/guards/public_table_rls.py +340 -0
  448. agentsec/guards/pydantic_model_construct.py +245 -0
  449. agentsec/guards/python_supply_chain.py +569 -0
  450. agentsec/guards/rag_isolation.py +314 -0
  451. agentsec/guards/rag_no_instruction_filter.py +892 -0
  452. agentsec/guards/rag_scoped_retrieval.py +291 -0
  453. agentsec/guards/rag_trust_boundary.py +204 -0
  454. agentsec/guards/rate_limit_no_persistent_store.py +237 -0
  455. agentsec/guards/rate_limit_no_user_key.py +206 -0
  456. agentsec/guards/rds_backup_retention_too_short.py +205 -0
  457. agentsec/guards/rds_publicly_accessible.py +139 -0
  458. agentsec/guards/rds_storage_not_encrypted.py +214 -0
  459. agentsec/guards/react_native_insecure_token_storage.py +160 -0
  460. agentsec/guards/redis_glob_pattern_injection.py +181 -0
  461. agentsec/guards/redos.py +549 -0
  462. agentsec/guards/refresh_token_plaintext.py +169 -0
  463. agentsec/guards/regex_html_sanitizer.py +182 -0
  464. agentsec/guards/request_body_size_unbounded.py +219 -0
  465. agentsec/guards/request_model_extra_forbid.py +220 -0
  466. agentsec/guards/response_model_set.py +382 -0
  467. agentsec/guards/reverse_shell_pattern.py +189 -0
  468. agentsec/guards/rls_anon_write_access.py +134 -0
  469. agentsec/guards/rls_auth_email_lockout.py +120 -0
  470. agentsec/guards/rls_auth_role_unknown_literal.py +417 -0
  471. agentsec/guards/rls_auth_uid_unwrapped.py +249 -0
  472. agentsec/guards/rls_auth_users_unbound_exists.py +151 -0
  473. agentsec/guards/rls_current_setting_unqualified.py +135 -0
  474. agentsec/guards/rls_current_user_tenant_key.py +149 -0
  475. agentsec/guards/rls_fkey_to_auth_non_primary.py +136 -0
  476. agentsec/guards/rls_hardcoded_tenant_literal.py +147 -0
  477. agentsec/guards/rls_inverted_auth_check.py +208 -0
  478. agentsec/guards/rls_multiple_permissive_policies.py +157 -0
  479. agentsec/guards/rls_no_user_metadata_claim.py +112 -0
  480. agentsec/guards/rls_partition_inherits_bypass.py +172 -0
  481. agentsec/guards/rls_pattern_match_auth_context.py +143 -0
  482. agentsec/guards/rls_permissive_policy.py +363 -0
  483. agentsec/guards/rls_realtime_published_no_rls.py +160 -0
  484. agentsec/guards/rls_restrictive_only.py +161 -0
  485. agentsec/guards/rls_update_privileged_column.py +368 -0
  486. agentsec/guards/ruby_command_injection.py +261 -0
  487. agentsec/guards/ruby_dangerous_dispatch.py +346 -0
  488. agentsec/guards/ruby_mass_assignment.py +193 -0
  489. agentsec/guards/ruby_sql_injection.py +354 -0
  490. agentsec/guards/ruby_tls_verify_disabled.py +154 -0
  491. agentsec/guards/ruby_unsafe_deserialization.py +188 -0
  492. agentsec/guards/ruby_unsafe_reflection.py +199 -0
  493. agentsec/guards/ruby_weak_crypto.py +125 -0
  494. agentsec/guards/s3_bucket_canned_acl.py +208 -0
  495. agentsec/guards/s3_bucket_insecure_transport_allowed.py +287 -0
  496. agentsec/guards/s3_bucket_policy_wildcard_principal.py +234 -0
  497. agentsec/guards/s3_mfa_delete_disabled.py +283 -0
  498. agentsec/guards/s3_public_access_block_disabled.py +160 -0
  499. agentsec/guards/sagemaker_notebook_not_encrypted.py +126 -0
  500. agentsec/guards/sandbox_denylist_bypass.py +261 -0
  501. agentsec/guards/secret_in_url_query.py +295 -0
  502. agentsec/guards/secret_str_serialized.py +290 -0
  503. agentsec/guards/secrets_manager_default_kms.py +134 -0
  504. agentsec/guards/security_headers.py +133 -0
  505. agentsec/guards/sensitive_columns.py +280 -0
  506. agentsec/guards/sensitive_logging.py +276 -0
  507. agentsec/guards/service_role_key.py +162 -0
  508. agentsec/guards/session_fixation_no_regenerate.py +136 -0
  509. agentsec/guards/session_no_csrf.py +256 -0
  510. agentsec/guards/setup_network_call.py +203 -0
  511. agentsec/guards/sfn_observability.py +198 -0
  512. agentsec/guards/shared_resource_authz.py +245 -0
  513. agentsec/guards/skill_poisoning.py +340 -0
  514. agentsec/guards/skill_untrusted_exec_path.py +314 -0
  515. agentsec/guards/slopsquatting.py +312 -0
  516. agentsec/guards/sns_topic_not_encrypted.py +112 -0
  517. agentsec/guards/sql_race_check_then_insert.py +296 -0
  518. agentsec/guards/sqlalchemy_text_parameterized.py +153 -0
  519. agentsec/guards/sqs_queue_not_encrypted.py +123 -0
  520. agentsec/guards/ssh_allowlist_absent.py +99 -0
  521. agentsec/guards/sshd_hardening.py +142 -0
  522. agentsec/guards/ssrf_bracketed_ipv6_bypass.py +260 -0
  523. agentsec/guards/ssrf_dns_rebind_toctou.py +233 -0
  524. agentsec/guards/ssrf_general.py +531 -0
  525. agentsec/guards/ssrf_ipv6_bypass.py +113 -0
  526. agentsec/guards/ssrf_redirect_bypass.py +218 -0
  527. agentsec/guards/ssti.py +215 -0
  528. agentsec/guards/staticfiles_broad_mount.py +126 -0
  529. agentsec/guards/storage_no_rls.py +278 -0
  530. agentsec/guards/string_format_injection.py +169 -0
  531. agentsec/guards/stripe_webhook.py +696 -0
  532. agentsec/guards/supabase_anon_key_rls_reachable.py +185 -0
  533. agentsec/guards/supabase_filter_injection.py +185 -0
  534. agentsec/guards/supabase_storage_public.py +284 -0
  535. agentsec/guards/supabase_vault_exposure.py +883 -0
  536. agentsec/guards/supabase_vault_plaintext_leak.py +357 -0
  537. agentsec/guards/svg_embedded_script.py +113 -0
  538. agentsec/guards/system_prompt_exposure.py +375 -0
  539. agentsec/guards/system_prompt_leak.py +164 -0
  540. agentsec/guards/target_blank_noopener.py +210 -0
  541. agentsec/guards/terraform_hardcoded_secret_literal.py +362 -0
  542. agentsec/guards/tls_verify_disabled.py +315 -0
  543. agentsec/guards/token_in_localstorage.py +172 -0
  544. agentsec/guards/tool_callback_enforcement.py +1022 -0
  545. agentsec/guards/tool_chaining_exfil.py +208 -0
  546. agentsec/guards/trust_boundary.py +239 -0
  547. agentsec/guards/trusted_host_absent.py +143 -0
  548. agentsec/guards/truthy_ownership_check.py +341 -0
  549. agentsec/guards/unauthenticated_file_download.py +217 -0
  550. agentsec/guards/unawaited_async_truthy.py +209 -0
  551. agentsec/guards/unrestricted_file_upload.py +93 -0
  552. agentsec/guards/unsafe_deserialization.py +423 -0
  553. agentsec/guards/untrusted_package_install_source.py +181 -0
  554. agentsec/guards/upload_no_size_limit.py +219 -0
  555. agentsec/guards/upstream_response_unvalidated.py +368 -0
  556. agentsec/guards/version_floors.json +590 -0
  557. agentsec/guards/vite_client_secret.py +161 -0
  558. agentsec/guards/vite_sourcemap_prod.py +180 -0
  559. agentsec/guards/vscode_tasks_auto_exec.py +471 -0
  560. agentsec/guards/weak_crypto.py +216 -0
  561. agentsec/guards/weak_password_length_check.py +134 -0
  562. agentsec/guards/weak_secret_key_literal.py +151 -0
  563. agentsec/guards/webhook_idempotency.py +183 -0
  564. agentsec/guards/webhook_signature_not_verified.py +478 -0
  565. agentsec/guards/websocket_no_auth.py +252 -0
  566. agentsec/guards/websocket_origin.py +175 -0
  567. agentsec/guards/xpath_injection.py +118 -0
  568. agentsec/guards/xxe_safe.py +92 -0
  569. agentsec/guards/zip_bomb.py +175 -0
  570. agentsec/guards/zip_slip.py +273 -0
  571. agentsec/hostaudit/__init__.py +13 -0
  572. agentsec/hostaudit/audit.py +353 -0
  573. agentsec/hostaudit/probes.py +549 -0
  574. agentsec/ingest.py +396 -0
  575. agentsec/intake.py +241 -0
  576. agentsec/js_harden.py +163 -0
  577. agentsec/k8s.py +85 -0
  578. agentsec/kev.py +105 -0
  579. agentsec/live.py +534 -0
  580. agentsec/livescan.py +288 -0
  581. agentsec/net.py +231 -0
  582. agentsec/patterns.py +16 -0
  583. agentsec/pins.py +174 -0
  584. agentsec/prioritize.py +114 -0
  585. agentsec/python_harden.py +234 -0
  586. agentsec/reachability.py +183 -0
  587. agentsec/registry.py +1140 -0
  588. agentsec/report.py +298 -0
  589. agentsec/runners/__init__.py +8 -0
  590. agentsec/runners/bandit.py +88 -0
  591. agentsec/runners/base.py +363 -0
  592. agentsec/runners/eslint.py +217 -0
  593. agentsec/runners/gitleaks.py +69 -0
  594. agentsec/runners/go_osv_hygiene.py +414 -0
  595. agentsec/runners/hadolint.py +80 -0
  596. agentsec/runners/node_audit.py +160 -0
  597. agentsec/runners/pip_audit.py +107 -0
  598. agentsec/runners/react_doctor.py +198 -0
  599. agentsec/runners/scorecard.py +161 -0
  600. agentsec/runners/semgrep.py +127 -0
  601. agentsec/runners/trivy.py +230 -0
  602. agentsec/setup.py +705 -0
  603. agentsec/sql_state.py +214 -0
  604. agentsec/ssrf_fetch.py +175 -0
  605. agentsec/targets.py +116 -0
  606. agentsec/text_sanitize.py +188 -0
  607. agentsec/textio.py +22 -0
  608. agentsec/tool_version.py +200 -0
  609. agentsec/tooling.py +227 -0
  610. agentsec/triage.py +165 -0
  611. agentsec/triage_cli.py +465 -0
  612. agentsec/update_check.py +262 -0
  613. agentsec/walk.py +619 -0
  614. ai_agent_security-0.22.2.dist-info/METADATA +267 -0
  615. ai_agent_security-0.22.2.dist-info/RECORD +618 -0
  616. ai_agent_security-0.22.2.dist-info/WHEEL +4 -0
  617. ai_agent_security-0.22.2.dist-info/entry_points.txt +2 -0
  618. ai_agent_security-0.22.2.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,512 @@
1
+ """Guard: no open redirect from user-controlled input (checklist §3a).
2
+
3
+ A redirect whose target is built from request input — e.g. the `next` query
4
+ param fed straight into a `redirect(...)` sink — lets an attacker send
5
+ `?next=https://evil.example` and bounce a victim off your trusted domain
6
+ (phishing, OAuth-token theft, filter bypass).
7
+ CWE-601 / OWASP:A01. The fix is to redirect only to a vetted internal target:
8
+ `url_for("dashboard")`, a path from an allow-list, or a relative path validated
9
+ to start with a single `/`.
10
+
11
+ Fires MEDIUM on a redirect sink whose target **provably derives from untrusted /
12
+ request input** — a request accessor directly, a typed FastAPI/Starlette request-data
13
+ parameter (`next: str = Query(...)` or `Annotated[str, Query()]`, incl. `Path`/`Body`/
14
+ `Form`/`Cookie`/`Header`/`File`), or a variable/f-string/concat that carries one
15
+ (intra-file taint) — and is NOT a `url_for(...)` call:
16
+
17
+ * Flask / Django — `redirect(...)`;
18
+ * Starlette / FastAPI — `RedirectResponse(...)`;
19
+ * Django — `HttpResponseRedirect(...)`.
20
+
21
+ This is provenance, not pattern-presence: a redirect to an internal/vetted value
22
+ (`redirect(dest)` where `dest` is a function param, or a `url_for(...)`-derived
23
+ variable) does NOT fire — that was the F2/B8 auto-exclude-noise the old
24
+ bare-variable heuristic emitted (issue #90). A static literal (`redirect("/home")`)
25
+ does not fire either. Suppress an audited case with `# security: allow-open-redirect`.
26
+
27
+ Lexing: the file is tokenized (stdlib `tokenize`) and the character spans of every
28
+ string literal and comment are blanked before analysis — so a request accessor or a
29
+ sink that appears as *text* inside a string, a comment, or a docstring code-example
30
+ (incl. multi-line strings) is never mistaken for code, while f-string *interpolations*
31
+ (`f"{request.args['n']}"`) are kept as the code they are. On a syntactically invalid
32
+ file it degrades to a best-effort raw scan (never raises).
33
+
34
+ Limitations: taint is tracked **intra-file** only; a **multi-line call** whose sink and
35
+ target sit on different physical lines is not matched (line-oriented match). Instance-attribute
36
+ taint is not tracked: `self.q = request.args.get(...)` followed by `redirect(self.q)` is a
37
+ false negative, because the taint model keys on BARE names and `self`/`cls` are deliberately
38
+ excluded (tainting `self` made every `redirect(self.anything)` in the file fire). The
39
+ recognized untrusted sources are the explicit request accessors in `_UNTRUSTED` and the
40
+ FastAPI request-data parameter markers (`Query`/`Path`/`Body`/`Form`/`Cookie`/`Header`/
41
+ `File`); broaden them if a framework's accessor or marker is missing.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import ast
46
+ import re
47
+ import tokenize
48
+ from collections import deque
49
+ from io import StringIO
50
+ from pathlib import Path
51
+
52
+ from agentsec.astutil import safe_ast_parse
53
+ from agentsec.detect import StackProfile
54
+ from agentsec.findings import Finding
55
+
56
+ from .base import CanaryPlant, Guard, comment_view, iter_files, python_scan_dirs, read, rel
57
+
58
+ _SINK = re.compile(r"\b(?:redirect|RedirectResponse|HttpResponseRedirect)\s*\(")
59
+ _PRAGMA = re.compile(r"#\s*security:\s*allow-open-redirect")
60
+
61
+ # Untrusted / request-derived sources. Explicit accessors (not a bare `request.`)
62
+ # so `request.method` etc. don't count. Covers Flask/Django (`request.args/form/
63
+ # values/GET/POST/json/get_json/data/cookies/headers`), Starlette/FastAPI
64
+ # `.query_params`, and Django class-based views (`self.request.`).
65
+ _UNTRUSTED = re.compile(
66
+ r"\brequest\s*\.\s*(?:args|form|values|GET|POST|json|get_json|data|cookies|headers|query_params)\b"
67
+ r"|\.\s*query_params\b"
68
+ r"|\bself\s*\.\s*request\s*\."
69
+ )
70
+ _WORD = re.compile(r"[A-Za-z_]\w*")
71
+ # Augmented assignment: `NAME <op>= rhs` (e.g. `path += request.args["s"]`).
72
+ _AUG = re.compile(r"^\s*([A-Za-z_]\w*)\s*(?:\+|-|\*|/|//|%|@|&|\||\^|>>|<<|\*\*)=(?!=)\s*(.+)$")
73
+ _WALRUS_HEAD = re.compile(r"([A-Za-z_]\w*)\s*:=\s*")
74
+
75
+ # FastAPI/Starlette request-data parameter markers. A route parameter whose default is one
76
+ # of these — `next: str = Query(...)` — or whose `Annotated[...]` metadata carries one —
77
+ # `next: Annotated[str, Query()]` — IS request input, so its name is an untrusted taint
78
+ # source even though it never appears as `name = request.X` (issue #296: a typed Query/Path/
79
+ # Body param is the most common FastAPI redirect-target source). Deliberately NOT Depends/
80
+ # Security (those inject a dependency's return — often a *validated* value like the
81
+ # authenticated user). A plain typed param with no marker (`dest: str`) is left alone —
82
+ # tainting those would reintroduce the #90 internal-param false positive.
83
+ #
84
+ # Recognition is gated on the marker name actually being imported FROM fastapi/starlette in
85
+ # this file (#296 round-5 review): the names collide with common stdlib/ORM constructors
86
+ # (`pathlib.Path`, `sqlalchemy.orm.Query`), so a `Path(...)`/`Query(...)` parameter default
87
+ # in a file that never imports the framework must NOT be read as a request binding.
88
+ _MARKERS = frozenset({"Query", "Path", "Body", "Form", "Cookie", "Header", "File"})
89
+ _DEF = re.compile(r"\bdef\s+[A-Za-z_]\w*\s*\(")
90
+ _DEFAULT_CALL = re.compile(r"^([A-Za-z_]\w*)\s*\(")
91
+ _NAME_ONLY = re.compile(r"^[A-Za-z_]\w*$")
92
+
93
+
94
+ def _is_framework_module(module: str) -> bool:
95
+ return module in ("fastapi", "starlette") or module.startswith(("fastapi.", "starlette."))
96
+
97
+
98
+ def _blank_strings_and_comments(text: str) -> list[str]:
99
+ """Overwrite the character spans of every STRING / COMMENT / f-string-literal token
100
+ with spaces so string content and comments (incl. multi-line strings) can never be
101
+ mis-read as code, while f-string *interpolation* code and the exact column layout are
102
+ preserved. Best-effort: on a tokenize error (a syntactically invalid file) the raw
103
+ lines are returned rather than raising."""
104
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
105
+ lines = text.split("\n")
106
+ try:
107
+ toks = list(tokenize.generate_tokens(StringIO(text).readline))
108
+ except (tokenize.TokenError, IndentationError, SyntaxError, ValueError, RecursionError, MemoryError):
109
+ return lines # unparseable / too-complex -> best-effort raw scan (#370)
110
+ blank_types = {tokenize.STRING, tokenize.COMMENT}
111
+ for _name in ("FSTRING_START", "FSTRING_MIDDLE", "FSTRING_END"): # PEP 701, py3.12+
112
+ _t = getattr(tokenize, _name, None)
113
+ if _t is not None:
114
+ blank_types.add(_t)
115
+ grid = [list(ln) for ln in lines]
116
+ for tok in toks:
117
+ if tok.type in blank_types:
118
+ (sr, sc), (er, ec) = tok.start, tok.end
119
+ for r in range(sr, er + 1):
120
+ if r - 1 >= len(grid):
121
+ break
122
+ row = grid[r - 1]
123
+ lo = sc if r == sr else 0
124
+ hi = ec if r == er else len(row)
125
+ for c in range(lo, min(hi, len(row))):
126
+ row[c] = " "
127
+ return ["".join(row) for row in grid]
128
+
129
+
130
+ def _walruses(code: str) -> list[tuple[str, str]]:
131
+ """(target, value) for each `name := <value>` on a line, value captured with bracket
132
+ balance to its own enclosing close (a nested call before the untrusted ref isn't
133
+ truncated at the first `)`)."""
134
+ out: list[tuple[str, str]] = []
135
+ for m in _WALRUS_HEAD.finditer(code):
136
+ depth = 0
137
+ j = m.end()
138
+ n = len(code)
139
+ while j < n:
140
+ c = code[j]
141
+ if c in "([{":
142
+ depth += 1
143
+ elif c in ")]}":
144
+ if depth == 0:
145
+ break
146
+ depth -= 1
147
+ elif c == "," and depth == 0:
148
+ break
149
+ j += 1
150
+ out.append((m.group(1), code[m.end():j]))
151
+ return out
152
+
153
+
154
+ def _refs_name(name: str, text: str) -> bool:
155
+ """True if `name` appears in `text` as a standalone variable reference — NOT an
156
+ attribute member (`obj.name`), a keyword-arg name (`name=`), or part of a longer
157
+ identifier (`user_name`). Stops a tainted name from colliding with an unrelated
158
+ `.name`/`name=`."""
159
+ return re.search(r"(?<![.\w])" + re.escape(name) + r"(?![\w=])", text) is not None
160
+
161
+
162
+ # Every standalone identifier reference in a piece of code (same boundary rule as `_refs_name`:
163
+ # not `.attr`, not a `kw=` name, not part of a longer identifier). Used to precompute an
164
+ # assignment's referenced names ONCE so the taint fixpoint is set-membership, not a regex per
165
+ # tainted name per pass (which was O(n^3) on a long assignment chain — #296 final review).
166
+ _STANDALONE_REF = re.compile(r"(?<![.\w])([A-Za-z_]\w*)(?![\w=])")
167
+
168
+
169
+ def _split_top_level_eq(line: str) -> list[str]:
170
+ """Split on `=` at bracket depth 0, excluding comparisons (`==`/`!=`/`<=`/`>=`),
171
+ augmented (`+=`), and walrus (`:=`). (Strings are already blanked upstream.)"""
172
+ parts: list[str] = []
173
+ depth = 0
174
+ start = 0
175
+ i = 0
176
+ n = len(line)
177
+ while i < n:
178
+ ch = line[i]
179
+ if ch in "([{":
180
+ depth += 1
181
+ elif ch in ")]}":
182
+ depth -= 1
183
+ elif ch == "=" and depth == 0:
184
+ nxt = line[i + 1] if i + 1 < n else ""
185
+ if nxt == "=" or (line[i - 1] if i > 0 else "") in "=!<>+-*/%&|^@~:":
186
+ if nxt == "=":
187
+ i += 1 # step over the second '=' of '=='
188
+ else:
189
+ parts.append(line[start:i])
190
+ start = i + 1
191
+ i += 1
192
+ parts.append(line[start:])
193
+ return parts
194
+
195
+
196
+ def _assign_targets(line: str) -> tuple[list[str], str] | None:
197
+ """(target-names, value-expr) for a simple / annotated / chained (`a = b = v`) /
198
+ tuple (`a, b = v`) / augmented (`x += v`) assignment, else None."""
199
+ m = _AUG.match(line)
200
+ if m:
201
+ return [m.group(1)], m.group(2)
202
+ segs = _split_top_level_eq(line)
203
+ if len(segs) < 2:
204
+ return None
205
+ target_text = "".join(segs[:-1]).split(":", 1)[0] # all-but-last are targets; drop annotation
206
+ # Drop `self`/`cls`: for `self.q = request.args.get(...)`, _WORD.findall("self.q") yields
207
+ # ["self", "q"], and tainting `self` made EVERY `redirect(self.anything)` in the file fire (#423).
208
+ # KNOWN LIMITATION (PR #450 review): the taint model keys on BARE names, so the attribute
209
+ # itself (`self.q`) is not tracked — a genuinely tainted `self.q = request...` followed by
210
+ # `redirect(self.q)` is a false negative. Accepted: the broad `self`-taint FP it replaces was
211
+ # worse; instance-attribute dataflow is out of scope for this line-level heuristic.
212
+ targets = [w for w in _WORD.findall(target_text) if w not in ("self", "cls")]
213
+ return targets, segs[-1]
214
+
215
+
216
+ def _split_top_level_commas(sig: str) -> list[str]:
217
+ """Split a signature's parameter list on commas at bracket depth 0, so a comma inside
218
+ an annotation (`Dict[str, int]`) or a default call doesn't split one parameter in two."""
219
+ out: list[str] = []
220
+ depth = 0
221
+ start = 0
222
+ for i, c in enumerate(sig):
223
+ if c in "([{":
224
+ depth += 1
225
+ elif c in ")]}":
226
+ depth -= 1
227
+ elif c == "," and depth == 0:
228
+ out.append(sig[start:i])
229
+ start = i + 1
230
+ out.append(sig[start:])
231
+ return out
232
+
233
+
234
+ def _imported_markers(raw: str, *, filename: str | Path = "<unknown>") -> set[str]:
235
+ """Names bound in this file to a fastapi/starlette request-data marker (`Query`/`Path`/…),
236
+ resolved with real import semantics via `ast`. A name is a marker iff its LAST binding in
237
+ source order is `from fastapi[.x] | starlette[.x] import <Marker>[ as name]`. Using the AST
238
+ (rather than a regex over import lines) makes aliases (`Query as Q` → the bound name `Q`),
239
+ import order / last-binding-wins shadowing, `;`-chained imports, and parenthesized or
240
+ `\\`-continued lists all correct — the class of edge cases that regex approximations kept
241
+ leaking (#296 review rounds 5-6). Relative imports (`from . import …`) are never framework.
242
+ Degrades to `set()` on a syntactically invalid file (never raises)."""
243
+ tree = safe_ast_parse(raw, filename=filename)
244
+ if tree is None:
245
+ return set()
246
+ froms = [n for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)]
247
+ froms.sort(key=lambda n: (n.lineno, n.col_offset))
248
+ binding: dict[str, bool] = {} # bound name -> resolves to a framework request-data marker
249
+ for node in froms:
250
+ module = "" if node.level else (node.module or "") # a relative import is never the framework
251
+ fw = _is_framework_module(module)
252
+ for alias in node.names:
253
+ binding[alias.asname or alias.name] = fw and alias.name in _MARKERS
254
+ return {name for name, is_marker in binding.items() if is_marker}
255
+
256
+
257
+ def _fastapi_param_sources(lines: list[str], raw: str, *, filename: str | Path = "<unknown>") -> set[str]:
258
+ """Names of parameters that are FastAPI/Starlette request-data bindings — a `def`
259
+ signature parameter whose default is a framework marker call (`Query()/Path()/Body()/
260
+ Form()/Cookie()/Header()/File()`), or whose `Annotated[...]` metadata carries one. Such a
261
+ parameter IS request input, so its name seeds the taint set (issue #296). Only names bound
262
+ to a framework marker count (`_imported_markers`, resolved from `raw` via AST); combined
263
+ with the `def`-signature scoping this keeps a `pathlib.Path(...)` / SQLAlchemy `Query(...)`
264
+ default from being misread as a request binding. Signature scan runs on the string/comment-
265
+ blanked `lines`."""
266
+ markers = _imported_markers(raw, filename=filename)
267
+ if not markers:
268
+ return set()
269
+ # A marker CALL anywhere in the annotation means it is `Annotated[..., Query()]` metadata
270
+ # (a bare `Marker(...)` never appears in a normal type annotation). Searching for the call
271
+ # directly — instead of `Annotated\[[^\]]*…` — is agnostic to nested generics like
272
+ # `Annotated[Optional[str], Query()]`, whose inner `]` the old bracket-bounded regex could
273
+ # not cross (#296 final review).
274
+ marker_call = re.compile(r"\b(?:" + "|".join(re.escape(m) for m in sorted(markers)) + r")\s*\(")
275
+ text = "\n".join(lines)
276
+ seeds: set[str] = set()
277
+ for dm in _DEF.finditer(text):
278
+ depth = 0
279
+ i = dm.end() - 1 # positioned on the signature's opening '('
280
+ n = len(text)
281
+ while i < n:
282
+ c = text[i]
283
+ if c in "([{":
284
+ depth += 1
285
+ elif c in ")]}":
286
+ depth -= 1
287
+ if depth == 0:
288
+ break
289
+ i += 1
290
+ for param in _split_top_level_commas(text[dm.end():i]):
291
+ segs = _split_top_level_eq(param)
292
+ name_annot = segs[0]
293
+ default = segs[-1].strip() if len(segs) > 1 else ""
294
+ name = name_annot.split(":", 1)[0].strip()
295
+ if not _NAME_ONLY.match(name):
296
+ continue
297
+ call = _DEFAULT_CALL.match(default)
298
+ annotated_marker = "Annotated" in name_annot and marker_call.search(name_annot) is not None
299
+ if (call and call.group(1) in markers) or annotated_marker:
300
+ seeds.add(name)
301
+ return seeds
302
+
303
+
304
+ def _tainted_vars(lines: list[str], raw: str, *, filename: str | Path = "<unknown>") -> set[str]:
305
+ """Names assigned (anywhere in the file) from an untrusted source, transitively.
306
+
307
+ Fixpoint over the file's assignments (simple / annotated / chained / tuple / augmented
308
+ / walrus): a name is tainted if the value it is assigned from names an untrusted request
309
+ accessor or an already-tainted name. Seeded with FastAPI/Starlette request-data
310
+ parameters (`_fastapi_param_sources`, issue #296) so a typed `Query`/`Path`/`Body` param
311
+ and anything derived from it taint too. Operates on string/comment-blanked lines (`raw` is
312
+ the unblanked source, used only for AST import resolution). Over-tainting only ever makes
313
+ the guard fire. Each assignment's direct-untrusted flag and referenced names are computed
314
+ ONCE up front, then propagation is a worklist over a `referenced-name -> assignments` index,
315
+ so tainting a name only re-examines the assignments that could newly taint. This is O(V+E)
316
+ and **order-independent** — a forward OR a reverse-order assignment chain both converge
317
+ linearly (the old regex-per-tainted-name-per-pass form was O(n^3); a plain in-place sweep is
318
+ still O(n^2) on a reverse-order chain — #296 final review + re-review)."""
319
+ prepared: list[tuple[list[str], bool, set[str]]] = []
320
+ for line in lines:
321
+ at = _assign_targets(line)
322
+ pairs = ([at] if at else []) + [([name], value) for name, value in _walruses(line)]
323
+ for targets, value in pairs:
324
+ prepared.append((targets, _UNTRUSTED.search(value) is not None, set(_STANDALONE_REF.findall(value))))
325
+ ref_index: dict[str, list[int]] = {} # a referenced name -> the assignments that reference it
326
+ for idx, (_targets, _direct, refs) in enumerate(prepared):
327
+ for r in refs:
328
+ ref_index.setdefault(r, []).append(idx)
329
+ tainted: set[str] = set(_fastapi_param_sources(lines, raw, filename=filename))
330
+ work: deque[str] = deque(tainted)
331
+ for targets, direct, _refs in prepared: # assignments tainted by a direct request accessor
332
+ if direct:
333
+ for t in targets:
334
+ if t not in tainted:
335
+ tainted.add(t)
336
+ work.append(t)
337
+ while work: # a newly-tainted name taints the targets of every assignment referencing it
338
+ for idx in ref_index.get(work.popleft(), ()):
339
+ for t in prepared[idx][0]:
340
+ if t not in tainted:
341
+ tainted.add(t)
342
+ work.append(t)
343
+ return tainted
344
+
345
+
346
+ _URL_FOR_CALL = re.compile(r"(?:[\w.]+\.)?\burl_for\s*\(")
347
+
348
+
349
+ def _blank_url_for_calls(a: str) -> str:
350
+ """Replace every `url_for(...)` call span with a space. `url_for` builds a vetted internal
351
+ path, so untrusted input *inside* its arguments is not an open-redirect risk — only untrusted
352
+ that survives OUTSIDE a url_for call is judged: a concatenation (`url_for('x') + request…`),
353
+ or a transform on the result (`url_for(…).lower()`), or a bare tainted target. Bracket-matched;
354
+ an unbalanced (multi-line) call keeps the remainder verbatim. Single forward pass, O(n) — the
355
+ search resumes past each blanked span rather than restarting from the start (#296 final review
356
+ + re-reviews: this replaced a substring test, then a whole-target test that mis-fired on a
357
+ trailing `.lower()`, then an O(n^2) repeated-search-from-start form)."""
358
+ out: list[str] = []
359
+ pos = 0
360
+ n = len(a)
361
+ while pos < n:
362
+ m = _URL_FOR_CALL.search(a, pos)
363
+ if not m:
364
+ out.append(a[pos:])
365
+ break
366
+ out.append(a[pos : m.start()]) # text before this url_for call, kept as-is
367
+ depth = 0
368
+ close = -1
369
+ j = m.end() - 1 # url_for's `(`
370
+ while j < n:
371
+ c = a[j]
372
+ if c in "([{":
373
+ depth += 1
374
+ elif c in ")]}":
375
+ depth -= 1
376
+ if depth == 0:
377
+ close = j
378
+ break
379
+ j += 1
380
+ if close == -1: # unbalanced (multi-line) -> keep the remainder verbatim and stop
381
+ out.append(a[m.start() :])
382
+ break
383
+ out.append(" ") # the blanked url_for(...) span
384
+ pos = close + 1
385
+ return "".join(out)
386
+
387
+
388
+ def _untrusted_target(arg: str, tainted: set[str]) -> bool:
389
+ """True if the redirect target derives from untrusted input. (`arg` is already
390
+ string/comment-blanked, so a literal `"…request.args…"` reads as empty. `url_for(...)` call
391
+ spans are blanked first — untrusted inside a vetted internal path is not an open redirect.)"""
392
+ a = _blank_url_for_calls(arg.strip())
393
+ if not a.strip():
394
+ return False
395
+ if _UNTRUSTED.search(a): # a request accessor directly in the (non-url_for) target expression
396
+ return True
397
+ return any(_refs_name(t, a) for t in tainted) # a tainted variable reference (not .name / name=)
398
+
399
+
400
+ _URL_KW = frozenset({"url", "to", "location", "redirect_to"})
401
+
402
+
403
+ def _sink_targets(line: str, paren: int) -> list[str]:
404
+ """The redirect-target expressions in a sink call on this line: the first POSITIONAL
405
+ argument, plus any keyword argument whose name is a redirect target (`url`/`to`/`location`/
406
+ `redirect_to`). So `RedirectResponse(status_code=302, url=request.query_params['n'])` is
407
+ inspected, not just the first argument (#296 final review — a target in a later or keyword
408
+ argument used to be missed). Line-oriented: the sink call's argument span is taken up to its
409
+ matching close paren (bracket-aware, so a nested `redirect(url_for(...))` is not truncated);
410
+ a missing close (a multi-line call) degrades to the rest of the line."""
411
+ depth = 0
412
+ end = len(line)
413
+ for i in range(paren, len(line)):
414
+ c = line[i]
415
+ if c in "([{":
416
+ depth += 1
417
+ elif c in ")]}":
418
+ depth -= 1
419
+ if depth == 0:
420
+ end = i
421
+ break
422
+ inner = line[paren + 1 : end]
423
+ args: list[str] = []
424
+ depth = 0
425
+ start = 0
426
+ for idx, ch in enumerate(inner):
427
+ if ch in "([{":
428
+ depth += 1
429
+ elif ch in ")]}":
430
+ depth -= 1
431
+ elif ch == "," and depth == 0:
432
+ args.append(inner[start:idx])
433
+ start = idx + 1
434
+ args.append(inner[start:])
435
+ targets: list[str] = []
436
+ positional_taken = False
437
+ for arg in args:
438
+ segs = _split_top_level_eq(arg)
439
+ if len(segs) == 1: # positional argument
440
+ if not positional_taken:
441
+ targets.append(segs[0])
442
+ positional_taken = True
443
+ elif segs[0].strip() in _URL_KW: # a redirect-target keyword argument
444
+ targets.append(segs[-1])
445
+ return targets
446
+
447
+
448
+ class OpenRedirectGuard(Guard):
449
+ id = "open-redirect"
450
+ title = "No open redirect from user input"
451
+ area = "Network requests"
452
+
453
+ # redirect.py: redirect to a bare request-derived variable -> open-redirect.
454
+ canary_plant = CanaryPlant(
455
+ files={
456
+ "redirect.py": (
457
+ "from flask import redirect, request\n\n\n"
458
+ "def go():\n next_url = request.args.get(\"name\")\n return redirect(next_url)\n"
459
+ ),
460
+ },
461
+ expects=frozenset({"open-redirect/user-controlled-target"}),
462
+ )
463
+
464
+ def applies(self, profile: StackProfile) -> bool:
465
+ return "python" in profile.features
466
+
467
+ def run(self, root: Path, profile: StackProfile) -> list[Finding]:
468
+ out: list[Finding] = []
469
+ seen: set[Path] = set()
470
+ for d in python_scan_dirs(root, profile):
471
+ for f in iter_files(d, (".py",)):
472
+ if f in seen:
473
+ continue
474
+ seen.add(f)
475
+ out.extend(self._scan(root, f))
476
+ return out
477
+
478
+ def _scan(self, root: Path, f: Path) -> list[Finding]:
479
+ raw = read(f)
480
+ blanked = _blank_strings_and_comments(raw)
481
+ # The pragma counts only as a real comment on the line, never quoted in a string there
482
+ # (#1040); the view keeps the tail RAW past a tokenize error, which is the old fallback.
483
+ # It is split as the lexer splits (on "\n" alone, never `splitlines`), so a form feed
484
+ # cannot shift the line numbers apart.
485
+ view = comment_view(raw.replace("\r\n", "\n").replace("\r", "\n"), "python")
486
+ pragma_lines = {i for i, vline in enumerate(view.split("\n"), start=1) if _PRAGMA.search(vline)}
487
+ tainted = _tainted_vars(blanked, raw, filename=f)
488
+ out: list[Finding] = []
489
+ for i, line in enumerate(blanked, start=1):
490
+ if i in pragma_lines:
491
+ continue
492
+ m = _SINK.search(line)
493
+ if m and any(_untrusted_target(t, tainted) for t in _sink_targets(line, m.end() - 1)):
494
+ out.append(Finding(
495
+ check_id=self.id,
496
+ severity="medium",
497
+ title="Redirect target built from user input (open redirect)",
498
+ location=f"{rel(root, f)}:{i}",
499
+ message=(
500
+ "This redirect target derives from request / untrusted input with no "
501
+ "allow-list — an attacker can set it to an external URL and bounce a "
502
+ "victim off your trusted domain (phishing, OAuth-token theft)."
503
+ ),
504
+ remediation=(
505
+ "Redirect only to a vetted internal target: `url_for(...)`, an allow-listed "
506
+ "path, or a relative path validated to start with a single `/`. Suppress an "
507
+ "audited case with `# security: allow-open-redirect`."
508
+ ),
509
+ rule="open-redirect/user-controlled-target",
510
+ standards=["OWASP:A01"],
511
+ ))
512
+ return out