diff --git a/scapy/ansmachine.py b/scapy/ansmachine.py index cb2281e982c..ab13fbb9730 100644 --- a/scapy/ansmachine.py +++ b/scapy/ansmachine.py @@ -19,7 +19,9 @@ import warnings from scapy.arch import get_if_addr +from scapy.data import MTU from scapy.config import conf +from scapy.error import log_runtime from scapy.sendrecv import sendp, sniff, AsyncSniffer from scapy.packet import Packet from scapy.plist import PacketList @@ -40,19 +42,21 @@ class ReferenceAM(type): - def __new__(cls, - name, # type: str - bases, # type: Tuple[type, ...] - dct # type: Dict[str, Any] - ): + def __new__( + cls, + name, # type: str + bases, # type: Tuple[type, ...] + dct, # type: Dict[str, Any] + ): # type: (...) -> Type['AnsweringMachine[_T]'] - obj = cast('Type[AnsweringMachine[_T]]', - super(ReferenceAM, cls).__new__(cls, name, bases, dct)) + obj = cast( + "Type[AnsweringMachine[_T]]", + super(ReferenceAM, cls).__new__(cls, name, bases, dct), + ) try: import inspect - obj.__signature__ = inspect.signature( # type: ignore - obj.parse_options - ) + + obj.__signature__ = inspect.signature(obj.parse_options) # type: ignore except (ImportError, AttributeError): pass if obj.function_name: @@ -62,7 +66,7 @@ def __new__(cls, func.__doc__ = obj.__doc__ or obj.parse_options.__doc__ try: func.__signature__ = obj.__signature__ # type: ignore - except (AttributeError): + except AttributeError: pass globals()[obj.function_name] = func return obj @@ -86,11 +90,21 @@ class AnsweringMachine(Generic[_T], metaclass=ReferenceAM): Provide a "function_name" class attribute to register the answering machine as a command. """ + function_name = "" filter = None # type: Optional[str] sniff_options = {"store": 0} # type: Dict[str, Any] - sniff_options_list = ["store", "iface", "count", "promisc", "filter", - "type", "prn", "stop_filter", "opened_socket"] + sniff_options_list = [ + "store", + "iface", + "count", + "promisc", + "filter", + "type", + "prn", + "stop_filter", + "opened_socket", + ] send_options = {"verbose": 0} # type: Dict[str, Any] send_options_list = ["iface", "inter", "loop", "verbose", "socket"] send_function = staticmethod(sendp) @@ -116,8 +130,8 @@ def __init__(self, **kargs): self.defoptsend.update(doptsend) self.defoptsniff = self.sniff_options.copy() self.defoptsniff.update(doptsniff) - self.optsend = {} # type: Dict[str, Any] - self.optsniff = {} # type: Dict[str, Any] + self.optsend = {} # type: Dict[str, Any] + self.optsniff = {} # type: Dict[str, Any] def parse_options(self): # type: () -> None @@ -145,7 +159,7 @@ def make_reply(self, req: Packet, address: Optional[Any] = None) -> _T: pass def send_reply(self, reply, send_function=None): - # type: (_T, Optional[Callable[..., None]]) -> None + # type: (_T, Optional[Callable[..., Any]]) -> None if send_function: send_function(reply) else: @@ -154,8 +168,7 @@ def send_reply(self, reply, send_function=None): def print_reply(self, req, reply): # type: (Packet, _T) -> None if isinstance(reply, PacketList): - print("%s ==> %s" % (req.summary(), - [res.summary() for res in reply])) + print("%s ==> %s" % (req.summary(), [res.summary() for res in reply])) else: print("%s ==> %s" % (req.summary(), reply.summary())) @@ -182,8 +195,7 @@ def reply(self, pkt, send_function=None, address=None): def run(self, *args, **kargs): # type: (Any, Any) -> None warnings.warn( - "run() method deprecated. The instance is now callable", - DeprecationWarning + "run() method deprecated. The instance is now callable", DeprecationWarning ) self(*args, **kargs) @@ -228,41 +240,58 @@ def sniff(self) -> None: elif self.mode in [self.MODE.TCP, self.MODE.UDP]: # Sniff using a normal socket from scapy.supersocket import StreamSocket + ssock = socket.socket(socket.AF_INET, self.mode) try: ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except OSError: pass - ssock.bind( - ( - get_if_addr(self.optsniff.get("iface", conf.iface)), - self.port - ) - ) + ssock.bind((get_if_addr(self.optsniff.get("iface", conf.iface)), self.port)) if self.mode == self.MODE.TCP: - ssock.listen() - sniffers = [] - try: - while True: - clientsocket, address = ssock.accept() - print("%s connected" % repr(address)) - sock = StreamSocket(clientsocket, self.cls) - optsniff = self.optsniff.copy() - optsniff["prn"] = functools.partial(self.reply, - send_function=sock.send, - address=address) - optsniff.pop("iface", None) - sniffer = AsyncSniffer(opened_socket=sock, **optsniff) - sniffer.start() - sniffers.append((sniffer, sock)) - finally: - for (sniffer, sock) in sniffers: - try: - sniffer.stop() - except Exception: - pass - sock.close() - ssock.close() + # TCP + ssock.listen(5) + sniffers = [] + try: + while True: + clientsocket, address = ssock.accept() + print("%s connected (TCP)" % repr(address)) + sock = StreamSocket(clientsocket, self.cls) + optsniff = self.optsniff.copy() + optsniff["prn"] = functools.partial( + self.reply, + send_function=sock.send, + address=address, + ) + optsniff.pop("iface", None) + sniffer = AsyncSniffer(opened_socket=sock, **optsniff) + sniffer.start() + sniffers.append((sniffer, sock)) + finally: + for sniffer, sock in sniffers: + try: + sniffer.stop() + except Exception: + pass + sock.close() + ssock.close() + else: + # UDP + try: + while True: + rpkt, address = ssock.recvfrom(MTU) + print("%s received (UDP)" % repr(address)) + try: + pkt = self.cls(rpkt) + except Exception as ex: + log_runtime.warning(str(ex)) + continue + self.reply( + pkt, + send_function=lambda x: ssock.sendto(bytes(x), address), # type: ignore # noqa: E501 + address=address, + ) + finally: + ssock.close() else: raise ValueError diff --git a/scapy/layers/dns.py b/scapy/layers/dns.py index 39f5bc50081..38745078a37 100644 --- a/scapy/layers/dns.py +++ b/scapy/layers/dns.py @@ -1684,6 +1684,8 @@ def parse_options( self.joker = joker self.joker6 = joker6 self.jokerarpa = jokerarpa + self.timeout = 1 + self.port = 53 def normv(v): if isinstance(v, (tuple, list)) and len(v) == 2: @@ -1729,6 +1731,8 @@ def is_request(self, req): query = req.getlayer(self.cls) if query is None or query.qr != 0: return False + if self.mode != self.mode.RAW: + return True if self.llmnr: # [RFC 4795] sect 2.1: an LLMNR query goes to the link-scope # multicast address with a hop limit of 1, so a responder must @@ -1935,7 +1939,12 @@ def make_reply(self, req, addr=None): if self.relay: # Relay mode ? try: - _rslv = dns_resolve(rq.qname, qtype=rq.qtype, raw=True) + _rslv = dns_resolve( + rq.qname, + qtype=rq.qtype, + raw=True, + timeout=self.timeout, + ) if _rslv: ans.extend(_rslv.an) ars.extend(_rslv.ar)