Add support for authentication and encryption

This commit is contained in:
Guillaume Meunier
2024-11-26 23:59:35 +01:00
committed by Patrick Nicolas
parent 447b77c35c
commit c6e773fd22
45 changed files with 1516 additions and 455 deletions
+97 -2
View File
@@ -17,16 +17,18 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <filesystem>
#include <fstream>
#define JSON_DISABLE_ENUM_SERIALIZATION 1
#ifdef JSON_DIAGNOSTICS
#undef JSON_DIAGNOSTICS
#endif
#define JSON_DIAGNOSTICS 1
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <random>
#include <stdlib.h>
#include <string>
#include "util/u_logging.h"
@@ -34,6 +36,7 @@
#include "utils/xdg_base_directory.h"
static std::filesystem::path config_file = xdg_config_home() / "wivrn" / "config.json";
static std::filesystem::path known_keys_file = xdg_config_home() / "wivrn" / "known_keys.json";
static std::filesystem::path cookie_file = xdg_config_home() / "wivrn" / "cookie";
namespace wivrn
@@ -181,4 +184,96 @@ std::string server_cookie()
return buffer;
}
}
std::vector<headset_key> known_keys()
{
if (not std::filesystem::exists(known_keys_file))
return {};
try
{
std::ifstream file(known_keys_file);
std::vector<headset_key> keys;
auto json = nlohmann::json::parse(file);
for (const auto & key: json)
{
keys.emplace_back(key["key"], key["name"]);
}
return keys;
}
catch (const std::exception & e)
{
U_LOG_E("Invalid key file: %s", e.what());
return {};
}
}
static void save_keys(const std::vector<headset_key> & keys)
{
nlohmann::json json;
for (const auto & key: keys)
{
json.push_back(nlohmann::json{
{"key", key.public_key},
{"name", key.name},
});
}
std::string json_str = json.dump();
std::filesystem::path known_keys_file_new = known_keys_file;
known_keys_file_new += ".new";
std::ofstream file(known_keys_file_new);
file.write(json_str.data(), json_str.size());
std::error_code ec;
std::filesystem::rename(known_keys_file_new, known_keys_file, ec);
if (ec)
U_LOG_E("Failed to save keys: %s", ec.message().c_str());
}
void add_known_key(headset_key key)
{
std::vector<headset_key> keys = known_keys();
if (key.name == "")
key.name = "Unknown headset";
int n = 1;
std::string original_name = key.name;
while (std::ranges::any_of(keys, [&](const headset_key & k) { return k.name == key.name; }))
{
key.name = original_name + " (" + std::to_string(++n) + ")";
}
keys.push_back(key);
save_keys(keys);
}
void remove_known_key(const std::string & key)
{
std::vector<headset_key> keys = known_keys();
std::erase_if(keys, [&](const headset_key & k) { return k.public_key == key; });
save_keys(keys);
}
void rename_known_key(headset_key key)
{
std::vector<headset_key> keys = known_keys();
for (headset_key & k: keys)
{
if (k.public_key == key.public_key)
k.name = key.name;
}
save_keys(keys);
}
} // namespace wivrn
+12 -1
View File
@@ -29,7 +29,6 @@
namespace wivrn
{
struct configuration
{
struct encoder
@@ -58,4 +57,16 @@ struct configuration
};
std::string server_cookie();
struct headset_key
{
std::string public_key;
std::string name;
};
std::vector<headset_key> known_keys();
void add_known_key(headset_key key);
void remove_known_key(const std::string & key);
void rename_known_key(headset_key key);
} // namespace wivrn
+3 -3
View File
@@ -124,7 +124,7 @@ static void create_encoders(wivrn_comp_target * cn)
assert(cn->wivrn_bundle);
cn->psc.status = 0;
auto & desc = cn->desc;
to_headset::video_stream_description & desc = cn->desc;
desc.width = cn->width;
desc.height = cn->height;
desc.foveation = cn->cnx.set_foveated_size(desc.width, desc.height);
@@ -148,7 +148,7 @@ static void create_encoders(wivrn_comp_target * cn)
std::string name = "encoder " + std::to_string(group);
pthread_setname_np(thread.native_handle(), name.c_str());
}
cn->cnx.send_control(desc);
cn->cnx.send_control(to_headset::video_stream_description{desc});
}
static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags flags)
@@ -746,7 +746,7 @@ void wivrn_comp_target::reset_encoders()
pacer.reset();
for (auto & encoder: encoders)
encoder->reset();
cnx.send_control(desc);
cnx.send_control(to_headset::video_stream_description{desc});
}
void wivrn_comp_target::render_dynamic_foveation(std::array<to_headset::foveation_parameter, 2> foveation)
+149 -76
View File
@@ -19,11 +19,16 @@
#include "wivrn_connection.h"
#include "configuration.h"
#include "util/u_logging.h"
#include "secrets.h"
#include "wivrn_ipc.h"
#include "wivrn_packets.h"
#include <algorithm>
#include <arpa/inet.h>
#include <chrono>
#include <poll.h>
#include <regex>
#include <sys/socket.h>
#include <variant>
using namespace std::chrono_literals;
@@ -32,16 +37,30 @@ static void handle_event_from_main_loop(to_monado::disconnect)
// Ignore disconnect request when no headset is connected
}
wivrn::wivrn_connection::wivrn_connection(TCP && tcp) :
control(std::move(tcp)), stream(-1)
static std::string clean_key(std::string key)
{
init();
static const std::regex header{"^-+BEGIN .*-+$", std::regex_constants::multiline};
static const std::regex footer{"^-+END .*-+$", std::regex_constants::multiline};
static const std::regex whitespace{"[[:space:]]"};
key = std::regex_replace(key, header, "");
key = std::regex_replace(key, footer, "");
key = std::regex_replace(key, whitespace, "");
return key;
}
void wivrn::wivrn_connection::init()
wivrn::wivrn_connection::wivrn_connection(std::stop_token stop_token, const std::string & pin, TCP && tcp) :
control(std::move(tcp)),
stream(-1),
pin(pin)
{
init(stop_token);
}
void wivrn::wivrn_connection::init(std::stop_token stop_token, std::function<void()> tick)
{
active = false;
stream = -1;
sockaddr_in6 server_address;
socklen_t len = sizeof(server_address);
@@ -58,9 +77,6 @@ void wivrn::wivrn_connection::init()
throw std::system_error(errno, std::system_category(), "Cannot get client address");
}
// Wait for client to send handshake
auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(10);
if (configuration::read_user_configuration().tcp_only)
{
port = -1;
@@ -71,84 +87,141 @@ void wivrn::wivrn_connection::init()
stream.bind(port);
}
auto receive = [&](std::optional<std::chrono::seconds> timeout = std::nullopt, bool allow_stream_socket = false) {
// Returns the packet and the port (on the stream socket) or -1 (on the control socket)
std::chrono::steady_clock::time_point timeout_abs{};
if (timeout)
timeout_abs = std::chrono::steady_clock::now() + *timeout;
while (true)
{
if (stop_token.stop_requested())
throw std::runtime_error("Connection cancelled");
tick();
pollfd fds[3] = {};
if (allow_stream_socket)
{
fds[0].events = POLLIN;
fds[0].fd = stream.get_fd();
}
fds[1].events = POLLIN;
fds[1].fd = control.get_fd();
fds[2].events = POLLIN;
fds[2].fd = wivrn_ipc_socket_monado->get_fd();
// Make sure tick() is called at least every 100ms
int r = ::poll(fds, std::size(fds), 100);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (allow_stream_socket and (fds[0].revents & (POLLHUP | POLLERR)))
throw std::runtime_error("Error on stream socket");
if (fds[1].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on control socket");
if (fds[2].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on IPC socket");
if (allow_stream_socket and (fds[0].revents & POLLIN))
{
auto [raw_packet, peer_addr] = stream.receive_from_raw();
// Ignore packets sent from the wrong address
if (memcmp(&peer_addr.sin6_addr, &client_address.sin6_addr, sizeof(peer_addr.sin6_addr)) == 0)
return std::make_pair(raw_packet.deserialize<from_headset::packets>(), (int)htons(peer_addr.sin6_port));
}
if (fds[1].revents & POLLIN)
{
std::optional<from_headset::packets> packet = control.receive();
if (packet)
return std::make_pair(std::move(*packet), -1);
}
if (fds[2].revents & POLLIN)
{
auto packet = receive_from_main();
if (packet)
std::visit([](auto && x) { handle_event_from_main_loop(x); }, *packet);
}
if (timeout and std::chrono::steady_clock::now() > timeout_abs)
{
throw std::runtime_error("No handshake received from client");
}
}
};
// Wait for client to send handshake packet
auto crypto_handshake = std::get<from_headset::crypto_handshake>(receive(10s).first);
crypto::key headset_key = crypto::key::from_public_key(crypto_handshake.public_key);
bool is_public_key_known = std::ranges::any_of(
wivrn::known_keys(),
[key = clean_key(crypto_handshake.public_key)](const wivrn::headset_key & k) {
return k.public_key == key;
});
// Generate an ephemeral key pair just for exchanging the AES key
crypto::key server_key = crypto::key::generate_x448_keypair();
control.send(to_headset::crypto_handshake{
.public_key = server_key.public_key(),
.pin_required = not is_public_key_known,
});
secrets s{server_key, headset_key, is_public_key_known ? "000000" : pin};
control.set_aes_key_and_ivs(s.control_key, s.control_iv_from_headset, s.control_iv_to_headset);
stream.set_aes_key_and_ivs(s.stream_key, s.stream_iv_header_from_headset, s.stream_iv_header_to_headset);
// Wait for confirmation that the client has set up encryption
if (not std::holds_alternative<from_headset::crypto_handshake>(receive().first))
throw std::runtime_error("No handshake received from client");
control.send(to_headset::handshake{.stream_port = port});
while (true)
auto [stream_handshake, client_port] = receive(10s, true);
// Check the packet type
if (not std::holds_alternative<from_headset::handshake>(stream_handshake))
{
pollfd fds[3] = {};
fds[0].events = POLLIN;
fds[0].fd = stream.get_fd();
fds[1].events = POLLIN;
fds[1].fd = control.get_fd();
fds[2].fd = wivrn_ipc_socket_monado->get_fd();
fds[2].events = POLLIN;
int r = ::poll(fds, std::size(fds), 1000);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (fds[0].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on stream socket");
if (fds[1].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on control socket");
if (fds[2].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on IPC socket");
if (fds[0].revents & POLLIN)
{
auto [packet, peer_addr] = stream.receive_from_raw();
if (memcmp(&peer_addr.sin6_addr, &client_address.sin6_addr, sizeof(peer_addr.sin6_addr)) == 0)
{
int client_port = htons(peer_addr.sin6_port);
stream.connect(peer_addr.sin6_addr, client_port);
U_LOG_D("Stream socket connected, client port %d", client_port);
stream.set_send_buffer_size(1024 * 1024 * 5);
break;
}
}
if (fds[1].revents & POLLIN)
{
auto packet = control.receive();
if (packet)
{
if (std::holds_alternative<from_headset::handshake>(*packet))
{
stream = decltype(stream)(-1);
port = -1;
U_LOG_I("Using TCP only");
break;
}
else
{
throw std::runtime_error("Invalid handshake received from client");
}
}
}
if (fds[2].revents & POLLIN)
{
auto packet = receive_from_main();
if (packet)
std::visit([](auto && x) { handle_event_from_main_loop(x); }, *packet);
}
if (std::chrono::steady_clock::now() > timeout)
{
throw std::runtime_error("No handshake received from client");
}
throw std::runtime_error("No handshake received from client");
}
if (client_port >= 0)
{
stream.connect(client_address.sin6_addr, client_port);
stream.set_send_buffer_size(1024 * 1024 * 5);
}
else
{
// No stream socket
}
control.send(to_headset::handshake{.stream_port = port});
info_packet = std::get<from_headset::headset_info_packet>(receive(10s).first);
active = true;
if (not is_public_key_known)
wivrn::add_known_key({
.public_key = clean_key(headset_key.public_key()),
.name = crypto_handshake.name,
});
}
void wivrn::wivrn_connection::reset(TCP && tcp)
void wivrn::wivrn_connection::reset(TCP && tcp, std::function<void()> tick)
{
if (stream)
stream = decltype(stream)();
control = std::move(tcp);
init();
init({}, tick);
}
void wivrn::wivrn_connection::shutdown()
+20 -8
View File
@@ -27,21 +27,24 @@
#include <optional>
#include <poll.h>
#include <stdexcept>
#include <stop_token>
#include <system_error>
namespace wivrn
{
class wivrn_connection
{
typed_socket<TCP, from_headset::packets, to_headset::packets> control;
typed_socket<UDP, from_headset::packets, to_headset::packets> stream;
std::atomic<bool> active = false;
std::string pin;
void init();
wivrn::from_headset::headset_info_packet info_packet;
void init(std::stop_token stop_token, std::function<void()> tick = []() {});
public:
wivrn_connection(TCP && tcp);
wivrn_connection(std::stop_token stop_token, const std::string & pin, TCP && tcp);
wivrn_connection(const wivrn_connection &) = delete;
wivrn_connection & operator=(const wivrn_connection &) = delete;
@@ -49,7 +52,7 @@ public:
{
return active;
}
void reset(TCP && tcp);
void reset(TCP && tcp, std::function<void()> tick = []() {});
void shutdown();
template <typename T>
@@ -66,15 +69,19 @@ public:
throw;
}
}
template <typename T>
void send_stream(T && packet)
{
try
{
if (active and stream)
stream.send(std::forward<T>(packet));
else
control.send(std::forward<T>(packet));
if (active)
{
if (stream)
stream.send(std::forward<T>(packet));
else
control.send(std::forward<T>(packet));
}
}
catch (...)
{
@@ -85,6 +92,11 @@ public:
std::optional<from_headset::packets> poll_control(int timeout);
const wivrn::from_headset::headset_info_packet & info() const
{
return info_packet;
}
template <typename T>
int poll(T && visitor, int timeout)
{
+30 -32
View File
@@ -122,24 +122,16 @@ bool wivrn::tracking_control_t::set_enabled(to_headset::tracking_control::id id,
return changed;
}
wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system & system) :
xrt_system_devices{
.get_roles = [](xrt_system_devices * self, xrt_system_roles * out_roles) { return ((wivrn_session *)self)->get_roles(out_roles); },
.feature_inc = [](xrt_system_devices * self, xrt_device_feature_type f) { return ((wivrn_session *)self)->feature_inc(f); },
.feature_dec = [](xrt_system_devices * self, xrt_device_feature_type f) { return ((wivrn_session *)self)->feature_dec(f); },
.destroy = [](xrt_system_devices * self) { delete ((wivrn_session *)self); },
},
connection(std::move(tcp)),
info([](wivrn_connection & connection) {
std::optional<wivrn::from_headset::packets> control;
while (not(control = connection.poll_control(-1)))
{
// FIXME: timeout
}
return std::get<from_headset::headset_info_packet>(*control);
}(connection)),
connection(std::move(connection)),
xrt_system(system),
hmd(this, info),
hmd(this, get_info()),
left_hand(0, &hmd, this),
right_hand(1, &hmd, this)
{
@@ -150,7 +142,7 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
"WiVRn(microphone)",
"wivrn.sink",
"WiVRn",
info,
get_info(),
*this);
if (audio_handle)
send_control(audio_handle->description());
@@ -198,14 +190,14 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
}
}
#endif
if (info.eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
if (get_info().eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
{
eye_tracker = std::make_unique<wivrn_eye_tracker>(&hmd);
foveation = std::make_unique<wivrn_foveation>();
static_roles.eyes = eye_tracker.get();
xdevs[xdev_count++] = eye_tracker.get();
}
if (info.face_tracking2_fb || is_forced_extension("FB_face_tracking2"))
if (get_info().face_tracking2_fb || is_forced_extension("FB_face_tracking2"))
{
fb_face2_tracker = std::make_unique<wivrn_fb_face2_tracker>(&hmd, *this);
static_roles.face = fb_face2_tracker.get();
@@ -234,10 +226,10 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
wivrn_session::~wivrn_session()
{
connection.shutdown();
connection->shutdown();
}
xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptr<wivrn_connection> connection,
u_system & system,
xrt_system_devices ** out_xsysd,
xrt_space_overseer ** out_xspovrs,
@@ -246,7 +238,7 @@ xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
std::unique_ptr<wivrn_session> self;
try
{
self.reset(new wivrn_session(std::move(tcp), system));
self.reset(new wivrn_session(std::move(connection), system));
}
catch (std::exception & e)
{
@@ -254,9 +246,9 @@ xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
return XRT_ERROR_DEVICE_CREATION_FAILED;
}
send_to_main(self->info);
send_to_main(self->get_info());
wivrn_comp_target_factory ctf(*self, self->info.preferred_refresh_rate);
wivrn_comp_target_factory ctf(*self, self->get_info().preferred_refresh_rate);
auto xret = comp_main_create_system_compositor(&self->hmd, &ctf, out_xsysc);
if (xret != XRT_SUCCESS)
{
@@ -294,7 +286,7 @@ clock_offset wivrn_session::get_offset()
bool wivrn_session::connected()
{
return connection.is_active();
return connection->is_active();
}
void wivrn_session::operator()(from_headset::headset_info_packet &&)
@@ -379,7 +371,7 @@ void wivrn_session::set_enabled(to_headset::tracking_control::id id, bool enable
void wivrn_session::set_enabled(device_id id, bool enabled)
{
if (tracking_control.set_enabled(to_tracking_control(id), enabled) and enabled)
tracking_control.send(connection, true);
tracking_control.send(*connection, true);
}
void wivrn_session::operator()(from_headset::feedback && feedback)
@@ -426,9 +418,9 @@ void wivrn_session::run(std::stop_token stop)
{
try
{
offset_est.request_sample(connection);
tracking_control.send(connection);
connection.poll(*this, 20);
offset_est.request_sample(*connection);
tracking_control.send(*connection);
connection->poll(*this, 20);
}
catch (const std::exception & e)
{
@@ -504,17 +496,18 @@ void wivrn_session::reconnect()
if (not tcp)
exit(0);
struct no_client_connected
{};
try
{
offset_est.reset();
connection.reset(std::move(*tcp));
std::optional<wivrn::from_headset::packets> control;
while (not(control = connection.poll_control(100)))
{
// FIXME: timeout
quit_if_no_client(xrt_system);
}
const auto & info = std::get<from_headset::headset_info_packet>(*control);
connection->reset(std::move(*tcp), [this]() {
if (quit_if_no_client(xrt_system))
throw no_client_connected{};
});
// const auto & info = connection->info();
// FIXME: ensure new client is compatible
comp_target->reset_encoders();
@@ -529,6 +522,11 @@ void wivrn_session::reconnect()
U_LOG_W("Failed to notify session state change");
}
}
catch (no_client_connected)
{
U_LOG_I("No OpenXR application connected");
exit(0);
}
catch (const std::exception & e)
{
U_LOG_E("Reconnection failed: %s", e.what());
+8 -8
View File
@@ -77,8 +77,7 @@ public:
class wivrn_session : public xrt_system_devices
{
friend wivrn_comp_target_factory;
wivrn_connection connection;
from_headset::headset_info_packet info{};
std::unique_ptr<wivrn_connection> connection;
u_system & xrt_system;
xrt_space_overseer * space_overseer;
@@ -113,12 +112,12 @@ class wivrn_session : public xrt_system_devices
std::jthread thread;
wivrn_session(TCP && tcp, u_system &);
wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system &);
public:
~wivrn_session();
static xrt_result_t create_session(TCP && tcp,
static xrt_result_t create_session(std::unique_ptr<wivrn_connection> connection,
u_system & system,
xrt_system_devices ** out_xsysd,
xrt_space_overseer ** out_xspovrs,
@@ -128,7 +127,7 @@ public:
bool connected();
const from_headset::headset_info_packet & get_info()
{
return info;
return connection->info();
};
void add_predict_offset(std::chrono::nanoseconds off)
@@ -139,8 +138,9 @@ public:
void set_enabled(to_headset::tracking_control::id id, bool enabled);
void set_enabled(device_id id, bool enabled);
void operator()(from_headset::handshake &&) {}
void operator()(from_headset::crypto_handshake &&) {}
void operator()(from_headset::headset_info_packet &&);
void operator()(from_headset::handshake &&) {}
void operator()(from_headset::trackings &&);
void operator()(const from_headset::tracking &);
void operator()(from_headset::hand_tracking &&);
@@ -155,13 +155,13 @@ public:
template <typename T>
void send_stream(T && packet)
{
connection.send_stream(std::forward<T>(packet));
connection->send_stream(std::forward<T>(packet));
}
template <typename T>
void send_control(T && packet)
{
connection.send_control(std::forward<T>(packet));
connection->send_control(std::forward<T>(packet));
}
std::array<to_headset::foveation_parameter, 2> set_foveated_size(uint32_t width, uint32_t height);