Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 9 additions & 45 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ endif()
include("cmake/compat_find.cmake")

find_package(Threads REQUIRED)
find_package(CapnProto 0.9 NO_MODULE)
# 0.10.3 is the oldest version with CallContextHook::from() that is not
# affected by CVE-2022-46149 (https://github.com/advisories/GHSA-qqff-4vw4-f6hx).
find_package(CapnProto 0.10.3 NO_MODULE)
if(NOT CapnProto_FOUND)
message(FATAL_ERROR
"Cap'n Proto is required but was not found.\n"
Expand All @@ -23,59 +25,21 @@ find_package(CapnProto 0.9 NO_MODULE)
)
endif()

# Cap'n Proto compatibility checks
set(CAPNPROTO_ISSUES "")
set(CAPNPROTO_CVE_AFFECTED FALSE)
set(CAPNPROTO_CLANG_INCOMPATIBLE FALSE)

# Check for list-of-pointers memory access bug from Nov 2022
# https://nvd.nist.gov/vuln/detail/CVE-2022-46149
# https://github.com/advisories/GHSA-qqff-4vw4-f6hx
# https://github.com/capnproto/capnproto/security/advisories/GHSA-qqff-4vw4-f6hx
# https://github.com/capnproto/capnproto/blob/master/security-advisories/2022-11-30-0-pointer-list-bounds.md
# https://capnproto.org/news/2022-11-30-CVE-2022-46149-security-advisory.html
# https://dwrensha.github.io/capnproto-rust/2022/11/30/out_of_bounds_memory_access_bug.html
if(CapnProto_VERSION STREQUAL "0.9.0"
OR CapnProto_VERSION STREQUAL "0.9.1"
OR CapnProto_VERSION STREQUAL "0.10.0"
OR CapnProto_VERSION STREQUAL "0.10.1"
OR CapnProto_VERSION STREQUAL "0.10.2")
set(CAPNPROTO_CVE_AFFECTED TRUE)
string(APPEND CAPNPROTO_ISSUES "- CVE-2022-46149 security vulnerability (details: https://github.com/advisories/GHSA-qqff-4vw4-f6hx)\n")
endif()

# Check for Cap'n Proto / Clang / C++20 incompatibility
# Cap'n Proto 0.9.x and 0.10.x are incompatible with Clang 16+ when using C++20
# Cap'n Proto 0.10.x is incompatible with Clang 16+ when using C++20
# due to P2468R2 implementation. This was fixed in Cap'n Proto 1.0+.
# See: https://github.com/bitcoin-core/libmultiprocess/issues/199
if((CapnProto_VERSION VERSION_GREATER_EQUAL "0.9.0") AND
(CapnProto_VERSION VERSION_LESS "1.0.0") AND
if((CapnProto_VERSION VERSION_LESS "1.0.0") AND
(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") AND
(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL "16") AND
(CMAKE_CXX_STANDARD EQUAL 20))
set(CAPNPROTO_CLANG_INCOMPATIBLE TRUE)
string(APPEND CAPNPROTO_ISSUES "- Incompatible with Clang ${CMAKE_CXX_COMPILER_VERSION} when using C++20\n")
endif()

if(CAPNPROTO_CVE_AFFECTED OR CAPNPROTO_CLANG_INCOMPATIBLE)
set(RESOLUTION_OPTIONS "")

# Fixes both issues
string(APPEND RESOLUTION_OPTIONS " - Upgrade to Cap'n Proto version 1.0 or newer (recommended)\n")

if(CAPNPROTO_CVE_AFFECTED AND NOT CAPNPROTO_CLANG_INCOMPATIBLE)
string(APPEND RESOLUTION_OPTIONS " - Upgrade to a patched minor version (0.9.2, 0.10.3, or later)\n")
elseif(CAPNPROTO_CLANG_INCOMPATIBLE AND NOT CAPNPROTO_CVE_AFFECTED)
string(APPEND RESOLUTION_OPTIONS " - Use GCC instead of Clang\n")
endif()

string(APPEND RESOLUTION_OPTIONS " - For Bitcoin Core compilation build with -DENABLE_IPC=OFF to disable multiprocess support\n")

message(FATAL_ERROR
"The version of Cap'n Proto detected: ${CapnProto_VERSION} has known compatibility issues:\n"
"${CAPNPROTO_ISSUES}"
"- Incompatible with Clang ${CMAKE_CXX_COMPILER_VERSION} when using C++20\n"
"To resolve, choose one of the following:\n"
"${RESOLUTION_OPTIONS}"
" - Upgrade to Cap'n Proto version 1.0 or newer (recommended)\n"
" - Use GCC instead of Clang\n"
" - For Bitcoin Core compilation build with -DENABLE_IPC=OFF to disable multiprocess support\n"
)
endif()

Expand Down
2 changes: 1 addition & 1 deletion ci/configs/olddeps.bash
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ CI_DIR=build-olddeps
# Pin olddeps to an older Nixpkgs channel, to be able to test an older GCC.
CI_NIXPKGS_CHANNEL=nixos-25.05
export CXXFLAGS="-Werror -Wall -Wextra -Wpedantic -Wunused -Wunused-const-variable -Wno-error=array-bounds"
CAPNP_CHECKOUT=v0.9.2 # Use a checkout to compile it with the selected GCC
CAPNP_CHECKOUT=v0.10.3 # Use a checkout to compile it with the selected GCC
NIX_ARGS=(--argstr capnprotoVersion "none" --argstr cmakeVersion "3.12.4" --argstr gccVersion "10")
BUILD_ARGS=(-k)
2 changes: 1 addition & 1 deletion doc/install.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# libmultiprocess Installation

Installation currently requires Cap'n Proto 0.9 or higher:
Installation currently requires Cap'n Proto 0.10.3 or higher:

```sh
apt install libcapnp-dev capnproto
Expand Down
103 changes: 91 additions & 12 deletions include/mp/proxy-io.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <capnp/rpc-twoparty.h>

#include <any>
#include <atomic>
#include <assert.h>
#include <algorithm>
#include <condition_variable>
Expand All @@ -34,6 +35,14 @@ struct Listener;

struct InvokeContext
{
explicit InvokeContext(Connection& connection) : connection{connection} {}
virtual ~InvokeContext() = default;

//! Call fn() on the event loop thread, for code that has to run there,
//! like GetCapability() and SyncValue(). ServerInvokeContext overrides this
//! to skip fn() if the request was canceled.
virtual void syncRequest(kj::FunctionParam<void()> fn);

Connection& connection;
};

Expand All @@ -55,23 +64,42 @@ struct ServerInvokeContext : InvokeContext
CallContext& call_context;
int req;
//! For IPC methods that execute asynchronously, not on the event-loop
//! thread: lock preventing the event-loop thread from freeing the params or
//! results structs if the request is canceled while the worker thread is
//! reading params (`call_context.getParams()`) or writing results
//! (`call_context.getResults()`).
Lock* cancel_lock{nullptr};
//! For IPC methods that execute asynchronously, not on the event-loop
//! thread, this is set to true if the IPC call was canceled by the client
//! or canceled by a disconnection. If the call runs on the event-loop
//! thread, it can't be canceled. This should be accessed with cancel_lock
//! held if it is not null, since in the asynchronous case it is accessed
//! from multiple threads.
bool request_canceled{false};
//! thread, this is set to true by the event loop thread if the IPC call was
//! canceled by the client or canceled by a disconnection. The params and
//! results structs stay valid after cancellation, because the worker holds
//! a reference to the call context (see PassField for mp.Context).
std::atomic<bool> request_canceled{false};

ServerInvokeContext(ProxyServer& proxy_server, CallContext& call_context, int req)
: InvokeContext{*proxy_server.m_context.connection}, proxy_server{proxy_server}, call_context{call_context}, req{req}
{
}

//! Call fn() on the event loop thread, or skip it if the request was
//! canceled, and throw InterruptException in that case. Checking
//! request_canceled on the event loop thread is enough to order fn()
//! against cancellation, because only the event loop thread sets it, and
//! ~Connection sets it (through m_canceler) before destroying anything.
void syncRequest(kj::FunctionParam<void()> fn) override
{
throwIfCanceledAfter([&] {
proxy_server.m_context.loop->sync([&] {
if (!request_canceled) fn();
});
});
}

//! Call fn(), then throw InterruptException if the request was canceled,
//! so the caller stops instead of building results for a canceled request.
//! If fn() itself threw, the InterruptException takes precedence over its
//! exception, which could not be returned to the canceled caller anyway.
template <typename Fn>
decltype(auto) throwIfCanceledAfter(Fn&& fn)
{
return TryFinally(std::forward<Fn>(fn), [&] {
if (request_canceled) throw InterruptException{"canceled"};
});
}
};

template <typename Interface, typename Params, typename Results>
Expand Down Expand Up @@ -551,6 +579,57 @@ class Connection
CleanupList m_sync_cleanup_fns;
};

//! Take the capability held by a Cap'n Proto field. Must be called on the
//! event loop thread (see GetCapability()).
template <typename Input>
auto TakeCapability(Input&& input)
{
using Client = std::remove_cvref_t<decltype(input.get())>;
if constexpr (std::is_lvalue_reference_v<decltype(input.get())>) {
// The input holds a client that was already read from the message, for
// example a ValueField from ReadList().
return Client{kj::mv(input.get())};
} else {
return Client{input.get()};
}
}

//! Call fn() on the event loop thread and return its result.
//!
//! Use this for code that uses invoke_context.connection, like building a
//! ProxyClient or ProxyServer. The Connection is destroyed on the event loop
//! thread, and ~Connection cancels the server requests using it before
//! destroying anything, so for a server request, fn() either runs before
//! ~Connection, or is skipped because the request is canceled, and
//! InterruptException is thrown instead.
template <typename Fn>
auto SyncValue(InvokeContext& invoke_context, Fn&& fn) -> decltype(fn())
{
auto& loop{*invoke_context.connection.m_loop};
// Testing hooks to simulate a disconnect before and after fn() runs.
if (loop.testing_hook_misc) loop.testing_hook_misc(std::string{"SyncValue:before"});
std::optional<decltype(fn())> result;
invoke_context.syncRequest([&] { result.emplace(fn()); });
// If the request was canceled, syncRequest() threw InterruptException
// instead of returning without setting result.
assert(result);
if (loop.testing_hook_misc) loop.testing_hook_misc(std::string{"SyncValue:after"});
return std::move(*result);
}

//! Read a capability from a Cap'n Proto field on the event loop thread.
//!
//! Reading a capability adds a reference to its ClientHook, and ClientHook
//! reference counts are not atomic. The event loop thread updates the same
//! counts when other messages refer to the capability, when it is released, and
//! when the connection is closed, so reading it on another thread is a data
//! race that could free the ClientHook while it is still in use.
template <typename Input>
auto GetCapability(InvokeContext& invoke_context, Input&& input)
{
return SyncValue(invoke_context, [&] { return TakeCapability(input); });
}

//! Vat id for server side of connection. Required argument to RpcSystem::bootStrap()
//!
//! "Vat" is Cap'n Proto nomenclature for a host of various objects that facilitates
Expand Down
60 changes: 27 additions & 33 deletions include/mp/proxy-types.h
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,21 @@ decltype(auto) ReadList(TypeList<LocalType>, InvokeContext& invoke_context, Inpu
return read_dest.update([&](auto& value) {
auto data = input.get();
init(value, data.size());
for (auto item : data) {
auto read_item{[&](auto&& item) {
ReadField(TypeList<LocalType>(), invoke_context, Make<ValueField>(item),
ReadDestEmplace(TypeList<LocalType>(), [&emplace, &value](auto&&... args) -> decltype(auto) {
return emplace(value, std::forward<decltype(args)>(args)...);
}));
}};
if constexpr (std::is_base_of_v<::capnp::Capability::Client, std::remove_cvref_t<decltype(data[0])>>) {
// Iterating over a list of capabilities reads them, so read each
// one on the event loop thread (see GetCapability()).
for (unsigned int i = 0; i < data.size(); ++i) {
struct Item { decltype(data)& list; unsigned int index; auto get() const { return list[index]; } };
read_item(GetCapability(invoke_context, Item{data, i}));
}
} else {
for (auto item : data) read_item(item);
}
});
}
Expand All @@ -351,7 +361,9 @@ auto PassField(Priority<1>, TypeList<LocalType&>, ServerContext& server_context,
const auto& params = server_context.call_context.getParams();
const auto& input = Make<StructField, Accessor>(params);
using Interface = typename Decay<decltype(input.get())>::Calls;
auto param = std::make_unique<ProxyClient<Interface>>(input.get(), server_context.proxy_server.m_context.connection, false);
auto param = SyncValue(server_context, [&] {
return std::make_unique<ProxyClient<Interface>>(TakeCapability(input), server_context.proxy_server.m_context.connection, false);
});
fn.invoke(server_context, std::forward<Args>(args)..., *param);
}

Expand Down Expand Up @@ -546,37 +558,19 @@ struct ServerCall
template <typename ServerContext, typename... Args>
decltype(auto) invoke(ServerContext& server_context, TypeList<>, Args&&... args) const
{
// If cancel_lock is set, release it while executing the method, and
// reacquire it afterwards. The lock is needed to prevent params and
// response structs from being deleted by the event loop thread if the
// request is canceled, so it is only needed before and after method
// execution. It is important to release the lock during execution
// because the method can take arbitrarily long to return and the event
// loop will need the lock itself in on_cancel if the call is canceled.
if (server_context.cancel_lock) server_context.cancel_lock->m_lock.unlock();
return TryFinally(
[&]() -> decltype(auto) {
return ProxyServerMethodTraits<
typename std::remove_reference_t<decltype(server_context.proxy_server)>::Interface,
typename decltype(server_context.call_context.getParams())::Reads
>::invoke(server_context, std::forward<Args>(args)...);
},
[&] {
if (server_context.cancel_lock) server_context.cancel_lock->m_lock.lock();
// If the IPC request was canceled, throw InterruptException
// because there is no point continuing and trying to fill the
// call_context.getResults() struct. It's also important to stop
// executing because the connection may have been destroyed as
// described in https://github.com/bitcoin/bitcoin/issues/34250
// and there could be invalid references to the destroyed
// Connection object if this continued.
// If the IPC method itself threw an exception, the
// InterruptException thrown below will take precedence over it.
// Since the call has been canceled that exception can't be
// returned to the caller, so it needs to be discarded like
// other result values.
if (server_context.request_canceled) throw InterruptException{"canceled"};
});
// If the call was canceled while the method ran, throw
// InterruptException afterwards, because there is no point continuing
// and trying to fill the call_context.getResults() struct. It's also
// important to stop executing because the connection may have been
// destroyed as described in https://github.com/bitcoin/bitcoin/issues/34250
// and there could be invalid references to the destroyed Connection
// object if this continued.
return server_context.throwIfCanceledAfter([&]() -> decltype(auto) {
return ProxyServerMethodTraits<
typename std::remove_reference_t<decltype(server_context.proxy_server)>::Interface,
typename decltype(server_context.call_context.getParams())::Reads
>::invoke(server_context, std::forward<Args>(args)...);
});
}
};

Expand Down
43 changes: 17 additions & 26 deletions include/mp/type-context.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#include <mp/proxy-io.h>
#include <mp/util.h>

#include <utility>

#include <kj/string.h>

namespace mp {
Expand Down Expand Up @@ -99,9 +101,11 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn&
auto& request_threads = thread_context.request_threads;
ConnThread request_thread;
bool inserted{false};
Mutex cancel_mutex;
Lock cancel_lock{cancel_mutex};
server_context.cancel_lock = &cancel_lock;
// Reference to the call context, keeping the params and results
// structs alive until this request finishes, even if it is canceled.
// Taken and released on the event loop thread, because CallContextHook
// reference counts are not atomic.
kj::Own<::capnp::CallContextHook> call_ref;
loop.sync([&] {
// Detect request being canceled before it executes.
if (cancel_monitor.m_canceled) {
Expand All @@ -110,22 +114,13 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn&
}
// Detect request being canceled while it executes.
assert(!cancel_monitor.m_on_cancel);
cancel_monitor.m_on_cancel = [&loop, &server_context, &cancel_mutex, req]() {
cancel_monitor.m_on_cancel = [&loop, &server_context, req]() {
MP_LOG(loop, Log::Info) << "IPC server request #" << req << " canceled while executing.";
// Lock cancel_mutex here to block the event loop
// thread and prevent it from deleting the request's
// params and response structs while the execution
// thread is accessing them. Because this lock is
// released before the event loop thread does delete
// the structs, the mutex does not provide any
// protection from the event loop deleting the
// structs _before_ the execution thread acquires
// it. So in addition to locking the mutex, the
// execution thread always checks request_canceled
// as well before accessing the structs.
Lock cancel_lock{cancel_mutex};
// Only set a flag. The params and results structs are kept
// alive by call_ref, so this never waits for the worker thread.
server_context.request_canceled = true;
};
call_ref = ::capnp::CallContextHook::from(call_context).addRef();
// Update requests_threads map if not canceled. We know
// the request is not canceled currently because
// cancel_monitor.m_canceled was checked above and this
Expand Down Expand Up @@ -154,14 +149,6 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn&
// makes another IPC call), so avoid modifying the map.
const bool erase_thread{inserted};
KJ_DEFER(
// Release the cancel lock before calling loop->sync and
// waiting for the event loop thread, because if a
// cancellation happened, it needs to run the on_cancel
// callback above. It's safe to release cancel_lock at
// this point because the fn.invoke() call below will be
// finished and no longer accessing the params or
// results structs.
cancel_lock.m_lock.unlock();
// Erase the request_threads entry on the event loop
// thread with loop->sync(), so if the connection is
// broken there is not a race between this thread and
Expand All @@ -174,9 +161,13 @@ auto PassField(Priority<1>, TypeList<>, ServerContext& server_context, const Fn&
// cancellation happened. So we do not need to be
// notified of cancellations after this point. Also
// we do not want to be notified because
// cancel_mutex and server_context could be out of
// scope when it happens.
// server_context could be out of scope when it
// happens.
cancel_monitor.m_on_cancel = nullptr;
// Release the call context on the event loop thread. If the
// request was canceled, this is the last reference, and
// ~RpcCallContext sends the cancellation return here.
call_ref = nullptr;
auto self_dispose{kj::mv(self)};
auto active_call_dispose{kj::mv(active_call)};
if (erase_thread) {
Expand Down
Loading
Loading