From 91afd32d151d4778826bc0a69e42cc5a095b7461 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:08:04 +0100 Subject: [PATCH] fix(dast): each browser tab gets its own browser context The pentest browser tool opened its tabs in Chrome's default context, so every pentest session on the same Chrome shared one cookie jar: one session's login was visible to the next. - New `cdp` module: one tab driven over CDP, created in its own browser context and disposed of with it on close. - The browser tool runs on it; its own copy of the CDP plumbing is gone. - `fill` no longer echoes the typed value back (it may be a password); it reports whether the field took it. - Test against a real Chrome (skipped without `CHROME_WS_URL`): a second tab does not see the first tab's cookie. It fails without the separate context. Refs #1000. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- compliance-dast/src/cdp.rs | 246 +++++++++++++++++++ compliance-dast/src/lib.rs | 1 + compliance-dast/src/tools/browser.rs | 341 ++++++--------------------- 3 files changed, 319 insertions(+), 269 deletions(-) create mode 100644 compliance-dast/src/cdp.rs diff --git a/compliance-dast/src/cdp.rs b/compliance-dast/src/cdp.rs new file mode 100644 index 0000000..2a75982 --- /dev/null +++ b/compliance-dast/src/cdp.rs @@ -0,0 +1,246 @@ +//! One Chrome tab driven over the Chrome DevTools Protocol (CDP). +//! +//! Each tab lives in its own browser context, Chrome's equivalent of a fresh +//! profile: its cookies and storage are invisible to every other tab, so one +//! scan's or pentest session's login never shows up in another's. + +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use tokio_tungstenite::tungstenite::Message; + +type WsStream = + tokio_tungstenite::WebSocketStream>; + +/// How long one CDP command may take to answer. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(30); + +/// A tab in its own browser context, closed with [`CdpTab::close`]. +pub(crate) struct CdpTab { + ws: WsStream, + next_id: u64, + session_id: String, + target_id: String, + context_id: String, +} + +impl CdpTab { + /// Open a blank tab in a new browser context of the Chrome at + /// `CHROME_WS_URL`, with the `Page` and `Runtime` domains on. + /// + /// # Errors + /// + /// Why Chrome cannot be reached or refused a command. + pub(crate) async fn open() -> Result { + let ws_url = std::env::var("CHROME_WS_URL").map_err(|_| { + "CHROME_WS_URL not set — headless Chrome is required for browser actions".to_string() + })?; + // `/json/version` names the browser's own WebSocket endpoint. + let http_url = ws_url + .replacen("ws://", "http://", 1) + .replacen("wss://", "https://", 1); + let version_url = format!("{}/json/version", http_url.trim_end_matches('/')); + let version: Value = reqwest::get(&version_url) + .await + .map_err(|e| format!("Cannot reach Chrome at {version_url}: {e}"))? + .json() + .await + .map_err(|e| format!("Invalid /json/version response: {e}"))?; + let browser_ws = version["webSocketDebuggerUrl"] + .as_str() + .ok_or_else(|| "No webSocketDebuggerUrl in /json/version".to_string())?; + let (ws, _) = tokio_tungstenite::connect_async(browser_ws) + .await + .map_err(|e| format!("WebSocket connect failed: {e}"))?; + + let mut tab = Self { + ws, + next_id: 1, + session_id: String::new(), + target_id: String::new(), + context_id: String::new(), + }; + let context = tab + .browser( + "Target.createBrowserContext", + json!({ "disposeOnDetach": true }), + ) + .await?; + tab.context_id = string_at(&context, "browserContextId")?; + let target = tab + .browser( + "Target.createTarget", + json!({ "url": "about:blank", "browserContextId": tab.context_id }), + ) + .await?; + tab.target_id = string_at(&target, "targetId")?; + let attached = tab + .browser( + "Target.attachToTarget", + json!({ "targetId": tab.target_id, "flatten": true }), + ) + .await?; + tab.session_id = string_at(&attached, "sessionId")?; + for domain in ["Page.enable", "Runtime.enable"] { + tab.call(domain, json!({})).await?; + } + Ok(tab) + } + + /// Send `method` to the tab and return the command's `result`. + /// + /// # Errors + /// + /// The CDP error, a broken connection, or no answer in time. + pub(crate) async fn call(&mut self, method: &str, params: Value) -> Result { + let message = json!({ + "id": self.next_id, + "sessionId": self.session_id, + "method": method, + "params": params, + }); + self.send(message).await + } + + /// Evaluate `expression` in the page and return its value as a string + /// (JSON for anything that is not a string; empty for `undefined`). + /// + /// # Errors + /// + /// As [`Self::call`]. + pub(crate) async fn evaluate(&mut self, expression: &str) -> Result { + let resp = self + .call( + "Runtime.evaluate", + json!({ "expression": expression, "returnByValue": true }), + ) + .await?; + Ok(match resp.get("result").and_then(|r| r.get("value")) { + Some(Value::String(s)) => s.clone(), + Some(v) => v.to_string(), + None => String::new(), + }) + } + + /// Close the tab and dispose of its browser context with every cookie in + /// it. Best effort: Chrome also disposes of the context when the + /// connection drops. + pub(crate) async fn close(&mut self) { + let _ = self + .browser("Target.closeTarget", json!({ "targetId": self.target_id })) + .await; + let _ = self + .browser( + "Target.disposeBrowserContext", + json!({ "browserContextId": self.context_id }), + ) + .await; + let _ = self.ws.close(None).await; + } + + /// Send `method` to the browser itself rather than the tab. + async fn browser(&mut self, method: &str, params: Value) -> Result { + let message = json!({ "id": self.next_id, "method": method, "params": params }); + self.send(message).await + } + + async fn send(&mut self, message: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + self.ws + .send(Message::Text(message.to_string().into())) + .await + .map_err(|e| format!("WS send failed: {e}"))?; + let deadline = tokio::time::Instant::now() + COMMAND_TIMEOUT; + loop { + let msg = tokio::time::timeout_at(deadline, self.ws.next()) + .await + .map_err(|_| format!("Timeout waiting for CDP response id={id}"))? + .ok_or_else(|| "WebSocket closed unexpectedly".to_string())? + .map_err(|e| format!("WebSocket read error: {e}"))?; + // Events and other commands' answers share the socket; skip them. + let Message::Text(text) = msg else { continue }; + let Ok(val) = serde_json::from_str::(&text) else { + continue; + }; + if val.get("id").and_then(Value::as_u64) != Some(id) { + continue; + } + if let Some(err) = val.get("error") { + return Err(format!("CDP error: {err}")); + } + return Ok(val.get("result").cloned().unwrap_or(Value::Null)); + } + } +} + +/// The string field `key` of a CDP result. +fn string_at(result: &Value, key: &str) -> Result { + result + .get(key) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| format!("No {key} in CDP response")) +} + +// Needs a real Chrome: set `CHROME_WS_URL` (e.g. `chromedp/headless-shell` +// on the host network). Without it the test passes without checking. +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::{Request, State}; + use axum::http::header::{COOKIE, SET_COOKIE}; + use axum::response::IntoResponse; + use axum::Router; + + use super::*; + + /// The `Cookie` header of every request the site saw. + type Seen = Arc>>>; + + /// A site that sets a cookie on every answer and records what came back. + async fn cookie_site(seen: Seen) -> String { + async fn any(State(seen): State, request: Request) -> impl IntoResponse { + let cookie = request + .headers() + .get(COOKIE) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + seen.lock().unwrap().push(cookie); + ([(SET_COOKIE, "visited=1; Path=/")], "") + } + let app = Router::new().fallback(any).with_state(seen); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}/") + } + + #[tokio::test] + async fn tabs_do_not_share_cookies() { + if std::env::var("CHROME_WS_URL").is_err() { + return; + } + let seen: Seen = Arc::default(); + let site = cookie_site(seen.clone()).await; + + let mut first = CdpTab::open().await.unwrap(); + let mut second = CdpTab::open().await.unwrap(); + let navigate = json!({ "url": site }); + first.call("Page.navigate", navigate.clone()).await.unwrap(); + first.call("Page.navigate", navigate.clone()).await.unwrap(); + second.call("Page.navigate", navigate).await.unwrap(); + first.close().await; + second.close().await; + + let seen = seen.lock().unwrap().clone(); + assert_eq!( + seen, + [None, Some("visited=1".to_string()), None], + "the first tab keeps its cookie, the second never sees it" + ); + } +} diff --git a/compliance-dast/src/lib.rs b/compliance-dast/src/lib.rs index 79a69f9..ec7a6c0 100644 --- a/compliance-dast/src/lib.rs +++ b/compliance-dast/src/lib.rs @@ -1,5 +1,6 @@ pub mod agents; pub mod auth; +mod cdp; pub mod crawler; pub mod orchestrator; pub mod recon; diff --git a/compliance-dast/src/tools/browser.rs b/compliance-dast/src/tools/browser.rs index 9dd4e3b..f4ceb4b 100644 --- a/compliance-dast/src/tools/browser.rs +++ b/compliance-dast/src/tools/browser.rs @@ -6,14 +6,11 @@ use std::time::Duration; use base64::Engine; use compliance_core::error::CoreError; use compliance_core::traits::pentest_tool::{PentestTool, PentestToolContext, PentestToolResult}; -use futures_util::{SinkExt, StreamExt}; use serde_json::json; use tokio::sync::Mutex; -use tokio_tungstenite::tungstenite::Message; use tracing::info; -type WsStream = - tokio_tungstenite::WebSocketStream>; +use crate::cdp::CdpTab; /// Global pool of persistent browser sessions keyed by pentest session ID. /// Each pentest session gets one Chrome tab that stays alive across tool calls. @@ -102,7 +99,7 @@ impl PentestTool for BrowserTool { if action == "close" { let mut pool = BROWSER_SESSIONS.lock().await; if let Some(mut sess) = pool.remove(&session_key) { - let _ = sess.close().await; + sess.close().await; } return Ok(PentestToolResult { summary: "Browser session closed".to_string(), @@ -142,7 +139,7 @@ impl PentestTool for BrowserTool { // If the session errored, remove it so the next call creates a fresh one if result.is_err() { if let Some(mut dead) = pool.remove(&session_key) { - let _ = dead.close().await; + dead.close().await; } } @@ -176,114 +173,35 @@ impl PentestTool for BrowserTool { }) } } - -/// A single CDP session wrapping a browser tab. +/// The pentest tool's tab: a [`CdpTab`] plus the actions the LLM may take. struct BrowserSession { - ws: WsStream, - next_id: u64, - session_id: String, - target_id: String, + tab: CdpTab, } impl BrowserSession { - /// Connect to headless Chrome and create a new tab. + /// Open a tab in its own browser context, so this pentest session sees + /// no other session's cookies. async fn connect() -> Result { - let ws_url = std::env::var("CHROME_WS_URL").map_err(|_| { - "CHROME_WS_URL not set — headless Chrome is required for browser actions".to_string() - })?; - - // Discover browser WS endpoint - let http_url = ws_url - .replace("ws://", "http://") - .replace("wss://", "https://"); - let version_url = format!("{http_url}/json/version"); - - let version: serde_json::Value = reqwest::get(&version_url) - .await - .map_err(|e| format!("Cannot reach Chrome at {version_url}: {e}"))? - .json() - .await - .map_err(|e| format!("Invalid /json/version response: {e}"))?; - - let browser_ws = version["webSocketDebuggerUrl"] - .as_str() - .ok_or_else(|| "No webSocketDebuggerUrl in /json/version".to_string())?; - - let (mut ws, _) = tokio_tungstenite::connect_async(browser_ws) - .await - .map_err(|e| format!("WebSocket connect failed: {e}"))?; - - let mut next_id: u64 = 1; - - // Create tab - let resp = cdp_send( - &mut ws, - next_id, - "Target.createTarget", - json!({ "url": "about:blank" }), - ) - .await?; - next_id += 1; - - let target_id = resp - .get("result") - .and_then(|r| r.get("targetId")) - .and_then(|t| t.as_str()) - .ok_or("No targetId in createTarget response")? - .to_string(); - - // Attach - let resp = cdp_send( - &mut ws, - next_id, - "Target.attachToTarget", - json!({ "targetId": target_id, "flatten": true }), - ) - .await?; - next_id += 1; - - let session_id = resp - .get("result") - .and_then(|r| r.get("sessionId")) - .and_then(|s| s.as_str()) - .ok_or("No sessionId in attachToTarget response")? - .to_string(); - - // Enable domains - cdp_send_session(&mut ws, next_id, &session_id, "Page.enable", json!({})).await?; - next_id += 1; - - cdp_send_session(&mut ws, next_id, &session_id, "Runtime.enable", json!({})).await?; - next_id += 1; - Ok(Self { - ws, - next_id, - session_id, - target_id, + tab: CdpTab::open().await?, }) } async fn navigate(&mut self, url: &str, wait_ms: u64) -> Result { - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Page.navigate", - json!({ "url": url }), - ) - .await?; - self.next_id += 1; - + self.tab + .call("Page.navigate", json!({ "url": url })) + .await?; tokio::time::sleep(Duration::from_millis(wait_ms)).await; // Get page title and current URL (may have redirected) let title = self - .evaluate_raw("document.title") + .tab + .evaluate("document.title") .await .unwrap_or_default(); let page_url = self - .evaluate_raw("window.location.href") + .tab + .evaluate("window.location.href") .await .unwrap_or_default(); @@ -298,7 +216,7 @@ impl BrowserSession { }); return JSON.stringify(items); })()"#; - let elements_json = self.evaluate_raw(links_js).await.unwrap_or_default(); + let elements_json = self.tab.evaluate(links_js).await.unwrap_or_default(); let elements: serde_json::Value = serde_json::from_str(&elements_json).unwrap_or(json!([])); // Auto-capture screenshot after every navigation @@ -315,19 +233,15 @@ impl BrowserSession { /// Capture a screenshot and return the base64 string (empty on failure). async fn capture_screenshot_b64(&mut self) -> Result { - let resp = cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Page.captureScreenshot", - json!({ "format": "png", "quality": 80 }), - ) - .await?; - self.next_id += 1; - + let resp = self + .tab + .call( + "Page.captureScreenshot", + json!({ "format": "png", "quality": 80 }), + ) + .await?; Ok(resp - .get("result") - .and_then(|r| r.get("data")) + .get("data") .and_then(|d| d.as_str()) .unwrap_or("") .to_string()) @@ -366,16 +280,18 @@ impl BrowserSession { raw = selector.replace('"', r#"\""#), ); - let result = self.evaluate_raw(&js).await?; + let result = self.tab.evaluate(&js).await?; tokio::time::sleep(Duration::from_millis(wait_ms)).await; // After click, get current URL (may have navigated) let current_url = self - .evaluate_raw("window.location.href") + .tab + .evaluate("window.location.href") .await .unwrap_or_default(); let title = self - .evaluate_raw("document.title") + .tab + .evaluate("document.title") .await .unwrap_or_default(); @@ -400,89 +316,36 @@ impl BrowserSession { value: &str, wait_ms: u64, ) -> Result { - // Step 1: Focus the element via JS - let focus_js = format!( - "(function(){{var e=document.querySelector({sel});\ - if(!e)return 'notfound';e.focus();e.select();return 'ok'}})()", - sel = serde_json::to_string(selector).unwrap_or_default(), - ); - let found = self.evaluate_raw(&focus_js).await?; - if found == "notfound" { + if !type_into(&mut self.tab, selector, value).await? { return Ok(json!({ "error": format!("Element not found: {selector}") })); } - // Step 2: Clear existing content with Select All + Delete - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Input.dispatchKeyEvent", - json!({"type": "keyDown", "key": "a", "code": "KeyA", "modifiers": 2}), - ) - .await?; - self.next_id += 1; - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Input.dispatchKeyEvent", - json!({"type": "keyUp", "key": "a", "code": "KeyA", "modifiers": 2}), - ) - .await?; - self.next_id += 1; - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Input.dispatchKeyEvent", - json!({"type": "keyDown", "key": "Backspace", "code": "Backspace"}), - ) - .await?; - self.next_id += 1; - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Input.dispatchKeyEvent", - json!({"type": "keyUp", "key": "Backspace", "code": "Backspace"}), - ) - .await?; - self.next_id += 1; - - // Step 3: Insert the text using Input.insertText (single CDP command, no JS eval) - cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Input.insertText", - json!({"text": value}), - ) - .await?; - self.next_id += 1; - - // Step 4: Verify the value was set + // Whether the field now holds the value; the value itself stays out + // of the result, since it may be a password. let verify_js = format!( - "(function(){{var e=document.querySelector({sel});return e?e.value:''}})()", + "(function(){{var e=document.querySelector({sel});return e?e.value.length:-1}})()", sel = serde_json::to_string(selector).unwrap_or_default(), ); - let final_value = self.evaluate_raw(&verify_js).await.unwrap_or_default(); + let length = self.tab.evaluate(&verify_js).await.unwrap_or_default(); tokio::time::sleep(Duration::from_millis(wait_ms)).await; Ok(json!({ "filled": true, "selector": selector, - "value": final_value, + "value_set": length == value.chars().count().to_string(), })) } async fn get_content(&mut self) -> Result { let title = self - .evaluate_raw("document.title") + .tab + .evaluate("document.title") .await .unwrap_or_default(); let url = self - .evaluate_raw("window.location.href") + .tab + .evaluate("window.location.href") .await .unwrap_or_default(); @@ -528,7 +391,7 @@ impl BrowserSession { return JSON.stringify(result); })()"#; - let summary = self.evaluate_raw(summary_js).await.unwrap_or_default(); + let summary = self.tab.evaluate(summary_js).await.unwrap_or_default(); let page_data: serde_json::Value = serde_json::from_str(&summary).unwrap_or(json!({})); Ok(json!({ @@ -539,49 +402,14 @@ impl BrowserSession { } async fn evaluate(&mut self, expression: &str) -> Result { - let result = self.evaluate_raw(expression).await?; + let result = self.tab.evaluate(expression).await?; Ok(json!({ "result": result, })) } - /// Execute JS and return the string result. - async fn evaluate_raw(&mut self, expression: &str) -> Result { - let resp = cdp_send_session( - &mut self.ws, - self.next_id, - &self.session_id, - "Runtime.evaluate", - json!({ - "expression": expression, - "returnByValue": true, - }), - ) - .await?; - self.next_id += 1; - - let result = resp - .get("result") - .and_then(|r| r.get("result")) - .and_then(|r| r.get("value")); - - match result { - Some(serde_json::Value::String(s)) => Ok(s.clone()), - Some(v) => Ok(v.to_string()), - None => Ok(String::new()), - } - } - - async fn close(&mut self) -> Result<(), String> { - let _ = cdp_send( - &mut self.ws, - self.next_id, - "Target.closeTarget", - json!({ "targetId": self.target_id }), - ) - .await; - let _ = self.ws.close(None).await; - Ok(()) + async fn close(&mut self) { + self.tab.close().await; } } @@ -589,62 +417,37 @@ impl BrowserSession { pub async fn cleanup_browser_session(session_id: &str) { let mut pool = BROWSER_SESSIONS.lock().await; if let Some(mut sess) = pool.remove(session_id) { - let _ = sess.close().await; + sess.close().await; } } -// ── CDP helpers ── - -async fn cdp_send( - ws: &mut WsStream, - id: u64, - method: &str, - params: serde_json::Value, -) -> Result { - let msg = json!({ "id": id, "method": method, "params": params }); - ws.send(Message::Text(msg.to_string().into())) - .await - .map_err(|e| format!("WS send failed: {e}"))?; - read_until_result(ws, id).await -} - -async fn cdp_send_session( - ws: &mut WsStream, - id: u64, - session_id: &str, - method: &str, - params: serde_json::Value, -) -> Result { - let msg = json!({ - "id": id, - "sessionId": session_id, - "method": method, - "params": params, - }); - ws.send(Message::Text(msg.to_string().into())) - .await - .map_err(|e| format!("WS send failed: {e}"))?; - read_until_result(ws, id).await -} - -async fn read_until_result(ws: &mut WsStream, id: u64) -> Result { - let deadline = tokio::time::Instant::now() + Duration::from_secs(30); - loop { - let msg = tokio::time::timeout_at(deadline, ws.next()) - .await - .map_err(|_| format!("Timeout waiting for CDP response id={id}"))? - .ok_or_else(|| "WebSocket closed unexpectedly".to_string())? - .map_err(|e| format!("WebSocket read error: {e}"))?; - - if let Message::Text(text) = msg { - if let Ok(val) = serde_json::from_str::(&text) { - if val.get("id").and_then(|i| i.as_u64()) == Some(id) { - if let Some(err) = val.get("error") { - return Err(format!("CDP error: {err}")); - } - return Ok(val); - } - } - } +/// Replace the content of the field at `selector` with `text`, typed through +/// CDP input events: `text` never becomes part of a script, so a password +/// cannot leak through one. `false` when no element matches. +/// +/// # Errors +/// +/// A CDP command failed. +async fn type_into(tab: &mut CdpTab, selector: &str, text: &str) -> Result { + let focus_js = format!( + "(function(){{var e=document.querySelector({sel});\ + if(!e)return 'notfound';e.focus();if(e.select)e.select();return 'ok'}})()", + sel = serde_json::to_string(selector).unwrap_or_default(), + ); + if tab.evaluate(&focus_js).await? == "notfound" { + return Ok(false); } + // Select all (Ctrl+A) and delete, then insert the text in one command. + let keys = [ + json!({"type": "keyDown", "key": "a", "code": "KeyA", "modifiers": 2}), + json!({"type": "keyUp", "key": "a", "code": "KeyA", "modifiers": 2}), + json!({"type": "keyDown", "key": "Backspace", "code": "Backspace"}), + json!({"type": "keyUp", "key": "Backspace", "code": "Backspace"}), + ]; + for key in keys { + tab.call("Input.dispatchKeyEvent", key).await?; + } + tab.call("Input.insertText", json!({ "text": text })) + .await?; + Ok(true) }