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
+1
View File
@@ -31,6 +31,7 @@ add_library(wivrn-common-base STATIC
add_library(wivrn-common STATIC
crypto.cpp
secrets.cpp
wivrn_sockets.cpp
utils/xdg_base_directory.cpp
vk/allocation.cpp
+32
View File
@@ -0,0 +1,32 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "secrets.h"
#include <cstring>
#include <type_traits>
secrets::secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin)
{
std::vector<uint8_t> dh = crypto::key::diffie_hellman(my_key, peer_key);
std::vector<uint8_t> secret = crypto::argon2(pin, "saltsalt", dh, sizeof(*this));
static_assert(std::is_standard_layout_v<secrets>);
static_assert(std::has_unique_object_representations_v<secrets>);
memcpy(this, secret.data(), secret.size());
}
+38
View File
@@ -0,0 +1,38 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "crypto.h"
#include <array>
#include <cstdint>
#include <string>
struct secrets
{
std::array<std::uint8_t, 16> control_key;
std::array<std::uint8_t, 16> control_iv_to_headset;
std::array<std::uint8_t, 16> control_iv_from_headset;
std::array<std::uint8_t, 16> stream_key;
std::array<std::uint8_t, 8> stream_iv_header_to_headset;
std::array<std::uint8_t, 8> stream_iv_header_from_headset;
secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin);
};
+31
View File
@@ -0,0 +1,31 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
namespace utils
{
template <class... Ts>
struct overloaded : Ts...
{
using Ts::operator()...;
};
template <class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
} // namespace utils
+180
View File
@@ -0,0 +1,180 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <condition_variable>
#include <mutex>
template <typename T>
class thread_safe_notifyable;
template <typename T, typename Mutex = std::mutex>
class locked
{
friend class thread_safe_notifyable<T>;
T & value;
std::unique_lock<Mutex> lock;
public:
locked(T & value, Mutex & mutex) :
value(value),
lock(mutex)
{}
T * operator->()
{
return &value;
}
const T * operator->() const
{
return &value;
}
T & operator*()
{
return value;
}
const T & operator*() const
{
return value;
}
};
template <typename T, typename Mutex = std::mutex>
class thread_safe
{
T value;
Mutex mutex;
public:
template <typename... Args>
thread_safe(Args &&... args) :
value(std::forward<Args>(args)...)
{}
locked<T, Mutex> lock()
{
return locked<T, Mutex>(value, mutex);
}
};
template <typename T>
class locked_notifiable
{
friend class thread_safe_notifyable<T>;
T & value;
std::unique_lock<std::mutex> lock;
std::condition_variable & cv;
public:
locked_notifiable(T & value, std::mutex & mutex, std::condition_variable & cv) :
value(value),
lock(mutex),
cv(cv)
{}
T * operator->()
{
return &value;
}
const T * operator->() const
{
return &value;
}
T & operator*()
{
return value;
}
const T & operator*() const
{
return value;
}
void notify_one() noexcept
{
cv.notify_one();
}
void notify_all() noexcept
{
cv.notify_all();
}
void wait()
{
cv.wait(lock);
}
template <class Predicate>
void wait(Predicate && pred)
{
cv.wait(lock, std::forward<Predicate>(pred));
}
template <class Rep, class Period>
std::cv_status wait_for(const std::chrono::duration<Rep, Period> & rel_time)
{
return cv.wait_for(lock, rel_time);
}
template <class Rep, class Period, class Predicate>
bool wait_for(const std::chrono::duration<Rep, Period> & rel_time, Predicate pred)
{
return cv.wait_for(lock, rel_time, pred);
}
template <class Clock, class Duration>
std::cv_status wait_until(const std::chrono::time_point<Clock, Duration> & abs_time)
{
return cv.wait_until(lock, abs_time);
}
template <class Clock, class Duration, class Predicate>
bool wait_until(const std::chrono::time_point<Clock, Duration> & abs_time, Predicate pred)
{
return cv.wait_until(lock, abs_time, pred);
}
};
template <typename T>
class thread_safe_notifyable : public thread_safe<T, std::mutex>
{
T value;
std::mutex mutex;
std::condition_variable cv;
public:
template <typename... Args>
thread_safe_notifyable(Args &&... args) :
thread_safe<T, std::mutex>(std::forward<Args>(args)...)
{}
locked_notifiable<T> lock()
{
return locked_notifiable<T>(value, mutex, cv);
}
};
+14 -4
View File
@@ -23,6 +23,7 @@
#include <chrono>
#include <cstdint>
#include <netinet/in.h>
#include <openssl/aes.h>
#include <optional>
#include <span>
#include <variant>
@@ -97,6 +98,11 @@ struct audio_data
namespace from_headset
{
struct crypto_handshake
{
std::string public_key; // In PEM format
std::string name;
};
struct headset_info_packet
{
@@ -255,11 +261,16 @@ struct battery
bool charging;
};
using packets = std::variant<headset_info_packet, feedback, audio_data, handshake, tracking, trackings, hand_tracking, inputs, timesync_response, battery>;
using packets = std::variant<crypto_handshake, headset_info_packet, feedback, audio_data, handshake, tracking, trackings, hand_tracking, inputs, timesync_response, battery>;
} // namespace from_headset
namespace to_headset
{
struct crypto_handshake
{
std::string public_key; // In PEM format
bool pin_required;
};
struct handshake
{
@@ -274,6 +285,7 @@ struct foveation_parameter_item
float a;
float b;
};
struct foveation_parameter
{
foveation_parameter_item x;
@@ -404,8 +416,6 @@ struct tracking_control
std::array<bool, size_t(id::last) + 1> enabled;
};
using packets = std::variant<handshake, audio_stream_description, video_stream_description, audio_data, video_stream_data_shard, haptics, timesync_query, tracking_control>;
using packets = std::variant<crypto_handshake, handshake, audio_stream_description, video_stream_description, audio_data, video_stream_data_shard, haptics, timesync_query, tracking_control>;
} // namespace to_headset
} // namespace wivrn
+30 -8
View File
@@ -98,9 +98,29 @@ size_t serialized_size(const T & x)
class deserialization_error : public std::runtime_error
{
static std::string hexdump(std::span<uint8_t> raw_data)
{
std::string s;
char buf[10];
for (int i = 0; i < raw_data.size(); i += 16)
{
sprintf(buf, "%04x ", i);
s += buf;
for (int j = i; j < std::min<int>(raw_data.size(), i + 16); j++)
{
sprintf(buf, "%02x ", (int)raw_data[j]);
s += buf;
}
s += "\n";
}
return s;
}
public:
deserialization_error() :
std::runtime_error("Deserialization error") {}
deserialization_error(std::span<uint8_t> raw_data) :
std::runtime_error("Deserialization error\n" + hexdump(raw_data)) {}
};
class serialization_packet
@@ -144,11 +164,11 @@ public:
serialization_traits<T>::serialize(value, *this);
}
operator const std::vector<std::span<uint8_t>> *()
operator std::vector<std::span<uint8_t>> *()
{
return &this->operator const std::vector<std::span<uint8_t>> &();
return &this->operator std::vector<std::span<uint8_t>> &();
}
operator const std::vector<std::span<uint8_t>> &()
operator std::vector<std::span<uint8_t>> &()
{
exp_spans.clear();
struct visitor
@@ -181,10 +201,12 @@ class deserialization_packet
std::span<uint8_t> buffer;
public:
std::span<uint8_t> initial_buffer;
deserialization_packet() = default;
explicit deserialization_packet(std::shared_ptr<uint8_t[]> memory, std::span<uint8_t> buffer) :
memory(memory),
buffer(buffer)
buffer(buffer),
initial_buffer(buffer)
{}
void read(void * data, size_t size)
@@ -211,7 +233,7 @@ public:
void check_remaining_size(size_t min_size) const
{
if (min_size > buffer.size_bytes())
throw deserialization_error();
throw deserialization_error(initial_buffer);
}
template <typename T>
@@ -773,7 +795,7 @@ struct serialization_traits<std::variant<T...>>
{
uint8_t type_index = packet.deserialize<uint8_t>();
if (type_index >= sizeof...(T))
throw deserialization_error();
throw deserialization_error(packet.initial_buffer);
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
}
-6
View File
@@ -28,12 +28,6 @@ namespace wivrn
// contains the data referenced by spans
struct data_holder
{
data_holder() = default;
data_holder(const data_holder &) = delete;
data_holder(data_holder &&) = default;
data_holder & operator=(const data_holder &) = delete;
data_holder & operator=(data_holder &&) = default;
std::shared_ptr<uint8_t[]> c;
};
+173 -54
View File
@@ -19,6 +19,8 @@
#include "wivrn_sockets.h"
#include "crypto.h"
#include <algorithm>
#include <arpa/inet.h>
#include <cassert>
#include <memory>
@@ -26,12 +28,16 @@
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <system_error>
#include <unistd.h>
thread_local crypto::encrypt_context wivrn::UDP::encrypter{EVP_aes_128_ctr()};
std::atomic<uint64_t> wivrn::UDP::iv_counter;
const char * wivrn::invalid_packet::what() const noexcept
{
return "Invalid packet";
@@ -63,6 +69,7 @@ wivrn::fd_base::~fd_base()
wivrn::UDP::UDP()
{
fd = socket(AF_INET6, SOCK_DGRAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -175,6 +182,7 @@ wivrn::TCP::TCP(int fd)
wivrn::TCP::TCP(in6_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -196,6 +204,7 @@ wivrn::TCP::TCP(in6_addr address, int port)
wivrn::TCP::TCP(in_addr address, int port)
{
fd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -214,10 +223,6 @@ wivrn::TCP::TCP(in_addr address, int port)
init();
}
wivrn::TCPListener::TCPListener()
{
}
wivrn::TCPListener::TCPListener(int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
@@ -271,8 +276,25 @@ std::pair<wivrn::deserialization_packet, sockaddr_in6> wivrn::UDP::receive_from_
bytes_received_ += received;
auto tmp = buffer.get();
return {deserialization_packet{std::move(buffer), std::span(tmp, received)}, addr};
std::span message{buffer.get(), (size_t)received};
if (encrypted)
{
// Not big enough for the IV: drop the packet
if (received < sizeof(uint64_t))
return {};
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), buffer.get(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), recv_iv_header.data(), recv_iv_header.size());
message = message.subspan(sizeof(uint64_t));
decrypter.set_iv(full_iv);
decrypter.decrypt_in_place(message);
}
return {deserialization_packet{std::move(buffer), message}, addr};
}
wivrn::deserialization_packet wivrn::UDP::receive_pending()
@@ -311,6 +333,7 @@ wivrn::deserialization_packet wivrn::UDP::receive_raw()
.iov_base = buffer.get() + message_size * i,
.iov_len = message_size,
});
mmsgs.push_back(
{
.msg_hdr = {
@@ -328,66 +351,114 @@ wivrn::deserialization_packet wivrn::UDP::receive_raw()
throw socket_shutdown();
messages.reserve(received);
for (int i = received - 1; i > 0; --i)
for (int i = received - 1; i >= 0; --i)
{
messages.emplace_back(
(uint8_t *)iovecs[i].iov_base,
mmsgs[i].msg_len);
bytes_received_ += mmsgs[i].msg_len;
std::span<uint8_t> message{(uint8_t *)iovecs[i].iov_base, mmsgs[i].msg_len};
assert(message.data() != nullptr);
if (encrypted)
{
// Not big enough for the IV: drop the packet
if (message.size() < sizeof(uint64_t))
throw std::runtime_error("Packet too small: " + std::to_string(message.size()));
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), message.data(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), recv_iv_header.data(), recv_iv_header.size());
message = message.subspan(sizeof(uint64_t));
decrypter.set_iv(full_iv);
decrypter.decrypt_in_place(message);
}
if (i == 0)
return deserialization_packet{buffer, message};
messages.push_back(message);
}
return deserialization_packet{buffer, std::span(buffer.get(), mmsgs[0].msg_len)};
__builtin_unreachable();
}
void wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
void wivrn::UDP::send_raw(serialization_packet && packet)
{
ssize_t sent = ::send(fd, data.data(), data.size(), 0);
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
thread_local std::vector<iovec> iovecs;
iovecs.clear();
bytes_sent_ += sent;
}
std::vector<std::span<uint8_t>> & data = packet;
uint64_t counter;
if (encrypted)
{
counter = iv_counter.fetch_add(1);
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), &counter, sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), send_iv_header.data(), send_iv_header.size());
iovecs.emplace_back(&counter, sizeof(uint64_t));
encrypter.set_key_and_iv(key, full_iv);
encrypter.encrypt_in_place(data);
}
void wivrn::UDP::send_raw(const std::vector<std::span<uint8_t>> & data)
{
thread_local std::vector<iovec> spans;
spans.clear();
for (const auto & span: data)
spans.emplace_back((void *)span.data(), span.size());
iovecs.emplace_back(span.data(), span.size());
if (::writev(fd, spans.data(), spans.size()) < 0)
if (::writev(fd, iovecs.data(), iovecs.size()) < 0)
throw std::system_error{errno, std::generic_category()};
}
void wivrn::UDP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data)
void wivrn::UDP::send_many_raw(std::vector<serialization_packet> && packets)
{
thread_local std::vector<iovec> iovecs;
thread_local std::vector<mmsghdr> mmsgs;
thread_local std::vector<uint64_t> iv_counters;
iovecs.clear();
mmsgs.clear();
for (const auto & message: data)
iv_counters.clear();
iv_counters.reserve(packets.size());
for (serialization_packet & packet: packets)
{
for (const auto & span: *message)
std::vector<std::span<uint8_t>> & data = packet;
if (encrypted)
{
iovecs.push_back(
{
.iov_base = span.data(),
.iov_len = span.size_bytes(),
});
iv_counters.push_back(iv_counter.fetch_add(1));
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), &iv_counters.back(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), send_iv_header.data(), send_iv_header.size());
iovecs.emplace_back(&iv_counters.back(), sizeof(uint64_t));
encrypter.set_key_and_iv(key, full_iv);
encrypter.encrypt_in_place(data);
}
for (const auto & span: data)
{
iovecs.emplace_back(span.data(), span.size_bytes());
}
if (encrypted)
mmsgs.push_back({.msg_hdr = {.msg_iovlen = data.size() + 1}});
else
mmsgs.push_back({.msg_hdr = {.msg_iovlen = data.size()}});
}
size_t i = 0;
for (const auto & message: data)
for (size_t i = 0, j = 0; i < packets.size(); ++i)
{
mmsgs.push_back(
{
.msg_hdr = {
.msg_iov = &iovecs[i],
.msg_iovlen = message->size(),
},
});
i += message->size();
mmsgs[i].msg_hdr.msg_iov = &iovecs[j];
j += mmsgs[i].msg_hdr.msg_iovlen;
}
// sendmmsg may not send all messages, just consider them as lost for UDP
if (sendmmsg(fd, mmsgs.data(), mmsgs.size(), 0) < 0)
throw std::system_error{errno, std::generic_category()};
@@ -422,18 +493,24 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
capacity_left = new_size - data.size_bytes();
}
ssize_t received = recv(fd, &*data.end(), capacity_left, MSG_DONTWAIT);
ssize_t received_size = recv(fd, &*data.end(), capacity_left, MSG_DONTWAIT);
if (received < 0)
if (received_size < 0)
throw std::system_error{errno, std::generic_category()};
if (received == 0)
if (received_size == 0)
throw socket_shutdown{};
bytes_received_ += received;
bytes_received_ += received_size;
data = std::span(data.data(), data.size() + received);
capacity_left -= received;
if (decrypter)
{
std::span<uint8_t> received_data{&*data.end(), (size_t)received_size};
decrypter.decrypt_in_place(received_data);
}
data = std::span(data.data(), data.size() + received_size);
capacity_left -= received_size;
if (data.size_bytes() < sizeof(uint16_t))
return {};
@@ -466,14 +543,16 @@ wivrn::deserialization_packet wivrn::TCP::receive_pending()
return deserialization_packet{buffer, span};
}
void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
void wivrn::TCP::send_raw(serialization_packet && packet)
{
thread_local std::vector<iovec> iovecs;
iovecs.clear();
std::vector<std::span<uint8_t>> & data = packet;
uint16_t size = 0;
iovecs.emplace_back(&size, sizeof(size));
for (const auto & span: spans)
for (const auto & span: data)
{
size += span.size_bytes();
iovecs.emplace_back(span.data(), span.size_bytes());
@@ -490,9 +569,14 @@ void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
};
std::lock_guard lock(*mutex);
if (encrypter)
{
data.insert(data.begin(), {(uint8_t *)&size, sizeof(size)});
encrypter.encrypt_in_place(data);
}
while (true)
{
const auto & data = spans[0];
ssize_t sent = ::sendmsg(fd, &hdr, MSG_NOSIGNAL);
if (sent == 0)
@@ -517,22 +601,30 @@ void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
}
}
void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data)
void wivrn::TCP::send_many_raw(std::vector<serialization_packet> && packets)
{
thread_local std::vector<iovec> iovecs;
thread_local std::vector<uint16_t> sizes;
thread_local std::vector<std::span<uint8_t>> spans;
iovecs.clear();
sizes.clear();
spans.clear();
sizes.reserve(data.size());
for (const auto & spans: data)
sizes.reserve(packets.size());
for (serialization_packet & packet: packets)
{
std::vector<std::span<uint8_t>> & data = packet;
auto & size = sizes.emplace_back(0);
iovecs.emplace_back(&size, sizeof(size));
for (const auto & span: *spans)
spans.emplace_back((uint8_t *)&size, sizeof(size));
for (const auto & span: data)
{
size += span.size_bytes();
iovecs.emplace_back(span.data(), span.size_bytes());
spans.emplace_back(span.data(), span.size_bytes());
}
}
@@ -547,6 +639,11 @@ void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *
};
std::lock_guard lock(*mutex);
if (encrypter)
{
encrypter.encrypt_in_place(spans);
}
while (true)
{
ssize_t sent = ::sendmsg(fd, &hdr, MSG_NOSIGNAL);
@@ -572,3 +669,25 @@ void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *
hdr.msg_iov[0].iov_len -= sent;
}
}
void wivrn::UDP::set_aes_key_and_ivs(std::span<std::uint8_t, 16> key_, std::span<std::uint8_t, 8> recv_iv_header_, std::span<std::uint8_t, 8> send_iv_header_)
{
decrypter = crypto::decrypt_context{EVP_aes_128_ctr()};
decrypter.set_key(key_);
std::ranges::copy(key_, key.begin());
std::ranges::copy(recv_iv_header_, recv_iv_header.begin());
std::ranges::copy(send_iv_header_, send_iv_header.begin());
encrypted = true;
}
void wivrn::TCP::set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 16> recv_iv, std::span<std::uint8_t, 16> send_iv)
{
encrypter = crypto::encrypt_context{EVP_aes_128_ctr()};
encrypter.set_key(key);
encrypter.set_iv(send_iv);
decrypter = crypto::decrypt_context{EVP_aes_128_ctr()};
decrypter.set_key(key);
decrypter.set_iv(recv_iv);
}
+37 -13
View File
@@ -19,11 +19,13 @@
#pragma once
#include "crypto.h"
#include "wivrn_serialization.h"
#include <atomic>
#include <cassert>
#include <exception>
#include <fcntl.h>
#include <memory>
#include <mutex>
#include <netinet/ip.h>
@@ -103,6 +105,16 @@ class UDP : public fd_base
std::shared_ptr<uint8_t[]> buffer;
std::vector<std::span<uint8_t>> messages;
crypto::decrypt_context decrypter;
static thread_local crypto::encrypt_context encrypter;
static std::atomic<uint64_t> iv_counter;
static_assert(sizeof(iv_counter) == 8);
bool encrypted = false;
std::array<uint8_t, 16> key;
std::array<uint8_t, 16 - sizeof(iv_counter)> recv_iv_header;
std::array<uint8_t, 16 - sizeof(iv_counter)> send_iv_header;
public:
UDP();
explicit UDP(int fd);
@@ -110,9 +122,8 @@ public:
deserialization_packet receive_raw();
deserialization_packet receive_pending();
std::pair<wivrn::deserialization_packet, sockaddr_in6> receive_from_raw();
void send_raw(const std::vector<uint8_t> & data);
void send_raw(const std::vector<std::span<uint8_t>> & data);
void send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data);
void send_raw(serialization_packet && packet);
void send_many_raw(std::vector<serialization_packet> && packets);
void connect(in6_addr address, int port);
void connect(in_addr address, int port);
@@ -122,6 +133,8 @@ public:
void set_receive_buffer_size(int size);
void set_send_buffer_size(int size);
void set_tos(int type_of_service);
void set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 8> recv_iv_header, std::span<std::uint8_t, 8> send_iv_header);
};
class TCP : public fd_base
@@ -133,15 +146,21 @@ class TCP : public fd_base
void init();
crypto::decrypt_context decrypter;
crypto::encrypt_context encrypter;
public:
TCP() = default;
TCP(in6_addr address, int port);
TCP(in_addr address, int port);
explicit TCP(int fd);
deserialization_packet receive_raw();
deserialization_packet receive_pending();
void send_raw(const std::vector<std::span<uint8_t>> & data);
void send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data);
void send_raw(serialization_packet && packet);
void send_many_raw(std::vector<serialization_packet> && packets);
void set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 16> recv_iv, std::span<std::uint8_t, 16> send_iv);
};
using UnixDatagram = UDP;
@@ -149,7 +168,7 @@ using UnixDatagram = UDP;
class TCPListener : public fd_base
{
public:
TCPListener();
TCPListener() = default;
TCPListener(int port);
template <typename T = TCP>
@@ -160,6 +179,7 @@ public:
socklen_t addrlen = sizeof(addr);
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd2 < 0)
throw std::system_error{errno, std::generic_category()};
@@ -185,6 +205,10 @@ struct Index<T, std::tuple<U, Types...>>
{
static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
};
template <typename T>
concept not_lvalue_reference = !std::is_lvalue_reference_v<T>;
} // namespace details
template <typename Socket, typename ReceivedType, typename... VariantTypes>
@@ -224,21 +248,21 @@ public:
p.serialize(data);
}
template <typename T>
void send(const T & data)
template <details::not_lvalue_reference T>
void send(T && data)
{
thread_local serialization_packet p;
serialize(p, data);
this->send_raw(p);
this->send_raw(std::move(p));
}
void send(const std::span<serialization_packet> & packets)
void send(std::vector<serialization_packet> && packets)
{
thread_local std::vector<const std::vector<std::span<uint8_t>> *> data;
thread_local std::vector<serialization_packet> data;
data.clear();
for (auto & packet: packets)
for (serialization_packet & packet: packets)
data.emplace_back(packet);
this->send_many_raw(data);
this->send_many_raw(std::move(data));
}
};