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

PowerDNS / pdns / 19347150143

13 Nov 2025 04:36PM UTC coverage: 61.588% (-11.5%) from 73.059%
19347150143

push

github

web-flow
Merge pull request #16494 from jsoref/codeql-unused-loop-iterator-name

Codeql unused loop iterator name

73081 of 185220 branches covered (39.46%)

Branch coverage included in aggregate %.

155550 of 186007 relevant lines covered (83.63%)

7024283.57 hits per line

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

0.0
/pdns/rfc2136handler.cc
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22

23
#ifdef HAVE_CONFIG_H
24
#include "config.h"
25
#endif
26
#include "dnswriter.hh"
27
#include "packethandler.hh"
28
#include "qtype.hh"
29
#include "dnspacket.hh"
30
#include "auth-caches.hh"
×
31
#include "statbag.hh"
×
32
#include "dnsseckeeper.hh"
×
33
#include "base64.hh"
34
#include "base32.hh"
35

×
36
#include "misc.hh"
×
37
#include "arguments.hh"
38
#include "resolver.hh"
×
39
#include "dns_random.hh"
×
40
#include "backends/gsql/ssql.hh"
×
41
#include "communicator.hh"
×
42
#include "query-local-address.hh"
×
43
#include "gss_context.hh"
×
44
#include "auth-main.hh"
×
45

×
46
std::mutex PacketHandler::s_rfc2136lock;
×
47

48
// Context data for RFC2136 operation
49
struct updateContext {
×
50
  DomainInfo di{};
×
51
  bool isPresigned{false};
×
52

×
53
  // The following may be modified
×
54
  bool narrow{false};
×
55
  bool haveNSEC3{false};
56
  NSEC3PARAMRecordContent ns3pr{};
57
  bool updatedSerial{false};
×
58

×
59
  // Logging-related fields
×
60
  std::string msgPrefix;
×
61
};
×
62

×
63
static void increaseSerial(const string& soaEditSetting, const updateContext& ctx);
64

×
65
// Implement section 3.2.1 and 3.2.2 of RFC2136
×
66
// NOLINTNEXTLINE(readability-identifier-length)
67
static int checkUpdatePrerequisites(const DNSRecord* rr, DomainInfo* di)
68
{
69
  if (rr->d_ttl != 0) {
×
70
    return RCode::FormErr;
71
  }
×
72

×
73
  // 3.2.1 and 3.2.2 check content length.
×
74
  if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_clen != 0) {
×
75
    return RCode::FormErr;
×
76
  }
77

×
78
  bool foundRecord = false;
×
79
  DNSResourceRecord rec;
×
80
  di->backend->lookup(QType(QType::ANY), rr->d_name, di->id);
81
  while (di->backend->get(rec)) {
×
82
    if (rec.qtype.getCode() == QType::ENT) {
×
83
      continue;
×
84
    }
85
    if ((rr->d_type != QType::ANY && rec.qtype == rr->d_type) || rr->d_type == QType::ANY) {
×
86
      foundRecord = true;
×
87
      di->backend->lookupEnd();
×
88
      break;
89
    }
×
90
  }
×
91

×
92
  // Section 3.2.1
93
  if (rr->d_class == QClass::ANY && !foundRecord) {
×
94
    if (rr->d_type == QType::ANY) {
×
95
      return RCode::NXDomain;
×
96
    }
97
    if (rr->d_type != QType::ANY) {
×
98
      return RCode::NXRRSet;
×
99
    }
100
  }
101

102
  // Section 3.2.2
103
  if (rr->d_class == QClass::NONE && foundRecord) {
×
104
    if (rr->d_type == QType::ANY) {
×
105
      return RCode::YXDomain;
106
    }
×
107
    if (rr->d_type != QType::ANY) {
×
108
      return RCode::YXRRSet;
×
109
    }
×
110
  }
111

×
112
  return RCode::NoError;
×
113
}
×
114

×
115
// Method implements section 3.4.1 of RFC2136
116
// NOLINTNEXTLINE(readability-identifier-length)
×
117
static int checkUpdatePrescan(const DNSRecord* rr)
×
118
{
×
119
  // The RFC stats that d_class != ZCLASS, but we only support the IN class.
×
120
  if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY) {
×
121
    return RCode::FormErr;
122
  }
123

×
124
  auto qtype = QType(rr->d_type);
×
125

×
126
  if (!qtype.isSupportedType()) {
×
127
    return RCode::FormErr;
128
  }
×
129

×
130
  if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_ttl != 0) {
×
131
    return RCode::FormErr;
×
132
  }
×
133

134
  if (rr->d_class == QClass::ANY && rr->d_clen != 0) {
×
135
    return RCode::FormErr;
×
136
  }
×
137

×
138
  if (qtype.isMetadataType()) {
×
139
    return RCode::FormErr;
140
  }
×
141

×
142
  if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY) {
×
143
    return RCode::FormErr;
×
144
  }
×
145

×
146
  return RCode::NoError;
147
}
148

149
// Implements section 3.4.2 of RFC2136
150
// Due to large complexity, this is stuck in multiple routines.
×
151

×
152
static bool mayPerformUpdate(const DNSRecord* rr, const updateContext& ctx) // NOLINT(readability-identifier-length)
×
153
{
×
154
  auto rrType = QType(rr->d_type);
×
155

156
  if (rrType == QType::NSEC || rrType == QType::NSEC3) {
×
157
    g_log << Logger::Warning << ctx.msgPrefix << "Trying to add/update/delete " << rr->d_name << "|" << rrType.toString() << ". These are generated records, ignoring!" << endl;
×
158
    return false;
×
159
  }
×
160

×
161
  if (!ctx.isPresigned && rrType == QType::RRSIG) {
×
162
    g_log << Logger::Warning << ctx.msgPrefix << "Trying to add/update/delete " << rr->d_name << "|" << rrType.toString() << " in non-presigned zone, ignoring!" << endl;
×
163
    return false;
×
164
  }
×
165

×
166
  if ((rrType == QType::NSEC3PARAM || rrType == QType::DNSKEY) && rr->d_name != ctx.di.zone.operator const DNSName&()) {
×
167
    g_log << Logger::Warning << ctx.msgPrefix << "Trying to add/update/delete " << rr->d_name << "|" << rrType.toString() << ", " << rrType.toString() << " must be at zone apex, ignoring!" << endl;
×
168
    return false;
×
169
  }
×
170

×
171
  return true;
×
172
}
173

174
// 3.4.2.2 QClass::IN means insert or update
×
175
// Caller has checked that we are allowed to insert the record and has handled
×
176
// the NSEC3PARAM case already.
×
177
// ctx is not const, may update updateSerial
×
178
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
×
179
static uint performInsert(const DNSRecord* rr, updateContext& ctx, vector<DNSResourceRecord>& rrset, set<DNSName>& insnonterm, set<DNSName>& delnonterm) // NOLINT(readability-identifier-length)
×
180
{
×
181
  uint changedRecords = 0;
×
182
  DNSResourceRecord rec;
×
183
  auto rrType = QType(rr->d_type);
×
184

×
185
  bool foundRecord = false;
×
186
  ctx.di.backend->lookup(rrType, rr->d_name, ctx.di.id);
×
187
  while (ctx.di.backend->get(rec)) {
×
188
    rrset.push_back(rec);
×
189
    foundRecord = true;
×
190
  }
191

192
  if (foundRecord) {
×
193
    switch (rrType) {
×
194
    case QType::SOA: {
×
195
      // SOA updates require the serial to be higher than the current
×
196
      SOAData sdOld;
×
197
      SOAData sdUpdate;
×
198
      DNSResourceRecord* oldRec = &rrset.front();
×
199
      fillSOAData(oldRec->content, sdOld);
×
200
      oldRec->setContent(rr->getContent()->getZoneRepresentation());
×
201
      fillSOAData(oldRec->content, sdUpdate);
×
202
      if (rfc1982LessThan(sdOld.serial, sdUpdate.serial)) {
×
203
        ctx.di.backend->replaceRRSet(ctx.di.id, oldRec->qname, oldRec->qtype, rrset);
×
204
        ctx.updatedSerial = true;
×
205
        changedRecords++;
×
206
        g_log << Logger::Notice << ctx.msgPrefix << "Replacing SOA record " << rr->d_name << "|" << rrType.toString() << endl;
×
207
      }
×
208
      else {
×
209
        g_log << Logger::Notice << ctx.msgPrefix << "Provided serial (" << sdUpdate.serial << ") is older than the current serial (" << sdOld.serial << "), ignoring SOA update." << endl;
×
210
      }
×
211
    } break;
×
212
    case QType::CNAME: {
×
213
      // It's not possible to have multiple CNAME's with the same NAME. So we always update.
×
214
      int changedCNames = 0;
×
215
      for (auto& i : rrset) { // NOLINT(readability-identifier-length)
×
216
        if (i.ttl != rr->d_ttl || i.content != rr->getContent()->getZoneRepresentation()) {
×
217
          i.ttl = rr->d_ttl;
×
218
          i.setContent(rr->getContent()->getZoneRepresentation());
×
219
          changedCNames++;
×
220
        }
×
221
      }
×
222
      if (changedCNames > 0) {
×
223
        ctx.di.backend->replaceRRSet(ctx.di.id, rr->d_name, rrType, rrset);
×
224
        g_log << Logger::Notice << ctx.msgPrefix << "Replacing CNAME record " << rr->d_name << "|" << rrType.toString() << endl;
225
        changedRecords += changedCNames;
226
      }
227
      else {
×
228
        g_log << Logger::Notice << ctx.msgPrefix << "Replace for CNAME record " << rr->d_name << "|" << rrType.toString() << " requested, but no changes made." << endl;
×
229
      }
230
    } break;
×
231
    default: {
×
232
      // In any other case, we must check if the TYPE and RDATA match to provide an update (which effectively means a update of TTL)
×
233
      int updateTTL = 0;
×
234
      foundRecord = false;
235
      bool lowerCase = false;
×
236
      switch (rrType.getCode()) {
×
237
      case QType::MX:
×
238
      case QType::PTR:
×
239
      case QType::SRV:
×
240
        lowerCase = true;
×
241
        break;
×
242
      }
×
243
      string content = rr->getContent()->getZoneRepresentation();
×
244
      if (lowerCase) {
×
245
        content = toLower(content);
×
246
      }
×
247
      for (auto& i : rrset) { // NOLINT(readability-identifier-length)
×
248
        if (rrType != i.qtype.getCode()) {
×
249
          continue;
×
250
        }
×
251
        if (!foundRecord) {
×
252
          string icontent = i.getZoneRepresentation();
×
253
          if (lowerCase) {
×
254
            icontent = toLower(icontent);
×
255
          }
256
          if (icontent == content) {
×
257
            foundRecord = true;
×
258
          }
259
        }
260
        if (i.ttl != rr->d_ttl) {
×
261
          i.ttl = rr->d_ttl;
×
262
          updateTTL++;
×
263
        }
×
264
      }
×
265
      if (updateTTL > 0) {
×
266
        ctx.di.backend->replaceRRSet(ctx.di.id, rr->d_name, rrType, rrset);
267
        g_log << Logger::Notice << ctx.msgPrefix << "Updating TTLs for " << rr->d_name << "|" << rrType.toString() << endl;
268
        changedRecords += updateTTL;
269
      }
270
      else if (foundRecord) {
×
271
        g_log << Logger::Notice << ctx.msgPrefix << "Replace for recordset " << rr->d_name << "|" << rrType.toString() << " requested, but no changes made." << endl;
272
      }
×
273
    } break;
×
274
    }
275

×
276
    // ReplaceRRSet dumps our ordername and auth flag, so we need to correct it if we have changed records.
×
277
    // We can take the auth flag from the first RR in the set, as the name is different, so should the auth be.
278
    if (changedRecords > 0) {
×
279
      bool auth = rrset.front().auth;
×
280

×
281
      if (ctx.haveNSEC3) {
×
282
        DNSName ordername;
×
283
        if (!ctx.narrow) {
×
284
          ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, rr->d_name)));
×
285
        }
×
286

×
287
        if (ctx.narrow) {
×
288
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), auth, QType::ANY, false);
289
        }
×
290
        else {
×
291
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, auth, QType::ANY, true);
×
292
        }
×
293
        if (!auth || rrType == QType::DS) {
×
294
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::NS, !ctx.narrow);
×
295
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, !ctx.narrow);
296
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, !ctx.narrow);
×
297
        }
×
298
      }
×
299
      else { // NSEC
×
300
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, rr->d_name.makeRelative(ctx.di.zone), auth, QType::ANY, false);
×
301
        if (!auth || rrType == QType::DS) {
×
302
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, false);
×
303
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, false);
×
304
        }
×
305
      }
×
306
    }
307
  } // if (foundRecord)
×
308

×
309
  // If we haven't found a record that matches, we must add it.
310
  if (!foundRecord) {
×
311
    g_log << Logger::Notice << ctx.msgPrefix << "Adding record " << rr->d_name << "|" << rrType.toString() << endl;
×
312
    delnonterm.insert(rr->d_name); // always remove any ENT's in the place where we're going to add a record.
×
313
    auto newRec = DNSResourceRecord::fromWire(*rr);
×
314
    newRec.domain_id = ctx.di.id;
315
    newRec.auth = (rr->d_name == ctx.di.zone.operator const DNSName&() || rrType.getCode() != QType::NS);
×
316
    ctx.di.backend->feedRecord(newRec, DNSName());
×
317
    changedRecords++;
×
318

319
    // because we added a record, we need to fix DNSSEC data.
×
320
    DNSName shorter(rr->d_name);
×
321
    bool auth = newRec.auth;
×
322
    bool fixDS = (rrType == QType::DS);
×
323

×
324
    if (ctx.di.zone.operator const DNSName&() != shorter) { // Everything at APEX is auth=1 && no ENT's
×
325
      do {
×
326
        if (ctx.di.zone.operator const DNSName&() == shorter) {
×
327
          break;
×
328
        }
×
329

×
330
        bool foundShorter = false;
×
331
        ctx.di.backend->lookup(QType(QType::ANY), shorter, ctx.di.id);
332
        while (ctx.di.backend->get(rec)) {
×
333
          if (rec.qname == rr->d_name && rec.qtype == QType::DS) {
×
334
            fixDS = true;
×
335
          }
×
336
          if (shorter != rr->d_name) {
×
337
            foundShorter = true;
×
338
          }
339
          if (rec.qtype == QType::NS) { // are we inserting below a delegate?
×
340
            auth = false;
×
341
          }
342
        }
×
343

×
344
        if (!foundShorter && auth && shorter != rr->d_name) { // haven't found any record at current level, insert ENT.
×
345
          insnonterm.insert(shorter);
×
346
        }
×
347
        if (foundShorter) {
×
348
          break; // if we find a shorter record, we can stop searching
×
349
        }
×
350
      } while (shorter.chopOff());
×
351
    }
×
352

×
353
    if (ctx.haveNSEC3) {
×
354
      DNSName ordername;
×
355
      if (!ctx.narrow) {
×
356
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, rr->d_name)));
357
      }
×
358

×
359
      if (ctx.narrow) {
×
360
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), auth, QType::ANY, false);
×
361
      }
362
      else {
×
363
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, auth, QType::ANY, true);
364
      }
×
365

×
366
      if (fixDS) {
×
367
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, true, QType::DS, !ctx.narrow);
×
368
      }
369

370
      if (!auth) {
×
371
        if (ctx.ns3pr.d_flags != 0) {
×
372
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::NS, !ctx.narrow);
×
373
        }
×
374
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, !ctx.narrow);
×
375
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, !ctx.narrow);
×
376
      }
×
377
    }
×
378
    else { // NSEC
×
379
      DNSName ordername = rr->d_name.makeRelative(ctx.di.zone);
×
380
      ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, auth, QType::ANY, false);
381
      if (fixDS) {
×
382
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, true, QType::DS, false);
383
      }
×
384
      if (!auth) {
×
385
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, false);
386
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, false);
×
387
      }
388
    }
389

390
    // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
×
391
    // Auth can only be false when the rr->d_name is not the zone
×
392
    if (!auth && rrType == QType::NS) {
×
393
      DLOG(g_log << ctx.msgPrefix << "Going to fix auth flags below " << rr->d_name << endl);
×
394
      insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
×
395
      vector<DNSName> qnames;
×
396
      ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
×
397
      while (ctx.di.backend->get(rec)) {
×
398
        if (rec.qtype.getCode() != QType::ENT && rec.qtype.getCode() != QType::DS && rr->d_name != rec.qname) { // Skip ENT, DS and our already corrected record.
×
399
          qnames.push_back(rec.qname);
400
        }
401
      }
×
402
      for (const auto& qname : qnames) {
×
403
        if (ctx.haveNSEC3) {
×
404
          DNSName ordername;
×
405
          if (!ctx.narrow) {
×
406
            ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, qname)));
407
          }
×
408

×
409
          if (ctx.narrow) {
×
410
            ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, DNSName(), auth, QType::ANY, false);
×
411
          }
×
412
          else {
×
413
            ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, ordername, auth, QType::ANY, true);
×
414
          }
415

416
          if (ctx.ns3pr.d_flags != 0) {
×
417
            ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, DNSName(), false, QType::NS, !ctx.narrow);
×
418
          }
×
419
        }
×
420
        else { // NSEC
×
421
          DNSName ordername = DNSName(qname).makeRelative(ctx.di.zone);
×
422
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, ordername, false, QType::NS, false);
×
423
        }
×
424

×
425
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, DNSName(), false, QType::A, ctx.haveNSEC3 && !ctx.narrow);
×
426
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, qname, DNSName(), false, QType::AAAA, ctx.haveNSEC3 && !ctx.narrow);
×
427
      }
×
428
    }
×
429
  }
×
430

×
431
  return changedRecords;
432
}
433

434
// 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
×
435
// the code that calls this performUpdate().
×
436
// Caller has checked that we are allowed to delete the record and has handled
×
437
// the NSEC3PARAM case already.
×
438
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
×
439
static uint performDelete(const DNSRecord* rr, const updateContext& ctx, vector<DNSResourceRecord>& rrset, set<DNSName>& insnonterm, set<DNSName>& delnonterm) // NOLINT(readability-identifier-length)
×
440
{
×
441
  vector<DNSResourceRecord> recordsToDelete;
×
442
  DNSResourceRecord rec;
443
  auto rrType = QType(rr->d_type);
×
444

×
445
  ctx.di.backend->lookup(rrType, rr->d_name, ctx.di.id);
×
446
  while (ctx.di.backend->get(rec)) {
×
447
    if (rr->d_class == QClass::ANY) { // 3.4.2.3
×
448
      if (rec.qname == ctx.di.zone.operator const DNSName&() && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) { // Never delete all SOA and NS's
×
449
        rrset.push_back(rec);
450
      }
×
451
      else {
×
452
        recordsToDelete.push_back(rec);
×
453
      }
×
454
    }
×
455
    if (rr->d_class == QClass::NONE) { // 3.4.2.4
×
456
      auto repr = rec.getZoneRepresentation();
×
457
      if (rec.qtype == QType::TXT) {
×
458
        DLOG(g_log << ctx.msgPrefix << "Adjusting TXT content from [" << repr << "]" << endl);
×
459
        auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
460
        auto ser = drc->serialize(rec.qname, true, true);
×
461
        auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser); // NOLINT(readability-identifier-length)
×
462
        repr = rc->getZoneRepresentation(true);
463
        DLOG(g_log << ctx.msgPrefix << "Adjusted TXT content to [" << repr << "]" << endl);
×
464
      }
×
465
      DLOG(g_log << ctx.msgPrefix << "Matching RR in RRset - (adjusted) representation from request=[" << repr << "], rr->getContent()->getZoneRepresentation()=[" << rr->getContent()->getZoneRepresentation() << "]" << endl);
×
466
      if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation()) {
×
467
        recordsToDelete.push_back(rec);
×
468
      }
×
469
      else {
×
470
        rrset.push_back(rec);
×
471
      }
472
    }
473
  }
×
474

475
  if (recordsToDelete.empty()) {
×
476
    g_log << Logger::Notice << ctx.msgPrefix << "Deletion for record " << rr->d_name << "|" << rrType.toString() << " requested, but not found." << endl;
×
477
    return 0;
×
478
  }
×
479

×
480
  ctx.di.backend->replaceRRSet(ctx.di.id, rr->d_name, rrType, rrset);
×
481
  g_log << Logger::Notice << ctx.msgPrefix << "Deleting record " << rr->d_name << "|" << rrType.toString() << endl;
×
482

×
483
  // If we've removed a delegate, we need to reset ordername/auth for some records.
×
484
  if (rrType == QType::NS && rr->d_name != ctx.di.zone.operator const DNSName&()) {
×
485
    vector<DNSName> belowOldDelegate;
×
486
    vector<DNSName> nsRecs;
487
    vector<DNSName> updateAuthFlag;
×
488
    ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
489
    while (ctx.di.backend->get(rec)) {
×
490
      if (rec.qtype.getCode() != QType::ENT) { // skip ENT records, they are always auth=false
×
491
        belowOldDelegate.push_back(rec.qname);
×
492
      }
×
493
      if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name) {
×
494
        nsRecs.push_back(rec.qname);
×
495
      }
496
    }
×
497

498
    for (auto& belowOldDel : belowOldDelegate) {
×
499
      bool isBelowDelegate = false;
500
      for (const auto& ns : nsRecs) { // NOLINT(readability-identifier-length)
×
501
        if (ns.isPartOf(belowOldDel)) {
×
502
          isBelowDelegate = true;
×
503
          break;
504
        }
×
505
      }
×
506
      if (!isBelowDelegate) {
×
507
        updateAuthFlag.push_back(belowOldDel);
×
508
      }
×
509
    }
×
510

×
511
    for (const auto& changeRec : updateAuthFlag) {
×
512
      DNSName ordername;
513
      if (ctx.haveNSEC3) {
×
514
        if (!ctx.narrow) {
×
515
          ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, changeRec)));
516
        }
517
      }
×
518
      else { // NSEC
519
        ordername = changeRec.makeRelative(ctx.di.zone);
×
520
      }
×
521
      ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, changeRec, ordername, true, QType::ANY, ctx.haveNSEC3 && !ctx.narrow);
×
522
    }
523
  }
524

525
  // Fix ENT records.
×
526
  // We must check if we have a record below the current level and if we removed the 'last' record
×
527
  // on that level. If so, we must insert an ENT record.
×
528
  // 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.
×
529
  bool foundDeeper = false;
×
530
  bool foundOtherWithSameName = false;
×
531
  ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
×
532
  while (ctx.di.backend->get(rec)) {
×
533
    if (rec.qname == rr->d_name && count(recordsToDelete.begin(), recordsToDelete.end(), rec) == 0) {
×
534
      foundOtherWithSameName = true;
×
535
    }
×
536
    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
×
537
      foundDeeper = true;
538
    }
539
  }
540

×
541
  if (foundDeeper && !foundOtherWithSameName) {
×
542
    insnonterm.insert(rr->d_name);
543
  }
×
544
  else if (!foundOtherWithSameName) {
×
545
    // If we didn't have to insert an ENT, we might have deleted a record at very deep level
×
546
    // and we must then clean up the ENT's above the deleted record.
547
    DNSName shorter(rr->d_name);
×
548
    while (shorter != ctx.di.zone.operator const DNSName&()) {
×
549
      shorter.chopOff();
×
550
      bool foundRealRR = false;
×
551
      bool foundEnt = false;
552

×
553
      // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
×
554
      // consider these non ENT-records:
555
      // b.c.d.e.test.com
×
556
      // b.d.e.test.com
×
557
      // 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.
×
558
      // At that point we can stop deleting ENT's because the tree is in tact again.
559
      ctx.di.backend->listSubZone(ZoneName(shorter), ctx.di.id);
×
560

×
561
      while (ctx.di.backend->get(rec)) {
×
562
        if (rec.qtype.getCode() != QType::ENT) {
×
563
          foundRealRR = true;
×
564
        }
565
        else {
×
566
          foundEnt = true;
×
567
        }
568
      }
×
569
      if (!foundRealRR) {
×
570
        if (foundEnt) { // only delete the ENT if we actually found one.
×
571
          delnonterm.insert(shorter);
×
572
        }
×
573
      }
×
574
      else {
×
575
        break;
576
      }
×
577
    }
×
578
  }
×
579

×
580
  return recordsToDelete.size();
581
}
×
582

×
583
static void updateENT(const updateContext& ctx, set<DNSName>& insnonterm, set<DNSName>& delnonterm)
×
584
{
×
585
  if (insnonterm.empty() && delnonterm.empty()) {
×
586
    return;
×
587
  }
×
588

×
589
  DLOG(g_log << ctx.msgPrefix << "Updating ENT records - " << insnonterm.size() << "|" << delnonterm.size() << endl);
×
590
  ctx.di.backend->updateEmptyNonTerminals(ctx.di.id, insnonterm, delnonterm, false);
×
591
  for (const auto& insert : insnonterm) {
×
592
    string hashed;
593
    if (ctx.haveNSEC3) {
×
594
      DNSName ordername;
×
595
      if (!ctx.narrow) {
×
596
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, insert)));
×
597
      }
×
598
      ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, insert, ordername, true, QType::ANY, !ctx.narrow);
×
599
    }
×
600
  }
×
601
}
×
602

×
603
static uint performUpdate(DNSSECKeeper& dsk, const DNSRecord* rr, updateContext& ctx) // NOLINT(readability-identifier-length)
×
604
{
×
605
  if (!mayPerformUpdate(rr, ctx)) {
×
606
    return 0;
×
607
  }
×
608

609
  auto rrType = QType(rr->d_type);
×
610

×
611
  // Decide which action to take.
×
612
  // 3.4.2.2 QClass::IN means insert or update
×
613
  bool insertAction = rr->d_class == QClass::IN;
×
614
  bool deleteAction = (rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA; // never delete a SOA.
×
615

×
616
  if (!insertAction && !deleteAction) {
×
617
    return 0; // nothing to do!
×
618
  }
×
619

×
620
  // Special processing for NSEC3PARAM
×
621
  if (rrType == QType::NSEC3PARAM) {
×
622
    if (insertAction) {
×
623
      g_log << Logger::Notice << ctx.msgPrefix << "Adding/updating NSEC3PARAM for zone, resetting ordernames." << endl;
×
624

×
625
      ctx.ns3pr = NSEC3PARAMRecordContent(rr->getContent()->getZoneRepresentation(), ctx.di.zone);
×
626
      // adding a NSEC3 will cause narrow mode to be dropped, as you cannot specify that in a NSEC3PARAM record
×
627
      ctx.narrow = false;
×
628
      dsk.setNSEC3PARAM(ctx.di.zone, ctx.ns3pr, ctx.narrow);
×
629
      ctx.haveNSEC3 = true;
630
    }
631
    else {
×
632
      g_log << Logger::Notice << ctx.msgPrefix << "Deleting NSEC3PARAM from zone, resetting ordernames." << endl;
×
633
      // Be sure to use a ZoneName with a variant matching the domain we are
×
634
      // working on, for the sake of unsetNSEC3PARAM.
×
635
      ZoneName zonename(rr->d_name, ctx.di.zone.getVariant());
×
636
      if (rr->d_class == QClass::ANY) {
×
637
        dsk.unsetNSEC3PARAM(zonename);
×
638
      }
×
639
      else { // rr->d_class == QClass::NONE then
×
640
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), ctx.di.zone);
×
641
        if (ctx.haveNSEC3 && ctx.ns3pr.getZoneRepresentation() == nsec3rr.getZoneRepresentation()) {
×
642
          dsk.unsetNSEC3PARAM(zonename);
×
643
        }
×
644
        else {
×
645
          return 0;
646
        }
×
647
      }
×
648

×
649
      // Update NSEC3 variables, other RR's in this update package might need them as well.
×
650
      ctx.narrow = false;
×
651
      ctx.haveNSEC3 = false;
×
652
    }
×
653

×
654
    string error;
×
655
    string info;
×
656
    if (!dsk.rectifyZone(ctx.di.zone, error, info, false)) {
×
657
      throw PDNSException("Failed to rectify '" + ctx.di.zone.toLogString() + "': " + error);
×
658
    }
×
659
    return 1;
×
660
  }
×
661

662
  uint changedRecords = 0;
×
663
  vector<DNSResourceRecord> rrset;
664
  // used to (at the end) fix ENT records.
665
  set<DNSName> delnonterm;
×
666
  set<DNSName> insnonterm;
×
667

668
  if (insertAction) {
×
669
    DLOG(g_log << ctx.msgPrefix << "Add/Update record (QClass == IN) " << rr->d_name << "|" << rrType.toString() << endl);
×
670
    changedRecords = performInsert(rr, ctx, rrset, insnonterm, delnonterm);
671
  }
672
  else {
×
673
    DLOG(g_log << ctx.msgPrefix << "Deleting records: " << rr->d_name << "; QClass:" << rr->d_class << "; rrType: " << rrType.toString() << endl);
674
    changedRecords = performDelete(rr, ctx, rrset, insnonterm, delnonterm);
675
  }
×
676

×
677
  //Insert and delete ENT's
×
678
  updateENT(ctx, insnonterm, delnonterm);
×
679

680
  return changedRecords;
×
681
}
×
682

×
683
static int forwardPacket(UeberBackend& B, const updateContext& ctx, const DNSPacket& p) // NOLINT(readability-identifier-length)
684
{
685
  vector<string> forward;
×
686
  B.getDomainMetadata(p.qdomainzone, "FORWARD-DNSUPDATE", forward);
687

688
  if (forward.empty() && !::arg().mustDo("forward-dnsupdate")) {
×
689
    g_log << Logger::Notice << ctx.msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
690
    return RCode::Refused;
691
  }
692

×
693
  for (const auto& remote : ctx.di.primaries) {
×
694
    g_log << Logger::Notice << ctx.msgPrefix << "Forwarding packet to primary " << remote << endl;
×
695

696
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
697
      continue;
×
698
    }
×
699
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
700
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
701
    if (sock < 0) {
×
702
      g_log << Logger::Error << ctx.msgPrefix << "Error creating socket: " << stringerror() << endl;
×
703
      continue;
×
704
    }
×
705

×
706
    if (connect(sock, (const struct sockaddr*)&remote, remote.getSocklen()) < 0) { // NOLINT(cppcoreguidelines-pro-type-cstyle-cast): less ugly than a reinterpret_cast + const_cast combination which would require a linter annotation anyway
×
707
      g_log << Logger::Error << ctx.msgPrefix << "Failed to connect to " << remote.toStringWithPort() << ": " << stringerror() << endl;
×
708
      try {
×
709
        closesocket(sock);
×
710
      }
×
711
      catch (const PDNSException& e) {
×
712
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
713
      }
×
714
      continue;
×
715
    }
×
716

×
717
    DNSPacket l_forwardPacket(p);
×
718
    l_forwardPacket.setID(dns_random_uint16());
×
719
    l_forwardPacket.setRemote(&remote);
×
720
    uint16_t len = htons(l_forwardPacket.getString().length());
×
721
    string buffer((const char*)&len, 2); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast): less ugly than a reinterpret_cast which would require a linter annotation anyway
×
722
    buffer.append(l_forwardPacket.getString());
×
723
    if (write(sock, buffer.c_str(), buffer.length()) < 0) {
×
724
      g_log << Logger::Error << ctx.msgPrefix << "Unable to forward update message to " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
725
      try {
×
726
        closesocket(sock);
×
727
      }
×
728
      catch (const PDNSException& e) {
×
729
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
730
      }
731
      continue;
×
732
    }
×
733

×
734
    int res = waitForData(sock, 10, 0);
×
735
    if (res == 0) {
×
736
      g_log << Logger::Error << ctx.msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
737
      try {
738
        closesocket(sock);
739
      }
×
740
      catch (const PDNSException& e) {
×
741
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
742
      }
×
743
      continue;
×
744
    }
745
    if (res < 0) {
×
746
      g_log << Logger::Error << ctx.msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
747
      try {
×
748
        closesocket(sock);
×
749
      }
750
      catch (const PDNSException& e) {
×
751
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
752
      }
×
753
      continue;
754
    }
755

756
    std::array<unsigned char, 2> lenBuf{};
757
    ssize_t recvRes = recv(sock, lenBuf.data(), lenBuf.size(), 0);
×
758
    if (recvRes < 0 || static_cast<size_t>(recvRes) < lenBuf.size()) {
×
759
      g_log << Logger::Error << ctx.msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
760
      try {
×
761
        closesocket(sock);
762
      }
×
763
      catch (const PDNSException& e) {
×
764
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
765
      }
×
766
      continue;
×
767
    }
×
768
    size_t packetLen = lenBuf[0] * 256 + lenBuf[1];
769

770
    buffer.resize(packetLen);
×
771
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
772
    if (recvRes < 0) {
×
773
      g_log << Logger::Error << ctx.msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
774
      try {
775
        closesocket(sock);
×
776
      }
×
777
      catch (const PDNSException& e) {
×
778
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
779
      }
780
      continue;
×
781
    }
782
    try {
×
783
      closesocket(sock);
×
784
    }
785
    catch (const PDNSException& e) {
786
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
787
    }
788

×
789
    try {
790
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
791
      g_log << Logger::Info << ctx.msgPrefix << "Forward update message to " << remote.toStringWithPort() << ", result was RCode " << mdp.d_header.rcode << endl;
×
792
      return mdp.d_header.rcode;
×
793
    }
794
    catch (...) {
×
795
      g_log << Logger::Error << ctx.msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
796
      continue;
×
797
    }
×
798
  }
×
799
  g_log << Logger::Error << ctx.msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
800
  return RCode::ServFail;
801
}
×
802

×
803
static bool isUpdateAllowed(UeberBackend& UBackend, const updateContext& ctx, DNSPacket& packet)
×
804
{
×
805
  // Check permissions - IP based
×
806
  vector<string> allowedRanges;
×
807

×
808
  UBackend.getDomainMetadata(packet.qdomainzone, "ALLOW-DNSUPDATE-FROM", allowedRanges);
809
  if (!::arg()["allow-dnsupdate-from"].empty()) {
×
810
    stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t");
×
811
  }
×
812

×
813
  NetmaskGroup nmg;
×
814
  for (const auto& range : allowedRanges) {
×
815
    nmg.addMask(range);
×
816
  }
×
817

×
818
  if (!nmg.match(packet.getInnerRemote())) {
×
819
    g_log << Logger::Error << ctx.msgPrefix << "Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED" << endl;
820
    return false;
×
821
  }
822

×
823
  // Check permissions - TSIG based.
×
824
  vector<string> tsigKeys;
×
825
  UBackend.getDomainMetadata(packet.qdomainzone, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
826
  if (!tsigKeys.empty()) {
×
827
    bool validKey = false;
×
828

×
829
    TSIGRecordContent trc;
×
830
    DNSName inputkey;
×
831
    string message;
×
832
    if (!packet.getTSIGDetails(&trc, &inputkey)) {
×
833
      g_log << Logger::Error << ctx.msgPrefix << "TSIG key required, but packet does not contain key. Sending REFUSED" << endl;
×
834
      return false;
×
835
    }
×
836
#ifdef ENABLE_GSS_TSIG
×
837
    if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
838
      GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
839
      for (const auto& key : tsigKeys) {
×
840
        if (inputname.match(key)) {
×
841
          validKey = true;
×
842
          break;
843
        }
×
844
      }
×
845
    }
×
846
    else
847
#endif
848
    {
849
      for (const auto& key : tsigKeys) {
×
850
        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.
×
851
          validKey = true;
×
852
          break;
×
853
        }
×
854
      }
×
855
    }
×
856

×
857
    if (!validKey) {
×
858
      g_log << Logger::Error << ctx.msgPrefix << "TSIG key (" << inputkey << ") required, but no matching key found in domainmetadata, tried " << tsigKeys.size() << ". Sending REFUSED" << endl;
×
859
      return false;
×
860
    }
×
861
  }
×
862
  else if (::arg().mustDo("dnsupdate-require-tsig")) {
×
863
    g_log << Logger::Error << ctx.msgPrefix << "TSIG key required, but domain is not secured with TSIG. Sending REFUSED" << endl;
×
864
    return false;
865
  }
×
866

×
867
  if (tsigKeys.empty() && packet.d_havetsig) {
×
868
    g_log << Logger::Warning << ctx.msgPrefix << "TSIG is provided, but domain is not secured with TSIG. Processing continues" << endl;
×
869
  }
870

871
  return true;
872
}
873

874
static uint8_t updatePrereqCheck323(MOADNSParser& mdp, const updateContext& ctx)
875
{
876
  using rrSetKey_t = pair<DNSName, QType>;
×
877
  using rrVector_t = vector<DNSResourceRecord>;
878
  using RRsetMap_t = std::map<rrSetKey_t, rrVector_t>;
×
879
  RRsetMap_t preReqRRsets;
×
880

×
881
  for (const auto& rec : mdp.d_answers) {
×
882
    const DNSRecord* dnsRecord = &rec;
883
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
×
884
      // Last line of 3.2.3
×
885
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
×
886
        return RCode::FormErr;
×
887
      }
888

×
889
      if (dnsRecord->d_class == QClass::IN) {
×
890
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
×
891
        rrVector_t* vec = &preReqRRsets[key];
×
892
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
×
893
      }
×
894
    }
×
895
  }
896

897
  if (!preReqRRsets.empty()) {
×
898
    RRsetMap_t zoneRRsets;
899
    for (auto& preReqRRset : preReqRRsets) {
×
900
      rrSetKey_t rrSet = preReqRRset.first;
901
      rrVector_t* vec = &preReqRRset.second;
×
902

903
      DNSResourceRecord rec;
×
904
      ctx.di.backend->lookup(QType(QType::ANY), rrSet.first, ctx.di.id);
×
905
      size_t foundRR{0};
906
      size_t matchRR{0};
×
907
      while (ctx.di.backend->get(rec)) {
×
908
        if (rec.qtype == rrSet.second) {
×
909
          foundRR++;
×
910
          for (auto& rrItem : *vec) {
×
911
            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.
912
            if (rrItem == rec) {
×
913
              matchRR++;
×
914
            }
×
915
          }
×
916
        }
×
917
      }
×
918
      if (matchRR != foundRR || foundRR != vec->size()) {
×
919
        g_log << Logger::Error << ctx.msgPrefix << "Failed PreRequisites check (RRs differ), returning NXRRSet" << endl;
×
920
        return RCode::NXRRSet;
921
      }
×
922
    }
×
923
  }
×
924
  return RCode::NoError;
×
925
}
×
926

×
927
static uint8_t updateRecords(MOADNSParser& mdp, DNSSECKeeper& dsk, uint& changedRecords, const std::unique_ptr<AuthLua4>& update_policy_lua, DNSPacket& packet, updateContext& ctx)
×
928
{
×
929
  vector<const DNSRecord*> cnamesToAdd;
×
930
  vector<const DNSRecord*> nonCnamesToAdd;
931
  vector<const DNSRecord*> nsRRtoDelete;
×
932

×
933
  bool anyRecordProcessed{false};
×
934
  bool anyRecordAcceptedByLua{false};
935
  for (const auto& answer : mdp.d_answers) {
×
936
    const DNSRecord* dnsRecord = &answer;
×
937
    if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
×
938
      anyRecordProcessed = true;
×
939
      /* see if it's permitted by policy */
×
940
      if (update_policy_lua != nullptr) {
×
941
        if (!update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), ctx.di.zone.operator const DNSName&(), packet)) {
×
942
          g_log << Logger::Warning << ctx.msgPrefix << "Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy" << endl;
×
943
          continue;
×
944
        }
×
945
        g_log << Logger::Debug << ctx.msgPrefix << "Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy" << endl;
946
        anyRecordAcceptedByLua = true;
×
947
      }
×
948

×
949
      if (dnsRecord->d_class == QClass::NONE && dnsRecord->d_type == QType::NS && dnsRecord->d_name == ctx.di.zone.operator const DNSName&()) {
×
950
        nsRRtoDelete.push_back(dnsRecord);
×
951
      }
×
952
      else if (dnsRecord->d_class == QClass::IN && dnsRecord->d_ttl > 0) {
×
953
        if (dnsRecord->d_type == QType::CNAME) {
×
954
          cnamesToAdd.push_back(dnsRecord);
955
        }
×
956
        else {
×
957
          nonCnamesToAdd.push_back(dnsRecord);
×
958
        }
×
959
      }
×
960
      else {
×
961
        changedRecords += performUpdate(dsk, dnsRecord, ctx);
×
962
      }
×
963
    }
×
964
  }
×
965

×
966
  if (update_policy_lua != nullptr) {
×
967
    // If the Lua update policy script has been invoked, and has rejected
×
968
    // everything, better return Refused.
×
969
    if (anyRecordProcessed && !anyRecordAcceptedByLua) {
×
970
      return RCode::Refused;
×
971
    }
972
  }
973

×
974
  for (const auto& resrec : cnamesToAdd) {
×
975
    DNSResourceRecord rec;
×
976
    ctx.di.backend->lookup(QType(QType::ANY), resrec->d_name, ctx.di.id);
×
977
    while (ctx.di.backend->get(rec)) {
×
978
      if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
×
979
        // leave database handle in a consistent state
×
980
        ctx.di.backend->lookupEnd();
×
981
        g_log << Logger::Warning << ctx.msgPrefix << "Refusing update for " << resrec->d_name << "/" << QType(resrec->d_type).toString() << ": Data other than CNAME exists for the same name" << endl;
×
982
        return RCode::Refused;
×
983
      }
×
984
    }
×
985
    changedRecords += performUpdate(dsk, resrec, ctx);
986
  }
×
987
  for (const auto& resrec : nonCnamesToAdd) {
×
988
    DNSResourceRecord rec;
×
989
    ctx.di.backend->lookup(QType(QType::CNAME), resrec->d_name, ctx.di.id);
×
990
    while (ctx.di.backend->get(rec)) {
×
991
      if (rec.qtype == QType::CNAME && resrec->d_type != QType::RRSIG) {
×
992
        // leave database handle in a consistent state
993
        ctx.di.backend->lookupEnd();
×
994
        g_log << Logger::Warning << ctx.msgPrefix << "Refusing update for " << resrec->d_name << "/" << QType(resrec->d_type).toString() << ": CNAME exists for the same name" << endl;
×
995
        return RCode::Refused;
996
      }
×
997
    }
×
998
    changedRecords += performUpdate(dsk, resrec, ctx);
×
999
  }
×
1000

1001
  if (!nsRRtoDelete.empty()) {
×
1002
    vector<DNSResourceRecord> nsRRInZone;
×
1003
    DNSResourceRecord rec;
×
1004
    ctx.di.backend->lookup(QType(QType::NS), ctx.di.zone.operator const DNSName&(), ctx.di.id);
×
1005
    while (ctx.di.backend->get(rec)) {
×
1006
      nsRRInZone.push_back(rec);
×
1007
    }
1008
    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)
×
1009
      for (auto& inZone : nsRRInZone) {
×
1010
        for (auto& resrec : nsRRtoDelete) {
×
1011
          if (inZone.getZoneRepresentation() == resrec->getContent()->getZoneRepresentation()) {
×
1012
            changedRecords += performUpdate(dsk, resrec, ctx);
×
1013
          }
1014
        }
1015
      }
×
1016
    }
×
1017
  }
×
1018

×
1019
  return RCode::NoError;
×
1020
}
×
1021

×
1022
int PacketHandler::processUpdate(DNSPacket& packet)
1023
{
×
1024
  if (!::arg().mustDo("dnsupdate")) {
×
1025
    return RCode::Refused;
1026
  }
×
1027

×
1028
  updateContext ctx{};
×
1029
  string msgPrefix = "UPDATE (" + std::to_string(packet.d.id) + ") from " + packet.getRemoteString() + " for " + packet.qdomainzone.toLogString() + ": ";
×
1030
  ctx.msgPrefix = std::move(msgPrefix);
×
1031

×
1032
  g_log << Logger::Info << ctx.msgPrefix << "Processing started." << endl;
×
1033

×
1034
  // if there is policy, we delegate all checks to it
×
1035
  if (this->d_update_policy_lua == nullptr) {
×
1036
    if (!isUpdateAllowed(B, ctx, packet)) {
×
1037
      return RCode::Refused;
×
1038
    }
×
1039
  }
×
1040

×
1041
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
1042
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
×
1043
  // variable names during the use of our MOADNSParser.
1044
  MOADNSParser mdp(false, packet.getString());
×
1045
  if (mdp.d_header.qdcount != 1) {
×
1046
    g_log << Logger::Warning << ctx.msgPrefix << "Zone Count is not 1, sending FormErr" << endl;
×
1047
    return RCode::FormErr;
×
1048
  }
×
1049

×
1050
  if (packet.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
×
1051
    g_log << Logger::Warning << ctx.msgPrefix << "Query ZTYPE is not SOA, sending FormErr" << endl;
×
1052
    return RCode::FormErr;
×
1053
  }
×
1054

×
1055
  if (packet.qclass != QClass::IN) {
×
1056
    g_log << Logger::Warning << ctx.msgPrefix << "Class is not IN, sending NotAuth" << endl;
×
1057
    return RCode::NotAuth;
1058
  }
1059

×
1060
  ctx.di.backend = nullptr;
×
1061
  if (!B.getDomainInfo(packet.qdomainzone, ctx.di) || (ctx.di.backend == nullptr)) {
×
1062
    g_log << Logger::Error << ctx.msgPrefix << "Can't determine backend for domain '" << packet.qdomainzone << "' (or backend does not support DNS update operation)" << endl;
×
1063
    return RCode::NotAuth;
1064
  }
1065
  // ctx.di field valid from now on
×
1066

×
1067
  if (ctx.di.kind == DomainInfo::Secondary) {
×
1068
    return forwardPacket(B, ctx, packet);
×
1069
  }
1070

×
1071
  // Check if all the records provided are within the zone
×
1072
  for (const auto& answer : mdp.d_answers) {
×
1073
    const DNSRecord* dnsRecord = &answer;
×
1074
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
×
1075
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
×
1076
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
×
1077
      continue;
1078
    }
1079

1080
    if (!dnsRecord->d_name.isPartOf(ctx.di.zone)) {
×
1081
      g_log << Logger::Error << ctx.msgPrefix << "Received update/record out of zone, sending NotZone." << endl;
1082
      return RCode::NotZone;
×
1083
    }
1084
  }
1085

1086
  auto lock = std::scoped_lock(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
1087
  g_log << Logger::Info << ctx.msgPrefix << "starting transaction." << endl;
1088
  if (!ctx.di.backend->startTransaction(packet.qdomainzone, UnknownDomainID)) { // Not giving the domain_id means that we do not delete the existing records.
×
1089
    g_log << Logger::Error << ctx.msgPrefix << "Backend for domain " << packet.qdomainzone << " does not support transaction. Can't do Update packet." << endl;
×
1090
    return RCode::NotImp;
1091
  }
1092

1093
  // 3.2.1 and 3.2.2 - Prerequisite check
1094
  for (const auto& answer : mdp.d_answers) {
×
1095
    const DNSRecord* dnsRecord = &answer;
×
1096
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
×
1097
      int res = checkUpdatePrerequisites(dnsRecord, &ctx.di);
1098
      if (res > 0) {
×
1099
        g_log << Logger::Error << ctx.msgPrefix << "Failed PreRequisites check for " << dnsRecord->d_name << ", returning " << RCode::to_s(res) << endl;
1100
        ctx.di.backend->abortTransaction();
1101
        return res;
1102
      }
1103
    }
1104
  }
1105

1106
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
1107
  if (auto rcode = updatePrereqCheck323(mdp, ctx); rcode != RCode::NoError) {
×
1108
    ctx.di.backend->abortTransaction();
1109
    return rcode;
1110
  }
1111

1112
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
1113
  try {
1114
    // 3.4.1 - Prescan section
1115
    for (const auto& answer : mdp.d_answers) {
×
1116
      const DNSRecord* dnsRecord = &answer;
1117
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
×
1118
        int res = checkUpdatePrescan(dnsRecord);
1119
        if (res > 0) {
×
1120
          g_log << Logger::Error << ctx.msgPrefix << "Failed prescan check, returning " << res << endl;
1121
          ctx.di.backend->abortTransaction();
1122
          return res;
1123
        }
1124
      }
1125
    }
1126

1127
    ctx.isPresigned = d_dk.isPresigned(ctx.di.zone);
1128
    ctx.narrow = false;
1129
    ctx.haveNSEC3 = d_dk.getNSEC3PARAM(ctx.di.zone, &ctx.ns3pr, &ctx.narrow);
1130
    ctx.updatedSerial = false;
1131
    // all ctx fields valid from now on
1132

1133
    string soaEditSetting;
1134
    d_dk.getSoaEdit(ctx.di.zone, soaEditSetting);
1135

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

1140
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
1141
    set<DNSName> cn; // NOLINT(readability-identifier-length)
1142
    set<DNSName> nocn;
1143
    for (const auto& rr : mdp.d_answers) { // NOLINT(readability-identifier-length)
×
1144
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
×
1145
        // Addition
1146
        if (rr.d_type == QType::CNAME) {
×
1147
          cn.insert(rr.d_name);
1148
        }
1149
        else if (rr.d_type != QType::RRSIG) {
×
1150
          nocn.insert(rr.d_name);
1151
        }
1152
      }
1153
    }
1154
    for (auto const& n : cn) { // NOLINT(readability-identifier-length)
×
1155
      if (nocn.count(n) > 0) {
×
1156
        g_log << Logger::Error << ctx.msgPrefix << "Refusing update, found CNAME and non-CNAME addition" << endl;
1157
        ctx.di.backend->abortTransaction();
1158
        return RCode::FormErr;
1159
      }
1160
    }
1161

1162
    uint changedRecords = 0;
1163
    if (auto rcode = updateRecords(mdp, d_dk, changedRecords, d_update_policy_lua, packet, ctx); rcode != RCode::NoError) {
×
1164
      ctx.di.backend->abortTransaction();
1165
      return rcode;
1166
    }
1167

1168
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
1169
    if (changedRecords != 0 && !ctx.updatedSerial) {
×
1170
      increaseSerial(soaEditSetting, ctx);
1171
      changedRecords++;
1172
    }
1173

1174
    if (changedRecords != 0) {
×
1175
      if (!ctx.di.backend->commitTransaction()) {
×
1176
        g_log << Logger::Error << ctx.msgPrefix << "Failed to commit updates!" << endl;
1177
        return RCode::ServFail;
1178
      }
1179

1180
      S.deposit("dnsupdate-changes", static_cast<int>(changedRecords));
1181

1182
      DNSSECKeeper::clearMetaCache(ctx.di.zone);
1183
      // Purge the records!
1184
      purgeAuthCaches(ctx.di.zone.operator const DNSName&().toString() + "$");
1185

1186
      // Notify secondaries
1187
      if (ctx.di.kind == DomainInfo::Primary) {
×
1188
        vector<string> notify;
1189
        B.getDomainMetadata(packet.qdomainzone, "NOTIFY-DNSUPDATE", notify);
1190
        if (!notify.empty() && notify.front() == "1") {
×
1191
          Communicator.notifyDomain(ctx.di.zone, &B);
1192
        }
1193
      }
1194

1195
      g_log << Logger::Info << ctx.msgPrefix << "Update completed, " << changedRecords << " changed records committed." << endl;
1196
    }
1197
    else {
1198
      //No change, no commit, we perform abort() because some backends might like this more.
1199
      g_log << Logger::Info << ctx.msgPrefix << "Update completed, 0 changes, rolling back." << endl;
1200
      ctx.di.backend->abortTransaction();
1201
    }
1202
    return RCode::NoError; //rfc 2136 3.4.2.5
1203
  }
1204
  catch (SSqlException& e) {
1205
    g_log << Logger::Error << ctx.msgPrefix << "Caught SSqlException: " << e.txtReason() << "; Sending ServFail!" << endl;
1206
    ctx.di.backend->abortTransaction();
1207
    return RCode::ServFail;
1208
  }
1209
  catch (DBException& e) {
1210
    g_log << Logger::Error << ctx.msgPrefix << "Caught DBException: " << e.reason << "; Sending ServFail!" << endl;
1211
    ctx.di.backend->abortTransaction();
1212
    return RCode::ServFail;
1213
  }
1214
  catch (PDNSException& e) {
1215
    g_log << Logger::Error << ctx.msgPrefix << "Caught PDNSException: " << e.reason << "; Sending ServFail!" << endl;
1216
    ctx.di.backend->abortTransaction();
1217
    return RCode::ServFail;
1218
  }
1219
  catch (std::exception& e) {
1220
    g_log << Logger::Error << ctx.msgPrefix << "Caught std:exception: " << e.what() << "; Sending ServFail!" << endl;
1221
    ctx.di.backend->abortTransaction();
1222
    return RCode::ServFail;
1223
  }
1224
  catch (...) {
1225
    g_log << Logger::Error << ctx.msgPrefix << "Caught unknown exception when performing update. Sending ServFail!" << endl;
1226
    ctx.di.backend->abortTransaction();
1227
    return RCode::ServFail;
1228
  }
1229
}
1230

1231
static void increaseSerial(const string& soaEditSetting, const updateContext& ctx)
1232
{
1233
  SOAData sd; // NOLINT(readability-identifier-length)
1234
  if (!ctx.di.backend->getSOA(ctx.di.zone, ctx.di.id, sd)) {
×
1235
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
1236
  }
1237

1238
  uint32_t oldSerial = sd.serial;
1239

1240
  vector<string> soaEdit2136Setting;
1241
  ctx.di.backend->getDomainMetadata(ctx.di.zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
1242
  string soaEdit2136 = "DEFAULT";
1243
  string soaEdit;
1244
  if (!soaEdit2136Setting.empty()) {
×
1245
    soaEdit2136 = soaEdit2136Setting[0];
1246
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136, "SOA-EDIT-INCREASE")) {
×
1247
      if (soaEditSetting.empty()) {
×
1248
        g_log << Logger::Error << ctx.msgPrefix << "Using " << soaEdit2136 << " for SOA-EDIT-DNSUPDATE increase on DNS update, but SOA-EDIT is not set for domain \"" << ctx.di.zone << "\". Using DEFAULT for SOA-EDIT-DNSUPDATE" << endl;
1249
        soaEdit2136 = "DEFAULT";
1250
      }
1251
      else {
1252
        soaEdit = soaEditSetting;
1253
      }
1254
    }
1255
  }
1256

1257
  DNSResourceRecord rr; // NOLINT(readability-identifier-length)
1258
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
×
1259
    ctx.di.backend->replaceRRSet(ctx.di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
1260
    g_log << Logger::Notice << ctx.msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
1261

1262
    //Correct ordername + auth flag
1263
    DNSName ordername;
1264
    if (ctx.haveNSEC3) {
×
1265
      if (!ctx.narrow) {
×
1266
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, rr.qname)));
1267
      }
1268
    }
1269
    else { // NSEC
1270
      ordername = rr.qname.makeRelative(ctx.di.zone);
1271
    }
1272
    ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr.qname, ordername, true, QType::ANY, ctx.haveNSEC3 && !ctx.narrow);
×
1273
  }
1274
}
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