]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/rfc2136handler.cc
Fix narrow test result
[thirdparty/pdns.git] / pdns / rfc2136handler.cc
CommitLineData
f1b59a55
RA
1#include "packethandler.hh"
2#include "qtype.hh"
3#include "dnspacket.hh"
4#include "packetcache.hh"
5#include "dnsseckeeper.hh"
6#include "base64.hh"
7#include "base32.hh"
8#include "misc.hh"
9#include "arguments.hh"
b3148887
RA
10#include "resolver.hh"
11#include "dns_random.hh"
7facf345 12#include "backends/gsql/ssql.hh"
f1b59a55
RA
13
14extern PacketCache PC;
276a5ce7 15extern StatBag S;
f1b59a55 16
ee9ef8f2
RA
17pthread_mutex_t PacketHandler::s_rfc2136lock=PTHREAD_MUTEX_INITIALIZER;
18
f1b59a55
RA
19// Implement section 3.2.1 and 3.2.2 of RFC2136
20int PacketHandler::checkUpdatePrerequisites(const DNSRecord *rr, DomainInfo *di) {
21 if (rr->d_ttl != 0)
22 return RCode::FormErr;
23
24 // 3.2.1 and 3.2.2 check content length.
25 if ( (rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_clen != 0)
26 return RCode::FormErr;
27
6a323f63 28 string rrLabel = stripDot(rr->d_label);
f1b59a55
RA
29
30 bool foundRecord=false;
31 DNSResourceRecord rec;
6a323f63 32 di->backend->lookup(QType(QType::ANY), rrLabel);
f1b59a55
RA
33 while(di->backend->get(rec)) {
34 if (!rec.qtype.getCode())
35 continue;
36 if ((rr->d_type != QType::ANY && rec.qtype == rr->d_type) || rr->d_type == QType::ANY)
37 foundRecord=true;
38 }
39
40 // Section 3.2.1
41 if (rr->d_class == QClass::ANY && !foundRecord) {
42 if (rr->d_type == QType::ANY)
43 return RCode::NXDomain;
44 if (rr->d_type != QType::ANY)
45 return RCode::NXRRSet;
46 }
47
48 // Section 3.2.2
49 if (rr->d_class == QClass::NONE && foundRecord) {
50 if (rr->d_type == QType::ANY)
51 return RCode::YXDomain;
52 if (rr->d_type != QType::ANY)
53 return RCode::YXRRSet;
54 }
55
56 return RCode::NoError;
57}
58
59
60// Method implements section 3.4.1 of RFC2136
61int PacketHandler::checkUpdatePrescan(const DNSRecord *rr) {
62 // The RFC stats that d_class != ZCLASS, but we only support the IN class.
63 if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY)
64 return RCode::FormErr;
65
66 QType qtype = QType(rr->d_type);
67
68 if (! qtype.isSupportedType())
69 return RCode::FormErr;
70
71 if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_ttl != 0)
72 return RCode::FormErr;
73
74 if (rr->d_class == QClass::ANY && rr->d_clen != 0)
75 return RCode::FormErr;
76
77 if (qtype.isMetadataType())
78 return RCode::FormErr;
79
80 if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY)
81 return RCode::FormErr;
82
83 return RCode::NoError;
84}
85
6a323f63 86
f1b59a55 87// Implements section 3.4.2 of RFC2136
dff32e09
RA
88uint16_t PacketHandler::performUpdate(const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool* narrow, bool* haveNSEC3, NSEC3PARAMRecordContent *ns3pr, bool *updatedSerial) {
89 string rrLabel = stripDot(rr->d_label);
90 rrLabel = toLower(rrLabel);
91 QType rrType = QType(rr->d_type);
92
93
94 if (rrType == QType::NSEC || rrType == QType::NSEC3) {
95 L<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rrLabel<<"|"<<rrType.getName()<<". These are generated records, ignoring!"<<endl;
96 return 0;
97 }
98
99 if (!isPresigned && (rrType == QType::RRSIG || rrType == QType::DNSKEY) ) {
100 L<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rrLabel<<"|"<<rrType.getName()<<" in non-presigned zone, ignoring!"<<endl;
101 return 0;
102 }
103
104 if (rrType == QType::NSEC3PARAM && rrLabel != di->zone) {
105 L<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rrLabel<<"|NSEC3PARAM, NSEC3PARAM must be at zone apex, ignoring!"<<endl;
106 return 0;
107 }
108
109
b0704e0d 110 uint16_t changedRecords = 0;
6a323f63
RA
111 DNSResourceRecord rec;
112 vector<DNSResourceRecord> rrset, recordsToDelete;
113 set<string> delnonterm, insnonterm; // used to (at the end) fix ENT records.
114
f1b59a55 115
6a323f63
RA
116 if (rr->d_class == QClass::IN) { // 3.4.2.2 QClass::IN means insert or update
117 DLOG(L<<msgPrefix<<"Add/Update record (QClass == IN) "<<rrLabel<<"|"<<rrType.getName()<<endl);
f1b59a55 118
dff32e09
RA
119 if (rrType == QType::NSEC3PARAM) {
120 L<<Logger::Notice<<msgPrefix<<"Setting NSEC3PARAM for zone, resetting ordernames."<<endl;
121 NSEC3PARAMRecordContent nsec3param(rr->d_content->getZoneRepresentation(), di->zone);
122 d_dk.setNSEC3PARAM(di->zone, nsec3param, (*narrow));
123 *haveNSEC3 = d_dk.getNSEC3PARAM(di->zone, ns3pr, narrow);
124 di->backend->list(di->zone, di->id);
125 vector<DNSResourceRecord> rrs;
126 while (di->backend->get(rec)) {
127 rrs.push_back(rec);
128 }
129 for (vector<DNSResourceRecord>::const_iterator i = rrs.begin(); i != rrs.end(); i++) {
130 if (*narrow) {
131 di->backend->nullifyDNSSECOrderNameAndUpdateAuth(di->id, i->qname, i->auth);
132 } else {
133 string hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, i->qname)));
134 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, i->qname, hashed, i->auth);
135 }
136 }
137 return 1;
138 }
139
6a323f63
RA
140 bool foundRecord = false;
141 di->backend->lookup(rrType, rrLabel);
f1b59a55 142 while (di->backend->get(rec)) {
dff32e09
RA
143 rrset.push_back(rec);
144 foundRecord = true;
6a323f63 145 }
6a323f63
RA
146
147 if (foundRecord) {
dff32e09 148 if (rrType == QType::SOA) { // SOA updates require the serial to be higher than the current
f1b59a55 149 SOAData sdOld, sdUpdate;
6a323f63
RA
150 DNSResourceRecord *oldRec = &rrset.front();
151 fillSOAData(oldRec->content, sdOld);
152 oldRec->setContent(rr->d_content->getZoneRepresentation());
153 fillSOAData(oldRec->content, sdUpdate);
f1b59a55 154 if (rfc1982LessThan(sdOld.serial, sdUpdate.serial)) {
b0704e0d 155 changedRecords++;
6a323f63 156 di->backend->replaceRRSet(di->id, oldRec->qname, oldRec->qtype, rrset);
f1b59a55 157 *updatedSerial = true;
7facf345 158 L<<Logger::Notice<<msgPrefix<<"Replacing record "<<rrLabel<<"|"<<rrType.getName()<<endl;
f1b59a55
RA
159 }
160 else
161 L<<Logger::Notice<<msgPrefix<<"Provided serial ("<<sdUpdate.serial<<") is older than the current serial ("<<sdOld.serial<<"), ignoring SOA update."<<endl;
6a323f63
RA
162
163 // It's not possible to have multiple CNAME's with the same NAME. So we always update.
164 } else if (rrType == QType::CNAME) {
165 for (vector<DNSResourceRecord>::iterator i = rrset.begin(); i != rrset.end(); i++) {
166 i->ttl = rr->d_ttl;
167 i->setContent(rr->d_content->getZoneRepresentation());
b0704e0d 168 changedRecords++;
f1b59a55 169 }
6a323f63 170 di->backend->replaceRRSet(di->id, rrLabel, rrType, rrset);
7facf345 171 L<<Logger::Notice<<msgPrefix<<"Replacing record "<<rrLabel<<"|"<<rrType.getName()<<endl;
6a323f63
RA
172
173 // In any other case, we must check if the TYPE and RDATA match to provide an update (which effectily means a update of TTL)
174 } else {
175 foundRecord = false;
176 for (vector<DNSResourceRecord>::iterator i = rrset.begin(); i != rrset.end(); i++) {
177 string content = rr->d_content->getZoneRepresentation();
178 if (rrType == i->qtype.getCode() && i->getZoneRepresentation() == content) {
179 foundRecord = true;
180 i->ttl = rr->d_ttl;
b0704e0d 181 changedRecords++;
6a323f63
RA
182 }
183 }
7facf345 184 if (foundRecord) {
6a323f63 185 di->backend->replaceRRSet(di->id, rrLabel, rrType, rrset);
7facf345
RA
186 L<<Logger::Notice<<msgPrefix<<"Replacing record "<<rrLabel<<"|"<<rrType.getName()<<endl;
187 }
f1b59a55 188 }
6e42cac2
RA
189
190 // ReplaceRRSet dumps our ordername and auth flag, so we need to correct it.
191 // We can take the auth flag from the first RR in the set, as the name is different, so should the auth be.
192 bool auth = rrset.front().auth;
dff32e09 193 if(*haveNSEC3) {
6e42cac2 194 string hashed;
dff32e09 195 if(! *narrow)
6e42cac2
RA
196 hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, rrLabel)));
197
198 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, rrLabel, hashed, auth);
199 if(!auth || rrType == QType::DS) {
200 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "NS");
201 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "A");
202 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "AAAA");
203 }
204
205 } else { // NSEC
206 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, rrLabel, auth);
207 if(!auth || rrType == QType::DS) {
208 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "A");
209 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "AAAA");
210 }
211 }
212
213 } // if (foundRecord)
f1b59a55 214
6a323f63 215 // If we haven't found a record that matches, we must add it.
f1b59a55 216 if (! foundRecord) {
6a323f63
RA
217 L<<Logger::Notice<<msgPrefix<<"Adding record "<<rrLabel<<"|"<<rrType.getName()<<endl;
218 delnonterm.insert(rrLabel); // always remove any ENT's in the place where we're going to add a record.
f1b59a55
RA
219 DNSResourceRecord newRec(*rr);
220 newRec.domain_id = di->id;
f1b59a55 221 di->backend->feedRecord(newRec);
b0704e0d 222 changedRecords++;
6a323f63
RA
223
224
225 // because we added a record, we need to fix DNSSEC data.
226 string shorter(rrLabel);
f1b59a55
RA
227 bool auth=true;
228
229 set<string> insnonterm;
6a323f63 230 if (shorter != di->zone && rrType != QType::DS) {
f1b59a55
RA
231 do {
232 if (shorter == di->zone)
233 break;
234
235 bool foundShorter = false;
236 di->backend->lookup(QType(QType::ANY), shorter);
237 while (di->backend->get(rec)) {
6a323f63 238 if (rec.qname != rrLabel)
f1b59a55
RA
239 foundShorter = true;
240 if (rec.qtype == QType::NS)
241 auth=false;
242 }
6a323f63 243 if (!foundShorter && shorter != rrLabel && shorter != di->zone)
f1b59a55
RA
244 insnonterm.insert(shorter);
245
246 } while(chopOff(shorter));
247 }
248
dff32e09 249 if(*haveNSEC3)
f1b59a55
RA
250 {
251 string hashed;
dff32e09 252 if(! *narrow)
6a323f63 253 hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, rrLabel)));
f1b59a55 254
6a323f63
RA
255 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, rrLabel, hashed, auth);
256 if(!auth || rrType == QType::DS)
f1b59a55 257 {
6a323f63
RA
258 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "NS");
259 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "A");
260 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "AAAA");
f1b59a55
RA
261 }
262 }
263 else // NSEC
264 {
6a323f63
RA
265 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, rrLabel, auth);
266 if(!auth || rrType == QType::DS)
f1b59a55 267 {
6a323f63
RA
268 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "A");
269 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, rrLabel, "AAAA");
f1b59a55
RA
270 }
271 }
6a323f63
RA
272
273
f1b59a55 274 // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
6a323f63
RA
275 // Auth can only be false when the rrLabel is not the zone
276 if (auth == false && rrType == QType::NS) {
277 DLOG(L<<msgPrefix<<"Going to fix auth flags below "<<rrLabel<<endl);
f1b59a55 278 vector<string> qnames;
6a323f63 279 di->backend->listSubZone(rrLabel, di->id);
f1b59a55
RA
280 while(di->backend->get(rec)) {
281 if (rec.qtype.getCode() && rec.qtype.getCode() != QType::DS) // Skip ENT and DS records.
282 qnames.push_back(rec.qname);
283 }
284 for(vector<string>::const_iterator qname=qnames.begin(); qname != qnames.end(); ++qname) {
dff32e09 285 if(*haveNSEC3) {
f1b59a55 286 string hashed;
dff32e09 287 if(! *narrow)
f1b59a55
RA
288 hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, *qname)));
289
290 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, *qname, hashed, auth);
291 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, *qname, "NS");
292 }
293 else // NSEC
294 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, *qname, auth);
295
296 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, *qname, "AAAA");
297 di->backend->nullifyDNSSECOrderNameAndAuth(di->id, *qname, "A");
298 }
299 }
f1b59a55
RA
300 }
301 } // rr->d_class == QClass::IN
302
6a323f63
RA
303
304 // Delete records - section 3.4.2.3 and 3.4.2.4 with the exception of the 'always leave 1 NS rule' as that's handled by
305 // the code that calls this performUpdate().
306 if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
fdf983eb 307 DLOG(L<<msgPrefix<<"Deleting records: "<<rrLabel<<"; QClasse:"<<rr->d_class<<"; rrType: "<<rrType.getName()<<endl);
dff32e09
RA
308
309 if (rrType == QType::NSEC3PARAM) {
310 L<<Logger::Notice<<msgPrefix<<"Removing NSEC3PARAM from zone, resetting ordernames."<<endl;
311 if (rr->d_class == QClass::ANY)
312 d_dk.unsetNSEC3PARAM(rrLabel);
313 else if (rr->d_class == QClass::NONE) {
314 NSEC3PARAMRecordContent nsec3rr(rr->d_content->getZoneRepresentation(), di->zone);
0bb68041 315 if (ns3pr->getZoneRepresentation() == nsec3rr.getZoneRepresentation())
dff32e09
RA
316 d_dk.unsetNSEC3PARAM(rrLabel);
317 else
318 return 0;
319 } else
320 return 0;
321
0bb68041 322 *haveNSEC3 = d_dk.getNSEC3PARAM(di->zone, ns3pr, narrow); // still update, as other records in this update packet need to use it as well.
dff32e09
RA
323 di->backend->list(di->zone, di->id);
324 vector<DNSResourceRecord> rrs;
325 while (di->backend->get(rec)) {
326 rrs.push_back(rec);
327 }
328 for (vector<DNSResourceRecord>::const_iterator i = rrs.begin(); i != rrs.end(); i++) {
329 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, i->qname, i->auth);
330 }
331 return 1;
332 }
333
334
6a323f63
RA
335 di->backend->lookup(rrType, rrLabel);
336 while(di->backend->get(rec)) {
337 if (rr->d_class == QClass::ANY) { // 3.4.2.3
338 if (rec.qname == di->zone && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) // Never delete all SOA and NS's
339 rrset.push_back(rec);
340 else
f1b59a55
RA
341 recordsToDelete.push_back(rec);
342 }
6a323f63
RA
343 if (rr->d_class == QClass::NONE) { // 3.4.2.4
344 if (rrType == rec.qtype && rec.getZoneRepresentation() == rr->d_content->getZoneRepresentation())
345 recordsToDelete.push_back(rec);
346 else
347 rrset.push_back(rec);
348 }
f1b59a55 349
f1b59a55 350 }
6a323f63 351 di->backend->replaceRRSet(di->id, rrLabel, rrType, rrset);
7facf345 352 L<<Logger::Notice<<msgPrefix<<"Deleting record "<<rrLabel<<"|"<<rrType.getName()<<endl;
f1b59a55 353
f1b59a55 354
6a323f63
RA
355 if (recordsToDelete.size()) {
356 // If we remove an NS which is not at apex of the zone, we need to make everthing below it auth=true as those now are not delegated anymore.
357 if (rrType == QType::NS && rrLabel != di->zone) {
f1b59a55 358 vector<string> changeAuth;
6a323f63 359 di->backend->listSubZone(rrLabel, di->id);
f1b59a55 360 while (di->backend->get(rec)) {
7a0a9f8a 361 if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
f1b59a55
RA
362 changeAuth.push_back(rec.qname);
363 }
364 for (vector<string>::const_iterator changeRec=changeAuth.begin(); changeRec!=changeAuth.end(); ++changeRec) {
dff32e09 365 if(*haveNSEC3) {
f1b59a55 366 string hashed;
dff32e09 367 if(! *narrow)
f1b59a55
RA
368 hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, *changeRec)));
369
370 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, *changeRec, hashed, true);
371 }
372 else // NSEC
373 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, *changeRec, true);
374 }
375 }
f1b59a55 376
6a323f63
RA
377 // Fix ENT records.
378 // We must check if we have a record below the current level and if we removed the 'last' record
379 // on that level. If so, we must insert an ENT record.
fdf983eb 380 // We take extra care here to not 'include' the record that we just deleted. Some backends will still return it as they only reload on a commit.
9353d244 381 bool foundDeeper = false, foundOtherWithSameName = false;
6a323f63
RA
382 di->backend->listSubZone(rrLabel, di->id);
383 while (di->backend->get(rec)) {
384 if (rec.qname == rrLabel && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
9353d244 385 foundOtherWithSameName = true;
7a0a9f8a 386 if (rec.qname != rrLabel && rec.qtype.getCode() != QType::NS) //Skip NS records, as this would be a delegate that we can ignore as this does not require us to create a ENT
6a323f63
RA
387 foundDeeper = true;
388 }
f1b59a55 389
9353d244 390 if (foundDeeper && !foundOtherWithSameName) {
6a323f63 391 insnonterm.insert(rrLabel);
9353d244 392 } else if (!foundOtherWithSameName) {
6a323f63
RA
393 // If we didn't have to insert an ENT, we might have deleted a record at very deep level
394 // and we must then clean up the ENT's above the deleted record.
395 string shorter(rrLabel);
9353d244
RA
396 while (shorter != di->zone) {
397 chopOff(shorter);
398 bool foundRealRR = false;
399
400 // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
6a323f63 401 // consider these non ENT-records:
9353d244
RA
402 // b.c.d.e.test.com
403 // b.d.e.test.com
404 // if we delete b.c.d.e.test.com, we go up to d.e.test.com and then find b.d.e.test.com because that's below d.e.test.com.
6a323f63
RA
405 // At that point we can stop deleting ENT's because the tree is in tact again.
406 di->backend->listSubZone(shorter, di->id);
9353d244
RA
407 while (di->backend->get(rec)) {
408 if (rec.qtype.getCode())
409 foundRealRR = true;
410 }
411 if (!foundRealRR)
412 delnonterm.insert(shorter);
413 else
414 break;
415 }
6a323f63 416 }
f1b59a55 417 }
6a323f63 418 }
f1b59a55 419
6a323f63
RA
420
421 //Insert and delete ENT's
422 if (insnonterm.size() > 0 || delnonterm.size() > 0) {
423 DLOG(L<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
424 di->backend->updateEmptyNonTerminals(di->id, di->zone, insnonterm, delnonterm, false);
425 for (set<string>::const_iterator i=insnonterm.begin(); i!=insnonterm.end(); i++) {
426 string hashed;
dff32e09 427 if(*haveNSEC3)
6a323f63 428 {
f1b59a55 429 string hashed;
dff32e09 430 if(! *narrow)
6a323f63
RA
431 hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, *i)));
432 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, *i, hashed, false);
f1b59a55
RA
433 }
434 }
435 }
436
b0704e0d 437 return recordsToDelete.size() + changedRecords;
f1b59a55
RA
438}
439
b3148887 440int PacketHandler::forwardPacket(const string &msgPrefix, DNSPacket *p, DomainInfo *di) {
e174b255
RA
441 vector<string> forward;
442 B.getDomainMetadata(p->qdomain, "FORWARD-2136", forward);
443
444 if (forward.size() == 0 && ! ::arg().mustDo("forward-2136")) {
d8293c79
RA
445 L<<Logger::Notice<<msgPrefix<<"Not configured to forward to master, returning Refused."<<endl;
446 return RCode::Refused;
e174b255
RA
447 }
448
b3148887 449 for(vector<string>::const_iterator master=di->masters.begin(); master != di->masters.end(); master++) {
dff32e09 450 L<<Logger::Notice<<msgPrefix<<"Forwarding packet to master "<<*master<<endl;
b3148887
RA
451 ComboAddress remote;
452 try {
cc456024 453 remote = ComboAddress(*master, 53);
b3148887
RA
454 }
455 catch (...) {
456 L<<Logger::Error<<msgPrefix<<"Failed to parse "<<*master<<" as valid remote."<<endl;
457 continue;
458 }
459
460 ComboAddress local;
461 if(remote.sin4.sin_family == AF_INET)
cc456024 462 local = ComboAddress(::arg()["query-local-address"]);
b3148887 463 else if(!::arg()["query-local-address6"].empty())
cc456024 464 local = ComboAddress(::arg()["query-local-address6"]);
b3148887 465 else
cc456024 466 local = ComboAddress("::");
b3148887
RA
467 int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
468
469 if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
470 L<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
471 Utility::closesocket(sock);
472 continue;
473 }
474
475 DNSPacket forwardPacket(*p);
476 forwardPacket.setID(dns_random(0xffff));
477 forwardPacket.setRemote(&remote);
478 uint16_t len=htons(forwardPacket.getString().length());
479 string buffer((const char*)&len, 2);
480 buffer.append(forwardPacket.getString());
481 if(write(sock, buffer.c_str(), buffer.length()) < 0) {
482 L<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
483 continue;
484 }
485
486 int res = waitForData(sock, 10, 0);
487 if (!res) {
cc456024 488 L<<Logger::Error<<msgPrefix<<"Timeout waiting for reply from master at "<<remote.toStringWithPort()<<endl;
b3148887
RA
489 Utility::closesocket(sock);
490 continue;
491 }
492 if (res < 0) {
493 L<<Logger::Error<<msgPrefix<<"Error waiting for answer from master at "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
494 Utility::closesocket(sock);
495 continue;
496 }
497
498 char lenBuf[2];
499 int recvRes;
500 recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
501 if (recvRes < 0) {
502 L<<Logger::Error<<msgPrefix<<"Could not receive data (length) from master at "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
503 Utility::closesocket(sock);
504 continue;
505 }
506 int packetLen = lenBuf[0]*256+lenBuf[1];
507
508
509 char buf[packetLen];
510 recvRes = recv(sock, &buf, packetLen, 0);
511 if (recvRes < 0) {
512 L<<Logger::Error<<msgPrefix<<"Could not receive data (dnspacket) from master at "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
513 Utility::closesocket(sock);
514 continue;
515 }
516 Utility::closesocket(sock);
517
518 try {
b3148887
RA
519 MOADNSParser mdp(buf, recvRes);
520 L<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
521 return mdp.d_header.rcode;
522 }
523 catch (...) {
524 L<<Logger::Error<<msgPrefix<<"Failed to parse response packet from master at "<<remote.toStringWithPort()<<endl;
525 continue;
526 }
527 }
528 L<<Logger::Error<<msgPrefix<<"Failed to forward packet to master(s). Returning ServFail."<<endl;
529 return RCode::ServFail;
530
531}
532
f1b59a55 533int PacketHandler::processUpdate(DNSPacket *p) {
629e6103 534 if (! ::arg().mustDo("experimental-rfc2136"))
f1b59a55
RA
535 return RCode::Refused;
536
7facf345 537 string msgPrefix="UPDATE (" + itoa(p->d.id) + ") from " + p->getRemote() + " for " + p->qdomain + ": ";
f1b59a55
RA
538 L<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
539
540 // Check permissions - IP based
541 vector<string> allowedRanges;
542 B.getDomainMetadata(p->qdomain, "ALLOW-2136-FROM", allowedRanges);
543 if (! ::arg()["allow-2136-from"].empty())
544 stringtok(allowedRanges, ::arg()["allow-2136-from"], ", \t" );
545
546 NetmaskGroup ng;
547 for(vector<string>::const_iterator i=allowedRanges.begin(); i != allowedRanges.end(); i++)
548 ng.addMask(*i);
549
550 if ( ! ng.match(&p->d_remote)) {
551 L<<Logger::Error<<msgPrefix<<"Remote not listed in allow-2136-from or domainmetadata. Sending REFUSED"<<endl;
552 return RCode::Refused;
553 }
554
555
556 // Check permissions - TSIG based.
557 vector<string> tsigKeys;
558 B.getDomainMetadata(p->qdomain, "TSIG-ALLOW-2136", tsigKeys);
559 if (tsigKeys.size() > 0) {
560 bool validKey = false;
561
562 TSIGRecordContent trc;
563 string inputkey, message;
564 if (! p->getTSIGDetails(&trc, &inputkey, &message)) {
565 L<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
566 return RCode::Refused;
567 }
568
569 for(vector<string>::const_iterator key=tsigKeys.begin(); key != tsigKeys.end(); key++) {
570 if (inputkey == *key) // because checkForCorrectTSIG has already been performed earlier on, if the names of the ky match with the domain given. THis is valid.
571 validKey=true;
572 }
573
574 if (!validKey) {
575 L<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
576 return RCode::Refused;
577 }
578 }
579
580 if (tsigKeys.size() == 0 && p->d_havetsig)
581 L<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
582
583 // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
584 // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
585 // variable names during the use of our MOADNSParser.
586 MOADNSParser mdp(p->getString());
587 if (mdp.d_header.qdcount != 1) {
588 L<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
589 return RCode::FormErr;
590 }
591
592 if (p->qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
593 L<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
594 return RCode::FormErr;
595 }
596
597 if (p->qclass != QClass::IN) {
598 L<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
599 return RCode::NotAuth;
600 }
601
602 DomainInfo di;
603 di.backend=0;
604 if(!B.getDomainInfo(p->qdomain, di) || !di.backend) {
605 L<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<p->qdomain<<"' (or backend does not support RFC2136 operation)"<<endl;
606 return RCode::NotAuth;
607 }
608
b3148887
RA
609 if (di.kind == DomainInfo::Slave)
610 return forwardPacket(msgPrefix, p, &di);
f1b59a55
RA
611
612 // Check if all the records provided are within the zone
613 for(MOADNSParser::answers_t::const_iterator i=mdp.d_answers.begin(); i != mdp.d_answers.end(); ++i) {
614 const DNSRecord *rr = &i->first;
615 // Skip this check for other field types (like the TSIG - which is in the additional section)
dff32e09 616 // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
f1b59a55
RA
617 if (! (rr->d_place == DNSRecord::Answer || rr->d_place == DNSRecord::Nameserver))
618 continue;
619
620 string label = stripDot(rr->d_label);
621
622 if (!endsOn(label, di.zone)) {
623 L<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
624 return RCode::NotZone;
625 }
626 }
627
dff32e09
RA
628
629 Lock l(&s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
f1b59a55 630 L<<Logger::Info<<msgPrefix<<"starting transaction."<<endl;
dff32e09 631 if (!di.backend->startTransaction(p->qdomain, -1)) { // Not giving the domain_id means that we do not delete the existing records.
f1b59a55
RA
632 L<<Logger::Error<<msgPrefix<<"Backend for domain "<<p->qdomain<<" does not support transaction. Can't do Update packet."<<endl;
633 return RCode::NotImp;
634 }
635
636 // 3.2.1 and 3.2.2 - Prerequisite check
637 for(MOADNSParser::answers_t::const_iterator i=mdp.d_answers.begin(); i != mdp.d_answers.end(); ++i) {
638 const DNSRecord *rr = &i->first;
639 if (rr->d_place == DNSRecord::Answer) {
640 int res = checkUpdatePrerequisites(rr, &di);
641 if (res>0) {
642 L<<Logger::Error<<msgPrefix<<"Failed PreRequisites check, returning "<<res<<endl;
643 di.backend->abortTransaction();
644 return res;
645 }
646 }
647 }
648
649 // 3.2.3 - Prerequisite check - this is outside of updatePrequisitesCheck because we check an RRSet and not the RR.
650 typedef pair<string, QType> rrSetKey_t;
651 typedef vector<DNSResourceRecord> rrVector_t;
652 typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
653 RRsetMap_t preReqRRsets;
654 for(MOADNSParser::answers_t::const_iterator i=mdp.d_answers.begin(); i != mdp.d_answers.end(); ++i) {
655 const DNSRecord *rr = &i->first;
656 if (rr->d_place == DNSRecord::Answer) {
657 // Last line of 3.2.3
658 if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY)
659 return RCode::FormErr;
660
661 if (rr->d_class == QClass::IN) {
662 rrSetKey_t key = make_pair(stripDot(rr->d_label), rr->d_type);
663 rrVector_t *vec = &preReqRRsets[key];
664 vec->push_back(DNSResourceRecord(*rr));
665 }
666 }
667 }
668
669 if (preReqRRsets.size() > 0) {
670 RRsetMap_t zoneRRsets;
671 for (RRsetMap_t::iterator preRRSet = preReqRRsets.begin(); preRRSet != preReqRRsets.end(); ++preRRSet) {
672 rrSetKey_t rrSet=preRRSet->first;
673 rrVector_t *vec = &preRRSet->second;
674
675 DNSResourceRecord rec;
676 di.backend->lookup(QType(QType::ANY), rrSet.first);
677 uint16_t foundRR=0, matchRR=0;
678 while (di.backend->get(rec)) {
679 if (rec.qtype == rrSet.second) {
680 foundRR++;
681 for(rrVector_t::iterator rrItem=vec->begin(); rrItem != vec->end(); ++rrItem) {
682 rrItem->ttl = rec.ttl; // The compare one line below also compares TTL, so we make them equal because TTL is not user within prerequisite checks.
683 if (*rrItem == rec)
684 matchRR++;
685 }
686 }
687 }
688 if (matchRR != foundRR || foundRR != vec->size()) {
689 L<<Logger::Error<<msgPrefix<<"Failed PreRequisites check, returning NXRRSet"<<endl;
690 di.backend->abortTransaction();
691 return RCode::NXRRSet;
692 }
693 }
694 }
695
696
697
0bb68041 698 // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
f1b59a55 699 try {
0bb68041 700 uint16_t changedRecords = 0;
f1b59a55
RA
701 // 3.4.1 - Prescan section
702 for(MOADNSParser::answers_t::const_iterator i=mdp.d_answers.begin(); i != mdp.d_answers.end(); ++i) {
703 const DNSRecord *rr = &i->first;
704 if (rr->d_place == DNSRecord::Nameserver) {
705 int res = checkUpdatePrescan(rr);
706 if (res>0) {
707 L<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
708 di.backend->abortTransaction();
709 return res;
710 }
711 }
712 }
713
714 bool updatedSerial=false;
715 NSEC3PARAMRecordContent ns3pr;
dff32e09 716 bool narrow=false;
f1b59a55 717 bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
dff32e09 718 bool isPresigned = d_dk.isPresigned(di.zone);
f1b59a55 719
f1b59a55
RA
720 // 3.4.2 - Perform the updates.
721 // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
722 // This means we must do it outside the normal performUpdate() because that focusses only on a seperate RR.
723 vector<const DNSRecord *> nsRRtoDelete;
724 for(MOADNSParser::answers_t::const_iterator i=mdp.d_answers.begin(); i != mdp.d_answers.end(); ++i) {
725 const DNSRecord *rr = &i->first;
726 if (rr->d_place == DNSRecord::Nameserver) {
727 if (rr->d_class == QClass::NONE && rr->d_type == QType::NS && stripDot(rr->d_label) == di.zone)
728 nsRRtoDelete.push_back(rr);
729 else
dff32e09 730 changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
f1b59a55
RA
731 }
732 }
733 if (nsRRtoDelete.size()) {
734 vector<DNSResourceRecord> nsRRInZone;
735 DNSResourceRecord rec;
736 di.backend->lookup(QType(QType::NS), di.zone);
737 while (di.backend->get(rec)) {
738 nsRRInZone.push_back(rec);
739 }
740 if (nsRRInZone.size() > nsRRtoDelete.size()) { // only delete if the NS's we delete are less then what we have in the zone (3.4.2.4)
741 for (vector<DNSResourceRecord>::iterator inZone=nsRRInZone.begin(); inZone != nsRRInZone.end(); inZone++) {
742 for (vector<const DNSRecord *>::iterator rr=nsRRtoDelete.begin(); rr != nsRRtoDelete.end(); rr++) {
743 if (inZone->getZoneRepresentation() == (*rr)->d_content->getZoneRepresentation())
dff32e09 744 changedRecords += performUpdate(msgPrefix, *rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
f1b59a55
RA
745 }
746 }
747 }
748 }
749
f1b59a55 750 // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
890c7124 751 if (changedRecords > 0 && !updatedSerial) {
166ac305 752 increaseSerial(msgPrefix, &di, haveNSEC3, narrow, &ns3pr);
890c7124
RA
753 changedRecords++;
754 }
755
0bb68041
RA
756 if (!di.backend->commitTransaction()) {
757 L<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
758 return RCode::ServFail;
759 }
760
276a5ce7 761 S.deposit("rfc2136-changes", changedRecords);
7facf345 762
0bb68041
RA
763 // Purge the records!
764 string zone(di.zone);
765 zone.append("$");
766 PC.purge(zone);
767
768 L<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records commited."<<endl;
769 return RCode::NoError; //rfc 2136 3.4.2.5
770 }
771 catch (SSqlException &e) {
772 L<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
773 di.backend->abortTransaction();
774 return RCode::ServFail;
f1b59a55 775 }
ee9ef8f2
RA
776 catch (DBException &e) {
777 L<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
778 di.backend->abortTransaction();
779 return RCode::ServFail;
780 }
f1b59a55
RA
781 catch (AhuException &e) {
782 L<<Logger::Error<<msgPrefix<<"Caught AhuException: "<<e.reason<<"; Sending ServFail!"<<endl;
783 di.backend->abortTransaction();
784 return RCode::ServFail;
785 }
786 catch (...) {
787 L<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
788 di.backend->abortTransaction();
789 return RCode::ServFail;
790 }
f1b59a55
RA
791}
792
166ac305 793void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
f1b59a55 794 DNSResourceRecord rec, newRec;
166ac305 795 di->backend->lookup(QType(QType::SOA), di->zone);
f1b59a55 796 bool foundSOA=false;
166ac305 797 while (di->backend->get(rec)) {
f1b59a55
RA
798 newRec = rec;
799 foundSOA=true;
800 }
801 if (!foundSOA) {
802 throw AhuException("SOA-Serial update failed because there was no SOA. Wowie.");
803 }
804 SOAData soa2Update;
805 fillSOAData(rec.content, soa2Update);
890c7124 806 int oldSerial = soa2Update.serial;
f1b59a55
RA
807
808 vector<string> soaEdit2136Setting;
166ac305 809 B.getDomainMetadata(di->zone, "SOA-EDIT-2136", soaEdit2136Setting);
f1b59a55
RA
810 string soaEdit2136 = "DEFAULT";
811 string soaEdit;
812 if (!soaEdit2136Setting.empty()) {
813 soaEdit2136 = soaEdit2136Setting[0];
814 if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
815 vector<string> soaEditSetting;
166ac305 816 B.getDomainMetadata(di->zone, "SOA-EDIT", soaEditSetting);
f1b59a55
RA
817 if (soaEditSetting.empty()) {
818 L<<Logger::Error<<msgPrefix<<"Using "<<soaEdit2136<<" for SOA-EDIT-2136 increase on RFC2136, but SOA-EDIT is not set for domain. Using DEFAULT for SOA-EDIT-2136"<<endl;
819 soaEdit2136 = "DEFAULT";
820 } else
821 soaEdit = soaEditSetting[0];
822 }
823 }
824
825
826 if (pdns_iequals(soaEdit2136, "INCREASE"))
827 soa2Update.serial++;
828 else if (pdns_iequals(soaEdit2136, "SOA-EDIT-INCREASE")) {
829 uint32_t newSer = calculateEditSOA(soa2Update, soaEdit);
830 if (newSer <= soa2Update.serial)
831 soa2Update.serial++;
832 else
833 soa2Update.serial = newSer;
834 } else if (pdns_iequals(soaEdit2136, "SOA-EDIT"))
835 soa2Update.serial = calculateEditSOA(soa2Update, soaEdit);
836 else if (pdns_iequals(soaEdit2136, "EPOCH"))
837 soa2Update.serial = time(0);
838 else {
839 time_t now = time(0);
840 struct tm tm;
841 localtime_r(&now, &tm);
842 boost::format fmt("%04d%02d%02d%02d");
843 string newserdate=(fmt % (tm.tm_year+1900) % (tm.tm_mon +1 )% tm.tm_mday % 1).str();
844 uint32_t newser = atol(newserdate.c_str());
845 if (newser <= soa2Update.serial)
846 soa2Update.serial++;
847 else
848 soa2Update.serial = newser;
849 }
850
851
852 newRec.content = serializeSOAData(soa2Update);
3e0ab216
RA
853 vector<DNSResourceRecord> rrset;
854 rrset.push_back(newRec);
166ac305 855 di->backend->replaceRRSet(di->id, newRec.qname, newRec.qtype, rrset);
dff32e09 856 L<<Logger::Notice<<msgPrefix<<"Increasing SOA serial ("<<oldSerial<<" -> "<<soa2Update.serial<<")"<<endl;
166ac305
RA
857
858 //Correct ordername + auth flag
c1c3e5a4
RA
859 if (haveNSEC3 && narrow)
860 di->backend->nullifyDNSSECOrderNameAndUpdateAuth(di->id, newRec.qname, true);
861 else if (haveNSEC3) {
166ac305 862 string hashed;
c1c3e5a4
RA
863 if (!narrow)
864 hashed = toLower(toBase32Hex(hashQNameWithSalt(ns3pr->d_iterations, ns3pr->d_salt, newRec.qname)));
865
166ac305
RA
866 di->backend->updateDNSSECOrderAndAuthAbsolute(di->id, newRec.qname, hashed, true);
867 }
868 else // NSEC
869 di->backend->updateDNSSECOrderAndAuth(di->id, di->zone, newRec.qname, true);
166ac305 870}