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

PowerDNS / pdns / 16673722362

01 Aug 2025 11:19AM UTC coverage: 65.826% (+12.0%) from 53.823%
16673722362

Pull #15955

github

web-flow
Merge 245ce2bbf into 631f2ad0f
Pull Request #15955: rec: test rpzPrimary instead of rpzMaster

42043 of 92440 branches covered (45.48%)

Branch coverage included in aggregate %.

127950 of 165806 relevant lines covered (77.17%)

6122257.21 hits per line

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

72.71
/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) {
418✔
31
  if (rr->d_ttl != 0)
418!
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)
418!
36
    return RCode::FormErr;
×
37

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

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

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

64
  return RCode::NoError;
308✔
65
}
352✔
66

67

68
// Method implements section 3.4.1 of RFC2136
69
int PacketHandler::checkUpdatePrescan(const DNSRecord *rr) {
5,006✔
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) {
5,006!
72
    return RCode::FormErr;
×
73
  }
×
74

75
  QType qtype = QType(rr->d_type);
5,006✔
76

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

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

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

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

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

97
  return RCode::NoError;
4,984✔
98
}
5,006✔
99

100

101
// Implements section 3.4.2 of RFC2136
102
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
103
uint PacketHandler::performUpdate(const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool* narrow, bool* haveNSEC3, NSEC3PARAMRecordContent *ns3pr, bool *updatedSerial) {
4,852✔
104

105
  QType rrType = QType(rr->d_type);
4,852✔
106

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

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

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

122

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

128

129
  if (rr->d_class == QClass::IN) { // 3.4.2.2 QClass::IN means insert or update
4,852✔
130
    DLOG(g_log<<msgPrefix<<"Add/Update record (QClass == IN) "<<rr->d_name<<"|"<<rrType.toString()<<endl);
3,644✔
131

132
    if (rrType == QType::NSEC3PARAM) {
3,644✔
133
      g_log<<Logger::Notice<<msgPrefix<<"Adding/updating NSEC3PARAM for zone, resetting ordernames."<<endl;
44✔
134

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

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

148

149

150
    bool foundRecord = false;
3,600✔
151
    di->backend->lookup(rrType, rr->d_name, di->id);
3,600✔
152
    while (di->backend->get(rec)) {
110,828✔
153
      rrset.push_back(rec);
107,228✔
154
      foundRecord = true;
107,228✔
155
    }
107,228✔
156

157
    if (foundRecord) {
3,600✔
158

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

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

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

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

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

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

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

257
    } // if (foundRecord)
2,552✔
258

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

269

270
      // because we added a record, we need to fix DNSSEC data.
271
      DNSName shorter(rr->d_name);
3,336✔
272
      bool auth=newRec.auth;
3,336✔
273
      bool fixDS = (rrType == QType::DS);
3,336✔
274

275
      if (di->zone.operator const DNSName&() != shorter) { // Everything at APEX is auth=1 && no ENT's
3,336✔
276
        do {
6,672✔
277

278
          if (di->zone.operator const DNSName&() == shorter) {
6,672✔
279
            break;
2,882✔
280
          }
2,882✔
281

282
          bool foundShorter = false;
3,790✔
283
          di->backend->lookup(QType(QType::ANY), shorter, di->id);
3,790✔
284
          while (di->backend->get(rec)) {
114,280✔
285
            if (rec.qname == rr->d_name && rec.qtype == QType::DS)
110,490✔
286
              fixDS = true;
66✔
287
            if (shorter != rr->d_name) {
110,490✔
288
              foundShorter = true;
366✔
289
            }
366✔
290
            if (rec.qtype == QType::NS) // are we inserting below a delegate?
110,490✔
291
              auth=false;
550✔
292
          }
110,490✔
293

294
          if (!foundShorter && auth && shorter != rr->d_name) { // haven't found any record at current level, insert ENT.
3,790✔
295
            insnonterm.insert(shorter);
220✔
296
          }
220✔
297
          if (foundShorter)
3,790✔
298
            break; // if we find a shorter record, we can stop searching
278✔
299
        } while(shorter.chopOff());
3,790!
300
      }
3,160✔
301

302
      if(*haveNSEC3)
3,336✔
303
      {
1,826✔
304
        DNSName ordername;
1,826✔
305
        if(! *narrow)
1,826✔
306
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
1,222✔
307

308
        if (*narrow) {
1,826✔
309
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth, QType::ANY, false);
604✔
310
        }
604✔
311
        else {
1,222✔
312
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, true);
1,222✔
313
        }
1,222✔
314

315
        if (fixDS) {
1,826✔
316
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, !*narrow);
36✔
317
        }
36✔
318

319
        if(!auth) {
1,826✔
320
          if (ns3pr->d_flags != 0) {
228✔
321
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS, !*narrow);
152✔
322
          }
152✔
323
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, !*narrow);
228✔
324
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, !*narrow);
228✔
325
        }
228✔
326
      }
1,826✔
327
      else { // NSEC
1,510✔
328
        DNSName ordername=rr->d_name.makeRelative(di->zone);
1,510✔
329
        di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, false);
1,510✔
330
        if (fixDS) {
1,510✔
331
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, false);
30✔
332
        }
30✔
333
        if(!auth) {
1,510✔
334
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, false);
190✔
335
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, false);
190✔
336
        }
190✔
337
      }
1,510✔
338

339

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

357
            if (*narrow) {
72✔
358
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth, QType::ANY, false);
24✔
359
            }
24✔
360
            else {
48✔
361
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth, QType::ANY, true);
48✔
362
            }
48✔
363

364
            if (ns3pr->d_flags != 0) {
72✔
365
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::NS, !*narrow);
48✔
366
            }
48✔
367
          }
72✔
368
          else { // NSEC
60✔
369
            DNSName ordername=DNSName(qname).makeRelative(di->zone);
60✔
370
            di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, false, QType::NS, false);
60✔
371
          }
60✔
372

373
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A, *haveNSEC3 && !*narrow);
132✔
374
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA, *haveNSEC3 && !*narrow);
132✔
375
        }
132✔
376
      }
242✔
377
    }
3,336✔
378
  } // rr->d_class == QClass::IN
3,600✔
379

380

381
  // 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
382
  // the code that calls this performUpdate().
383
  if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
4,808✔
384
    DLOG(g_log<<msgPrefix<<"Deleting records: "<<rr->d_name<<"; QClass:"<<rr->d_class<<"; rrType: "<<rrType.toString()<<endl);
1,186✔
385

386
    if (rrType == QType::NSEC3PARAM) {
1,186✔
387
      g_log<<Logger::Notice<<msgPrefix<<"Deleting NSEC3PARAM from zone, resetting ordernames."<<endl;
28✔
388
      // Be sure to use a ZoneName with a variant matching the domain we are
389
      // working on, for the sake of unsetNSEC3PARAM.
390
      ZoneName zonename(rr->d_name, di->zone.getVariant());
28✔
391
      if (rr->d_class == QClass::ANY) {
28!
392
        d_dk.unsetNSEC3PARAM(zonename);
28✔
393
      }
28✔
394
      else if (rr->d_class == QClass::NONE) {
×
395
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), di->zone);
×
396
        if (*haveNSEC3 && ns3pr->getZoneRepresentation() == nsec3rr.getZoneRepresentation())
×
397
          d_dk.unsetNSEC3PARAM(zonename);
×
398
        else
×
399
          return 0;
×
400
      } else
×
401
        return 0;
×
402

403
      // Update NSEC3 variables, other RR's in this update package might need them as well.
404
      *haveNSEC3 = false;
28✔
405
      *narrow = false;
28✔
406

407
      string error;
28✔
408
      string info;
28✔
409
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
28!
410
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
411
      }
×
412
      return 1;
28✔
413
    } // end of NSEC3PARAM delete block
28✔
414

415

416
    di->backend->lookup(rrType, rr->d_name, di->id);
1,158✔
417
    while(di->backend->get(rec)) {
4,736✔
418
      if (rr->d_class == QClass::ANY) { // 3.4.2.3
3,578✔
419
        if (rec.qname == di->zone.operator const DNSName&() && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) { // Never delete all SOA and NS's
2,992!
420
          rrset.push_back(rec);
44✔
421
        }
44✔
422
        else
2,948✔
423
          recordsToDelete.push_back(rec);
2,948✔
424
      }
2,992✔
425
      if (rr->d_class == QClass::NONE) { // 3.4.2.4
3,578✔
426
        auto repr = rec.getZoneRepresentation();
586✔
427
        if (rec.qtype == QType::TXT) {
586✔
428
          DLOG(g_log<<msgPrefix<<"Adjusting TXT content from ["<<repr<<"]"<<endl);
66✔
429
          auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
66✔
430
          auto ser = drc->serialize(rec.qname, true, true);
66✔
431
          auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser);
66✔
432
          repr = rc->getZoneRepresentation(true);
66✔
433
          DLOG(g_log<<msgPrefix<<"Adjusted TXT content to ["<<repr<<"]"<<endl);
66✔
434
        }
66✔
435
        DLOG(g_log<<msgPrefix<<"Matching RR in RRset - (adjusted) representation from request=["<<repr<<"], rr->getContent()->getZoneRepresentation()=["<<rr->getContent()->getZoneRepresentation()<<"]"<<endl);
586✔
436
        if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation())
586!
437
          recordsToDelete.push_back(rec);
410✔
438
        else
176✔
439
          rrset.push_back(rec);
176✔
440
      }
586✔
441
    }
3,578✔
442
  
443
    if (recordsToDelete.size()) {
1,158✔
444
      di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
1,114✔
445
      g_log<<Logger::Notice<<msgPrefix<<"Deleting record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
1,114✔
446
      changedRecords += recordsToDelete.size();
1,114✔
447

448

449
      // If we've removed a delegate, we need to reset ordername/auth for some records.
450
      if (rrType == QType::NS && rr->d_name != di->zone.operator const DNSName&()) { 
1,114✔
451
        vector<DNSName> belowOldDelegate, nsRecs, updateAuthFlag;
154✔
452
        di->backend->listSubZone(ZoneName(rr->d_name), di->id);
154✔
453
        while (di->backend->get(rec)) {
396✔
454
          if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
242!
455
            belowOldDelegate.push_back(rec.qname);
242✔
456
          if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name)
242!
457
            nsRecs.push_back(rec.qname);
22✔
458
        }
242✔
459

460
        for(auto &belowOldDel: belowOldDelegate)
154✔
461
        {
242✔
462
          bool isBelowDelegate = false;
242✔
463
          for(const auto & ns: nsRecs) {
242✔
464
            if (ns.isPartOf(belowOldDel)) {
66✔
465
              isBelowDelegate=true;
22✔
466
              break;
22✔
467
            }
22✔
468
          }
66✔
469
          if (!isBelowDelegate)
242✔
470
            updateAuthFlag.push_back(belowOldDel);
220✔
471
        }
242✔
472

473
        for (const auto &changeRec:updateAuthFlag) {
220✔
474
          DNSName ordername;
220✔
475
          if(*haveNSEC3)  {
220✔
476
            if(! *narrow) {
120✔
477
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, changeRec)));
80✔
478
            }
80✔
479
          }
120✔
480
          else { // NSEC
100✔
481
            ordername=changeRec.makeRelative(di->zone);
100✔
482
          }
100✔
483
          di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true, QType::ANY, *haveNSEC3 && !*narrow);
220✔
484
        }
220✔
485
      }
154✔
486

487
      // Fix ENT records.
488
      // We must check if we have a record below the current level and if we removed the 'last' record
489
      // on that level. If so, we must insert an ENT record.
490
      // 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.
491
      bool foundDeeper = false, foundOtherWithSameName = false;
1,114✔
492
      di->backend->listSubZone(ZoneName(rr->d_name), di->id);
1,114✔
493
      while (di->backend->get(rec)) {
6,328✔
494
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
5,214!
495
          foundOtherWithSameName = true;
946✔
496
        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
5,214✔
497
          foundDeeper = true;
3,872✔
498
      }
5,214✔
499

500
      if (foundDeeper && !foundOtherWithSameName) {
1,114✔
501
        insnonterm.insert(rr->d_name);
132✔
502
      } else if (!foundOtherWithSameName) {
982✔
503
        // If we didn't have to insert an ENT, we might have deleted a record at very deep level
504
        // and we must then clean up the ENT's above the deleted record.
505
        DNSName shorter(rr->d_name);
718✔
506
        while (shorter != di->zone.operator const DNSName&()) {
1,114!
507
          shorter.chopOff();
1,114✔
508
          bool foundRealRR = false;
1,114✔
509
          bool foundEnt = false;
1,114✔
510

511
          // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
512
          // consider these non ENT-records:
513
          // b.c.d.e.test.com
514
          // b.d.e.test.com
515
          // 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.
516
          // At that point we can stop deleting ENT's because the tree is in tact again.
517
          di->backend->listSubZone(ZoneName(shorter), di->id);
1,114✔
518

519
          while (di->backend->get(rec)) {
15,170✔
520
            if (rec.qtype.getCode())
14,056✔
521
              foundRealRR = true;
12,150✔
522
            else
1,906✔
523
              foundEnt = true;
1,906✔
524
          }
14,056✔
525
          if (!foundRealRR) {
1,114✔
526
            if (foundEnt) // only delete the ENT if we actually found one.
396✔
527
              delnonterm.insert(shorter);
330✔
528
          } else
396✔
529
            break;
718✔
530
        }
1,114✔
531
      }
718✔
532
    } else { // if (recordsToDelete.size())
1,114✔
533
      g_log<<Logger::Notice<<msgPrefix<<"Deletion for record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but not found."<<endl;
44✔
534
    }
44✔
535
  } // (End of delete block d_class == ANY || d_class == NONE
1,158✔
536
  
537

538

539
  //Insert and delete ENT's
540
  if (insnonterm.size() > 0 || delnonterm.size() > 0) {
4,780✔
541
    DLOG(g_log<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
3,644✔
542
    di->backend->updateEmptyNonTerminals(di->id, insnonterm, delnonterm, false);
3,644✔
543
    for (const auto &i: insnonterm) {
3,644✔
544
      string hashed;
352✔
545
      if(*haveNSEC3)
352✔
546
      {
192✔
547
        DNSName ordername;
192✔
548
        if(! *narrow) {
192✔
549
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, i)));
128✔
550
        }
128✔
551
        di->backend->updateDNSSECOrderNameAndAuth(di->id, i, ordername, true, QType::ANY, !*narrow);
192✔
552
      }
192✔
553
    }
352✔
554
  }
3,644✔
555

556
  return changedRecords;
4,780✔
557
}
4,808✔
558

559
int PacketHandler::forwardPacket(const string &msgPrefix, const DNSPacket& p, const DomainInfo& di) {
×
560
  vector<string> forward;
×
561
  B.getDomainMetadata(p.qdomainzone, "FORWARD-DNSUPDATE", forward);
×
562

563
  if (forward.size() == 0 && ! ::arg().mustDo("forward-dnsupdate")) {
×
564
    g_log << Logger::Notice << msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
565
    return RCode::Refused;
×
566
  }
×
567

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

571
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
572
      continue;
×
573
    }
×
574
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
575
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
576
    if(sock < 0) {
×
577
      g_log<<Logger::Error<<msgPrefix<<"Error creating socket: "<<stringerror()<<endl;
×
578
      continue;
×
579
    }
×
580

581
    if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
×
582
      g_log<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
×
583
      try {
×
584
        closesocket(sock);
×
585
      }
×
586
      catch(const PDNSException& e) {
×
587
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
×
588
      }
×
589
      continue;
×
590
    }
×
591

592
    DNSPacket l_forwardPacket(p);
×
593
    l_forwardPacket.setID(dns_random_uint16());
×
594
    l_forwardPacket.setRemote(&remote);
×
595
    uint16_t len=htons(l_forwardPacket.getString().length());
×
596
    string buffer((const char*)&len, 2);
×
597
    buffer.append(l_forwardPacket.getString());
×
598
    if(write(sock, buffer.c_str(), buffer.length()) < 0) {
×
599
      g_log<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
×
600
      try {
×
601
        closesocket(sock);
×
602
      }
×
603
      catch(const PDNSException& e) {
×
604
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
605
      }
×
606
      continue;
×
607
    }
×
608

609
    int res = waitForData(sock, 10, 0);
×
610
    if (!res) {
×
611
      g_log << Logger::Error << msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
×
612
      try {
×
613
        closesocket(sock);
×
614
      }
×
615
      catch(const PDNSException& e) {
×
616
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
617
      }
×
618
      continue;
×
619
    }
×
620
    if (res < 0) {
×
621
      g_log << Logger::Error << msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
622
      try {
×
623
        closesocket(sock);
×
624
      }
×
625
      catch(const PDNSException& e) {
×
626
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
627
      }
×
628
      continue;
×
629
    }
×
630

631
    unsigned char lenBuf[2];
×
632
    ssize_t recvRes;
×
633
    recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
×
634
    if (recvRes < 0 || static_cast<size_t>(recvRes) < sizeof(lenBuf)) {
×
635
      g_log << Logger::Error << msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
636
      try {
×
637
        closesocket(sock);
×
638
      }
×
639
      catch(const PDNSException& e) {
×
640
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
641
      }
×
642
      continue;
×
643
    }
×
644
    size_t packetLen = lenBuf[0]*256+lenBuf[1];
×
645

646
    buffer.resize(packetLen);
×
647
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
648
    if (recvRes < 0) {
×
649
      g_log << Logger::Error << msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
650
      try {
×
651
        closesocket(sock);
×
652
      }
×
653
      catch(const PDNSException& e) {
×
654
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
655
      }
×
656
      continue;
×
657
    }
×
658
    try {
×
659
      closesocket(sock);
×
660
    }
×
661
    catch(const PDNSException& e) {
×
662
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
663
    }
×
664

665
    try {
×
666
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
667
      g_log<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
×
668
      return mdp.d_header.rcode;
×
669
    }
×
670
    catch (...) {
×
671
      g_log << Logger::Error << msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
672
      continue;
×
673
    }
×
674
  }
×
675
  g_log << Logger::Error << msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
×
676
  return RCode::ServFail;
×
677

678
}
×
679

680
int PacketHandler::processUpdate(DNSPacket& packet) { // NOLINT(readability-function-cognitive-complexity)
2,294✔
681
  if (! ::arg().mustDo("dnsupdate"))
2,294!
682
    return RCode::Refused;
×
683

684
  string msgPrefix="UPDATE (" + std::to_string(packet.d.id) + ") from " + packet.getRemoteString() + " for " + packet.qdomainzone.toLogString() + ": ";
2,294✔
685
  g_log<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
2,294✔
686

687
  // if there is policy, we delegate all checks to it
688
  if (this->d_update_policy_lua == nullptr) {
2,294!
689

690
    // Check permissions - IP based
691
    vector<string> allowedRanges;
2,294✔
692
    B.getDomainMetadata(packet.qdomainzone, "ALLOW-DNSUPDATE-FROM", allowedRanges);
2,294✔
693
    if (! ::arg()["allow-dnsupdate-from"].empty())
2,294!
694
      stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t" );
2,294✔
695

696
    NetmaskGroup ng;
2,294✔
697
    for(const auto& i: allowedRanges) {
4,588✔
698
      ng.addMask(i);
4,588✔
699
    }
4,588✔
700

701
    if ( ! ng.match(packet.getInnerRemote())) {
2,294!
702
      g_log<<Logger::Error<<msgPrefix<<"Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED"<<endl;
×
703
      return RCode::Refused;
×
704
    }
×
705

706

707
    // Check permissions - TSIG based.
708
    vector<string> tsigKeys;
2,294✔
709
    B.getDomainMetadata(packet.qdomainzone, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
2,294✔
710
    if (tsigKeys.size() > 0) {
2,294!
711
      bool validKey = false;
×
712

713
      TSIGRecordContent trc;
×
714
      DNSName inputkey;
×
715
      string message;
×
716
      if (! packet.getTSIGDetails(&trc,  &inputkey)) {
×
717
        g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
×
718
        return RCode::Refused;
×
719
      }
×
720
#ifdef ENABLE_GSS_TSIG
×
721
      if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
722
        GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
723
        for(const auto& key: tsigKeys) {
×
724
          if (inputname.match(key)) {
×
725
            validKey = true;
×
726
            break;
×
727
          }
×
728
        }
×
729
      }
×
730
      else
×
731
#endif
×
732
        {
×
733
        for(const auto& key: tsigKeys) {
×
734
          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.
×
735
            validKey=true;
×
736
            break;
×
737
          }
×
738
        }
×
739
      }
×
740

741
      if (!validKey) {
×
742
        g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
743
        return RCode::Refused;
×
744
      }
×
745
    } else if(::arg().mustDo("dnsupdate-require-tsig")) {
2,294!
746
      g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but domain is not secured with TSIG. Sending REFUSED"<<endl;
×
747
      return RCode::Refused;
×
748
    }
×
749

750
    if (tsigKeys.empty() && packet.d_havetsig) {
2,294!
751
      g_log<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
×
752
    }
×
753

754
  }
2,294✔
755

756
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
757
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
758
  // variable names during the use of our MOADNSParser.
759
  MOADNSParser mdp(false, packet.getString());
2,294✔
760
  if (mdp.d_header.qdcount != 1) {
2,294!
761
    g_log<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
×
762
    return RCode::FormErr;
×
763
  }
×
764

765
  if (packet.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
2,294!
766
    g_log<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
×
767
    return RCode::FormErr;
×
768
  }
×
769

770
  if (packet.qclass != QClass::IN) {
2,294!
771
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
772
    return RCode::NotAuth;
×
773
  }
×
774

775
  DomainInfo di;
2,294✔
776
  di.backend=nullptr;
2,294✔
777
  if(!B.getDomainInfo(packet.qdomainzone, di) || (di.backend == nullptr)) {
2,294!
778
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<packet.qdomainzone<<"' (or backend does not support DNS update operation)"<<endl;
22✔
779
    return RCode::NotAuth;
22✔
780
  }
22✔
781

782
  if (di.kind == DomainInfo::Secondary)
2,272!
783
    return forwardPacket(msgPrefix, packet, di);
×
784

785
  // Check if all the records provided are within the zone
786
  for(const auto & answer : mdp.d_answers) {
5,556✔
787
    const DNSRecord *dnsRecord = &answer;
5,556✔
788
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
789
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
790
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
5,556!
791
      continue;
×
792
    }
×
793

794
    if (!dnsRecord->d_name.isPartOf(di.zone)) {
5,556✔
795
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
44✔
796
      return RCode::NotZone;
44✔
797
    }
44✔
798
  }
5,556✔
799

800

801
  auto lock = std::scoped_lock(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
2,228✔
802
  g_log<<Logger::Info<<msgPrefix<<"starting transaction."<<endl;
2,228✔
803
  if (!di.backend->startTransaction(packet.qdomainzone, UnknownDomainID)) { // Not giving the domain_id means that we do not delete the existing records.
2,228!
804
    g_log<<Logger::Error<<msgPrefix<<"Backend for domain "<<packet.qdomainzone<<" does not support transaction. Can't do Update packet."<<endl;
×
805
    return RCode::NotImp;
×
806
  }
×
807

808
  // 3.2.1 and 3.2.2 - Prerequisite check
809
  for(const auto & answer : mdp.d_answers) {
5,424✔
810
    const DNSRecord *dnsRecord = &answer;
5,424✔
811
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,424✔
812
      int res = checkUpdatePrerequisites(dnsRecord, &di);
418✔
813
      if (res>0) {
418✔
814
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<dnsRecord->d_name<<", returning "<<RCode::to_s(res)<<endl;
110✔
815
        di.backend->abortTransaction();
110✔
816
        return res;
110✔
817
      }
110✔
818
    }
418✔
819
  }
5,424✔
820

821
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
822
  typedef pair<DNSName, QType> rrSetKey_t;
2,118✔
823
  typedef vector<DNSResourceRecord> rrVector_t;
2,118✔
824
  typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
2,118✔
825
  RRsetMap_t preReqRRsets;
2,118✔
826
  for(const auto& i: mdp.d_answers) {
5,314✔
827
    const DNSRecord* dnsRecord = &i;
5,314✔
828
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,314✔
829
      // Last line of 3.2.3
830
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
308!
831
        di.backend->abortTransaction();
×
832
        return RCode::FormErr;
×
833
      }
×
834

835
      if (dnsRecord->d_class == QClass::IN) {
308✔
836
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
198✔
837
        rrVector_t *vec = &preReqRRsets[key];
198✔
838
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
198✔
839
      }
198✔
840
    }
308✔
841
  }
5,314✔
842

843
  if (preReqRRsets.size() > 0) {
2,118✔
844
    RRsetMap_t zoneRRsets;
66✔
845
    for (auto & preReqRRset : preReqRRsets) {
66✔
846
      rrSetKey_t rrSet=preReqRRset.first;
66✔
847
      rrVector_t *vec = &preReqRRset.second;
66✔
848

849
      DNSResourceRecord rec;
66✔
850
      di.backend->lookup(QType(QType::ANY), rrSet.first, di.id);
66✔
851
      uint16_t foundRR=0, matchRR=0;
66✔
852
      while (di.backend->get(rec)) {
264✔
853
        if (rec.qtype == rrSet.second) {
198!
854
          foundRR++;
198✔
855
          for(auto & rrItem : *vec) {
594✔
856
            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.
594✔
857
            if (rrItem == rec)
594✔
858
              matchRR++;
198✔
859
          }
594✔
860
        }
198✔
861
      }
198✔
862
      if (matchRR != foundRR || foundRR != vec->size()) {
66!
863
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
44✔
864
        di.backend->abortTransaction();
44✔
865
        return RCode::NXRRSet;
44✔
866
      }
44✔
867
    }
66✔
868
  }
66✔
869

870

871

872
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
873
  try {
2,074✔
874
    uint changedRecords = 0;
2,074✔
875
    // 3.4.1 - Prescan section
876
    for(const auto & answer : mdp.d_answers) {
5,182✔
877
      const DNSRecord *dnsRecord = &answer;
5,182✔
878
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,182✔
879
        int res = checkUpdatePrescan(dnsRecord);
5,006✔
880
        if (res>0) {
5,006✔
881
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
22✔
882
          di.backend->abortTransaction();
22✔
883
          return res;
22✔
884
        }
22✔
885
      }
5,006✔
886
    }
5,182✔
887

888
    bool updatedSerial=false;
2,052✔
889
    NSEC3PARAMRecordContent ns3pr;
2,052✔
890
    bool narrow=false;
2,052✔
891
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
2,052✔
892
    bool isPresigned = d_dk.isPresigned(di.zone);
2,052✔
893
    string soaEditSetting;
2,052✔
894
    d_dk.getSoaEdit(di.zone, soaEditSetting);
2,052✔
895

896
    // 3.4.2 - Perform the updates.
897
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
898
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
899
    vector<const DNSRecord *> nsRRtoDelete;
2,052✔
900

901
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
902
    set<DNSName> cn, nocn;
2,052✔
903
    for (const auto &rr : mdp.d_answers) {
5,160✔
904
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
5,160!
905
        // Addition
906
        if (rr.d_type == QType::CNAME) {
3,732✔
907
          cn.insert(rr.d_name);
176✔
908
        } else if (rr.d_type != QType::RRSIG) {
3,556!
909
          nocn.insert(rr.d_name);
3,556✔
910
        }
3,556✔
911
      }
3,732✔
912
    }
5,160✔
913
    for (auto const &n : cn) {
2,052✔
914
      if (nocn.count(n) > 0) {
176✔
915
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
22✔
916
        di.backend->abortTransaction();
22✔
917
        return RCode::FormErr;
22✔
918
      }
22✔
919
    }
176✔
920

921
    vector<const DNSRecord *> cnamesToAdd, nonCnamesToAdd;
2,030✔
922
    for(const auto & answer : mdp.d_answers) {
5,116✔
923
      const DNSRecord *dnsRecord = &answer;
5,116✔
924
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,116✔
925
        /* see if it's permitted by policy */
926
        if (this->d_update_policy_lua != nullptr) {
4,940!
927
          if (!this->d_update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), di.zone.operator const DNSName&(), packet)) {
×
928
            g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy"<<endl;
×
929
            continue;
×
930
          } else {
×
931
            g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy"<<endl;
×
932
          }
×
933
        }
×
934

935
        if (dnsRecord->d_class == QClass::NONE  && dnsRecord->d_type == QType::NS && dnsRecord->d_name == di.zone.operator const DNSName&()) {
4,940!
936
          nsRRtoDelete.push_back(dnsRecord);
66✔
937
        }
66✔
938
        else if (dnsRecord->d_class == QClass::IN &&  dnsRecord->d_ttl > 0) {
4,874!
939
          if (dnsRecord->d_type == QType::CNAME) {
3,688✔
940
            cnamesToAdd.push_back(dnsRecord);
154✔
941
          } else {
3,534✔
942
            nonCnamesToAdd.push_back(dnsRecord);
3,534✔
943
          }
3,534✔
944
        }
3,688✔
945
        else
1,186✔
946
          changedRecords += performUpdate(msgPrefix, dnsRecord, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
1,186✔
947
      }
4,940✔
948
    }
5,116✔
949
    for (const auto &rr : cnamesToAdd) {
2,030✔
950
      DNSResourceRecord rec;
154✔
951
      di.backend->lookup(QType(QType::ANY), rr->d_name, di.id);
154✔
952
      while (di.backend->get(rec)) {
220✔
953
        if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
88!
954
          // leave database handle in a consistent state
955
          while (di.backend->get(rec))
22!
956
            ;
×
957
          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;
22✔
958
          di.backend->abortTransaction();
22✔
959
          return RCode::Refused;
22✔
960
        }
22✔
961
      }
88✔
962
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
132✔
963
    }
132✔
964
    for (const auto &rr : nonCnamesToAdd) {
3,534✔
965
      DNSResourceRecord rec;
3,534✔
966
      di.backend->lookup(QType(QType::CNAME), rr->d_name, di.id);
3,534✔
967
      while (di.backend->get(rec)) {
3,534✔
968
        if (rec.qtype == QType::CNAME && rr->d_type != QType::RRSIG) {
22!
969
          // leave database handle in a consistent state
970
          while (di.backend->get(rec))
22!
971
            ;
×
972
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": CNAME exists for the same name"<<endl;
22✔
973
          di.backend->abortTransaction();
22✔
974
          return RCode::Refused;
22✔
975
        }
22✔
976
      }
22✔
977
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
3,512✔
978
    }
3,512✔
979
    if (nsRRtoDelete.size()) {
1,986✔
980
      vector<DNSResourceRecord> nsRRInZone;
44✔
981
      DNSResourceRecord rec;
44✔
982
      di.backend->lookup(QType(QType::NS), di.zone.operator const DNSName&(), di.id);
44✔
983
      while (di.backend->get(rec)) {
132✔
984
        nsRRInZone.push_back(rec);
88✔
985
      }
88✔
986
      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)
44✔
987
        for (auto& inZone: nsRRInZone) {
44✔
988
          for (auto& rr: nsRRtoDelete) {
44✔
989
            if (inZone.getZoneRepresentation() == (rr)->getContent()->getZoneRepresentation())
44✔
990
              changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
22✔
991
          }
44✔
992
        }
44✔
993
      }
22✔
994
    }
44✔
995

996
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
997
    if (changedRecords > 0 && !updatedSerial) {
1,986✔
998
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
1,766✔
999
      changedRecords++;
1,766✔
1000
    }
1,766✔
1001

1002
    if (changedRecords > 0) {
1,986✔
1003
      if (!di.backend->commitTransaction()) {
1,810!
1004
       g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
1005
        return RCode::ServFail;
×
1006
      }
×
1007

1008
      S.deposit("dnsupdate-changes", changedRecords);
1,810✔
1009

1010
      d_dk.clearMetaCache(di.zone);
1,810✔
1011
      // Purge the records!
1012
      purgeAuthCaches(di.zone.operator const DNSName&().toString() + "$");
1,810✔
1013

1014
      // Notify secondaries
1015
      if (di.kind == DomainInfo::Primary) {
1,810!
1016
        vector<string> notify;
1,810✔
1017
        B.getDomainMetadata(packet.qdomainzone, "NOTIFY-DNSUPDATE", notify);
1,810✔
1018
        if (!notify.empty() && notify.front() == "1") {
1,810!
1019
          Communicator.notifyDomain(di.zone, &B);
×
1020
        }
×
1021
      }
1,810✔
1022

1023
      g_log<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records committed."<<endl;
1,810✔
1024
    } else {
1,810✔
1025
      //No change, no commit, we perform abort() because some backends might like this more.
1026
      g_log<<Logger::Info<<msgPrefix<<"Update completed, 0 changes, rolling back."<<endl;
176✔
1027
      di.backend->abortTransaction();
176✔
1028
    }
176✔
1029
    return RCode::NoError; //rfc 2136 3.4.2.5
1,986✔
1030
  }
1,986✔
1031
  catch (SSqlException &e) {
2,074✔
1032
    g_log<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
×
1033
    di.backend->abortTransaction();
×
1034
    return RCode::ServFail;
×
1035
  }
×
1036
  catch (DBException &e) {
2,074✔
1037
    g_log<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1038
    di.backend->abortTransaction();
×
1039
    return RCode::ServFail;
×
1040
  }
×
1041
  catch (PDNSException &e) {
2,074✔
1042
    g_log<<Logger::Error<<msgPrefix<<"Caught PDNSException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1043
    di.backend->abortTransaction();
×
1044
    return RCode::ServFail;
×
1045
  }
×
1046
  catch(std::exception &e) {
2,074✔
1047
    g_log<<Logger::Error<<msgPrefix<<"Caught std:exception: "<<e.what()<<"; Sending ServFail!"<<endl;
×
1048
    di.backend->abortTransaction();
×
1049
    return RCode::ServFail;
×
1050
  }
×
1051
  catch (...) {
2,074✔
1052
    g_log<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
×
1053
    di.backend->abortTransaction();
×
1054
    return RCode::ServFail;
×
1055
  }
×
1056
}
2,074✔
1057

1058
void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, const string& soaEditSetting,  bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
1,766✔
1059
  SOAData sd;
1,766✔
1060
  if (!di->backend->getSOA(di->zone, di->id, sd)) {
1,766!
1061
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
×
1062
  }
×
1063

1064
  uint32_t oldSerial = sd.serial;
1,766✔
1065

1066
  vector<string> soaEdit2136Setting;
1,766✔
1067
  B.getDomainMetadata(di->zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
1,766✔
1068
  string soaEdit2136 = "DEFAULT";
1,766✔
1069
  string soaEdit;
1,766✔
1070
  if (!soaEdit2136Setting.empty()) {
1,766!
1071
    soaEdit2136 = soaEdit2136Setting[0];
×
1072
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
×
1073
      if (soaEditSetting.empty()) {
×
1074
        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;
×
1075
        soaEdit2136 = "DEFAULT";
×
1076
      } else
×
1077
        soaEdit = soaEditSetting;
×
1078
    }
×
1079
  }
×
1080

1081
  DNSResourceRecord rr;
1,766✔
1082
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
1,766!
1083
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
1,766✔
1084
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
1,766✔
1085

1086
    //Correct ordername + auth flag
1087
    DNSName ordername;
1,766✔
1088
    if (haveNSEC3) {
1,766✔
1089
      if (!narrow) {
968✔
1090
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
660✔
1091
      }
660✔
1092
    } else { // NSEC
968✔
1093
      ordername = rr.qname.makeRelative(di->zone);
798✔
1094
    }
798✔
1095
    di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true, QType::ANY, haveNSEC3 && !narrow);
1,766✔
1096
  }
1,766✔
1097
}
1,766✔
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