Beispiel #1
0
Datei: main.py Projekt: ii0/scapy
def _read_config_file(cf, _globals=globals(), _locals=locals(), interactive=True):
    """Read a config file: execute a python file while loading scapy, that may contain
    some pre-configured values.

    If _globals or _locals are specified, they will be updated with the loaded vars.
    This allows an external program to use the function. Otherwise, vars are only available
    from inside the scapy console.

    params:
    - _globals: the globals() vars
    - _locals: the locals() vars
    - interactive: specified whether or not errors should be printed using the scapy console or
    raised.

    ex, content of a config.py file:
        'conf.verb = 42\n'
    Manual loading:
        >>> _read_config_file("./config.py"))
        >>> conf.verb
        42
    """
    log_loading.debug("Loading config file [%s]", cf)
    try:
        exec(compile(open(cf).read(), cf, 'exec'), _globals, _locals)
    except IOError as e:
        if interactive:
            raise
        log_loading.warning("Cannot read config file [%s] [%s]", cf, e)
    except Exception as e:
        if interactive:
            raise
        log_loading.exception("Error during evaluation of config file [%s]", cf)
Beispiel #2
0
def apply_ipython_style(shell):
    """Updates the specified IPython console shell with
    the conf.color_theme scapy theme."""
    try:
        from IPython.terminal.prompts import Prompts, Token
    except:
        from scapy.error import log_loading
        log_loading.warning("IPython too old. Shell color won't be handled.")
        return
    from scapy.config import conf
    if isinstance(conf.prompt, Prompts):
        shell.prompts_class = conf.prompt  # Set custom prompt style
    else:

        class ClassicPrompt(Prompts):
            def in_prompt_tokens(self, cli=None):
                return [
                    (Token.Prompt, str(conf.prompt)),
                ]

            def out_prompt_tokens(self):
                return [
                    (Token.OutPrompt, ''),
                ]

        shell.prompts_class = ClassicPrompt  # Apply classic prompt style
    shell.highlighting_style_overrides = { # Register and apply scapy color style
        Token.Prompt: Color.ansi_to_pygments(conf.color_theme.style_prompt),
    }
    try:
        get_ipython().refresh_style()
    except NameError:
        pass
Beispiel #3
0
 def _reload(self):
     self.pdfreader = None
     self.psreader = None
     self.svgreader = None
     # We try some magic to find the appropriate executables
     self.dot = win_find_exe("dot")
     self.tcpdump = win_find_exe("windump")
     self.tshark = win_find_exe("tshark")
     self.tcpreplay = win_find_exe("tcpreplay")
     self.display = self._default
     self.hexedit = win_find_exe("hexer")
     self.sox = win_find_exe("sox")
     self.wireshark = win_find_exe("wireshark", "wireshark")
     self.usbpcapcmd = win_find_exe(
         "USBPcapCMD",
         installsubdir="USBPcap",
         env="programfiles"
     )
     self.powershell = win_find_exe(
         "powershell",
         installsubdir="System32\\WindowsPowerShell\\v1.0",
         env="SystemRoot"
     )
     self.cscript = win_find_exe("cscript", installsubdir="System32",
                                 env="SystemRoot")
     self.cmd = win_find_exe("cmd", installsubdir="System32",
                             env="SystemRoot")
     if self.wireshark:
         try:
             manu_path = load_manuf(os.path.sep.join(self.wireshark.split(os.path.sep)[:-1]) + os.path.sep + "manuf")  # noqa: E501
         except (IOError, OSError):  # FileNotFoundError not available on Py2 - using OSError  # noqa: E501
             log_loading.warning("Wireshark is installed, but cannot read manuf !")  # noqa: E501
             manu_path = None
         scapy.data.MANUFDB = conf.manufdb = manu_path
Beispiel #4
0
def load_services(filename):
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)
    udct = DADict(_name="%s-udp" % filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    if lt[1].endswith(b"/tcp"):
                        tdct[lt[0]] = int(lt[1].split(b'/')[0])
                    elif lt[1].endswith(b"/udp"):
                        udct[lt[0]] = int(lt[1].split(b'/')[0])
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Beispiel #5
0
def _read_config_file(cf, _globals=globals(), _locals=locals(), interactive=True):
    """Read a config file: execute a python file while loading scapy, that may contain
    some pre-configured values.
    
    If _globals or _locals are specified, they will be updated with the loaded vars.
    This allows an external program to use the function. Otherwise, vars are only available
    from inside the scapy console.
    
    params:
    - _globals: the globals() vars
    - _locals: the locals() vars
    - interactive: specified whether or not errors should be printed using the scapy console or
    raised.

    ex, content of a config.py file:
        'conf.verb = 42\n'
    Manual loading:
        >>> _read_config_file("./config.py"))
        >>> conf.verb
        42
    """
    log_loading.debug("Loading config file [%s]", cf)
    try:
        exec(compile(open(cf).read(), cf, 'exec'), _globals, _locals)
    except IOError as e:
        if interactive:
            raise
        log_loading.warning("Cannot read config file [%s] [%s]", cf, e)
    except Exception as e:
        if interactive:
            raise
        log_loading.exception("Error during evaluation of config file [%s]", cf)
Beispiel #6
0
def apply_ipython_style(shell):
    """Updates the specified IPython console shell with
    the conf.color_theme scapy theme."""
    try:
        from IPython.terminal.prompts import Prompts, Token
    except Exception:
        from scapy.error import log_loading
        log_loading.warning(
            "IPython too old. Shell color won't be handled."
        )
        return
    from scapy.config import conf
    if isinstance(conf.prompt, Prompts):
        shell.prompts_class = conf.prompt  # Set custom prompt style
    else:
        class ClassicPrompt(Prompts):
            def in_prompt_tokens(self, cli=None):
                return [(Token.Prompt, str(conf.prompt)), ]

            def out_prompt_tokens(self):
                return [(Token.OutPrompt, ''), ]
        shell.prompts_class = ClassicPrompt  # Apply classic prompt style
    shell.highlighting_style_overrides = {  # Register and apply scapy color style  # noqa: E501
        Token.Prompt: Color.ansi_to_pygments(conf.color_theme.style_prompt),
    }
    try:
        get_ipython().refresh_style()
    except NameError:
        pass
Beispiel #7
0
def load_manuf(filename):
    """
    Loads manuf file from Wireshark.

    :param filename: the file to load the manuf file from
    :returns: a ManufDA filled object
    """
    manufdb = ManufDA(_name=filename)
    with open(filename, "rb") as fdesc:
        for line in fdesc:
            try:
                line = line.strip()
                if not line or line.startswith(b"#"):
                    continue
                parts = line.split(None, 2)
                oui, shrt = parts[:2]
                lng = parts[2].lstrip(b"#").strip() if len(parts) > 2 else ""
                lng = lng or shrt
                manufdb[oui] = plain_str(shrt), plain_str(lng)
            except Exception:
                log_loading.warning("Couldn't parse one line from [%s] [%r]",
                                    filename,
                                    line,
                                    exc_info=True)
    return manufdb
Beispiel #8
0
    def _reload(self):
        self.pdfreader = None
        self.psreader = None
        # We try some magic to find the appropriate executables
        self.dot = win_find_exe("dot")
        self.tcpdump = win_find_exe("windump")
        self.tshark = win_find_exe("tshark")
        self.tcpreplay = win_find_exe("tcpreplay")
        self.display = self._default
        self.hexedit = win_find_exe("hexer")
        self.sox = win_find_exe("sox")
        self.wireshark = win_find_exe("wireshark", "wireshark")
        self.powershell = win_find_exe(
            "powershell",
            installsubdir="System32\\WindowsPowerShell\\v1.0",
            env="SystemRoot"
        )
        self.cscript = win_find_exe("cscript", installsubdir="System32",
                                    env="SystemRoot")
        self.cmd = win_find_exe("cmd", installsubdir="System32",
                                env="SystemRoot")
        if self.wireshark:
            try:
                manu_path = load_manuf(os.path.sep.join(self.wireshark.split(os.path.sep)[:-1]) + os.path.sep + "manuf")  # noqa: E501
            except (IOError, OSError):  # FileNotFoundError not available on Py2 - using OSError  # noqa: E501
                log_loading.warning("Wireshark is installed, but cannot read manuf !")  # noqa: E501
                manu_path = None
            scapy.data.MANUFDB = conf.manufdb = manu_path

        self.os_access = (self.powershell is not None) or (self.cscript is not None)  # noqa: E501
Beispiel #9
0
def load_services(filename):
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)
    udct = DADict(_name="%s-udp" % filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    if lt[1].endswith(b"/tcp"):
                        tdct[lt[0]] = int(lt[1].split(b'/')[0])
                    elif lt[1].endswith(b"/udp"):
                        udct[lt[0]] = int(lt[1].split(b'/')[0])
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Beispiel #10
0
def load_services(filename):
    spaces = re.compile("[ \t]+|\n")
    tdct=DADict(_name="%s-tcp"%filename)
    udct=DADict(_name="%s-udp"%filename)
    try:
        f=open(filename)
        for l in f:
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                if lt[1].endswith("/tcp"):
                    tdct[lt[0]] = int(lt[1].split('/')[0])
                elif lt[1].endswith("/udp"):
                    udct[lt[0]] = int(lt[1].split('/')[0])
            except Exception as e:
                log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e))
        f.close()
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct,udct
Beispiel #11
0
def read_routes6():
    routes6 = []
    if WINDOWS_XP:
        return routes6
    try:
        routes6 = _read_routes_c(ipv6=True)
    except Exception as e:
        log_loading.warning("Error building scapy IPv6 routing table : %s", e)
    return routes6
Beispiel #12
0
 def _update_pcapdata(self):
     """Supplement more info from pypcap and the Windows registry"""
     
     # XXX: We try eth0 - eth29 by bruteforce and match by IP address, 
     # because only the IP is available in both pypcap and dnet.
     # This may not work with unorthodox network configurations and is
     # slow because we have to walk through the Windows registry.
     for n in range(30): # change 30 to 15
         guess = "eth%s" % n
         win_name = pcapdnet.pcap.ex_name(guess)
         if win_name.endswith("}"):
             
             try:
                 uuid = win_name[win_name.index("{"):win_name.index("}")+1]
                 keyname = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % uuid
                 try:
                     key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname)
                 except WindowsError:
                     log_loading.debug("Couldn't open 'HKEY_LOCAL_MACHINE\\%s' (for guessed pcap iface name '%s')." % (keyname, guess))
                     continue
                 try:  
                     ip_list = _winreg.QueryValueEx(key, "IPAddress")[0]
                     ip_list = [ ipx.encode("utf-8") for ipx in ip_list ]
                     
                     fixed_ip = _winreg.QueryValueEx(key, "IPAddress")[0][0].encode("utf-8")
                 except (WindowsError, UnicodeDecodeError, IndexError):
                     log_loading.debug("Query ip address of %s error " % (guess,) )
                     fixed_ip = None
                     ip_list = []
                 try:
                     dhcp_ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0].encode("utf-8")
                 except (WindowsError, UnicodeDecodeError, IndexError):
                     dhcp_ip = None
                 # "0.0.0.0" or None means the value is not set (at least not correctly).
                 # If both fixed_ip and dhcp_ip are set, fixed_ip takes precedence 
                 if fixed_ip is not None and fixed_ip != "0.0.0.0":
                     ip = fixed_ip
                 elif dhcp_ip is not None and dhcp_ip != "0.0.0.0":
                     ip = dhcp_ip
                     ip_list = [dhcp_ip]
                 else:
                     log_loading.debug('continue ...')
                     continue
             except IOError:
                 log_loading.warning("IOError")
                 continue
             else:
                 if ip == self.ip or self.ip in ip_list:
                     self.pcap_name = guess
                     self.win_name = win_name
                     self.uuid = uuid                        
                     self.ip_list = ip_list
                     
                     
                     break
     else:
         raise PcapNameNotFoundError
Beispiel #13
0
def read_routes():
    routes = []
    try:
        if WINDOWS_XP:
            routes = _read_routes_c_v1()
        else:
            routes = _read_routes_c(ipv6=False)
    except Exception as e:
        log_loading.warning("Error building scapy IPv4 routing table : %s", e)
    return routes
Beispiel #14
0
 def load_from_powershell(self):
     for i in get_windows_if_list():
         try:
             interface = NetworkInterface(i)
             self.data[interface.name] = interface
         except (KeyError, PcapNameNotFoundError):
             pass
     if len(self.data) == 0:
         log_loading.warning("No match between your pcap and windows network interfaces found. "
                             "You probably won't be able to send packets. "
                             "Deactivating unneeded interfaces and restarting Scapy might help."
                             "Check your winpcap and powershell installation, and access rights.")
Beispiel #15
0
 def __new__(cls, name, bases, dct):
     from scapy.error import log_loading
     import traceback
     try:
         for tb in traceback.extract_stack()+[("??",-1,None,"")]:
             f,l,_,line = tb
             if line.startswith("class"):
                 break
     except:
         f,l="??",-1
         raise
     log_loading.warning("Deprecated (no more needed) use of NewDefaultValues  (%s l. %i).", f, l)
     
     return super(NewDefaultValues, cls).__new__(cls, name, bases, dct)
Beispiel #16
0
 def __new__(cls, name, bases, dct):
     from scapy.error import log_loading
     import traceback
     try:
         for tb in traceback.extract_stack()+[("??",-1,None,"")]:
             f,l,_,line = tb
             if line.startswith("class"):
                 break
     except:
         f,l="??",-1
         raise
     log_loading.warning("Deprecated (no more needed) use of NewDefaultValues  (%s l. %i).", f, l)
     
     return super(NewDefaultValues, cls).__new__(cls, name, bases, dct)
 def load_from_dnet(self):
     """Populate interface table via dnet"""
     for i in pcapdnet.dnet.intf():
         try:
             # XXX: Only Ethernet for the moment: localhost is not supported by dnet and pcap
             # We only take interfaces that have an IP address, because the IP
             # is used for the mapping between dnet and pcap interface names
             # and this significantly improves Scapy's startup performance
             if i["name"].startswith("eth") and "addr" in i:
                 self.data[i["name"]] = NetworkInterface(i)
         except (KeyError, PcapNameNotFoundError):
             pass
     if len(self.data) == 0:
         log_loading.warning("No match between your pcap and dnet network interfaces found. "
                             "You probably won't be able to send packets. "
                             "Deactivating unneeded interfaces and restarting Scapy might help.")
Beispiel #18
0
def read_routes():
    routes = []
    release = platform.release()
    try:
        if release in ["post2008Server", "8"]:
            routes = read_routes_post2008()
        elif release == "XP":
            routes = read_routes_xp()
        else:
            routes = read_routes_7()
    except Exception as e:    
        log_loading.warning("Error building scapy routing table : %s"%str(e))
    else:
        if not routes:
            log_loading.warning("No default IPv4 routes found. Your Windows release may no be supported and you have to enter your routes manually")
    return routes
Beispiel #19
0
 def load_from_dnet(self):
     """Populate interface table via dnet"""
     for i in pcapdnet.dnet.intf():
         try:
             # XXX: Only Ethernet for the moment: localhost is not supported by dnet and pcap
             # We only take interfaces that have an IP address, because the IP
             # is used for the mapping between dnet and pcap interface names
             # and this significantly improves Scapy's startup performance
             if i["name"].startswith("eth") and "addr" in i:
                 self.data[i["name"]] = NetworkInterface(i)
         except (KeyError, PcapNameNotFoundError):
             pass
     if len(self.data) == 0:
         log_loading.warning("No match between your pcap and dnet network interfaces found. "
                             "You probably won't be able to send packets. "
                             "Deactivating unneeded interfaces and restarting Scapy might help.")
Beispiel #20
0
def read_routes():
    routes = []
    release = platform.release()
    try:
        if release in ["post2008Server", "8"]:
            routes = read_routes_post2008()
        elif release == "XP":
            routes = read_routes_xp()
        else:
            routes = read_routes_7()
    except Exception as e:    
        log_loading.warning("Error building scapy routing table : %s"%str(e))
    else:
        if not routes:
            log_loading.warning("No default IPv4 routes found. Your Windows release may no be supported and you have to enter your routes manually")
    return routes
def read_routes():
    ok = 0
    routes = []
    ip = '(\d+\.\d+\.\d+\.\d+)'
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = '(.+)'
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f = os.popen("netstat -rn")
    for l in f.readlines():
        match = re.search(pattern, l)
        if match:
            dest = match.group(1)
            mask = match.group(2)
            gw = match.group(3)
            netif = match.group(4)
            metric = match.group(5)
            try:
                intf = pcapdnet.dnet.intf().get_dst(
                    pcapdnet.dnet.addr(type=2, addrtxt=dest))
            except OSError:
                log_loading.warning(
                    "Building Scapy's routing table: Couldn't get outgoing interface for destination %s"
                    % dest)
                continue
            if not intf.has_key("addr"):
                break
            addr = str(intf["addr"])
            addr = addr.split("/")[0]

            dest = atol(dest)
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search('\d+\.\d+\.\d+\.\d+', gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
            routes.append((dest, mask, gw, str(intf["name"]), addr))
    f.close()
    return routes
Beispiel #22
0
def read_routes():
    ok = 0
    routes = []
    ip = "(\d+\.\d+\.\d+\.\d+)"
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = "(.+)"
    metric_pattern = "(\d+)"
    delim = "\s+"  # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f = os.popen("netstat -rn")
    for l in f.readlines():
        match = re.search(pattern, l)
        if match:
            dest = match.group(1)
            mask = match.group(2)
            gw = match.group(3)
            netif = match.group(4)
            metric = match.group(5)
            try:
                intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest))
            except OSError:
                log_loading.warning(
                    "Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest
                )
                continue
            if not intf.has_key("addr"):
                break
            addr = str(intf["addr"])
            addr = addr.split("/")[0]

            dest = atol(dest)
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search("\d+\.\d+\.\d+\.\d+", gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
            routes.append((dest, mask, gw, str(intf["name"]), addr))
    f.close()
    return routes
Beispiel #23
0
def load_manuf(filename):
    manufdb = ManufDA(_name=filename)
    with open(filename, "rb") as fdesc:
        for line in fdesc:
            try:
                line = line.strip()
                if not line or line.startswith(b"#"):
                    continue
                oui, shrt = line.split()[:2]
                i = line.find(b"#")
                if i < 0:
                    lng = shrt
                else:
                    lng = line[i + 2:]
                manufdb[oui] = plain_str(shrt), plain_str(lng)
            except Exception:
                log_loading.warning("Couldn't parse one line from [%s] [%r]",
                                    filename, line, exc_info=True)
    return manufdb
Beispiel #24
0
def load_services(filename):
    # type: (str) -> Tuple[DADict[int, str], DADict[int, str]]
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)  # type: DADict[int, str]
    udct = DADict(_name="%s-udp" % filename)  # type: DADict[int, str]
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dtct = None
                    if lt[1].endswith(b"/tcp"):
                        dtct = tdct
                    elif lt[1].endswith(b"/udp"):
                        dtct = udct
                    else:
                        continue
                    port = lt[1].split(b'/')[0]
                    name = fixname(lt[0])
                    if b"-" in port:
                        sport, eport = port.split(b"-")
                        for i in range(int(sport), int(eport) + 1):
                            dtct[i] = name
                    else:
                        dtct[int(port)] = name
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Beispiel #25
0
def load_manuf(filename):
    manufdb=ManufDA(_name=filename)
    with open(filename, "rb") as fdesc:
        for l in fdesc:
            try:
                l = l.strip()
                if not l or l.startswith(b"#"):
                    continue
                oui, shrt=l.split()[:2]
                i = l.find(b"#")
                if i < 0:
                    lng=shrt
                else:
                    lng = l[i+2:]
                manufdb[oui] = plain_str(shrt), plain_str(lng)
            except Exception:
                log_loading.warning("Couldn't parse one line from [%s] [%r]",
                                    filename, l, exc_info=True)
    return manufdb
Beispiel #26
0
    def _pcap_check(cls):
        """Performs checks/restart pcap adapter"""
        if not conf.use_pcap:
            # Winpcap/Npcap isn't installed
            return

        _detect = pcap_service_status()

        def _ask_user():
            if not conf.interactive:
                return False
            msg = "Do you want to start it ? (yes/no) [y]: "
            try:
                # Better IPython compatibility
                import IPython
                return IPython.utils.io.ask_yes_no(msg, default='y')
            except (NameError, ImportError):
                while True:
                    _confir = input(msg)
                    _confir = _confir.lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
        if _detect:
            # No action needed
            return
        else:
            log_interactive.warning(
                "Scapy has detected that your pcap service is not running !"
            )
            if not conf.interactive or _ask_user():
                succeed = pcap_service_start(askadmin=conf.interactive)
                if succeed:
                    log_loading.info("Pcap service started !")
                    return
        log_loading.warning(
            "Could not start the pcap service! "
            "You probably won't be able to send packets. "
            "Check your winpcap/npcap installation "
            "and access rights."
        )
Beispiel #27
0
def load_manuf(filename):
    """Load manuf file from Wireshark.
    param:
     - filename: the file to load the manuf file from"""
    manufdb = ManufDA(_name=filename)
    with open(filename, "rb") as fdesc:
        for line in fdesc:
            try:
                line = line.strip()
                if not line or line.startswith(b"#"):
                    continue
                parts = line.split(None, 2)
                oui, shrt = parts[:2]
                lng = parts[2].lstrip(b"#").strip() if len(parts) > 2 else ""
                lng = lng or shrt
                manufdb[oui] = plain_str(shrt), plain_str(lng)
            except Exception:
                log_loading.warning("Couldn't parse one line from [%s] [%r]",
                                    filename, line, exc_info=True)
    return manufdb
Beispiel #28
0
def load_manuf(filename):
    try:
        manufdb=ManufDA(_name=filename)
        for l in open(filename):
            try:
                l = l.strip()
                if not l or l.startswith("#"):
                    continue
                oui,shrt=l.split()[:2]
                i = l.find("#")
                if i < 0:
                    lng=shrt
                else:
                    lng = l[i+2:]
                manufdb[oui] = shrt,lng
            except Exception,e:
                log_loading.warning("Couldn't parse one line from [%s] [%r] (%s)" % (filename, l, e))
    except IOError:
        #log_loading.warning("Couldn't open [%s] file" % filename)
        pass
    return manufdb
Beispiel #29
0
def load_manuf(filename):
    try:
        manufdb=ManufDA(_name=filename)
        for l in open(filename):
            try:
                l = l.strip()
                if not l or l.startswith("#"):
                    continue
                oui,shrt=l.split()[:2]
                i = l.find("#")
                if i < 0:
                    lng=shrt
                else:
                    lng = l[i+2:]
                manufdb[oui] = shrt, lng
            except Exception as e:
                log_loading.warning("Couldn't parse one line from [%s] [%r] (%s)" % (filename, l, e))
    except IOError:
        log_loading.warning("Couldn't open [%s] file" % filename)
        return ""
    return manufdb
Beispiel #30
0
      # Detect Pcap version
      version = pcap_lib_version()
      if "winpcap" in version.lower():
          if os.path.exists(os.environ["WINDIR"] + "\\System32\\Npcap\\wpcap.dll"):
              warning("Winpcap is installed over Npcap. Will use Winpcap (see 'Winpcap/Npcap conflicts' in scapy's docs)", True)
          elif platform.release() != "XP":
              warning("WinPcap is now deprecated (not maintened). Please use Npcap instead", True)
      elif "npcap" in version.lower():
          conf.use_npcap = True
          LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"
  except OSError as e:
      def winpcapy_get_if_list():
          return []
      conf.use_winpcapy = False
      if conf.interactive:
          log_loading.warning("wpcap.dll is not installed. You won't be able to send/recieve packets. Visit the scapy's doc to install it")

  # From BSD net/bpf.h
  #BIOCIMMEDIATE=0x80044270
  BIOCIMMEDIATE=-2147204496

  class PcapTimeoutElapsed(Scapy_Exception):
      pass

  def get_if_raw_hwaddr(iff):
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = b"\0\0\0\0\0\0"
    
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
Beispiel #31
0
        if b"winpcap" in version.lower():
            if os.path.exists(NPCAP_PATH + "\\wpcap.dll"):
                warning("Winpcap is installed over Npcap. "
                        "Will use Winpcap (see 'Winpcap/Npcap conflicts' "
                        "in Scapy's docs)")
            elif platform.release() != "XP":
                warning("WinPcap is now deprecated (not maintained). "
                        "Please use Npcap instead")
        elif b"npcap" in version.lower():
            conf.use_npcap = True
            LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"  # noqa: E501
    except OSError:
        conf.use_winpcapy = False
        if conf.interactive:
            log_loading.warning("wpcap.dll is not installed. "
                                "Restricted mode enabled ! "
                                "Visit the Scapy's doc to install it")

    if conf.use_winpcapy:

        def get_if_list():
            """Returns all pcap names"""
            if not conf.cache_iflist:
                load_winpcapy()
            return [x[0] for x in conf.cache_iflist.values()]
    else:
        get_if_list = lambda: {}

    class _PcapWrapper_winpcap:  # noqa: F811
        """Wrapper for the WinPcap calls"""
        def __init__(self, device, snaplen, promisc, to_ms, monitor=None):
Beispiel #32
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=20):
    global SESSION
    global GLOBKEYS

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("%(levelname)s: %(message)s"))
    log_scapy.addHandler(console_handler)

    from scapy.config import conf
    conf.color_theme = DefaultTheme()
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    init_session(session_name, mydict)

    if conf.fancy_prompt:

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        quote, author = choice(QUOTES)
        the_banner.extend(_prepare_quote(quote, author, max_len=39))
        the_banner.append("   |")
        the_banner = "\n".join(
            logo + banner
            for logo, banner in six.moves.zip_longest((
                conf.color_theme.logo(line)
                for line in the_logo), (conf.color_theme.success(line)
                                        for line in the_banner),
                                                      fillvalue=""))
    else:
        the_banner = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    IPYTHON = False
    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            IPython
            IPYTHON = True
        except NameError as e:
            log_loading.warning(
                "IPython not available. Using standard Python shell instead. "
                "AutoCompletion, History are disabled.")
            IPYTHON = False

    init_session(session_name, mydict)

    if IPYTHON:
        banner = the_banner + " using IPython %s\n" % IPython.__version__
        from IPython.terminal.embed import InteractiveShellEmbed
        from IPython.terminal.prompts import Prompts, Token
        from IPython.utils.generics import complete_object
        from traitlets.config.loader import Config
        from scapy.packet import Packet

        cfg = Config()

        @complete_object.when_type(Packet)
        def complete_packet(obj, prev_completions):
            return prev_completions + [fld.name for fld in obj.fields_desc]

        try:
            get_ipython
        except NameError:
            # Set "classic" prompt style when launched from run_scapy(.bat) files
            class ClassicPrompt(Prompts):
                def in_prompt_tokens(self, cli=None):
                    return [
                        (Token.Prompt, '>>> '),
                    ]

                def out_prompt_tokens(self):
                    return [
                        (Token.OutPrompt, ''),
                    ]

            cfg.TerminalInteractiveShell.prompts_class = ClassicPrompt  # Set classic prompt style
            apply_ipython_color(shell=cfg.TerminalInteractiveShell
                                )  # Register and apply scapy color style
            cfg.TerminalInteractiveShell.confirm_exit = False  # Remove confirm exit
            cfg.TerminalInteractiveShell.separate_in = u''  # Remove spacing line

        cfg.TerminalInteractiveShell.hist_file = conf.histfile

        # configuration can thus be specified here.
        ipshell = InteractiveShellEmbed(
            config=cfg,
            banner1=banner,
            hist_file=conf.histfile if conf.histfile else None,
            user_ns=SESSION)

        ipshell(local_ns=SESSION)
    else:
        code.interact(banner=the_banner, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del (six.moves.builtins.__dict__[k])
        except:
            pass
Beispiel #33
0
    ETHER_TYPES = load_ethertypes(None)
    MANUFDB = ManufDA()
else:
    IP_PROTOS = load_protocols("/etc/protocols")
    ETHER_TYPES = load_ethertypes("/etc/ethertypes")
    TCP_SERVICES, UDP_SERVICES = load_services("/etc/services")
    MANUFDB = ManufDA()
    manuf_path = select_path([
        '/usr', '/usr/local', '/opt', '/opt/wireshark',
        '/Applications/Wireshark.app/Contents/Resources'
    ], "share/wireshark/manuf")
    if manuf_path:
        try:
            MANUFDB = load_manuf(manuf_path)
        except (IOError, OSError):
            log_loading.warning("Cannot read wireshark manuf database")

#####################
#  knowledge bases  #
#####################


class KnowledgeBase:
    def __init__(self, filename):
        self.filename = filename
        self.base = None

    def lazy_init(self):
        self.base = ""

    def reload(self, filename=None):
Beispiel #34
0
        if b"winpcap" in version.lower():
            if os.path.exists(NPCAP_PATH + "\\wpcap.dll"):
                warning("Winpcap is installed over Npcap. "
                        "Will use Winpcap (see 'Winpcap/Npcap conflicts' "
                        "in Scapy's docs)")
            elif platform.release() != "XP":
                warning("WinPcap is now deprecated (not maintained). "
                        "Please use Npcap instead")
        elif b"npcap" in version.lower():
            conf.use_npcap = True
            LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"  # noqa: E501
    except OSError:
        conf.use_winpcapy = False
        if conf.interactive:
            log_loading.warning("wpcap.dll is not installed. "
                                "Restricted mode enabled ! "
                                "Visit the Scapy's doc to install it")

    if conf.use_winpcapy:
        def get_if_list():
            """Returns all pcap names"""
            if not conf.cache_iflist:
                load_winpcapy()
            return [x[0] for x in conf.cache_iflist.values()]
    else:
        get_if_list = lambda: {}

    class _PcapWrapper_winpcap:  # noqa: F811
        """Wrapper for the WinPcap calls"""

        def __init__(self, device, snaplen, promisc, to_ms, monitor=None):
Beispiel #35
0
if conf.prog.tcpdump and conf.use_npcap:
    def test_windump_npcap():
        """Return whether windump version is correct or not"""
        try:
            p_test_windump = sp.Popen([conf.prog.tcpdump, "-help"], stdout=sp.PIPE, stderr=sp.STDOUT)  # noqa: E501
            stdout, err = p_test_windump.communicate()
            _windows_title()
            _output = stdout.lower()
            return b"npcap" in _output and b"winpcap" not in _output
        except Exception:
            return False
    windump_ok = test_windump_npcap()
    if not windump_ok:
        log_loading.warning(
            "The installed Windump version does not work with Npcap! "
            "Refer to 'Winpcap/Npcap conflicts' in scapy's installation doc"
        )
    del windump_ok


def get_windows_if_list(extended=False):
    """Returns windows interfaces through GetAdaptersAddresses.

    params:
     - extended: include anycast and multicast IPv6 (default False)"""
    # Should work on Windows XP+
    def _get_mac(x):
        size = x["physical_address_length"]
        if size != 6:
            return ""
        data = bytearray(x["physical_address"])
Beispiel #36
0
PACKET_HOST = 0  # To us
PACKET_BROADCAST = 1  # To all
PACKET_MULTICAST = 2  # To group
PACKET_OTHERHOST = 3  # To someone else
PACKET_OUTGOING = 4  # Outgoing of any type
PACKET_LOOPBACK = 5  # MC/BRD frame looped back
PACKET_USER = 6  # To user space
PACKET_KERNEL = 7  # To kernel space
PACKET_FASTROUTE = 6  # Fastrouted frame
# Unused, PACKET_FASTROUTE and PACKET_LOOPBACK are invisible to user space

LOOPBACK_NAME = "lo"

with os.popen("%s -V 2> /dev/null" % conf.prog.tcpdump) as _f:
    if _f.close() >> 8 == 0x7f:
        log_loading.warning(
            "Failed to execute tcpdump. Check it is installed and in the PATH")
        TCPDUMP = 0
    else:
        TCPDUMP = 1
del (_f)


def get_if_raw_hwaddr(iff):
    return struct.unpack("16xh6s8x", get_if(iff, SIOCGIFHWADDR))


def get_if_raw_addr(iff):
    try:
        return get_if(iff, SIOCGIFADDR)[20:24]
    except IOError:
        return "\0\0\0\0"
Beispiel #37
0
    MATPLOTLIB = 0
    MATPLOTLIB_INLINED = 0
    MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()
    log_loading.info("Can't import matplotlib. Won't be able to plot.")

# PYX


def _test_pyx():
    """Returns if PyX is correctly installed or not"""
    try:
        with open(os.devnull, 'wb') as devnull:
            r = subprocess.check_call(["pdflatex", "--version"],
                                      stdout=devnull, stderr=subprocess.STDOUT)
    except (subprocess.CalledProcessError, OSError):
        return False
    else:
        return r == 0


try:
    import pyx  # noqa: F401
    if _test_pyx():
        PYX = 1
    else:
        log_loading.warning("PyX dependencies are not installed ! Please install TexLive or MikTeX.")  # noqa: E501
        PYX = 0
except ImportError:
    log_loading.info("Can't import PyX. Won't be able to use psdump() or pdfdump().")  # noqa: E501
    PYX = 0
Beispiel #38
0
def read_routes():
    ifaces.load_from_dnet()
    
    zmap = {}
    for i in ifaces:
        for ip in ifaces.get(i).ip_list:
            zmap[ip] = i
    

    ok = 0
    routes = []
    ip = '(\d+\.\d+\.\d+\.\d+)'
    # On Vista and Windows 7 the gateway can be IP or 'On-link'.
    # But the exact 'On-link' string depends on the locale, so we allow any text.
    gw_pattern = '(.+)'
    metric_pattern = "(\d+)"
    delim = "\s+"        # The columns are separated by whitespace
    netstat_line = delim.join([ip, ip, gw_pattern, ip, metric_pattern])
    pattern = re.compile(netstat_line)
    f=os.popen("netstat -rn")
    
    import platform
    is_win7 =  not platform.platform().lower().startswith('windows-xp')
    
    for l in f.readlines():
        #l = l.encode('utf-8')
       
        
        if is_win7:
            str1 = u'永久路由'.encode('gbk')
            if l.find( str1 )!=-1 or l.find('permanant route')!=-1 \
                or l.find('Persistent Routes') !=-1 :
                # Igore the permanant route on Vista and Win7                
                break
        
        match = re.search(pattern,l)
        if match:
            dest2   = match.group(1)
            mask   = match.group(2)
            gw     = match.group(3)
            netif  = match.group(4)
            metric = match.group(5)
           
            dest = atol(dest2)
            if dest >= I_MULTIIP_START and dest <= I_MULTIIP_END:
                # multiple ip address
                
                ifname = zmap.get(netif, 'lo0')
                addr = netif
                
            else:
            
                try:
                    # If addrtxt is multicast IP, it will not function well
                    intf = pcapdnet.dnet.intf().get_dst(pcapdnet.dnet.addr(type=2, addrtxt=dest2))
                except OSError:
                    log_loading.warning("Building Scapy's routing table: Couldn't get outgoing interface for destination %s" % dest)
                    continue               
                if not intf.has_key("addr"):
                    break
                addr = str(intf["addr"])
                addr = addr.split("/")[0]
                
                
                ifname = str(intf["name"])
                
                
            mask = atol(mask)
            # If the gateway is no IP we assume it's on-link
            gw_ipmatch = re.search('\d+\.\d+\.\d+\.\d+', gw)
            if gw_ipmatch:
                gw = gw_ipmatch.group(0)
            else:
                gw = netif
                
                
            #routes.append((dest,mask,gw, str(intf["name"]), addr))
            # when a interface has multi IPs, addr may not be the correct OutIP
            # So I extract the correct IP from ifaces 
            #                                      by  chenzongze 2012.07.24                
            output_ip = netif
            for ifs in ifaces:
                if addr in ifaces[ifs].ip_list:
                
                    for my_ip in ifaces[ifs].ip_list:
                        if ( atol(my_ip) & mask) == ( atol(gw) & mask ) and (mask !=0):
                            output_ip = my_ip
                            break
                    
                    break
            

            
            
            # Add metric        by chenzongze 2012.07.24
            routes.append((dest,mask,gw, ifname, output_ip, metric))
            
            
            
            
            
    f.close()
    return routes
Beispiel #39
0
# PYX


def _test_pyx():
    """Returns if PyX is correctly installed or not"""
    try:
        with open(os.devnull, 'wb') as devnull:
            r = subprocess.check_call(["pdflatex", "--version"],
                                      stdout=devnull,
                                      stderr=subprocess.STDOUT)
    except (subprocess.CalledProcessError, OSError):
        return False
    else:
        return r == 0


try:
    import pyx  # noqa: F401
    if _test_pyx():
        PYX = 1
    else:
        log_loading.warning(
            "PyX dependencies are not installed ! Please install TexLive or MikTeX."
        )  # noqa: E501
        PYX = 0
except ImportError:
    log_loading.info(
        "Can't import PyX. Won't be able to use psdump() or pdfdump()."
    )  # noqa: E501
    PYX = 0
Beispiel #40
0
            elif platform.release() != "XP":
                warning(
                    "WinPcap is now deprecated (not maintened). Please use Npcap instead",
                    onlyOnce=True)
        elif b"npcap" in version.lower():
            conf.use_npcap = True
            LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"
    except OSError as e:

        def winpcapy_get_if_list():
            return []

        conf.use_winpcapy = False
        if conf.interactive:
            log_loading.warning(
                "wpcap.dll is not installed. You won't be able to send/recieve packets. Visit the scapy's doc to install it"
            )

    # From BSD net/bpf.h
    #BIOCIMMEDIATE=0x80044270
    BIOCIMMEDIATE = -2147204496

    class PcapTimeoutElapsed(Scapy_Exception):
        pass

    def get_if_raw_hwaddr(iff):
        err = create_string_buffer(PCAP_ERRBUF_SIZE)
        devs = POINTER(pcap_if_t)()
        ret = b"\0\0\0\0\0\0"

        if pcap_findalldevs(byref(devs), err) < 0:
Beispiel #41
0
        MANUFDB = None
else:
    IP_PROTOS = load_protocols("/etc/protocols")
    ETHER_TYPES = load_ethertypes("/etc/ethertypes")
    TCP_SERVICES, UDP_SERVICES = load_services("/etc/services")
    MANUFDB = None
    for prefix in ['/usr', '/usr/local', '/opt', '/opt/wireshark']:
        try:
            MANUFDB = load_manuf(os.path.join(prefix, "share", "wireshark",
                                              "manuf"))
            if MANUFDB:
                break
        except (IOError, OSError):  # Same as above
            pass
    if not MANUFDB:
        log_loading.warning("Cannot read wireshark manuf database")


#####################
#  knowledge bases  #
#####################

class KnowledgeBase:
    def __init__(self, filename):
        self.filename = filename
        self.base = None

    def lazy_init(self):
        self.base = ""

    def reload(self, filename=None):
Beispiel #42
0
def interact(mydict=None,argv=None,mybanner=None,loglevel=20):
    global SESSION
    global GLOBKEYS

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
    log_scapy.addHandler(console_handler)

    from scapy.config import conf
    conf.color_theme = DefaultTheme()
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel-10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1]))


    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    init_session(session_name, mydict)

    if conf.fancy_prompt:

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        quote, author = choice(QUOTES)
        the_banner.extend(_prepare_quote(quote, author, max_len=39))
        the_banner.append("   |")
        the_banner = "\n".join(
            logo + banner for logo, banner in six.moves.zip_longest(
                (conf.color_theme.logo(line) for line in the_logo),
                (conf.color_theme.success(line) for line in the_banner),
                fillvalue=""
            )
        )
    else:
        the_banner = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            import IPython
            from IPython.terminal.embed import InteractiveShellEmbed
        except ImportError:
            log_loading.warning(
                "IPython not available. Using standard Python shell "
                "instead.\nAutoCompletion, History are disabled."
            )
            IPYTHON = False
        else:
            IPYTHON = True
    else:
        IPYTHON = False

    init_session(session_name, mydict)

    if IPYTHON:
        banner = the_banner + " using IPython %s\n" % IPython.__version__
        try:
            from traitlets.config.loader import Config
        except ImportError:
            log_loading.warning(
                "traitlets not available. Some Scapy shell features won't be "
                "available."
            )
            ipshell = InteractiveShellEmbed(
                banner1=banner,
                user_ns=SESSION,
            )
        else:
            cfg = Config()
            try:
                get_ipython
            except NameError:
                # Set "classic" prompt style when launched from run_scapy(.bat) files
                # Register and apply scapy color+prompt style
                apply_ipython_style(shell=cfg.TerminalInteractiveShell)
                cfg.TerminalInteractiveShell.confirm_exit = False
                cfg.TerminalInteractiveShell.separate_in = u''
            cfg.TerminalInteractiveShell.hist_file = conf.histfile
            # configuration can thus be specified here.
            ipshell = InteractiveShellEmbed(config=cfg,
                                            banner1=banner,
                                            hist_file=conf.histfile if conf.histfile else None,
                                            user_ns=SESSION)
        ipshell(local_ns=SESSION)
    else:
        code.interact(banner = the_banner, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del(six.moves.builtins.__dict__[k])
        except:
            pass
Beispiel #43
0
            if os.path.exists(NPCAP_PATH + "\\wpcap.dll"):
                warning("Winpcap is installed over Npcap. "
                        "Will use Winpcap (see 'Winpcap/Npcap conflicts' "
                        "in Scapy's docs)")
            elif platform.release() != "XP":
                warning("WinPcap is now deprecated (not maintained). "
                        "Please use Npcap instead")
        elif b"npcap" in version.lower():
            conf.use_npcap = True
            LOOPBACK_NAME = scapy.consts.LOOPBACK_NAME = "Npcap Loopback Adapter"  # noqa: E501
    except OSError:
        conf.use_winpcapy = False
        if conf.interactive:
            log_loading.warning(
                conf.color_theme.format(
                    "Npcap/Winpcap is not installed ! See "
                    "https://scapy.readthedocs.io/en/latest/installation.html#windows",  # noqa: E501
                    "black+bg_red"))

    if conf.use_winpcapy:

        def get_if_list():
            """Returns all pcap names"""
            if not conf.cache_iflist:
                load_winpcapy()
            return list(conf.cache_iflist)
    else:
        get_if_list = lambda: []

    class _PcapWrapper_winpcap:  # noqa: F811
        """Wrapper for the WinPcap calls"""
Beispiel #44
0
# From if_packet.h
PACKET_HOST = 0  # To us
PACKET_BROADCAST = 1  # To all
PACKET_MULTICAST = 2  # To group
PACKET_OTHERHOST = 3  # To someone else
PACKET_OUTGOING = 4  # Outgoing of any type
PACKET_LOOPBACK = 5  # MC/BRD frame looped back
PACKET_USER = 6  # To user space
PACKET_KERNEL = 7  # To kernel space
PACKET_FASTROUTE = 6  # Fastrouted frame
# Unused, PACKET_FASTROUTE and PACKET_LOOPBACK are invisible to user space


with os.popen("%s -V 2> /dev/null" % conf.prog.tcpdump) as _f:
    if _f.close() >> 8 == 0x7f:
        log_loading.warning("Failed to execute tcpdump. Check it is installed and in the PATH")  # noqa: E501
        TCPDUMP = 0
    else:
        TCPDUMP = 1
del(_f)


def get_if_raw_hwaddr(iff):
    return struct.unpack("16xh6s8x", get_if(iff, SIOCGIFHWADDR))


def get_if_raw_addr(iff):
    try:
        return get_if(iff, SIOCGIFADDR)[20:24]
    except IOError:
        return b"\0\0\0\0"
Beispiel #45
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=logging.INFO):
    """Starts Scapy's console."""
    global SESSION
    global GLOBKEYS

    try:
        if WINDOWS:
            # colorama is bundled within IPython.
            # logging.StreamHandler will be overwritten when called,
            # We can't wait for IPython to call it
            import colorama
            colorama.init()
        # Success
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(
            ScapyColoredFormatter(
                "%(levelname)s: %(message)s",
            )
        )
    except ImportError:
        # Failure: ignore colors in the logger
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(
            logging.Formatter(
                "%(levelname)s: %(message)s",
            )
        )
    log_scapy.addHandler(console_handler)

    # We're in interactive mode, let's throw the DeprecationWarnings
    warnings.simplefilter("always")

    from scapy.config import conf
    conf.interactive = True
    conf.color_theme = DefaultTheme()
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d:H")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-H":
                conf.fancy_prompt = False
                conf.verb = 30
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1]))  # noqa: E501

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    # Reset sys.argv, otherwise IPython thinks it is for him
    sys.argv = sys.argv[:1]

    init_session(session_name, mydict)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            import IPython
            from IPython import start_ipython
        except ImportError:
            log_loading.warning(
                "IPython not available. Using standard Python shell "
                "instead.\nAutoCompletion, History are disabled."
            )
            if WINDOWS:
                log_loading.warning(
                    "On Windows, colors are also disabled"
                )
                conf.color_theme = BlackAndWhite()
            IPYTHON = False
        else:
            IPYTHON = True
    else:
        IPYTHON = False

    if conf.fancy_prompt:
        from scapy.utils import get_terminal_width
        mini_banner = (get_terminal_width() or 84) <= 75

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        # Used on mini screens
        the_logo_mini = [
            "      .SYPACCCSASYY  ",
            "P /SCS/CCS        ACS",
            "       /A          AC",
            "     A/PS       /SPPS",
            "        YP        (SC",
            "       SPS/A.      SC",
            "   Y/PACC          PP",
            "    PY*AYC        CAA",
            "         YYCY//SCYP  ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        if mini_banner:
            the_logo = the_logo_mini
            the_banner = [x[2:] for x in the_banner[3:-1]]
            the_banner = [""] + the_banner + [""]
        else:
            quote, author = choice(QUOTES)
            the_banner.extend(_prepare_quote(quote, author, max_len=39))
            the_banner.append("   |")
        the_banner = "\n".join(
            logo + banner for logo, banner in six.moves.zip_longest(
                (conf.color_theme.logo(line) for line in the_logo),
                (conf.color_theme.success(line) for line in the_banner),
                fillvalue=""
            )
        )
    else:
        the_banner = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if IPYTHON:
        banner = the_banner + " using IPython %s\n" % IPython.__version__
        try:
            from traitlets.config.loader import Config
        except ImportError:
            log_loading.warning(
                "traitlets not available. Some Scapy shell features won't be "
                "available."
            )
            try:
                start_ipython(
                    display_banner=False,
                    user_ns=SESSION,
                    exec_lines=["print(\"\"\"" + banner + "\"\"\")"]
                )
            except Exception:
                code.interact(banner=the_banner, local=SESSION)
        else:
            cfg = Config()
            try:
                get_ipython
            except NameError:
                # Set "classic" prompt style when launched from run_scapy(.bat) files  # noqa: E501
                # Register and apply scapy color+prompt style
                apply_ipython_style(shell=cfg.TerminalInteractiveShell)
                cfg.TerminalInteractiveShell.confirm_exit = False
                cfg.TerminalInteractiveShell.separate_in = u''
            if int(IPython.__version__[0]) >= 6:
                cfg.TerminalInteractiveShell.term_title_format = "Scapy v%s" % conf.version  # noqa: E501
            else:
                cfg.TerminalInteractiveShell.term_title = False
            cfg.HistoryAccessor.hist_file = conf.histfile
            cfg.InteractiveShell.banner1 = banner
            # configuration can thus be specified here.
            try:
                start_ipython(config=cfg, user_ns=SESSION)
            except (AttributeError, TypeError):
                code.interact(banner=the_banner, local=SESSION)
    else:
        code.interact(banner=the_banner, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del(six.moves.builtins.__dict__[k])
        except Exception:
            pass
Beispiel #46
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=20):
    global SESSION
    global GLOBKEYS

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(
        logging.Formatter("%(levelname)s: %(message)s"))
    log_scapy.addHandler(console_handler)

    from scapy.config import conf
    conf.color_theme = DefaultTheme()
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    session_name = None

    if argv is None:
        argv = sys.argv

    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    init_session(session_name, mydict)

    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE, interactive=True)
    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE, interactive=True)

    if not conf.interactive_shell or conf.interactive_shell.lower() in [
            "ipython", "auto"
    ]:
        try:
            import IPython
            from IPython import start_ipython
        except ImportError:
            log_loading.warning(
                "IPython not available. Using standard Python shell "
                "instead.\nAutoCompletion, History are disabled.")
            if WINDOWS:
                log_loading.warning(
                    "IPyton not available. On Windows, colors are disabled")
                conf.color_theme = BlackAndWhite()
            IPYTHON = False
        else:
            IPYTHON = True
    else:
        IPYTHON = False

    if conf.fancy_prompt:

        the_logo = [
            "                                      ",
            "                     aSPY//YASa       ",
            "             apyyyyCY//////////YCa    ",
            "            sY//////YSpcs  scpCY//Pp  ",
            " ayp ayyyyyyySCP//Pp           syY//C ",
            " AYAsAYYYYYYYY///Ps              cY//S",
            "         pCCCCY//p          cSSps y//Y",
            "         SPPPP///a          pP///AC//Y",
            "              A//A            cyP////C",
            "              p///Ac            sC///a",
            "              P////YCpc           A//A",
            "       scccccp///pSP///p          p//Y",
            "      sY/////////y  caa           S//P",
            "       cayCyayP//Ya              pY/Ya",
            "        sY/PsY////YCc          aC//Yp ",
            "         sc  sccaCY//PCypaapyCP//YSs  ",
            "                  spCPY//////YPSps    ",
            "                       ccaacs         ",
            "                                      ",
        ]

        the_banner = [
            "",
            "",
            "   |",
            "   | Welcome to Scapy",
            "   | Version %s" % conf.version,
            "   |",
            "   | https://github.com/secdev/scapy",
            "   |",
            "   | Have fun!",
            "   |",
        ]

        quote, author = choice(QUOTES)
        the_banner.extend(_prepare_quote(quote, author, max_len=39))
        the_banner.append("   |")
        the_banner = "\n".join(
            logo + banner
            for logo, banner in six.moves.zip_longest((
                conf.color_theme.logo(line)
                for line in the_logo), (conf.color_theme.success(line)
                                        for line in the_banner),
                                                      fillvalue=""))
    else:
        the_banner = "Welcome to Scapy (%s)" % conf.version
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if IPYTHON:
        banner = the_banner + " using IPython %s\n" % IPython.__version__
        try:
            from traitlets.config.loader import Config
        except ImportError:
            log_loading.warning(
                "traitlets not available. Some Scapy shell features won't be "
                "available.")
            try:
                start_ipython(display_banner=False,
                              user_ns=SESSION,
                              exec_lines=["print(\"\"\"" + banner + "\"\"\")"])
            except:
                code.interact(banner=the_banner, local=SESSION)
        else:
            cfg = Config()
            try:
                get_ipython
            except NameError:
                # Set "classic" prompt style when launched from run_scapy(.bat) files
                # Register and apply scapy color+prompt style
                apply_ipython_style(shell=cfg.TerminalInteractiveShell)
                cfg.TerminalInteractiveShell.confirm_exit = False
                cfg.TerminalInteractiveShell.separate_in = u''
            if int(IPython.__version__[0]) >= 6:
                cfg.TerminalInteractiveShell.term_title_format = "Scapy v" + conf.version
            else:
                cfg.TerminalInteractiveShell.term_title = False
            cfg.HistoryAccessor.hist_file = conf.histfile
            cfg.InteractiveShell.banner1 = banner
            # configuration can thus be specified here.
            try:
                start_ipython(config=cfg, user_ns=SESSION)
            except (AttributeError, TypeError):
                code.interact(banner=the_banner, local=SESSION)
    else:
        code.interact(banner=the_banner, local=SESSION)

    if conf.session:
        save_session(conf.session, SESSION)

    for k in GLOBKEYS:
        try:
            del (six.moves.builtins.__dict__[k])
        except:
            pass
Beispiel #47
0
def apply_ipython_style(shell):
    """Updates the specified IPython console shell with
    the conf.color_theme scapy theme."""
    try:
        from IPython.terminal.prompts import Prompts, Token
    except Exception:
        from scapy.error import log_loading
        log_loading.warning(
            "IPython too old. Shell color won't be handled."
        )
        return
    from scapy.config import conf
    scapy_style = {}
    # Overwrite colors
    if isinstance(conf.color_theme, NoTheme):
        shell.colors = 'nocolor'
    elif isinstance(conf.color_theme, BrightTheme):
        # lightbg is optimized for light backgrounds
        shell.colors = 'lightbg'
    elif isinstance(conf.color_theme, ColorOnBlackTheme):
        # linux is optimised for dark backgrounds
        shell.colors = 'linux'
    else:
        # default
        shell.colors = 'neutral'
    try:
        get_ipython()
        # This function actually contains tons of hacks
        color_magic = shell.magics_manager.magics["line"]["colors"]
        color_magic(shell.colors)
    except NameError:
        pass
    # Prompt Style
    if isinstance(conf.prompt, Prompts):
        # Set custom prompt style
        shell.prompts_class = conf.prompt
    else:
        if isinstance(conf.color_theme, (FormatTheme, NoTheme)):
            # Formatable
            if isinstance(conf.color_theme, HTMLTheme):
                prompt = cgi.escape(conf.prompt)
            elif isinstance(conf.color_theme, LatexTheme):
                from scapy.utils import tex_escape
                prompt = tex_escape(conf.prompt)
            else:
                prompt = conf.prompt
            prompt = conf.color_theme.prompt(prompt)
        else:
            # Needs to be manually set
            prompt = str(conf.prompt)
            scapy_style[Token.Prompt] = Color.ansi_to_pygments(
                conf.color_theme.style_prompt
            )

        class ClassicPrompt(Prompts):
            def in_prompt_tokens(self, cli=None):
                return [(Token.Prompt, prompt), ]

            def out_prompt_tokens(self):
                return [(Token.OutPrompt, ''), ]
        # Apply classic prompt style
        shell.prompts_class = ClassicPrompt
        sys.ps1 = prompt
    # Register scapy color style
    shell.highlighting_style_overrides = scapy_style
    # Apply if Live
    try:
        get_ipython().refresh_style()
    except NameError:
        pass