lokinet/llarp/router_contact.cpp

576 lines
13 KiB
C++
Raw Normal View History

#include "router_contact.hpp"
#include "constants/version.hpp"
#include "crypto/crypto.hpp"
#include "net/net.hpp"
#include "util/bencode.hpp"
#include "util/buffer.hpp"
#include "util/logging/logger.hpp"
#include "util/mem.hpp"
#include "util/printer.hpp"
#include "util/time.hpp"
#include <oxenmq/bt_serialize.h>
2018-08-31 12:46:54 +00:00
#include <fstream>
#include "util/fs.hpp"
2018-08-31 12:46:54 +00:00
2018-08-30 18:48:43 +00:00
namespace llarp
{
NetID&
2019-01-05 00:49:06 +00:00
NetID::DefaultValue()
{
static NetID defaultID(reinterpret_cast<const byte_t*>(llarp::DEFAULT_NETID));
2019-01-05 00:49:06 +00:00
return defaultID;
}
2019-08-26 23:29:17 +00:00
bool RouterContact::BlockBogons = true;
#ifdef TESTNET
// 1 minute for testnet
2020-02-24 19:40:45 +00:00
llarp_time_t RouterContact::Lifetime = 1min;
#else
2018-12-19 17:48:29 +00:00
/// 1 day for real network
2020-02-24 19:40:45 +00:00
llarp_time_t RouterContact::Lifetime = 24h;
#endif
/// an RC inserted long enough ago (4 hrs) is considered stale and is removed
2020-02-24 19:40:45 +00:00
llarp_time_t RouterContact::StaleInsertionAge = 4h;
/// update RCs shortly before they are about to expire
llarp_time_t RouterContact::UpdateInterval = RouterContact::StaleInsertionAge - 5min;
2019-01-02 22:21:29 +00:00
NetID::NetID(const byte_t* val)
2019-01-05 00:49:06 +00:00
{
size_t len = strnlen(reinterpret_cast<const char*>(val), size());
2019-01-05 00:49:06 +00:00
std::copy(val, val + len, begin());
}
NetID::NetID() : NetID(DefaultValue().data())
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
{}
bool
NetID::operator==(const NetID& other) const
{
2018-12-28 15:04:05 +00:00
return ToString() == other.ToString();
}
std::string
NetID::ToString() const
{
auto term = std::find(begin(), end(), '\0');
return std::string(begin(), term);
}
bool
NetID::BDecode(llarp_buffer_t* buf)
{
Zero();
llarp_buffer_t strbuf;
if (!bencode_read_string(buf, &strbuf))
return false;
2019-08-26 23:29:17 +00:00
if (strbuf.sz > size())
return false;
std::copy(strbuf.base, strbuf.base + strbuf.sz, begin());
return true;
}
bool
NetID::BEncode(llarp_buffer_t* buf) const
{
auto term = std::find(begin(), end(), '\0');
return bencode_write_bytestring(buf, data(), std::distance(begin(), term));
}
2018-08-30 18:48:43 +00:00
bool
RouterContact::BEncode(llarp_buffer_t* buf) const
{
if (version == 0)
return BEncodeSignedSection(buf);
else if (version == 1)
{
// TODO: heapless serialization for this in lokimq's bt serialization.
2020-09-29 00:07:40 +00:00
if (not buf->writef("li1e%zu:", signature.size()))
return false;
if (not buf->write(signature.begin(), signature.end()))
return false;
if (not buf->write(signed_bt_dict.begin(), signed_bt_dict.end()))
return false;
if (not buf->writef("e"))
return false;
return true;
}
return false;
}
std::ostream&
RouterContact::ToTXTRecord(std::ostream& out) const
{
for (const auto& addr : addrs)
{
out << "ai_addr=" << addr.toIpAddress() << "; ";
out << "ai_pk=" << addr.pubkey.ToHex() << "; ";
}
out << "updated=" << last_updated.count() << "; ";
out << "onion_pk=" << enckey.ToHex() << "; ";
if (routerVersion.has_value())
out << "router_version=" << routerVersion->ToString() << "; ";
return out;
}
bool
RouterContact::BEncodeSignedSection(llarp_buffer_t* buf) const
2018-05-13 18:07:36 +00:00
{
2018-08-30 18:48:43 +00:00
/* write dict begin */
if (!bencode_start_dict(buf))
2018-06-10 14:05:48 +00:00
return false;
2018-08-30 18:48:43 +00:00
/* write ai if they exist */
if (!bencode_write_bytestring(buf, "a", 1))
2018-05-13 18:07:36 +00:00
return false;
if (!BEncodeWriteList(addrs.begin(), addrs.end(), buf))
2018-05-13 18:07:36 +00:00
return false;
/* write netid */
if (!bencode_write_bytestring(buf, "i", 1))
return false;
if (!netID.BEncode(buf))
return false;
2018-08-30 18:48:43 +00:00
/* write signing pubkey */
if (!bencode_write_bytestring(buf, "k", 1))
return false;
if (!pubkey.BEncode(buf))
2018-05-13 18:07:36 +00:00
return false;
2018-08-30 18:48:43 +00:00
std::string nick = Nick();
if (!nick.empty())
{
2018-08-30 18:48:43 +00:00
/* write nickname */
if (!bencode_write_bytestring(buf, "n", 1))
2019-08-26 23:29:17 +00:00
{
2018-08-30 18:48:43 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
if (!bencode_write_bytestring(buf, nick.c_str(), nick.size()))
2019-08-26 23:29:17 +00:00
{
2018-08-30 18:48:43 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
}
2018-05-13 18:07:36 +00:00
2018-08-30 18:48:43 +00:00
/* write encryption pubkey */
if (!bencode_write_bytestring(buf, "p", 1))
2018-05-13 18:07:36 +00:00
return false;
if (!enckey.BEncode(buf))
2018-05-13 18:07:36 +00:00
return false;
2020-01-25 16:28:07 +00:00
// write router version if present
if (routerVersion)
2020-01-25 16:28:07 +00:00
{
if (not BEncodeWriteDictEntry("r", *routerVersion, buf))
2020-01-25 16:28:07 +00:00
return false;
}
2018-08-30 18:48:43 +00:00
/* write last updated */
if (!bencode_write_bytestring(buf, "u", 1))
2018-08-30 18:48:43 +00:00
return false;
if (!bencode_write_uint64(buf, last_updated.count()))
2018-08-30 18:48:43 +00:00
return false;
2018-05-13 18:07:36 +00:00
/* write versions */
if (!bencode_write_uint64_entry(buf, "v", 1, version))
2018-08-30 18:48:43 +00:00
return false;
2020-08-19 19:10:11 +00:00
if (serializeExit)
{
/* write xi if they exist */
if (!bencode_write_bytestring(buf, "x", 1))
return false;
/* no exits anymore in RCs */
const std::vector<AlignedBuffer<8>> exits{};
if (!BEncodeWriteList(exits.begin(), exits.end(), buf))
return false;
}
if (version == 0)
{
/* write signature */
if (!bencode_write_bytestring(buf, "z", 1))
return false;
if (!signature.BEncode(buf))
return false;
}
2018-08-30 18:48:43 +00:00
return bencode_end(buf);
}
2018-05-10 23:32:46 +00:00
2018-08-31 13:51:24 +00:00
void
RouterContact::Clear()
{
addrs.clear();
signature.Zero();
nickname.Zero();
enckey.Zero();
pubkey.Zero();
routerVersion = std::optional<RouterVersion>{};
last_updated = 0s;
2018-08-31 13:51:24 +00:00
}
2019-02-11 17:14:43 +00:00
util::StatusObject
RouterContact::ExtractStatus() const
2019-02-08 19:43:25 +00:00
{
2021-03-05 17:31:52 +00:00
util::StatusObject obj{
{"lastUpdated", last_updated.count()},
{"publicRouter", IsPublicRouter()},
{"identity", pubkey.ToString()},
{"addresses", addrs}};
2019-08-19 22:25:40 +00:00
if (HasNick())
2019-08-26 23:29:17 +00:00
{
obj["nickname"] = Nick();
2019-08-26 23:29:17 +00:00
}
if (routerVersion)
2020-01-25 16:28:07 +00:00
{
obj["routerVersion"] = routerVersion->ToString();
}
2019-02-11 17:14:43 +00:00
return obj;
2019-02-08 19:43:25 +00:00
}
bool
RouterContact::BDecode(llarp_buffer_t* buf)
{
Clear();
if (*buf->cur == 'd') // old format
{
return DecodeVersion_0(buf);
}
else if (*buf->cur != 'l') // if not dict, should be new format and start with list
{
return false;
}
try
{
2020-10-02 14:06:08 +00:00
std::string_view buf_view(reinterpret_cast<char*>(buf->cur), buf->size_left());
oxenmq::bt_list_consumer btlist(buf_view);
uint64_t outer_version = btlist.consume_integer<uint64_t>();
if (outer_version == 1)
{
bool decode_result = DecodeVersion_1(btlist);
// advance the llarp_buffer_t since lokimq serialization is unaware of it.
buf->cur += btlist.current_buffer().data() - buf_view.data() + 1;
return decode_result;
}
else
{
llarp::LogWarn("Received RouterContact with unkown version (", outer_version, ")");
return false;
}
}
catch (const std::exception& e)
{
llarp::LogDebug("RouterContact::BDecode failed, reason: ", e.what());
}
return false;
}
bool
RouterContact::DecodeVersion_0(llarp_buffer_t* buf)
{
return bencode_decode_dict(*this, buf);
}
bool
RouterContact::DecodeVersion_1(oxenmq::bt_list_consumer& btlist)
{
auto signature_string = btlist.consume_string_view();
signed_bt_dict = btlist.consume_dict_data();
if (not btlist.is_finished())
{
llarp::LogDebug("RouterContact serialized list too long for specified version.");
return false;
}
llarp_buffer_t sigbuf(signature_string.data(), signature_string.size());
if (not signature.FromBytestring(&sigbuf))
{
llarp::LogDebug("RouterContact serialized signature had invalid length.");
return false;
}
llarp_buffer_t data_dict_buf(signed_bt_dict.data(), signed_bt_dict.size());
return bencode_decode_dict(*this, &data_dict_buf);
}
2018-08-30 18:48:43 +00:00
bool
RouterContact::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf)
2018-08-09 15:36:58 +00:00
{
2018-08-30 18:48:43 +00:00
bool read = false;
if (!BEncodeMaybeReadDictList("a", addrs, read, key, buf))
2018-08-09 15:36:58 +00:00
return false;
2018-08-30 18:48:43 +00:00
if (!BEncodeMaybeReadDictEntry("i", netID, read, key, buf))
return false;
if (!BEncodeMaybeReadDictEntry("k", pubkey, read, key, buf))
2018-08-09 15:36:58 +00:00
return false;
if (key == "r")
2020-01-25 16:28:07 +00:00
{
RouterVersion r;
if (not r.BDecode(buf))
2020-01-25 16:28:07 +00:00
return false;
routerVersion = r;
return true;
}
if (key == "n")
2018-08-31 13:51:24 +00:00
{
llarp_buffer_t strbuf;
if (!bencode_read_string(buf, &strbuf))
2019-08-26 23:29:17 +00:00
{
2018-08-31 13:51:24 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
if (strbuf.sz > llarp::AlignedBuffer<(32)>::size())
2019-08-26 23:29:17 +00:00
{
2018-08-31 13:51:24 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
2018-08-31 13:51:24 +00:00
nickname.Zero();
2019-01-02 22:21:29 +00:00
std::copy(strbuf.base, strbuf.base + strbuf.sz, nickname.begin());
2018-08-31 13:51:24 +00:00
return true;
}
2018-06-12 12:49:23 +00:00
if (!BEncodeMaybeReadDictEntry("p", enckey, read, key, buf))
2018-08-30 18:48:43 +00:00
return false;
2018-05-21 12:44:50 +00:00
if (!BEncodeMaybeReadDictInt("u", last_updated, read, key, buf))
2018-08-31 13:51:24 +00:00
return false;
if (!BEncodeMaybeReadDictInt("v", version, read, key, buf))
2018-08-30 18:48:43 +00:00
return false;
2018-05-10 23:32:46 +00:00
2020-08-19 19:10:11 +00:00
if (key == "x" and serializeExit)
{
return bencode_discard(buf);
}
2018-08-30 18:48:43 +00:00
if (!BEncodeMaybeReadDictEntry("z", signature, read, key, buf))
return false;
2018-08-30 18:48:43 +00:00
return read;
2018-05-10 23:32:46 +00:00
}
2018-08-31 12:46:54 +00:00
bool
RouterContact::IsPublicRouter() const
{
if (not routerVersion)
return false;
2019-08-26 23:29:17 +00:00
return !addrs.empty();
2018-08-31 12:46:54 +00:00
}
bool
RouterContact::HasNick() const
{
return nickname[0] != 0;
}
void
RouterContact::SetNick(std::string_view nick)
2018-08-31 12:46:54 +00:00
{
nickname.Zero();
std::copy(
nick.begin(), nick.begin() + std::min(nick.size(), nickname.size()), nickname.begin());
2018-08-31 12:46:54 +00:00
}
bool
RouterContact::IsExpired(llarp_time_t now) const
2019-07-15 16:56:09 +00:00
{
2019-09-09 11:36:21 +00:00
(void)now;
2019-09-09 10:37:26 +00:00
return false;
// return Age(now) >= Lifetime;
2019-07-15 16:56:09 +00:00
}
llarp_time_t
RouterContact::TimeUntilExpires(llarp_time_t now) const
{
2019-06-04 13:19:45 +00:00
const auto expiresAt = last_updated + Lifetime;
2020-02-24 19:40:45 +00:00
return now < expiresAt ? expiresAt - now : 0s;
2019-07-15 16:56:09 +00:00
}
llarp_time_t
RouterContact::Age(llarp_time_t now) const
{
2020-02-24 19:40:45 +00:00
return now > last_updated ? now - last_updated : 0s;
}
bool
RouterContact::ExpiresSoon(llarp_time_t now, llarp_time_t dlt) const
{
2019-07-15 16:56:09 +00:00
return TimeUntilExpires(now) <= dlt;
}
2018-08-31 12:46:54 +00:00
std::string
RouterContact::Nick() const
{
auto term = std::find(nickname.begin(), nickname.end(), '\0');
return std::string(nickname.begin(), term);
2018-08-31 12:46:54 +00:00
}
bool
RouterContact::Sign(const SecretKey& secretkey)
2018-08-31 12:46:54 +00:00
{
2019-02-02 23:12:42 +00:00
pubkey = llarp::seckey_topublic(secretkey);
std::array<byte_t, MAX_RC_SIZE> tmp;
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
2018-08-31 12:46:54 +00:00
signature.Zero();
2018-11-19 22:45:37 +00:00
last_updated = time_now_ms();
if (!BEncodeSignedSection(&buf))
2019-08-26 23:29:17 +00:00
{
2018-08-31 12:46:54 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
buf.sz = buf.cur - buf.base;
2018-08-31 12:46:54 +00:00
buf.cur = buf.base;
signed_bt_dict = std::string(reinterpret_cast<char*>(buf.base), buf.sz);
if (version == 0 or version == 1)
{
return CryptoManager::instance()->sign(signature, secretkey, buf);
}
return false;
2018-08-31 12:46:54 +00:00
}
2018-10-15 12:02:32 +00:00
bool
2019-06-04 13:19:45 +00:00
RouterContact::Verify(llarp_time_t now, bool allowExpired) const
2018-10-15 12:02:32 +00:00
{
if (netID != NetID::DefaultValue())
2018-12-28 15:04:05 +00:00
{
2020-05-15 13:07:28 +00:00
llarp::LogError(
"netid mismatch: '", netID, "' (theirs) != '", NetID::DefaultValue(), "' (ours)");
return false;
2018-12-28 15:04:05 +00:00
}
if (IsExpired(now))
2018-12-28 15:04:05 +00:00
{
if (!allowExpired)
2019-06-04 13:19:45 +00:00
{
llarp::LogError("RC is expired");
return false;
}
llarp::LogWarn("RC is expired");
2018-12-28 15:04:05 +00:00
}
for (const auto& a : addrs)
2018-10-15 12:02:32 +00:00
{
if (IsBogon(a.ip) && BlockBogons)
2018-10-15 12:02:32 +00:00
{
llarp::LogError("invalid address info: ", a);
return false;
}
}
if (!VerifySignature())
2018-12-28 15:04:05 +00:00
{
2020-01-15 15:42:28 +00:00
llarp::LogError("invalid signature: ", *this);
2018-12-28 15:04:05 +00:00
return false;
}
return true;
2018-10-15 12:02:32 +00:00
}
2018-08-31 12:46:54 +00:00
bool
RouterContact::VerifySignature() const
2018-08-31 12:46:54 +00:00
{
if (version == 0)
2018-08-31 13:51:24 +00:00
{
RouterContact copy;
copy = *this;
copy.signature.Zero();
std::array<byte_t, MAX_RC_SIZE> tmp;
llarp_buffer_t buf(tmp);
if (!copy.BEncode(&buf))
{
llarp::LogError("bencode failed");
return false;
}
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
return CryptoManager::instance()->verify(pubkey, buf, signature);
2018-08-31 13:51:24 +00:00
}
/* else */
if (version == 1)
{
llarp_buffer_t buf(signed_bt_dict);
return CryptoManager::instance()->verify(pubkey, buf, signature);
}
return false;
2018-08-31 12:46:54 +00:00
}
bool
RouterContact::Write(const fs::path& fname) const
2018-08-31 12:46:54 +00:00
{
std::array<byte_t, MAX_RC_SIZE> tmp;
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
if (!BEncode(&buf))
2019-08-26 23:29:17 +00:00
{
2018-08-31 12:46:54 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
auto f = llarp::util::OpenFileStream<std::ofstream>(fname, std::ios::binary);
if (!f)
2019-08-26 23:29:17 +00:00
{
2019-06-24 16:39:03 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
if (!f->is_open())
2019-08-26 23:29:17 +00:00
{
2019-01-11 01:44:45 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
f->write((char*)buf.base, buf.sz);
2018-08-31 12:46:54 +00:00
return true;
}
bool
RouterContact::Read(const fs::path& fname)
2018-08-31 12:46:54 +00:00
{
std::array<byte_t, MAX_RC_SIZE> tmp;
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
2019-01-11 01:44:45 +00:00
std::ifstream f;
f.open(fname.string(), std::ios::binary);
if (!f.is_open())
2018-08-31 12:46:54 +00:00
{
2019-01-11 01:44:45 +00:00
llarp::LogError("Failed to open ", fname);
return false;
2018-08-31 12:46:54 +00:00
}
2019-01-11 01:44:45 +00:00
f.seekg(0, std::ios::end);
2019-01-26 11:12:48 +00:00
auto l = f.tellg();
if (l > static_cast<std::streamoff>(sizeof tmp))
2019-08-26 23:29:17 +00:00
{
2019-01-24 15:13:41 +00:00
return false;
2019-08-26 23:29:17 +00:00
}
2019-01-11 01:44:45 +00:00
f.seekg(0, std::ios::beg);
f.read((char*)tmp.data(), l);
2018-08-31 12:46:54 +00:00
return BDecode(&buf);
}
std::ostream&
RouterContact::print(std::ostream& stream, int level, int spaces) const
2019-02-24 23:46:37 +00:00
{
Printer printer(stream, level, spaces);
printer.printAttribute("k", pubkey);
2020-02-24 19:40:45 +00:00
printer.printAttribute("updated", last_updated.count());
2019-02-24 23:46:37 +00:00
printer.printAttribute("netid", netID);
printer.printAttribute("v", version);
printer.printAttribute("ai", addrs);
printer.printAttribute("e", enckey);
printer.printAttribute("z", signature);
return stream;
}
2018-08-30 18:48:43 +00:00
} // namespace llarp