Truly independent web browser
LibRequests+RequestServer: Resolve system lookups in the UI process
sideshowbarkerc836d453c5e8
diff --git a/Libraries/LibRequests/CMakeLists.txt b/Libraries/LibRequests/CMakeLists.txtindex 8eceb4a999c..b98447de482 100644--- a/Libraries/LibRequests/CMakeLists.txt+++ b/Libraries/LibRequests/CMakeLists.txt@@ -23,4 +23,4 @@ compile_ipc(${LADYBIRD_SOURCE_DIR}/Services/RequestServer/RequestServerControlClcompile_ipc(${LADYBIRD_SOURCE_DIR}/Services/RequestServer/RequestServerControl.ipc ${CMAKE_BINARY_DIR}/Services/RequestServer/RequestServerControlEndpoint.h)ladybird_lib(LibRequests requests)-target_link_libraries(LibRequests PRIVATE LibCore LibHTTP LibIPC LibURL)+target_link_libraries(LibRequests PRIVATE LibCore LibHTTP LibIPC LibThreading LibURL)diff --git a/Libraries/LibRequests/RequestControlClient.cpp b/Libraries/LibRequests/RequestControlClient.cppindex d60d7d26d8f..3bb2bfc17d0 100644--- a/Libraries/LibRequests/RequestControlClient.cpp+++ b/Libraries/LibRequests/RequestControlClient.cpp@@ -5,7 +5,9 @@*/#include <LibCore/EventLoop.h>+#include <LibCore/Socket.h>#include <LibRequests/RequestControlClient.h>+#include <LibThreading/ThreadPool.h>namespace Requests {@@ -65,6 +67,31 @@ void RequestControlClient::retrieve_http_cookie(int client_id, u64 request_id, Rasync_retrieved_http_cookie(client_id, request_id, request_type, cookie_request_id, cookie);}+void RequestControlClient::resolve_host_with_system_resolver(u64 resolution_id, ByteString host, bool ipv6)+{+ // getaddrinfo() blocks, for as long as the lookup takes, so it runs on a worker, and the answer goes back to+ // RequestServer from this thread.+ Threading::ThreadPool::the().submit([weak_this = make_weak_ptr<RequestControlClient>(), resolution_id, host = move(host), ipv6, event_loop = Core::EventLoop::current_weak()] mutable {+ auto family = ipv6 ? Core::Socket::AddressFamily::IPv6Only : Core::Socket::AddressFamily::IPv4Only;+ auto addresses_or_error = Core::Socket::resolve_host(host, Core::Socket::SocketType::Stream, family);++ Optional<Vector<ByteString>> addresses;+ if (!addresses_or_error.is_error()) {+ addresses = Vector<ByteString> {};+ for (auto const& address : addresses_or_error.value())+ address.visit([&](auto const& address) { addresses->append(ByteString::formatted("{}", address)); });+ }++ auto origin_event_loop = event_loop->take();+ if (!origin_event_loop.is_alive())+ return;+ origin_event_loop->deferred_invoke([weak_this = move(weak_this), resolution_id, addresses = move(addresses)] mutable {+ if (auto self = weak_this.strong_ref())+ self->async_resolved_host_with_system_resolver(resolution_id, move(addresses));+ });+ });+}+void RequestControlClient::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){if (on_store_response_cookies_and_hsts_policy)diff --git a/Libraries/LibRequests/RequestControlClient.h b/Libraries/LibRequests/RequestControlClient.hindex e74f6a3445f..acee35761c5 100644--- a/Libraries/LibRequests/RequestControlClient.h+++ b/Libraries/LibRequests/RequestControlClient.h@@ -56,6 +56,7 @@ private:virtual void disk_cache_size_changed(u64 size) override;virtual void retrieved_cache_access_profile(u64 access_profile_request_id, Vector<CacheAccessBucket> buckets) override;virtual void request_adopter_designated(u64 designation_id) override;+ virtual void resolve_host_with_system_resolver(u64 resolution_id, ByteString host, bool ipv6) override;HashMap<u64, NonnullRefPtr<Core::Promise<CacheSizes>>> m_pending_cache_size_estimations;u64 m_next_cache_size_estimation_id { 0 };diff --git a/Services/RequestServer/ControlConnectionFromClient.cpp b/Services/RequestServer/ControlConnectionFromClient.cppindex 51ff5ae6582..0986357e6b3 100644--- a/Services/RequestServer/ControlConnectionFromClient.cpp+++ b/Services/RequestServer/ControlConnectionFromClient.cpp@@ -27,6 +27,10 @@ ControlConnectionFromClient::ControlConnectionFromClient(NonnullOwnPtr<IPC::Tran{VERIFY(s_control_connection == nullptr);s_control_connection = this;+#if defined(AK_OS_LINUX)+ // The Linux sandbox denies RequestServer the files that the system resolver reads, like /etc/resolv.conf.+ Resolver::resolve_system_names_remotely();+#endifif (m_disk_cache.has_value()) {// Coalesce the size changes of a burst of cache writes into one report.@@ -70,6 +74,11 @@ void ControlConnectionFromClient::die()if (s_control_connection == this)s_control_connection = nullptr;+ // No answer comes for a lookup that's still waiting on the process that launched RequestServer.+ auto pending_system_resolutions = move(m_pending_system_resolutions);+ for (auto& [resolution_id, on_resolved] : pending_system_resolutions)+ on_resolved(Error::from_string_literal("The system resolver's process is gone"));+if (m_connections.is_empty())Core::EventLoop::current().quit(0);}@@ -255,6 +264,40 @@ void ControlConnectionFromClient::remove_cache_entries_accessed_before(UnixDateTm_disk_cache->remove_entries_accessed_before(before);}+void ControlConnectionFromClient::resolve_host_with_system_resolver(ByteString const& host, Core::Socket::AddressFamily family, Function<void(DNS::Resolver::SystemResolution)> on_resolved)+{+ VERIFY(family != Core::Socket::AddressFamily::Unspecified);++ auto resolution_id = m_next_system_resolution_id++;+ m_pending_system_resolutions.set(resolution_id, move(on_resolved));+ async_resolve_host_with_system_resolver(resolution_id, host, family == Core::Socket::AddressFamily::IPv6Only);+}++void ControlConnectionFromClient::resolved_host_with_system_resolver(u64 resolution_id, Optional<Vector<ByteString>> addresses)+{+ auto on_resolved = m_pending_system_resolutions.take(resolution_id);+ if (!on_resolved.has_value()) {+ did_misbehave("Unexpected system resolver answer");+ return;+ }++ if (!addresses.has_value()) {+ (*on_resolved)(Error::from_string_literal("The system resolver could not resolve the name"));+ return;+ }++ Vector<Variant<IPv4Address, IPv6Address>> parsed_addresses;+ for (auto const& address : *addresses) {+ if (auto ipv4_address = IPv4Address::from_string(address); ipv4_address.has_value())+ parsed_addresses.append(*ipv4_address);+ else if (auto ipv6_address = IPv6Address::from_string(address); ipv6_address.has_value())+ parsed_addresses.append(*ipv6_address);+ else+ dbgln("RequestServer: Ignoring an address the system resolver returned that does not parse: {}", address);+ }+ (*on_resolved)(move(parsed_addresses));+}+void ControlConnectionFromClient::retrieved_http_cookie(int client_id, u64 request_id, RequestType request_type, u64 cookie_request_id, String cookie){note_event_tick("ipc-retrieved-cookie"sv);diff --git a/Services/RequestServer/ControlConnectionFromClient.h b/Services/RequestServer/ControlConnectionFromClient.hindex 4145b6e1b31..b31878960fd 100644--- a/Services/RequestServer/ControlConnectionFromClient.h+++ b/Services/RequestServer/ControlConnectionFromClient.h@@ -9,6 +9,7 @@#include <AK/Optional.h>#include <AK/Time.h>#include <LibCore/Timer.h>+#include <LibDNS/Resolver.h>#include <LibHTTP/Cache/DiskCacheSettings.h>#include <LibHTTP/Forward.h>#include <LibIPC/ConnectionFromClient.h>@@ -33,6 +34,9 @@ public:static Optional<ControlConnectionFromClient&> the();+ // Resolves a name through the system resolver of the process that launched RequestServer.+ void resolve_host_with_system_resolver(ByteString const& host, Core::Socket::AddressFamily, Function<void(DNS::Resolver::SystemResolution)>);+private:ControlConnectionFromClient(NonnullOwnPtr<IPC::Transport>, RequestServer::ConnectionFromClient::ConnectionMap&, RequestServer::ConnectionFromClient::RequestTransferLeaseMap&, Optional<HTTP::DiskCache&>);@@ -59,6 +63,8 @@ private:virtual void retrieved_http_cookie(int client_id, u64 request_id, RequestType request_type, u64 cookie_request_id, String cookie) override;virtual void stored_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id) override;+ virtual void resolved_host_with_system_resolver(u64 resolution_id, Optional<Vector<ByteString>> addresses) override;+struct ClientSocket {IPC::TransportHandle handle;int client_id { -1 };@@ -76,6 +82,9 @@ private:RefPtr<Core::Timer> m_performance_timer;Optional<MonotonicTime> m_last_performance_push;++ HashMap<u64, Function<void(DNS::Resolver::SystemResolution)>> m_pending_system_resolutions;+ u64 m_next_system_resolution_id { 0 };};}diff --git a/Services/RequestServer/RequestServerControl.ipc b/Services/RequestServer/RequestServerControl.ipcindex 104fb1498d4..177df17423e 100644--- a/Services/RequestServer/RequestServerControl.ipc+++ b/Services/RequestServer/RequestServerControl.ipc@@ -39,4 +39,6 @@ endpoint RequestServerControlretrieved_http_cookie(int client_id, u64 request_id, ::RequestServer::RequestType request_type, u64 cookie_request_id, String cookie) =|stored_response_cookies_and_hsts_policy(int client_id, u64 request_id, u64 store_request_id) =|+ // The addresses that the system resolver found for a name, or nothing if the lookup failed.+ resolved_host_with_system_resolver(u64 resolution_id, Optional<Vector<ByteString>> addresses) =|}diff --git a/Services/RequestServer/RequestServerControlClient.ipc b/Services/RequestServer/RequestServerControlClient.ipcindex fe5cc6a294d..20bd1057dcc 100644--- a/Services/RequestServer/RequestServerControlClient.ipc+++ b/Services/RequestServer/RequestServerControlClient.ipc@@ -26,4 +26,7 @@ endpoint RequestServerControlClientretrieved_cache_access_profile(u64 access_profile_request_id, Vector<Requests::CacheAccessBucket> buckets) =|request_adopter_designated(u64 designation_id) =|+ // RequestServer has no access to the files the system resolver reads, such as /etc/resolv.conf, so the process+ // that launched it resolves a name for it. ipv6: whether to look up IPv6 addresses rather than IPv4 ones.+ resolve_host_with_system_resolver(u64 resolution_id, ByteString host, bool ipv6) =|}diff --git a/Services/RequestServer/Resolver.cpp b/Services/RequestServer/Resolver.cppindex 5c4010625af..19e244075bc 100644--- a/Services/RequestServer/Resolver.cpp+++ b/Services/RequestServer/Resolver.cpp@@ -6,8 +6,10 @@*/#include <AK/NeverDestroyed.h>+#include <LibCore/EventLoop.h>#include <LibTLS/TLSv12.h>#include <RequestServer/CURL.h>+#include <RequestServer/ControlConnectionFromClient.h>#include <RequestServer/Resolver.h>namespace RequestServer {@@ -58,6 +60,22 @@ DNSInfo& DNSInfo::the()return g_dns_info;}+static bool s_resolves_system_names_remotely = false;++static void use_remote_system_resolver(DNS::Resolver& resolver)+{+ resolver.set_remote_system_resolver([](ByteString const& host, Core::Socket::AddressFamily family, Function<void(DNS::Resolver::SystemResolution)> on_resolved) {+ if (auto control_connection = ControlConnectionFromClient::the(); control_connection.has_value()) {+ control_connection->resolve_host_with_system_resolver(host, family, move(on_resolved));+ return;+ }+ // The resolver expects its answer later, never from inside this call.+ Core::deferred_invoke([on_resolved = move(on_resolved)] mutable {+ on_resolved(Error::from_string_literal("No process to resolve the name with the system resolver"));+ });+ });+}+// System resolver to resolve the resolvers themselves.static DNS::Resolver& system_resolver(){@@ -144,6 +162,19 @@ NonnullRefPtr<Resolver> Resolver::private_resolver()return resolver;}+void Resolver::resolve_system_names_remotely()+{+ if (s_resolves_system_names_remotely)+ return;+ s_resolves_system_names_remotely = true;++ use_remote_system_resolver(system_resolver());+ for (auto* weak_resolver : { &g_default_resolver, &g_private_resolver }) {+ if (auto resolver = weak_resolver->strong_ref())+ use_remote_system_resolver(resolver->dns);+ }+}+void Resolver::reset_connections(){for (auto* weak_resolver : { &g_default_resolver, &g_private_resolver }) {@@ -190,6 +221,8 @@ NonnullRefPtr<Resolver> Resolver::create()};}));resolver->dns.set_loopback_domains(DNSInfo::the().loopback_domains);+ if (s_resolves_system_names_remotely)+ use_remote_system_resolver(resolver->dns);return resolver;}diff --git a/Services/RequestServer/Resolver.h b/Services/RequestServer/Resolver.hindex 8f8faf6401d..c58e2fd81b7 100644--- a/Services/RequestServer/Resolver.h+++ b/Services/RequestServer/Resolver.h@@ -44,6 +44,10 @@ struct Resolverstatic void reset_connections();+ // From now on, every resolver sends the names that it looks up with the system resolver to the process that+ // launched RequestServer: RequestServer may not read the files the system resolver needs, like /etc/resolv.conf.+ static void resolve_system_names_remotely();+DNS::Resolver dns;private:diff --git a/Services/RequestServer/SandboxLinux.cpp b/Services/RequestServer/SandboxLinux.cppindex 7c628e70fb0..4a8380bee6e 100644--- a/Services/RequestServer/SandboxLinux.cpp+++ b/Services/RequestServer/SandboxLinux.cpp@@ -9,14 +9,12 @@#include <AK/String.h>#include <LibCore/DirIterator.h>#include <LibCore/Environment.h>-#include <LibCore/File.h>#include <LibCore/System.h>#include <LibSandbox/Sandbox.h>#include <LibSandbox/Seccomp.h>#include <RequestServer/ResourceSubstitutionMap.h>#include <RequestServer/Sandbox.h>#include <curl/curl.h>-#include <dlfcn.h>#include <openssl/conf.h>#include <openssl/crypto.h>#include <openssl/x509.h>@@ -111,61 +109,16 @@ static ErrorOr<void> add_certificate_store_paths(Vector<Sandbox::PathRule>& pathreturn {};}-static Vector<ByteString> nss_host_modules_from_nsswitch(StringView nsswitch_contents)-{- Vector<ByteString> modules;- for (auto line : nsswitch_contents.lines()) {- auto trimmed = line.trim_whitespace();- if (!trimmed.starts_with("hosts:"sv))- continue;- for (auto token : trimmed.substring_view("hosts:"sv.length()).split_view_if(is_ascii_space)) {- // Action specifiers such as [NOTFOUND=return] and trailing comments are not modules.- if (token.starts_with('['))- continue;- if (token.starts_with('#'))- break;- modules.append(token);- }- break;- }- return modules;-}--// glibc dlopens the NSS modules named on the hosts line of /etc/nsswitch.conf the first time getaddrinfo()-// runs, and LibDNS still resolves through getaddrinfo() unless a DNS server is configured. Load them now so-// the resolver keeps working once the sandbox denies the library directories and executable file mappings.-static void preload_nss_host_modules()-{- auto file = Core::File::open("/etc/nsswitch.conf"sv, Core::File::OpenMode::Read);- if (file.is_error())- return;- auto contents = file.value()->read_until_eof();- if (contents.is_error())- return;-- for (auto const& module : nss_host_modules_from_nsswitch(contents.value())) {- auto library_name = ByteString::formatted("libnss_{}.so.2", module);- (void)dlopen(library_name.characters(), RTLD_LAZY | RTLD_GLOBAL | RTLD_NODELETE);- }-}-ErrorOr<void> apply_sandbox(StringView, Vector<ByteString> const& certificates, Optional<StringView> disk_cache_directory){TRY(Sandbox::install_no_new_privileges());TRY(Sandbox::configure_runtime());- preload_nss_host_modules();-Vector<Sandbox::PathRule> paths;TRY(add_certificate_store_paths(paths));- TRY(Sandbox::add_path_if_exists(paths, "/etc/host.conf"sv, Sandbox::PathRule::Access::ReadOnly));- TRY(Sandbox::add_path_if_exists(paths, "/etc/hosts"sv, Sandbox::PathRule::Access::ReadOnly));- TRY(Sandbox::add_path_if_exists(paths, "/etc/nsswitch.conf"sv, Sandbox::PathRule::Access::ReadOnly));- TRY(Sandbox::add_path_if_exists(paths, "/etc/resolv.conf"sv, Sandbox::PathRule::Access::ReadOnly));- TRY(Sandbox::add_path_if_exists(paths, "/run/systemd/resolve"sv, Sandbox::PathRule::Access::ReadOnly));- // nss-resolve checks this sysctl to decide whether to ask for AAAA records.- TRY(Sandbox::add_path_if_exists(paths, "/proc/sys/net/ipv6/conf/all/disable_ipv6"sv, Sandbox::PathRule::Access::ReadOnly));+ // The process that launched RequestServer resolves names with the system resolver for it, so none of the files that+ // the system resolver reads, like /etc/resolv.conf, are needed here.for (auto const& certificate : certificates)TRY(Sandbox::add_path_if_exists(paths, certificate, Sandbox::PathRule::Access::ReadOnly));