mirror of https://github.com/oxen-io/lokinet
crypto and message encoding
- libsodium calls streamlined and moved away from stupid typedefs - buffer handling taken away from buffer_t and towards ustrings and strings - lots of stuff deleted - team is working well - re-implementing message handling in proper link_manager methodspull/2204/head
parent
ae319091d6
commit
d9ead7d0f6
@ -1,6 +1,504 @@
|
||||
#include "crypto.hpp"
|
||||
|
||||
#include <sodium/core.h>
|
||||
#include <sodium/crypto_generichash.h>
|
||||
#include <sodium/crypto_sign.h>
|
||||
#include <sodium/crypto_scalarmult.h>
|
||||
#include <sodium/crypto_scalarmult_ed25519.h>
|
||||
#include <sodium/crypto_stream_xchacha20.h>
|
||||
#include <sodium/crypto_core_ed25519.h>
|
||||
#include <sodium/crypto_aead_xchacha20poly1305.h>
|
||||
#include <sodium/randombytes.h>
|
||||
#include <sodium/utils.h>
|
||||
#include <oxenc/endian.h>
|
||||
#include <llarp/util/mem.hpp>
|
||||
#include <llarp/util/str.hpp>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#ifdef HAVE_CRYPT
|
||||
#include <crypt.h>
|
||||
#endif
|
||||
|
||||
#include <llarp/util/str.hpp>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
Crypto* CryptoManager::m_crypto = nullptr;
|
||||
}
|
||||
static bool
|
||||
dh(llarp::SharedSecret& out,
|
||||
const PubKey& client_pk,
|
||||
const PubKey& server_pk,
|
||||
const uint8_t* themPub,
|
||||
const SecretKey& usSec)
|
||||
{
|
||||
llarp::SharedSecret shared;
|
||||
crypto_generichash_state h;
|
||||
|
||||
if (crypto_scalarmult_curve25519(shared.data(), usSec.data(), themPub))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
crypto_generichash_blake2b_init(&h, nullptr, 0U, shared.size());
|
||||
crypto_generichash_blake2b_update(&h, client_pk.data(), 32);
|
||||
crypto_generichash_blake2b_update(&h, server_pk.data(), 32);
|
||||
crypto_generichash_blake2b_update(&h, shared.data(), 32);
|
||||
crypto_generichash_blake2b_final(&h, out.data(), shared.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
dh_client_priv(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
llarp::SharedSecret dh_result;
|
||||
|
||||
if (dh(dh_result, sk.toPublic(), pk, pk.data(), sk))
|
||||
{
|
||||
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32)
|
||||
!= -1;
|
||||
}
|
||||
llarp::LogWarn("crypto::dh_client - dh failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool
|
||||
dh_server_priv(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
llarp::SharedSecret dh_result;
|
||||
if (dh(dh_result, pk, sk.toPublic(), pk.data(), sk))
|
||||
{
|
||||
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32)
|
||||
!= -1;
|
||||
}
|
||||
llarp::LogWarn("crypto::dh_server - dh failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
Crypto::Crypto()
|
||||
{
|
||||
if (sodium_init() == -1)
|
||||
{
|
||||
throw std::runtime_error("sodium_init() returned -1");
|
||||
}
|
||||
char* avx2 = std::getenv("AVX2_FORCE_DISABLE");
|
||||
if (avx2 && std::string(avx2) == "1")
|
||||
{
|
||||
ntru_init(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ntru_init(0);
|
||||
}
|
||||
int seed = 0;
|
||||
randombytes(reinterpret_cast<unsigned char*>(&seed), sizeof(seed));
|
||||
srand(seed);
|
||||
}
|
||||
|
||||
std::optional<AlignedBuffer<32>>
|
||||
Crypto::maybe_decrypt_name(std::string_view ciphertext, SymmNonce nounce, std::string_view name)
|
||||
{
|
||||
const auto payloadsize = ciphertext.size() - crypto_aead_xchacha20poly1305_ietf_ABYTES;
|
||||
if (payloadsize != 32)
|
||||
return {};
|
||||
|
||||
SharedSecret derivedKey{};
|
||||
ShortHash namehash{};
|
||||
ustring name_buf{reinterpret_cast<const uint8_t*>(name.data()), name.size()};
|
||||
|
||||
if (not shorthash(namehash, name_buf.data(), name_buf.size()))
|
||||
return {};
|
||||
if (not hmac(derivedKey.data(), name_buf.data(), derivedKey.size(), namehash))
|
||||
return {};
|
||||
AlignedBuffer<32> result{};
|
||||
if (crypto_aead_xchacha20poly1305_ietf_decrypt(
|
||||
result.data(),
|
||||
nullptr,
|
||||
nullptr,
|
||||
reinterpret_cast<const byte_t*>(ciphertext.data()),
|
||||
ciphertext.size(),
|
||||
nullptr,
|
||||
0,
|
||||
nounce.data(),
|
||||
derivedKey.data())
|
||||
== -1)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::xchacha20(uint8_t* buf, size_t size, const SharedSecret& k, const TunnelNonce& n)
|
||||
{
|
||||
return crypto_stream_xchacha20_xor(buf, buf, size, n.data(), k.data()) == 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::xchacha20_alt(
|
||||
const llarp_buffer_t& out, const llarp_buffer_t& in, const SharedSecret& k, const byte_t* n)
|
||||
{
|
||||
if (in.sz > out.sz)
|
||||
return false;
|
||||
return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) == 0;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::dh_client(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_client_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// path dh relay side
|
||||
bool
|
||||
Crypto::dh_server(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_server_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// transport dh client side
|
||||
bool
|
||||
Crypto::transport_dh_client(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_client_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// transport dh server side
|
||||
bool
|
||||
Crypto::transport_dh_server(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_server_priv(shared, pk, sk, n);
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::shorthash(ShortHash& result, uint8_t* buf, size_t size)
|
||||
{
|
||||
return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, buf, size, nullptr, 0) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::hmac(uint8_t* result, uint8_t* buf, size_t size, const SharedSecret& secret)
|
||||
{
|
||||
return crypto_generichash_blake2b(result, HMACSIZE, buf, size, secret.data(), HMACSECSIZE)
|
||||
!= -1;
|
||||
}
|
||||
|
||||
static bool
|
||||
hash(uint8_t* result, const llarp_buffer_t& buff)
|
||||
{
|
||||
return crypto_generichash_blake2b(result, HASHSIZE, buff.base, buff.sz, nullptr, 0) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::sign(Signature& sig, const SecretKey& secret, uint8_t* buf, size_t size)
|
||||
{
|
||||
return crypto_sign_detached(sig.data(), nullptr, buf, size, secret.data()) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::sign(Signature& sig, const PrivateKey& privkey, uint8_t* buf, size_t size)
|
||||
{
|
||||
PubKey pubkey;
|
||||
|
||||
privkey.toPublic(pubkey);
|
||||
|
||||
crypto_hash_sha512_state hs;
|
||||
unsigned char nonce[64];
|
||||
unsigned char hram[64];
|
||||
unsigned char mulres[32];
|
||||
|
||||
// r = H(s || M) where here s is pseudorandom bytes typically generated as
|
||||
// part of hashing the seed (i.e. [a,s] = H(k)), but for derived
|
||||
// PrivateKeys will come from a hash of the root key's s concatenated with
|
||||
// the derivation hash.
|
||||
crypto_hash_sha512_init(&hs);
|
||||
crypto_hash_sha512_update(&hs, privkey.signingHash(), 32);
|
||||
crypto_hash_sha512_update(&hs, buf, size);
|
||||
crypto_hash_sha512_final(&hs, nonce);
|
||||
crypto_core_ed25519_scalar_reduce(nonce, nonce);
|
||||
|
||||
// copy pubkey into sig to make (for now) sig = (R || A)
|
||||
memmove(sig.data() + 32, pubkey.data(), 32);
|
||||
|
||||
// R = r * B
|
||||
crypto_scalarmult_ed25519_base_noclamp(sig.data(), nonce);
|
||||
|
||||
// hram = H(R || A || M)
|
||||
crypto_hash_sha512_init(&hs);
|
||||
crypto_hash_sha512_update(&hs, sig.data(), 64);
|
||||
crypto_hash_sha512_update(&hs, buf, size);
|
||||
crypto_hash_sha512_final(&hs, hram);
|
||||
|
||||
// S = r + H(R || A || M) * s, so sig = (R || S)
|
||||
crypto_core_ed25519_scalar_reduce(hram, hram);
|
||||
crypto_core_ed25519_scalar_mul(mulres, hram, privkey.data());
|
||||
crypto_core_ed25519_scalar_add(sig.data() + 32, mulres, nonce);
|
||||
|
||||
sodium_memzero(nonce, sizeof nonce);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::verify(const PubKey& pub, uint8_t* buf, size_t size, const Signature& sig)
|
||||
{
|
||||
return crypto_sign_verify_detached(sig.data(), buf, size, pub.data()) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::verify(uint8_t* pub, uint8_t* buf, size_t size, uint8_t* sig)
|
||||
{
|
||||
return crypto_sign_verify_detached(sig, buf, size, pub) != -1;
|
||||
}
|
||||
|
||||
/// clamp a 32 byte ec point
|
||||
static void
|
||||
clamp_ed25519(byte_t* out)
|
||||
{
|
||||
out[0] &= 248;
|
||||
out[31] &= 127;
|
||||
out[31] |= 64;
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
static K
|
||||
clamp(const K& p)
|
||||
{
|
||||
K out = p;
|
||||
clamp_ed25519(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
static bool
|
||||
is_clamped(const K& key)
|
||||
{
|
||||
K other(key);
|
||||
clamp_ed25519(other.data());
|
||||
return other == key;
|
||||
}
|
||||
|
||||
constexpr static char derived_key_hash_str[161] =
|
||||
"just imagine what would happen if we all decided to understand. you "
|
||||
"can't in the and by be or then before so just face it this text hurts "
|
||||
"to read? lokinet yolo!";
|
||||
|
||||
template <typename K>
|
||||
static bool
|
||||
make_scalar(AlignedBuffer<32>& out, const K& k, uint64_t i)
|
||||
{
|
||||
// b = BLIND-STRING || k || i
|
||||
std::array<byte_t, 160 + K::SIZE + sizeof(uint64_t)> buf;
|
||||
std::copy(derived_key_hash_str, derived_key_hash_str + 160, buf.begin());
|
||||
std::copy(k.begin(), k.end(), buf.begin() + 160);
|
||||
oxenc::write_host_as_little(i, buf.data() + 160 + K::SIZE);
|
||||
// n = H(b)
|
||||
// h = make_point(n)
|
||||
ShortHash n;
|
||||
return -1
|
||||
!= crypto_generichash_blake2b(n.data(), ShortHash::SIZE, buf.data(), buf.size(), nullptr, 0)
|
||||
&& -1 != crypto_core_ed25519_from_uniform(out.data(), n.data());
|
||||
}
|
||||
|
||||
static AlignedBuffer<32> zero;
|
||||
|
||||
bool
|
||||
Crypto::derive_subkey(
|
||||
PubKey& out_pubkey, const PubKey& root_pubkey, uint64_t key_n, const AlignedBuffer<32>* hash)
|
||||
{
|
||||
// scalar h = H( BLIND-STRING || root_pubkey || key_n )
|
||||
AlignedBuffer<32> h;
|
||||
if (hash)
|
||||
h = *hash;
|
||||
else if (not make_scalar(h, root_pubkey, key_n))
|
||||
{
|
||||
LogError("cannot make scalar");
|
||||
return false;
|
||||
}
|
||||
|
||||
return 0 == crypto_scalarmult_ed25519(out_pubkey.data(), h.data(), root_pubkey.data());
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::derive_subkey_private(
|
||||
PrivateKey& out_key, const SecretKey& root_key, uint64_t key_n, const AlignedBuffer<32>* hash)
|
||||
{
|
||||
// Derives a private subkey from a root key.
|
||||
//
|
||||
// The basic idea is:
|
||||
//
|
||||
// h = H( BLIND-STRING || A || key_n )
|
||||
// a - private key
|
||||
// A = aB - public key
|
||||
// s - signing hash
|
||||
// a' = ah - derived private key
|
||||
// A' = a'B = (ah)B - derived public key
|
||||
// s' = H(h || s) - derived signing hash
|
||||
//
|
||||
// libsodium throws some wrenches in the mechanics which are a nuisance,
|
||||
// the biggest of which is that sodium's secret key is *not* `a`; rather
|
||||
// it is the seed. If you want to get the private key (i.e. "a"), you
|
||||
// need to SHA-512 hash it and then clamp that.
|
||||
//
|
||||
// This also makes signature verification harder: we can't just use
|
||||
// sodium's sign function because it wants to be given the seed rather
|
||||
// than the private key, and moreover we can't actually *get* the seed to
|
||||
// make libsodium happy because we only have `ah` above; thus we
|
||||
// reimplemented most of sodium's detached signing function but without
|
||||
// the hash step.
|
||||
//
|
||||
// Lastly, for the signing hash s', we need some value that is both
|
||||
// different from the root s but also unknowable from the public key
|
||||
// (since otherwise `r` in the signing function would be known), so we
|
||||
// generate it from a hash of `h` and the root key's (psuedorandom)
|
||||
// signing hash, `s`.
|
||||
//
|
||||
const auto root_pubkey = root_key.toPublic();
|
||||
|
||||
AlignedBuffer<32> h;
|
||||
if (hash)
|
||||
h = *hash;
|
||||
else if (not make_scalar(h, root_pubkey, key_n))
|
||||
{
|
||||
LogError("cannot make scalar");
|
||||
return false;
|
||||
}
|
||||
|
||||
h[0] &= 248;
|
||||
h[31] &= 63;
|
||||
h[31] |= 64;
|
||||
|
||||
PrivateKey a;
|
||||
if (!root_key.toPrivate(a))
|
||||
return false;
|
||||
|
||||
// a' = ha
|
||||
crypto_core_ed25519_scalar_mul(out_key.data(), h.data(), a.data());
|
||||
|
||||
// s' = H(h || s)
|
||||
std::array<byte_t, 64> buf;
|
||||
std::copy(h.begin(), h.end(), buf.begin());
|
||||
std::copy(a.signingHash(), a.signingHash() + 32, buf.begin() + 32);
|
||||
return -1
|
||||
!= crypto_generichash_blake2b(
|
||||
out_key.signingHash(), 32, buf.data(), buf.size(), nullptr, 0);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::seed_to_secretkey(llarp::SecretKey& secret, const llarp::IdentitySecret& seed)
|
||||
{
|
||||
return crypto_sign_ed25519_seed_keypair(secret.data() + 32, secret.data(), seed.data()) != -1;
|
||||
}
|
||||
void
|
||||
Crypto::randomize(const llarp_buffer_t& buff)
|
||||
{
|
||||
randombytes((unsigned char*)buff.base, buff.sz);
|
||||
}
|
||||
|
||||
void
|
||||
Crypto::randbytes(byte_t* ptr, size_t sz)
|
||||
{
|
||||
randombytes((unsigned char*)ptr, sz);
|
||||
}
|
||||
|
||||
void
|
||||
Crypto::identity_keygen(llarp::SecretKey& keys)
|
||||
{
|
||||
PubKey pk;
|
||||
int result = crypto_sign_keypair(pk.data(), keys.data());
|
||||
assert(result != -1);
|
||||
const PubKey sk_pk = keys.toPublic();
|
||||
assert(pk == sk_pk);
|
||||
(void)result;
|
||||
(void)sk_pk;
|
||||
|
||||
// encryption_keygen(keys);
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::check_identity_privkey(const llarp::SecretKey& keys)
|
||||
{
|
||||
AlignedBuffer<crypto_sign_SEEDBYTES> seed;
|
||||
llarp::PubKey pk;
|
||||
llarp::SecretKey sk;
|
||||
if (crypto_sign_ed25519_sk_to_seed(seed.data(), keys.data()) == -1)
|
||||
return false;
|
||||
if (crypto_sign_seed_keypair(pk.data(), sk.data(), seed.data()) == -1)
|
||||
return false;
|
||||
return keys.toPublic() == pk && sk == keys;
|
||||
}
|
||||
|
||||
void
|
||||
Crypto::encryption_keygen(llarp::SecretKey& keys)
|
||||
{
|
||||
auto d = keys.data();
|
||||
randbytes(d, 32);
|
||||
crypto_scalarmult_curve25519_base(d + 32, d);
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::pqe_encrypt(PQCipherBlock& ciphertext, SharedSecret& sharedkey, const PQPubKey& pubkey)
|
||||
{
|
||||
return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) != -1;
|
||||
}
|
||||
bool
|
||||
Crypto::pqe_decrypt(
|
||||
const PQCipherBlock& ciphertext, SharedSecret& sharedkey, const byte_t* secretkey)
|
||||
{
|
||||
return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) != -1;
|
||||
}
|
||||
|
||||
void
|
||||
Crypto::pqe_keygen(PQKeyPair& keypair)
|
||||
{
|
||||
auto d = keypair.data();
|
||||
crypto_kem_keypair(d + PQ_SECRETKEYSIZE, d);
|
||||
}
|
||||
|
||||
bool
|
||||
Crypto::check_passwd_hash(std::string pwhash, std::string challenge)
|
||||
{
|
||||
(void)pwhash;
|
||||
(void)challenge;
|
||||
bool ret = false;
|
||||
#ifdef HAVE_CRYPT
|
||||
auto pos = pwhash.find_last_of('$');
|
||||
auto settings = pwhash.substr(0, pos);
|
||||
crypt_data data{};
|
||||
if (char* ptr = crypt_r(challenge.c_str(), settings.c_str(), &data))
|
||||
{
|
||||
ret = ptr == pwhash;
|
||||
}
|
||||
sodium_memzero(&data, sizeof(data));
|
||||
#endif
|
||||
return ret;
|
||||
}
|
||||
|
||||
const byte_t*
|
||||
seckey_topublic(const SecretKey& sec)
|
||||
{
|
||||
return sec.data() + 32;
|
||||
}
|
||||
|
||||
const byte_t*
|
||||
pq_keypair_to_public(const PQKeyPair& k)
|
||||
{
|
||||
return k.data() + PQ_SECRETKEYSIZE;
|
||||
}
|
||||
|
||||
const byte_t*
|
||||
pq_keypair_to_secret(const PQKeyPair& k)
|
||||
{
|
||||
return k.data();
|
||||
}
|
||||
|
||||
uint64_t
|
||||
randint()
|
||||
{
|
||||
uint64_t i;
|
||||
randombytes((byte_t*)&i, sizeof(i));
|
||||
return i;
|
||||
}
|
||||
} // namespace llarp
|
||||
|
@ -1,518 +0,0 @@
|
||||
#include "crypto_libsodium.hpp"
|
||||
#include <sodium/crypto_generichash.h>
|
||||
#include <sodium/crypto_sign.h>
|
||||
#include <sodium/crypto_scalarmult.h>
|
||||
#include <sodium/crypto_scalarmult_ed25519.h>
|
||||
#include <sodium/crypto_stream_xchacha20.h>
|
||||
#include <sodium/crypto_core_ed25519.h>
|
||||
#include <sodium/crypto_aead_xchacha20poly1305.h>
|
||||
#include <sodium/randombytes.h>
|
||||
#include <sodium/utils.h>
|
||||
#include <oxenc/endian.h>
|
||||
#include <llarp/util/mem.hpp>
|
||||
#include <llarp/util/str.hpp>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#ifdef HAVE_CRYPT
|
||||
#include <crypt.h>
|
||||
#endif
|
||||
|
||||
#include <llarp/util/str.hpp>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
extern int
|
||||
sodium_init(void);
|
||||
}
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
namespace sodium
|
||||
{
|
||||
static bool
|
||||
dh(llarp::SharedSecret& out,
|
||||
const PubKey& client_pk,
|
||||
const PubKey& server_pk,
|
||||
const uint8_t* themPub,
|
||||
const SecretKey& usSec)
|
||||
{
|
||||
llarp::SharedSecret shared;
|
||||
crypto_generichash_state h;
|
||||
|
||||
if (crypto_scalarmult_curve25519(shared.data(), usSec.data(), themPub))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
crypto_generichash_blake2b_init(&h, nullptr, 0U, shared.size());
|
||||
crypto_generichash_blake2b_update(&h, client_pk.data(), 32);
|
||||
crypto_generichash_blake2b_update(&h, server_pk.data(), 32);
|
||||
crypto_generichash_blake2b_update(&h, shared.data(), 32);
|
||||
crypto_generichash_blake2b_final(&h, out.data(), shared.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
dh_client_priv(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
llarp::SharedSecret dh_result;
|
||||
|
||||
if (dh(dh_result, sk.toPublic(), pk, pk.data(), sk))
|
||||
{
|
||||
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32)
|
||||
!= -1;
|
||||
}
|
||||
llarp::LogWarn("crypto::dh_client - dh failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool
|
||||
dh_server_priv(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
llarp::SharedSecret dh_result;
|
||||
if (dh(dh_result, pk, sk.toPublic(), pk.data(), sk))
|
||||
{
|
||||
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32)
|
||||
!= -1;
|
||||
}
|
||||
llarp::LogWarn("crypto::dh_server - dh failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
CryptoLibSodium::CryptoLibSodium()
|
||||
{
|
||||
if (sodium_init() == -1)
|
||||
{
|
||||
throw std::runtime_error("sodium_init() returned -1");
|
||||
}
|
||||
char* avx2 = std::getenv("AVX2_FORCE_DISABLE");
|
||||
if (avx2 && std::string(avx2) == "1")
|
||||
{
|
||||
ntru_init(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ntru_init(0);
|
||||
}
|
||||
int seed = 0;
|
||||
randombytes(reinterpret_cast<unsigned char*>(&seed), sizeof(seed));
|
||||
srand(seed);
|
||||
}
|
||||
|
||||
std::optional<AlignedBuffer<32>>
|
||||
CryptoLibSodium::maybe_decrypt_name(
|
||||
std::string_view ciphertext, SymmNonce nounce, std::string_view name)
|
||||
{
|
||||
const auto payloadsize = ciphertext.size() - crypto_aead_xchacha20poly1305_ietf_ABYTES;
|
||||
if (payloadsize != 32)
|
||||
return {};
|
||||
|
||||
SharedSecret derivedKey{};
|
||||
ShortHash namehash{};
|
||||
const llarp_buffer_t namebuf(reinterpret_cast<const char*>(name.data()), name.size());
|
||||
if (not shorthash(namehash, namebuf))
|
||||
return {};
|
||||
if (not hmac(derivedKey.data(), namebuf, namehash))
|
||||
return {};
|
||||
AlignedBuffer<32> result{};
|
||||
if (crypto_aead_xchacha20poly1305_ietf_decrypt(
|
||||
result.data(),
|
||||
nullptr,
|
||||
nullptr,
|
||||
reinterpret_cast<const byte_t*>(ciphertext.data()),
|
||||
ciphertext.size(),
|
||||
nullptr,
|
||||
0,
|
||||
nounce.data(),
|
||||
derivedKey.data())
|
||||
== -1)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::xchacha20(
|
||||
const llarp_buffer_t& buff, const SharedSecret& k, const TunnelNonce& n)
|
||||
{
|
||||
return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, n.data(), k.data()) == 0;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::xchacha20_alt(
|
||||
const llarp_buffer_t& out, const llarp_buffer_t& in, const SharedSecret& k, const byte_t* n)
|
||||
{
|
||||
if (in.sz > out.sz)
|
||||
return false;
|
||||
return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) == 0;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::dh_client(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_client_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// path dh relay side
|
||||
bool
|
||||
CryptoLibSodium::dh_server(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_server_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// transport dh client side
|
||||
bool
|
||||
CryptoLibSodium::transport_dh_client(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_client_priv(shared, pk, sk, n);
|
||||
}
|
||||
/// transport dh server side
|
||||
bool
|
||||
CryptoLibSodium::transport_dh_server(
|
||||
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n)
|
||||
{
|
||||
return dh_server_priv(shared, pk, sk, n);
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::shorthash(ShortHash& result, const llarp_buffer_t& buff)
|
||||
{
|
||||
return crypto_generichash_blake2b(
|
||||
result.data(), ShortHash::SIZE, buff.base, buff.sz, nullptr, 0)
|
||||
!= -1;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::hmac(byte_t* result, const llarp_buffer_t& buff, const SharedSecret& secret)
|
||||
{
|
||||
return crypto_generichash_blake2b(
|
||||
result, HMACSIZE, buff.base, buff.sz, secret.data(), HMACSECSIZE)
|
||||
!= -1;
|
||||
}
|
||||
|
||||
static bool
|
||||
hash(uint8_t* result, const llarp_buffer_t& buff)
|
||||
{
|
||||
return crypto_generichash_blake2b(result, HASHSIZE, buff.base, buff.sz, nullptr, 0) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::sign(Signature& sig, const SecretKey& secret, const llarp_buffer_t& buf)
|
||||
{
|
||||
return crypto_sign_detached(sig.data(), nullptr, buf.base, buf.sz, secret.data()) != -1;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::sign(Signature& sig, const PrivateKey& privkey, const llarp_buffer_t& buf)
|
||||
{
|
||||
PubKey pubkey;
|
||||
|
||||
privkey.toPublic(pubkey);
|
||||
|
||||
crypto_hash_sha512_state hs;
|
||||
unsigned char nonce[64];
|
||||
unsigned char hram[64];
|
||||
unsigned char mulres[32];
|
||||
|
||||
// r = H(s || M) where here s is pseudorandom bytes typically generated as
|
||||
// part of hashing the seed (i.e. [a,s] = H(k)), but for derived
|
||||
// PrivateKeys will come from a hash of the root key's s concatenated with
|
||||
// the derivation hash.
|
||||
crypto_hash_sha512_init(&hs);
|
||||
crypto_hash_sha512_update(&hs, privkey.signingHash(), 32);
|
||||
crypto_hash_sha512_update(&hs, buf.base, buf.sz);
|
||||
crypto_hash_sha512_final(&hs, nonce);
|
||||
crypto_core_ed25519_scalar_reduce(nonce, nonce);
|
||||
|
||||
// copy pubkey into sig to make (for now) sig = (R || A)
|
||||
memmove(sig.data() + 32, pubkey.data(), 32);
|
||||
|
||||
// R = r * B
|
||||
crypto_scalarmult_ed25519_base_noclamp(sig.data(), nonce);
|
||||
|
||||
// hram = H(R || A || M)
|
||||
crypto_hash_sha512_init(&hs);
|
||||
crypto_hash_sha512_update(&hs, sig.data(), 64);
|
||||
crypto_hash_sha512_update(&hs, buf.base, buf.sz);
|
||||
crypto_hash_sha512_final(&hs, hram);
|
||||
|
||||
// S = r + H(R || A || M) * s, so sig = (R || S)
|
||||
crypto_core_ed25519_scalar_reduce(hram, hram);
|
||||
crypto_core_ed25519_scalar_mul(mulres, hram, privkey.data());
|
||||
crypto_core_ed25519_scalar_add(sig.data() + 32, mulres, nonce);
|
||||
|
||||
sodium_memzero(nonce, sizeof nonce);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::verify(const PubKey& pub, const llarp_buffer_t& buf, const Signature& sig)
|
||||
{
|
||||
return crypto_sign_verify_detached(sig.data(), buf.base, buf.sz, pub.data()) != -1;
|
||||
}
|
||||
|
||||
/// clamp a 32 byte ec point
|
||||
static void
|
||||
clamp_ed25519(byte_t* out)
|
||||
{
|
||||
out[0] &= 248;
|
||||
out[31] &= 127;
|
||||
out[31] |= 64;
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
static K
|
||||
clamp(const K& p)
|
||||
{
|
||||
K out = p;
|
||||
clamp_ed25519(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
template <typename K>
|
||||
static bool
|
||||
is_clamped(const K& key)
|
||||
{
|
||||
K other(key);
|
||||
clamp_ed25519(other.data());
|
||||
return other == key;
|
||||
}
|
||||
|
||||
constexpr static char derived_key_hash_str[161] =
|
||||
"just imagine what would happen if we all decided to understand. you "
|
||||
"can't in the and by be or then before so just face it this text hurts "
|
||||
"to read? lokinet yolo!";
|
||||
|
||||
template <typename K>
|
||||
static bool
|
||||
make_scalar(AlignedBuffer<32>& out, const K& k, uint64_t i)
|
||||
{
|
||||
// b = BLIND-STRING || k || i
|
||||
std::array<byte_t, 160 + K::SIZE + sizeof(uint64_t)> buf;
|
||||
std::copy(derived_key_hash_str, derived_key_hash_str + 160, buf.begin());
|
||||
std::copy(k.begin(), k.end(), buf.begin() + 160);
|
||||
oxenc::write_host_as_little(i, buf.data() + 160 + K::SIZE);
|
||||
// n = H(b)
|
||||
// h = make_point(n)
|
||||
ShortHash n;
|
||||
return -1
|
||||
!= crypto_generichash_blake2b(
|
||||
n.data(), ShortHash::SIZE, buf.data(), buf.size(), nullptr, 0)
|
||||
&& -1 != crypto_core_ed25519_from_uniform(out.data(), n.data());
|
||||
}
|
||||
|
||||
static AlignedBuffer<32> zero;
|
||||
|
||||
bool
|
||||
CryptoLibSodium::derive_subkey(
|
||||
PubKey& out_pubkey,
|
||||
const PubKey& root_pubkey,
|
||||
uint64_t key_n,
|
||||
const AlignedBuffer<32>* hash)
|
||||
{
|
||||
// scalar h = H( BLIND-STRING || root_pubkey || key_n )
|
||||
AlignedBuffer<32> h;
|
||||
if (hash)
|
||||
h = *hash;
|
||||
else if (not make_scalar(h, root_pubkey, key_n))
|
||||
{
|
||||
LogError("cannot make scalar");
|
||||
return false;
|
||||
}
|
||||
|
||||
return 0 == crypto_scalarmult_ed25519(out_pubkey.data(), h.data(), root_pubkey.data());
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::derive_subkey_private(
|
||||
PrivateKey& out_key,
|
||||
const SecretKey& root_key,
|
||||
uint64_t key_n,
|
||||
const AlignedBuffer<32>* hash)
|
||||
{
|
||||
// Derives a private subkey from a root key.
|
||||
//
|
||||
// The basic idea is:
|
||||
//
|
||||
// h = H( BLIND-STRING || A || key_n )
|
||||
// a - private key
|
||||
// A = aB - public key
|
||||
// s - signing hash
|
||||
// a' = ah - derived private key
|
||||
// A' = a'B = (ah)B - derived public key
|
||||
// s' = H(h || s) - derived signing hash
|
||||
//
|
||||
// libsodium throws some wrenches in the mechanics which are a nuisance,
|
||||
// the biggest of which is that sodium's secret key is *not* `a`; rather
|
||||
// it is the seed. If you want to get the private key (i.e. "a"), you
|
||||
// need to SHA-512 hash it and then clamp that.
|
||||
//
|
||||
// This also makes signature verification harder: we can't just use
|
||||
// sodium's sign function because it wants to be given the seed rather
|
||||
// than the private key, and moreover we can't actually *get* the seed to
|
||||
// make libsodium happy because we only have `ah` above; thus we
|
||||
// reimplemented most of sodium's detached signing function but without
|
||||
// the hash step.
|
||||
//
|
||||
// Lastly, for the signing hash s', we need some value that is both
|
||||
// different from the root s but also unknowable from the public key
|
||||
// (since otherwise `r` in the signing function would be known), so we
|
||||
// generate it from a hash of `h` and the root key's (psuedorandom)
|
||||
// signing hash, `s`.
|
||||
//
|
||||
const auto root_pubkey = root_key.toPublic();
|
||||
|
||||
AlignedBuffer<32> h;
|
||||
if (hash)
|
||||
h = *hash;
|
||||
else if (not make_scalar(h, root_pubkey, key_n))
|
||||
{
|
||||
LogError("cannot make scalar");
|
||||
return false;
|
||||
}
|
||||
|
||||
h[0] &= 248;
|
||||
h[31] &= 63;
|
||||
h[31] |= 64;
|
||||
|
||||
PrivateKey a;
|
||||
if (!root_key.toPrivate(a))
|
||||
return false;
|
||||
|
||||
// a' = ha
|
||||
crypto_core_ed25519_scalar_mul(out_key.data(), h.data(), a.data());
|
||||
|
||||
// s' = H(h || s)
|
||||
std::array<byte_t, 64> buf;
|
||||
std::copy(h.begin(), h.end(), buf.begin());
|
||||
std::copy(a.signingHash(), a.signingHash() + 32, buf.begin() + 32);
|
||||
return -1
|
||||
!= crypto_generichash_blake2b(
|
||||
out_key.signingHash(), 32, buf.data(), buf.size(), nullptr, 0);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::seed_to_secretkey(llarp::SecretKey& secret, const llarp::IdentitySecret& seed)
|
||||
{
|
||||
return crypto_sign_ed25519_seed_keypair(secret.data() + 32, secret.data(), seed.data()) != -1;
|
||||
}
|
||||
void
|
||||
CryptoLibSodium::randomize(const llarp_buffer_t& buff)
|
||||
{
|
||||
randombytes((unsigned char*)buff.base, buff.sz);
|
||||
}
|
||||
|
||||
void
|
||||
CryptoLibSodium::randbytes(byte_t* ptr, size_t sz)
|
||||
{
|
||||
randombytes((unsigned char*)ptr, sz);
|
||||
}
|
||||
|
||||
void
|
||||
CryptoLibSodium::identity_keygen(llarp::SecretKey& keys)
|
||||
{
|
||||
PubKey pk;
|
||||
int result = crypto_sign_keypair(pk.data(), keys.data());
|
||||
assert(result != -1);
|
||||
const PubKey sk_pk = keys.toPublic();
|
||||
assert(pk == sk_pk);
|
||||
(void)result;
|
||||
(void)sk_pk;
|
||||
|
||||
// encryption_keygen(keys);
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::check_identity_privkey(const llarp::SecretKey& keys)
|
||||
{
|
||||
AlignedBuffer<crypto_sign_SEEDBYTES> seed;
|
||||
llarp::PubKey pk;
|
||||
llarp::SecretKey sk;
|
||||
if (crypto_sign_ed25519_sk_to_seed(seed.data(), keys.data()) == -1)
|
||||
return false;
|
||||
if (crypto_sign_seed_keypair(pk.data(), sk.data(), seed.data()) == -1)
|
||||
return false;
|
||||
return keys.toPublic() == pk && sk == keys;
|
||||
}
|
||||
|
||||
void
|
||||
CryptoLibSodium::encryption_keygen(llarp::SecretKey& keys)
|
||||
{
|
||||
auto d = keys.data();
|
||||
randbytes(d, 32);
|
||||
crypto_scalarmult_curve25519_base(d + 32, d);
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::pqe_encrypt(
|
||||
PQCipherBlock& ciphertext, SharedSecret& sharedkey, const PQPubKey& pubkey)
|
||||
{
|
||||
return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) != -1;
|
||||
}
|
||||
bool
|
||||
CryptoLibSodium::pqe_decrypt(
|
||||
const PQCipherBlock& ciphertext, SharedSecret& sharedkey, const byte_t* secretkey)
|
||||
{
|
||||
return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) != -1;
|
||||
}
|
||||
|
||||
void
|
||||
CryptoLibSodium::pqe_keygen(PQKeyPair& keypair)
|
||||
{
|
||||
auto d = keypair.data();
|
||||
crypto_kem_keypair(d + PQ_SECRETKEYSIZE, d);
|
||||
}
|
||||
|
||||
bool
|
||||
CryptoLibSodium::check_passwd_hash(std::string pwhash, std::string challenge)
|
||||
{
|
||||
(void)pwhash;
|
||||
(void)challenge;
|
||||
bool ret = false;
|
||||
#ifdef HAVE_CRYPT
|
||||
auto pos = pwhash.find_last_of('$');
|
||||
auto settings = pwhash.substr(0, pos);
|
||||
crypt_data data{};
|
||||
if (char* ptr = crypt_r(challenge.c_str(), settings.c_str(), &data))
|
||||
{
|
||||
ret = ptr == pwhash;
|
||||
}
|
||||
sodium_memzero(&data, sizeof(data));
|
||||
#endif
|
||||
return ret;
|
||||
}
|
||||
} // namespace sodium
|
||||
|
||||
const byte_t*
|
||||
seckey_topublic(const SecretKey& sec)
|
||||
{
|
||||
return sec.data() + 32;
|
||||
}
|
||||
|
||||
const byte_t*
|
||||
pq_keypair_to_public(const PQKeyPair& k)
|
||||
{
|
||||
return k.data() + PQ_SECRETKEYSIZE;
|
||||
}
|
||||
|
||||
const byte_t*
|
||||
pq_keypair_to_secret(const PQKeyPair& k)
|
||||
{
|
||||
return k.data();
|
||||
}
|
||||
|
||||
uint64_t
|
||||
randint()
|
||||
{
|
||||
uint64_t i;
|
||||
randombytes((byte_t*)&i, sizeof(i));
|
||||
return i;
|
||||
}
|
||||
|
||||
} // namespace llarp
|
@ -1,113 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "crypto.hpp"
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
namespace sodium
|
||||
{
|
||||
struct CryptoLibSodium final : public Crypto
|
||||
{
|
||||
CryptoLibSodium();
|
||||
|
||||
~CryptoLibSodium() override = default;
|
||||
|
||||
/// decrypt cipherText given the key generated from name
|
||||
std::optional<AlignedBuffer<32>>
|
||||
maybe_decrypt_name(
|
||||
std::string_view ciphertext, SymmNonce nounce, std::string_view name) override;
|
||||
|
||||
/// xchacha symmetric cipher
|
||||
bool
|
||||
xchacha20(const llarp_buffer_t&, const SharedSecret&, const TunnelNonce&) override;
|
||||
|
||||
/// xchacha symmetric cipher (multibuffer)
|
||||
bool
|
||||
xchacha20_alt(
|
||||
const llarp_buffer_t&,
|
||||
const llarp_buffer_t&,
|
||||
const SharedSecret&,
|
||||
const byte_t*) override;
|
||||
|
||||
/// path dh creator's side
|
||||
bool
|
||||
dh_client(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override;
|
||||
/// path dh relay side
|
||||
bool
|
||||
dh_server(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override;
|
||||
/// transport dh client side
|
||||
bool
|
||||
transport_dh_client(
|
||||
SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override;
|
||||
/// transport dh server side
|
||||
bool
|
||||
transport_dh_server(
|
||||
SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override;
|
||||
/// blake2b 256 bit
|
||||
bool
|
||||
shorthash(ShortHash&, const llarp_buffer_t&) override;
|
||||
/// blake2s 256 bit hmac
|
||||
bool
|
||||
hmac(byte_t*, const llarp_buffer_t&, const SharedSecret&) override;
|
||||
/// ed25519 sign
|
||||
bool
|
||||
sign(Signature&, const SecretKey&, const llarp_buffer_t&) override;
|
||||
/// ed25519 sign (custom with derived keys)
|
||||
bool
|
||||
sign(Signature&, const PrivateKey&, const llarp_buffer_t&) override;
|
||||
/// ed25519 verify
|
||||
bool
|
||||
verify(const PubKey&, const llarp_buffer_t&, const Signature&) override;
|
||||
|
||||
/// derive sub keys for public keys. hash is really only intended for
|
||||
/// testing and overrides key_n if given.
|
||||
bool
|
||||
derive_subkey(
|
||||
PubKey& derived,
|
||||
const PubKey& root,
|
||||
uint64_t key_n,
|
||||
const AlignedBuffer<32>* hash = nullptr) override;
|
||||
|
||||
/// derive sub keys for private keys. hash is really only intended for
|
||||
/// testing and overrides key_n if given.
|
||||
bool
|
||||
derive_subkey_private(
|
||||
PrivateKey& derived,
|
||||
const SecretKey& root,
|
||||
uint64_t key_n,
|
||||
const AlignedBuffer<32>* hash = nullptr) override;
|
||||
|
||||
/// seed to secretkey
|
||||
bool
|
||||
seed_to_secretkey(llarp::SecretKey&, const llarp::IdentitySecret&) override;
|
||||
/// randomize buffer
|
||||
void
|
||||
randomize(const llarp_buffer_t&) override;
|
||||
/// randomizer memory
|
||||
void
|
||||
randbytes(byte_t*, size_t) override;
|
||||
/// generate signing keypair
|
||||
void
|
||||
identity_keygen(SecretKey&) override;
|
||||
/// generate encryption keypair
|
||||
void
|
||||
encryption_keygen(SecretKey&) override;
|
||||
/// generate post quantum encrytion key
|
||||
void
|
||||
pqe_keygen(PQKeyPair&) override;
|
||||
/// post quantum decrypt (buffer, sharedkey_dst, sec)
|
||||
bool
|
||||
pqe_decrypt(const PQCipherBlock&, SharedSecret&, const byte_t*) override;
|
||||
/// post quantum encrypt (buffer, sharedkey_dst, pub)
|
||||
bool
|
||||
pqe_encrypt(PQCipherBlock&, SharedSecret&, const PQPubKey&) override;
|
||||
|
||||
bool
|
||||
check_identity_privkey(const SecretKey&) override;
|
||||
|
||||
bool
|
||||
check_passwd_hash(std::string pwhash, std::string challenge) override;
|
||||
};
|
||||
} // namespace sodium
|
||||
|
||||
} // namespace llarp
|
@ -1,211 +0,0 @@
|
||||
#ifndef LLARP_DHT_CONTEXT
|
||||
#define LLARP_DHT_CONTEXT
|
||||
|
||||
#include "bucket.hpp"
|
||||
#include "dht.h"
|
||||
#include "key.hpp"
|
||||
#include "message.hpp"
|
||||
#include <llarp/dht/messages/findintro.hpp>
|
||||
#include "node.hpp"
|
||||
#include "tx.hpp"
|
||||
#include "txholder.hpp"
|
||||
#include "txowner.hpp"
|
||||
#include <llarp/service/intro_set.hpp>
|
||||
#include <llarp/util/time.hpp>
|
||||
#include <llarp/util/status.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <set>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
struct Router;
|
||||
|
||||
namespace dht
|
||||
{
|
||||
/// number of routers to publish to
|
||||
static constexpr size_t IntroSetRelayRedundancy = 2;
|
||||
|
||||
/// number of dht locations handled per relay
|
||||
static constexpr size_t IntroSetRequestsPerRelay = 2;
|
||||
|
||||
static constexpr size_t IntroSetStorageRedundancy =
|
||||
(IntroSetRelayRedundancy * IntroSetRequestsPerRelay);
|
||||
|
||||
struct AbstractDHTMessageHandler /* : public AbstractMessageHandler */
|
||||
{
|
||||
using PendingIntrosetLookups = TXHolder<TXOwner, service::EncryptedIntroSet>;
|
||||
using PendingRouterLookups = TXHolder<RouterID, RouterContact>;
|
||||
using PendingExploreLookups = TXHolder<RouterID, RouterID>;
|
||||
|
||||
virtual ~AbstractDHTMessageHandler() = 0;
|
||||
|
||||
virtual bool
|
||||
LookupRouter(const RouterID& target, RouterLookupHandler result) = 0;
|
||||
|
||||
virtual void
|
||||
LookupRouterRecursive(
|
||||
const RouterID& target,
|
||||
const Key_t& whoasked,
|
||||
uint64_t whoaskedTX,
|
||||
const Key_t& askpeer,
|
||||
RouterLookupHandler result = nullptr) = 0;
|
||||
|
||||
/// Ask a Service Node to perform an Introset lookup for us
|
||||
virtual void
|
||||
LookupIntroSetRelayed(
|
||||
const Key_t& target,
|
||||
const Key_t& whoasked,
|
||||
uint64_t whoaskedTX,
|
||||
const Key_t& askpeer,
|
||||
uint64_t relayOrder,
|
||||
service::EncryptedIntroSetLookupHandler result =
|
||||
service::EncryptedIntroSetLookupHandler()) = 0;
|
||||
|
||||
/// Directly as a Service Node for an Introset
|
||||
virtual void
|
||||
LookupIntroSetDirect(
|
||||
const Key_t& target,
|
||||
const Key_t& whoasked,
|
||||
uint64_t whoaskedTX,
|
||||
const Key_t& askpeer,
|
||||
service::EncryptedIntroSetLookupHandler result =
|
||||
service::EncryptedIntroSetLookupHandler()) = 0;
|
||||
|
||||
virtual bool
|
||||
HasRouterLookup(const RouterID& target) const = 0;
|
||||
|
||||
/// issue dht lookup for router via askpeer and send reply to local path
|
||||
virtual void
|
||||
LookupRouterForPath(
|
||||
const RouterID& target, uint64_t txid, const PathID_t& path, const Key_t& askpeer) = 0;
|
||||
|
||||
virtual void
|
||||
LookupIntroSetForPath(
|
||||
const Key_t& addr,
|
||||
uint64_t txid,
|
||||
const PathID_t& path,
|
||||
const Key_t& askpeer,
|
||||
uint64_t relayOrder) = 0;
|
||||
|
||||
virtual void
|
||||
DHTSendTo(const RouterID& peer, AbstractDHTMessage* msg, bool keepalive = true) = 0;
|
||||
|
||||
/// get routers closest to target excluding requester
|
||||
virtual bool
|
||||
HandleExploritoryRouterLookup(
|
||||
const Key_t& requester,
|
||||
uint64_t txid,
|
||||
const RouterID& target,
|
||||
std::vector<std::unique_ptr<AbstractDHTMessage>>& reply) = 0;
|
||||
|
||||
/// handle rc lookup from requester for target
|
||||
virtual void
|
||||
LookupRouterRelayed(
|
||||
const Key_t& requester,
|
||||
uint64_t txid,
|
||||
const Key_t& target,
|
||||
bool recursive,
|
||||
std::vector<std::unique_ptr<AbstractDHTMessage>>& replies) = 0;
|
||||
|
||||
virtual bool
|
||||
RelayRequestForPath(const PathID_t& localPath, const AbstractDHTMessage& msg) = 0;
|
||||
|
||||
/// send introset to peer from source with S counter and excluding peers
|
||||
virtual void
|
||||
PropagateLocalIntroSet(
|
||||
const PathID_t& path,
|
||||
uint64_t sourceTX,
|
||||
const service::EncryptedIntroSet& introset,
|
||||
const Key_t& peer,
|
||||
uint64_t relayOrder) = 0;
|
||||
|
||||
/// send introset to peer from source with S counter and excluding peers
|
||||
virtual void
|
||||
PropagateIntroSetTo(
|
||||
const Key_t& source,
|
||||
uint64_t sourceTX,
|
||||
const service::EncryptedIntroSet& introset,
|
||||
const Key_t& peer,
|
||||
uint64_t relayOrder) = 0;
|
||||
|
||||
virtual void
|
||||
Init(const Key_t& us, Router* router) = 0;
|
||||
|
||||
virtual std::optional<llarp::service::EncryptedIntroSet>
|
||||
GetIntroSetByLocation(const Key_t& location) const = 0;
|
||||
|
||||
virtual llarp_time_t
|
||||
Now() const = 0;
|
||||
|
||||
virtual void
|
||||
ExploreNetworkVia(const Key_t& peer) = 0;
|
||||
|
||||
virtual llarp::Router*
|
||||
GetRouter() const = 0;
|
||||
|
||||
virtual bool
|
||||
GetRCFromNodeDB(const Key_t& k, llarp::RouterContact& rc) const = 0;
|
||||
|
||||
virtual const Key_t&
|
||||
OurKey() const = 0;
|
||||
|
||||
virtual PendingIntrosetLookups&
|
||||
pendingIntrosetLookups() = 0;
|
||||
|
||||
virtual const PendingIntrosetLookups&
|
||||
pendingIntrosetLookups() const = 0;
|
||||
|
||||
virtual PendingRouterLookups&
|
||||
pendingRouterLookups() = 0;
|
||||
|
||||
virtual const PendingRouterLookups&
|
||||
pendingRouterLookups() const = 0;
|
||||
|
||||
virtual PendingExploreLookups&
|
||||
pendingExploreLookups() = 0;
|
||||
|
||||
virtual const PendingExploreLookups&
|
||||
pendingExploreLookups() const = 0;
|
||||
|
||||
virtual Bucket<ISNode>*
|
||||
services() = 0;
|
||||
|
||||
virtual bool&
|
||||
AllowTransit() = 0;
|
||||
virtual const bool&
|
||||
AllowTransit() const = 0;
|
||||
|
||||
virtual Bucket<RCNode>*
|
||||
Nodes() const = 0;
|
||||
|
||||
virtual void
|
||||
PutRCNodeAsync(const RCNode& val) = 0;
|
||||
|
||||
virtual void
|
||||
DelRCNodeAsync(const Key_t& val) = 0;
|
||||
|
||||
virtual util::StatusObject
|
||||
ExtractStatus() const = 0;
|
||||
|
||||
virtual void
|
||||
StoreRC(const RouterContact rc) const = 0;
|
||||
|
||||
virtual bool
|
||||
handle_message(
|
||||
const AbstractDHTMessage&, std::vector<std::unique_ptr<dht::AbstractDHTMessage>>&) = 0;
|
||||
};
|
||||
|
||||
std::unique_ptr<AbstractDHTMessageHandler>
|
||||
make_handler();
|
||||
} // namespace dht
|
||||
} // namespace llarp
|
||||
|
||||
struct llarp_dht_context
|
||||
{
|
||||
std::unique_ptr<llarp::dht::AbstractDHTMessageHandler> impl;
|
||||
llarp::Router* parent;
|
||||
llarp_dht_context(llarp::Router* router);
|
||||
};
|
||||
|
||||
#endif
|
@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
#include <llarp/dht/message.hpp>
|
||||
#include <llarp/router_version.hpp>
|
||||
|
||||
namespace llarp::dht
|
||||
{
|
||||
struct ConsensusMessage
|
||||
{
|
||||
/// H
|
||||
ShortHash m_Hash;
|
||||
/// K
|
||||
std::vector<RouterID> m_Keys;
|
||||
/// N
|
||||
uint64_t m_NumberOfEntries;
|
||||
/// O
|
||||
uint64_t m_EntryOffset;
|
||||
/// T
|
||||
uint64_t m_TxID;
|
||||
/// U
|
||||
llarp_time_t m_NextUpdateRequired;
|
||||
/// V
|
||||
RouterVersion m_RotuerVersion;
|
||||
};
|
||||
} // namespace llarp::dht
|
@ -0,0 +1,4 @@
|
||||
#include "link_endpoints.hpp"
|
||||
|
||||
namespace llarp
|
||||
{} // namespace llarp
|
@ -0,0 +1,4 @@
|
||||
#pragma once
|
||||
|
||||
namespace llarp
|
||||
{} // namespace llarp
|
@ -1,84 +0,0 @@
|
||||
#include "dht_immediate.hpp"
|
||||
|
||||
#include <llarp/router/router.hpp>
|
||||
#include <llarp/dht/context.hpp>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
void
|
||||
DHTImmediateMessage::clear()
|
||||
{
|
||||
msgs.clear();
|
||||
version = 0;
|
||||
}
|
||||
|
||||
/** Note: this is where AbstractDHTMessage::bt_encode() is called. Contextually, this is a
|
||||
bit confusing as it is within the ::bt_encode() method of DHTImmediateMessage, which is
|
||||
not an AbstractDHTMessage, but an AbstractLinkMessage. To see why AbstractLinkMessage
|
||||
overrides the ::bt_encode() that returns an std::string, see the comment in llarp/router/
|
||||
outbound_message_handler.cpp above OutboundMessageHandler::EncodeBuffer(...).
|
||||
|
||||
In this context, there is already a bt_dict_producer being used by DHTImmediateMessage's
|
||||
bt_encode() method. This allows us to easily choose the override of bt_encode() that returns
|
||||
nothing, but takes a bt_dict_producer as a reference.
|
||||
*/
|
||||
std::string
|
||||
DHTImmediateMessage::bt_encode() const
|
||||
{
|
||||
oxenc::bt_dict_producer btdp;
|
||||
|
||||
try
|
||||
{
|
||||
btdp.append("a", "m");
|
||||
{
|
||||
auto subdict = btdp.append_dict("m");
|
||||
for (auto& m : msgs)
|
||||
m->bt_encode(subdict);
|
||||
}
|
||||
|
||||
btdp.append("v", llarp::constants::proto_version);
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
log::critical(link_cat, "Error: DHTImmediateMessage failed to bt encode contents!");
|
||||
}
|
||||
|
||||
return std::move(btdp).str();
|
||||
}
|
||||
|
||||
bool
|
||||
DHTImmediateMessage::decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf)
|
||||
{
|
||||
if (key.startswith("m"))
|
||||
return llarp::dht::DecodeMessageList(dht::Key_t(conn->remote_rc.pubkey), buf, msgs);
|
||||
if (key.startswith("v"))
|
||||
{
|
||||
if (!bencode_read_integer(buf, &version))
|
||||
return false;
|
||||
return version == llarp::constants::proto_version;
|
||||
}
|
||||
// bad key
|
||||
return false;
|
||||
}
|
||||
|
||||
bool
|
||||
DHTImmediateMessage::handle_message(Router* router) const
|
||||
{
|
||||
DHTImmediateMessage reply;
|
||||
reply.conn = conn;
|
||||
bool result = true;
|
||||
auto dht = router->dht();
|
||||
for (const auto& msg : msgs)
|
||||
{
|
||||
result &= dht->handle_message(*msg, reply.msgs);
|
||||
}
|
||||
if (reply.msgs.size())
|
||||
{
|
||||
if (result)
|
||||
{
|
||||
result = router->SendToOrQueue(conn->remote_rc.pubkey, reply);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace llarp
|
@ -1,35 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <llarp/dht/message.hpp>
|
||||
#include "link_message.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
struct DHTImmediateMessage final : public AbstractLinkMessage
|
||||
{
|
||||
DHTImmediateMessage() = default;
|
||||
~DHTImmediateMessage() override = default;
|
||||
|
||||
std::vector<std::unique_ptr<dht::AbstractDHTMessage>> msgs;
|
||||
|
||||
std::string
|
||||
bt_encode() const override;
|
||||
|
||||
bool
|
||||
decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
|
||||
|
||||
bool
|
||||
handle_message(Router* router) const override;
|
||||
|
||||
void
|
||||
clear() override;
|
||||
|
||||
const char*
|
||||
name() const override
|
||||
{
|
||||
return "DHTImmediate";
|
||||
}
|
||||
};
|
||||
} // namespace llarp
|
File diff suppressed because it is too large
Load Diff
@ -1,32 +0,0 @@
|
||||
#include "lookup.hpp"
|
||||
|
||||
#include <llarp/path/path.hpp>
|
||||
#include <llarp/util/time.hpp>
|
||||
#include <llarp/router/router.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
struct Router;
|
||||
|
||||
namespace service
|
||||
{
|
||||
IServiceLookup::IServiceLookup(
|
||||
ILookupHolder* p, uint64_t tx, std::string n, llarp_time_t timeout)
|
||||
: m_parent(p), txid(tx), name(std::move(n)), m_created{time_now_ms()}, m_timeout{timeout}
|
||||
{
|
||||
p->PutLookup(this, tx);
|
||||
}
|
||||
|
||||
bool
|
||||
IServiceLookup::SendRequestViaPath(path::Path_ptr path, Router* r)
|
||||
{
|
||||
auto msg = BuildRequestMessage();
|
||||
if (!msg)
|
||||
return false;
|
||||
r->loop()->call(
|
||||
[path = std::move(path), msg = std::move(msg), r] { path->SendRoutingMessage(*msg, r); });
|
||||
return true;
|
||||
}
|
||||
} // namespace service
|
||||
} // namespace llarp
|
@ -1,113 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <llarp/routing/message.hpp>
|
||||
#include "intro_set.hpp"
|
||||
#include <llarp/path/pathset.hpp>
|
||||
|
||||
#include <llarp/endpoint_base.hpp>
|
||||
|
||||
#include <set>
|
||||
|
||||
namespace llarp
|
||||
{
|
||||
// forward declare
|
||||
namespace path
|
||||
{
|
||||
struct Path;
|
||||
}
|
||||
|
||||
namespace service
|
||||
{
|
||||
struct ILookupHolder;
|
||||
|
||||
constexpr size_t MaxConcurrentLookups = size_t(16);
|
||||
|
||||
struct IServiceLookup
|
||||
{
|
||||
IServiceLookup() = delete;
|
||||
virtual ~IServiceLookup() = default;
|
||||
|
||||
/// handle lookup result for introsets
|
||||
virtual bool
|
||||
HandleIntrosetResponse(const std::set<EncryptedIntroSet>&)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// handle lookup result for introsets
|
||||
virtual bool
|
||||
HandleNameResponse(std::optional<Address>)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual void
|
||||
HandleTimeout()
|
||||
{
|
||||
HandleIntrosetResponse({});
|
||||
}
|
||||
|
||||
/// determine if this request has timed out
|
||||
bool
|
||||
IsTimedOut(llarp_time_t now) const
|
||||
{
|
||||
return TimeLeft(now) == 0ms;
|
||||
}
|
||||
|
||||
/// return how long this request has left to be fufilled
|
||||
llarp_time_t
|
||||
TimeLeft(llarp_time_t now) const
|
||||
{
|
||||
if (now > (m_created + m_timeout))
|
||||
return 0s;
|
||||
return now - (m_created + m_timeout);
|
||||
}
|
||||
|
||||
/// build request message for service lookup
|
||||
virtual std::shared_ptr<routing::AbstractRoutingMessage>
|
||||
BuildRequestMessage() = 0;
|
||||
|
||||
/// build a new request message and send it via a path
|
||||
virtual bool
|
||||
SendRequestViaPath(path::Path_ptr p, Router* r);
|
||||
|
||||
ILookupHolder* m_parent;
|
||||
uint64_t txid;
|
||||
const std::string name;
|
||||
RouterID endpoint;
|
||||
|
||||
/// return true if this lookup is for a remote address
|
||||
virtual bool
|
||||
IsFor(EndpointBase::AddressVariant_t) const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
util::StatusObject
|
||||
ExtractStatus() const
|
||||
{
|
||||
auto now = time_now_ms();
|
||||
util::StatusObject obj{
|
||||
{"txid", txid},
|
||||
{"endpoint", endpoint.ToHex()},
|
||||
{"name", name},
|
||||
{"timedOut", IsTimedOut(now)},
|
||||
{"createdAt", m_created.count()}};
|
||||
return obj;
|
||||
}
|
||||
|
||||
protected:
|
||||
IServiceLookup(
|
||||
ILookupHolder* parent, uint64_t tx, std::string name, llarp_time_t timeout = 10s);
|
||||
|
||||
const llarp_time_t m_created, m_timeout;
|
||||
};
|
||||
|
||||
struct ILookupHolder
|
||||
{
|
||||
virtual void
|
||||
PutLookup(IServiceLookup* l, uint64_t txid) = 0;
|
||||
};
|
||||
|
||||
} // namespace service
|
||||
} // namespace llarp
|
Loading…
Reference in New Issue