Skip to content

Truly independent web browser

RequestServer: Stop matching hosts against a certificate's Common Name

Shannon Boothb7abdfc55a3a
diff --git a/Services/RequestServer/CURL.cpp b/Services/RequestServer/CURL.cpp
index 81ddaff5fbf..c9694b121b7 100644
--- a/Services/RequestServer/CURL.cpp
+++ b/Services/RequestServer/CURL.cpp
@@ -11,6 +11,7 @@
#include <RequestServer/CURL.h>
#include <RequestServer/Resolver.h>
#include <openssl/ssl.h>
+#include <openssl/x509v3.h>
#include <string.h>
namespace RequestServer {
@@ -59,6 +60,30 @@ static void share_certificate_store(SSL_CTX* ssl_context)
}
#endif
+// curl matches the server's certificate against its Common Name when the certificate has no DNS or IP subject
+// alternative name. Fail verification of such certificates, so that only subject alternative names identify a server.
+static int verify_server_certificate_has_subject_alt_name(int preverify_ok, X509_STORE_CTX* context)
+{
+ if (!preverify_ok || X509_STORE_CTX_get_error_depth(context) != 0)
+ return preverify_ok;
+
+ auto* names = static_cast<GENERAL_NAMES*>(X509_get_ext_d2i(X509_STORE_CTX_get_current_cert(context), NID_subject_alt_name, nullptr, nullptr));
+ auto has_host_name = false;
+ for (int i = 0; i < sk_GENERAL_NAME_num(names); ++i) {
+ auto type = sk_GENERAL_NAME_value(names, i)->type;
+ if (type == GEN_DNS || type == GEN_IPADD) {
+ has_host_name = true;
+ break;
+ }
+ }
+ GENERAL_NAMES_free(names);
+
+ if (has_host_name)
+ return 1;
+ X509_STORE_CTX_set_error(context, X509_V_ERR_HOSTNAME_MISMATCH);
+ return 0;
+}
+
CURLcode configure_ssl_context(CURL*, [[maybe_unused]] void* ssl_context, [[maybe_unused]] void* aia_collector)
{
// Everything below casts ssl_context to an SSL_CTX, which only holds when curl is built against OpenSSL.
@@ -76,6 +101,12 @@ CURLcode configure_ssl_context(CURL*, [[maybe_unused]] void* ssl_context, [[mayb
SSL_CTX_set_options(static_cast<SSL_CTX*>(ssl_context), SSL_OP_IGNORE_UNEXPECTED_EOF);
#endif
+ // Keep curl's verify mode: it sets SSL_VERIFY_NONE and checks the verification result once the handshake is done.
+ if (curl_uses_openssl) {
+ auto* context = static_cast<SSL_CTX*>(ssl_context);
+ SSL_CTX_set_verify(context, SSL_CTX_get_verify_mode(context), verify_server_certificate_has_subject_alt_name);
+ }
+
#ifdef AK_OS_MACOS
if (curl_uses_openssl)
share_certificate_store(static_cast<SSL_CTX*>(ssl_context));
diff --git a/Tests/LibWeb/Fixtures/http-test-server.py b/Tests/LibWeb/Fixtures/http-test-server.py
index 568e8c34dfe..da0033dab9e 100755
--- a/Tests/LibWeb/Fixtures/http-test-server.py
+++ b/Tests/LibWeb/Fixtures/http-test-server.py
@@ -100,6 +100,18 @@ stalled_tls_connection_count = 0
# Per RFC 6455: appended to Sec-WebSocket-Key before hashing to compute the Sec-WebSocket-Accept value.
WEBSOCKET_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+def websocket_handshake_response(key):
+ accept = base64.b64encode(hashlib.sha1((key + WEBSOCKET_ACCEPT_GUID).encode("utf-8")).digest()).decode("ascii")
+ return (
+ "HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ f"Sec-WebSocket-Accept: {accept}\r\n"
+ "\r\n"
+ ).encode("ascii")
+
+
# The browser saves a download as <name>.<id>.<uuid>.download until it finishes. That suffix takes at most 67 of the
# 255 bytes a filename may have, so a name of up to 188 bytes is never cut short.
MAXIMUM_REPORTED_DOWNLOAD_NAME_LENGTH = 188
@@ -754,17 +766,9 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
self.send_error(400, "Missing Sec-WebSocket-Key")
return
- accept = base64.b64encode(hashlib.sha1((key + WEBSOCKET_ACCEPT_GUID).encode("utf-8")).digest()).decode("ascii")
- handshake = (
- "HTTP/1.1 101 Switching Protocols\r\n"
- "Upgrade: websocket\r\n"
- "Connection: Upgrade\r\n"
- f"Sec-WebSocket-Accept: {accept}\r\n"
- "\r\n"
- )
# We now own the raw socket; stop the HTTP handler from parsing another request on it.
self.close_connection = True
- self.connection.sendall(handshake.encode("ascii"))
+ self.connection.sendall(websocket_handshake_response(key))
if self.path == "/reflect-websocket-cookie":
self._send_websocket_frame(self.headers.get("Cookie", "").encode("utf-8"))
@@ -861,6 +865,12 @@ class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
class AIALeafHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
+ if self.headers.get("Upgrade", "").lower() == "websocket":
+ # Accept the handshake and hang up, so a test can tell whether a wss:// connection got past TLS.
+ self.wfile.write(websocket_handshake_response(self.headers.get("Sec-WebSocket-Key", "")))
+ self.close_connection = True
+ return
+
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", "2")
@@ -1032,6 +1042,26 @@ def _setup_tls_test_servers(http_port, ca_cert_output):
)
scenarios["untrusted"] = (untrusted_leaf, untrusted_leaf_key)
+ # Leaves issued by the root itself, naming localhost either only in the Common Name or also in a subjectAltName.
+ def add_root_issued_scenario(name, subject_alt_names):
+ leaf_key = new_key()
+ builder = (
+ x509.CertificateBuilder()
+ .subject_name(dn("localhost"))
+ .issuer_name(root.subject)
+ .public_key(leaf_key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(not_before)
+ .not_valid_after(not_after)
+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
+ )
+ if subject_alt_names:
+ builder = builder.add_extension(x509.SubjectAlternativeName(subject_alt_names), critical=False)
+ scenarios[name] = (builder.sign(root_key, hashes.SHA256()), leaf_key)
+
+ add_root_issued_scenario("common_name_only", [])
+ add_root_issued_scenario("subject_alt_name", [x509.DNSName("localhost")])
+
TestHTTPRequestHandler.aia_artifacts = artifacts
# Write the root CA so RequestServer (via --certificate/CAINFO) trusts the completed chains.
diff --git a/Tests/LibWeb/Text/expected/certificate-without-subject-alt-name.txt b/Tests/LibWeb/Text/expected/certificate-without-subject-alt-name.txt
new file mode 100644
index 00000000000..bfaff4b9cae
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/certificate-without-subject-alt-name.txt
@@ -0,0 +1,4 @@
+localhost in subjectAltName: loaded
+localhost only in Common Name: failed
+wss:// with localhost in subjectAltName: opened
+wss:// with localhost only in Common Name: failed
diff --git a/Tests/LibWeb/Text/input/certificate-without-subject-alt-name.html b/Tests/LibWeb/Text/input/certificate-without-subject-alt-name.html
new file mode 100644
index 00000000000..b47ee489823
--- /dev/null
+++ b/Tests/LibWeb/Text/input/certificate-without-subject-alt-name.html
@@ -0,0 +1,51 @@
+<!doctype html>
+<script src="./include.js"></script>
+<script>
+ // A certificate that names its host only in the Common Name must not be accepted for that host.
+ asyncTest(async done => {
+ const base = httpTestServer().baseURL;
+
+ let config;
+ try {
+ config = await (await fetch(`${base}/aia-test/config`)).json();
+ } catch (error) {
+ println("FAIL - could not read TLS test config: " + error);
+ done();
+ return;
+ }
+
+ if (!config.common_name_only) {
+ println(
+ "FAIL - TLS test HTTPS servers unavailable (is the 'cryptography' package installed for the test runner's python?)"
+ );
+ done();
+ return;
+ }
+
+ async function loads(port) {
+ try {
+ await fetch(`https://localhost:${port}/`, { mode: "no-cors" });
+ return "loaded";
+ } catch {
+ return "failed";
+ }
+ }
+
+ function opens(port) {
+ return new Promise(resolve => {
+ const ws = new WebSocket(`wss://localhost:${port}/`);
+ ws.onopen = () => {
+ ws.close();
+ resolve("opened");
+ };
+ ws.onerror = () => resolve("failed");
+ });
+ }
+
+ println("localhost in subjectAltName: " + (await loads(config.subject_alt_name)));
+ println("localhost only in Common Name: " + (await loads(config.common_name_only)));
+ println("wss:// with localhost in subjectAltName: " + (await opens(config.subject_alt_name)));
+ println("wss:// with localhost only in Common Name: " + (await opens(config.common_name_only)));
+ done();
+ });
+</script>