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

PowerDNS / pdns / 17649353846

11 Sep 2025 03:23PM UTC coverage: 66.026% (+0.008%) from 66.018%
17649353846

Pull #16113

github

web-flow
Merge 7969a3491 into 1f79f8639
Pull Request #16113: auth: remove confusing message

42247 of 92612 branches covered (45.62%)

Branch coverage included in aggregate %.

19 of 21 new or added lines in 1 file covered. (90.48%)

20 existing lines in 4 files now uncovered.

128510 of 166008 relevant lines covered (77.41%)

5339881.1 hits per line

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

72.91
/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

26
std::mutex PacketHandler::s_rfc2136lock;
27

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

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

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

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

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

66
  return RCode::NoError;
308✔
67
}
352✔
68

69

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

77
  QType qtype = QType(rr->d_type);
5,006✔
78

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

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

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

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

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

99
  return RCode::NoError;
4,984✔
100
}
5,006✔
101

102

103
// Implements section 3.4.2 of RFC2136
104
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
105
static uint performUpdate(DNSSECKeeper& dsk, const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool& narrow, bool& haveNSEC3, NSEC3PARAMRecordContent& ns3pr, bool& updatedSerial) // NOLINT(readability-identifier-length)
106
{
4,852✔
107
  QType rrType = QType(rr->d_type);
4,852✔
108

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

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

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

124

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

130

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

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

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

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

150

151

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

159
    if (foundRecord) {
3,600✔
160

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

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

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

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

242
        if(haveNSEC3) {
242✔
243
          DNSName ordername;
132✔
244
          if(! narrow) {
132✔
245
            ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, rr->d_name)));
88✔
246
          }
88✔
247

248
          if (narrow) {
132✔
249
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth, QType::ANY, false);
44✔
250
          }
44✔
251
          else {
88✔
252
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, true);
88✔
253
          }
88✔
254
          if(!auth || rrType == QType::DS) {
132!
255
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS, !narrow);
×
256
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, !narrow);
×
257
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, !narrow);
×
258
          }
×
259

260
        } else { // NSEC
132✔
261
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, rr->d_name.makeRelative(di->zone), auth, QType::ANY, false);
110✔
262
          if(!auth || rrType == QType::DS) {
110!
263
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, false);
×
264
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, false);
×
265
          }
×
266
        }
110✔
267
      }
242✔
268

269
    } // if (foundRecord)
2,552✔
270

271
    // If we haven't found a record that matches, we must add it.
272
    if (! foundRecord) {
3,600✔
273
      g_log<<Logger::Notice<<msgPrefix<<"Adding record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
3,336✔
274
      delnonterm.insert(rr->d_name); // always remove any ENT's in the place where we're going to add a record.
3,336✔
275
      auto newRec = DNSResourceRecord::fromWire(*rr);
3,336✔
276
      newRec.domain_id = di->id;
3,336✔
277
      newRec.auth = (rr->d_name == di->zone.operator const DNSName&() || rrType.getCode() != QType::NS);
3,336✔
278
      di->backend->feedRecord(newRec, DNSName());
3,336✔
279
      changedRecords++;
3,336✔
280

281

282
      // because we added a record, we need to fix DNSSEC data.
283
      DNSName shorter(rr->d_name);
3,336✔
284
      bool auth=newRec.auth;
3,336✔
285
      bool fixDS = (rrType == QType::DS);
3,336✔
286

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

290
          if (di->zone.operator const DNSName&() == shorter) {
6,672✔
291
            break;
2,882✔
292
          }
2,882✔
293

294
          bool foundShorter = false;
3,790✔
295
          di->backend->lookup(QType(QType::ANY), shorter, di->id);
3,790✔
296
          while (di->backend->get(rec)) {
114,280✔
297
            if (rec.qname == rr->d_name && rec.qtype == QType::DS)
110,490✔
298
              fixDS = true;
66✔
299
            if (shorter != rr->d_name) {
110,490✔
300
              foundShorter = true;
366✔
301
            }
366✔
302
            if (rec.qtype == QType::NS) // are we inserting below a delegate?
110,490✔
303
              auth=false;
550✔
304
          }
110,490✔
305

306
          if (!foundShorter && auth && shorter != rr->d_name) { // haven't found any record at current level, insert ENT.
3,790✔
307
            insnonterm.insert(shorter);
220✔
308
          }
220✔
309
          if (foundShorter)
3,790✔
310
            break; // if we find a shorter record, we can stop searching
278✔
311
        } while(shorter.chopOff());
3,790!
312
      }
3,160✔
313

314
      if(haveNSEC3)
3,336✔
315
      {
1,826✔
316
        DNSName ordername;
1,826✔
317
        if(! narrow) {
1,826✔
318
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, rr->d_name)));
1,222✔
319
        }
1,222✔
320

321
        if (narrow) {
1,826✔
322
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth, QType::ANY, false);
604✔
323
        }
604✔
324
        else {
1,222✔
325
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, true);
1,222✔
326
        }
1,222✔
327

328
        if (fixDS) {
1,826✔
329
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, !narrow);
36✔
330
        }
36✔
331

332
        if(!auth) {
1,826✔
333
          if (ns3pr.d_flags != 0) {
228✔
334
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS, !narrow);
152✔
335
          }
152✔
336
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, !narrow);
228✔
337
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, !narrow);
228✔
338
        }
228✔
339
      }
1,826✔
340
      else { // NSEC
1,510✔
341
        DNSName ordername=rr->d_name.makeRelative(di->zone);
1,510✔
342
        di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, false);
1,510✔
343
        if (fixDS) {
1,510✔
344
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, false);
30✔
345
        }
30✔
346
        if(!auth) {
1,510✔
347
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, false);
190✔
348
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, false);
190✔
349
        }
190✔
350
      }
1,510✔
351

352

353
      // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
354
      // Auth can only be false when the rr->d_name is not the zone
355
      if (auth == false && rrType == QType::NS) {
3,336✔
356
        DLOG(g_log<<msgPrefix<<"Going to fix auth flags below "<<rr->d_name<<endl);
242✔
357
        insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
242✔
358
        vector<DNSName> qnames;
242✔
359
        di->backend->listSubZone(ZoneName(rr->d_name), di->id);
242✔
360
        while(di->backend->get(rec)) {
726✔
361
          if (rec.qtype.getCode() && rec.qtype.getCode() != QType::DS && rr->d_name != rec.qname) // Skip ENT, DS and our already corrected record.
484✔
362
            qnames.push_back(rec.qname);
132✔
363
        }
484✔
364
        for(const auto & qname : qnames) {
242✔
365
          if(haveNSEC3)  {
132✔
366
            DNSName ordername;
72✔
367
            if(! narrow) {
72✔
368
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, qname)));
48✔
369
            }
48✔
370

371
            if (narrow) {
72✔
372
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth, QType::ANY, false);
24✔
373
            }
24✔
374
            else {
48✔
375
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth, QType::ANY, true);
48✔
376
            }
48✔
377

378
            if (ns3pr.d_flags != 0) {
72✔
379
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::NS, !narrow);
48✔
380
            }
48✔
381
          }
72✔
382
          else { // NSEC
60✔
383
            DNSName ordername=DNSName(qname).makeRelative(di->zone);
60✔
384
            di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, false, QType::NS, false);
60✔
385
          }
60✔
386

387
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A, haveNSEC3 && !narrow);
132✔
388
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA, haveNSEC3 && !narrow);
132✔
389
        }
132✔
390
      }
242✔
391
    }
3,336✔
392
  } // rr->d_class == QClass::IN
3,600✔
393

394

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

400
    if (rrType == QType::NSEC3PARAM) {
1,186✔
401
      g_log<<Logger::Notice<<msgPrefix<<"Deleting NSEC3PARAM from zone, resetting ordernames."<<endl;
28✔
402
      // Be sure to use a ZoneName with a variant matching the domain we are
403
      // working on, for the sake of unsetNSEC3PARAM.
404
      ZoneName zonename(rr->d_name, di->zone.getVariant());
28✔
405
      if (rr->d_class == QClass::ANY) {
28!
406
        dsk.unsetNSEC3PARAM(zonename);
28✔
407
      }
28✔
408
      else if (rr->d_class == QClass::NONE) {
×
409
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), di->zone);
×
410
        if (haveNSEC3 && ns3pr.getZoneRepresentation() == nsec3rr.getZoneRepresentation()) {
×
411
          dsk.unsetNSEC3PARAM(zonename);
×
412
        }
×
413
        else {
×
414
          return 0;
×
415
        }
×
416
      } else {
×
417
        return 0;
×
418
      }
×
419

420
      // Update NSEC3 variables, other RR's in this update package might need them as well.
421
      haveNSEC3 = false;
28✔
422
      narrow = false;
28✔
423

424
      string error;
28✔
425
      string info;
28✔
426
      if (!dsk.rectifyZone(di->zone, error, info, false)) {
28!
427
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
428
      }
×
429
      return 1;
28✔
430
    } // end of NSEC3PARAM delete block
28✔
431

432

433
    di->backend->lookup(rrType, rr->d_name, di->id);
1,158✔
434
    while(di->backend->get(rec)) {
4,736✔
435
      if (rr->d_class == QClass::ANY) { // 3.4.2.3
3,578✔
436
        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!
437
          rrset.push_back(rec);
44✔
438
        }
44✔
439
        else
2,948✔
440
          recordsToDelete.push_back(rec);
2,948✔
441
      }
2,992✔
442
      if (rr->d_class == QClass::NONE) { // 3.4.2.4
3,578✔
443
        auto repr = rec.getZoneRepresentation();
586✔
444
        if (rec.qtype == QType::TXT) {
586✔
445
          DLOG(g_log<<msgPrefix<<"Adjusting TXT content from ["<<repr<<"]"<<endl);
66✔
446
          auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
66✔
447
          auto ser = drc->serialize(rec.qname, true, true);
66✔
448
          auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser);
66✔
449
          repr = rc->getZoneRepresentation(true);
66✔
450
          DLOG(g_log<<msgPrefix<<"Adjusted TXT content to ["<<repr<<"]"<<endl);
66✔
451
        }
66✔
452
        DLOG(g_log<<msgPrefix<<"Matching RR in RRset - (adjusted) representation from request=["<<repr<<"], rr->getContent()->getZoneRepresentation()=["<<rr->getContent()->getZoneRepresentation()<<"]"<<endl);
586✔
453
        if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation())
586!
454
          recordsToDelete.push_back(rec);
410✔
455
        else
176✔
456
          rrset.push_back(rec);
176✔
457
      }
586✔
458
    }
3,578✔
459
  
460
    if (recordsToDelete.size()) {
1,158✔
461
      di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
1,114✔
462
      g_log<<Logger::Notice<<msgPrefix<<"Deleting record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
1,114✔
463
      changedRecords += recordsToDelete.size();
1,114✔
464

465

466
      // If we've removed a delegate, we need to reset ordername/auth for some records.
467
      if (rrType == QType::NS && rr->d_name != di->zone.operator const DNSName&()) { 
1,114✔
468
        vector<DNSName> belowOldDelegate, nsRecs, updateAuthFlag;
154✔
469
        di->backend->listSubZone(ZoneName(rr->d_name), di->id);
154✔
470
        while (di->backend->get(rec)) {
396✔
471
          if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
242!
472
            belowOldDelegate.push_back(rec.qname);
242✔
473
          if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name)
242!
474
            nsRecs.push_back(rec.qname);
22✔
475
        }
242✔
476

477
        for(auto &belowOldDel: belowOldDelegate)
154✔
478
        {
242✔
479
          bool isBelowDelegate = false;
242✔
480
          for(const auto & ns: nsRecs) {
242✔
481
            if (ns.isPartOf(belowOldDel)) {
66✔
482
              isBelowDelegate=true;
22✔
483
              break;
22✔
484
            }
22✔
485
          }
66✔
486
          if (!isBelowDelegate)
242✔
487
            updateAuthFlag.push_back(belowOldDel);
220✔
488
        }
242✔
489

490
        for (const auto &changeRec:updateAuthFlag) {
220✔
491
          DNSName ordername;
220✔
492
          if(haveNSEC3)  {
220✔
493
            if(! narrow) {
120✔
494
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, changeRec)));
80✔
495
            }
80✔
496
          }
120✔
497
          else { // NSEC
100✔
498
            ordername=changeRec.makeRelative(di->zone);
100✔
499
          }
100✔
500
          di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true, QType::ANY, haveNSEC3 && !narrow);
220✔
501
        }
220✔
502
      }
154✔
503

504
      // Fix ENT records.
505
      // We must check if we have a record below the current level and if we removed the 'last' record
506
      // on that level. If so, we must insert an ENT record.
507
      // 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.
508
      bool foundDeeper = false, foundOtherWithSameName = false;
1,114✔
509
      di->backend->listSubZone(ZoneName(rr->d_name), di->id);
1,114✔
510
      while (di->backend->get(rec)) {
6,328✔
511
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
5,214!
512
          foundOtherWithSameName = true;
946✔
513
        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✔
514
          foundDeeper = true;
3,872✔
515
      }
5,214✔
516

517
      if (foundDeeper && !foundOtherWithSameName) {
1,114✔
518
        insnonterm.insert(rr->d_name);
132✔
519
      } else if (!foundOtherWithSameName) {
982✔
520
        // If we didn't have to insert an ENT, we might have deleted a record at very deep level
521
        // and we must then clean up the ENT's above the deleted record.
522
        DNSName shorter(rr->d_name);
718✔
523
        while (shorter != di->zone.operator const DNSName&()) {
1,114!
524
          shorter.chopOff();
1,114✔
525
          bool foundRealRR = false;
1,114✔
526
          bool foundEnt = false;
1,114✔
527

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

536
          while (di->backend->get(rec)) {
15,170✔
537
            if (rec.qtype.getCode())
14,056✔
538
              foundRealRR = true;
12,150✔
539
            else
1,906✔
540
              foundEnt = true;
1,906✔
541
          }
14,056✔
542
          if (!foundRealRR) {
1,114✔
543
            if (foundEnt) // only delete the ENT if we actually found one.
396✔
544
              delnonterm.insert(shorter);
330✔
545
          } else
396✔
546
            break;
718✔
547
        }
1,114✔
548
      }
718✔
549
    } else { // if (recordsToDelete.size())
1,114✔
550
      g_log<<Logger::Notice<<msgPrefix<<"Deletion for record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but not found."<<endl;
44✔
551
    }
44✔
552
  } // (End of delete block d_class == ANY || d_class == NONE
1,158✔
553
  
554

555

556
  //Insert and delete ENT's
557
  if (insnonterm.size() > 0 || delnonterm.size() > 0) {
4,780✔
558
    DLOG(g_log<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
3,644✔
559
    di->backend->updateEmptyNonTerminals(di->id, insnonterm, delnonterm, false);
3,644✔
560
    for (const auto &i: insnonterm) {
3,644✔
561
      string hashed;
352✔
562
      if(haveNSEC3)
352✔
563
      {
192✔
564
        DNSName ordername;
192✔
565
        if(! narrow) {
192✔
566
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, i)));
128✔
567
        }
128✔
568
        di->backend->updateDNSSECOrderNameAndAuth(di->id, i, ordername, true, QType::ANY, !narrow);
192✔
569
      }
192✔
570
    }
352✔
571
  }
3,644✔
572

573
  return changedRecords;
4,780✔
574
}
4,808✔
575

576
int PacketHandler::forwardPacket(const string &msgPrefix, const DNSPacket& p, const DomainInfo& di) {
×
577
  vector<string> forward;
×
578
  B.getDomainMetadata(p.qdomainzone, "FORWARD-DNSUPDATE", forward);
×
579

580
  if (forward.size() == 0 && ! ::arg().mustDo("forward-dnsupdate")) {
×
581
    g_log << Logger::Notice << msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
582
    return RCode::Refused;
×
583
  }
×
584

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

588
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
589
      continue;
×
590
    }
×
591
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
592
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
593
    if(sock < 0) {
×
594
      g_log<<Logger::Error<<msgPrefix<<"Error creating socket: "<<stringerror()<<endl;
×
595
      continue;
×
596
    }
×
597

598
    if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
×
599
      g_log<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
×
600
      try {
×
601
        closesocket(sock);
×
602
      }
×
603
      catch(const PDNSException& e) {
×
604
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
×
605
      }
×
606
      continue;
×
607
    }
×
608

609
    DNSPacket l_forwardPacket(p);
×
610
    l_forwardPacket.setID(dns_random_uint16());
×
611
    l_forwardPacket.setRemote(&remote);
×
612
    uint16_t len=htons(l_forwardPacket.getString().length());
×
613
    string buffer((const char*)&len, 2);
×
614
    buffer.append(l_forwardPacket.getString());
×
615
    if(write(sock, buffer.c_str(), buffer.length()) < 0) {
×
616
      g_log<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
×
617
      try {
×
618
        closesocket(sock);
×
619
      }
×
620
      catch(const PDNSException& e) {
×
621
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
622
      }
×
623
      continue;
×
624
    }
×
625

626
    int res = waitForData(sock, 10, 0);
×
627
    if (!res) {
×
628
      g_log << Logger::Error << msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
×
629
      try {
×
630
        closesocket(sock);
×
631
      }
×
632
      catch(const PDNSException& e) {
×
633
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
634
      }
×
635
      continue;
×
636
    }
×
637
    if (res < 0) {
×
638
      g_log << Logger::Error << msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
639
      try {
×
640
        closesocket(sock);
×
641
      }
×
642
      catch(const PDNSException& e) {
×
643
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
644
      }
×
645
      continue;
×
646
    }
×
647

648
    unsigned char lenBuf[2];
×
649
    ssize_t recvRes;
×
650
    recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
×
651
    if (recvRes < 0 || static_cast<size_t>(recvRes) < sizeof(lenBuf)) {
×
652
      g_log << Logger::Error << msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
653
      try {
×
654
        closesocket(sock);
×
655
      }
×
656
      catch(const PDNSException& e) {
×
657
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
658
      }
×
659
      continue;
×
660
    }
×
661
    size_t packetLen = lenBuf[0]*256+lenBuf[1];
×
662

663
    buffer.resize(packetLen);
×
664
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
665
    if (recvRes < 0) {
×
666
      g_log << Logger::Error << msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
667
      try {
×
668
        closesocket(sock);
×
669
      }
×
670
      catch(const PDNSException& e) {
×
671
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
672
      }
×
673
      continue;
×
674
    }
×
675
    try {
×
676
      closesocket(sock);
×
677
    }
×
678
    catch(const PDNSException& e) {
×
679
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
680
    }
×
681

682
    try {
×
683
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
684
      g_log<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
×
685
      return mdp.d_header.rcode;
×
686
    }
×
687
    catch (...) {
×
688
      g_log << Logger::Error << msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
689
      continue;
×
690
    }
×
691
  }
×
692
  g_log << Logger::Error << msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
×
693
  return RCode::ServFail;
×
694

695
}
×
696

697
static bool isUpdateAllowed(UeberBackend& UBackend, const std::string& msgPrefix, DNSPacket& packet)
698
{
2,294✔
699
  // Check permissions - IP based
700
  vector<string> allowedRanges;
2,294✔
701

702
  UBackend.getDomainMetadata(packet.qdomainzone, "ALLOW-DNSUPDATE-FROM", allowedRanges);
2,294✔
703
  if (! ::arg()["allow-dnsupdate-from"].empty()) {
2,294!
704
    stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t" );
2,294✔
705
  }
2,294✔
706

707
  NetmaskGroup nmg;
2,294✔
708
  for(const auto& range: allowedRanges) {
4,588✔
709
    nmg.addMask(range);
4,588✔
710
  }
4,588✔
711

712
  if ( ! nmg.match(packet.getInnerRemote())) {
2,294!
713
    g_log<<Logger::Error<<msgPrefix<<"Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED"<<endl;
×
714
    return false;
×
715
  }
×
716

717
  // Check permissions - TSIG based.
718
  vector<string> tsigKeys;
2,294✔
719
  UBackend.getDomainMetadata(packet.qdomainzone, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
2,294✔
720
  if (!tsigKeys.empty()) {
2,294!
721
    bool validKey = false;
×
722

723
    TSIGRecordContent trc;
×
724
    DNSName inputkey;
×
725
    string message;
×
726
    if (! packet.getTSIGDetails(&trc,  &inputkey)) {
×
727
      g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
×
728
      return false;
×
729
    }
×
730
#ifdef ENABLE_GSS_TSIG
×
731
    if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
732
      GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
733
      for(const auto& key: tsigKeys) {
×
734
        if (inputname.match(key)) {
×
735
          validKey = true;
×
736
          break;
×
737
        }
×
738
      }
×
739
    }
×
740
    else
×
741
#endif
×
742
    {
×
743
      for(const auto& key: tsigKeys) {
×
744
        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.
×
745
          validKey=true;
×
746
          break;
×
747
        }
×
748
      }
×
749
    }
×
750

751
    if (!validKey) {
×
752
      g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
753
      return false;
×
754
    }
×
755
  } else if(::arg().mustDo("dnsupdate-require-tsig")) {
2,294!
756
    g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but domain is not secured with TSIG. Sending REFUSED"<<endl;
×
757
    return false;
×
758
  }
×
759

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

764
  return true;
2,294✔
765
}
2,294✔
766

767
static uint8_t updatePrereqCheck323(MOADNSParser& mdp, DomainInfo& info, const std::string& msgPrefix)
768
{
2,118✔
769
  using rrSetKey_t = pair<DNSName, QType>;
2,118✔
770
  using rrVector_t = vector<DNSResourceRecord>;
2,118✔
771
  using RRsetMap_t = std::map<rrSetKey_t, rrVector_t>;
2,118✔
772
  RRsetMap_t preReqRRsets;
2,118✔
773

774
  for(const auto& rec: mdp.d_answers) {
5,314✔
775
    const DNSRecord* dnsRecord = &rec;
5,314✔
776
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,314✔
777
      // Last line of 3.2.3
778
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
308!
779
        return RCode::FormErr;
×
780
      }
×
781

782
      if (dnsRecord->d_class == QClass::IN) {
308✔
783
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
198✔
784
        rrVector_t *vec = &preReqRRsets[key];
198✔
785
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
198✔
786
      }
198✔
787
    }
308✔
788
  }
5,314✔
789

790
  if (!preReqRRsets.empty()) {
2,118✔
791
    RRsetMap_t zoneRRsets;
66✔
792
    for (auto & preReqRRset : preReqRRsets) {
66✔
793
      rrSetKey_t rrSet=preReqRRset.first;
66✔
794
      rrVector_t *vec = &preReqRRset.second;
66✔
795

796
      DNSResourceRecord rec;
66✔
797
      info.backend->lookup(QType(QType::ANY), rrSet.first, info.id);
66✔
798
      size_t foundRR{0};
66✔
799
      size_t matchRR{0};
66✔
800
      while (info.backend->get(rec)) {
264✔
801
        if (rec.qtype == rrSet.second) {
198!
802
          foundRR++;
198✔
803
          for(auto & rrItem : *vec) {
594✔
804
            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✔
805
            if (rrItem == rec) {
594✔
806
              matchRR++;
198✔
807
            }
198✔
808
          }
594✔
809
        }
198✔
810
      }
198✔
811
      if (matchRR != foundRR || foundRR != vec->size()) {
66!
812
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
44✔
813
        return RCode::NXRRSet;
44✔
814
      }
44✔
815
    }
66✔
816
  }
66✔
817
  return RCode::NoError;
2,074✔
818
}
2,118✔
819

820
static uint8_t updateRecords(MOADNSParser& mdp, DNSSECKeeper& dsk, DomainInfo& info, uint& changedRecords, const std::unique_ptr<AuthLua4>& update_policy_lua, DNSPacket& packet, bool isPresigned, bool& narrow, bool& haveNSEC3, NSEC3PARAMRecordContent& ns3pr, bool& updatedSerial, const std::string& msgPrefix)
821
{
2,030✔
822
  vector<const DNSRecord *> cnamesToAdd;
2,030✔
823
  vector<const DNSRecord *> nonCnamesToAdd;
2,030✔
824
  vector<const DNSRecord *> nsRRtoDelete;
2,030✔
825

826
  bool anyRecordProcessed{false};
2,030✔
827
  bool anyRecordAcceptedByLua{false};
2,030✔
828
  for(const auto & answer : mdp.d_answers) {
5,116✔
829
    const DNSRecord *dnsRecord = &answer;
5,116✔
830
    if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,116✔
831
      anyRecordProcessed = true;
4,940✔
832
      /* see if it's permitted by policy */
833
      if (update_policy_lua != nullptr) {
4,940!
834
        if (!update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), info.zone.operator const DNSName&(), packet)) {
×
835
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy"<<endl;
×
836
          continue;
×
837
        }
×
838
        g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy"<<endl;
×
839
        anyRecordAcceptedByLua = true;
×
840
      }
×
841

842
      if (dnsRecord->d_class == QClass::NONE  && dnsRecord->d_type == QType::NS && dnsRecord->d_name == info.zone.operator const DNSName&()) {
4,940!
843
        nsRRtoDelete.push_back(dnsRecord);
66✔
844
      }
66✔
845
      else if (dnsRecord->d_class == QClass::IN && dnsRecord->d_ttl > 0) {
4,874!
846
        if (dnsRecord->d_type == QType::CNAME) {
3,688✔
847
          cnamesToAdd.push_back(dnsRecord);
154✔
848
        } else {
3,534✔
849
          nonCnamesToAdd.push_back(dnsRecord);
3,534✔
850
        }
3,534✔
851
      }
3,688✔
852
      else {
1,186✔
853
        changedRecords += performUpdate(dsk, msgPrefix, dnsRecord, &info, isPresigned, narrow, haveNSEC3, ns3pr, updatedSerial);
1,186✔
854
      }
1,186✔
855
    }
4,940✔
856
  }
5,116✔
857

858
  if (update_policy_lua != nullptr) {
2,030!
859
    // If the Lua update policy script has been invoked, and has rejected
860
    // everything, better return Refused.
861
    if (anyRecordProcessed && !anyRecordAcceptedByLua) {
×
862
      return RCode::Refused;
×
863
    }
×
864
  }
×
865

866
  for (const auto &resrec : cnamesToAdd) {
2,030✔
867
    DNSResourceRecord rec;
154✔
868
    info.backend->lookup(QType(QType::ANY), resrec->d_name, info.id);
154✔
869
    while (info.backend->get(rec)) {
220✔
870
      if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
88!
871
        // leave database handle in a consistent state
872
        info.backend->lookupEnd();
22✔
873
        g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << resrec->d_name << "/" << QType(resrec->d_type).toString() << ": Data other than CNAME exists for the same name"<<endl;
22✔
874
        return RCode::Refused;
22✔
875
      }
22✔
876
    }
88✔
877
    changedRecords += performUpdate(dsk, msgPrefix, resrec, &info, isPresigned, narrow, haveNSEC3, ns3pr, updatedSerial);
132✔
878
  }
132✔
879
  for (const auto &resrec : nonCnamesToAdd) {
3,534✔
880
    DNSResourceRecord rec;
3,534✔
881
    info.backend->lookup(QType(QType::CNAME), resrec->d_name, info.id);
3,534✔
882
    while (info.backend->get(rec)) {
3,534✔
883
      if (rec.qtype == QType::CNAME && resrec->d_type != QType::RRSIG) {
22!
884
        // leave database handle in a consistent state
885
        info.backend->lookupEnd();
22✔
886
        g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << resrec->d_name << "/" << QType(resrec->d_type).toString() << ": CNAME exists for the same name"<<endl;
22✔
887
        return RCode::Refused;
22✔
888
      }
22✔
889
    }
22✔
890
    changedRecords += performUpdate(dsk, msgPrefix, resrec, &info, isPresigned, narrow, haveNSEC3, ns3pr, updatedSerial);
3,512✔
891
  }
3,512✔
892

893
  if (!nsRRtoDelete.empty()) {
1,986✔
894
    vector<DNSResourceRecord> nsRRInZone;
44✔
895
    DNSResourceRecord rec;
44✔
896
    info.backend->lookup(QType(QType::NS), info.zone.operator const DNSName&(), info.id);
44✔
897
    while (info.backend->get(rec)) {
132✔
898
      nsRRInZone.push_back(rec);
88✔
899
    }
88✔
900
    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✔
901
      for (auto& inZone: nsRRInZone) {
44✔
902
        for (auto& resrec: nsRRtoDelete) {
44✔
903
          if (inZone.getZoneRepresentation() == resrec->getContent()->getZoneRepresentation()) {
44✔
904
            changedRecords += performUpdate(dsk, msgPrefix, resrec, &info, isPresigned, narrow, haveNSEC3, ns3pr, updatedSerial);
22✔
905
          }
22✔
906
        }
44✔
907
      }
44✔
908
    }
22✔
909
  }
44✔
910

911
  return RCode::NoError;
1,986✔
912
}
2,008✔
913

914
int PacketHandler::processUpdate(DNSPacket& packet)
915
{
2,294✔
916
  if (! ::arg().mustDo("dnsupdate")) {
2,294!
917
    return RCode::Refused;
×
918
  }
×
919

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

923
  // if there is policy, we delegate all checks to it
924
  if (this->d_update_policy_lua == nullptr) {
2,294!
925
    if (!isUpdateAllowed(B, msgPrefix, packet)) {
2,294!
926
      return RCode::Refused;
×
927
    }
×
928
  }
2,294✔
929

930
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
931
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
932
  // variable names during the use of our MOADNSParser.
933
  MOADNSParser mdp(false, packet.getString());
2,294✔
934
  if (mdp.d_header.qdcount != 1) {
2,294!
935
    g_log<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
×
936
    return RCode::FormErr;
×
937
  }
×
938

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

944
  if (packet.qclass != QClass::IN) {
2,294!
945
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
946
    return RCode::NotAuth;
×
947
  }
×
948

949
  DomainInfo di;
2,294✔
950
  di.backend=nullptr;
2,294✔
951
  if(!B.getDomainInfo(packet.qdomainzone, di) || (di.backend == nullptr)) {
2,294!
952
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<packet.qdomainzone<<"' (or backend does not support DNS update operation)"<<endl;
22✔
953
    return RCode::NotAuth;
22✔
954
  }
22✔
955

956
  if (di.kind == DomainInfo::Secondary) {
2,272!
957
    return forwardPacket(msgPrefix, packet, di);
×
958
  }
×
959

960
  // Check if all the records provided are within the zone
961
  for(const auto & answer : mdp.d_answers) {
5,556✔
962
    const DNSRecord *dnsRecord = &answer;
5,556✔
963
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
964
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
965
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
5,556!
966
      continue;
×
967
    }
×
968

969
    if (!dnsRecord->d_name.isPartOf(di.zone)) {
5,556✔
970
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
44✔
971
      return RCode::NotZone;
44✔
972
    }
44✔
973
  }
5,556✔
974

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

982
  // 3.2.1 and 3.2.2 - Prerequisite check
983
  for(const auto & answer : mdp.d_answers) {
5,424✔
984
    const DNSRecord *dnsRecord = &answer;
5,424✔
985
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,424✔
986
      int res = checkUpdatePrerequisites(dnsRecord, &di);
418✔
987
      if (res>0) {
418✔
988
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<dnsRecord->d_name<<", returning "<<RCode::to_s(res)<<endl;
110✔
989
        di.backend->abortTransaction();
110✔
990
        return res;
110✔
991
      }
110✔
992
    }
418✔
993
  }
5,424✔
994

995
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
996
  if (auto rcode = updatePrereqCheck323(mdp, di, msgPrefix); rcode != RCode::NoError) {
2,118✔
997
    di.backend->abortTransaction();
44✔
998
    return rcode;
44✔
999
  }
44✔
1000

1001
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
1002
  try {
2,074✔
1003
    // 3.4.1 - Prescan section
1004
    for(const auto & answer : mdp.d_answers) {
5,182✔
1005
      const DNSRecord *dnsRecord = &answer;
5,182✔
1006
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,182✔
1007
        int res = checkUpdatePrescan(dnsRecord);
5,006✔
1008
        if (res>0) {
5,006✔
1009
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
22✔
1010
          di.backend->abortTransaction();
22✔
1011
          return res;
22✔
1012
        }
22✔
1013
      }
5,006✔
1014
    }
5,182✔
1015

1016
    bool updatedSerial{false};
2,052✔
1017
    NSEC3PARAMRecordContent ns3pr;
2,052✔
1018
    bool narrow=false;
2,052✔
1019
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
2,052✔
1020
    bool isPresigned = d_dk.isPresigned(di.zone);
2,052✔
1021
    string soaEditSetting;
2,052✔
1022
    d_dk.getSoaEdit(di.zone, soaEditSetting);
2,052✔
1023

1024
    // 3.4.2 - Perform the updates.
1025
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
1026
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
1027

1028
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
1029
    set<DNSName> cn, nocn;
2,052✔
1030
    for (const auto &rr : mdp.d_answers) {
5,160✔
1031
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
5,160!
1032
        // Addition
1033
        if (rr.d_type == QType::CNAME) {
3,732✔
1034
          cn.insert(rr.d_name);
176✔
1035
        } else if (rr.d_type != QType::RRSIG) {
3,556!
1036
          nocn.insert(rr.d_name);
3,556✔
1037
        }
3,556✔
1038
      }
3,732✔
1039
    }
5,160✔
1040
    for (auto const &n : cn) {
2,052✔
1041
      if (nocn.count(n) > 0) {
176✔
1042
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
22✔
1043
        di.backend->abortTransaction();
22✔
1044
        return RCode::FormErr;
22✔
1045
      }
22✔
1046
    }
176✔
1047

1048
    uint changedRecords = 0;
2,030✔
1049
    if (auto rcode = updateRecords(mdp, d_dk, di, changedRecords, d_update_policy_lua, packet, isPresigned, narrow, haveNSEC3, ns3pr, updatedSerial, msgPrefix); rcode != RCode::NoError) {
2,030✔
1050
      di.backend->abortTransaction();
44✔
1051
      return rcode;
44✔
1052
    }
44✔
1053

1054
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
1055
    if (changedRecords != 0 && !updatedSerial) {
1,986✔
1056
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
1,766✔
1057
      changedRecords++;
1,766✔
1058
    }
1,766✔
1059

1060
    if (changedRecords != 0) {
1,986✔
1061
      if (!di.backend->commitTransaction()) {
1,810!
1062
        g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
1063
        return RCode::ServFail;
×
1064
      }
×
1065

1066
      S.deposit("dnsupdate-changes", changedRecords);
1,810✔
1067

1068
      d_dk.clearMetaCache(di.zone);
1,810✔
1069
      // Purge the records!
1070
      purgeAuthCaches(di.zone.operator const DNSName&().toString() + "$");
1,810✔
1071

1072
      // Notify secondaries
1073
      if (di.kind == DomainInfo::Primary) {
1,810!
1074
        vector<string> notify;
1,810✔
1075
        B.getDomainMetadata(packet.qdomainzone, "NOTIFY-DNSUPDATE", notify);
1,810✔
1076
        if (!notify.empty() && notify.front() == "1") {
1,810!
1077
          Communicator.notifyDomain(di.zone, &B);
×
1078
        }
×
1079
      }
1,810✔
1080

1081
      g_log<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records committed."<<endl;
1,810✔
1082
    } else {
1,810✔
1083
      //No change, no commit, we perform abort() because some backends might like this more.
1084
      g_log<<Logger::Info<<msgPrefix<<"Update completed, 0 changes, rolling back."<<endl;
176✔
1085
      di.backend->abortTransaction();
176✔
1086
    }
176✔
1087
    return RCode::NoError; //rfc 2136 3.4.2.5
1,986✔
1088
  }
1,986✔
1089
  catch (SSqlException &e) {
2,074✔
1090
    g_log<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
×
1091
    di.backend->abortTransaction();
×
1092
    return RCode::ServFail;
×
1093
  }
×
1094
  catch (DBException &e) {
2,074✔
1095
    g_log<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1096
    di.backend->abortTransaction();
×
1097
    return RCode::ServFail;
×
1098
  }
×
1099
  catch (PDNSException &e) {
2,074✔
1100
    g_log<<Logger::Error<<msgPrefix<<"Caught PDNSException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1101
    di.backend->abortTransaction();
×
1102
    return RCode::ServFail;
×
1103
  }
×
1104
  catch(std::exception &e) {
2,074✔
1105
    g_log<<Logger::Error<<msgPrefix<<"Caught std:exception: "<<e.what()<<"; Sending ServFail!"<<endl;
×
1106
    di.backend->abortTransaction();
×
1107
    return RCode::ServFail;
×
1108
  }
×
1109
  catch (...) {
2,074✔
1110
    g_log<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
×
1111
    di.backend->abortTransaction();
×
1112
    return RCode::ServFail;
×
1113
  }
×
1114
}
2,074✔
1115

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

1122
  uint32_t oldSerial = sd.serial;
1,766✔
1123

1124
  vector<string> soaEdit2136Setting;
1,766✔
1125
  B.getDomainMetadata(di->zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
1,766✔
1126
  string soaEdit2136 = "DEFAULT";
1,766✔
1127
  string soaEdit;
1,766✔
1128
  if (!soaEdit2136Setting.empty()) {
1,766!
1129
    soaEdit2136 = soaEdit2136Setting[0];
×
1130
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
×
1131
      if (soaEditSetting.empty()) {
×
1132
        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;
×
1133
        soaEdit2136 = "DEFAULT";
×
1134
      } else
×
1135
        soaEdit = soaEditSetting;
×
1136
    }
×
1137
  }
×
1138

1139
  DNSResourceRecord rr;
1,766✔
1140
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
1,766!
1141
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
1,766✔
1142
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
1,766✔
1143

1144
    //Correct ordername + auth flag
1145
    DNSName ordername;
1,766✔
1146
    if (haveNSEC3) {
1,766✔
1147
      if (!narrow) {
968✔
1148
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
660✔
1149
      }
660✔
1150
    } else { // NSEC
968✔
1151
      ordername = rr.qname.makeRelative(di->zone);
798✔
1152
    }
798✔
1153
    di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true, QType::ANY, haveNSEC3 && !narrow);
1,766✔
1154
  }
1,766✔
1155
}
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