2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 Robby <robby@chatbelgie.be>
5 * Copyright (C) 2015, 2017-2020 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2013, 2015-2016 Adam <Adam@anope.org>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "modules/dns.h"
29 #pragma comment(lib, "Iphlpapi.lib")
34 /** Maximum value of a dns request id, 16 bits wide, 0xFFFF.
36 const unsigned int MAX_REQUEST_ID = 0xFFFF;
41 /** A full packet sent or received to/from the nameserver
43 class Packet : public Query
45 void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
47 if (pos + name.length() + 2 > output_size)
48 throw Exception("Unable to pack name");
50 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
52 irc::sepstream sep(name, '.');
55 while (sep.GetToken(token))
57 output[pos++] = token.length();
58 memcpy(&output[pos], token.data(), token.length());
59 pos += token.length();
65 std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
68 unsigned short pos_ptr = pos, lowest_ptr = input_size;
69 bool compressed = false;
71 if (pos_ptr >= input_size)
72 throw Exception("Unable to unpack name - no input");
74 while (input[pos_ptr] > 0)
76 unsigned short offset = input[pos_ptr];
80 if ((offset & POINTER) != POINTER)
81 throw Exception("Unable to unpack name - bogus compression header");
82 if (pos_ptr + 1 >= input_size)
83 throw Exception("Unable to unpack name - bogus compression header");
85 /* Place pos at the second byte of the first (farthest) compression pointer */
86 if (compressed == false)
92 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
94 /* Pointers can only go back */
95 if (pos_ptr >= lowest_ptr)
96 throw Exception("Unable to unpack name - bogus compression pointer");
101 if (pos_ptr + offset + 1 >= input_size)
102 throw Exception("Unable to unpack name - offset too large");
105 for (unsigned i = 1; i <= offset; ++i)
106 name += input[pos_ptr + i];
108 pos_ptr += offset + 1;
109 if (compressed == false)
115 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
119 throw Exception("Unable to unpack name - no name");
121 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
126 Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
130 q.name = this->UnpackName(input, input_size, pos);
132 if (pos + 4 > input_size)
133 throw Exception("Unable to unpack question");
135 q.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
138 // Skip over query class code
144 ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
146 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
148 if (pos + 6 > input_size)
149 throw Exception("Unable to unpack resource record");
151 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
154 uint16_t rdlength = input[pos] << 8 | input[pos + 1];
161 if (pos + 4 > input_size)
162 throw Exception("Unable to unpack resource record");
164 irc::sockets::sockaddrs addrs;
165 memset(&addrs, 0, sizeof(addrs));
167 addrs.in4.sin_family = AF_INET;
168 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
171 record.rdata = addrs.addr();
176 if (pos + 16 > input_size)
177 throw Exception("Unable to unpack resource record");
179 irc::sockets::sockaddrs addrs;
180 memset(&addrs, 0, sizeof(addrs));
182 addrs.in6.sin6_family = AF_INET6;
183 for (int j = 0; j < 16; ++j)
184 addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
187 record.rdata = addrs.addr();
194 record.rdata = this->UnpackName(input, input_size, pos);
195 if (!InspIRCd::IsHost(record.rdata))
196 throw Exception("Invalid name"); // XXX: Causes the request to time out
202 if (pos + rdlength > input_size)
203 throw Exception("Unable to unpack txt resource record");
205 record.rdata = std::string(reinterpret_cast<const char *>(input + pos), rdlength);
208 if (record.rdata.find_first_of("\r\n\0", 0, 3) != std::string::npos)
209 throw Exception("Invalid character in txt record");
217 if (!record.name.empty() && !record.rdata.empty())
218 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
224 static const int POINTER = 0xC0;
225 static const int LABEL = 0x3F;
226 static const int HEADER_LENGTH = 12;
228 /* ID for this packet */
230 /* Flags on the packet */
231 unsigned short flags;
233 Packet() : id(0), flags(0)
237 void Fill(const unsigned char* input, const unsigned short len)
239 if (len < HEADER_LENGTH)
240 throw Exception("Unable to fill packet");
242 unsigned short packet_pos = 0;
244 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
247 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
250 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
253 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
256 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
259 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
262 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
265 throw Exception("Question count != 1 in incoming packet");
267 this->question = this->UnpackQuestion(input, len, packet_pos);
269 for (unsigned i = 0; i < ancount; ++i)
270 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
273 unsigned short Pack(unsigned char* output, unsigned short output_size)
275 if (output_size < HEADER_LENGTH)
276 throw Exception("Unable to pack packet");
278 unsigned short pos = 0;
280 output[pos++] = this->id >> 8;
281 output[pos++] = this->id & 0xFF;
282 output[pos++] = this->flags >> 8;
283 output[pos++] = this->flags & 0xFF;
284 output[pos++] = 0; // Question count, high byte
285 output[pos++] = 1; // Question count, low byte
286 output[pos++] = 0; // Answer count, high byte
287 output[pos++] = 0; // Answer count, low byte
294 Question& q = this->question;
296 if (q.type == QUERY_PTR)
298 irc::sockets::sockaddrs ip;
299 irc::sockets::aptosa(q.name, 0, ip);
301 if (q.name.find(':') != std::string::npos)
303 static const char* const hex = "0123456789abcdef";
304 char reverse_ip[128];
305 unsigned reverse_ip_count = 0;
306 for (int j = 15; j >= 0; --j)
308 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
309 reverse_ip[reverse_ip_count++] = '.';
310 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
311 reverse_ip[reverse_ip_count++] = '.';
313 reverse_ip[reverse_ip_count++] = 0;
316 q.name += "ip6.arpa";
320 unsigned long forward = ip.in4.sin_addr.s_addr;
321 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
323 q.name = ip.addr() + ".in-addr.arpa";
327 this->PackName(output, output_size, pos, q.name);
329 if (pos + 4 >= output_size)
330 throw Exception("Unable to pack packet");
332 short s = htons(q.type);
333 memcpy(&output[pos], &s, 2);
336 // Query class, always IN
345 class MyManager : public Manager, public Timer, public EventHandler
347 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
350 irc::sockets::sockaddrs myserver;
353 /** Maximum number of entries in cache
355 static const unsigned int MAX_CACHE_SIZE = 1000;
357 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
359 const ResourceRecord& req = record.answers[0];
360 return (req.created + static_cast<time_t>(req.ttl) < now);
363 /** Check the DNS cache to see if request can be handled by a cached result
364 * @return true if a cached result was found.
366 bool CheckCache(DNS::Request* req, const DNS::Question& question)
368 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
370 cache_map::iterator it = this->cache.find(question);
371 if (it == this->cache.end())
374 Query& record = it->second;
375 if (IsExpired(record))
377 this->cache.erase(it);
381 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
382 record.cached = true;
383 req->OnLookupComplete(&record);
387 /** Add a record to the dns cache
388 * @param r The record
390 void AddCache(Query& r)
392 if (cache.size() >= MAX_CACHE_SIZE)
395 // Determine the lowest TTL value and use that as the TTL of the cache entry
396 unsigned int cachettl = UINT_MAX;
397 for (std::vector<ResourceRecord>::const_iterator i = r.answers.begin(); i != r.answers.end(); ++i)
399 const ResourceRecord& rr = *i;
400 if (rr.ttl < cachettl)
404 cachettl = std::min(cachettl, (unsigned int)5*60);
405 ResourceRecord& rr = r.answers.front();
406 // Set TTL to what we've determined to be the lowest
408 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
409 this->cache[r.question] = r;
413 DNS::Request* requests[MAX_REQUEST_ID+1];
415 MyManager(Module* c) : Manager(c), Timer(5*60, true)
418 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
420 ServerInstance->Timers.AddTimer(this);
425 // Ensure Process() will fail for new requests
428 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
430 DNS::Request* request = requests[i];
434 Query rr(request->question);
435 rr.error = ERROR_UNKNOWN;
436 request->OnError(&rr);
442 void Process(DNS::Request* req) CXX11_OVERRIDE
444 if ((unloading) || (req->creator->dying))
445 throw Exception("Module is being unloaded");
447 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
450 unsigned int tries = 0;
454 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
456 if (++tries == DNS::MAX_REQUEST_ID*5)
458 // If we couldn't find an empty slot this many times, do a sequential scan as a last
459 // resort. If an empty slot is found that way, go on, otherwise throw an exception
461 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
463 if (!this->requests[i])
471 throw Exception("DNS: All ids are in use");
476 while (this->requests[id]);
479 this->requests[req->id] = req;
482 p.flags = QUERYFLAGS_RD;
484 p.question = req->question;
486 unsigned char buffer[524];
487 unsigned short len = p.Pack(buffer, sizeof(buffer));
489 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
490 * to contain the value that would be in the DNS cache, which is why this is here.
492 if (req->use_cache && this->CheckCache(req, p.question))
494 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
499 // Update name in the original request so question checking works for PTR queries
500 req->question.name = p.question.name;
502 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
503 throw Exception("DNS: Unable to send query");
505 // Add timer for timeout
506 ServerInstance->Timers.AddTimer(req);
509 void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
511 if (requests[req->id] == req)
512 requests[req->id] = NULL;
515 std::string GetErrorStr(Error e) CXX11_OVERRIDE
520 return "Module is unloading";
522 return "Request timed out";
523 case ERROR_NOT_AN_ANSWER:
524 case ERROR_NONSTANDARD_QUERY:
525 case ERROR_FORMAT_ERROR:
526 case ERROR_MALFORMED:
527 return "Malformed answer";
528 case ERROR_SERVER_FAILURE:
529 case ERROR_NOT_IMPLEMENTED:
531 case ERROR_INVALIDTYPE:
532 return "Nameserver failure";
533 case ERROR_DOMAIN_NOT_FOUND:
534 case ERROR_NO_RECORDS:
535 return "Domain not found";
539 return "Unknown error";
543 std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
562 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
564 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
567 void OnEventHandlerRead() CXX11_OVERRIDE
569 unsigned char buffer[524];
570 irc::sockets::sockaddrs from;
571 socklen_t x = sizeof(from);
573 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
575 if (length < Packet::HEADER_LENGTH)
578 if (myserver != from)
580 std::string server1 = from.str();
581 std::string server2 = myserver.str();
582 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
583 server1.c_str(), server2.c_str());
592 recv_packet.Fill(buffer, length);
595 catch (Exception& ex)
597 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
600 // recv_packet.id must be filled in here
601 DNS::Request* request = this->requests[recv_packet.id];
604 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
608 if (request->question != recv_packet.question)
610 // This can happen under high latency, drop it silently, do not fail the request
611 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
617 ServerInstance->stats.DnsBad++;
618 recv_packet.error = ERROR_MALFORMED;
619 request->OnError(&recv_packet);
621 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
623 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
624 ServerInstance->stats.DnsBad++;
625 recv_packet.error = ERROR_NONSTANDARD_QUERY;
626 request->OnError(&recv_packet);
628 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
630 Error error = ERROR_UNKNOWN;
632 switch (recv_packet.flags & QUERYFLAGS_RCODE)
635 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
636 error = ERROR_FORMAT_ERROR;
639 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
640 error = ERROR_SERVER_FAILURE;
643 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
644 error = ERROR_DOMAIN_NOT_FOUND;
647 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
648 error = ERROR_NOT_IMPLEMENTED;
651 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
652 error = ERROR_REFUSED;
658 ServerInstance->stats.DnsBad++;
659 recv_packet.error = error;
660 request->OnError(&recv_packet);
662 else if (recv_packet.answers.empty())
664 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
665 ServerInstance->stats.DnsBad++;
666 recv_packet.error = ERROR_NO_RECORDS;
667 request->OnError(&recv_packet);
671 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
672 ServerInstance->stats.DnsGood++;
673 request->OnLookupComplete(&recv_packet);
674 this->AddCache(recv_packet);
677 ServerInstance->stats.Dns++;
679 /* Request's destructor removes it from the request map */
683 bool Tick(time_t now) CXX11_OVERRIDE
685 unsigned long expired = 0;
686 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
688 const Query& query = it->second;
689 if (IsExpired(query, now))
692 this->cache.erase(it++);
699 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purged %lu expired DNS entries", expired);
704 void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
708 SocketEngine::Shutdown(this, 2);
709 SocketEngine::Close(this);
711 // Remove all entries from the cache.
715 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
717 /* Initialize mastersocket */
718 int s = socket(myserver.family(), SOCK_DGRAM, 0);
721 /* Have we got a socket? */
722 if (this->GetFd() != -1)
724 SocketEngine::SetReuse(s);
725 SocketEngine::NonBlocking(s);
727 irc::sockets::sockaddrs bindto;
728 if (sourceaddr.empty())
730 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
731 if (myserver.family() == AF_INET)
732 sourceaddr = "0.0.0.0";
733 else if (myserver.family() == AF_INET6)
736 irc::sockets::aptosa(sourceaddr, sourceport, bindto);
738 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
741 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
742 SocketEngine::Close(this->GetFd());
745 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
747 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
748 SocketEngine::Close(this->GetFd());
752 if (bindto.family() != myserver.family())
753 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
757 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
762 class ModuleDNS : public Module
765 std::string DNSServer;
766 std::string SourceIP;
767 unsigned int SourcePort;
772 // attempt to look up their nameserver from the system
773 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
775 PFIXED_INFO pFixedInfo;
776 DWORD dwBufferSize = sizeof(FIXED_INFO);
777 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
781 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
783 HeapFree(GetProcessHeap(), 0, pFixedInfo);
784 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
789 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
790 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
792 HeapFree(GetProcessHeap(), 0, pFixedInfo);
795 if (!DNSServer.empty())
797 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
802 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
804 // attempt to look up their nameserver from /etc/resolv.conf
805 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
807 std::ifstream resolv("/etc/resolv.conf");
809 while (resolv >> DNSServer)
811 if (DNSServer == "nameserver")
814 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
816 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
822 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
824 DNSServer = "127.0.0.1";
828 ModuleDNS() : manager(this)
833 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
835 std::string oldserver = DNSServer;
836 const std::string oldip = SourceIP;
837 const unsigned int oldport = SourcePort;
839 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
840 DNSServer = tag->getString("server");
841 SourceIP = tag->getString("sourceip");
842 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
844 if (DNSServer.empty())
847 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
848 this->manager.Rehash(DNSServer, SourceIP, SourcePort);
851 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
853 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
855 DNS::Request* req = this->manager.requests[i];
859 if (req->creator == mod)
861 Query rr(req->question);
862 rr.error = ERROR_UNLOADED;
870 Version GetVersion() CXX11_OVERRIDE
872 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
876 MODULE_INIT(ModuleDNS)