/
isachkov
/
crypto_server
Обзор
Документация
Войти
/
isachkov
/
crypto_server
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
include/crypto_chat/secure_layer.hpp
84 строки
3 KB
Ivan Sachkov
CryptoServer
15 май 2024, 20:26
15 май 2024, 20:26
9de0f1f
Код
Авторство
О чём код?
#pragma once #include "ssl_provider.hpp" #include <function2/function2.hpp> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/ssl.h> /** SSL channel data flow, in general: +------+ +-----+ |......|--> read(fd) --> BIO_write(rbio) -->|.....|--> SSL_read(ssl) --> IN |......| |.....| |.sock.| |.SSL.| |......| |.....| |......|<-- write(fd) <-- BIO_read(wbio) <--|.....|<-- SSL_write(ssl) <-- OUT +------+ +-----+ | | | | |<-------------------------------->| |<------------------->| | encrypted bytes | | unencrypted bytes | Illustration is borrowed from a project alike yet in C: https://github.com/darrenjs/openssl_examples/blob/master/README.md We support such data pipeline for each of the connections, so all possible locality optimizations are applicable here. Yet, for illustration purposes code is not well optimized, see comments. */ class SecureLayer { public: // Ad-hoc solution for illustration purposes only using Buffer = std::vector<uint8_t>; // Egress using OnEncrypted = fu2::function<void(Buffer)>; // Ingress using OnDecrypted = fu2::function<void(Buffer)>; SecureLayer(SSLInstancePtr); SecureLayer(const SecureLayer&) = delete; SecureLayer(SecureLayer&&) = delete; SecureLayer& operator=(const SecureLayer&) = delete; SecureLayer& operator=(SecureLayer&&) = delete; // Data sent here is decrypted and pops out in OnDecrypted callback void receive(Buffer); // Triggers OnEncrypted void send(Buffer); void on_encrypted(OnEncrypted); void on_decrypted(OnDecrypted); // Boolean parameter is actually bad, so in a practical design // you should stick to an enum, which would allow different session types // with support of different protocol modes [[nodiscard]] bool init(bool is_server = false); private: // You may join these into a single enum/matching list if needed bool is_ssl_io_requested(int code); bool is_ssl_failure(int code); bool check_connection_state(); void print_ssl_state(); void perform_ssl_handshake(); void perform_ssl_exchange(); int receive_decoded(Buffer&); int receive_encoded(Buffer&); OnEncrypted on_encrypted_; OnDecrypted on_decrypted_; // SSL writes, we read BIO* ssl_to_socket_; // We write, SSL reads BIO* socket_to_ssl_; SSLInstancePtr ssl_; };