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

PowerDNS / pdns / 8246836297

12 Mar 2024 09:56AM UTC coverage: 53.746% (-5.4%) from 59.178%
8246836297

push

github

web-flow
Merge pull request #13879 from Habbie/auth-lua-filterforward-empty

auth LUA: support returning empty set in filterForward

23464 of 68850 branches covered (34.08%)

Branch coverage included in aggregate %.

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

12574 existing lines in 133 files now uncovered.

89131 of 140646 relevant lines covered (63.37%)

3409522.02 hits per line

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

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

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

24
extern StatBag S;
25
extern CommunicatorClass Communicator;
26

27
std::mutex PacketHandler::s_rfc2136lock;
28

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

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

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

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

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

UNCOV
64
  return RCode::NoError;
×
UNCOV
65
}
×
66

67

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

UNCOV
75
  QType qtype = QType(rr->d_type);
×
76

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

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

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

UNCOV
89
  if (qtype.isMetadataType()) {
×
90
    return RCode::FormErr;
×
91
  }
×
92

UNCOV
93
  if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY) {
×
UNCOV
94
    return RCode::FormErr;
×
UNCOV
95
  }
×
96

UNCOV
97
  return RCode::NoError;
×
UNCOV
98
}
×
99

100

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

UNCOV
104
  QType rrType = QType(rr->d_type);
×
105

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

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

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

121

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

127

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

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

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

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

147

148

UNCOV
149
    bool foundRecord = false;
×
UNCOV
150
    di->backend->lookup(rrType, rr->d_name, di->id);
×
UNCOV
151
    while (di->backend->get(rec)) {
×
UNCOV
152
      rrset.push_back(rec);
×
UNCOV
153
      foundRecord = true;
×
UNCOV
154
    }
×
155

UNCOV
156
    if (foundRecord) {
×
157

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

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

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

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

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

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

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

UNCOV
254
    } // if (foundRecord)
×
255

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

266

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

UNCOV
272
      if (di->zone != shorter) { // Everything at APEX is auth=1 && no ENT's
×
UNCOV
273
        do {
×
274

UNCOV
275
          if (di->zone == shorter)
×
UNCOV
276
            break;
×
277

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

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

UNCOV
296
      if(*haveNSEC3)
×
UNCOV
297
      {
×
UNCOV
298
        DNSName ordername;
×
UNCOV
299
        if(! *narrow)
×
UNCOV
300
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
×
301

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

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

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

331

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

UNCOV
349
            if (*narrow)
×
UNCOV
350
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth);
×
UNCOV
351
            else
×
UNCOV
352
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth);
×
353

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

UNCOV
362
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A);
×
UNCOV
363
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA);
×
UNCOV
364
        }
×
UNCOV
365
      }
×
UNCOV
366
    }
×
UNCOV
367
  } // rr->d_class == QClass::IN
×
368

369

370
  // Delete records - section 3.4.2.3 and 3.4.2.4 with the exception of the 'always leave 1 NS rule' as that's handled by
371
  // the code that calls this performUpdate().
UNCOV
372
  if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
×
UNCOV
373
    DLOG(g_log<<msgPrefix<<"Deleting records: "<<rr->d_name<<"; QClass:"<<rr->d_class<<"; rrType: "<<rrType.toString()<<endl);
×
374

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

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

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

400

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

432

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

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

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

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

472
      // Fix ENT records.
473
      // We must check if we have a record below the current level and if we removed the 'last' record
474
      // on that level. If so, we must insert an ENT record.
475
      // We take extra care here to not 'include' the record that we just deleted. Some backends will still return it as they only reload on a commit.
UNCOV
476
      bool foundDeeper = false, foundOtherWithSameName = false;
×
UNCOV
477
      di->backend->listSubZone(rr->d_name, di->id);
×
UNCOV
478
      while (di->backend->get(rec)) {
×
UNCOV
479
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
×
UNCOV
480
          foundOtherWithSameName = true;
×
UNCOV
481
        if (rec.qname != rr->d_name && rec.qtype.getCode() != QType::NS) //Skip NS records, as this would be a delegate that we can ignore as this does not require us to create a ENT
×
UNCOV
482
          foundDeeper = true;
×
UNCOV
483
      }
×
484

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

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

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

523

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

UNCOV
540
  return changedRecords;
×
UNCOV
541
}
×
542

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

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

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

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

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

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

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

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

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

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

662
}
×
663

UNCOV
664
int PacketHandler::processUpdate(DNSPacket& p) {
×
UNCOV
665
  if (! ::arg().mustDo("dnsupdate"))
×
666
    return RCode::Refused;
×
667

UNCOV
668
  string msgPrefix="UPDATE (" + std::to_string(p.d.id) + ") from " + p.getRemoteString() + " for " + p.qdomain.toLogString() + ": ";
×
UNCOV
669
  g_log<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
×
670

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

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

UNCOV
680
    NetmaskGroup ng;
×
UNCOV
681
    for(const auto& i: allowedRanges) {
×
UNCOV
682
      ng.addMask(i);
×
UNCOV
683
    }
×
684

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

690

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

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

725
      if (!validKey) {
×
726
        g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
727
        return RCode::Refused;
×
728
      }
×
729
    }
×
730

UNCOV
731
    if (tsigKeys.size() == 0 && p.d_havetsig)
×
732
      g_log<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
×
733

UNCOV
734
  }
×
735

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

UNCOV
745
  if (p.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
×
746
    g_log<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
×
747
    return RCode::FormErr;
×
748
  }
×
749

UNCOV
750
  if (p.qclass != QClass::IN) {
×
751
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
752
    return RCode::NotAuth;
×
753
  }
×
754

UNCOV
755
  DomainInfo di;
×
UNCOV
756
  di.backend=nullptr;
×
UNCOV
757
  if(!B.getDomainInfo(p.qdomain, di) || !di.backend) {
×
UNCOV
758
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<p.qdomain<<"' (or backend does not support DNS update operation)"<<endl;
×
UNCOV
759
    return RCode::NotAuth;
×
UNCOV
760
  }
×
761

UNCOV
762
  if (di.kind == DomainInfo::Secondary)
×
763
    return forwardPacket(msgPrefix, p, di);
×
764

765
  // Check if all the records provided are within the zone
UNCOV
766
  for(const auto & answer : mdp.d_answers) {
×
UNCOV
767
    const DNSRecord *rr = &answer.first;
×
768
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
769
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
UNCOV
770
    if (! (rr->d_place == DNSResourceRecord::ANSWER || rr->d_place == DNSResourceRecord::AUTHORITY))
×
771
      continue;
×
772

UNCOV
773
    if (!rr->d_name.isPartOf(di.zone)) {
×
UNCOV
774
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
×
UNCOV
775
      return RCode::NotZone;
×
UNCOV
776
    }
×
UNCOV
777
  }
×
778

779

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

787
  // 3.2.1 and 3.2.2 - Prerequisite check
UNCOV
788
  for(const auto & answer : mdp.d_answers) {
×
UNCOV
789
    const DNSRecord *rr = &answer.first;
×
UNCOV
790
    if (rr->d_place == DNSResourceRecord::ANSWER) {
×
UNCOV
791
      int res = checkUpdatePrerequisites(rr, &di);
×
UNCOV
792
      if (res>0) {
×
UNCOV
793
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<rr->d_name<<", returning "<<RCode::to_s(res)<<endl;
×
UNCOV
794
        di.backend->abortTransaction();
×
UNCOV
795
        return res;
×
UNCOV
796
      }
×
UNCOV
797
    }
×
UNCOV
798
  }
×
799

800
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
UNCOV
801
  typedef pair<DNSName, QType> rrSetKey_t;
×
UNCOV
802
  typedef vector<DNSResourceRecord> rrVector_t;
×
UNCOV
803
  typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
×
UNCOV
804
  RRsetMap_t preReqRRsets;
×
UNCOV
805
  for(const auto& i: mdp.d_answers) {
×
UNCOV
806
    const DNSRecord* rr = &i.first;
×
UNCOV
807
    if (rr->d_place == DNSResourceRecord::ANSWER) {
×
808
      // Last line of 3.2.3
UNCOV
809
      if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY)
×
810
        return RCode::FormErr;
×
811

UNCOV
812
      if (rr->d_class == QClass::IN) {
×
UNCOV
813
        rrSetKey_t key = {rr->d_name, QType(rr->d_type)};
×
UNCOV
814
        rrVector_t *vec = &preReqRRsets[key];
×
UNCOV
815
        vec->push_back(DNSResourceRecord::fromWire(*rr));
×
UNCOV
816
      }
×
UNCOV
817
    }
×
UNCOV
818
  }
×
819

UNCOV
820
  if (preReqRRsets.size() > 0) {
×
UNCOV
821
    RRsetMap_t zoneRRsets;
×
UNCOV
822
    for (auto & preReqRRset : preReqRRsets) {
×
UNCOV
823
      rrSetKey_t rrSet=preReqRRset.first;
×
UNCOV
824
      rrVector_t *vec = &preReqRRset.second;
×
825

UNCOV
826
      DNSResourceRecord rec;
×
UNCOV
827
      di.backend->lookup(QType(QType::ANY), rrSet.first, di.id);
×
UNCOV
828
      uint16_t foundRR=0, matchRR=0;
×
UNCOV
829
      while (di.backend->get(rec)) {
×
UNCOV
830
        if (rec.qtype == rrSet.second) {
×
UNCOV
831
          foundRR++;
×
UNCOV
832
          for(auto & rrItem : *vec) {
×
UNCOV
833
            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.
×
UNCOV
834
            if (rrItem == rec)
×
UNCOV
835
              matchRR++;
×
UNCOV
836
          }
×
UNCOV
837
        }
×
UNCOV
838
      }
×
UNCOV
839
      if (matchRR != foundRR || foundRR != vec->size()) {
×
UNCOV
840
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
×
UNCOV
841
        di.backend->abortTransaction();
×
UNCOV
842
        return RCode::NXRRSet;
×
UNCOV
843
      }
×
UNCOV
844
    }
×
UNCOV
845
  }
×
846

847

848

849
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
UNCOV
850
  try {
×
UNCOV
851
    uint changedRecords = 0;
×
852
    // 3.4.1 - Prescan section
UNCOV
853
    for(const auto & answer : mdp.d_answers) {
×
UNCOV
854
      const DNSRecord *rr = &answer.first;
×
UNCOV
855
      if (rr->d_place == DNSResourceRecord::AUTHORITY) {
×
UNCOV
856
        int res = checkUpdatePrescan(rr);
×
UNCOV
857
        if (res>0) {
×
UNCOV
858
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
×
UNCOV
859
          di.backend->abortTransaction();
×
UNCOV
860
          return res;
×
UNCOV
861
        }
×
UNCOV
862
      }
×
UNCOV
863
    }
×
864

UNCOV
865
    bool updatedSerial=false;
×
UNCOV
866
    NSEC3PARAMRecordContent ns3pr;
×
UNCOV
867
    bool narrow=false;
×
UNCOV
868
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
×
UNCOV
869
    bool isPresigned = d_dk.isPresigned(di.zone);
×
UNCOV
870
    string soaEditSetting;
×
UNCOV
871
    d_dk.getSoaEdit(di.zone, soaEditSetting);
×
872

873
    // 3.4.2 - Perform the updates.
874
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
875
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
UNCOV
876
    vector<const DNSRecord *> nsRRtoDelete;
×
877

878
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
UNCOV
879
    set<DNSName> cn, nocn;
×
UNCOV
880
    for (const auto &rr : mdp.d_answers) {
×
UNCOV
881
      if (rr.first.d_place == DNSResourceRecord::AUTHORITY && rr.first.d_class == QClass::IN && rr.first.d_ttl > 0) {
×
882
        // Addition
UNCOV
883
        if (rr.first.d_type == QType::CNAME) {
×
UNCOV
884
          cn.insert(rr.first.d_name);
×
UNCOV
885
        } else if (rr.first.d_type != QType::RRSIG) {
×
UNCOV
886
          nocn.insert(rr.first.d_name);
×
UNCOV
887
        }
×
UNCOV
888
      }
×
UNCOV
889
    }
×
UNCOV
890
    for (auto const &n : cn) {
×
UNCOV
891
      if (nocn.count(n) > 0) {
×
UNCOV
892
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
×
UNCOV
893
        di.backend->abortTransaction();
×
UNCOV
894
        return RCode::FormErr;
×
UNCOV
895
      }
×
UNCOV
896
    }
×
897

UNCOV
898
    vector<const DNSRecord *> cnamesToAdd, nonCnamesToAdd;
×
UNCOV
899
    for(const auto & answer : mdp.d_answers) {
×
UNCOV
900
      const DNSRecord *rr = &answer.first;
×
UNCOV
901
      if (rr->d_place == DNSResourceRecord::AUTHORITY) {
×
902
        /* see if it's permitted by policy */
UNCOV
903
        if (this->d_update_policy_lua != nullptr) {
×
904
          if (this->d_update_policy_lua->updatePolicy(rr->d_name, QType(rr->d_type), di.zone, p) == false) {
×
905
            g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": Not permitted by policy"<<endl;
×
906
            continue;
×
907
          } else {
×
908
            g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": Permitted by policy"<<endl;
×
909
          }
×
910
        }
×
911

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

972
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
UNCOV
973
    if (changedRecords > 0 && !updatedSerial) {
×
UNCOV
974
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
×
UNCOV
975
      changedRecords++;
×
UNCOV
976
    }
×
977

UNCOV
978
    if (changedRecords > 0) {
×
UNCOV
979
      if (!di.backend->commitTransaction()) {
×
980
       g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
981
        return RCode::ServFail;
×
982
      }
×
983

UNCOV
984
      S.deposit("dnsupdate-changes", changedRecords);
×
985

UNCOV
986
      d_dk.clearMetaCache(di.zone);
×
987
      // Purge the records!
UNCOV
988
      string zone(di.zone.toString());
×
UNCOV
989
      zone.append("$");
×
UNCOV
990
      purgeAuthCaches(zone);
×
991

992
      // Notify secondaries
UNCOV
993
      if (di.kind == DomainInfo::Primary) {
×
UNCOV
994
        vector<string> notify;
×
UNCOV
995
        B.getDomainMetadata(p.qdomain, "NOTIFY-DNSUPDATE", notify);
×
UNCOV
996
        if (!notify.empty() && notify.front() == "1") {
×
997
          Communicator.notifyDomain(di.zone, &B);
×
998
        }
×
UNCOV
999
      }
×
1000

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

UNCOV
1036
void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, const string& soaEditSetting,  bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
×
UNCOV
1037
  SOAData sd;
×
UNCOV
1038
  if (!di->backend->getSOA(di->zone, sd)) {
×
1039
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
×
1040
  }
×
1041

UNCOV
1042
  uint32_t oldSerial = sd.serial;
×
1043

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

UNCOV
1059
  DNSResourceRecord rr;
×
UNCOV
1060
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
×
UNCOV
1061
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
×
UNCOV
1062
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
×
1063

1064
    //Correct ordername + auth flag
UNCOV
1065
    if (haveNSEC3) {
×
UNCOV
1066
      DNSName ordername;
×
UNCOV
1067
      if (!narrow)
×
UNCOV
1068
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
×
1069

UNCOV
1070
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
×
UNCOV
1071
    } else { // NSEC
×
UNCOV
1072
      DNSName ordername = rr.qname.makeRelative(di->zone);
×
UNCOV
1073
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
×
UNCOV
1074
    }
×
UNCOV
1075
  }
×
UNCOV
1076
}
×
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