2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2013 Adam <Adam@anope.org>
5 * Copyright (C) 2003-2013 Anope Team <team@anope.org>
7 * This file is part of InspIRCd. InspIRCd is free software: you can
8 * redistribute it and/or modify it under the terms of the GNU General Public
9 * License as published by the Free Software Foundation, version 2.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include "modules/dns.h"
27 #pragma comment(lib, "Iphlpapi.lib")
32 /** Maximum value of a dns request id, 16 bits wide, 0xFFFF.
34 const unsigned int MAX_REQUEST_ID = 0xFFFF;
39 /** A full packet sent or received to/from the nameserver
41 class Packet : public Query
43 void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
45 if (pos + name.length() + 2 > output_size)
46 throw Exception("Unable to pack name");
48 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
50 irc::sepstream sep(name, '.');
53 while (sep.GetToken(token))
55 output[pos++] = token.length();
56 memcpy(&output[pos], token.data(), token.length());
57 pos += token.length();
63 std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
66 unsigned short pos_ptr = pos, lowest_ptr = input_size;
67 bool compressed = false;
69 if (pos_ptr >= input_size)
70 throw Exception("Unable to unpack name - no input");
72 while (input[pos_ptr] > 0)
74 unsigned short offset = input[pos_ptr];
78 if ((offset & POINTER) != POINTER)
79 throw Exception("Unable to unpack name - bogus compression header");
80 if (pos_ptr + 1 >= input_size)
81 throw Exception("Unable to unpack name - bogus compression header");
83 /* Place pos at the second byte of the first (farthest) compression pointer */
84 if (compressed == false)
90 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
92 /* Pointers can only go back */
93 if (pos_ptr >= lowest_ptr)
94 throw Exception("Unable to unpack name - bogus compression pointer");
99 if (pos_ptr + offset + 1 >= input_size)
100 throw Exception("Unable to unpack name - offset too large");
103 for (unsigned i = 1; i <= offset; ++i)
104 name += input[pos_ptr + i];
106 pos_ptr += offset + 1;
107 if (compressed == false)
113 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
117 throw Exception("Unable to unpack name - no name");
119 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
124 Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
128 q.name = this->UnpackName(input, input_size, pos);
130 if (pos + 4 > input_size)
131 throw Exception("Unable to unpack question");
133 q.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
136 // Skip over query class code
142 ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
144 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
146 if (pos + 6 > input_size)
147 throw Exception("Unable to unpack resource record");
149 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
152 uint16_t rdlength = input[pos] << 8 | input[pos + 1];
159 if (pos + 4 > input_size)
160 throw Exception("Unable to unpack resource record");
162 irc::sockets::sockaddrs addrs;
163 memset(&addrs, 0, sizeof(addrs));
165 addrs.in4.sin_family = AF_INET;
166 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
169 record.rdata = addrs.addr();
174 if (pos + 16 > input_size)
175 throw Exception("Unable to unpack resource record");
177 irc::sockets::sockaddrs addrs;
178 memset(&addrs, 0, sizeof(addrs));
180 addrs.in6.sin6_family = AF_INET6;
181 for (int j = 0; j < 16; ++j)
182 addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
185 record.rdata = addrs.addr();
192 record.rdata = this->UnpackName(input, input_size, pos);
193 if (!InspIRCd::IsHost(record.rdata))
194 throw Exception("Invalid name"); // XXX: Causes the request to time out
200 if (pos + rdlength > input_size)
201 throw Exception("Unable to unpack txt resource record");
203 record.rdata = std::string(reinterpret_cast<const char *>(input + pos), rdlength);
206 if (record.rdata.find_first_of("\r\n\0", 0, 3) != std::string::npos)
207 throw Exception("Invalid character in txt record");
215 if (!record.name.empty() && !record.rdata.empty())
216 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
222 static const int POINTER = 0xC0;
223 static const int LABEL = 0x3F;
224 static const int HEADER_LENGTH = 12;
226 /* ID for this packet */
228 /* Flags on the packet */
229 unsigned short flags;
231 Packet() : id(0), flags(0)
235 void Fill(const unsigned char* input, const unsigned short len)
237 if (len < HEADER_LENGTH)
238 throw Exception("Unable to fill packet");
240 unsigned short packet_pos = 0;
242 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
245 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
248 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
251 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
254 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
257 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
260 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
263 throw Exception("Question count != 1 in incoming packet");
265 this->question = this->UnpackQuestion(input, len, packet_pos);
267 for (unsigned i = 0; i < ancount; ++i)
268 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
271 unsigned short Pack(unsigned char* output, unsigned short output_size)
273 if (output_size < HEADER_LENGTH)
274 throw Exception("Unable to pack packet");
276 unsigned short pos = 0;
278 output[pos++] = this->id >> 8;
279 output[pos++] = this->id & 0xFF;
280 output[pos++] = this->flags >> 8;
281 output[pos++] = this->flags & 0xFF;
282 output[pos++] = 0; // Question count, high byte
283 output[pos++] = 1; // Question count, low byte
284 output[pos++] = 0; // Answer count, high byte
285 output[pos++] = 0; // Answer count, low byte
292 Question& q = this->question;
294 if (q.type == QUERY_PTR)
296 irc::sockets::sockaddrs ip;
297 irc::sockets::aptosa(q.name, 0, ip);
299 if (q.name.find(':') != std::string::npos)
301 static const char* const hex = "0123456789abcdef";
302 char reverse_ip[128];
303 unsigned reverse_ip_count = 0;
304 for (int j = 15; j >= 0; --j)
306 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
307 reverse_ip[reverse_ip_count++] = '.';
308 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
309 reverse_ip[reverse_ip_count++] = '.';
311 reverse_ip[reverse_ip_count++] = 0;
314 q.name += "ip6.arpa";
318 unsigned long forward = ip.in4.sin_addr.s_addr;
319 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
321 q.name = ip.addr() + ".in-addr.arpa";
325 this->PackName(output, output_size, pos, q.name);
327 if (pos + 4 >= output_size)
328 throw Exception("Unable to pack packet");
330 short s = htons(q.type);
331 memcpy(&output[pos], &s, 2);
334 // Query class, always IN
343 class MyManager : public Manager, public Timer, public EventHandler
345 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
348 irc::sockets::sockaddrs myserver;
351 /** Maximum number of entries in cache
353 static const unsigned int MAX_CACHE_SIZE = 1000;
355 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
357 const ResourceRecord& req = record.answers[0];
358 return (req.created + static_cast<time_t>(req.ttl) < now);
361 /** Check the DNS cache to see if request can be handled by a cached result
362 * @return true if a cached result was found.
364 bool CheckCache(DNS::Request* req, const DNS::Question& question)
366 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
368 cache_map::iterator it = this->cache.find(question);
369 if (it == this->cache.end())
372 Query& record = it->second;
373 if (IsExpired(record))
375 this->cache.erase(it);
379 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
380 record.cached = true;
381 req->OnLookupComplete(&record);
385 /** Add a record to the dns cache
386 * @param r The record
388 void AddCache(Query& r)
390 if (cache.size() >= MAX_CACHE_SIZE)
393 // Determine the lowest TTL value and use that as the TTL of the cache entry
394 unsigned int cachettl = UINT_MAX;
395 for (std::vector<ResourceRecord>::const_iterator i = r.answers.begin(); i != r.answers.end(); ++i)
397 const ResourceRecord& rr = *i;
398 if (rr.ttl < cachettl)
402 cachettl = std::min(cachettl, (unsigned int)5*60);
403 ResourceRecord& rr = r.answers.front();
404 // Set TTL to what we've determined to be the lowest
406 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
407 this->cache[r.question] = r;
411 DNS::Request* requests[MAX_REQUEST_ID+1];
413 MyManager(Module* c) : Manager(c), Timer(5*60, true)
416 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
418 ServerInstance->Timers.AddTimer(this);
423 // Ensure Process() will fail for new requests
426 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
428 DNS::Request* request = requests[i];
432 Query rr(request->question);
433 rr.error = ERROR_UNKNOWN;
434 request->OnError(&rr);
440 void Process(DNS::Request* req) CXX11_OVERRIDE
442 if ((unloading) || (req->creator->dying))
443 throw Exception("Module is being unloaded");
445 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
448 unsigned int tries = 0;
452 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
454 if (++tries == DNS::MAX_REQUEST_ID*5)
456 // If we couldn't find an empty slot this many times, do a sequential scan as a last
457 // resort. If an empty slot is found that way, go on, otherwise throw an exception
459 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
461 if (!this->requests[i])
469 throw Exception("DNS: All ids are in use");
474 while (this->requests[id]);
477 this->requests[req->id] = req;
480 p.flags = QUERYFLAGS_RD;
482 p.question = req->question;
484 unsigned char buffer[524];
485 unsigned short len = p.Pack(buffer, sizeof(buffer));
487 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
488 * to contain the value that would be in the DNS cache, which is why this is here.
490 if (req->use_cache && this->CheckCache(req, p.question))
492 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
497 // Update name in the original request so question checking works for PTR queries
498 req->question.name = p.question.name;
500 if (SocketEngine::SendTo(this, buffer, len, 0, this->myserver) != len)
501 throw Exception("DNS: Unable to send query");
503 // Add timer for timeout
504 ServerInstance->Timers.AddTimer(req);
507 void RemoveRequest(DNS::Request* req) CXX11_OVERRIDE
509 if (requests[req->id] == req)
510 requests[req->id] = NULL;
513 std::string GetErrorStr(Error e) CXX11_OVERRIDE
518 return "Module is unloading";
520 return "Request timed out";
521 case ERROR_NOT_AN_ANSWER:
522 case ERROR_NONSTANDARD_QUERY:
523 case ERROR_FORMAT_ERROR:
524 case ERROR_MALFORMED:
525 return "Malformed answer";
526 case ERROR_SERVER_FAILURE:
527 case ERROR_NOT_IMPLEMENTED:
529 case ERROR_INVALIDTYPE:
530 return "Nameserver failure";
531 case ERROR_DOMAIN_NOT_FOUND:
532 case ERROR_NO_RECORDS:
533 return "Domain not found";
537 return "Unknown error";
541 std::string GetTypeStr(QueryType qt) CXX11_OVERRIDE
560 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
562 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
565 void OnEventHandlerRead() CXX11_OVERRIDE
567 unsigned char buffer[524];
568 irc::sockets::sockaddrs from;
569 socklen_t x = sizeof(from);
571 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
573 if (length < Packet::HEADER_LENGTH)
576 if (myserver != from)
578 std::string server1 = from.str();
579 std::string server2 = myserver.str();
580 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
581 server1.c_str(), server2.c_str());
590 recv_packet.Fill(buffer, length);
593 catch (Exception& ex)
595 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
598 // recv_packet.id must be filled in here
599 DNS::Request* request = this->requests[recv_packet.id];
602 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
606 if (request->question != recv_packet.question)
608 // This can happen under high latency, drop it silently, do not fail the request
609 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
615 ServerInstance->stats.DnsBad++;
616 recv_packet.error = ERROR_MALFORMED;
617 request->OnError(&recv_packet);
619 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
621 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
622 ServerInstance->stats.DnsBad++;
623 recv_packet.error = ERROR_NONSTANDARD_QUERY;
624 request->OnError(&recv_packet);
626 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
628 Error error = ERROR_UNKNOWN;
630 switch (recv_packet.flags & QUERYFLAGS_RCODE)
633 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
634 error = ERROR_FORMAT_ERROR;
637 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
638 error = ERROR_SERVER_FAILURE;
641 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
642 error = ERROR_DOMAIN_NOT_FOUND;
645 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
646 error = ERROR_NOT_IMPLEMENTED;
649 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
650 error = ERROR_REFUSED;
656 ServerInstance->stats.DnsBad++;
657 recv_packet.error = error;
658 request->OnError(&recv_packet);
660 else if (recv_packet.answers.empty())
662 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
663 ServerInstance->stats.DnsBad++;
664 recv_packet.error = ERROR_NO_RECORDS;
665 request->OnError(&recv_packet);
669 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
670 ServerInstance->stats.DnsGood++;
671 request->OnLookupComplete(&recv_packet);
672 this->AddCache(recv_packet);
675 ServerInstance->stats.Dns++;
677 /* Request's destructor removes it from the request map */
681 bool Tick(time_t now) CXX11_OVERRIDE
683 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
685 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
687 const Query& query = it->second;
688 if (IsExpired(query, now))
689 this->cache.erase(it++);
696 void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
698 if (this->GetFd() > -1)
700 SocketEngine::Shutdown(this, 2);
701 SocketEngine::Close(this);
703 /* Remove expired entries from the cache */
704 this->Tick(ServerInstance->Time());
707 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
709 /* Initialize mastersocket */
710 int s = socket(myserver.family(), SOCK_DGRAM, 0);
713 /* Have we got a socket? */
714 if (this->GetFd() != -1)
716 SocketEngine::SetReuse(s);
717 SocketEngine::NonBlocking(s);
719 irc::sockets::sockaddrs bindto;
720 if (sourceaddr.empty())
722 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
723 if (myserver.family() == AF_INET)
724 sourceaddr = "0.0.0.0";
725 else if (myserver.family() == AF_INET6)
728 irc::sockets::aptosa(sourceaddr, sourceport, bindto);
730 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
733 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
734 SocketEngine::Close(this->GetFd());
737 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
739 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
740 SocketEngine::Close(this->GetFd());
744 if (bindto.family() != myserver.family())
745 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
749 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
754 class ModuleDNS : public Module
757 std::string DNSServer;
758 std::string SourceIP;
759 unsigned int SourcePort;
764 // attempt to look up their nameserver from the system
765 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
767 PFIXED_INFO pFixedInfo;
768 DWORD dwBufferSize = sizeof(FIXED_INFO);
769 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
773 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
775 HeapFree(GetProcessHeap(), 0, pFixedInfo);
776 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
781 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
782 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
784 HeapFree(GetProcessHeap(), 0, pFixedInfo);
787 if (!DNSServer.empty())
789 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
794 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
796 // attempt to look up their nameserver from /etc/resolv.conf
797 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
799 std::ifstream resolv("/etc/resolv.conf");
801 while (resolv >> DNSServer)
803 if (DNSServer == "nameserver")
806 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
808 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
814 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
816 DNSServer = "127.0.0.1";
820 ModuleDNS() : manager(this)
825 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
827 std::string oldserver = DNSServer;
828 const std::string oldip = SourceIP;
829 const unsigned int oldport = SourcePort;
831 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
832 DNSServer = tag->getString("server");
833 SourceIP = tag->getString("sourceip");
834 SourcePort = tag->getUInt("sourceport", 0, 0, UINT16_MAX);
836 if (DNSServer.empty())
839 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
840 this->manager.Rehash(DNSServer, SourceIP, SourcePort);
843 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
845 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
847 DNS::Request* req = this->manager.requests[i];
851 if (req->creator == mod)
853 Query rr(req->question);
854 rr.error = ERROR_UNLOADED;
862 Version GetVersion() CXX11_OVERRIDE
864 return Version("Provides support for DNS lookups", VF_CORE|VF_VENDOR);
868 MODULE_INIT(ModuleDNS)