Skip to content

Truly independent web browser

LibWeb+RequestServer: Allow trusting self-signed certificates

Ali Mohammad Purae1a048ed4f1
diff --git a/Base/res/ladybird/about-pages/certificate.html b/Base/res/ladybird/about-pages/certificate.html
new file mode 100644
index 00000000000..5581c01f3f6
--- /dev/null
+++ b/Base/res/ladybird/about-pages/certificate.html
@@ -0,0 +1,206 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="color-scheme" content="light dark" />
+ <title>Untrusted Certificate</title>
+ <link rel="icon" type="image/png" href="resource://icons/48x48/app-browser.png" />
+ <link rel="stylesheet" type="text/css" href="resource://ladybird/ladybird.css" />
+ <link rel="stylesheet" type="text/css" href="resource://ladybird/about-pages/webui.css" />
+ <style>
+ :root {
+ --danger-tint: rgba(179, 38, 30, 0.08);
+ }
+
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --danger-tint: rgba(255, 154, 143, 0.12);
+ }
+ }
+
+ body {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ min-height: 100vh;
+ max-width: none;
+ padding: 24px;
+ font-size: 15px;
+ text-align: center;
+ }
+
+ main {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 16px;
+ max-width: 640px;
+ }
+
+ header {
+ flex-direction: column;
+ gap: 32px;
+ margin-bottom: 8px;
+ }
+
+ svg {
+ height: 64px;
+ width: auto;
+ stroke: var(--error);
+ fill: var(--danger-tint);
+ stroke-width: 1.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ }
+
+ header h1 {
+ font-size: 24px;
+ color: var(--error);
+ overflow-wrap: anywhere;
+ }
+
+ p {
+ line-height: 1.4;
+ }
+
+ .warning {
+ padding: 12px 16px;
+ border-left: 4px solid var(--error);
+ border-radius: 4px;
+ background-color: var(--danger-tint);
+ text-align: left;
+ }
+
+ .secondary {
+ color: var(--secondary-text-color);
+ }
+
+ #fingerprint {
+ display: block;
+ margin-top: 4px;
+ font-family: monospace;
+ font-size: 12px;
+ overflow-wrap: anywhere;
+ }
+
+ .buttons {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ margin-top: 16px;
+ }
+
+ #reject {
+ height: 36px;
+ padding: 0 32px;
+ font-size: 15px;
+ }
+
+ #trust {
+ font: inherit;
+ font-size: 13px;
+ padding: 2px 4px;
+ color: var(--secondary-text-color);
+ background: none;
+ border: none;
+ text-decoration: underline;
+ cursor: pointer;
+ }
+
+ #trust:hover {
+ color: var(--error);
+ }
+
+ [hidden] {
+ display: none !important;
+ }
+ </style>
+ </head>
+ <body>
+ <main id="status">
+ <p class="secondary">Loading the certificate warning. If nothing appears, go back or reload the page.</p>
+ </main>
+ <main id="warning" hidden>
+ <header>
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
+ <path d="M12 2.75 4.75 5.5v6c0 4.5 3.1 8.4 7.25 9.75 4.15-1.35 7.25-5.25 7.25-9.75v-6z" />
+ <path d="M12 8.5v4M12 15.75v.5" />
+ </svg>
+ <h1>Your connection to <span class="host"></span> is not secure</h1>
+ </header>
+ <p class="warning">
+ The certificate of <strong class="host"></strong> isn't trusted by Ladybird: it's self-signed, or its
+ chain ends at a self-signed root Ladybird doesn't trust. Someone might be intercepting your connection
+ to access private information, like passwords, messages, or credit cards.
+ </p>
+ <p class="secondary">
+ Only continue if you know this is a local or development server you control. Trusting lets Ladybird
+ accept this certificate from <span id="origin"></span> until Ladybird is closed. Any other certificate
+ the site presents is still verified as usual.
+ </p>
+ <p class="secondary" id="resends-form" hidden>Trusting sends the form you submitted again.</p>
+ <p class="secondary" id="form-not-resent" hidden>
+ The form you submitted came from another site, so trusting won't submit it. Submit it again once the
+ page has loaded.
+ </p>
+ <p class="secondary">
+ Server certificate SHA-256 fingerprint:
+ <span id="fingerprint"></span>
+ </p>
+ <div class="buttons">
+ <button id="reject" class="primary-button">Don't trust</button>
+ <button id="trust">Trust anyway</button>
+ </div>
+ </main>
+ <main id="nothing" hidden>
+ <p class="secondary">There is no certificate to review.</p>
+ </main>
+ <script>
+ function formatFingerprint(fingerprint) {
+ return fingerprint
+ .toUpperCase()
+ .match(/.{1,2}/g)
+ .join(":");
+ }
+
+ // Answers name the warning they were given, so they can't apply to one shown after it.
+ let reviewedWarning = null;
+
+ function answer(name) {
+ if (reviewedWarning)
+ ladybird.sendMessage(name, { url: reviewedWarning.url, fingerprint: reviewedWarning.fingerprint });
+ }
+
+ document.getElementById("trust").addEventListener("click", () => answer("trustCertificate"));
+ document.getElementById("reject").addEventListener("click", () => answer("rejectCertificate"));
+
+ document.addEventListener("WebUIMessage", event => {
+ if (event.detail.name !== "loadCertificateWarning") return;
+
+ document.getElementById("status").hidden = true;
+
+ const warning = event.detail.data;
+ reviewedWarning = warning;
+ if (!warning) {
+ document.getElementById("nothing").hidden = false;
+ return;
+ }
+
+ for (const host of document.querySelectorAll(".host")) host.textContent = warning.host;
+ document.getElementById("origin").textContent = warning.origin;
+ document.getElementById("fingerprint").textContent = formatFingerprint(warning.fingerprint);
+ document.getElementById("resends-form").hidden = !warning.resendsForm;
+ document.getElementById("form-not-resent").hidden = !warning.formIsNotResent;
+ document.getElementById("warning").hidden = false;
+
+ // Autofocus skips the initially hidden button.
+ if (!document.activeElement || document.activeElement === document.body)
+ document.getElementById("reject").focus();
+ });
+
+ document.addEventListener("WebUILoaded", () => ladybird.sendMessage("loadCertificateWarning"));
+ </script>
+ </body>
+</html>
diff --git a/Base/res/ladybird/templates/error.html b/Base/res/ladybird/templates/error.html
index ee526ecb332..1ad4f9e0620 100644
--- a/Base/res/ladybird/templates/error.html
+++ b/Base/res/ladybird/templates/error.html
@@ -116,6 +116,11 @@
color: var(--muted);
overflow-wrap: anywhere;
}
+ .hint {
+ margin-top: 10px;
+ font-size: 12px;
+ color: var(--muted);
+ }
:focus-visible {
outline: none;
box-shadow:
@@ -148,6 +153,9 @@
Try again
</button>
</div>
+ <p class="hint" %certificate_setting_hidden%>
+ Advanced user? Turn on “Offer to trust self-signed certificates” in Settings, under Advanced.
+ </p>
</main>
</body>
</html>
diff --git a/Libraries/LibRequests/ExportedRequest.cpp b/Libraries/LibRequests/ExportedRequest.cpp
index fb5965cf4f6..394cf0f779e 100644
--- a/Libraries/LibRequests/ExportedRequest.cpp
+++ b/Libraries/LibRequests/ExportedRequest.cpp
@@ -21,6 +21,7 @@ ErrorOr<void> encode(Encoder& encoder, Requests::ExportedRequest const& request)
TRY(encoder.encode(request.status_code));
TRY(encoder.encode(request.reason_phrase));
TRY(encoder.encode(request.response_headers));
+ TRY(encoder.encode(request.may_rely_on_certificate_exception));
TRY(encoder.encode(request.body));
TRY(encoder.encode(request.status));
return {};
@@ -38,6 +39,7 @@ ErrorOr<Requests::ExportedRequest> decode(Decoder& decoder)
request.status_code = TRY(decoder.decode<Optional<u32>>());
request.reason_phrase = TRY(decoder.decode<Optional<String>>());
request.response_headers = TRY(decoder.decode<Vector<HTTP::Header>>());
+ request.may_rely_on_certificate_exception = TRY(decoder.decode<bool>());
request.body = TRY(decoder.decode<IPC::File>());
request.status = TRY(decoder.decode<IPC::File>());
return request;
diff --git a/Libraries/LibRequests/ExportedRequest.h b/Libraries/LibRequests/ExportedRequest.h
index 8aa18843878..22ee19b1145 100644
--- a/Libraries/LibRequests/ExportedRequest.h
+++ b/Libraries/LibRequests/ExportedRequest.h
@@ -32,6 +32,9 @@ struct ExportedRequest {
Optional<String> reason_phrase;
Vector<HTTP::Header> response_headers;
+ // The exporter could only reach the server through a certificate exception, so the response must not be cached.
+ bool may_rely_on_certificate_exception { false };
+
IPC::File body;
IPC::File status;
};
diff --git a/Libraries/LibRequests/NetworkError.h b/Libraries/LibRequests/NetworkError.h
index ddeb9b60bef..a1603e0fdfa 100644
--- a/Libraries/LibRequests/NetworkError.h
+++ b/Libraries/LibRequests/NetworkError.h
@@ -18,6 +18,7 @@ enum class NetworkError {
TooManyRedirects,
SSLHandshakeFailed,
SSLVerificationFailed,
+ SSLSelfSignedCertificate,
MalformedUrl,
IncompleteContent,
InvalidContentEncoding,
@@ -43,6 +44,8 @@ constexpr StringView network_error_to_string(NetworkError network_error)
return "SSL handshake failed"sv;
case NetworkError::SSLVerificationFailed:
return "SSL verification failed"sv;
+ case NetworkError::SSLSelfSignedCertificate:
+ return "The server's certificate is self-signed"sv;
case NetworkError::MalformedUrl:
return "The URL is not formatted properly"sv;
case NetworkError::IncompleteContent:
diff --git a/Libraries/LibRequests/RequestControlClient.cpp b/Libraries/LibRequests/RequestControlClient.cpp
index 3bb2bfc17d0..c470b2c2296 100644
--- a/Libraries/LibRequests/RequestControlClient.cpp
+++ b/Libraries/LibRequests/RequestControlClient.cpp
@@ -51,6 +51,12 @@ void RequestControlClient::network_usage(Vector<NetworkUsage> usage, u64 interva
on_network_usage(move(usage), interval_microseconds);
}
+void RequestControlClient::rejected_self_signed_certificate(ByteString host, u16 port, ByteString fingerprint)
+{
+ if (on_rejected_self_signed_certificate)
+ on_rejected_self_signed_certificate(host, port, fingerprint);
+}
+
void RequestControlClient::client_disconnected(int client_id)
{
if (on_client_disconnected)
diff --git a/Libraries/LibRequests/RequestControlClient.h b/Libraries/LibRequests/RequestControlClient.h
index acee35761c5..1fab9928f07 100644
--- a/Libraries/LibRequests/RequestControlClient.h
+++ b/Libraries/LibRequests/RequestControlClient.h
@@ -38,6 +38,7 @@ public:
NonnullRefPtr<Core::Promise<Empty>> designate_request_adopter(RequestTransferLeaseKey, int adopter_client_id);
Function<void(Vector<NetworkUsage>, u64 interval_microseconds)> on_network_usage;
+ Function<void(ByteString const& host, u16 port, ByteString const& fingerprint)> on_rejected_self_signed_certificate;
Function<void(int client_id)> on_client_disconnected;
Function<String(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext)> on_retrieve_http_cookie;
Function<void(int client_id, URL::URL const&, Optional<HTTP::Cookie::PartitionContext> const&, HTTP::Cookie::SameSiteContext, Vector<HTTP::Cookie::ParsedCookie> const&, Optional<HTTP::HSTS::ParsedHSTSPolicy> const&)> on_store_response_cookies_and_hsts_policy;
@@ -48,6 +49,7 @@ private:
virtual void die() override;
virtual void network_usage(Vector<NetworkUsage> usage, u64 interval_microseconds) override;
+ virtual void rejected_self_signed_certificate(ByteString host, u16 port, ByteString fingerprint) override;
virtual void client_disconnected(int client_id) override;
virtual void retrieve_http_cookie(int client_id, u64 request_id, RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context) override;
virtual void store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) override;
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 619973f2fc4..b1df79d36df 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -2899,6 +2899,11 @@ static Engine::Event::NetworkActivity::RequestStarted network_request_started(Lo
};
}
+Utf16String network_request_failed_error_message(Optional<StringView> error_message)
+{
+ return Utf16String::formatted("Load failed: {}", error_message.value_or("Unknown error"sv));
+}
+
// https://fetch.spec.whatwg.org/#concept-http-network-fetch
// Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
// It also handles file:// URLs since those can also go through ResourceLoader.
@@ -3097,7 +3102,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
engine_record->event_sink().handle_event(Engine::Event::RequestTransmissionEnded { move(network_phases) });
body_pump->handle_network_complete(Infrastructure::is_http_or_https_scheme(request->current_url().scheme()) ? Optional<i64>(timing_info.encoded_body_size) : Optional<i64> {});
} else {
- auto error = Utf16String::formatted("Load failed: {}", error_message.value_or("Unknown error"sv));
+ auto error = network_request_failed_error_message(error_message);
body_pump->handle_network_error(error.to_utf8_but_should_be_ported_to_utf16());
if (!pending_response->is_resolved())
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
index 740b8581e2c..12549724eda 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
@@ -76,6 +76,8 @@ void set_sec_fetch_user_header(Infrastructure::Request&);
void append_fetch_metadata_headers_for_request(Infrastructure::Request&);
void append_user_agent_client_hints_for_request(Infrastructure::Request&);
+WEB_API Utf16String network_request_failed_error_message(Optional<StringView> error_message);
+
WEB_API void set_http_memory_cache_enabled(bool enabled);
WEB_API bool http_memory_cache_enabled();
WEB_API void clear_http_memory_cache();
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 5458adfa749..1bf2d792fb0 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -87,6 +87,7 @@
#include <LibWeb/Layout/NodeArena.h>
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Loader/GeneratedPagesLoader.h>
+#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Page/EventHandler.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
@@ -3244,10 +3245,24 @@ GC::Ref<DocumentToCreate> DocumentToCreate::create(GC::Ref<NavigationParams> nav
return GC::Heap::the().allocate<DocumentToCreate>(navigation_params, load_steps, move(origin));
}
+static bool should_offer_to_trust_self_signed_certificate(LocalNavigable& navigable, Utf16String const& error_message)
+{
+ if (!navigable.is_top_level_traversable())
+ return false;
+ // NB: Only the error message survives across processes; no server-controlled message matches it exactly.
+ // A false match only requests a UI warning for an unrecorded certificate.
+ auto description = network_error_description(Requests::NetworkError::SSLSelfSignedCertificate);
+ return error_message == Fetch::Fetching::network_request_failed_error_message(description.bytes_as_string_view());
+}
+
static GC::Ref<DOM::Document> create_navigation_error_document(NavigationParams const& navigation_params, URL::URL const& url, Utf16String const& error_message)
{
- auto error_html = load_error_page(url, error_message.to_utf8()).release_value_but_fixme_should_propagate_errors();
- auto document = create_document_for_inline_content(navigation_params, [&error_html](auto& document) {
+ auto is_self_signed_certificate_error = should_offer_to_trust_self_signed_certificate(*navigation_params.navigable, error_message);
+ // The UI process replaces this page with a warning only if certificate trust prompts are enabled.
+ auto offer_to_trust_certificate = is_self_signed_certificate_error && navigation_params.navigable->page().offers_to_trust_self_signed_certificates();
+ auto mention_certificate_setting = is_self_signed_certificate_error && !offer_to_trust_certificate ? MentionCertificateSetting::Yes : MentionCertificateSetting::No;
+ auto error_html = load_error_page(url, error_message.to_utf8(), mention_certificate_setting).release_value_but_fixme_should_propagate_errors();
+ auto document = create_document_for_inline_content(navigation_params, [&error_html, offer_to_trust_certificate, &url](auto& document) {
auto scripting_mode = document.is_scripting_enabled() ? HTML::ParserScriptingMode::Normal : HTML::ParserScriptingMode::Disabled;
auto parser = HTMLParser::create_from_byte_string(document, error_html, scripting_mode, "utf-8"sv);
document.set_url(URL::about_error());
@@ -3257,8 +3272,19 @@ static GC::Ref<DOM::Document> create_navigation_error_document(NavigationParams
// FIXME: Directly calling parser->the_end results in a deadlock, because it waits for the warning image to load.
// However the response is never processed when parser->the_end is called.
// Queuing a global task is a workaround for now.
- queue_a_task(Task::Source::Unspecified, HTML::main_thread_event_loop(), document, GC::create_function(document.heap(), GC::captures(document, parser), [](auto& document, auto& parser) {
+ queue_a_task(Task::Source::Unspecified, HTML::main_thread_event_loop(), document, GC::create_function(document.heap(), GC::captures(document, parser, offer_to_trust_certificate, url), [](auto& document, auto& parser, auto const& offer_to_trust_certificate, auto const& url) {
HTMLParser::the_end(document, parser);
+
+ // The UI process owns certificate trust and only accepts requests from the displayed document.
+ if (!offer_to_trust_certificate)
+ return;
+ auto navigable = document.navigable();
+ if (!navigable || !navigable->active_document_is(document))
+ return;
+ auto entry = navigable->active_session_history_entry();
+ if (!entry || !entry->document_state())
+ return;
+ document.page().client().page_did_request_certificate_warning(url, entry->document_state()->cross_process_id());
}));
});
diff --git a/Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp b/Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp
index dc5ba3dbb1d..ffd8ca3f01b 100644
--- a/Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp
+++ b/Libraries/LibWeb/Loader/GeneratedPagesLoader.cpp
@@ -16,7 +16,7 @@
namespace Web {
-ErrorOr<String> load_error_page(URL::URL const& url, StringView error_message)
+ErrorOr<String> load_error_page(URL::URL const& url, StringView error_message, MentionCertificateSetting mention_certificate_setting)
{
// Generate HTML error page from error template file
// FIXME: Use an actual templating engine (our own one when it's built, preferably with a way to check these usages at compile time)
@@ -32,6 +32,7 @@ ErrorOr<String> load_error_page(URL::URL const& url, StringView error_message)
failed_host = ByteString::formatted("{}:{}", failed_host, *url.port());
generator.set("failed_host", escape_html_entities(failed_host));
generator.set("error_message", escape_html_entities(error_message));
+ generator.set("certificate_setting_hidden", mention_certificate_setting == MentionCertificateSetting::Yes ? ""sv : "hidden"sv);
generator.append(template_file->data());
return TRY(String::from_utf8(generator.as_string_view()));
}
diff --git a/Libraries/LibWeb/Loader/GeneratedPagesLoader.h b/Libraries/LibWeb/Loader/GeneratedPagesLoader.h
index 13d8f328baf..d989bae2ef1 100644
--- a/Libraries/LibWeb/Loader/GeneratedPagesLoader.h
+++ b/Libraries/LibWeb/Loader/GeneratedPagesLoader.h
@@ -11,7 +11,11 @@
namespace Web {
-ErrorOr<String> load_error_page(URL::URL const&, StringView error_message);
+enum class MentionCertificateSetting : u8 {
+ No,
+ Yes,
+};
+ErrorOr<String> load_error_page(URL::URL const&, StringView error_message, MentionCertificateSetting = MentionCertificateSetting::No);
ErrorOr<String> load_file_directory_page(URL::URL const&);
}
diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cpp
index fe5c45849f3..8f5eee1e44e 100644
--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp
+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp
@@ -203,6 +203,11 @@ void ResourceLoader::preconnect(GC::Ptr<DOM::Document> document, URL::URL const&
request_client->ensure_connection(url, RequestServer::CacheLevel::CreateConnection);
}
+String network_error_description(Requests::NetworkError network_error)
+{
+ return MUST(String::formatted("Request finished with error: {}", Requests::network_error_to_string(network_error)));
+}
+
static ByteString sanitized_url_for_logging(URL::URL const& url)
{
if (url.scheme() == "data"sv)
@@ -563,9 +568,7 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&
log_success(request);
on_complete->function()(true, timing_info, {}, network_request_end);
} else {
- auto error_description = MUST(String::formatted(
- "Request finished with error: {}",
- network_error_to_string(*network_error)));
+ auto error_description = network_error_description(*network_error);
log_failure(request, error_description);
on_complete->function()(false, timing_info, error_description, network_request_end);
}
diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.h
index 1ef97872317..92a50981fcd 100644
--- a/Libraries/LibWeb/Loader/ResourceLoader.h
+++ b/Libraries/LibWeb/Loader/ResourceLoader.h
@@ -29,6 +29,8 @@
namespace Web {
+WEB_API String network_error_description(Requests::NetworkError);
+
// Each agent has a loader of its own, which holds its connections to the RequestServer and its requests, and only its
// thread can use it. The static settings are the process's.
class WEB_API ResourceLoader : public Core::EventReceiver {
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index cf4566182f7..853f60ef323 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -269,6 +269,10 @@ public:
bool enable_primary_paste() const { return m_enable_primary_paste; }
void set_enable_primary_paste(bool b) { m_enable_primary_paste = b; }
+ // Whether the UI process replaces self-signed certificate error pages with trust prompts.
+ bool offers_to_trust_self_signed_certificates() const { return m_offers_to_trust_self_signed_certificates; }
+ void set_offers_to_trust_self_signed_certificates(bool b) { m_offers_to_trust_self_signed_certificates = b; }
+
u64 wheel_event_listener_state_generation() const { return m_wheel_event_listener_state_generation; }
u64 keyboard_scroll_state_generation() const { return m_keyboard_scroll_state_generation; }
void invalidate_compositor_wheel_event_listener_state(DOM::Document&);
@@ -610,6 +614,7 @@ private:
bool m_should_block_pop_ups { true };
bool m_enable_autoscroll { true };
bool m_enable_primary_paste { true };
+ bool m_offers_to_trust_self_signed_certificates { false };
u64 m_wheel_event_listener_state_generation { 0 };
u64 m_keyboard_scroll_state_generation { 0 };
bool m_keyboard_scroll_state_is_current { false };
@@ -844,6 +849,7 @@ public:
virtual void page_did_change_title(Utf16String const&) { }
virtual void page_did_update_editing_history_state(bool, bool) { }
virtual void page_did_set_text_fragment_indication_visibility(bool) { }
+ virtual void page_did_request_certificate_warning(URL::URL const&, HTML::CrossProcessId) { }
virtual void page_did_request_resize_window(Gfx::IntSize, u64) { }
virtual void page_did_request_reposition_window(Gfx::IntPoint, u64) { }
virtual void page_did_request_restore_window() { }
diff --git a/Libraries/LibWebView/BrowsingSession.h b/Libraries/LibWebView/BrowsingSession.h
index ab58a33a45a..96c8b528c33 100644
--- a/Libraries/LibWebView/BrowsingSession.h
+++ b/Libraries/LibWebView/BrowsingSession.h
@@ -6,10 +6,14 @@
#pragma once
+#include <AK/ByteString.h>
+#include <AK/HashMap.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/OwnPtr.h>
#include <AK/RefCounted.h>
+#include <AK/Time.h>
#include <AK/Types.h>
+#include <AK/Vector.h>
#include <AK/Weakable.h>
#include <LibWebView/Export.h>
#include <LibWebView/Forward.h>
@@ -42,6 +46,24 @@ public:
OwnPtr<HSTSStore> hsts_store;
OwnPtr<PermissionManager> permission_manager;
+ struct CertificateException {
+ ByteString host;
+ u16 port { 0 };
+ ByteString fingerprint;
+
+ bool operator==(CertificateException const&) const = default;
+ };
+
+ // Keep recent rejections until their warnings arrive, so users can only trust certificates actually presented.
+ struct RejectedCertificate {
+ CertificateException certificate;
+ MonotonicTime rejected_at;
+ };
+ HashMap<ByteString, Vector<RejectedCertificate>> rejected_self_signed_certificates;
+
+ // Every RequestServer of the session accepts these, including those launched after the user trusted them.
+ Vector<CertificateException> trusted_certificates;
+
private:
explicit BrowsingSession(IsPrivate);
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 008e7d92b8b..9d9ad69d8dd 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -99,6 +99,7 @@ set(SOURCES
WebUI.cpp
WebUI/AboutUI.cpp
WebUI/ApplicationWebUI.cpp
+ WebUI/CertificateUI.cpp
WebUI/CrashReportsUI.cpp
WebUI/SupportUI.cpp
WebUI/SettingsUI.cpp
diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.h
index 2f6cf6b03ff..244e1b887f3 100644
--- a/Libraries/LibWebView/Forward.h
+++ b/Libraries/LibWebView/Forward.h
@@ -60,6 +60,7 @@ class RequestServerManager;
class RequestServerSiteBindings;
class PermissionManager;
class Settings;
+class CertificateUI;
class SettingsUI;
class SpellChecker;
class Translator;
diff --git a/Libraries/LibWebView/RequestServerManager.cpp b/Libraries/LibWebView/RequestServerManager.cpp
index e74ff4cceb7..fb1b94b1f5e 100644
--- a/Libraries/LibWebView/RequestServerManager.cpp
+++ b/Libraries/LibWebView/RequestServerManager.cpp
@@ -24,6 +24,11 @@
namespace WebView {
+static ByteString certificate_exception_key(ByteString const& host, u16 port)
+{
+ return ByteString::formatted("{}:{}", host, port);
+}
+
// Entries last accessed in the same time bucket are evicted together.
static constexpr auto cache_access_granularity = AK::Duration::from_seconds(1);
@@ -147,8 +152,15 @@ ErrorOr<void> RequestServerManager::launch_process(RequestServerInstance& instan
if (auto instance = weak_instance.strong_ref())
the().disk_cache_size_changed(*instance, size);
};
+ control_client->on_rejected_self_signed_certificate = [weak_instance](ByteString const& host, u16 port, ByteString const& fingerprint) {
+ if (auto instance = weak_instance.strong_ref())
+ the().did_reject_self_signed_certificate(instance->session(), { .host = host, .port = port, .fingerprint = fingerprint });
+ };
Application::the().configure_request_server_control_client(*control_client);
+ for (auto const& exception : instance.session().trusted_certificates)
+ control_client->async_trust_certificate(exception.host, exception.port, exception.fingerprint);
+
instance.m_control_client = move(control_client);
instance.m_ui_client = nullptr;
@@ -266,6 +278,58 @@ void RequestServerManager::retire_idle_instances()
}
}
+static constexpr auto rejected_certificate_lifetime = AK::Duration::from_seconds(30);
+
+static void remove_stale_rejections(Vector<BrowsingSession::RejectedCertificate>& rejections)
+{
+ auto now = MonotonicTime::now_coarse();
+ rejections.remove_all_matching([&](auto const& rejection) { return now - rejection.rejected_at > rejected_certificate_lifetime; });
+}
+
+void RequestServerManager::did_reject_self_signed_certificate(BrowsingSession& session, BrowsingSession::CertificateException certificate)
+{
+ auto& rejections = session.rejected_self_signed_certificates.ensure(certificate_exception_key(certificate.host, certificate.port));
+ remove_stale_rejections(rejections);
+ rejections.remove_all_matching([&](auto const& rejection) { return rejection.certificate == certificate; });
+ rejections.append({ .certificate = move(certificate), .rejected_at = MonotonicTime::now_coarse() });
+}
+
+// Warnings identify only the host and port. If recent rejections disagree, offering any certificate risks trusting
+// one other than the certificate that triggered the warning.
+Optional<BrowsingSession::CertificateException> RequestServerManager::rejected_self_signed_certificate(BrowsingSession& session, URL::URL const& url) const
+{
+ auto key = certificate_exception_key(url.serialized_host().to_byte_string(), url.port_or_default());
+ auto rejections = session.rejected_self_signed_certificates.get(key);
+ if (!rejections.has_value())
+ return {};
+
+ remove_stale_rejections(*rejections);
+ if (rejections->is_empty()) {
+ session.rejected_self_signed_certificates.remove(key);
+ return {};
+ }
+ if (rejections->size() != 1)
+ return {};
+ return rejections->first().certificate;
+}
+
+void RequestServerManager::trust_certificate(BrowsingSession& session, BrowsingSession::CertificateException const& certificate)
+{
+ // A trusted certificate is no longer a candidate for a later warning about the same host and port.
+ if (auto rejections = session.rejected_self_signed_certificates.get(certificate_exception_key(certificate.host, certificate.port)); rejections.has_value())
+ rejections->remove_all_matching([&](auto const& rejection) { return rejection.certificate == certificate; });
+
+ if (session.trusted_certificates.contains_slow(certificate))
+ return;
+
+ for (auto& instance : m_instances) {
+ if (&instance->session() == &session)
+ (void)send_sync_to_helper<Messages::RequestServerControl::TrustCertificate>(instance->control_client(), certificate.host, certificate.port, certificate.fingerprint);
+ }
+
+ session.trusted_certificates.append(certificate);
+}
+
void RequestServerManager::disk_cache_settings_changed()
{
auto settings = Application::settings().disk_cache_settings();
diff --git a/Libraries/LibWebView/RequestServerManager.h b/Libraries/LibWebView/RequestServerManager.h
index 6e2c5d99ac0..dfd9075f1c7 100644
--- a/Libraries/LibWebView/RequestServerManager.h
+++ b/Libraries/LibWebView/RequestServerManager.h
@@ -94,6 +94,13 @@ public:
ErrorOr<RequestServerClientConnection> connect_new_client(RequestServerInstance&, BrowsingSession&, RequestServer::SiteBinding);
+ // The recently rejected certificate for this session, host and port, if unambiguous.
+ Optional<BrowsingSession::CertificateException> rejected_self_signed_certificate(BrowsingSession&, URL::URL const&) const;
+ void did_reject_self_signed_certificate(BrowsingSession&, BrowsingSession::CertificateException);
+
+ // Makes every RequestServer of the session accept the certificate, including those launched later.
+ void trust_certificate(BrowsingSession&, BrowsingSession::CertificateException const&);
+
void disk_cache_settings_changed();
void dns_settings_changed();
diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cpp
index 5afb3756a75..9256daebfe3 100644
--- a/Libraries/LibWebView/Settings.cpp
+++ b/Libraries/LibWebView/Settings.cpp
@@ -212,6 +212,14 @@ static auto const& CONFIG_VARIABLE_DEFINITIONS = *new Array<ConfigVariableDefini
.default_value = false,
.array_element_type = {},
},
+ {
+ .id = ConfigVariableID::OfferToTrustSelfSignedCertificates,
+ .name = "security.certificates.offer_to_trust_self_signed"sv,
+ .title = "Offer to trust self-signed certificates"sv,
+ .description = "When a site presents a self-signed certificate, ask whether to trust it until Ladybird is closed, instead of refusing to connect. Meant for local and development servers: on a public site, a self-signed certificate may mean someone is intercepting the connection."sv,
+ .default_value = false,
+ .array_element_type = {},
+ },
#if defined(LADYBIRD_HAS_UPDATE_CHECK)
{
.id = ConfigVariableID::UpdateCheckInterval,
diff --git a/Libraries/LibWebView/Settings.h b/Libraries/LibWebView/Settings.h
index 798e2eee146..64918ba9efa 100644
--- a/Libraries/LibWebView/Settings.h
+++ b/Libraries/LibWebView/Settings.h
@@ -167,6 +167,7 @@ enum class ConfigVariableID : u8 {
SplitDownloadsWithoutValidators,
RestartStalledConnections,
DisableHighDynamicRangeSurfaces,
+ OfferToTrustSelfSignedCertificates,
#if defined(LADYBIRD_HAS_UPDATE_CHECK)
UpdateCheckInterval,
#endif
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 628b31c18e5..f346a72ec1c 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -975,6 +975,69 @@ void ViewImplementation::load_html(StringView html)
set_loading_state(true);
}
+void ViewImplementation::did_request_certificate_warning(Badge<WebContentPage>, URL::URL const& url, Web::HTML::CrossProcessId document_state_id)
+{
+ if (!Application::settings().config_variable_as_bool(ConfigVariableID::OfferToTrustSelfSignedCertificates))
+ return;
+
+ // Only the error page the view still displays may ask, and not once another navigation has started.
+ if (traversable().has_uncommitted_navigation() || traversable().session_history().current_entry().document_state->id != document_state_id)
+ return;
+
+ // Snapshot the rejected certificate so trusting it cannot trust a later rejection for the same host.
+ auto certificate = RequestServerManager::the().rejected_self_signed_certificate(session(), url);
+ if (!certificate.has_value())
+ return;
+
+ // Declining reloads the error page; suppress its repeated warning request.
+ if (auto declined = exchange(m_declined_certificate, {}); declined == certificate)
+ return;
+
+ CertificateWarning warning { .url = url, .certificate = certificate.release_value(), .form_submission = {}, .form_initiator_origin = URL::Origin::create_opaque(), .form_is_not_resent = false };
+
+ // Preserve the form for resubmission before replacing the error page's history entry.
+ auto const& document_state = *traversable().session_history().current_entry().document_state;
+ if (auto const* form_submission = document_state.resource.get_pointer<Web::HTML::POSTResource>()) {
+ auto const& initiator_origin = document_state.initiator_origin;
+ if (initiator_origin.has_value() && !initiator_origin->is_opaque() && initiator_origin->is_same_site(url.origin())) {
+ warning.form_submission = *form_submission;
+ warning.form_initiator_origin = *initiator_origin;
+ } else {
+ warning.form_is_not_resent = true;
+ }
+ }
+
+ m_certificate_warning = move(warning);
+ load(traversable().prepare_navigation(URL::URL::about("certificate"sv), {}, Web::Bindings::NavigationHistoryBehavior::Replace));
+}
+
+void ViewImplementation::answer_certificate_warning(Badge<CertificateUI>, URL::URL const& url, StringView fingerprint, bool trust)
+{
+ // Apply the answer only to the warning the user reviewed.
+ if (!m_certificate_warning.has_value() || m_certificate_warning->url != url || m_certificate_warning->certificate.fingerprint != fingerprint)
+ return;
+ auto warning = exchange(m_certificate_warning, {});
+
+ if (!trust) {
+ // NB: Never send the form to a server whose certificate the user declined.
+ m_declined_certificate = warning->certificate;
+ load(traversable().prepare_navigation(warning->url, {}, Web::Bindings::NavigationHistoryBehavior::Replace));
+ return;
+ }
+
+ RequestServerManager::the().trust_certificate(session(), warning->certificate);
+
+ if (!warning->form_submission.has_value()) {
+ load(traversable().prepare_navigation(warning->url, {}, Web::Bindings::NavigationHistoryBehavior::Replace));
+ return;
+ }
+
+ auto navigation = traversable().prepare_navigation(warning->url, warning->form_submission.release_value(), Web::Bindings::NavigationHistoryBehavior::Replace);
+ navigation.csp_navigation_type = Web::ContentSecurityPolicy::Directives::NavigationType::FormSubmission;
+ navigation.initiator_origin_snapshot = move(warning->form_initiator_origin);
+ load(move(navigation));
+}
+
void ViewImplementation::reload(BypassCache bypass_cache)
{
m_history_visit_transition_for_next_load = HistoryVisitTransition::Reload;
@@ -1112,6 +1175,10 @@ void ViewImplementation::did_not_apply_reload()
void ViewImplementation::did_commit_history_step()
{
+ // A pending certificate warning belongs to the about:certificate page that shows it.
+ if (m_certificate_warning.has_value() && !url().equals(URL::URL::about("certificate"sv), URL::ExcludeFragment::Yes))
+ m_certificate_warning.clear();
+
did_update_url();
update_navigation_action_state();
}
@@ -1921,6 +1988,11 @@ static void send_global_privacy_control(WebContentPage const& page)
page.async_set_enable_global_privacy_control(Application::settings().global_privacy_control() == GlobalPrivacyControl::Yes);
}
+static void send_offer_to_trust_self_signed_certificates(WebContentPage const& page)
+{
+ page.async_set_offers_to_trust_self_signed_certificates(Application::settings().config_variable_as_bool(ConfigVariableID::OfferToTrustSelfSignedCertificates));
+}
+
// Only a page hosting the tab's traversable takes this request: It applies to the page's local traversable, which a page
// embedding an out-of-process iframe doesn't have.
static void send_force_dark(WebContentPage const& page)
@@ -1940,6 +2012,7 @@ void ViewImplementation::send_preferences_to_page(WebContentPage& page)
send_browsing_behavior(page);
send_autoplay_settings(page);
send_global_privacy_control(page);
+ send_offer_to_trust_self_signed_certificates(page);
auto* spell_checker = Application::the().spell_checker();
page.async_set_spell_checking_available(spell_checker != nullptr);
page.async_set_writing_suggestions_available(spell_checker && spell_checker->can_suggest());
@@ -5180,6 +5253,12 @@ void ViewImplementation::global_privacy_control_changed()
traversable().for_each_hosting_page(send_global_privacy_control);
}
+void ViewImplementation::config_variable_changed(ConfigVariableID id)
+{
+ if (id == ConfigVariableID::OfferToTrustSelfSignedCertificates)
+ traversable().for_each_hosting_page(send_offer_to_trust_self_signed_certificates);
+}
+
Vector<SitePermissionRow> ViewImplementation::site_permission_rows() const
{
auto origin = permission_origin();
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 136c2ae9ac6..ce80da24db1 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -285,6 +285,20 @@ public:
// A URL the user chose in the browser's UI. Loading a file: URL this way grants a root for that file.
void load_from_browser_ui(URL::URL const&, Web::Bindings::NavigationHistoryBehavior = Web::Bindings::NavigationHistoryBehavior::Auto);
+
+ // Shown by about:certificate so only the user, never a web page, can answer it.
+ struct CertificateWarning {
+ URL::URL url;
+ BrowsingSession::CertificateException certificate;
+ // Resubmit after trust: the failed TLS handshake prevented the server from receiving this form.
+ Optional<Web::HTML::POSTResource> form_submission;
+ URL::Origin form_initiator_origin;
+ // A form another site submitted isn't sent again: the browser's UI would send it as the user's own.
+ bool form_is_not_resent { false };
+ };
+ void did_request_certificate_warning(Badge<WebContentPage>, URL::URL const&, Web::HTML::CrossProcessId document_state_id);
+ Optional<CertificateWarning> const& certificate_warning() const { return m_certificate_warning; }
+ void answer_certificate_warning(Badge<CertificateUI>, URL::URL const& url, StringView fingerprint, bool trust);
void open_url_in_new_tab(URL::URL const&, Web::HTML::ActivateTab);
void open_url_in_new_window(URL::URL const&, IsPrivate);
void load(Web::HTML::PreparedNavigationDescriptor, LocalFileAccess = {});
@@ -960,6 +974,7 @@ protected:
virtual void autoplay_settings_changed() override;
virtual void permission_settings_changed(Web::Permissions::PermissionName name) override;
virtual void global_privacy_control_changed() override;
+ virtual void config_variable_changed(ConfigVariableID) override;
void send_context_menu_request(ContextMenuRequest, Gfx::IntPoint content_position);
void handle_external_url(URL::URL, URL::Origin, bool has_transient_activation);
@@ -1149,6 +1164,9 @@ protected:
Optional<WebDriverNavigationObservation> m_webdriver_navigation_observation;
Optional<NavigationToRetry> m_last_stopped_navigation;
+ Optional<CertificateWarning> m_certificate_warning;
+ Optional<BrowsingSession::CertificateException> m_declined_certificate;
+
// A view that shows the source of a page offers no source of its own to view: Each view of the source of a source
// page would wrap the one before in another layer of markup, without end. The source is the document of one
// document state, which a fragment navigation keeps and history traversal brings back.
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 688a9287b4a..acfc8344b36 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -1035,6 +1035,12 @@ void WebContentPage::did_find_in_page(size_t current_match_index, Optional<size_
}
}
+void WebContentPage::did_request_certificate_warning(URL::URL url, Web::HTML::CrossProcessId document_state_id)
+{
+ if (displays_tab())
+ view().did_request_certificate_warning({}, url, document_state_id);
+}
+
void WebContentPage::did_request_cursor_change(Gfx::Cursor cursor)
{
view().did_request_cursor_change({}, move(cursor));
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index ae697d8f63d..2f3086ac9b0 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -221,6 +221,7 @@ private:
virtual void did_set_browser_zoom(double factor) override;
virtual void did_set_device_pixel_ratio_for_testing(double device_pixel_ratio) override;
virtual void did_find_in_page(size_t current_match_index, Optional<size_t> total_match_count) override;
+ virtual void did_request_certificate_warning(URL::URL url, Web::HTML::CrossProcessId document_state_id) override;
virtual void did_request_cursor_change(Gfx::Cursor cursor) override;
virtual void did_update_editing_history_state(bool can_undo, bool can_redo) override;
virtual void did_set_text_fragment_indication_visibility(bool visible) override;
diff --git a/Libraries/LibWebView/WebUI.cpp b/Libraries/LibWebView/WebUI.cpp
index 1b736f93ed2..69f1e590c34 100644
--- a/Libraries/LibWebView/WebUI.cpp
+++ b/Libraries/LibWebView/WebUI.cpp
@@ -12,6 +12,7 @@
#include <LibWebView/WebUI.h>
#include <LibWebView/WebUI/AboutUI.h>
#include <LibWebView/WebUI/ApplicationWebUI.h>
+#include <LibWebView/WebUI/CertificateUI.h>
#include <LibWebView/WebUI/CrashReportsUI.h>
#include <LibWebView/WebUI/SettingsUI.h>
#include <LibWebView/WebUI/SupportUI.h>
@@ -20,6 +21,7 @@ namespace WebView {
static constexpr auto s_pages = to_array<WebUI::Page>({
{ "about"sv, "About URLs"sv, WebUI::PageType::Dynamic },
+ { "certificate"sv, "Certificate Warning"sv, WebUI::PageType::Dynamic },
{ "crashes"sv, "Crash Reports"sv, WebUI::PageType::Dynamic },
{ "licenses"sv, "Licenses"sv, WebUI::PageType::Static },
{ "newtab"sv, "New Tab"sv, WebUI::PageType::Static },
@@ -95,6 +97,8 @@ ErrorOr<RefPtr<WebUI>> WebUI::create(WebContentClient& client, Web::PageId page_
web_ui = TRY(create_web_ui<ApplicationWebUI>(client, page_id, move(host)));
else if (page->host == "about"sv)
web_ui = TRY(create_web_ui<AboutUI>(client, page_id, move(host)));
+ else if (page->host == "certificate"sv)
+ web_ui = TRY(create_web_ui<CertificateUI>(client, page_id, move(host)));
else if (page->host == "crashes"sv)
web_ui = TRY(create_web_ui<CrashReportsUI>(client, page_id, move(host)));
else if (page->host.is_one_of("settings"sv, "welcome"sv))
diff --git a/Libraries/LibWebView/WebUI/CertificateUI.cpp b/Libraries/LibWebView/WebUI/CertificateUI.cpp
new file mode 100644
index 00000000000..814ff54832c
--- /dev/null
+++ b/Libraries/LibWebView/WebUI/CertificateUI.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/JsonObject.h>
+#include <LibURL/Parser.h>
+#include <LibWebView/ViewImplementation.h>
+#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
+#include <LibWebView/WebUI/CertificateUI.h>
+
+namespace WebView {
+
+void CertificateUI::register_interfaces()
+{
+ register_interface("loadCertificateWarning"sv, [this](auto const&) {
+ load_certificate_warning();
+ });
+ register_interface("trustCertificate"sv, [this](auto const& data) {
+ answer_certificate_warning(data, true);
+ });
+ register_interface("rejectCertificate"sv, [this](auto const& data) {
+ answer_certificate_warning(data, false);
+ });
+}
+
+ViewImplementation* CertificateUI::view() const
+{
+ if (!has_client())
+ return nullptr;
+
+ auto* page = client().page(page_id());
+ if (!page || !page->displays_tab())
+ return nullptr;
+ return &page->view();
+}
+
+void CertificateUI::load_certificate_warning()
+{
+ auto* view = this->view();
+ if (!view || !view->certificate_warning().has_value()) {
+ async_send_message("loadCertificateWarning"sv, JsonValue {});
+ return;
+ }
+
+ auto const& warning = *view->certificate_warning();
+
+ JsonObject object;
+ // Use the URL to identify the answer, but display only the origin to omit credentials, paths and queries.
+ object.set("url"sv, warning.url.serialize());
+ object.set("origin"sv, warning.url.origin().serialize());
+ object.set("resendsForm"sv, warning.form_submission.has_value());
+ object.set("formIsNotResent"sv, warning.form_is_not_resent);
+ object.set("host"sv, MUST(String::from_byte_string(warning.certificate.host)));
+ object.set("fingerprint"sv, MUST(String::from_byte_string(warning.certificate.fingerprint)));
+ async_send_message("loadCertificateWarning"sv, move(object));
+}
+
+void CertificateUI::answer_certificate_warning(JsonValue const& data, bool trust)
+{
+ if (!data.is_object())
+ return;
+
+ auto url_string = data.as_object().get_string("url"sv);
+ auto fingerprint = data.as_object().get_string("fingerprint"sv);
+ if (!url_string.has_value() || !fingerprint.has_value())
+ return;
+
+ auto url = URL::Parser::basic_parse(*url_string);
+ if (!url.has_value())
+ return;
+
+ if (auto* view = this->view())
+ view->answer_certificate_warning({}, *url, *fingerprint, trust);
+}
+
+}
diff --git a/Libraries/LibWebView/WebUI/CertificateUI.h b/Libraries/LibWebView/WebUI/CertificateUI.h
new file mode 100644
index 00000000000..f8d9d75e7be
--- /dev/null
+++ b/Libraries/LibWebView/WebUI/CertificateUI.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWebView/WebUI.h>
+
+namespace WebView {
+
+// Only about:certificate can answer the warning: the UI process assigns it a WebUI process shared with no web page.
+class CertificateUI final : public WebUI {
+ WEB_UI(CertificateUI);
+
+private:
+ virtual void register_interfaces() override;
+
+ ViewImplementation* view() const;
+
+ void load_certificate_warning();
+ void answer_certificate_warning(JsonValue const&, bool trust);
+};
+
+}
diff --git a/Services/RequestServer/AIA.cpp b/Services/RequestServer/AIA.cpp
index 00b20ba4c94..951adf7948f 100644
--- a/Services/RequestServer/AIA.cpp
+++ b/Services/RequestServer/AIA.cpp
@@ -6,6 +6,7 @@
#include <LibCrypto/OpenSSL.h>
#include <RequestServer/AIA.h>
+#include <RequestServer/CertificateExceptions.h>
#include <AK/AnyOf.h>
#include <AK/ByteString.h>
@@ -32,6 +33,14 @@ namespace RequestServer {
// This max was chosen to align with the (telemetry-tuned) value Chromium uses.
static constexpr size_t max_ca_issuers_urls_per_certificate = 5;
+// On macOS, curl leaves OpenSSL's trust store empty, so OpenSSL cannot identify missing issuers or untrusted roots.
+// SecTrust fetches missing intermediates and verifies after the handshake unless OpenSSL already verified.
+#ifdef AK_OS_MACOS
+static constexpr bool openssl_trust_store_is_authoritative = false;
+#else
+static constexpr bool openssl_trust_store_is_authoritative = true;
+#endif
+
// Upper bound on the process-wide fetched-intermediate cache — so a long-lived process that visits many misconfigured
// sites can't grow it without limit.
static constexpr size_t max_cached_intermediates = 256;
@@ -189,6 +198,85 @@ static void promote_fetched_intermediates(X509_STORE_CTX* context, AIACollector&
}
}
+static bool is_self_signed_certificate_error(int verify_error)
+{
+ if (verify_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
+ return true;
+ // On macOS, OpenSSL's empty trust store rejects any chain containing its root, even if SecTrust trusts it.
+ return openssl_trust_store_is_authoritative && verify_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
+}
+
+static bool certificate_matches_host(X509* certificate, ByteString const& host)
+{
+ auto address = host.view();
+ if (address.starts_with('[') && address.ends_with(']'))
+ address = address.substring_view(1, address.length() - 2);
+
+ // Like curl, match an IP literal only against iPAddress names, and refuse partial wildcards such as w*.example.com.
+ // X509_check_ip_asc() returns -2 when the input is not an IP address.
+ auto address_string = ByteString { address };
+ if (auto result = X509_check_ip_asc(certificate, address_string.characters(), 0); result != -2)
+ return result == 1;
+
+ // Like curl, match a fully qualified name such as example.com. without its trailing dot.
+ auto name = host.view();
+ if (name.ends_with('.'))
+ name = name.substring_view(0, name.length() - 1);
+ return X509_check_host(certificate, name.characters_without_null_termination(), name.length(), X509_CHECK_FLAG_NEVER_CHECK_SUBJECT | X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS, nullptr) == 1;
+}
+
+// OpenSSL stops at a self-signed certificate before it checks validity periods, so check them here.
+static int validity_period_error(X509_STORE_CTX* context, X509* leaf)
+{
+ auto* chain = X509_STORE_CTX_get0_chain(context);
+ auto chain_length = chain ? sk_X509_num(chain) : 0;
+ for (int i = 0; i < max(chain_length, 1); ++i) {
+ auto* certificate = chain_length > 0 ? sk_X509_value(chain, i) : leaf;
+ auto not_before = X509_cmp_current_time(X509_get0_notBefore(certificate));
+ if (not_before == 0)
+ return X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
+ if (not_before > 0)
+ return X509_V_ERR_CERT_NOT_YET_VALID;
+ auto not_after = X509_cmp_current_time(X509_get0_notAfter(certificate));
+ if (not_after == 0)
+ return X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
+ if (not_after < 0)
+ return X509_V_ERR_CERT_HAS_EXPIRED;
+ }
+ return X509_V_OK;
+}
+
+static int apply_self_signed_certificate_exception(X509_STORE_CTX* context, AIACollector& collector)
+{
+ if (!is_self_signed_certificate_error(X509_STORE_CTX_get_error(context)))
+ return 0;
+
+ // NB: The certificate may be issued to another name. Devices on a local network often come with one for localhost,
+ // and the exception is for this certificate on this host and port only.
+ auto* leaf = X509_STORE_CTX_get0_cert(context);
+ if (!leaf)
+ return 0;
+
+ // Neither trusted nor offered to the user: no exception could make an out-of-date certificate valid.
+ if (auto error = validity_period_error(context, leaf); error != X509_V_OK) {
+ X509_STORE_CTX_set_error(context, error);
+ return 0;
+ }
+
+ auto fingerprint = certificate_fingerprint(leaf);
+ if (fingerprint.is_empty())
+ return 0;
+
+ if (has_certificate_exception(collector.host, collector.port, fingerprint)) {
+ // curl checks SSL_get_verify_result() after the handshake, which reports the error left on the context.
+ X509_STORE_CTX_set_error(context, X509_V_OK);
+ return 1;
+ }
+
+ collector.rejected_self_signed_certificate_fingerprint = move(fingerprint);
+ return 0;
+}
+
// Installed via SSL_CTX_set_cert_verify_callback. On failure, we record the failing cert's caIssuers URLs for the
// request layer to fetch and retry.
static int verify_callback(X509_STORE_CTX* context, void* collector_data)
@@ -216,6 +304,23 @@ static int verify_callback(X509_STORE_CTX* context, void* collector_data)
sk_X509_free(untrusted);
}
+ auto accepted_by_exception = false;
+ if (result <= 0 && collector) {
+ result = apply_self_signed_certificate_exception(context, *collector);
+ accepted_by_exception = result > 0;
+ }
+
+ // Only the certificate the user trusted may name another host. Fail the handshake for any other, as on macOS curl
+ // would otherwise go on to verify the chain with SecTrust, which then doesn't check the name either.
+ if (collector && collector->checks_host_name && !accepted_by_exception) {
+ auto* leaf = X509_STORE_CTX_get0_cert(context);
+ if (!leaf || !certificate_matches_host(leaf, collector->host)) {
+ if (result > 0)
+ X509_STORE_CTX_set_error(context, X509_V_ERR_HOSTNAME_MISMATCH);
+ return 0;
+ }
+ }
+
if (result > 0 && collector && !collector->fetched_intermediates.is_empty())
promote_fetched_intermediates(context, *collector);
@@ -224,7 +329,7 @@ static int verify_callback(X509_STORE_CTX* context, void* collector_data)
auto const verify_error = X509_STORE_CTX_get_error(context);
auto const issuer_is_missing = verify_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT || verify_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
- if (result <= 0 && collector && issuer_is_missing) {
+ if (result <= 0 && collector && issuer_is_missing && openssl_trust_store_is_authoritative) {
if (auto* current = X509_STORE_CTX_get_current_cert(context)) {
for (auto& url : ca_issuers_urls(current)) {
if (collector->attempted_urls.contains(url))
@@ -242,6 +347,10 @@ static int verify_callback(X509_STORE_CTX* context, void* collector_data)
// X509_verify_cert() returns -1 in exceptional cases, and a negative return from a cert_verify_callback tells
// OpenSSL to suspend the handshake and retry it later. Collapse it to a plain pass/fail.
+ // NB: With SSL_VERIFY_PEER (see apply_aia_verification()), let the handshake continue for these failures;
+ // curl reads the verification error from the context.
+ if (collector && collector->checks_host_name)
+ return 1;
return result > 0 ? 1 : 0;
}
@@ -269,6 +378,11 @@ void apply_aia_verification(SSL_CTX* ssl_context, AIACollector& collector)
return;
}
SSL_CTX_set_cert_verify_callback(ssl_context, verify_callback, &collector);
+
+ // curl sets SSL_VERIFY_NONE and looks at the verification result once the handshake is done. Then a host name
+ // mismatch found during verification has to fail the handshake.
+ if (collector.checks_host_name)
+ SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, SSL_CTX_get_verify_callback(ssl_context));
}
}
diff --git a/Services/RequestServer/AIA.h b/Services/RequestServer/AIA.h
index d2b2b6b2f60..a9225cc94c7 100644
--- a/Services/RequestServer/AIA.h
+++ b/Services/RequestServer/AIA.h
@@ -8,6 +8,7 @@
#include <AK/ByteString.h>
#include <AK/HashTable.h>
+#include <AK/Optional.h>
#include <AK/RefCounted.h>
#include <AK/RefPtr.h>
#include <AK/Span.h>
@@ -33,8 +34,19 @@ public:
// Only intermediates used in verified chains enter the shared cache, preventing unrelated-chain poisoning.
Vector<Crypto::OpenSSL_X509> fetched_intermediates;
+
+ // Certificate exceptions must match the request's host and port.
+ ByteString host;
+ u16 port { 0 };
+
+ // Verification checks the host name instead of curl when an exception may allow a certificate for another name.
+ bool checks_host_name { false };
+
+ Optional<ByteString> rejected_self_signed_certificate_fingerprint;
};
+// Accept self-signed certificates with user exceptions; otherwise record the rejected fingerprint in the collector.
+//
// During verification, any cert whose issuer we can't find locally or in the fetched-intermediate cache has its
// caIssuers URLs appended to collector.pending_urls (skipping ones already attempted or recently known dead).
void apply_aia_verification(SSL_CTX* ssl_context, AIACollector& collector);
diff --git a/Services/RequestServer/CMakeLists.txt b/Services/RequestServer/CMakeLists.txt
index 4b772bb4f74..0dade8670d5 100644
--- a/Services/RequestServer/CMakeLists.txt
+++ b/Services/RequestServer/CMakeLists.txt
@@ -1,6 +1,7 @@
set(SOURCES
AIA.cpp
AlternativeServices.cpp
+ CertificateExceptions.cpp
ConnectionFromClient.cpp
ControlConnectionFromClient.cpp
CURL.cpp
diff --git a/Services/RequestServer/CURL.cpp b/Services/RequestServer/CURL.cpp
index a2bbfdf6732..2763a64f899 100644
--- a/Services/RequestServer/CURL.cpp
+++ b/Services/RequestServer/CURL.cpp
@@ -9,6 +9,7 @@
#include <AK/Format.h>
#include <RequestServer/AIA.h>
#include <RequestServer/CURL.h>
+#include <RequestServer/CertificateExceptions.h>
#include <RequestServer/Resolver.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
@@ -85,25 +86,43 @@ static int verify_server_certificate_has_subject_alt_name(int preverify_ok, X509
return 0;
}
-CURLcode configure_ssl_context(CURL*, [[maybe_unused]] void* ssl_context, [[maybe_unused]] void* aia_collector)
+// Our SSL context callbacks require OpenSSL's SSL_CTX.
+static bool curl_uses_openssl()
{
- // Everything below casts ssl_context to an SSL_CTX, which only holds when curl is built against OpenSSL.
- [[maybe_unused]] static auto const curl_uses_openssl = [] {
+ static auto const uses_openssl = [] {
auto const* version_info = curl_version_info(CURLVERSION_NOW);
VERIFY(version_info);
return version_info->ssl_version && StringView { version_info->ssl_version, strlen(version_info->ssl_version) }.starts_with("OpenSSL/"sv);
}();
+ return uses_openssl;
+}
+
+CURLcode configure_certificate_verification(CURL* handle, AIACollector& collector)
+{
+ // Exceptions may allow another host name, so our OpenSSL verifier must check names instead of curl.
+ // Other backends keep curl's host name checks.
+ collector.checks_host_name = curl_uses_openssl() && has_any_certificate_exception(collector.host, collector.port);
+ if (auto result = curl_easy_setopt(handle, CURLOPT_SSL_CTX_FUNCTION, configure_ssl_context); result != CURLE_OK)
+ return result;
+ if (auto result = curl_easy_setopt(handle, CURLOPT_SSL_CTX_DATA, &collector); result != CURLE_OK)
+ return result;
+ return curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, collector.checks_host_name ? 0L : 2L);
+}
+
+CURLcode configure_ssl_context(CURL*, [[maybe_unused]] void* ssl_context, [[maybe_unused]] void* aia_collector)
+{
+ [[maybe_unused]] auto const uses_openssl = curl_uses_openssl();
#if defined(SSL_OP_IGNORE_UNEXPECTED_EOF)
// Some HTTPS servers, including the Python server used by WPT, close the connection without sending the
// mandatory TLS close-notify alert. Other browsers treat such a post-handshake transport EOF as a clean TLS EOF
// for compatibility. Do the same while leaving curl responsible for detecting incomplete HTTP framing.
- if (curl_uses_openssl)
+ if (uses_openssl)
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) {
+ if (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);
}
@@ -111,21 +130,21 @@ CURLcode configure_ssl_context(CURL*, [[maybe_unused]] void* ssl_context, [[mayb
// Offer only modern key exchange groups, with key shares for the two X25519 based groups. Some CDNs reject
// requests that have a browser User-Agent and the TLS fingerprint of a default OpenSSL client. OpenSSL older than
// 3.5 does not understand this syntax. It rejects the list and keeps its default groups.
- if (curl_uses_openssl) {
+ if (uses_openssl) {
char groups[] = "*X25519MLKEM768:*X25519:P-256:P-384";
if (SSL_CTX_set1_groups_list(static_cast<SSL_CTX*>(ssl_context), groups) != 1)
ERR_clear_error();
}
#ifdef AK_OS_MACOS
- if (curl_uses_openssl)
+ if (uses_openssl)
share_certificate_store(static_cast<SSL_CTX*>(ssl_context));
-#else
+#endif
// curl keeps one SSL context callback per handle, and AIA has to run against the same SSL_CTX configured above. So
// both are applied here. The collector arrives as CURLOPT_SSL_CTX_DATA and is null on handles lacking AIA state.
- if (curl_uses_openssl && aia_collector)
+ // NB: On macOS, curl uses SecTrust only if OpenSSL has not already verified the certificate.
+ if (uses_openssl && aia_collector)
apply_aia_verification(static_cast<SSL_CTX*>(ssl_context), *static_cast<AIACollector*>(aia_collector));
-#endif
return CURLE_OK;
}
diff --git a/Services/RequestServer/CURL.h b/Services/RequestServer/CURL.h
index 0dacd2adfdb..06462b65b87 100644
--- a/Services/RequestServer/CURL.h
+++ b/Services/RequestServer/CURL.h
@@ -23,6 +23,8 @@
namespace RequestServer {
+class AIACollector;
+
// CURLOPT_RESOLVE entries look like "[+]HOST:PORT:ADDRESS[,ADDRESS]", and "-HOST:PORT" removes an entry, so a host
// beginning with either sign cannot be pinned. Callers must not resolve such hosts through the resolve list at all.
bool can_pin_host_in_curl_resolve_list(StringView host);
@@ -36,7 +38,10 @@ Optional<ByteString> build_curl_connect_to_entry(DNS::LookupResult const& dns_re
Requests::NetworkError curl_code_to_network_error(int code);
ErrorOr<void> initialize_libcurl();
-// A CURLOPT_SSL_CTX_FUNCTION. Its CURLOPT_SSL_CTX_DATA is the handle's AIACollector, or null to skip AIA.
+// The caller keeps the collector alive until the handle is cleaned up, including if the TLS handshake fails.
+CURLcode configure_certificate_verification(CURL*, AIACollector&);
+
+// A CURLOPT_SSL_CTX_FUNCTION. Its CURLOPT_SSL_CTX_DATA is the handle's AIACollector.
CURLcode configure_ssl_context(CURL*, void* ssl_context, void* aia_collector);
}
diff --git a/Services/RequestServer/CertificateExceptions.cpp b/Services/RequestServer/CertificateExceptions.cpp
new file mode 100644
index 00000000000..261a3943e3c
--- /dev/null
+++ b/Services/RequestServer/CertificateExceptions.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashMap.h>
+#include <AK/HashTable.h>
+#include <AK/StringBuilder.h>
+#include <RequestServer/CertificateExceptions.h>
+
+#if defined(AK_OS_WINDOWS)
+// Included before the OpenSSL headers so the winsock2 struct timeval is renamed and can't collide with AK's.
+# include <AK/Windows.h>
+#endif
+
+#include <openssl/evp.h>
+#include <openssl/x509.h>
+
+namespace RequestServer {
+
+static HashMap<ByteString, HashTable<ByteString>>& certificate_exceptions()
+{
+ static HashMap<ByteString, HashTable<ByteString>> exceptions;
+ return exceptions;
+}
+
+static ByteString exception_key(ByteString const& host, u16 port)
+{
+ return ByteString::formatted("{}:{}", host, port);
+}
+
+ByteString certificate_fingerprint(X509* certificate)
+{
+ u8 digest[EVP_MAX_MD_SIZE];
+ unsigned int digest_length = 0;
+ if (X509_digest(certificate, EVP_sha256(), digest, &digest_length) != 1)
+ return {};
+
+ StringBuilder builder;
+ for (unsigned int i = 0; i < digest_length; ++i)
+ builder.appendff("{:02x}", digest[i]);
+ return builder.to_byte_string();
+}
+
+void add_certificate_exception(ByteString const& host, u16 port, ByteString fingerprint)
+{
+ if (fingerprint.is_empty())
+ return;
+ certificate_exceptions().ensure(exception_key(host, port)).set(move(fingerprint));
+}
+
+bool has_certificate_exception(ByteString const& host, u16 port, ByteString const& fingerprint)
+{
+ if (fingerprint.is_empty())
+ return false;
+ auto exceptions = certificate_exceptions().get(exception_key(host, port));
+ return exceptions.has_value() && exceptions->contains(fingerprint);
+}
+
+bool has_any_certificate_exception(ByteString const& host, u16 port)
+{
+ return certificate_exceptions().contains(exception_key(host, port));
+}
+
+}
diff --git a/Services/RequestServer/CertificateExceptions.h b/Services/RequestServer/CertificateExceptions.h
new file mode 100644
index 00000000000..4895922b676
--- /dev/null
+++ b/Services/RequestServer/CertificateExceptions.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteString.h>
+#include <AK/Types.h>
+#include <LibTLS/OpenSSLForward.h>
+
+namespace RequestServer {
+
+// The hex-encoded SHA-256 digest of a certificate's DER encoding.
+ByteString certificate_fingerprint(X509* certificate);
+
+// The UI process grants exceptions for user-trusted certificates that fail verification.
+// Each is limited to one host and port and lasts for this process's lifetime.
+void add_certificate_exception(ByteString const& host, u16 port, ByteString fingerprint);
+bool has_certificate_exception(ByteString const& host, u16 port, ByteString const& fingerprint);
+bool has_any_certificate_exception(ByteString const& host, u16 port);
+
+}
diff --git a/Services/RequestServer/ConnectionFromClient.cpp b/Services/RequestServer/ConnectionFromClient.cpp
index 893eacc7af3..f8edffa119a 100644
--- a/Services/RequestServer/ConnectionFromClient.cpp
+++ b/Services/RequestServer/ConnectionFromClient.cpp
@@ -1070,7 +1070,7 @@ void ConnectionFromClient::open_websocket(u64 websocket_id, u64 originating_page
if (auto const& path = default_certificate_path(); !path.is_empty())
connection_info.set_root_certificates_path(path);
- auto impl = WebSocketImplCurl::create(m_websocket_curl.handle);
+ auto impl = WebSocketImplCurl::create(m_websocket_curl.handle, m_is_private);
impl->set_proxy(move(proxy));
impl->set_performance_origin(client_id(), originating_page_id);
auto connection = WebSocket::WebSocket::create(move(connection_info), move(impl));
diff --git a/Services/RequestServer/ControlConnectionFromClient.cpp b/Services/RequestServer/ControlConnectionFromClient.cpp
index 0986357e6b3..0b85784e3ff 100644
--- a/Services/RequestServer/ControlConnectionFromClient.cpp
+++ b/Services/RequestServer/ControlConnectionFromClient.cpp
@@ -8,6 +8,7 @@
#include <LibHTTP/Cache/DiskCache.h>
#include <LibIPC/TransportHandle.h>
#include <RequestServer/AlternativeServices.h>
+#include <RequestServer/CertificateExceptions.h>
#include <RequestServer/ControlConnectionFromClient.h>
#include <RequestServer/Request.h>
#include <RequestServer/Resolver.h>
@@ -199,6 +200,11 @@ void ControlConnectionFromClient::set_proxy_configuration(HTTP::ProxyConfigurati
RequestServer::set_proxy_configuration(move(proxy_configuration));
}
+void ControlConnectionFromClient::trust_certificate(ByteString host, u16 port, ByteString fingerprint)
+{
+ add_certificate_exception(host, port, move(fingerprint));
+}
+
void ControlConnectionFromClient::set_performance_monitor_enabled(bool enabled)
{
Request::set_performance_monitor_enabled(enabled);
diff --git a/Services/RequestServer/ControlConnectionFromClient.h b/Services/RequestServer/ControlConnectionFromClient.h
index b31878960fd..4c694415601 100644
--- a/Services/RequestServer/ControlConnectionFromClient.h
+++ b/Services/RequestServer/ControlConnectionFromClient.h
@@ -53,6 +53,8 @@ private:
virtual void set_proxy_configuration(HTTP::ProxyConfiguration) override;
+ virtual void trust_certificate(ByteString host, u16 port, ByteString fingerprint) override;
+
virtual void set_performance_monitor_enabled(bool) override;
virtual void estimate_cache_size_accessed_since(u64 cache_size_estimation_id, UnixDateTime since) override;
diff --git a/Services/RequestServer/Request.cpp b/Services/RequestServer/Request.cpp
index 94c0b5973ca..0c8b1182ae6 100644
--- a/Services/RequestServer/Request.cpp
+++ b/Services/RequestServer/Request.cpp
@@ -21,6 +21,7 @@
#include <LibTextCodec/Decoder.h>
#include <RequestServer/AIA.h>
#include <RequestServer/CURL.h>
+#include <RequestServer/CertificateExceptions.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/ControlConnectionFromClient.h>
#include <RequestServer/Request.h>
@@ -580,6 +581,7 @@ NonnullOwnPtr<Request> Request::import(
request->m_import = Import {};
request->m_import->body_fd = exported.body.take_fd();
request->m_import->status_fd = exported.status.take_fd();
+ request->m_import->may_rely_on_certificate_exception = exported.may_rely_on_certificate_exception;
request->transition_to_state(State::ReadImported);
return request;
}
@@ -756,6 +758,9 @@ void Request::handle_fetch_complete(int result_code)
m_alternative_services_disabled = true;
m_alternative_service.clear();
m_dns_result = nullptr;
+ // The origin may present another certificate than the alternative service did.
+ if (m_aia_collector)
+ m_aia_collector->rejected_self_signed_certificate_fingerprint.clear();
MUST(free_curl_structs());
reset_for_retry();
@@ -798,7 +803,8 @@ void Request::handle_fetch_complete(int result_code)
if (is_revalidation_request()) {
auto is_not_modified = result_code == CURLE_OK && acquire_status_code() == 304;
- if (is_not_modified && HTTP::can_freshen_stored_response(m_cache_entry_reader->response_headers(), *m_response_headers)) {
+ // As with storing a response, a 304 that may rely on a certificate exception must not extend a stored one.
+ if (is_not_modified && !may_rely_on_certificate_exception() && HTTP::can_freshen_stored_response(m_cache_entry_reader->response_headers(), *m_response_headers)) {
if (m_type == RequestType::BackgroundRevalidation && m_disk_cache->mode() == HTTP::DiskCache::Mode::Testing)
m_response_headers->set({ HTTP::TEST_CACHE_REVALIDATION_STATUS_HEADER, "fresh"sv });
@@ -945,8 +951,10 @@ void Request::retry_after_aia(Badge<ConnectionFromClient>)
MUST(free_curl_structs());
m_curl_result_code = {};
- if (m_aia_collector)
+ if (m_aia_collector) {
m_aia_collector->pending_urls.clear();
+ m_aia_collector->rejected_self_signed_certificate_fingerprint.clear();
+ }
transition_to_state(State::Fetch);
}
@@ -1403,6 +1411,29 @@ void Request::handle_retrieve_cookie_state()
}
}
+// Imported responses rely on the exporter to report certificate exceptions this RequestServer cannot see.
+bool Request::may_rely_on_certificate_exception() const
+{
+ if (m_import.has_value())
+ return m_import->may_rely_on_certificate_exception;
+ return m_aia_collector && has_any_certificate_exception(m_aia_collector->host, m_aia_collector->port);
+}
+
+bool Request::configure_certificate_verification()
+{
+ if (!m_aia_collector) {
+ m_aia_collector = make_ref_counted<AIACollector>(m_client->is_private());
+ m_aia_collector->host = m_url.serialized_host().to_byte_string();
+ m_aia_collector->port = m_url.port_or_default();
+ }
+ if (auto result = RequestServer::configure_certificate_verification(m_curl_easy_handle, *m_aia_collector); result != CURLE_OK) {
+ m_curl_result_code = result;
+ transition_to_state(State::Error);
+ return false;
+ }
+ return true;
+}
+
void Request::handle_connect_state()
{
m_curl_easy_handle = curl_easy_init();
@@ -1420,7 +1451,8 @@ void Request::handle_connect_state()
set_option(CURLOPT_NOSIGNAL, 1L);
- set_option(CURLOPT_SSL_CTX_FUNCTION, configure_ssl_context);
+ if (!configure_certificate_verification())
+ return;
set_option(CURLOPT_URL, url_without_credentials(m_url).characters());
set_option(CURLOPT_DISALLOW_USERNAME_IN_URL, 1L);
@@ -1470,12 +1502,8 @@ void Request::handle_fetch_state()
if (auto const& path = default_certificate_path(); !path.is_empty())
set_option(CURLOPT_CAINFO, path.characters());
- set_option(CURLOPT_SSL_CTX_FUNCTION, configure_ssl_context);
-#ifndef AK_OS_MACOS
- if (!m_aia_collector)
- m_aia_collector = make_ref_counted<AIACollector>(m_client->is_private());
- set_option(CURLOPT_SSL_CTX_DATA, m_aia_collector.ptr());
-#endif
+ if (!configure_certificate_verification())
+ return;
if (m_content_decoding_disabled) {
set_option(CURLOPT_ACCEPT_ENCODING, "identity");
@@ -1660,6 +1688,13 @@ void Request::handle_complete_state()
if (m_curl_result_code != CURLE_OK) {
m_network_error = curl_code_to_network_error(*m_curl_result_code);
+ if (m_network_error == Requests::NetworkError::SSLVerificationFailed && m_aia_collector && m_aia_collector->rejected_self_signed_certificate_fingerprint.has_value()) {
+ m_network_error = Requests::NetworkError::SSLSelfSignedCertificate;
+
+ if (auto control_connection = ControlConnectionFromClient::the(); control_connection.has_value())
+ control_connection->async_rejected_self_signed_certificate(m_aia_collector->host, m_aia_collector->port, *m_aia_collector->rejected_self_signed_certificate_fingerprint);
+ }
+
if (m_network_error == Requests::NetworkError::Unknown) {
char const* curl_error_message = curl_easy_strerror(static_cast<CURLcode>(*m_curl_result_code));
dbgln("Request::handle_complete_state: Unable to map error ({}): \"\033[31;1m{}\033[0m\"", *m_curl_result_code, curl_error_message);
@@ -1750,6 +1785,7 @@ Request::Import::Import(Import&& other)
, body_notifier(move(other.body_notifier))
, status_notifier(move(other.status_notifier))
, body_ended(other.body_ended)
+ , may_rely_on_certificate_exception(other.may_rely_on_certificate_exception)
, status_bytes(move(other.status_bytes))
, timing_info(move(other.timing_info))
, network_error(move(other.network_error))
@@ -1805,6 +1841,7 @@ ErrorOr<Requests::ExportedRequest> Request::export_response()
.status_code = m_status_code,
.reason_phrase = m_reason_phrase,
.response_headers = m_response_headers->headers(),
+ .may_rely_on_certificate_exception = may_rely_on_certificate_exception(),
.body = move(body),
.status = move(status),
};
@@ -2227,6 +2264,12 @@ void Request::transfer_headers_to_client_if_needed()
if (m_disk_cache.has_value() && m_disk_cache_partition.has_value() && !m_method.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv, "TRACE"sv) && *m_status_code >= 200 && *m_status_code < 400)
m_disk_cache->invalidate(*m_disk_cache_partition, m_url);
+ // Cached responses could outlive a certificate exception and be served without the server presenting a certificate.
+ if (m_cache_entry_writer.has_value() && may_rely_on_certificate_exception()) {
+ close_disk_cache_entry(DiskCacheEntryOutcome::Incomplete);
+ m_cache_status = CacheStatus::NotCached;
+ }
+
if (m_cache_entry_writer.has_value()) {
if (m_cache_entry_writer->write_status_and_reason(*m_status_code, m_reason_phrase, m_request_headers, m_response_headers).is_error()) {
m_cache_status = CacheStatus::NotCached;
diff --git a/Services/RequestServer/Request.h b/Services/RequestServer/Request.h
index 00232f92aa6..7e1c467e1e8 100644
--- a/Services/RequestServer/Request.h
+++ b/Services/RequestServer/Request.h
@@ -240,6 +240,8 @@ private:
bool should_retry_without_alternative_service(int curl_result_code) const;
u16 connect_port() const;
void handle_retrieve_cookie_state();
+ bool configure_certificate_verification();
+ bool may_rely_on_certificate_exception() const;
void handle_connect_state();
void handle_fetch_state();
void handle_read_imported_state();
@@ -423,6 +425,7 @@ private:
RefPtr<Core::Notifier> body_notifier;
RefPtr<Core::Notifier> status_notifier;
bool body_ended { false };
+ bool may_rely_on_certificate_exception { false };
ByteBuffer status_bytes;
Optional<Requests::RequestTimingInfo> timing_info;
Optional<Requests::NetworkError> network_error;
diff --git a/Services/RequestServer/RequestServerControl.ipc b/Services/RequestServer/RequestServerControl.ipc
index 177df17423e..24c855365db 100644
--- a/Services/RequestServer/RequestServerControl.ipc
+++ b/Services/RequestServer/RequestServerControl.ipc
@@ -28,6 +28,9 @@ endpoint RequestServerControl
set_proxy_configuration(HTTP::ProxyConfiguration proxy_configuration) =|
+ // Synchronous so the exception applies before the UI process reloads.
+ trust_certificate(ByteString host, u16 port, ByteString fingerprint) => ()
+
set_performance_monitor_enabled(bool enabled) =|
estimate_cache_size_accessed_since(u64 cache_size_estimation_id, UnixDateTime since) =|
diff --git a/Services/RequestServer/RequestServerControlClient.ipc b/Services/RequestServer/RequestServerControlClient.ipc
index 20bd1057dcc..6f32575ddde 100644
--- a/Services/RequestServer/RequestServerControlClient.ipc
+++ b/Services/RequestServer/RequestServerControlClient.ipc
@@ -16,6 +16,8 @@ endpoint RequestServerControlClient
retrieve_http_cookie(int client_id, u64 request_id, ::RequestServer::RequestType request_type, u64 cookie_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context) =|
store_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id, URL::URL url, Optional<HTTP::Cookie::PartitionContext> partition_context, HTTP::Cookie::SameSiteContext same_site_context, Vector<HTTP::Cookie::ParsedCookie> cookies, Optional<HTTP::HSTS::ParsedHSTSPolicy> hsts_policy) =|
+ rejected_self_signed_certificate(ByteString host, u16 port, ByteString fingerprint) =|
+
network_usage(Vector<Requests::NetworkUsage> usage, u64 interval_microseconds) =|
estimated_cache_size(u64 cache_size_estimation_id, Requests::CacheSizes sizes) =|
diff --git a/Services/RequestServer/WebSocketImplCurl.cpp b/Services/RequestServer/WebSocketImplCurl.cpp
index 5fddc6e41a3..310f00cd57e 100644
--- a/Services/RequestServer/WebSocketImplCurl.cpp
+++ b/Services/RequestServer/WebSocketImplCurl.cpp
@@ -6,6 +6,7 @@
#include <AK/ScopeGuard.h>
#include <LibCore/Notifier.h>
+#include <RequestServer/AIA.h>
#include <RequestServer/CURL.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/Request.h>
@@ -16,13 +17,14 @@ namespace RequestServer {
static constexpr long s_connect_timeout_seconds = 90L;
-NonnullRefPtr<WebSocketImplCurl> WebSocketImplCurl::create(CURLM* multi_handle)
+NonnullRefPtr<WebSocketImplCurl> WebSocketImplCurl::create(CURLM* multi_handle, IsPrivate is_private)
{
- return adopt_ref(*new WebSocketImplCurl(multi_handle));
+ return adopt_ref(*new WebSocketImplCurl(multi_handle, is_private));
}
-WebSocketImplCurl::WebSocketImplCurl(CURLM* multi_handle)
+WebSocketImplCurl::WebSocketImplCurl(CURLM* multi_handle, IsPrivate is_private)
: m_multi_handle(multi_handle)
+ , m_aia_collector(make_ref_counted<AIACollector>(is_private))
{
}
@@ -84,7 +86,12 @@ void WebSocketImplCurl::connect(WebSocket::ConnectionInfo const& info)
if (auto root_certs = info.root_certificates_path(); root_certs.has_value())
set_option(CURLOPT_CAINFO, root_certs->characters());
- set_option(CURLOPT_SSL_CTX_FUNCTION, configure_ssl_context);
+ m_aia_collector->host = url.serialized_host().to_byte_string();
+ m_aia_collector->port = url.port_or_default();
+ if (configure_certificate_verification(m_easy_handle, *m_aia_collector) != CURLE_OK) {
+ on_connection_error();
+ return;
+ }
auto const origin_header = ByteString::formatted("Origin: {}", info.origin());
curl_slist* curl_headers = curl_slist_append(nullptr, origin_header.characters());
diff --git a/Services/RequestServer/WebSocketImplCurl.h b/Services/RequestServer/WebSocketImplCurl.h
index 4a34941e743..9fc7c0f8d73 100644
--- a/Services/RequestServer/WebSocketImplCurl.h
+++ b/Services/RequestServer/WebSocketImplCurl.h
@@ -11,6 +11,7 @@
#include <LibHTTP/Proxy.h>
#include <LibRequests/NetworkUsage.h>
#include <LibWebSocket/Impl/WebSocketImpl.h>
+#include <RequestServer/IsPrivate.h>
typedef void CURL;
typedef void CURLM;
@@ -18,11 +19,13 @@ struct curl_slist;
namespace RequestServer {
+class AIACollector;
+
class WebSocketImplCurl final : public WebSocket::WebSocketImpl {
public:
virtual ~WebSocketImplCurl() override;
- static NonnullRefPtr<WebSocketImplCurl> create(CURLM*);
+ static NonnullRefPtr<WebSocketImplCurl> create(CURLM*, IsPrivate);
void set_proxy(Optional<HTTP::Proxy> proxy) { m_proxy = move(proxy); }
void set_performance_origin(int client_id, u64 page_id) { m_performance_origin = { client_id, page_id, 0, 0 }; }
@@ -36,7 +39,7 @@ public:
bool did_connect();
private:
- explicit WebSocketImplCurl(CURLM*);
+ WebSocketImplCurl(CURLM*, IsPrivate);
void read_from_socket();
bool flush_pending_write_buffer();
@@ -46,6 +49,7 @@ private:
Optional<HTTP::Proxy> m_proxy;
Requests::NetworkUsage m_performance_origin;
CURL* m_easy_handle { nullptr };
+ NonnullRefPtr<AIACollector> m_aia_collector;
RefPtr<Core::Notifier> m_read_notifier;
RefPtr<Core::Notifier> m_write_notifier;
RefPtr<Core::Notifier> m_error_notifier;
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index f9b38875b2c..976aaa02cd3 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -4118,6 +4118,12 @@ void ConnectionFromClient::set_has_picture_in_picture_support(Web::PageId page_i
page->page().picture_in_picture_controller().set_has_picture_in_picture_support(has_support);
}
+void ConnectionFromClient::set_offers_to_trust_self_signed_certificates(Web::PageId page_id, bool offers)
+{
+ if (auto page = this->page(page_id); page.has_value())
+ page->page().set_offers_to_trust_self_signed_certificates(offers);
+}
+
void ConnectionFromClient::did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size)
{
if (auto page = this->page(page_id); page.has_value())
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index ccc4ab65305..4bcbaff8f41 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -378,6 +378,7 @@ private:
virtual void exit_fullscreen(Web::PageId page_id) override;
virtual void set_has_picture_in_picture_support(Web::PageId page_id, bool has_support) override;
+ virtual void set_offers_to_trust_self_signed_certificates(Web::PageId page_id, bool offers) override;
virtual void did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size) override;
virtual void picture_in_picture_window_did_resize(Web::PageId page_id, Gfx::IntSize window_size) override;
virtual void picture_in_picture_window_did_close(Web::PageId page_id, bool pause_video) override;
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 1b017c6791e..7dba53c9b0c 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -974,6 +974,12 @@ void PageClient::page_did_set_text_fragment_indication_visibility(bool visible)
{
client().async_did_set_text_fragment_indication_visibility(m_id, visible);
}
+
+void PageClient::page_did_request_certificate_warning(URL::URL const& url, Web::HTML::CrossProcessId document_state_id)
+{
+ client().async_did_request_certificate_warning(m_id, url, document_state_id);
+}
+
void PageClient::page_did_request_resize_window(Gfx::IntSize size, u64 completion_id)
{
client().async_did_request_resize_window(m_id, size, completion_id);
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 99d4e7036ea..aeec7b2f6e0 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -262,6 +262,7 @@ private:
virtual void page_did_change_title(Utf16String const&) override;
virtual void page_did_update_editing_history_state(bool can_undo, bool can_redo) override;
virtual void page_did_set_text_fragment_indication_visibility(bool) override;
+ virtual void page_did_request_certificate_warning(URL::URL const&, Web::HTML::CrossProcessId document_state_id) override;
virtual void page_did_request_resize_window(Gfx::IntSize, u64 completion_id) override;
virtual void page_did_request_reposition_window(Gfx::IntPoint, u64 completion_id) override;
virtual void page_did_request_restore_window() override;
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index e76cb2abaae..51cb2ccce53 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -121,6 +121,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_receive_download_data(Web::PageId page_id, u64 download_id, ByteBuffer data) =|
did_finish_download(Web::PageId page_id, u64 download_id) =|
did_fail_download(Web::PageId page_id, u64 download_id, String error) =|
+ did_request_certificate_warning(Web::PageId page_id, URL::URL url, Web::HTML::CrossProcessId document_state_id) =|
did_request_cursor_change(Web::PageId page_id, Gfx::Cursor cursor) =|
did_change_title(Web::PageId page_id, Utf16String title) =|
did_update_editing_history_state(Web::PageId page_id, bool can_undo, bool can_redo) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index 94083a7e466..f2b6a9b60b4 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -355,6 +355,7 @@ endpoint WebContentServer routed by Web::PageId page_id
exit_fullscreen(Web::PageId page_id) =|
set_has_picture_in_picture_support(Web::PageId page_id, bool has_support) =|
+ set_offers_to_trust_self_signed_certificates(Web::PageId page_id, bool offers) =|
did_open_picture_in_picture_window(Web::PageId page_id, Gfx::IntSize window_size) =|
picture_in_picture_window_did_resize(Web::PageId page_id, Gfx::IntSize window_size) =|
picture_in_picture_window_did_close(Web::PageId page_id, bool pause_video) =|
diff --git a/Tests/LibWebView/TestOmnibox.cpp b/Tests/LibWebView/TestOmnibox.cpp
index ea2533e2fac..fa260e02b1b 100644
--- a/Tests/LibWebView/TestOmnibox.cpp
+++ b/Tests/LibWebView/TestOmnibox.cpp
@@ -349,6 +349,7 @@ TEST_CASE(all_web_ui_pages_are_suggested)
{
static constexpr Array expected_urls {
"about:about"sv,
+ "about:certificate"sv,
"about:crashes"sv,
"about:licenses"sv,
"about:newtab"sv,
diff --git a/Tests/RequestServer/CMakeLists.txt b/Tests/RequestServer/CMakeLists.txt
index a5eec6bbf41..2357832cd13 100644
--- a/Tests/RequestServer/CMakeLists.txt
+++ b/Tests/RequestServer/CMakeLists.txt
@@ -20,7 +20,7 @@ if (LINUX)
endif()
if (NOT WIN32)
- list(APPEND TEST_SOURCES TestHTTP2ConnectionSpecificFields.cpp)
+ list(APPEND TEST_SOURCES TestCertificateExceptions.cpp TestHTTP2ConnectionSpecificFields.cpp)
endif()
target_sources(TestRequestServer PRIVATE ${TEST_SOURCES})
diff --git a/Tests/RequestServer/TestCertificateExceptions.cpp b/Tests/RequestServer/TestCertificateExceptions.cpp
new file mode 100644
index 00000000000..ce60b75842b
--- /dev/null
+++ b/Tests/RequestServer/TestCertificateExceptions.cpp
@@ -0,0 +1,491 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <AK/Base64.h>
+#include <AK/ByteString.h>
+#include <AK/Optional.h>
+#include <AK/ScopeGuard.h>
+#include <AK/StringBuilder.h>
+#include <AK/Time.h>
+#include <LibCrypto/Hash/Hash.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+#include <LibURL/Parser.h>
+#include <RequestServer/AIA.h>
+#include <RequestServer/CURL.h>
+#include <RequestServer/CertificateExceptions.h>
+#include <RequestServer/Resolver.h>
+#include <RequestServer/WebSocketImplCurl.h>
+
+#include <arpa/inet.h>
+#include <curl/curl.h>
+#include <netinet/in.h>
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <signal.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+// Generated certificate fixtures (EC/prime256v1, fixed validity 2020-2050):
+// - SELF_SIGNED_A, SELF_SIGNED_B: certificates for localhost and 127.0.0.1, as often found on local network devices.
+// - CA: "Certificate Exception Test CA", the only trusted root.
+// - OTHER_NAME: issued by CA to other.test.
+// - DEVICE_NAME: issued by CA to device.test, the host every request goes to.
+// - EXPIRED_SELF_SIGNED: like SELF_SIGNED_A, but valid only during 2000.
+// - NAME_TEST_CA: "Certificate Exception Name Test CA", trusted only by the name matching tests.
+// - PARTIAL_WILDCARD: issued by NAME_TEST_CA to DNS:w*.device.test.
+// - IP_AS_DNS_NAME: issued by NAME_TEST_CA to DNS:127.0.0.1, without an iPAddress name.
+static constexpr auto self_signed_a_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBZDCCAQqgAwIBAgIBATAKBggqhkjOPQQDAjAUMRIwEAYDVQQDDAlsb2NhbGhv
+c3QwIBcNMjAwMTAxMDAwMDAwWhgPMjA1MDAxMDEwMDAwMDBaMBQxEjAQBgNVBAMM
+CWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABO9Zmgz9JJ+yYsdb
+68yZNCiZH7nTRbPx2x7JRn1XHiHjASAYVGUodkvAlIRshFm4oykktaRIsKj1tFVs
+Y+IhwA+jSzBJMB0GA1UdDgQWBBT190sAlEy0XYzmE9mPvTY+pHrusDAaBgNVHREE
+EzARgglsb2NhbGhvc3SHBH8AAAEwDAYDVR0TAQH/BAIwADAKBggqhkjOPQQDAgNI
+ADBFAiAptd6uWBDjWlh8EqsB14lrQ1pz+Rf+5OaPDPgTMtxrBQIhALF84JTwcteB
+a9KHLuihxdmnOEJHCOvmkyPTo5C0l+eG
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto self_signed_a_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgy9/s6BM6FpyYR9Lq
+gbX/FNOKvPDW8NSdr0W2k9rHT2WhRANCAATvWZoM/SSfsmLHW+vMmTQomR+500Wz
+8dseyUZ9Vx4h4wEgGFRlKHZLwJSEbIRZuKMpJLWkSLCo9bRVbGPiIcAP
+-----END PRIVATE KEY-----)PEM"sv;
+static constexpr auto self_signed_b_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBZDCCAQqgAwIBAgIBATAKBggqhkjOPQQDAjAUMRIwEAYDVQQDDAlsb2NhbGhv
+c3QwIBcNMjAwMTAxMDAwMDAwWhgPMjA1MDAxMDEwMDAwMDBaMBQxEjAQBgNVBAMM
+CWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABO+lbIADnuw8EzYD
+VxLZM5Ylb4/Bzub2K+mjBKpW2A5riYsVt8JlVVjLoDgR/A/wURFz875O4/bMllRT
+Y/VLMy6jSzBJMB0GA1UdDgQWBBSN/v6hQeVmC9hdwpDiIv0gMCK/NzAaBgNVHREE
+EzARgglsb2NhbGhvc3SHBH8AAAEwDAYDVR0TAQH/BAIwADAKBggqhkjOPQQDAgNI
+ADBFAiBbHM0jkzqs8ayK9uudf0pDK+yBLqP+n1jjv1AwBY1wHwIhANevnjgnJYJ+
+QYHtA90qRSZzF88B3WieMuZXzzszXEXM
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto self_signed_b_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCrzyL/sUk5v7lfIU
+jK3bfEkeHFQEZOai+87RG+MwneKhRANCAATvpWyAA57sPBM2A1cS2TOWJW+Pwc7m
+9ivpowSqVtgOa4mLFbfCZVVYy6A4EfwP8FERc/O+TuP2zJZUU2P1SzMu
+-----END PRIVATE KEY-----)PEM"sv;
+static constexpr auto ca_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBdDCCARmgAwIBAgIBATAKBggqhkjOPQQDAjAoMSYwJAYDVQQDDB1DZXJ0aWZp
+Y2F0ZSBFeGNlcHRpb24gVGVzdCBDQTAgFw0yMDAxMDEwMDAwMDBaGA8yMDUwMDEw
+MTAwMDAwMFowKDEmMCQGA1UEAwwdQ2VydGlmaWNhdGUgRXhjZXB0aW9uIFRlc3Qg
+Q0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATEEi1yk5a7Sxn3oAC7KR8FPPAJ
+qfOQXFxopx97KL3+llTlqWixgpxYcNm+WHryfAgTGo52y0OGKtAMqQp8xiLdozIw
+MDAdBgNVHQ4EFgQU2xKqM4jS50/iBg0ClmBTVoKav7owDwYDVR0TAQH/BAUwAwEB
+/zAKBggqhkjOPQQDAgNJADBGAiEAoYypwtjKWGMJWq3owgdvmMkRFUfxyFkq6Rb6
+Ki145MkCIQDl+r81A2QTv68DQXITfh0KweDR/su9BcHjfPcoN6Kp7w==
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto other_name_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBVTCB+6ADAgECAgECMAoGCCqGSM49BAMCMCgxJjAkBgNVBAMMHUNlcnRpZmlj
+YXRlIEV4Y2VwdGlvbiBUZXN0IENBMCAXDTIwMDEwMTAwMDAwMFoYDzIwNTAwMTAx
+MDAwMDAwWjAVMRMwEQYDVQQDDApvdGhlci50ZXN0MFkwEwYHKoZIzj0CAQYIKoZI
+zj0DAQcDQgAE7Ie4T89950YWnYRiu/5tyIwPXEMkbX9Sh4tJds9U9FV/t3vf+ctw
+LgP+ZlAOV2vrQHUmQxNMXt/vQiy1VxRAeKMnMCUwFQYDVR0RBA4wDIIKb3RoZXIu
+dGVzdDAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMCA0kAMEYCIQDhFTG2aruG4zor
+PfaP1XzYuxuccAbe4FrDV2sC88gxzwIhAKKL4hQvPvGqzjS+ywwLRDyGaYikQxRU
+NgSESoKH0saU
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto other_name_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQglCB7+ZM1i/yF6sEH
+mNmxWC7HIAKz6//mUkuLtAYJhLyhRANCAATsh7hPz33nRhadhGK7/m3IjA9cQyRt
+f1KHi0l2z1T0VX+3e9/5y3AuA/5mUA5Xa+tAdSZDE0xe3+9CLLVXFEB4
+-----END PRIVATE KEY-----)PEM"sv;
+static constexpr auto device_name_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBVjCB/aADAgECAgECMAoGCCqGSM49BAMCMCgxJjAkBgNVBAMMHUNlcnRpZmlj
+YXRlIEV4Y2VwdGlvbiBUZXN0IENBMCAXDTIwMDEwMTAwMDAwMFoYDzIwNTAwMTAx
+MDAwMDAwWjAWMRQwEgYDVQQDDAtkZXZpY2UudGVzdDBZMBMGByqGSM49AgEGCCqG
+SM49AwEHA0IABBp8Gr7JlmkYUyIg8blVKdDebqE2af/OjjAUFjFv1Y8Mswi8gDW3
+6JRWhCV4wxPWhJ000b7WVfv9GkRTOKhp52OjKDAmMBYGA1UdEQQPMA2CC2Rldmlj
+ZS50ZXN0MAwGA1UdEwEB/wQCMAAwCgYIKoZIzj0EAwIDSAAwRQIhAJLsK1rTUs3o
+zg5qBMBnPx2PR9W88Vvb1VIiJR3L7FHaAiBER0MVsgsJagepf7V27sQpU8gZPGKy
+SsZNJ2jsOiQ40g==
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto device_name_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgTS9Xd7fs6qsAyqCu
+7g6UKt+UqB8/PmOuaFLEzDmDM/ihRANCAAQafBq+yZZpGFMiIPG5VSnQ3m6hNmn/
+zo4wFBYxb9WPDLMIvIA1t+iUVoQleMMT1oSdNNG+1lX7/RpEUzioaedj
+-----END PRIVATE KEY-----)PEM"sv;
+
+static constexpr auto expired_self_signed_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBYjCCAQigAwIBAgIBATAKBggqhkjOPQQDAjAUMRIwEAYDVQQDDAlsb2NhbGhv
+c3QwHhcNMDAwMTAxMDAwMDAwWhcNMDEwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDAls
+b2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQEBjjfZb5MsAjgRlGN
+37BzpalJzdrzYVFJYjew4RGw3v2DxA1/RaA0cP+BvHYSQfZm8Rzb5d/NUeSxQc5W
+2jrEo0swSTAdBgNVHQ4EFgQURRoQocTWe4dD4RGWWG4uZI1pygYwGgYDVR0RBBMw
+EYIJbG9jYWxob3N0hwR/AAABMAwGA1UdEwEB/wQCMAAwCgYIKoZIzj0EAwIDSAAw
+RQIgfUL3H3kiTmVkqFDhe4SZlldhC5u28Mfy/IHfWeGHKisCIQCGYZJHsFLw86SZ
+AIz29iYsviCmrVeGHGU8dKf3qTBWlA==
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto expired_self_signed_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgARDe2t0Cw7bhGF2R
+WVNoBL6T0f7VohXoKklul39phsmhRANCAAQEBjjfZb5MsAjgRlGN37BzpalJzdrz
+YVFJYjew4RGw3v2DxA1/RaA0cP+BvHYSQfZm8Rzb5d/NUeSxQc5W2jrE
+-----END PRIVATE KEY-----)PEM"sv;
+static constexpr auto name_test_ca_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBjTCCATOgAwIBAgIBATAKBggqhkjOPQQDAjAtMSswKQYDVQQDDCJDZXJ0aWZp
+Y2F0ZSBFeGNlcHRpb24gTmFtZSBUZXN0IENBMCAXDTIwMDEwMTAwMDAwMFoYDzIw
+NTAwMTAxMDAwMDAwWjAtMSswKQYDVQQDDCJDZXJ0aWZpY2F0ZSBFeGNlcHRpb24g
+TmFtZSBUZXN0IENBMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE33kn8GusidyX
+ZJQjryeTakIu3bR5t3l+pZjJLtoMXLCPnGowLz0QRlgYC72Y3ITXS5ET0JpNtRDr
+PYe3mFAijqNCMEAwHQYDVR0OBBYEFGostUXUlgdCV5BohUWYhB3C3JLtMA8GA1Ud
+EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIEMAoGCCqGSM49BAMCA0gAMEUCIQC/
+RS3IsvtuvcYNkbKD8qNsZ4SKlAQPuVUL0yVBYPQnWQIgPGdAMao7UEMM5uDmukHC
+MHGGMAGWj9WXAbtuLClBAH4=
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto partial_wildcard_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBYjCCAQigAwIBAgIBBDAKBggqhkjOPQQDAjAtMSswKQYDVQQDDCJDZXJ0aWZp
+Y2F0ZSBFeGNlcHRpb24gTmFtZSBUZXN0IENBMCAXDTIwMDEwMTAwMDAwMFoYDzIw
+NTAwMTAxMDAwMDAwWjAZMRcwFQYDVQQDDA53Ki5kZXZpY2UudGVzdDBZMBMGByqG
+SM49AgEGCCqGSM49AwEHA0IABKTU3Whq098R6YYEL9kzzxSEB/MrhZSqAiH4TAwD
+RtJ9pRsvspz1TwrbjcVdovwLC60aTrVpx0vh05ZQnb+6tV+jKzApMBkGA1UdEQQS
+MBCCDncqLmRldmljZS50ZXN0MAwGA1UdEwEB/wQCMAAwCgYIKoZIzj0EAwIDSAAw
+RQIgCH+/ygRkA2V5+sHuSamsw+u1Ljy2rAV18tvMfDFwwAcCIQDQAwAggxuK4x33
+sOi+3h6xHRmZCztULswCNeYo5yJ6Ng==
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto partial_wildcard_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgtMywkaXIKfR0rgbc
+l6guYImTnzidJxLlr9lEoraItwyhRANCAASk1N1oatPfEemGBC/ZM88UhAfzK4WU
+qgIh+EwMA0bSfaUbL7Kc9U8K243FXaL8CwutGk61acdL4dOWUJ2/urVf
+-----END PRIVATE KEY-----)PEM"sv;
+static constexpr auto ip_as_dns_name_certificate = R"PEM(-----BEGIN CERTIFICATE-----
+MIIBWDCB/qADAgECAgEDMAoGCCqGSM49BAMCMC0xKzApBgNVBAMMIkNlcnRpZmlj
+YXRlIEV4Y2VwdGlvbiBOYW1lIFRlc3QgQ0EwIBcNMjAwMTAxMDAwMDAwWhgPMjA1
+MDAxMDEwMDAwMDBaMBQxEjAQBgNVBAMMCTEyNy4wLjAuMTBZMBMGByqGSM49AgEG
+CCqGSM49AwEHA0IABPlHM3ZKAim06qymiS63nC820LbiLon5VpAaKlbMMBVgubxd
+Q423Z64t9m/w3qkcs6mGLCrTR4Elbp6W8WW8ky6jJjAkMBQGA1UdEQQNMAuCCTEy
+Ny4wLjAuMTAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMCA0kAMEYCIQCCjhjoa/Ju
+Z15vfWF0RBYsj59P39qpLqZDe3B2DSngpAIhAM/wbF910sHBT5ojT7te6jZcla6H
+mooAyalhHgxvFzib
+-----END CERTIFICATE-----)PEM"sv;
+static constexpr auto ip_as_dns_name_key = R"PEM(-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCGpiM3wQasG6TgSv
+/oGrd8upHgYNoa73DD9nlq7mRvKhRANCAAT5RzN2SgIptOqspokut5wvNtC24i6J
++VaQGipWzDAVYLm8XUONt2euLfZv8N6pHLOphiwq00eBJW6elvFlvJMu
+-----END PRIVATE KEY-----)PEM"sv;
+
+static constexpr auto host = "device.test"sv;
+
+// Serves HTTPS and WebSocket handshakes with the same certificate on a loopback port.
+class TLSServer {
+public:
+ TLSServer(StringView certificate, StringView key)
+ {
+ // A client that rejects the certificate closes the connection mid-handshake.
+ signal(SIGPIPE, SIG_IGN);
+
+ m_context = SSL_CTX_new(TLS_server_method());
+ VERIFY(m_context);
+
+ auto* certificate_bio = BIO_new_mem_buf(certificate.characters_without_null_termination(), static_cast<int>(certificate.length()));
+ auto* x509 = PEM_read_bio_X509(certificate_bio, nullptr, nullptr, nullptr);
+ BIO_free(certificate_bio);
+ auto* key_bio = BIO_new_mem_buf(key.characters_without_null_termination(), static_cast<int>(key.length()));
+ auto* private_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
+ BIO_free(key_bio);
+ VERIFY(x509 && private_key);
+ VERIFY(SSL_CTX_use_certificate(m_context, x509) == 1);
+ VERIFY(SSL_CTX_use_PrivateKey(m_context, private_key) == 1);
+ X509_free(x509);
+ EVP_PKEY_free(private_key);
+
+ m_socket = socket(AF_INET, SOCK_STREAM, 0);
+ VERIFY(m_socket >= 0);
+ sockaddr_in address {};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ VERIFY(bind(m_socket, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0);
+ VERIFY(listen(m_socket, 8) == 0);
+ socklen_t length = sizeof(address);
+ VERIFY(getsockname(m_socket, reinterpret_cast<sockaddr*>(&address), &length) == 0);
+ m_port = ntohs(address.sin_port);
+
+ m_thread = Threading::Thread::construct("TLSServer"sv, [this] { return serve(); });
+ m_thread->start();
+ }
+
+ ~TLSServer()
+ {
+ m_stopping.store(true);
+ // Wake up accept() with a connection of our own.
+ auto wake = socket(AF_INET, SOCK_STREAM, 0);
+ sockaddr_in address {};
+ address.sin_family = AF_INET;
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ address.sin_port = htons(m_port);
+ (void)connect(wake, reinterpret_cast<sockaddr*>(&address), sizeof(address));
+ (void)m_thread->join();
+ close(wake);
+ close(m_socket);
+ SSL_CTX_free(m_context);
+ }
+
+ u16 port() const { return m_port; }
+
+private:
+ intptr_t serve()
+ {
+ while (true) {
+ auto connection = accept(m_socket, nullptr, nullptr);
+ if (connection < 0)
+ continue;
+ if (m_stopping.load()) {
+ close(connection);
+ return 0;
+ }
+
+ timeval timeout { 10, 0 };
+ VERIFY(setsockopt(connection, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0);
+ VERIFY(setsockopt(connection, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) == 0);
+ auto* ssl = SSL_new(m_context);
+ SSL_set_fd(ssl, connection);
+ if (SSL_accept(ssl) == 1) {
+ StringBuilder request;
+ while (!request.string_view().contains("\r\n\r\n"sv) && request.length() < 16 * KiB) {
+ char buffer[4096];
+ auto count = SSL_read(ssl, buffer, sizeof(buffer));
+ if (count <= 0)
+ break;
+ request.append(StringView { buffer, static_cast<size_t>(count) });
+ }
+ if (request.string_view().contains("\r\n\r\n"sv)) {
+ ByteString response = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
+ for (auto line : request.string_view().split_view("\r\n"sv)) {
+ if (!line.starts_with("Sec-WebSocket-Key:"sv, CaseSensitivity::CaseInsensitive))
+ continue;
+ auto key = line.substring_view("Sec-WebSocket-Key:"sv.length()).trim_whitespace();
+ auto accept_input = ByteString::formatted("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key);
+ auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA1, accept_input.bytes());
+ auto accept = MUST(encode_base64(digest.bytes()));
+ response = ByteString::formatted("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {}\r\n\r\n", accept);
+ }
+ (void)SSL_write(ssl, response.characters(), static_cast<int>(response.length()));
+ }
+ SSL_shutdown(ssl);
+ }
+ SSL_free(ssl);
+ close(connection);
+ }
+ }
+
+ SSL_CTX* m_context { nullptr };
+ int m_socket { -1 };
+ u16 m_port { 0 };
+ Atomic<bool> m_stopping { false };
+ RefPtr<Threading::Thread> m_thread;
+};
+
+struct FetchResult {
+ CURLcode code;
+ Optional<ByteString> rejected_self_signed_certificate_fingerprint;
+ long verify_result { X509_V_OK };
+};
+
+static FetchResult fetch(TLSServer const& server, bool connect_only = false, StringView hostname = host, StringView trusted_ca = ca_certificate)
+{
+ // A custom certificate path prevents macOS from sharing the root store, isolating each fetch's fixture root.
+ RequestServer::set_default_certificate_path("fixture-root");
+ ScopeGuard restore_certificate_path = [] { RequestServer::set_default_certificate_path({}); };
+
+ auto collector = make_ref_counted<RequestServer::AIACollector>(RequestServer::IsPrivate::No);
+ collector->host = hostname;
+ collector->port = server.port();
+
+ auto url = ByteString::formatted("https://{}:{}/", hostname, server.port());
+ auto resolve_entry = ByteString::formatted("{}:{}:127.0.0.1", hostname, server.port());
+ auto* resolve = curl_slist_append(nullptr, resolve_entry.characters());
+
+ curl_blob ca_blob {
+ .data = const_cast<char*>(trusted_ca.characters_without_null_termination()),
+ .len = trusted_ca.length(),
+ .flags = CURL_BLOB_COPY,
+ };
+
+ auto* curl = curl_easy_init();
+ curl_easy_setopt(curl, CURLOPT_URL, url.characters());
+ curl_easy_setopt(curl, CURLOPT_RESOLVE, resolve);
+ curl_easy_setopt(curl, CURLOPT_CAINFO_BLOB, &ca_blob);
+ curl_easy_setopt(curl, CURLOPT_CAPATH, nullptr);
+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
+ curl_easy_setopt(curl, CURLOPT_NOPROXY, "*");
+ curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, connect_only ? 1L : 0L);
+ EXPECT_EQ(RequestServer::configure_certificate_verification(curl, *collector), CURLE_OK);
+ auto code = curl_easy_perform(curl);
+ long verify_result = X509_V_OK;
+ curl_easy_getinfo(curl, CURLINFO_SSL_VERIFYRESULT, &verify_result);
+ curl_easy_cleanup(curl);
+ curl_slist_free_all(resolve);
+
+ return { code, collector->rejected_self_signed_certificate_fingerprint, verify_result };
+}
+
+static CURLcode connect_websocket(TLSServer const& server, StringView hostname = host)
+{
+ auto* multi = curl_multi_init();
+ VERIFY(multi);
+ ScopeGuard cleanup = [&] { curl_multi_cleanup(multi); };
+ auto impl = RequestServer::WebSocketImplCurl::create(multi, RequestServer::IsPrivate::No);
+ impl->on_connected = [] { };
+ impl->on_connection_error = [] { };
+ impl->on_ready_to_read = [] { };
+
+ auto name = DNS::Messages::DomainName::from_string(hostname);
+ auto dns_result = make_ref_counted<DNS::LookupResult>(name);
+ dns_result->add_record({ name, DNS::Messages::ResourceType::A, DNS::Messages::Class::IN, 60,
+ DNS::Messages::Records::A { IPv4Address { 127, 0, 0, 1 } }, {} });
+ auto url = URL::Parser::basic_parse(ByteString::formatted("wss://{}:{}/", hostname, server.port())).release_value();
+ WebSocket::ConnectionInfo info { move(url) };
+ info.set_dns_result(move(dns_result));
+ impl->connect(info);
+
+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(10);
+ int running = 0;
+ do {
+ if (curl_multi_perform(multi, &running) != CURLM_OK)
+ return CURLE_FAILED_INIT;
+ int remaining = 0;
+ while (auto* message = curl_multi_info_read(multi, &remaining)) {
+ if (message->msg == CURLMSG_DONE)
+ return message->data.result;
+ }
+ if (curl_multi_poll(multi, nullptr, 0, 100, nullptr) != CURLM_OK)
+ return CURLE_FAILED_INIT;
+ } while (running && MonotonicTime::now() < deadline);
+ return CURLE_OPERATION_TIMEDOUT;
+}
+
+TEST_CASE(self_signed_certificate_for_another_name_can_be_trusted)
+{
+ TLSServer server { self_signed_a_certificate, self_signed_a_key };
+
+ auto rejected = fetch(server);
+ EXPECT_EQ(rejected.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT(rejected.rejected_self_signed_certificate_fingerprint.has_value());
+
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), *rejected.rejected_self_signed_certificate_fingerprint);
+ auto trusted = fetch(server);
+ EXPECT_EQ(trusted.code, CURLE_OK);
+ EXPECT(!trusted.rejected_self_signed_certificate_fingerprint.has_value());
+
+ TLSServer same_certificate_elsewhere { self_signed_a_certificate, self_signed_a_key };
+ EXPECT_EQ(fetch(same_certificate_elsewhere).code, CURLE_PEER_FAILED_VERIFICATION);
+}
+
+TEST_CASE(exception_does_not_cover_another_self_signed_certificate)
+{
+ TLSServer server { self_signed_b_certificate, self_signed_b_key };
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), "00"sv);
+
+ // Still offered to the user, who may want to trust the new certificate instead.
+ auto result = fetch(server);
+ EXPECT_EQ(result.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT(result.rejected_self_signed_certificate_fingerprint.has_value());
+}
+
+TEST_CASE(exception_does_not_lift_the_name_check_for_other_certificates)
+{
+ TLSServer server { other_name_certificate, other_name_key };
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), "00"sv);
+
+ auto result = fetch(server);
+ EXPECT_EQ(result.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(result.verify_result, X509_V_ERR_HOSTNAME_MISMATCH);
+ EXPECT(!result.rejected_self_signed_certificate_fingerprint.has_value());
+}
+
+static ByteString fingerprint_of(StringView pem)
+{
+ auto* bio = BIO_new_mem_buf(pem.characters_without_null_termination(), static_cast<int>(pem.length()));
+ auto* certificate = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
+ BIO_free(bio);
+ VERIFY(certificate);
+ auto fingerprint = RequestServer::certificate_fingerprint(certificate);
+ X509_free(certificate);
+ return fingerprint;
+}
+
+// OpenSSL reports a self-signed certificate before it checks validity periods.
+TEST_CASE(exception_does_not_accept_an_expired_certificate)
+{
+ TLSServer server { expired_self_signed_certificate, expired_self_signed_key };
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), fingerprint_of(expired_self_signed_certificate));
+
+ // Not offered to the user either, as trusting it could not make it valid.
+ auto result = fetch(server);
+ EXPECT_EQ(result.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT(!result.rejected_self_signed_certificate_fingerprint.has_value());
+}
+
+// curl matches a fully qualified name without its trailing dot.
+TEST_CASE(exception_keeps_a_trailing_dot_name_working)
+{
+ TLSServer server { device_name_certificate, device_name_key };
+ RequestServer::add_certificate_exception("device.test."sv, server.port(), "00"sv);
+
+ EXPECT_EQ(fetch(server, false, "device.test."sv).code, CURLE_OK);
+}
+
+// Match curl's rejection of partial wildcards.
+TEST_CASE(exception_does_not_allow_partial_wildcards_for_other_certificates)
+{
+ TLSServer server { partial_wildcard_certificate, partial_wildcard_key };
+ RequestServer::add_certificate_exception("www.device.test"sv, server.port(), "00"sv);
+
+ auto result = fetch(server, false, "www.device.test"sv, name_test_ca_certificate);
+ EXPECT_EQ(result.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(result.verify_result, X509_V_ERR_HOSTNAME_MISMATCH);
+}
+
+// curl matches an IP address only against iPAddress names.
+TEST_CASE(exception_does_not_match_an_ip_address_against_dns_names)
+{
+ TLSServer server { ip_as_dns_name_certificate, ip_as_dns_name_key };
+ RequestServer::add_certificate_exception("127.0.0.1"sv, server.port(), "00"sv);
+
+ auto result = fetch(server, false, "127.0.0.1"sv, name_test_ca_certificate);
+ EXPECT_EQ(result.code, CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(result.verify_result, X509_V_ERR_HOSTNAME_MISMATCH);
+}
+
+TEST_CASE(exception_keeps_certificates_for_the_right_name_working)
+{
+ TLSServer server { device_name_certificate, device_name_key };
+ EXPECT_EQ(fetch(server).code, CURLE_OK);
+
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), "00"sv);
+ EXPECT_EQ(fetch(server).code, CURLE_OK);
+}
+
+TEST_CASE(certificate_exception_allows_secure_websockets_and_preconnects)
+{
+ TLSServer server { self_signed_a_certificate, self_signed_a_key };
+ auto rejected = fetch(server);
+ EXPECT_EQ(rejected.code, CURLE_PEER_FAILED_VERIFICATION);
+ VERIFY(rejected.rejected_self_signed_certificate_fingerprint.has_value());
+ EXPECT_EQ(connect_websocket(server), CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(fetch(server, true).code, CURLE_PEER_FAILED_VERIFICATION);
+
+ RequestServer::add_certificate_exception(ByteString { host }, server.port(), *rejected.rejected_self_signed_certificate_fingerprint);
+ EXPECT_EQ(connect_websocket(server), CURLE_OK);
+ EXPECT_EQ(fetch(server, true).code, CURLE_OK);
+ EXPECT_EQ(connect_websocket(server, "other.test"sv), CURLE_PEER_FAILED_VERIFICATION);
+
+ TLSServer another_port { self_signed_a_certificate, self_signed_a_key };
+ EXPECT_EQ(connect_websocket(another_port), CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(fetch(another_port, true).code, CURLE_PEER_FAILED_VERIFICATION);
+}
+
+TEST_CASE(certificate_exception_does_not_allow_other_websocket_or_preconnect_certificates)
+{
+ TLSServer trusted { self_signed_a_certificate, self_signed_a_key };
+ auto rejected = fetch(trusted);
+ VERIFY(rejected.rejected_self_signed_certificate_fingerprint.has_value());
+
+ TLSServer another_certificate { self_signed_b_certificate, self_signed_b_key };
+ RequestServer::add_certificate_exception(ByteString { host }, another_certificate.port(), *rejected.rejected_self_signed_certificate_fingerprint);
+ EXPECT_EQ(connect_websocket(another_certificate), CURLE_PEER_FAILED_VERIFICATION);
+ EXPECT_EQ(fetch(another_certificate, true).code, CURLE_PEER_FAILED_VERIFICATION);
+}
diff --git a/Tests/RequestServer/TestDiskCacheWaiters.cpp b/Tests/RequestServer/TestDiskCacheWaiters.cpp
index 07e4b066d7e..2cd71548fb0 100644
--- a/Tests/RequestServer/TestDiskCacheWaiters.cpp
+++ b/Tests/RequestServer/TestDiskCacheWaiters.cpp
@@ -20,6 +20,7 @@
#include <LibTest/TestCase.h>
#include <LibURL/Parser.h>
#include <RequestServer/CURL.h>
+#include <RequestServer/CertificateExceptions.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/Request.h>
#include <RequestServer/ResourceSubstitutionMap.h>
@@ -586,6 +587,34 @@ TEST_CASE(not_modified_response_with_another_validator_fails_revalidation)
EXPECT_EQ(http_server.connection_count(), 4u);
}
+// Revalidation must not let a cached response outlive the certificate exception it relies on.
+TEST_CASE(not_modified_response_that_may_rely_on_a_certificate_exception_fails_revalidation)
+{
+ RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(10));
+ RequestServer::Request::set_revalidation_stall_timeout(AK::Duration::from_seconds(60));
+
+ TestServer server;
+ auto disk_cache = create_test_disk_cache();
+ TestConnection connection { server, disk_cache };
+
+ StallingServer http_server { [](size_t connection_index) -> Optional<ServerResponse> {
+ if (connection_index == 1)
+ return ServerResponse::at_once("HTTP/1.1 304 Not Modified\r\nETag: \"v1\"\r\nConnection: close\r\n\r\n");
+ return ServerResponse::at_once(http_response("no-cache"sv, "hello"sv));
+ } };
+
+ auto url = http_server.url_for_path("/resource"sv);
+ connection.start_request(1, url);
+ expect_finished_without_error(connection.wait_for_request_to_finish(1, AK::Duration::from_seconds(10)), "written-to-cache"sv);
+
+ RequestServer::add_certificate_exception(url.serialized_host().to_byte_string(), url.port_or_default(), "00"sv);
+
+ // The 304 matches the stored response, but is refused; the response fetched again is not stored either.
+ connection.start_request(2, url);
+ expect_finished_without_error(connection.wait_for_request_to_finish(2, AK::Duration::from_seconds(10)), "not-cached"sv);
+ EXPECT_EQ(http_server.connection_count(), 3u);
+}
+
TEST_CASE(truncated_background_revalidation_response_is_not_stored)
{
RequestServer::Request::set_wait_for_cache_timeout(AK::Duration::from_seconds(10));
diff --git a/Tests/RequestServer/TestExportImport.cpp b/Tests/RequestServer/TestExportImport.cpp
index 9d6f6a2bb38..eb0eeb3ee1a 100644
--- a/Tests/RequestServer/TestExportImport.cpp
+++ b/Tests/RequestServer/TestExportImport.cpp
@@ -18,6 +18,7 @@
#include <LibURL/Parser.h>
#include <LibURL/Site.h>
#include <RequestServer/CURL.h>
+#include <RequestServer/CertificateExceptions.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/Resolver.h>
#include <RequestServer/ResourceSubstitutionMap.h>
@@ -425,6 +426,68 @@ TEST_CASE(imported_response_whose_transfer_failed_is_not_cached)
EXPECT_EQ(http_server.request_count(), 2u);
}
+TEST_CASE(exporter_reports_a_response_from_a_server_with_a_certificate_exception)
+{
+ Core::EventLoop event_loop;
+ TestServer server { "certificate-exception-export"sv };
+ DrippingServer http_server { patterned_body(16 * KiB), 16 * KiB, AK::Duration::from_milliseconds(2) };
+ auto url = http_server.url();
+ auto key = navigation_key_for(url);
+
+ RequestServer::add_certificate_exception(url.serialized_host().to_byte_string(), url.port_or_default(), "00"sv);
+
+ TestConnection navigator { server, ReadsBodies::No };
+ TestConnection ui { server, ReadsBodies::No };
+ navigator.start_request(1, url, key, true);
+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);
+ ui.adopt_request(navigator.client_id(), 1, 10, true, navigator.client_id());
+ (void)ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 10);
+
+ auto exported = ui.export_request(10);
+ EXPECT(exported.has_value());
+ EXPECT(exported->may_rely_on_certificate_exception);
+}
+
+TEST_CASE(imported_response_that_may_rely_on_a_certificate_exception_is_not_cached)
+{
+ Core::EventLoop event_loop;
+ TestServer source_server { "certificate-exception-source"sv };
+ TestServer target_server { "certificate-exception-target"sv };
+ DrippingServer http_server { patterned_body(64 * KiB), 16 * KiB, AK::Duration::from_milliseconds(2) };
+ auto url = http_server.url();
+ auto key = navigation_key_for(url);
+
+ TestConnection navigator { source_server, ReadsBodies::No };
+ TestConnection source_ui { source_server, ReadsBodies::No };
+ navigator.start_request(1, url, key, true);
+ (void)navigator.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 1);
+ source_ui.adopt_request(navigator.client_id(), 1, 10, true, navigator.client_id());
+ (void)source_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 10);
+
+ auto exported = source_ui.export_request(10);
+ EXPECT(exported.has_value());
+
+ // NB: The target RequestServer has no exception for the server, so only the exporter's word keeps this uncached.
+ exported->may_rely_on_certificate_exception = true;
+
+ TestConnection target_ui { target_server, ReadsBodies::No };
+ TestConnection target { target_server };
+ target_ui.import_request(20, exported.release_value(), true);
+ (void)target_ui.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 20);
+ target.adopt_request(target_ui.client_id(), 20, 30, false, target_ui.client_id());
+ auto finished = target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 30);
+ EXPECT(!finished->network_error().has_value());
+ (void)target.read_whole_body(event_loop, 30);
+
+ target.start_request(31, url, key, false);
+ auto headers = target.wait_for<Messages::RequestClient::HeadersBecameAvailable>(event_loop, 31);
+ auto cache_status = headers->response_headers().first_matching([](auto const& header) { return header.name == HTTP::TEST_CACHE_STATUS_HEADER; });
+ EXPECT(cache_status.has_value());
+ EXPECT_NE(cache_status->value, "read-from-cache"sv);
+ (void)target.wait_for<Messages::RequestClient::RequestFinished>(event_loop, 31);
+ EXPECT_EQ(http_server.request_count(), 2u);
+}
+
TEST_CASE(failed_request_with_a_transfer_lease_releases_its_cache_entry)
{
Core::EventLoop event_loop;
diff --git a/UI/cmake/ResourceFiles.cmake b/UI/cmake/ResourceFiles.cmake
index 760c2eab1eb..c76122eb8ee 100644
--- a/UI/cmake/ResourceFiles.cmake
+++ b/UI/cmake/ResourceFiles.cmake
@@ -28,6 +28,7 @@ list(TRANSFORM INTERNAL_RESOURCES PREPEND "${LADYBIRD_SOURCE_DIR}/Base/res/ladyb
set(ABOUT_PAGES
about.html
bookmarks.html
+ certificate.html
crashes.html
downloads.html
history.html