From ea19093a20fd4d0a1fc7dd91cff641e2da548969 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 2 Jan 2019 01:04:04 +0000 Subject: [PATCH] Remove const byte* conversion operators from llarp::AlignedBuffer --- llarp/address_info.cpp | 2 +- llarp/aligned.hpp | 48 ++++++++++------- llarp/buffer.hpp | 5 +- llarp/crypto.cpp | 2 +- llarp/crypto.hpp | 26 +++++----- llarp/crypto_libsodium.cpp | 97 +++++++++++++++++++---------------- llarp/dht/context.cpp | 19 +++---- llarp/dht/context.hpp | 2 +- llarp/dht/dht_immediate.cpp | 3 +- llarp/dht/find_router.cpp | 4 +- llarp/dht/key.hpp | 4 +- llarp/dns_dotlokilookup.cpp | 4 +- llarp/encrypted_frame.cpp | 10 ++-- llarp/encrypted_frame.hpp | 12 ++--- llarp/exit/obtain_exit.cpp | 19 ++----- llarp/handlers/null.hpp | 2 +- llarp/handlers/tun.cpp | 8 +-- llarp/handlers/tun.hpp | 2 +- llarp/link/server.cpp | 10 ++-- llarp/link/server.hpp | 16 +++--- llarp/link/session.hpp | 2 +- llarp/link/utp.cpp | 43 ++++++++-------- llarp/link/utp_internal.hpp | 7 ++- llarp/messages/exit.hpp | 35 +++++++------ llarp/nodedb.cpp | 8 +-- llarp/nodedb.hpp | 8 +-- llarp/path.hpp | 31 +++++------ llarp/pathbuilder.cpp | 12 ++--- llarp/pathbuilder.hpp | 4 +- llarp/relay_commit.cpp | 2 +- llarp/router.cpp | 30 +++++------ llarp/router_contact.cpp | 6 +-- llarp/router_id.hpp | 2 +- llarp/routing/message.hpp | 7 ++- llarp/service.cpp | 9 ++-- llarp/service/Identity.hpp | 2 +- llarp/service/Info.hpp | 20 ++++++-- llarp/service/context.cpp | 3 +- llarp/service/context.hpp | 3 +- llarp/service/endpoint.cpp | 15 +++--- llarp/service/endpoint.hpp | 6 +-- llarp/service/handler.hpp | 2 +- llarp/service/protocol.cpp | 6 +-- llarp/service/protocol.hpp | 4 +- llarp/service/tag.hpp | 4 +- test/obtain_exit_unittest.cpp | 15 +++--- test/test_llarp_aligned.cpp | 2 +- 47 files changed, 309 insertions(+), 274 deletions(-) diff --git a/llarp/address_info.cpp b/llarp/address_info.cpp index ce754a405..7ed32da56 100644 --- a/llarp/address_info.cpp +++ b/llarp/address_info.cpp @@ -137,7 +137,7 @@ namespace llarp /* encryption key */ if(!bencode_write_bytestring(buff, "e", 1)) return false; - if(!bencode_write_bytestring(buff, pubkey.as_array().data(), PUBKEYSIZE)) + if(!bencode_write_bytestring(buff, pubkey.data(), PUBKEYSIZE)) return false; /** ip */ ipstr = inet_ntop(AF_INET6, (void *)&ip, ipbuff, sizeof(ipbuff)); diff --git a/llarp/aligned.hpp b/llarp/aligned.hpp index ce0eaf18f..7ce5deac0 100644 --- a/llarp/aligned.hpp +++ b/llarp/aligned.hpp @@ -48,7 +48,7 @@ namespace llarp AlignedBuffer(const Data& buf) { new(&val) Data; - std::copy(buf.begin(), buf.end(), as_array().begin()); + std::copy(buf.begin(), buf.end(), begin()); } AlignedBuffer& @@ -74,8 +74,7 @@ namespace llarp operator~() const { AlignedBuffer< sz > ret; - std::transform(as_array().begin(), as_array().end(), - ret.as_array().begin(), [](byte_t a) { return ~a; }); + std::transform(begin(), end(), ret.begin(), [](byte_t a) { return ~a; }); return ret; } @@ -120,8 +119,7 @@ namespace llarp operator^(const AlignedBuffer& other) const { AlignedBuffer< sz > ret; - std::transform(as_array().begin(), as_array().end(), - other.as_array().begin(), ret.as_array().begin(), + std::transform(begin(), end(), other.begin(), ret.begin(), std::bit_xor< byte_t >()); return ret; } @@ -130,8 +128,6 @@ namespace llarp operator^=(const AlignedBuffer& other) { // Mutate in place instead. - // Well defined for std::transform, - for(size_t i = 0; i < as_array().size(); ++i) { as_array()[i] ^= other.as_array()[i]; @@ -175,13 +171,24 @@ namespace llarp return reinterpret_cast< const Data& >(val); } + byte_t* + data() + { + return as_array().data(); + } + + const byte_t* + data() const + { + return as_array().data(); + } + bool IsZero() const { auto notZero = [](byte_t b) { return b != 0; }; - return std::find_if(as_array().begin(), as_array().end(), notZero) - == as_array().end(); + return std::find_if(begin(), end(), notZero) == end(); } void @@ -193,12 +200,7 @@ namespace llarp void Randomize() { - randombytes(as_array().data(), SIZE); - } - - operator const byte_t*() const - { - return as_array().data(); + randombytes(data(), SIZE); } typename Data::iterator @@ -225,10 +227,20 @@ namespace llarp return as_array().cend(); } + llarp_buffer_t + as_buffer() + { + llarp_buffer_t buff; + buff.base = data(); + buff.cur = buff.base; + buff.sz = size(); + return buff; + } + bool BEncode(llarp_buffer_t* buf) const { - return bencode_write_bytestring(buf, as_array().data(), sz); + return bencode_write_bytestring(buf, data(), sz); } bool @@ -244,7 +256,7 @@ namespace llarp llarp::LogError("bdecode buffer size missmatch ", strbuf.sz, "!=", sz); return false; } - memcpy(as_array().data(), strbuf.base, sz); + memcpy(data(), strbuf.base, sz); return true; } @@ -260,7 +272,7 @@ namespace llarp size_t operator()(const AlignedBuffer& buf) const { - return std::accumulate(buf.as_array().begin(), buf.as_array().end(), 0, + return std::accumulate(buf.begin(), buf.end(), 0, std::bit_xor< size_t >()); } }; diff --git a/llarp/buffer.hpp b/llarp/buffer.hpp index 6638a6bf5..bec289dd8 100644 --- a/llarp/buffer.hpp +++ b/llarp/buffer.hpp @@ -35,7 +35,10 @@ namespace llarp Buffer(T& t) { llarp_buffer_t buff; - buff.base = &t[0]; + // use data over the first element to "enforce" the container used has + // contiguous memory. (Note this isn't required by the standard, but a + // reasonable test on most standard library implementations). + buff.base = t.data(); buff.cur = buff.base; buff.sz = t.size(); return buff; diff --git a/llarp/crypto.cpp b/llarp/crypto.cpp index 7a0cec3f1..445b00b59 100644 --- a/llarp/crypto.cpp +++ b/llarp/crypto.cpp @@ -7,7 +7,7 @@ namespace llarp bool PubKey::FromString(const std::string& str) { - return HexDecode(str.c_str(), as_array().data(), size()); + return HexDecode(str.c_str(), begin(), size()); } std::string diff --git a/llarp/crypto.hpp b/llarp/crypto.hpp index 62d46168c..063e7e7fc 100644 --- a/llarp/crypto.hpp +++ b/llarp/crypto.hpp @@ -75,7 +75,7 @@ namespace llarp PubKey & operator=(const byte_t *ptr) { - std::copy(ptr, ptr + SIZE, as_array().begin()); + std::copy(ptr, ptr + SIZE, begin()); return *this; } }; @@ -98,7 +98,7 @@ namespace llarp SecretKey & operator=(const byte_t *ptr) { - std::copy(ptr, ptr + SIZE, as_array().begin()); + std::copy(ptr, ptr + SIZE, begin()); return *this; } }; @@ -116,20 +116,20 @@ namespace llarp /// label functors /// PKE(result, publickey, secretkey, nonce) - using path_dh_func = std::function< bool(SharedSecret &, const PubKey &, - const byte_t *, const byte_t *) >; + 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 byte_t *, const byte_t *) >; + SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; /// SD/SE(buffer, key, nonce) - using sym_cipher_func = - std::function< bool(llarp_buffer_t, const byte_t *, const byte_t *) >; + using sym_cipher_func = std::function< bool( + llarp_buffer_t, const SharedSecret &, const TunnelNonce &) >; /// SD/SE(dst, src, key, nonce) using sym_cipher_alt_func = std::function< bool( - llarp_buffer_t, llarp_buffer_t, const byte_t *, const byte_t *) >; + llarp_buffer_t, llarp_buffer_t, const SharedSecret &, const byte_t *) >; /// H(result, body) using hash_func = std::function< bool(byte_t *, llarp_buffer_t) >; @@ -147,7 +147,7 @@ namespace llarp /// V(pubkey, body, sig) using verify_func = - std::function< bool(const PubKey &, llarp_buffer_t, const byte_t *) >; + std::function< bool(const PubKey &, llarp_buffer_t, const Signature &) >; /// library crypto configuration struct Crypto @@ -188,7 +188,7 @@ namespace llarp std::function< bool(const PQCipherBlock &, SharedSecret &, const byte_t *) > pqe_decrypt; /// post quantum encrypt (buffer, sharedkey_dst, pub) - std::function< bool(PQCipherBlock &, SharedSecret &, const byte_t *) > + std::function< bool(PQCipherBlock &, SharedSecret &, const PQPubKey &) > pqe_encrypt; // Give a basic type tag for the constructor to pick libsodium @@ -204,13 +204,13 @@ namespace llarp randint(); const byte_t * - seckey_topublic(const byte_t *secret); + seckey_topublic(const SecretKey &secret); const byte_t * - pq_keypair_to_public(const byte_t *keypair); + pq_keypair_to_public(const PQKeyPair &keypair); const byte_t * - pq_keypair_to_secret(const byte_t *keypair); + pq_keypair_to_secret(const PQKeyPair &keypair); } // namespace llarp diff --git a/llarp/crypto_libsodium.cpp b/llarp/crypto_libsodium.cpp index 3a9adb87b..b1a276492 100644 --- a/llarp/crypto_libsodium.cpp +++ b/llarp/crypto_libsodium.cpp @@ -18,49 +18,56 @@ namespace llarp namespace sodium { static bool - xchacha20(llarp_buffer_t buff, const byte_t *k, const byte_t *n) + xchacha20(llarp_buffer_t buff, const SharedSecret &k, const TunnelNonce &n) { - return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, n, k) + return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, + n.data(), + k.data()) == 0; } static bool - xchacha20_alt(llarp_buffer_t out, llarp_buffer_t in, const byte_t *k, + xchacha20_alt(llarp_buffer_t out, llarp_buffer_t in, const SharedSecret &k, const byte_t *n) { if(in.sz > out.sz) return false; - return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k) == 0; + return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, + k.data()) + == 0; } static bool dh(llarp::SharedSecret &out, const PubKey &client_pk, - const uint8_t *server_pk, const uint8_t *themPub, const uint8_t *usSec) + const PubKey &server_pk, const uint8_t *themPub, const SecretKey &usSec) { llarp::SharedSecret shared; crypto_generichash_state h; const size_t outsz = SHAREDKEYSIZE; - if(crypto_scalarmult_curve25519(shared.as_array().data(), usSec, themPub)) + if(crypto_scalarmult_curve25519(shared.data(), + usSec.data(), themPub)) return false; crypto_generichash_blake2b_init(&h, nullptr, 0U, outsz); - crypto_generichash_blake2b_update(&h, client_pk.as_array().data(), 32); - crypto_generichash_blake2b_update(&h, server_pk, 32); - crypto_generichash_blake2b_update(&h, shared, 32); - crypto_generichash_blake2b_final(&h, out.as_array().data(), outsz); + 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(), outsz); return true; } static bool - dh_client(llarp::SharedSecret &shared, const PubKey &pk, const uint8_t *sk, - const uint8_t *n) + dh_client(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) { llarp::SharedSecret dh_result; - if(dh(dh_result, llarp::seckey_topublic(sk), pk, pk, sk)) + if(dh(dh_result, llarp::seckey_topublic(sk), pk.data(), + pk.data(), sk)) { - return crypto_generichash_blake2b(shared.as_array().data(), 32, n, 32, - dh_result, 32) + return crypto_generichash_blake2b(shared.data(), 32, + n.data(), 32, + dh_result.data(), 32) != -1; } llarp::LogWarn("crypto::dh_client - dh failed"); @@ -68,14 +75,16 @@ namespace llarp } static bool - dh_server(llarp::SharedSecret &shared, const uint8_t *pk, const uint8_t *sk, - const uint8_t *n) + dh_server(llarp::SharedSecret &shared, const PubKey &pk, + const SecretKey &sk, const TunnelNonce &n) { llarp::SharedSecret dh_result; - if(dh(dh_result, pk, llarp::seckey_topublic(sk), pk, sk)) + if(dh(dh_result, pk, llarp::seckey_topublic(sk), pk.data(), + sk)) { - return crypto_generichash_blake2b(shared.as_array().data(), 32, n, 32, - dh_result, 32) + return crypto_generichash_blake2b(shared.data(), 32, + n.data(), 32, + dh_result.data(), 32) != -1; } llarp::LogWarn("crypto::dh_server - dh failed"); @@ -93,7 +102,7 @@ namespace llarp static bool shorthash(ShortHash &result, llarp_buffer_t buff) { - return crypto_generichash_blake2b(result.as_array().data(), + return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, buff.base, buff.sz, nullptr, 0) != -1; @@ -103,24 +112,25 @@ namespace llarp hmac(byte_t *result, llarp_buffer_t buff, const SharedSecret &secret) { return crypto_generichash_blake2b(result, HMACSIZE, buff.base, buff.sz, - secret.as_array().data(), HMACSECSIZE) + secret.data(), HMACSECSIZE) != -1; } static bool sign(Signature &result, const SecretKey &secret, llarp_buffer_t buff) { - return crypto_sign_detached(result.as_array().begin(), nullptr, buff.base, - buff.sz, secret.as_array().begin()) - != -1; + int rc = + crypto_sign_detached(result.data(), nullptr, buff.base, + buff.sz, secret.data()); + return rc != -1; } static bool - verify(const PubKey &pub, llarp_buffer_t buff, const uint8_t *sig) + verify(const PubKey &pub, llarp_buffer_t buff, const Signature &sig) { - return crypto_sign_verify_detached(sig, buff.base, buff.sz, - pub.as_array().data()) - != -1; + int rc = crypto_sign_verify_detached(sig.data(), buff.base, + buff.sz, pub.data()); + return rc != -1; } static void @@ -138,62 +148,63 @@ namespace llarp static void sigkeygen(llarp::SecretKey &keys) { - auto d = keys.as_array().data(); + byte_t *d = keys.data(); crypto_sign_keypair(d + 32, d); } static void enckeygen(llarp::SecretKey &keys) { - auto d = keys.as_array().data(); + auto d = keys.data(); randombytes(d, 32); crypto_scalarmult_curve25519_base(d + 32, d); } } // namespace sodium const byte_t * - seckey_topublic(const byte_t *sec) + seckey_topublic(const SecretKey &sec) { - return sec + 32; + return sec.data() + 32; } namespace pq { bool encrypt(PQCipherBlock &ciphertext, SharedSecret &sharedkey, - const byte_t *pubkey) + const PQPubKey &pubkey) { - return crypto_kem_enc(ciphertext.as_array().data(), - sharedkey.as_array().data(), pubkey) + return crypto_kem_enc(ciphertext.data(), + sharedkey.data(), + pubkey.data()) != -1; } bool decrypt(const PQCipherBlock &ciphertext, SharedSecret &sharedkey, const byte_t *secretkey) { - return crypto_kem_dec(sharedkey.as_array().data(), - ciphertext.as_array().data(), secretkey) + return crypto_kem_dec(sharedkey.data(), + ciphertext.data(), secretkey) != -1; } void keygen(PQKeyPair &keypair) { - auto d = keypair.as_array().data(); + auto d = keypair.data(); crypto_kem_keypair(d + PQ_SECRETKEYSIZE, d); } } // namespace pq const byte_t * - pq_keypair_to_public(const byte_t *k) + pq_keypair_to_public(const PQKeyPair &k) { - return k + PQ_SECRETKEYSIZE; + return k.data() + PQ_SECRETKEYSIZE; } const byte_t * - pq_keypair_to_secret(const byte_t *k) + pq_keypair_to_secret(const PQKeyPair &k) { - return k; + return k.data(); } Crypto::Crypto(Crypto::sodium tag) diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index 664621925..96e36e73d 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -57,7 +57,8 @@ namespace llarp void Start(const TXOwner &peer) override { - parent->DHTSendTo(peer.node, new FindRouterMessage(peer.txid)); + parent->DHTSendTo(peer.node.as_array(), + new FindRouterMessage(peer.txid)); } bool @@ -284,7 +285,7 @@ namespace llarp } void - Context::DHTSendTo(const byte_t *peer, IMessage *msg, bool keepalive) + Context::DHTSendTo(const RouterID &peer, IMessage *msg, bool keepalive) { llarp::DHTImmeidateMessage m; m.msgs.emplace_back(msg); @@ -352,7 +353,7 @@ namespace llarp void Start(const TXOwner &peer) override { - parent->DHTSendTo(peer.node, + parent->DHTSendTo(peer.node.as_array(), new FindIntroMessage(peer.txid, target, R)); } @@ -373,7 +374,7 @@ namespace llarp if(handleResult) handleResult(valuesFound); - parent->DHTSendTo(whoasked.node, + parent->DHTSendTo(whoasked.node.as_array(), new GotIntroMessage(valuesFound, whoasked.txid)); } }; @@ -462,7 +463,7 @@ namespace llarp std::vector< Key_t > exclude; for(const auto &router : dontTell) exclude.push_back(router); - parent->DHTSendTo(peer.node, + parent->DHTSendTo(peer.node.as_array(), new PublishIntroMessage(I, peer.txid, S, exclude)); } @@ -552,7 +553,7 @@ namespace llarp void Start(const TXOwner &peer) override { - parent->DHTSendTo(peer.node, + parent->DHTSendTo(peer.node.as_array(), new FindIntroMessage(target, peer.txid, R)); } @@ -589,7 +590,7 @@ namespace llarp { values.push_back(introset); } - parent->DHTSendTo(whoasked.node, + parent->DHTSendTo(whoasked.node.as_array(), new GotIntroMessage(values, whoasked.txid)); } }; @@ -730,7 +731,7 @@ namespace llarp void Start(const TXOwner &peer) override { - parent->DHTSendTo(peer.node, new FindRouterMessage(peer.txid, target)); + parent->DHTSendTo(peer.node.as_array(), new FindRouterMessage(peer.txid, target)); } virtual void @@ -743,7 +744,7 @@ namespace llarp else { parent->DHTSendTo( - whoasked.node, + whoasked.node.as_array(), new GotRouterMessage({}, whoasked.txid, valuesFound, false)); } } diff --git a/llarp/dht/context.hpp b/llarp/dht/context.hpp index f11ecaf99..248886c95 100644 --- a/llarp/dht/context.hpp +++ b/llarp/dht/context.hpp @@ -205,7 +205,7 @@ namespace llarp /// send a dht message to peer, if keepalive is true then keep the session /// with that peer alive for 10 seconds void - DHTSendTo(const byte_t* peer, IMessage* msg, bool keepalive = true); + DHTSendTo(const RouterID& peer, IMessage* msg, bool keepalive = true); /// get routers closest to target excluding requester bool diff --git a/llarp/dht/dht_immediate.cpp b/llarp/dht/dht_immediate.cpp index fb8206ba6..be36c7df5 100644 --- a/llarp/dht/dht_immediate.cpp +++ b/llarp/dht/dht_immediate.cpp @@ -18,7 +18,8 @@ namespace llarp DHTImmeidateMessage::DecodeKey(llarp_buffer_t key, llarp_buffer_t *buf) { if(llarp_buffer_eq(key, "m")) - return llarp::dht::DecodeMesssageList(session->GetPubKey(), buf, msgs); + return llarp::dht::DecodeMesssageList(session->GetPubKey().as_array(), + buf, msgs); if(llarp_buffer_eq(key, "v")) { if(!bencode_read_integer(buf, &version)) diff --git a/llarp/dht/find_router.cpp b/llarp/dht/find_router.cpp index 7dc33d85a..2afa29089 100644 --- a/llarp/dht/find_router.cpp +++ b/llarp/dht/find_router.cpp @@ -75,7 +75,7 @@ namespace llarp // key if(!bencode_write_bytestring(buf, "K", 1)) return false; - if(!bencode_write_bytestring(buf, K.as_array().data(), K.size())) + if(!bencode_write_bytestring(buf, K.data(), K.size())) return false; // txid @@ -124,7 +124,7 @@ namespace llarp if(strbuf.sz != K.size()) return false; - std::copy(strbuf.base, strbuf.base + K.SIZE, K.as_array().begin()); + std::copy(strbuf.base, strbuf.base + K.SIZE, K.begin()); return true; } if(llarp_buffer_eq(key, "T")) diff --git a/llarp/dht/key.hpp b/llarp/dht/key.hpp index 60ef18f6b..21c3f730f 100644 --- a/llarp/dht/key.hpp +++ b/llarp/dht/key.hpp @@ -28,8 +28,8 @@ namespace llarp operator^(const Key_t& other) const { Key_t dist; - std::transform(as_array().begin(), as_array().end(), - other.as_array().begin(), dist.as_array().begin(), + std::transform(begin(), end(), + other.begin(), dist.begin(), std::bit_xor< byte_t >()); return dist; } diff --git a/llarp/dns_dotlokilookup.cpp b/llarp/dns_dotlokilookup.cpp index a6bd9b561..e5653c05f 100644 --- a/llarp/dns_dotlokilookup.cpp +++ b/llarp/dns_dotlokilookup.cpp @@ -41,8 +41,8 @@ decode_request_name(const std::string &name, llarp::AlignedBuffer< 32 > &addr, auto pos = name.find(".snode"); if(pos != std::string::npos) { - if(!llarp::HexDecode(name.substr(0, pos).c_str(), - serviceAddr.as_array().data(), serviceAddr.size())) + if(!llarp::HexDecode(name.substr(0, pos).c_str(), serviceAddr.begin(), + serviceAddr.size())) { return false; } diff --git a/llarp/encrypted_frame.cpp b/llarp/encrypted_frame.cpp index bb27324bc..132927586 100644 --- a/llarp/encrypted_frame.cpp +++ b/llarp/encrypted_frame.cpp @@ -6,8 +6,8 @@ namespace llarp { bool - EncryptedFrame::EncryptInPlace(const byte_t* ourSecretKey, - const byte_t* otherPubkey, + EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey, + const PubKey& otherPubkey, llarp::Crypto* crypto) { // format of frame is @@ -65,7 +65,7 @@ namespace llarp } bool - EncryptedFrame::DecryptInPlace(const byte_t* ourSecretKey, + EncryptedFrame::DecryptInPlace(const SecretKey& ourSecretKey, llarp::Crypto* crypto) { // format of frame is @@ -98,13 +98,13 @@ namespace llarp return false; } - if(!MDS(digest.as_array().data(), buf, shared)) + if(!MDS(digest.data(), buf, shared)) { llarp::LogError("Digest failed"); return false; } - if(memcmp(digest, hash, digest.size())) + if(!std::equal(digest.begin(), digest.end(), hash)) { llarp::LogError("message authentication failed"); return false; diff --git a/llarp/encrypted_frame.hpp b/llarp/encrypted_frame.hpp index 642303947..bca825f3b 100644 --- a/llarp/encrypted_frame.hpp +++ b/llarp/encrypted_frame.hpp @@ -38,14 +38,14 @@ namespace llarp } bool - DecryptInPlace(const byte_t* seckey, llarp::Crypto* crypto); + DecryptInPlace(const SecretKey& seckey, llarp::Crypto* crypto); bool - EncryptInPlace(const byte_t* seckey, const byte_t* other, + EncryptInPlace(const SecretKey& seckey, const PubKey& other, llarp::Crypto* crypto); }; - /// TOOD: can only handle 1 frame at a time + /// TODO: can only handle 1 frame at a time template < typename User > struct AsyncFrameEncrypter { @@ -92,7 +92,7 @@ namespace llarp } }; - /// TOOD: can only handle 1 frame at a time + /// TODO: can only handle 1 frame at a time template < typename User > struct AsyncFrameDecrypter { @@ -114,7 +114,7 @@ namespace llarp ctx->result(nullptr, ctx->context); } - AsyncFrameDecrypter(llarp::Crypto* c, const byte_t* secretkey, + AsyncFrameDecrypter(llarp::Crypto* c, const SecretKey& secretkey, DecryptHandler h) : result(h), crypto(c), seckey(secretkey) { @@ -123,7 +123,7 @@ namespace llarp DecryptHandler result; User* context; llarp::Crypto* crypto; - const byte_t* seckey; + const SecretKey& seckey; EncryptedFrame target; void diff --git a/llarp/exit/obtain_exit.cpp b/llarp/exit/obtain_exit.cpp index 672cd34c2..60da9bdbd 100644 --- a/llarp/exit/obtain_exit.cpp +++ b/llarp/exit/obtain_exit.cpp @@ -6,21 +6,6 @@ namespace llarp { namespace routing { - ObtainExitMessage& - ObtainExitMessage::operator=(const ObtainExitMessage& other) - { - B = other.B; - E = other.E; - I = other.I; - T = other.T; - W = other.W; - X = other.X; - version = other.version; - S = other.S; - Z = other.Z; - return *this; - } - bool ObtainExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk) { @@ -29,7 +14,9 @@ namespace llarp I = llarp::seckey_topublic(sk); Z.Zero(); if(!BEncode(&buf)) + { return false; + } buf.sz = buf.cur - buf.base; return c->sign(Z, sk, buf); } @@ -43,7 +30,9 @@ namespace llarp copy = *this; copy.Z.Zero(); if(!copy.BEncode(&buf)) + { return false; + } // rewind buffer buf.sz = buf.cur - buf.base; return c->verify(I, buf, Z); diff --git a/llarp/handlers/null.hpp b/llarp/handlers/null.hpp index 0a5c67013..02b47314c 100644 --- a/llarp/handlers/null.hpp +++ b/llarp/handlers/null.hpp @@ -25,7 +25,7 @@ namespace llarp } bool - HasAddress(const byte_t *) const override + HasAddress(const AlignedBuffer< 32 > &) const override { return false; } diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index d6f05833c..60305e74f 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -226,9 +226,9 @@ namespace llarp } else if(addr.FromString(qname, ".loki")) { - if(HasAddress(addr.as_array().data())) + if(HasAddress(addr)) { - huint32_t ip = ObtainIPForAddr(addr.as_array().data(), false); + huint32_t ip = ObtainIPForAddr(addr, false); msg.AddINReply(ip); } else @@ -243,7 +243,7 @@ namespace llarp { // TODO: add hook to EnsurePathToSNode EnsurePathToSNode(addr.as_array()); - huint32_t ip = ObtainIPForAddr(addr.as_array().data(), true); + huint32_t ip = ObtainIPForAddr(addr, true); msg.AddINReply(ip); } else @@ -325,7 +325,7 @@ namespace llarp { if(ctx) { - huint32_t ip = ObtainIPForAddr(addr.as_array().data(), false); + huint32_t ip = ObtainIPForAddr(addr, false); request.AddINReply(ip); } else diff --git a/llarp/handlers/tun.hpp b/llarp/handlers/tun.hpp index e9b02d4dc..b0f1746aa 100644 --- a/llarp/handlers/tun.hpp +++ b/llarp/handlers/tun.hpp @@ -115,7 +115,7 @@ namespace llarp } bool - HasAddress(const byte_t* addr) const override + HasAddress(const AlignedBuffer< 32 >& addr) const override { return m_AddrToIP.find(addr) != m_AddrToIP.end(); } diff --git a/llarp/link/server.cpp b/llarp/link/server.cpp index fdba8dac1..7f020cda3 100644 --- a/llarp/link/server.cpp +++ b/llarp/link/server.cpp @@ -3,7 +3,7 @@ namespace llarp { - ILinkLayer::ILinkLayer(const byte_t* routerEncSecret, GetRCFunc getrc, + ILinkLayer::ILinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc, LinkMessageHandler handler, SignBufferFunc signbuf, SessionEstablishedHandler establishedSession, SessionRenegotiateHandler reneg, @@ -210,7 +210,7 @@ namespace llarp } void - ILinkLayer::CloseSessionTo(const byte_t* remote) + ILinkLayer::CloseSessionTo(const RouterID& remote) { Lock l(m_AuthedLinksMutex); RouterID r = remote; @@ -225,7 +225,7 @@ namespace llarp } void - ILinkLayer::KeepAliveSessionTo(const byte_t* remote) + ILinkLayer::KeepAliveSessionTo(const RouterID& remote) { Lock l(m_AuthedLinksMutex); auto range = m_AuthedLinks.equal_range(remote); @@ -238,7 +238,7 @@ namespace llarp } bool - ILinkLayer::SendTo(const byte_t* remote, llarp_buffer_t buf) + ILinkLayer::SendTo(const RouterID& remote, llarp_buffer_t buf) { ILinkSession* s = nullptr; { @@ -279,7 +279,7 @@ namespace llarp return llarp::seckey_topublic(TransportSecretKey()); } - const byte_t* + const SecretKey& ILinkLayer::TransportSecretKey() const { return m_SecretKey; diff --git a/llarp/link/server.hpp b/llarp/link/server.hpp index c582b6fb5..7fa3c5a75 100644 --- a/llarp/link/server.hpp +++ b/llarp/link/server.hpp @@ -42,7 +42,7 @@ namespace llarp struct ILinkLayer { - ILinkLayer(const byte_t* routerEncSecret, GetRCFunc getrc, + ILinkLayer(const SecretKey& routerEncSecret, GetRCFunc getrc, LinkMessageHandler handler, SignBufferFunc signFunc, SessionEstablishedHandler sessionEstablish, SessionRenegotiateHandler renegotiate, TimeoutHandler timeout, @@ -82,7 +82,7 @@ namespace llarp llarp::LogWarn("no udp set"); return; } - // maybe chekc from too? + // maybe check from too? // no it's never null static_cast< ILinkLayer* >(udp->user)->RecvFrom(*from, buf.base, buf.sz); } @@ -116,13 +116,13 @@ namespace llarp Name() const = 0; void - CloseSessionTo(const byte_t* remote); + CloseSessionTo(const RouterID& remote); void - KeepAliveSessionTo(const byte_t* remote); + KeepAliveSessionTo(const RouterID& remote); bool - SendTo(const byte_t* remote, llarp_buffer_t buf); + SendTo(const RouterID& remote, llarp_buffer_t buf); bool GetOurAddressInfo(AddressInfo& addr) const; @@ -140,13 +140,13 @@ namespace llarp const byte_t* TransportPubKey() const; - const byte_t* + const SecretKey& RouterEncryptionSecret() const { return m_RouterEncSecret; } - const byte_t* + const SecretKey& TransportSecretKey() const; bool @@ -187,7 +187,7 @@ namespace llarp ScheduleTick(uint64_t interval); uint32_t tick_id; - const byte_t* m_RouterEncSecret; + const SecretKey& m_RouterEncSecret; protected: using Lock = util::NullLock; diff --git a/llarp/link/session.hpp b/llarp/link/session.hpp index 0b33fe8dc..f95f81c1b 100644 --- a/llarp/link/session.hpp +++ b/llarp/link/session.hpp @@ -42,7 +42,7 @@ namespace llarp std::function< bool(llarp_time_t) > TimedOut; /// get remote public identity key - std::function< const byte_t *(void) > GetPubKey; + std::function< const PubKey &(void) > GetPubKey; /// get remote address std::function< Addr(void) > GetRemoteEndpoint; diff --git a/llarp/link/utp.cpp b/llarp/link/utp.cpp index ca5df4f4c..0e4090d36 100644 --- a/llarp/link/utp.cpp +++ b/llarp/link/utp.cpp @@ -126,10 +126,14 @@ namespace llarp bool Session::DoKeyExchange(transport_dh_func dh, SharedSecret& K, const KeyExchangeNonce& n, const PubKey& other, - const byte_t* secret) + const SecretKey& secret) { ShortHash t_h; - AlignedBuffer< 64 > tmp; + static constexpr size_t TMP_SIZE = 64; + static_assert(SharedSecret::SIZE + KeyExchangeNonce::SIZE == TMP_SIZE, + "Invalid sizes"); + + AlignedBuffer< TMP_SIZE > tmp; std::copy(K.begin(), K.end(), tmp.begin()); std::copy(n.begin(), n.end(), tmp.begin() + K.size()); // t_h = HS(K + L.n) @@ -140,7 +144,7 @@ namespace llarp } // K = TKE(a.p, B_a.e, sk, t_h) - if(!dh(K, other, secret, t_h.as_array().data())) + if(!dh(K, other, secret, t_h)) { llarp::LogError("key exchange with ", other, " failed"); return false; @@ -153,10 +157,10 @@ namespace llarp Session::MutateKey(SharedSecret& K, const AlignedBuffer< 24 >& A) { AlignedBuffer< 56 > tmp; - auto buf = llarp::Buffer(tmp); + auto buf = tmp.as_buffer(); std::copy(K.begin(), K.end(), buf.cur); buf.cur += K.size(); - memcpy(buf.cur, A, A.size()); + std::copy(A.begin(), A.end(), buf.cur); buf.cur = buf.base; return Crypto()->shorthash(K, buf); } @@ -187,7 +191,7 @@ namespace llarp s -= left; recvBufOffset = 0; buf += left; - if(!VerifyThenDecrypt(recvBuf.as_array().data())) + if(!VerifyThenDecrypt(recvBuf.data())) return false; } } @@ -342,7 +346,8 @@ namespace llarp return 0; } - LinkLayer::LinkLayer(llarp::Crypto* crypto, const byte_t* routerEncSecret, + LinkLayer::LinkLayer(llarp::Crypto* crypto, + const SecretKey& routerEncSecret, llarp::GetRCFunc getrc, llarp::LinkMessageHandler h, llarp::SignBufferFunc sign, llarp::SessionEstablishedHandler established, @@ -525,7 +530,7 @@ namespace llarp } std::unique_ptr< ILinkLayer > - NewServer(llarp::Crypto* crypto, const byte_t* routerEncSecret, + NewServer(llarp::Crypto* crypto, const SecretKey& routerEncSecret, llarp::GetRCFunc getrc, llarp::LinkMessageHandler h, llarp::SessionEstablishedHandler est, llarp::SessionRenegotiateHandler reneg, @@ -612,9 +617,9 @@ namespace llarp remoteTransportPubKey = addr.pubkey; remoteRC = rc; RouterID rid = remoteRC.pubkey; - Crypto()->shorthash(txKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE)); - rid = p->GetOurRC().pubkey.as_array(); - Crypto()->shorthash(rxKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE)); + Crypto()->shorthash(txKey, rid.as_buffer()); + rid = p->GetOurRC().pubkey; + Crypto()->shorthash(rxKey, rid.as_buffer()); sock = s; assert(utp_set_userdata(sock, this) == this); @@ -628,7 +633,7 @@ namespace llarp Session::Session(LinkLayer* p, utp_socket* s, const Addr& addr) : Session(p) { RouterID rid = p->GetOurRC().pubkey; - Crypto()->shorthash(rxKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE)); + Crypto()->shorthash(rxKey, rid.as_buffer()); remoteRC.Clear(); sock = s; assert(s == sock); @@ -655,9 +660,7 @@ namespace llarp if(!gotLIM) { remoteRC = msg->rc; - Crypto()->shorthash( - txKey, - llarp::InitBuffer(remoteRC.pubkey.as_array().data(), PUBKEYSIZE)); + Crypto()->shorthash(txKey, remoteRC.pubkey.as_buffer()); if(!DoKeyExchange(Crypto()->transport_dh_server, rxKey, msg->N, remoteRC.enckey, parent->TransportSecretKey())) @@ -905,10 +908,10 @@ namespace llarp auto& buf = sendq.back(); vecq.emplace_back(); auto& vec = vecq.back(); - vec.iov_base = buf.as_array().data(); + vec.iov_base = buf.data(); vec.iov_len = FragmentBufferSize; buf.Randomize(); - byte_t* nonce = buf.as_array().data() + FragmentHashSize; + byte_t* nonce = buf.data() + FragmentHashSize; byte_t* body = nonce + FragmentNonceSize; byte_t* base = body; AlignedBuffer< 24 > A = base; @@ -937,7 +940,7 @@ namespace llarp payload.cur = payload.base; payload.sz = FragmentBufferSize - FragmentHashSize; // key'd hash - if(!Crypto()->hmac(buf.as_array().data(), payload, txKey)) + if(!Crypto()->hmac(buf.data(), payload, txKey)) return false; return MutateKey(txKey, A); } @@ -1003,7 +1006,7 @@ namespace llarp auto hbuf = InitBuffer(ptr + FragmentHashSize, FragmentBufferSize - FragmentHashSize); - if(!Crypto()->hmac(digest.as_array().data(), hbuf, rxKey)) + if(!Crypto()->hmac(digest.data(), hbuf, rxKey)) { llarp::LogError("keyed hash failed"); return false; @@ -1020,7 +1023,7 @@ namespace llarp auto in = InitBuffer(ptr + FragmentOverheadSize, FragmentBufferSize - FragmentOverheadSize); - auto out = Buffer(rxFragBody); + llarp_buffer_t out = rxFragBody.as_buffer(); // decrypt if(!Crypto()->xchacha20_alt(out, in, rxKey, ptr + FragmentHashSize)) diff --git a/llarp/link/utp_internal.hpp b/llarp/link/utp_internal.hpp index fb0de468f..e73a400a4 100644 --- a/llarp/link/utp_internal.hpp +++ b/llarp/link/utp_internal.hpp @@ -55,8 +55,7 @@ namespace llarp MessageBuffer _msg; /// for accessing message buffer - llarp_buffer_t buffer = - llarp::InitBuffer(_msg.as_array().data(), _msg.size()); + llarp_buffer_t buffer = _msg.as_buffer(); bool operator==(const InboundMessage& other) const @@ -209,7 +208,7 @@ namespace llarp bool DoKeyExchange(transport_dh_func dh, SharedSecret& K, const KeyExchangeNonce& n, const PubKey& other, - const byte_t* secret); + const SecretKey& secret); /// does K = HS(K + A) bool @@ -284,7 +283,7 @@ namespace llarp OnLog(utp_callback_arguments* arg); /// construct - LinkLayer(llarp::Crypto* crypto, const byte_t* routerEncSecret, + LinkLayer(llarp::Crypto* crypto, const SecretKey& routerEncSecret, llarp::GetRCFunc getrc, llarp::LinkMessageHandler h, llarp::SignBufferFunc sign, llarp::SessionEstablishedHandler established, diff --git a/llarp/messages/exit.hpp b/llarp/messages/exit.hpp index 251d6c961..73177ab7b 100644 --- a/llarp/messages/exit.hpp +++ b/llarp/messages/exit.hpp @@ -20,7 +20,7 @@ namespace llarp llarp_time_t X; llarp::Signature Z; - ObtainExitMessage() : IMessage() + ObtainExitMessage() : IMessage(), E(0), T(0), X(0) { } @@ -28,11 +28,8 @@ namespace llarp { } - ObtainExitMessage& - operator=(const ObtainExitMessage& other); - void - Clear() override + Clear() override { B.clear(); W.clear(); @@ -87,8 +84,10 @@ namespace llarp bool HandleMessage(IMessageHandler* h, llarp::Router* r) const override; - void - Clear() override {} + void + Clear() override + { + } }; struct RejectExitMessage final : public IMessage @@ -108,7 +107,7 @@ namespace llarp { } - void + void Clear() override { R.clear(); @@ -148,8 +147,10 @@ namespace llarp { } - void - Clear() override {} + void + Clear() override + { + } UpdateExitVerifyMessage& operator=(const UpdateExitVerifyMessage& other); @@ -204,8 +205,10 @@ namespace llarp bool HandleMessage(IMessageHandler* h, llarp::Router* r) const override; - void - Clear() override {} + void + Clear() override + { + } }; struct CloseExitMessage final : public IMessage @@ -240,9 +243,11 @@ namespace llarp bool Verify(llarp::Crypto* c, const llarp::PubKey& pk) const; - - void - Clear() override {} + + void + Clear() override + { + } }; } // namespace routing diff --git a/llarp/nodedb.cpp b/llarp/nodedb.cpp index e454ede83..0f991bed4 100644 --- a/llarp/nodedb.cpp +++ b/llarp/nodedb.cpp @@ -15,7 +15,7 @@ static const char skiplist_subdirs[] = "0123456789abcdef"; static const std::string RC_FILE_EXT = ".signed"; bool -llarp_nodedb::Remove(const byte_t *pk) +llarp_nodedb::Remove(const llarp::RouterID &pk) { llarp::util::Lock lock(access); auto itr = entries.find(pk); @@ -34,7 +34,7 @@ llarp_nodedb::Clear() } bool -llarp_nodedb::Get(const byte_t *pk, llarp::RouterContact &result) +llarp_nodedb::Get(const llarp::RouterID &pk, llarp::RouterContact &result) { llarp::util::Lock lock(access); auto itr = entries.find(pk); @@ -45,7 +45,7 @@ llarp_nodedb::Get(const byte_t *pk, llarp::RouterContact &result) } bool -llarp_nodedb::Has(const byte_t *pk) +llarp_nodedb::Has(const llarp::RouterID &pk) { llarp::util::Lock lock(access); return entries.find(pk) != entries.end(); @@ -54,7 +54,7 @@ llarp_nodedb::Has(const byte_t *pk) /// skiplist directory is hex encoded first nibble /// skiplist filename is .snode.signed std::string -llarp_nodedb::getRCFilePath(const byte_t *pubkey) const +llarp_nodedb::getRCFilePath(const llarp::RouterID &pubkey) const { char ftmp[68] = {0}; const char *hexname = diff --git a/llarp/nodedb.hpp b/llarp/nodedb.hpp index 59ed2b1bb..83491aefc 100644 --- a/llarp/nodedb.hpp +++ b/llarp/nodedb.hpp @@ -47,19 +47,19 @@ struct llarp_nodedb fs::path nodePath; bool - Remove(const byte_t *pk); + Remove(const llarp::RouterID &pk); void Clear(); bool - Get(const byte_t *pk, llarp::RouterContact &result); + Get(const llarp::RouterID &pk, llarp::RouterContact &result); bool - Has(const byte_t *pk); + Has(const llarp::RouterID &pk); std::string - getRCFilePath(const byte_t *pubkey) const; + getRCFilePath(const llarp::RouterID &pubkey) const; /// insert and write to disk bool diff --git a/llarp/path.hpp b/llarp/path.hpp index 8313f1b70..49613b49d 100644 --- a/llarp/path.hpp +++ b/llarp/path.hpp @@ -74,30 +74,27 @@ namespace llarp || upstream < other.upstream || downstream < other.downstream; } - struct Hash + struct PathIDHash { std::size_t - operator()(TransitHopInfo const& a) const + operator()(const PathID_t& a) const { - std::size_t idx0, idx1, idx2, idx3; - memcpy(&idx0, a.upstream, sizeof(std::size_t)); - memcpy(&idx1, a.downstream, sizeof(std::size_t)); - memcpy(&idx2, a.txID, sizeof(std::size_t)); - memcpy(&idx3, a.rxID, sizeof(std::size_t)); - return idx0 ^ idx1 ^ idx2; + return AlignedBuffer< PathID_t::SIZE >::Hash()(a); } }; - }; - struct PathIDHash - { - std::size_t - operator()(const PathID_t& a) const + struct Hash { - std::size_t idx0; - memcpy(&idx0, a, sizeof(std::size_t)); - return idx0; - } + std::size_t + operator()(TransitHopInfo const& a) const + { + std::size_t idx0 = RouterID::Hash()(a.upstream); + std::size_t idx1 = RouterID::Hash()(a.downstream); + std::size_t idx2 = PathIDHash()(a.txID); + std::size_t idx3 = PathIDHash()(a.rxID); + return idx0 ^ idx1 ^ idx2 ^ idx3; + } + }; }; struct IHopHandler diff --git a/llarp/pathbuilder.cpp b/llarp/pathbuilder.cpp index 21f31dd39..9578795ac 100644 --- a/llarp/pathbuilder.cpp +++ b/llarp/pathbuilder.cpp @@ -49,25 +49,25 @@ namespace llarp hop.nonce.Randomize(); // do key exchange if(!ctx->crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, - hop.nonce)) + hop.nonce.data())) { llarp::LogError("Failed to generate shared key for path build"); delete ctx; return; } // generate nonceXOR valueself->hop->pathKey - ctx->crypto->shorthash(hop.nonceXOR, llarp::Buffer(hop.shared)); + ctx->crypto->shorthash(hop.nonceXOR, hop.shared.as_buffer()); ++ctx->idx; bool isFarthestHop = ctx->idx == ctx->path->hops.size(); if(isFarthestHop) { - hop.upstream = hop.rc.pubkey.as_array(); + hop.upstream = hop.rc.pubkey; } else { - hop.upstream = ctx->path->hops[ctx->idx].rc.pubkey.as_array(); + hop.upstream = ctx->path->hops[ctx->idx].rc.pubkey; } // build record @@ -90,7 +90,7 @@ namespace llarp delete ctx; return; } - // use ephameral keypair for frame + // use ephemeral keypair for frame SecretKey framekey; ctx->crypto->encryption_keygen(framekey); if(!frame.EncryptInPlace(framekey, hop.rc.enckey, ctx->crypto)) @@ -210,7 +210,7 @@ namespace llarp return keygens.load() > 0; } - const byte_t* + const SecretKey& Builder::GetTunnelEncryptionSecretKey() const { return enckey; diff --git a/llarp/pathbuilder.hpp b/llarp/pathbuilder.hpp index 8719a0fde..1b4455773 100644 --- a/llarp/pathbuilder.hpp +++ b/llarp/pathbuilder.hpp @@ -48,7 +48,7 @@ namespace llarp ShouldBuildMore(llarp_time_t now) const override; /// return true if we hit our soft limit for building paths too fast - bool + bool BuildCooldownHit(llarp_time_t now) const; virtual bool @@ -74,7 +74,7 @@ namespace llarp void ManualRebuild(size_t N, PathRole roles = ePathRoleAny); - virtual const byte_t* + virtual const SecretKey& GetTunnelEncryptionSecretKey() const; virtual void diff --git a/llarp/relay_commit.cpp b/llarp/relay_commit.cpp index 066614b44..5e8b8958c 100644 --- a/llarp/relay_commit.cpp +++ b/llarp/relay_commit.cpp @@ -278,7 +278,7 @@ namespace llarp } // generate hash of hop key for nonce mutation self->context->Crypto()->shorthash(self->hop->nonceXOR, - llarp::Buffer(self->hop->pathKey)); + self->hop->pathKey.as_buffer()); if(self->record.work && self->record.work->IsValid(self->context->Crypto()->shorthash, now)) { diff --git a/llarp/router.cpp b/llarp/router.cpp index 7aa18623f..02158ab75 100644 --- a/llarp/router.cpp +++ b/llarp/router.cpp @@ -47,8 +47,7 @@ struct TryConnectJob void Failed() { - llarp::LogInfo("session to ", llarp::RouterID(rc.pubkey.as_array()), - " closed"); + llarp::LogInfo("session to ", llarp::RouterID(rc.pubkey), " closed"); link->CloseSessionTo(rc.pubkey); } @@ -113,7 +112,7 @@ llarp_router_try_connect(llarp::Router *router, auto link = router->outboundLink.get(); auto itr = router->pendingEstablishJobs.emplace( - remote.pubkey.as_array(), + remote.pubkey, std::make_unique< TryConnectJob >(remote, link, numretries, router)); TryConnectJob *job = itr.first->second.get(); // try establishing async @@ -135,14 +134,15 @@ llarp_findOrCreateIdentity(llarp::Crypto *crypto, const char *fpath, std::ofstream f(path.string(), std::ios::binary); if(f.is_open()) { - f.write(reinterpret_cast< char * >(secretkey.as_array().data()), - SECKEYSIZE); + std::copy(secretkey.begin(), secretkey.end(), + std::ostream_iterator< byte_t >(f)); } } std::ifstream f(path.string(), std::ios::binary); if(f.is_open()) { - f.read(reinterpret_cast< char * >(secretkey.as_array().data()), SECKEYSIZE); + std::copy_n(std::istream_iterator< byte_t >(f), secretkey.size(), + secretkey.begin()); return true; } llarp::LogInfo("failed to get identity key"); @@ -172,8 +172,8 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const char *fpath, std::ifstream f(path.string(), std::ios::binary); if(f.is_open()) { - f.read(reinterpret_cast< char * >(encryption.as_array().data()), - SECKEYSIZE); + std::copy_n(std::istream_iterator< byte_t >(f), encryption.size(), + encryption.begin()); return true; } llarp::LogInfo("failed to get encryption key"); @@ -264,13 +264,13 @@ namespace llarp { for(const auto &link : inboundLinks) { - if(link->HasSessionTo(remote.as_array())) + if(link->HasSessionTo(remote)) { SendTo(remote, msg, link.get()); return true; } } - if(outboundLink && outboundLink->HasSessionTo(remote.as_array())) + if(outboundLink && outboundLink->HasSessionTo(remote)) { SendTo(remote, msg, outboundLink.get()); return true; @@ -508,7 +508,7 @@ namespace llarp llarp::RouterContact rc = job->rc; - router->validRouters.emplace(pk.as_array(), rc); + router->validRouters.emplace(pk, rc); // track valid router in dht router->dht->impl.nodes->PutNode(rc); @@ -845,7 +845,7 @@ namespace llarp void Router::SessionClosed(llarp::RouterID remote) { - __llarp_dht_remove_peer(dht, remote); + __llarp_dht_remove_peer(dht, remote.data()); // remove from valid routers if it's a valid router validRouters.erase(remote); llarp::LogInfo("Session to ", remote, " fully closed"); @@ -1444,7 +1444,7 @@ namespace llarp llarp::PubKey pk; if(pk.FromString(val)) { - if(self->strictConnectPubkeys.insert(pk.as_array()).second) + if(self->strictConnectPubkeys.emplace(pk).second) llarp::LogInfo("added ", pk, " to strict connect list"); else llarp::LogWarn("duplicate key for strict connect: ", pk); @@ -1521,11 +1521,11 @@ namespace llarp auto &rc = self->bootstrapRCList.back(); if(rc.Read(val) && rc.Verify(&self->crypto, self->Now())) { - llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey.as_array())); + llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey)); } else if(self->Now() - rc.last_updated > RouterContact::Lifetime) { - llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey.as_array()), + llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey), " is too old and needs to be refreshed"); self->bootstrapRCList.pop_back(); } diff --git a/llarp/router_contact.cpp b/llarp/router_contact.cpp index 5f29014f6..4f517a958 100644 --- a/llarp/router_contact.cpp +++ b/llarp/router_contact.cpp @@ -27,7 +27,7 @@ namespace llarp { size_t len = strnlen(reinterpret_cast< const char * >(DefaultValue), size()); - std::copy(DefaultValue, DefaultValue + len, as_array().begin()); + std::copy(DefaultValue, DefaultValue + len, begin()); } bool @@ -53,7 +53,7 @@ namespace llarp if(strbuf.sz > size()) return false; - std::copy(strbuf.base, strbuf.base + strbuf.sz, as_array().begin()); + std::copy(strbuf.base, strbuf.base + strbuf.sz, begin()); return true; } @@ -162,7 +162,7 @@ namespace llarp return false; nickname.Zero(); std::copy(strbuf.base, strbuf.base + strbuf.sz, - nickname.as_array().begin()); + nickname.begin()); return true; } diff --git a/llarp/router_id.hpp b/llarp/router_id.hpp index 0cddd4987..e9704a26e 100644 --- a/llarp/router_id.hpp +++ b/llarp/router_id.hpp @@ -32,7 +32,7 @@ namespace llarp RouterID& operator=(const byte_t* ptr) { - std::copy(ptr, ptr + SIZE, as_array().begin()); + std::copy(ptr, ptr + SIZE, begin()); return *this; } diff --git a/llarp/routing/message.hpp b/llarp/routing/message.hpp index c22b8f77a..dab3fecef 100644 --- a/llarp/routing/message.hpp +++ b/llarp/routing/message.hpp @@ -15,9 +15,9 @@ namespace llarp struct IMessage : public llarp::IBEncodeMessage { llarp::PathID_t from; - uint64_t S = 0; + uint64_t S; - IMessage() : llarp::IBEncodeMessage() + IMessage() : llarp::IBEncodeMessage(), S(0) { } @@ -26,11 +26,10 @@ namespace llarp virtual bool HandleMessage(IMessageHandler* h, llarp::Router* r) const = 0; - virtual void + virtual void Clear() = 0; }; - } // namespace routing } // namespace llarp diff --git a/llarp/service.cpp b/llarp/service.cpp index 4bffa1f5b..b07218ab0 100644 --- a/llarp/service.cpp +++ b/llarp/service.cpp @@ -221,7 +221,8 @@ namespace llarp bool Identity::KeyExchange(path_dh_func dh, SharedSecret& result, - const ServiceInfo& other, const byte_t* N) const + const ServiceInfo& other, + const KeyExchangeNonce& N) const { return dh(result, other.EncryptionPublicKey(), enckey, N); } @@ -273,12 +274,12 @@ namespace llarp if(!BDecode(&buf)) return false; - const byte_t* ptr = nullptr; + ServiceInfo::OptNonce van; if(!vanity.IsZero()) - ptr = vanity.as_array().data(); + van = vanity; // update pubkeys pub.Update(llarp::seckey_topublic(enckey), - llarp::seckey_topublic(signkey), ptr); + llarp::seckey_topublic(signkey), van); return true; } diff --git a/llarp/service/Identity.hpp b/llarp/service/Identity.hpp index 952261783..b5a971a33 100644 --- a/llarp/service/Identity.hpp +++ b/llarp/service/Identity.hpp @@ -41,7 +41,7 @@ namespace llarp bool KeyExchange(llarp::path_dh_func dh, SharedSecret& sharedkey, - const ServiceInfo& other, const byte_t* N) const; + const ServiceInfo& other, const KeyExchangeNonce& N) const; bool DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; diff --git a/llarp/service/Info.hpp b/llarp/service/Info.hpp index d4a5dcf0d..c7c57f9aa 100644 --- a/llarp/service/Info.hpp +++ b/llarp/service/Info.hpp @@ -5,6 +5,12 @@ #include #include +#if __cplusplus >= 201703L +#include +#else +#include +#endif + namespace llarp { namespace service @@ -18,6 +24,12 @@ namespace llarp public: VanityNonce vanity; +#if __cplusplus >= 201703L + using OptNonce = std::optional< VanityNonce >; +#else + using OptNonce = tl::optional< VanityNonce >; +#endif + ServiceInfo() = default; ServiceInfo(ServiceInfo&& other) @@ -52,7 +64,7 @@ namespace llarp return crypto->verify(signkey, payload, sig); } - const byte_t* + const PubKey& EncryptionPublicKey() const { return enckey; @@ -60,12 +72,14 @@ namespace llarp bool Update(const byte_t* enc, const byte_t* sign, - const byte_t* nonce = nullptr) + const OptNonce& nonce = OptNonce()) { enckey = enc; signkey = sign; if(nonce) - vanity = nonce; + { + vanity = nonce.value(); + } return UpdateAddr(); } diff --git a/llarp/service/context.cpp b/llarp/service/context.cpp index 5cd4bd01e..e3f4cbcee 100644 --- a/llarp/service/context.cpp +++ b/llarp/service/context.cpp @@ -141,7 +141,8 @@ namespace llarp } bool - Context::FindBestAddressFor(const byte_t *addr, bool isSNode, huint32_t &ip) + Context::FindBestAddressFor(const llarp::AlignedBuffer< 32 > &addr, + bool isSNode, huint32_t &ip) { auto itr = m_Endpoints.begin(); while(itr != m_Endpoints.end()) diff --git a/llarp/service/context.hpp b/llarp/service/context.hpp index 6232be351..5ff34851c 100644 --- a/llarp/service/context.hpp +++ b/llarp/service/context.hpp @@ -33,7 +33,8 @@ namespace llarp getFirstEndpoint(); bool - FindBestAddressFor(const byte_t *addr, bool isSNode, huint32_t &); + FindBestAddressFor(const llarp::AlignedBuffer< 32 > &addr, bool isSNode, + huint32_t &); /// DRY refactor llarp::handlers::TunEndpoint * diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 88813a605..5964bb2b5 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -462,12 +462,12 @@ namespace llarp bool Endpoint::GetCachedSessionKeyFor(const ConvoTag& tag, - const byte_t*& secret) const + SharedSecret& secret) const { auto itr = m_Sessions.find(tag); if(itr == m_Sessions.end()) return false; - secret = itr->second.sharedKey.as_array().data(); + secret = itr->second.sharedKey; return true; } @@ -1183,7 +1183,7 @@ namespace llarp return false; } Introduction remoteIntro; - const byte_t* K = nullptr; + SharedSecret K; for(const auto& tag : tags) { if(tag.IsZero()) @@ -1468,9 +1468,8 @@ namespace llarp AsyncKeyExchange* self = static_cast< AsyncKeyExchange* >(user); // derive ntru session key component SharedSecret K; - self->crypto->pqe_encrypt(self->frame.C, K, - self->introPubKey.as_array().data()); - // randomize Nounce + self->crypto->pqe_encrypt(self->frame.C, K, self->introPubKey); + // randomize Nonce self->frame.N.Randomize(); // compure post handshake session key // PKE (A, B, N) @@ -1710,8 +1709,8 @@ namespace llarp Endpoint::SendContext::EncryptAndSendTo(llarp_buffer_t payload, ProtocolType t) { - auto crypto = m_Endpoint->Router()->crypto; - const byte_t* shared = nullptr; + auto crypto = m_Endpoint->Router()->crypto; + SharedSecret shared; routing::PathTransferMessage msg; ProtocolFrame& f = msg.T; f.N.Randomize(); diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index ff48f1e10..fbe8ad6bc 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -107,7 +107,7 @@ namespace llarp ObtainIPForAddr(const AlignedBuffer< 32 >& addr, bool serviceNode) = 0; virtual bool - HasAddress(const byte_t* addr) const = 0; + HasAddress(const AlignedBuffer< 32 >& addr) const = 0; /// return true if we have a pending job to build to a hidden service but /// it's not done yet @@ -177,7 +177,7 @@ namespace llarp llarp_buffer_t Buffer() { - return llarp::InitBuffer(payload.data(), payload.size()); + return llarp::Buffer(payload); } }; @@ -351,7 +351,7 @@ namespace llarp bool GetCachedSessionKeyFor(const ConvoTag& remote, - const byte_t*& secret) const override; + SharedSecret& secret) const override; void PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret) override; diff --git a/llarp/service/handler.hpp b/llarp/service/handler.hpp index 28035d8bf..8d69091b6 100644 --- a/llarp/service/handler.hpp +++ b/llarp/service/handler.hpp @@ -20,7 +20,7 @@ namespace llarp virtual bool GetCachedSessionKeyFor(const ConvoTag& remote, - const byte_t*& secret) const = 0; + SharedSecret& secret) const = 0; virtual void PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret) = 0; diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index 7df2c2192..5552cb91b 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -154,7 +154,7 @@ namespace llarp bool ProtocolFrame::DecryptPayloadInto(llarp::Crypto* crypto, - const byte_t* sharedkey, + const SharedSecret& sharedkey, ProtocolMessage& msg) const { Encrypted_t tmp = D; @@ -166,7 +166,7 @@ namespace llarp bool ProtocolFrame::EncryptAndSign(llarp::Crypto* crypto, const ProtocolMessage& msg, - const byte_t* sessionKey, + const SharedSecret& sessionKey, const Identity& localIdent) { byte_t tmp[MAX_PROTOCOL_MESSAGE_SIZE]; @@ -325,7 +325,7 @@ namespace llarp llarp_threadpool_queue_job(worker, {dh, &AsyncFrameDecrypt::Work}); return true; } - const byte_t* shared = nullptr; + SharedSecret shared; if(!handler->GetCachedSessionKeyFor(T, shared)) { llarp::LogError("No cached session for T=", T); diff --git a/llarp/service/protocol.hpp b/llarp/service/protocol.hpp index 3db68d463..e60909f9f 100644 --- a/llarp/service/protocol.hpp +++ b/llarp/service/protocol.hpp @@ -99,7 +99,7 @@ namespace llarp bool EncryptAndSign(llarp::Crypto* c, const ProtocolMessage& msg, - const byte_t* sharedkey, const Identity& localIdent); + const SharedSecret& sharedkey, const Identity& localIdent); bool AsyncDecryptAndVerify(llarp::Logic* logic, llarp::Crypto* c, @@ -108,7 +108,7 @@ namespace llarp IDataHandler* handler) const; bool - DecryptPayloadInto(llarp::Crypto* c, const byte_t* sharedkey, + DecryptPayloadInto(llarp::Crypto* c, const SharedSecret& sharedkey, ProtocolMessage& into) const; bool diff --git a/llarp/service/tag.hpp b/llarp/service/tag.hpp index 7a5e01d22..b8703f597 100644 --- a/llarp/service/tag.hpp +++ b/llarp/service/tag.hpp @@ -29,7 +29,7 @@ namespace llarp // evidently, does nothing on LP64 systems (where size_t is *already* // unsigned long but zero-extends this on LLP64 systems std::copy(str.begin(), str.begin() + std::min(16UL, str.size()), - as_array().begin()); + begin()); } Tag& @@ -43,7 +43,7 @@ namespace llarp operator=(const std::string& str) { std::copy(str.begin(), str.begin() + std::min(16UL, str.size()), - as_array().begin()); + begin()); return *this; } diff --git a/test/obtain_exit_unittest.cpp b/test/obtain_exit_unittest.cpp index afbb4cf0d..b3d149c46 100644 --- a/test/obtain_exit_unittest.cpp +++ b/test/obtain_exit_unittest.cpp @@ -7,11 +7,10 @@ using ObtainExitMessage = llarp::routing::ObtainExitMessage; class ObtainExitTest : public ::testing::Test { public: - llarp::Crypto crypto; + llarp::Crypto crypto; llarp::SecretKey alice; - ObtainExitTest() - : crypto(llarp::Crypto::sodium{}) + ObtainExitTest() : crypto(llarp::Crypto::sodium{}) { } @@ -32,9 +31,9 @@ TEST_F(ObtainExitTest, TestSignVerify) msg.Z.Zero(); msg.S = llarp::randint(); msg.T = llarp::randint(); - ASSERT_TRUE(msg.Sign(&crypto, alice)); - ASSERT_TRUE(msg.Verify(&crypto)); - ASSERT_TRUE(msg.I == llarp::PubKey(llarp::seckey_topublic(alice))); - ASSERT_FALSE(msg.version != LLARP_PROTO_VERSION); - ASSERT_FALSE(msg.Z.IsZero()); + EXPECT_TRUE(msg.Sign(&crypto, alice)); + EXPECT_TRUE(msg.Verify(&crypto)); + EXPECT_TRUE(msg.I == llarp::PubKey(llarp::seckey_topublic(alice))); + EXPECT_FALSE(msg.version != LLARP_PROTO_VERSION); + EXPECT_FALSE(msg.Z.IsZero()); }; diff --git a/test/test_llarp_aligned.cpp b/test/test_llarp_aligned.cpp index bc1c01c3d..dbd2c6070 100644 --- a/test/test_llarp_aligned.cpp +++ b/test/test_llarp_aligned.cpp @@ -66,7 +66,7 @@ TYPED_TEST(AlignedBufferTest, AltConstructors) Buffer c(b.as_array()); EXPECT_FALSE(c.IsZero()); - Buffer d(c.as_array().data()); + Buffer d(c.data()); EXPECT_FALSE(d.IsZero()); }