Skip to content
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
d157667
🛡️ Sentinel: [CRITICAL] Fix stored SSRF in webhook URL endpoint
seonghobae Aug 9, 2026
5eddd98
test(security): reject non-string webhook URLs
seonghobae Aug 9, 2026
7bc59a1
test(security): exercise malformed webhook bodies at API boundary
seonghobae Aug 9, 2026
fbc77cb
🛡️ Sentinel: [CRITICAL] Fix stored SSRF and Uncaught Exception in web…
seonghobae Aug 9, 2026
e9d4946
test(scanner): reproduce stored SSRF detection gap
seonghobae Aug 9, 2026
057df0e
security(scanner): detect direct stored webhook SSRF
seonghobae Aug 9, 2026
3d6f57b
test(controlplane): pin webhook input validation boundary
seonghobae Aug 9, 2026
6d55440
fix(controlplane): reject malformed webhook payloads
seonghobae Aug 9, 2026
c9752fa
test(controlplane): prove invalid webhook input preserves state
seonghobae Aug 9, 2026
1689ba7
test(scanner): expose stored SSRF variable-flow blind spot
seonghobae Aug 9, 2026
30af47d
fix(scanner): detect unvalidated stored SSRF variable flow
seonghobae Aug 9, 2026
35578cd
test(scanner): expose SSRF finding metadata misclassification
seonghobae Aug 9, 2026
e051776
fix(scanner): classify CWE-918 findings as SSRF
seonghobae Aug 9, 2026
e65cda8
test(scanner): expose stored SSRF rule evasion paths
seonghobae Aug 9, 2026
2cd9a8f
fix(scanner): close stored SSRF rule evasion paths
seonghobae Aug 9, 2026
2ce25b2
test(scanner): expose non-enforcing SSRF guard bypass
seonghobae Aug 9, 2026
14240fa
test(scanner): pin fail-closed SSRF guard semantics
seonghobae Aug 9, 2026
48a6da5
fix(scanner): require enforcing SSRF validation guards
seonghobae Aug 9, 2026
40b5c63
docs(tests): document stored SSRF regression contracts
seonghobae Aug 9, 2026
40c521e
test(scanner): expose equivalent stored SSRF accessors
seonghobae Aug 9, 2026
999095e
fix(scanner): detect equivalent stored SSRF accessors
seonghobae Aug 9, 2026
5ba9131
docs(tests): document webhook validation helpers
seonghobae Aug 9, 2026
84a2708
security(scanner): preserve stored SSRF detection after endpoint fix
seonghobae Aug 12, 2026
c75987d
perf(scanner): prefilter stored SSRF rule by sink literal
seonghobae Aug 12, 2026
b5c95e3
fix(scanner): evaluate stored SSRF validation per sink
seonghobae Aug 12, 2026
2beb859
fix(scanner): accept none-aware fail-closed SSRF guard
seonghobae Aug 12, 2026
1013819
🎨 Palette: 개선된 파일 업로드 버튼 UX 적용 (#925)
seonghobae Aug 12, 2026
6c6a830
chore: restack stored SSRF scanner on current develop
seonghobae Aug 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,13 @@
**Vulnerability:** DOM XSS via unescaped `severity` string interpolated into `innerHTML` in `scanner/dashboard/index.html`.
**Learning:** Even enum-like or seemingly safe meta-fields like `severity` can contain malicious payloads if sourced from user input (findings file) and directly injected into innerHTML.
**Prevention:** Always use the `esc()` sanitizer for any dynamically rendered property from `findings.json`, regardless of expected schema types.

## 2024-05-24 - [SSRF in Webhook Endpoint]
**Vulnerability:** The `/api/v1/webhook` endpoint accepted arbitrary URLs for the drift alert webhook without any server-side request forgery (SSRF) validation before saving them to the database.
**Learning:** Even if a URL is validated prior to use (e.g., in `_send_alert`), accepting and storing arbitrary URLs without validation introduces a Stored SSRF vulnerability vector and violates the principle of failing fast and securely on untrusted input.
**Prevention:** Always apply security validation functions (like `_is_safe_url`) immediately at the boundary/endpoint level prior to performing database insertion or mutation.

## 2024-05-24 - [Uncaught Exception in _is_safe_url]
**Vulnerability:** The `_is_safe_url` function relied on `urllib.parse.urlparse`, which assumes string inputs. Passing non-string inputs (like integers or booleans) caused an `AttributeError` exception, potentially leading to denial of service or 500 errors in JSON APIs expecting fail-closed validation.
**Learning:** Security validation functions must handle malformed data types (not just malformed strings) gracefully without raising framework exceptions.
**Prevention:** Explicitly validate input types (e.g., `isinstance(url, str)`) before passing them to parsing libraries that make type assumptions.
14 changes: 11 additions & 3 deletions appguardrail_core/controlplane.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,9 @@ def _is_safe_url(url: str) -> bool:
import urllib.parse
import socket

if not isinstance(url, str):
return False

try:
parsed = urllib.parse.urlparse(
url
Expand Down Expand Up @@ -629,10 +632,15 @@ def do_POST(self):
if not has_role(role, "owner"):
return self._json(403, {"error": "owner role required"})
body = self._body()
if body is None:
if not isinstance(body, dict):
return self._json(400, {"error": "invalid JSON body"})
set_webhook(conn, org, (body or {}).get("url"))
return self._json(200, {"webhook_url": (body or {}).get("url")})
webhook_url = body.get("url")
if webhook_url not in (None, "") and (
not isinstance(webhook_url, str) or not _is_safe_url(webhook_url)
):
return self._json(400, {"error": "unsafe webhook url"})
set_webhook(conn, org, webhook_url)
return self._json(200, {"webhook_url": webhook_url})

if path == "/api/v1/keys":
if not has_role(role, "owner"):
Expand Down
26 changes: 25 additions & 1 deletion appguardrail_core/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,25 @@
"OWASP A07:2021 - Identification and Authentication Failures",
"CWE-798 - Use of Hard-coded Credentials",
),
"ssrf": (
"OWASP A10:2021 - Server-Side Request Forgery",
"CWE-918 - Server-Side Request Forgery",
),
"storage": ("OWASP A01:2021 - Broken Access Control",),
}

REFERENCE_CATEGORY_OVERRIDES = {
"CWE-918": "ssrf",
}

SAMM_BY_CATEGORY = {
"authz": "Implementation / Secure Build",
"dependency": "Implementation / Secure Build",
"injection": "Implementation / Secure Build",
"misconfig": "Operations / Environment Management",
"payment": "Verification / Requirements-driven Testing",
"secrets": "Operations / Environment Management",
"ssrf": "Implementation / Secure Build",
"storage": "Implementation / Secure Build",
}

Expand Down Expand Up @@ -59,6 +68,10 @@
"Remove the secret from source, rotate it, and load future values from "
"managed secret storage."
),
"ssrf": (
"Validate untrusted URLs before persistence, reject non-public destinations, "
"and revalidate redirects or pin the outbound destination before delivery."
),
"storage": "Enforce storage or database access controls with authenticated ownership policies.",
}

Expand Down Expand Up @@ -101,6 +114,15 @@ def extract_public_references(message: str) -> tuple[str, ...]:
)


def _category_for_references(references: tuple[str, ...], fallback: str) -> str:
"""Prefer an authoritative public taxonomy over a rule-id heuristic."""
for reference in references:
for prefix, category in REFERENCE_CATEGORY_OVERRIDES.items():
if reference.startswith(prefix):
return category
return fallback


def build_rule_metadata(
rule_id: str,
severity: str,
Expand All @@ -110,8 +132,10 @@ def build_rule_metadata(
source: str = "appguardrail-rule",
) -> RuleMetadata:
"""Build a stable metadata envelope for a scanner finding."""
public_references = extract_public_references(message)
category = _category_for_references(public_references, category)
references = _merge_references(
extract_public_references(message),
public_references,
CATEGORY_REFERENCE_DEFAULTS.get(category, ()),
)
return RuleMetadata(
Expand Down
53 changes: 29 additions & 24 deletions scanner/cli/appguardrail.py
Original file line number Diff line number Diff line change
Expand Up @@ -1622,6 +1622,9 @@ def _is_safe_url(url: str) -> bool:
import socket
import urllib.parse

if not isinstance(url, str):
return False

try:
parsed = urllib.parse.urlparse(
url
Expand Down Expand Up @@ -1711,9 +1714,7 @@ def _push_findings(url, findings):

base_path = parsed.path.rstrip("/")
endpoint_path = f"{base_path}/api/v1/scans" if base_path else "/api/v1/scans"
endpoint = urllib.parse.urlunsplit(
("https", parsed.netloc, endpoint_path, "", "")
)
endpoint = urllib.parse.urlunsplit(("https", parsed.netloc, endpoint_path, "", ""))
payload = {
"findings": list(normalize_findings(findings)),
"repo": os.environ.get("GITHUB_REPOSITORY"),
Expand Down Expand Up @@ -2725,20 +2726,22 @@ def _run_semgrep_scan(scan_path: Path, config: str = "auto"):

config = config or "auto"
try:
process = subprocess.run( # noqa: S603 - Semgrep path resolved with shutil.which
[
semgrep,
"scan",
"--config",
config,
"--json",
str(scan_path),
],
shell=False,
capture_output=True,
text=True,
check=False,
timeout=600,
process = (
subprocess.run( # noqa: S603 - Semgrep path resolved with shutil.which
[
semgrep,
"scan",
"--config",
config,
"--json",
str(scan_path),
],
shell=False,
capture_output=True,
text=True,
check=False,
timeout=600,
)
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError("Semgrep scan timed out.") from exc
Expand Down Expand Up @@ -2805,13 +2808,15 @@ def _run_zap_baseline(target_url: str):
with tempfile.TemporaryDirectory() as tmpdir:
report_path = Path(tmpdir) / "zap-baseline.json"
try:
process = subprocess.run( # noqa: S603 - ZAP path resolved with shutil.which
[zap, "-t", target_url, "-J", str(report_path), "-I"],
shell=False,
capture_output=True,
text=True,
check=False,
timeout=900,
process = (
subprocess.run( # noqa: S603 - ZAP path resolved with shutil.which
[zap, "-t", target_url, "-J", str(report_path), "-I"],
shell=False,
capture_output=True,
text=True,
check=False,
timeout=900,
)
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError("ZAP baseline scan timed out.") from exc
Expand Down
13 changes: 13 additions & 0 deletions scanner/rules/ssrf.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
rules:
- id: python-stored-ssrf-webhook-url
patterns:
- pattern-regex: '(?is)(?:\bset_webhook\s*\(\s*[^,\n]+,\s*[^,\n]+,\s*(?:\([^\)\n]*\)|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)(?:\.get\s*\(\s*["\x27]url["\x27]\s*\)|\[\s*["\x27]url["\x27]\s*\])|\b(?P<webhook_url_var>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:\([^\)\n]*\)|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)(?:\.get\s*\(\s*["\x27]url["\x27]\s*\)|\[\s*["\x27]url["\x27]\s*\])(?!(?:(?!\bset_webhook\b).){0,800}(?m:^(?P<reject_indent>[ \t]*)if\b(?:(?!:).){0,600}\bnot\s+_is_safe_url\s*\(\s*(?P=webhook_url_var)\s*\)(?:(?!:).){0,100}:\s*(?:#[^\n]*)?\n(?:(?P=reject_indent)[ \t]+[^\n]*\n){0,20}?(?P=reject_indent)[ \t]+\b(?:return|raise)\b))(?!(?:(?!\bset_webhook\b).){0,800}(?m:^(?P<guard_indent>[ \t]*)if\s+(?:(?!\bnot\b)[^\n:]){0,400}_is_safe_url\s*\(\s*(?P=webhook_url_var)\s*\)[^\n:]{0,100}:\s*(?:#[^\n]*)?\n(?:(?P=guard_indent)[ \t]+[^\n]*\n){0,20}?(?P=guard_indent)[ \t]+\bset_webhook\s*\(\s*[^,\n]+,\s*[^,\n]+,\s*(?P=webhook_url_var)\s*\)))(?:(?!\bset_webhook\b).){0,800}?\bset_webhook\s*\(\s*[^,\n]+,\s*[^,\n]+,\s*(?P=webhook_url_var)\s*\))'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
message: |
A webhook URL is persisted directly from request data without an explicit
validation boundary. Validate the URL with a fail-closed SSRF policy before
storing it, and revalidate or pin the destination before outbound delivery.
[CWE-918 - Server-Side Request Forgery]
severity: HIGH
languages: [python]
cwe: [CWE-918]
owasp: [A10:2021]
9 changes: 9 additions & 0 deletions tests/test_controlplane.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,15 @@ def test_api_set_webhook(server):
assert status == 200 and body["webhook_url"] == "http://hook.example/y"


def test_api_set_webhook_unsafe_url(server):
base, key = server
with pytest.raises(urllib.error.HTTPError) as e:
_req("POST", f"{base}/api/v1/webhook", key, {"url": "http://127.0.0.1/"})
assert e.value.code == 400
body = json.loads(e.value.read())
assert body["error"] == "unsafe webhook url"


def test_roles_and_key_scoping():
conn = connect(":memory:")
oid, owner_key = create_org(conn, "Acme")
Expand Down
77 changes: 77 additions & 0 deletions tests/test_ssrf_rule_accessors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Regression tests for equivalent stored-SSRF request accessors."""

import pytest

from scanner.cli.appguardrail import SCAN_RULES, _scan_file

_RULE_ID = "python-stored-ssrf-webhook-url"


def _rule():
"""Return the packaged stored-SSRF rule under test."""
matches = [rule for rule in SCAN_RULES if rule["id"] == _RULE_ID]
assert len(matches) == 1
return matches[0]


def _source(accessor, *, direct=False, validated=False):
"""Build a direct or one-hop request URL persistence flow."""
sink = "set_" + "webhook"
if direct:
return "\n".join(
[
"def update_webhook(conn, org, body):",
f" {sink}(conn, org, {accessor})",
"",
]
)

lines = [
"def update_webhook(conn, org, body):",
f" target = {accessor}",
]
if validated:
lines.extend(
[
" if not _is_safe_url(target):",
" return",
]
)
lines.extend([f" {sink}(conn, org, target)", ""])
return "\n".join(lines)


@pytest.mark.parametrize(
"source",
[
_source('body["url"]', direct=True),
_source('request.json["url"]'),
_source('request.json.get("url")'),
],
)
def test_packaged_rule_matches_equivalent_request_url_accessors(source):
"""Detect direct, subscript, and attribute-based URL sources."""
assert _rule()["pattern"].search(source)


def test_scan_file_emits_finding_for_subscript_variable_flow(tmp_path):
"""Emit the stored-SSRF finding for a subscript one-hop flow."""
source_file = tmp_path / "webhook.py"
source_file.write_text(_source('body["url"]'), encoding="utf-8")

findings = [
finding
for finding in _scan_file(source_file, tmp_path)
if finding["rule_id"] == _RULE_ID
]

assert len(findings) == 1
assert findings[0]["line"] == 2
assert findings[0]["category"] == "ssrf"


def test_packaged_rule_ignores_validated_subscript_flow():
"""Do not flag a subscript source protected by a fail-closed guard."""
assert not _rule()["pattern"].search(
_source('body["url"]', validated=True)
)
Loading
Loading