mirror of
https://github.com/BigBodyCobain/Shadowbroker.git
synced 2026-12-05 09:03:39 +01:00
Merge pull request #760 from BigBodyCobain/fix/infonet-join-no-login
Infonet join without admin login; fix Docker same-origin check
This commit is contained in:
6 files changed
+276
-4
No files matched your search
@@ -420,6 +420,48 @@ def is_local_operator_request(request: Request) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The operator's own client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
OPERATOR_CLIENT_HEADER = "X-SB-Operator-Client"
|
||||
_OPERATOR_CLIENT_CONTEXT = b"shadowbroker-operator-client-v1"
|
||||
|
||||
|
||||
def operator_client_token(admin_key: str | None = None) -> str:
|
||||
"""The credential the web UI's server-side proxy presents for the
|
||||
operator's own browser.
|
||||
|
||||
It is an HMAC of the admin key, so the proxy can vouch for its own UI
|
||||
without handing the admin key to a browser that has not logged in, and
|
||||
the token cannot be turned back into the key. It never grants admin
|
||||
controls: only routes guarded by ``require_operator_client`` accept it.
|
||||
Empty when no admin key is configured."""
|
||||
key = str(admin_key if admin_key is not None else _current_admin_key() or "").strip()
|
||||
if not key:
|
||||
return ""
|
||||
return hmac.new(key.encode("utf-8"), _OPERATOR_CLIENT_CONTEXT, _hashlib_mod.sha256).hexdigest()
|
||||
|
||||
|
||||
def _presents_operator_client_token(request: Request) -> bool:
|
||||
expected = operator_client_token()
|
||||
presented = str(request.headers.get(OPERATOR_CLIENT_HEADER, "") or "").strip()
|
||||
if not expected or not presented:
|
||||
return False
|
||||
return hmac.compare_digest(presented.encode(), expected.encode())
|
||||
|
||||
|
||||
def require_operator_client(request: Request):
|
||||
"""The operator's own client: the admin key, or the token the web UI's
|
||||
proxy presents (``operator_client_token``). Guards participation routes
|
||||
the UI uses without an admin-key login, such as joining Infonet. A caller
|
||||
that reaches the backend directly (LAN, or the onion service, which maps
|
||||
to the backend port) has no token and still needs the admin key."""
|
||||
if operator_origin_allowed(request) and _presents_operator_client_token(request):
|
||||
return
|
||||
require_local_operator(request)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenClaw HMAC authentication
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -13,6 +13,7 @@ from auth import (
|
||||
_strong_claims_policy_snapshot,
|
||||
require_admin,
|
||||
require_local_operator,
|
||||
require_operator_client,
|
||||
)
|
||||
from limiter import limiter
|
||||
|
||||
@@ -622,7 +623,7 @@ async def api_get_wormhole_status(request: Request):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/wormhole/join", dependencies=[Depends(require_local_operator)])
|
||||
@router.post("/api/wormhole/join", dependencies=[Depends(require_operator_client)])
|
||||
@limiter.limit("10/minute")
|
||||
async def api_wormhole_join(request: Request):
|
||||
from services.config import get_settings
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""The operator's own UI can join Infonet without an admin-key login.
|
||||
|
||||
The frontend proxy presents an HMAC of the admin key in X-SB-Operator-Client.
|
||||
The backend accepts that token only where require_operator_client is used,
|
||||
and a missing or wrong token still falls back to the admin-key check.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import auth
|
||||
|
||||
ADMIN_KEY = "test-admin-key-for-operator-client"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setattr(auth, "_current_admin_key", lambda: ADMIN_KEY)
|
||||
app = FastAPI()
|
||||
|
||||
@app.post("/join", dependencies=[Depends(auth.require_operator_client)])
|
||||
def join():
|
||||
return {"ok": True}
|
||||
|
||||
@app.post("/admin-only", dependencies=[Depends(auth.require_local_operator)])
|
||||
def admin_only():
|
||||
return {"ok": True}
|
||||
|
||||
return TestClient(app, client=("203.0.113.9", 50000))
|
||||
|
||||
|
||||
def _expected_token() -> str:
|
||||
return hmac.new(ADMIN_KEY.encode(), b"shadowbroker-operator-client-v1", hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def test_token_matches_the_proxy_formula():
|
||||
assert auth.operator_client_token(ADMIN_KEY) == _expected_token()
|
||||
|
||||
|
||||
def test_no_token_and_no_key_is_refused(client):
|
||||
assert client.post("/join").status_code == 403
|
||||
|
||||
|
||||
def test_wrong_token_is_refused(client):
|
||||
resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: "0" * 64})
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_proxy_token_is_accepted(client):
|
||||
resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()})
|
||||
assert resp.status_code == 200
|
||||
|
||||
|
||||
def test_admin_key_still_works(client):
|
||||
assert client.post("/join", headers={"X-Admin-Key": ADMIN_KEY}).status_code == 200
|
||||
|
||||
|
||||
def test_token_is_refused_from_a_foreign_origin(client):
|
||||
resp = client.post(
|
||||
"/join",
|
||||
headers={
|
||||
auth.OPERATOR_CLIENT_HEADER: _expected_token(),
|
||||
"Origin": "https://evil.example",
|
||||
"Sec-Fetch-Site": "cross-site",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_token_does_not_unlock_admin_routes(client):
|
||||
resp = client.post("/admin-only", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()})
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_no_token_without_an_admin_key(monkeypatch):
|
||||
monkeypatch.setattr(auth, "_current_admin_key", lambda: "")
|
||||
assert auth.operator_client_token() == ""
|
||||
|
||||
|
||||
def test_join_route_uses_the_operator_client_check():
|
||||
from routers import wormhole
|
||||
|
||||
route = next(r for r in wormhole.router.routes if getattr(r, "path", "") == "/api/wormhole/join")
|
||||
calls = {d.call for d in route.dependant.dependencies}
|
||||
assert auth.require_operator_client in calls
|
||||
@@ -0,0 +1,58 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { POST } from '@/app/api/[...path]/route';
|
||||
import { isAllowedBrowserRequest, requestOwnOrigin } from '@/lib/requestOrigin';
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
|
||||
// The Docker image runs the standalone server with HOSTNAME=0.0.0.0, so the
|
||||
// server's own URL is http://0.0.0.0:3000 while the browser is on
|
||||
// http://localhost:3000 (or the node's LAN name).
|
||||
const DOCKER_URL = 'http://0.0.0.0:3000/api/wormhole/join';
|
||||
|
||||
function dockerRequest(host: string, origin: string, site = 'same-origin') {
|
||||
return new NextRequest(DOCKER_URL, {
|
||||
method: 'POST',
|
||||
headers: { host, origin, 'sec-fetch-site': site, 'content-type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
}
|
||||
|
||||
describe('same-origin check behind a 0.0.0.0 bind', () => {
|
||||
it('uses the Host the browser connected to', () => {
|
||||
expect(requestOwnOrigin(dockerRequest('localhost:3000', 'http://localhost:3000'))).toBe('http://localhost:3000');
|
||||
});
|
||||
|
||||
it.each(['localhost:3000', '127.0.0.1:3000', 'mynode.lan:3000', '[::1]:3000'])('allows the UI served from %s', (host) => {
|
||||
expect(isAllowedBrowserRequest(dockerRequest(host, 'http://' + host))).toBe(true);
|
||||
});
|
||||
|
||||
it('still denies a foreign page', () => {
|
||||
expect(isAllowedBrowserRequest(dockerRequest('localhost:3000', 'https://attacker.example', 'cross-site'))).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores a malformed Host header', () => {
|
||||
expect(requestOwnOrigin(dockerRequest('evil.example/x', 'http://localhost:3000'))).toBe('http://0.0.0.0:3000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('operator-client token behind a 0.0.0.0 bind', () => {
|
||||
async function forwardedToken(host: string) {
|
||||
vi.stubEnv('ADMIN_KEY', 'docker-origin-test-key');
|
||||
const upstream = vi.fn().mockResolvedValue(new Response('{}'));
|
||||
vi.stubGlobal('fetch', upstream);
|
||||
const res = await POST(dockerRequest(host, 'http://' + host), {
|
||||
params: Promise.resolve({ path: ['wormhole', 'join'] }),
|
||||
});
|
||||
expect(res.status).not.toBe(403);
|
||||
return new Headers(upstream.mock.calls[0][1].headers).get('x-sb-operator-client');
|
||||
}
|
||||
|
||||
it('is sent when the browser is on localhost', async () => {
|
||||
expect(await forwardedToken('localhost:3000')).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it('is not sent for a public DNS name pointed at the node', async () => {
|
||||
expect(await forwardedToken('rebind.attacker.example:3000')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -10,10 +10,12 @@
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createHmac } from 'crypto';
|
||||
import { isIP } from 'net';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { resolveAdminSessionToken, verifyPresentedAdminKey } from '@/lib/server/adminSessionStore';
|
||||
import { isAllowedBrowserRequest } from '@/lib/requestOrigin';
|
||||
import { isAllowedBrowserRequest, requestOwnOrigin } from '@/lib/requestOrigin';
|
||||
import { readRequestBody, RequestBodyTooLarge } from '@/lib/server/requestBody';
|
||||
|
||||
// Headers that must not be forwarded to the backend.
|
||||
@@ -23,6 +25,7 @@ const STRIP_REQUEST = new Set([
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'x-admin-key',
|
||||
'x-sb-operator-client',
|
||||
'te',
|
||||
'trailers',
|
||||
'transfer-encoding',
|
||||
@@ -95,6 +98,63 @@ function isSensitiveProxyPath(pathSegments: string[]): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Token that tells the backend a request came through this proxy from the
|
||||
* operator's own UI (mirrors backend/auth.py operator_client_token). It is an
|
||||
* HMAC of the admin key, so the proxy can vouch for its own UI without giving
|
||||
* the admin key to a browser that has not logged in. The backend accepts it
|
||||
* only on routes the operator's UI needs before login (joining Infonet),
|
||||
* never for admin controls. A caller that reaches the backend directly is
|
||||
* still a stranger.
|
||||
*/
|
||||
let operatorClientCache: { key: string; token: string } | null = null;
|
||||
function operatorClientToken(): string {
|
||||
const key = String(process.env.ADMIN_KEY || '').trim();
|
||||
if (!key) return '';
|
||||
if (operatorClientCache?.key !== key) {
|
||||
operatorClientCache = {
|
||||
key,
|
||||
token: createHmac('sha256', key).update('shadowbroker-operator-client-v1').digest('hex'),
|
||||
};
|
||||
}
|
||||
return operatorClientCache.token;
|
||||
}
|
||||
|
||||
const LOCAL_HOST_SUFFIXES = ['.localhost', '.local', '.lan', '.internal', '.home.arpa', '.ts.net'];
|
||||
|
||||
/**
|
||||
* A web page on someone else's domain can point that domain at this machine
|
||||
* (DNS rebinding) and pass a same-origin check. Names like that are public
|
||||
* DNS names; the names people use to reach their own node are IPs,
|
||||
* localhost, single-label or LAN names, a Tailscale name, or a reverse-proxy
|
||||
* name they configured. Only those get the operator-client token.
|
||||
*/
|
||||
function hostIsOperatorReachable(req: NextRequest): boolean {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(requestOwnOrigin(req)).hostname.toLowerCase();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
host = host.replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
||||
if (!host) return false;
|
||||
if (host === 'localhost' || isIP(host)) return true;
|
||||
if (!host.includes('.') || LOCAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) return true;
|
||||
const configured = [
|
||||
...(process.env.SHADOWBROKER_ALLOWED_ORIGINS || '').split(','),
|
||||
...(process.env.SHADOWBROKER_TRUSTED_FRONTEND_HOSTS || '').split(','),
|
||||
];
|
||||
return configured.some((value) => {
|
||||
const entry = value.trim().toLowerCase();
|
||||
if (!entry) return false;
|
||||
try {
|
||||
return (entry.includes('://') ? new URL(entry).hostname : entry) === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function proxy(req: NextRequest, pathSegments: string[]): Promise<NextResponse> {
|
||||
try {
|
||||
if (!isAllowedBrowserRequest(req)) {
|
||||
@@ -217,6 +277,8 @@ async function proxy(req: NextRequest, pathSegments: string[]): Promise<NextResp
|
||||
if (authenticatedKey && (isSensitiveProxyPath(pathSegments) || isSensitiveMeshPath)) {
|
||||
forwardHeaders.set('X-Admin-Key', authenticatedKey);
|
||||
}
|
||||
const clientToken = hostIsOperatorReachable(req) ? operatorClientToken() : '';
|
||||
if (clientToken) forwardHeaders.set('X-SB-Operator-Client', clientToken);
|
||||
|
||||
const isBodyless = req.method === 'GET' || req.method === 'HEAD';
|
||||
let upstream: Response | null = null;
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
const HOST_HEADER = /^[a-z0-9.-]+(:\d{1,5})?$|^\[[0-9a-f:.]+\](:\d{1,5})?$/i;
|
||||
|
||||
/**
|
||||
* The origin the browser used to reach this server. The Host header comes
|
||||
* from the browser and a cross-site page cannot set it. nextUrl.origin is
|
||||
* not enough: a standalone server bound with HOSTNAME=0.0.0.0 (the Docker
|
||||
* image) reports http://0.0.0.0:3000 there, so every browser POST from
|
||||
* http://localhost:3000 looked cross-origin.
|
||||
*/
|
||||
export function requestOwnOrigin(request: NextRequest): string {
|
||||
const host = (request.headers.get('host') || '').trim();
|
||||
if (host && HOST_HEADER.test(host)) {
|
||||
try {
|
||||
return new URL((request.nextUrl.protocol || 'http:') + '//' + host).origin;
|
||||
} catch {
|
||||
// fall back to the server's own idea of its origin
|
||||
}
|
||||
}
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
export function isAllowedBrowserRequest(request: NextRequest): boolean {
|
||||
const site = (request.headers.get('sec-fetch-site') || '').toLowerCase();
|
||||
const origin = request.headers.get('origin');
|
||||
@@ -10,8 +31,7 @@ export function isAllowedBrowserRequest(request: NextRequest): boolean {
|
||||
return false;
|
||||
}
|
||||
if (source.href !== source.origin + '/' && source.href !== source.origin) return false;
|
||||
const ownOrigin = request.nextUrl.origin ||
|
||||
new URL('http://' + request.headers.get('host')).origin;
|
||||
const ownOrigin = requestOwnOrigin(request);
|
||||
const allowed = (process.env.SHADOWBROKER_ALLOWED_ORIGINS || '').split(',')
|
||||
.map((value) => value.trim()).filter(Boolean);
|
||||
// Public reverse-proxy origins must be configured; forwarding headers are untrusted.
|
||||
|
||||
Reference in new issue
Block a user