You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lokinet/llarp/dns/server.cpp

300 lines
8.5 KiB
C++

#include <dns/server.hpp>
#include <dns/dns.hpp>
#include <crypto/crypto.hpp>
#include <util/thread/logic.hpp>
#include <array>
#include <utility>
6 years ago
namespace llarp
{
namespace dns
{
Proxy::Proxy(
llarp_ev_loop_ptr serverLoop,
Logic_ptr serverLogic,
llarp_ev_loop_ptr clientLoop,
Logic_ptr clientLogic,
IQueryHandler* h)
: m_ServerLoop(std::move(serverLoop))
, m_ClientLoop(std::move(clientLoop))
, m_ServerLogic(std::move(serverLogic))
, m_ClientLogic(std::move(clientLogic))
5 years ago
, m_QueryHandler(h)
6 years ago
{
m_Client.user = this;
m_Server.user = this;
m_Client.tick = nullptr;
m_Server.tick = nullptr;
m_Client.recvfrom = &HandleUDPRecv_client;
m_Server.recvfrom = &HandleUDPRecv_server;
6 years ago
}
void
Proxy::Stop()
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>
4 years ago
{}
6 years ago
bool
Proxy::Start(const IpAddress& addr, const std::vector<IpAddress>& resolvers)
6 years ago
{
if (resolvers.size())
{
if (not SetupUnboundResolver(resolvers))
{
return false;
}
}
const IpAddress any("0.0.0.0", 0);
auto self = shared_from_this();
LogicCall(m_ClientLogic, [=]() {
llarp_ev_add_udp(self->m_ClientLoop.get(), &self->m_Client, any.createSockAddr());
});
LogicCall(m_ServerLogic, [=]() {
llarp_ev_add_udp(self->m_ServerLoop.get(), &self->m_Server, addr.createSockAddr());
});
return true;
6 years ago
}
5 years ago
static Proxy::Buffer_t
CopyBuffer(const llarp_buffer_t& buf)
{
std::vector<byte_t> msgbuf(buf.sz);
5 years ago
std::copy_n(buf.base, buf.sz, msgbuf.data());
return msgbuf;
}
6 years ago
void
Proxy::HandleUDPRecv_server(llarp_udp_io* u, const SockAddr& from, ManagedBuffer buf)
6 years ago
{
5 years ago
Buffer_t msgbuf = CopyBuffer(buf.underlying);
auto self = static_cast<Proxy*>(u->user)->shared_from_this();
5 years ago
// yes we use the server loop here because if the server loop is not the
// client loop we'll crash again
LogicCall(
self->m_ServerLogic, [self, from, msgbuf]() { self->HandlePktServer(from, msgbuf); });
}
void
Proxy::HandleUDPRecv_client(llarp_udp_io* u, const SockAddr& from, ManagedBuffer buf)
{
5 years ago
Buffer_t msgbuf = CopyBuffer(buf.underlying);
auto self = static_cast<Proxy*>(u->user)->shared_from_this();
LogicCall(
self->m_ServerLogic, [self, from, msgbuf]() { self->HandlePktClient(from, msgbuf); });
6 years ago
}
IpAddress
6 years ago
Proxy::PickRandomResolver() const
{
const size_t sz = m_Resolvers.size();
if (sz <= 1)
6 years ago
return m_Resolvers[0];
auto itr = m_Resolvers.begin();
std::advance(itr, llarp::randint() % sz);
6 years ago
return *itr;
}
bool
Proxy::SetupUnboundResolver(const std::vector<IpAddress>& resolvers)
{
auto failFunc = [self = weak_from_this()](SockAddr to, Message msg) {
4 years ago
auto this_ptr = self.lock();
if (this_ptr)
{
this_ptr->SendServerMessageTo(to, std::move(msg));
4 years ago
}
};
auto replyFunc = [self = weak_from_this()](SockAddr to, std::vector<byte_t> buf) {
auto this_ptr = self.lock();
if (this_ptr)
{
this_ptr->HandleUpstreamResponse(to, std::move(buf));
}
};
m_UnboundResolver = std::make_shared<UnboundResolver>(
m_ServerLoop, std::move(replyFunc), std::move(failFunc));
if (not m_UnboundResolver->Init())
{
llarp::LogError("Failed to initialize upstream DNS resolver.");
m_UnboundResolver = nullptr;
return false;
}
for (const auto& resolver : resolvers)
{
if (not m_UnboundResolver->AddUpstreamResolver(resolver.toHost()))
{
llarp::LogError("Failed to add upstream DNS server: ", resolver.toHost());
m_UnboundResolver = nullptr;
return false;
}
}
return true;
}
6 years ago
void
Proxy::HandleTick(llarp_udp_io*)
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>
4 years ago
{}
6 years ago
void
Proxy::SendServerMessageBufferTo(const SockAddr& to, const llarp_buffer_t& buf)
{
llarp_ev_udp_sendto(&m_Server, to, buf);
}
6 years ago
void
Proxy::SendServerMessageTo(const SockAddr& to, Message msg)
6 years ago
{
auto self = shared_from_this();
LogicCall(m_ServerLogic, [to, msg = std::move(msg), self]() {
std::array<byte_t, 1500> tmp = {{0}};
llarp_buffer_t buf(tmp);
if (msg.Encode(&buf))
{
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
self->SendServerMessageBufferTo(to, buf);
}
else
llarp::LogWarn("failed to encode dns message when sending");
});
}
void
Proxy::HandleUpstreamResponse(SockAddr to, std::vector<byte_t> buf)
{
auto self = shared_from_this();
LogicCall(m_ServerLogic, [to, buffer = std::move(buf), self]() {
llarp_buffer_t buf(buffer);
self->SendServerMessageBufferTo(to, buf);
});
}
void
Proxy::SendClientMessageTo(const SockAddr& to, Message msg)
{
auto self = shared_from_this();
LogicCall(m_ClientLogic, [to, msg, self]() {
std::array<byte_t, 1500> tmp = {{0}};
llarp_buffer_t buf(tmp);
if (msg.Encode(&buf))
{
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
llarp_ev_udp_sendto(&self->m_Client, to, buf);
}
else
llarp::LogWarn("failed to encode dns message when sending");
});
6 years ago
}
void
Proxy::HandlePktClient(const SockAddr& from, Buffer_t buf)
6 years ago
{
llarp_buffer_t pkt(buf);
MessageHeader hdr;
if (!hdr.Decode(&pkt))
{
llarp::LogWarn("failed to parse dns header from ", from);
return;
}
TX tx = {hdr.id, from};
auto itr = m_Forwarded.find(tx);
if (itr == m_Forwarded.end())
return;
const auto& requester = itr->second;
auto self = shared_from_this();
Message msg(hdr);
if (msg.Decode(&pkt))
{
if (m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg))
{
msg.hdr_id = itr->first.txid;
if (!m_QueryHandler->HandleHookedDNSMessage(
std::move(msg),
std::bind(
&Proxy::SendServerMessageTo,
self,
requester.createSockAddr(),
std::placeholders::_1)))
{
llarp::LogWarn("failed to handle hooked dns");
}
return;
}
}
LogicCall(m_ServerLogic, [=]() {
// forward reply to requester via server
5 years ago
const llarp_buffer_t tmpbuf(buf);
llarp_ev_udp_sendto(&self->m_Server, requester.createSockAddr(), tmpbuf);
5 years ago
});
// remove pending
m_Forwarded.erase(itr);
}
void
Proxy::HandlePktServer(const SockAddr& from, Buffer_t buf)
{
MessageHeader hdr;
5 years ago
llarp_buffer_t pkt(buf);
if (!hdr.Decode(&pkt))
{
llarp::LogWarn("failed to parse dns header from ", from);
return;
}
5 years ago
TX tx = {hdr.id, from};
Message msg(hdr);
if (!msg.Decode(&pkt))
6 years ago
{
llarp::LogWarn("failed to parse dns message from ", from);
6 years ago
return;
}
// we don't provide a DoH resolver because it requires verified TLS
// TLS needs X509/ASN.1-DER and opting into the Root CA Cabal
// thankfully mozilla added a backdoor that allows ISPs to turn it off
// so we disable DoH for firefox using mozilla's ISP backdoor
// see: https://github.com/loki-project/loki-network/issues/832
for (const auto& q : msg.questions)
{
// is this firefox looking for their backdoor record?
if (q.IsName("use-application-dns.net"))
{
// yea it is, let's turn off DoH because god is dead.
msg.AddNXReply();
// press F to pay respects
SendServerMessageTo(from, std::move(msg));
return;
}
}
auto self = shared_from_this();
if (m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg))
6 years ago
{
if (!m_QueryHandler->HandleHookedDNSMessage(
std::move(msg),
std::bind(&Proxy::SendServerMessageTo, self, from, std::placeholders::_1)))
6 years ago
{
llarp::LogWarn("failed to handle hooked dns");
}
}
else if (not m_UnboundResolver)
{
// no upstream resolvers
// let's serv fail it
msg.AddServFail();
5 years ago
SendServerMessageTo(from, std::move(msg));
}
6 years ago
else
{
m_UnboundResolver->Lookup(from, std::move(msg));
6 years ago
}
}
} // namespace dns
} // namespace llarp