From f24f554a01bb6426a0bd127f2db67ed6d8acde3b Mon Sep 17 00:00:00 2001 From: Michael Date: Sat, 26 Jan 2019 15:40:58 +0000 Subject: [PATCH] Convert llarp::Crypto into an abstract base class --- llarp/context.cpp | 4 +- llarp/crypto/crypto.hpp | 107 +++++---- llarp/crypto/crypto_libsodium.cpp | 207 ++++++++++-------- llarp/crypto/crypto_libsodium.hpp | 89 ++++++++ llarp/crypto/encrypted_frame.cpp | 22 +- llarp/dht/context.cpp | 2 +- llarp/dht/messages/gotintro.cpp | 2 +- llarp/dht/messages/pubintro.cpp | 8 +- llarp/exit/session.cpp | 6 +- llarp/handlers/exit.cpp | 2 +- llarp/link/utp.cpp | 42 ++-- llarp/messages/link_intro.cpp | 2 +- llarp/messages/relay_commit.cpp | 14 +- llarp/path/path.cpp | 61 +++--- llarp/path/pathbuilder.cpp | 4 +- llarp/path/transit_hop.cpp | 18 +- llarp/router/router.cpp | 36 +-- llarp/router/router.hpp | 7 +- llarp/router_contact.cpp | 2 +- llarp/service/IntroSet.cpp | 3 +- llarp/service/endpoint.cpp | 35 +-- llarp/service/protocol.cpp | 6 +- test/crypto/test_llarp_crypto.cpp | 19 +- test/link/test_llarp_link.cpp | 10 +- .../test_llarp_routing_obtainexitmessage.cpp | 10 +- test/service/test_llarp_service_address.cpp | 3 +- test/service/test_llarp_service_identity.cpp | 9 +- test/test_libabyss.cpp | 5 +- test/test_llarp_encrypted_frame.cpp | 5 +- test/test_llarp_router.cpp | 5 +- test/test_llarp_router_contact.cpp | 6 +- 31 files changed, 441 insertions(+), 310 deletions(-) create mode 100644 llarp/crypto/crypto_libsodium.hpp diff --git a/llarp/context.cpp b/llarp/context.cpp index 4af4d6897..406a4e930 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -97,8 +98,7 @@ namespace llarp int Context::LoadDatabase() { - crypto = std::unique_ptr< llarp::Crypto >( - new llarp::Crypto{llarp::Crypto::sodium{}}); + crypto = std::make_unique< sodium::CryptoLibSodium >(); nodedb = new llarp_nodedb(crypto.get(), router->disk); if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) diff --git a/llarp/crypto/crypto.hpp b/llarp/crypto/crypto.hpp index 0b96f36a0..a4c3b659a 100644 --- a/llarp/crypto/crypto.hpp +++ b/llarp/crypto/crypto.hpp @@ -19,8 +19,6 @@ namespace llarp { - /// label functors - /// PKE(result, publickey, secretkey, nonce) using path_dh_func = std::function< bool( SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; @@ -29,88 +27,83 @@ namespace llarp using transport_dh_func = std::function< bool( SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; - /// SD/SE(buffer, key, nonce) - using sym_cipher_func = std::function< bool( - llarp_buffer_t, const SharedSecret &, const TunnelNonce &) >; - - /// SD/SE(dst, src, key, nonce) - using sym_cipher_alt_func = std::function< bool( - llarp_buffer_t, llarp_buffer_t, const SharedSecret &, const byte_t *) >; - - /// H(result, body) - using hash_func = std::function< bool(byte_t *, llarp_buffer_t) >; - /// SH(result, body) using shorthash_func = std::function< bool(ShortHash &, llarp_buffer_t) >; - /// MDS(result, body, shared_secret) - using hmac_func = - std::function< bool(byte_t *, llarp_buffer_t, const SharedSecret &) >; - - /// S(sig, secretkey, body) - using sign_func = - std::function< bool(Signature &, const SecretKey &, llarp_buffer_t) >; - - /// V(pubkey, body, sig) - using verify_func = - std::function< bool(const PubKey &, llarp_buffer_t, const Signature &) >; - - /// converts seed to secretkey - using seed_to_secret_func = - std::function< bool(llarp::SecretKey &, const llarp::IdentitySecret &) >; - /// library crypto configuration struct Crypto { + virtual ~Crypto() = 0; + /// xchacha symmetric cipher - sym_cipher_func xchacha20; + virtual bool + xchacha20(llarp_buffer_t, const SharedSecret &, const TunnelNonce &) = 0; + /// xchacha symmetric cipher (multibuffer) - sym_cipher_alt_func xchacha20_alt; + virtual bool + xchacha20_alt(llarp_buffer_t, llarp_buffer_t, const SharedSecret &, + const byte_t *) = 0; + /// path dh creator's side - path_dh_func dh_client; + virtual bool + dh_client(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) = 0; /// path dh relay side - path_dh_func dh_server; + virtual bool + dh_server(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) = 0; /// transport dh client side - transport_dh_func transport_dh_client; + virtual bool + transport_dh_client(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) = 0; /// transport dh server side - transport_dh_func transport_dh_server; + virtual bool + transport_dh_server(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) = 0; /// blake2b 512 bit - hash_func hash; + virtual bool + hash(byte_t *, llarp_buffer_t) = 0; /// blake2b 256 bit - shorthash_func shorthash; + virtual bool + shorthash(ShortHash &, llarp_buffer_t) = 0; /// blake2s 256 bit hmac - hmac_func hmac; + virtual bool + hmac(byte_t *, llarp_buffer_t, const SharedSecret &) = 0; /// ed25519 sign - sign_func sign; + virtual bool + sign(Signature &, const SecretKey &, llarp_buffer_t) = 0; /// ed25519 verify - verify_func verify; + virtual bool + verify(const PubKey &, llarp_buffer_t, const Signature &) = 0; /// seed to secretkey - seed_to_secret_func seed_to_secretkey; + virtual bool + seed_to_secretkey(llarp::SecretKey &, const llarp::IdentitySecret &) = 0; /// randomize buffer - std::function< void(llarp_buffer_t) > randomize; + virtual void randomize(llarp_buffer_t) = 0; /// randomizer memory - std::function< void(void *, size_t) > randbytes; + virtual void + randbytes(void *, size_t) = 0; /// generate signing keypair - std::function< void(SecretKey &) > identity_keygen; + virtual void + identity_keygen(SecretKey &) = 0; /// generate encryption keypair - std::function< void(SecretKey &) > encryption_keygen; + virtual void + encryption_keygen(SecretKey &) = 0; /// generate post quantum encrytion key - std::function< void(PQKeyPair &) > pqe_keygen; + virtual void + pqe_keygen(PQKeyPair &) = 0; /// post quantum decrypt (buffer, sharedkey_dst, sec) - std::function< bool(const PQCipherBlock &, SharedSecret &, const byte_t *) > - pqe_decrypt; + virtual bool + pqe_decrypt(const PQCipherBlock &, SharedSecret &, const byte_t *) = 0; /// post quantum encrypt (buffer, sharedkey_dst, pub) - std::function< bool(PQCipherBlock &, SharedSecret &, const PQPubKey &) > - pqe_encrypt; - - // Give a basic type tag for the constructor to pick libsodium - struct sodium - { - }; - - Crypto(Crypto::sodium tag); + virtual bool + pqe_encrypt(PQCipherBlock &, SharedSecret &, const PQPubKey &) = 0; }; + inline Crypto::~Crypto() + { + } + /// return random 64bit unsigned interger uint64_t randint(); diff --git a/llarp/crypto/crypto_libsodium.cpp b/llarp/crypto/crypto_libsodium.cpp index 4b07073f6..6d5ddc683 100644 --- a/llarp/crypto/crypto_libsodium.cpp +++ b/llarp/crypto/crypto_libsodium.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -18,24 +18,6 @@ namespace llarp { namespace sodium { - static bool - xchacha20(llarp_buffer_t buff, const SharedSecret &k, const TunnelNonce &n) - { - return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, - n.data(), k.data()) - == 0; - } - - static bool - xchacha20_alt(llarp_buffer_t out, llarp_buffer_t in, const SharedSecret &k, - const byte_t *n) - { - if(in.sz > out.sz) - return false; - return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) - == 0; - } - static bool dh(llarp::SharedSecret &out, const PubKey &client_pk, const PubKey &server_pk, const uint8_t *themPub, const SecretKey &usSec) @@ -44,7 +26,9 @@ namespace llarp crypto_generichash_state h; if(crypto_scalarmult_curve25519(shared.data(), usSec.data(), themPub)) + { return false; + } crypto_generichash_blake2b_init(&h, nullptr, 0U, shared.size()); crypto_generichash_blake2b_update(&h, client_pk.data(), 32); crypto_generichash_blake2b_update(&h, server_pk.data(), 32); @@ -54,8 +38,8 @@ namespace llarp } static bool - dh_client(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + dh_client_priv(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) { llarp::SharedSecret dh_result; @@ -70,8 +54,8 @@ namespace llarp } static bool - dh_server(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + dh_server_priv(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) { llarp::SharedSecret dh_result; if(dh(dh_result, pk, sk.toPublic(), pk.data(), sk)) @@ -84,113 +68,184 @@ namespace llarp return false; } - static bool - hash(uint8_t *result, llarp_buffer_t buff) + CryptoLibSodium::CryptoLibSodium() + { + if(sodium_init() == -1) + { + throw std::runtime_error("sodium_init() returned -1"); + } + char *avx2 = std::getenv("AVX2_FORCE_DISABLE"); + if(avx2 && std::string(avx2) == "1") + { + ntru_init(1); + } + else + { + ntru_init(0); + } + int seed = 0; + this->randbytes(&seed, sizeof(seed)); + srand(seed); + } + + bool + CryptoLibSodium::xchacha20(llarp_buffer_t buff, const SharedSecret &k, + const TunnelNonce &n) + { + return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, + n.data(), k.data()) + == 0; + } + + bool + CryptoLibSodium::xchacha20_alt(llarp_buffer_t out, llarp_buffer_t in, + const SharedSecret &k, const byte_t *n) + { + if(in.sz > out.sz) + return false; + return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) + == 0; + } + + bool + CryptoLibSodium::dh_client(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) + { + return dh_client_priv(shared, pk, sk, n); + } + /// path dh relay side + bool + CryptoLibSodium::dh_server(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) + { + return dh_server_priv(shared, pk, sk, n); + } + /// transport dh client side + bool + CryptoLibSodium::transport_dh_client(llarp::SharedSecret &shared, + const PubKey &pk, const SecretKey &sk, + const TunnelNonce &n) + { + return dh_client_priv(shared, pk, sk, n); + } + /// transport dh server side + bool + CryptoLibSodium::transport_dh_server(llarp::SharedSecret &shared, + const PubKey &pk, const SecretKey &sk, + const TunnelNonce &n) + { + return dh_server_priv(shared, pk, sk, n); + } + + bool + CryptoLibSodium::hash(uint8_t *result, llarp_buffer_t buff) { return crypto_generichash_blake2b(result, HASHSIZE, buff.base, buff.sz, nullptr, 0) != -1; } - static bool - shorthash(ShortHash &result, llarp_buffer_t buff) + bool + CryptoLibSodium::shorthash(ShortHash &result, llarp_buffer_t buff) { return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, buff.base, buff.sz, nullptr, 0) != -1; } - static bool - hmac(byte_t *result, llarp_buffer_t buff, const SharedSecret &secret) + bool + CryptoLibSodium::hmac(byte_t *result, llarp_buffer_t buff, + const SharedSecret &secret) { return crypto_generichash_blake2b(result, HMACSIZE, buff.base, buff.sz, secret.data(), HMACSECSIZE) != -1; } - static bool - sign(Signature &result, const SecretKey &secret, llarp_buffer_t buff) + bool + CryptoLibSodium::sign(Signature &result, const SecretKey &secret, + llarp_buffer_t buff) { int rc = crypto_sign_detached(result.data(), nullptr, buff.base, buff.sz, secret.data()); return rc != -1; } - static bool - verify(const PubKey &pub, llarp_buffer_t buff, const Signature &sig) + bool + CryptoLibSodium::verify(const PubKey &pub, llarp_buffer_t buff, + const Signature &sig) { int rc = crypto_sign_verify_detached(sig.data(), buff.base, buff.sz, pub.data()); return rc != -1; } - static bool - seed_to_secretkey(llarp::SecretKey &secret, - const llarp::IdentitySecret &seed) + bool + CryptoLibSodium::seed_to_secretkey(llarp::SecretKey &secret, + const llarp::IdentitySecret &seed) { byte_t pk[crypto_sign_ed25519_PUBLICKEYBYTES]; return crypto_sign_ed25519_seed_keypair(pk, secret.data(), seed.data()) != -1; } - static void - randomize(llarp_buffer_t buff) + void + CryptoLibSodium::randomize(llarp_buffer_t buff) { randombytes((unsigned char *)buff.base, buff.sz); } - static inline void - randbytes(void *ptr, size_t sz) + void + CryptoLibSodium::randbytes(void *ptr, size_t sz) { randombytes((unsigned char *)ptr, sz); } - static void - sigkeygen(llarp::SecretKey &keys) + void + CryptoLibSodium::identity_keygen(llarp::SecretKey &keys) { byte_t *d = keys.data(); crypto_sign_keypair(d + 32, d); } - static void - enckeygen(llarp::SecretKey &keys) + void + CryptoLibSodium::encryption_keygen(llarp::SecretKey &keys) { auto d = keys.data(); randombytes(d, 32); crypto_scalarmult_curve25519_base(d + 32, d); } - } // namespace sodium - - const byte_t * - seckey_topublic(const SecretKey &sec) - { - return sec.data() + 32; - } - namespace pq - { bool - encrypt(PQCipherBlock &ciphertext, SharedSecret &sharedkey, - const PQPubKey &pubkey) + CryptoLibSodium::pqe_encrypt(PQCipherBlock &ciphertext, + SharedSecret &sharedkey, + const PQPubKey &pubkey) { return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) != -1; } bool - decrypt(const PQCipherBlock &ciphertext, SharedSecret &sharedkey, - const byte_t *secretkey) + CryptoLibSodium::pqe_decrypt(const PQCipherBlock &ciphertext, + SharedSecret &sharedkey, + const byte_t *secretkey) { return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) != -1; } void - keygen(PQKeyPair &keypair) + CryptoLibSodium::pqe_keygen(PQKeyPair &keypair) { auto d = keypair.data(); crypto_kem_keypair(d + PQ_SECRETKEYSIZE, d); } - } // namespace pq + } // namespace sodium + + const byte_t * + seckey_topublic(const SecretKey &sec) + { + return sec.data() + 32; + } const byte_t * pq_keypair_to_public(const PQKeyPair &k) @@ -204,40 +259,6 @@ namespace llarp return k.data(); } - Crypto::Crypto(Crypto::sodium tag) - { - (void)tag; - if(sodium_init() == -1) - throw std::runtime_error("sodium_init() returned -1"); - char *avx2 = std::getenv("AVX2_FORCE_DISABLE"); - if(avx2 && std::string(avx2) == "1") - ntru_init(1); - else - ntru_init(0); - this->xchacha20 = llarp::sodium::xchacha20; - this->xchacha20_alt = llarp::sodium::xchacha20_alt; - this->dh_client = llarp::sodium::dh_client; - this->dh_server = llarp::sodium::dh_server; - this->transport_dh_client = llarp::sodium::dh_client; - this->transport_dh_server = llarp::sodium::dh_server; - this->hash = llarp::sodium::hash; - this->shorthash = llarp::sodium::shorthash; - this->hmac = llarp::sodium::hmac; - this->sign = llarp::sodium::sign; - this->verify = llarp::sodium::verify; - this->randomize = llarp::sodium::randomize; - this->randbytes = llarp::sodium::randbytes; - this->identity_keygen = llarp::sodium::sigkeygen; - this->encryption_keygen = llarp::sodium::enckeygen; - this->seed_to_secretkey = llarp::sodium::seed_to_secretkey; - this->pqe_encrypt = llarp::pq::encrypt; - this->pqe_decrypt = llarp::pq::decrypt; - this->pqe_keygen = llarp::pq::keygen; - int seed = 0; - this->randbytes(&seed, sizeof(seed)); - srand(seed); - } - uint64_t randint() { diff --git a/llarp/crypto/crypto_libsodium.hpp b/llarp/crypto/crypto_libsodium.hpp new file mode 100644 index 000000000..57e79c737 --- /dev/null +++ b/llarp/crypto/crypto_libsodium.hpp @@ -0,0 +1,89 @@ +#ifndef LLARP_CRYPTO_LIBSODIUM_HPP +#define LLARP_CRYPTO_LIBSODIUM_HPP + +#include + +namespace llarp +{ + namespace sodium + { + struct CryptoLibSodium final : public Crypto + { + CryptoLibSodium(); + + ~CryptoLibSodium() + { + } + + /// xchacha symmetric cipher + bool + xchacha20(llarp_buffer_t, const SharedSecret &, + const TunnelNonce &) override; + + /// xchacha symmetric cipher (multibuffer) + bool + xchacha20_alt(llarp_buffer_t, llarp_buffer_t, const SharedSecret &, + const byte_t *) override; + + /// path dh creator's side + bool + dh_client(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) override; + /// path dh relay side + bool + dh_server(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) override; + /// transport dh client side + bool + transport_dh_client(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) override; + /// transport dh server side + bool + transport_dh_server(SharedSecret &, const PubKey &, const SecretKey &, + const TunnelNonce &) override; + /// blake2b 512 bit + bool + hash(byte_t *, llarp_buffer_t) override; + /// blake2b 256 bit + bool + shorthash(ShortHash &, llarp_buffer_t) override; + /// blake2s 256 bit hmac + bool + hmac(byte_t *, llarp_buffer_t, const SharedSecret &) override; + /// ed25519 sign + bool + sign(Signature &, const SecretKey &, llarp_buffer_t) override; + /// ed25519 verify + bool + verify(const PubKey &, llarp_buffer_t, const Signature &) override; + /// seed to secretkey + bool + seed_to_secretkey(llarp::SecretKey &, + const llarp::IdentitySecret &) override; + /// randomize buffer + void randomize(llarp_buffer_t) override; + /// randomizer memory + void + randbytes(void *, size_t) override; + /// generate signing keypair + void + identity_keygen(SecretKey &) override; + /// generate encryption keypair + void + encryption_keygen(SecretKey &) override; + /// generate post quantum encrytion key + void + pqe_keygen(PQKeyPair &) override; + /// post quantum decrypt (buffer, sharedkey_dst, sec) + bool + pqe_decrypt(const PQCipherBlock &, SharedSecret &, + const byte_t *) override; + /// post quantum encrypt (buffer, sharedkey_dst, pub) + bool + pqe_encrypt(PQCipherBlock &, SharedSecret &, const PQPubKey &) override; + }; + } // namespace sodium + +} // namespace llarp + +#endif diff --git a/llarp/crypto/encrypted_frame.cpp b/llarp/crypto/encrypted_frame.cpp index 666ec7b26..0558c3e27 100644 --- a/llarp/crypto/encrypted_frame.cpp +++ b/llarp/crypto/encrypted_frame.cpp @@ -24,10 +24,6 @@ namespace llarp SharedSecret shared; - auto DH = crypto->dh_client; - auto Encrypt = crypto->xchacha20; - auto MDS = crypto->hmac; - llarp_buffer_t buf; buf.base = body; buf.cur = buf.base; @@ -40,14 +36,14 @@ namespace llarp TunnelNonce nonce(noncePtr); // derive shared key - if(!DH(shared, otherPubkey, ourSecretKey, nonce)) + if(!crypto->dh_client(shared, otherPubkey, ourSecretKey, nonce)) { llarp::LogError("DH failed"); return false; } // encrypt body - if(!Encrypt(buf, shared, nonce)) + if(!crypto->xchacha20(buf, shared, nonce)) { llarp::LogError("encrypt failed"); return false; @@ -58,7 +54,7 @@ namespace llarp buf.cur = buf.base; buf.sz = size() - SHORTHASHSIZE; - if(!MDS(hash, buf, shared)) + if(!crypto->hmac(hash, buf, shared)) { llarp::LogError("Failed to generate message auth"); return false; @@ -82,14 +78,10 @@ namespace llarp TunnelNonce nonce(noncePtr); PubKey otherPubkey(noncePtr + TUNNONCESIZE); - // use dh_server because we are not the creator of this message - auto DH = crypto->dh_server; - auto Decrypt = crypto->xchacha20; - auto MDS = crypto->hmac; - SharedSecret shared; - if(!DH(shared, otherPubkey, ourSecretKey, nonce)) + // use dh_server because we are not the creator of this message + if(!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce)) { llarp::LogError("DH failed"); return false; @@ -101,7 +93,7 @@ namespace llarp buf.sz = size() - SHORTHASHSIZE; ShortHash digest; - if(!MDS(digest.data(), buf, shared)) + if(!crypto->hmac(digest.data(), buf, shared)) { llarp::LogError("Digest failed"); return false; @@ -117,7 +109,7 @@ namespace llarp buf.cur = body; buf.sz = size() - EncryptedFrameOverheadSize; - if(!Decrypt(buf, shared, nonce)) + if(!crypto->xchacha20(buf, shared, nonce)) { llarp::LogError("decrypt failed"); return false; diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index 5b488372d..b30734992 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -826,7 +826,7 @@ namespace llarp llarp::Crypto * Context::Crypto() { - return &router->crypto; + return router->crypto.get(); } llarp_time_t diff --git a/llarp/dht/messages/gotintro.cpp b/llarp/dht/messages/gotintro.cpp index d32653a7f..08073bc54 100644 --- a/llarp/dht/messages/gotintro.cpp +++ b/llarp/dht/messages/gotintro.cpp @@ -25,7 +25,7 @@ namespace llarp std::vector< std::unique_ptr< IMessage > > &replies) const { auto &dht = ctx->impl; - auto crypto = &dht.router->crypto; + auto crypto = dht.router->crypto.get(); for(const auto &introset : I) { diff --git a/llarp/dht/messages/pubintro.cpp b/llarp/dht/messages/pubintro.cpp index d78f184f5..fe452a004 100644 --- a/llarp/dht/messages/pubintro.cpp +++ b/llarp/dht/messages/pubintro.cpp @@ -52,14 +52,18 @@ namespace llarp return false; } auto &dht = ctx->impl; - if(!I.Verify(&dht.router->crypto, now)) + if(!I.Verify(dht.router->crypto.get(), now)) { llarp::LogWarn("invalid introset: ", I); // don't propogate or store replies.emplace_back(new GotIntroMessage({}, txID)); return true; } - if(I.W && !I.W->IsValid(dht.router->crypto.shorthash, now)) + + using namespace std::placeholders; + shorthash_func shorthash = + std::bind(&Crypto::shorthash, dht.router->crypto.get(), _1, _2); + if(I.W && !I.W->IsValid(shorthash, now)) { llarp::LogWarn("proof of work not good enough for IntroSet"); // don't propogate or store diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index 0d4125a77..d99a589c7 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -16,7 +16,7 @@ namespace llarp , m_Counter(0) , m_LastUse(0) { - r->crypto.identity_keygen(m_ExitIdentity); + r->crypto->identity_keygen(m_ExitIdentity); } BaseSession::~BaseSession() @@ -78,7 +78,7 @@ namespace llarp obtain.S = p->NextSeqNo(); obtain.T = llarp::randint(); PopulateRequest(obtain); - if(!obtain.Sign(&router->crypto, m_ExitIdentity)) + if(!obtain.Sign(router->crypto.get(), m_ExitIdentity)) { llarp::LogError("Failed to sign exit request"); return; @@ -107,7 +107,7 @@ namespace llarp { llarp::LogInfo(p->Name(), " closing exit path"); llarp::routing::CloseExitMessage msg; - if(!(msg.Sign(&router->crypto, m_ExitIdentity) + if(!(msg.Sign(router->crypto.get(), m_ExitIdentity) && p->SendExitClose(&msg, router))) llarp::LogWarn(p->Name(), " failed to send exit close message"); } diff --git a/llarp/handlers/exit.cpp b/llarp/handlers/exit.cpp index e3036d90f..902e0ce46 100644 --- a/llarp/handlers/exit.cpp +++ b/llarp/handlers/exit.cpp @@ -246,7 +246,7 @@ namespace llarp Crypto * ExitEndpoint::GetCrypto() { - return &m_Router->crypto; + return m_Router->crypto.get(); } huint32_t diff --git a/llarp/link/utp.cpp b/llarp/link/utp.cpp index 0f82e0d36..6b5bb239d 100644 --- a/llarp/link/utp.cpp +++ b/llarp/link/utp.cpp @@ -28,6 +28,8 @@ namespace llarp { namespace utp { + using namespace std::placeholders; + bool InboundMessage::IsExpired(llarp_time_t now) const { @@ -549,7 +551,7 @@ namespace llarp NewServerFromRouter(llarp::Router* r) { return NewServer( - &r->crypto, r->encryption, std::bind(&llarp::Router::rc, r), + r->crypto.get(), r->encryption, std::bind(&llarp::Router::rc, r), std::bind(&llarp::Router::HandleRecvLinkMessageBuffer, r, std::placeholders::_1, std::placeholders::_2), std::bind(&llarp::Router::OnSessionEstablished, r, @@ -665,8 +667,10 @@ namespace llarp remoteRC = msg->rc; Crypto()->shorthash(txKey, remoteRC.pubkey.as_buffer()); - if(!DoKeyExchange(Crypto()->transport_dh_server, rxKey, msg->N, - remoteRC.enckey, parent->TransportSecretKey())) + if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, Crypto(), _1, + _2, _3, _4), + rxKey, msg->N, remoteRC.enckey, + parent->TransportSecretKey())) return false; byte_t tmp[LinkIntroMessage::MaxSize]; @@ -706,8 +710,10 @@ namespace llarp Close(); return false; } - if(!DoKeyExchange(Crypto()->transport_dh_client, txKey, replymsg.N, - remoteRC.enckey, parent->RouterEncryptionSecret())) + if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, Crypto(), _1, + _2, _3, _4), + txKey, replymsg.N, remoteRC.enckey, + parent->RouterEncryptionSecret())) return false; llarp::LogDebug("Sent reply LIM"); @@ -761,8 +767,10 @@ namespace llarp } remoteRC = msg->rc; gotLIM = true; - if(!DoKeyExchange(Crypto()->transport_dh_server, rxKey, msg->N, - remoteRC.enckey, parent->RouterEncryptionSecret())) + + if(!DoKeyExchange( + std::bind(&Crypto::transport_dh_server, Crypto(), _1, _2, _3, _4), + rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret())) { Close(); return false; @@ -814,9 +822,11 @@ namespace llarp Close(); return; } - if(!DoKeyExchange(Crypto()->transport_dh_client, txKey, msg.N, - remoteTransportPubKey, - parent->RouterEncryptionSecret())) + + if(!DoKeyExchange( + std::bind(&Crypto::transport_dh_client, Crypto(), _1, _2, _3, _4), + txKey, msg.N, remoteTransportPubKey, + parent->RouterEncryptionSecret())) { llarp::LogError("failed to mix keys for outbound session to ", remoteAddr); @@ -988,8 +998,9 @@ namespace llarp // set remote rc remoteRC = msg->rc; // recalcuate rx key - return DoKeyExchange(Crypto()->transport_dh_server, rxKey, msg->N, - remoteRC.enckey, parent->RouterEncryptionSecret()); + return DoKeyExchange( + std::bind(&Crypto::transport_dh_server, Crypto(), _1, _2, _3, _4), + rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret()); } bool @@ -1012,8 +1023,9 @@ namespace llarp if(!SendMessageBuffer(buf)) return false; // regen our tx Key - return DoKeyExchange(Crypto()->transport_dh_client, txKey, lim.N, - remoteRC.enckey, parent->RouterEncryptionSecret()); + return DoKeyExchange( + std::bind(&Crypto::transport_dh_client, Crypto(), _1, _2, _3, _4), + txKey, lim.N, remoteRC.enckey, parent->RouterEncryptionSecret()); } bool @@ -1080,7 +1092,9 @@ namespace llarp // get message if(m_RecvMsgs.find(msgid) == m_RecvMsgs.end()) + { m_RecvMsgs.emplace(msgid, InboundMessage{}); + } auto itr = m_RecvMsgs.find(msgid); // add message activity diff --git a/llarp/messages/link_intro.cpp b/llarp/messages/link_intro.cpp index c314e2b6a..7a1c6ce52 100644 --- a/llarp/messages/link_intro.cpp +++ b/llarp/messages/link_intro.cpp @@ -117,7 +117,7 @@ namespace llarp bool LinkIntroMessage::HandleMessage(llarp::Router* router) const { - if(!Verify(&router->crypto)) + if(!Verify(router->crypto.get())) return false; return session->GotLIM(this); } diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index 4a855225e..df74fd9fc 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -269,19 +269,21 @@ namespace llarp return; } // generate path key as we are in a worker thread - auto DH = self->context->Crypto()->dh_server; - if(!DH(self->hop->pathKey, self->record.commkey, - self->context->EncryptionSecretKey(), self->record.tunnelNonce)) + auto crypto = self->context->Crypto(); + if(!crypto->dh_server(self->hop->pathKey, self->record.commkey, + self->context->EncryptionSecretKey(), + self->record.tunnelNonce)) { llarp::LogError("LRCM DH Failed ", info); delete self; return; } // generate hash of hop key for nonce mutation - self->context->Crypto()->shorthash(self->hop->nonceXOR, - self->hop->pathKey.as_buffer()); + crypto->shorthash(self->hop->nonceXOR, self->hop->pathKey.as_buffer()); + using namespace std::placeholders; if(self->record.work - && self->record.work->IsValid(self->context->Crypto()->shorthash, now)) + && self->record.work->IsValid( + std::bind(&Crypto::shorthash, crypto, _1, _2), now)) { llarp::LogDebug("LRCM extended lifetime by ", self->record.work->extendedLifetime, " seconds for ", diff --git a/llarp/path/path.cpp b/llarp/path/path.cpp index 204e4bab8..6b41569bb 100644 --- a/llarp/path/path.cpp +++ b/llarp/path/path.cpp @@ -43,7 +43,7 @@ namespace llarp llarp::Crypto* PathContext::Crypto() { - return &m_Router->crypto; + return m_Router->crypto.get(); } llarp::Logic* @@ -155,24 +155,26 @@ namespace llarp IHopHandler* PathContext::GetByUpstream(const RouterID& remote, const PathID_t& id) { - auto own = MapGet(m_OurPaths, id, - [](__attribute__((unused)) const PathSet* s) -> bool { - // TODO: is this right? - return true; - }, - [remote, id](PathSet* p) -> IHopHandler* { - return p->GetByUpstream(remote, id); - }); + auto own = MapGet( + m_OurPaths, id, + [](__attribute__((unused)) const PathSet* s) -> bool { + // TODO: is this right? + return true; + }, + [remote, id](PathSet* p) -> IHopHandler* { + return p->GetByUpstream(remote, id); + }); if(own) return own; - return MapGet(m_TransitPaths, id, - [remote](const std::shared_ptr< TransitHop >& hop) -> bool { - return hop->info.upstream == remote; - }, - [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { - return h.get(); - }); + return MapGet( + m_TransitPaths, id, + [remote](const std::shared_ptr< TransitHop >& hop) -> bool { + return hop->info.upstream == remote; + }, + [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { + return h.get(); + }); } bool @@ -189,13 +191,14 @@ namespace llarp IHopHandler* PathContext::GetByDownstream(const RouterID& remote, const PathID_t& id) { - return MapGet(m_TransitPaths, id, - [remote](const std::shared_ptr< TransitHop >& hop) -> bool { - return hop->info.downstream == remote; - }, - [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { - return h.get(); - }); + return MapGet( + m_TransitPaths, id, + [remote](const std::shared_ptr< TransitHop >& hop) -> bool { + return hop->info.downstream == remote; + }, + [](const std::shared_ptr< TransitHop >& h) -> IHopHandler* { + return h.get(); + }); } PathSet* @@ -506,7 +509,7 @@ namespace llarp TunnelNonce n = Y; for(const auto& hop : hops) { - r->crypto.xchacha20(buf, hop.shared, n); + r->crypto->xchacha20(buf, hop.shared, n); n ^= hop.nonceXOR; } RelayUpstreamMessage msg; @@ -546,7 +549,7 @@ namespace llarp for(const auto& hop : hops) { n ^= hop.nonceXOR; - r->crypto.xchacha20(buf, hop.shared, n); + r->crypto->xchacha20(buf, hop.shared, n); } return HandleRoutingMessage(buf, r); } @@ -605,7 +608,7 @@ namespace llarp if(buf.sz < MESSAGE_PAD_SIZE) { // randomize padding - r->crypto.randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz); + r->crypto->randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz); buf.sz = MESSAGE_PAD_SIZE; } buf.cur = buf.base; @@ -716,7 +719,7 @@ namespace llarp /// allows exits to close from their end if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) { - if(msg->Verify(&r->crypto, EndpointPubKey())) + if(msg->Verify(r->crypto.get(), EndpointPubKey())) { llarp::LogInfo(Name(), " had its exit closed"); _role &= ~ePathRoleExit; @@ -775,7 +778,7 @@ namespace llarp { if(m_ExitObtainTX && msg->T == m_ExitObtainTX) { - if(!msg->Verify(&r->crypto, EndpointPubKey())) + if(!msg->Verify(r->crypto.get(), EndpointPubKey())) { llarp::LogError(Name(), "RXM invalid signature"); return false; @@ -794,7 +797,7 @@ namespace llarp { if(m_ExitObtainTX && msg->T == m_ExitObtainTX) { - if(!msg->Verify(&r->crypto, EndpointPubKey())) + if(!msg->Verify(r->crypto.get(), EndpointPubKey())) { llarp::LogError(Name(), " GXM signature failed"); return false; diff --git a/llarp/path/pathbuilder.cpp b/llarp/path/pathbuilder.cpp index f8be5cf27..c6ab6f3b0 100644 --- a/llarp/path/pathbuilder.cpp +++ b/llarp/path/pathbuilder.cpp @@ -167,7 +167,7 @@ namespace llarp , numHops(hops) { p_router->paths.AddPathBuilder(this); - p_router->crypto.encryption_keygen(enckey); + p_router->crypto->encryption_keygen(enckey); _run.store(true); keygens.store(0); } @@ -281,7 +281,7 @@ namespace llarp lastBuild = Now(); // async generate keys AsyncPathKeyExchangeContext< Builder >* ctx = - new AsyncPathKeyExchangeContext< Builder >(&router->crypto); + new AsyncPathKeyExchangeContext< Builder >(router->crypto.get()); ctx->router = router; ctx->pathset = this; auto path = new llarp::path::Path(hops, this, roles); diff --git a/llarp/path/transit_hop.cpp b/llarp/path/transit_hop.cpp index 2a4e05983..22bd7adfa 100644 --- a/llarp/path/transit_hop.cpp +++ b/llarp/path/transit_hop.cpp @@ -75,7 +75,7 @@ namespace llarp { dlt = MESSAGE_PAD_SIZE - dlt; // randomize padding - r->crypto.randbytes(buf.cur, dlt); + r->crypto->randbytes(buf.cur, dlt); buf.sz += dlt; } buf.cur = buf.base; @@ -89,7 +89,7 @@ namespace llarp RelayDownstreamMessage msg; msg.pathid = info.rxID; msg.Y = Y ^ nonceXOR; - r->crypto.xchacha20(buf, pathKey, Y); + r->crypto->xchacha20(buf, pathKey, Y); msg.X = buf; llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", info.upstream, " to ", info.downstream); @@ -100,7 +100,7 @@ namespace llarp TransitHop::HandleUpstream(llarp_buffer_t buf, const TunnelNonce& Y, llarp::Router* r) { - r->crypto.xchacha20(buf, pathKey, Y); + r->crypto->xchacha20(buf, pathKey, Y); if(IsEndpoint(r->pubkey())) { m_LastActivity = r->Now(); @@ -157,13 +157,13 @@ namespace llarp TransitHop::HandleObtainExitMessage( const llarp::routing::ObtainExitMessage* msg, llarp::Router* r) { - if(msg->Verify(&r->crypto) + if(msg->Verify(r->crypto.get()) && r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0)) { llarp::routing::GrantExitMessage grant; grant.S = NextSeqNo(); grant.T = msg->T; - if(!grant.Sign(&r->crypto, r->identity)) + if(!grant.Sign(r->crypto.get(), r->identity)) { llarp::LogError("Failed to sign grant exit message"); return false; @@ -175,7 +175,7 @@ namespace llarp llarp::routing::RejectExitMessage reject; reject.S = NextSeqNo(); reject.T = msg->T; - if(!reject.Sign(&r->crypto, r->identity)) + if(!reject.Sign(r->crypto.get(), r->identity)) { llarp::LogError("Failed to sign reject exit message"); return false; @@ -189,13 +189,13 @@ namespace llarp { llarp::routing::DataDiscardMessage discard(info.rxID, msg->S); auto ep = r->exitContext.FindEndpointForPath(info.rxID); - if(ep && msg->Verify(&r->crypto, ep->PubKey())) + if(ep && msg->Verify(r->crypto.get(), ep->PubKey())) { ep->Close(); // ep is now gone af llarp::routing::CloseExitMessage reply; reply.S = NextSeqNo(); - if(reply.Sign(&r->crypto, r->identity)) + if(reply.Sign(r->crypto.get(), r->identity)) return SendRoutingMessage(&reply, r); } return SendRoutingMessage(&discard, r); @@ -218,7 +218,7 @@ namespace llarp auto ep = r->exitContext.FindEndpointForPath(msg->P); if(ep) { - if(!msg->Verify(&r->crypto, ep->PubKey())) + if(!msg->Verify(r->crypto.get(), ep->PubKey())) return false; if(ep->UpdateLocalPath(info.rxID)) diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index 7ecfa628a..909785cb4 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -205,7 +206,7 @@ namespace llarp , netloop(_netloop) , tp(_tp) , logic(_logic) - , crypto(llarp::Crypto::sodium{}) + , crypto(std::make_unique< sodium::CryptoLibSodium >()) , paths(this) , exitContext(this) , dht(llarp_dht_context_new(this)) @@ -343,7 +344,7 @@ namespace llarp { return; } - if(results[0].Verify(&crypto, Now())) + if(results[0].Verify(crypto.get(), Now())) { nodedb->Insert(results[0]); TryConnectAsync(results[0], 10); @@ -391,7 +392,7 @@ namespace llarp llarp::LogError("failure to decode or verify of remote RC"); return; } - if(remote.Verify(&crypto, Now())) + if(remote.Verify(crypto.get(), Now())) { llarp::LogDebug("verified signature"); // store into filesystem @@ -415,15 +416,16 @@ namespace llarp if(!EnsureEncryptionKey()) return false; if(usingSNSeed) - return llarp_loadServiceNodeIdentityKey(&crypto, ident_keyfile, identity); + return llarp_loadServiceNodeIdentityKey(crypto.get(), ident_keyfile, + identity); else - return llarp_findOrCreateIdentity(&crypto, ident_keyfile, identity); + return llarp_findOrCreateIdentity(crypto.get(), ident_keyfile, identity); } bool Router::EnsureEncryptionKey() { - return llarp_findOrCreateEncryption(&crypto, encryption_keyfile, + return llarp_findOrCreateEncryption(crypto.get(), encryption_keyfile, this->encryption); } @@ -459,7 +461,7 @@ namespace llarp Router::SaveRC() { llarp::LogDebug("verify RC signature"); - if(!_rc.Verify(&crypto, Now())) + if(!_rc.Verify(crypto.get(), Now())) { rc().Dump< MAX_RC_SIZE >(); llarp::LogError("RC is invalid, not saving"); @@ -585,7 +587,7 @@ namespace llarp return; for(const auto &rc : results) { - if(rc.Verify(&crypto, Now())) + if(rc.Verify(crypto.get(), Now())) nodedb->Insert(rc); else return; @@ -672,11 +674,11 @@ namespace llarp llarp::RouterContact nextRC = _rc; if(rotateKeys) { - crypto.encryption_keygen(nextOnionKey); + crypto->encryption_keygen(nextOnionKey); nextRC.enckey = llarp::seckey_topublic(nextOnionKey); } nextRC.last_updated = Now(); - if(!nextRC.Sign(&crypto, identity)) + if(!nextRC.Sign(crypto.get(), identity)) return false; _rc = nextRC; if(rotateKeys) @@ -816,7 +818,7 @@ namespace llarp bool Router::Sign(llarp::Signature &sig, llarp_buffer_t buf) const { - return crypto.sign(sig, identity, buf); + return crypto->sign(sig, identity, buf); } void @@ -966,7 +968,7 @@ namespace llarp job->nodedb = nodedb; job->logic = logic; - // job->crypto = &crypto; // we already have this + // job->crypto = crypto.get(); // we already have this job->cryptoworker = tp; job->diskworker = disk; if(rc.IsPublicRouter()) @@ -1050,7 +1052,7 @@ namespace llarp a); } llarp::LogInfo("Signing rc..."); - if(!_rc.Sign(&crypto, identity)) + if(!_rc.Sign(crypto.get(), identity)) { llarp::LogError("failed to sign rc"); return false; @@ -1103,11 +1105,11 @@ namespace llarp { // we are a client // regenerate keys and resign rc before everything else - crypto.identity_keygen(identity); - crypto.encryption_keygen(encryption); + crypto->identity_keygen(identity); + crypto->encryption_keygen(encryption); _rc.pubkey = llarp::seckey_topublic(identity); _rc.enckey = llarp::seckey_topublic(encryption); - if(!_rc.Sign(&crypto, identity)) + if(!_rc.Sign(crypto.get(), identity)) { llarp::LogError("failed to regenerate keys and sign RC"); return false; @@ -1616,7 +1618,7 @@ namespace llarp self->bootstrapRCList.pop_back(); return; } - if(rc.Verify(&self->crypto, self->Now())) + if(rc.Verify(self->crypto.get(), self->Now())) { llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey)); } diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index 2aaa94229..e2dbfe530 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -26,9 +26,10 @@ #include #include #include -#include -#include +#include #include +#include +#include namespace llarp { @@ -105,7 +106,7 @@ namespace llarp llarp_ev_loop *netloop; llarp_threadpool *tp; llarp::Logic *logic; - llarp::Crypto crypto; + std::unique_ptr< llarp::Crypto > crypto; llarp::path::PathContext paths; llarp::exit::Context exitContext; llarp::SecretKey identity; diff --git a/llarp/router_contact.cpp b/llarp/router_contact.cpp index 3e5ac72bb..475367461 100644 --- a/llarp/router_contact.cpp +++ b/llarp/router_contact.cpp @@ -338,7 +338,7 @@ namespace llarp } f.seekg(0, std::ios::end); auto l = f.tellg(); - if(l > sizeof(tmp)) + if(l > static_cast< std::streamoff >(sizeof(tmp))) return false; f.seekg(0, std::ios::beg); f.read((char *)tmp, l); diff --git a/llarp/service/IntroSet.cpp b/llarp/service/IntroSet.cpp index 571733dae..3581f77b8 100644 --- a/llarp/service/IntroSet.cpp +++ b/llarp/service/IntroSet.cpp @@ -122,7 +122,8 @@ namespace llarp if(!A.Verify(crypto, buf, Z)) return false; // validate PoW - if(W && !W->IsValid(crypto->shorthash, now)) + using namespace std::placeholders; + if(W && !W->IsValid(std::bind(&Crypto::shorthash, crypto, _1, _2), now)) return false; // valid timestamps // add max clock skew diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 6bafeb3a2..883609c5a 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -116,7 +116,7 @@ namespace llarp return; } m_IntroSet.topic = m_Tag; - if(!m_Identity.SignIntroSet(m_IntroSet, &m_Router->crypto, now)) + if(!m_Identity.SignIntroSet(m_IntroSet, m_Router->crypto.get(), now)) { llarp::LogWarn("failed to sign introset for endpoint ", Name()); return; @@ -352,7 +352,7 @@ namespace llarp bool Endpoint::HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg) { - auto crypto = &m_Router->crypto; + auto crypto = m_Router->crypto.get(); std::set< IntroSet > remote; for(const auto& introset : msg->I) { @@ -492,7 +492,7 @@ namespace llarp bool Endpoint::LoadKeyFile() { - auto crypto = &m_Router->crypto; + auto crypto = m_Router->crypto.get(); if(m_Keyfile.size()) { if(!m_Identity.EnsureKeys(m_Keyfile, crypto)) @@ -1233,7 +1233,7 @@ namespace llarp f.C.Zero(); transfer.Y.Randomize(); transfer.P = remoteIntro.pathID; - if(!f.EncryptAndSign(&Router()->crypto, m, K, m_Identity)) + if(!f.EncryptAndSign(Router()->crypto.get(), m, K, m_Identity)) { llarp::LogError("failed to encrypt and sign"); return false; @@ -1260,12 +1260,13 @@ namespace llarp } } // no converstation - return EnsurePathToService(remote, - [](Address, OutboundContext* c) { - if(c) - c->UpdateIntroSet(true); - }, - 5000, false); + return EnsurePathToService( + remote, + [](Address, OutboundContext* c) { + if(c) + c->UpdateIntroSet(true); + }, + 5000, false); } bool @@ -1491,9 +1492,11 @@ namespace llarp // compure post handshake session key // PKE (A, B, N) SharedSecret sharedSecret; - if(!self->m_LocalIdentity.KeyExchange(self->crypto->dh_client, - sharedSecret, self->remote, - self->frame.N)) + using namespace std::placeholders; + path_dh_func dh_client = + std::bind(&Crypto::dh_client, self->crypto, _1, _2, _3, _4); + if(!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret, + self->remote, self->frame.N)) { llarp::LogError("failed to derive x25519 shared key component"); } @@ -1726,7 +1729,7 @@ namespace llarp Endpoint::SendContext::EncryptAndSendTo(llarp_buffer_t payload, ProtocolType t) { - auto crypto = m_Endpoint->Router()->crypto; + auto crypto = m_Endpoint->Router()->crypto.get(); SharedSecret shared; routing::PathTransferMessage msg; ProtocolFrame& f = msg.T; @@ -1762,7 +1765,7 @@ namespace llarp m.PutBuffer(payload); m.tag = f.T; - if(!f.EncryptAndSign(&crypto, m, shared, m_Endpoint->m_Identity)) + if(!f.EncryptAndSign(crypto, m, shared, m_Endpoint->m_Identity)) { llarp::LogError("failed to sign"); return; @@ -1804,7 +1807,7 @@ namespace llarp llarp::Crypto* Endpoint::Crypto() { - return &m_Router->crypto; + return m_Router->crypto.get(); } llarp_threadpool* diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index 86e85c2da..fc564d7f7 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -269,7 +269,11 @@ namespace llarp } // PKE (A, B, N) SharedSecret sharedSecret; - if(!self->m_LocalIdentity.KeyExchange(crypto->dh_server, sharedSecret, + using namespace std::placeholders; + path_dh_func dh_server = + std::bind(&Crypto::dh_server, self->crypto, _1, _2, _3, _4); + + if(!self->m_LocalIdentity.KeyExchange(dh_server, sharedSecret, self->msg->sender, self->frame.N)) { llarp::LogError("x25519 key exchange failed"); diff --git a/test/crypto/test_llarp_crypto.cpp b/test/crypto/test_llarp_crypto.cpp index 6aaf5b3b9..0c3427fd2 100644 --- a/test/crypto/test_llarp_crypto.cpp +++ b/test/crypto/test_llarp_crypto.cpp @@ -1,4 +1,4 @@ -#include +#include #include @@ -6,16 +6,15 @@ namespace llarp { - struct IdentityKeyTest : public ::testing::Test + struct IdentityKeyTest : public ::testing::Test { - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; llarp::IdentitySecret seed; - IdentityKeyTest() : crypto(llarp::Crypto::sodium{}) + IdentityKeyTest() { - } - + llarp::Crypto* Crypto() { @@ -27,15 +26,13 @@ namespace llarp { seed.Randomize(); } - - }; TEST_F(IdentityKeyTest, TestSeedToSecretKey) { SecretKey secret; ASSERT_TRUE(crypto.seed_to_secretkey(secret, seed)); - AlignedBuffer<128> random; + AlignedBuffer< 128 > random; random.Randomize(); Signature sig; ASSERT_TRUE(crypto.sign(sig, secret, random.as_buffer())); @@ -47,10 +44,10 @@ namespace llarp struct PQCryptoTest : public ::testing::Test { - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; PQKeyPair keys; - PQCryptoTest() : crypto(llarp::Crypto::sodium{}) + PQCryptoTest() { } diff --git a/test/link/test_llarp_link.cpp b/test/link/test_llarp_link.cpp index c0cd9e8a7..de3b4c483 100644 --- a/test/link/test_llarp_link.cpp +++ b/test/link/test_llarp_link.cpp @@ -4,6 +4,8 @@ #include #include +#include + #include struct LinkLayerTest : public ::testing::Test @@ -97,7 +99,7 @@ struct LinkLayerTest : public ::testing::Test } }; - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; Context Alice; Context Bob; @@ -109,11 +111,7 @@ struct LinkLayerTest : public ::testing::Test llarp_time_t oldRCLifetime; - LinkLayerTest() - : crypto(llarp::Crypto::sodium{}) - , Alice(crypto) - , Bob(crypto) - , netLoop(nullptr) + LinkLayerTest() : Alice(crypto), Bob(crypto), netLoop(nullptr) { } diff --git a/test/routing/test_llarp_routing_obtainexitmessage.cpp b/test/routing/test_llarp_routing_obtainexitmessage.cpp index dfc8898e3..ff1271d09 100644 --- a/test/routing/test_llarp_routing_obtainexitmessage.cpp +++ b/test/routing/test_llarp_routing_obtainexitmessage.cpp @@ -1,17 +1,19 @@ -#include +#include #include -#include +#include + +#include using ObtainExitMessage = llarp::routing::ObtainExitMessage; class ObtainExitTest : public ::testing::Test { public: - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; llarp::SecretKey alice; - ObtainExitTest() : crypto(llarp::Crypto::sodium{}) + ObtainExitTest() { } diff --git a/test/service/test_llarp_service_address.cpp b/test/service/test_llarp_service_address.cpp index e800f86c7..e8d313830 100644 --- a/test/service/test_llarp_service_address.cpp +++ b/test/service/test_llarp_service_address.cpp @@ -1,6 +1,7 @@ -#include #include +#include + struct ServiceAddressTest : public ::testing::Test { const std::string snode = diff --git a/test/service/test_llarp_service_identity.cpp b/test/service/test_llarp_service_identity.cpp index 6872ceecf..f5392d3ec 100644 --- a/test/service/test_llarp_service_identity.cpp +++ b/test/service/test_llarp_service_identity.cpp @@ -1,18 +1,19 @@ -#include - #include +#include #include #include #include #include #include +#include + struct HiddenServiceTest : public ::testing::Test { - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; llarp::service::Identity ident; - HiddenServiceTest() : crypto(llarp::Crypto::sodium{}) + HiddenServiceTest() { } diff --git a/test/test_libabyss.cpp b/test/test_libabyss.cpp index 5090ffa16..279e8fb6e 100644 --- a/test/test_libabyss.cpp +++ b/test/test_libabyss.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -9,7 +10,7 @@ struct AbyssTestBase : public ::testing::Test { - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; llarp_threadpool* threadpool = nullptr; llarp_ev_loop* loop = nullptr; std::unique_ptr< llarp::Logic > logic; @@ -18,7 +19,7 @@ struct AbyssTestBase : public ::testing::Test const std::string method = "test.method"; bool called = false; - AbyssTestBase() : crypto(llarp::Crypto::sodium{}) + AbyssTestBase() { } diff --git a/test/test_llarp_encrypted_frame.cpp b/test/test_llarp_encrypted_frame.cpp index 478f7fd64..c50de3fa8 100644 --- a/test/test_llarp_encrypted_frame.cpp +++ b/test/test_llarp_encrypted_frame.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -13,10 +14,10 @@ using LRCR = llarp::LR_CommitRecord; class FrameTest : public ::testing::Test { public: - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; SecretKey alice, bob; - FrameTest() : crypto(llarp::Crypto::sodium{}) + FrameTest() { } diff --git a/test/test_llarp_router.cpp b/test/test_llarp_router.cpp index 9edcd0ddc..56fdbbb7d 100644 --- a/test/test_llarp_router.cpp +++ b/test/test_llarp_router.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -13,11 +14,11 @@ using FindOrCreateFunc = std::function< bool(llarp::Crypto *, const fs::path &, struct FindOrCreate : public ::testing::TestWithParam< FindOrCreateFunc > { - FindOrCreate() : crypto(llarp::Crypto::sodium{}) + FindOrCreate() { } - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; }; // Concerns diff --git a/test/test_llarp_router_contact.cpp b/test/test_llarp_router_contact.cpp index 52aca2e66..d4a20a327 100644 --- a/test/test_llarp_router_contact.cpp +++ b/test/test_llarp_router_contact.cpp @@ -1,6 +1,7 @@ #include #include +#include #include static const byte_t DEF_VALUE[] = "unittest"; @@ -10,8 +11,7 @@ struct RCTest : public ::testing::Test using RC_t = llarp::RouterContact; using SecKey_t = llarp::SecretKey; - RCTest() - : crypto(llarp::Crypto::sodium{}), oldval(llarp::NetID::DefaultValue()) + RCTest() : oldval(llarp::NetID::DefaultValue()) { llarp::NetID::DefaultValue() = llarp::NetID(DEF_VALUE); } @@ -21,7 +21,7 @@ struct RCTest : public ::testing::Test llarp::NetID::DefaultValue() = oldval; } - llarp::Crypto crypto; + llarp::sodium::CryptoLibSodium crypto; const llarp::NetID oldval; };