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 recieved to/from the nameserver
41 class Packet : public Query
43 static bool IsValidName(const std::string& name)
45 return (name.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-") == std::string::npos);
48 void PackName(unsigned char* output, unsigned short output_size, unsigned short& pos, const std::string& name)
50 if (pos + name.length() + 2 > output_size)
51 throw Exception("Unable to pack name");
53 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Packing name " + name);
55 irc::sepstream sep(name, '.');
58 while (sep.GetToken(token))
60 output[pos++] = token.length();
61 memcpy(&output[pos], token.data(), token.length());
62 pos += token.length();
68 std::string UnpackName(const unsigned char* input, unsigned short input_size, unsigned short& pos)
71 unsigned short pos_ptr = pos, lowest_ptr = input_size;
72 bool compressed = false;
74 if (pos_ptr >= input_size)
75 throw Exception("Unable to unpack name - no input");
77 while (input[pos_ptr] > 0)
79 unsigned short offset = input[pos_ptr];
83 if ((offset & POINTER) != POINTER)
84 throw Exception("Unable to unpack name - bogus compression header");
85 if (pos_ptr + 1 >= input_size)
86 throw Exception("Unable to unpack name - bogus compression header");
88 /* Place pos at the second byte of the first (farthest) compression pointer */
89 if (compressed == false)
95 pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1];
97 /* Pointers can only go back */
98 if (pos_ptr >= lowest_ptr)
99 throw Exception("Unable to unpack name - bogus compression pointer");
100 lowest_ptr = pos_ptr;
104 if (pos_ptr + offset + 1 >= input_size)
105 throw Exception("Unable to unpack name - offset too large");
108 for (unsigned i = 1; i <= offset; ++i)
109 name += input[pos_ptr + i];
111 pos_ptr += offset + 1;
112 if (compressed == false)
118 /* +1 pos either to one byte after the compression pointer or one byte after the ending \0 */
122 throw Exception("Unable to unpack name - no name");
124 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unpack name " + name);
129 Question UnpackQuestion(const unsigned char* input, unsigned short input_size, unsigned short& pos)
133 q.name = this->UnpackName(input, input_size, pos);
135 if (pos + 4 > input_size)
136 throw Exception("Unable to unpack question");
138 q.type = static_cast<QueryType>(input[pos] << 8 | input[pos + 1]);
141 // Skip over query class code
147 ResourceRecord UnpackResourceRecord(const unsigned char* input, unsigned short input_size, unsigned short& pos)
149 ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos));
151 if (pos + 6 > input_size)
152 throw Exception("Unable to unpack resource record");
154 record.ttl = (input[pos] << 24) | (input[pos + 1] << 16) | (input[pos + 2] << 8) | input[pos + 3];
157 //record.rdlength = input[pos] << 8 | input[pos + 1];
164 if (pos + 4 > input_size)
165 throw Exception("Unable to unpack resource record");
167 irc::sockets::sockaddrs addrs;
168 memset(&addrs, 0, sizeof(addrs));
170 addrs.in4.sin_family = AF_INET;
171 addrs.in4.sin_addr.s_addr = input[pos] | (input[pos + 1] << 8) | (input[pos + 2] << 16) | (input[pos + 3] << 24);
174 record.rdata = addrs.addr();
179 if (pos + 16 > input_size)
180 throw Exception("Unable to unpack resource record");
182 irc::sockets::sockaddrs addrs;
183 memset(&addrs, 0, sizeof(addrs));
185 addrs.in6.sin6_family = AF_INET6;
186 for (int j = 0; j < 16; ++j)
187 addrs.in6.sin6_addr.s6_addr[j] = input[pos + j];
190 record.rdata = addrs.addr();
197 record.rdata = this->UnpackName(input, input_size, pos);
198 if (!IsValidName(record.rdata))
199 throw Exception("Invalid name"); // XXX: Causes the request to time out
207 if (!record.name.empty() && !record.rdata.empty())
208 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, record.name + " -> " + record.rdata);
214 static const int POINTER = 0xC0;
215 static const int LABEL = 0x3F;
216 static const int HEADER_LENGTH = 12;
218 /* ID for this packet */
220 /* Flags on the packet */
221 unsigned short flags;
223 Packet() : id(0), flags(0)
227 void Fill(const unsigned char* input, const unsigned short len)
229 if (len < HEADER_LENGTH)
230 throw Exception("Unable to fill packet");
232 unsigned short packet_pos = 0;
234 this->id = (input[packet_pos] << 8) | input[packet_pos + 1];
237 this->flags = (input[packet_pos] << 8) | input[packet_pos + 1];
240 unsigned short qdcount = (input[packet_pos] << 8) | input[packet_pos + 1];
243 unsigned short ancount = (input[packet_pos] << 8) | input[packet_pos + 1];
246 unsigned short nscount = (input[packet_pos] << 8) | input[packet_pos + 1];
249 unsigned short arcount = (input[packet_pos] << 8) | input[packet_pos + 1];
252 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "qdcount: " + ConvToStr(qdcount) + " ancount: " + ConvToStr(ancount) + " nscount: " + ConvToStr(nscount) + " arcount: " + ConvToStr(arcount));
255 throw Exception("Question count != 1 in incoming packet");
257 this->question = this->UnpackQuestion(input, len, packet_pos);
259 for (unsigned i = 0; i < ancount; ++i)
260 this->answers.push_back(this->UnpackResourceRecord(input, len, packet_pos));
263 unsigned short Pack(unsigned char* output, unsigned short output_size)
265 if (output_size < HEADER_LENGTH)
266 throw Exception("Unable to pack packet");
268 unsigned short pos = 0;
270 output[pos++] = this->id >> 8;
271 output[pos++] = this->id & 0xFF;
272 output[pos++] = this->flags >> 8;
273 output[pos++] = this->flags & 0xFF;
274 output[pos++] = 0; // Question count, high byte
275 output[pos++] = 1; // Question count, low byte
276 output[pos++] = 0; // Answer count, high byte
277 output[pos++] = 0; // Answer count, low byte
284 Question& q = this->question;
286 if (q.type == QUERY_PTR)
288 irc::sockets::sockaddrs ip;
289 irc::sockets::aptosa(q.name, 0, ip);
291 if (q.name.find(':') != std::string::npos)
293 static const char* const hex = "0123456789abcdef";
294 char reverse_ip[128];
295 unsigned reverse_ip_count = 0;
296 for (int j = 15; j >= 0; --j)
298 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] & 0xF];
299 reverse_ip[reverse_ip_count++] = '.';
300 reverse_ip[reverse_ip_count++] = hex[ip.in6.sin6_addr.s6_addr[j] >> 4];
301 reverse_ip[reverse_ip_count++] = '.';
303 reverse_ip[reverse_ip_count++] = 0;
306 q.name += "ip6.arpa";
310 unsigned long forward = ip.in4.sin_addr.s_addr;
311 ip.in4.sin_addr.s_addr = forward << 24 | (forward & 0xFF00) << 8 | (forward & 0xFF0000) >> 8 | forward >> 24;
313 q.name = ip.addr() + ".in-addr.arpa";
317 this->PackName(output, output_size, pos, q.name);
319 if (pos + 4 >= output_size)
320 throw Exception("Unable to pack packet");
322 short s = htons(q.type);
323 memcpy(&output[pos], &s, 2);
326 // Query class, always IN
335 class MyManager : public Manager, public Timer, public EventHandler
337 typedef TR1NS::unordered_map<Question, Query, Question::hash> cache_map;
340 irc::sockets::sockaddrs myserver;
343 /** Maximum number of entries in cache
345 static const unsigned int MAX_CACHE_SIZE = 1000;
347 static bool IsExpired(const Query& record, time_t now = ServerInstance->Time())
349 const ResourceRecord& req = record.answers[0];
350 return (req.created + static_cast<time_t>(req.ttl) < now);
353 /** Check the DNS cache to see if request can be handled by a cached result
354 * @return true if a cached result was found.
356 bool CheckCache(DNS::Request* req, const DNS::Question& question)
358 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "cache: Checking cache for " + question.name);
360 cache_map::iterator it = this->cache.find(question);
361 if (it == this->cache.end())
364 Query& record = it->second;
365 if (IsExpired(record))
367 this->cache.erase(it);
371 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: Using cached result for " + question.name);
372 record.cached = true;
373 req->OnLookupComplete(&record);
377 /** Add a record to the dns cache
378 * @param r The record
380 void AddCache(Query& r)
382 if (cache.size() >= MAX_CACHE_SIZE)
385 // Determine the lowest TTL value and use that as the TTL of the cache entry
386 unsigned int cachettl = UINT_MAX;
387 for (std::vector<ResourceRecord>::const_iterator i = r.answers.begin(); i != r.answers.end(); ++i)
389 const ResourceRecord& rr = *i;
390 if (rr.ttl < cachettl)
394 cachettl = std::min(cachettl, (unsigned int)5*60);
395 ResourceRecord& rr = r.answers.front();
396 // Set TTL to what we've determined to be the lowest
398 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: added cache for " + rr.name + " -> " + rr.rdata + " ttl: " + ConvToStr(rr.ttl));
399 this->cache[r.question] = r;
403 DNS::Request* requests[MAX_REQUEST_ID+1];
405 MyManager(Module* c) : Manager(c), Timer(5*60, true)
408 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
410 ServerInstance->Timers.AddTimer(this);
415 // Ensure Process() will fail for new requests
418 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
420 DNS::Request* request = requests[i];
424 Query rr(request->question);
425 rr.error = ERROR_UNKNOWN;
426 request->OnError(&rr);
432 void Process(DNS::Request* req)
434 if ((unloading) || (req->creator->dying))
435 throw Exception("Module is being unloaded");
437 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Processing request to lookup " + req->question.name + " of type " + ConvToStr(req->question.type) + " to " + this->myserver.addr());
440 unsigned int tries = 0;
444 id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID+1);
446 if (++tries == DNS::MAX_REQUEST_ID*5)
448 // If we couldn't find an empty slot this many times, do a sequential scan as a last
449 // resort. If an empty slot is found that way, go on, otherwise throw an exception
451 for (unsigned int i = 0; i <= DNS::MAX_REQUEST_ID; i++)
453 if (!this->requests[i])
461 throw Exception("DNS: All ids are in use");
466 while (this->requests[id]);
469 this->requests[req->id] = req;
472 p.flags = QUERYFLAGS_RD;
474 p.question = req->question;
476 unsigned char buffer[524];
477 unsigned short len = p.Pack(buffer, sizeof(buffer));
479 /* Note that calling Pack() above can actually change the contents of p.question.name, if the query is a PTR,
480 * to contain the value that would be in the DNS cache, which is why this is here.
482 if (req->use_cache && this->CheckCache(req, p.question))
484 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Using cached result");
489 // Update name in the original request so question checking works for PTR queries
490 req->question.name = p.question.name;
492 if (SocketEngine::SendTo(this, buffer, len, 0, &this->myserver.sa, this->myserver.sa_size()) != len)
493 throw Exception("DNS: Unable to send query");
495 // Add timer for timeout
496 ServerInstance->Timers.AddTimer(req);
499 void RemoveRequest(DNS::Request* req)
501 if (requests[req->id] == req)
502 requests[req->id] = NULL;
505 std::string GetErrorStr(Error e)
510 return "Module is unloading";
512 return "Request timed out";
513 case ERROR_NOT_AN_ANSWER:
514 case ERROR_NONSTANDARD_QUERY:
515 case ERROR_FORMAT_ERROR:
516 case ERROR_MALFORMED:
517 return "Malformed answer";
518 case ERROR_SERVER_FAILURE:
519 case ERROR_NOT_IMPLEMENTED:
521 case ERROR_INVALIDTYPE:
522 return "Nameserver failure";
523 case ERROR_DOMAIN_NOT_FOUND:
524 case ERROR_NO_RECORDS:
525 return "Domain not found";
529 return "Unknown error";
533 void OnEventHandlerError(int errcode) CXX11_OVERRIDE
535 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "UDP socket got an error event");
538 void OnEventHandlerRead() CXX11_OVERRIDE
540 unsigned char buffer[524];
541 irc::sockets::sockaddrs from;
542 socklen_t x = sizeof(from);
544 int length = SocketEngine::RecvFrom(this, buffer, sizeof(buffer), 0, &from.sa, &x);
546 if (length < Packet::HEADER_LENGTH)
549 if (myserver != from)
551 std::string server1 = from.str();
552 std::string server2 = myserver.str();
553 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'",
554 server1.c_str(), server2.c_str());
563 recv_packet.Fill(buffer, length);
566 catch (Exception& ex)
568 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, ex.GetReason());
571 // recv_packet.id must be filled in here
572 DNS::Request* request = this->requests[recv_packet.id];
575 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer for something we didn't request");
579 if (request->question != recv_packet.question)
581 // This can happen under high latency, drop it silently, do not fail the request
582 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received an answer that isn't for a question we asked");
588 ServerInstance->stats.DnsBad++;
589 recv_packet.error = ERROR_MALFORMED;
590 request->OnError(&recv_packet);
592 else if (recv_packet.flags & QUERYFLAGS_OPCODE)
594 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Received a nonstandard query");
595 ServerInstance->stats.DnsBad++;
596 recv_packet.error = ERROR_NONSTANDARD_QUERY;
597 request->OnError(&recv_packet);
599 else if (!(recv_packet.flags & QUERYFLAGS_QR) || (recv_packet.flags & QUERYFLAGS_RCODE))
601 Error error = ERROR_UNKNOWN;
603 switch (recv_packet.flags & QUERYFLAGS_RCODE)
606 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "format error");
607 error = ERROR_FORMAT_ERROR;
610 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "server error");
611 error = ERROR_SERVER_FAILURE;
614 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "domain not found");
615 error = ERROR_DOMAIN_NOT_FOUND;
618 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "not implemented");
619 error = ERROR_NOT_IMPLEMENTED;
622 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "refused");
623 error = ERROR_REFUSED;
629 ServerInstance->stats.DnsBad++;
630 recv_packet.error = error;
631 request->OnError(&recv_packet);
633 else if (recv_packet.answers.empty())
635 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "No resource records returned");
636 ServerInstance->stats.DnsBad++;
637 recv_packet.error = ERROR_NO_RECORDS;
638 request->OnError(&recv_packet);
642 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Lookup complete for " + request->question.name);
643 ServerInstance->stats.DnsGood++;
644 request->OnLookupComplete(&recv_packet);
645 this->AddCache(recv_packet);
648 ServerInstance->stats.Dns++;
650 /* Request's destructor removes it from the request map */
654 bool Tick(time_t now)
656 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "cache: purging DNS cache");
658 for (cache_map::iterator it = this->cache.begin(); it != this->cache.end(); )
660 const Query& query = it->second;
661 if (IsExpired(query, now))
662 this->cache.erase(it++);
669 void Rehash(const std::string& dnsserver, std::string sourceaddr, unsigned int sourceport)
671 if (this->GetFd() > -1)
673 SocketEngine::Shutdown(this, 2);
674 SocketEngine::Close(this);
676 /* Remove expired entries from the cache */
677 this->Tick(ServerInstance->Time());
680 irc::sockets::aptosa(dnsserver, DNS::PORT, myserver);
682 /* Initialize mastersocket */
683 int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0);
686 /* Have we got a socket? */
687 if (this->GetFd() != -1)
689 SocketEngine::SetReuse(s);
690 SocketEngine::NonBlocking(s);
692 irc::sockets::sockaddrs bindto;
693 if (sourceaddr.empty())
695 // set a sourceaddr for irc::sockets::aptosa() based on the servers af type
696 if (myserver.sa.sa_family == AF_INET)
697 sourceaddr = "0.0.0.0";
698 else if (myserver.sa.sa_family == AF_INET6)
701 irc::sockets::aptosa(sourceaddr, sourceport, bindto);
703 if (SocketEngine::Bind(this->GetFd(), bindto) < 0)
706 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error binding dns socket - hostnames will NOT resolve");
707 SocketEngine::Close(this->GetFd());
710 else if (!SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE))
712 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Internal error starting DNS - hostnames will NOT resolve.");
713 SocketEngine::Close(this->GetFd());
717 if (bindto.sa.sa_family != myserver.sa.sa_family)
718 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Nameserver address family differs from source address family - hostnames might not resolve");
722 ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "Error creating DNS socket - hostnames will NOT resolve");
727 class ModuleDNS : public Module
730 std::string DNSServer;
731 std::string SourceIP;
732 unsigned int SourcePort;
737 // attempt to look up their nameserver from the system
738 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
740 PFIXED_INFO pFixedInfo;
741 DWORD dwBufferSize = sizeof(FIXED_INFO);
742 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
746 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW)
748 HeapFree(GetProcessHeap(), 0, pFixedInfo);
749 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
754 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
755 DNSServer = pFixedInfo->DnsServerList.IpAddress.String;
757 HeapFree(GetProcessHeap(), 0, pFixedInfo);
760 if (!DNSServer.empty())
762 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first active resolver in the system settings.", DNSServer.c_str());
767 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
769 // attempt to look up their nameserver from /etc/resolv.conf
770 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
772 std::ifstream resolv("/etc/resolv.conf");
774 while (resolv >> DNSServer)
776 if (DNSServer == "nameserver")
779 if (DNSServer.find_first_not_of("0123456789.") == std::string::npos || DNSServer.find_first_not_of("0123456789ABCDEFabcdef:") == std::string::npos)
781 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",DNSServer.c_str());
787 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
789 DNSServer = "127.0.0.1";
793 ModuleDNS() : manager(this)
798 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
800 std::string oldserver = DNSServer;
801 const std::string oldip = SourceIP;
802 const unsigned int oldport = SourcePort;
804 ConfigTag* tag = ServerInstance->Config->ConfValue("dns");
805 DNSServer = tag->getString("server");
806 SourceIP = tag->getString("sourceip");
807 SourcePort = tag->getInt("sourceport", 0, 0, 65535);
809 if (DNSServer.empty())
812 if (oldserver != DNSServer || oldip != SourceIP || oldport != SourcePort)
813 this->manager.Rehash(DNSServer, SourceIP, SourcePort);
816 void OnUnloadModule(Module* mod)
818 for (unsigned int i = 0; i <= MAX_REQUEST_ID; ++i)
820 DNS::Request* req = this->manager.requests[i];
824 if (req->creator == mod)
826 Query rr(req->question);
827 rr.error = ERROR_UNLOADED;
837 return Version("DNS support", VF_CORE|VF_VENDOR);
841 MODULE_INIT(ModuleDNS)