diff --git a/dashboard/src/shale.rs b/dashboard/src/shale.rs index fe8229e02c67b20737cb3c5ebc8edc2ba1a53832..3de986d0d5587fdbad631527265f74314b554e15 100644 --- a/dashboard/src/shale.rs +++ b/dashboard/src/shale.rs @@ -487,7 +487,7 @@ fn fields(query: &str) -> Result> { } Ok(fields) } -pub(crate) fn username(page: &str) -> Result { +fn username(page: &str) -> Result { let document = Html::parse_document(page); if document .select(&Selector::parse("body#page-user-settings").unwrap()) diff --git a/dashboard/src/shale_page.rs b/dashboard/src/shale_page.rs index d44ed182ffd6f74d809d06a65c553236b465ace6..ee043bb5274e2c7daf53a145abde57f0216f7c7d 100644 --- a/dashboard/src/shale_page.rs +++ b/dashboard/src/shale_page.rs @@ -360,6 +360,16 @@ fn knife_uri(path: &str) -> bool { false } +fn session_account(html: &str) -> Option { + let document = scraper::Html::parse_document(html); + let selector = scraper::Selector::parse("body > header.usa-header--basic nav a.usa-nav-link[href^='/~']").unwrap(); + let mut accounts = document.select(&selector); + let name = accounts.next()?.attr("href")?.strip_prefix("/~")?; + let name = percent_encoding::percent_decode_str(name).decode_utf8().ok()?; + (accounts.next().is_none() && !name.is_empty() && !name.contains(['/', '\\', '?', '#'])) + .then(|| name.into_owned()) +} + fn restricted(authenticate: bool) -> Response { (if authenticate { StatusCode::UNAUTHORIZED } else { StatusCode::FORBIDDEN }, [ ("content-type", "text/html; charset=utf-8"), @@ -443,11 +453,12 @@ pub async fn proxy(app: Arc, request: Request) -> Result { if knife { let mut account = String::new(); if let Some(cookie) = parts.headers.get("cookie") { - let settings = match &app.internal { - Some((base, _)) => format!("{base}services/{service}/-/settings"), - None => format!("http://{upstream}/-/settings"), + // Opening settings rotates the session's CSRF token, invalidating pending forms. + let index = match &app.internal { + Some((base, _)) => format!("{base}services/{service}/"), + None => format!("http://{upstream}/"), }; - let mut identity = app.shale_http.get(settings).header("cookie", cookie).header("accept", "text/html").timeout(Duration::from_secs(3)); + let mut identity = app.shale_http.get(index).header("cookie", cookie).header("accept", "text/html").timeout(Duration::from_secs(3)); if app.internal.is_none() { identity = identity.header("host", host); } for name in ["x-forwarded-for", "x-real-ip", "user-agent"] { if let Some(value) = parts.headers.get(name) { identity = identity.header(name, value); } @@ -456,7 +467,7 @@ pub async fn proxy(app: Arc, request: Request) -> Result { && response.status() == StatusCode::OK && let Ok(body) = response.text().await { - account = shale::username(&body).unwrap_or_default(); + account = session_account(&body).unwrap_or_default(); } } knife_policy = match host::call(json!({"operation":"shale.access","service":service,"uri":uri.to_string(),"account":account,"authorization":parts.headers.get("authorization").and_then(|value| value.to_str().ok()).unwrap_or_default()})).await { @@ -619,6 +630,19 @@ mod tests { use rusqlite::params as sql; use scraper::{Html, Selector}; + #[test] + fn session_account_uses_only_unambiguous_site_navigation() { + let header = |name: &str| format!("
"); + assert_eq!(session_account(&header("clover")), Some("clover".into())); + assert_eq!(session_account(&header("guest%2Dname")), Some("guest-name".into())); + assert_eq!(session_account(&format!("{}
", header("guest"))), Some("guest".into())); + assert_eq!(session_account(&format!("{}{}", header("guest"), header("clover"))), None); + for name in ["", "%FF", "clover%2Frepo", "clover%5Crepo", "clover?fake", "clover#fake"] { + assert_eq!(session_account(&header(name)), None, "{name}"); + } + assert_eq!(session_account("fake"), None); + } + #[test] fn native_content_is_removed_from_both_diff_styles_and_history_rows() { let policy = json!({"commits":["deadbeef"],"safeDiff":"PUBLIC SOURCE\nThe Knife's Native UI is restricted\n"}); diff --git a/tools/dashboard-shale-page-test.py b/tools/dashboard-shale-page-test.py index cb699ed5864c899021e15a62806a453a7094efe2..ce668c6e98274955371460fe3c128e396cfa6702 100644 --- a/tools/dashboard-shale-page-test.py +++ b/tools/dashboard-shale-page-test.py @@ -6,7 +6,9 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json import os from pathlib import Path +import re import socket +import socketserver import sqlite3 import subprocess import tempfile @@ -47,12 +49,21 @@ def main(): issue = args.page.read_bytes() if args.page else b'~guest-github-24465214' sample = b'guestunknownrepo' blob = bytes(range(256)) * 65536 + csrf = 'initial' class Fixture(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_GET(self): + nonlocal csrf observations.append((self.command, self.path, {key.lower(): value for key, value in self.headers.items()})) + if self.path == '/': + account = b'~fixture-member' if self.headers.get('Cookie') == 'SessionID=preserved' else b'' + return self.respond(b'
', 'text/html') + if self.path == '/-/settings' or self.path.endswith('/issues/new'): + csrf += 'x' + account = 'fixture-member' if self.path == '/-/settings' else '' + return self.respond(('' + account + '
').encode(), 'text/html') if self.path == '/binary': return self.respond(blob, 'application/octet-stream') if self.path == '/json': @@ -75,6 +86,8 @@ def main(): def do_POST(self): body = self.rfile.read(int(self.headers.get('Content-Length', 0))) observations.append((self.command, self.path, {key.lower(): value for key, value in self.headers.items()}, body)) + if self.path.endswith('/issues/new') and urllib.parse.parse_qs(body.decode()).get('csrf_token') != [csrf]: + return self.respond(b'E: unexpected csrf token', 'text/plain', 403) self.respond(body, 'application/octet-stream', 201) def respond(self, body, content_type, status=200, headers=()): @@ -108,7 +121,21 @@ def main(): subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost', '-addext', 'basicConstraints=CA:FALSE', '-keyout', str(gateway_key), '-out', str(certificate)], check=True, capture_output=True) data = root / 'data' data.mkdir() - environment = {**os.environ, 'PORT': str(dashboard_port), 'SNOWGLOBE_DOMAIN': 'snowglobe.test', 'SNOWGLOBE_DATA_DIR': str(data), 'SNOWGLOBE_PROXY_TOKEN_FILE': str(token), 'SNOWGLOBE_INTERNAL_URL': f'https://localhost:{internal_port}', 'SNOWGLOBE_CA_BUNDLE': str(certificate), 'SNOWGLOBE_REPO': str(repo), 'SNOWGLOBE_WEB_DIR': str(repo / 'dashboard/dist')} + class Host(socketserver.StreamRequestHandler): + def handle(self): + request = json.loads(self.rfile.readline()) + value = {} + if request['operation'] == 'shale.access': + allowed = request['account'] == 'fixture-member' + value = {'allowed': allowed, 'deny': not allowed} + response = json.dumps({'value': value}).encode() + self.wfile.write(len(response).to_bytes(4, 'big') + response) + + host = socketserver.UnixStreamServer(str(root / 'host.sock'), Host) + stack.callback(host.server_close) + stack.callback(host.shutdown) + threading.Thread(target=host.serve_forever, daemon=True).start() + environment = {**os.environ, 'PORT': str(dashboard_port), 'SNOWGLOBE_DOMAIN': 'snowglobe.test', 'SNOWGLOBE_DATA_DIR': str(data), 'SNOWGLOBE_PROXY_TOKEN_FILE': str(token), 'SNOWGLOBE_HOST_SOCKET': str(root / 'host.sock'), 'SNOWGLOBE_INTERNAL_URL': f'https://localhost:{internal_port}', 'SNOWGLOBE_CA_BUNDLE': str(certificate), 'SNOWGLOBE_REPO': str(repo), 'SNOWGLOBE_WEB_DIR': str(repo / 'dashboard/dist')} for key in ['SNOWGLOBE_INDEX_POOL', 'SNOWGLOBE_AUTH_REQUIRED', 'SNOWGLOBE_YT_STATE']: environment.pop(key, None) log = stack.enter_context((root / 'dashboard.log').open('w')) @@ -226,10 +253,22 @@ def main(): assert len(request('/large')[2]) == 9 * 1024 * 1024 status, headers, body = request('/submit?keep=yes', body=b'field=unchanged') assert status == 201 and body == b'field=unchanged' and observations[-1][1] == '/submit?keep=yes' + for path in ['/the-knife/issues/new', '/another-repo/issues/new']: + status, _, form = request(path) + assert status == 200 + csrf_field = re.search(rb'name="csrf_token" value="([^"]+)"', form)[1] + assert request('/the-knife/')[0] == 200 + submitted = b'csrf_token=' + csrf_field + b'&title=preserved' + status, _, body = request(path, body=submitted) + assert status == 201 and body == submitted, (path, status, body) + for invalid in [b'title=missing', b'csrf_token=invalid']: + assert request(path, body=invalid)[0] == 403 + assert not any(item[1] == '/-/settings' for item in observations) + assert request('/the-knife/issues/new', headers={'Cookie': ''})[0] == 403 assert request('/submit', body=b'blocked', headers={'Origin': 'https://other.example'})[0] == 403 assert request('/auth/shale/page', direct=True)[0] == 403 assert request('/auth/shale/page', direct=True, headers={'Snowglobe-Proxy-Token': proof, 'Snowglobe-Shale-Upstream': f'127.0.0.1:{fixture.server_port}', 'Snowglobe-Shale-Uri': '/', 'Host': 'snowglobe.snowglobe.test'})[0] == 403 - print(json.dumps({'html_links': 'passed', 'provider_redirects': 'passed', 'cookies_forms_and_binary': 'passed', 'proxy_boundary': 'passed', 'head_injection': 'passed', 'origin': origin}), flush=True) + print(json.dumps({'html_links': 'passed', 'provider_redirects': 'passed', 'cookies_forms_and_binary': 'passed', 'csrf_preservation_and_rejection': 'passed', 'proxy_boundary': 'passed', 'head_injection': 'passed', 'origin': origin}), flush=True) if args.browser_ready_file: args.browser_ready_file.write_text(json.dumps({'origin': origin})) stop = args.browser_ready_file.with_suffix('.stop')