0

I have a DNS server which I want to add some rate-limiting on, since I'm receiving some bursts of floods of queries.

I read through https://github.com/racker/python-twisted-core/blob/master/doc/examples/shaper.py and adapted it to my needs:

from twisted.internet import reactor, protocol
from twisted.protocols import htb

udpBucket = htb.Bucket()
udpBucket.maxburst = 100000 # 1000 kb/s
udpBucket.rate     = 100000 # 1000 kb/s thereafter 

udpFilter = htb.HierarchicalBucketFilter()
udpFilter.buckets[None] = udpBucket

class DNSClientBucket(htb.Bucket):
  maxburst = 10000 # 10 kb/s
  rate     =  1000 #  1 kb/s thereafter

udpFilter2 = htb.FilterByHost(udpFilter)
udpFilter2.bucketFactory = DNSClientBucket

class DnsUdpProtocol(protocol.Protocol):
  def datagramReceived(self, data, client):
    print(data)

dns_udp_protocol = DnsUdpProtocol()
dns_udp_protocol = htb.ShapedProtocolFactory(dns_udp_protocol, udpFilter2)

dns_udp_interface   = socket.gethostbyname(socket.gethostname())
dns_udp_server_port = 53
reactor.listenUDP(port=dns_udp_server_port, protocol=dns_udp_protocol, interface=dns_udp_interface)

But I'm getting the following exception:

Traceback (most recent call last):
  File "server.py", line 263, in <module>
    reactor.listenUDP(port=dns_udp_server_port, protocol=dns_udp_protocol, interface=dns_udp_interface)
  File "/usr/lib/python3.7/site-packages/twisted/internet/posixbase.py", line 369, in listenUDP
    p.startListening()
  File "/usr/lib/python3.7/site-packages/twisted/internet/udp.py", line 179, in startListening
    self._connectToProtocol()
  File "/usr/lib/python3.7/site-packages/twisted/internet/udp.py", line 217, in _connectToProtocol
    self.protocol.makeConnection(self)
AttributeError: 'ShapedProtocolFactory' object has no attribute 'makeConnection'

Is it even possible to to use twisted.protocols.htb with the UDP protocol?

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • I don't know the tool, but since it's a factory (and following the link you added), shouldnt you call it first to create a protocol instance? Try `htb.ShapedProtocolFactory(dns_udp_protocol, udpFilter2)()` – Kacperito Sep 09 '19 at 23:05

1 Answers1

0

Probably not. HTB in Twisted is for stream-oriented sockets, not for datagram-oriented sockets like UDP.

Also, the HTB in Twisted is probably pretty sketchy even for its intended purpose.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122