From 447b77c35c52a747f48ed0f5ea7cd6b0d17e54bb Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Sun, 3 Nov 2024 23:03:57 +0100 Subject: [PATCH] Add OpenSSL --- .github/workflows/Build.yml | 6 +- CMakeLists.txt | 4 + client/CMakeLists.txt | 1 - common/CMakeLists.txt | 44 ++- common/crypto.cpp | 539 +++++++++++++++++++++++++++++ common/crypto.h | 187 ++++++++++ server/driver/wivrn_connection.cpp | 1 + 7 files changed, 777 insertions(+), 5 deletions(-) create mode 100644 common/crypto.cpp create mode 100644 common/crypto.h diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 2f4927a4..fbf377bc 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -28,7 +28,7 @@ jobs: - name: Install dependencies run: > - sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev policykit-1 libboost-all-dev librsvg2-bin + sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libavahi-glib-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev nlohmann-json3-dev libpulse-dev xz-utils libpipewire-0.3-dev libcli11-dev qt6-base-dev qt6-tools-dev libcap-dev policykit-1 libboost-all-dev librsvg2-bin libssl-dev - name: Prepare Vulkan SDK uses: humbletim/setup-vulkan-sdk@286ed76c72de45dbf50c515779cf4ca2f6aa3944 with: @@ -126,7 +126,7 @@ jobs: - name: Install dependencies run: > - sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev libxcb-glx0-dev gettext libfontconfig-dev libboost-all-dev librsvg2-bin + sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev libxcb-glx0-dev gettext libfontconfig-dev libboost-all-dev librsvg2-bin libssl-dev - name: Configure CMake run: > @@ -163,7 +163,7 @@ jobs: - name: Install dependencies run: > - sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev libopenxr-dev wireshark wireshark-dev + sudo apt-get update && sudo apt-get install libvulkan-dev libcjson-dev libx264-dev libavcodec-dev libavutil-dev libswscale-dev libavfilter-dev libbsd-dev libavahi-client-dev libeigen3-dev glslang-tools libudev-dev libwayland-dev libx11-xcb-dev libxrandr-dev libxcb-randr0-dev libgl-dev libglx-dev mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev libsystemd-dev libva-dev libopenxr-dev wireshark wireshark-dev libssl-dev - name: Configure CMake run: > diff --git a/CMakeLists.txt b/CMakeLists.txt index 649e39d9..6fe35222 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,6 +69,9 @@ endif() find_package(PkgConfig REQUIRED) find_package(Vulkan REQUIRED) find_package(Git) +if (NOT ANDROID) + find_package(OpenSSL REQUIRED) +endif() include(VulkanVersion) if (WIVRN_USE_SYSTEM_BOOST STREQUAL "AUTO") @@ -218,6 +221,7 @@ endif() # Common dependencies FetchContent_Declare(boostpfr EXCLUDE_FROM_ALL SYSTEM URL https://github.com/boostorg/pfr/archive/refs/tags/2.2.0.tar.gz) FetchContent_Declare(boost EXCLUDE_FROM_ALL SYSTEM URL https://github.com/boostorg/boost/releases/download/boost-1.84.0/boost-1.84.0.tar.xz) + # Client dependencies FetchContent_Declare(simdjson EXCLUDE_FROM_ALL SYSTEM URL https://github.com/simdjson/simdjson/archive/refs/tags/v3.10.1.tar.gz) FetchContent_Declare(fastgltf EXCLUDE_FROM_ALL SYSTEM URL https://github.com/spnda/fastgltf/archive/refs/tags/v0.7.1.tar.gz) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index bd4d0764..907bb2cd 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -174,7 +174,6 @@ else() endif() - ############################################################################## # Internationalization # diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 032564e8..8dcd3003 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -30,6 +30,7 @@ add_library(wivrn-common-base STATIC ) add_library(wivrn-common STATIC + crypto.cpp wivrn_sockets.cpp utils/xdg_base_directory.cpp vk/allocation.cpp @@ -56,11 +57,52 @@ if(ANDROID) target_include_directories(wivrn-common SYSTEM PUBLIC ${CMAKE_BINARY_DIR}/Vulkan-Headers-vulkan-sdk-${VULKAN_VERSION}/include) target_compile_definitions(wivrn-common PUBLIC VMA_VULKAN_VERSION=1001000) + + + # The NDK does not include OpenSSL, download it + set(OPENSSL_VERSION "3.4.0") + if(NOT EXISTS ${CMAKE_BINARY_DIR}/openssl-src) + if(NOT EXISTS ${CMAKE_BINARY_DIR}/openssl-${OPENSSL_VERSION}.tar.gz) + if (EXISTS ${CMAKE_SOURCE_DIR}/openssl-${OPENSSL_VERSION}.tar.gz) + file(CREATE_LINK ${CMAKE_SOURCE_DIR}/openssl-${OPENSSL_VERSION}.tar.gz ${CMAKE_BINARY_DIR}/openssl-${OPENSSL_VERSION}.tar.gz SYMBOLIC) + else() + file(DOWNLOAD https://github.com/openssl/openssl/archive/refs/tags/openssl-${OPENSSL_VERSION}.tar.gz ${CMAKE_BINARY_DIR}/openssl-${OPENSSL_VERSION}.tar.gz + EXPECTED_HASH SHA256=1ca043a26fbea74cdf7faf623a6f14032a01117d141c4a5208ccac819ccc896b) + endif() + endif() + + file(ARCHIVE_EXTRACT INPUT ${CMAKE_BINARY_DIR}/openssl-${OPENSSL_VERSION}.tar.gz DESTINATION ${CMAKE_BINARY_DIR}) + file(RENAME ${CMAKE_BINARY_DIR}/openssl-openssl-${OPENSSL_VERSION} ${CMAKE_BINARY_DIR}/openssl-src) + endif() + + execute_process( + COMMAND ${CMAKE_COMMAND} -E env ANDROID_NDK_ROOT=${CMAKE_ANDROID_NDK} PATH=${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin:$ENV{PATH} ./Configure + android-arm64 + --prefix=${CMAKE_BINARY_DIR}/openssl + --openssldir=${CMAKE_BINARY_DIR}/openssl + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/openssl-src + OUTPUT_FILE ${CMAKE_BINARY_DIR}/openssl-config-out + ERROR_FILE ${CMAKE_BINARY_DIR}/openssl-config-err + ) + + if (NOT EXISTS ${CMAKE_BINARY_DIR}/openssl/lib/libcrypto.so) + execute_process( + COMMAND ${CMAKE_COMMAND} -E env ANDROID_NDK_ROOT=${CMAKE_ANDROID_NDK} PATH=${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin:$ENV{PATH} make -j${CMAKE_BUILD_PARALLEL_LEVEL} + COMMAND ${CMAKE_COMMAND} -E env ANDROID_NDK_ROOT=${CMAKE_ANDROID_NDK} PATH=${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin:$ENV{PATH} make install_sw + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/openssl-src + OUTPUT_FILE ${CMAKE_BINARY_DIR}/openssl-make-out + ERROR_FILE ${CMAKE_BINARY_DIR}/openssl-make-err + ) + endif() + + add_library(OpenSSL::Crypto STATIC IMPORTED) + set_property(TARGET OpenSSL::Crypto PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/openssl/lib/libcrypto.so) + target_include_directories(OpenSSL::Crypto INTERFACE ${CMAKE_BINARY_DIR}/openssl/include) else() target_link_libraries(wivrn-common PUBLIC Vulkan::Headers) endif() target_include_directories(wivrn-common-base PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) -target_link_libraries(wivrn-common PUBLIC Boost::pfr wivrn-external wivrn-common-base) +target_link_libraries(wivrn-common PUBLIC Boost::pfr OpenSSL::Crypto wivrn-external wivrn-common-base) target_compile_features(wivrn-common PRIVATE cxx_std_20) target_compile_definitions(wivrn-common PUBLIC VULKAN_HPP_NO_STRUCT_CONSTRUCTORS) diff --git a/common/crypto.cpp b/common/crypto.cpp new file mode 100644 index 00000000..20b1318e --- /dev/null +++ b/common/crypto.cpp @@ -0,0 +1,539 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#include "crypto.h" + +#include +#include +#include +#include +#include +#include +#include +// #include +#include +#include + +namespace +{ +void throw_openssl_error() +{ + char buf[256]; + ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); + throw std::runtime_error(buf); +} + +struct bio +{ + BIO * mem = nullptr; + + bio() + { + mem = BIO_new(BIO_s_mem()); + } + + bio(std::string_view data) + { + mem = BIO_new_mem_buf(data.data(), data.size()); + if (!mem) + throw_openssl_error(); + } + + bio(const bio &) = delete; + bio & operator=(const bio &) = delete; + + ~bio() + { + BIO_free(mem); + } + + operator BIO *() + { + return mem; + } + + operator std::string_view() + { + char * data = nullptr; + size_t size = BIO_get_mem_data(mem, &data); + + return {data, size}; + } + + operator std::string() + { + char * data = nullptr; + size_t size = BIO_get_mem_data(mem, &data); + + return {data, size}; + } +}; +} // namespace + +namespace crypto::details +{ +class key_context +{ + EVP_PKEY_CTX * ctx = nullptr; + +public: + key_context() = default; + key_context(const key_context &) = delete; + key_context & operator=(const key_context &) = delete; + key_context(key_context && other) noexcept : + ctx(other.ctx) + { + other.ctx = nullptr; + } + + key_context & operator=(key_context && other) noexcept + { + std::swap(ctx, other.ctx); + return *this; + } + + ~key_context() + { + EVP_PKEY_CTX_free(ctx); + } + + key_context(EVP_PKEY_CTX * ctx) : + ctx(ctx) {} + + static key_context from_id(int id) + { + key_context ctx{EVP_PKEY_CTX_new_id(id, nullptr)}; + if (!ctx) + throw_openssl_error(); + return ctx; + } + + static key_context from_key(key & k) + { + key_context ctx{EVP_PKEY_CTX_new(k, nullptr)}; + if (!ctx) + throw_openssl_error(); + return ctx; + } + + operator EVP_PKEY_CTX *() + { + return ctx; + } + + operator bool() const + { + return ctx != nullptr; + } +}; + +class kdf_context +{ + EVP_KDF * kdf = nullptr; + EVP_KDF_CTX * ctx = nullptr; + +public: + kdf_context() = default; + kdf_context(const kdf_context &) = delete; + kdf_context & operator=(const kdf_context &) = delete; + kdf_context(kdf_context && other) noexcept : + ctx(other.ctx) + { + other.ctx = nullptr; + } + + kdf_context & operator=(kdf_context && other) noexcept + { + std::swap(ctx, other.ctx); + return *this; + } + + ~kdf_context() + { + EVP_KDF_CTX_free(ctx); + EVP_KDF_free(kdf); + } + + kdf_context(const char * algorithm) + { + kdf = EVP_KDF_fetch(nullptr, algorithm /*"ARGON2D"*/, nullptr); + if (!kdf) + throw_openssl_error(); + + ctx = EVP_KDF_CTX_new(kdf); + if (!ctx) + { + EVP_KDF_free(kdf); + throw_openssl_error(); + } + } + + operator EVP_KDF_CTX *() + { + return ctx; + } + + operator bool() const + { + return ctx != nullptr; + } +}; + +} // namespace crypto::details + +namespace crypto +{ +key key::from_public_key(std::string_view pem) +{ + bio mem{pem}; + + key pkey{PEM_read_bio_PUBKEY(mem, nullptr, nullptr, nullptr)}; + + if (!pkey.pkey) + throw_openssl_error(); + + return pkey; +} + +key key::from_private_key(std::string_view pem) +{ + bio mem{pem}; + + key pkey{PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr)}; + + if (!pkey.pkey) + throw_openssl_error(); + + return pkey; +} + +std::string key::public_key() const +{ + bio mem; + PEM_write_bio_PUBKEY(mem, pkey); + return mem; +} + +std::string key::private_key() const +{ + bio mem; + PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr, nullptr); + return mem; +} + +key key::generate_rsa_keypair(int bits) +{ + auto ctx = details::key_context::from_id(EVP_PKEY_RSA); + + if (EVP_PKEY_keygen_init(ctx) <= 0) + throw_openssl_error(); + + if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) <= 0) + throw_openssl_error(); + + EVP_PKEY * pkey = nullptr; + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + throw_openssl_error(); + + return pkey; +} + +key key::generate_x25519_keypair() +{ + auto ctx = details::key_context::from_id(EVP_PKEY_X25519); + + if (EVP_PKEY_keygen_init(ctx) <= 0) + throw_openssl_error(); + + EVP_PKEY * pkey = nullptr; + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + throw_openssl_error(); + + return pkey; +} + +key key::generate_x448_keypair() +{ + auto ctx = details::key_context::from_id(EVP_PKEY_X448); + + if (EVP_PKEY_keygen_init(ctx) <= 0) + throw_openssl_error(); + + EVP_PKEY * pkey = nullptr; + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + throw_openssl_error(); + + return pkey; +} + +std::vector key::diffie_hellman(key & my_key, key & peer_key) +{ + auto ctx = details::key_context::from_key(my_key); + + if (EVP_PKEY_derive_init(ctx) <= 0) + throw_openssl_error(); + + if (EVP_PKEY_derive_set_peer(ctx, peer_key) <= 0) + throw_openssl_error(); + + size_t skeylen = 0; + if (EVP_PKEY_derive(ctx, NULL, &skeylen) <= 0) + throw_openssl_error(); + + std::vector skey; + skey.resize(skeylen); + + if (EVP_PKEY_derive(ctx, skey.data(), &skeylen) <= 0) + throw_openssl_error(); + + return skey; +} + +key::wrapped_secret key::encapsulate() +{ + auto ctx = details::key_context::from_key(*this); + + if (EVP_PKEY_encapsulate_init(ctx, nullptr) <= 0) + throw_openssl_error(); + + if (EVP_PKEY_CTX_set_kem_op(ctx, "RSASVE") <= 0) + throw_openssl_error(); + + size_t wrapped_len = 0, secret_len = 0; + if (EVP_PKEY_encapsulate(ctx, nullptr, &wrapped_len, nullptr, &secret_len) <= 0) + throw_openssl_error(); + + wrapped_secret ws; + + ws.wrapped.resize(wrapped_len); + ws.secret.resize(secret_len); + + if (EVP_PKEY_encapsulate(ctx, ws.wrapped.data(), &wrapped_len, ws.secret.data(), &secret_len) <= 0) + throw_openssl_error(); + + return ws; +} + +std::vector key::decapsulate(std::span wrapped) +{ + auto ctx = details::key_context::from_key(*this); + + if (EVP_PKEY_decapsulate_init(ctx, nullptr) <= 0) + throw_openssl_error(); + + if (EVP_PKEY_CTX_set_kem_op(ctx, "RSASVE") <= 0) + throw_openssl_error(); + + size_t secret_len = 0; + if (EVP_PKEY_decapsulate(ctx, nullptr, &secret_len, wrapped.data(), wrapped.size()) <= 0) + throw_openssl_error(); + + std::vector secret; + secret.resize(secret_len); + + if (EVP_PKEY_decapsulate(ctx, secret.data(), &secret_len, wrapped.data(), wrapped.size()) <= 0) + throw_openssl_error(); + + return secret; +} + +void cipher_context::set_key(std::span key) +{ + if (not ctx) + throw std::invalid_argument("Uninitalized context"); + + if (key.size() != key_length()) + throw std::invalid_argument("Wrong key length, expected " + std::to_string(key_length()) + ", got " + std::to_string(key.size())); + + if (not EVP_CipherInit_ex2(ctx, nullptr, key.data(), nullptr, -1, nullptr)) + throw_openssl_error(); +} + +void cipher_context::set_iv(std::span iv) +{ + if (not ctx) + throw std::invalid_argument("Uninitalized context"); + + if (iv.size() != iv_length()) + throw std::invalid_argument("Wrong IV length, expected" + std::to_string(iv_length()) + ", got " + std::to_string(iv.size())); + + if (not EVP_CipherInit_ex2(ctx, nullptr, nullptr, iv.data(), -1, nullptr)) + throw_openssl_error(); +} + +void cipher_context::set_key_and_iv(std::span key, std::span iv) +{ + if (not ctx) + throw std::invalid_argument("Uninitalized context"); + + if (key.size() != key_length()) + throw std::invalid_argument("Wrong key length, expected " + std::to_string(key_length()) + ", got " + std::to_string(key.size())); + + if (iv.size() != iv_length()) + throw std::invalid_argument("Wrong IV length, expected" + std::to_string(iv_length()) + ", got " + std::to_string(iv.size())); + + if (not EVP_CipherInit_ex2(ctx, nullptr, key.data(), iv.data(), -1, nullptr)) + throw_openssl_error(); +} + +encrypt_context::encrypt_context(const EVP_CIPHER * cipher) +{ + ctx = EVP_CIPHER_CTX_new(); + if (!ctx) + throw_openssl_error(); + + if (not EVP_EncryptInit_ex2(ctx, cipher, nullptr, nullptr, nullptr)) + throw_openssl_error(); + + key_length_ = EVP_CIPHER_CTX_get_key_length(ctx); + iv_length_ = EVP_CIPHER_CTX_get_iv_length(ctx); + block_size_ = EVP_CIPHER_CTX_get_block_size(ctx); +} + +// TODO handle AES-GCM correctly +std::vector encrypt_context::encrypt(std::span plaintext) +{ + if (not EVP_EncryptInit_ex2(ctx, nullptr, nullptr, nullptr, nullptr)) + throw_openssl_error(); + + std::vector ciphertext; + ciphertext.resize(plaintext.size() + block_size()); + + int size_out = 0; + if (not EVP_EncryptUpdate(ctx, ciphertext.data(), &size_out, plaintext.data(), plaintext.size())) + throw_openssl_error(); + + int size_out2 = 0; + if (not EVP_EncryptFinal_ex(ctx, plaintext.data() + size_out, &size_out2)) + throw_openssl_error(); + + ciphertext.resize(size_out + size_out2); + return ciphertext; +} + +void encrypt_context::encrypt_in_place(std::span text) +{ + if (block_size() != 1) + throw std::runtime_error("Not a stream cipher"); + + int size_out = text.size(); + if (not EVP_EncryptUpdate(ctx, text.data(), &size_out, text.data(), text.size())) + throw_openssl_error(); +} + +void encrypt_context::encrypt_in_place(std::span> text) +{ + if (block_size() != 1) + throw std::runtime_error("Not a stream cipher"); + + for (std::span i: text) + { + int size_out = i.size(); + if (not EVP_EncryptUpdate(ctx, i.data(), &size_out, i.data(), i.size())) + throw_openssl_error(); + } +} + +decrypt_context::decrypt_context(const EVP_CIPHER * cipher) +{ + ctx = EVP_CIPHER_CTX_new(); + if (!ctx) + throw_openssl_error(); + + if (not EVP_DecryptInit(ctx, cipher, nullptr, nullptr)) + throw_openssl_error(); + + key_length_ = EVP_CIPHER_CTX_get_key_length(ctx); + iv_length_ = EVP_CIPHER_CTX_get_iv_length(ctx); + block_size_ = EVP_CIPHER_CTX_get_block_size(ctx); +} + +std::vector decrypt_context::decrypt(std::span ciphertext) +{ + if (not EVP_DecryptInit_ex2(ctx, nullptr, nullptr, nullptr, nullptr)) + throw_openssl_error(); + + std::vector plaintext; + plaintext.resize(ciphertext.size() + block_size()); + + int size_out = 0; + if (not EVP_DecryptUpdate(ctx, plaintext.data(), &size_out, ciphertext.data(), ciphertext.size())) + throw_openssl_error(); + + int size_out2 = 0; + if (not EVP_DecryptFinal_ex(ctx, ciphertext.data() + size_out, &size_out2)) + throw_openssl_error(); + + plaintext.resize(size_out + size_out2); + return plaintext; +} + +void decrypt_context::decrypt_in_place(std::span text) +{ + if (block_size() != 1) + throw std::runtime_error("Not a stream cipher"); + + int size_out = text.size(); + if (not EVP_DecryptUpdate(ctx, text.data(), &size_out, text.data(), text.size())) + throw_openssl_error(); +} + +void decrypt_context::decrypt_in_place(std::span> text) +{ + if (block_size() != 1) + throw std::runtime_error("Not a stream cipher"); + + for (std::span i: text) + { + int size_out = i.size(); + if (not EVP_DecryptUpdate(ctx, i.data(), &size_out, i.data(), i.size())) + throw_openssl_error(); + } +} + +std::vector argon2(std::string pass, std::string salt, std::span secret, size_t size) +{ + /* argon2 params, please refer to RFC9106 for recommended defaults */ + uint32_t lanes = 2; + uint32_t threads = 2; + uint32_t memcost = 65536; + + // if (OSSL_set_max_threads(nullptr, threads) != 1) + // throw_openssl_error(); + + std::array params{ + OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_THREADS, &threads), + OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES, &lanes), + OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memcost), + OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt.data(), salt.size()), + OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, pass.data(), pass.size()), + OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, secret.data(), secret.size()), + OSSL_PARAM_construct_end(), + }; + + details::kdf_context kdf{"ARGON2I"}; + + std::vector result; + result.resize(size); + if (EVP_KDF_derive(kdf, result.data(), size, params.data()) != 1) + throw_openssl_error(); + + return result; +} + +} // namespace crypto diff --git a/common/crypto.h b/common/crypto.h new file mode 100644 index 00000000..743394f6 --- /dev/null +++ b/common/crypto.h @@ -0,0 +1,187 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include + +namespace crypto +{ +class key +{ + EVP_PKEY * pkey = nullptr; + +public: + key() = default; + key(const key &) = delete; + key & operator=(const key &) = delete; + key(key && other) noexcept : + pkey(other.pkey) + { + other.pkey = nullptr; + } + + key & operator=(key && other) noexcept + { + std::swap(pkey, other.pkey); + + return *this; + } + + ~key() + { + EVP_PKEY_free(pkey); + } + + key(EVP_PKEY * pkey) : + pkey(pkey) {} + + static key from_public_key(std::string_view pem); + static key from_private_key(std::string_view pem); + static key generate_rsa_keypair(int bits); + static key generate_x25519_keypair(); + static key generate_x448_keypair(); + + std::string public_key() const; + std::string private_key() const; + + operator EVP_PKEY *() + { + return pkey; + } + + operator bool() const + { + return pkey != nullptr; + } + + // Works with x25519, x448 keys + static std::vector diffie_hellman(key & my_key, key & peer_key); + + struct wrapped_secret + { + std::vector wrapped; + std::vector secret; + }; + + // Works with RSA keys + wrapped_secret encapsulate(); + std::vector decapsulate(std::span wrapped); +}; + +class cipher_context +{ +protected: + EVP_CIPHER_CTX * ctx = nullptr; + + cipher_context() = default; + cipher_context(const cipher_context &) = delete; + cipher_context & operator=(const cipher_context &) = delete; + cipher_context(cipher_context && other) noexcept : + ctx(other.ctx), + key_length_(other.key_length_), + iv_length_(other.iv_length_), + block_size_(other.block_size_) + { + other.ctx = nullptr; + } + + cipher_context & operator=(cipher_context && other) noexcept + { + std::swap(ctx, other.ctx); + key_length_ = other.key_length_; + iv_length_ = other.iv_length_; + block_size_ = other.block_size_; + return *this; + } + + ~cipher_context() + { + EVP_CIPHER_CTX_free(ctx); + } + size_t key_length_; + size_t iv_length_; + size_t block_size_; + +public: + void set_key(std::span key); + void set_iv(std::span iv); + void set_key_and_iv(std::span key, std::span iv); + + size_t key_length() const + { + return key_length_; + } + + size_t iv_length() const + { + return iv_length_; + } + + size_t block_size() const + { + return block_size_; + } + + operator bool() const + { + return ctx != nullptr; + } +}; + +class encrypt_context : public cipher_context +{ +public: + encrypt_context() = default; + encrypt_context(const encrypt_context &) = delete; + encrypt_context & operator=(const encrypt_context &) = delete; + encrypt_context(encrypt_context &&) noexcept = default; + encrypt_context & operator=(encrypt_context &&) noexcept = default; + ~encrypt_context() = default; + + explicit encrypt_context(const EVP_CIPHER * cipher); + + std::vector encrypt(std::span plaintext); + void encrypt_in_place(std::span plaintext); + void encrypt_in_place(std::span> plaintext); +}; + +class decrypt_context : public cipher_context +{ +public: + decrypt_context() = default; + decrypt_context(const decrypt_context &) = delete; + decrypt_context & operator=(const decrypt_context &) = delete; + decrypt_context(decrypt_context && other) noexcept = default; + decrypt_context & operator=(decrypt_context &&) noexcept = default; + ~decrypt_context() = default; + + explicit decrypt_context(const EVP_CIPHER * cipher); + + std::vector decrypt(std::span ciphertext); + void decrypt_in_place(std::span ciphertext); + void decrypt_in_place(std::span> ciphertext); +}; + +// Salt must be at least 8 characters +std::vector argon2(std::string pass, std::string salt, std::span secret, size_t size); + +} // namespace crypto diff --git a/server/driver/wivrn_connection.cpp b/server/driver/wivrn_connection.cpp index deb115ee..d801d14a 100644 --- a/server/driver/wivrn_connection.cpp +++ b/server/driver/wivrn_connection.cpp @@ -22,6 +22,7 @@ #include "util/u_logging.h" #include "wivrn_ipc.h" #include +#include #include using namespace std::chrono_literals;