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.
23 #include "threadname.hh"
25 #include "dnsdist-ecs.hh"
26 #include "dnsdist-lua.hh"
27 #include "dnsdist-protobuf.hh"
28 #include "dnsdist-kvs.hh"
32 #include "ednsoptions.hh"
33 #include "fstrm_logger.hh"
34 #include "remote_logger.hh"
36 #include <boost/optional/optional_io.hpp>
39 #include "ipcipher.hh"
40 #endif /* HAVE_LIBCRYPTO */
42 class DropAction
: public DNSAction
45 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
49 std::string
toString() const override
55 class AllowAction
: public DNSAction
58 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
62 std::string
toString() const override
68 class NoneAction
: public DNSAction
71 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
75 std::string
toString() const override
81 class QPSAction
: public DNSAction
84 QPSAction(int limit
) : d_qps(limit
, limit
)
86 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
93 std::string
toString() const override
95 return "qps limit to "+std::to_string(d_qps
.getRate());
101 class DelayAction
: public DNSAction
104 DelayAction(int msec
) : d_msec(msec
)
106 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
108 *ruleresult
=std::to_string(d_msec
);
109 return Action::Delay
;
111 std::string
toString() const override
113 return "delay by "+std::to_string(d_msec
)+ " msec";
120 class TeeAction
: public DNSAction
123 TeeAction(const ComboAddress
& ca
, bool addECS
=false);
124 ~TeeAction() override
;
125 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
;
126 std::string
toString() const override
;
127 std::map
<std::string
, double> getStats() const override
;
130 ComboAddress d_remote
;
131 std::thread d_worker
;
135 mutable std::atomic
<unsigned long> d_senderrors
{0};
136 unsigned long d_recverrors
{0};
137 mutable std::atomic
<unsigned long> d_queries
{0};
138 unsigned long d_responses
{0};
139 unsigned long d_nxdomains
{0};
140 unsigned long d_servfails
{0};
141 unsigned long d_refuseds
{0};
142 unsigned long d_formerrs
{0};
143 unsigned long d_notimps
{0};
144 unsigned long d_noerrors
{0};
145 mutable unsigned long d_tcpdrops
{0};
146 unsigned long d_otherrcode
{0};
147 std::atomic
<bool> d_pleaseQuit
{false};
148 bool d_addECS
{false};
151 TeeAction::TeeAction(const ComboAddress
& ca
, bool addECS
) : d_remote(ca
), d_addECS(addECS
)
153 d_fd
=SSocket(d_remote
.sin4
.sin_family
, SOCK_DGRAM
, 0);
154 SConnect(d_fd
, d_remote
);
155 setNonBlocking(d_fd
);
156 d_worker
=std::thread(std::bind(&TeeAction::worker
, this));
159 TeeAction::~TeeAction()
166 DNSAction::Action
TeeAction::operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const
177 uint16_t len
= dq
->len
;
178 bool ednsAdded
= false;
179 bool ecsAdded
= false;
180 query
.reserve(dq
->size
);
181 query
.assign((char*) dq
->dh
, len
);
183 std::string newECSOption
;
184 generateECSOption(dq
->ecsSet
? dq
->ecs
.getNetwork() : *dq
->remote
, newECSOption
, dq
->ecsSet
? dq
->ecs
.getBits() : dq
->ecsPrefixLength
);
186 if (!handleEDNSClientSubnet(const_cast<char*>(query
.c_str()), query
.capacity(), dq
->qname
->wirelength(), &len
, &ednsAdded
, &ecsAdded
, dq
->ecsOverride
, newECSOption
, g_preserveTrailingData
)) {
187 return DNSAction::Action::None
;
190 res
= send(d_fd
, query
.c_str(), len
, 0);
193 res
= send(d_fd
, (char*)dq
->dh
, dq
->len
, 0);
199 return DNSAction::Action::None
;
202 std::string
TeeAction::toString() const
204 return "tee to "+d_remote
.toStringWithPort();
207 std::map
<std::string
,double> TeeAction::getStats() const
209 return {{"queries", d_queries
},
210 {"responses", d_responses
},
211 {"recv-errors", d_recverrors
},
212 {"send-errors", d_senderrors
},
213 {"noerrors", d_noerrors
},
214 {"nxdomains", d_nxdomains
},
215 {"refuseds", d_refuseds
},
216 {"servfails", d_servfails
},
217 {"other-rcode", d_otherrcode
},
218 {"tcp-drops", d_tcpdrops
}
222 void TeeAction::worker()
224 setThreadName("dnsdist/TeeWork");
227 struct dnsheader
* dh
=(struct dnsheader
*)packet
;
229 res
=waitForData(d_fd
, 0, 250000);
238 res
=recv(d_fd
, packet
, sizeof(packet
), 0);
239 if(res
<= (int)sizeof(struct dnsheader
))
244 if(dh
->rcode
== RCode::NoError
)
246 else if(dh
->rcode
== RCode::ServFail
)
248 else if(dh
->rcode
== RCode::NXDomain
)
250 else if(dh
->rcode
== RCode::Refused
)
252 else if(dh
->rcode
== RCode::FormErr
)
254 else if(dh
->rcode
== RCode::NotImp
)
259 class PoolAction
: public DNSAction
262 PoolAction(const std::string
& pool
) : d_pool(pool
) {}
263 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
268 std::string
toString() const override
270 return "to pool "+d_pool
;
278 class QPSPoolAction
: public DNSAction
281 QPSPoolAction(unsigned int limit
, const std::string
& pool
) : d_qps(limit
, limit
), d_pool(pool
) {}
282 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
291 std::string
toString() const override
293 return "max " +std::to_string(d_qps
.getRate())+" to pool "+d_pool
;
301 class RCodeAction
: public DNSAction
304 RCodeAction(uint8_t rcode
) : d_rcode(rcode
) {}
305 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
307 dq
->dh
->rcode
= d_rcode
;
308 dq
->dh
->qr
= true; // for good measure
309 return Action::HeaderModify
;
311 std::string
toString() const override
313 return "set rcode "+std::to_string(d_rcode
);
320 class ERCodeAction
: public DNSAction
323 ERCodeAction(uint8_t rcode
) : d_rcode(rcode
) {}
324 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
326 dq
->dh
->rcode
= (d_rcode
& 0xF);
327 dq
->ednsRCode
= ((d_rcode
& 0xFFF0) >> 4);
328 dq
->dh
->qr
= true; // for good measure
329 return Action::HeaderModify
;
331 std::string
toString() const override
333 return "set ercode "+ERCode::to_s(d_rcode
);
340 class TCAction
: public DNSAction
343 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
345 return Action::Truncate
;
347 std::string
toString() const override
349 return "tc=1 answer";
353 DNSAction::Action
LuaAction::operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const
355 std::lock_guard
<std::mutex
> lock(g_luamutex
);
357 auto ret
= d_func(dq
);
359 if (boost::optional
<std::string
> rule
= std::get
<1>(ret
)) {
363 // default to empty string
367 return (Action
)std::get
<0>(ret
);
368 } catch (std::exception
&e
) {
369 warnlog("LuaAction failed inside lua, returning ServFail: %s", e
.what());
371 warnlog("LuaAction failed inside lua, returning ServFail: [unknown exception]");
373 return DNSAction::Action::ServFail
;
376 DNSResponseAction::Action
LuaResponseAction::operator()(DNSResponse
* dr
, std::string
* ruleresult
) const
378 std::lock_guard
<std::mutex
> lock(g_luamutex
);
380 auto ret
= d_func(dr
);
382 if (boost::optional
<std::string
> rule
= std::get
<1>(ret
)) {
386 // default to empty string
390 return (Action
)std::get
<0>(ret
);
391 } catch (std::exception
&e
) {
392 warnlog("LuaResponseAction failed inside lua, returning ServFail: %s", e
.what());
394 warnlog("LuaResponseAction failed inside lua, returning ServFail: [unknown exception]");
396 return DNSResponseAction::Action::ServFail
;
399 DNSAction::Action
SpoofAction::operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const
401 uint16_t qtype
= dq
->qtype
;
402 // do we even have a response?
403 if(d_cname
.empty() && !std::count_if(d_addrs
.begin(), d_addrs
.end(), [qtype
](const ComboAddress
& a
)
405 return (qtype
== QType::ANY
|| ((a
.sin4
.sin_family
== AF_INET
&& qtype
== QType::A
) ||
406 (a
.sin4
.sin_family
== AF_INET6
&& qtype
== QType::AAAA
)));
410 vector
<ComboAddress
> addrs
;
411 unsigned int totrdatalen
=0;
412 if (!d_cname
.empty()) {
413 qtype
= QType::CNAME
;
414 totrdatalen
+= d_cname
.toDNSString().size();
416 for(const auto& addr
: d_addrs
) {
417 if(qtype
!= QType::ANY
&& ((addr
.sin4
.sin_family
== AF_INET
&& qtype
!= QType::A
) ||
418 (addr
.sin4
.sin_family
== AF_INET6
&& qtype
!= QType::AAAA
))) {
421 totrdatalen
+= addr
.sin4
.sin_family
== AF_INET
? sizeof(addr
.sin4
.sin_addr
.s_addr
) : sizeof(addr
.sin6
.sin6_addr
.s6_addr
);
422 addrs
.push_back(addr
);
427 random_shuffle(addrs
.begin(), addrs
.end());
429 unsigned int consumed
=0;
430 DNSName
ignore((char*)dq
->dh
, dq
->len
, sizeof(dnsheader
), false, 0, 0, &consumed
);
432 if (dq
->size
< (sizeof(dnsheader
) + consumed
+ 4 + ((d_cname
.empty() ? 0 : 1) + addrs
.size())*12 /* recordstart */ + totrdatalen
)) {
436 bool dnssecOK
= false;
437 bool hadEDNS
= false;
438 if (g_addEDNSToSelfGeneratedResponses
&& queryHasEDNS(*dq
)) {
440 dnssecOK
= getEDNSZ(*dq
) & EDNS_HEADER_FLAG_DO
;
443 dq
->len
= sizeof(dnsheader
) + consumed
+ 4; // there goes your EDNS
444 char* dest
= ((char*)dq
->dh
) + dq
->len
;
446 dq
->dh
->qr
= true; // for good measure
447 dq
->dh
->ra
= dq
->dh
->rd
; // for good measure
450 dq
->dh
->arcount
= 0; // for now, forget about your EDNS, we're marching over it
452 if(qtype
== QType::CNAME
) {
453 std::string wireData
= d_cname
.toDNSString(); // Note! This doesn't do compression!
454 const unsigned char recordstart
[]={0xc0, 0x0c, // compressed name
455 0, (unsigned char) qtype
,
458 0, (unsigned char)wireData
.length()};
459 static_assert(sizeof(recordstart
) == 12, "sizeof(recordstart) must be equal to 12, otherwise the above check is invalid");
461 memcpy(dest
, recordstart
, sizeof(recordstart
));
462 dest
+= sizeof(recordstart
);
463 memcpy(dest
, wireData
.c_str(), wireData
.length());
464 dq
->len
+= wireData
.length() + sizeof(recordstart
);
468 for(const auto& addr
: addrs
) {
469 unsigned char rdatalen
= addr
.sin4
.sin_family
== AF_INET
? sizeof(addr
.sin4
.sin_addr
.s_addr
) : sizeof(addr
.sin6
.sin6_addr
.s6_addr
);
470 const unsigned char recordstart
[]={0xc0, 0x0c, // compressed name
471 0, (unsigned char) (addr
.sin4
.sin_family
== AF_INET
? QType::A
: QType::AAAA
),
475 static_assert(sizeof(recordstart
) == 12, "sizeof(recordstart) must be equal to 12, otherwise the above check is invalid");
477 memcpy(dest
, recordstart
, sizeof(recordstart
));
478 dest
+= sizeof(recordstart
);
481 addr
.sin4
.sin_family
== AF_INET
? (void*)&addr
.sin4
.sin_addr
.s_addr
: (void*)&addr
.sin6
.sin6_addr
.s6_addr
,
484 dq
->len
+= rdatalen
+ sizeof(recordstart
);
489 dq
->dh
->ancount
= htons(dq
->dh
->ancount
);
492 addEDNS(dq
->dh
, dq
->len
, dq
->size
, dnssecOK
, g_PayloadSizeSelfGenAnswers
, 0);
495 return Action::HeaderModify
;
498 class MacAddrAction
: public DNSAction
501 MacAddrAction(uint16_t code
) : d_code(code
)
503 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
508 std::string mac
= getMACAddress(*dq
->remote
);
512 std::string optRData
;
513 generateEDNSOption(d_code
, mac
, optRData
);
516 generateOptRR(optRData
, res
, g_EdnsUDPPayloadSize
, 0, false);
518 if ((dq
->size
- dq
->len
) < res
.length())
521 dq
->dh
->arcount
= htons(1);
522 char* dest
= ((char*)dq
->dh
) + dq
->len
;
523 memcpy(dest
, res
.c_str(), res
.length());
524 dq
->len
+= res
.length();
528 std::string
toString() const override
530 return "add EDNS MAC (code="+std::to_string(d_code
)+")";
536 class NoRecurseAction
: public DNSAction
539 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
544 std::string
toString() const override
550 class LogAction
: public DNSAction
, public boost::noncopyable
553 LogAction() : d_fp(0)
556 LogAction(const std::string
& str
, bool binary
=true, bool append
=false, bool buffered
=true) : d_fname(str
), d_binary(binary
)
561 d_fp
= fopen(str
.c_str(), "a+");
563 d_fp
= fopen(str
.c_str(), "w");
565 throw std::runtime_error("Unable to open file '"+str
+"' for logging: "+stringerror());
569 ~LogAction() override
574 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
577 vinfolog("Packet from %s for %s %s with id %d", dq
->remote
->toStringWithPort(), dq
->qname
->toString(), QType(dq
->qtype
).getName(), dq
->dh
->id
);
581 std::string out
= dq
->qname
->toDNSString();
582 fwrite(out
.c_str(), 1, out
.size(), d_fp
);
583 fwrite((void*)&dq
->qtype
, 1, 2, d_fp
);
586 fprintf(d_fp
, "Packet from %s for %s %s with id %d\n", dq
->remote
->toStringWithPort().c_str(), dq
->qname
->toString().c_str(), QType(dq
->qtype
).getName().c_str(), dq
->dh
->id
);
591 std::string
toString() const override
593 if (!d_fname
.empty()) {
594 return "log to " + d_fname
;
605 class DisableValidationAction
: public DNSAction
608 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
613 std::string
toString() const override
619 class SkipCacheAction
: public DNSAction
622 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
624 dq
->skipCache
= true;
627 std::string
toString() const override
633 class TempFailureCacheTTLAction
: public DNSAction
636 TempFailureCacheTTLAction(uint32_t ttl
) : d_ttl(ttl
)
638 TempFailureCacheTTLAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
640 dq
->tempFailureTTL
= d_ttl
;
643 std::string
toString() const override
645 return "set tempfailure cache ttl to "+std::to_string(d_ttl
);
651 class ECSPrefixLengthAction
: public DNSAction
654 ECSPrefixLengthAction(uint16_t v4Length
, uint16_t v6Length
) : d_v4PrefixLength(v4Length
), d_v6PrefixLength(v6Length
)
657 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
659 dq
->ecsPrefixLength
= dq
->remote
->sin4
.sin_family
== AF_INET
? d_v4PrefixLength
: d_v6PrefixLength
;
662 std::string
toString() const override
664 return "set ECS prefix length to " + std::to_string(d_v4PrefixLength
) + "/" + std::to_string(d_v6PrefixLength
);
667 uint16_t d_v4PrefixLength
;
668 uint16_t d_v6PrefixLength
;
671 class ECSOverrideAction
: public DNSAction
674 ECSOverrideAction(bool ecsOverride
) : d_ecsOverride(ecsOverride
)
677 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
679 dq
->ecsOverride
= d_ecsOverride
;
682 std::string
toString() const override
684 return "set ECS override to " + std::to_string(d_ecsOverride
);
691 class DisableECSAction
: public DNSAction
694 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
699 std::string
toString() const override
701 return "disable ECS";
705 class SetECSAction
: public DNSAction
708 SetECSAction(const Netmask
& v4
): d_v4(v4
), d_hasV6(false)
712 SetECSAction(const Netmask
& v4
, const Netmask
& v6
): d_v4(v4
), d_v6(v6
), d_hasV6(true)
716 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
721 dq
->ecs
= dq
->remote
->isIPv4() ? d_v4
: d_v6
;
730 std::string
toString() const override
732 std::string result
= "set ECS to " + d_v4
.toString();
734 result
+= " / " + d_v6
.toString();
746 class DnstapLogAction
: public DNSAction
, public boost::noncopyable
749 DnstapLogAction(const std::string
& identity
, std::shared_ptr
<RemoteLoggerInterface
>& logger
, boost::optional
<std::function
<void(DNSQuestion
*, DnstapMessage
*)> > alterFunc
): d_identity(identity
), d_logger(logger
), d_alterFunc(alterFunc
)
752 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
755 DnstapMessage
message(d_identity
, dq
->remote
, dq
->local
, dq
->tcp
, reinterpret_cast<const char*>(dq
->dh
), dq
->len
, dq
->queryTime
, nullptr);
758 std::lock_guard
<std::mutex
> lock(g_luamutex
);
759 (*d_alterFunc
)(dq
, &message
);
763 message
.serialize(data
);
764 d_logger
->queueData(data
);
765 #endif /* HAVE_PROTOBUF */
768 std::string
toString() const override
770 return "remote log as dnstap to " + (d_logger
? d_logger
->toString() : "");
773 std::string d_identity
;
774 std::shared_ptr
<RemoteLoggerInterface
> d_logger
;
775 boost::optional
<std::function
<void(DNSQuestion
*, DnstapMessage
*)> > d_alterFunc
;
778 class RemoteLogAction
: public DNSAction
, public boost::noncopyable
781 RemoteLogAction(std::shared_ptr
<RemoteLoggerInterface
>& logger
, boost::optional
<std::function
<void(DNSQuestion
*, DNSDistProtoBufMessage
*)> > alterFunc
, const std::string
& serverID
, const std::string
& ipEncryptKey
): d_logger(logger
), d_alterFunc(alterFunc
), d_serverID(serverID
), d_ipEncryptKey(ipEncryptKey
)
784 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
788 dq
->uniqueId
= getUniqueID();
791 DNSDistProtoBufMessage
message(*dq
);
792 if (!d_serverID
.empty()) {
793 message
.setServerIdentity(d_serverID
);
797 if (!d_ipEncryptKey
.empty())
799 message
.setRequestor(encryptCA(*dq
->remote
, d_ipEncryptKey
));
801 #endif /* HAVE_LIBCRYPTO */
804 std::lock_guard
<std::mutex
> lock(g_luamutex
);
805 (*d_alterFunc
)(dq
, &message
);
809 message
.serialize(data
);
810 d_logger
->queueData(data
);
811 #endif /* HAVE_PROTOBUF */
814 std::string
toString() const override
816 return "remote log to " + (d_logger
? d_logger
->toString() : "");
819 std::shared_ptr
<RemoteLoggerInterface
> d_logger
;
820 boost::optional
<std::function
<void(DNSQuestion
*, DNSDistProtoBufMessage
*)> > d_alterFunc
;
821 std::string d_serverID
;
822 std::string d_ipEncryptKey
;
825 class SNMPTrapAction
: public DNSAction
828 SNMPTrapAction(const std::string
& reason
): d_reason(reason
)
831 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
833 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
834 g_snmpAgent
->sendDNSTrap(*dq
, d_reason
);
839 std::string
toString() const override
841 return "send SNMP trap";
844 std::string d_reason
;
847 class TagAction
: public DNSAction
850 TagAction(const std::string
& tag
, const std::string
& value
): d_tag(tag
), d_value(value
)
853 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
856 dq
->qTag
= std::make_shared
<QTag
>();
859 dq
->qTag
->insert({d_tag
, d_value
});
863 std::string
toString() const override
865 return "set tag '" + d_tag
+ "' to value '" + d_value
+ "'";
872 class DnstapLogResponseAction
: public DNSResponseAction
, public boost::noncopyable
875 DnstapLogResponseAction(const std::string
& identity
, std::shared_ptr
<RemoteLoggerInterface
>& logger
, boost::optional
<std::function
<void(DNSResponse
*, DnstapMessage
*)> > alterFunc
): d_identity(identity
), d_logger(logger
), d_alterFunc(alterFunc
)
878 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
883 DnstapMessage
message(d_identity
, dr
->remote
, dr
->local
, dr
->tcp
, reinterpret_cast<const char*>(dr
->dh
), dr
->len
, dr
->queryTime
, &now
);
886 std::lock_guard
<std::mutex
> lock(g_luamutex
);
887 (*d_alterFunc
)(dr
, &message
);
891 message
.serialize(data
);
892 d_logger
->queueData(data
);
893 #endif /* HAVE_PROTOBUF */
896 std::string
toString() const override
898 return "log response as dnstap to " + (d_logger
? d_logger
->toString() : "");
901 std::string d_identity
;
902 std::shared_ptr
<RemoteLoggerInterface
> d_logger
;
903 boost::optional
<std::function
<void(DNSResponse
*, DnstapMessage
*)> > d_alterFunc
;
906 class RemoteLogResponseAction
: public DNSResponseAction
, public boost::noncopyable
909 RemoteLogResponseAction(std::shared_ptr
<RemoteLoggerInterface
>& logger
, boost::optional
<std::function
<void(DNSResponse
*, DNSDistProtoBufMessage
*)> > alterFunc
, const std::string
& serverID
, const std::string
& ipEncryptKey
, bool includeCNAME
): d_logger(logger
), d_alterFunc(alterFunc
), d_serverID(serverID
), d_ipEncryptKey(ipEncryptKey
), d_includeCNAME(includeCNAME
)
912 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
916 dr
->uniqueId
= getUniqueID();
919 DNSDistProtoBufMessage
message(*dr
, d_includeCNAME
);
920 if (!d_serverID
.empty()) {
921 message
.setServerIdentity(d_serverID
);
925 if (!d_ipEncryptKey
.empty())
927 message
.setRequestor(encryptCA(*dr
->remote
, d_ipEncryptKey
));
929 #endif /* HAVE_LIBCRYPTO */
932 std::lock_guard
<std::mutex
> lock(g_luamutex
);
933 (*d_alterFunc
)(dr
, &message
);
937 message
.serialize(data
);
938 d_logger
->queueData(data
);
939 #endif /* HAVE_PROTOBUF */
942 std::string
toString() const override
944 return "remote log response to " + (d_logger
? d_logger
->toString() : "");
947 std::shared_ptr
<RemoteLoggerInterface
> d_logger
;
948 boost::optional
<std::function
<void(DNSResponse
*, DNSDistProtoBufMessage
*)> > d_alterFunc
;
949 std::string d_serverID
;
950 std::string d_ipEncryptKey
;
954 class DropResponseAction
: public DNSResponseAction
957 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
961 std::string
toString() const override
967 class AllowResponseAction
: public DNSResponseAction
970 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
972 return Action::Allow
;
974 std::string
toString() const override
980 class DelayResponseAction
: public DNSResponseAction
983 DelayResponseAction(int msec
) : d_msec(msec
)
985 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
987 *ruleresult
=std::to_string(d_msec
);
988 return Action::Delay
;
990 std::string
toString() const override
992 return "delay by "+std::to_string(d_msec
)+ " msec";
998 class SNMPTrapResponseAction
: public DNSResponseAction
1001 SNMPTrapResponseAction(const std::string
& reason
): d_reason(reason
)
1004 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
1006 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
1007 g_snmpAgent
->sendDNSTrap(*dr
, d_reason
);
1010 return Action::None
;
1012 std::string
toString() const override
1014 return "send SNMP trap";
1017 std::string d_reason
;
1020 class TagResponseAction
: public DNSResponseAction
1023 TagResponseAction(const std::string
& tag
, const std::string
& value
): d_tag(tag
), d_value(value
)
1026 DNSResponseAction::Action
operator()(DNSResponse
* dr
, std::string
* ruleresult
) const override
1029 dr
->qTag
= std::make_shared
<QTag
>();
1032 dr
->qTag
->insert({d_tag
, d_value
});
1034 return Action::None
;
1036 std::string
toString() const override
1038 return "set tag '" + d_tag
+ "' to value '" + d_value
+ "'";
1042 std::string d_value
;
1045 class ContinueAction
: public DNSAction
1048 ContinueAction(std::shared_ptr
<DNSAction
>& action
): d_action(action
)
1052 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
1055 /* call the action */
1056 auto action
= (*d_action
)(dq
, ruleresult
);
1058 /* apply the changes if needed (pool selection, flags, etc */
1059 processRulesResult(action
, *dq
, *ruleresult
, drop
);
1062 /* but ignore the resulting action no matter what */
1063 return Action::None
;
1066 std::string
toString() const override
1069 return "continue after: " + (d_action
? d_action
->toString() : "");
1077 std::shared_ptr
<DNSAction
> d_action
;
1080 #ifdef HAVE_DNS_OVER_HTTPS
1081 class HTTPStatusAction
: public DNSAction
1084 HTTPStatusAction(int code
, const std::string
& body
, const std::string
& contentType
): d_body(body
), d_contentType(contentType
), d_code(code
)
1088 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
1091 return Action::None
;
1094 dq
->du
->setHTTPResponse(d_code
, d_body
, d_contentType
);
1095 dq
->dh
->qr
= true; // for good measure
1096 return Action::HeaderModify
;
1099 std::string
toString() const override
1101 return "return an HTTP status of " + std::to_string(d_code
);
1105 std::string d_contentType
;
1108 #endif /* HAVE_DNS_OVER_HTTPS */
1110 class KeyValueStoreLookupAction
: public DNSAction
1113 KeyValueStoreLookupAction(std::shared_ptr
<KeyValueStore
>& kvs
, std::shared_ptr
<KeyValueLookupKey
>& lookupKey
, const std::string
& destinationTag
): d_kvs(kvs
), d_key(lookupKey
), d_tag(destinationTag
)
1117 DNSAction::Action
operator()(DNSQuestion
* dq
, std::string
* ruleresult
) const override
1119 std::vector
<std::string
> keys
= d_key
->getKeys(*dq
);
1121 for (const auto& key
: keys
) {
1122 if (d_kvs
->getValue(key
, result
) == true) {
1128 dq
->qTag
= std::make_shared
<QTag
>();
1131 dq
->qTag
->insert({d_tag
, std::move(result
)});
1133 return Action::None
;
1136 std::string
toString() const override
1138 return "lookup key-value store based on '" + d_key
->toString() + "' and set the result in tag '" + d_tag
+ "'";
1142 std::shared_ptr
<KeyValueStore
> d_kvs
;
1143 std::shared_ptr
<KeyValueLookupKey
> d_key
;
1147 template<typename T
, typename ActionT
>
1148 static void addAction(GlobalStateHolder
<vector
<T
> > *someRulActions
, luadnsrule_t var
, std::shared_ptr
<ActionT
> action
, boost::optional
<luaruleparams_t
> params
) {
1151 boost::uuids::uuid uuid
;
1152 uint64_t creationOrder
;
1153 parseRuleParams(params
, uuid
, creationOrder
);
1155 auto rule
=makeRule(var
);
1156 someRulActions
->modify([rule
, action
, uuid
, creationOrder
](vector
<T
>& rulactions
){
1157 rulactions
.push_back({rule
, action
, uuid
, creationOrder
});
1161 void setupLuaActions()
1163 g_lua
.writeFunction("newRuleAction", [](luadnsrule_t dnsrule
, std::shared_ptr
<DNSAction
> action
, boost::optional
<luaruleparams_t
> params
) {
1164 boost::uuids::uuid uuid
;
1165 uint64_t creationOrder
;
1166 parseRuleParams(params
, uuid
, creationOrder
);
1168 auto rule
=makeRule(dnsrule
);
1169 DNSDistRuleAction
ra({rule
, action
, uuid
, creationOrder
});
1170 return std::make_shared
<DNSDistRuleAction
>(ra
);
1173 g_lua
.writeFunction("addAction", [](luadnsrule_t var
, boost::variant
<std::shared_ptr
<DNSAction
>, std::shared_ptr
<DNSResponseAction
> > era
, boost::optional
<luaruleparams_t
> params
) {
1174 if (era
.type() != typeid(std::shared_ptr
<DNSAction
>)) {
1175 throw std::runtime_error("addAction() can only be called with query-related actions, not response-related ones. Are you looking for addResponseAction()?");
1178 addAction(&g_rulactions
, var
, boost::get
<std::shared_ptr
<DNSAction
> >(era
), params
);
1181 g_lua
.writeFunction("addResponseAction", [](luadnsrule_t var
, boost::variant
<std::shared_ptr
<DNSAction
>, std::shared_ptr
<DNSResponseAction
> > era
, boost::optional
<luaruleparams_t
> params
) {
1182 if (era
.type() != typeid(std::shared_ptr
<DNSResponseAction
>)) {
1183 throw std::runtime_error("addResponseAction() can only be called with response-related actions, not query-related ones. Are you looking for addAction()?");
1186 addAction(&g_resprulactions
, var
, boost::get
<std::shared_ptr
<DNSResponseAction
> >(era
), params
);
1189 g_lua
.writeFunction("addCacheHitResponseAction", [](luadnsrule_t var
, boost::variant
<std::shared_ptr
<DNSAction
>, std::shared_ptr
<DNSResponseAction
>> era
, boost::optional
<luaruleparams_t
> params
) {
1190 if (era
.type() != typeid(std::shared_ptr
<DNSResponseAction
>)) {
1191 throw std::runtime_error("addCacheHitResponseAction() can only be called with response-related actions, not query-related ones. Are you looking for addAction()?");
1194 addAction(&g_cachehitresprulactions
, var
, boost::get
<std::shared_ptr
<DNSResponseAction
> >(era
), params
);
1197 g_lua
.writeFunction("addSelfAnsweredResponseAction", [](luadnsrule_t var
, boost::variant
<std::shared_ptr
<DNSAction
>, std::shared_ptr
<DNSResponseAction
>> era
, boost::optional
<luaruleparams_t
> params
) {
1198 if (era
.type() != typeid(std::shared_ptr
<DNSResponseAction
>)) {
1199 throw std::runtime_error("addSelfAnsweredResponseAction() can only be called with response-related actions, not query-related ones. Are you looking for addAction()?");
1202 addAction(&g_selfansweredresprulactions
, var
, boost::get
<std::shared_ptr
<DNSResponseAction
> >(era
), params
);
1205 g_lua
.registerFunction
<void(DNSAction::*)()>("printStats", [](const DNSAction
& ta
) {
1206 setLuaNoSideEffect();
1207 auto stats
= ta
.getStats();
1208 for(const auto& s
: stats
) {
1209 g_outputBuffer
+=s
.first
+"\t";
1210 if((uint64_t)s
.second
== s
.second
)
1211 g_outputBuffer
+= std::to_string((uint64_t)s
.second
)+"\n";
1213 g_outputBuffer
+= std::to_string(s
.second
)+"\n";
1217 g_lua
.writeFunction("getAction", [](unsigned int num
) {
1218 setLuaNoSideEffect();
1219 boost::optional
<std::shared_ptr
<DNSAction
>> ret
;
1220 auto rulactions
= g_rulactions
.getCopy();
1221 if(num
< rulactions
.size())
1222 ret
=rulactions
[num
].d_action
;
1226 g_lua
.registerFunction("getStats", &DNSAction::getStats
);
1228 g_lua
.writeFunction("LuaAction", [](LuaAction::func_t func
) {
1230 return std::shared_ptr
<DNSAction
>(new LuaAction(func
));
1233 g_lua
.writeFunction("NoRecurseAction", []() {
1234 return std::shared_ptr
<DNSAction
>(new NoRecurseAction
);
1237 g_lua
.writeFunction("MacAddrAction", [](int code
) {
1238 return std::shared_ptr
<DNSAction
>(new MacAddrAction(code
));
1241 g_lua
.writeFunction("PoolAction", [](const std::string
& a
) {
1242 return std::shared_ptr
<DNSAction
>(new PoolAction(a
));
1245 g_lua
.writeFunction("QPSAction", [](int limit
) {
1246 return std::shared_ptr
<DNSAction
>(new QPSAction(limit
));
1249 g_lua
.writeFunction("QPSPoolAction", [](int limit
, const std::string
& a
) {
1250 return std::shared_ptr
<DNSAction
>(new QPSPoolAction(limit
, a
));
1253 g_lua
.writeFunction("SpoofAction", [](boost::variant
<std::string
,vector
<pair
<int, std::string
>>> inp
, boost::optional
<std::string
> b
) {
1254 vector
<ComboAddress
> addrs
;
1255 if(auto s
= boost::get
<std::string
>(&inp
))
1256 addrs
.push_back(ComboAddress(*s
));
1258 const auto& v
= boost::get
<vector
<pair
<int,std::string
>>>(inp
);
1259 for(const auto& a
: v
)
1260 addrs
.push_back(ComboAddress(a
.second
));
1263 addrs
.push_back(ComboAddress(*b
));
1264 return std::shared_ptr
<DNSAction
>(new SpoofAction(addrs
));
1267 g_lua
.writeFunction("SpoofCNAMEAction", [](const std::string
& a
) {
1268 return std::shared_ptr
<DNSAction
>(new SpoofAction(a
));
1271 g_lua
.writeFunction("DropAction", []() {
1272 return std::shared_ptr
<DNSAction
>(new DropAction
);
1275 g_lua
.writeFunction("AllowAction", []() {
1276 return std::shared_ptr
<DNSAction
>(new AllowAction
);
1279 g_lua
.writeFunction("NoneAction", []() {
1280 return std::shared_ptr
<DNSAction
>(new NoneAction
);
1283 g_lua
.writeFunction("DelayAction", [](int msec
) {
1284 return std::shared_ptr
<DNSAction
>(new DelayAction(msec
));
1287 g_lua
.writeFunction("TCAction", []() {
1288 return std::shared_ptr
<DNSAction
>(new TCAction
);
1291 g_lua
.writeFunction("DisableValidationAction", []() {
1292 return std::shared_ptr
<DNSAction
>(new DisableValidationAction
);
1295 g_lua
.writeFunction("LogAction", [](const std::string
& fname
, boost::optional
<bool> binary
, boost::optional
<bool> append
, boost::optional
<bool> buffered
) {
1296 return std::shared_ptr
<DNSAction
>(new LogAction(fname
, binary
? *binary
: true, append
? *append
: false, buffered
? *buffered
: false));
1299 g_lua
.writeFunction("RCodeAction", [](uint8_t rcode
) {
1300 return std::shared_ptr
<DNSAction
>(new RCodeAction(rcode
));
1303 g_lua
.writeFunction("ERCodeAction", [](uint8_t rcode
) {
1304 return std::shared_ptr
<DNSAction
>(new ERCodeAction(rcode
));
1307 g_lua
.writeFunction("SkipCacheAction", []() {
1308 return std::shared_ptr
<DNSAction
>(new SkipCacheAction
);
1311 g_lua
.writeFunction("TempFailureCacheTTLAction", [](int maxTTL
) {
1312 return std::shared_ptr
<DNSAction
>(new TempFailureCacheTTLAction(maxTTL
));
1315 g_lua
.writeFunction("DropResponseAction", []() {
1316 return std::shared_ptr
<DNSResponseAction
>(new DropResponseAction
);
1319 g_lua
.writeFunction("AllowResponseAction", []() {
1320 return std::shared_ptr
<DNSResponseAction
>(new AllowResponseAction
);
1323 g_lua
.writeFunction("DelayResponseAction", [](int msec
) {
1324 return std::shared_ptr
<DNSResponseAction
>(new DelayResponseAction(msec
));
1327 g_lua
.writeFunction("LuaResponseAction", [](LuaResponseAction::func_t func
) {
1329 return std::shared_ptr
<DNSResponseAction
>(new LuaResponseAction(func
));
1332 g_lua
.writeFunction("RemoteLogAction", [](std::shared_ptr
<RemoteLoggerInterface
> logger
, boost::optional
<std::function
<void(DNSQuestion
*, DNSDistProtoBufMessage
*)> > alterFunc
, boost::optional
<std::unordered_map
<std::string
, std::string
>> vars
) {
1334 // avoids potentially-evaluated-expression warning with clang.
1335 RemoteLoggerInterface
& rl
= *logger
.get();
1336 if (typeid(rl
) != typeid(RemoteLogger
)) {
1337 // We could let the user do what he wants, but wrapping PowerDNS Protobuf inside a FrameStream tagged as dnstap is logically wrong.
1338 throw std::runtime_error(std::string("RemoteLogAction only takes RemoteLogger. For other types, please look at DnstapLogAction."));
1342 std::string serverID
;
1343 std::string ipEncryptKey
;
1345 if (vars
->count("serverID")) {
1346 serverID
= boost::get
<std::string
>((*vars
)["serverID"]);
1348 if (vars
->count("ipEncryptKey")) {
1349 ipEncryptKey
= boost::get
<std::string
>((*vars
)["ipEncryptKey"]);
1353 #ifdef HAVE_PROTOBUF
1354 return std::shared_ptr
<DNSAction
>(new RemoteLogAction(logger
, alterFunc
, serverID
, ipEncryptKey
));
1356 throw std::runtime_error("Protobuf support is required to use RemoteLogAction");
1360 g_lua
.writeFunction("RemoteLogResponseAction", [](std::shared_ptr
<RemoteLoggerInterface
> logger
, boost::optional
<std::function
<void(DNSResponse
*, DNSDistProtoBufMessage
*)> > alterFunc
, boost::optional
<bool> includeCNAME
, boost::optional
<std::unordered_map
<std::string
, std::string
>> vars
) {
1362 // avoids potentially-evaluated-expression warning with clang.
1363 RemoteLoggerInterface
& rl
= *logger
.get();
1364 if (typeid(rl
) != typeid(RemoteLogger
)) {
1365 // We could let the user do what he wants, but wrapping PowerDNS Protobuf inside a FrameStream tagged as dnstap is logically wrong.
1366 throw std::runtime_error("RemoteLogResponseAction only takes RemoteLogger. For other types, please look at DnstapLogResponseAction.");
1370 std::string serverID
;
1371 std::string ipEncryptKey
;
1373 if (vars
->count("serverID")) {
1374 serverID
= boost::get
<std::string
>((*vars
)["serverID"]);
1376 if (vars
->count("ipEncryptKey")) {
1377 ipEncryptKey
= boost::get
<std::string
>((*vars
)["ipEncryptKey"]);
1381 #ifdef HAVE_PROTOBUF
1382 return std::shared_ptr
<DNSResponseAction
>(new RemoteLogResponseAction(logger
, alterFunc
, serverID
, ipEncryptKey
, includeCNAME
? *includeCNAME
: false));
1384 throw std::runtime_error("Protobuf support is required to use RemoteLogResponseAction");
1388 g_lua
.writeFunction("DnstapLogAction", [](const std::string
& identity
, std::shared_ptr
<RemoteLoggerInterface
> logger
, boost::optional
<std::function
<void(DNSQuestion
*, DnstapMessage
*)> > alterFunc
) {
1389 #ifdef HAVE_PROTOBUF
1390 return std::shared_ptr
<DNSAction
>(new DnstapLogAction(identity
, logger
, alterFunc
));
1392 throw std::runtime_error("Protobuf support is required to use DnstapLogAction");
1396 g_lua
.writeFunction("DnstapLogResponseAction", [](const std::string
& identity
, std::shared_ptr
<RemoteLoggerInterface
> logger
, boost::optional
<std::function
<void(DNSResponse
*, DnstapMessage
*)> > alterFunc
) {
1397 #ifdef HAVE_PROTOBUF
1398 return std::shared_ptr
<DNSResponseAction
>(new DnstapLogResponseAction(identity
, logger
, alterFunc
));
1400 throw std::runtime_error("Protobuf support is required to use DnstapLogResponseAction");
1404 g_lua
.writeFunction("TeeAction", [](const std::string
& remote
, boost::optional
<bool> addECS
) {
1405 return std::shared_ptr
<DNSAction
>(new TeeAction(ComboAddress(remote
, 53), addECS
? *addECS
: false));
1408 g_lua
.writeFunction("ECSPrefixLengthAction", [](uint16_t v4PrefixLength
, uint16_t v6PrefixLength
) {
1409 return std::shared_ptr
<DNSAction
>(new ECSPrefixLengthAction(v4PrefixLength
, v6PrefixLength
));
1412 g_lua
.writeFunction("ECSOverrideAction", [](bool ecsOverride
) {
1413 return std::shared_ptr
<DNSAction
>(new ECSOverrideAction(ecsOverride
));
1416 g_lua
.writeFunction("DisableECSAction", []() {
1417 return std::shared_ptr
<DNSAction
>(new DisableECSAction());
1420 g_lua
.writeFunction("SetECSAction", [](const std::string v4
, boost::optional
<std::string
> v6
) {
1422 return std::shared_ptr
<DNSAction
>(new SetECSAction(Netmask(v4
), Netmask(*v6
)));
1424 return std::shared_ptr
<DNSAction
>(new SetECSAction(Netmask(v4
)));
1427 g_lua
.writeFunction("SNMPTrapAction", [](boost::optional
<std::string
> reason
) {
1428 #ifdef HAVE_NET_SNMP
1429 return std::shared_ptr
<DNSAction
>(new SNMPTrapAction(reason
? *reason
: ""));
1431 throw std::runtime_error("NET SNMP support is required to use SNMPTrapAction()");
1432 #endif /* HAVE_NET_SNMP */
1435 g_lua
.writeFunction("SNMPTrapResponseAction", [](boost::optional
<std::string
> reason
) {
1436 #ifdef HAVE_NET_SNMP
1437 return std::shared_ptr
<DNSResponseAction
>(new SNMPTrapResponseAction(reason
? *reason
: ""));
1439 throw std::runtime_error("NET SNMP support is required to use SNMPTrapResponseAction()");
1440 #endif /* HAVE_NET_SNMP */
1443 g_lua
.writeFunction("TagAction", [](std::string tag
, std::string value
) {
1444 return std::shared_ptr
<DNSAction
>(new TagAction(tag
, value
));
1447 g_lua
.writeFunction("TagResponseAction", [](std::string tag
, std::string value
) {
1448 return std::shared_ptr
<DNSResponseAction
>(new TagResponseAction(tag
, value
));
1451 g_lua
.writeFunction("ContinueAction", [](std::shared_ptr
<DNSAction
> action
) {
1452 return std::shared_ptr
<DNSAction
>(new ContinueAction(action
));
1455 #ifdef HAVE_DNS_OVER_HTTPS
1456 g_lua
.writeFunction("HTTPStatusAction", [](uint16_t status
, std::string body
, boost::optional
<std::string
> contentType
) {
1457 return std::shared_ptr
<DNSAction
>(new HTTPStatusAction(status
, body
, contentType
? *contentType
: ""));
1459 #endif /* HAVE_DNS_OVER_HTTPS */
1461 g_lua
.writeFunction("KeyValueStoreLookupAction", [](std::shared_ptr
<KeyValueStore
>& kvs
, std::shared_ptr
<KeyValueLookupKey
>& lookupKey
, const std::string
& destinationTag
) {
1462 return std::shared_ptr
<DNSAction
>(new KeyValueStoreLookupAction(kvs
, lookupKey
, destinationTag
));