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

PowerDNS / pdns / 19277975675

11 Nov 2025 08:40PM UTC coverage: 73.006% (-0.03%) from 73.033%
19277975675

push

github

web-flow
Merge pull request #16343 from miodvallat/bacf'

auth rfc2136: more churning

38283 of 63152 branches covered (60.62%)

Branch coverage included in aggregate %.

135 of 185 new or added lines in 1 file covered. (72.97%)

71 existing lines in 15 files now uncovered.

127566 of 164020 relevant lines covered (77.77%)

5303480.75 hits per line

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

73.97
/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
{
418✔
69
  if (rr->d_ttl != 0) {
418!
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) {
418!
75
    return RCode::FormErr;
×
76
  }
×
77

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

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

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

112
  return RCode::NoError;
308✔
113
}
352✔
114

115
// Method implements section 3.4.1 of RFC2136
116
// NOLINTNEXTLINE(readability-identifier-length)
117
static int checkUpdatePrescan(const DNSRecord* rr)
118
{
5,006✔
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) {
5,006!
121
    return RCode::FormErr;
×
122
  }
×
123

124
  auto qtype = QType(rr->d_type);
5,006✔
125

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

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

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

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

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

146
  return RCode::NoError;
4,984✔
147
}
5,006✔
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
{
4,852✔
154
  auto rrType = QType(rr->d_type);
4,852✔
155

156
  if (rrType == QType::NSEC || rrType == QType::NSEC3) {
4,852!
NEW
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) {
4,852!
NEW
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&()) {
4,852!
NEW
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;
4,852✔
172
}
4,852✔
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
{
3,600✔
181
  uint changedRecords = 0;
3,600✔
182
  DNSResourceRecord rec;
3,600✔
183
  auto rrType = QType(rr->d_type);
3,600✔
184

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

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

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

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

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

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

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

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

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

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

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

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

370
      if (!auth) {
1,826✔
371
        if (ctx.ns3pr.d_flags != 0) {
228✔
372
          ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::NS, !ctx.narrow);
152✔
373
        }
152✔
374
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, !ctx.narrow);
228✔
375
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, !ctx.narrow);
228✔
376
      }
228✔
377
    }
1,826✔
378
    else { // NSEC
1,510✔
379
      DNSName ordername = rr->d_name.makeRelative(ctx.di.zone);
1,510✔
380
      ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, auth, QType::ANY, false);
1,510✔
381
      if (fixDS) {
1,510✔
382
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, ordername, true, QType::DS, false);
30✔
383
      }
30✔
384
      if (!auth) {
1,510✔
385
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::A, false);
190✔
386
        ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, rr->d_name, DNSName(), false, QType::AAAA, false);
190✔
387
      }
190✔
388
    }
1,510✔
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) {
3,336✔
393
      DLOG(g_log << ctx.msgPrefix << "Going to fix auth flags below " << rr->d_name << endl);
242✔
394
      insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
242✔
395
      vector<DNSName> qnames;
242✔
396
      ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
242✔
397
      while (ctx.di.backend->get(rec)) {
726✔
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.
484✔
399
          qnames.push_back(rec.qname);
132✔
400
        }
132✔
401
      }
484✔
402
      for (const auto& qname : qnames) {
242✔
403
        if (ctx.haveNSEC3) {
132✔
404
          DNSName ordername;
72✔
405
          if (!ctx.narrow) {
72✔
406
            ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, qname)));
48✔
407
          }
48✔
408

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

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

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

431
  return changedRecords;
×
432
}
3,600✔
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
{
1,158✔
441
  vector<DNSResourceRecord> recordsToDelete;
1,158✔
442
  DNSResourceRecord rec;
1,158✔
443
  auto rrType = QType(rr->d_type);
1,158✔
444

445
  ctx.di.backend->lookup(rrType, rr->d_name, ctx.di.id);
1,158✔
446
  while (ctx.di.backend->get(rec)) {
4,736✔
447
    if (rr->d_class == QClass::ANY) { // 3.4.2.3
3,578✔
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
2,992!
449
        rrset.push_back(rec);
44✔
450
      }
44✔
451
      else {
2,948✔
452
        recordsToDelete.push_back(rec);
2,948✔
453
      }
2,948✔
454
    }
2,992✔
455
    if (rr->d_class == QClass::NONE) { // 3.4.2.4
3,578✔
456
      auto repr = rec.getZoneRepresentation();
586✔
457
      if (rec.qtype == QType::TXT) {
586✔
458
        DLOG(g_log << ctx.msgPrefix << "Adjusting TXT content from [" << repr << "]" << endl);
66✔
459
        auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
66✔
460
        auto ser = drc->serialize(rec.qname, true, true);
66✔
461
        auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser); // NOLINT(readability-identifier-length)
66✔
462
        repr = rc->getZoneRepresentation(true);
66✔
463
        DLOG(g_log << ctx.msgPrefix << "Adjusted TXT content to [" << repr << "]" << endl);
66✔
464
      }
66✔
465
      DLOG(g_log << ctx.msgPrefix << "Matching RR in RRset - (adjusted) representation from request=[" << repr << "], rr->getContent()->getZoneRepresentation()=[" << rr->getContent()->getZoneRepresentation() << "]" << endl);
586✔
466
      if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation()) {
586!
467
        recordsToDelete.push_back(rec);
410✔
468
      }
410✔
469
      else {
176✔
470
        rrset.push_back(rec);
176✔
471
      }
176✔
472
    }
586✔
473
  }
3,578✔
474

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

480
  ctx.di.backend->replaceRRSet(ctx.di.id, rr->d_name, rrType, rrset);
1,114✔
481
  g_log << Logger::Notice << ctx.msgPrefix << "Deleting record " << rr->d_name << "|" << rrType.toString() << endl;
1,114✔
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&()) {
1,114✔
485
    vector<DNSName> belowOldDelegate;
154✔
486
    vector<DNSName> nsRecs;
154✔
487
    vector<DNSName> updateAuthFlag;
154✔
488
    ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
154✔
489
    while (ctx.di.backend->get(rec)) {
396✔
490
      if (rec.qtype.getCode() != QType::ENT) { // skip ENT records, they are always auth=false
242!
491
        belowOldDelegate.push_back(rec.qname);
242✔
492
      }
242✔
493
      if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name) {
242!
494
        nsRecs.push_back(rec.qname);
22✔
495
      }
22✔
496
    }
242✔
497

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

511
    for (const auto& changeRec : updateAuthFlag) {
220✔
512
      DNSName ordername;
220✔
513
      if (ctx.haveNSEC3) {
220✔
514
        if (!ctx.narrow) {
120✔
515
          ordername = DNSName(toBase32Hex(hashQNameWithSalt(ctx.ns3pr, changeRec)));
80✔
516
        }
80✔
517
      }
120✔
518
      else { // NSEC
100✔
519
        ordername = changeRec.makeRelative(ctx.di.zone);
100✔
520
      }
100✔
521
      ctx.di.backend->updateDNSSECOrderNameAndAuth(ctx.di.id, changeRec, ordername, true, QType::ANY, ctx.haveNSEC3 && !ctx.narrow);
220✔
522
    }
220✔
523
  }
154✔
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;
1,114✔
530
  bool foundOtherWithSameName = false;
1,114✔
531
  ctx.di.backend->listSubZone(ZoneName(rr->d_name), ctx.di.id);
1,114✔
532
  while (ctx.di.backend->get(rec)) {
6,328✔
533
    if (rec.qname == rr->d_name && count(recordsToDelete.begin(), recordsToDelete.end(), rec) == 0) {
5,214!
534
      foundOtherWithSameName = true;
946✔
535
    }
946✔
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
5,214✔
537
      foundDeeper = true;
3,872✔
538
    }
3,872✔
539
  }
5,214✔
540

541
  if (foundDeeper && !foundOtherWithSameName) {
1,114✔
542
    insnonterm.insert(rr->d_name);
132✔
543
  }
132✔
544
  else if (!foundOtherWithSameName) {
982✔
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);
718✔
548
    while (shorter != ctx.di.zone.operator const DNSName&()) {
1,114!
549
      shorter.chopOff();
1,114✔
550
      bool foundRealRR = false;
1,114✔
551
      bool foundEnt = false;
1,114✔
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);
1,114✔
560

561
      while (ctx.di.backend->get(rec)) {
15,170✔
562
        if (rec.qtype.getCode() != QType::ENT) {
14,056✔
563
          foundRealRR = true;
12,150✔
564
        }
12,150✔
565
        else {
1,906✔
566
          foundEnt = true;
1,906✔
567
        }
1,906✔
568
      }
14,056✔
569
      if (!foundRealRR) {
1,114✔
570
        if (foundEnt) { // only delete the ENT if we actually found one.
396✔
571
          delnonterm.insert(shorter);
330✔
572
        }
330✔
573
      }
396✔
574
      else {
718✔
575
        break;
718✔
576
      }
718✔
577
    }
1,114✔
578
  }
718✔
579

580
  return recordsToDelete.size();
1,114✔
581
}
1,158✔
582

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

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

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

609
  auto rrType = QType(rr->d_type);
4,852✔
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;
4,852✔
614
  bool deleteAction = (rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA; // never delete a SOA.
4,852✔
615

616
  if (!insertAction && !deleteAction) {
4,852✔
617
    return 0; // nothing to do!
22✔
618
  }
22✔
619

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

625
      ctx.ns3pr = NSEC3PARAMRecordContent(rr->getContent()->getZoneRepresentation(), ctx.di.zone);
44✔
626
      // adding a NSEC3 will cause narrow mode to be dropped, as you cannot specify that in a NSEC3PARAM record
627
      ctx.narrow = false;
44✔
628
      dsk.setNSEC3PARAM(ctx.di.zone, ctx.ns3pr, ctx.narrow);
44✔
629
      ctx.haveNSEC3 = true;
44✔
630
    }
44✔
631
    else {
28✔
632
      g_log << Logger::Notice << ctx.msgPrefix << "Deleting NSEC3PARAM from zone, resetting ordernames." << endl;
28✔
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());
28✔
636
      if (rr->d_class == QClass::ANY) {
28!
637
        dsk.unsetNSEC3PARAM(zonename);
28✔
638
      }
28✔
639
      else { // rr->d_class == QClass::NONE then
×
NEW
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;
28✔
651
      ctx.haveNSEC3 = false;
28✔
652
    }
28✔
653

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

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

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

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

680
  return changedRecords;
4,758✔
681
}
4,830✔
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")) {
×
NEW
689
    g_log << Logger::Notice << ctx.msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
690
    return RCode::Refused;
×
691
  }
×
692

NEW
693
  for (const auto& remote : ctx.di.primaries) {
×
NEW
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) {
×
NEW
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
×
NEW
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) {
×
NEW
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) {
×
NEW
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) {
×
NEW
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()) {
×
NEW
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) {
×
NEW
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));
×
NEW
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 (...) {
×
NEW
795
      g_log << Logger::Error << ctx.msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
796
      continue;
×
797
    }
×
798
  }
×
NEW
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
{
2,294✔
805
  // Check permissions - IP based
806
  vector<string> allowedRanges;
2,294✔
807

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

813
  NetmaskGroup nmg;
2,294✔
814
  for (const auto& range : allowedRanges) {
4,588✔
815
    nmg.addMask(range);
4,588✔
816
  }
4,588✔
817

818
  if (!nmg.match(packet.getInnerRemote())) {
2,294!
NEW
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;
2,294✔
825
  UBackend.getDomainMetadata(packet.qdomainzone, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
2,294✔
826
  if (!tsigKeys.empty()) {
2,294!
827
    bool validKey = false;
×
828

829
    TSIGRecordContent trc;
×
830
    DNSName inputkey;
×
831
    string message;
×
832
    if (!packet.getTSIGDetails(&trc, &inputkey)) {
×
NEW
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) {
×
NEW
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")) {
2,294!
NEW
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) {
2,294!
NEW
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;
2,294✔
872
}
2,294✔
873

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

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

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

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

903
      DNSResourceRecord rec;
66✔
904
      ctx.di.backend->lookup(QType(QType::ANY), rrSet.first, ctx.di.id);
66✔
905
      size_t foundRR{0};
66✔
906
      size_t matchRR{0};
66✔
907
      while (ctx.di.backend->get(rec)) {
264✔
908
        if (rec.qtype == rrSet.second) {
198!
909
          foundRR++;
198✔
910
          for (auto& rrItem : *vec) {
594✔
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.
594✔
912
            if (rrItem == rec) {
594✔
913
              matchRR++;
198✔
914
            }
198✔
915
          }
594✔
916
        }
198✔
917
      }
198✔
918
      if (matchRR != foundRR || foundRR != vec->size()) {
66!
919
        g_log << Logger::Error << ctx.msgPrefix << "Failed PreRequisites check (RRs differ), returning NXRRSet" << endl;
44✔
920
        return RCode::NXRRSet;
44✔
921
      }
44✔
922
    }
66✔
923
  }
66✔
924
  return RCode::NoError;
2,074✔
925
}
2,118✔
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
{
2,030✔
929
  vector<const DNSRecord*> cnamesToAdd;
2,030✔
930
  vector<const DNSRecord*> nonCnamesToAdd;
2,030✔
931
  vector<const DNSRecord*> nsRRtoDelete;
2,030✔
932

933
  bool anyRecordProcessed{false};
2,030✔
934
  bool anyRecordAcceptedByLua{false};
2,030✔
935
  for (const auto& answer : mdp.d_answers) {
5,116✔
936
    const DNSRecord* dnsRecord = &answer;
5,116✔
937
    if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,116✔
938
      anyRecordProcessed = true;
4,940✔
939
      /* see if it's permitted by policy */
940
      if (update_policy_lua != nullptr) {
4,940!
NEW
941
        if (!update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), ctx.di.zone.operator const DNSName&(), packet)) {
×
NEW
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
        }
×
NEW
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&()) {
4,940!
950
        nsRRtoDelete.push_back(dnsRecord);
66✔
951
      }
66✔
952
      else if (dnsRecord->d_class == QClass::IN && dnsRecord->d_ttl > 0) {
4,874!
953
        if (dnsRecord->d_type == QType::CNAME) {
3,688✔
954
          cnamesToAdd.push_back(dnsRecord);
154✔
955
        }
154✔
956
        else {
3,534✔
957
          nonCnamesToAdd.push_back(dnsRecord);
3,534✔
958
        }
3,534✔
959
      }
3,688✔
960
      else {
1,186✔
961
        changedRecords += performUpdate(dsk, dnsRecord, ctx);
1,186✔
962
      }
1,186✔
963
    }
4,940✔
964
  }
5,116✔
965

966
  if (update_policy_lua != nullptr) {
2,030!
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) {
2,030✔
975
    DNSResourceRecord rec;
154✔
976
    ctx.di.backend->lookup(QType(QType::ANY), resrec->d_name, ctx.di.id);
154✔
977
    while (ctx.di.backend->get(rec)) {
220✔
978
      if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
88!
979
        // leave database handle in a consistent state
980
        ctx.di.backend->lookupEnd();
22✔
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;
22✔
982
        return RCode::Refused;
22✔
983
      }
22✔
984
    }
88✔
985
    changedRecords += performUpdate(dsk, resrec, ctx);
132✔
986
  }
132✔
987
  for (const auto& resrec : nonCnamesToAdd) {
3,534✔
988
    DNSResourceRecord rec;
3,534✔
989
    ctx.di.backend->lookup(QType(QType::CNAME), resrec->d_name, ctx.di.id);
3,534✔
990
    while (ctx.di.backend->get(rec)) {
3,534✔
991
      if (rec.qtype == QType::CNAME && resrec->d_type != QType::RRSIG) {
22!
992
        // leave database handle in a consistent state
993
        ctx.di.backend->lookupEnd();
22✔
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;
22✔
995
        return RCode::Refused;
22✔
996
      }
22✔
997
    }
22✔
998
    changedRecords += performUpdate(dsk, resrec, ctx);
3,512✔
999
  }
3,512✔
1000

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

1019
  return RCode::NoError;
1,986✔
1020
}
2,008✔
1021

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

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

1032
  g_log << Logger::Info << ctx.msgPrefix << "Processing started." << endl;
2,294✔
1033

1034
  // if there is policy, we delegate all checks to it
1035
  if (this->d_update_policy_lua == nullptr) {
2,294!
1036
    if (!isUpdateAllowed(B, ctx, packet)) {
2,294!
1037
      return RCode::Refused;
×
1038
    }
×
1039
  }
2,294✔
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());
2,294✔
1045
  if (mdp.d_header.qdcount != 1) {
2,294!
NEW
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
2,294!
NEW
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) {
2,294!
NEW
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;
2,294✔
1061
  if (!B.getDomainInfo(packet.qdomainzone, ctx.di) || (ctx.di.backend == nullptr)) {
2,294!
1062
    g_log << Logger::Error << ctx.msgPrefix << "Can't determine backend for domain '" << packet.qdomainzone << "' (or backend does not support DNS update operation)" << endl;
22✔
1063
    return RCode::NotAuth;
22✔
1064
  }
22✔
1065
  // ctx.di field valid from now on
1066

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

1071
  // Check if all the records provided are within the zone
1072
  for (const auto& answer : mdp.d_answers) {
5,556✔
1073
    const DNSRecord* dnsRecord = &answer;
5,556✔
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) {
5,556!
1077
      continue;
×
1078
    }
×
1079

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

1086
  auto lock = std::scoped_lock(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
2,228✔
1087
  g_log << Logger::Info << ctx.msgPrefix << "starting transaction." << endl;
2,228✔
1088
  if (!ctx.di.backend->startTransaction(packet.qdomainzone, UnknownDomainID)) { // Not giving the domain_id means that we do not delete the existing records.
2,228!
NEW
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) {
5,424✔
1095
    const DNSRecord* dnsRecord = &answer;
5,424✔
1096
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,424✔
1097
      int res = checkUpdatePrerequisites(dnsRecord, &ctx.di);
418✔
1098
      if (res > 0) {
418✔
1099
        g_log << Logger::Error << ctx.msgPrefix << "Failed PreRequisites check for " << dnsRecord->d_name << ", returning " << RCode::to_s(res) << endl;
110✔
1100
        ctx.di.backend->abortTransaction();
110✔
1101
        return res;
110✔
1102
      }
110✔
1103
    }
418✔
1104
  }
5,424✔
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) {
2,118✔
1108
    ctx.di.backend->abortTransaction();
44✔
1109
    return rcode;
44✔
1110
  }
44✔
1111

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

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

1133
    string soaEditSetting;
2,052✔
1134
    d_dk.getSoaEdit(ctx.di.zone, soaEditSetting);
2,052✔
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)
2,052✔
1142
    set<DNSName> nocn;
2,052✔
1143
    for (const auto& rr : mdp.d_answers) { // NOLINT(readability-identifier-length)
5,160✔
1144
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
5,160!
1145
        // Addition
1146
        if (rr.d_type == QType::CNAME) {
3,732✔
1147
          cn.insert(rr.d_name);
176✔
1148
        }
176✔
1149
        else if (rr.d_type != QType::RRSIG) {
3,556!
1150
          nocn.insert(rr.d_name);
3,556✔
1151
        }
3,556✔
1152
      }
3,732✔
1153
    }
5,160✔
1154
    for (auto const& n : cn) { // NOLINT(readability-identifier-length)
2,052✔
1155
      if (nocn.count(n) > 0) {
176✔
1156
        g_log << Logger::Error << ctx.msgPrefix << "Refusing update, found CNAME and non-CNAME addition" << endl;
22✔
1157
        ctx.di.backend->abortTransaction();
22✔
1158
        return RCode::FormErr;
22✔
1159
      }
22✔
1160
    }
176✔
1161

1162
    uint changedRecords = 0;
2,030✔
1163
    if (auto rcode = updateRecords(mdp, d_dk, changedRecords, d_update_policy_lua, packet, ctx); rcode != RCode::NoError) {
2,030✔
1164
      ctx.di.backend->abortTransaction();
44✔
1165
      return rcode;
44✔
1166
    }
44✔
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) {
1,986✔
1170
      increaseSerial(soaEditSetting, ctx);
1,766✔
1171
      changedRecords++;
1,766✔
1172
    }
1,766✔
1173

1174
    if (changedRecords != 0) {
1,986✔
1175
      if (!ctx.di.backend->commitTransaction()) {
1,810!
NEW
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));
1,810✔
1181

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

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

1195
      g_log << Logger::Info << ctx.msgPrefix << "Update completed, " << changedRecords << " changed records committed." << endl;
1,810✔
1196
    }
1,810✔
1197
    else {
176✔
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;
176✔
1200
      ctx.di.backend->abortTransaction();
176✔
1201
    }
176✔
1202
    return RCode::NoError; //rfc 2136 3.4.2.5
1,986✔
1203
  }
1,986✔
1204
  catch (SSqlException& e) {
2,074✔
NEW
1205
    g_log << Logger::Error << ctx.msgPrefix << "Caught SSqlException: " << e.txtReason() << "; Sending ServFail!" << endl;
×
NEW
1206
    ctx.di.backend->abortTransaction();
×
1207
    return RCode::ServFail;
×
1208
  }
×
1209
  catch (DBException& e) {
2,074✔
NEW
1210
    g_log << Logger::Error << ctx.msgPrefix << "Caught DBException: " << e.reason << "; Sending ServFail!" << endl;
×
NEW
1211
    ctx.di.backend->abortTransaction();
×
1212
    return RCode::ServFail;
×
1213
  }
×
1214
  catch (PDNSException& e) {
2,074✔
NEW
1215
    g_log << Logger::Error << ctx.msgPrefix << "Caught PDNSException: " << e.reason << "; Sending ServFail!" << endl;
×
NEW
1216
    ctx.di.backend->abortTransaction();
×
1217
    return RCode::ServFail;
×
1218
  }
×
1219
  catch (std::exception& e) {
2,074✔
NEW
1220
    g_log << Logger::Error << ctx.msgPrefix << "Caught std:exception: " << e.what() << "; Sending ServFail!" << endl;
×
NEW
1221
    ctx.di.backend->abortTransaction();
×
1222
    return RCode::ServFail;
×
1223
  }
×
1224
  catch (...) {
2,074✔
NEW
1225
    g_log << Logger::Error << ctx.msgPrefix << "Caught unknown exception when performing update. Sending ServFail!" << endl;
×
NEW
1226
    ctx.di.backend->abortTransaction();
×
1227
    return RCode::ServFail;
×
1228
  }
×
1229
}
2,074✔
1230

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

1238
  uint32_t oldSerial = sd.serial;
1,766✔
1239

1240
  vector<string> soaEdit2136Setting;
1,766✔
1241
  ctx.di.backend->getDomainMetadata(ctx.di.zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
1,766✔
1242
  string soaEdit2136 = "DEFAULT";
1,766✔
1243
  string soaEdit;
1,766✔
1244
  if (!soaEdit2136Setting.empty()) {
1,766!
1245
    soaEdit2136 = soaEdit2136Setting[0];
×
1246
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136, "SOA-EDIT-INCREASE")) {
×
1247
      if (soaEditSetting.empty()) {
×
NEW
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)
1,766✔
1258
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
1,766!
1259
    ctx.di.backend->replaceRRSet(ctx.di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
1,766✔
1260
    g_log << Logger::Notice << ctx.msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
1,766✔
1261

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