]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/dnsdistdist/docs/rules-actions.rst
Merge pull request #7904 from rgacogne/rec-filterpo-optims
[thirdparty/pdns.git] / pdns / dnsdistdist / docs / rules-actions.rst
1 Packet Policies
2 ===============
3
4 dnsdist works in essence like any other loadbalancer:
5
6 It receives packets on one or several addresses it listens on, and determines whether it will process this packet based on the :doc:`advanced/acl`. Should the packet be processed, dnsdist attempts to match any of the configured rules in order and when one matches, the associated action is performed.
7
8 These rule and action combinations are considered policies.
9
10 Packet Actions
11 --------------
12
13 Each packet can be:
14
15 - Dropped
16 - Turned into an answer directly
17 - Forwarded to a downstream server
18 - Modified and forwarded to a downstream and be modified back
19 - Be delayed
20
21 This decision can be taken at different times during the forwarding process.
22
23 Examples
24 ~~~~~~~~
25
26 Rules for traffic exceeding QPS limits
27 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
28
29 Traffic that exceeds a QPS limit, in total or per IP (subnet) can be matched by a rule.
30
31 For example::
32
33 addAction(MaxQPSIPRule(5, 32, 48), DelayAction(100))
34
35 This measures traffic per IPv4 address and per /48 of IPv6, and if traffic for such an address (range) exceeds 5 qps, it gets delayed by 100ms.
36
37 As another example::
38
39 addAction(MaxQPSIPRule(5), NoRecurseAction())
40
41 This strips the Recursion Desired (RD) bit from any traffic per IPv4 or IPv6 /64 that exceeds 5 qps.
42 This means any those traffic bins is allowed to make a recursor do 'work' for only 5 qps.
43
44 If this is not enough, try::
45
46 addAction(MaxQPSIPRule(5), DropAction())
47
48 or::
49
50 addAction(MaxQPSIPRule(5), TCAction())
51
52 This will respectively drop traffic exceeding that 5 QPS limit per IP or range, or return it with TC=1, forcing clients to fall back to TCP.
53
54 To turn this per IP or range limit into a global limit, use ``NotRule(MaxQPSRule(5000))`` instead of :func:`MaxQPSIPRule`.
55
56 Regular Expressions
57 ^^^^^^^^^^^^^^^^^^^
58
59 :func:`RegexRule` matches a regular expression on the query name, and it works like this::
60
61 addAction(RegexRule("[0-9]{5,}"), DelayAction(750)) -- milliseconds
62 addAction(RegexRule("[0-9]{4,}\\.example$"), DropAction())
63
64 This delays any query for a domain name with 5 or more consecutive digits in it.
65 The second rule drops anything with more than 4 consecutive digits within a .example domain.
66
67 Note that the query name is presented without a trailing dot to the regex.
68 The regex is applied case insensitively.
69
70 Alternatively, if compiled in, :func:`RE2Rule` provides similar functionality, but against libre2.
71
72 Rule Generators
73 ---------------
74
75 :program:`dnsdist` contains several functions that make it easier to add actions and rules.
76
77 .. function:: addAnyTCRule()
78
79 .. deprecated:: 1.2.0
80
81 Set the TC-bit (truncate) on ANY queries received over UDP, forcing a retry over TCP.
82 This function is deprecated as of 1.2.0 and will be removed in 1.3.0. This is equivalent to doing::
83
84 addAction(AndRule({QTypeRule(DNSQType.ANY), TCPRule(false)}), TCAction())
85
86 .. versionchanged:: 1.4.0
87 Before 1.4.0, the QTypes were in the ``dnsdist`` namespace. Use ``dnsdist.ANY`` in these versions.
88
89 .. function:: addDelay(DNSrule, delay)
90
91 .. deprecated:: 1.2.0
92
93 Delay the query for ``delay`` milliseconds before sending to a backend.
94 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use instead:
95
96 addAction(DNSRule, DelayAction(delay))
97
98 :param DNSRule: The DNSRule to match traffic
99 :param int delay: The delay time in milliseconds.
100
101 .. function:: addDisableValidationRule(DNSrule)
102
103 .. deprecated:: 1.2.0
104
105 Set the CD (Checking Disabled) flag to 1 for all queries matching the DNSRule.
106 This function is deprecated as of 1.2.0 and will be removed in 1.3.0. Please use the :func:`DisableValidationAction` action instead.
107
108 .. function:: addDomainBlock(domain)
109
110 .. deprecated:: 1.2.0
111
112 Drop all queries for ``domain`` and all names below it.
113 Deprecated as of 1.2.0 and will be removed in 1.3.0, please use instead:
114
115 addAction(domain, DropAction())
116
117 :param string domain: The domain name to block
118
119 .. function:: addDomainSpoof(domain, IPv4[, IPv6])
120 addDomainSpoof(domain, {IP[,...]})
121
122 .. deprecated:: 1.2.0
123
124 Generate answers for A/AAAA/ANY queries.
125 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:
126
127 addAction(domain, SpoofAction({IP[,...]}))
128
129 or:
130
131 addAction(domain, SpoofAction(IPv4[, IPv6]))
132
133 :param string domain: Domain name to spoof for
134 :param string IPv4: IPv4 address to spoof in the reply
135 :param string IPv6: IPv6 address to spoof in the reply
136 :param string IP: IP address to spoof in the reply
137
138 .. function:: addDomainCNAMESpoof(domain, cname)
139
140 .. deprecated:: 1.2.0
141
142 Generate CNAME answers for queries. This function is deprecated as of 1.2.0 and will be removed in 1.3.0, in favor of using:
143
144 addAction(domain, SpoofCNAMEAction(cname))
145
146 :param string domain: Domain name to spoof for
147 :param string cname: Domain name to add CNAME to
148
149 .. function:: addLuaAction(DNSrule, function [, options])
150
151 .. versionchanged:: 1.3.0
152 Added the optional parameter ``options``.
153
154 .. versionchanged:: 1.3.0
155 The second argument returned by the ``function`` can be omitted. For earlier releases, simply return an empty string.
156
157 .. deprecated:: 1.4.0
158 Removed in 1.4.0, use :func:`LuaAction` with :func:`addAction` instead.
159
160 Invoke a Lua function that accepts a :class:`DNSQuestion`.
161 This function works similar to using :func:`LuaAction`.
162 The ``function`` should return both a :ref:`DNSAction` and its argument `rule`. The `rule` is used as an argument
163 of the following :ref:`DNSAction`: `DNSAction.Spoof`, `DNSAction.Pool` and `DNSAction.Delay`.
164 If the Lua code fails, ServFail is returned.
165
166 :param DNSRule: match queries based on this rule
167 :param string function: the name of a Lua function
168 :param table options: A table with key: value pairs with options.
169
170 Options:
171
172 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
173
174 ::
175
176 function luarule(dq)
177 if(dq.qtype==dnsdist.NAPTR)
178 then
179 return DNSAction.Pool, "abuse" -- send to abuse pool
180 else
181 return DNSAction.None, "" -- no action
182 -- return DNSAction.None -- as of dnsdist version 1.3.0
183 end
184 end
185
186 addLuaAction(AllRule(), luarule)
187
188 .. function:: addLuaResponseAction(DNSrule, function [, options])
189
190 .. versionchanged:: 1.3.0
191 Added the optional parameter ``options``.
192
193 .. versionchanged:: 1.3.0
194 The second argument returned by the ``function`` can be omitted. For earlier releases, simply return an empty string.
195
196 .. deprecated:: 1.4.0
197 Removed in 1.4.0, use :func:`LuaResponseAction` with :func:`addResponseAction` instead.
198
199 Invoke a Lua function that accepts a :class:`DNSResponse`.
200 This function works similar to using :func:`LuaResponseAction`.
201 The ``function`` should return both a :ref:`DNSResponseAction` and its argument `rule`. The `rule` is used as an argument
202 of the `DNSResponseAction.Delay`.
203 If the Lua code fails, ServFail is returned.
204
205 :param DNSRule: match queries based on this rule
206 :param string function: the name of a Lua function
207 :param table options: A table with key: value pairs with options.
208
209 Options:
210
211 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
212
213 .. function:: addNoRecurseRule(DNSrule)
214
215 .. deprecated:: 1.2.0
216
217 Clear the RD flag for all queries matching the rule.
218 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:
219
220 addAction(DNSRule, NoRecurseAction())
221
222 :param DNSRule: match queries based on this rule
223
224 .. function:: addPoolRule(DNSRule, pool)
225
226 .. deprecated:: 1.2.0
227
228 Send queries matching the first argument to the pool ``pool``.
229 e.g.::
230
231 addPoolRule("example.com", "myPool")
232
233 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, this is equivalent to::
234
235 addAction("example.com", PoolAction("myPool"))
236
237 :param DNSRule: match queries based on this rule
238 :param string pool: The name of the pool to send the queries to
239
240 .. function:: addQPSLimit(DNSrule, limit)
241
242 .. deprecated:: 1.2.0
243
244 Limit queries matching the DNSRule to ``limit`` queries per second.
245 All queries over the limit are dropped.
246 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, please use:
247
248 addAction(DNSRule, QPSAction(limit))
249
250 :param DNSRule: match queries based on this rule
251 :param int limit: QPS limit for this rule
252
253 .. function:: addQPSPoolRule(DNSRule, limit, pool)
254
255 .. deprecated:: 1.2.0
256
257 Send at most ``limit`` queries/s for this pool, letting the subsequent rules apply otherwise.
258 This function is deprecated as of 1.2.0 and will be removed in 1.3.0, as it is only a convience function for the following syntax::
259
260 addAction("192.0.2.0/24", QPSPoolAction(15, "myPool")
261
262 :param DNSRule: match queries based on this rule
263 :param int limit: QPS limit for this rule
264 :param string pool: The name of the pool to send the queries to
265
266
267 Managing Rules
268 --------------
269
270 Active Rules can be shown with :func:`showRules` and removed with :func:`rmRule`::
271
272 > addAction("h4xorbooter.xyz.", QPSAction(10))
273 > addAction({"130.161.0.0/16", "145.14.0.0/16"} , QPSAction(20))
274 > addAction({"nl.", "be."}, QPSAction(1))
275 > showRules()
276 # Matches Rule Action
277 0 0 h4xorbooter.xyz. qps limit to 10
278 1 0 130.161.0.0/16, 145.14.0.0/16 qps limit to 20
279 2 0 nl., be. qps limit to 1
280
281 For Rules related to the incoming query:
282
283 .. function:: addAction(DNSrule, action [, options])
284
285 .. versionchanged:: 1.3.0
286 Added the optional parameter ``options``.
287
288 Add a Rule and Action to the existing rules.
289
290 :param DNSrule rule: A DNSRule, e.g. an :func:`AllRule` or a compounded bunch of rules using e.g. :func:`AndRule`
291 :param action: The action to take
292 :param table options: A table with key: value pairs with options.
293
294 Options:
295
296 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
297
298 .. function:: clearRules()
299
300 Remove all current rules.
301
302 .. function:: getAction(n) -> Action
303
304 Returns the Action associated with rule ``n``.
305
306 :param int n: The rule number
307
308 .. function:: mvRule(from, to)
309
310 Move rule ``from`` to a position where it is in front of ``to``.
311 ``to`` can be one larger than the largest rule, in which case the rule will be moved to the last position.
312
313 :param int from: Rule number to move
314 :param int to: Location to more the Rule to
315
316 .. function:: newRuleAction(rule, action[, options])
317
318 .. versionchanged:: 1.3.0
319 Added the optional parameter ``options``.
320
321 Return a pair of DNS Rule and DNS Action, to be used with :func:`setRules`.
322
323 :param Rule rule: A `Rule <#traffic-matching>`_
324 :param Action action: The `Action <#actions>`_ to apply to the matched traffic
325 :param table options: A table with key: value pairs with options.
326
327 Options:
328
329 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
330
331 .. function:: setRules(rules)
332
333 Replace the current rules with the supplied list of pairs of DNS Rules and DNS Actions (see :func:`newRuleAction`)
334
335 :param [RuleAction] rules: A list of RuleActions
336
337 .. function:: showRules([options])
338
339 .. versionchanged:: 1.3.0
340 ``options`` optional parameter added
341
342 Show all defined rules for queries, optionally displaying their UUIDs.
343
344 :param table options: A table with key: value pairs with display options.
345
346 Options:
347
348 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
349 * ``truncateRuleWidth=-1``: int - Truncate rules output to ``truncateRuleWidth`` size. Defaults to ``-1`` to display the full rule.
350
351 .. function:: topRule()
352
353 Move the last rule to the first position.
354
355 .. function:: rmRule(id)
356
357 .. versionchanged:: 1.3.0
358 ``id`` can now be an UUID.
359
360 Remove rule ``id``.
361
362 :param int id: The UUID of the rule to remove if ``id`` is an UUID, its position otherwise
363
364 For Rules related to responses:
365
366 .. function:: addResponseAction(DNSRule, action [, options])
367
368 .. versionchanged:: 1.3.0
369 Added the optional parameter ``options``.
370
371 Add a Rule and Action for responses to the existing rules.
372
373 :param DNSRule: A DNSRule, e.g. an :func:`AllRule` or a compounded bunch of rules using e.g. :func:`AndRule`
374 :param action: The action to take
375 :param table options: A table with key: value pairs with options.
376
377 Options:
378
379 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
380
381 .. function:: mvResponseRule(from, to)
382
383 Move response rule ``from`` to a position where it is in front of ``to``.
384 ``to`` can be one larger than the largest rule, in which case the rule will be moved to the last position.
385
386 :param int from: Rule number to move
387 :param int to: Location to more the Rule to
388
389 .. function:: rmResponseRule(id)
390
391 .. versionchanged:: 1.3.0
392 ``id`` can now be an UUID.
393
394 Remove response rule ``id``.
395
396 :param int id: The UUID of the rule to remove if ``id`` is an UUID, its position otherwise
397
398 .. function:: showResponseRules([options])
399
400 .. versionchanged:: 1.3.0
401 ``options`` optional parameter added
402
403 Show all defined response rules, optionally displaying their UUIDs.
404
405 :param table options: A table with key: value pairs with display options.
406
407 Options:
408
409 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
410 * ``truncateRuleWidth=-1``: int - Truncate rules output to ``truncateRuleWidth`` size. Defaults to ``-1`` to display the full rule.
411
412 .. function:: topResponseRule()
413
414 Move the last response rule to the first position.
415
416 Functions for manipulating Cache Hit Respone Rules:
417
418 .. function:: addCacheHitResponseAction(DNSRule, action [, options])
419
420 .. versionadded:: 1.2.0
421
422 .. versionchanged:: 1.3.0
423 Added the optional parameter ``options``.
424
425 Add a Rule and ResponseAction for Cache Hits to the existing rules.
426
427 :param DNSRule: A DNSRule, e.g. an :func:`AllRule` or a compounded bunch of rules using e.g. :func:`AndRule`
428 :param action: The action to take
429 :param table options: A table with key: value pairs with options.
430
431 Options:
432
433 * ``uuid``: string - UUID to assign to the new rule. By default a random UUID is generated for each rule.
434
435 .. function:: mvCacheHitResponseRule(from, to)
436
437 .. versionadded:: 1.2.0
438
439 Move cache hit response rule ``from`` to a position where it is in front of ``to``.
440 ``to`` can be one larger than the largest rule, in which case the rule will be moved to the last position.
441
442 :param int from: Rule number to move
443 :param int to: Location to more the Rule to
444
445 .. function:: rmCacheHitResponseRule(id)
446
447 .. versionadded:: 1.2.0
448
449 .. versionchanged:: 1.3.0
450 ``id`` can now be an UUID.
451
452 :param int id: The UUID of the rule to remove if ``id`` is an UUID, its position otherwise
453
454 .. function:: showCacheHitResponseRules([options])
455
456 .. versionadded:: 1.2.0
457
458 .. versionchanged:: 1.3.0
459 ``options`` optional parameter added
460
461 Show all defined cache hit response rules, optionally displaying their UUIDs.
462
463 :param table options: A table with key: value pairs with display options.
464
465 Options:
466
467 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
468 * ``truncateRuleWidth=-1``: int - Truncate rules output to ``truncateRuleWidth`` size. Defaults to ``-1`` to display the full rule.
469
470 .. function:: topCacheHitResponseRule()
471
472 .. versionadded:: 1.2.0
473
474 Move the last cache hit response rule to the first position.
475
476 Functions for manipulating Self-Answered Response Rules:
477
478 .. function:: addSelfAnsweredResponseAction(DNSRule, action [, options])
479
480 .. versionadded:: 1.3.0
481
482 Add a Rule and Action for Self-Answered queries to the existing rules.
483
484 :param DNSRule: A DNSRule, e.g. an :func:`AllRule` or a compounded bunch of rules using e.g. :func:`AndRule`
485 :param action: The action to take
486
487 .. function:: mvSelfAnsweredResponseRule(from, to)
488
489 .. versionadded:: 1.3.0
490
491 Move self answered response rule ``from`` to a position where it is in front of ``to``.
492 ``to`` can be one larger than the largest rule, in which case the rule will be moved to the last position.
493
494 :param int from: Rule number to move
495 :param int to: Location to more the Rule to
496
497 .. function:: rmSelfAnsweredResponseRule(id)
498
499 .. versionadded:: 1.3.0
500
501 Remove self answered response rule ``id``.
502
503 :param int id: The UUID of the rule to remove if ``id`` is an UUID, its position otherwise
504
505 .. function:: showSelfAnsweredResponseRules([options])
506
507 .. versionadded:: 1.3.0
508
509 Show all defined self answered response rules, optionally displaying their UUIDs.
510
511 :param table options: A table with key: value pairs with display options.
512
513 Options:
514
515 * ``showUUIDs=false``: bool - Whether to display the UUIDs, defaults to false.
516 * ``truncateRuleWidth=-1``: int - Truncate rules output to ``truncateRuleWidth`` size. Defaults to ``-1`` to display the full rule.
517
518 .. function:: topSelfAnsweredResponseRule()
519
520 .. versionadded:: 1.3.0
521
522 Move the last self answered response rule to the first position.
523
524 .. _RulesIntro:
525
526 Matching Packets (Selectors)
527 ----------------------------
528
529 Packets can be matched by selectors, called a ``DNSRule``.
530 These ``DNSRule``\ s be one of the following items:
531
532 * A string that is either a domain name or netmask
533 * A list of strings that are either domain names or netmasks
534 * A :class:`DNSName`
535 * A list of :class:`DNSName`\ s
536 * A (compounded) ``Rule``
537
538 .. versionadded:: 1.2.0
539 A DNSRule can also be a :class:`DNSName` or a list of these
540
541 .. function:: AllRule()
542
543 Matches all traffic
544
545 .. function:: DNSSECRule()
546
547 Matches queries with the DO flag set
548
549 .. function:: DSTPortRule(port)
550
551 Matches questions received to the destination port.
552
553 :param int port: Match destination port.
554
555 .. function:: EDNSOptionRule(optcode)
556
557 .. versionadded:: 1.4.0
558
559 Matches queries or responses with the specified EDNS option present.
560 ``optcode`` is specified as an integer, or a constant such as `EDNSOptionCode.ECS`.
561
562 .. function:: EDNSVersionRule(version)
563
564 .. versionadded:: 1.4.0
565
566 Matches queries or responses with an OPT record whose EDNS version is greater than the specified EDNS version.
567
568 :param int version: The EDNS version to match on
569
570 .. function:: ERCodeRule(rcode)
571
572 Matches queries or responses with the specified ``rcode``.
573 ``rcode`` can be specified as an integer or as one of the built-in :ref:`DNSRCode`.
574 The full 16bit RCode will be matched. If no EDNS OPT RR is present, the upper 12 bits are treated as 0.
575
576 :param int rcode: The RCODE to match on
577
578 .. function:: HTTPHeaderRule(name, regex)
579 .. versionadded:: 1.4.0
580
581 Matches DNS over HTTPS queries with a HTTP header ``name`` whose content matches the regular expression ``regex``.
582
583 :param str name: The case-insensitive name of the HTTP header to match on
584 :param str regex: A regular expression to match the content of the specified header
585
586 .. function:: HTTPPathRule(path)
587 .. versionadded:: 1.4.0
588
589 Matches DNS over HTTPS queries with a HTTP path of ``path``. For example, if the query has been sent to the https://192.0.2.1:443/PowerDNS?dns=... URL, the path would be '/PowerDNS'.
590
591 :param str path: The exact HTTP path to match on
592
593 .. function:: MaxQPSIPRule(qps[, v4Mask[, v6Mask[, burst[, expiration[, cleanupDelay[, scanFraction]]]]]])
594 .. versionchanged:: 1.3.1
595 Added the optional parameters ``expiration``, ``cleanupDelay`` and ``scanFraction``.
596
597 Matches traffic for a subnet specified by ``v4Mask`` or ``v6Mask`` exceeding ``qps`` queries per second up to ``burst`` allowed.
598 This rule keeps track of QPS by netmask or source IP. This state is cleaned up regularly if ``cleanupDelay`` is greater than zero,
599 removing existing netmasks or IP addresses that have not been seen in the last ``expiration`` seconds.
600
601 :param int qps: The number of queries per second allowed, above this number traffic is matched
602 :param int v4Mask: The IPv4 netmask to match on. Default is 32 (the whole address)
603 :param int v6Mask: The IPv6 netmask to match on. Default is 64
604 :param int burst: The number of burstable queries per second allowed. Default is same as qps
605 :param int expiration: How long to keep netmask or IP addresses after they have last been seen, in seconds. Default is 300
606 :param int cleanupDelay: The number of seconds between two cleanups. Default is 60
607 :param int scanFraction: The maximum fraction of the store to scan for expired entries, for example 5 would scan at most 20% of it. Default is 10 so 10%
608
609 .. function:: MaxQPSRule(qps)
610
611 Matches traffic **not** exceeding this qps limit. If e.g. this is set to 50, starting at the 51st query of the current second traffic stops being matched.
612 This can be used to enforce a global QPS limit.
613
614 :param int qps: The number of queries per second allowed, above this number the traffic is **not** matched anymore
615
616 .. function:: NetmaskGroupRule(nmg[, src])
617
618 Matches traffic from/to the network range specified in ``nmg``.
619
620 Set the ``src`` parameter to false to match ``nmg`` against destination address instead of source address.
621 This can be used to differentiate between clients
622
623 :param NetMaskGroup nmg: The NetMaskGroup to match on
624 :param bool src: Whether to match source or destination address of the packet. Defaults to true (matches source)
625
626 .. function:: OpcodeRule(code)
627
628 Matches queries with opcode ``code``.
629 ``code`` can be directly specified as an integer, or one of the :ref:`built-in DNSOpcodes <DNSOpcode>`.
630
631 :param int code: The opcode to match
632
633 .. function:: ProbaRule(probability)
634
635 .. versionadded:: 1.3.0
636
637 Matches queries with a given probability. 1.0 means "always"
638
639 :param double probability: Probability of a match
640
641 .. function:: QClassRule(qclass)
642
643 Matches queries with the specified ``qclass``.
644 ``class`` can be specified as an integer or as one of the built-in :ref:`DNSClass`.
645
646 :param int qclass: The Query Class to match on
647
648 .. function:: QNameRule(qname)
649
650 .. versionadded:: 1.2.0
651
652 Matches queries with the specified qname exactly.
653
654 :param string qname: Qname to match
655
656 .. function:: QNameSetRule(set)
657
658 .. versionadded:: 1.4.0
659
660 Matches if the set contains exact qname.
661
662 To match subdomain names, see :func:`SuffixMatchNodeRule`.
663
664 :param DNSNameSet set: Set with qnames.
665
666 .. function:: QNameLabelsCountRule(min, max)
667
668 Matches if the qname has less than ``min`` or more than ``max`` labels.
669
670 :param int min: Minimum number of labels
671 :param int max: Maximum nimber of labels
672
673 .. function:: QNameWireLengthRule(min, max)
674
675 Matches if the qname's length on the wire is less than ``min`` or more than ``max`` bytes.
676
677 :param int min: Minimum number of bytes
678 :param int max: Maximum nimber of bytes
679
680 .. function:: QTypeRule(qtype)
681
682 Matches queries with the specified ``qtype``
683 ``qtype`` may be specified as an integer or as one of the built-in QTypes.
684 For instance ``dnsdist.A``, ``dnsdist.TXT`` and ``dnsdist.ANY``.
685
686 :param int qtype: The QType to match on
687
688 .. function:: RCodeRule(rcode)
689
690 Matches queries or responses with the specified ``rcode``.
691 ``rcode`` can be specified as an integer or as one of the built-in :ref:`DNSRCode`.
692 Only the non-extended RCode is matched (lower 4bits).
693
694 :param int rcode: The RCODE to match on
695
696 .. function:: RDRule()
697
698 .. versionadded:: 1.2.0
699
700 Matches queries with the RD flag set.
701
702 .. function:: RegexRule(regex)
703
704 Matches the query name against the ``regex``.
705
706 .. code-block:: Lua
707
708 addAction(RegexRule("[0-9]{5,}"), DelayAction(750)) -- milliseconds
709 addAction(RegexRule("[0-9]{4,}\\.example$"), DropAction())
710
711 This delays any query for a domain name with 5 or more consecutive digits in it.
712 The second rule drops anything with more than 4 consecutive digits within a .EXAMPLE domain.
713
714 Note that the query name is presented without a trailing dot to the regex.
715 The regex is applied case insensitively.
716
717 :param string regex: A regular expression to match the traffic on
718
719 .. function:: RecordsCountRule(section, minCount, maxCount)
720
721 Matches if there is at least ``minCount`` and at most ``maxCount`` records in the section ``section``.
722 ``section`` can be specified as an integer or as a :ref:`DNSSection`.
723
724 :param int section: The section to match on
725 :param int minCount: The minimum number of entries
726 :param int maxCount: The maximum number of entries
727
728 .. function:: RecordsTypeCountRule(section, qtype, minCount, maxCount)
729
730 Matches if there is at least ``minCount`` and at most ``maxCount`` records of type ``type`` in the section ``section``.
731 ``section`` can be specified as an integer or as a :ref:`DNSSection`.
732 ``qtype`` may be specified as an integer or as one of the :ref:`built-in QTypes <DNSQType>`, for instance ``DNSQType.A`` or ``DNSQType.TXT``.
733
734 :param int section: The section to match on
735 :param int qtype: The QTYPE to match on
736 :param int minCount: The minimum number of entries
737 :param int maxCount: The maximum number of entries
738
739 .. function:: RE2Rule(regex)
740
741 Matches the query name against the supplied regex using the RE2 engine.
742
743 For an example of usage, see :func:`RegexRule`.
744
745 :note: Only available when dnsdist was built with libre2 support.
746
747 :param str regex: The regular expression to match the QNAME.
748
749 .. function:: SNIRule(name)
750 .. versionadded:: 1.4.0
751
752 Matches against the TLS Server Name Indication value sent by the client, if any. Only makes
753 sense for DoT or DoH, and for that last one matching on the HTTP Host header using :func:`HTTPHeaderRule`
754 might provide more consistent results.
755 As of the version 2.3.0-beta of h2o, it is unfortunately not possible to extract the SNI value from DoH
756 connections, and it is therefore necessary to use the HTTP Host header until version 2.3.0 is released.
757
758 :param str name: The exact SNI name to match.
759
760 .. function:: SuffixMatchNodeRule(smn[, quiet])
761
762 Matches based on a group of domain suffixes for rapid testing of membership.
763 Pass true as second parameter to prevent listing of all domains matched.
764
765 To match domain names exactly, see :func:`QNameSetRule`.
766
767 :param SuffixMatchNode smb: The SuffixMatchNode to match on
768 :param bool quiet: Do not return the list of matched domains. Default is false.
769
770 .. function:: TagRule(name [, value])
771
772 .. versionadded:: 1.3.0
773
774 Matches question or answer with a tag named ``name`` set. If ``value`` is specified, the existing tag value should match too.
775
776 :param bool name: The name of the tag that has to be set
777 :param bool value: If set, the value the tag has to be set to. Default is unset
778
779 .. function:: TCPRule([tcp])
780
781 Matches question received over TCP if ``tcp`` is true, over UDP otherwise.
782
783 :param bool tcp: Match TCP traffic. Default is true.
784
785 .. function:: TrailingDataRule()
786
787 Matches if the query has trailing data.
788
789 .. function:: PoolAvailableRule(poolname)
790
791 .. versionadded:: 1.3.3
792
793 Check whether a pool has any servers available to handle queries
794
795 .. code-block:: Lua
796
797 --- Send queries to default pool when servers are available
798 addAction(PoolAvailableRule(""), PoolAction(""))
799 --- Send queries to fallback pool if not
800 addAction(AllRule(), PoolAction("fallback"))
801
802 :param string poolname: Pool to check
803
804 Combining Rules
805 ~~~~~~~~~~~~~~~
806
807 .. function:: AndRule(selectors)
808
809 Matches traffic if all ``selectors`` match.
810
811 :param {Rule} selectors: A table of Rules
812
813 .. function:: NotRule(selector)
814
815 Matches the traffic if the ``selector`` rule does not match;
816
817 :param Rule selector: A Rule
818
819 .. function:: OrRule(selectors)
820
821 Matches the traffic if one or more of the the ``selectors`` Rules does match.
822
823 :param {Rule} selector: A table of Rules
824
825 Convenience Functions
826 ~~~~~~~~~~~~~~~~~~~~~
827
828 .. function:: makeRule(rule)
829
830 Make a :func:`NetmaskGroupRule` or a :func:`SuffixMatchNodeRule`, depending on it is called.
831 ``makeRule("0.0.0.0/0")`` will for example match all IPv4 traffic, ``makeRule({"be","nl","lu"})`` will match all Benelux DNS traffic.
832
833 :param string rule: A string to convert to a rule.
834
835
836 Actions
837 -------
838
839 :ref:`RulesIntro` need to be combined with an action for them to actually do something with the matched packets.
840 Some actions allow further processing of rules, this is noted in their description.
841 The following actions exist.
842
843 .. function:: AllowAction()
844
845 Let these packets go through.
846
847 .. function:: AllowResponseAction()
848
849 Let these packets go through.
850
851 .. function:: DelayAction(milliseconds)
852
853 Delay the response by the specified amount of milliseconds (UDP-only).
854 Subsequent rules are processed after this action.
855
856 :param int milliseconds: The amount of milliseconds to delay the response
857
858 .. function:: DelayResponseAction(milliseconds)
859
860 Delay the response by the specified amount of milliseconds (UDP-only).
861 Subsequent rules are processed after this action.
862
863 :param int milliseconds: The amount of milliseconds to delay the response
864
865 .. function:: DisableECSAction()
866
867 Disable the sending of ECS to the backend.
868 Subsequent rules are processed after this action.
869
870 .. function:: DisableValidationAction()
871
872 Set the CD bit in the query and let it go through.
873
874 .. function:: DnstapLogAction(identity, logger[, alterFunction])
875
876 .. versionadded:: 1.3.0
877
878 Send the the current query to a remote logger as a :doc:`dnstap <reference/dnstap>` message.
879 ``alterFunction`` is a callback, receiving a :class:`DNSQuestion` and a :class:`DnstapMessage`, that can be used to modify the message.
880
881 :param string identity: Server identity to store in the dnstap message
882 :param logger: The :func:`FrameStreamLogger <newFrameStreamUnixLogger>` or :func:`RemoteLogger <newRemoteLogger>` object to write to
883 :param alterFunction: A Lua function to alter the message before sending
884
885 .. function:: DnstapLogResponseAction(identity, logger[, alterFunction])
886
887 .. versionadded:: 1.3.0
888
889 Send the the current response to a remote logger as a :doc:`dnstap <reference/dnstap>` message.
890 ``alterFunction`` is a callback, receiving a :class:`DNSQuestion` and a :class:`DnstapMessage`, that can be used to modify the message.
891
892 :param string identity: Server identity to store in the dnstap message
893 :param logger: The :func:`FrameStreamLogger <newFrameStreamUnixLogger>` or :func:`RemoteLogger <newRemoteLogger>` object to write to
894 :param alterFunction: A Lua function to alter the message before sending
895
896 .. function:: DropAction()
897
898 Drop the packet.
899
900 .. function:: DropResponseAction()
901
902 Drop the packet.
903
904 .. function:: ECSOverrideAction(override)
905
906 Whether an existing EDNS Client Subnet value should be overridden (true) or not (false).
907 Subsequent rules are processed after this action.
908
909 :param bool override: Whether or not to override ECS value
910
911 .. function:: ECSPrefixLengthAction(v4, v6)
912
913 Set the ECS prefix length.
914 Subsequent rules are processed after this action.
915
916 :param int v4: The IPv4 netmask length
917 :param int v6: The IPv6 netmask length
918
919
920 .. function:: ERCodeAction(rcode)
921
922 .. versionadded:: 1.4.0
923
924 Reply immediately by turning the query into a response with the specified EDNS extended ``rcode``.
925 ``rcode`` can be specified as an integer or as one of the built-in :ref:`DNSRCode`.
926
927 :param int rcode: The extended RCODE to respond with.
928
929 .. function:: LogAction([filename[, binary[, append[, buffered]]]])
930
931 Log a line for each query, to the specified ``file`` if any, to the console (require verbose) otherwise.
932 When logging to a file, the ``binary`` optional parameter specifies whether we log in binary form (default) or in textual form.
933 The ``append`` optional parameter specifies whether we open the file for appending or truncate each time (default).
934 The ``buffered`` optional parameter specifies whether writes to the file are buffered (default) or not.
935 Subsequent rules are processed after this action.
936
937 :param string filename: File to log to. Set to an empty string to log to the normal stdout log, this only works when ``-v`` is set on the command line.
938 :param bool binary: Do binary logging. Default true
939 :param bool append: Append to the log. Default false
940 :param bool buffered: Use buffered I/O. default true
941
942 .. function:: LuaAction(function)
943
944 Invoke a Lua function that accepts a :class:`DNSQuestion`.
945
946 The ``function`` should return a :ref:`DNSAction`. If the Lua code fails, ServFail is returned.
947
948 :param string function: the name of a Lua function
949
950 .. function:: LuaResponseAction(function)
951
952 Invoke a Lua function that accepts a :class:`DNSResponse`.
953
954 The ``function`` should return a :ref:`DNSResponseAction`. If the Lua code fails, ServFail is returned.
955
956 :param string function: the name of a Lua function
957
958 .. function:: MacAddrAction(option)
959
960 Add the source MAC address to the query as EDNS0 option ``option``.
961 This action is currently only supported on Linux.
962 Subsequent rules are processed after this action.
963
964 :param int option: The EDNS0 option number
965
966 .. function:: NoneAction()
967
968 Does nothing.
969 Subsequent rules are processed after this action.
970
971 .. function:: NoRecurseAction()
972
973 Strip RD bit from the question, let it go through.
974 Subsequent rules are processed after this action.
975
976 .. function:: PoolAction(poolname)
977
978 Send the packet into the specified pool.
979
980 :param string poolname: The name of the pool
981
982 .. function:: QPSAction(maxqps)
983
984 Drop a packet if it does exceed the ``maxqps`` queries per second limits.
985 Letting the subsequent rules apply otherwise.
986
987 :param int maxqps: The QPS limit
988
989 .. function:: QPSPoolAction(maxqps, poolname)
990
991 Send the packet into the specified pool only if it does not exceed the ``maxqps`` queries per second limits.
992 Letting the subsequent rules apply otherwise.
993
994 :param int maxqps: The QPS limit for that pool
995 :param string poolname: The name of the pool
996
997 .. function:: RCodeAction(rcode)
998
999 Reply immediately by turning the query into a response with the specified ``rcode``.
1000 ``rcode`` can be specified as an integer or as one of the built-in :ref:`DNSRCode`.
1001
1002 :param int rcode: The RCODE to respond with.
1003
1004 .. function:: RemoteLogAction(remoteLogger[, alterFunction [, options]])
1005
1006 .. versionchanged:: 1.3.0
1007 ``options`` optional parameter added.
1008
1009 .. versionchanged:: 1.4.0
1010 ``ipEncryptKey`` optional key added to the options table.
1011
1012 Send the content of this query to a remote logger via Protocol Buffer.
1013 ``alterFunction`` is a callback, receiving a :class:`DNSQuestion` and a :class:`DNSDistProtoBufMessage`, that can be used to modify the Protocol Buffer content, for example for anonymization purposes
1014
1015 :param string remoteLogger: The :func:`remoteLogger <newRemoteLogger>` object to write to
1016 :param string alterFunction: Name of a function to modify the contents of the logs before sending
1017 :param table options: A table with key: value pairs.
1018
1019 Options:
1020
1021 * ``serverID=""``: str - Set the Server Identity field.
1022 * ``ipEncryptKey=""``: str - A key, that can be generated via the :func:`makeIPCipherKey` function, to encrypt the IP address of the requestor for anonymization purposes. The encryption is done using ipcrypt for IPv4 and a 128-bit AES ECB operation for IPv6.
1023
1024 .. function:: RemoteLogResponseAction(remoteLogger[, alterFunction[, includeCNAME [, options]]])
1025
1026 .. versionchanged:: 1.3.0
1027 ``options`` optional parameter added.
1028
1029 .. versionchanged:: 1.4.0
1030 ``ipEncryptKey`` optional key added to the options table.
1031
1032 Send the content of this response to a remote logger via Protocol Buffer.
1033 ``alterFunction`` is the same callback that receiving a :class:`DNSQuestion` and a :class:`DNSDistProtoBufMessage`, that can be used to modify the Protocol Buffer content, for example for anonymization purposes
1034 ``includeCNAME`` indicates whether CNAME records inside the response should be parsed and exported.
1035 The default is to only exports A and AAAA records
1036
1037 :param string remoteLogger: The :func:`remoteLogger <newRemoteLogger>` object to write to
1038 :param string alterFunction: Name of a function to modify the contents of the logs before sending
1039 :param bool includeCNAME: Whether or not to parse and export CNAMEs. Default false
1040 :param table options: A table with key: value pairs.
1041
1042 Options:
1043
1044 * ``serverID=""``: str - Set the Server Identity field.
1045 * ``ipEncryptKey=""``: str - A key, that can be generated via the :func:`makeIPCipherKey` function, to encrypt the IP address of the requestor for anonymization purposes. The encryption is done using ipcrypt for IPv4 and a 128-bit AES ECB operation for IPv6.
1046
1047 .. function:: SetECSAction(v4 [, v6])
1048
1049 .. versionadded:: 1.3.1
1050
1051 Set the ECS prefix and prefix length sent to backends to an arbitrary value.
1052 If both IPv4 and IPv6 masks are supplied the IPv4 one will be used for IPv4 clients
1053 and the IPv6 one for IPv6 clients. Otherwise the first mask is used for both, and
1054 can actually be an IPv6 mask.
1055 Subsequent rules are processed after this action.
1056
1057 :param string v4: The IPv4 netmask, for example "192.0.2.1/32"
1058 :param string v6: The IPv6 netmask, if any
1059
1060 .. function:: SkipCacheAction()
1061
1062 Don't lookup the cache for this query, don't store the answer.
1063
1064 .. function:: SNMPTrapAction([message])
1065
1066 Send an SNMP trap, adding the optional ``message`` string as the query description.
1067 Subsequent rules are processed after this action.
1068
1069 :param string message: The message to include
1070
1071 .. function:: SNMPTrapResponseAction([message])
1072
1073 Send an SNMP trap, adding the optional ``message`` string as the query description.
1074 Subsequent rules are processed after this action.
1075
1076 :param string message: The message to include
1077
1078 .. function:: SpoofAction(ip[, ip[...]])
1079 SpoofAction(ips)
1080
1081 Forge a response with the specified IPv4 (for an A query) or IPv6 (for an AAAA) addresses.
1082 If you specify multiple addresses, all that match the query type (A, AAAA or ANY) will get spoofed in.
1083
1084 :param string ip: An IPv4 and/or IPv6 address to spoof
1085 :param {string} ips: A table of IPv4 and/or IPv6 addresses to spoof
1086
1087 .. function:: SpoofCNAMEAction(cname)
1088
1089 Forge a response with the specified CNAME value.
1090
1091 :param string cname: The name to respond with
1092
1093 .. function:: TagAction(name, value)
1094
1095 .. versionadded:: 1.3.0
1096
1097 Associate a tag named ``name`` with a value of ``value`` to this query, that will be passed on to the response.
1098
1099 :param string name: The name of the tag to set
1100 :param string cname: The value of the tag
1101
1102 .. function:: TagResponseAction(name, value)
1103
1104 .. versionadded:: 1.3.0
1105
1106 Associate a tag named ``name`` with a value of ``value`` to this response.
1107
1108 :param string name: The name of the tag to set
1109 :param string cname: The value of the tag
1110
1111 .. function:: TCAction()
1112
1113 Create answer to query with TC and RD bits set, to force the client to TCP.
1114
1115 .. function:: TeeAction(remote[, addECS])
1116
1117 Send copy of query to ``remote``, keep stats on responses.
1118 If ``addECS`` is set to true, EDNS Client Subnet information will be added to the query.
1119
1120 :param string remote: An IP:PORT conbination to send the copied queries to
1121 :param bool addECS: Whether or not to add ECS information. Default false
1122
1123 .. function:: TempFailureCacheTTLAction(ttl)
1124
1125 Set the cache TTL to use for ServFail and Refused replies. TTL is not applied for successful replies.
1126
1127 :param int ttl: Cache TTL for temporary failure replies