lokinet/llarp/service/protocol.cpp

533 lines
16 KiB
C++
Raw Permalink Normal View History

#include "protocol.hpp"
#include <llarp/path/path.hpp>
#include <llarp/routing/handler.hpp>
#include <llarp/util/buffer.hpp>
#include <llarp/util/mem.hpp>
#include <llarp/util/meta/memfn.hpp>
#include "endpoint.hpp"
#include <llarp/router/abstractrouter.hpp>
2019-07-30 23:42:13 +00:00
#include <utility>
2018-07-19 04:58:39 +00:00
namespace llarp
{
namespace service
{
2018-07-22 23:14:29 +00:00
ProtocolMessage::ProtocolMessage()
2018-07-19 04:58:39 +00:00
{
2018-08-09 19:02:17 +00:00
tag.Zero();
2018-07-19 04:58:39 +00:00
}
2018-08-09 19:02:17 +00:00
ProtocolMessage::ProtocolMessage(const ConvoTag& t) : tag(t)
Config file improvements (#1397) * Config file API/comment improvements API improvements: ================= Make the config API use position-independent tag parameters (Required, Default{123}, MultiValue) rather than a sequence of bools with overloads. For example, instead of: conf.defineOption<int>("a", "b", false, true, 123, [] { ... }); you now write: conf.defineOption<int>("a", "b", MultiValue, Default{123}, [] { ... }); The tags are: - Required - MultiValue - Default{value} plus new abilities (see below): - Hidden - RelayOnly - ClientOnly - Comment{"line1", "line2", "line3"} Made option definition more powerful: ===================================== - `Hidden` allows you to define an option that won't show up in the generated config file if it isn't set. - `RelayOnly`/`ClientOnly` sets up an option that is only accepted and only shows up for relay or client configs. (If neither is specified the option shows up in both modes). - `Comment{...}` lets the option comments be specified as part of the defineOption. Comment improvements ==================== - Rewrote comments for various options to expand on details. - Inlined all the comments with the option definitions. - Several options that were missing comments got comments added. - Made various options for deprecated and or internal options hidden by default so that they don't show up in a default config file. - show the section comment (but not option comments) *after* the [section] tag instead of before it as it makes more sense that way (particularly for the [bind] section which has a new long comment to describe how it works). Disable profiling by default ============================ We had this weird state where we use and store profiling by default but never *load* it when starting up. This commit makes us just not use profiling at all unless explicitly enabled. Other misc changes: =================== - change default worker threads to 0 (= num cpus) instead of 1, and fix it to allow 0. - Actually apply worker-threads option - fixed default data-dir value erroneously having quotes around it - reordered ifname/ifaddr/mapaddr (was previously mapaddr/ifaddr/ifname) as mapaddr is a sort of specialization of ifaddr and so makes more sense to come after it (particularly because it now references ifaddr in its help message). - removed peer-stats option (since we always require it for relays and never use it for clients) - removed router profiles filename option (this doesn't need to be configurable) - removed defunct `service-node-seed` option - Change default logging output file to "" (which means stdout), and also made "-" work for stdout. * Router hive compilation fixes * Comments for SNApp SRV settings in ini file * Add extra blank line after section comments * Better deprecated option handling Allow {client,relay}-only options in {relay,client} configs to be specified as implicitly deprecated options: they warn, and don't set anything. Add an explicit `Deprecated` tag and move deprecated option handling into definition.cpp. * Move backwards compat options into section definitions Keep the "addBackwardsCompatibleConfigOptions" only for options in sections that no longer exist. * Fix INI parsing issues & C++17-ify - don't allow inline comments because it seems they aren't allowed in ini formats in general, and is going to cause problems if there is a comment character in a value (e.g. an exit auth string). Additionally it was breaking on a line such as: # some comment; see? because it was treating only `; see?` as the comment and then producing an error message about the rest of the line being invalid. - make section parsing stricter: the `[` and `]` have to be at the beginning at end of the line now (after stripping whitespace). - Move whitespace stripping to the top since everything in here does it. - chop off string_view suffix/prefix rather than maintaining position values - fix potential infinite loop/segfault when given a line such as `]foo[` * Make config parsing failure fatal Load() LogError's and returns false on failure, so we weren't aborting on config file errors. * Formatting: allow `{}` for empty functions/structs Instead of using two lines when empty: { } * Make default dns bind 127.0.0.1 on non-Linux * Don't show empty section; fix tests We can conceivably have sections that only make sense for clients or relays, and so want to completely omit that section if we have no options for the type of config being generated. Also fixes missing empty lines between tests. Co-authored-by: Thomas Winget <tewinget@gmail.com>
2020-10-07 22:22:58 +00:00
{}
2018-07-19 04:58:39 +00:00
2019-07-30 23:42:13 +00:00
ProtocolMessage::~ProtocolMessage() = default;
2018-07-19 04:58:39 +00:00
void
ProtocolMessage::PutBuffer(const llarp_buffer_t& buf)
2018-07-19 04:58:39 +00:00
{
payload.resize(buf.sz);
memcpy(payload.data(), buf.base, buf.sz);
}
2018-07-22 23:14:29 +00:00
2018-08-09 19:02:17 +00:00
void
ProtocolMessage::ProcessAsync(
path::Path_ptr path, PathID_t from, std::shared_ptr<ProtocolMessage> self)
2018-08-09 19:02:17 +00:00
{
if (!self->handler->HandleDataMessage(path, from, self))
2019-06-14 13:13:06 +00:00
LogWarn("failed to handle data message from ", path->Name());
2018-08-09 19:02:17 +00:00
}
bool
ProtocolMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
2018-08-09 19:02:17 +00:00
{
bool read = false;
if (!BEncodeMaybeReadDictInt("a", proto, read, k, buf))
2018-08-09 19:02:17 +00:00
return false;
if (k.startswith("d"))
2018-08-09 19:02:17 +00:00
{
llarp_buffer_t strbuf;
if (!bencode_read_string(buf, &strbuf))
2018-08-09 19:02:17 +00:00
return false;
PutBuffer(strbuf);
return true;
}
if (!BEncodeMaybeReadDictEntry("i", introReply, read, k, buf))
2018-08-09 19:02:17 +00:00
return false;
if (!BEncodeMaybeReadDictInt("n", seqno, read, k, buf))
return false;
if (!BEncodeMaybeReadDictEntry("s", sender, read, k, buf))
2018-08-09 19:02:17 +00:00
return false;
if (!BEncodeMaybeReadDictEntry("t", tag, read, k, buf))
2018-08-09 19:02:17 +00:00
return false;
if (!BEncodeMaybeReadDictInt("v", version, read, k, buf))
2018-08-09 19:02:17 +00:00
return false;
return read;
}
bool
ProtocolMessage::BEncode(llarp_buffer_t* buf) const
{
if (!bencode_start_dict(buf))
2018-08-09 19:02:17 +00:00
return false;
if (!BEncodeWriteDictInt("a", proto, buf))
2018-08-09 19:02:17 +00:00
return false;
2020-06-17 13:07:05 +00:00
if (not payload.empty())
{
if (!bencode_write_bytestring(buf, "d", 1))
return false;
if (!bencode_write_bytestring(buf, payload.data(), payload.size()))
return false;
}
if (!BEncodeWriteDictEntry("i", introReply, buf))
2018-08-09 19:02:17 +00:00
return false;
if (!BEncodeWriteDictInt("n", seqno, buf))
return false;
if (!BEncodeWriteDictEntry("s", sender, buf))
2018-08-09 19:02:17 +00:00
return false;
if (!tag.IsZero())
2018-08-09 19:02:17 +00:00
{
if (!BEncodeWriteDictEntry("t", tag, buf))
2018-08-09 19:02:17 +00:00
return false;
}
if (!BEncodeWriteDictInt("v", version, buf))
2018-08-09 19:02:17 +00:00
return false;
return bencode_end(buf);
}
std::vector<char>
ProtocolMessage::EncodeAuthInfo() const
2020-06-17 13:07:05 +00:00
{
std::array<byte_t, 1024> info;
llarp_buffer_t buf{info};
if (not bencode_start_dict(&buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not BEncodeWriteDictInt("a", proto, &buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not BEncodeWriteDictEntry("i", introReply, &buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not BEncodeWriteDictEntry("s", sender, &buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not BEncodeWriteDictEntry("t", tag, &buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not BEncodeWriteDictInt("v", version, &buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
if (not bencode_end(&buf))
throw std::runtime_error("impossibly small buffer");
2020-06-17 13:07:05 +00:00
const std::size_t encodedSize = buf.cur - buf.base;
std::vector<char> data;
2020-06-17 13:07:05 +00:00
data.resize(encodedSize);
std::copy_n(buf.base, encodedSize, data.data());
return data;
}
2019-07-30 23:42:13 +00:00
ProtocolFrame::~ProtocolFrame() = default;
2018-07-22 23:14:29 +00:00
bool
ProtocolFrame::BEncode(llarp_buffer_t* buf) const
{
if (!bencode_start_dict(buf))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeWriteDictMsgType(buf, "A", "H"))
2018-08-12 17:22:29 +00:00
return false;
if (!C.IsZero())
2018-07-22 23:14:29 +00:00
{
if (!BEncodeWriteDictEntry("C", C, buf))
2018-07-22 23:14:29 +00:00
return false;
}
if (D.size() > 0)
2019-03-08 16:00:45 +00:00
{
if (!BEncodeWriteDictEntry("D", D, buf))
2019-03-08 16:00:45 +00:00
return false;
}
if (!BEncodeWriteDictEntry("F", F, buf))
return false;
if (!N.IsZero())
2019-03-08 16:00:45 +00:00
{
if (!BEncodeWriteDictEntry("N", N, buf))
2019-03-08 16:00:45 +00:00
return false;
}
if (R)
2019-03-08 16:00:45 +00:00
{
if (!BEncodeWriteDictInt("R", R, buf))
2019-03-08 16:00:45 +00:00
return false;
}
if (!T.IsZero())
2018-08-09 19:02:17 +00:00
{
if (!BEncodeWriteDictEntry("T", T, buf))
2018-08-09 19:02:17 +00:00
return false;
}
if (!BEncodeWriteDictInt("V", version, buf))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeWriteDictEntry("Z", Z, buf))
2018-07-22 23:14:29 +00:00
return false;
return bencode_end(buf);
}
bool
ProtocolFrame::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val)
2018-07-22 23:14:29 +00:00
{
bool read = false;
if (key.startswith("A"))
2018-08-12 17:22:29 +00:00
{
llarp_buffer_t strbuf;
if (!bencode_read_string(val, &strbuf))
2018-08-12 17:22:29 +00:00
return false;
if (strbuf.sz != 1)
2018-08-12 17:22:29 +00:00
return false;
return *strbuf.cur == 'H';
}
if (!BEncodeMaybeReadDictEntry("D", D, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeMaybeReadDictEntry("F", F, read, key, val))
return false;
if (!BEncodeMaybeReadDictEntry("C", C, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeMaybeReadDictEntry("N", N, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeMaybeReadDictInt("S", S, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeMaybeReadDictInt("R", R, read, key, val))
2019-03-08 16:00:45 +00:00
return false;
if (!BEncodeMaybeReadDictEntry("T", T, read, key, val))
2018-08-09 19:02:17 +00:00
return false;
2022-05-26 15:59:44 +00:00
if (!BEncodeMaybeVerifyVersion("V", version, llarp::constants::proto_version, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
if (!BEncodeMaybeReadDictEntry("Z", Z, read, key, val))
2018-07-22 23:14:29 +00:00
return false;
return read;
}
2018-08-09 19:02:17 +00:00
bool
ProtocolFrame::DecryptPayloadInto(const SharedSecret& sharedkey, ProtocolMessage& msg) const
2018-08-09 19:02:17 +00:00
{
2018-12-20 16:49:05 +00:00
Encrypted_t tmp = D;
auto buf = tmp.Buffer();
CryptoManager::instance()->xchacha20(*buf, sharedkey, N);
2019-05-24 02:01:36 +00:00
return bencode_decode_dict(msg, buf);
2018-08-09 19:02:17 +00:00
}
2019-03-08 16:00:45 +00:00
bool
ProtocolFrame::Sign(const Identity& localIdent)
2019-03-08 16:00:45 +00:00
{
Z.Zero();
std::array<byte_t, MAX_PROTOCOL_MESSAGE_SIZE> tmp;
2019-03-08 16:00:45 +00:00
llarp_buffer_t buf(tmp);
// encode
if (!BEncode(&buf))
2019-03-08 16:00:45 +00:00
{
LogError("message too big to encode");
2019-03-08 16:00:45 +00:00
return false;
}
// rewind
buf.sz = buf.cur - buf.base;
2019-03-08 16:00:45 +00:00
buf.cur = buf.base;
// sign
return localIdent.Sign(Z, buf);
2019-03-08 16:00:45 +00:00
}
2018-07-22 23:14:29 +00:00
bool
ProtocolFrame::EncryptAndSign(
const ProtocolMessage& msg, const SharedSecret& sessionKey, const Identity& localIdent)
2018-07-22 23:14:29 +00:00
{
std::array<byte_t, MAX_PROTOCOL_MESSAGE_SIZE> tmp;
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
2018-08-14 21:17:18 +00:00
// encode message
if (!msg.BEncode(&buf))
2018-09-19 17:04:55 +00:00
{
LogError("message too big to encode");
2018-08-14 21:17:18 +00:00
return false;
2018-09-19 17:04:55 +00:00
}
2018-08-14 21:17:18 +00:00
// rewind
buf.sz = buf.cur - buf.base;
2018-08-14 21:17:18 +00:00
buf.cur = buf.base;
// encrypt
CryptoManager::instance()->xchacha20(buf, sessionKey, N);
2018-08-14 21:17:18 +00:00
// put encrypted buffer
D = buf;
// zero out signature
Z.Zero();
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf2(tmp);
2018-08-14 21:17:18 +00:00
// encode frame
if (!BEncode(&buf2))
2018-09-19 17:04:55 +00:00
{
LogError("frame too big to encode");
DumpBuffer(buf2);
2018-07-22 23:14:29 +00:00
return false;
2018-09-19 17:04:55 +00:00
}
2018-07-22 23:14:29 +00:00
// rewind
buf2.sz = buf2.cur - buf2.base;
2018-09-21 12:47:07 +00:00
buf2.cur = buf2.base;
2018-07-22 23:14:29 +00:00
// sign
if (!localIdent.Sign(Z, buf2))
2018-09-19 17:04:55 +00:00
{
LogError("failed to sign? wtf?!");
2018-09-19 17:04:55 +00:00
return false;
}
return true;
2018-07-22 23:14:29 +00:00
}
2018-08-14 21:17:18 +00:00
struct AsyncFrameDecrypt
2018-08-09 19:02:17 +00:00
{
2019-06-14 13:13:06 +00:00
path::Path_ptr path;
EventLoop_ptr loop;
std::shared_ptr<ProtocolMessage> msg;
const Identity& m_LocalIdentity;
2020-05-28 11:07:32 +00:00
Endpoint* handler;
2018-09-17 16:12:42 +00:00
const ProtocolFrame frame;
2019-04-10 13:19:32 +00:00
const Introduction fromIntro;
2018-08-09 19:02:17 +00:00
AsyncFrameDecrypt(
2021-03-02 15:23:38 +00:00
EventLoop_ptr l,
const Identity& localIdent,
2020-05-28 11:07:32 +00:00
Endpoint* h,
std::shared_ptr<ProtocolMessage> m,
const ProtocolFrame& f,
const Introduction& recvIntro)
: loop(std::move(l))
2019-07-30 23:42:13 +00:00
, msg(std::move(m))
, m_LocalIdentity(localIdent)
2018-08-09 19:02:17 +00:00
, handler(h)
, frame(f)
2019-04-10 13:19:32 +00:00
, fromIntro(recvIntro)
Config file improvements (#1397) * Config file API/comment improvements API improvements: ================= Make the config API use position-independent tag parameters (Required, Default{123}, MultiValue) rather than a sequence of bools with overloads. For example, instead of: conf.defineOption<int>("a", "b", false, true, 123, [] { ... }); you now write: conf.defineOption<int>("a", "b", MultiValue, Default{123}, [] { ... }); The tags are: - Required - MultiValue - Default{value} plus new abilities (see below): - Hidden - RelayOnly - ClientOnly - Comment{"line1", "line2", "line3"} Made option definition more powerful: ===================================== - `Hidden` allows you to define an option that won't show up in the generated config file if it isn't set. - `RelayOnly`/`ClientOnly` sets up an option that is only accepted and only shows up for relay or client configs. (If neither is specified the option shows up in both modes). - `Comment{...}` lets the option comments be specified as part of the defineOption. Comment improvements ==================== - Rewrote comments for various options to expand on details. - Inlined all the comments with the option definitions. - Several options that were missing comments got comments added. - Made various options for deprecated and or internal options hidden by default so that they don't show up in a default config file. - show the section comment (but not option comments) *after* the [section] tag instead of before it as it makes more sense that way (particularly for the [bind] section which has a new long comment to describe how it works). Disable profiling by default ============================ We had this weird state where we use and store profiling by default but never *load* it when starting up. This commit makes us just not use profiling at all unless explicitly enabled. Other misc changes: =================== - change default worker threads to 0 (= num cpus) instead of 1, and fix it to allow 0. - Actually apply worker-threads option - fixed default data-dir value erroneously having quotes around it - reordered ifname/ifaddr/mapaddr (was previously mapaddr/ifaddr/ifname) as mapaddr is a sort of specialization of ifaddr and so makes more sense to come after it (particularly because it now references ifaddr in its help message). - removed peer-stats option (since we always require it for relays and never use it for clients) - removed router profiles filename option (this doesn't need to be configurable) - removed defunct `service-node-seed` option - Change default logging output file to "" (which means stdout), and also made "-" work for stdout. * Router hive compilation fixes * Comments for SNApp SRV settings in ini file * Add extra blank line after section comments * Better deprecated option handling Allow {client,relay}-only options in {relay,client} configs to be specified as implicitly deprecated options: they warn, and don't set anything. Add an explicit `Deprecated` tag and move deprecated option handling into definition.cpp. * Move backwards compat options into section definitions Keep the "addBackwardsCompatibleConfigOptions" only for options in sections that no longer exist. * Fix INI parsing issues & C++17-ify - don't allow inline comments because it seems they aren't allowed in ini formats in general, and is going to cause problems if there is a comment character in a value (e.g. an exit auth string). Additionally it was breaking on a line such as: # some comment; see? because it was treating only `; see?` as the comment and then producing an error message about the rest of the line being invalid. - make section parsing stricter: the `[` and `]` have to be at the beginning at end of the line now (after stripping whitespace). - Move whitespace stripping to the top since everything in here does it. - chop off string_view suffix/prefix rather than maintaining position values - fix potential infinite loop/segfault when given a line such as `]foo[` * Make config parsing failure fatal Load() LogError's and returns false on failure, so we weren't aborting on config file errors. * Formatting: allow `{}` for empty functions/structs Instead of using two lines when empty: { } * Make default dns bind 127.0.0.1 on non-Linux * Don't show empty section; fix tests We can conceivably have sections that only make sense for clients or relays, and so want to completely omit that section if we have no options for the type of config being generated. Also fixes missing empty lines between tests. Co-authored-by: Thomas Winget <tewinget@gmail.com>
2020-10-07 22:22:58 +00:00
{}
2018-08-09 19:02:17 +00:00
static void
2020-05-28 11:07:32 +00:00
Work(std::shared_ptr<AsyncFrameDecrypt> self)
2018-08-09 19:02:17 +00:00
{
2019-07-30 23:42:13 +00:00
auto crypto = CryptoManager::instance();
SharedSecret K;
SharedSecret sharedKey;
// copy
2018-09-17 16:12:42 +00:00
ProtocolFrame frame(self->frame);
if (!crypto->pqe_decrypt(self->frame.C, K, pq_keypair_to_secret(self->m_LocalIdentity.pq)))
2018-08-09 19:02:17 +00:00
{
LogError("pqke failed C=", self->frame.C);
2019-05-03 13:15:03 +00:00
self->msg.reset();
2018-08-09 19:02:17 +00:00
return;
}
2018-08-14 21:17:18 +00:00
// decrypt
auto buf = frame.D.Buffer();
2018-09-17 16:12:42 +00:00
crypto->xchacha20(*buf, K, self->frame.N);
if (!bencode_decode_dict(*self->msg, buf))
2018-08-09 19:02:17 +00:00
{
LogError("failed to decode inner protocol message");
DumpBuffer(*buf);
2019-05-03 13:15:03 +00:00
self->msg.reset();
2018-08-09 19:02:17 +00:00
return;
}
// verify signature of outer message after we parsed the inner message
if (!self->frame.Verify(self->msg->sender))
{
LogError(
"intro frame has invalid signature Z=",
self->frame.Z,
" from ",
self->msg->sender.Addr());
Dump<MAX_PROTOCOL_MESSAGE_SIZE>(self->frame);
Dump<MAX_PROTOCOL_MESSAGE_SIZE>(*self->msg);
2019-05-03 13:15:03 +00:00
self->msg.reset();
return;
}
2019-04-12 18:37:43 +00:00
if (self->handler->HasConvoTag(self->msg->tag))
2019-04-12 18:37:43 +00:00
{
LogError("dropping duplicate convo tag T=", self->msg->tag);
2019-04-12 18:37:43 +00:00
// TODO: send convotag reset
2019-05-03 13:15:03 +00:00
self->msg.reset();
2019-04-12 18:37:43 +00:00
return;
}
// PKE (A, B, N)
SharedSecret sharedSecret;
path_dh_func dh_server = util::memFn(&Crypto::dh_server, CryptoManager::instance());
if (!self->m_LocalIdentity.KeyExchange(
dh_server, sharedSecret, self->msg->sender, self->frame.N))
{
LogError("x25519 key exchange failed");
Dump<MAX_PROTOCOL_MESSAGE_SIZE>(self->frame);
2019-05-03 13:15:03 +00:00
self->msg.reset();
return;
}
std::array<byte_t, 64> tmp;
// K
std::copy(K.begin(), K.end(), tmp.begin());
// S = HS( K + PKE( A, B, N))
std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32);
2019-02-02 23:12:42 +00:00
crypto->shorthash(sharedKey, llarp_buffer_t(tmp));
std::shared_ptr<ProtocolMessage> msg = std::move(self->msg);
path::Path_ptr path = std::move(self->path);
const PathID_t from = self->frame.F;
2020-05-28 11:07:32 +00:00
msg->handler = self->handler;
2020-06-17 13:07:05 +00:00
self->handler->AsyncProcessAuthMessage(
msg,
2020-05-28 11:07:32 +00:00
[path, msg, from, handler = self->handler, fromIntro = self->fromIntro, sharedKey](
2020-05-28 11:21:47 +00:00
AuthResult result) {
2021-02-24 12:14:15 +00:00
if (result.code == AuthResultCode::eAuthAccepted)
2020-05-28 11:07:32 +00:00
{
if (handler->WantsOutboundSession(msg->sender.Addr()))
{
handler->PutSenderFor(msg->tag, msg->sender, false);
}
else
{
handler->PutSenderFor(msg->tag, msg->sender, true);
}
handler->PutReplyIntroFor(msg->tag, msg->introReply);
2020-05-28 11:07:32 +00:00
handler->PutCachedSessionKeyFor(msg->tag, sharedKey);
handler->SendAuthResult(path, from, msg->tag, result);
LogInfo("auth okay for T=", msg->tag, " from ", msg->sender.Addr());
2020-05-28 11:07:32 +00:00
ProtocolMessage::ProcessAsync(path, from, msg);
}
else
{
LogWarn("auth not okay for T=", msg->tag, ": ", result.reason);
}
handler->Pump(time_now_ms());
2020-05-28 11:07:32 +00:00
});
2018-08-09 19:02:17 +00:00
}
};
2018-08-14 21:17:18 +00:00
ProtocolFrame&
ProtocolFrame::operator=(const ProtocolFrame& other)
{
C = other.C;
D = other.D;
F = other.F;
N = other.N;
Z = other.Z;
T = other.T;
R = other.R;
S = other.S;
version = other.version;
2018-08-14 21:17:18 +00:00
return *this;
}
2019-11-28 23:08:02 +00:00
struct AsyncDecrypt
{
ServiceInfo si;
SharedSecret shared;
ProtocolFrame frame;
};
2018-08-09 19:02:17 +00:00
bool
2019-07-09 13:47:24 +00:00
ProtocolFrame::AsyncDecryptAndVerify(
2021-03-02 15:23:38 +00:00
EventLoop_ptr loop,
path::Path_ptr recvPath,
const Identity& localIdent,
2021-01-01 18:55:31 +00:00
Endpoint* handler,
std::function<void(std::shared_ptr<ProtocolMessage>)> hook) const
2018-08-09 19:02:17 +00:00
{
auto msg = std::make_shared<ProtocolMessage>();
2019-11-28 23:08:02 +00:00
msg->handler = handler;
if (T.IsZero())
2018-08-09 19:02:17 +00:00
{
// we need to dh
2020-05-28 11:07:32 +00:00
auto dh = std::make_shared<AsyncFrameDecrypt>(
loop, localIdent, handler, msg, *this, recvPath->intro);
2019-06-14 13:13:06 +00:00
dh->path = recvPath;
handler->Router()->QueueWork([dh = std::move(dh)] { return AsyncFrameDecrypt::Work(dh); });
2020-05-20 11:41:42 +00:00
return true;
2018-08-09 19:02:17 +00:00
}
2019-11-28 23:08:02 +00:00
2020-05-28 11:07:32 +00:00
auto v = std::make_shared<AsyncDecrypt>();
2019-11-28 23:08:02 +00:00
if (!handler->GetCachedSessionKeyFor(T, v->shared))
2018-08-09 19:02:17 +00:00
{
LogError("No cached session for T=", T);
return false;
2018-08-09 19:02:17 +00:00
}
if (v->shared.IsZero())
{
LogError("bad cached session key for T=", T);
return false;
}
2019-11-28 23:08:02 +00:00
if (!handler->GetSenderFor(T, v->si))
2018-08-09 19:02:17 +00:00
{
LogError("No sender for T=", T);
2018-08-09 19:02:17 +00:00
return false;
}
if (v->si.Addr().IsZero())
{
LogError("Bad sender for T=", T);
return false;
}
2019-11-28 23:08:02 +00:00
v->frame = *this;
auto callback = [loop, hook](std::shared_ptr<ProtocolMessage> msg) {
2021-01-01 18:55:31 +00:00
if (hook)
{
2021-03-02 15:23:38 +00:00
loop->call([msg, hook]() { hook(msg); });
}
2021-01-01 18:55:31 +00:00
};
handler->Router()->QueueWork(
[v, msg = std::move(msg), recvPath = std::move(recvPath), callback, handler]() {
auto resetTag = [handler, tag = v->frame.T, from = v->frame.F, path = recvPath]() {
handler->ResetConvoTag(tag, path, from);
};
2021-01-01 18:55:31 +00:00
if (not v->frame.Verify(v->si))
{
LogError("Signature failure from ", v->si.Addr());
handler->Loop()->call_soon(resetTag);
2021-01-01 18:55:31 +00:00
return;
}
if (not v->frame.DecryptPayloadInto(v->shared, *msg))
{
LogError("failed to decrypt message from ", v->si.Addr());
handler->Loop()->call_soon(resetTag);
2021-01-01 18:55:31 +00:00
return;
}
callback(msg);
RecvDataEvent ev;
ev.fromPath = std::move(recvPath);
ev.pathid = v->frame.F;
2021-03-11 13:34:14 +00:00
auto* handler = msg->handler;
2021-01-01 18:55:31 +00:00
ev.msg = std::move(msg);
2021-03-08 21:15:07 +00:00
handler->QueueRecvData(std::move(ev));
2021-01-01 18:55:31 +00:00
});
2020-05-20 11:41:42 +00:00
return true;
2018-08-09 19:02:17 +00:00
}
2018-09-17 15:32:37 +00:00
bool
ProtocolFrame::operator==(const ProtocolFrame& other) const
{
return C == other.C && D == other.D && N == other.N && Z == other.Z && T == other.T
&& S == other.S && version == other.version;
2018-09-17 15:32:37 +00:00
}
2018-07-22 23:14:29 +00:00
bool
2019-08-02 09:27:27 +00:00
ProtocolFrame::Verify(const ServiceInfo& svc) const
2018-07-22 23:14:29 +00:00
{
2018-09-17 13:28:26 +00:00
ProtocolFrame copy(*this);
2018-07-22 23:14:29 +00:00
// save signature
// zero out signature for verify
2018-08-09 19:02:17 +00:00
copy.Z.Zero();
2018-07-22 23:14:29 +00:00
// serialize
std::array<byte_t, MAX_PROTOCOL_MESSAGE_SIZE> tmp;
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
if (!copy.BEncode(&buf))
2018-07-22 23:14:29 +00:00
{
LogError("bencode fail");
2018-09-17 15:32:37 +00:00
return false;
2018-07-22 23:14:29 +00:00
}
2018-09-17 15:32:37 +00:00
// rewind buffer
buf.sz = buf.cur - buf.base;
2018-09-17 15:32:37 +00:00
buf.cur = buf.base;
// verify
2019-08-02 09:27:27 +00:00
return svc.Verify(buf, Z);
2018-07-22 23:14:29 +00:00
}
bool
ProtocolFrame::HandleMessage(routing::IMessageHandler* h, AbstractRouter* /*r*/) const
{
return h->HandleHiddenServiceFrame(*this);
}
2018-07-19 04:58:39 +00:00
} // namespace service
} // namespace llarp