Exemple #1
0
 def fileno(self):
     if WINDOWS:
         log_loading.error("Cannot get selectable PCAP fd on Windows")
         return 0
     else:
         # This does not exist under Windows
         return pcap_get_selectable_fd(self.pcap)
Exemple #2
0
 def fileno(self):
     if WINDOWS:
         log_loading.error("Cannot get selectable PCAP fd on Windows")
         return 0
     else:
         # This does not exist under Windows
         from scapy.modules.winpcapy import pcap_get_selectable_fd
         return pcap_get_selectable_fd(self.pcap)
Exemple #3
0
def init_session(
    session_name,  # type: Optional[Union[str, None]]
    mydict=None  # type: Optional[Union[Dict[str, Any], None]]
):
    # type: (...) -> Tuple[Dict[str, Any], List[str]]
    from scapy.config import conf
    SESSION = {}  # type: Dict[str, Any]
    GLOBKEYS = []  # type: List[str]

    scapy_builtins = {
        k: v
        for k, v in six.iteritems(
            importlib.import_module(".all", "scapy").__dict__)
        if _validate_local(k)
    }
    six.moves.builtins.__dict__.update(scapy_builtins)
    GLOBKEYS.extend(scapy_builtins)
    GLOBKEYS.append("scapy_session")

    if session_name:
        try:
            os.stat(session_name)
        except OSError:
            log_loading.info("New session [%s]" % session_name)
        else:
            try:
                try:
                    SESSION = six.moves.cPickle.load(
                        gzip.open(session_name, "rb"))
                except IOError:
                    SESSION = six.moves.cPickle.load(open(session_name, "rb"))
                log_loading.info("Using session [%s]" % session_name)
            except EOFError:
                log_loading.error("Error opening session [%s]" % session_name)
            except AttributeError:
                log_loading.error("Error opening session [%s]. "
                                  "Attribute missing" % session_name)

        if SESSION:
            if "conf" in SESSION:
                conf.configure(SESSION["conf"])
                conf.session = session_name
                SESSION["conf"] = conf
            else:
                conf.session = session_name
        else:
            conf.session = session_name
            SESSION = {"conf": conf}
    else:
        SESSION = {"conf": conf}

    six.moves.builtins.__dict__["scapy_session"] = SESSION

    if mydict is not None:
        six.moves.builtins.__dict__["scapy_session"].update(mydict)
        update_ipython_session(mydict)
        GLOBKEYS.extend(mydict)
    return SESSION, GLOBKEYS
Exemple #4
0
 def setfilter(self, f):
     filter_exp = create_string_buffer(f)
     if pcap_compile(self.pcap, byref(self.bpf_program), filter_exp, 0, -1) == -1:
       log_loading.error("Could not compile filter expression %s" % f)
       return False
     else:
       if pcap_setfilter(self.pcap, byref(self.bpf_program)) == -1:
         log_loading.error("Could not install filter %s" % f)
         return False
     return True
Exemple #5
0
 def setfilter(self, f):
     filter_exp = create_string_buffer(f.encode("utf8"))
     if pcap_compile(self.pcap, byref(self.bpf_program), filter_exp, 0, -1) == -1:
       log_loading.error("Could not compile filter expression %s", f)
       return False
     else:
       if pcap_setfilter(self.pcap, byref(self.bpf_program)) == -1:
         log_loading.error("Could not install filter %s", f)
         return False
     return True
Exemple #6
0
def init_session(session_name, mydict=None):
    from scapy.config import conf
    global SESSION
    global GLOBKEYS

    scapy_builtins = {
        k: v
        for k, v in six.iteritems(
            importlib.import_module(".all", "scapy").__dict__)
        if _validate_local(k)
    }  # noqa: E501
    six.moves.builtins.__dict__.update(scapy_builtins)
    GLOBKEYS.extend(scapy_builtins)
    GLOBKEYS.append("scapy_session")
    scapy_builtins = None

    if session_name:
        try:
            os.stat(session_name)
        except OSError:
            log_loading.info("New session [%s]" % session_name)
        else:
            try:
                try:
                    SESSION = six.moves.cPickle.load(
                        gzip.open(session_name, "rb"))  # noqa: E501
                except IOError:
                    SESSION = six.moves.cPickle.load(open(session_name, "rb"))
                log_loading.info("Using session [%s]" % session_name)
            except EOFError:
                log_loading.error("Error opening session [%s]" % session_name)
            except AttributeError:
                log_loading.error(
                    "Error opening session [%s]. Attribute missing" %
                    session_name)  # noqa: E501

        if SESSION:
            if "conf" in SESSION:
                conf.configure(SESSION["conf"])
                conf.session = session_name
                SESSION["conf"] = conf
            else:
                conf.session = session_name
        else:
            conf.session = session_name
            SESSION = {"conf": conf}
    else:
        SESSION = {"conf": conf}

    six.moves.builtins.__dict__["scapy_session"] = SESSION

    if mydict is not None:
        six.moves.builtins.__dict__["scapy_session"].update(mydict)
        update_ipython_session(mydict)
        GLOBKEYS.extend(mydict)
Exemple #7
0
def init_session(session_name, mydict=None):
    global SESSION
    global GLOBKEYS

    scapy_builtins = {k: v for k, v in six.iteritems(importlib.import_module(".all", "scapy").__dict__) if _validate_local(k)}  # noqa: E501
    six.moves.builtins.__dict__.update(scapy_builtins)
    GLOBKEYS.extend(scapy_builtins)
    GLOBKEYS.append("scapy_session")
    scapy_builtins = None  # XXX replace with "with" statement

    if session_name:
        try:
            os.stat(session_name)
        except OSError:
            log_loading.info("New session [%s]" % session_name)
        else:
            try:
                try:
                    SESSION = six.moves.cPickle.load(gzip.open(session_name, "rb"))  # noqa: E501
                except IOError:
                    SESSION = six.moves.cPickle.load(open(session_name, "rb"))
                log_loading.info("Using session [%s]" % session_name)
            except EOFError:
                log_loading.error("Error opening session [%s]" % session_name)
            except AttributeError:
                log_loading.error("Error opening session [%s]. Attribute missing" % session_name)  # noqa: E501

        if SESSION:
            if "conf" in SESSION:
                conf.configure(SESSION["conf"])
                conf.session = session_name
                SESSION["conf"] = conf
            else:
                conf.session = session_name
        else:
            conf.session = session_name
            SESSION = {"conf": conf}
    else:
        SESSION = {"conf": conf}

    six.moves.builtins.__dict__["scapy_session"] = SESSION

    if mydict is not None:
        six.moves.builtins.__dict__["scapy_session"].update(mydict)
        update_ipython_session(mydict)
        GLOBKEYS.extend(mydict)
Exemple #8
0
def init_session(
        session_name,  # type: Optional[Union[str, None]]
        mydict=None,  # type: Optional[Union[Dict[str, Any], None]]
        ret=False,  # type: bool
):
    # type: (...) -> Optional[Dict[str, Any]]
    from scapy.config import conf
    SESSION = {}  # type: Optional[Dict[str, Any]]

    if session_name:
        try:
            os.stat(session_name)
        except OSError:
            log_loading.info("New session [%s]", session_name)
        else:
            try:
                try:
                    SESSION = six.moves.cPickle.load(
                        gzip.open(session_name, "rb"))
                except IOError:
                    SESSION = six.moves.cPickle.load(open(session_name, "rb"))
                log_loading.info("Using existing session [%s]", session_name)
            except ValueError:
                msg = "Error opening Python3 pickled session on Python2 [%s]"
                log_loading.error(msg, session_name)
            except EOFError:
                log_loading.error("Error opening session [%s]", session_name)
            except AttributeError:
                log_loading.error(
                    "Error opening session [%s]. "
                    "Attribute missing", session_name)

        if SESSION:
            if "conf" in SESSION:
                conf.configure(SESSION["conf"])
                conf.session = session_name
                SESSION["conf"] = conf
            else:
                conf.session = session_name
        else:
            conf.session = session_name
            SESSION = {"conf": conf}
    else:
        SESSION = {"conf": conf}

    # Load Scapy
    scapy_builtins = _scapy_builtins()

    SESSION.update(scapy_builtins)
    SESSION["_scpybuiltins"] = scapy_builtins.keys()
    six.moves.builtins.__dict__["scapy_session"] = SESSION

    if mydict is not None:
        six.moves.builtins.__dict__["scapy_session"].update(mydict)
        update_ipython_session(mydict)
    if ret:
        return SESSION
    return None
Exemple #9
0
 def fileno(self):
     if sys.platform.startswith("win"):
       log_loading.error("Cannot get selectable PCAP fd on Windows")
       return 0
     return pcap_get_selectable_fd(self.pcap) 
Exemple #10
0
          sx = str(cls()/x)
          if hasattr(x, "sent_time"):
              x.sent_time = time.time()
          return self.ins.send(sx)
  conf.L2socket=L2pcapSocket
  conf.L3socket=L3pcapSocket
    
if conf.use_pcap:
    try:
        import pcap
    except ImportError as e:
        try:
            import pcapy as pcap
        except ImportError as e2:
            if conf.interactive:
                log_loading.error("Unable to import pcap module: %s/%s" % (e,e2))
                conf.use_pcap = False
            else:
                raise
    if conf.use_pcap:
        
        # From BSD net/bpf.h
        #BIOCIMMEDIATE=0x80044270
        BIOCIMMEDIATE=-2147204496

        if hasattr(pcap,"pcap"): # python-pypcap
            class _PcapWrapper_pypcap:
                def __init__(self, device, snaplen, promisc, to_ms):
                    try:
                        self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms)
                    except TypeError:
Exemple #11
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
Exemple #12
0
 def fileno(self):
     if sys.platform.startswith("win"):
         log_loading.error("Cannot get selectable PCAP fd on Windows")
         return 0
     return pcap_get_selectable_fd(self.pcap)
Exemple #13
0
            if hasattr(x, "sent_time"):
                x.sent_time = time.time()
            return self.ins.send(sx)

    conf.L2socket = L2pcapSocket
    conf.L3socket = L3pcapSocket

if conf.use_pcap:
    try:
        import pcap
    except ImportError as e:
        try:
            import pcapy as pcap
        except ImportError as e2:
            if conf.interactive:
                log_loading.error("Unable to import pcap module: %s/%s", e, e2)
                conf.use_pcap = False
            else:
                raise
    if conf.use_pcap:

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

        if hasattr(pcap, "pcap"):  # python-pypcap

            class _PcapWrapper_pypcap:
                def __init__(self, device, snaplen, promisc, to_ms):
                    try:
                        self.pcap = pcap.pcap(device,
Exemple #14
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
Exemple #15
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
Exemple #16
0
      devs = POINTER(pcap_if_t)()
      ret = []
      if pcap_findalldevs(byref(devs), err) < 0:
        return ret
      try:
        p = devs
        while p:
          ret.append(p.contents.name.decode('ascii'))
          p = p.contents.next
        return ret
      finally:
        pcap_freealldevs(devs)

  except OSError as e:
    if conf.interactive:
      log_loading.error("Unable to import libpcap library: %s" % e)
      conf.use_winpcapy = False
    else:
      raise

  # 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 = "\0\0\0\0\0\0"
Exemple #17
0
if conf.use_pcap:
    try:
        import pcap  # python-pypcap
        _PCAP_MODE = "pypcap"
    except ImportError as e:
        try:
            import libpcap as pcap  # python-libpcap
            _PCAP_MODE = "libpcap"
        except ImportError as e2:
            try:
                import pcapy as pcap  # python-pcapy
                _PCAP_MODE = "pcapy"
            except ImportError as e3:
                if conf.interactive:
                    log_loading.error("Unable to import pcap module: %s/%s", e, e2)  # noqa: E501
                    conf.use_pcap = False
                else:
                    raise
    if conf.use_pcap:

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

        if _PCAP_MODE == "pypcap":  # python-pypcap
            class _PcapWrapper_pypcap:  # noqa: F811
                def __init__(self, device, snaplen, promisc, to_ms, monitor=False):  # noqa: E501
                    try:
                        self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms, rfmon=monitor)  # noqa: E501
                    except TypeError:
Exemple #18
0
     import pcapy as pcap  # python-pcapy
     _PCAP_MODE = "pcapy"
 except ImportError as e:
     try:
         import pcap  # python-pypcap
         _PCAP_MODE = "pypcap"
     except ImportError as e2:
         try:
             # This is our last chance, but we don't really
             # recommand it as very little tested
             import libpcap as pcap  # python-libpcap
             _PCAP_MODE = "libpcap"
         except ImportError:
             if conf.interactive:
                 log_loading.error(
                     "Unable to import any of the pcap "
                     "modules: %s/%s", e, e2
                 )
                 conf.use_pcap = False
             else:
                 raise
 if conf.use_pcap:
     if _PCAP_MODE == "pypcap":  # python-pypcap
         class _PcapWrapper_pypcap:  # noqa: F811
             def __init__(self, device, snaplen, promisc,
                          to_ms, monitor=False):
                 try:
                     self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms, rfmon=monitor)  # noqa: E501
                 except TypeError:
                     try:
                         if monitor:
                             warning("Your pypcap version is too old to support monitor mode, Please use pypcap 1.2.1+ !")  # noqa: E501
Exemple #19
0
##########

# DEPRECATED

if conf.use_dnet:
    warning("dnet usage with scapy is deprecated, and will be removed in a future version.")  # noqa: E501
    try:
        try:
            # First try to import dnet
            import dnet
        except ImportError:
            # Then, try to import dumbnet as dnet
            import dumbnet as dnet
    except ImportError as e:
        if conf.interactive:
            log_loading.error("Unable to import dnet module: %s", e)
            conf.use_dnet = False

            def get_if_raw_hwaddr(iff):
                "dummy"
                return (0, b"\0\0\0\0\0\0")

            def get_if_raw_addr(iff):  # noqa: F811
                "dummy"
                return b"\0\0\0\0"

            def get_if_list():
                "dummy"
                return {}
        else:
            raise
 def fileno(self):
     if WINDOWS:
         log_loading.error("Cannot get selectable PCAP fd on Windows")
         return 0
     return pcap_get_selectable_fd(self.pcap)
Exemple #21
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
Exemple #22
0
        import pcapy as pcap  # python-pcapy
        _PCAP_MODE = "pcapy"
    except ImportError as e:
        try:
            import pcap  # python-pypcap
            _PCAP_MODE = "pypcap"
        except ImportError as e2:
            try:
                # This is our last chance, but we don't really
                # recommend it as very little tested
                import libpcap as pcap  # python-libpcap
                _PCAP_MODE = "libpcap"
            except ImportError:
                if conf.interactive:
                    log_loading.error(
                        "Unable to import any of the pcap "
                        "modules: %s/%s", e, e2)
                    conf.use_pcap = False
                else:
                    raise
    if conf.use_pcap:
        if _PCAP_MODE == "pypcap":  # python-pypcap

            class _PcapWrapper_pypcap:  # noqa: F811
                def __init__(self,
                             device,
                             snaplen,
                             promisc,
                             to_ms,
                             monitor=False):
                    try: