• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 12452944705

22 Dec 2024 09:10AM UTC coverage: 64.791% (+0.2%) from 64.568%
12452944705

Pull #10692

github

web-flow
Merge 261b10c6f into d165e0b05
Pull Request #10692: auth: added self weighted lua function

37714 of 89004 branches covered (42.37%)

Branch coverage included in aggregate %.

0 of 46 new or added lines in 1 file covered. (0.0%)

11285 existing lines in 160 files now uncovered.

126084 of 163806 relevant lines covered (76.97%)

4314414.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.22
/pdns/rfc2136handler.cc
1
#include "dnswriter.hh"
2
#ifdef HAVE_CONFIG_H
3
#include "config.h"
4
#endif
5
#include "packethandler.hh"
6
#include "qtype.hh"
7
#include "dnspacket.hh"
8
#include "auth-caches.hh"
9
#include "statbag.hh"
10
#include "dnsseckeeper.hh"
11
#include "base64.hh"
12
#include "base32.hh"
13

14
#include "misc.hh"
15
#include "arguments.hh"
16
#include "resolver.hh"
17
#include "dns_random.hh"
18
#include "backends/gsql/ssql.hh"
19
#include "communicator.hh"
20
#include "query-local-address.hh"
21
#include "gss_context.hh"
22
#include "auth-main.hh"
23

24
extern StatBag S;
25
extern CommunicatorClass Communicator;
26

27
std::mutex PacketHandler::s_rfc2136lock;
28

29
// Implement section 3.2.1 and 3.2.2 of RFC2136
30
int PacketHandler::checkUpdatePrerequisites(const DNSRecord *rr, DomainInfo *di) {
228✔
31
  if (rr->d_ttl != 0)
228!
32
    return RCode::FormErr;
×
33

34
  // 3.2.1 and 3.2.2 check content length.
35
  if ( (rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_clen != 0)
228!
36
    return RCode::FormErr;
×
37

38
  bool foundRecord=false;
228✔
39
  DNSResourceRecord rec;
228✔
40
  di->backend->lookup(QType(QType::ANY), rr->d_name, di->id);
228✔
41
  while(di->backend->get(rec)) {
624✔
42
    if (!rec.qtype.getCode())
396✔
43
      continue;
12✔
44
    if ((rr->d_type != QType::ANY && rec.qtype == rr->d_type) || rr->d_type == QType::ANY)
384!
45
      foundRecord=true;
384✔
46
  }
384✔
47

48
  // Section 3.2.1
49
  if (rr->d_class == QClass::ANY && !foundRecord) {
228✔
50
    if (rr->d_type == QType::ANY)
36✔
51
      return RCode::NXDomain;
24✔
52
    if (rr->d_type != QType::ANY)
12!
53
      return RCode::NXRRSet;
12✔
54
  }
12✔
55

56
  // Section 3.2.2
57
  if (rr->d_class == QClass::NONE && foundRecord) {
192✔
58
    if (rr->d_type == QType::ANY)
24✔
59
      return RCode::YXDomain;
12✔
60
    if (rr->d_type != QType::ANY)
12!
61
      return RCode::YXRRSet;
12✔
62
  }
12✔
63

64
  return RCode::NoError;
168✔
65
}
192✔
66

67

68
// Method implements section 3.4.1 of RFC2136
69
int PacketHandler::checkUpdatePrescan(const DNSRecord *rr) {
2,732✔
70
  // The RFC stats that d_class != ZCLASS, but we only support the IN class.
71
  if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY) {
2,732!
72
    return RCode::FormErr;
×
73
  }
×
74

75
  QType qtype = QType(rr->d_type);
2,732✔
76

77
  if (!qtype.isSupportedType()) {
2,732!
78
    return RCode::FormErr;
×
79
  }
×
80

81
  if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_ttl != 0) {
2,732!
82
    return RCode::FormErr;
×
83
  }
×
84

85
  if (rr->d_class == QClass::ANY && rr->d_clen != 0) {
2,732!
86
    return RCode::FormErr;
×
87
  }
×
88

89
  if (qtype.isMetadataType()) {
2,732!
90
    return RCode::FormErr;
×
91
  }
×
92

93
  if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY) {
2,732✔
94
    return RCode::FormErr;
12✔
95
  }
12✔
96

97
  return RCode::NoError;
2,720✔
98
}
2,732✔
99

100

101
// Implements section 3.4.2 of RFC2136
102
uint PacketHandler::performUpdate(const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool* narrow, bool* haveNSEC3, NSEC3PARAMRecordContent *ns3pr, bool *updatedSerial) {
2,648✔
103

104
  QType rrType = QType(rr->d_type);
2,648✔
105

106
  if (rrType == QType::NSEC || rrType == QType::NSEC3) {
2,648!
107
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<". These are generated records, ignoring!"<<endl;
×
108
    return 0;
×
109
  }
×
110

111
  if (!isPresigned && rrType == QType::RRSIG) {
2,648!
112
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<" in non-presigned zone, ignoring!"<<endl;
×
113
    return 0;
×
114
  }
×
115

116
  if ((rrType == QType::NSEC3PARAM || rrType == QType::DNSKEY) && rr->d_name != di->zone) {
2,648!
117
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<", "<<rrType.toString()<<" must be at zone apex, ignoring!"<<endl;
×
118
    return 0;
×
119
  }
×
120

121

122
  uint changedRecords = 0;
2,648✔
123
  DNSResourceRecord rec;
2,648✔
124
  vector<DNSResourceRecord> rrset, recordsToDelete;
2,648✔
125
  set<DNSName> delnonterm, insnonterm; // used to (at the end) fix ENT records.
2,648✔
126

127

128
  if (rr->d_class == QClass::IN) { // 3.4.2.2 QClass::IN means insert or update
2,648✔
129
    DLOG(g_log<<msgPrefix<<"Add/Update record (QClass == IN) "<<rr->d_name<<"|"<<rrType.toString()<<endl);
1,988✔
130

131
    if (rrType == QType::NSEC3PARAM) {
1,988✔
132
      g_log<<Logger::Notice<<msgPrefix<<"Adding/updating NSEC3PARAM for zone, resetting ordernames."<<endl;
24✔
133

134
      *ns3pr = NSEC3PARAMRecordContent(rr->getContent()->getZoneRepresentation(), di->zone);
24✔
135
      *narrow = false; // adding a NSEC3 will cause narrow mode to be dropped, as you cannot specify that in a NSEC3PARAM record
24✔
136
      d_dk.setNSEC3PARAM(di->zone, *ns3pr, (*narrow));
24✔
137
      *haveNSEC3 = true;
24✔
138

139
      string error;
24✔
140
      string info;
24✔
141
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
24!
142
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
143
      }
×
144
      return 1;
24✔
145
    }
24✔
146

147

148

149
    bool foundRecord = false;
1,964✔
150
    di->backend->lookup(rrType, rr->d_name, di->id);
1,964✔
151
    while (di->backend->get(rec)) {
60,452✔
152
      rrset.push_back(rec);
58,488✔
153
      foundRecord = true;
58,488✔
154
    }
58,488✔
155

156
    if (foundRecord) {
1,964✔
157

158
      if (rrType == QType::SOA) { // SOA updates require the serial to be higher than the current
1,392✔
159
        SOAData sdOld, sdUpdate;
48✔
160
        DNSResourceRecord *oldRec = &rrset.front();
48✔
161
        fillSOAData(oldRec->content, sdOld);
48✔
162
        oldRec->setContent(rr->getContent()->getZoneRepresentation());
48✔
163
        fillSOAData(oldRec->content, sdUpdate);
48✔
164
        if (rfc1982LessThan(sdOld.serial, sdUpdate.serial)) {
48✔
165
          di->backend->replaceRRSet(di->id, oldRec->qname, oldRec->qtype, rrset);
24✔
166
          *updatedSerial = true;
24✔
167
          changedRecords++;
24✔
168
          g_log<<Logger::Notice<<msgPrefix<<"Replacing SOA record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
24✔
169
        } else {
24✔
170
          g_log<<Logger::Notice<<msgPrefix<<"Provided serial ("<<sdUpdate.serial<<") is older than the current serial ("<<sdOld.serial<<"), ignoring SOA update."<<endl;
24✔
171
        }
24✔
172

173
      // It's not possible to have multiple CNAME's with the same NAME. So we always update.
174
      } else if (rrType == QType::CNAME) {
1,344✔
175
        int changedCNames = 0;
24✔
176
        for (auto& i : rrset) {
24✔
177
          if (i.ttl != rr->d_ttl || i.content != rr->getContent()->getZoneRepresentation()) {
24!
178
            i.ttl = rr->d_ttl;
24✔
179
            i.setContent(rr->getContent()->getZoneRepresentation());
24✔
180
            changedCNames++;
24✔
181
          }
24✔
182
        }
24✔
183
        if (changedCNames > 0) {
24!
184
          di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
24✔
185
          g_log<<Logger::Notice<<msgPrefix<<"Replacing CNAME record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
24✔
186
          changedRecords += changedCNames;
24✔
187
        } else {
24✔
188
          g_log<<Logger::Notice<<msgPrefix<<"Replace for CNAME record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but no changes made."<<endl;
×
189
        }
×
190

191
      // In any other case, we must check if the TYPE and RDATA match to provide an update (which effectively means a update of TTL)
192
      } else {
1,320✔
193
        int updateTTL=0;
1,320✔
194
        foundRecord = false;
1,320✔
195
        bool lowerCase = false;
1,320✔
196
        if (rrType.getCode() == QType::PTR ||
1,320✔
197
            rrType.getCode() == QType::MX ||
1,320✔
198
            rrType.getCode() == QType::SRV) {
1,320✔
199
          lowerCase = true;
84✔
200
        }
84✔
201
        string content = rr->getContent()->getZoneRepresentation();
1,320✔
202
        if (lowerCase) content = toLower(content);
1,320✔
203
        for (auto& i : rrset) {
58,416✔
204
          string icontent = i.getZoneRepresentation();
58,416✔
205
          if (lowerCase) icontent = toLower(icontent);
58,416✔
206
          if (rrType == i.qtype.getCode()) {
58,416!
207
            if (icontent == content) {
58,416✔
208
              foundRecord=true;
72✔
209
            }
72✔
210
            if (i.ttl != rr->d_ttl)  {
58,416✔
211
              i.ttl = rr->d_ttl;
144✔
212
              updateTTL++;
144✔
213
            }
144✔
214
          }
58,416✔
215
        }
58,416✔
216
        if (updateTTL > 0) {
1,320✔
217
          di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
84✔
218
          g_log<<Logger::Notice<<msgPrefix<<"Updating TTLs for "<<rr->d_name<<"|"<<rrType.toString()<<endl;
84✔
219
          changedRecords += updateTTL;
84✔
220
        } else {
1,236✔
221
          g_log<<Logger::Notice<<msgPrefix<<"Replace for recordset "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but no changes made."<<endl;
1,236✔
222
        }
1,236✔
223
      }
1,320✔
224

225
      // ReplaceRRSet dumps our ordername and auth flag, so we need to correct it if we have changed records.
226
      // We can take the auth flag from the first RR in the set, as the name is different, so should the auth be.
227
      if (changedRecords > 0) {
1,392✔
228
        bool auth = rrset.front().auth;
132✔
229

230
        if(*haveNSEC3) {
132✔
231
          DNSName ordername;
66✔
232
          if(! *narrow)
66✔
233
            ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
44✔
234

235
          if (*narrow)
66✔
236
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth);
22✔
237
          else
44✔
238
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
44✔
239
          if(!auth || rrType == QType::DS) {
66!
240
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS);
×
241
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
242
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
243
          }
×
244

245
        } else { // NSEC
66✔
246
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, rr->d_name.makeRelative(di->zone), auth);
66✔
247
          if(!auth || rrType == QType::DS) {
66!
248
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
249
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
250
          }
×
251
        }
66✔
252
      }
132✔
253

254
    } // if (foundRecord)
1,392✔
255

256
    // If we haven't found a record that matches, we must add it.
257
    if (! foundRecord) {
1,964✔
258
      g_log<<Logger::Notice<<msgPrefix<<"Adding record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
1,820✔
259
      delnonterm.insert(rr->d_name); // always remove any ENT's in the place where we're going to add a record.
1,820✔
260
      auto newRec = DNSResourceRecord::fromWire(*rr);
1,820✔
261
      newRec.domain_id = di->id;
1,820✔
262
      newRec.auth = (rr->d_name == di->zone || rrType.getCode() != QType::NS);
1,820✔
263
      di->backend->feedRecord(newRec, DNSName());
1,820✔
264
      changedRecords++;
1,820✔
265

266

267
      // because we added a record, we need to fix DNSSEC data.
268
      DNSName shorter(rr->d_name);
1,820✔
269
      bool auth=newRec.auth;
1,820✔
270
      bool fixDS = (rrType == QType::DS);
1,820✔
271

272
      if (di->zone != shorter) { // Everything at APEX is auth=1 && no ENT's
1,820✔
273
        do {
3,640✔
274

275
          if (di->zone == shorter)
3,640✔
276
            break;
1,572✔
277

278
          bool foundShorter = false;
2,068✔
279
          di->backend->lookup(QType(QType::ANY), shorter, di->id);
2,068✔
280
          while (di->backend->get(rec)) {
62,336✔
281
            if (rec.qname == rr->d_name && rec.qtype == QType::DS)
60,268✔
282
              fixDS = true;
36✔
283
            if (shorter != rr->d_name)
60,268✔
284
              foundShorter = true;
200✔
285
            if (rec.qtype == QType::NS) // are we inserting below a delegate?
60,268✔
286
              auth=false;
300✔
287
          }
60,268✔
288

289
          if (!foundShorter && auth && shorter != rr->d_name) // haven't found any record at current level, insert ENT.
2,068✔
290
            insnonterm.insert(shorter);
120✔
291
          if (foundShorter)
2,068✔
292
            break; // if we find a shorter record, we can stop searching
152✔
293
        } while(shorter.chopOff());
2,068!
294
      }
1,724✔
295

296
      if(*haveNSEC3)
1,820✔
297
      {
914✔
298
        DNSName ordername;
914✔
299
        if(! *narrow)
914✔
300
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
612✔
301

302
        if (*narrow)
914✔
303
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth);
302✔
304
        else
612✔
305
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
612✔
306

307
        if (fixDS)
914✔
308
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS);
18✔
309

310
        if(!auth)
914✔
311
        {
114✔
312
          if (ns3pr->d_flags)
114✔
313
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS);
76✔
314
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
114✔
315
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
114✔
316
        }
114✔
317
      }
914✔
318
      else // NSEC
906✔
319
      {
906✔
320
        DNSName ordername=rr->d_name.makeRelative(di->zone);
906✔
321
        di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
906✔
322
        if (fixDS) {
906✔
323
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS);
18✔
324
        }
18✔
325
        if(!auth) {
906✔
326
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
114✔
327
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
114✔
328
        }
114✔
329
      }
906✔
330

331

332
      // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
333
      // Auth can only be false when the rr->d_name is not the zone
334
      if (auth == false && rrType == QType::NS) {
1,820✔
335
        DLOG(g_log<<msgPrefix<<"Going to fix auth flags below "<<rr->d_name<<endl);
132✔
336
        insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
132✔
337
        vector<DNSName> qnames;
132✔
338
        di->backend->listSubZone(rr->d_name, di->id);
132✔
339
        while(di->backend->get(rec)) {
396✔
340
          if (rec.qtype.getCode() && rec.qtype.getCode() != QType::DS && rr->d_name != rec.qname) // Skip ENT, DS and our already corrected record.
264✔
341
            qnames.push_back(rec.qname);
72✔
342
        }
264✔
343
        for(const auto & qname : qnames) {
132✔
344
          if(*haveNSEC3)  {
72✔
345
            DNSName ordername;
36✔
346
            if(! *narrow)
36✔
347
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, qname)));
24✔
348

349
            if (*narrow)
36✔
350
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth);
12✔
351
            else
24✔
352
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth);
24✔
353

354
            if (ns3pr->d_flags)
36✔
355
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::NS);
24✔
356
          }
36✔
357
          else { // NSEC
36✔
358
            DNSName ordername=DNSName(qname).makeRelative(di->zone);
36✔
359
            di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, false, QType::NS);
36✔
360
          }
36✔
361

362
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A);
72✔
363
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA);
72✔
364
        }
72✔
365
      }
132✔
366
    }
1,820✔
367
  } // rr->d_class == QClass::IN
1,964✔
368

369

370
  // 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
371
  // the code that calls this performUpdate().
372
  if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
2,624✔
373
    DLOG(g_log<<msgPrefix<<"Deleting records: "<<rr->d_name<<"; QClass:"<<rr->d_class<<"; rrType: "<<rrType.toString()<<endl);
648✔
374

375
    if (rrType == QType::NSEC3PARAM) {
648✔
376
      g_log<<Logger::Notice<<msgPrefix<<"Deleting NSEC3PARAM from zone, resetting ordernames."<<endl;
16✔
377
      if (rr->d_class == QClass::ANY)
16!
378
        d_dk.unsetNSEC3PARAM(rr->d_name);
16✔
379
      else if (rr->d_class == QClass::NONE) {
×
380
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), di->zone);
×
381
        if (*haveNSEC3 && ns3pr->getZoneRepresentation() == nsec3rr.getZoneRepresentation())
×
382
          d_dk.unsetNSEC3PARAM(rr->d_name);
×
383
        else
×
384
          return 0;
×
385
      } else
×
386
        return 0;
×
387

388
      // Update NSEC3 variables, other RR's in this update package might need them as well.
389
      *haveNSEC3 = false;
16✔
390
      *narrow = false;
16✔
391

392
      string error;
16✔
393
      string info;
16✔
394
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
16!
395
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
396
      }
×
397
      return 1;
16✔
398
    } // end of NSEC3PARAM delete block
16✔
399

400

401
    di->backend->lookup(rrType, rr->d_name, di->id);
632✔
402
    while(di->backend->get(rec)) {
2,584✔
403
      if (rr->d_class == QClass::ANY) { // 3.4.2.3
1,952✔
404
        if (rec.qname == di->zone && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) // Never delete all SOA and NS's
1,632!
405
          rrset.push_back(rec);
24✔
406
        else
1,608✔
407
          recordsToDelete.push_back(rec);
1,608✔
408
      }
1,632✔
409
      if (rr->d_class == QClass::NONE) { // 3.4.2.4
1,952✔
410
        auto repr = rec.getZoneRepresentation();
320✔
411
        if (rec.qtype == QType::TXT) {
320✔
412
          DLOG(g_log<<msgPrefix<<"Adjusting TXT content from ["<<repr<<"]"<<endl);
36✔
413
          auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
36✔
414
          auto ser = drc->serialize(rec.qname, true, true);
36✔
415
          auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser);
36✔
416
          repr = rc->getZoneRepresentation(true);
36✔
417
          DLOG(g_log<<msgPrefix<<"Adjusted TXT content to ["<<repr<<"]"<<endl);
36✔
418
        }
36✔
419
        DLOG(g_log<<msgPrefix<<"Matching RR in RRset - (adjusted) representation from request=["<<repr<<"], rr->getContent()->getZoneRepresentation()=["<<rr->getContent()->getZoneRepresentation()<<"]"<<endl);
320✔
420
        if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation())
320!
421
          recordsToDelete.push_back(rec);
224✔
422
        else
96✔
423
          rrset.push_back(rec);
96✔
424
      }
320✔
425
    }
1,952✔
426
  
427
    if (recordsToDelete.size()) {
632✔
428
      di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
608✔
429
      g_log<<Logger::Notice<<msgPrefix<<"Deleting record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
608✔
430
      changedRecords += recordsToDelete.size();
608✔
431

432

433
      // If we've removed a delegate, we need to reset ordername/auth for some records.
434
      if (rrType == QType::NS && rr->d_name != di->zone) { 
608✔
435
        vector<DNSName> belowOldDelegate, nsRecs, updateAuthFlag;
84✔
436
        di->backend->listSubZone(rr->d_name, di->id);
84✔
437
        while (di->backend->get(rec)) {
216✔
438
          if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
132!
439
            belowOldDelegate.push_back(rec.qname);
132✔
440
          if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name)
132!
441
            nsRecs.push_back(rec.qname);
12✔
442
        }
132✔
443

444
        for(auto &belowOldDel: belowOldDelegate)
84✔
445
        {
132✔
446
          bool isBelowDelegate = false;
132✔
447
          for(const auto & ns: nsRecs) {
132✔
448
            if (ns.isPartOf(belowOldDel)) {
36✔
449
              isBelowDelegate=true;
12✔
450
              break;
12✔
451
            }
12✔
452
          }
36✔
453
          if (!isBelowDelegate)
132✔
454
            updateAuthFlag.push_back(belowOldDel);
120✔
455
        }
132✔
456

457
        for (const auto &changeRec:updateAuthFlag) {
120✔
458
          if(*haveNSEC3)  {
120✔
459
            DNSName ordername;
60✔
460
            if(! *narrow)
60✔
461
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, changeRec)));
40✔
462

463
            di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true);
60✔
464
          }
60✔
465
          else { // NSEC
60✔
466
            DNSName ordername=changeRec.makeRelative(di->zone);
60✔
467
            di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true);
60✔
468
          }
60✔
469
        }
120✔
470
      }
84✔
471

472
      // Fix ENT records.
473
      // We must check if we have a record below the current level and if we removed the 'last' record
474
      // on that level. If so, we must insert an ENT record.
475
      // 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.
476
      bool foundDeeper = false, foundOtherWithSameName = false;
608✔
477
      di->backend->listSubZone(rr->d_name, di->id);
608✔
478
      while (di->backend->get(rec)) {
3,452✔
479
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
2,844!
480
          foundOtherWithSameName = true;
516✔
481
        if (rec.qname != rr->d_name && 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
2,844✔
482
          foundDeeper = true;
2,112✔
483
      }
2,844✔
484

485
      if (foundDeeper && !foundOtherWithSameName) {
608✔
486
        insnonterm.insert(rr->d_name);
72✔
487
      } else if (!foundOtherWithSameName) {
536✔
488
        // If we didn't have to insert an ENT, we might have deleted a record at very deep level
489
        // and we must then clean up the ENT's above the deleted record.
490
        DNSName shorter(rr->d_name);
392✔
491
        while (shorter != di->zone) {
608!
492
          shorter.chopOff();
608✔
493
          bool foundRealRR = false;
608✔
494
          bool foundEnt = false;
608✔
495

496
          // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
497
          // consider these non ENT-records:
498
          // b.c.d.e.test.com
499
          // b.d.e.test.com
500
          // 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.
501
          // At that point we can stop deleting ENT's because the tree is in tact again.
502
          di->backend->listSubZone(shorter, di->id);
608✔
503

504
          while (di->backend->get(rec)) {
8,276✔
505
            if (rec.qtype.getCode())
7,668✔
506
              foundRealRR = true;
6,628✔
507
            else
1,040✔
508
              foundEnt = true;
1,040✔
509
          }
7,668✔
510
          if (!foundRealRR) {
608✔
511
            if (foundEnt) // only delete the ENT if we actually found one.
216✔
512
              delnonterm.insert(shorter);
180✔
513
          } else
216✔
514
            break;
392✔
515
        }
608✔
516
      }
392✔
517
    } else { // if (recordsToDelete.size())
608✔
518
      g_log<<Logger::Notice<<msgPrefix<<"Deletion for record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but not found."<<endl;
24✔
519
    }
24✔
520
  } // (End of delete block d_class == ANY || d_class == NONE
632✔
521
  
522

523

524
  //Insert and delete ENT's
525
  if (insnonterm.size() > 0 || delnonterm.size() > 0) {
2,608✔
526
    DLOG(g_log<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
1,988✔
527
    di->backend->updateEmptyNonTerminals(di->id, insnonterm, delnonterm, false);
1,988✔
528
    for (const auto &i: insnonterm) {
1,988✔
529
      string hashed;
192✔
530
      if(*haveNSEC3)
192✔
531
      {
96✔
532
        DNSName ordername;
96✔
533
        if(! *narrow)
96✔
534
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, i)));
64✔
535
        di->backend->updateDNSSECOrderNameAndAuth(di->id, i, ordername, true);
96✔
536
      }
96✔
537
    }
192✔
538
  }
1,988✔
539

540
  return changedRecords;
2,608✔
541
}
2,624✔
542

543
int PacketHandler::forwardPacket(const string &msgPrefix, const DNSPacket& p, const DomainInfo& di) {
×
544
  vector<string> forward;
×
545
  B.getDomainMetadata(p.qdomain, "FORWARD-DNSUPDATE", forward);
×
546

547
  if (forward.size() == 0 && ! ::arg().mustDo("forward-dnsupdate")) {
×
548
    g_log << Logger::Notice << msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
549
    return RCode::Refused;
×
550
  }
×
551

552
  for (const auto& remote : di.primaries) {
×
553
    g_log << Logger::Notice << msgPrefix << "Forwarding packet to primary " << remote << endl;
×
554

555
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
556
      continue;
×
557
    }
×
558
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
559
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
560
    if(sock < 0) {
×
561
      g_log<<Logger::Error<<msgPrefix<<"Error creating socket: "<<stringerror()<<endl;
×
562
      continue;
×
563
    }
×
564

565
    if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
×
566
      g_log<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
×
567
      try {
×
568
        closesocket(sock);
×
569
      }
×
570
      catch(const PDNSException& e) {
×
571
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
×
572
      }
×
573
      continue;
×
574
    }
×
575

576
    DNSPacket l_forwardPacket(p);
×
577
    l_forwardPacket.setID(dns_random_uint16());
×
578
    l_forwardPacket.setRemote(&remote);
×
579
    uint16_t len=htons(l_forwardPacket.getString().length());
×
580
    string buffer((const char*)&len, 2);
×
581
    buffer.append(l_forwardPacket.getString());
×
582
    if(write(sock, buffer.c_str(), buffer.length()) < 0) {
×
583
      g_log<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
×
584
      try {
×
585
        closesocket(sock);
×
586
      }
×
587
      catch(const PDNSException& e) {
×
588
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
589
      }
×
590
      continue;
×
591
    }
×
592

593
    int res = waitForData(sock, 10, 0);
×
594
    if (!res) {
×
595
      g_log << Logger::Error << msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
×
596
      try {
×
597
        closesocket(sock);
×
598
      }
×
599
      catch(const PDNSException& e) {
×
600
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
601
      }
×
602
      continue;
×
603
    }
×
604
    if (res < 0) {
×
605
      g_log << Logger::Error << msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
606
      try {
×
607
        closesocket(sock);
×
608
      }
×
609
      catch(const PDNSException& e) {
×
610
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
611
      }
×
612
      continue;
×
613
    }
×
614

615
    unsigned char lenBuf[2];
×
616
    ssize_t recvRes;
×
617
    recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
×
618
    if (recvRes < 0 || static_cast<size_t>(recvRes) < sizeof(lenBuf)) {
×
619
      g_log << Logger::Error << msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
620
      try {
×
621
        closesocket(sock);
×
622
      }
×
623
      catch(const PDNSException& e) {
×
624
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
625
      }
×
626
      continue;
×
627
    }
×
628
    size_t packetLen = lenBuf[0]*256+lenBuf[1];
×
629

630
    buffer.resize(packetLen);
×
631
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
632
    if (recvRes < 0) {
×
633
      g_log << Logger::Error << msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
634
      try {
×
635
        closesocket(sock);
×
636
      }
×
637
      catch(const PDNSException& e) {
×
638
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
639
      }
×
640
      continue;
×
641
    }
×
642
    try {
×
643
      closesocket(sock);
×
644
    }
×
645
    catch(const PDNSException& e) {
×
646
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
647
    }
×
648

649
    try {
×
650
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
651
      g_log<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
×
652
      return mdp.d_header.rcode;
×
653
    }
×
654
    catch (...) {
×
655
      g_log << Logger::Error << msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
656
      continue;
×
657
    }
×
658
  }
×
659
  g_log << Logger::Error << msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
×
660
  return RCode::ServFail;
×
661

662
}
×
663

664
int PacketHandler::processUpdate(DNSPacket& packet) { // NOLINT(readability-function-cognitive-complexity)
1,252✔
665
  if (! ::arg().mustDo("dnsupdate"))
1,252!
666
    return RCode::Refused;
×
667

668
  string msgPrefix="UPDATE (" + std::to_string(packet.d.id) + ") from " + packet.getRemoteString() + " for " + packet.qdomain.toLogString() + ": ";
1,252✔
669
  g_log<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
1,252✔
670

671
  // if there is policy, we delegate all checks to it
672
  if (this->d_update_policy_lua == nullptr) {
1,252!
673

674
    // Check permissions - IP based
675
    vector<string> allowedRanges;
1,252✔
676
    B.getDomainMetadata(packet.qdomain, "ALLOW-DNSUPDATE-FROM", allowedRanges);
1,252✔
677
    if (! ::arg()["allow-dnsupdate-from"].empty())
1,252!
678
      stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t" );
1,252✔
679

680
    NetmaskGroup ng;
1,252✔
681
    for(const auto& i: allowedRanges) {
2,504✔
682
      ng.addMask(i);
2,504✔
683
    }
2,504✔
684

685
    if ( ! ng.match(packet.getInnerRemote())) {
1,252!
686
      g_log<<Logger::Error<<msgPrefix<<"Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED"<<endl;
×
687
      return RCode::Refused;
×
688
    }
×
689

690

691
    // Check permissions - TSIG based.
692
    vector<string> tsigKeys;
1,252✔
693
    B.getDomainMetadata(packet.qdomain, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
1,252✔
694
    if (tsigKeys.size() > 0) {
1,252!
695
      bool validKey = false;
×
696

697
      TSIGRecordContent trc;
×
698
      DNSName inputkey;
×
699
      string message;
×
700
      if (! packet.getTSIGDetails(&trc,  &inputkey)) {
×
701
        g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
×
702
        return RCode::Refused;
×
703
      }
×
704
#ifdef ENABLE_GSS_TSIG
×
705
      if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
706
        GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
707
        for(const auto& key: tsigKeys) {
×
708
          if (inputname.match(key)) {
×
709
            validKey = true;
×
710
            break;
×
711
          }
×
712
        }
×
713
      }
×
714
      else
×
715
#endif
×
716
        {
×
717
        for(const auto& key: tsigKeys) {
×
718
          if (inputkey == DNSName(key)) { // because checkForCorrectTSIG has already been performed earlier on, if the name of the key matches with the domain given it is valid.
×
719
            validKey=true;
×
720
            break;
×
721
          }
×
722
        }
×
723
      }
×
724

725
      if (!validKey) {
×
726
        g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
727
        return RCode::Refused;
×
728
      }
×
729
    } else if(::arg().mustDo("dnsupdate-require-tsig")) {
1,252!
730
      g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but domain is not secured with TSIG. Sending REFUSED"<<endl;
×
731
      return RCode::Refused;
×
732
    }
×
733

734
    if (tsigKeys.empty() && packet.d_havetsig) {
1,252!
735
      g_log<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
×
736
    }
×
737

738
  }
1,252✔
739

740
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
741
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
742
  // variable names during the use of our MOADNSParser.
743
  MOADNSParser mdp(false, packet.getString());
1,252✔
744
  if (mdp.d_header.qdcount != 1) {
1,252!
745
    g_log<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
×
746
    return RCode::FormErr;
×
747
  }
×
748

749
  if (packet.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
1,252!
750
    g_log<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
×
751
    return RCode::FormErr;
×
752
  }
×
753

754
  if (packet.qclass != QClass::IN) {
1,252!
755
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
756
    return RCode::NotAuth;
×
757
  }
×
758

759
  DomainInfo di;
1,252✔
760
  di.backend=nullptr;
1,252✔
761
  if(!B.getDomainInfo(packet.qdomain, di) || (di.backend == nullptr)) {
1,252!
762
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<packet.qdomain<<"' (or backend does not support DNS update operation)"<<endl;
12✔
763
    return RCode::NotAuth;
12✔
764
  }
12✔
765

766
  if (di.kind == DomainInfo::Secondary)
1,240!
767
    return forwardPacket(msgPrefix, packet, di);
×
768

769
  // Check if all the records provided are within the zone
770
  for(const auto & answer : mdp.d_answers) {
3,032✔
771
    const DNSRecord *dnsRecord = &answer;
3,032✔
772
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
773
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
774
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
3,032!
775
      continue;
×
UNCOV
776
    }
×
777

778
    if (!dnsRecord->d_name.isPartOf(di.zone)) {
3,032✔
779
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
24✔
780
      return RCode::NotZone;
24✔
781
    }
24✔
782
  }
3,032✔
783

784

785
  std::lock_guard<std::mutex> l(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
1,216✔
786
  g_log<<Logger::Info<<msgPrefix<<"starting transaction."<<endl;
1,216✔
787
  if (!di.backend->startTransaction(packet.qdomain, -1)) { // Not giving the domain_id means that we do not delete the existing records.
1,216!
788
    g_log<<Logger::Error<<msgPrefix<<"Backend for domain "<<packet.qdomain<<" does not support transaction. Can't do Update packet."<<endl;
×
789
    return RCode::NotImp;
×
UNCOV
790
  }
×
791

792
  // 3.2.1 and 3.2.2 - Prerequisite check
793
  for(const auto & answer : mdp.d_answers) {
2,960✔
794
    const DNSRecord *dnsRecord = &answer;
2,960✔
795
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
2,960✔
796
      int res = checkUpdatePrerequisites(dnsRecord, &di);
228✔
797
      if (res>0) {
228✔
798
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<dnsRecord->d_name<<", returning "<<RCode::to_s(res)<<endl;
60✔
799
        di.backend->abortTransaction();
60✔
800
        return res;
60✔
801
      }
60✔
802
    }
228✔
803
  }
2,960✔
804

805
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
806
  typedef pair<DNSName, QType> rrSetKey_t;
1,156✔
807
  typedef vector<DNSResourceRecord> rrVector_t;
1,156✔
808
  typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
1,156✔
809
  RRsetMap_t preReqRRsets;
1,156✔
810
  for(const auto& i: mdp.d_answers) {
2,900✔
811
    const DNSRecord* dnsRecord = &i;
2,900✔
812
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
2,900✔
813
      // Last line of 3.2.3
814
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
168!
UNCOV
815
        return RCode::FormErr;
×
UNCOV
816
      }
×
817

818
      if (dnsRecord->d_class == QClass::IN) {
168✔
819
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
108✔
820
        rrVector_t *vec = &preReqRRsets[key];
108✔
821
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
108✔
822
      }
108✔
823
    }
168✔
824
  }
2,900✔
825

826
  if (preReqRRsets.size() > 0) {
1,156✔
827
    RRsetMap_t zoneRRsets;
36✔
828
    for (auto & preReqRRset : preReqRRsets) {
36✔
829
      rrSetKey_t rrSet=preReqRRset.first;
36✔
830
      rrVector_t *vec = &preReqRRset.second;
36✔
831

832
      DNSResourceRecord rec;
36✔
833
      di.backend->lookup(QType(QType::ANY), rrSet.first, di.id);
36✔
834
      uint16_t foundRR=0, matchRR=0;
36✔
835
      while (di.backend->get(rec)) {
144✔
836
        if (rec.qtype == rrSet.second) {
108!
837
          foundRR++;
108✔
838
          for(auto & rrItem : *vec) {
324✔
839
            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.
324✔
840
            if (rrItem == rec)
324✔
841
              matchRR++;
108✔
842
          }
324✔
843
        }
108✔
844
      }
108✔
845
      if (matchRR != foundRR || foundRR != vec->size()) {
36!
846
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
24✔
847
        di.backend->abortTransaction();
24✔
848
        return RCode::NXRRSet;
24✔
849
      }
24✔
850
    }
36✔
851
  }
36✔
852

853

854

855
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
856
  try {
1,132✔
857
    uint changedRecords = 0;
1,132✔
858
    // 3.4.1 - Prescan section
859
    for(const auto & answer : mdp.d_answers) {
2,828✔
860
      const DNSRecord *dnsRecord = &answer;
2,828✔
861
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
2,828✔
862
        int res = checkUpdatePrescan(dnsRecord);
2,732✔
863
        if (res>0) {
2,732✔
864
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
12✔
865
          di.backend->abortTransaction();
12✔
866
          return res;
12✔
867
        }
12✔
868
      }
2,732✔
869
    }
2,828✔
870

871
    bool updatedSerial=false;
1,120✔
872
    NSEC3PARAMRecordContent ns3pr;
1,120✔
873
    bool narrow=false;
1,120✔
874
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
1,120✔
875
    bool isPresigned = d_dk.isPresigned(di.zone);
1,120✔
876
    string soaEditSetting;
1,120✔
877
    d_dk.getSoaEdit(di.zone, soaEditSetting);
1,120✔
878

879
    // 3.4.2 - Perform the updates.
880
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
881
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
882
    vector<const DNSRecord *> nsRRtoDelete;
1,120✔
883

884
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
885
    set<DNSName> cn, nocn;
1,120✔
886
    for (const auto &rr : mdp.d_answers) {
2,816✔
887
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
2,816!
888
        // Addition
889
        if (rr.d_type == QType::CNAME) {
2,036✔
890
          cn.insert(rr.d_name);
96✔
891
        } else if (rr.d_type != QType::RRSIG) {
1,940!
892
          nocn.insert(rr.d_name);
1,940✔
893
        }
1,940✔
894
      }
2,036✔
895
    }
2,816✔
896
    for (auto const &n : cn) {
1,120✔
897
      if (nocn.count(n) > 0) {
96✔
898
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
12✔
899
        di.backend->abortTransaction();
12✔
900
        return RCode::FormErr;
12✔
901
      }
12✔
902
    }
96✔
903

904
    vector<const DNSRecord *> cnamesToAdd, nonCnamesToAdd;
1,108✔
905
    for(const auto & answer : mdp.d_answers) {
2,792✔
906
      const DNSRecord *dnsRecord = &answer;
2,792✔
907
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
2,792✔
908
        /* see if it's permitted by policy */
909
        if (this->d_update_policy_lua != nullptr) {
2,696!
910
          if (!this->d_update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), di.zone, packet)) {
×
911
            g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy"<<endl;
×
912
            continue;
×
913
          } else {
×
914
            g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy"<<endl;
×
UNCOV
915
          }
×
UNCOV
916
        }
×
917

918
        if (dnsRecord->d_class == QClass::NONE  && dnsRecord->d_type == QType::NS && dnsRecord->d_name == di.zone) {
2,696!
919
          nsRRtoDelete.push_back(dnsRecord);
36✔
920
        }
36✔
921
        else if (dnsRecord->d_class == QClass::IN &&  dnsRecord->d_ttl > 0) {
2,660!
922
          if (dnsRecord->d_type == QType::CNAME) {
2,012✔
923
            cnamesToAdd.push_back(dnsRecord);
84✔
924
          } else {
1,928✔
925
            nonCnamesToAdd.push_back(dnsRecord);
1,928✔
926
          }
1,928✔
927
        }
2,012✔
928
        else
648✔
929
          changedRecords += performUpdate(msgPrefix, dnsRecord, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
648✔
930
      }
2,696✔
931
    }
2,792✔
932
    for (const auto &rr : cnamesToAdd) {
1,108✔
933
      DNSResourceRecord rec;
84✔
934
      di.backend->lookup(QType(QType::ANY), rr->d_name, di.id);
84✔
935
      while (di.backend->get(rec)) {
120✔
936
        if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
48!
937
          // leave database handle in a consistent state
938
          while (di.backend->get(rec))
12!
UNCOV
939
            ;
×
940
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": Data other than CNAME exists for the same name"<<endl;
12✔
941
          di.backend->abortTransaction();
12✔
942
          return RCode::Refused;
12✔
943
        }
12✔
944
      }
48✔
945
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
72✔
946
    }
72✔
947
    for (const auto &rr : nonCnamesToAdd) {
1,928✔
948
      DNSResourceRecord rec;
1,928✔
949
      di.backend->lookup(QType(QType::CNAME), rr->d_name, di.id);
1,928✔
950
      while (di.backend->get(rec)) {
1,928✔
951
        if (rec.qtype == QType::CNAME && rr->d_type != QType::RRSIG) {
12!
952
          // leave database handle in a consistent state
953
          while (di.backend->get(rec))
12!
UNCOV
954
            ;
×
955
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": CNAME exists for the same name"<<endl;
12✔
956
          di.backend->abortTransaction();
12✔
957
          return RCode::Refused;
12✔
958
        }
12✔
959
      }
12✔
960
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
1,916✔
961
    }
1,916✔
962
    if (nsRRtoDelete.size()) {
1,084✔
963
      vector<DNSResourceRecord> nsRRInZone;
24✔
964
      DNSResourceRecord rec;
24✔
965
      di.backend->lookup(QType(QType::NS), di.zone, di.id);
24✔
966
      while (di.backend->get(rec)) {
72✔
967
        nsRRInZone.push_back(rec);
48✔
968
      }
48✔
969
      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)
24✔
970
        for (auto& inZone: nsRRInZone) {
24✔
971
          for (auto& rr: nsRRtoDelete) {
24✔
972
            if (inZone.getZoneRepresentation() == (rr)->getContent()->getZoneRepresentation())
24✔
973
              changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
12✔
974
          }
24✔
975
        }
24✔
976
      }
12✔
977
    }
24✔
978

979
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
980
    if (changedRecords > 0 && !updatedSerial) {
1,084✔
981
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
964✔
982
      changedRecords++;
964✔
983
    }
964✔
984

985
    if (changedRecords > 0) {
1,084✔
986
      if (!di.backend->commitTransaction()) {
988!
UNCOV
987
       g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
UNCOV
988
        return RCode::ServFail;
×
UNCOV
989
      }
×
990

991
      S.deposit("dnsupdate-changes", changedRecords);
988✔
992

993
      d_dk.clearMetaCache(di.zone);
988✔
994
      // Purge the records!
995
      string zone(di.zone.toString());
988✔
996
      zone.append("$");
988✔
997
      purgeAuthCaches(zone);
988✔
998

999
      // Notify secondaries
1000
      if (di.kind == DomainInfo::Primary) {
988!
1001
        vector<string> notify;
988✔
1002
        B.getDomainMetadata(packet.qdomain, "NOTIFY-DNSUPDATE", notify);
988✔
1003
        if (!notify.empty() && notify.front() == "1") {
988!
UNCOV
1004
          Communicator.notifyDomain(di.zone, &B);
×
UNCOV
1005
        }
×
1006
      }
988✔
1007

1008
      g_log<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records committed."<<endl;
988✔
1009
    } else {
988✔
1010
      //No change, no commit, we perform abort() because some backends might like this more.
1011
      g_log<<Logger::Info<<msgPrefix<<"Update completed, 0 changes, rolling back."<<endl;
96✔
1012
      di.backend->abortTransaction();
96✔
1013
    }
96✔
1014
    return RCode::NoError; //rfc 2136 3.4.2.5
1,084✔
1015
  }
1,084✔
1016
  catch (SSqlException &e) {
1,132✔
1017
    g_log<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
×
UNCOV
1018
    di.backend->abortTransaction();
×
1019
    return RCode::ServFail;
×
1020
  }
×
1021
  catch (DBException &e) {
1,132✔
1022
    g_log<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
UNCOV
1023
    di.backend->abortTransaction();
×
1024
    return RCode::ServFail;
×
1025
  }
×
1026
  catch (PDNSException &e) {
1,132✔
1027
    g_log<<Logger::Error<<msgPrefix<<"Caught PDNSException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
UNCOV
1028
    di.backend->abortTransaction();
×
1029
    return RCode::ServFail;
×
1030
  }
×
1031
  catch(std::exception &e) {
1,132✔
1032
    g_log<<Logger::Error<<msgPrefix<<"Caught std:exception: "<<e.what()<<"; Sending ServFail!"<<endl;
×
UNCOV
1033
    di.backend->abortTransaction();
×
1034
    return RCode::ServFail;
×
1035
  }
×
1036
  catch (...) {
1,132✔
1037
    g_log<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
×
UNCOV
1038
    di.backend->abortTransaction();
×
UNCOV
1039
    return RCode::ServFail;
×
UNCOV
1040
  }
×
1041
}
1,132✔
1042

1043
void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, const string& soaEditSetting,  bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
964✔
1044
  SOAData sd;
964✔
1045
  if (!di->backend->getSOA(di->zone, sd)) {
964!
UNCOV
1046
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
×
UNCOV
1047
  }
×
1048

1049
  uint32_t oldSerial = sd.serial;
964✔
1050

1051
  vector<string> soaEdit2136Setting;
964✔
1052
  B.getDomainMetadata(di->zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
964✔
1053
  string soaEdit2136 = "DEFAULT";
964✔
1054
  string soaEdit;
964✔
1055
  if (!soaEdit2136Setting.empty()) {
964!
1056
    soaEdit2136 = soaEdit2136Setting[0];
×
1057
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
×
1058
      if (soaEditSetting.empty()) {
×
1059
        g_log<<Logger::Error<<msgPrefix<<"Using "<<soaEdit2136<<" for SOA-EDIT-DNSUPDATE increase on DNS update, but SOA-EDIT is not set for domain \""<< di->zone <<"\". Using DEFAULT for SOA-EDIT-DNSUPDATE"<<endl;
×
1060
        soaEdit2136 = "DEFAULT";
×
1061
      } else
×
UNCOV
1062
        soaEdit = soaEditSetting;
×
UNCOV
1063
    }
×
UNCOV
1064
  }
×
1065

1066
  DNSResourceRecord rr;
964✔
1067
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
964!
1068
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
964✔
1069
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
964✔
1070

1071
    //Correct ordername + auth flag
1072
    if (haveNSEC3) {
964✔
1073
      DNSName ordername;
486✔
1074
      if (!narrow)
486✔
1075
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
332✔
1076

1077
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
486✔
1078
    } else { // NSEC
486✔
1079
      DNSName ordername = rr.qname.makeRelative(di->zone);
478✔
1080
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
478✔
1081
    }
478✔
1082
  }
964✔
1083
}
964✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc