Skip to content

Truly independent web browser

LibWebCommon: Reject requests from web pages to the WebDriver endpoint

Andreas Kling4ac6ad959824
diff --git a/Libraries/LibWebCommon/WebDriver/Client.cpp b/Libraries/LibWebCommon/WebDriver/Client.cpp
index ec57b988118..6b6d18f4eb0 100644
--- a/Libraries/LibWebCommon/WebDriver/Client.cpp
+++ b/Libraries/LibWebCommon/WebDriver/Client.cpp
@@ -11,6 +11,8 @@
#include <AK/ByteBuffer.h>
#include <AK/Debug.h>
#include <AK/Format.h>
+#include <AK/IPv4Address.h>
+#include <AK/IPv6Address.h>
#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
#include <AK/Span.h>
@@ -187,6 +189,56 @@ static JsonValue make_success_response(JsonValue value)
return result;
}
+// NB: A page using DNS rebinding sends a Host header with its own domain name, which resolves to the local machine. A
+// WebDriver client names the listener by IP address, or as localhost.
+static bool is_allowed_host(StringView host)
+{
+ if (host.starts_with('[')) {
+ auto closing_bracket = host.find(']');
+ if (!closing_bracket.has_value())
+ return false;
+ auto rest = host.substring_view(*closing_bracket + 1);
+ if (!rest.is_empty() && !rest.starts_with(':'))
+ return false;
+ return IPv6Address::from_string(host.substring_view(1, *closing_bracket - 1)).has_value();
+ }
+
+ if (auto colon = host.find_last(':'); colon.has_value())
+ host = host.substring_view(0, *colon);
+ return host.equals_ignoring_ascii_case("localhost"sv) || IPv4Address::from_string(host).has_value();
+}
+
+static Optional<StringView> find_header(HTTP::HttpRequest const& request, StringView name)
+{
+ if (auto it = request.headers().headers().find_if([&](auto& header) { return header.name.equals_ignoring_ascii_case(name); }); !it.is_end())
+ return it->value.view();
+ return {};
+}
+
+// NB: The WebDriver endpoint controls the browser without authentication, so web pages must not reach it.
+static ErrorOr<void, Error> reject_requests_from_web_pages(HTTP::HttpRequest const& request)
+{
+ auto host = find_header(request, "Host"sv);
+ if (!host.has_value() || !is_allowed_host(host->trim_whitespace()))
+ return Error { 403, "unknown error"_string, "The Host header does not name the local machine"_string, {} };
+
+ // A browser sends Origin with every request a page makes, except for a same-origin GET or HEAD, which a page can
+ // only make to WebDriver through DNS rebinding.
+ if (find_header(request, "Origin"sv).has_value())
+ return Error { 403, "unknown error"_string, "Requests from web pages are not allowed"_string, {} };
+
+ // A page can send a request with a CORS-safelisted Content-Type without a CORS preflight.
+ if (auto content_type = find_header(request, "Content-Type"sv); content_type.has_value()) {
+ auto essence = content_type->find_first_split_view(';').trim_whitespace();
+ if (essence.equals_ignoring_ascii_case("application/x-www-form-urlencoded"sv)
+ || essence.equals_ignoring_ascii_case("multipart/form-data"sv)
+ || essence.equals_ignoring_ascii_case("text/plain"sv))
+ return Error { 415, "unknown error"_string, "The Content-Type of the request is not allowed"_string, {} };
+ }
+
+ return {};
+}
+
static bool is_keep_alive_request(HTTP::HttpRequest const& request)
{
if (auto it = request.headers().headers().find_if([](auto& header) { return header.name.equals_ignoring_ascii_case("Connection"sv); }); !it.is_end())
@@ -277,6 +329,12 @@ void Client::process_next_pending_request()
return;
auto pending_request = this_ref->m_pending_requests.head();
+ if (auto result = reject_requests_from_web_pages(pending_request->http_request); result.is_error()) {
+ this_ref->handle_error(pending_request->http_request, result.release_error());
+ this_ref->dequeue_current_pending_request();
+ return;
+ }
+
auto body = read_body_as_json(pending_request->http_request);
if (body.is_error()) {
this_ref->handle_error(pending_request->http_request, body.release_error());
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 97e10b90b1b..cde19f7fe59 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -33,6 +33,7 @@ if (BUILD_TESTING AND NOT WIN32)
if (PDFJS_FOUND)
ladybird_python_test(test-webdriver-pdf-viewer-ignores-the-csp-of-its-pdf.py ARGS $<TARGET_FILE:WebDriver>)
endif()
+ ladybird_python_test(test-webdriver-rejects-web-page-requests.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-screenshot-with-cross-site-iframe.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-search-engine-settings.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-webdriver-set-permission.py ARGS $<TARGET_FILE:WebDriver>)
diff --git a/Tests/LibWebView/test-webdriver-rejects-web-page-requests.py b/Tests/LibWebView/test-webdriver-rejects-web-page-requests.py
new file mode 100644
index 00000000000..e26b6132079
--- /dev/null
+++ b/Tests/LibWebView/test-webdriver-rejects-web-page-requests.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import http.client
+import importlib
+import subprocess
+
+WEBDRIVER_REQUEST_TIMEOUT_SECONDS = 30
+
+webdriver_helpers = importlib.import_module("test-webdriver-delete-session")
+
+
+def request(port, method, path, headers, body=None):
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=WEBDRIVER_REQUEST_TIMEOUT_SECONDS)
+ try:
+ connection.putrequest(method, path, skip_host=True, skip_accept_encoding=True)
+ for name, value in headers.items():
+ connection.putheader(name, value)
+ if body is not None:
+ connection.putheader("Content-Length", str(len(body)))
+ connection.endheaders(body)
+ response = connection.getresponse()
+ return response.status, response.read().decode()
+ finally:
+ connection.close()
+
+
+def expect(port, method, path, headers, expected_status, body=None):
+ status, response_body = request(port, method, path, headers, body)
+ if status != expected_status:
+ raise AssertionError(
+ f"{method} {path} with {headers} returned HTTP {status}, expected {expected_status}: {response_body}"
+ )
+
+
+def run_test(webdriver_binary):
+ webdriver, port = webdriver_helpers.launch_webdriver(webdriver_binary, "--headless")
+ try:
+ # A WebDriver client names the listener by IP address or as localhost.
+ for host in (f"127.0.0.1:{port}", f"localhost:{port}", f"LOCALHOST:{port}", f"[::1]:{port}", "127.0.0.1"):
+ expect(port, "GET", "/status", {"Host": host}, 200)
+
+ # A page using DNS rebinding names its own domain.
+ for host in (f"attacker.example:{port}", "attacker.example", "[::1", "[::1]x", ""):
+ expect(port, "GET", "/status", {"Host": host}, 403)
+ expect(port, "GET", "/status", {"Accept": "application/json"}, 403)
+
+ # A page's request carries an Origin header.
+ host = {"Host": f"127.0.0.1:{port}"}
+ expect(port, "GET", "/status", {**host, "Origin": "https://attacker.example"}, 403)
+ expect(port, "GET", "/status", {**host, "Origin": "null"}, 403)
+
+ # A page can send these without a CORS preflight. No browser must launch for them.
+ session_body = b'{"capabilities":{}}'
+ for content_type in (
+ "text/plain",
+ "text/plain;charset=UTF-8",
+ "application/x-www-form-urlencoded",
+ "multipart/form-data; boundary=x",
+ ):
+ expect(port, "POST", "/session", {**host, "Content-Type": content_type}, 415, session_body)
+ finally:
+ webdriver.terminate()
+ try:
+ webdriver.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ webdriver.kill()
+ webdriver.wait()
+
+ if webdriver.returncode not in (0, -15):
+ raise RuntimeError(f"WebDriver exited with status {webdriver.returncode}")
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("webdriver_binary")
+ args = parser.parse_args()
+
+ run_test(args.webdriver_binary)
+
+
+if __name__ == "__main__":
+ main()