2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 Robby <robby@chatbelgie.be>
5 * Copyright (C) 2015, 2017-2021 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
429 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
431 DNS::Request* request = requests[i];
435 Query rr(request->question);
436 rr.error = ERROR_UNKNOWN;
437 request->OnError(&rr);
445 // Shutdown the socket if it exists.
448 SocketEngine::Shutdown(this, 2);
449 SocketEngine::Close(this);
452 // Remove all entries from the cache.
456 void Process(DNS::Request* req) CXX11_OVERRIDE
458 if ((unloading) || (req->creator->dying))
459 throw Exception("Module is being unloaded");
463 Query rr(req->question);
464 rr.error = ERROR_DISABLED;
469 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
472 unsigned int tries = 0;
476 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
478 if (++tries == DNS::MAX_REQUEST_ID*5)
480 // If we couldn't find an empty slot this many times, do a sequential scan as a last
481 // resort. If an empty slot is found that way, go on, otherwise throw an exception
483 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
485 if (!this->requests[i])
493 throw Exception("DNS: All ids are in use");
498 while (this->requests[id]);
501 this->requests[req->id] = req;
504 p.flags = QUERYFLAGS_RD;
506 p.question = req->question;
508 unsigned char buffer[524];
509 unsigned short len = p.Pack(buffer, sizeof(buffer));
511 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
512 * to contain the value that would be in the DNS cache, which is why this is here.
514 if (req->use_cache && this->CheckCache(req, p.question))
516 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
521 // Update name in the original request so question checking works for PTR queries
522 req->question.name = p.question.name;
524 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
525 throw Exception("DNS: Unable to send query");
527 // Add timer for timeout
528 ServerInstance->Timers.AddTimer(req);
531 void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
533 if (requests[req->id] == req)
534 requests[req->id] = NULL;
537 std::string GetErrorStr(Error e) CXX11_OVERRIDE
542 return "Module is unloading";
544 return "Request timed out";
545 case ERROR_NOT_AN_ANSWER:
546 case ERROR_NONSTANDARD_QUERY:
547 case ERROR_FORMAT_ERROR:
548 case ERROR_MALFORMED:
549 return "Malformed answer";
550 case ERROR_SERVER_FAILURE:
551 case ERROR_NOT_IMPLEMENTED:
553 case ERROR_INVALIDTYPE:
554 return "Nameserver failure";
555 case ERROR_DOMAIN_NOT_FOUND:
556 case ERROR_NO_RECORDS:
557 return "Domain not found";
559 return "DNS lookups are disabled";
563 return "Unknown error";
567 std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
586 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
588 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
591 void OnEventHandlerRead() CXX11_OVERRIDE
593 unsigned char buffer[524];
594 irc::sockets::sockaddrs from;
595 socklen_t x = sizeof(from);
597 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
599 if (length < Packet::HEADER_LENGTH)
602 if (myserver != from)
604 std::string server1 = from.str();
605 std::string server2 = myserver.str();
606 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
607 server1.c_str(), server2.c_str());
616 recv_packet.Fill(buffer, length);
619 catch (Exception& ex)
621 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
624 // recv_packet.id must be filled in here
625 DNS::Request* request = this->requests[recv_packet.id];
628 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
632 if (request->question != recv_packet.question)
634 // This can happen under high latency, drop it silently, do not fail the request
635 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
641 ServerInstance->stats.DnsBad++;
642 recv_packet.error = ERROR_MALFORMED;
643 request->OnError(&recv_packet);
645 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
647 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
648 ServerInstance->stats.DnsBad++;
649 recv_packet.error = ERROR_NONSTANDARD_QUERY;
650 request->OnError(&recv_packet);
652 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
654 Error error = ERROR_UNKNOWN;
656 switch (recv_packet.flags & QUERYFLAGS_RCODE)
659 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
660 error = ERROR_FORMAT_ERROR;
663 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
664 error = ERROR_SERVER_FAILURE;
667 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
668 error = ERROR_DOMAIN_NOT_FOUND;
671 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
672 error = ERROR_NOT_IMPLEMENTED;
675 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
676 error = ERROR_REFUSED;
682 ServerInstance->stats.DnsBad++;
683 recv_packet.error = error;
684 request->OnError(&recv_packet);
686 else if (recv_packet.answers.empty())
688 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
689 ServerInstance->stats.DnsBad++;
690 recv_packet.error = ERROR_NO_RECORDS;
691 request->OnError(&recv_packet);
695 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
696 ServerInstance->stats.DnsGood++;
697 request->OnLookupComplete(&recv_packet);
698 this->AddCache(recv_packet);
701 ServerInstance->stats.Dns++;
703 /* Request's destructor removes it from the request map */
707 bool Tick(time_t now) CXX11_OVERRIDE
709 unsigned long expired = 0;
710 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
712 const Query& query = it->second;
713 if (IsExpired(query, now))
716 this->cache.erase(it++);
723 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purged %lu expired DNS entries", expired);
728 void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
730 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
732 /* Initialize mastersocket */
734 int s = socket(myserver.family(), SOCK_DGRAM, 0);
737 /* Have we got a socket? */
740 SocketEngine::SetReuse(s);
741 SocketEngine::NonBlocking(s);
743 irc::sockets::sockaddrs bindto;
744 if (sourceaddr.empty())
746 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
747 if (myserver.family() == AF_INET)
748 sourceaddr = "0.0.0.0";
749 else if (myserver.family() == AF_INET6)
752 irc::sockets::aptosa(sourceaddr, sourceport, bindto);
754 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
757 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
758 SocketEngine::Close(this->GetFd());
761 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
763 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
764 SocketEngine::Close(this->GetFd());
768 if (bindto.family() != myserver.family())
769 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
773 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
778 class ModuleDNS : public Module
781 std::string DNSServer;
782 std::string SourceIP;
783 unsigned int SourcePort;
788 // attempt to look up their nameserver from the system
789 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
791 PFIXED_INFO pFixedInfo;
792 DWORD dwBufferSize = sizeof(FIXED_INFO);
793 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
797 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
799 HeapFree(GetProcessHeap(), 0, pFixedInfo);
800 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
805 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
806 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
808 HeapFree(GetProcessHeap(), 0, pFixedInfo);
811 if (!DNSServer.empty())
813 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
818 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
820 // attempt to look up their nameserver from /etc/resolv.conf
821 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
823 std::ifstream resolv("/etc/resolv.conf");
825 while (resolv >> DNSServer)
827 if (DNSServer == "nameserver")
830 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
832 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
838 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
840 DNSServer = "127.0.0.1";
844 ModuleDNS() : manager(this)
849 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
851 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
852 if (!tag->getBool("enabled", true))
854 // Clear these so they get reset if DNS is enabled again.
859 this->manager.Close();
863 const std::string oldserver = DNSServer;
864 DNSServer = tag->getString("server");
866 const std::string oldip = SourceIP;
867 SourceIP = tag->getString("sourceip");
869 const unsigned int oldport = SourcePort;
870 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
872 if (DNSServer.empty())
875 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
876 this->manager.Rehash(DNSServer, SourceIP, SourcePort);
879 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
881 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
883 DNS::Request* req = this->manager.requests[i];
887 if (req->creator == mod)
889 Query rr(req->question);
890 rr.error = ERROR_UNLOADED;
898 Version GetVersion() CXX11_OVERRIDE
900 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
904 MODULE_INIT(ModuleDNS)