Coverage Report

Created: 2026-12-01 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/pdns/dnsdistdist/dnsdist-ecs.cc
Line
Count
Source
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
#include "dns.hh"
23
#include "dnsname.hh"
24
#include "dolog.hh"
25
#include "dnsdist.hh"
26
#include "dnsdist-dnsparser.hh"
27
#include "dnsdist-ecs.hh"
28
#include "dnsparser.hh"
29
#include "dnswriter.hh"
30
#include "ednsoptions.hh"
31
#include "ednssubnet.hh"
32
#include "qtype.hh"
33
34
int rewriteResponseWithoutEDNS(const PacketBuffer& initialPacket, PacketBuffer& newContent)
35
3.11k
{
36
3.11k
  if (initialPacket.size() < sizeof(dnsheader)) {
37
8
    return ENOENT;
38
8
  }
39
40
3.10k
  const dnsheader_aligned dnsHeader(initialPacket.data());
41
42
3.10k
  if (ntohs(dnsHeader->arcount) == 0) {
43
248
    return ENOENT;
44
248
  }
45
46
2.86k
  if (ntohs(dnsHeader->qdcount) == 0) {
47
40
    return ENOENT;
48
40
  }
49
50
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
51
2.82k
  PacketReader packetReader(std::string_view(reinterpret_cast<const char*>(initialPacket.data()), initialPacket.size()));
52
53
2.82k
  size_t idx = 0;
54
2.82k
  uint16_t qdcount = ntohs(dnsHeader->qdcount);
55
2.82k
  uint16_t ancount = ntohs(dnsHeader->ancount);
56
2.82k
  uint16_t nscount = ntohs(dnsHeader->nscount);
57
2.82k
  uint16_t arcount = ntohs(dnsHeader->arcount);
58
2.82k
  string blob;
59
2.82k
  dnsrecordheader recordHeader{};
60
61
2.82k
  auto rrname = packetReader.getName();
62
2.82k
  auto rrtype = packetReader.get16BitInt();
63
2.82k
  auto rrclass = packetReader.get16BitInt();
64
65
2.82k
  GenericDNSPacketWriter<PacketBuffer> packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode);
66
2.82k
  packetWriter.getHeader()->id = dnsHeader->id;
67
2.82k
  packetWriter.getHeader()->qr = dnsHeader->qr;
68
2.82k
  packetWriter.getHeader()->aa = dnsHeader->aa;
69
2.82k
  packetWriter.getHeader()->tc = dnsHeader->tc;
70
2.82k
  packetWriter.getHeader()->rd = dnsHeader->rd;
71
2.82k
  packetWriter.getHeader()->ra = dnsHeader->ra;
72
2.82k
  packetWriter.getHeader()->ad = dnsHeader->ad;
73
2.82k
  packetWriter.getHeader()->cd = dnsHeader->cd;
74
2.82k
  packetWriter.getHeader()->rcode = dnsHeader->rcode;
75
76
  /* consume remaining qd if any */
77
2.82k
  if (qdcount > 1) {
78
145k
    for (idx = 1; idx < qdcount; idx++) {
79
144k
      rrname = packetReader.getName();
80
144k
      rrtype = packetReader.get16BitInt();
81
144k
      rrclass = packetReader.get16BitInt();
82
144k
      (void)rrtype;
83
144k
      (void)rrclass;
84
144k
    }
85
398
  }
86
87
  /* copy AN and NS */
88
18.8k
  for (idx = 0; idx < ancount; idx++) {
89
16.0k
    rrname = packetReader.getName();
90
16.0k
    packetReader.getDnsrecordheader(recordHeader);
91
92
16.0k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true);
93
16.0k
    packetReader.xfrBlob(blob);
94
16.0k
    packetWriter.xfrBlob(blob);
95
16.0k
  }
96
97
8.98k
  for (idx = 0; idx < nscount; idx++) {
98
6.16k
    rrname = packetReader.getName();
99
6.16k
    packetReader.getDnsrecordheader(recordHeader);
100
101
6.16k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true);
102
6.16k
    packetReader.xfrBlob(blob);
103
6.16k
    packetWriter.xfrBlob(blob);
104
6.16k
  }
105
  /* consume AR, looking for OPT */
106
28.2k
  for (idx = 0; idx < arcount; idx++) {
107
25.4k
    rrname = packetReader.getName();
108
25.4k
    packetReader.getDnsrecordheader(recordHeader);
109
110
25.4k
    if (!rrname.isRoot() || recordHeader.d_type != QType::OPT) {
111
19.1k
      packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true);
112
19.1k
      packetReader.xfrBlob(blob);
113
19.1k
      packetWriter.xfrBlob(blob);
114
19.1k
    }
115
6.28k
    else {
116
117
6.28k
      packetReader.skip(recordHeader.d_clen);
118
6.28k
    }
119
25.4k
  }
120
2.82k
  packetWriter.commit();
121
122
2.82k
  return 0;
123
2.86k
}
124
125
static bool addOrReplaceEDNSOption(std::vector<std::pair<uint16_t, std::string>>& options, uint16_t optionCode, bool& optionAdded, bool overrideExisting, bool allowMultiple, const string& newOptionContent)
126
4.84k
{
127
4.84k
  if (!allowMultiple) {
128
36.9k
    for (auto it = options.begin(); it != options.end();) {
129
32.0k
      if (it->first == optionCode) {
130
1.41k
        optionAdded = false;
131
132
1.41k
        if (!overrideExisting) {
133
0
          return false;
134
0
        }
135
136
1.41k
        it = options.erase(it);
137
1.41k
      }
138
30.6k
      else {
139
30.6k
        ++it;
140
30.6k
      }
141
32.0k
    }
142
4.84k
  }
143
144
4.84k
  if (newOptionContent.size() == EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE) {
145
0
    options.emplace_back(optionCode, "");
146
0
    return true;
147
0
  }
148
149
4.84k
  options.emplace_back(optionCode, std::string(&newOptionContent.at(EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), newOptionContent.size() - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE)));
150
4.84k
  return true;
151
4.84k
}
152
153
bool slowRewriteEDNSOptionInQueryWithRecords(const PacketBuffer& initialPacket, PacketBuffer& newContent, bool& ednsAdded, uint16_t optionToReplace, bool& optionAdded, bool overrideExisting, bool allowMultiple, const string& newOptionContent)
154
1.93k
{
155
1.93k
  if (initialPacket.size() < sizeof(dnsheader)) {
156
0
    return false;
157
0
  }
158
159
1.93k
  const dnsheader_aligned dnsHeader(initialPacket.data());
160
161
1.93k
  if (ntohs(dnsHeader->qdcount) == 0) {
162
5
    return false;
163
5
  }
164
165
1.93k
  if (ntohs(dnsHeader->ancount) == 0 && ntohs(dnsHeader->nscount) == 0 && ntohs(dnsHeader->arcount) == 0) {
166
0
    throw std::runtime_error("slowRewriteEDNSOptionInQueryWithRecords should not be called for queries that have no records");
167
0
  }
168
169
1.93k
  optionAdded = false;
170
1.93k
  ednsAdded = true;
171
172
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
173
1.93k
  PacketReader packetReader(std::string_view(reinterpret_cast<const char*>(initialPacket.data()), initialPacket.size()));
174
175
1.93k
  size_t idx = 0;
176
1.93k
  uint16_t qdcount = ntohs(dnsHeader->qdcount);
177
1.93k
  uint16_t ancount = ntohs(dnsHeader->ancount);
178
1.93k
  uint16_t nscount = ntohs(dnsHeader->nscount);
179
1.93k
  uint16_t arcount = ntohs(dnsHeader->arcount);
180
1.93k
  string blob;
181
1.93k
  dnsrecordheader recordHeader{};
182
183
1.93k
  auto rrname = packetReader.getName();
184
1.93k
  auto rrtype = packetReader.get16BitInt();
185
1.93k
  auto rrclass = packetReader.get16BitInt();
186
187
1.93k
  GenericDNSPacketWriter<PacketBuffer> packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode);
188
1.93k
  packetWriter.getHeader()->id = dnsHeader->id;
189
1.93k
  packetWriter.getHeader()->qr = dnsHeader->qr;
190
1.93k
  packetWriter.getHeader()->aa = dnsHeader->aa;
191
1.93k
  packetWriter.getHeader()->tc = dnsHeader->tc;
192
1.93k
  packetWriter.getHeader()->rd = dnsHeader->rd;
193
1.93k
  packetWriter.getHeader()->ra = dnsHeader->ra;
194
1.93k
  packetWriter.getHeader()->ad = dnsHeader->ad;
195
1.93k
  packetWriter.getHeader()->cd = dnsHeader->cd;
196
1.93k
  packetWriter.getHeader()->rcode = dnsHeader->rcode;
197
198
  /* consume remaining qd if any */
199
1.93k
  if (qdcount > 1) {
200
62.2k
    for (idx = 1; idx < qdcount; idx++) {
201
61.9k
      rrname = packetReader.getName();
202
61.9k
      rrtype = packetReader.get16BitInt();
203
61.9k
      rrclass = packetReader.get16BitInt();
204
61.9k
      (void)rrtype;
205
61.9k
      (void)rrclass;
206
61.9k
    }
207
303
  }
208
209
  /* copy AN and NS */
210
19.2k
  for (idx = 0; idx < ancount; idx++) {
211
17.3k
    rrname = packetReader.getName();
212
17.3k
    packetReader.getDnsrecordheader(recordHeader);
213
214
17.3k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true);
215
17.3k
    packetReader.xfrBlob(blob);
216
17.3k
    packetWriter.xfrBlob(blob);
217
17.3k
  }
218
219
8.89k
  for (idx = 0; idx < nscount; idx++) {
220
6.96k
    rrname = packetReader.getName();
221
6.96k
    packetReader.getDnsrecordheader(recordHeader);
222
223
6.96k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true);
224
6.96k
    packetReader.xfrBlob(blob);
225
6.96k
    packetWriter.xfrBlob(blob);
226
6.96k
  }
227
228
  /* consume AR, looking for OPT */
229
26.5k
  for (idx = 0; idx < arcount; idx++) {
230
24.6k
    rrname = packetReader.getName();
231
24.6k
    packetReader.getDnsrecordheader(recordHeader);
232
233
24.6k
    if (!rrname.isRoot() || recordHeader.d_type != QType::OPT) {
234
19.0k
      packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true);
235
19.0k
      packetReader.xfrBlob(blob);
236
19.0k
      packetWriter.xfrBlob(blob);
237
19.0k
    }
238
5.57k
    else {
239
240
5.57k
      ednsAdded = false;
241
5.57k
      packetReader.xfrBlob(blob);
242
243
5.57k
      std::vector<std::pair<uint16_t, std::string>> options;
244
5.57k
      getEDNSOptionsFromContent(blob, options);
245
246
      /* getDnsrecordheader() has helpfully converted the TTL for us, which we do not want in that case */
247
5.57k
      uint32_t ttl = htonl(recordHeader.d_ttl);
248
5.57k
      EDNS0Record edns0{};
249
5.57k
      static_assert(sizeof(edns0) == sizeof(ttl), "sizeof(EDNS0Record) must match sizeof(uint32_t) AKA RR TTL size");
250
5.57k
      memcpy(&edns0, &ttl, sizeof(edns0));
251
252
      /* addOrReplaceEDNSOption will set it to false if there is already an existing option */
253
5.57k
      optionAdded = true;
254
5.57k
      addOrReplaceEDNSOption(options, optionToReplace, optionAdded, overrideExisting, allowMultiple, newOptionContent);
255
5.57k
      packetWriter.addOpt(recordHeader.d_class, edns0.extRCode, ntohs(edns0.extFlags), options, edns0.version);
256
5.57k
    }
257
24.6k
  }
258
259
1.93k
  if (ednsAdded) {
260
90
    if (newOptionContent.size() == EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE) {
261
0
      packetWriter.addOpt(dnsdist::configuration::s_EdnsUDPPayloadSize, 0, 0, {{optionToReplace, std::string()}}, 0);
262
0
    }
263
90
    else {
264
90
      packetWriter.addOpt(dnsdist::configuration::s_EdnsUDPPayloadSize, 0, 0, {{optionToReplace, std::string(&newOptionContent.at(EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE), newOptionContent.size() - (EDNS_OPTION_CODE_SIZE + EDNS_OPTION_LENGTH_SIZE))}}, 0);
265
90
    }
266
90
    optionAdded = true;
267
90
  }
268
269
1.93k
  packetWriter.commit();
270
271
1.93k
  return true;
272
1.93k
}
273
274
namespace dnsdist
275
{
276
/* extract the start of the OPT RR in a QUERY packet if any
277
 * optRDPosition points to the first byte of the RDLEN field
278
 * remaining contains the number of bytes in the packet after optRDPosition (i.e. packet.size() - optRDPosition)
279
 */
280
int getEDNSOptionsStart(const PacketBuffer& packet, const size_t qnameWireLength, uint16_t* optRDPosition, size_t* remaining)
281
4.72k
{
282
4.72k
  if (optRDPosition == nullptr || remaining == nullptr) {
283
0
    throw std::runtime_error("Invalid values passed to getEDNSOptionsStart");
284
0
  }
285
286
4.72k
  const dnsheader_aligned dnsHeader(packet.data());
287
288
4.72k
  if (qnameWireLength >= packet.size()) {
289
0
    return ENOENT;
290
0
  }
291
292
4.72k
  if (ntohs(dnsHeader->qdcount) != 1 || ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->arcount) != 1 || ntohs(dnsHeader->nscount) != 0) {
293
2.47k
    return ENOENT;
294
2.47k
  }
295
296
2.24k
  size_t pos = sizeof(dnsheader) + qnameWireLength;
297
2.24k
  pos += DNS_TYPE_SIZE + DNS_CLASS_SIZE;
298
299
2.24k
  if (pos >= packet.size()) {
300
30
    return ENOENT;
301
30
  }
302
303
2.21k
  if ((pos + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE) >= packet.size()) {
304
84
    return ENOENT;
305
84
  }
306
307
2.12k
  if (packet[pos] != 0) {
308
    /* not the root so not an OPT record */
309
224
    return ENOENT;
310
224
  }
311
1.90k
  pos += 1;
312
313
1.90k
  uint16_t qtype = packet.at(pos) * 256 + packet.at(pos + 1);
314
1.90k
  pos += DNS_TYPE_SIZE;
315
1.90k
  pos += DNS_CLASS_SIZE;
316
317
1.90k
  if (qtype != QType::OPT || (packet.size() - pos) < (DNS_TTL_SIZE + DNS_RDLENGTH_SIZE)) {
318
293
    return ENOENT;
319
293
  }
320
321
1.61k
  pos += DNS_TTL_SIZE;
322
1.61k
  *optRDPosition = pos;
323
1.61k
  *remaining = packet.size() - pos;
324
325
1.61k
  return 0;
326
1.90k
}
327
}
328
329
void generateECSOption(const ComboAddress& source, string& res, uint16_t ECSPrefixLength)
330
2.88k
{
331
2.88k
  Netmask sourceNetmask(source, ECSPrefixLength);
332
2.88k
  EDNSSubnetOpts ecsOpts;
333
2.88k
  ecsOpts.setSource(sourceNetmask);
334
2.88k
  string payload = ecsOpts.makeOptString();
335
2.88k
  generateEDNSOption(EDNSOptionCode::ECS, payload, res);
336
2.88k
}
337
338
bool generateOptRR(const std::string& optRData, PacketBuffer& res, size_t maximumSize, uint16_t udpPayloadSize, uint8_t ednsrcode, bool dnssecOK)
339
386
{
340
386
  const uint8_t name = 0;
341
386
  dnsrecordheader dnsHeader{};
342
386
  EDNS0Record edns0{};
343
386
  edns0.extRCode = ednsrcode;
344
386
  edns0.version = 0;
345
386
  edns0.extFlags = dnssecOK ? htons(EDNS_HEADER_FLAG_DO) : 0;
346
347
386
  if (res.size() >= maximumSize || (maximumSize - res.size()) < (sizeof(name) + sizeof(dnsHeader) + optRData.length())) {
348
0
    return false;
349
0
  }
350
351
386
  dnsHeader.d_type = htons(QType::OPT);
352
386
  dnsHeader.d_class = htons(udpPayloadSize);
353
386
  static_assert(sizeof(EDNS0Record) == sizeof(dnsHeader.d_ttl), "sizeof(EDNS0Record) must match sizeof(dnsrecordheader.d_ttl)");
354
386
  memcpy(&dnsHeader.d_ttl, &edns0, sizeof edns0);
355
386
  dnsHeader.d_clen = htons(static_cast<uint16_t>(optRData.length()));
356
357
386
  res.reserve(res.size() + sizeof(name) + sizeof(dnsHeader) + optRData.length());
358
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic)
359
386
  res.insert(res.end(), reinterpret_cast<const uint8_t*>(&name), reinterpret_cast<const uint8_t*>(&name) + sizeof(name));
360
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic)
361
386
  res.insert(res.end(), reinterpret_cast<const uint8_t*>(&dnsHeader), reinterpret_cast<const uint8_t*>(&dnsHeader) + sizeof(dnsHeader));
362
386
  res.insert(res.end(), optRData.begin(), optRData.end());
363
364
386
  return true;
365
386
}
366
367
static bool replaceEDNSClientSubnetOption(PacketBuffer& packet, size_t maximumSize, size_t const oldEcsOptionStartPosition, size_t const oldEcsOptionSize, size_t const optRDLenPosition, const string& newECSOption)
368
253
{
369
253
  if (oldEcsOptionStartPosition >= packet.size() || optRDLenPosition >= packet.size()) {
370
0
    throw std::runtime_error("Invalid values passed to replaceEDNSClientSubnetOption");
371
0
  }
372
373
253
  if (newECSOption.size() == oldEcsOptionSize) {
374
    /* same size as the existing option */
375
3
    memcpy(&packet.at(oldEcsOptionStartPosition), newECSOption.c_str(), oldEcsOptionSize);
376
3
  }
377
250
  else {
378
    /* different size than the existing option */
379
250
    const unsigned int newPacketLen = packet.size() + (newECSOption.length() - oldEcsOptionSize);
380
250
    const size_t beforeOptionLen = oldEcsOptionStartPosition;
381
250
    const size_t dataBehindSize = packet.size() - beforeOptionLen - oldEcsOptionSize;
382
383
    /* check that it fits in the existing buffer */
384
250
    if (newPacketLen > packet.size()) {
385
182
      if (newPacketLen > maximumSize) {
386
0
        return false;
387
0
      }
388
389
182
      packet.resize(newPacketLen);
390
182
    }
391
392
    /* fix the size of ECS Option RDLen */
393
250
    uint16_t newRDLen = (packet.at(optRDLenPosition) * 256) + packet.at(optRDLenPosition + 1);
394
250
    newRDLen += (newECSOption.size() - oldEcsOptionSize);
395
250
    packet.at(optRDLenPosition) = newRDLen / 256;
396
250
    packet.at(optRDLenPosition + 1) = newRDLen % 256;
397
398
250
    if (dataBehindSize > 0) {
399
231
      memmove(&packet.at(oldEcsOptionStartPosition), &packet.at(oldEcsOptionStartPosition + oldEcsOptionSize), dataBehindSize);
400
231
    }
401
250
    memcpy(&packet.at(oldEcsOptionStartPosition + dataBehindSize), newECSOption.c_str(), newECSOption.size());
402
250
    packet.resize(newPacketLen);
403
250
  }
404
405
253
  return true;
406
253
}
407
408
/* This function looks for an OPT RR, return true if a valid one was found (even if there was no options)
409
   and false otherwise. */
410
std::optional<EDNSOptionViewMap> parseEDNSOptions(const DNSQuestion& dnsQuestion)
411
0
{
412
0
  EDNSOptionViewMap ednsOptions{};
413
0
  const auto dnsHeader = dnsQuestion.getHeader();
414
0
  if (ntohs(dnsHeader->arcount) == 0) {
415
    /* nothing in additional so no EDNS */
416
0
    return std::nullopt;
417
0
  }
418
419
0
  if (ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->nscount) != 0 || ntohs(dnsHeader->arcount) > 1) {
420
0
    if (slowParseEDNSOptions(dnsQuestion.getData(), ednsOptions)) {
421
0
      return ednsOptions;
422
0
    }
423
0
    return std::nullopt;
424
0
  }
425
426
0
  size_t remaining = 0;
427
0
  uint16_t optRDPosition{};
428
0
  int res = dnsdist::getEDNSOptionsStart(dnsQuestion.getData(), dnsQuestion.ids.qname.wirelength(), &optRDPosition, &remaining);
429
430
0
  if (res == 0) {
431
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
432
0
    res = getEDNSOptions(reinterpret_cast<const char*>(&dnsQuestion.getData().at(optRDPosition)), remaining, ednsOptions);
433
0
    if (res != 0) {
434
0
      return std::nullopt;
435
0
    }
436
0
    return ednsOptions;
437
0
  }
438
439
0
  return std::nullopt;
440
0
}
441
442
static bool addECSToExistingOPT(PacketBuffer& packet, size_t maximumSize, const string& newECSOption, size_t optRDLenPosition, bool& ecsAdded)
443
232
{
444
  /* we need to add one EDNS0 ECS option, fixing the size of EDNS0 RDLENGTH */
445
  /* getEDNSOptionsStart has already checked that there is exactly one AR,
446
     no NS and no AN */
447
232
  uint16_t oldRDLen = (packet.at(optRDLenPosition) * 256) + packet.at(optRDLenPosition + 1);
448
232
  if (packet.size() != (optRDLenPosition + sizeof(uint16_t) + oldRDLen)) {
449
    /* we are supposed to be the last record, do we have some trailing data to remove? */
450
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
451
144
    uint32_t realPacketLen = getDNSPacketLength(reinterpret_cast<const char*>(packet.data()), packet.size());
452
144
    packet.resize(realPacketLen);
453
144
  }
454
455
232
  if ((maximumSize - packet.size()) < newECSOption.size()) {
456
0
    return false;
457
0
  }
458
459
232
  const uint32_t computedRDLen = static_cast<uint32_t>(oldRDLen) + newECSOption.size();
460
232
  if (computedRDLen > std::numeric_limits<uint16_t>::max()) {
461
0
    return false;
462
0
  }
463
232
  const auto newRDLen = static_cast<uint16_t>(computedRDLen);
464
232
  packet.at(optRDLenPosition) = newRDLen / 256;
465
232
  packet.at(optRDLenPosition + 1) = newRDLen % 256;
466
467
232
  packet.insert(packet.end(), newECSOption.begin(), newECSOption.end());
468
232
  ecsAdded = true;
469
470
232
  return true;
471
232
}
472
473
static bool addEDNSWithECS(PacketBuffer& packet, size_t maximumSize, const string& newECSOption, bool& ednsAdded, bool& ecsAdded)
474
386
{
475
386
  if (!generateOptRR(newECSOption, packet, maximumSize, dnsdist::configuration::s_EdnsUDPPayloadSize, 0, false)) {
476
0
    return false;
477
0
  }
478
479
386
  dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [](dnsheader& header) {
480
386
    uint16_t arcount = ntohs(header.arcount);
481
386
    arcount++;
482
386
    header.arcount = htons(arcount);
483
386
    return true;
484
386
  });
485
386
  ednsAdded = true;
486
386
  ecsAdded = true;
487
488
386
  return true;
489
386
}
490
491
bool handleEDNSClientSubnet(PacketBuffer& packet, const size_t maximumSize, const size_t qnameWireLength, bool& ednsAdded, bool& ecsAdded, bool overrideExisting, const string& newECSOption)
492
2.88k
{
493
2.88k
  if (qnameWireLength > packet.size()) {
494
0
    throw std::runtime_error("Invalid value passed to handleEDNSClientSubnet");
495
0
  }
496
497
2.88k
  const dnsheader_aligned dnsHeader(packet.data());
498
499
2.88k
  if (ntohs(dnsHeader->ancount) != 0 || ntohs(dnsHeader->nscount) != 0 || (ntohs(dnsHeader->arcount) != 0 && ntohs(dnsHeader->arcount) != 1)) {
500
1.93k
    PacketBuffer newContent;
501
1.93k
    newContent.reserve(packet.size());
502
503
1.93k
    if (!slowRewriteEDNSOptionInQueryWithRecords(packet, newContent, ednsAdded, EDNSOptionCode::ECS, ecsAdded, overrideExisting, false, newECSOption)) {
504
5
      return false;
505
5
    }
506
507
1.93k
    if (newContent.size() > maximumSize) {
508
30
      ednsAdded = false;
509
30
      ecsAdded = false;
510
30
      return false;
511
30
    }
512
513
1.90k
    packet = std::move(newContent);
514
1.90k
    return true;
515
1.93k
  }
516
517
946
  uint16_t optRDPosition = 0;
518
946
  size_t remaining = 0;
519
520
946
  int res = dnsdist::getEDNSOptionsStart(packet, qnameWireLength, &optRDPosition, &remaining);
521
522
946
  if (res != 0) {
523
    /* no EDNS but there might be another record in additional (TSIG?) */
524
    /* Careful, this code assumes that ANCOUNT == 0 && NSCOUNT == 0 */
525
386
    size_t minimumPacketSize = sizeof(dnsheader) + qnameWireLength + sizeof(uint16_t) + sizeof(uint16_t);
526
386
    if (packet.size() > minimumPacketSize) {
527
372
      if (ntohs(dnsHeader->arcount) == 0) {
528
        /* well now.. */
529
33
        packet.resize(minimumPacketSize);
530
33
      }
531
339
      else {
532
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
533
339
        uint32_t realPacketLen = getDNSPacketLength(reinterpret_cast<const char*>(packet.data()), packet.size());
534
339
        packet.resize(realPacketLen);
535
339
      }
536
372
    }
537
538
386
    return addEDNSWithECS(packet, maximumSize, newECSOption, ednsAdded, ecsAdded);
539
386
  }
540
541
560
  size_t ecsOptionStartPosition = 0;
542
560
  size_t ecsOptionSize = 0;
543
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
544
560
  res = getEDNSOption(reinterpret_cast<const char*>(&packet.at(optRDPosition)), remaining, EDNSOptionCode::ECS, &ecsOptionStartPosition, &ecsOptionSize);
545
546
560
  if (res == 0) {
547
    /* there is already an ECS value */
548
253
    if (!overrideExisting) {
549
0
      return true;
550
0
    }
551
552
253
    return replaceEDNSClientSubnetOption(packet, maximumSize, optRDPosition + ecsOptionStartPosition, ecsOptionSize, optRDPosition, newECSOption);
553
253
  }
554
555
307
  if (res != ENOENT) {
556
    /* something is wrong */
557
75
    return false;
558
75
  }
559
560
  /* we have an EDNS OPT RR but no existing ECS option */
561
232
  return addECSToExistingOPT(packet, maximumSize, newECSOption, optRDPosition, ecsAdded);
562
307
}
563
564
bool handleEDNSClientSubnet(DNSQuestion& dnsQuestion, bool& ednsAdded, bool& ecsAdded)
565
0
{
566
0
  string newECSOption;
567
0
  generateECSOption(dnsQuestion.ecs ? dnsQuestion.ecs->getNetwork() : dnsQuestion.ids.origRemote, newECSOption, dnsQuestion.ecs ? dnsQuestion.ecs->getBits() : dnsQuestion.ecsPrefixLength);
568
569
0
  return handleEDNSClientSubnet(dnsQuestion.getMutableData(), dnsQuestion.getMaximumSize(), dnsQuestion.ids.qname.wirelength(), ednsAdded, ecsAdded, dnsQuestion.ecsOverride, newECSOption);
570
0
}
571
572
static int removeEDNSOptionFromOptions(unsigned char* optionsStart, const uint16_t optionsLen, const uint16_t optionCodeToRemove, uint16_t* newOptionsLen)
573
5.39k
{
574
5.39k
  const pdns::views::UnsignedCharView view(optionsStart, optionsLen);
575
5.39k
  size_t pos = 0;
576
50.5k
  while ((pos + 4) <= view.size()) {
577
47.4k
    size_t optionBeginPos = pos;
578
47.4k
    const uint16_t optionCode = 0x100 * view.at(pos) + view.at(pos + 1);
579
47.4k
    pos += sizeof(optionCode);
580
47.4k
    const uint16_t optionLen = 0x100 * view.at(pos) + view.at(pos + 1);
581
47.4k
    pos += sizeof(optionLen);
582
47.4k
    if ((pos + optionLen) > view.size()) {
583
1.01k
      return EINVAL;
584
1.01k
    }
585
46.4k
    if (optionCode == optionCodeToRemove) {
586
1.28k
      if (pos + optionLen < view.size()) {
587
        /* move remaining options over the removed one,
588
           if any */
589
        // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
590
853
        memmove(optionsStart + optionBeginPos, optionsStart + pos + optionLen, optionsLen - (pos + optionLen));
591
853
      }
592
1.28k
      *newOptionsLen = optionsLen - (sizeof(optionCode) + sizeof(optionLen) + optionLen);
593
1.28k
      return 0;
594
1.28k
    }
595
45.1k
    pos += optionLen;
596
45.1k
  }
597
3.09k
  return ENOENT;
598
5.39k
}
599
600
int removeEDNSOptionFromOPT(char* optStart, size_t* optLen, const uint16_t optionCodeToRemove)
601
0
{
602
0
  if (*optLen < optRecordMinimumSize) {
603
0
    return EINVAL;
604
0
  }
605
0
  const pdns::views::UnsignedCharView view(optStart, *optLen);
606
  /* skip the root label, qtype, qclass and TTL */
607
0
  size_t position = 9;
608
0
  uint16_t rdLen = (0x100 * view.at(position) + view.at(position + 1));
609
0
  position += sizeof(rdLen);
610
0
  if (position + rdLen != view.size()) {
611
0
    return EINVAL;
612
0
  }
613
0
  uint16_t newRdLen = 0;
614
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic)
615
0
  int res = removeEDNSOptionFromOptions(reinterpret_cast<unsigned char*>(optStart + position), rdLen, optionCodeToRemove, &newRdLen);
616
0
  if (res != 0) {
617
0
    return res;
618
0
  }
619
0
  *optLen -= (rdLen - newRdLen);
620
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-bounds-pointer-arithmetic)
621
0
  auto* rdLenPtr = reinterpret_cast<unsigned char*>(optStart + 9);
622
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
623
0
  rdLenPtr[0] = newRdLen / 0x100;
624
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
625
0
  rdLenPtr[1] = newRdLen % 0x100;
626
0
  return 0;
627
0
}
628
629
bool isEDNSOptionInOpt(const PacketBuffer& packet, const size_t optStart, const size_t optLen, const uint16_t optionCodeToFind, size_t* optContentStart, uint16_t* optContentLen)
630
1.00k
{
631
1.00k
  if (optLen < optRecordMinimumSize) {
632
0
    return false;
633
0
  }
634
1.00k
  size_t position = optStart + 9;
635
1.00k
  uint16_t rdLen = (0x100 * static_cast<unsigned char>(packet.at(position)) + static_cast<unsigned char>(packet.at(position + 1)));
636
1.00k
  position += sizeof(rdLen);
637
1.00k
  if (rdLen > (optLen - optRecordMinimumSize)) {
638
36
    return false;
639
36
  }
640
641
970
  size_t rdEnd = position + rdLen;
642
35.4k
  while ((position + 4) <= rdEnd) {
643
34.9k
    const uint16_t optionCode = 0x100 * static_cast<unsigned char>(packet.at(position)) + static_cast<unsigned char>(packet.at(position + 1));
644
34.9k
    position += sizeof(optionCode);
645
34.9k
    const uint16_t optionLen = 0x100 * static_cast<unsigned char>(packet.at(position)) + static_cast<unsigned char>(packet.at(position + 1));
646
34.9k
    position += sizeof(optionLen);
647
648
34.9k
    if ((position + optionLen) > rdEnd) {
649
157
      return false;
650
157
    }
651
652
34.8k
    if (optionCode == optionCodeToFind) {
653
347
      if (optContentStart != nullptr) {
654
347
        *optContentStart = position;
655
347
      }
656
657
347
      if (optContentLen != nullptr) {
658
347
        *optContentLen = optionLen;
659
347
      }
660
661
347
      return true;
662
347
    }
663
34.4k
    position += optionLen;
664
34.4k
  }
665
466
  return false;
666
970
}
667
668
int rewriteResponseWithoutEDNSOption(const PacketBuffer& initialPacket, const uint16_t optionCodeToSkip, PacketBuffer& newContent)
669
3.11k
{
670
3.11k
  if (initialPacket.size() < sizeof(dnsheader)) {
671
8
    return ENOENT;
672
8
  }
673
674
3.10k
  const dnsheader_aligned dnsHeader(initialPacket.data());
675
676
3.10k
  if (ntohs(dnsHeader->arcount) == 0) {
677
248
    return ENOENT;
678
248
  }
679
680
2.86k
  if (ntohs(dnsHeader->qdcount) == 0) {
681
40
    return ENOENT;
682
40
  }
683
684
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
685
2.82k
  PacketReader packetReader(std::string_view(reinterpret_cast<const char*>(initialPacket.data()), initialPacket.size()));
686
687
2.82k
  size_t idx = 0;
688
2.82k
  DNSName rrname;
689
2.82k
  uint16_t qdcount = ntohs(dnsHeader->qdcount);
690
2.82k
  uint16_t ancount = ntohs(dnsHeader->ancount);
691
2.82k
  uint16_t nscount = ntohs(dnsHeader->nscount);
692
2.82k
  uint16_t arcount = ntohs(dnsHeader->arcount);
693
2.82k
  uint16_t rrtype = 0;
694
2.82k
  uint16_t rrclass = 0;
695
2.82k
  string blob;
696
2.82k
  dnsrecordheader recordHeader{};
697
698
2.82k
  rrname = packetReader.getName();
699
2.82k
  rrtype = packetReader.get16BitInt();
700
2.82k
  rrclass = packetReader.get16BitInt();
701
702
2.82k
  GenericDNSPacketWriter<PacketBuffer> packetWriter(newContent, rrname, rrtype, rrclass, dnsHeader->opcode);
703
2.82k
  packetWriter.getHeader()->id = dnsHeader->id;
704
2.82k
  packetWriter.getHeader()->qr = dnsHeader->qr;
705
2.82k
  packetWriter.getHeader()->aa = dnsHeader->aa;
706
2.82k
  packetWriter.getHeader()->tc = dnsHeader->tc;
707
2.82k
  packetWriter.getHeader()->rd = dnsHeader->rd;
708
2.82k
  packetWriter.getHeader()->ra = dnsHeader->ra;
709
2.82k
  packetWriter.getHeader()->ad = dnsHeader->ad;
710
2.82k
  packetWriter.getHeader()->cd = dnsHeader->cd;
711
2.82k
  packetWriter.getHeader()->rcode = dnsHeader->rcode;
712
713
  /* consume remaining qd if any */
714
2.82k
  if (qdcount > 1) {
715
145k
    for (idx = 1; idx < qdcount; idx++) {
716
144k
      rrname = packetReader.getName();
717
144k
      rrtype = packetReader.get16BitInt();
718
144k
      rrclass = packetReader.get16BitInt();
719
144k
      (void)rrtype;
720
144k
      (void)rrclass;
721
144k
    }
722
398
  }
723
724
  /* copy AN and NS */
725
18.8k
  for (idx = 0; idx < ancount; idx++) {
726
16.0k
    rrname = packetReader.getName();
727
16.0k
    packetReader.getDnsrecordheader(recordHeader);
728
729
16.0k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ANSWER, true);
730
16.0k
    packetReader.xfrBlob(blob);
731
16.0k
    packetWriter.xfrBlob(blob);
732
16.0k
  }
733
734
8.98k
  for (idx = 0; idx < nscount; idx++) {
735
6.16k
    rrname = packetReader.getName();
736
6.16k
    packetReader.getDnsrecordheader(recordHeader);
737
738
6.16k
    packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::AUTHORITY, true);
739
6.16k
    packetReader.xfrBlob(blob);
740
6.16k
    packetWriter.xfrBlob(blob);
741
6.16k
  }
742
743
  /* consume AR, looking for OPT */
744
28.2k
  for (idx = 0; idx < arcount; idx++) {
745
25.4k
    rrname = packetReader.getName();
746
25.4k
    packetReader.getDnsrecordheader(recordHeader);
747
748
25.4k
    if (!rrname.isRoot() || recordHeader.d_type != QType::OPT) {
749
19.1k
      packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, true);
750
19.1k
      packetReader.xfrBlob(blob);
751
19.1k
      packetWriter.xfrBlob(blob);
752
19.1k
    }
753
6.27k
    else {
754
6.27k
      packetWriter.startRecord(rrname, recordHeader.d_type, recordHeader.d_ttl, recordHeader.d_class, DNSResourceRecord::ADDITIONAL, false);
755
6.27k
      packetReader.xfrBlob(blob);
756
6.27k
      uint16_t rdLen = blob.length();
757
      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
758
6.27k
      removeEDNSOptionFromOptions(reinterpret_cast<unsigned char*>(blob.data()), rdLen, optionCodeToSkip, &rdLen);
759
      /* xfrBlob(string, size) completely ignores size.. */
760
6.27k
      if (rdLen > 0) {
761
2.62k
        blob.resize((size_t)rdLen);
762
2.62k
        packetWriter.xfrBlob(blob);
763
2.62k
      }
764
3.65k
      else {
765
3.65k
        packetWriter.commit();
766
3.65k
      }
767
6.27k
    }
768
25.4k
  }
769
2.82k
  packetWriter.commit();
770
771
2.82k
  return 0;
772
2.86k
}
773
774
bool addEDNS(PacketBuffer& packet, size_t maximumSize, bool dnssecOK, uint16_t payloadSize, uint8_t ednsrcode)
775
0
{
776
0
  if (!generateOptRR(std::string(), packet, maximumSize, payloadSize, ednsrcode, dnssecOK)) {
777
0
    return false;
778
0
  }
779
780
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [](dnsheader& header) {
781
0
    header.arcount = htons(ntohs(header.arcount) + 1);
782
0
    return true;
783
0
  });
784
785
0
  return true;
786
0
}
787
788
/*
789
  This function keeps the existing header and DNSSECOK bit (if any) but wipes anything else,
790
  generating a NXD or NODATA answer with a SOA record in the additional section (or optionally the authority section for a full cacheable NXDOMAIN/NODATA).
791
*/
792
bool setNegativeAndAdditionalSOA(DNSQuestion& dnsQuestion, bool nxd, const DNSName& zone, uint32_t ttl, const DNSName& mname, const DNSName& rname, uint32_t serial, uint32_t refresh, uint32_t retry, uint32_t expire, uint32_t minimum, bool soaInAuthoritySection)
793
0
{
794
0
  auto& packet = dnsQuestion.getMutableData();
795
0
  auto dnsHeader = dnsQuestion.getHeader();
796
0
  if (ntohs(dnsHeader->qdcount) != 1) {
797
0
    return false;
798
0
  }
799
800
0
  size_t queryPartSize = sizeof(dnsheader) + dnsQuestion.ids.qname.wirelength() + DNS_TYPE_SIZE + DNS_CLASS_SIZE;
801
0
  if (packet.size() < queryPartSize) {
802
    /* something is already wrong, don't build on flawed foundations */
803
0
    return false;
804
0
  }
805
806
0
  uint16_t qtype = htons(QType::SOA);
807
0
  uint16_t qclass = htons(QClass::IN);
808
0
  uint16_t rdLength = mname.wirelength() + rname.wirelength() + sizeof(serial) + sizeof(refresh) + sizeof(retry) + sizeof(expire) + sizeof(minimum);
809
0
  size_t soaSize = zone.wirelength() + sizeof(qtype) + sizeof(qclass) + sizeof(ttl) + sizeof(rdLength) + rdLength;
810
0
  bool hadEDNS = false;
811
0
  bool dnssecOK = false;
812
813
0
  if (dnsdist::configuration::getCurrentRuntimeConfiguration().d_addEDNSToSelfGeneratedResponses) {
814
0
    uint16_t payloadSize = 0;
815
0
    uint16_t zValue = 0;
816
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
817
0
    hadEDNS = getEDNSUDPPayloadSizeAndZ(reinterpret_cast<const char*>(packet.data()), packet.size(), &payloadSize, &zValue);
818
0
    if (hadEDNS) {
819
0
      dnssecOK = (zValue & EDNS_HEADER_FLAG_DO) != 0;
820
0
    }
821
0
  }
822
823
  /* chop off everything after the question */
824
0
  packet.resize(queryPartSize);
825
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [nxd](dnsheader& header) {
826
0
    if (nxd) {
827
0
      header.rcode = RCode::NXDomain;
828
0
    }
829
0
    else {
830
0
      header.rcode = RCode::NoError;
831
0
    }
832
0
    header.qr = true;
833
0
    header.ancount = 0;
834
0
    header.nscount = 0;
835
0
    header.arcount = 0;
836
0
    return true;
837
0
  });
838
839
0
  rdLength = htons(rdLength);
840
0
  ttl = htonl(ttl);
841
0
  serial = htonl(serial);
842
0
  refresh = htonl(refresh);
843
0
  retry = htonl(retry);
844
0
  expire = htonl(expire);
845
0
  minimum = htonl(minimum);
846
847
0
  std::string soa;
848
0
  soa.reserve(soaSize);
849
0
  soa.append(zone.toDNSString());
850
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
851
0
  soa.append(reinterpret_cast<const char*>(&qtype), sizeof(qtype));
852
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
853
0
  soa.append(reinterpret_cast<const char*>(&qclass), sizeof(qclass));
854
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
855
0
  soa.append(reinterpret_cast<const char*>(&ttl), sizeof(ttl));
856
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
857
0
  soa.append(reinterpret_cast<const char*>(&rdLength), sizeof(rdLength));
858
0
  soa.append(mname.toDNSString());
859
0
  soa.append(rname.toDNSString());
860
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
861
0
  soa.append(reinterpret_cast<const char*>(&serial), sizeof(serial));
862
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
863
0
  soa.append(reinterpret_cast<const char*>(&refresh), sizeof(refresh));
864
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
865
0
  soa.append(reinterpret_cast<const char*>(&retry), sizeof(retry));
866
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
867
0
  soa.append(reinterpret_cast<const char*>(&expire), sizeof(expire));
868
  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
869
0
  soa.append(reinterpret_cast<const char*>(&minimum), sizeof(minimum));
870
871
0
  if (soa.size() != soaSize) {
872
0
    throw std::runtime_error("Unexpected SOA response size: " + std::to_string(soa.size()) + " vs " + std::to_string(soaSize));
873
0
  }
874
875
0
  packet.insert(packet.end(), soa.begin(), soa.end());
876
877
  /* We are populating a response with only the query in place, order of sections is QD,AN,NS,AR
878
     NS (authority) is before AR (additional) so we can just decide which section the SOA record is in here
879
     and have EDNS added to AR afterwards */
880
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [soaInAuthoritySection](dnsheader& header) {
881
0
    if (soaInAuthoritySection) {
882
0
      header.nscount = htons(1);
883
0
    }
884
0
    else {
885
0
      header.arcount = htons(1);
886
0
    }
887
0
    return true;
888
0
  });
889
890
0
  if (hadEDNS) {
891
    /* now we need to add a new OPT record */
892
0
    return addEDNS(packet, dnsQuestion.getMaximumSize(), dnssecOK, dnsdist::configuration::getCurrentRuntimeConfiguration().d_payloadSizeSelfGenAnswers, dnsQuestion.ednsRCode);
893
0
  }
894
895
0
  return true;
896
0
}
897
898
bool addEDNSToQueryTurnedResponse(DNSQuestion& dnsQuestion)
899
0
{
900
0
  uint16_t optRDPosition{};
901
  /* remaining is at least the size of the rdlen + the options if any + the following records if any */
902
0
  size_t remaining = 0;
903
904
0
  auto& packet = dnsQuestion.getMutableData();
905
0
  int res = dnsdist::getEDNSOptionsStart(packet, dnsQuestion.ids.qname.wirelength(), &optRDPosition, &remaining);
906
907
0
  if (res != 0) {
908
    /* if the initial query did not have EDNS0, we are done */
909
0
    return true;
910
0
  }
911
912
0
  const size_t existingOptLen = /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + /* Z */ 2 + remaining;
913
0
  if (existingOptLen >= packet.size()) {
914
    /* something is wrong, bail out */
915
0
    return false;
916
0
  }
917
918
0
  const size_t optPosition = (optRDPosition - (/* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + /* Z */ 2));
919
920
0
  size_t zPosition = optPosition + /* root */ 1 + DNS_TYPE_SIZE + DNS_CLASS_SIZE + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE;
921
0
  uint16_t zValue = 0x100 * packet.at(zPosition) + packet.at(zPosition + 1);
922
0
  bool dnssecOK = (zValue & EDNS_HEADER_FLAG_DO) != 0;
923
924
  /* remove the existing OPT record, and everything else that follows (any SIG or TSIG would be useless anyway) */
925
0
  packet.resize(packet.size() - existingOptLen);
926
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(packet, [](dnsheader& header) {
927
0
    header.arcount = 0;
928
0
    return true;
929
0
  });
930
931
0
  if (dnsdist::configuration::getCurrentRuntimeConfiguration().d_addEDNSToSelfGeneratedResponses) {
932
    /* now we need to add a new OPT record */
933
0
    return addEDNS(packet, dnsQuestion.getMaximumSize(), dnssecOK, dnsdist::configuration::getCurrentRuntimeConfiguration().d_payloadSizeSelfGenAnswers, dnsQuestion.ednsRCode);
934
0
  }
935
936
  /* otherwise we are just fine */
937
0
  return true;
938
0
}
939
940
namespace dnsdist
941
{
942
static std::optional<size_t> getEDNSRecordPosition(const DNSQuestion& dnsQuestion)
943
0
{
944
0
  try {
945
0
    const auto& packet = dnsQuestion.getData();
946
0
    if (packet.size() <= sizeof(dnsheader)) {
947
0
      return std::nullopt;
948
0
    }
949
950
0
    uint16_t optRDPosition = 0;
951
0
    size_t remaining = 0;
952
0
    auto res = getEDNSOptionsStart(packet, dnsQuestion.ids.qname.wirelength(), &optRDPosition, &remaining);
953
0
    if (res != 0) {
954
0
      return std::nullopt;
955
0
    }
956
957
0
    if (optRDPosition < DNS_TTL_SIZE) {
958
0
      return std::nullopt;
959
0
    }
960
961
0
    return optRDPosition - DNS_TTL_SIZE;
962
0
  }
963
0
  catch (...) {
964
0
    return std::nullopt;
965
0
  }
966
0
}
967
968
// goal in life - if you send us a reasonably normal packet, we'll get Z for you, otherwise 0
969
int getEDNSZ(const DNSQuestion& dnsQuestion)
970
0
{
971
0
  try {
972
0
    auto position = getEDNSRecordPosition(dnsQuestion);
973
974
0
    if (!position) {
975
0
      return 0;
976
0
    }
977
978
0
    const auto& packet = dnsQuestion.getData();
979
0
    if ((*position + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + 1) >= packet.size()) {
980
0
      return 0;
981
0
    }
982
983
0
    return 0x100 * packet.at(*position + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE) + packet.at(*position + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE + 1);
984
0
  }
985
0
  catch (...) {
986
0
    return 0;
987
0
  }
988
0
}
989
990
std::optional<uint8_t> getEDNSVersion(const DNSQuestion& dnsQuestion)
991
0
{
992
0
  try {
993
0
    auto position = getEDNSRecordPosition(dnsQuestion);
994
995
0
    if (!position) {
996
0
      return std::nullopt;
997
0
    }
998
999
0
    const auto& packet = dnsQuestion.getData();
1000
0
    if ((*position + EDNS_EXTENDED_RCODE_SIZE + EDNS_VERSION_SIZE) >= packet.size()) {
1001
0
      return std::nullopt;
1002
0
    }
1003
1004
0
    return packet.at(*position + EDNS_EXTENDED_RCODE_SIZE);
1005
0
  }
1006
0
  catch (...) {
1007
0
    return std::nullopt;
1008
0
  }
1009
0
}
1010
1011
std::optional<uint8_t> getEDNSExtendedRCode(const DNSQuestion& dnsQuestion)
1012
0
{
1013
0
  try {
1014
0
    auto position = getEDNSRecordPosition(dnsQuestion);
1015
1016
0
    if (!position) {
1017
0
      return std::nullopt;
1018
0
    }
1019
1020
0
    const auto& packet = dnsQuestion.getData();
1021
0
    if ((*position + EDNS_EXTENDED_RCODE_SIZE) >= packet.size()) {
1022
0
      return std::nullopt;
1023
0
    }
1024
1025
0
    return packet.at(*position);
1026
0
  }
1027
0
  catch (...) {
1028
0
    return std::nullopt;
1029
0
  }
1030
0
}
1031
1032
}
1033
1034
bool queryHasEDNS(const DNSQuestion& dnsQuestion)
1035
0
{
1036
0
  uint16_t optRDPosition = 0;
1037
0
  size_t ecsRemaining = 0;
1038
1039
0
  int res = dnsdist::getEDNSOptionsStart(dnsQuestion.getData(), dnsQuestion.ids.qname.wirelength(), &optRDPosition, &ecsRemaining);
1040
0
  return res == 0;
1041
0
}
1042
1043
bool getEDNS0Record(const PacketBuffer& packet, EDNS0Record& edns0)
1044
3.11k
{
1045
3.11k
  uint16_t optStart = 0;
1046
3.11k
  size_t optLen = 0;
1047
3.11k
  bool last = false;
1048
3.11k
  int res = locateEDNSOptRR(packet, &optStart, &optLen, &last);
1049
3.11k
  if (res != 0) {
1050
    // no EDNS OPT RR
1051
362
    return false;
1052
362
  }
1053
1054
2.75k
  if (optLen < optRecordMinimumSize) {
1055
0
    return false;
1056
0
  }
1057
1058
2.75k
  if (optStart < packet.size() && packet.at(optStart) != 0) {
1059
    // OPT RR Name != '.'
1060
39
    return false;
1061
39
  }
1062
1063
2.71k
  static_assert(sizeof(EDNS0Record) == sizeof(uint32_t), "sizeof(EDNS0Record) must match sizeof(uint32_t) AKA RR TTL size");
1064
  // copy out 4-byte "ttl" (really the EDNS0 record), after root label (1) + type (2) + class (2).
1065
2.71k
  memcpy(&edns0, &packet.at(optStart + 5), sizeof edns0);
1066
2.71k
  return true;
1067
2.75k
}
1068
1069
bool setEDNSOption(PacketBuffer& buf, uint16_t ednsCode, const std::string& ednsData, size_t maximumSize, bool& ednsAdded, bool& optionAdded)
1070
0
{
1071
0
  if (buf.size() < sizeof(dnsheader)) {
1072
0
    return false;
1073
0
  }
1074
0
  std::string optRData;
1075
0
  generateEDNSOption(ednsCode, ednsData, optRData);
1076
1077
0
  const dnsheader_aligned dnsHeader(buf.data());
1078
0
  if (dnsHeader->arcount != 0) {
1079
0
    ednsAdded = false;
1080
0
    optionAdded = false;
1081
0
    PacketBuffer newContent;
1082
0
    newContent.reserve(buf.size());
1083
1084
0
    if (!slowRewriteEDNSOptionInQueryWithRecords(buf, newContent, ednsAdded, ednsCode, optionAdded, true, false, optRData)) {
1085
0
      return false;
1086
0
    }
1087
1088
0
    if (newContent.size() > maximumSize) {
1089
0
      return false;
1090
0
    }
1091
1092
0
    buf = std::move(newContent);
1093
0
    return true;
1094
0
  }
1095
1096
0
  if (!generateOptRR(optRData, buf, maximumSize, dnsdist::configuration::s_EdnsUDPPayloadSize, 0, false)) {
1097
0
    return false;
1098
0
  }
1099
1100
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(buf, [](dnsheader& header) {
1101
0
    header.arcount = htons(1);
1102
0
    return true;
1103
0
  });
1104
0
  ednsAdded = true;
1105
1106
0
  return true;
1107
0
}
1108
1109
bool setEDNSOption(DNSQuestion& dnsQuestion, uint16_t ednsCode, const std::string& ednsData, bool isQuery)
1110
0
{
1111
0
  bool ednsAdded = false;
1112
0
  bool optionAdded = false;
1113
0
  auto ret = setEDNSOption(dnsQuestion.getMutableData(), ednsCode, ednsData, dnsQuestion.getMaximumSize(), ednsAdded, optionAdded);
1114
0
  if (!ret) {
1115
0
    return ret;
1116
0
  }
1117
1118
0
  if (isQuery && !dnsQuestion.ids.ednsAdded && ednsAdded) {
1119
0
    dnsQuestion.ids.ednsAdded = true;
1120
0
  }
1121
1122
0
  return true;
1123
0
}
1124
1125
namespace dnsdist
1126
{
1127
bool setInternalQueryRCode(InternalQueryState& state, PacketBuffer& buffer, uint8_t rcode, bool clearAnswers)
1128
0
{
1129
0
  const auto qnameLength = state.qname.wirelength();
1130
0
  if (buffer.size() < sizeof(dnsheader) + qnameLength + sizeof(uint16_t) + sizeof(uint16_t)) {
1131
0
    return false;
1132
0
  }
1133
1134
0
  EDNS0Record edns0{};
1135
0
  bool hadEDNS = false;
1136
0
  if (clearAnswers) {
1137
0
    hadEDNS = getEDNS0Record(buffer, edns0);
1138
0
  }
1139
1140
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(buffer, [rcode, clearAnswers](dnsheader& header) {
1141
0
    header.rcode = rcode;
1142
0
    header.ad = false;
1143
0
    header.aa = false;
1144
0
    header.ra = header.rd;
1145
0
    header.qr = true;
1146
1147
0
    if (clearAnswers) {
1148
0
      header.ancount = 0;
1149
0
      header.nscount = 0;
1150
0
      header.arcount = 0;
1151
0
    }
1152
0
    return true;
1153
0
  });
1154
1155
0
  if (clearAnswers) {
1156
0
    buffer.resize(sizeof(dnsheader) + qnameLength + sizeof(uint16_t) + sizeof(uint16_t));
1157
0
    if (hadEDNS) {
1158
0
      DNSQuestion dnsQuestion(state, buffer);
1159
0
      if (!addEDNS(buffer, dnsQuestion.getMaximumSize(), (edns0.extFlags & htons(EDNS_HEADER_FLAG_DO)) != 0, dnsdist::configuration::getCurrentRuntimeConfiguration().d_payloadSizeSelfGenAnswers, 0)) {
1160
0
        return false;
1161
0
      }
1162
0
    }
1163
0
  }
1164
1165
0
  return true;
1166
0
}
1167
}