2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
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.
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.
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.
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.
24 #include <unordered_set>
27 #include "dnsdist-rings.hh"
28 #include "statnode.hh"
30 #include "dnsdist-lua-inspection-ffi.hh"
32 // dnsdist_ffi_stat_node_t is a lightuserdata
34 struct LuaContext::Pusher<dnsdist_ffi_stat_node_t*> {
35 static const int minSize = 1;
36 static const int maxSize = 1;
38 static PushedObject push(lua_State* state, dnsdist_ffi_stat_node_t* ptr) noexcept {
39 lua_pushlightuserdata(state, ptr);
40 return PushedObject{state, 1};
44 typedef std::function<bool(dnsdist_ffi_stat_node_t*)> dnsdist_ffi_stat_node_visitor_t;
46 struct dnsdist_ffi_stat_node_t
48 dnsdist_ffi_stat_node_t(const StatNode& node_, const StatNode::Stat& self_, const StatNode::Stat& children_): node(node_), self(self_), children(children_)
53 const StatNode::Stat& self;
54 const StatNode::Stat& children;
57 class DynBlockRulesGroup
63 std::map<uint8_t, uint64_t> d_rcodeCounts;
64 std::map<uint16_t, uint64_t> d_qtypeCounts;
66 uint64_t respBytes{0};
71 DynBlockRule(): d_enabled(false)
75 DynBlockRule(const std::string& blockReason, unsigned int blockDuration, unsigned int rate, unsigned int warningRate, unsigned int seconds, DNSAction::Action action): d_blockReason(blockReason), d_blockDuration(blockDuration), d_rate(rate), d_warningRate(warningRate), d_seconds(seconds), d_action(action), d_enabled(true)
79 bool matches(const struct timespec& when)
85 if (d_seconds && when < d_cutOff) {
89 if (when < d_minTime) {
96 bool rateExceeded(unsigned int count, const struct timespec& now) const
102 double delta = d_seconds ? d_seconds : DiffTime(now, d_minTime);
103 double limit = delta * d_rate;
104 return (count > limit);
107 bool warningRateExceeded(unsigned int count, const struct timespec& now) const
109 if (d_warningRate == 0) {
113 double delta = d_seconds ? d_seconds : DiffTime(now, d_minTime);
114 double limit = delta * d_warningRate;
115 return (count > limit);
118 bool isEnabled() const
123 std::string toString() const
129 std::stringstream result;
130 if (d_action != DNSAction::Action::None) {
131 result << DNSAction::typeToString(d_action) << " ";
134 result << "Apply the global DynBlock action ";
136 result << "for " << std::to_string(d_blockDuration) << " seconds when over " << std::to_string(d_rate) << " during the last " << d_seconds << " seconds, reason: '" << d_blockReason << "'";
141 std::string d_blockReason;
142 struct timespec d_cutOff;
143 struct timespec d_minTime;
144 unsigned int d_blockDuration{0};
145 unsigned int d_rate{0};
146 unsigned int d_warningRate{0};
147 unsigned int d_seconds{0};
148 DNSAction::Action d_action{DNSAction::Action::None};
149 bool d_enabled{false};
152 typedef std::unordered_map<ComboAddress, Counts, ComboAddress::addressOnlyHash, ComboAddress::addressOnlyEqual> counts_t;
159 void setQueryRate(unsigned int rate, unsigned int warningRate, unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action)
161 d_queryRateRule = DynBlockRule(reason, blockDuration, rate, warningRate, seconds, action);
164 /* rate is in bytes per second */
165 void setResponseByteRate(unsigned int rate, unsigned int warningRate, unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action)
167 d_respRateRule = DynBlockRule(reason, blockDuration, rate, warningRate, seconds, action);
170 void setRCodeRate(uint8_t rcode, unsigned int rate, unsigned int warningRate, unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action)
172 auto& entry = d_rcodeRules[rcode];
173 entry = DynBlockRule(reason, blockDuration, rate, warningRate, seconds, action);
176 void setQTypeRate(uint16_t qtype, unsigned int rate, unsigned int warningRate, unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action)
178 auto& entry = d_qtypeRules[qtype];
179 entry = DynBlockRule(reason, blockDuration, rate, warningRate, seconds, action);
182 typedef std::function<bool(const StatNode&, const StatNode::Stat&, const StatNode::Stat&)> smtVisitor_t;
184 void setSuffixMatchRule(unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action, smtVisitor_t visitor)
186 d_suffixMatchRule = DynBlockRule(reason, blockDuration, 0, 0, seconds, action);
187 d_smtVisitor = visitor;
190 void setSuffixMatchRuleFFI(unsigned int seconds, std::string reason, unsigned int blockDuration, DNSAction::Action action, dnsdist_ffi_stat_node_visitor_t visitor)
192 d_suffixMatchRule = DynBlockRule(reason, blockDuration, 0, 0, seconds, action);
193 d_smtVisitorFFI = visitor;
204 void apply(const struct timespec& now)
207 StatNode statNodeRoot;
209 size_t entriesCount = 0;
210 if (hasQueryRules()) {
211 entriesCount += g_rings.getNumberOfQueryEntries();
213 if (hasResponseRules()) {
214 entriesCount += g_rings.getNumberOfResponseEntries();
216 counts.reserve(entriesCount);
218 processQueryRules(counts, now);
219 processResponseRules(counts, statNodeRoot, now);
221 if (counts.empty() && statNodeRoot.empty()) {
225 boost::optional<NetmaskTree<DynBlock> > blocks;
226 bool updated = false;
228 for (const auto& entry : counts) {
229 const auto& requestor = entry.first;
230 const auto& counters = entry.second;
232 if (d_queryRateRule.warningRateExceeded(counters.queries, now)) {
233 handleWarning(blocks, now, requestor, d_queryRateRule, updated);
236 if (d_queryRateRule.rateExceeded(counters.queries, now)) {
237 addBlock(blocks, now, requestor, d_queryRateRule, updated);
241 if (d_respRateRule.warningRateExceeded(counters.respBytes, now)) {
242 handleWarning(blocks, now, requestor, d_respRateRule, updated);
245 if (d_respRateRule.rateExceeded(counters.respBytes, now)) {
246 addBlock(blocks, now, requestor, d_respRateRule, updated);
250 for (const auto& pair : d_qtypeRules) {
251 const auto qtype = pair.first;
253 const auto& typeIt = counters.d_qtypeCounts.find(qtype);
254 if (typeIt != counters.d_qtypeCounts.cend()) {
256 if (pair.second.warningRateExceeded(typeIt->second, now)) {
257 handleWarning(blocks, now, requestor, pair.second, updated);
260 if (pair.second.rateExceeded(typeIt->second, now)) {
261 addBlock(blocks, now, requestor, pair.second, updated);
267 for (const auto& pair : d_rcodeRules) {
268 const auto rcode = pair.first;
270 const auto& rcodeIt = counters.d_rcodeCounts.find(rcode);
271 if (rcodeIt != counters.d_rcodeCounts.cend()) {
272 if (pair.second.warningRateExceeded(rcodeIt->second, now)) {
273 handleWarning(blocks, now, requestor, pair.second, updated);
276 if (pair.second.rateExceeded(rcodeIt->second, now)) {
277 addBlock(blocks, now, requestor, pair.second, updated);
284 if (updated && blocks) {
285 g_dynblockNMG.setState(*blocks);
288 if (!statNodeRoot.empty()) {
290 std::unordered_set<DNSName> namesToBlock;
291 statNodeRoot.visit([this,&namesToBlock](const StatNode* node_, const StatNode::Stat& self, const StatNode::Stat& children) {
294 if (d_smtVisitorFFI) {
295 dnsdist_ffi_stat_node_t tmp(*node_, self, children);
296 block = d_smtVisitorFFI(&tmp);
299 block = d_smtVisitor(*node_, self, children);
303 namesToBlock.insert(DNSName(node_->fullname));
308 if (!namesToBlock.empty()) {
310 SuffixMatchTree<DynBlock> smtBlocks = g_dynblockSMT.getCopy();
311 for (const auto& name : namesToBlock) {
312 addOrRefreshBlockSMT(smtBlocks, now, name, d_suffixMatchRule, updated);
315 g_dynblockSMT.setState(smtBlocks);
321 void excludeRange(const Netmask& range)
323 d_excludedSubnets.addMask(range);
326 void includeRange(const Netmask& range)
328 d_excludedSubnets.addMask(range, false);
331 void excludeDomain(const DNSName& domain)
333 d_excludedDomains.add(domain);
336 std::string toString() const
338 std::stringstream result;
340 result << "Query rate rule: " << d_queryRateRule.toString() << std::endl;
341 result << "Response rate rule: " << d_respRateRule.toString() << std::endl;
342 result << "SuffixMatch rule: " << d_suffixMatchRule.toString() << std::endl;
343 result << "RCode rules: " << std::endl;
344 for (const auto& rule : d_rcodeRules) {
345 result << "- " << RCode::to_s(rule.first) << ": " << rule.second.toString() << std::endl;
347 result << "QType rules: " << std::endl;
348 for (const auto& rule : d_qtypeRules) {
349 result << "- " << QType(rule.first).getName() << ": " << rule.second.toString() << std::endl;
351 result << "Excluded Subnets: " << d_excludedSubnets.toString() << std::endl;
352 result << "Excluded Domains: " << d_excludedDomains.toString() << std::endl;
357 void setQuiet(bool quiet)
363 bool checkIfQueryTypeMatches(const Rings::Query& query)
365 auto rule = d_qtypeRules.find(query.qtype);
366 if (rule == d_qtypeRules.end()) {
370 return rule->second.matches(query.when);
373 bool checkIfResponseCodeMatches(const Rings::Response& response)
375 auto rule = d_rcodeRules.find(response.dh.rcode);
376 if (rule == d_rcodeRules.end()) {
380 return rule->second.matches(response.when);
383 void addOrRefreshBlock(boost::optional<NetmaskTree<DynBlock> >& blocks, const struct timespec& now, const ComboAddress& requestor, const DynBlockRule& rule, bool& updated, bool warning)
385 if (d_excludedSubnets.match(requestor)) {
386 /* do not add a block for excluded subnets */
391 blocks = g_dynblockNMG.getCopy();
393 struct timespec until = now;
394 until.tv_sec += rule.d_blockDuration;
395 unsigned int count = 0;
396 const auto& got = blocks->lookup(Netmask(requestor));
397 bool expired = false;
398 bool wasWarning = false;
401 if (warning && !got->second.warning) {
402 /* we have an existing entry which is not a warning,
406 else if (!warning && got->second.warning) {
410 if (until < got->second.until) {
411 // had a longer policy
416 if (now < got->second.until) {
417 // only inherit count on fresh query we are extending
418 count = got->second.blocks;
425 DynBlock db{rule.d_blockReason, until, DNSName(), warning ? DNSAction::Action::NoOp : rule.d_action};
427 db.warning = warning;
428 if (!d_beQuiet && (!got || expired || wasWarning)) {
429 warnlog("Inserting %sdynamic block for %s for %d seconds: %s", warning ? "(warning) " :"", requestor.toString(), rule.d_blockDuration, rule.d_blockReason);
431 blocks->insert(Netmask(requestor)).second = db;
435 void addOrRefreshBlockSMT(SuffixMatchTree<DynBlock>& blocks, const struct timespec& now, const DNSName& name, const DynBlockRule& rule, bool& updated)
437 if (d_excludedDomains.check(name)) {
438 /* do not add a block for excluded domains */
442 struct timespec until = now;
443 until.tv_sec += rule.d_blockDuration;
444 unsigned int count = 0;
445 const auto& got = blocks.lookup(name);
446 bool expired = false;
449 if (until < got->until) {
450 // had a longer policy
454 if (now < got->until) {
455 // only inherit count on fresh query we are extending
463 DynBlock db{rule.d_blockReason, until, name, rule.d_action};
466 if (!d_beQuiet && (!got || expired)) {
467 warnlog("Inserting dynamic block for %s for %d seconds: %s", name, rule.d_blockDuration, rule.d_blockReason);
469 blocks.add(name, db);
473 void addBlock(boost::optional<NetmaskTree<DynBlock> >& blocks, const struct timespec& now, const ComboAddress& requestor, const DynBlockRule& rule, bool& updated)
475 addOrRefreshBlock(blocks, now, requestor, rule, updated, false);
478 void handleWarning(boost::optional<NetmaskTree<DynBlock> >& blocks, const struct timespec& now, const ComboAddress& requestor, const DynBlockRule& rule, bool& updated)
480 addOrRefreshBlock(blocks, now, requestor, rule, updated, true);
483 bool hasQueryRules() const
485 return d_queryRateRule.isEnabled() || !d_qtypeRules.empty();
488 bool hasResponseRules() const
490 return d_respRateRule.isEnabled() || !d_rcodeRules.empty();
493 bool hasSuffixMatchRules() const
495 return d_suffixMatchRule.isEnabled();
498 bool hasRules() const
500 return hasQueryRules() || hasResponseRules();
503 void processQueryRules(counts_t& counts, const struct timespec& now)
505 if (!hasQueryRules()) {
509 d_queryRateRule.d_cutOff = d_queryRateRule.d_minTime = now;
510 d_queryRateRule.d_cutOff.tv_sec -= d_queryRateRule.d_seconds;
512 for (auto& rule : d_qtypeRules) {
513 rule.second.d_cutOff = rule.second.d_minTime = now;
514 rule.second.d_cutOff.tv_sec -= rule.second.d_seconds;
517 for (const auto& shard : g_rings.d_shards) {
518 std::lock_guard<std::mutex> rl(shard->queryLock);
519 for(const auto& c : shard->queryRing) {
524 bool qRateMatches = d_queryRateRule.matches(c.when);
525 bool typeRuleMatches = checkIfQueryTypeMatches(c);
527 if (qRateMatches || typeRuleMatches) {
528 auto& entry = counts[c.requestor];
532 if (typeRuleMatches) {
533 entry.d_qtypeCounts[c.qtype]++;
540 void processResponseRules(counts_t& counts, StatNode& root, const struct timespec& now)
542 if (!hasResponseRules() && !hasSuffixMatchRules()) {
546 d_respRateRule.d_cutOff = d_respRateRule.d_minTime = now;
547 d_respRateRule.d_cutOff.tv_sec -= d_respRateRule.d_seconds;
549 d_suffixMatchRule.d_cutOff = d_suffixMatchRule.d_minTime = now;
550 d_suffixMatchRule.d_cutOff.tv_sec -= d_suffixMatchRule.d_seconds;
552 for (auto& rule : d_rcodeRules) {
553 rule.second.d_cutOff = rule.second.d_minTime = now;
554 rule.second.d_cutOff.tv_sec -= rule.second.d_seconds;
557 for (const auto& shard : g_rings.d_shards) {
558 std::lock_guard<std::mutex> rl(shard->respLock);
559 for(const auto& c : shard->respRing) {
564 bool respRateMatches = d_respRateRule.matches(c.when);
565 bool suffixMatchRuleMatches = d_suffixMatchRule.matches(c.when);
566 bool rcodeRuleMatches = checkIfResponseCodeMatches(c);
568 if (respRateMatches || rcodeRuleMatches) {
569 auto& entry = counts[c.requestor];
570 if (respRateMatches) {
571 entry.respBytes += c.size;
573 if (rcodeRuleMatches) {
574 entry.d_rcodeCounts[c.dh.rcode]++;
578 if (suffixMatchRuleMatches) {
579 root.submit(c.name, c.dh.rcode, boost::none);
585 std::map<uint8_t, DynBlockRule> d_rcodeRules;
586 std::map<uint16_t, DynBlockRule> d_qtypeRules;
587 DynBlockRule d_queryRateRule;
588 DynBlockRule d_respRateRule;
589 DynBlockRule d_suffixMatchRule;
590 NetmaskGroup d_excludedSubnets;
591 SuffixMatchNode d_excludedDomains;
592 smtVisitor_t d_smtVisitor;
593 dnsdist_ffi_stat_node_visitor_t d_smtVisitorFFI;
594 bool d_beQuiet{false};