Port code to use CryptoManager over passing Crypto pointers

pull/625/head
Michael 5 years ago
parent aea0e32efc
commit 491fee206b
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C

@ -20,6 +20,7 @@ namespace llarp
{ {
struct Config; struct Config;
struct Crypto; struct Crypto;
struct CryptoManager;
class Logic; class Logic;
struct AbstractRouter; struct AbstractRouter;
struct RouterContact; struct RouterContact;
@ -55,6 +56,7 @@ namespace llarp
std::map< std::string, std::string > metricTags; std::map< std::string, std::string > metricTags;
std::unique_ptr< Crypto > crypto; std::unique_ptr< Crypto > crypto;
std::unique_ptr< CryptoManager > cryptoManager;
std::unique_ptr< AbstractRouter > router; std::unique_ptr< AbstractRouter > router;
std::unique_ptr< llarp_threadpool > worker; std::unique_ptr< llarp_threadpool > worker;
std::shared_ptr< Logic > logic; std::shared_ptr< Logic > logic;

@ -203,9 +203,7 @@ __ ___ ____ _ _ ___ _ _ ____
int int
Context::LoadDatabase() Context::LoadDatabase()
{ {
crypto = std::make_unique< sodium::CryptoLibSodium >(); nodedb = std::make_unique< llarp_nodedb >(router->diskworker());
nodedb =
std::make_unique< llarp_nodedb >(crypto.get(), router->diskworker());
if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str()))
{ {
@ -270,6 +268,9 @@ __ ___ ____ _ _ ___ _ _ ____
else else
logic = std::make_shared< Logic >(); 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); router = std::make_unique< Router >(worker.get(), mainloop, logic);
if(!router->Configure(config.get())) if(!router->Configure(config.get()))
{ {

@ -20,18 +20,6 @@
namespace llarp 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 /// library crypto configuration
struct Crypto struct Crypto
{ {

@ -8,8 +8,7 @@ namespace llarp
{ {
bool bool
EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey, EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey,
const PubKey& otherPubkey, const PubKey& otherPubkey)
llarp::Crypto* crypto)
{ {
// format of frame is // format of frame is
// <32 bytes keyed hash of following data> // <32 bytes keyed hash of following data>
@ -29,6 +28,8 @@ namespace llarp
buf.cur = buf.base; buf.cur = buf.base;
buf.sz = size() - EncryptedFrameOverheadSize; buf.sz = size() - EncryptedFrameOverheadSize;
auto crypto = CryptoManager::instance();
// set our pubkey // set our pubkey
memcpy(pubkey, ourSecretKey.toPublic().data(), PUBKEYSIZE); memcpy(pubkey, ourSecretKey.toPublic().data(), PUBKEYSIZE);
// randomize nonce // randomize nonce
@ -63,8 +64,7 @@ namespace llarp
} }
bool bool
EncryptedFrame::DecryptInPlace(const SecretKey& ourSecretKey, EncryptedFrame::DecryptInPlace(const SecretKey& ourSecretKey)
llarp::Crypto* crypto)
{ {
// format of frame is // format of frame is
// <32 bytes keyed hash of following data> // <32 bytes keyed hash of following data>
@ -80,6 +80,8 @@ namespace llarp
SharedSecret shared; SharedSecret shared;
auto crypto = CryptoManager::instance();
// use dh_server because we are not the creator of this message // use dh_server because we are not the creator of this message
if(!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce)) if(!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce))
{ {

@ -9,8 +9,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
static constexpr size_t EncryptedFrameOverheadSize = static constexpr size_t EncryptedFrameOverheadSize =
PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE; PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE;
static constexpr size_t EncryptedFrameBodySize = 128 * 6; static constexpr size_t EncryptedFrameBodySize = 128 * 6;
@ -40,57 +38,10 @@ namespace llarp
} }
bool bool
DecryptInPlace(const SecretKey& seckey, llarp::Crypto* crypto); DecryptInPlace(const SecretKey& seckey);
bool bool
EncryptInPlace(const SecretKey& seckey, const PubKey& other, 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});
}
}; };
/// TODO: can only handle 1 frame at a time /// TODO: can only handle 1 frame at a time
@ -106,7 +57,7 @@ namespace llarp
AsyncFrameDecrypter< User >* ctx = AsyncFrameDecrypter< User >* ctx =
static_cast< AsyncFrameDecrypter< User >* >(user); static_cast< AsyncFrameDecrypter< User >* >(user);
if(ctx->target.DecryptInPlace(ctx->seckey, ctx->crypto)) if(ctx->target.DecryptInPlace(ctx->seckey))
{ {
auto buf = ctx->target.Buffer(); auto buf = ctx->target.Buffer();
buf->cur = buf->base + EncryptedFrameOverheadSize; buf->cur = buf->base + EncryptedFrameOverheadSize;
@ -117,15 +68,13 @@ namespace llarp
ctx->user = nullptr; ctx->user = nullptr;
} }
AsyncFrameDecrypter(llarp::Crypto* c, const SecretKey& secretkey, AsyncFrameDecrypter(const SecretKey& secretkey, DecryptHandler h)
DecryptHandler h) : result(h), seckey(secretkey)
: result(h), crypto(c), seckey(secretkey)
{ {
} }
DecryptHandler result; DecryptHandler result;
User_ptr user; User_ptr user;
llarp::Crypto* crypto;
const SecretKey& seckey; const SecretKey& seckey;
EncryptedFrame target; EncryptedFrame target;

@ -164,6 +164,18 @@ namespace llarp
using PQCipherBlock = AlignedBuffer< PQ_CIPHERTEXTSIZE + 1 >; using PQCipherBlock = AlignedBuffer< PQ_CIPHERTEXTSIZE + 1 >;
using PQPubKey = AlignedBuffer< PQ_PUBKEYSIZE >; using PQPubKey = AlignedBuffer< PQ_PUBKEYSIZE >;
using PQKeyPair = AlignedBuffer< PQ_KEYPAIRSIZE >; 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 } // namespace llarp
#endif #endif

@ -41,9 +41,6 @@ namespace llarp
util::StatusObject util::StatusObject
ExtractStatus() const override; ExtractStatus() const override;
llarp::Crypto*
Crypto() const override;
/// on behalf of whoasked request introset for target from dht router with /// on behalf of whoasked request introset for target from dht router with
/// key askpeer /// key askpeer
void void
@ -696,12 +693,6 @@ namespace llarp
} }
} }
llarp::Crypto*
Context::Crypto() const
{
return router->crypto();
}
llarp_time_t llarp_time_t
Context::Now() const Context::Now() const
{ {

@ -129,9 +129,6 @@ namespace llarp
virtual void virtual void
ExploreNetworkVia(const Key_t& peer) = 0; ExploreNetworkVia(const Key_t& peer) = 0;
virtual llarp::Crypto*
Crypto() const = 0;
virtual llarp::AbstractRouter* virtual llarp::AbstractRouter*
GetRouter() const = 0; GetRouter() const = 0;

@ -25,12 +25,11 @@ namespace llarp
__attribute__((unused)) __attribute__((unused))
std::vector< std::unique_ptr< IMessage > > &replies) const std::vector< std::unique_ptr< IMessage > > &replies) const
{ {
auto &dht = *ctx->impl; auto &dht = *ctx->impl;
auto crypto = dht.GetRouter()->crypto();
for(const auto &introset : I) for(const auto &introset : I)
{ {
if(!introset.Verify(crypto, dht.Now())) if(!introset.Verify(dht.Now()))
{ {
llarp::LogWarn( llarp::LogWarn(
"Invalid introset while handling direct GotIntro " "Invalid introset while handling direct GotIntro "

@ -53,7 +53,7 @@ namespace llarp
return false; return false;
} }
auto &dht = *ctx->impl; auto &dht = *ctx->impl;
if(!I.Verify(dht.Crypto(), now)) if(!I.Verify(now))
{ {
llarp::LogWarn("invalid introset: ", I); llarp::LogWarn("invalid introset: ", I);
// don't propogate or store // don't propogate or store
@ -61,10 +61,7 @@ namespace llarp
return true; return true;
} }
using namespace std::placeholders; if(I.W && !I.W->IsValid(now))
shorthash_func shorthash =
std::bind(&Crypto::shorthash, dht.Crypto(), _1, _2);
if(I.W && !I.W->IsValid(shorthash, now))
{ {
llarp::LogWarn("proof of work not good enough for IntroSet"); llarp::LogWarn("proof of work not good enough for IntroSet");
// don't propogate or store // don't propogate or store

@ -22,7 +22,7 @@ namespace llarp
bool bool
RecursiveRouterLookup::Validate(const RouterContact &rc) const 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"); llarp::LogWarn("rc from lookup result is invalid");
return false; return false;

@ -22,7 +22,7 @@ namespace llarp
bool bool
ServiceAddressLookup::Validate(const service::IntroSet &value) const 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"); llarp::LogWarn("Got invalid introset from service lookup");
return false; return false;

@ -10,7 +10,7 @@ namespace llarp
bool bool
TagLookup::Validate(const service::IntroSet &introset) const 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"); llarp::LogWarn("got invalid introset from tag lookup");
return false; return false;

@ -40,7 +40,7 @@ namespace llarp
} }
bool bool
CloseExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const CloseExitMessage::Verify(const llarp::PubKey& pk) const
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -50,11 +50,11 @@ namespace llarp
if(!copy.BEncode(&buf)) if(!copy.BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->verify(pk, buf, Z); return CryptoManager::instance()->verify(pk, buf, Z);
} }
bool bool
CloseExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) CloseExitMessage::Sign(const llarp::SecretKey& sk)
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -63,7 +63,7 @@ namespace llarp
if(!BEncode(&buf)) if(!BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->sign(Z, sk, buf); return CryptoManager::instance()->sign(Z, sk, buf);
} }
bool bool

@ -45,7 +45,7 @@ namespace llarp
} }
bool bool
GrantExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const GrantExitMessage::Verify(const llarp::PubKey& pk) const
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -55,11 +55,11 @@ namespace llarp
if(!copy.BEncode(&buf)) if(!copy.BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->verify(pk, buf, Z); return CryptoManager::instance()->verify(pk, buf, Z);
} }
bool bool
GrantExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) GrantExitMessage::Sign(const llarp::SecretKey& sk)
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -68,7 +68,7 @@ namespace llarp
if(!BEncode(&buf)) if(!BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->sign(Z, sk, buf); return CryptoManager::instance()->sign(Z, sk, buf);
} }
bool bool

@ -8,7 +8,7 @@ namespace llarp
namespace routing namespace routing
{ {
bool bool
ObtainExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) ObtainExitMessage::Sign(const llarp::SecretKey& sk)
{ {
std::array< byte_t, 1024 > tmp; std::array< byte_t, 1024 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -19,11 +19,11 @@ namespace llarp
return false; return false;
} }
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->sign(Z, sk, buf); return CryptoManager::instance()->sign(Z, sk, buf);
} }
bool bool
ObtainExitMessage::Verify(llarp::Crypto* c) const ObtainExitMessage::Verify() const
{ {
std::array< byte_t, 1024 > tmp; std::array< byte_t, 1024 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -36,7 +36,7 @@ namespace llarp
} }
// rewind buffer // rewind buffer
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->verify(I, buf, Z); return CryptoManager::instance()->verify(I, buf, Z);
} }
bool bool

@ -53,7 +53,7 @@ namespace llarp
} }
bool bool
RejectExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) RejectExitMessage::Sign(const llarp::SecretKey& sk)
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -62,11 +62,11 @@ namespace llarp
if(!BEncode(&buf)) if(!BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->sign(Z, sk, buf); return CryptoManager::instance()->sign(Z, sk, buf);
} }
bool bool
RejectExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const RejectExitMessage::Verify(const llarp::PubKey& pk) const
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -76,7 +76,7 @@ namespace llarp
if(!copy.BEncode(&buf)) if(!copy.BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->verify(pk, buf, Z); return CryptoManager::instance()->verify(pk, buf, Z);
} }
bool bool

@ -1,5 +1,6 @@
#include <exit/session.hpp> #include <exit/session.hpp>
#include <crypto/crypto.hpp>
#include <nodedb.hpp> #include <nodedb.hpp>
#include <path/path.hpp> #include <path/path.hpp>
#include <router/abstractrouter.hpp> #include <router/abstractrouter.hpp>
@ -19,7 +20,7 @@ namespace llarp
, m_LastUse(0) , m_LastUse(0)
, m_BundleRC(bundleRC) , m_BundleRC(bundleRC)
{ {
r->crypto()->identity_keygen(m_ExitIdentity); CryptoManager::instance()->identity_keygen(m_ExitIdentity);
} }
BaseSession::~BaseSession() BaseSession::~BaseSession()
@ -109,11 +110,11 @@ namespace llarp
p->AddObtainExitHandler(std::bind(&BaseSession::HandleGotExit, this, p->AddObtainExitHandler(std::bind(&BaseSession::HandleGotExit, this,
std::placeholders::_1, std::placeholders::_1,
std::placeholders::_2)); std::placeholders::_2));
llarp::routing::ObtainExitMessage obtain; routing::ObtainExitMessage obtain;
obtain.S = p->NextSeqNo(); obtain.S = p->NextSeqNo();
obtain.T = llarp::randint(); obtain.T = llarp::randint();
PopulateRequest(obtain); PopulateRequest(obtain);
if(!obtain.Sign(router->crypto(), m_ExitIdentity)) if(!obtain.Sign(m_ExitIdentity))
{ {
llarp::LogError("Failed to sign exit request"); llarp::LogError("Failed to sign exit request");
return; return;
@ -168,9 +169,8 @@ namespace llarp
if(p->SupportsAnyRoles(roles)) if(p->SupportsAnyRoles(roles))
{ {
llarp::LogInfo(p->Name(), " closing exit path"); llarp::LogInfo(p->Name(), " closing exit path");
llarp::routing::CloseExitMessage msg; routing::CloseExitMessage msg;
if(msg.Sign(router->crypto(), m_ExitIdentity) if(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, router))
&& p->SendExitClose(msg, router))
{ {
p->ClearRoles(roles); p->ClearRoles(roles);
} }
@ -186,19 +186,18 @@ namespace llarp
BaseSession::Stop() BaseSession::Stop()
{ {
CallPendingCallbacks(false); CallPendingCallbacks(false);
auto sendExitClose = [&](const llarp::path::Path_ptr p) { auto sendExitClose = [&](const path::Path_ptr p) {
if(p->SupportsAnyRoles(llarp::path::ePathRoleExit)) if(p->SupportsAnyRoles(path::ePathRoleExit))
{ {
llarp::LogInfo(p->Name(), " closing exit path"); LogInfo(p->Name(), " closing exit path");
llarp::routing::CloseExitMessage msg; routing::CloseExitMessage msg;
if(!(msg.Sign(router->crypto(), m_ExitIdentity) if(!(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, router)))
&& p->SendExitClose(msg, router))) LogWarn(p->Name(), " failed to send exit close message");
llarp::LogWarn(p->Name(), " failed to send exit close message");
} }
}; };
ForEachPath(sendExitClose); ForEachPath(sendExitClose);
router->pathContext().RemovePathSet(shared_from_this()); router->pathContext().RemovePathSet(shared_from_this());
return llarp::path::Builder::Stop(); return path::Builder::Stop();
} }
bool bool

@ -45,7 +45,7 @@ namespace llarp
} }
bool bool
UpdateExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const UpdateExitMessage::Verify(const llarp::PubKey& pk) const
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
@ -56,11 +56,11 @@ namespace llarp
if(!copy.BEncode(&buf)) if(!copy.BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->verify(pk, buf, Z); return CryptoManager::instance()->verify(pk, buf, Z);
} }
bool bool
UpdateExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) UpdateExitMessage::Sign(const llarp::SecretKey& sk)
{ {
std::array< byte_t, 512 > tmp; std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -68,7 +68,7 @@ namespace llarp
if(!BEncode(&buf)) if(!BEncode(&buf))
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
return c->sign(Z, sk, buf); return CryptoManager::instance()->sign(Z, sk, buf);
} }
bool bool

@ -304,12 +304,6 @@ namespace llarp
return m_Router; return m_Router;
} }
Crypto *
ExitEndpoint::GetCrypto()
{
return m_Router->crypto();
}
huint32_t huint32_t
ExitEndpoint::GetIfAddr() const ExitEndpoint::GetIfAddr() const
{ {

@ -62,9 +62,6 @@ namespace llarp
llarp_time_t llarp_time_t
Now() const; Now() const;
Crypto*
GetCrypto();
template < typename Stats > template < typename Stats >
void void
CalculateTrafficStats(Stats& stats) CalculateTrafficStats(Stats& stats)

@ -11,7 +11,7 @@ namespace llarp
{ {
using namespace std::placeholders; using namespace std::placeholders;
return NewServer( 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::HandleRecvLinkMessageBuffer, r, _1, _2),
std::bind(&AbstractRouter::OnSessionEstablished, r, _1), std::bind(&AbstractRouter::OnSessionEstablished, r, _1),
std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2), std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2),
@ -21,12 +21,11 @@ namespace llarp
} }
std::unique_ptr< ILinkLayer > std::unique_ptr< ILinkLayer >
NewServer(Crypto* c, const SecretKey& enckey, GetRCFunc getrc, NewServer(const SecretKey& enckey, GetRCFunc getrc, LinkMessageHandler h,
LinkMessageHandler h, SessionEstablishedHandler est, SessionEstablishedHandler est, SessionRenegotiateHandler reneg,
SessionRenegotiateHandler reneg, SignBufferFunc sign, SignBufferFunc sign, TimeoutHandler t,
TimeoutHandler t, SessionClosedHandler closed) SessionClosedHandler closed)
{ {
(void)c;
(void)enckey; (void)enckey;
(void)getrc; (void)getrc;
(void)h; (void)h;

@ -12,9 +12,8 @@ namespace llarp
namespace iwp namespace iwp
{ {
std::unique_ptr< ILinkLayer > std::unique_ptr< ILinkLayer >
NewServer(llarp::Crypto* crypto, const SecretKey& routerEncSecret, NewServer(const SecretKey& routerEncSecret, llarp::GetRCFunc getrc,
llarp::GetRCFunc getrc, llarp::LinkMessageHandler h, llarp::LinkMessageHandler h, llarp::SessionEstablishedHandler est,
llarp::SessionEstablishedHandler est,
llarp::SessionRenegotiateHandler reneg, llarp::SessionRenegotiateHandler reneg,
llarp::SignBufferFunc sign, llarp::TimeoutHandler timeout, llarp::SignBufferFunc sign, llarp::TimeoutHandler timeout,
llarp::SessionClosedHandler closed); llarp::SessionClosedHandler closed);

@ -4,11 +4,11 @@ namespace llarp
{ {
namespace iwp namespace iwp
{ {
LinkLayer::LinkLayer(Crypto* c, const SecretKey& enckey, GetRCFunc getrc, LinkLayer::LinkLayer(const SecretKey& enckey, GetRCFunc getrc,
LinkMessageHandler h, SessionEstablishedHandler est, LinkMessageHandler h, SessionEstablishedHandler est,
SessionRenegotiateHandler reneg, SignBufferFunc sign, SessionRenegotiateHandler reneg, SignBufferFunc sign,
TimeoutHandler t, SessionClosedHandler closed) 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(); m_FlowCookie.Randomize();
} }
@ -33,7 +33,7 @@ namespace llarp
LinkLayer::KeyGen(SecretKey& k) LinkLayer::KeyGen(SecretKey& k)
{ {
k.Zero(); k.Zero();
crypto->encryption_keygen(k); CryptoManager::instance()->encryption_keygen(k);
return !k.IsZero(); return !k.IsZero();
} }
@ -68,7 +68,8 @@ namespace llarp
{ {
case eOCMD_ObtainFlowID: case eOCMD_ObtainFlowID:
sigbuf.sz -= m_OuterMsg.Zsig.size(); 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 '", LogError("failed to verify signature on '",
(char)m_OuterMsg.command, "' message from ", from); (char)m_OuterMsg.command, "' message from ", from);
@ -132,7 +133,7 @@ namespace llarp
tmp.begin() + 64 + pk.size()); tmp.begin() + 64 + pk.size());
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
ShortHash h; ShortHash h;
if(!crypto->shorthash(h, buf)) if(!CryptoManager::instance()->shorthash(h, buf))
return false; return false;
std::copy_n(h.begin(), flow.size(), flow.begin()); std::copy_n(h.begin(), flow.size(), flow.begin());
return true; return true;

@ -14,22 +14,13 @@ namespace llarp
{ {
struct LinkLayer final : public ILinkLayer struct LinkLayer final : public ILinkLayer
{ {
LinkLayer(Crypto *crypto, const SecretKey &encryptionSecretKey, LinkLayer(const SecretKey &encryptionSecretKey, GetRCFunc getrc,
GetRCFunc getrc, LinkMessageHandler h, LinkMessageHandler h, SessionEstablishedHandler established,
SessionEstablishedHandler established,
SessionRenegotiateHandler reneg, SignBufferFunc sign, SessionRenegotiateHandler reneg, SignBufferFunc sign,
TimeoutHandler timeout, SessionClosedHandler closed); TimeoutHandler timeout, SessionClosedHandler closed);
~LinkLayer(); ~LinkLayer();
Crypto *const crypto;
Crypto *
OurCrypto() override
{
return crypto;
}
bool bool
Start(std::shared_ptr< Logic > l) override; Start(std::shared_ptr< Logic > l) override;

@ -61,9 +61,6 @@ namespace llarp
return llarp_ev_loop_time_now_ms(m_Loop); return llarp_ev_loop_time_now_ms(m_Loop);
} }
virtual Crypto*
OurCrypto() = 0;
bool bool
HasSessionTo(const RouterID& pk); HasSessionTo(const RouterID& pk);

@ -9,7 +9,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
namespace routing namespace routing
{ {
struct ObtainExitMessage final : public IMessage struct ObtainExitMessage final : public IMessage
@ -44,10 +43,10 @@ namespace llarp
/// populates I and signs /// populates I and signs
bool bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk); Sign(const llarp::SecretKey& sk);
bool bool
Verify(llarp::Crypto* c) const; Verify() const;
bool bool
BEncode(llarp_buffer_t* buf) const override; BEncode(llarp_buffer_t* buf) const override;
@ -71,10 +70,10 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override; BEncode(llarp_buffer_t* buf) const override;
bool bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk); Sign(const llarp::SecretKey& sk);
bool bool
Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; Verify(const llarp::PubKey& pk) const;
bool bool
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override; DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
@ -111,10 +110,10 @@ namespace llarp
} }
bool bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk); Sign(const llarp::SecretKey& sk);
bool bool
Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; Verify(const llarp::PubKey& pk) const;
bool bool
BEncode(llarp_buffer_t* buf) const override; BEncode(llarp_buffer_t* buf) const override;
@ -133,13 +132,7 @@ namespace llarp
Nonce_t Y; Nonce_t Y;
llarp::Signature Z; llarp::Signature Z;
UpdateExitVerifyMessage() : IMessage() ~UpdateExitVerifyMessage() = default;
{
}
~UpdateExitVerifyMessage()
{
}
void void
Clear() override Clear() override
@ -149,15 +142,6 @@ namespace llarp
Z.Zero(); 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 bool
BEncode(llarp_buffer_t* buf) const override; BEncode(llarp_buffer_t* buf) const override;
@ -177,10 +161,10 @@ namespace llarp
llarp::Signature Z; llarp::Signature Z;
bool bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk); Sign(const llarp::SecretKey& sk);
bool bool
Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; Verify(const llarp::PubKey& pk) const;
bool bool
BEncode(llarp_buffer_t* buf) const override; BEncode(llarp_buffer_t* buf) const override;
@ -218,10 +202,10 @@ namespace llarp
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override; HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
bool bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk); Sign(const llarp::SecretKey& sk);
bool bool
Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; Verify(const llarp::PubKey& pk) const;
void void
Clear() override Clear() override

@ -101,9 +101,10 @@ namespace llarp
} }
bool bool
LinkIntroMessage::HandleMessage(AbstractRouter* router) const LinkIntroMessage::HandleMessage(
ABSL_ATTRIBUTE_UNUSED AbstractRouter* router) const
{ {
if(!Verify(router->crypto())) if(!Verify())
return false; return false;
return session->GotLIM(this); return session->GotLIM(this);
} }
@ -132,7 +133,7 @@ namespace llarp
} }
bool bool
LinkIntroMessage::Verify(llarp::Crypto* c) const LinkIntroMessage::Verify() const
{ {
LinkIntroMessage copy; LinkIntroMessage copy;
copy = *this; copy = *this;
@ -144,13 +145,13 @@ namespace llarp
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
// outer signature // outer signature
if(!c->verify(rc.pubkey, buf, Z)) if(!CryptoManager::instance()->verify(rc.pubkey, buf, Z))
{ {
llarp::LogError("outer signature failure"); llarp::LogError("outer signature failure");
return false; return false;
} }
// verify RC // verify RC
if(!rc.Verify(c, llarp::time_now_ms())) if(!rc.Verify(llarp::time_now_ms()))
{ {
llarp::LogError("invalid RC in link intro"); llarp::LogError("invalid RC in link intro");
return false; return false;

@ -35,7 +35,7 @@ namespace llarp
Sign(std::function< bool(Signature&, const llarp_buffer_t&) > signer); Sign(std::function< bool(Signature&, const llarp_buffer_t&) > signer);
bool bool
Verify(llarp::Crypto* c) const; Verify() const;
void void
Clear() override; Clear() override;

@ -1,5 +1,6 @@
#include <messages/relay_commit.hpp> #include <messages/relay_commit.hpp>
#include <crypto/crypto.hpp>
#include <messages/path_confirm.hpp> #include <messages/path_confirm.hpp>
#include <path/path.hpp> #include <path/path.hpp>
#include <router/abstractrouter.hpp> #include <router/abstractrouter.hpp>
@ -235,7 +236,7 @@ namespace llarp
// ... and it's valid // ... and it's valid
const auto now = self->context->Router()->Now(); const auto now = self->context->Router()->Now();
if(self->record.nextRC->IsPublicRouter() 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(); llarp_nodedb* n = self->context->Router()->nodedb();
const RouterContact rc = *self->record.nextRC; const RouterContact rc = *self->record.nextRC;
@ -309,7 +310,7 @@ namespace llarp
return; return;
} }
// generate path key as we are in a worker thread // 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, if(!crypto->dh_server(self->hop->pathKey, self->record.commkey,
self->context->EncryptionSecretKey(), self->context->EncryptionSecretKey(),
self->record.tunnelNonce)) self->record.tunnelNonce))
@ -321,10 +322,7 @@ namespace llarp
// generate hash of hop key for nonce mutation // generate hash of hop key for nonce mutation
crypto->shorthash(self->hop->nonceXOR, crypto->shorthash(self->hop->nonceXOR,
llarp_buffer_t(self->hop->pathKey)); llarp_buffer_t(self->hop->pathKey));
using namespace std::placeholders; if(self->record.work && self->record.work->IsValid(now))
if(self->record.work
&& self->record.work->IsValid(
std::bind(&Crypto::shorthash, crypto, _1, _2), now))
{ {
llarp::LogDebug("LRCM extended lifetime by ", llarp::LogDebug("LRCM extended lifetime by ",
self->record.work->extendedLifetime, " seconds for ", self->record.work->extendedLifetime, " seconds for ",
@ -382,8 +380,7 @@ namespace llarp
LR_CommitMessage::AsyncDecrypt(llarp::path::PathContext* context) const LR_CommitMessage::AsyncDecrypt(llarp::path::PathContext* context) const
{ {
auto decrypter = std::make_unique< LRCMFrameDecrypt::Decrypter >( auto decrypter = std::make_unique< LRCMFrameDecrypt::Decrypter >(
context->crypto(), context->EncryptionSecretKey(), context->EncryptionSecretKey(), &LRCMFrameDecrypt::HandleDecrypted);
&LRCMFrameDecrypt::HandleDecrypted);
// copy frames so we own them // copy frames so we own them
auto frameDecrypt = std::make_shared< LRCMFrameDecrypt >( auto frameDecrypt = std::make_shared< LRCMFrameDecrypt >(
context, std::move(decrypter), this); context, std::move(decrypter), this);

@ -209,7 +209,7 @@ llarp_nodedb::loadfile(const fs::path &fpath)
llarp::LogError("failed to read file ", fpath); llarp::LogError("failed to read file ", fpath);
return false; return false;
} }
if(!rc.Verify(crypto, llarp::time_now_ms())) if(!rc.Verify(llarp::time_now_ms()))
{ {
llarp::LogError(fpath, " contains invalid RC"); llarp::LogError(fpath, " contains invalid RC");
return false; return false;
@ -295,8 +295,7 @@ crypto_threadworker_verifyrc(void *user)
llarp_async_verify_rc *verify_request = llarp_async_verify_rc *verify_request =
static_cast< llarp_async_verify_rc * >(user); static_cast< llarp_async_verify_rc * >(user);
llarp::RouterContact rc = verify_request->rc; llarp::RouterContact rc = verify_request->rc;
verify_request->valid = verify_request->valid = rc.Verify(llarp::time_now_ms());
rc.Verify(verify_request->nodedb->crypto, llarp::time_now_ms());
// if it's valid we need to set it // if it's valid we need to set it
if(verify_request->valid && rc.IsPublicRouter()) if(verify_request->valid && rc.IsPublicRouter())
{ {

@ -26,7 +26,6 @@ struct llarp_threadpool;
namespace llarp namespace llarp
{ {
struct Crypto;
class Logic; class Logic;
namespace thread namespace thread
@ -45,8 +44,8 @@ struct llarp_nodedb_iter
struct llarp_nodedb struct llarp_nodedb
{ {
llarp_nodedb(llarp::Crypto *c, llarp::thread::ThreadPool *diskworker) explicit llarp_nodedb(llarp::thread::ThreadPool *diskworker)
: crypto(c), disk(diskworker) : disk(diskworker)
{ {
} }
@ -55,7 +54,6 @@ struct llarp_nodedb
Clear(); Clear();
} }
llarp::Crypto *crypto;
llarp::thread::ThreadPool *disk; llarp::thread::ThreadPool *disk;
mutable llarp::util::Mutex access; // protects entries mutable llarp::util::Mutex access; // protects entries
std::unordered_map< llarp::RouterID, llarp::RouterContact, std::unordered_map< llarp::RouterID, llarp::RouterContact,

@ -57,12 +57,6 @@ namespace llarp
return m_Router->threadpool(); return m_Router->threadpool();
} }
Crypto*
PathContext::crypto()
{
return m_Router->crypto();
}
std::shared_ptr< Logic > std::shared_ptr< Logic >
PathContext::logic() PathContext::logic()
{ {
@ -597,7 +591,7 @@ namespace llarp
TunnelNonce n = Y; TunnelNonce n = Y;
for(const auto& hop : hops) for(const auto& hop : hops)
{ {
r->crypto()->xchacha20(buf, hop.shared, n); CryptoManager::instance()->xchacha20(buf, hop.shared, n);
n ^= hop.nonceXOR; n ^= hop.nonceXOR;
} }
RelayUpstreamMessage msg; RelayUpstreamMessage msg;
@ -639,7 +633,7 @@ namespace llarp
for(const auto& hop : hops) for(const auto& hop : hops)
{ {
n ^= hop.nonceXOR; n ^= hop.nonceXOR;
r->crypto()->xchacha20(buf, hop.shared, n); CryptoManager::instance()->xchacha20(buf, hop.shared, n);
} }
if(!HandleRoutingMessage(buf, r)) if(!HandleRoutingMessage(buf, r))
return false; return false;
@ -699,7 +693,7 @@ namespace llarp
if(buf.sz < pad_size) if(buf.sz < pad_size)
{ {
// randomize padding // 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.sz = pad_size;
} }
buf.cur = buf.base; buf.cur = buf.base;
@ -799,12 +793,12 @@ namespace llarp
bool bool
Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg,
AbstractRouter* r) ABSL_ATTRIBUTE_UNUSED AbstractRouter* r)
{ {
/// allows exits to close from their end /// allows exits to close from their end
if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC))
{ {
if(msg.Verify(r->crypto(), EndpointPubKey())) if(msg.Verify(EndpointPubKey()))
{ {
LogInfo(Name(), " had its exit closed"); LogInfo(Name(), " had its exit closed");
_role &= ~ePathRoleExit; _role &= ~ePathRoleExit;
@ -862,7 +856,7 @@ namespace llarp
{ {
if(m_ExitObtainTX && msg.T == m_ExitObtainTX) if(m_ExitObtainTX && msg.T == m_ExitObtainTX)
{ {
if(!msg.Verify(r->crypto(), EndpointPubKey())) if(!msg.Verify(EndpointPubKey()))
{ {
LogError(Name(), "RXM invalid signature"); LogError(Name(), "RXM invalid signature");
return false; return false;
@ -881,7 +875,7 @@ namespace llarp
{ {
if(m_ExitObtainTX && msg.T == m_ExitObtainTX) if(m_ExitObtainTX && msg.T == m_ExitObtainTX)
{ {
if(!msg.Verify(r->crypto(), EndpointPubKey())) if(!msg.Verify(EndpointPubKey()))
{ {
LogError(Name(), " GXM signature failed"); LogError(Name(), " GXM signature failed");
return false; return false;

@ -27,7 +27,6 @@ namespace llarp
{ {
class Logic; class Logic;
struct AbstractRouter; struct AbstractRouter;
struct Crypto;
struct LR_CommitMessage; struct LR_CommitMessage;
struct LR_CommitRecord; struct LR_CommitRecord;
@ -705,9 +704,6 @@ namespace llarp
llarp_threadpool* llarp_threadpool*
Worker(); Worker();
llarp::Crypto*
crypto();
std::shared_ptr< Logic > std::shared_ptr< Logic >
logic(); logic();

@ -1,5 +1,6 @@
#include <path/pathbuilder.hpp> #include <path/pathbuilder.hpp>
#include <crypto/crypto.hpp>
#include <messages/relay_commit.hpp> #include <messages/relay_commit.hpp>
#include <nodedb.hpp> #include <nodedb.hpp>
#include <path/path.hpp> #include <path/path.hpp>
@ -27,7 +28,6 @@ namespace llarp
AbstractRouter* router = nullptr; AbstractRouter* router = nullptr;
llarp_threadpool* worker = nullptr; llarp_threadpool* worker = nullptr;
std::shared_ptr< Logic > logic = nullptr; std::shared_ptr< Logic > logic = nullptr;
Crypto* crypto = nullptr;
LR_CommitMessage LRCM; LR_CommitMessage LRCM;
~AsyncPathKeyExchangeContext() ~AsyncPathKeyExchangeContext()
@ -53,12 +53,13 @@ namespace llarp
auto& hop = ctx->path->hops[ctx->idx]; auto& hop = ctx->path->hops[ctx->idx];
auto& frame = ctx->LRCM.frames[ctx->idx]; auto& frame = ctx->LRCM.frames[ctx->idx];
auto crypto = CryptoManager::instance();
// generate key // generate key
ctx->crypto->encryption_keygen(hop.commkey); crypto->encryption_keygen(hop.commkey);
hop.nonce.Randomize(); hop.nonce.Randomize();
// do key exchange // do key exchange
if(!ctx->crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, if(!crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, hop.nonce))
hop.nonce))
{ {
LogError(ctx->pathset->Name(), LogError(ctx->pathset->Name(),
" Failed to generate shared key for path build"); " Failed to generate shared key for path build");
@ -66,7 +67,7 @@ namespace llarp
return; return;
} }
// generate nonceXOR valueself->hop->pathKey // 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; ++ctx->idx;
bool isFarthestHop = ctx->idx == ctx->path->hops.size(); bool isFarthestHop = ctx->idx == ctx->path->hops.size();
@ -104,8 +105,8 @@ namespace llarp
} }
// use ephemeral keypair for frame // use ephemeral keypair for frame
SecretKey framekey; SecretKey framekey;
ctx->crypto->encryption_keygen(framekey); crypto->encryption_keygen(framekey);
if(!frame.EncryptInPlace(framekey, hop.rc.enckey, ctx->crypto)) if(!frame.EncryptInPlace(framekey, hop.rc.enckey))
{ {
LogError(ctx->pathset->Name(), " Failed to encrypt LRCR"); LogError(ctx->pathset->Name(), " Failed to encrypt LRCR");
delete ctx; delete ctx;
@ -125,10 +126,6 @@ namespace llarp
} }
} }
AsyncPathKeyExchangeContext(Crypto* c) : crypto(c)
{
}
/// Generate all keys asynchronously and call handler when done /// Generate all keys asynchronously and call handler when done
void void
AsyncGenerateKeys(Path_t p, std::shared_ptr< Logic > l, AsyncGenerateKeys(Path_t p, std::shared_ptr< Logic > l,
@ -173,7 +170,7 @@ namespace llarp
size_t pathNum, size_t hops) size_t pathNum, size_t hops)
: path::PathSet(pathNum), router(p_router), dht(p_dht), numHops(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); _run.store(true);
} }
@ -319,7 +316,7 @@ namespace llarp
const auto aligned = const auto aligned =
router->pathContext().FindOwnedPathsWithEndpoint(remote); router->pathContext().FindOwnedPathsWithEndpoint(remote);
/// pick the lowest latency path that aligns to 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; Path_ptr p;
llarp_time_t min = std::numeric_limits< llarp_time_t >::max(); llarp_time_t min = std::numeric_limits< llarp_time_t >::max();
for(const auto& path : aligned) for(const auto& path : aligned)
@ -409,7 +406,7 @@ namespace llarp
lastBuild = Now(); lastBuild = Now();
// async generate keys // async generate keys
AsyncPathKeyExchangeContext< Builder >* ctx = AsyncPathKeyExchangeContext< Builder >* ctx =
new AsyncPathKeyExchangeContext< Builder >(router->crypto()); new AsyncPathKeyExchangeContext< Builder >();
ctx->router = router; ctx->router = router;
ctx->pathset = GetSelf(); ctx->pathset = GetSelf();
auto path = std::make_shared< path::Path >(hops, this, roles); auto path = std::make_shared< path::Path >(hops, this, roles);

@ -64,7 +64,7 @@ namespace llarp
{ {
dlt = pad_size - dlt; dlt = pad_size - dlt;
// randomize padding // randomize padding
r->crypto()->randbytes(buf.cur, dlt); CryptoManager::instance()->randbytes(buf.cur, dlt);
buf.sz += dlt; buf.sz += dlt;
} }
buf.cur = buf.base; buf.cur = buf.base;
@ -78,7 +78,7 @@ namespace llarp
RelayDownstreamMessage msg; RelayDownstreamMessage msg;
msg.pathid = info.rxID; msg.pathid = info.rxID;
msg.Y = Y ^ nonceXOR; msg.Y = Y ^ nonceXOR;
r->crypto()->xchacha20(buf, pathKey, Y); CryptoManager::instance()->xchacha20(buf, pathKey, Y);
msg.X = buf; msg.X = buf;
llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ",
info.upstream, " to ", info.downstream); info.upstream, " to ", info.downstream);
@ -89,7 +89,7 @@ namespace llarp
TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y, TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
AbstractRouter* r) AbstractRouter* r)
{ {
r->crypto()->xchacha20(buf, pathKey, Y); CryptoManager::instance()->xchacha20(buf, pathKey, Y);
if(IsEndpoint(r->pubkey())) if(IsEndpoint(r->pubkey()))
{ {
m_LastActivity = r->Now(); m_LastActivity = r->Now();
@ -146,13 +146,13 @@ namespace llarp
TransitHop::HandleObtainExitMessage( TransitHop::HandleObtainExitMessage(
const llarp::routing::ObtainExitMessage& msg, AbstractRouter* r) 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)) && r->exitContext().ObtainNewExit(msg.I, info.rxID, msg.E != 0))
{ {
llarp::routing::GrantExitMessage grant; llarp::routing::GrantExitMessage grant;
grant.S = NextSeqNo(); grant.S = NextSeqNo();
grant.T = msg.T; grant.T = msg.T;
if(!grant.Sign(r->crypto(), r->identity())) if(!grant.Sign(r->identity()))
{ {
llarp::LogError("Failed to sign grant exit message"); llarp::LogError("Failed to sign grant exit message");
return false; return false;
@ -164,7 +164,7 @@ namespace llarp
llarp::routing::RejectExitMessage reject; llarp::routing::RejectExitMessage reject;
reject.S = NextSeqNo(); reject.S = NextSeqNo();
reject.T = msg.T; reject.T = msg.T;
if(!reject.Sign(r->crypto(), r->identity())) if(!reject.Sign(r->identity()))
{ {
llarp::LogError("Failed to sign reject exit message"); llarp::LogError("Failed to sign reject exit message");
return false; return false;
@ -178,12 +178,12 @@ namespace llarp
{ {
const llarp::routing::DataDiscardMessage discard(info.rxID, msg.S); const llarp::routing::DataDiscardMessage discard(info.rxID, msg.S);
auto ep = r->exitContext().FindEndpointForPath(info.rxID); 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; llarp::routing::CloseExitMessage reply;
reply.Y = msg.Y; reply.Y = msg.Y;
reply.S = NextSeqNo(); reply.S = NextSeqNo();
if(reply.Sign(r->crypto(), r->identity())) if(reply.Sign(r->identity()))
{ {
if(SendRoutingMessage(reply, r)) if(SendRoutingMessage(reply, r))
{ {
@ -213,7 +213,7 @@ namespace llarp
auto ep = r->exitContext().FindEndpointForPath(msg.P); auto ep = r->exitContext().FindEndpointForPath(msg.P);
if(ep) if(ep)
{ {
if(!msg.Verify(r->crypto(), ep->PubKey())) if(!msg.Verify(ep->PubKey()))
return false; return false;
if(ep->UpdateLocalPath(info.rxID)) if(ep->UpdateLocalPath(info.rxID))

@ -1,5 +1,6 @@
#include <pow.hpp> #include <pow.hpp>
#include <crypto/crypto.hpp>
#include <util/buffer.hpp> #include <util/buffer.hpp>
#include <cmath> #include <cmath>
@ -28,7 +29,7 @@ namespace llarp
} }
bool 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)) if(now - timestamp > (uint64_t(extendedLifetime) * 1000))
return false; return false;
@ -43,7 +44,7 @@ namespace llarp
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
// hash // hash
if(!hashfunc(digest, buf)) if(!CryptoManager::instance()->shorthash(digest, buf))
return false; return false;
// check bytes required // check bytes required
uint32_t required = std::floor(std::log(extendedLifetime)); uint32_t required = std::floor(std::log(extendedLifetime));

@ -1,7 +1,6 @@
#ifndef LLARP_POW_HPP #ifndef LLARP_POW_HPP
#define LLARP_POW_HPP #define LLARP_POW_HPP
#include <crypto/crypto.hpp>
#include <router_id.hpp> #include <router_id.hpp>
#include <util/buffer.hpp> #include <util/buffer.hpp>
@ -19,7 +18,7 @@ namespace llarp
~PoW(); ~PoW();
bool bool
IsValid(shorthash_func hashfunc, llarp_time_t now) const; IsValid(llarp_time_t now) const;
bool bool
DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* val); DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* val);

@ -17,7 +17,6 @@ namespace llarp
{ {
class Logic; class Logic;
struct Config; struct Config;
struct Crypto;
struct RouterID; struct RouterID;
struct ILinkMessage; struct ILinkMessage;
struct ILinkSession; struct ILinkSession;
@ -68,9 +67,6 @@ namespace llarp
virtual llarp_dht_context * virtual llarp_dht_context *
dht() const = 0; dht() const = 0;
virtual Crypto *
crypto() const = 0;
virtual llarp_nodedb * virtual llarp_nodedb *
nodedb() const = 0; nodedb() const = 0;

@ -123,7 +123,7 @@ on_try_connecting(std::shared_ptr< TryConnectJob > j)
} }
bool bool
llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath, llarp_loadServiceNodeIdentityKey(const fs::path &fpath,
llarp::SecretKey &secret) llarp::SecretKey &secret)
{ {
std::string path = fpath.string(); std::string path = fpath.string();
@ -132,12 +132,11 @@ llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath,
if(!ident.LoadFromFile(path.c_str())) if(!ident.LoadFromFile(path.c_str()))
return false; return false;
return crypto->seed_to_secretkey(secret, ident); return llarp::CryptoManager::instance()->seed_to_secretkey(secret, ident);
} }
bool bool
llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, llarp_findOrCreateIdentity(const fs::path &path, llarp::SecretKey &secretkey)
llarp::SecretKey &secretkey)
{ {
std::string fpath = path.string(); std::string fpath = path.string();
llarp::LogDebug("find or create ", fpath); llarp::LogDebug("find or create ", fpath);
@ -145,7 +144,7 @@ llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path,
if(!fs::exists(path, ec)) if(!fs::exists(path, ec))
{ {
llarp::LogInfo("generating new identity key"); llarp::LogInfo("generating new identity key");
crypto->identity_keygen(secretkey); llarp::CryptoManager::instance()->identity_keygen(secretkey);
if(!secretkey.SaveToFile(fpath.c_str())) if(!secretkey.SaveToFile(fpath.c_str()))
return false; return false;
} }
@ -154,8 +153,7 @@ llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path,
// C++ ... // C++ ...
bool bool
llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path, llarp_findOrCreateEncryption(const fs::path &path, llarp::SecretKey &encryption)
llarp::SecretKey &encryption)
{ {
std::string fpath = path.string(); std::string fpath = path.string();
llarp::LogDebug("find or create ", fpath); llarp::LogDebug("find or create ", fpath);
@ -163,7 +161,7 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path,
if(!fs::exists(path, ec)) if(!fs::exists(path, ec))
{ {
llarp::LogInfo("generating new encryption key"); llarp::LogInfo("generating new encryption key");
crypto->encryption_keygen(encryption); llarp::CryptoManager::instance()->encryption_keygen(encryption);
if(!encryption.SaveToFile(fpath.c_str())) if(!encryption.SaveToFile(fpath.c_str()))
return false; return false;
} }
@ -220,7 +218,6 @@ namespace llarp
, _netloop(__netloop) , _netloop(__netloop)
, tp(_tp) , tp(_tp)
, _logic(l) , _logic(l)
, _crypto(std::make_unique< sodium::CryptoLibSodium >())
, paths(this) , paths(this)
, _exitContext(this) , _exitContext(this)
, disk(1, 1000) , disk(1, 1000)
@ -384,7 +381,7 @@ namespace llarp
{ {
return; return;
} }
if(results[0].Verify(crypto(), Now())) if(results[0].Verify(Now()))
{ {
TryConnectAsync(results[0], 10); TryConnectAsync(results[0], 10);
return; return;
@ -431,7 +428,7 @@ namespace llarp
LogError("failure to decode or verify of remote RC"); LogError("failure to decode or verify of remote RC");
return; return;
} }
if(remote.Verify(crypto(), Now())) if(remote.Verify(Now()))
{ {
LogDebug("verified signature"); LogDebug("verified signature");
if(!TryConnectAsync(remote, 10)) if(!TryConnectAsync(remote, 10))
@ -450,17 +447,15 @@ namespace llarp
if(!EnsureEncryptionKey()) if(!EnsureEncryptionKey())
return false; return false;
if(usingSNSeed) if(usingSNSeed)
return llarp_loadServiceNodeIdentityKey(crypto(), ident_keyfile, return llarp_loadServiceNodeIdentityKey(ident_keyfile, _identity);
_identity);
else else
return llarp_findOrCreateIdentity(crypto(), ident_keyfile, _identity); return llarp_findOrCreateIdentity(ident_keyfile, _identity);
} }
bool bool
Router::EnsureEncryptionKey() Router::EnsureEncryptionKey()
{ {
return llarp_findOrCreateEncryption(crypto(), encryption_keyfile, return llarp_findOrCreateEncryption(encryption_keyfile, _encryption);
_encryption);
} }
void void
@ -504,7 +499,7 @@ namespace llarp
Router::SaveRC() Router::SaveRC()
{ {
LogDebug("verify RC signature"); LogDebug("verify RC signature");
if(!_rc.Verify(crypto(), Now())) if(!_rc.Verify(Now()))
{ {
Dump< MAX_RC_SIZE >(rc()); Dump< MAX_RC_SIZE >(rc());
LogError("RC is invalid, not saving"); LogError("RC is invalid, not saving");
@ -632,7 +627,7 @@ namespace llarp
const auto numConnected = NumberOfConnectedRouters(); const auto numConnected = NumberOfConnectedRouters();
for(const auto &rc : results) for(const auto &rc : results)
{ {
if(!rc.Verify(crypto(), Now())) if(!rc.Verify(Now()))
continue; continue;
nodedb()->InsertAsync(rc); nodedb()->InsertAsync(rc);
@ -760,7 +755,7 @@ namespace llarp
RouterContact nextRC = _rc; RouterContact nextRC = _rc;
if(rotateKeys) if(rotateKeys)
{ {
crypto()->encryption_keygen(nextOnionKey); CryptoManager::instance()->encryption_keygen(nextOnionKey);
std::string f = encryption_keyfile.string(); std::string f = encryption_keyfile.string();
// TODO: use disk worker // TODO: use disk worker
if(nextOnionKey.SaveToFile(f.c_str())) if(nextOnionKey.SaveToFile(f.c_str()))
@ -770,7 +765,7 @@ namespace llarp
} }
} }
nextRC.last_updated = Now(); nextRC.last_updated = Now();
if(!nextRC.Sign(crypto(), identity())) if(!nextRC.Sign(identity()))
return false; return false;
_rc = nextRC; _rc = nextRC;
// propagate RC by renegotiating sessions // propagate RC by renegotiating sessions
@ -1025,7 +1020,7 @@ namespace llarp
; ;
return; return;
} }
if(rc.Verify(crypto(), Now())) if(rc.Verify(Now()))
{ {
const auto result = bootstrapRCList.insert(rc); const auto result = bootstrapRCList.insert(rc);
if(result.second) if(result.second)
@ -1339,7 +1334,7 @@ namespace llarp
Router::Sign(Signature &sig, const llarp_buffer_t &buf) const Router::Sign(Signature &sig, const llarp_buffer_t &buf) const
{ {
METRICS_TIME_BLOCK("Router", "Sign"); METRICS_TIME_BLOCK("Router", "Sign");
return crypto()->sign(sig, identity(), buf); return CryptoManager::instance()->sign(sig, identity(), buf);
} }
void void
@ -1620,7 +1615,7 @@ namespace llarp
_rc.enckey = seckey_topublic(encryption()); _rc.enckey = seckey_topublic(encryption());
LogInfo("Signing rc..."); LogInfo("Signing rc...");
if(!_rc.Sign(crypto(), identity())) if(!_rc.Sign(identity()))
{ {
LogError("failed to sign rc"); LogError("failed to sign rc");
return false; return false;
@ -1678,11 +1673,11 @@ namespace llarp
maxConnectedRouters = minConnectedRouters + 1; maxConnectedRouters = minConnectedRouters + 1;
// we are a client // we are a client
// regenerate keys and resign rc before everything else // regenerate keys and resign rc before everything else
crypto()->identity_keygen(_identity); CryptoManager::instance()->identity_keygen(_identity);
crypto()->encryption_keygen(_encryption); CryptoManager::instance()->encryption_keygen(_encryption);
_rc.pubkey = seckey_topublic(identity()); _rc.pubkey = seckey_topublic(identity());
_rc.enckey = seckey_topublic(encryption()); _rc.enckey = seckey_topublic(encryption());
if(!_rc.Sign(crypto(), identity())) if(!_rc.Sign(identity()))
{ {
LogError("failed to regenerate keys and sign RC"); LogError("failed to regenerate keys and sign RC");
return false; return false;

@ -37,19 +37,17 @@
namespace llarp namespace llarp
{ {
struct Config; struct Config;
struct Crypto;
} // namespace llarp } // namespace llarp
bool bool
llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &fpath, llarp_findOrCreateEncryption(const fs::path &fpath,
llarp::SecretKey &encryption); llarp::SecretKey &encryption);
bool bool
llarp_findOrCreateIdentity(llarp::Crypto *crypto, const fs::path &path, llarp_findOrCreateIdentity(const fs::path &path, llarp::SecretKey &secretkey);
llarp::SecretKey &secretkey);
bool bool
llarp_loadServiceNodeIdentityKey(llarp::Crypto *crypto, const fs::path &fpath, llarp_loadServiceNodeIdentityKey(const fs::path &fpath,
llarp::SecretKey &secretkey); llarp::SecretKey &secretkey);
struct TryConnectJob; struct TryConnectJob;
@ -101,12 +99,6 @@ namespace llarp
util::StatusObject util::StatusObject
ExtractStatus() const override; ExtractStatus() const override;
Crypto *
crypto() const override
{
return _crypto.get();
}
llarp_nodedb * llarp_nodedb *
nodedb() const override nodedb() const override
{ {
@ -184,7 +176,6 @@ namespace llarp
llarp_ev_loop_ptr _netloop; llarp_ev_loop_ptr _netloop;
llarp_threadpool *tp; llarp_threadpool *tp;
std::shared_ptr< Logic > _logic; std::shared_ptr< Logic > _logic;
std::unique_ptr< Crypto > _crypto;
path::PathContext paths; path::PathContext paths;
exit::Context _exitContext; exit::Context _exitContext;
SecretKey _identity; SecretKey _identity;

@ -263,7 +263,7 @@ namespace llarp
} }
bool bool
RouterContact::Sign(llarp::Crypto *crypto, const SecretKey &secretkey) RouterContact::Sign(const SecretKey &secretkey)
{ {
pubkey = llarp::seckey_topublic(secretkey); pubkey = llarp::seckey_topublic(secretkey);
std::array< byte_t, MAX_RC_SIZE > tmp; std::array< byte_t, MAX_RC_SIZE > tmp;
@ -274,11 +274,11 @@ namespace llarp
return false; return false;
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
return crypto->sign(signature, secretkey, buf); return CryptoManager::instance()->sign(signature, secretkey, buf);
} }
bool bool
RouterContact::Verify(llarp::Crypto *crypto, llarp_time_t now) const RouterContact::Verify(llarp_time_t now) const
{ {
if(netID != NetID::DefaultValue()) if(netID != NetID::DefaultValue())
{ {
@ -307,7 +307,7 @@ namespace llarp
return false; return false;
} }
} }
if(!VerifySignature(crypto)) if(!VerifySignature())
{ {
llarp::LogError("invalid signature"); llarp::LogError("invalid signature");
return false; return false;
@ -316,7 +316,7 @@ namespace llarp
} }
bool bool
RouterContact::VerifySignature(llarp::Crypto *crypto) const RouterContact::VerifySignature() const
{ {
RouterContact copy; RouterContact copy;
copy = *this; copy = *this;
@ -330,7 +330,7 @@ namespace llarp
} }
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
return crypto->verify(pubkey, buf, signature); return CryptoManager::instance()->verify(pubkey, buf, signature);
} }
bool bool

@ -17,8 +17,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
/// NetID /// NetID
struct NetID final : public AlignedBuffer< 8 > struct NetID final : public AlignedBuffer< 8 >
{ {
@ -166,10 +164,10 @@ namespace llarp
SetNick(const std::string &nick); SetNick(const std::string &nick);
bool bool
Verify(llarp::Crypto *crypto, llarp_time_t now) const; Verify(llarp_time_t now) const;
bool bool
Sign(llarp::Crypto *crypto, const llarp::SecretKey &secret); Sign(const llarp::SecretKey &secret);
/// does this RC expire soon? default delta is 1 minute /// does this RC expire soon? default delta is 1 minute
bool bool
@ -195,7 +193,7 @@ namespace llarp
private: private:
bool bool
VerifySignature(llarp::Crypto *crypto) const; VerifySignature() const;
}; };
inline std::ostream & inline std::ostream &

@ -8,14 +8,13 @@ namespace llarp
{ {
namespace service namespace service
{ {
AsyncKeyExchange::AsyncKeyExchange(std::shared_ptr< Logic > l, Crypto* c, AsyncKeyExchange::AsyncKeyExchange(std::shared_ptr< Logic > l,
const ServiceInfo& r, const ServiceInfo& r,
const Identity& localident, const Identity& localident,
const PQPubKey& introsetPubKey, const PQPubKey& introsetPubKey,
const Introduction& remote, const Introduction& remote,
IDataHandler* h, const ConvoTag& t) IDataHandler* h, const ConvoTag& t)
: logic(l) : logic(l)
, crypto(c)
, remote(r) , remote(r)
, m_LocalIdentity(localident) , m_LocalIdentity(localident)
, introPubKey(introsetPubKey) , introPubKey(introsetPubKey)
@ -44,7 +43,8 @@ namespace llarp
AsyncKeyExchange* self = static_cast< AsyncKeyExchange* >(user); AsyncKeyExchange* self = static_cast< AsyncKeyExchange* >(user);
// derive ntru session key component // derive ntru session key component
SharedSecret K; 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 // randomize Nonce
self->frame.N.Randomize(); self->frame.N.Randomize();
// compure post handshake session key // compure post handshake session key
@ -52,7 +52,7 @@ namespace llarp
SharedSecret sharedSecret; SharedSecret sharedSecret;
using namespace std::placeholders; using namespace std::placeholders;
path_dh_func dh_client = 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, if(!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret,
self->remote, self->frame.N)) self->remote, self->frame.N))
{ {
@ -63,7 +63,7 @@ namespace llarp
std::copy(K.begin(), K.end(), tmp.begin()); std::copy(K.begin(), K.end(), tmp.begin());
// H (K + PKE(A, B, N)) // H (K + PKE(A, B, N))
std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32); 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 // set tag
self->msg.tag = self->tag; self->msg.tag = self->tag;
// set sender // set sender
@ -73,8 +73,7 @@ namespace llarp
// set protocol // set protocol
self->msg.proto = eProtocolTraffic; self->msg.proto = eProtocolTraffic;
// encrypt and sign // encrypt and sign
if(self->frame.EncryptAndSign(self->crypto, self->msg, K, if(self->frame.EncryptAndSign(self->msg, K, self->m_LocalIdentity))
self->m_LocalIdentity))
self->logic->queue_job({self, &Result}); self->logic->queue_job({self, &Result});
else else
{ {

@ -8,14 +8,12 @@
namespace llarp namespace llarp
{ {
class Logic; class Logic;
struct Crypto;
namespace service namespace service
{ {
struct AsyncKeyExchange struct AsyncKeyExchange
{ {
std::shared_ptr< Logic > logic; std::shared_ptr< Logic > logic;
Crypto* crypto;
SharedSecret sharedKey; SharedSecret sharedKey;
ServiceInfo remote; ServiceInfo remote;
const Identity& m_LocalIdentity; const Identity& m_LocalIdentity;
@ -28,8 +26,8 @@ namespace llarp
IDataHandler* handler; IDataHandler* handler;
ConvoTag tag; ConvoTag tag;
AsyncKeyExchange(std::shared_ptr< Logic > l, Crypto* c, AsyncKeyExchange(std::shared_ptr< Logic > l, const ServiceInfo& r,
const ServiceInfo& r, const Identity& localident, const Identity& localident,
const PQPubKey& introsetPubKey, const PQPubKey& introsetPubKey,
const Introduction& remote, IDataHandler* h, const Introduction& remote, IDataHandler* h,
const ConvoTag& t); const ConvoTag& t);

@ -159,7 +159,7 @@ namespace llarp
return; return;
} }
m_IntroSet.topic = m_Tag; 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()); LogWarn("failed to sign introset for endpoint ", Name());
return; return;
@ -347,11 +347,10 @@ namespace llarp
bool bool
Endpoint::HandleGotIntroMessage(dht::GotIntroMessage_constptr msg) Endpoint::HandleGotIntroMessage(dht::GotIntroMessage_constptr msg)
{ {
auto crypto = m_Router->crypto();
std::set< IntroSet > remote; std::set< IntroSet > remote;
for(const auto& introset : msg->I) 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) if(m_Identity.pub == introset.A && m_CurrentPublishTX == msg->T)
IntroSetPublishFail(); IntroSetPublishFail();
@ -482,10 +481,9 @@ namespace llarp
bool bool
Endpoint::LoadKeyFile() Endpoint::LoadKeyFile()
{ {
auto crypto = m_Router->crypto();
if(!m_Keyfile.empty()) if(!m_Keyfile.empty())
{ {
if(!m_Identity.EnsureKeys(m_Keyfile, crypto)) if(!m_Identity.EnsureKeys(m_Keyfile))
{ {
LogError("Can't ensure keyfile [", m_Keyfile, "]"); LogError("Can't ensure keyfile [", m_Keyfile, "]");
return false; return false;
@ -493,7 +491,7 @@ namespace llarp
} }
else else
{ {
m_Identity.RegenerateKeys(crypto); m_Identity.RegenerateKeys();
} }
return true; return true;
} }
@ -884,16 +882,15 @@ namespace llarp
if(!GetSenderFor(frame.T, si)) if(!GetSenderFor(frame.T, si))
return false; return false;
// verify source // verify source
if(!frame.Verify(crypto(), si)) if(!frame.Verify(si))
return false; return false;
// remove convotag it doesn't exist // remove convotag it doesn't exist
LogWarn("remove convotag T=", frame.T); LogWarn("remove convotag T=", frame.T);
RemoveConvoTag(frame.T); RemoveConvoTag(frame.T);
return true; return true;
} }
if(!frame.AsyncDecryptAndVerify(EndpointLogic(), crypto(), p, if(!frame.AsyncDecryptAndVerify(EndpointLogic(), p, CryptoWorker(),
CryptoWorker(), m_Identity, m_Identity, m_DataHandler))
m_DataHandler))
{ {
// send discard // send discard
ProtocolFrame f; ProtocolFrame f;
@ -901,7 +898,7 @@ namespace llarp
f.T = frame.T; f.T = frame.T;
f.F = p->intro.pathID; f.F = p->intro.pathID;
if(!f.Sign(crypto(), m_Identity)) if(!f.Sign(m_Identity))
return false; return false;
{ {
util::Lock lock(&m_SendQueueMutex); util::Lock lock(&m_SendQueueMutex);
@ -1047,7 +1044,7 @@ namespace llarp
// send downstream packets to user for snode // send downstream packets to user for snode
for(const auto& item : m_SNodeSessions) for(const auto& item : m_SNodeSessions)
item.second->FlushDownstream(); item.second->FlushDownstream();
// send downstrream traffic to user for hidden service // send downstream traffic to user for hidden service
util::Lock lock(&m_InboundTrafficQueueMutex); util::Lock lock(&m_InboundTrafficQueueMutex);
while(m_InboundTrafficQueue.size()) while(m_InboundTrafficQueue.size())
{ {
@ -1128,7 +1125,7 @@ namespace llarp
f.F = m.introReply.pathID; f.F = m.introReply.pathID;
f.S = GetSeqNoForConvo(f.T); f.S = GetSeqNoForConvo(f.T);
transfer->P = remoteIntro.pathID; 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"); LogError("failed to encrypt and sign");
return false; return false;
@ -1225,12 +1222,6 @@ namespace llarp
return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic(); return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic();
} }
Crypto*
Endpoint::crypto()
{
return m_Router->crypto();
}
llarp_threadpool* llarp_threadpool*
Endpoint::CryptoWorker() Endpoint::CryptoWorker()
{ {

@ -105,9 +105,6 @@ namespace llarp
llarp_ev_loop_ptr llarp_ev_loop_ptr
EndpointNetLoop(); EndpointNetLoop();
Crypto*
crypto();
/// crypto worker threadpool /// crypto worker threadpool
llarp_threadpool* llarp_threadpool*
CryptoWorker(); CryptoWorker();

@ -1,5 +1,6 @@
#include <service/identity.hpp> #include <service/identity.hpp>
#include <crypto/crypto.hpp>
#include <util/fs.hpp> #include <util/fs.hpp>
namespace llarp namespace llarp
@ -53,8 +54,9 @@ namespace llarp
} }
void void
Identity::RegenerateKeys(Crypto* crypto) Identity::RegenerateKeys()
{ {
auto crypto = CryptoManager::instance();
crypto->encryption_keygen(enckey); crypto->encryption_keygen(enckey);
crypto->identity_keygen(signkey); crypto->identity_keygen(signkey);
pub.Update(seckey_topublic(enckey), seckey_topublic(signkey)); pub.Update(seckey_topublic(enckey), seckey_topublic(signkey));
@ -70,13 +72,13 @@ namespace llarp
} }
bool 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 bool
Identity::EnsureKeys(const std::string& fname, Crypto* c) Identity::EnsureKeys(const std::string& fname)
{ {
std::array< byte_t, 4096 > tmp; std::array< byte_t, 4096 > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -90,7 +92,7 @@ namespace llarp
return false; return false;
} }
// regen and encode // regen and encode
RegenerateKeys(c); RegenerateKeys();
if(!BEncode(&buf)) if(!BEncode(&buf))
return false; return false;
// rewind // rewind
@ -132,7 +134,7 @@ namespace llarp
} }
bool 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) if(i.I.size() == 0)
return false; return false;
@ -152,7 +154,7 @@ namespace llarp
// rewind and resize buffer // rewind and resize buffer
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
return Sign(crypto, i.Z, buf); return Sign(i.Z, buf);
} }
} // namespace service } // namespace service
} // namespace llarp } // namespace llarp

@ -12,8 +12,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
namespace service namespace service
{ {
// private keys // private keys
@ -30,13 +28,13 @@ namespace llarp
// regenerate secret keys // regenerate secret keys
void void
RegenerateKeys(Crypto* c); RegenerateKeys();
bool bool
BEncode(llarp_buffer_t* buf) const; BEncode(llarp_buffer_t* buf) const;
bool bool
EnsureKeys(const std::string& fpath, Crypto* c); EnsureKeys(const std::string& fpath);
bool bool
KeyExchange(path_dh_func dh, SharedSecret& sharedkey, KeyExchange(path_dh_func dh, SharedSecret& sharedkey,
@ -46,10 +44,10 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf);
bool bool
SignIntroSet(IntroSet& i, Crypto* c, llarp_time_t now) const; SignIntroSet(IntroSet& i, llarp_time_t now) const;
bool bool
Sign(Crypto*, Signature& sig, const llarp_buffer_t& buf) const; Sign(Signature& sig, const llarp_buffer_t& buf) const;
}; };
inline bool inline bool

@ -13,10 +13,10 @@ namespace llarp
namespace service namespace service
{ {
bool bool
ServiceInfo::Verify(Crypto* crypto, const llarp_buffer_t& payload, ServiceInfo::Verify(const llarp_buffer_t& payload,
const Signature& sig) const const Signature& sig) const
{ {
return crypto->verify(signkey, payload, sig); return CryptoManager::instance()->verify(signkey, payload, sig);
} }
bool bool

@ -10,8 +10,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
namespace service namespace service
{ {
struct ServiceInfo struct ServiceInfo
@ -34,8 +32,7 @@ namespace llarp
} }
bool bool
Verify(Crypto* crypto, const llarp_buffer_t& payload, Verify(const llarp_buffer_t& payload, const Signature& sig) const;
const Signature& sig) const;
const PubKey& const PubKey&
EncryptionPublicKey() const EncryptionPublicKey() const

@ -114,7 +114,7 @@ namespace llarp
} }
bool 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; std::array< byte_t, MAX_INTROSET_SIZE > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
@ -128,13 +128,12 @@ namespace llarp
// rewind and resize buffer // rewind and resize buffer
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
if(!A.Verify(crypto, buf, Z)) if(!A.Verify(buf, Z))
{ {
return false; return false;
} }
// validate PoW // validate PoW
using namespace std::placeholders; if(W && !W->IsValid(now))
if(W && !W->IsValid(std::bind(&Crypto::shorthash, crypto, _1, _2), now))
{ {
return false; return false;
} }

@ -18,8 +18,6 @@
namespace llarp namespace llarp
{ {
struct Crypto;
namespace service namespace service
{ {
constexpr std::size_t MAX_INTROSET_SIZE = 4096; constexpr std::size_t MAX_INTROSET_SIZE = 4096;
@ -70,7 +68,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf);
bool bool
Verify(Crypto* crypto, llarp_time_t now) const; Verify(llarp_time_t now) const;
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;

@ -161,9 +161,8 @@ namespace llarp
} }
currentConvoTag.Randomize(); currentConvoTag.Randomize();
AsyncKeyExchange* ex = new AsyncKeyExchange( AsyncKeyExchange* ex = new AsyncKeyExchange(
m_Endpoint->RouterLogic(), m_Endpoint->crypto(), remoteIdent, m_Endpoint->RouterLogic(), remoteIdent, m_Endpoint->GetIdentity(),
m_Endpoint->GetIdentity(), currentIntroSet.K, remoteIntro, currentIntroSet.K, remoteIntro, m_DataHandler, currentConvoTag);
m_DataHandler, currentConvoTag);
ex->hook = ex->hook =
std::bind(&OutboundContext::Send, this, std::placeholders::_1, path); std::bind(&OutboundContext::Send, this, std::placeholders::_1, path);

@ -172,18 +172,17 @@ namespace llarp
} }
bool bool
ProtocolFrame::DecryptPayloadInto(Crypto* crypto, ProtocolFrame::DecryptPayloadInto(const SharedSecret& sharedkey,
const SharedSecret& sharedkey,
ProtocolMessage& msg) const ProtocolMessage& msg) const
{ {
Encrypted_t tmp = D; Encrypted_t tmp = D;
auto buf = tmp.Buffer(); auto buf = tmp.Buffer();
crypto->xchacha20(*buf, sharedkey, N); CryptoManager::instance()->xchacha20(*buf, sharedkey, N);
return bencode_decode_dict(msg, buf); return bencode_decode_dict(msg, buf);
} }
bool bool
ProtocolFrame::Sign(Crypto* crypto, const Identity& localIdent) ProtocolFrame::Sign(const Identity& localIdent)
{ {
Z.Zero(); Z.Zero();
std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp; std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp;
@ -198,11 +197,11 @@ namespace llarp
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
// sign // sign
return localIdent.Sign(crypto, Z, buf); return localIdent.Sign(Z, buf);
} }
bool bool
ProtocolFrame::EncryptAndSign(Crypto* crypto, const ProtocolMessage& msg, ProtocolFrame::EncryptAndSign(const ProtocolMessage& msg,
const SharedSecret& sessionKey, const SharedSecret& sessionKey,
const Identity& localIdent) const Identity& localIdent)
{ {
@ -218,7 +217,7 @@ namespace llarp
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
// encrypt // encrypt
crypto->xchacha20(buf, sessionKey, N); CryptoManager::instance()->xchacha20(buf, sessionKey, N);
// put encrypted buffer // put encrypted buffer
D = buf; D = buf;
// zero out signature // zero out signature
@ -235,7 +234,7 @@ namespace llarp
buf2.sz = buf2.cur - buf2.base; buf2.sz = buf2.cur - buf2.base;
buf2.cur = buf2.base; buf2.cur = buf2.base;
// sign // sign
if(!localIdent.Sign(crypto, Z, buf2)) if(!localIdent.Sign(Z, buf2))
{ {
LogError("failed to sign? wtf?!"); LogError("failed to sign? wtf?!");
return false; return false;
@ -245,7 +244,6 @@ namespace llarp
struct AsyncFrameDecrypt struct AsyncFrameDecrypt
{ {
Crypto* crypto;
std::shared_ptr< Logic > logic; std::shared_ptr< Logic > logic;
std::shared_ptr< ProtocolMessage > msg; std::shared_ptr< ProtocolMessage > msg;
const Identity& m_LocalIdentity; const Identity& m_LocalIdentity;
@ -253,12 +251,11 @@ namespace llarp
const ProtocolFrame frame; const ProtocolFrame frame;
const Introduction fromIntro; const Introduction fromIntro;
AsyncFrameDecrypt(std::shared_ptr< Logic > l, Crypto* c, AsyncFrameDecrypt(std::shared_ptr< Logic > l, const Identity& localIdent,
const Identity& localIdent, IDataHandler* h, IDataHandler* h,
const std::shared_ptr< ProtocolMessage >& m, const std::shared_ptr< ProtocolMessage >& m,
const ProtocolFrame& f, const Introduction& recvIntro) const ProtocolFrame& f, const Introduction& recvIntro)
: crypto(c) : logic(l)
, logic(l)
, msg(m) , msg(m)
, m_LocalIdentity(localIdent) , m_LocalIdentity(localIdent)
, handler(h) , handler(h)
@ -271,7 +268,7 @@ namespace llarp
Work(void* user) Work(void* user)
{ {
AsyncFrameDecrypt* self = static_cast< AsyncFrameDecrypt* >(user); AsyncFrameDecrypt* self = static_cast< AsyncFrameDecrypt* >(user);
auto crypto = self->crypto; auto crypto = CryptoManager::instance();
SharedSecret K; SharedSecret K;
SharedSecret sharedKey; SharedSecret sharedKey;
// copy // copy
@ -296,7 +293,7 @@ namespace llarp
return; return;
} }
// verify signature of outer message after we parsed the inner message // 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, LogError("intro frame has invalid signature Z=", self->frame.Z,
" from ", self->msg->sender.Addr()); " from ", self->msg->sender.Addr());
@ -319,8 +316,8 @@ namespace llarp
// PKE (A, B, N) // PKE (A, B, N)
SharedSecret sharedSecret; SharedSecret sharedSecret;
using namespace std::placeholders; using namespace std::placeholders;
path_dh_func dh_server = path_dh_func dh_server = std::bind(
std::bind(&Crypto::dh_server, self->crypto, _1, _2, _3, _4); &Crypto::dh_server, CryptoManager::instance(), _1, _2, _3, _4);
if(!self->m_LocalIdentity.KeyExchange(dh_server, sharedSecret, if(!self->m_LocalIdentity.KeyExchange(dh_server, sharedSecret,
self->msg->sender, self->frame.N)) self->msg->sender, self->frame.N))
@ -367,7 +364,7 @@ namespace llarp
bool bool
ProtocolFrame::AsyncDecryptAndVerify(std::shared_ptr< Logic > logic, ProtocolFrame::AsyncDecryptAndVerify(std::shared_ptr< Logic > logic,
Crypto* c, path::Path_ptr recvPath, path::Path_ptr recvPath,
llarp_threadpool* worker, llarp_threadpool* worker,
const Identity& localIdent, const Identity& localIdent,
IDataHandler* handler) const IDataHandler* handler) const
@ -378,8 +375,8 @@ namespace llarp
LogInfo("Got protocol frame with new convo"); LogInfo("Got protocol frame with new convo");
msg->srcPath = recvPath->RXID(); msg->srcPath = recvPath->RXID();
// we need to dh // we need to dh
auto dh = new AsyncFrameDecrypt(logic, c, localIdent, handler, msg, auto dh = new AsyncFrameDecrypt(logic, localIdent, handler, msg, *this,
*this, recvPath->intro); recvPath->intro);
llarp_threadpool_queue_job(worker, {dh, &AsyncFrameDecrypt::Work}); llarp_threadpool_queue_job(worker, {dh, &AsyncFrameDecrypt::Work});
return true; return true;
} }
@ -395,12 +392,12 @@ namespace llarp
LogError("No sender for T=", T); LogError("No sender for T=", T);
return false; return false;
} }
if(!Verify(c, si)) if(!Verify(si))
{ {
LogError("Signature failure from ", si.Addr()); LogError("Signature failure from ", si.Addr());
return false; return false;
} }
if(!DecryptPayloadInto(c, shared, *msg)) if(!DecryptPayloadInto(shared, *msg))
{ {
LogError("failed to decrypt message"); LogError("failed to decrypt message");
return false; return false;
@ -419,7 +416,7 @@ namespace llarp
} }
bool bool
ProtocolFrame::Verify(Crypto* crypto, const ServiceInfo& from) const ProtocolFrame::Verify(const ServiceInfo& from) const
{ {
ProtocolFrame copy(*this); ProtocolFrame copy(*this);
// save signature // save signature
@ -438,7 +435,7 @@ namespace llarp
buf.sz = buf.cur - buf.base; buf.sz = buf.cur - buf.base;
buf.cur = buf.base; buf.cur = buf.base;
// verify // verify
return from.Verify(crypto, buf, Z); return from.Verify(buf, Z);
} }
bool bool

@ -19,7 +19,6 @@ struct llarp_threadpool;
namespace llarp namespace llarp
{ {
struct Crypto;
class Logic; class Logic;
namespace path namespace path
@ -120,20 +119,20 @@ namespace llarp
operator=(const ProtocolFrame& other); operator=(const ProtocolFrame& other);
bool bool
EncryptAndSign(Crypto* c, const ProtocolMessage& msg, EncryptAndSign(const ProtocolMessage& msg, const SharedSecret& sharedkey,
const SharedSecret& sharedkey, const Identity& localIdent); const Identity& localIdent);
bool bool
Sign(Crypto* c, const Identity& localIdent); Sign(const Identity& localIdent);
bool bool
AsyncDecryptAndVerify(std::shared_ptr< Logic > logic, Crypto* c, AsyncDecryptAndVerify(std::shared_ptr< Logic > logic,
path::Path_ptr fromPath, llarp_threadpool* worker, path::Path_ptr fromPath, llarp_threadpool* worker,
const Identity& localIdent, const Identity& localIdent,
IDataHandler* handler) const; IDataHandler* handler) const;
bool bool
DecryptPayloadInto(Crypto* c, const SharedSecret& sharedkey, DecryptPayloadInto(const SharedSecret& sharedkey,
ProtocolMessage& into) const; ProtocolMessage& into) const;
bool bool
@ -161,7 +160,7 @@ namespace llarp
} }
bool bool
Verify(Crypto* c, const ServiceInfo& from) const; Verify(const ServiceInfo& from) const;
bool bool
HandleMessage(routing::IMessageHandler* h, HandleMessage(routing::IMessageHandler* h,

@ -55,7 +55,6 @@ namespace llarp
void void
SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t) SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t)
{ {
auto crypto = m_Endpoint->Router()->crypto();
SharedSecret shared; SharedSecret shared;
ProtocolFrame f; ProtocolFrame f;
f.N.Randomize(); f.N.Randomize();
@ -94,7 +93,7 @@ namespace llarp
m.sender = m_Endpoint->GetIdentity().pub; m.sender = m_Endpoint->GetIdentity().pub;
m.tag = f.T; m.tag = f.T;
m.PutBuffer(payload); m.PutBuffer(payload);
if(!f.EncryptAndSign(crypto, m, shared, m_Endpoint->GetIdentity())) if(!f.EncryptAndSign(m, shared, m_Endpoint->GetIdentity()))
{ {
LogError("failed to sign"); LogError("failed to sign");
return; return;

@ -140,16 +140,14 @@ namespace llarp
return 0; return 0;
} }
LinkLayer::LinkLayer(Crypto* crypto, const SecretKey& routerEncSecret, LinkLayer::LinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc,
GetRCFunc getrc, LinkMessageHandler h, LinkMessageHandler h, SignBufferFunc sign,
SignBufferFunc sign,
SessionEstablishedHandler established, SessionEstablishedHandler established,
SessionRenegotiateHandler reneg, SessionRenegotiateHandler reneg,
TimeoutHandler timeout, SessionClosedHandler closed) TimeoutHandler timeout, SessionClosedHandler closed)
: ILinkLayer(routerEncSecret, getrc, h, sign, established, reneg, : ILinkLayer(routerEncSecret, getrc, h, sign, established, reneg,
timeout, closed) timeout, closed)
{ {
_crypto = crypto;
_utp_ctx = utp_init(2); _utp_ctx = utp_init(2);
utp_context_set_userdata(_utp_ctx, this); utp_context_set_userdata(_utp_ctx, this);
utp_set_callback(_utp_ctx, UTP_SENDTO, &LinkLayer::SendTo); utp_set_callback(_utp_ctx, UTP_SENDTO, &LinkLayer::SendTo);
@ -304,7 +302,7 @@ namespace llarp
bool bool
LinkLayer::KeyGen(SecretKey& k) LinkLayer::KeyGen(SecretKey& k)
{ {
OurCrypto()->encryption_keygen(k); CryptoManager::instance()->encryption_keygen(k);
return true; return true;
} }

@ -17,7 +17,6 @@ namespace llarp
struct LinkLayer final : public ILinkLayer struct LinkLayer final : public ILinkLayer
{ {
utp_context* _utp_ctx = nullptr; utp_context* _utp_ctx = nullptr;
Crypto* _crypto = nullptr;
// low level read callback // low level read callback
static uint64 static uint64
@ -47,8 +46,8 @@ namespace llarp
OnLog(utp_callback_arguments* arg); OnLog(utp_callback_arguments* arg);
/// construct /// construct
LinkLayer(Crypto* crypto, const SecretKey& routerEncSecret, LinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc,
GetRCFunc getrc, LinkMessageHandler h, SignBufferFunc sign, LinkMessageHandler h, SignBufferFunc sign,
SessionEstablishedHandler established, SessionEstablishedHandler established,
SessionRenegotiateHandler reneg, TimeoutHandler timeout, SessionRenegotiateHandler reneg, TimeoutHandler timeout,
SessionClosedHandler closed); SessionClosedHandler closed);
@ -70,12 +69,6 @@ namespace llarp
ProcessICMP(); ProcessICMP();
#endif #endif
Crypto*
OurCrypto() override
{
return _crypto;
}
/// pump sessions /// pump sessions
void void
Pump() override; Pump() override;

@ -19,12 +19,6 @@ namespace llarp
LogDebug("link established with ", remoteAddr); LogDebug("link established with ", remoteAddr);
} }
Crypto*
Session::OurCrypto()
{
return parent->OurCrypto();
}
/// pump tx queue /// pump tx queue
void void
Session::PumpWrite() Session::PumpWrite()
@ -91,10 +85,11 @@ namespace llarp
OutboundHandshake(); OutboundHandshake();
} }
template < bool (Crypto::*dh_func)(SharedSecret&, const PubKey&,
const SecretKey&, const TunnelNonce&) >
bool bool
Session::DoKeyExchange(transport_dh_func dh, SharedSecret& K, Session::DoKeyExchange(SharedSecret& K, const KeyExchangeNonce& n,
const KeyExchangeNonce& n, const PubKey& other, const PubKey& other, const SecretKey& secret)
const SecretKey& secret)
{ {
ShortHash t_h; ShortHash t_h;
static constexpr size_t TMP_SIZE = 64; static constexpr size_t TMP_SIZE = 64;
@ -105,14 +100,14 @@ namespace llarp
std::copy(K.begin(), K.end(), tmp.begin()); std::copy(K.begin(), K.end(), tmp.begin());
std::copy(n.begin(), n.end(), tmp.begin() + K.size()); std::copy(n.begin(), n.end(), tmp.begin() + K.size());
// t_h = HS(K + L.n) // 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); LogError("failed to mix key to ", remoteAddr);
return false; return false;
} }
// K = TKE(a.p, B_a.e, sk, t_h) // 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"); LogError("key exchange with ", other, " failed");
return false; return false;
@ -130,7 +125,7 @@ namespace llarp
buf.cur += K.size(); buf.cur += K.size();
std::copy(A.begin(), A.end(), buf.cur); std::copy(A.begin(), A.end(), buf.cur);
buf.cur = buf.base; buf.cur = buf.base;
return OurCrypto()->shorthash(K, buf); return CryptoManager::instance()->shorthash(K, buf);
} }
void void
@ -312,7 +307,7 @@ namespace llarp
// build our RC // build our RC
LinkIntroMessage msg; LinkIntroMessage msg;
msg.rc = parent->GetOurRC(); 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); LogError("our RC is invalid? closing session to", remoteAddr);
Close(); Close();
@ -344,10 +339,8 @@ namespace llarp
return; return;
} }
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(), _1, if(!DoClientKeyExchange(txKey, msg.N, remoteTransportPubKey,
_2, _3, _4), parent->RouterEncryptionSecret()))
txKey, msg.N, remoteTransportPubKey,
parent->RouterEncryptionSecret()))
{ {
LogError("failed to mix keys for outbound session to ", remoteAddr); LogError("failed to mix keys for outbound session to ", remoteAddr);
Close(); Close();
@ -400,14 +393,14 @@ namespace llarp
TunnelNonce nonce(noncePtr); TunnelNonce nonce(noncePtr);
// encrypt // encrypt
if(!OurCrypto()->xchacha20(payload, txKey, nonce)) if(!CryptoManager::instance()->xchacha20(payload, txKey, nonce))
return false; return false;
payload.base = noncePtr; payload.base = noncePtr;
payload.cur = payload.base; payload.cur = payload.base;
payload.sz = FragmentBufferSize - FragmentHashSize; payload.sz = FragmentBufferSize - FragmentHashSize;
// key'd hash // key'd hash
if(!OurCrypto()->hmac(buf.data(), payload, txKey)) if(!CryptoManager::instance()->hmac(buf.data(), payload, txKey))
return false; return false;
return MutateKey(txKey, A); return MutateKey(txKey, A);
} }
@ -449,9 +442,8 @@ namespace llarp
// set remote rc // set remote rc
remoteRC = msg->rc; remoteRC = msg->rc;
// recalculate rx key // recalculate rx key
return DoKeyExchange( return DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey,
std::bind(&Crypto::transport_dh_server, OurCrypto(), _1, _2, _3, _4), parent->RouterEncryptionSecret());
rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret());
} }
bool bool
@ -475,9 +467,8 @@ namespace llarp
if(!SendMessageBuffer(buf)) if(!SendMessageBuffer(buf))
return false; return false;
// regen our tx Key // regen our tx Key
return DoKeyExchange( return DoClientKeyExchange(txKey, lim.N, remoteRC.enckey,
std::bind(&Crypto::transport_dh_client, OurCrypto(), _1, _2, _3, _4), parent->RouterEncryptionSecret());
txKey, lim.N, remoteRC.enckey, parent->RouterEncryptionSecret());
} }
bool bool
@ -488,7 +479,7 @@ namespace llarp
llarp_buffer_t hbuf(ptr + FragmentHashSize, llarp_buffer_t hbuf(ptr + FragmentHashSize,
FragmentBufferSize - FragmentHashSize); FragmentBufferSize - FragmentHashSize);
if(!OurCrypto()->hmac(digest.data(), hbuf, rxKey)) if(!CryptoManager::instance()->hmac(digest.data(), hbuf, rxKey))
{ {
LogError("keyed hash failed"); LogError("keyed hash failed");
return false; return false;
@ -508,7 +499,8 @@ namespace llarp
llarp_buffer_t out(rxFragBody); llarp_buffer_t out(rxFragBody);
// decrypt // 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); LogError("failed to decrypt message from ", remoteAddr);
return false; return false;
@ -611,7 +603,7 @@ namespace llarp
sock = s; sock = s;
remoteAddr = addr; remoteAddr = addr;
RouterID rid = p->GetOurRC().pubkey; RouterID rid = p->GetOurRC().pubkey;
OurCrypto()->shorthash(rxKey, llarp_buffer_t(rid)); CryptoManager::instance()->shorthash(rxKey, llarp_buffer_t(rid));
remoteRC.Clear(); remoteRC.Clear();
ABSL_ATTRIBUTE_UNUSED void* res = utp_set_userdata(sock, this); ABSL_ATTRIBUTE_UNUSED void* res = utp_set_userdata(sock, this);
@ -631,19 +623,18 @@ namespace llarp
if(!gotLIM) if(!gotLIM)
{ {
remoteRC = msg->rc; 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(), if(!DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey,
_1, _2, _3, _4), parent->TransportSecretKey()))
rxKey, msg->N, remoteRC.enckey,
parent->TransportSecretKey()))
return false; return false;
std::array< byte_t, LinkIntroMessage::MaxSize > tmp; std::array< byte_t, LinkIntroMessage::MaxSize > tmp;
llarp_buffer_t buf(tmp); llarp_buffer_t buf(tmp);
LinkIntroMessage replymsg; LinkIntroMessage replymsg;
replymsg.rc = parent->GetOurRC(); 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); LogError("our RC is invalid? closing session to", remoteAddr);
Close(); Close();
@ -675,10 +666,8 @@ namespace llarp
Close(); Close();
return false; return false;
} }
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(), if(!DoClientKeyExchange(txKey, replymsg.N, remoteRC.enckey,
_1, _2, _3, _4), parent->RouterEncryptionSecret()))
txKey, replymsg.N, remoteRC.enckey,
parent->RouterEncryptionSecret()))
return false; return false;
LogDebug("Sent reply LIM"); LogDebug("Sent reply LIM");
@ -701,9 +690,9 @@ namespace llarp
remoteAddr = addr; remoteAddr = addr;
RouterID rid = remoteRC.pubkey; RouterID rid = remoteRC.pubkey;
OurCrypto()->shorthash(txKey, llarp_buffer_t(rid)); CryptoManager::instance()->shorthash(txKey, llarp_buffer_t(rid));
rid = p->GetOurRC().pubkey; 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); ABSL_ATTRIBUTE_UNUSED void* res = utp_set_userdata(sock, this);
assert(res == this); assert(res == this);
@ -729,10 +718,8 @@ namespace llarp
remoteRC = msg->rc; remoteRC = msg->rc;
gotLIM = true; gotLIM = true;
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, OurCrypto(), _1, if(!DoServerKeyExchange(rxKey, msg->N, remoteRC.enckey,
_2, _3, _4), parent->RouterEncryptionSecret()))
rxKey, msg->N, remoteRC.enckey,
parent->RouterEncryptionSecret()))
{ {
Close(); Close();
return false; return false;

@ -91,9 +91,6 @@ namespace llarp
void void
OnLinkEstablished(ILinkLayer* p) override; OnLinkEstablished(ILinkLayer* p) override;
Crypto*
OurCrypto();
/// switch states /// switch states
void void
EnterState(State st); EnterState(State st);
@ -159,10 +156,27 @@ namespace llarp
OutboundHandshake(); OutboundHandshake();
// do key exchange for handshake // 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 bool
DoKeyExchange(transport_dh_func dh, SharedSecret& K, DoClientKeyExchange(SharedSecret& K, const KeyExchangeNonce& n,
const KeyExchangeNonce& n, const PubKey& other, const PubKey& other, const SecretKey& secret)
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) /// does K = HS(K + A)
bool bool

@ -10,13 +10,13 @@ namespace llarp
using namespace std::placeholders; using namespace std::placeholders;
LinkLayer_ptr LinkLayer_ptr
NewServer(Crypto* crypto, const SecretKey& routerEncSecret, GetRCFunc getrc, NewServer(const SecretKey& routerEncSecret, GetRCFunc getrc,
LinkMessageHandler h, SessionEstablishedHandler est, LinkMessageHandler h, SessionEstablishedHandler est,
SessionRenegotiateHandler reneg, SignBufferFunc sign, SessionRenegotiateHandler reneg, SignBufferFunc sign,
TimeoutHandler timeout, SessionClosedHandler closed) TimeoutHandler timeout, SessionClosedHandler closed)
{ {
return std::make_shared< LinkLayer >(crypto, routerEncSecret, getrc, h, return std::make_shared< LinkLayer >(routerEncSecret, getrc, h, sign, est,
sign, est, reneg, timeout, closed); reneg, timeout, closed);
} }
LinkLayer_ptr LinkLayer_ptr
@ -24,7 +24,7 @@ namespace llarp
{ {
using namespace std::placeholders; using namespace std::placeholders;
return NewServer( 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::HandleRecvLinkMessageBuffer, r, _1, _2),
std::bind(&AbstractRouter::OnSessionEstablished, r, _1), std::bind(&AbstractRouter::OnSessionEstablished, r, _1),
std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2), std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2),

@ -11,7 +11,7 @@ namespace llarp
namespace utp namespace utp
{ {
LinkLayer_ptr LinkLayer_ptr
NewServer(Crypto* crypto, const SecretKey& routerEncSecret, GetRCFunc getrc, NewServer(const SecretKey& routerEncSecret, GetRCFunc getrc,
LinkMessageHandler h, SessionEstablishedHandler est, LinkMessageHandler h, SessionEstablishedHandler est,
SessionRenegotiateHandler reneg, SignBufferFunc sign, SessionRenegotiateHandler reneg, SignBufferFunc sign,
TimeoutHandler timeout, SessionClosedHandler closed); TimeoutHandler timeout, SessionClosedHandler closed);

@ -13,12 +13,6 @@ namespace llarp
IdentityKeyTest() IdentityKeyTest()
{ {
} }
llarp::Crypto*
Crypto()
{
return &crypto;
}
}; };
TEST_F(IdentityKeyTest, TestSignVerify) TEST_F(IdentityKeyTest, TestSignVerify)
@ -46,12 +40,6 @@ namespace llarp
{ {
} }
llarp::Crypto*
Crypto()
{
return &crypto;
}
void void
SetUp() SetUp()
{ {
@ -63,7 +51,7 @@ namespace llarp
{ {
PQCipherBlock block; PQCipherBlock block;
SharedSecret shared, otherShared; SharedSecret shared, otherShared;
auto c = Crypto(); auto c = &crypto;
ASSERT_TRUE(keys.size() == PQ_KEYPAIRSIZE); ASSERT_TRUE(keys.size() == PQ_KEYPAIRSIZE);
ASSERT_TRUE( ASSERT_TRUE(

@ -88,8 +88,6 @@ namespace llarp
MOCK_METHOD1(ExploreNetworkVia, void(const dht::Key_t& peer)); MOCK_METHOD1(ExploreNetworkVia, void(const dht::Key_t& peer));
MOCK_CONST_METHOD0(Crypto, llarp::Crypto*());
MOCK_CONST_METHOD0(GetRouter, llarp::AbstractRouter*()); MOCK_CONST_METHOD0(GetRouter, llarp::AbstractRouter*());
MOCK_CONST_METHOD0(OurKey, const dht::Key_t&()); MOCK_CONST_METHOD0(OurKey, const dht::Key_t&());

@ -24,6 +24,7 @@ static constexpr uint64_t EXPIRY = 1548503831ull;
struct TestDhtServiceAddressLookup : public ::testing::Test struct TestDhtServiceAddressLookup : public ::testing::Test
{ {
test::MockCrypto crypto; test::MockCrypto crypto;
CryptoManager cm;
MockIntroSetHandler introsetHandler; MockIntroSetHandler introsetHandler;
dht::Key_t ourKey; dht::Key_t ourKey;
@ -37,7 +38,8 @@ struct TestDhtServiceAddressLookup : public ::testing::Test
std::unique_ptr< dht::ServiceAddressLookup > serviceAddressLookup; std::unique_ptr< dht::ServiceAddressLookup > serviceAddressLookup;
TestDhtServiceAddressLookup() TestDhtServiceAddressLookup()
: ourKey(makeBuf< dht::Key_t >(0xFF)) : cm(&crypto)
, ourKey(makeBuf< dht::Key_t >(0xFF))
, txKey(makeBuf< dht::Key_t >(0x01)) , txKey(makeBuf< dht::Key_t >(0x01))
, txId(2) , txId(2)
, txOwner(txKey, txId) , txOwner(txKey, txId)
@ -62,7 +64,6 @@ TEST_F(TestDhtServiceAddressLookup, validate)
{ {
service::IntroSet introset; service::IntroSet introset;
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false));
@ -78,7 +79,6 @@ TEST_F(TestDhtServiceAddressLookup, validate)
EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1;
// Set expectations // Set expectations
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true));
@ -97,7 +97,6 @@ TEST_F(TestDhtServiceAddressLookup, validate)
EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1;
// Set expectations // Set expectations
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true));

@ -18,6 +18,7 @@ static constexpr uint64_t EXPIRY = 1548503831ull;
struct TestDhtTagLookup : public ::testing::Test struct TestDhtTagLookup : public ::testing::Test
{ {
test::MockCrypto crypto; test::MockCrypto crypto;
CryptoManager cm;
dht::Key_t txKey; dht::Key_t txKey;
uint64_t txId; uint64_t txId;
dht::TXOwner txOwner; dht::TXOwner txOwner;
@ -28,7 +29,8 @@ struct TestDhtTagLookup : public ::testing::Test
dht::TagLookup tagLookup; dht::TagLookup tagLookup;
TestDhtTagLookup() TestDhtTagLookup()
: txKey(makeBuf< dht::Key_t >(0x01)) : cm(&crypto)
, txKey(makeBuf< dht::Key_t >(0x01))
, txId(2) , txId(2)
, txOwner(txKey, txId) , txOwner(txKey, txId)
, tag(makeBuf< service::Tag >(0x03)) , tag(makeBuf< service::Tag >(0x03))
@ -47,7 +49,6 @@ TEST_F(TestDhtTagLookup, validate)
{ {
service::IntroSet introset; service::IntroSet introset;
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(false));
@ -65,7 +66,6 @@ TEST_F(TestDhtTagLookup, validate)
EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1;
// Set expectations // Set expectations
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true));
@ -83,7 +83,6 @@ TEST_F(TestDhtTagLookup, validate)
EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1; EXPIRY + service::MAX_INTROSET_TIME_DELTA + 1;
// Set expectations // Set expectations
EXPECT_CALL(context, Crypto()).WillOnce(Return(&crypto));
EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY)); EXPECT_CALL(context, Now()).WillOnce(Return(EXPIRY));
EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true)); EXPECT_CALL(crypto, verify(_, _, _)).WillOnce(Return(true));

@ -15,11 +15,10 @@ struct LinkLayerTest : public ::testing::Test
struct Context struct Context
{ {
Context(llarp::Crypto& c) Context()
{ {
crypto = &c; llarp::CryptoManager::instance()->identity_keygen(signingKey);
crypto->identity_keygen(signingKey); llarp::CryptoManager::instance()->encryption_keygen(encryptionKey);
crypto->encryption_keygen(encryptionKey);
rc.pubkey = signingKey.toPublic(); rc.pubkey = signingKey.toPublic();
rc.enckey = encryptionKey.toPublic(); rc.enckey = encryptionKey.toPublic();
} }
@ -29,8 +28,6 @@ struct LinkLayerTest : public ::testing::Test
llarp::RouterContact rc; llarp::RouterContact rc;
llarp::Crypto* crypto;
bool gotLIM = false; bool gotLIM = false;
const llarp::RouterContact& const llarp::RouterContact&
@ -49,9 +46,9 @@ struct LinkLayerTest : public ::testing::Test
bool bool
Regen() Regen()
{ {
crypto->encryption_keygen(encryptionKey); llarp::CryptoManager::instance()->encryption_keygen(encryptionKey);
rc.enckey = llarp::seckey_topublic(encryptionKey); rc.enckey = llarp::seckey_topublic(encryptionKey);
return rc.Sign(crypto, signingKey); return rc.Sign(signingKey);
} }
std::shared_ptr< llarp::ILinkLayer > link; std::shared_ptr< llarp::ILinkLayer > link;
@ -68,7 +65,8 @@ struct LinkLayerTest : public ::testing::Test
} }
bool bool
Start(std::shared_ptr<llarp::Logic> 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) if(!link)
return false; return false;
@ -79,7 +77,7 @@ struct LinkLayerTest : public ::testing::Test
rc.addrs.emplace_back(); rc.addrs.emplace_back();
if(!link->GetOurAddressInfo(rc.addrs[0])) if(!link->GetOurAddressInfo(rc.addrs[0]))
return false; return false;
if(!rc.Sign(crypto, signingKey)) if(!rc.Sign(signingKey))
return false; return false;
return link->Start(logic); return link->Start(logic);
} }
@ -100,6 +98,7 @@ struct LinkLayerTest : public ::testing::Test
}; };
llarp::sodium::CryptoLibSodium crypto; llarp::sodium::CryptoLibSodium crypto;
llarp::CryptoManager cm;
Context Alice; Context Alice;
Context Bob; Context Bob;
@ -111,7 +110,7 @@ struct LinkLayerTest : public ::testing::Test
llarp_time_t oldRCLifetime; 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) TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
{ {
Alice.link = llarp::utp::NewServer( Alice.link = llarp::utp::NewServer(
&crypto, Alice.encryptionKey, Alice.encryptionKey,
[&]() -> const llarp::RouterContact& { return Alice.GetRC(); }, [&]() -> const llarp::RouterContact& { return Alice.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
if(Alice.gotLIM) if(Alice.gotLIM)
@ -216,7 +215,7 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
}; };
Bob.link = llarp::utp::NewServer( Bob.link = llarp::utp::NewServer(
&crypto, Bob.encryptionKey, Bob.encryptionKey,
[&]() -> const llarp::RouterContact& { return Bob.GetRC(); }, [&]() -> const llarp::RouterContact& { return Bob.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
llarp::LinkIntroMessage msg; llarp::LinkIntroMessage msg;
@ -260,7 +259,7 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
TEST_F(LinkLayerTest, TestUTPAliceConnectToBob) TEST_F(LinkLayerTest, TestUTPAliceConnectToBob)
{ {
Alice.link = llarp::utp::NewServer( Alice.link = llarp::utp::NewServer(
&crypto, Alice.encryptionKey, Alice.encryptionKey,
[&]() -> const llarp::RouterContact& { return Alice.GetRC(); }, [&]() -> const llarp::RouterContact& { return Alice.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
llarp::LinkIntroMessage lim; llarp::LinkIntroMessage lim;
@ -293,7 +292,7 @@ TEST_F(LinkLayerTest, TestUTPAliceConnectToBob)
[&](llarp::RouterID router) { ASSERT_EQ(router, Bob.GetRouterID()); }); [&](llarp::RouterID router) { ASSERT_EQ(router, Bob.GetRouterID()); });
Bob.link = llarp::utp::NewServer( Bob.link = llarp::utp::NewServer(
&crypto, Bob.encryptionKey, Bob.encryptionKey,
[&]() -> const llarp::RouterContact& { return Bob.GetRC(); }, [&]() -> const llarp::RouterContact& { return Bob.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool { [&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
llarp::LinkIntroMessage lim; llarp::LinkIntroMessage lim;

@ -11,18 +11,10 @@ class ObtainExitTest : public ::testing::Test
{ {
public: public:
llarp::sodium::CryptoLibSodium crypto; llarp::sodium::CryptoLibSodium crypto;
llarp::CryptoManager cm;
llarp::SecretKey alice; llarp::SecretKey alice;
ObtainExitTest() ObtainExitTest() : cm(&crypto)
{
}
~ObtainExitTest()
{
}
void
SetUp()
{ {
crypto.identity_keygen(alice); crypto.identity_keygen(alice);
} }
@ -34,8 +26,8 @@ TEST_F(ObtainExitTest, TestSignVerify)
msg.Z.Zero(); msg.Z.Zero();
msg.S = llarp::randint(); msg.S = llarp::randint();
msg.T = llarp::randint(); msg.T = llarp::randint();
EXPECT_TRUE(msg.Sign(&crypto, alice)); EXPECT_TRUE(msg.Sign(alice));
EXPECT_TRUE(msg.Verify(&crypto)); EXPECT_TRUE(msg.Verify());
EXPECT_TRUE(msg.I == llarp::PubKey(llarp::seckey_topublic(alice))); EXPECT_TRUE(msg.I == llarp::PubKey(llarp::seckey_topublic(alice)));
EXPECT_FALSE(msg.version != LLARP_PROTO_VERSION); EXPECT_FALSE(msg.version != LLARP_PROTO_VERSION);
EXPECT_FALSE(msg.Z.IsZero()); EXPECT_FALSE(msg.Z.IsZero());

@ -18,24 +18,19 @@ using namespace testing;
struct HiddenServiceTest : public ::testing::Test struct HiddenServiceTest : public ::testing::Test
{ {
sodium::CryptoLibSodium crypto; sodium::CryptoLibSodium crypto;
CryptoManager cm;
service::Identity ident; service::Identity ident;
HiddenServiceTest() HiddenServiceTest() : cm(&crypto)
{ {
} ident.RegenerateKeys();
ident.pub.RandomizeVanity();
llarp::Crypto* ident.pub.UpdateAddr();
Crypto()
{
return &crypto;
} }
void void
SetUp() SetUp()
{ {
ident.RegenerateKeys(Crypto());
ident.pub.RandomizeVanity();
ident.pub.UpdateAddr();
} }
}; };
@ -54,8 +49,8 @@ TEST_F(HiddenServiceTest, TestGenerateIntroSet)
intro.pathID.Randomize(); intro.pathID.Randomize();
I.I.emplace_back(std::move(intro)); I.I.emplace_back(std::move(intro));
} }
ASSERT_TRUE(ident.SignIntroSet(I, Crypto(), now)); ASSERT_TRUE(ident.SignIntroSet(I, now));
ASSERT_TRUE(I.Verify(Crypto(), now)); ASSERT_TRUE(I.Verify(now));
} }
TEST_F(HiddenServiceTest, TestAddressToFromString) TEST_F(HiddenServiceTest, TestAddressToFromString)
@ -69,6 +64,10 @@ TEST_F(HiddenServiceTest, TestAddressToFromString)
struct ServiceIdentityTest : public ::testing::Test struct ServiceIdentityTest : public ::testing::Test
{ {
test::MockCrypto crypto; test::MockCrypto crypto;
CryptoManager cm;
ServiceIdentityTest() : cm(&crypto)
{
}
}; };
template < typename Arg > template < typename Arg >
@ -95,13 +94,13 @@ TEST_F(ServiceIdentityTest, EnsureKeys)
.WillOnce(WithArg< 0 >(FillArg< PQKeyPair >(0x03))); .WillOnce(WithArg< 0 >(FillArg< PQKeyPair >(0x03)));
service::Identity identity; service::Identity identity;
ASSERT_TRUE(identity.EnsureKeys(p.string(), &crypto)); ASSERT_TRUE(identity.EnsureKeys(p.string()));
ASSERT_TRUE(fs::exists(fs::status(p))); ASSERT_TRUE(fs::exists(fs::status(p)));
// Verify what is on disk is what is what was generated // Verify what is on disk is what is what was generated
service::Identity other; service::Identity other;
// No need to set more mocks, as we shouldn't need to re-keygen // 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); ASSERT_EQ(identity, other);
} }
@ -115,7 +114,7 @@ TEST_F(ServiceIdentityTest, EnsureKeysDir)
ASSERT_TRUE(fs::create_directory(p, code)) << code; ASSERT_TRUE(fs::create_directory(p, code)) << code;
service::Identity identity; service::Identity identity;
ASSERT_FALSE(identity.EnsureKeys(p.string(), &crypto)); ASSERT_FALSE(identity.EnsureKeys(p.string()));
} }
TEST_F(ServiceIdentityTest, EnsureKeysBrokenFile) TEST_F(ServiceIdentityTest, EnsureKeysBrokenFile)
@ -132,5 +131,5 @@ TEST_F(ServiceIdentityTest, EnsureKeysBrokenFile)
file.close(); file.close();
service::Identity identity; service::Identity identity;
ASSERT_FALSE(identity.EnsureKeys(p.string(), &crypto)); ASSERT_FALSE(identity.EnsureKeys(p.string()));
} }

@ -15,27 +15,14 @@ class FrameTest : public ::testing::Test
{ {
public: public:
llarp::sodium::CryptoLibSodium crypto; llarp::sodium::CryptoLibSodium crypto;
llarp::CryptoManager cm;
SecretKey alice, bob; SecretKey alice, bob;
FrameTest() FrameTest() : cm(&crypto)
{
}
~FrameTest()
{
}
void
SetUp()
{ {
crypto.encryption_keygen(alice); crypto.encryption_keygen(alice);
crypto.encryption_keygen(bob); crypto.encryption_keygen(bob);
} }
void
TearDown()
{
}
}; };
TEST_F(FrameTest, TestFrameCrypto) TEST_F(FrameTest, TestFrameCrypto)
@ -56,9 +43,9 @@ TEST_F(FrameTest, TestFrameCrypto)
// rewind buffer // rewind buffer
buf->cur = buf->base + llarp::EncryptedFrameOverheadSize; buf->cur = buf->base + llarp::EncryptedFrameOverheadSize;
// encrypt to alice // encrypt to alice
ASSERT_TRUE(f.EncryptInPlace(alice, bob.toPublic(), &crypto)); ASSERT_TRUE(f.EncryptInPlace(alice, bob.toPublic()));
// decrypt from alice // decrypt from alice
ASSERT_TRUE(f.DecryptInPlace(bob, &crypto)); ASSERT_TRUE(f.DecryptInPlace(bob));
LRCR otherRecord; LRCR otherRecord;
ASSERT_TRUE(otherRecord.BDecode(buf)); ASSERT_TRUE(otherRecord.BDecode(buf));

@ -9,16 +9,17 @@
#include <test_util.hpp> #include <test_util.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using FindOrCreateFunc = std::function< bool(llarp::Crypto *, const fs::path &, using FindOrCreateFunc =
llarp::SecretKey &) >; std::function< bool(const fs::path &, llarp::SecretKey &) >;
struct FindOrCreate : public ::testing::TestWithParam< FindOrCreateFunc > struct FindOrCreate : public ::testing::TestWithParam< FindOrCreateFunc >
{ {
FindOrCreate() FindOrCreate() : cm(&crypto)
{ {
} }
llarp::sodium::CryptoLibSodium crypto; llarp::sodium::CryptoLibSodium crypto;
llarp::CryptoManager cm;
}; };
// Concerns // Concerns
@ -35,7 +36,7 @@ TEST_P(FindOrCreate, find_file_missing)
llarp::test::FileGuard guard(p); llarp::test::FileGuard guard(p);
ASSERT_TRUE(GetParam()(&crypto, p, key)); ASSERT_TRUE(GetParam()(p, key));
ASSERT_TRUE(fs::exists(fs::status(p))); ASSERT_TRUE(fs::exists(fs::status(p)));
ASSERT_FALSE(key.IsZero()); ASSERT_FALSE(key.IsZero());
} }
@ -53,7 +54,7 @@ TEST_P(FindOrCreate, find_file_empty)
llarp::test::FileGuard guard(p); llarp::test::FileGuard guard(p);
ASSERT_FALSE(GetParam()(&crypto, p, key)); ASSERT_FALSE(GetParam()(p, key));
// Verify we didn't delete an invalid file // Verify we didn't delete an invalid file
ASSERT_TRUE(fs::exists(fs::status(p))); ASSERT_TRUE(fs::exists(fs::status(p)));
} }
@ -72,7 +73,7 @@ TEST_P(FindOrCreate, happy_path)
llarp::test::FileGuard guard(p); llarp::test::FileGuard guard(p);
ASSERT_TRUE(GetParam()(&crypto, p, key)); ASSERT_TRUE(GetParam()(p, key));
// Verify we didn't delete the file // Verify we didn't delete the file
ASSERT_TRUE(fs::exists(fs::status(p))); ASSERT_TRUE(fs::exists(fs::status(p)));
} }

@ -11,7 +11,7 @@ struct RCTest : public ::testing::Test
using RC_t = llarp::RouterContact; using RC_t = llarp::RouterContact;
using SecKey_t = llarp::SecretKey; using SecKey_t = llarp::SecretKey;
RCTest() : oldval(llarp::NetID::DefaultValue()) RCTest() : cm(&crypto), oldval(llarp::NetID::DefaultValue())
{ {
llarp::NetID::DefaultValue() = llarp::NetID(DEF_VALUE); llarp::NetID::DefaultValue() = llarp::NetID(DEF_VALUE);
} }
@ -22,6 +22,7 @@ struct RCTest : public ::testing::Test
} }
llarp::sodium::CryptoLibSodium crypto; llarp::sodium::CryptoLibSodium crypto;
llarp::CryptoManager cm;
const llarp::NetID oldval; const llarp::NetID oldval;
}; };
@ -39,6 +40,6 @@ TEST_F(RCTest, TestSignVerify)
rc.exits.emplace_back(rc.pubkey, llarp::nuint32_t{50000}); rc.exits.emplace_back(rc.pubkey, llarp::nuint32_t{50000});
ASSERT_TRUE(rc.netID == netid); ASSERT_TRUE(rc.netID == netid);
ASSERT_TRUE(rc.netID == llarp::NetID::DefaultValue()); ASSERT_TRUE(rc.netID == llarp::NetID::DefaultValue());
ASSERT_TRUE(rc.Sign(&crypto, sign)); ASSERT_TRUE(rc.Sign(sign));
ASSERT_TRUE(rc.Verify(&crypto, llarp::time_now_ms())); ASSERT_TRUE(rc.Verify(llarp::time_now_ms()));
} }

Loading…
Cancel
Save