From 491fee206b2d9debcd426e02c951e2fb965d6e4a Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 28 May 2019 20:45:08 +0100 Subject: [PATCH] Port code to use CryptoManager over passing Crypto pointers --- include/llarp.hpp | 2 + llarp/context.cpp | 7 +- llarp/crypto/crypto.hpp | 12 --- llarp/crypto/encrypted_frame.cpp | 10 ++- llarp/crypto/encrypted_frame.hpp | 61 ++------------- llarp/crypto/types.hpp | 12 +++ llarp/dht/context.cpp | 9 --- llarp/dht/context.hpp | 3 - llarp/dht/messages/gotintro.cpp | 5 +- llarp/dht/messages/pubintro.cpp | 7 +- llarp/dht/recursiverouterlookup.cpp | 2 +- llarp/dht/serviceaddresslookup.cpp | 2 +- llarp/dht/taglookup.cpp | 2 +- llarp/exit/close_exit.cpp | 8 +- llarp/exit/grant_exit.cpp | 8 +- llarp/exit/obtain_exit.cpp | 8 +- llarp/exit/reject_exit.cpp | 8 +- llarp/exit/session.cpp | 27 ++++--- llarp/exit/update_exit.cpp | 8 +- llarp/handlers/exit.cpp | 6 -- llarp/handlers/exit.hpp | 3 - llarp/iwp/iwp.cpp | 11 ++- llarp/iwp/iwp.hpp | 5 +- llarp/iwp/linklayer.cpp | 11 +-- llarp/iwp/linklayer.hpp | 13 +--- llarp/link/server.hpp | 3 - llarp/messages/exit.hpp | 38 +++------- llarp/messages/link_intro.cpp | 11 +-- llarp/messages/link_intro.hpp | 2 +- llarp/messages/relay_commit.cpp | 13 ++-- llarp/nodedb.cpp | 5 +- llarp/nodedb.hpp | 6 +- llarp/path/path.cpp | 20 ++--- llarp/path/path.hpp | 4 - llarp/path/pathbuilder.cpp | 25 +++---- llarp/path/transit_hop.cpp | 18 ++--- llarp/pow.cpp | 5 +- llarp/pow.hpp | 3 +- llarp/router/abstractrouter.hpp | 4 - llarp/router/router.cpp | 47 ++++++------ llarp/router/router.hpp | 15 +--- llarp/router_contact.cpp | 12 +-- llarp/router_contact.hpp | 8 +- llarp/service/async_key_exchange.cpp | 13 ++-- llarp/service/async_key_exchange.hpp | 6 +- llarp/service/endpoint.cpp | 29 +++---- llarp/service/endpoint.hpp | 3 - llarp/service/identity.cpp | 16 ++-- llarp/service/identity.hpp | 10 +-- llarp/service/info.cpp | 4 +- llarp/service/info.hpp | 5 +- llarp/service/intro_set.cpp | 7 +- llarp/service/intro_set.hpp | 4 +- llarp/service/outbound_context.cpp | 5 +- llarp/service/protocol.cpp | 45 ++++++----- llarp/service/protocol.hpp | 13 ++-- llarp/service/sendcontext.cpp | 3 +- llarp/utp/linklayer.cpp | 8 +- llarp/utp/linklayer.hpp | 11 +-- llarp/utp/session.cpp | 75 ++++++++----------- llarp/utp/session.hpp | 26 +++++-- llarp/utp/utp.cpp | 8 +- llarp/utp/utp.hpp | 2 +- test/crypto/test_llarp_crypto.cpp | 14 +--- test/dht/mock_context.hpp | 2 - .../test_llarp_dht_serviceaddresslookup.cpp | 7 +- test/dht/test_llarp_dht_taglookup.cpp | 7 +- test/link/test_llarp_link.cpp | 29 ++++--- .../test_llarp_routing_obtainexitmessage.cpp | 16 +--- test/service/test_llarp_service_identity.cpp | 31 ++++---- test/test_llarp_encrypted_frame.cpp | 21 +----- test/test_llarp_router.cpp | 13 ++-- test/test_llarp_router_contact.cpp | 7 +- 73 files changed, 359 insertions(+), 570 deletions(-) diff --git a/include/llarp.hpp b/include/llarp.hpp index 8d4b66462..78f0a9fd7 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -20,6 +20,7 @@ namespace llarp { struct Config; struct Crypto; + struct CryptoManager; class Logic; struct AbstractRouter; struct RouterContact; @@ -55,6 +56,7 @@ namespace llarp std::map< std::string, std::string > metricTags; std::unique_ptr< Crypto > crypto; + std::unique_ptr< CryptoManager > cryptoManager; std::unique_ptr< AbstractRouter > router; std::unique_ptr< llarp_threadpool > worker; std::shared_ptr< Logic > logic; diff --git a/llarp/context.cpp b/llarp/context.cpp index 87a1854b4..2b1dbb5a8 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -203,9 +203,7 @@ __ ___ ____ _ _ ___ _ _ ____ int Context::LoadDatabase() { - crypto = std::make_unique< sodium::CryptoLibSodium >(); - nodedb = - std::make_unique< llarp_nodedb >(crypto.get(), router->diskworker()); + nodedb = std::make_unique< llarp_nodedb >(router->diskworker()); if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) { @@ -270,6 +268,9 @@ __ ___ ____ _ _ ___ _ _ ____ else logic = std::make_shared< Logic >(); + crypto = std::make_unique< sodium::CryptoLibSodium >(); + cryptoManager = std::make_unique< CryptoManager >(crypto.get()); + router = std::make_unique< Router >(worker.get(), mainloop, logic); if(!router->Configure(config.get())) { diff --git a/llarp/crypto/crypto.hpp b/llarp/crypto/crypto.hpp index 7d683f20a..994ee8820 100644 --- a/llarp/crypto/crypto.hpp +++ b/llarp/crypto/crypto.hpp @@ -20,18 +20,6 @@ namespace llarp { - /// PKE(result, publickey, secretkey, nonce) - using path_dh_func = std::function< bool( - SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; - - /// TKE(result, publickey, secretkey, nonce) - using transport_dh_func = std::function< bool( - SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; - - /// SH(result, body) - using shorthash_func = - std::function< bool(ShortHash &, const llarp_buffer_t &) >; - /// library crypto configuration struct Crypto { diff --git a/llarp/crypto/encrypted_frame.cpp b/llarp/crypto/encrypted_frame.cpp index 0558c3e27..6e3852c31 100644 --- a/llarp/crypto/encrypted_frame.cpp +++ b/llarp/crypto/encrypted_frame.cpp @@ -8,8 +8,7 @@ namespace llarp { bool EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey, - const PubKey& otherPubkey, - llarp::Crypto* crypto) + const PubKey& otherPubkey) { // format of frame is // <32 bytes keyed hash of following data> @@ -29,6 +28,8 @@ namespace llarp buf.cur = buf.base; buf.sz = size() - EncryptedFrameOverheadSize; + auto crypto = CryptoManager::instance(); + // set our pubkey memcpy(pubkey, ourSecretKey.toPublic().data(), PUBKEYSIZE); // randomize nonce @@ -63,8 +64,7 @@ namespace llarp } bool - EncryptedFrame::DecryptInPlace(const SecretKey& ourSecretKey, - llarp::Crypto* crypto) + EncryptedFrame::DecryptInPlace(const SecretKey& ourSecretKey) { // format of frame is // <32 bytes keyed hash of following data> @@ -80,6 +80,8 @@ namespace llarp SharedSecret shared; + auto crypto = CryptoManager::instance(); + // use dh_server because we are not the creator of this message if(!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce)) { diff --git a/llarp/crypto/encrypted_frame.hpp b/llarp/crypto/encrypted_frame.hpp index ffd9a36a0..34b32132d 100644 --- a/llarp/crypto/encrypted_frame.hpp +++ b/llarp/crypto/encrypted_frame.hpp @@ -9,8 +9,6 @@ namespace llarp { - struct Crypto; - static constexpr size_t EncryptedFrameOverheadSize = PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE; static constexpr size_t EncryptedFrameBodySize = 128 * 6; @@ -40,57 +38,10 @@ namespace llarp } bool - DecryptInPlace(const SecretKey& seckey, llarp::Crypto* crypto); + DecryptInPlace(const SecretKey& seckey); bool - EncryptInPlace(const SecretKey& seckey, const PubKey& other, - llarp::Crypto* crypto); - }; - - /// TODO: can only handle 1 frame at a time - template < typename User > - struct AsyncFrameEncrypter - { - using EncryptHandler = std::function< void(EncryptedFrame*, User*) >; - - static void - Encrypt(void* user) - { - AsyncFrameEncrypter< User >* ctx = - static_cast< AsyncFrameEncrypter< User >* >(user); - - if(ctx->frame.EncryptInPlace(ctx->seckey, ctx->otherKey, ctx->crypto)) - ctx->handler(&ctx->frame, ctx->user); - else - { - ctx->handler(nullptr, ctx->user); - } - } - - llarp::Crypto* crypto; - byte_t* secretkey; - EncryptHandler handler; - EncryptedFrame frame; - User* user; - byte_t* otherKey; - - AsyncFrameEncrypter(llarp::Crypto* c, byte_t* seckey, EncryptHandler h) - : crypto(c), secretkey(seckey), handler(h) - { - } - - void - AsyncEncrypt(llarp_threadpool* worker, llarp_buffer_t buf, byte_t* other, - User* u) - { - // TODO: should we own otherKey? - otherKey = other; - if(buf.sz > EncryptedFrameBodySize) - return; - memcpy(frame.data() + EncryptedFrameOverheadSize, buf.base, buf.sz); - user = u; - llarp_threadpool_queue_job(worker, {this, &Encrypt}); - } + EncryptInPlace(const SecretKey& seckey, const PubKey& other); }; /// TODO: can only handle 1 frame at a time @@ -106,7 +57,7 @@ namespace llarp AsyncFrameDecrypter< User >* ctx = static_cast< AsyncFrameDecrypter< User >* >(user); - if(ctx->target.DecryptInPlace(ctx->seckey, ctx->crypto)) + if(ctx->target.DecryptInPlace(ctx->seckey)) { auto buf = ctx->target.Buffer(); buf->cur = buf->base + EncryptedFrameOverheadSize; @@ -117,15 +68,13 @@ namespace llarp ctx->user = nullptr; } - AsyncFrameDecrypter(llarp::Crypto* c, const SecretKey& secretkey, - DecryptHandler h) - : result(h), crypto(c), seckey(secretkey) + AsyncFrameDecrypter(const SecretKey& secretkey, DecryptHandler h) + : result(h), seckey(secretkey) { } DecryptHandler result; User_ptr user; - llarp::Crypto* crypto; const SecretKey& seckey; EncryptedFrame target; diff --git a/llarp/crypto/types.hpp b/llarp/crypto/types.hpp index 4ce73af92..aead0d3a4 100644 --- a/llarp/crypto/types.hpp +++ b/llarp/crypto/types.hpp @@ -164,6 +164,18 @@ namespace llarp using PQCipherBlock = AlignedBuffer< PQ_CIPHERTEXTSIZE + 1 >; using PQPubKey = AlignedBuffer< PQ_PUBKEYSIZE >; using PQKeyPair = AlignedBuffer< PQ_KEYPAIRSIZE >; + + /// PKE(result, publickey, secretkey, nonce) + using path_dh_func = std::function< bool( + SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; + + /// TKE(result, publickey, secretkey, nonce) + using transport_dh_func = std::function< bool( + SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; + + /// SH(result, body) + using shorthash_func = + std::function< bool(ShortHash &, const llarp_buffer_t &) >; } // namespace llarp #endif diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index a29ac19be..01dba22a1 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -41,9 +41,6 @@ namespace llarp util::StatusObject ExtractStatus() const override; - llarp::Crypto* - Crypto() const override; - /// on behalf of whoasked request introset for target from dht router with /// key askpeer void @@ -696,12 +693,6 @@ namespace llarp } } - llarp::Crypto* - Context::Crypto() const - { - return router->crypto(); - } - llarp_time_t Context::Now() const { diff --git a/llarp/dht/context.hpp b/llarp/dht/context.hpp index b0789c567..9ecea6ec4 100644 --- a/llarp/dht/context.hpp +++ b/llarp/dht/context.hpp @@ -129,9 +129,6 @@ namespace llarp virtual void ExploreNetworkVia(const Key_t& peer) = 0; - virtual llarp::Crypto* - Crypto() const = 0; - virtual llarp::AbstractRouter* GetRouter() const = 0; diff --git a/llarp/dht/messages/gotintro.cpp b/llarp/dht/messages/gotintro.cpp index 7d1cc23c4..ddd099e1d 100644 --- a/llarp/dht/messages/gotintro.cpp +++ b/llarp/dht/messages/gotintro.cpp @@ -25,12 +25,11 @@ namespace llarp __attribute__((unused)) std::vector< std::unique_ptr< IMessage > > &replies) const { - auto &dht = *ctx->impl; - auto crypto = dht.GetRouter()->crypto(); + auto &dht = *ctx->impl; for(const auto &introset : I) { - if(!introset.Verify(crypto, dht.Now())) + if(!introset.Verify(dht.Now())) { llarp::LogWarn( "Invalid introset while handling direct GotIntro " diff --git a/llarp/dht/messages/pubintro.cpp b/llarp/dht/messages/pubintro.cpp index 5c9d06d08..52bc22a1e 100644 --- a/llarp/dht/messages/pubintro.cpp +++ b/llarp/dht/messages/pubintro.cpp @@ -53,7 +53,7 @@ namespace llarp return false; } auto &dht = *ctx->impl; - if(!I.Verify(dht.Crypto(), now)) + if(!I.Verify(now)) { llarp::LogWarn("invalid introset: ", I); // don't propogate or store @@ -61,10 +61,7 @@ namespace llarp return true; } - using namespace std::placeholders; - shorthash_func shorthash = - std::bind(&Crypto::shorthash, dht.Crypto(), _1, _2); - if(I.W && !I.W->IsValid(shorthash, now)) + if(I.W && !I.W->IsValid(now)) { llarp::LogWarn("proof of work not good enough for IntroSet"); // don't propogate or store diff --git a/llarp/dht/recursiverouterlookup.cpp b/llarp/dht/recursiverouterlookup.cpp index ff6a8775f..40a6a9380 100644 --- a/llarp/dht/recursiverouterlookup.cpp +++ b/llarp/dht/recursiverouterlookup.cpp @@ -22,7 +22,7 @@ namespace llarp bool RecursiveRouterLookup::Validate(const RouterContact &rc) const { - if(!rc.Verify(parent->Crypto(), parent->Now())) + if(!rc.Verify(parent->Now())) { llarp::LogWarn("rc from lookup result is invalid"); return false; diff --git a/llarp/dht/serviceaddresslookup.cpp b/llarp/dht/serviceaddresslookup.cpp index 9eb8b7f30..e83f0d811 100644 --- a/llarp/dht/serviceaddresslookup.cpp +++ b/llarp/dht/serviceaddresslookup.cpp @@ -22,7 +22,7 @@ namespace llarp bool ServiceAddressLookup::Validate(const service::IntroSet &value) const { - if(!value.Verify(parent->Crypto(), parent->Now())) + if(!value.Verify(parent->Now())) { llarp::LogWarn("Got invalid introset from service lookup"); return false; diff --git a/llarp/dht/taglookup.cpp b/llarp/dht/taglookup.cpp index ccca855ea..8fa07416c 100644 --- a/llarp/dht/taglookup.cpp +++ b/llarp/dht/taglookup.cpp @@ -10,7 +10,7 @@ namespace llarp bool TagLookup::Validate(const service::IntroSet &introset) const { - if(!introset.Verify(parent->Crypto(), parent->Now())) + if(!introset.Verify(parent->Now())) { llarp::LogWarn("got invalid introset from tag lookup"); return false; diff --git a/llarp/exit/close_exit.cpp b/llarp/exit/close_exit.cpp index a74a9188d..f3ded97a3 100644 --- a/llarp/exit/close_exit.cpp +++ b/llarp/exit/close_exit.cpp @@ -40,7 +40,7 @@ namespace llarp } bool - CloseExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const + CloseExitMessage::Verify(const llarp::PubKey& pk) const { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -50,11 +50,11 @@ namespace llarp if(!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->verify(pk, buf, Z); + return CryptoManager::instance()->verify(pk, buf, Z); } bool - CloseExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) + CloseExitMessage::Sign(const llarp::SecretKey& sk) { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -63,7 +63,7 @@ namespace llarp if(!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->sign(Z, sk, buf); + return CryptoManager::instance()->sign(Z, sk, buf); } bool diff --git a/llarp/exit/grant_exit.cpp b/llarp/exit/grant_exit.cpp index 9471ea2dc..fbb32c638 100644 --- a/llarp/exit/grant_exit.cpp +++ b/llarp/exit/grant_exit.cpp @@ -45,7 +45,7 @@ namespace llarp } bool - GrantExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const + GrantExitMessage::Verify(const llarp::PubKey& pk) const { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -55,11 +55,11 @@ namespace llarp if(!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->verify(pk, buf, Z); + return CryptoManager::instance()->verify(pk, buf, Z); } bool - GrantExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) + GrantExitMessage::Sign(const llarp::SecretKey& sk) { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -68,7 +68,7 @@ namespace llarp if(!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->sign(Z, sk, buf); + return CryptoManager::instance()->sign(Z, sk, buf); } bool diff --git a/llarp/exit/obtain_exit.cpp b/llarp/exit/obtain_exit.cpp index ac769d3a2..39cd777bd 100644 --- a/llarp/exit/obtain_exit.cpp +++ b/llarp/exit/obtain_exit.cpp @@ -8,7 +8,7 @@ namespace llarp namespace routing { bool - ObtainExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) + ObtainExitMessage::Sign(const llarp::SecretKey& sk) { std::array< byte_t, 1024 > tmp; llarp_buffer_t buf(tmp); @@ -19,11 +19,11 @@ namespace llarp return false; } buf.sz = buf.cur - buf.base; - return c->sign(Z, sk, buf); + return CryptoManager::instance()->sign(Z, sk, buf); } bool - ObtainExitMessage::Verify(llarp::Crypto* c) const + ObtainExitMessage::Verify() const { std::array< byte_t, 1024 > tmp; llarp_buffer_t buf(tmp); @@ -36,7 +36,7 @@ namespace llarp } // rewind buffer buf.sz = buf.cur - buf.base; - return c->verify(I, buf, Z); + return CryptoManager::instance()->verify(I, buf, Z); } bool diff --git a/llarp/exit/reject_exit.cpp b/llarp/exit/reject_exit.cpp index 4f468fb05..388ad7e8b 100644 --- a/llarp/exit/reject_exit.cpp +++ b/llarp/exit/reject_exit.cpp @@ -53,7 +53,7 @@ namespace llarp } bool - RejectExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) + RejectExitMessage::Sign(const llarp::SecretKey& sk) { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -62,11 +62,11 @@ namespace llarp if(!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->sign(Z, sk, buf); + return CryptoManager::instance()->sign(Z, sk, buf); } bool - RejectExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const + RejectExitMessage::Verify(const llarp::PubKey& pk) const { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -76,7 +76,7 @@ namespace llarp if(!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->verify(pk, buf, Z); + return CryptoManager::instance()->verify(pk, buf, Z); } bool diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index 2e0fd9e47..1c21f9729 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -19,7 +20,7 @@ namespace llarp , m_LastUse(0) , m_BundleRC(bundleRC) { - r->crypto()->identity_keygen(m_ExitIdentity); + CryptoManager::instance()->identity_keygen(m_ExitIdentity); } BaseSession::~BaseSession() @@ -109,11 +110,11 @@ namespace llarp p->AddObtainExitHandler(std::bind(&BaseSession::HandleGotExit, this, std::placeholders::_1, std::placeholders::_2)); - llarp::routing::ObtainExitMessage obtain; + routing::ObtainExitMessage obtain; obtain.S = p->NextSeqNo(); obtain.T = llarp::randint(); PopulateRequest(obtain); - if(!obtain.Sign(router->crypto(), m_ExitIdentity)) + if(!obtain.Sign(m_ExitIdentity)) { llarp::LogError("Failed to sign exit request"); return; @@ -168,9 +169,8 @@ namespace llarp if(p->SupportsAnyRoles(roles)) { llarp::LogInfo(p->Name(), " closing exit path"); - llarp::routing::CloseExitMessage msg; - if(msg.Sign(router->crypto(), m_ExitIdentity) - && p->SendExitClose(msg, router)) + routing::CloseExitMessage msg; + if(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, router)) { p->ClearRoles(roles); } @@ -186,19 +186,18 @@ namespace llarp BaseSession::Stop() { CallPendingCallbacks(false); - auto sendExitClose = [&](const llarp::path::Path_ptr p) { - if(p->SupportsAnyRoles(llarp::path::ePathRoleExit)) + auto sendExitClose = [&](const path::Path_ptr p) { + if(p->SupportsAnyRoles(path::ePathRoleExit)) { - llarp::LogInfo(p->Name(), " closing exit path"); - llarp::routing::CloseExitMessage msg; - if(!(msg.Sign(router->crypto(), m_ExitIdentity) - && p->SendExitClose(msg, router))) - llarp::LogWarn(p->Name(), " failed to send exit close message"); + LogInfo(p->Name(), " closing exit path"); + routing::CloseExitMessage msg; + if(!(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, router))) + LogWarn(p->Name(), " failed to send exit close message"); } }; ForEachPath(sendExitClose); router->pathContext().RemovePathSet(shared_from_this()); - return llarp::path::Builder::Stop(); + return path::Builder::Stop(); } bool diff --git a/llarp/exit/update_exit.cpp b/llarp/exit/update_exit.cpp index 0e3ad230a..e29b974cc 100644 --- a/llarp/exit/update_exit.cpp +++ b/llarp/exit/update_exit.cpp @@ -45,7 +45,7 @@ namespace llarp } bool - UpdateExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const + UpdateExitMessage::Verify(const llarp::PubKey& pk) const { std::array< byte_t, 512 > tmp; @@ -56,11 +56,11 @@ namespace llarp if(!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->verify(pk, buf, Z); + return CryptoManager::instance()->verify(pk, buf, Z); } bool - UpdateExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) + UpdateExitMessage::Sign(const llarp::SecretKey& sk) { std::array< byte_t, 512 > tmp; llarp_buffer_t buf(tmp); @@ -68,7 +68,7 @@ namespace llarp if(!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; - return c->sign(Z, sk, buf); + return CryptoManager::instance()->sign(Z, sk, buf); } bool diff --git a/llarp/handlers/exit.cpp b/llarp/handlers/exit.cpp index cf7e78414..318933e27 100644 --- a/llarp/handlers/exit.cpp +++ b/llarp/handlers/exit.cpp @@ -304,12 +304,6 @@ namespace llarp return m_Router; } - Crypto * - ExitEndpoint::GetCrypto() - { - return m_Router->crypto(); - } - huint32_t ExitEndpoint::GetIfAddr() const { diff --git a/llarp/handlers/exit.hpp b/llarp/handlers/exit.hpp index 87abf9e6b..90e320515 100644 --- a/llarp/handlers/exit.hpp +++ b/llarp/handlers/exit.hpp @@ -62,9 +62,6 @@ namespace llarp llarp_time_t Now() const; - Crypto* - GetCrypto(); - template < typename Stats > void CalculateTrafficStats(Stats& stats) diff --git a/llarp/iwp/iwp.cpp b/llarp/iwp/iwp.cpp index 545170ccc..025a665af 100644 --- a/llarp/iwp/iwp.cpp +++ b/llarp/iwp/iwp.cpp @@ -11,7 +11,7 @@ namespace llarp { using namespace std::placeholders; return NewServer( - r->crypto(), r->encryption(), std::bind(&AbstractRouter::rc, r), + r->encryption(), std::bind(&AbstractRouter::rc, r), std::bind(&AbstractRouter::HandleRecvLinkMessageBuffer, r, _1, _2), std::bind(&AbstractRouter::OnSessionEstablished, r, _1), std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2), @@ -21,12 +21,11 @@ namespace llarp } std::unique_ptr< ILinkLayer > - NewServer(Crypto* c, const SecretKey& enckey, GetRCFunc getrc, - LinkMessageHandler h, SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, SignBufferFunc sign, - TimeoutHandler t, SessionClosedHandler closed) + NewServer(const SecretKey& enckey, GetRCFunc getrc, LinkMessageHandler h, + SessionEstablishedHandler est, SessionRenegotiateHandler reneg, + SignBufferFunc sign, TimeoutHandler t, + SessionClosedHandler closed) { - (void)c; (void)enckey; (void)getrc; (void)h; diff --git a/llarp/iwp/iwp.hpp b/llarp/iwp/iwp.hpp index fd161160a..b3c5464ca 100644 --- a/llarp/iwp/iwp.hpp +++ b/llarp/iwp/iwp.hpp @@ -12,9 +12,8 @@ namespace llarp namespace iwp { std::unique_ptr< ILinkLayer > - NewServer(llarp::Crypto* crypto, const SecretKey& routerEncSecret, - llarp::GetRCFunc getrc, llarp::LinkMessageHandler h, - llarp::SessionEstablishedHandler est, + NewServer(const SecretKey& routerEncSecret, llarp::GetRCFunc getrc, + llarp::LinkMessageHandler h, llarp::SessionEstablishedHandler est, llarp::SessionRenegotiateHandler reneg, llarp::SignBufferFunc sign, llarp::TimeoutHandler timeout, llarp::SessionClosedHandler closed); diff --git a/llarp/iwp/linklayer.cpp b/llarp/iwp/linklayer.cpp index 45dbbadd6..d2eacf5d0 100644 --- a/llarp/iwp/linklayer.cpp +++ b/llarp/iwp/linklayer.cpp @@ -4,11 +4,11 @@ namespace llarp { namespace iwp { - LinkLayer::LinkLayer(Crypto* c, const SecretKey& enckey, GetRCFunc getrc, + LinkLayer::LinkLayer(const SecretKey& enckey, GetRCFunc getrc, LinkMessageHandler h, SessionEstablishedHandler est, SessionRenegotiateHandler reneg, SignBufferFunc sign, TimeoutHandler t, SessionClosedHandler closed) - : ILinkLayer(enckey, getrc, h, sign, est, reneg, t, closed), crypto(c) + : ILinkLayer(enckey, getrc, h, sign, est, reneg, t, closed) { m_FlowCookie.Randomize(); } @@ -33,7 +33,7 @@ namespace llarp LinkLayer::KeyGen(SecretKey& k) { k.Zero(); - crypto->encryption_keygen(k); + CryptoManager::instance()->encryption_keygen(k); return !k.IsZero(); } @@ -68,7 +68,8 @@ namespace llarp { case eOCMD_ObtainFlowID: sigbuf.sz -= m_OuterMsg.Zsig.size(); - if(!crypto->verify(m_OuterMsg.pubkey, sigbuf, m_OuterMsg.Zsig)) + if(!CryptoManager::instance()->verify(m_OuterMsg.pubkey, sigbuf, + m_OuterMsg.Zsig)) { LogError("failed to verify signature on '", (char)m_OuterMsg.command, "' message from ", from); @@ -132,7 +133,7 @@ namespace llarp tmp.begin() + 64 + pk.size()); llarp_buffer_t buf(tmp); ShortHash h; - if(!crypto->shorthash(h, buf)) + if(!CryptoManager::instance()->shorthash(h, buf)) return false; std::copy_n(h.begin(), flow.size(), flow.begin()); return true; diff --git a/llarp/iwp/linklayer.hpp b/llarp/iwp/linklayer.hpp index 8e8f129cb..50f9f3557 100644 --- a/llarp/iwp/linklayer.hpp +++ b/llarp/iwp/linklayer.hpp @@ -14,22 +14,13 @@ namespace llarp { struct LinkLayer final : public ILinkLayer { - LinkLayer(Crypto *crypto, const SecretKey &encryptionSecretKey, - GetRCFunc getrc, LinkMessageHandler h, - SessionEstablishedHandler established, + LinkLayer(const SecretKey &encryptionSecretKey, GetRCFunc getrc, + LinkMessageHandler h, SessionEstablishedHandler established, SessionRenegotiateHandler reneg, SignBufferFunc sign, TimeoutHandler timeout, SessionClosedHandler closed); ~LinkLayer(); - Crypto *const crypto; - - Crypto * - OurCrypto() override - { - return crypto; - } - bool Start(std::shared_ptr< Logic > l) override; diff --git a/llarp/link/server.hpp b/llarp/link/server.hpp index 8923ada95..20af6c0ae 100644 --- a/llarp/link/server.hpp +++ b/llarp/link/server.hpp @@ -61,9 +61,6 @@ namespace llarp return llarp_ev_loop_time_now_ms(m_Loop); } - virtual Crypto* - OurCrypto() = 0; - bool HasSessionTo(const RouterID& pk); diff --git a/llarp/messages/exit.hpp b/llarp/messages/exit.hpp index 9e3af6ecb..22c0a032e 100644 --- a/llarp/messages/exit.hpp +++ b/llarp/messages/exit.hpp @@ -9,7 +9,6 @@ namespace llarp { - struct Crypto; namespace routing { struct ObtainExitMessage final : public IMessage @@ -44,10 +43,10 @@ namespace llarp /// populates I and signs bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); + Sign(const llarp::SecretKey& sk); bool - Verify(llarp::Crypto* c) const; + Verify() const; bool BEncode(llarp_buffer_t* buf) const override; @@ -71,10 +70,10 @@ namespace llarp BEncode(llarp_buffer_t* buf) const override; bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); + Sign(const llarp::SecretKey& sk); bool - Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; + Verify(const llarp::PubKey& pk) const; bool DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override; @@ -111,10 +110,10 @@ namespace llarp } bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); + Sign(const llarp::SecretKey& sk); bool - Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; + Verify(const llarp::PubKey& pk) const; bool BEncode(llarp_buffer_t* buf) const override; @@ -133,13 +132,7 @@ namespace llarp Nonce_t Y; llarp::Signature Z; - UpdateExitVerifyMessage() : IMessage() - { - } - - ~UpdateExitVerifyMessage() - { - } + ~UpdateExitVerifyMessage() = default; void Clear() override @@ -149,15 +142,6 @@ namespace llarp Z.Zero(); } - UpdateExitVerifyMessage& - operator=(const UpdateExitVerifyMessage& other); - - bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); - - bool - Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; - bool BEncode(llarp_buffer_t* buf) const override; @@ -177,10 +161,10 @@ namespace llarp llarp::Signature Z; bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); + Sign(const llarp::SecretKey& sk); bool - Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; + Verify(const llarp::PubKey& pk) const; bool BEncode(llarp_buffer_t* buf) const override; @@ -218,10 +202,10 @@ namespace llarp HandleMessage(IMessageHandler* h, AbstractRouter* r) const override; bool - Sign(llarp::Crypto* c, const llarp::SecretKey& sk); + Sign(const llarp::SecretKey& sk); bool - Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; + Verify(const llarp::PubKey& pk) const; void Clear() override diff --git a/llarp/messages/link_intro.cpp b/llarp/messages/link_intro.cpp index 5834b56fa..dbf091120 100644 --- a/llarp/messages/link_intro.cpp +++ b/llarp/messages/link_intro.cpp @@ -101,9 +101,10 @@ namespace llarp } bool - LinkIntroMessage::HandleMessage(AbstractRouter* router) const + LinkIntroMessage::HandleMessage( + ABSL_ATTRIBUTE_UNUSED AbstractRouter* router) const { - if(!Verify(router->crypto())) + if(!Verify()) return false; return session->GotLIM(this); } @@ -132,7 +133,7 @@ namespace llarp } bool - LinkIntroMessage::Verify(llarp::Crypto* c) const + LinkIntroMessage::Verify() const { LinkIntroMessage copy; copy = *this; @@ -144,13 +145,13 @@ namespace llarp buf.sz = buf.cur - buf.base; buf.cur = buf.base; // outer signature - if(!c->verify(rc.pubkey, buf, Z)) + if(!CryptoManager::instance()->verify(rc.pubkey, buf, Z)) { llarp::LogError("outer signature failure"); return false; } // verify RC - if(!rc.Verify(c, llarp::time_now_ms())) + if(!rc.Verify(llarp::time_now_ms())) { llarp::LogError("invalid RC in link intro"); return false; diff --git a/llarp/messages/link_intro.hpp b/llarp/messages/link_intro.hpp index 0b2cc5523..0e37b6669 100644 --- a/llarp/messages/link_intro.hpp +++ b/llarp/messages/link_intro.hpp @@ -35,7 +35,7 @@ namespace llarp Sign(std::function< bool(Signature&, const llarp_buffer_t&) > signer); bool - Verify(llarp::Crypto* c) const; + Verify() const; void Clear() override; diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index 82c14271e..da4a60610 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -235,7 +236,7 @@ namespace llarp // ... and it's valid const auto now = self->context->Router()->Now(); if(self->record.nextRC->IsPublicRouter() - && self->record.nextRC->Verify(self->context->crypto(), now)) + && self->record.nextRC->Verify(now)) { llarp_nodedb* n = self->context->Router()->nodedb(); const RouterContact rc = *self->record.nextRC; @@ -309,7 +310,7 @@ namespace llarp return; } // generate path key as we are in a worker thread - auto crypto = self->context->crypto(); + auto crypto = CryptoManager::instance(); if(!crypto->dh_server(self->hop->pathKey, self->record.commkey, self->context->EncryptionSecretKey(), self->record.tunnelNonce)) @@ -321,10 +322,7 @@ namespace llarp // generate hash of hop key for nonce mutation crypto->shorthash(self->hop->nonceXOR, llarp_buffer_t(self->hop->pathKey)); - using namespace std::placeholders; - if(self->record.work - && self->record.work->IsValid( - std::bind(&Crypto::shorthash, crypto, _1, _2), now)) + if(self->record.work && self->record.work->IsValid(now)) { llarp::LogDebug("LRCM extended lifetime by ", self->record.work->extendedLifetime, " seconds for ", @@ -382,8 +380,7 @@ namespace llarp LR_CommitMessage::AsyncDecrypt(llarp::path::PathContext* context) const { auto decrypter = std::make_unique< LRCMFrameDecrypt::Decrypter >( - context->crypto(), context->EncryptionSecretKey(), - &LRCMFrameDecrypt::HandleDecrypted); + context->EncryptionSecretKey(), &LRCMFrameDecrypt::HandleDecrypted); // copy frames so we own them auto frameDecrypt = std::make_shared< LRCMFrameDecrypt >( context, std::move(decrypter), this); diff --git a/llarp/nodedb.cpp b/llarp/nodedb.cpp index ea0bdf8ae..75336a86c 100644 --- a/llarp/nodedb.cpp +++ b/llarp/nodedb.cpp @@ -209,7 +209,7 @@ llarp_nodedb::loadfile(const fs::path &fpath) llarp::LogError("failed to read file ", fpath); return false; } - if(!rc.Verify(crypto, llarp::time_now_ms())) + if(!rc.Verify(llarp::time_now_ms())) { llarp::LogError(fpath, " contains invalid RC"); return false; @@ -295,8 +295,7 @@ crypto_threadworker_verifyrc(void *user) llarp_async_verify_rc *verify_request = static_cast< llarp_async_verify_rc * >(user); llarp::RouterContact rc = verify_request->rc; - verify_request->valid = - rc.Verify(verify_request->nodedb->crypto, llarp::time_now_ms()); + verify_request->valid = rc.Verify(llarp::time_now_ms()); // if it's valid we need to set it if(verify_request->valid && rc.IsPublicRouter()) { diff --git a/llarp/nodedb.hpp b/llarp/nodedb.hpp index da22a1b43..72d5aaf02 100644 --- a/llarp/nodedb.hpp +++ b/llarp/nodedb.hpp @@ -26,7 +26,6 @@ struct llarp_threadpool; namespace llarp { - struct Crypto; class Logic; namespace thread @@ -45,8 +44,8 @@ struct llarp_nodedb_iter struct llarp_nodedb { - llarp_nodedb(llarp::Crypto *c, llarp::thread::ThreadPool *diskworker) - : crypto(c), disk(diskworker) + explicit llarp_nodedb(llarp::thread::ThreadPool *diskworker) + : disk(diskworker) { } @@ -55,7 +54,6 @@ struct llarp_nodedb Clear(); } - llarp::Crypto *crypto; llarp::thread::ThreadPool *disk; mutable llarp::util::Mutex access; // protects entries std::unordered_map< llarp::RouterID, llarp::RouterContact, diff --git a/llarp/path/path.cpp b/llarp/path/path.cpp index 7c9291acd..38bc82b45 100644 --- a/llarp/path/path.cpp +++ b/llarp/path/path.cpp @@ -57,12 +57,6 @@ namespace llarp return m_Router->threadpool(); } - Crypto* - PathContext::crypto() - { - return m_Router->crypto(); - } - std::shared_ptr< Logic > PathContext::logic() { @@ -597,7 +591,7 @@ namespace llarp TunnelNonce n = Y; for(const auto& hop : hops) { - r->crypto()->xchacha20(buf, hop.shared, n); + CryptoManager::instance()->xchacha20(buf, hop.shared, n); n ^= hop.nonceXOR; } RelayUpstreamMessage msg; @@ -639,7 +633,7 @@ namespace llarp for(const auto& hop : hops) { n ^= hop.nonceXOR; - r->crypto()->xchacha20(buf, hop.shared, n); + CryptoManager::instance()->xchacha20(buf, hop.shared, n); } if(!HandleRoutingMessage(buf, r)) return false; @@ -699,7 +693,7 @@ namespace llarp if(buf.sz < pad_size) { // randomize padding - r->crypto()->randbytes(buf.cur, pad_size - buf.sz); + CryptoManager::instance()->randbytes(buf.cur, pad_size - buf.sz); buf.sz = pad_size; } buf.cur = buf.base; @@ -799,12 +793,12 @@ namespace llarp bool Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, - AbstractRouter* r) + ABSL_ATTRIBUTE_UNUSED AbstractRouter* r) { /// allows exits to close from their end if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) { - if(msg.Verify(r->crypto(), EndpointPubKey())) + if(msg.Verify(EndpointPubKey())) { LogInfo(Name(), " had its exit closed"); _role &= ~ePathRoleExit; @@ -862,7 +856,7 @@ namespace llarp { if(m_ExitObtainTX && msg.T == m_ExitObtainTX) { - if(!msg.Verify(r->crypto(), EndpointPubKey())) + if(!msg.Verify(EndpointPubKey())) { LogError(Name(), "RXM invalid signature"); return false; @@ -881,7 +875,7 @@ namespace llarp { if(m_ExitObtainTX && msg.T == m_ExitObtainTX) { - if(!msg.Verify(r->crypto(), EndpointPubKey())) + if(!msg.Verify(EndpointPubKey())) { LogError(Name(), " GXM signature failed"); return false; diff --git a/llarp/path/path.hpp b/llarp/path/path.hpp index ad1684936..9005089f8 100644 --- a/llarp/path/path.hpp +++ b/llarp/path/path.hpp @@ -27,7 +27,6 @@ namespace llarp { class Logic; struct AbstractRouter; - struct Crypto; struct LR_CommitMessage; struct LR_CommitRecord; @@ -705,9 +704,6 @@ namespace llarp llarp_threadpool* Worker(); - llarp::Crypto* - crypto(); - std::shared_ptr< Logic > logic(); diff --git a/llarp/path/pathbuilder.cpp b/llarp/path/pathbuilder.cpp index 7f16dd60c..faa31266c 100644 --- a/llarp/path/pathbuilder.cpp +++ b/llarp/path/pathbuilder.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -27,7 +28,6 @@ namespace llarp AbstractRouter* router = nullptr; llarp_threadpool* worker = nullptr; std::shared_ptr< Logic > logic = nullptr; - Crypto* crypto = nullptr; LR_CommitMessage LRCM; ~AsyncPathKeyExchangeContext() @@ -53,12 +53,13 @@ namespace llarp auto& hop = ctx->path->hops[ctx->idx]; auto& frame = ctx->LRCM.frames[ctx->idx]; + auto crypto = CryptoManager::instance(); + // generate key - ctx->crypto->encryption_keygen(hop.commkey); + crypto->encryption_keygen(hop.commkey); hop.nonce.Randomize(); // do key exchange - if(!ctx->crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, - hop.nonce)) + if(!crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, hop.nonce)) { LogError(ctx->pathset->Name(), " Failed to generate shared key for path build"); @@ -66,7 +67,7 @@ namespace llarp return; } // generate nonceXOR valueself->hop->pathKey - ctx->crypto->shorthash(hop.nonceXOR, llarp_buffer_t(hop.shared)); + crypto->shorthash(hop.nonceXOR, llarp_buffer_t(hop.shared)); ++ctx->idx; bool isFarthestHop = ctx->idx == ctx->path->hops.size(); @@ -104,8 +105,8 @@ namespace llarp } // use ephemeral keypair for frame SecretKey framekey; - ctx->crypto->encryption_keygen(framekey); - if(!frame.EncryptInPlace(framekey, hop.rc.enckey, ctx->crypto)) + crypto->encryption_keygen(framekey); + if(!frame.EncryptInPlace(framekey, hop.rc.enckey)) { LogError(ctx->pathset->Name(), " Failed to encrypt LRCR"); delete ctx; @@ -125,10 +126,6 @@ namespace llarp } } - AsyncPathKeyExchangeContext(Crypto* c) : crypto(c) - { - } - /// Generate all keys asynchronously and call handler when done void AsyncGenerateKeys(Path_t p, std::shared_ptr< Logic > l, @@ -173,7 +170,7 @@ namespace llarp size_t pathNum, size_t hops) : path::PathSet(pathNum), router(p_router), dht(p_dht), numHops(hops) { - p_router->crypto()->encryption_keygen(enckey); + CryptoManager::instance()->encryption_keygen(enckey); _run.store(true); } @@ -319,7 +316,7 @@ namespace llarp const auto aligned = router->pathContext().FindOwnedPathsWithEndpoint(remote); /// pick the lowest latency path that aligns to remote - /// note: peer exuastion is made worse happen here + /// note: peer exhaustion is made worse happen here Path_ptr p; llarp_time_t min = std::numeric_limits< llarp_time_t >::max(); for(const auto& path : aligned) @@ -409,7 +406,7 @@ namespace llarp lastBuild = Now(); // async generate keys AsyncPathKeyExchangeContext< Builder >* ctx = - new AsyncPathKeyExchangeContext< Builder >(router->crypto()); + new AsyncPathKeyExchangeContext< Builder >(); ctx->router = router; ctx->pathset = GetSelf(); auto path = std::make_shared< path::Path >(hops, this, roles); diff --git a/llarp/path/transit_hop.cpp b/llarp/path/transit_hop.cpp index 4c97be371..b638c9fbd 100644 --- a/llarp/path/transit_hop.cpp +++ b/llarp/path/transit_hop.cpp @@ -64,7 +64,7 @@ namespace llarp { dlt = pad_size - dlt; // randomize padding - r->crypto()->randbytes(buf.cur, dlt); + CryptoManager::instance()->randbytes(buf.cur, dlt); buf.sz += dlt; } buf.cur = buf.base; @@ -78,7 +78,7 @@ namespace llarp RelayDownstreamMessage msg; msg.pathid = info.rxID; msg.Y = Y ^ nonceXOR; - r->crypto()->xchacha20(buf, pathKey, Y); + CryptoManager::instance()->xchacha20(buf, pathKey, Y); msg.X = buf; llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", info.upstream, " to ", info.downstream); @@ -89,7 +89,7 @@ namespace llarp TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y, AbstractRouter* r) { - r->crypto()->xchacha20(buf, pathKey, Y); + CryptoManager::instance()->xchacha20(buf, pathKey, Y); if(IsEndpoint(r->pubkey())) { m_LastActivity = r->Now(); @@ -146,13 +146,13 @@ namespace llarp TransitHop::HandleObtainExitMessage( const llarp::routing::ObtainExitMessage& msg, AbstractRouter* r) { - if(msg.Verify(r->crypto()) + if(msg.Verify() && 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->identity())) { llarp::LogError("Failed to sign grant exit message"); return false; @@ -164,7 +164,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->identity())) { llarp::LogError("Failed to sign reject exit message"); return false; @@ -178,12 +178,12 @@ namespace llarp { const 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(ep->PubKey())) { llarp::routing::CloseExitMessage reply; reply.Y = msg.Y; reply.S = NextSeqNo(); - if(reply.Sign(r->crypto(), r->identity())) + if(reply.Sign(r->identity())) { if(SendRoutingMessage(reply, r)) { @@ -213,7 +213,7 @@ namespace llarp auto ep = r->exitContext().FindEndpointForPath(msg.P); if(ep) { - if(!msg.Verify(r->crypto(), ep->PubKey())) + if(!msg.Verify(ep->PubKey())) return false; if(ep->UpdateLocalPath(info.rxID)) diff --git a/llarp/pow.cpp b/llarp/pow.cpp index d5754749e..d8f20cd35 100644 --- a/llarp/pow.cpp +++ b/llarp/pow.cpp @@ -1,5 +1,6 @@ #include +#include #include #include @@ -28,7 +29,7 @@ namespace llarp } bool - PoW::IsValid(shorthash_func hashfunc, llarp_time_t now) const + PoW::IsValid(llarp_time_t now) const { if(now - timestamp > (uint64_t(extendedLifetime) * 1000)) return false; @@ -43,7 +44,7 @@ namespace llarp buf.sz = buf.cur - buf.base; buf.cur = buf.base; // hash - if(!hashfunc(digest, buf)) + if(!CryptoManager::instance()->shorthash(digest, buf)) return false; // check bytes required uint32_t required = std::floor(std::log(extendedLifetime)); diff --git a/llarp/pow.hpp b/llarp/pow.hpp index 4af5d397f..d9cfd0aee 100644 --- a/llarp/pow.hpp +++ b/llarp/pow.hpp @@ -1,7 +1,6 @@ #ifndef LLARP_POW_HPP #define LLARP_POW_HPP -#include #include #include @@ -19,7 +18,7 @@ namespace llarp ~PoW(); bool - IsValid(shorthash_func hashfunc, llarp_time_t now) const; + IsValid(llarp_time_t now) const; bool DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* val); diff --git a/llarp/router/abstractrouter.hpp b/llarp/router/abstractrouter.hpp index 6de36e78f..ea9a2e22d 100644 --- a/llarp/router/abstractrouter.hpp +++ b/llarp/router/abstractrouter.hpp @@ -17,7 +17,6 @@ namespace llarp { class Logic; struct Config; - struct Crypto; struct RouterID; struct ILinkMessage; struct ILinkSession; @@ -68,9 +67,6 @@ namespace llarp virtual llarp_dht_context * dht() const = 0; - virtual Crypto * - crypto() const = 0; - virtual llarp_nodedb * nodedb() const = 0; diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index 89e19e778..c7bd3aa1f 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -123,7 +123,7 @@ on_try_connecting(std::shared_ptr< TryConnectJob > j) } bool -llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath, +llarp_loadServiceNodeIdentityKey(const fs::path &fpath, llarp::SecretKey &secret) { std::string path = fpath.string(); @@ -132,12 +132,11 @@ llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath, if(!ident.LoadFromFile(path.c_str())) return false; - return crypto->seed_to_secretkey(secret, ident); + return llarp::CryptoManager::instance()->seed_to_secretkey(secret, ident); } bool -llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, - llarp::SecretKey &secretkey) +llarp_findOrCreateIdentity(const fs::path &path, llarp::SecretKey &secretkey) { std::string fpath = path.string(); llarp::LogDebug("find or create ", fpath); @@ -145,7 +144,7 @@ llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, if(!fs::exists(path, ec)) { llarp::LogInfo("generating new identity key"); - crypto->identity_keygen(secretkey); + llarp::CryptoManager::instance()->identity_keygen(secretkey); if(!secretkey.SaveToFile(fpath.c_str())) return false; } @@ -154,8 +153,7 @@ llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, // C++ ... bool -llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path, - llarp::SecretKey &encryption) +llarp_findOrCreateEncryption(const fs::path &path, llarp::SecretKey &encryption) { std::string fpath = path.string(); llarp::LogDebug("find or create ", fpath); @@ -163,7 +161,7 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path, if(!fs::exists(path, ec)) { llarp::LogInfo("generating new encryption key"); - crypto->encryption_keygen(encryption); + llarp::CryptoManager::instance()->encryption_keygen(encryption); if(!encryption.SaveToFile(fpath.c_str())) return false; } @@ -220,7 +218,6 @@ namespace llarp , _netloop(__netloop) , tp(_tp) , _logic(l) - , _crypto(std::make_unique< sodium::CryptoLibSodium >()) , paths(this) , _exitContext(this) , disk(1, 1000) @@ -384,7 +381,7 @@ namespace llarp { return; } - if(results[0].Verify(crypto(), Now())) + if(results[0].Verify(Now())) { TryConnectAsync(results[0], 10); return; @@ -431,7 +428,7 @@ namespace llarp LogError("failure to decode or verify of remote RC"); return; } - if(remote.Verify(crypto(), Now())) + if(remote.Verify(Now())) { LogDebug("verified signature"); if(!TryConnectAsync(remote, 10)) @@ -450,17 +447,15 @@ namespace llarp if(!EnsureEncryptionKey()) return false; if(usingSNSeed) - return llarp_loadServiceNodeIdentityKey(crypto(), ident_keyfile, - _identity); + return llarp_loadServiceNodeIdentityKey(ident_keyfile, _identity); else - return llarp_findOrCreateIdentity(crypto(), ident_keyfile, _identity); + return llarp_findOrCreateIdentity(ident_keyfile, _identity); } bool Router::EnsureEncryptionKey() { - return llarp_findOrCreateEncryption(crypto(), encryption_keyfile, - _encryption); + return llarp_findOrCreateEncryption(encryption_keyfile, _encryption); } void @@ -504,7 +499,7 @@ namespace llarp Router::SaveRC() { LogDebug("verify RC signature"); - if(!_rc.Verify(crypto(), Now())) + if(!_rc.Verify(Now())) { Dump< MAX_RC_SIZE >(rc()); LogError("RC is invalid, not saving"); @@ -632,7 +627,7 @@ namespace llarp const auto numConnected = NumberOfConnectedRouters(); for(const auto &rc : results) { - if(!rc.Verify(crypto(), Now())) + if(!rc.Verify(Now())) continue; nodedb()->InsertAsync(rc); @@ -760,7 +755,7 @@ namespace llarp RouterContact nextRC = _rc; if(rotateKeys) { - crypto()->encryption_keygen(nextOnionKey); + CryptoManager::instance()->encryption_keygen(nextOnionKey); std::string f = encryption_keyfile.string(); // TODO: use disk worker if(nextOnionKey.SaveToFile(f.c_str())) @@ -770,7 +765,7 @@ namespace llarp } } nextRC.last_updated = Now(); - if(!nextRC.Sign(crypto(), identity())) + if(!nextRC.Sign(identity())) return false; _rc = nextRC; // propagate RC by renegotiating sessions @@ -1025,7 +1020,7 @@ namespace llarp ; return; } - if(rc.Verify(crypto(), Now())) + if(rc.Verify(Now())) { const auto result = bootstrapRCList.insert(rc); if(result.second) @@ -1339,7 +1334,7 @@ namespace llarp Router::Sign(Signature &sig, const llarp_buffer_t &buf) const { METRICS_TIME_BLOCK("Router", "Sign"); - return crypto()->sign(sig, identity(), buf); + return CryptoManager::instance()->sign(sig, identity(), buf); } void @@ -1620,7 +1615,7 @@ namespace llarp _rc.enckey = seckey_topublic(encryption()); LogInfo("Signing rc..."); - if(!_rc.Sign(crypto(), identity())) + if(!_rc.Sign(identity())) { LogError("failed to sign rc"); return false; @@ -1678,11 +1673,11 @@ namespace llarp maxConnectedRouters = minConnectedRouters + 1; // we are a client // regenerate keys and resign rc before everything else - crypto()->identity_keygen(_identity); - crypto()->encryption_keygen(_encryption); + CryptoManager::instance()->identity_keygen(_identity); + CryptoManager::instance()->encryption_keygen(_encryption); _rc.pubkey = seckey_topublic(identity()); _rc.enckey = seckey_topublic(encryption()); - if(!_rc.Sign(crypto(), identity())) + if(!_rc.Sign(identity())) { LogError("failed to regenerate keys and sign RC"); return false; diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index 60df1b479..5b1513c19 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -37,19 +37,17 @@ namespace llarp { struct Config; - struct Crypto; } // namespace llarp bool -llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &fpath, +llarp_findOrCreateEncryption(const fs::path &fpath, llarp::SecretKey &encryption); bool -llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, - llarp::SecretKey &secretkey); +llarp_findOrCreateIdentity(const fs::path &path, llarp::SecretKey &secretkey); bool -llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath, +llarp_loadServiceNodeIdentityKey(const fs::path &fpath, llarp::SecretKey &secretkey); struct TryConnectJob; @@ -101,12 +99,6 @@ namespace llarp util::StatusObject ExtractStatus() const override; - Crypto * - crypto() const override - { - return _crypto.get(); - } - llarp_nodedb * nodedb() const override { @@ -184,7 +176,6 @@ namespace llarp llarp_ev_loop_ptr _netloop; llarp_threadpool *tp; std::shared_ptr< Logic > _logic; - std::unique_ptr< Crypto > _crypto; path::PathContext paths; exit::Context _exitContext; SecretKey _identity; diff --git a/llarp/router_contact.cpp b/llarp/router_contact.cpp index af01ddc35..9f63d9df9 100644 --- a/llarp/router_contact.cpp +++ b/llarp/router_contact.cpp @@ -263,7 +263,7 @@ namespace llarp } bool - RouterContact::Sign(llarp::Crypto *crypto, const SecretKey &secretkey) + RouterContact::Sign(const SecretKey &secretkey) { pubkey = llarp::seckey_topublic(secretkey); std::array< byte_t, MAX_RC_SIZE > tmp; @@ -274,11 +274,11 @@ namespace llarp return false; buf.sz = buf.cur - buf.base; buf.cur = buf.base; - return crypto->sign(signature, secretkey, buf); + return CryptoManager::instance()->sign(signature, secretkey, buf); } bool - RouterContact::Verify(llarp::Crypto *crypto, llarp_time_t now) const + RouterContact::Verify(llarp_time_t now) const { if(netID != NetID::DefaultValue()) { @@ -307,7 +307,7 @@ namespace llarp return false; } } - if(!VerifySignature(crypto)) + if(!VerifySignature()) { llarp::LogError("invalid signature"); return false; @@ -316,7 +316,7 @@ namespace llarp } bool - RouterContact::VerifySignature(llarp::Crypto *crypto) const + RouterContact::VerifySignature() const { RouterContact copy; copy = *this; @@ -330,7 +330,7 @@ namespace llarp } buf.sz = buf.cur - buf.base; buf.cur = buf.base; - return crypto->verify(pubkey, buf, signature); + return CryptoManager::instance()->verify(pubkey, buf, signature); } bool diff --git a/llarp/router_contact.hpp b/llarp/router_contact.hpp index 2376c099f..a73c4af5a 100644 --- a/llarp/router_contact.hpp +++ b/llarp/router_contact.hpp @@ -17,8 +17,6 @@ namespace llarp { - struct Crypto; - /// NetID struct NetID final : public AlignedBuffer< 8 > { @@ -166,10 +164,10 @@ namespace llarp SetNick(const std::string &nick); bool - Verify(llarp::Crypto *crypto, llarp_time_t now) const; + Verify(llarp_time_t now) const; bool - Sign(llarp::Crypto *crypto, const llarp::SecretKey &secret); + Sign(const llarp::SecretKey &secret); /// does this RC expire soon? default delta is 1 minute bool @@ -195,7 +193,7 @@ namespace llarp private: bool - VerifySignature(llarp::Crypto *crypto) const; + VerifySignature() const; }; inline std::ostream & diff --git a/llarp/service/async_key_exchange.cpp b/llarp/service/async_key_exchange.cpp index e3201780a..7a3140ec9 100644 --- a/llarp/service/async_key_exchange.cpp +++ b/llarp/service/async_key_exchange.cpp @@ -8,14 +8,13 @@ namespace llarp { namespace service { - AsyncKeyExchange::AsyncKeyExchange(std::shared_ptr< Logic > l, Crypto* c, + AsyncKeyExchange::AsyncKeyExchange(std::shared_ptr< Logic > l, const ServiceInfo& r, const Identity& localident, const PQPubKey& introsetPubKey, const Introduction& remote, IDataHandler* h, const ConvoTag& t) : logic(l) - , crypto(c) , remote(r) , m_LocalIdentity(localident) , introPubKey(introsetPubKey) @@ -44,7 +43,8 @@ namespace llarp AsyncKeyExchange* self = static_cast< AsyncKeyExchange* >(user); // derive ntru session key component SharedSecret K; - self->crypto->pqe_encrypt(self->frame.C, K, self->introPubKey); + auto crypto = CryptoManager::instance(); + crypto->pqe_encrypt(self->frame.C, K, self->introPubKey); // randomize Nonce self->frame.N.Randomize(); // compure post handshake session key @@ -52,7 +52,7 @@ namespace llarp SharedSecret sharedSecret; using namespace std::placeholders; path_dh_func dh_client = - std::bind(&Crypto::dh_client, self->crypto, _1, _2, _3, _4); + std::bind(&Crypto::dh_client, crypto, _1, _2, _3, _4); if(!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret, self->remote, self->frame.N)) { @@ -63,7 +63,7 @@ namespace llarp std::copy(K.begin(), K.end(), tmp.begin()); // H (K + PKE(A, B, N)) std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32); - self->crypto->shorthash(self->sharedKey, llarp_buffer_t(tmp)); + crypto->shorthash(self->sharedKey, llarp_buffer_t(tmp)); // set tag self->msg.tag = self->tag; // set sender @@ -73,8 +73,7 @@ namespace llarp // set protocol self->msg.proto = eProtocolTraffic; // encrypt and sign - if(self->frame.EncryptAndSign(self->crypto, self->msg, K, - self->m_LocalIdentity)) + if(self->frame.EncryptAndSign(self->msg, K, self->m_LocalIdentity)) self->logic->queue_job({self, &Result}); else { diff --git a/llarp/service/async_key_exchange.hpp b/llarp/service/async_key_exchange.hpp index e7c1d893d..88138fa23 100644 --- a/llarp/service/async_key_exchange.hpp +++ b/llarp/service/async_key_exchange.hpp @@ -8,14 +8,12 @@ namespace llarp { class Logic; - struct Crypto; namespace service { struct AsyncKeyExchange { std::shared_ptr< Logic > logic; - Crypto* crypto; SharedSecret sharedKey; ServiceInfo remote; const Identity& m_LocalIdentity; @@ -28,8 +26,8 @@ namespace llarp IDataHandler* handler; ConvoTag tag; - AsyncKeyExchange(std::shared_ptr< Logic > l, Crypto* c, - const ServiceInfo& r, const Identity& localident, + AsyncKeyExchange(std::shared_ptr< Logic > l, const ServiceInfo& r, + const Identity& localident, const PQPubKey& introsetPubKey, const Introduction& remote, IDataHandler* h, const ConvoTag& t); diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 3cb615e0f..e6a5a961b 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -159,7 +159,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, now)) { LogWarn("failed to sign introset for endpoint ", Name()); return; @@ -347,11 +347,10 @@ namespace llarp bool Endpoint::HandleGotIntroMessage(dht::GotIntroMessage_constptr msg) { - auto crypto = m_Router->crypto(); std::set< IntroSet > remote; for(const auto& introset : msg->I) { - if(!introset.Verify(crypto, Now())) + if(!introset.Verify(Now())) { if(m_Identity.pub == introset.A && m_CurrentPublishTX == msg->T) IntroSetPublishFail(); @@ -482,10 +481,9 @@ namespace llarp bool Endpoint::LoadKeyFile() { - auto crypto = m_Router->crypto(); if(!m_Keyfile.empty()) { - if(!m_Identity.EnsureKeys(m_Keyfile, crypto)) + if(!m_Identity.EnsureKeys(m_Keyfile)) { LogError("Can't ensure keyfile [", m_Keyfile, "]"); return false; @@ -493,7 +491,7 @@ namespace llarp } else { - m_Identity.RegenerateKeys(crypto); + m_Identity.RegenerateKeys(); } return true; } @@ -884,16 +882,15 @@ namespace llarp if(!GetSenderFor(frame.T, si)) return false; // verify source - if(!frame.Verify(crypto(), si)) + if(!frame.Verify(si)) return false; // remove convotag it doesn't exist LogWarn("remove convotag T=", frame.T); RemoveConvoTag(frame.T); return true; } - if(!frame.AsyncDecryptAndVerify(EndpointLogic(), crypto(), p, - CryptoWorker(), m_Identity, - m_DataHandler)) + if(!frame.AsyncDecryptAndVerify(EndpointLogic(), p, CryptoWorker(), + m_Identity, m_DataHandler)) { // send discard ProtocolFrame f; @@ -901,7 +898,7 @@ namespace llarp f.T = frame.T; f.F = p->intro.pathID; - if(!f.Sign(crypto(), m_Identity)) + if(!f.Sign(m_Identity)) return false; { util::Lock lock(&m_SendQueueMutex); @@ -1047,7 +1044,7 @@ namespace llarp // send downstream packets to user for snode for(const auto& item : m_SNodeSessions) item.second->FlushDownstream(); - // send downstrream traffic to user for hidden service + // send downstream traffic to user for hidden service util::Lock lock(&m_InboundTrafficQueueMutex); while(m_InboundTrafficQueue.size()) { @@ -1128,7 +1125,7 @@ namespace llarp f.F = m.introReply.pathID; f.S = GetSeqNoForConvo(f.T); transfer->P = remoteIntro.pathID; - if(!f.EncryptAndSign(Router()->crypto(), m, K, m_Identity)) + if(!f.EncryptAndSign(m, K, m_Identity)) { LogError("failed to encrypt and sign"); return false; @@ -1225,12 +1222,6 @@ namespace llarp return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic(); } - Crypto* - Endpoint::crypto() - { - return m_Router->crypto(); - } - llarp_threadpool* Endpoint::CryptoWorker() { diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index 7b15f947a..6a127a095 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -105,9 +105,6 @@ namespace llarp llarp_ev_loop_ptr EndpointNetLoop(); - Crypto* - crypto(); - /// crypto worker threadpool llarp_threadpool* CryptoWorker(); diff --git a/llarp/service/identity.cpp b/llarp/service/identity.cpp index 3ecaf7c3a..e157f9b13 100644 --- a/llarp/service/identity.cpp +++ b/llarp/service/identity.cpp @@ -1,5 +1,6 @@ #include +#include #include namespace llarp @@ -53,8 +54,9 @@ namespace llarp } void - Identity::RegenerateKeys(Crypto* crypto) + Identity::RegenerateKeys() { + auto crypto = CryptoManager::instance(); crypto->encryption_keygen(enckey); crypto->identity_keygen(signkey); pub.Update(seckey_topublic(enckey), seckey_topublic(signkey)); @@ -70,13 +72,13 @@ namespace llarp } bool - Identity::Sign(Crypto* c, Signature& sig, const llarp_buffer_t& buf) const + Identity::Sign(Signature& sig, const llarp_buffer_t& buf) const { - return c->sign(sig, signkey, buf); + return CryptoManager::instance()->sign(sig, signkey, buf); } bool - Identity::EnsureKeys(const std::string& fname, Crypto* c) + Identity::EnsureKeys(const std::string& fname) { std::array< byte_t, 4096 > tmp; llarp_buffer_t buf(tmp); @@ -90,7 +92,7 @@ namespace llarp return false; } // regen and encode - RegenerateKeys(c); + RegenerateKeys(); if(!BEncode(&buf)) return false; // rewind @@ -132,7 +134,7 @@ namespace llarp } bool - Identity::SignIntroSet(IntroSet& i, Crypto* crypto, llarp_time_t now) const + Identity::SignIntroSet(IntroSet& i, llarp_time_t now) const { if(i.I.size() == 0) return false; @@ -152,7 +154,7 @@ namespace llarp // rewind and resize buffer buf.sz = buf.cur - buf.base; buf.cur = buf.base; - return Sign(crypto, i.Z, buf); + return Sign(i.Z, buf); } } // namespace service } // namespace llarp diff --git a/llarp/service/identity.hpp b/llarp/service/identity.hpp index 2cbd315f0..1b94ec34b 100644 --- a/llarp/service/identity.hpp +++ b/llarp/service/identity.hpp @@ -12,8 +12,6 @@ namespace llarp { - struct Crypto; - namespace service { // private keys @@ -30,13 +28,13 @@ namespace llarp // regenerate secret keys void - RegenerateKeys(Crypto* c); + RegenerateKeys(); bool BEncode(llarp_buffer_t* buf) const; bool - EnsureKeys(const std::string& fpath, Crypto* c); + EnsureKeys(const std::string& fpath); bool KeyExchange(path_dh_func dh, SharedSecret& sharedkey, @@ -46,10 +44,10 @@ namespace llarp DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); bool - SignIntroSet(IntroSet& i, Crypto* c, llarp_time_t now) const; + SignIntroSet(IntroSet& i, llarp_time_t now) const; bool - Sign(Crypto*, Signature& sig, const llarp_buffer_t& buf) const; + Sign(Signature& sig, const llarp_buffer_t& buf) const; }; inline bool diff --git a/llarp/service/info.cpp b/llarp/service/info.cpp index 4a74dd126..427d2baa7 100644 --- a/llarp/service/info.cpp +++ b/llarp/service/info.cpp @@ -13,10 +13,10 @@ namespace llarp namespace service { bool - ServiceInfo::Verify(Crypto* crypto, const llarp_buffer_t& payload, + ServiceInfo::Verify(const llarp_buffer_t& payload, const Signature& sig) const { - return crypto->verify(signkey, payload, sig); + return CryptoManager::instance()->verify(signkey, payload, sig); } bool diff --git a/llarp/service/info.hpp b/llarp/service/info.hpp index de92f8e89..2effc74fa 100644 --- a/llarp/service/info.hpp +++ b/llarp/service/info.hpp @@ -10,8 +10,6 @@ namespace llarp { - struct Crypto; - namespace service { struct ServiceInfo @@ -34,8 +32,7 @@ namespace llarp } bool - Verify(Crypto* crypto, const llarp_buffer_t& payload, - const Signature& sig) const; + Verify(const llarp_buffer_t& payload, const Signature& sig) const; const PubKey& EncryptionPublicKey() const diff --git a/llarp/service/intro_set.cpp b/llarp/service/intro_set.cpp index 3d41c3fac..bf19d75fe 100644 --- a/llarp/service/intro_set.cpp +++ b/llarp/service/intro_set.cpp @@ -114,7 +114,7 @@ namespace llarp } bool - IntroSet::Verify(Crypto* crypto, llarp_time_t now) const + IntroSet::Verify(llarp_time_t now) const { std::array< byte_t, MAX_INTROSET_SIZE > tmp; llarp_buffer_t buf(tmp); @@ -128,13 +128,12 @@ namespace llarp // rewind and resize buffer buf.sz = buf.cur - buf.base; buf.cur = buf.base; - if(!A.Verify(crypto, buf, Z)) + if(!A.Verify(buf, Z)) { return false; } // validate PoW - using namespace std::placeholders; - if(W && !W->IsValid(std::bind(&Crypto::shorthash, crypto, _1, _2), now)) + if(W && !W->IsValid(now)) { return false; } diff --git a/llarp/service/intro_set.hpp b/llarp/service/intro_set.hpp index 18f59da8c..fb5141314 100644 --- a/llarp/service/intro_set.hpp +++ b/llarp/service/intro_set.hpp @@ -18,8 +18,6 @@ namespace llarp { - struct Crypto; - namespace service { constexpr std::size_t MAX_INTROSET_SIZE = 4096; @@ -70,7 +68,7 @@ namespace llarp DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); bool - Verify(Crypto* crypto, llarp_time_t now) const; + Verify(llarp_time_t now) const; util::StatusObject ExtractStatus() const; diff --git a/llarp/service/outbound_context.cpp b/llarp/service/outbound_context.cpp index ada02d128..a154fc7f3 100644 --- a/llarp/service/outbound_context.cpp +++ b/llarp/service/outbound_context.cpp @@ -161,9 +161,8 @@ namespace llarp } currentConvoTag.Randomize(); AsyncKeyExchange* ex = new AsyncKeyExchange( - m_Endpoint->RouterLogic(), m_Endpoint->crypto(), remoteIdent, - m_Endpoint->GetIdentity(), currentIntroSet.K, remoteIntro, - m_DataHandler, currentConvoTag); + m_Endpoint->RouterLogic(), remoteIdent, m_Endpoint->GetIdentity(), + currentIntroSet.K, remoteIntro, m_DataHandler, currentConvoTag); ex->hook = std::bind(&OutboundContext::Send, this, std::placeholders::_1, path); diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index b33e1fa13..d4d9599b7 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -172,18 +172,17 @@ namespace llarp } bool - ProtocolFrame::DecryptPayloadInto(Crypto* crypto, - const SharedSecret& sharedkey, + ProtocolFrame::DecryptPayloadInto(const SharedSecret& sharedkey, ProtocolMessage& msg) const { Encrypted_t tmp = D; auto buf = tmp.Buffer(); - crypto->xchacha20(*buf, sharedkey, N); + CryptoManager::instance()->xchacha20(*buf, sharedkey, N); return bencode_decode_dict(msg, buf); } bool - ProtocolFrame::Sign(Crypto* crypto, const Identity& localIdent) + ProtocolFrame::Sign(const Identity& localIdent) { Z.Zero(); std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp; @@ -198,11 +197,11 @@ namespace llarp buf.sz = buf.cur - buf.base; buf.cur = buf.base; // sign - return localIdent.Sign(crypto, Z, buf); + return localIdent.Sign(Z, buf); } bool - ProtocolFrame::EncryptAndSign(Crypto* crypto, const ProtocolMessage& msg, + ProtocolFrame::EncryptAndSign(const ProtocolMessage& msg, const SharedSecret& sessionKey, const Identity& localIdent) { @@ -218,7 +217,7 @@ namespace llarp buf.sz = buf.cur - buf.base; buf.cur = buf.base; // encrypt - crypto->xchacha20(buf, sessionKey, N); + CryptoManager::instance()->xchacha20(buf, sessionKey, N); // put encrypted buffer D = buf; // zero out signature @@ -235,7 +234,7 @@ namespace llarp buf2.sz = buf2.cur - buf2.base; buf2.cur = buf2.base; // sign - if(!localIdent.Sign(crypto, Z, buf2)) + if(!localIdent.Sign(Z, buf2)) { LogError("failed to sign? wtf?!"); return false; @@ -245,7 +244,6 @@ namespace llarp struct AsyncFrameDecrypt { - Crypto* crypto; std::shared_ptr< Logic > logic; std::shared_ptr< ProtocolMessage > msg; const Identity& m_LocalIdentity; @@ -253,12 +251,11 @@ namespace llarp const ProtocolFrame frame; const Introduction fromIntro; - AsyncFrameDecrypt(std::shared_ptr< Logic > l, Crypto* c, - const Identity& localIdent, IDataHandler* h, + AsyncFrameDecrypt(std::shared_ptr< Logic > l, const Identity& localIdent, + IDataHandler* h, const std::shared_ptr< ProtocolMessage >& m, const ProtocolFrame& f, const Introduction& recvIntro) - : crypto(c) - , logic(l) + : logic(l) , msg(m) , m_LocalIdentity(localIdent) , handler(h) @@ -271,7 +268,7 @@ namespace llarp Work(void* user) { AsyncFrameDecrypt* self = static_cast< AsyncFrameDecrypt* >(user); - auto crypto = self->crypto; + auto crypto = CryptoManager::instance(); SharedSecret K; SharedSecret sharedKey; // copy @@ -296,7 +293,7 @@ namespace llarp return; } // verify signature of outer message after we parsed the inner message - if(!self->frame.Verify(crypto, self->msg->sender)) + if(!self->frame.Verify(self->msg->sender)) { LogError("intro frame has invalid signature Z=", self->frame.Z, " from ", self->msg->sender.Addr()); @@ -319,8 +316,8 @@ namespace llarp // PKE (A, B, N) SharedSecret sharedSecret; using namespace std::placeholders; - path_dh_func dh_server = - std::bind(&Crypto::dh_server, self->crypto, _1, _2, _3, _4); + path_dh_func dh_server = std::bind( + &Crypto::dh_server, CryptoManager::instance(), _1, _2, _3, _4); if(!self->m_LocalIdentity.KeyExchange(dh_server, sharedSecret, self->msg->sender, self->frame.N)) @@ -367,7 +364,7 @@ namespace llarp bool ProtocolFrame::AsyncDecryptAndVerify(std::shared_ptr< Logic > logic, - Crypto* c, path::Path_ptr recvPath, + path::Path_ptr recvPath, llarp_threadpool* worker, const Identity& localIdent, IDataHandler* handler) const @@ -378,8 +375,8 @@ namespace llarp LogInfo("Got protocol frame with new convo"); msg->srcPath = recvPath->RXID(); // we need to dh - auto dh = new AsyncFrameDecrypt(logic, c, localIdent, handler, msg, - *this, recvPath->intro); + auto dh = new AsyncFrameDecrypt(logic, localIdent, handler, msg, *this, + recvPath->intro); llarp_threadpool_queue_job(worker, {dh, &AsyncFrameDecrypt::Work}); return true; } @@ -395,12 +392,12 @@ namespace llarp LogError("No sender for T=", T); return false; } - if(!Verify(c, si)) + if(!Verify(si)) { LogError("Signature failure from ", si.Addr()); return false; } - if(!DecryptPayloadInto(c, shared, *msg)) + if(!DecryptPayloadInto(shared, *msg)) { LogError("failed to decrypt message"); return false; @@ -419,7 +416,7 @@ namespace llarp } bool - ProtocolFrame::Verify(Crypto* crypto, const ServiceInfo& from) const + ProtocolFrame::Verify(const ServiceInfo& from) const { ProtocolFrame copy(*this); // save signature @@ -438,7 +435,7 @@ namespace llarp buf.sz = buf.cur - buf.base; buf.cur = buf.base; // verify - return from.Verify(crypto, buf, Z); + return from.Verify(buf, Z); } bool diff --git a/llarp/service/protocol.hpp b/llarp/service/protocol.hpp index 780176d8c..a150fd741 100644 --- a/llarp/service/protocol.hpp +++ b/llarp/service/protocol.hpp @@ -19,7 +19,6 @@ struct llarp_threadpool; namespace llarp { - struct Crypto; class Logic; namespace path @@ -120,20 +119,20 @@ namespace llarp operator=(const ProtocolFrame& other); bool - EncryptAndSign(Crypto* c, const ProtocolMessage& msg, - const SharedSecret& sharedkey, const Identity& localIdent); + EncryptAndSign(const ProtocolMessage& msg, const SharedSecret& sharedkey, + const Identity& localIdent); bool - Sign(Crypto* c, const Identity& localIdent); + Sign(const Identity& localIdent); bool - AsyncDecryptAndVerify(std::shared_ptr< Logic > logic, Crypto* c, + AsyncDecryptAndVerify(std::shared_ptr< Logic > logic, path::Path_ptr fromPath, llarp_threadpool* worker, const Identity& localIdent, IDataHandler* handler) const; bool - DecryptPayloadInto(Crypto* c, const SharedSecret& sharedkey, + DecryptPayloadInto(const SharedSecret& sharedkey, ProtocolMessage& into) const; bool @@ -161,7 +160,7 @@ namespace llarp } bool - Verify(Crypto* c, const ServiceInfo& from) const; + Verify(const ServiceInfo& from) const; bool HandleMessage(routing::IMessageHandler* h, diff --git a/llarp/service/sendcontext.cpp b/llarp/service/sendcontext.cpp index 04a97a880..67697cd3b 100644 --- a/llarp/service/sendcontext.cpp +++ b/llarp/service/sendcontext.cpp @@ -55,7 +55,6 @@ namespace llarp void SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t) { - auto crypto = m_Endpoint->Router()->crypto(); SharedSecret shared; ProtocolFrame f; f.N.Randomize(); @@ -94,7 +93,7 @@ namespace llarp m.sender = m_Endpoint->GetIdentity().pub; m.tag = f.T; m.PutBuffer(payload); - if(!f.EncryptAndSign(crypto, m, shared, m_Endpoint->GetIdentity())) + if(!f.EncryptAndSign(m, shared, m_Endpoint->GetIdentity())) { LogError("failed to sign"); return; diff --git a/llarp/utp/linklayer.cpp b/llarp/utp/linklayer.cpp index 267b3c5eb..009650bbd 100644 --- a/llarp/utp/linklayer.cpp +++ b/llarp/utp/linklayer.cpp @@ -140,16 +140,14 @@ namespace llarp return 0; } - LinkLayer::LinkLayer(Crypto* crypto, const SecretKey& routerEncSecret, - GetRCFunc getrc, LinkMessageHandler h, - SignBufferFunc sign, + LinkLayer::LinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc, + LinkMessageHandler h, SignBufferFunc sign, SessionEstablishedHandler established, SessionRenegotiateHandler reneg, TimeoutHandler timeout, SessionClosedHandler closed) : ILinkLayer(routerEncSecret, getrc, h, sign, established, reneg, timeout, closed) { - _crypto = crypto; _utp_ctx = utp_init(2); utp_context_set_userdata(_utp_ctx, this); utp_set_callback(_utp_ctx, UTP_SENDTO, &LinkLayer::SendTo); @@ -304,7 +302,7 @@ namespace llarp bool LinkLayer::KeyGen(SecretKey& k) { - OurCrypto()->encryption_keygen(k); + CryptoManager::instance()->encryption_keygen(k); return true; } diff --git a/llarp/utp/linklayer.hpp b/llarp/utp/linklayer.hpp index 809fae00c..a22b04dbe 100644 --- a/llarp/utp/linklayer.hpp +++ b/llarp/utp/linklayer.hpp @@ -17,7 +17,6 @@ namespace llarp struct LinkLayer final : public ILinkLayer { utp_context* _utp_ctx = nullptr; - Crypto* _crypto = nullptr; // low level read callback static uint64 @@ -47,8 +46,8 @@ namespace llarp OnLog(utp_callback_arguments* arg); /// construct - LinkLayer(Crypto* crypto, const SecretKey& routerEncSecret, - GetRCFunc getrc, LinkMessageHandler h, SignBufferFunc sign, + LinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc, + LinkMessageHandler h, SignBufferFunc sign, SessionEstablishedHandler established, SessionRenegotiateHandler reneg, TimeoutHandler timeout, SessionClosedHandler closed); @@ -70,12 +69,6 @@ namespace llarp ProcessICMP(); #endif - Crypto* - OurCrypto() override - { - return _crypto; - } - /// pump sessions void Pump() override; diff --git a/llarp/utp/session.cpp b/llarp/utp/session.cpp index c9939e9dc..442ff24ba 100644 --- a/llarp/utp/session.cpp +++ b/llarp/utp/session.cpp @@ -19,12 +19,6 @@ namespace llarp LogDebug("link established with ", remoteAddr); } - Crypto* - Session::OurCrypto() - { - return parent->OurCrypto(); - } - /// pump tx queue void Session::PumpWrite() @@ -91,10 +85,11 @@ namespace llarp OutboundHandshake(); } + template < bool (Crypto::*dh_func)(SharedSecret&, const PubKey&, + const SecretKey&, const TunnelNonce&) > bool - Session::DoKeyExchange(transport_dh_func dh, SharedSecret& K, - const KeyExchangeNonce& n, const PubKey& other, - const SecretKey& secret) + Session::DoKeyExchange(SharedSecret& K, const KeyExchangeNonce& n, + const PubKey& other, const SecretKey& secret) { ShortHash t_h; static constexpr size_t TMP_SIZE = 64; @@ -105,14 +100,14 @@ namespace llarp std::copy(K.begin(), K.end(), tmp.begin()); std::copy(n.begin(), n.end(), tmp.begin() + K.size()); // t_h = HS(K + L.n) - if(!OurCrypto()->shorthash(t_h, llarp_buffer_t(tmp))) + if(!CryptoManager::instance()->shorthash(t_h, llarp_buffer_t(tmp))) { LogError("failed to mix key to ", remoteAddr); return false; } // K = TKE(a.p, B_a.e, sk, t_h) - if(!dh(K, other, secret, t_h)) + if(!(CryptoManager::instance()->*dh_func)(K, other, secret, t_h)) { LogError("key exchange with ", other, " failed"); return false; @@ -130,7 +125,7 @@ namespace llarp buf.cur += K.size(); std::copy(A.begin(), A.end(), buf.cur); buf.cur = buf.base; - return OurCrypto()->shorthash(K, buf); + return CryptoManager::instance()->shorthash(K, buf); } void @@ -312,7 +307,7 @@ namespace llarp // build our RC LinkIntroMessage msg; msg.rc = parent->GetOurRC(); - if(!msg.rc.Verify(OurCrypto(), parent->Now())) + if(!msg.rc.Verify(parent->Now())) { LogError("our RC is invalid? closing session to", remoteAddr); Close(); @@ -344,10 +339,8 @@ namespace llarp return; } - if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(), _1, - _2, _3, _4), - txKey, msg.N, remoteTransportPubKey, - parent->RouterEncryptionSecret())) + if(!DoClientKeyExchange(txKey, msg.N, remoteTransportPubKey, + parent->RouterEncryptionSecret())) { LogError("failed to mix keys for outbound session to ", remoteAddr); Close(); @@ -400,14 +393,14 @@ namespace llarp TunnelNonce nonce(noncePtr); // encrypt - if(!OurCrypto()->xchacha20(payload, txKey, nonce)) + if(!CryptoManager::instance()->xchacha20(payload, txKey, nonce)) return false; payload.base = noncePtr; payload.cur = payload.base; payload.sz = FragmentBufferSize - FragmentHashSize; // key'd hash - if(!OurCrypto()->hmac(buf.data(), payload, txKey)) + if(!CryptoManager::instance()->hmac(buf.data(), payload, txKey)) return false; return MutateKey(txKey, A); } @@ -449,9 +442,8 @@ namespace llarp // set remote rc remoteRC = msg->rc; // recalculate rx key - return DoKeyExchange( - std::bind(&Crypto::transport_dh_server, OurCrypto(), _1, _2, _3, _4), - rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret()); + return DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey, + parent->RouterEncryptionSecret()); } bool @@ -475,9 +467,8 @@ namespace llarp if(!SendMessageBuffer(buf)) return false; // regen our tx Key - return DoKeyExchange( - std::bind(&Crypto::transport_dh_client, OurCrypto(), _1, _2, _3, _4), - txKey, lim.N, remoteRC.enckey, parent->RouterEncryptionSecret()); + return DoClientKeyExchange(txKey, lim.N, remoteRC.enckey, + parent->RouterEncryptionSecret()); } bool @@ -488,7 +479,7 @@ namespace llarp llarp_buffer_t hbuf(ptr + FragmentHashSize, FragmentBufferSize - FragmentHashSize); - if(!OurCrypto()->hmac(digest.data(), hbuf, rxKey)) + if(!CryptoManager::instance()->hmac(digest.data(), hbuf, rxKey)) { LogError("keyed hash failed"); return false; @@ -508,7 +499,8 @@ namespace llarp llarp_buffer_t out(rxFragBody); // decrypt - if(!OurCrypto()->xchacha20_alt(out, in, rxKey, ptr + FragmentHashSize)) + if(!CryptoManager::instance()->xchacha20_alt(out, in, rxKey, + ptr + FragmentHashSize)) { LogError("failed to decrypt message from ", remoteAddr); return false; @@ -611,7 +603,7 @@ namespace llarp sock = s; remoteAddr = addr; RouterID rid = p->GetOurRC().pubkey; - OurCrypto()->shorthash(rxKey, llarp_buffer_t(rid)); + CryptoManager::instance()->shorthash(rxKey, llarp_buffer_t(rid)); remoteRC.Clear(); ABSL_ATTRIBUTE_UNUSED void* res = utp_set_userdata(sock, this); @@ -631,19 +623,18 @@ namespace llarp if(!gotLIM) { remoteRC = msg->rc; - OurCrypto()->shorthash(txKey, llarp_buffer_t(remoteRC.pubkey)); + CryptoManager::instance()->shorthash(txKey, + llarp_buffer_t(remoteRC.pubkey)); - if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, OurCrypto(), - _1, _2, _3, _4), - rxKey, msg->N, remoteRC.enckey, - parent->TransportSecretKey())) + if(!DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey, + parent->TransportSecretKey())) return false; std::array< byte_t, LinkIntroMessage::MaxSize > tmp; llarp_buffer_t buf(tmp); LinkIntroMessage replymsg; replymsg.rc = parent->GetOurRC(); - if(!replymsg.rc.Verify(OurCrypto(), parent->Now())) + if(!replymsg.rc.Verify(parent->Now())) { LogError("our RC is invalid? closing session to", remoteAddr); Close(); @@ -675,10 +666,8 @@ namespace llarp Close(); return false; } - if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(), - _1, _2, _3, _4), - txKey, replymsg.N, remoteRC.enckey, - parent->RouterEncryptionSecret())) + if(!DoClientKeyExchange(txKey, replymsg.N, remoteRC.enckey, + parent->RouterEncryptionSecret())) return false; LogDebug("Sent reply LIM"); @@ -701,9 +690,9 @@ namespace llarp remoteAddr = addr; RouterID rid = remoteRC.pubkey; - OurCrypto()->shorthash(txKey, llarp_buffer_t(rid)); + CryptoManager::instance()->shorthash(txKey, llarp_buffer_t(rid)); rid = p->GetOurRC().pubkey; - OurCrypto()->shorthash(rxKey, llarp_buffer_t(rid)); + CryptoManager::instance()->shorthash(rxKey, llarp_buffer_t(rid)); ABSL_ATTRIBUTE_UNUSED void* res = utp_set_userdata(sock, this); assert(res == this); @@ -729,10 +718,8 @@ namespace llarp remoteRC = msg->rc; gotLIM = true; - if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, OurCrypto(), _1, - _2, _3, _4), - rxKey, msg->N, remoteRC.enckey, - parent->RouterEncryptionSecret())) + if(!DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey, + parent->RouterEncryptionSecret())) { Close(); return false; diff --git a/llarp/utp/session.hpp b/llarp/utp/session.hpp index eb77e3156..0e9e486b2 100644 --- a/llarp/utp/session.hpp +++ b/llarp/utp/session.hpp @@ -91,9 +91,6 @@ namespace llarp void OnLinkEstablished(ILinkLayer* p) override; - Crypto* - OurCrypto(); - /// switch states void EnterState(State st); @@ -159,10 +156,27 @@ namespace llarp OutboundHandshake(); // do key exchange for handshake + template < bool (Crypto::*dh_func)(SharedSecret&, const PubKey&, + const SecretKey&, const TunnelNonce&) > + bool + DoKeyExchange(SharedSecret& K, const KeyExchangeNonce& n, + const PubKey& other, const SecretKey& secret); + bool - DoKeyExchange(transport_dh_func dh, SharedSecret& K, - const KeyExchangeNonce& n, const PubKey& other, - const SecretKey& secret); + DoClientKeyExchange(SharedSecret& K, const KeyExchangeNonce& n, + const PubKey& other, const SecretKey& secret) + { + return DoKeyExchange< &Crypto::transport_dh_client >(K, n, other, + secret); + } + + bool + DoServerKeyExchange(SharedSecret& K, const KeyExchangeNonce& n, + const PubKey& other, const SecretKey& secret) + { + return DoKeyExchange< &Crypto::transport_dh_server >(K, n, other, + secret); + } /// does K = HS(K + A) bool diff --git a/llarp/utp/utp.cpp b/llarp/utp/utp.cpp index 16a5dc138..da544d9cd 100644 --- a/llarp/utp/utp.cpp +++ b/llarp/utp/utp.cpp @@ -10,13 +10,13 @@ namespace llarp using namespace std::placeholders; LinkLayer_ptr - NewServer(Crypto* crypto, const SecretKey& routerEncSecret, GetRCFunc getrc, + NewServer(const SecretKey& routerEncSecret, GetRCFunc getrc, LinkMessageHandler h, SessionEstablishedHandler est, SessionRenegotiateHandler reneg, SignBufferFunc sign, TimeoutHandler timeout, SessionClosedHandler closed) { - return std::make_shared< LinkLayer >(crypto, routerEncSecret, getrc, h, - sign, est, reneg, timeout, closed); + return std::make_shared< LinkLayer >(routerEncSecret, getrc, h, sign, est, + reneg, timeout, closed); } LinkLayer_ptr @@ -24,7 +24,7 @@ namespace llarp { using namespace std::placeholders; return NewServer( - r->crypto(), r->encryption(), std::bind(&AbstractRouter::rc, r), + r->encryption(), std::bind(&AbstractRouter::rc, r), std::bind(&AbstractRouter::HandleRecvLinkMessageBuffer, r, _1, _2), std::bind(&AbstractRouter::OnSessionEstablished, r, _1), std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2), diff --git a/llarp/utp/utp.hpp b/llarp/utp/utp.hpp index 3aa78ba3e..fb8284345 100644 --- a/llarp/utp/utp.hpp +++ b/llarp/utp/utp.hpp @@ -11,7 +11,7 @@ namespace llarp namespace utp { LinkLayer_ptr - NewServer(Crypto* crypto, const SecretKey& routerEncSecret, GetRCFunc getrc, + NewServer(const SecretKey& routerEncSecret, GetRCFunc getrc, LinkMessageHandler h, SessionEstablishedHandler est, SessionRenegotiateHandler reneg, SignBufferFunc sign, TimeoutHandler timeout, SessionClosedHandler closed); diff --git a/test/crypto/test_llarp_crypto.cpp b/test/crypto/test_llarp_crypto.cpp index f1a0c81f2..938820159 100644 --- a/test/crypto/test_llarp_crypto.cpp +++ b/test/crypto/test_llarp_crypto.cpp @@ -13,12 +13,6 @@ namespace llarp IdentityKeyTest() { } - - llarp::Crypto* - Crypto() - { - return &crypto; - } }; TEST_F(IdentityKeyTest, TestSignVerify) @@ -46,12 +40,6 @@ namespace llarp { } - llarp::Crypto* - Crypto() - { - return &crypto; - } - void SetUp() { @@ -63,7 +51,7 @@ namespace llarp { PQCipherBlock block; SharedSecret shared, otherShared; - auto c = Crypto(); + auto c = &crypto; ASSERT_TRUE(keys.size() == PQ_KEYPAIRSIZE); ASSERT_TRUE( diff --git a/test/dht/mock_context.hpp b/test/dht/mock_context.hpp index 4e36f7e63..8f2861462 100644 --- a/test/dht/mock_context.hpp +++ b/test/dht/mock_context.hpp @@ -88,8 +88,6 @@ namespace llarp MOCK_METHOD1(ExploreNetworkVia, void(const dht::Key_t& peer)); - MOCK_CONST_METHOD0(Crypto, llarp::Crypto*()); - MOCK_CONST_METHOD0(GetRouter, llarp::AbstractRouter*()); MOCK_CONST_METHOD0(OurKey, const dht::Key_t&()); diff --git a/test/dht/test_llarp_dht_serviceaddresslookup.cpp b/test/dht/test_llarp_dht_serviceaddresslookup.cpp index 033a2613e..ac2f02dbc 100644 --- a/test/dht/test_llarp_dht_serviceaddresslookup.cpp +++ b/test/dht/test_llarp_dht_serviceaddresslookup.cpp @@ -24,6 +24,7 @@ static constexpr uint64_t EXPIRY = 1548503831ull; struct TestDhtServiceAddressLookup : public ::testing::Test { test::MockCrypto crypto; + CryptoManager cm; MockIntroSetHandler introsetHandler; dht::Key_t ourKey; @@ -37,7 +38,8 @@ struct TestDhtServiceAddressLookup : public ::testing::Test std::unique_ptr< dht::ServiceAddressLookup > serviceAddressLookup; TestDhtServiceAddressLookup() - : ourKey(makeBuf< dht::Key_t >(0xFF)) + : cm(&crypto) + , ourKey(makeBuf< dht::Key_t >(0xFF)) , txKey(makeBuf< dht::Key_t >(0x01)) , txId(2) , txOwner(txKey, txId) @@ -62,7 +64,6 @@ TEST_F(TestDhtServiceAddressLookup, validate) { service::IntroSet introset; - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false)); @@ -78,7 +79,6 @@ TEST_F(TestDhtServiceAddressLookup, validate) EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; // Set expectations - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); @@ -97,7 +97,6 @@ TEST_F(TestDhtServiceAddressLookup, validate) EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; // Set expectations - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); diff --git a/test/dht/test_llarp_dht_taglookup.cpp b/test/dht/test_llarp_dht_taglookup.cpp index 0971d62c8..d98e7013f 100644 --- a/test/dht/test_llarp_dht_taglookup.cpp +++ b/test/dht/test_llarp_dht_taglookup.cpp @@ -18,6 +18,7 @@ static constexpr uint64_t EXPIRY = 1548503831ull; struct TestDhtTagLookup : public ::testing::Test { test::MockCrypto crypto; + CryptoManager cm; dht::Key_t txKey; uint64_t txId; dht::TXOwner txOwner; @@ -28,7 +29,8 @@ struct TestDhtTagLookup : public ::testing::Test dht::TagLookup tagLookup; TestDhtTagLookup() - : txKey(makeBuf< dht::Key_t >(0x01)) + : cm(&crypto) + , txKey(makeBuf< dht::Key_t >(0x01)) , txId(2) , txOwner(txKey, txId) , tag(makeBuf< service::Tag >(0x03)) @@ -47,7 +49,6 @@ TEST_F(TestDhtTagLookup, validate) { service::IntroSet introset; - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false)); @@ -65,7 +66,6 @@ TEST_F(TestDhtTagLookup, validate) EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; // Set expectations - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); @@ -83,7 +83,6 @@ TEST_F(TestDhtTagLookup, validate) EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; // Set expectations - EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); diff --git a/test/link/test_llarp_link.cpp b/test/link/test_llarp_link.cpp index 4372f1e85..1dff8d944 100644 --- a/test/link/test_llarp_link.cpp +++ b/test/link/test_llarp_link.cpp @@ -15,11 +15,10 @@ struct LinkLayerTest : public ::testing::Test struct Context { - Context(llarp::Crypto& c) + Context() { - crypto = &c; - crypto->identity_keygen(signingKey); - crypto->encryption_keygen(encryptionKey); + llarp::CryptoManager::instance()->identity_keygen(signingKey); + llarp::CryptoManager::instance()->encryption_keygen(encryptionKey); rc.pubkey = signingKey.toPublic(); rc.enckey = encryptionKey.toPublic(); } @@ -29,8 +28,6 @@ struct LinkLayerTest : public ::testing::Test llarp::RouterContact rc; - llarp::Crypto* crypto; - bool gotLIM = false; const llarp::RouterContact& @@ -49,9 +46,9 @@ struct LinkLayerTest : public ::testing::Test bool Regen() { - crypto->encryption_keygen(encryptionKey); + llarp::CryptoManager::instance()->encryption_keygen(encryptionKey); rc.enckey = llarp::seckey_topublic(encryptionKey); - return rc.Sign(crypto, signingKey); + return rc.Sign(signingKey); } std::shared_ptr< llarp::ILinkLayer > link; @@ -68,7 +65,8 @@ struct LinkLayerTest : public ::testing::Test } bool - Start(std::shared_ptr logic, llarp_ev_loop_ptr loop, uint16_t port) + Start(std::shared_ptr< llarp::Logic > logic, llarp_ev_loop_ptr loop, + uint16_t port) { if(!link) return false; @@ -79,7 +77,7 @@ struct LinkLayerTest : public ::testing::Test rc.addrs.emplace_back(); if(!link->GetOurAddressInfo(rc.addrs[0])) return false; - if(!rc.Sign(crypto, signingKey)) + if(!rc.Sign(signingKey)) return false; return link->Start(logic); } @@ -100,6 +98,7 @@ struct LinkLayerTest : public ::testing::Test }; llarp::sodium::CryptoLibSodium crypto; + llarp::CryptoManager cm; Context Alice; Context Bob; @@ -111,7 +110,7 @@ struct LinkLayerTest : public ::testing::Test llarp_time_t oldRCLifetime; - LinkLayerTest() : Alice(crypto), Bob(crypto), netLoop(nullptr) + LinkLayerTest() : cm(&crypto), netLoop(nullptr) { } @@ -169,7 +168,7 @@ struct LinkLayerTest : public ::testing::Test TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob) { Alice.link = llarp::utp::NewServer( - &crypto, Alice.encryptionKey, + Alice.encryptionKey, [&]() -> const llarp::RouterContact& { return Alice.GetRC(); }, [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { if(Alice.gotLIM) @@ -216,7 +215,7 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob) }; Bob.link = llarp::utp::NewServer( - &crypto, Bob.encryptionKey, + Bob.encryptionKey, [&]() -> const llarp::RouterContact& { return Bob.GetRC(); }, [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { llarp::LinkIntroMessage msg; @@ -260,7 +259,7 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob) TEST_F(LinkLayerTest, TestUTPAliceConnectToBob) { Alice.link = llarp::utp::NewServer( - &crypto, Alice.encryptionKey, + Alice.encryptionKey, [&]() -> const llarp::RouterContact& { return Alice.GetRC(); }, [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { llarp::LinkIntroMessage lim; @@ -293,7 +292,7 @@ TEST_F(LinkLayerTest, TestUTPAliceConnectToBob) [&](llarp::RouterID router) { ASSERT_EQ(router, Bob.GetRouterID()); }); Bob.link = llarp::utp::NewServer( - &crypto, Bob.encryptionKey, + Bob.encryptionKey, [&]() -> const llarp::RouterContact& { return Bob.GetRC(); }, [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { llarp::LinkIntroMessage lim; diff --git a/test/routing/test_llarp_routing_obtainexitmessage.cpp b/test/routing/test_llarp_routing_obtainexitmessage.cpp index d3ec38b1e..1aefca4dd 100644 --- a/test/routing/test_llarp_routing_obtainexitmessage.cpp +++ b/test/routing/test_llarp_routing_obtainexitmessage.cpp @@ -11,18 +11,10 @@ class ObtainExitTest : public ::testing::Test { public: llarp::sodium::CryptoLibSodium crypto; + llarp::CryptoManager cm; llarp::SecretKey alice; - ObtainExitTest() - { - } - - ~ObtainExitTest() - { - } - - void - SetUp() + ObtainExitTest() : cm(&crypto) { crypto.identity_keygen(alice); } @@ -34,8 +26,8 @@ TEST_F(ObtainExitTest, TestSignVerify) msg.Z.Zero(); msg.S = llarp::randint(); msg.T = llarp::randint(); - EXPECT_TRUE(msg.Sign(&crypto, alice)); - EXPECT_TRUE(msg.Verify(&crypto)); + EXPECT_TRUE(msg.Sign(alice)); + EXPECT_TRUE(msg.Verify()); EXPECT_TRUE(msg.I == llarp::PubKey(llarp::seckey_topublic(alice))); EXPECT_FALSE(msg.version != LLARP_PROTO_VERSION); EXPECT_FALSE(msg.Z.IsZero()); diff --git a/test/service/test_llarp_service_identity.cpp b/test/service/test_llarp_service_identity.cpp index 04666110d..76037bade 100644 --- a/test/service/test_llarp_service_identity.cpp +++ b/test/service/test_llarp_service_identity.cpp @@ -18,24 +18,19 @@ using namespace testing; struct HiddenServiceTest : public ::testing::Test { sodium::CryptoLibSodium crypto; + CryptoManager cm; service::Identity ident; - HiddenServiceTest() + HiddenServiceTest() : cm(&crypto) { - } - - llarp::Crypto* - Crypto() - { - return &crypto; + ident.RegenerateKeys(); + ident.pub.RandomizeVanity(); + ident.pub.UpdateAddr(); } void SetUp() { - ident.RegenerateKeys(Crypto()); - ident.pub.RandomizeVanity(); - ident.pub.UpdateAddr(); } }; @@ -54,8 +49,8 @@ TEST_F(HiddenServiceTest, TestGenerateIntroSet) intro.pathID.Randomize(); I.I.emplace_back(std::move(intro)); } - ASSERT_TRUE(ident.SignIntroSet(I, Crypto(), now)); - ASSERT_TRUE(I.Verify(Crypto(), now)); + ASSERT_TRUE(ident.SignIntroSet(I, now)); + ASSERT_TRUE(I.Verify(now)); } TEST_F(HiddenServiceTest, TestAddressToFromString) @@ -69,6 +64,10 @@ TEST_F(HiddenServiceTest, TestAddressToFromString) struct ServiceIdentityTest : public ::testing::Test { test::MockCrypto crypto; + CryptoManager cm; + ServiceIdentityTest() : cm(&crypto) + { + } }; template < typename Arg > @@ -95,13 +94,13 @@ TEST_F(ServiceIdentityTest, EnsureKeys) .WillOnce(WithArg< 0 >(FillArg< PQKeyPair >(0x03))); service::Identity identity; - ASSERT_TRUE(identity.EnsureKeys(p.string(), &crypto)); + ASSERT_TRUE(identity.EnsureKeys(p.string())); ASSERT_TRUE(fs::exists(fs::status(p))); // Verify what is on disk is what is what was generated service::Identity other; // No need to set more mocks, as we shouldn't need to re-keygen - ASSERT_TRUE(other.EnsureKeys(p.string(), &crypto)); + ASSERT_TRUE(other.EnsureKeys(p.string())); ASSERT_EQ(identity, other); } @@ -115,7 +114,7 @@ TEST_F(ServiceIdentityTest, EnsureKeysDir) ASSERT_TRUE(fs::create_directory(p, code)) << code; service::Identity identity; - ASSERT_FALSE(identity.EnsureKeys(p.string(), &crypto)); + ASSERT_FALSE(identity.EnsureKeys(p.string())); } TEST_F(ServiceIdentityTest, EnsureKeysBrokenFile) @@ -132,5 +131,5 @@ TEST_F(ServiceIdentityTest, EnsureKeysBrokenFile) file.close(); service::Identity identity; - ASSERT_FALSE(identity.EnsureKeys(p.string(), &crypto)); + ASSERT_FALSE(identity.EnsureKeys(p.string())); } diff --git a/test/test_llarp_encrypted_frame.cpp b/test/test_llarp_encrypted_frame.cpp index 8a3525a79..66a93491c 100644 --- a/test/test_llarp_encrypted_frame.cpp +++ b/test/test_llarp_encrypted_frame.cpp @@ -15,27 +15,14 @@ class FrameTest : public ::testing::Test { public: llarp::sodium::CryptoLibSodium crypto; + llarp::CryptoManager cm; SecretKey alice, bob; - FrameTest() - { - } - - ~FrameTest() - { - } - - void - SetUp() + FrameTest() : cm(&crypto) { crypto.encryption_keygen(alice); crypto.encryption_keygen(bob); } - - void - TearDown() - { - } }; TEST_F(FrameTest, TestFrameCrypto) @@ -56,9 +43,9 @@ TEST_F(FrameTest, TestFrameCrypto) // rewind buffer buf->cur = buf->base + llarp::EncryptedFrameOverheadSize; // encrypt to alice - ASSERT_TRUE(f.EncryptInPlace(alice, bob.toPublic(), &crypto)); + ASSERT_TRUE(f.EncryptInPlace(alice, bob.toPublic())); // decrypt from alice - ASSERT_TRUE(f.DecryptInPlace(bob, &crypto)); + ASSERT_TRUE(f.DecryptInPlace(bob)); LRCR otherRecord; ASSERT_TRUE(otherRecord.BDecode(buf)); diff --git a/test/test_llarp_router.cpp b/test/test_llarp_router.cpp index 9eb48fe09..d2dfda027 100644 --- a/test/test_llarp_router.cpp +++ b/test/test_llarp_router.cpp @@ -9,16 +9,17 @@ #include #include -using FindOrCreateFunc = std::function< bool(llarp::Crypto *, const fs::path &, - llarp::SecretKey &) >; +using FindOrCreateFunc = + std::function< bool(const fs::path &, llarp::SecretKey &) >; struct FindOrCreate : public ::testing::TestWithParam< FindOrCreateFunc > { - FindOrCreate() + FindOrCreate() : cm(&crypto) { } llarp::sodium::CryptoLibSodium crypto; + llarp::CryptoManager cm; }; // Concerns @@ -35,7 +36,7 @@ TEST_P(FindOrCreate, find_file_missing) llarp::test::FileGuard guard(p); - ASSERT_TRUE(GetParam()(&crypto, p, key)); + ASSERT_TRUE(GetParam()(p, key)); ASSERT_TRUE(fs::exists(fs::status(p))); ASSERT_FALSE(key.IsZero()); } @@ -53,7 +54,7 @@ TEST_P(FindOrCreate, find_file_empty) llarp::test::FileGuard guard(p); - ASSERT_FALSE(GetParam()(&crypto, p, key)); + ASSERT_FALSE(GetParam()(p, key)); // Verify we didn't delete an invalid file ASSERT_TRUE(fs::exists(fs::status(p))); } @@ -72,7 +73,7 @@ TEST_P(FindOrCreate, happy_path) llarp::test::FileGuard guard(p); - ASSERT_TRUE(GetParam()(&crypto, p, key)); + ASSERT_TRUE(GetParam()(p, key)); // Verify we didn't delete the file ASSERT_TRUE(fs::exists(fs::status(p))); } diff --git a/test/test_llarp_router_contact.cpp b/test/test_llarp_router_contact.cpp index 32e3d6262..6b94f6609 100644 --- a/test/test_llarp_router_contact.cpp +++ b/test/test_llarp_router_contact.cpp @@ -11,7 +11,7 @@ struct RCTest : public ::testing::Test using RC_t = llarp::RouterContact; using SecKey_t = llarp::SecretKey; - RCTest() : oldval(llarp::NetID::DefaultValue()) + RCTest() : cm(&crypto), oldval(llarp::NetID::DefaultValue()) { llarp::NetID::DefaultValue() = llarp::NetID(DEF_VALUE); } @@ -22,6 +22,7 @@ struct RCTest : public ::testing::Test } llarp::sodium::CryptoLibSodium crypto; + llarp::CryptoManager cm; const llarp::NetID oldval; }; @@ -39,6 +40,6 @@ TEST_F(RCTest, TestSignVerify) rc.exits.emplace_back(rc.pubkey, llarp::nuint32_t{50000}); ASSERT_TRUE(rc.netID == netid); ASSERT_TRUE(rc.netID == llarp::NetID::DefaultValue()); - ASSERT_TRUE(rc.Sign(&crypto, sign)); - ASSERT_TRUE(rc.Verify(&crypto, llarp::time_now_ms())); + ASSERT_TRUE(rc.Sign(sign)); + ASSERT_TRUE(rc.Verify(llarp::time_now_ms())); }