1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
|
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "utility.hh"
#include "resolver.hh"
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
#include <cerrno>
#include "misc.hh"
#include <algorithm>
#include <sstream>
#include "dnsrecords.hh"
#include <cstring>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "dns.hh"
#include "qtype.hh"
#include "pdnsexception.hh"
#include "arguments.hh"
#include "base64.hh"
#include "dnswriter.hh"
#include "dnsparser.hh"
#include "query-local-address.hh"
#include "dns_random.hh"
#include <poll.h>
#include "gss_context.hh"
#include "namespaces.hh"
using pdns::resolver::parseResult;
int makeQuerySocket(const ComboAddress& local, bool udpOrTCP, bool nonLocalBind)
{
ComboAddress ourLocal(local);
int sock=socket(ourLocal.sin4.sin_family, udpOrTCP ? SOCK_DGRAM : SOCK_STREAM, 0);
if(sock < 0) {
if(errno == EAFNOSUPPORT && local.sin4.sin_family == AF_INET6) {
return -1;
}
unixDie("Creating local resolver socket for address '"+ourLocal.toString()+"'");
}
setCloseOnExec(sock);
if(nonLocalBind)
Utility::setBindAny(local.sin4.sin_family, sock);
if(udpOrTCP) {
// udp, try hard to bind an unpredictable port
int tries=10;
while(--tries) {
ourLocal.sin4.sin_port = htons(10000+(dns_random(10000)));
if (::bind(sock, (struct sockaddr *)&ourLocal, ourLocal.getSocklen()) >= 0)
break;
}
// cerr<<"bound udp port "<<ourLocal.sin4.sin_port<<", "<<tries<<" tries left"<<endl;
if(!tries) {
closesocket(sock);
throw PDNSException("Resolver binding to local UDP socket on '"+ourLocal.toString()+"': "+stringerror());
}
}
else {
// tcp, let the kernel figure out the port
ourLocal.sin4.sin_port = 0;
if(::bind(sock, (struct sockaddr *)&ourLocal, ourLocal.getSocklen()) < 0) {
closesocket(sock);
throw PDNSException("Resolver binding to local TCP socket on '"+ourLocal.toString()+"': "+stringerror());
}
}
return sock;
}
Resolver::Resolver()
{
locals["default4"] = -1;
locals["default6"] = -1;
try {
if (pdns::isQueryLocalAddressFamilyEnabled(AF_INET)) {
locals["default4"] = makeQuerySocket(pdns::getQueryLocalAddress(AF_INET, 0), true, ::arg().mustDo("non-local-bind"));
}
if (pdns::isQueryLocalAddressFamilyEnabled(AF_INET6)) {
locals["default6"] = makeQuerySocket(pdns::getQueryLocalAddress(AF_INET6, 0), true, ::arg().mustDo("non-local-bind"));
}
}
catch(...) {
if(locals["default4"]>=0)
close(locals["default4"]);
if(locals["default6"]>=0)
close(locals["default6"]);
throw;
}
}
Resolver::~Resolver()
{
for (auto& iter: locals) {
if (iter.second >= 0)
close(iter.second);
}
}
uint16_t Resolver::sendResolve(const ComboAddress& remote, const ComboAddress& local,
const DNSName &domain, int type, int *localsock, bool dnssecOK,
const DNSName& tsigkeyname, const DNSName& tsigalgorithm,
const string& tsigsecret)
{
uint16_t randomid;
vector<uint8_t> packet;
DNSPacketWriter pw(packet, domain, type);
pw.getHeader()->id = randomid = dns_random_uint16();
if(dnssecOK) {
pw.addOpt(2800, 0, EDNSOpts::DNSSECOK);
pw.commit();
}
if(!tsigkeyname.empty()) {
// cerr<<"Adding TSIG to notification, key name: '"<<tsigkeyname<<"', algo: '"<<tsigalgorithm<<"', secret: "<<Base64Encode(tsigsecret)<<endl;
TSIGRecordContent trc;
if (tsigalgorithm == DNSName("hmac-md5"))
trc.d_algoName = tsigalgorithm + DNSName("sig-alg.reg.int");
else
trc.d_algoName = tsigalgorithm;
trc.d_time = time(nullptr);
trc.d_fudge = 300;
trc.d_origID=ntohs(randomid);
trc.d_eRcode=0;
addTSIG(pw, trc, tsigkeyname, tsigsecret, "", false);
}
int sock;
// choose socket based on local
if (local.sin4.sin_family == 0) {
// up to us.
if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
string ipv = remote.sin4.sin_family == AF_INET ? "4" : "6";
throw ResolverException("No IPv" + ipv + " socket available, is such an address configured in query-local-address?");
}
sock = remote.sin4.sin_family == AF_INET ? locals["default4"] : locals["default6"];
} else {
std::string lstr = local.toString();
std::map<std::string, int>::iterator lptr;
// reuse an existing local socket or make a new one
if ((lptr = locals.find(lstr)) != locals.end()) {
sock = lptr->second;
} else {
// try to make socket
sock = makeQuerySocket(local, true);
if (sock < 0)
throw ResolverException("Unable to create local socket on '"+lstr+"'' to '"+remote.toLogString()+"': "+stringerror());
setNonBlocking( sock );
locals[lstr] = sock;
}
}
if (localsock != nullptr) {
*localsock = sock;
}
if(sendto(sock, &packet[0], packet.size(), 0, (struct sockaddr*)(&remote), remote.getSocklen()) < 0) {
throw ResolverException("Unable to ask query of '"+remote.toLogString()+"': "+stringerror());
}
return randomid;
}
namespace pdns {
namespace resolver {
int parseResult(MOADNSParser& mdp, const DNSName& origQname, uint16_t /* origQtype */, uint16_t id, Resolver::res_t* result)
{
result->clear();
if(mdp.d_header.rcode)
return mdp.d_header.rcode;
if(origQname.countLabels()) { // not AXFR
if(mdp.d_header.id != id)
throw ResolverException("Remote nameserver replied with wrong id");
if(mdp.d_header.qdcount != 1)
throw ResolverException("resolver: received answer with wrong number of questions ("+std::to_string(mdp.d_header.qdcount)+")");
if(mdp.d_qname != origQname)
throw ResolverException(string("resolver: received an answer to another question (")+mdp.d_qname.toLogString()+"!="+ origQname.toLogString()+".)");
}
vector<DNSResourceRecord> ret;
DNSResourceRecord rr;
result->reserve(mdp.d_answers.size());
for (const auto& i: mdp.d_answers) {
rr.qname = i.d_name;
rr.qtype = i.d_type;
rr.ttl = i.d_ttl;
rr.content = i.getContent()->getZoneRepresentation(true);
result->push_back(rr);
}
return 0;
}
} // namespace resolver
} // namespace pdns
bool Resolver::tryGetSOASerial(DNSName *domain, ComboAddress* remote, uint32_t *theirSerial, uint32_t *theirInception, uint32_t *theirExpire, uint16_t* id)
{
auto fds = std::make_unique<struct pollfd[]>(locals.size());
size_t i = 0, k;
int sock;
for (const auto& iter: locals) {
fds[i].fd = iter.second;
fds[i].events = POLLIN;
++i;
}
if (poll(fds.get(), i, 250) < 1) { // wait for 0.25s
return false;
}
sock = -1;
// determine who
for(k=0;k<i;k++) {
if ((fds[k].revents & POLLIN) == POLLIN) {
sock = fds[k].fd;
break;
}
}
if (sock < 0) return false; // false alarm
int err;
remote->sin6.sin6_family = AF_INET6; // make sure getSocklen() below returns a large enough value
socklen_t addrlen=remote->getSocklen();
char buf[3000];
err = recvfrom(sock, buf, sizeof(buf), 0,(struct sockaddr*)(remote), &addrlen);
if(err < 0) {
if(errno == EAGAIN)
return false;
throw ResolverException("recvfrom error waiting for answer: "+stringerror());
}
MOADNSParser mdp(false, (char*)buf, err);
*id=mdp.d_header.id;
*domain = mdp.d_qname;
if(domain->empty())
throw ResolverException("SOA query to '" + remote->toLogString() + "' produced response without domain name (RCode: " + RCode::to_s(mdp.d_header.rcode) + ")");
if(mdp.d_answers.empty())
throw ResolverException("Query to '" + remote->toLogString() + "' for SOA of '" + domain->toLogString() + "' produced no results (RCode: " + RCode::to_s(mdp.d_header.rcode) + ")");
if(mdp.d_qtype != QType::SOA)
throw ResolverException("Query to '" + remote->toLogString() + "' for SOA of '" + domain->toLogString() + "' returned wrong record type");
if(mdp.d_header.rcode != 0)
throw ResolverException("Query to '" + remote->toLogString() + "' for SOA of '" + domain->toLogString() + "' returned Rcode " + RCode::to_s(mdp.d_header.rcode));
*theirInception = *theirExpire = 0;
bool gotSOA=false;
for(const MOADNSParser::answers_t::value_type& drc : mdp.d_answers) {
if(drc.d_type == QType::SOA && drc.d_name == *domain) {
auto src = getRR<SOARecordContent>(drc);
if (src) {
*theirSerial = src->d_st.serial;
gotSOA = true;
}
}
if(drc.d_type == QType::RRSIG && drc.d_name == *domain) {
auto rrc = getRR<RRSIGRecordContent>(drc);
if(rrc && rrc->d_type == QType::SOA) {
*theirInception= std::max(*theirInception, rrc->d_siginception);
*theirExpire = std::max(*theirExpire, rrc->d_sigexpire);
}
}
}
if(!gotSOA)
throw ResolverException("Query to '" + remote->toLogString() + "' for SOA of '" + domain->toLogString() + "' did not return a SOA");
return true;
}
int Resolver::resolve(const ComboAddress& to, const DNSName &domain, int type, Resolver::res_t* res, const ComboAddress &local)
{
try {
int sock = -1;
int id = sendResolve(to, local, domain, type, &sock);
int err=waitForData(sock, 0, 3000000);
if(!err) {
throw ResolverException("Timeout waiting for answer");
}
if(err < 0)
throw ResolverException("Error waiting for answer: "+stringerror());
ComboAddress from;
socklen_t addrlen = sizeof(from);
char buffer[3000];
int len;
if((len=recvfrom(sock, buffer, sizeof(buffer), 0,(struct sockaddr*)(&from), &addrlen)) < 0)
throw ResolverException("recvfrom error waiting for answer: "+stringerror());
if (from != to) {
throw ResolverException("Got answer from the wrong peer while resolving ('"+from.toLogString()+"' instead of '"+to.toLogString()+"', discarding");
}
MOADNSParser mdp(false, buffer, len);
return parseResult(mdp, domain, type, id, res);
}
catch(ResolverException &re) {
throw ResolverException(re.reason+" from "+to.toLogString());
}
}
int Resolver::resolve(const ComboAddress& ipport, const DNSName &domain, int type, Resolver::res_t* res) {
ComboAddress local;
local.sin4.sin_family = 0;
return resolve(ipport, domain, type, res, local);
}
void Resolver::getSoaSerial(const ComboAddress& ipport, const DNSName &domain, uint32_t *serial)
{
vector<DNSResourceRecord> res;
int ret = resolve(ipport, domain, QType::SOA, &res);
if(ret || res.empty())
throw ResolverException("Query to '" + ipport.toLogString() + "' for SOA of '" + domain.toLogString() + "' produced no answers");
if(res[0].qtype.getCode() != QType::SOA)
throw ResolverException("Query to '" + ipport.toLogString() + "' for SOA of '" + domain.toLogString() + "' produced a "+res[0].qtype.toString()+" record");
vector<string>parts;
stringtok(parts, res[0].content);
if(parts.size()<3)
throw ResolverException("Query to '" + ipport.toLogString() + "' for SOA of '" + domain.toLogString() + "' produced an unparseable response");
try {
*serial = pdns::checked_stoi<uint32_t>(parts[2]);
}
catch(const std::out_of_range& oor) {
throw ResolverException("Query to '" + ipport.toLogString() + "' for SOA of '" + domain.toLogString() + "' produced an unparseable serial");
}
}
|