Exemplo n.º 1
0
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None):
    """Send packets at layer 2 using tcpreplay for performance
    pps:  packets per second
    mpbs: MBits per second
    realtime: use packet's timestamp, bending time with realtime value
    loop: number of times to process the packet list
    file_cache: cache packets in RAM instead of reading from disk at each iteration
    iface: output interface """
    if iface is None:
        iface = conf.iface
    argv = [conf.prog.tcpreplay, "--intf1=%s" % iface ]
    if pps is not None:
        argv.append("--pps=%i" % pps)
    elif mbps is not None:
        argv.append("--mbps=%f" % mbps)
    elif realtime is not None:
        argv.append("--multiplier=%f" % realtime)
    else:
        argv.append("--topspeed")

    if loop:
        argv.append("--loop=%i" % loop)
        if file_cache:
            argv.append("--enable-file-cache")

    f = get_temp_file()
    argv.append(f)
    wrpcap(f, x)
    try:
        subprocess.check_call(argv)
    except KeyboardInterrupt:
        log_interactive.info("Interrupted by user")
    except Exception,e:
        log_interactive.error("while trying to exec [%s]: %s" % (argv[0],e))
Exemplo n.º 2
0
def save_session(fname=None, session=None, pickleProto=-1):
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
            log_interactive.info("Use [%s] as session file" % fname)
    if session is None:
        session = __builtin__.__dict__["scapy_session"]

    to_be_saved = session.copy()

    if to_be_saved.has_key("__builtins__"):
        del (to_be_saved["__builtins__"])

    for k in to_be_saved.keys():
        if type(to_be_saved[k]) in [
                types.TypeType, types.ClassType, types.ModuleType
        ]:
            log_interactive.error("[%s] (%s) can't be saved." %
                                  (k, type(to_be_saved[k])))
            del (to_be_saved[k])

    try:
        os.rename(fname, fname + ".bak")
    except OSError:
        pass
    f = gzip.open(fname, "wb")
    cPickle.dump(to_be_saved, f, pickleProto)
    f.close()
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None,  # noqa: E501
              parse_results=False):
    """Send packets at layer 2 using tcpreplay for performance

    :param pps:  packets per second
    :param mpbs: MBits per second
    :param realtime: use packet's timestamp, bending time with real-time value
    :param loop: number of times to process the packet list
    :param file_cache: cache packets in RAM instead of reading from
        disk at each iteration
    :param iface: output interface
    :param replay_args: List of additional tcpreplay args (List[str])
    :param parse_results: Return a dictionary of information
        outputted by tcpreplay (default=False)
    :returns: stdout, stderr, command used
    """
    if iface is None:
        iface = conf.iface
    argv = [conf.prog.tcpreplay, "--intf1=%s" % network_name(iface)]
    if pps is not None:
        argv.append("--pps=%i" % pps)
    elif mbps is not None:
        argv.append("--mbps=%f" % mbps)
    elif realtime is not None:
        argv.append("--multiplier=%f" % realtime)
    else:
        argv.append("--topspeed")

    if loop:
        argv.append("--loop=%i" % loop)
    if file_cache:
        argv.append("--preload-pcap")

    # Check for any additional args we didn't cover.
    if replay_args is not None:
        argv.extend(replay_args)

    f = get_temp_file()
    argv.append(f)
    wrpcap(f, x)
    results = None
    with ContextManagerSubprocess(conf.prog.tcpreplay):
        try:
            cmd = subprocess.Popen(argv, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        except KeyboardInterrupt:
            log_interactive.info("Interrupted by user")
        except Exception:
            os.unlink(f)
            raise
        else:
            stdout, stderr = cmd.communicate()
            if stderr:
                log_runtime.warning(stderr.decode())
            if parse_results:
                results = _parse_tcpreplay_result(stdout, stderr, argv)
            elif conf.verb > 2:
                log_runtime.info(stdout.decode())
    os.unlink(f)
    return results
Exemplo n.º 4
0
Arquivo: main.py Projeto: secdev/scapy
def save_session(fname=None, session=None, pickleProto=-1):
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
            log_interactive.info("Use [%s] as session file" % fname)
    if session is None:
        session = __builtin__.__dict__["scapy_session"]

    to_be_saved = session.copy()
        
    if to_be_saved.has_key("__builtins__"):
        del(to_be_saved["__builtins__"])

    for k in to_be_saved.keys():
        if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]:
             log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k])))
             del(to_be_saved[k])

    try:
        os.rename(fname, fname+".bak")
    except OSError:
        pass
    f=gzip.open(fname,"wb")
    cPickle.dump(to_be_saved, f, pickleProto)
    f.close()
    def svgdump(self, filename=None, **kargs):
        # type: (Optional[str], **Any) -> None
        """
        svgdump(filename=None, layer_shift=0, rebuild=1)

        Creates an SVG file describing a packet. If filename is not provided a
        temporary file is created and gs is called.

        :param filename: the file's filename
        """
        from scapy.config import conf
        from scapy.utils import get_temp_file, ContextManagerSubprocess
        canvas = self.canvas_dump(**kargs)
        if filename is None:
            fname = cast(str,
                         get_temp_file(autoext=kargs.get("suffix", ".svg")))
            canvas.writeSVGfile(fname)
            if WINDOWS and conf.prog.svgreader is None:
                os.startfile(fname)
            else:
                with ContextManagerSubprocess(conf.prog.svgreader):
                    subprocess.Popen([conf.prog.svgreader, fname])
        else:
            canvas.writeSVGfile(filename)
        print()
Exemplo n.º 6
0
def http_request(host,
                 path="/",
                 port=80,
                 timeout=3,
                 display=False,
                 verbose=0,
                 iptables=False,
                 **headers):
    """Util to perform an HTTP request, using the TCP_client.

    :param host: the host to connect to
    :param path: the path of the request (default /)
    :param port: the port (default 80)
    :param timeout: timeout before None is returned
    :param display: display the resullt in the default browser (default False)
    :param iptables: temporarily prevents the kernel from
      answering with a TCP RESET message.
    :param headers: any additional headers passed to the request

    :returns: the HTTPResponse packet
    """
    http_headers = {
        "Accept_Encoding": b'gzip, deflate',
        "Cache_Control": b'no-cache',
        "Pragma": b'no-cache',
        "Connection": b'keep-alive',
        "Host": host,
        "Path": path,
    }
    http_headers.update(headers)
    req = HTTP() / HTTPRequest(**http_headers)
    tcp_client = TCP_client.tcplink(HTTP, host, port, debug=verbose)
    ans = None
    if iptables:
        ip = tcp_client.atmt.dst
        iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP"
        assert (os.system(iptables_rule % ('A', ip)) == 0)
    try:
        ans = tcp_client.sr1(req, timeout=timeout, verbose=verbose)
    finally:
        tcp_client.close()
        if iptables:
            assert (os.system(iptables_rule % ('D', ip)) == 0)
    if ans:
        if display:
            if Raw not in ans:
                warning("No HTTP content returned. Cannot display")
                return ans
            # Write file
            file = get_temp_file(autoext=".html")
            with open(file, "wb") as fd:
                fd.write(ans.load)
            # Open browser
            if WINDOWS:
                os.startfile(file)
            else:
                with ContextManagerSubprocess(conf.prog.universal_open):
                    subprocess.Popen([conf.prog.universal_open, file])
        return ans
Exemplo n.º 7
0
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None,  # noqa: E501
              parse_results=False):
    """Send packets at layer 2 using tcpreplay for performance
    pps:  packets per second
    mpbs: MBits per second
    realtime: use packet's timestamp, bending time with real-time value
    loop: number of times to process the packet list
    file_cache: cache packets in RAM instead of reading from disk at each iteration  # noqa: E501
    iface: output interface
    replay_args: List of additional tcpreplay args (List[str])
    parse_results: Return a dictionary of information outputted by tcpreplay (default=False)  # noqa: E501
    :returns stdout, stderr, command used"""
    if iface is None:
        iface = conf.iface
    argv = [conf.prog.tcpreplay, "--intf1=%s" % iface]
    if pps is not None:
        argv.append("--pps=%i" % pps)
    elif mbps is not None:
        argv.append("--mbps=%f" % mbps)
    elif realtime is not None:
        argv.append("--multiplier=%f" % realtime)
    else:
        argv.append("--topspeed")

    if loop:
        argv.append("--loop=%i" % loop)
    if file_cache:
        argv.append("--preload-pcap")

    # Check for any additional args we didn't cover.
    if replay_args is not None:
        argv.extend(replay_args)

    f = get_temp_file()
    argv.append(f)
    wrpcap(f, x)
    results = None
    try:
        log_runtime.info(argv)
        with subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as cmd:  # noqa: E501
            stdout, stderr = cmd.communicate()
            log_runtime.info(stdout)
            log_runtime.warning(stderr)
            if parse_results:
                results = _parse_tcpreplay_result(stdout, stderr, argv)

    except KeyboardInterrupt:
        log_interactive.info("Interrupted by user")
    except Exception:
        if conf.interactive:
            log_interactive.error("Cannot execute [%s]", argv[0], exc_info=True)  # noqa: E501
        else:
            raise
    finally:
        os.unlink(f)
        return results
Exemplo n.º 8
0
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None,  # noqa: E501
              parse_results=False):
    """Send packets at layer 2 using tcpreplay for performance
    pps:  packets per second
    mpbs: MBits per second
    realtime: use packet's timestamp, bending time with real-time value
    loop: number of times to process the packet list
    file_cache: cache packets in RAM instead of reading from disk at each iteration  # noqa: E501
    iface: output interface
    replay_args: List of additional tcpreplay args (List[str])
    parse_results: Return a dictionary of information outputted by tcpreplay (default=False)  # noqa: E501
    :returns stdout, stderr, command used"""
    if iface is None:
        iface = conf.iface
    argv = [conf.prog.tcpreplay, "--intf1=%s" % iface]
    if pps is not None:
        argv.append("--pps=%i" % pps)
    elif mbps is not None:
        argv.append("--mbps=%f" % mbps)
    elif realtime is not None:
        argv.append("--multiplier=%f" % realtime)
    else:
        argv.append("--topspeed")

    if loop:
        argv.append("--loop=%i" % loop)
    if file_cache:
        argv.append("--preload-pcap")

    # Check for any additional args we didn't cover.
    if replay_args is not None:
        argv.extend(replay_args)

    f = get_temp_file()
    argv.append(f)
    wrpcap(f, x)
    results = None
    with ContextManagerSubprocess("sendpfast()", conf.prog.tcpreplay):
        try:
            cmd = subprocess.Popen(argv, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        except KeyboardInterrupt:
            log_interactive.info("Interrupted by user")
        except Exception:
            os.unlink(f)
            raise
        else:
            stdout, stderr = cmd.communicate()
            if stderr:
                log_runtime.warning(stderr.decode())
            if parse_results:
                results = _parse_tcpreplay_result(stdout, stderr, argv)
            elif conf.verb > 2:
                log_runtime.info(stdout.decode())
    os.unlink(f)
    return results
Exemplo n.º 9
0
 def pdfdump(self, filename=None, **kargs):
     """pdfdump(filename=None, layer_shift=0, rebuild=1)
     Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called."""
     canvas = self.canvas_dump(**kargs)
     if filename is None:
         fname = get_temp_file(autoext=".pdf")
         canvas.writePDFfile(fname)
         subprocess.Popen([conf.prog.pdfreader, fname+".pdf"])
     else:
         canvas.writePDFfile(filename)
Exemplo n.º 10
0
 def pdfdump(self, filename=None, **kargs):
     """pdfdump(filename=None, layer_shift=0, rebuild=1)
     Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called."""
     canvas = self.canvas_dump(**kargs)
     if filename is None:
         fname = get_temp_file(autoext=".pdf")
         canvas.writePDFfile(fname)
         subprocess.Popen([conf.prog.pdfreader, fname+".pdf"])
     else:
         canvas.writePDFfile(filename)
Exemplo n.º 11
0
def save_session(fname="", session=None, pickleProto=-1):
    # type: (str, Optional[Dict[str, Any]], int) -> None
    """Save current Scapy session to the file specified in the fname arg.

    params:
     - fname: file to save the scapy session in
     - session: scapy session to use. If None, the console one will be used
     - pickleProto: pickle proto version (default: -1 = latest)"""
    from scapy import utils
    from scapy.config import conf, ConfClass
    if not fname:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
    log_interactive.info("Saving session into [%s]", fname)

    if not session:
        try:
            from IPython import get_ipython
            session = get_ipython().user_ns
        except Exception:
            session = six.moves.builtins.__dict__["scapy_session"]

    if not session:
        log_interactive.error("No session found ?!")
        return

    ignore = session.get("_scpybuiltins", [])
    hard_ignore = ["scapy_session", "In", "Out"]
    to_be_saved = session.copy()

    for k in list(to_be_saved):
        i = to_be_saved[k]
        if k[0] == "_":
            del(to_be_saved[k])
        elif hasattr(i, "__module__") and i.__module__.startswith("IPython"):
            del(to_be_saved[k])
        elif isinstance(i, ConfClass):
            del(to_be_saved[k])
        elif k in ignore or k in hard_ignore:
            del(to_be_saved[k])
        elif isinstance(i, (type, types.ModuleType)):
            if k[0] != "_":
                log_interactive.warning("[%s] (%s) can't be saved.", k,
                                        type(to_be_saved[k]))
            del(to_be_saved[k])

    try:
        os.rename(fname, fname + ".bak")
    except OSError:
        pass

    f = gzip.open(fname, "wb")
    six.moves.cPickle.dump(to_be_saved, f, pickleProto)
    f.close()
Exemplo n.º 12
0
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Could not write history to [%s]. Discarded" % tmp)
Exemplo n.º 13
0
Arquivo: main.py Projeto: secdev/scapy
def scapy_write_history_file(readline):
    if conf.histfile:
        try:
            readline.write_history_file(conf.histfile)
        except IOError,e:
            try:
                warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e))
                tmp = utils.get_temp_file(keep=True)
                readline.write_history_file(tmp)
                warning("Wrote history to [%s]" % tmp)
            except:
                warning("Could not write history to [%s]. Discarded" % tmp)
Exemplo n.º 14
0
 def pdfdump(self, filename=None, **kargs):
     """Creates a PDF file with a psdump of every packet
     filename: name of the file to write to. If empty, a temporary file is used and
               conf.prog.pdfreader is called"""
     d = self._dump_document(**kargs)
     if filename is None:
         filename = get_temp_file(autoext=".pdf")
         d.writePDFfile(filename)
         subprocess.Popen([conf.prog.pdfreader, filename + ".pdf"])
     else:
         d.writePDFfile(filename)
     print
Exemplo n.º 15
0
 def pdfdump(self, filename = None, **kargs):
     """Creates a PDF file with a psdump of every packet
     filename: name of the file to write to. If empty, a temporary file is used and
               conf.prog.pdfreader is called"""
     d = self._dump_document(**kargs)
     if filename is None:
         filename = get_temp_file(autoext=".pdf")
         d.writePDFfile(filename)
         subprocess.Popen([conf.prog.pdfreader, filename+".pdf"])
     else:
         d.writePDFfile(filename)
     print
Exemplo n.º 16
0
 def _start_windows(self):
     if not self.opened:
         self.opened = True
         self.__f = get_temp_file()
         self.name = "Scapy" if self.name is None else self.name
         # Start a powershell in a new window and print the PID
         cmd = "$app = Start-Process PowerShell -ArgumentList '-command &{$host.ui.RawUI.WindowTitle=\\\"%s\\\";Get-Content \\\"%s\\\" -wait}' -passthru; echo $app.Id" % (self.name, self.__f.replace("\\", "\\\\"))
         _p = subprocess.Popen([conf.prog.powershell, cmd], stdout=subprocess.PIPE)
         _output, _stderr = _p.communicate()
         # This is the process PID
         self.__p = int(_output)
         print("PID:" + str(self.__p))
Exemplo n.º 17
0
 def _start_windows(self):
     if not self.opened:
         self.opened = True
         self.__f = get_temp_file()
         open(self.__f, "a").close()
         self.name = "Scapy" if self.name is None else self.name
         # Start a powershell in a new window and print the PID
         cmd = "$app = Start-Process PowerShell -ArgumentList '-command &{$host.ui.RawUI.WindowTitle=\\\"%s\\\";Get-Content \\\"%s\\\" -wait}' -passthru; echo $app.Id" % (self.name, self.__f.replace("\\", "\\\\"))  # noqa: E501
         proc = subprocess.Popen([conf.prog.powershell, cmd], stdout=subprocess.PIPE)  # noqa: E501
         output, _ = proc.communicate()
         # This is the process PID
         self.pid = int(output)
         print("PID: %d" % self.pid)
Exemplo n.º 18
0
 def psdump(self, filename = None, **kargs):
     """Creates a multi-page postcript file with a psdump of every packet
     filename: name of the file to write to. If empty, a temporary file is used and
               conf.prog.psreader is called"""
     d = self._dump_document(**kargs)
     if filename is None:
         filename = get_temp_file(autoext=".ps")
         d.writePSfile(filename)
         with ContextManagerSubprocess("psdump()"):
             subprocess.Popen([conf.prog.psreader, filename+".ps"])
     else:
         d.writePSfile(filename)
     print()
Exemplo n.º 19
0
def voip_play(s1, list=None, **kargs):
    FIFO = get_temp_file()
    FIFO1 = FIFO % 1
    FIFO2 = FIFO % 2

    os.mkfifo(FIFO1)
    os.mkfifo(FIFO2)
    try:
        os.system("soxmix -t .ul %s -t .ul %s -t ossdsp /dev/dsp &" %
                  (FIFO1, FIFO2))

        c1 = open(FIFO1, "w", 4096)
        c2 = open(FIFO2, "w", 4096)
        fcntl.fcntl(c1.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
        fcntl.fcntl(c2.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

        #    dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp")
        def play(pkt, last=None):
            if last is None:
                last = []
            if not pkt:
                return
            if not pkt.haslayer(UDP):
                return
            ip = pkt.getlayer(IP)
            if s1 in [ip.src, ip.dst]:
                if not last:
                    last.append(pkt)
                    return
                load = last.pop()
                #            x1 = load.load[12:]
                c1.write(load.load[12:])
                if load.getlayer(IP).src == ip.src:
                    #                x2 = ""
                    c2.write("\x00" * len(load.load[12:]))
                    last.append(pkt)
                else:
                    #                x2 = pkt.load[:12]
                    c2.write(pkt.load[12:])
    #            dsp.write(merge(x1,x2))

        if list is None:
            sniff(store=0, prn=play, **kargs)
        else:
            for p in list:
                play(p)
    finally:
        os.unlink(FIFO1)
        os.unlink(FIFO2)
Exemplo n.º 20
0
def http_request(host,
                 path="/",
                 port=80,
                 timeout=3,
                 display=False,
                 verbose=None,
                 **headers):
    """Util to perform an HTTP request, using the TCP_client.

    :param host: the host to connect to
    :param path: the path of the request (default /)
    :param port: the port (default 80)
    :param timeout: timeout before None is returned
    :param display: display the resullt in the default browser (default False)
    :param headers: any additional headers passed to the request

    :returns: the HTTPResponse packet
    """
    http_headers = {
        "Accept_Encoding": b'gzip, deflate',
        "Cache_Control": b'no-cache',
        "Pragma": b'no-cache',
        "Connection": b'keep-alive',
        "Host": host,
        "Path": path,
    }
    http_headers.update(headers)
    req = HTTP() / HTTPRequest(**http_headers)
    tcp_client = TCP_client.tcplink(HTTP, host, 80)
    ans = None
    try:
        ans = tcp_client.sr1(req, timeout=timeout, verbose=verbose)
    finally:
        tcp_client.close()
    if ans:
        if display:
            # Write file
            file = get_temp_file(autoext=".html")
            with open(file, "wb") as fd:
                fd.write(ans.load)
            # Open browser
            if WINDOWS:
                os.startfile(file)
            else:
                with ContextManagerSubprocess("http_request()",
                                              conf.prog.universal_open):
                    subprocess.Popen([conf.prog.universal_open, file])
        else:
            return ans
Exemplo n.º 21
0
def save_session(fname=None, session=None, pickleProto=-1):
    """Save current Scapy session to the file specified in the fname arg.

    params:
     - fname: file to save the scapy session in
     - session: scapy session to use. If None, the console one will be used
     - pickleProto: pickle proto version (default: -1 = latest)"""
    from scapy import utils
    from scapy.config import conf, ConfClass
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
    log_interactive.info("Use [%s] as session file" % fname)

    if session is None:
        try:
            session = get_ipython().user_ns
        except Exception:
            session = six.moves.builtins.__dict__["scapy_session"]

    to_be_saved = session.copy()
    if "__builtins__" in to_be_saved:
        del (to_be_saved["__builtins__"])

    for k in list(to_be_saved):
        i = to_be_saved[k]
        if hasattr(i, "__module__") and (
                k[0] == "_"
                or i.__module__.startswith("IPython")):  # noqa: E501
            del (to_be_saved[k])
        if isinstance(i, ConfClass):
            del (to_be_saved[k])
        elif isinstance(i, (type, type, types.ModuleType)):
            if k[0] != "_":
                log_interactive.error("[%s] (%s) can't be saved.", k,
                                      type(to_be_saved[k]))  # noqa: E501
            del (to_be_saved[k])

    try:
        os.rename(fname, fname + ".bak")
    except OSError:
        pass

    f = gzip.open(fname, "wb")
    six.moves.cPickle.dump(to_be_saved, f, pickleProto)
    f.close()
    del f
Exemplo n.º 22
0
def voip_play(s1,list=None,**kargs):
    FIFO=get_temp_file()
    FIFO1=FIFO % 1
    FIFO2=FIFO % 2
    
    os.mkfifo(FIFO1)
    os.mkfifo(FIFO2)
    try:
        os.system("soxmix -t .ul %s -t .ul %s -t ossdsp /dev/dsp &" % (FIFO1,FIFO2))
        
        c1=open(FIFO1,"w", 4096)
        c2=open(FIFO2,"w", 4096)
        fcntl.fcntl(c1.fileno(),fcntl.F_SETFL, os.O_NONBLOCK)
        fcntl.fcntl(c2.fileno(),fcntl.F_SETFL, os.O_NONBLOCK)
    
    #    dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp")
        def play(pkt, last=None):
            if last is None:
                last = []
            if not pkt:
                return 
            if not pkt.haslayer(UDP):
                return 
            ip=pkt.getlayer(IP)
            if s1 in [ip.src, ip.dst]:
                if not last:
                    last.append(pkt)
                    return
                load=last.pop()
    #            x1 = load.load[12:]
                c1.write(load.load[12:])
                if load.getlayer(IP).src == ip.src:
    #                x2 = ""
                    c2.write("\x00"*len(load.load[12:]))
                    last.append(pkt)
                else:
    #                x2 = pkt.load[:12]
                    c2.write(pkt.load[12:])
    #            dsp.write(merge(x1,x2))
    
        if list is None:
            sniff(store=0, prn=play, **kargs)
        else:
            for p in list:
                play(p)
    finally:
        os.unlink(FIFO1)
        os.unlink(FIFO2)
Exemplo n.º 23
0
 def pdfdump(self, filename=None, **kargs):
     """Creates a PDF file with a psdump of every packet
     filename: name of the file to write to. If empty, a temporary file is used and  # noqa: E501
               conf.prog.pdfreader is called"""
     d = self._dump_document(**kargs)
     if filename is None:
         filename = get_temp_file(autoext=".pdf")
         d.writePDFfile(filename)
         if WINDOWS and conf.prog.pdfreader is None:
             os.startfile(filename)
         else:
             with ContextManagerSubprocess("pdfdump()", conf.prog.pdfreader):  # noqa: E501
                 subprocess.Popen([conf.prog.pdfreader, filename])
     else:
         d.writePDFfile(filename)
     print()
Exemplo n.º 24
0
 def pdfdump(self, filename = None, **kargs):
     """Creates a PDF file with a psdump of every packet
     filename: name of the file to write to. If empty, a temporary file is used and
               conf.prog.pdfreader is called"""
     d = self._dump_document(**kargs)
     if filename is None:
         filename = get_temp_file(autoext=".pdf")
         d.writePDFfile(filename)
         if WINDOWS and conf.prog.pdfreader is None:
             os.startfile(filename)
         else:
             with ContextManagerSubprocess("pdfdump()", conf.prog.pdfreader):
                 subprocess.Popen([conf.prog.pdfreader, filename])
     else:
         d.writePDFfile(filename)
     print()
Exemplo n.º 25
0
Arquivo: main.py Projeto: 6WIND/scapy
def save_session(fname=None, session=None, pickleProto=-1):
    """Save current Scapy session to the file specified in the fname arg.

    params:
     - fname: file to save the scapy session in
     - session: scapy session to use. If None, the console one will be used
     - pickleProto: pickle proto version (default: -1 = latest)"""
    from scapy import utils
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
    log_interactive.info("Use [%s] as session file" % fname)

    if session is None:
        try:
            session = get_ipython().user_ns
        except:
            session = six.moves.builtins.__dict__["scapy_session"]

    to_be_saved = session.copy()
    if "__builtins__" in to_be_saved:
        del(to_be_saved["__builtins__"])

    for k in list(to_be_saved):
        i = to_be_saved[k]
        if hasattr(i, "__module__") and (k[0] == "_" or i.__module__.startswith("IPython")):
            del(to_be_saved[k])
        if isinstance(i, ConfClass):
            del(to_be_saved[k])
        elif isinstance(i, (type, type, types.ModuleType)):
            if k[0] != "_":
                log_interactive.error("[%s] (%s) can't be saved.", k, type(to_be_saved[k]))
            del(to_be_saved[k])

    try:
         os.rename(fname, fname+".bak")
    except OSError:
         pass
    
    f=gzip.open(fname,"wb")
    six.moves.cPickle.dump(to_be_saved, f, pickleProto)
    f.close()
    del f
Exemplo n.º 26
0
    def pdfdump(self, filename=None, **kargs):
        """
        pdfdump(filename=None, layer_shift=0, rebuild=1)

        Creates a PDF file describing a packet. If filename is not provided a
        temporary file is created and xpdf is called.

        :param filename: the file's filename
        """
        from scapy.config import conf
        from scapy.utils import get_temp_file, ContextManagerSubprocess
        canvas = self.canvas_dump(**kargs)
        if filename is None:
            fname = get_temp_file(autoext=kargs.get("suffix", ".pdf"))
            canvas.writePDFfile(fname)
            if WINDOWS and conf.prog.pdfreader is None:
                os.startfile(fname)
            else:
                with ContextManagerSubprocess(conf.prog.pdfreader):
                    subprocess.Popen([conf.prog.pdfreader, fname])
        else:
            canvas.writePDFfile(filename)
        print()
Exemplo n.º 27
0
    def psdump(self, filename=None, **kargs):
        """
        psdump(filename=None, layer_shift=0, rebuild=1)

        Creates an EPS file describing a packet. If filename is not provided a
        temporary file is created and gs is called.

        :param filename: the file's filename
        """
        from scapy.config import conf
        from scapy.utils import get_temp_file, ContextManagerSubprocess
        canvas = self.canvas_dump(**kargs)
        if filename is None:
            fname = get_temp_file(autoext=kargs.get("suffix", ".eps"))
            canvas.writeEPSfile(fname)
            if WINDOWS and conf.prog.psreader is None:
                os.startfile(fname)
            else:
                with ContextManagerSubprocess("psdump()", conf.prog.psreader):
                    subprocess.Popen([conf.prog.psreader, fname])
        else:
            canvas.writeEPSfile(filename)
        print()
Exemplo n.º 28
0
def http_request(host,
                 path="/",
                 port=80,
                 timeout=3,
                 display=False,
                 verbose=0,
                 raw=False,
                 iptables=False,
                 iface=None,
                 **headers):
    """Util to perform an HTTP request, using the TCP_client.

    :param host: the host to connect to
    :param path: the path of the request (default /)
    :param port: the port (default 80)
    :param timeout: timeout before None is returned
    :param display: display the resullt in the default browser (default False)
    :param raw: opens a raw socket instead of going through the OS's TCP
                socket. Scapy will then use its own TCP client.
                Careful, the OS might cancel the TCP connection with RST.
    :param iptables: when raw is enabled, this calls iptables to temporarily
                     prevent the OS from sending TCP RST to the host IP.
                     On Linux, you'll almost certainly need this.
    :param iface: interface to use. Changing this turns on "raw"
    :param headers: any additional headers passed to the request

    :returns: the HTTPResponse packet
    """
    from scapy.sessions import TCPSession
    http_headers = {
        "Accept_Encoding": b'gzip, deflate',
        "Cache_Control": b'no-cache',
        "Pragma": b'no-cache',
        "Connection": b'keep-alive',
        "Host": host,
        "Path": path,
    }
    http_headers.update(headers)
    req = HTTP() / HTTPRequest(**http_headers)
    ans = None

    # Open a socket
    if iface is not None:
        raw = True
    if raw:
        # Use TCP_client on a raw socket
        iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP"
        if iptables:
            host = str(Net(host))
            assert (os.system(iptables_rule % ('A', host)) == 0)
        sock = TCP_client.tcplink(HTTP, host, port, debug=verbose, iface=iface)
    else:
        # Use a native TCP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        sock = StreamSocket(sock, HTTP)
    # Send the request and wait for the answer
    try:
        ans = sock.sr1(req,
                       session=TCPSession(app=True),
                       timeout=timeout,
                       verbose=verbose)
    finally:
        sock.close()
        if raw and iptables:
            host = str(Net(host))
            assert (os.system(iptables_rule % ('D', host)) == 0)
    if ans:
        if display:
            if Raw not in ans:
                warning("No HTTP content returned. Cannot display")
                return ans
            # Write file
            file = get_temp_file(autoext=".html")
            with open(file, "wb") as fd:
                fd.write(ans.load)
            # Open browser
            if WINDOWS:
                os.startfile(file)
            else:
                with ContextManagerSubprocess(conf.prog.universal_open):
                    subprocess.Popen([conf.prog.universal_open, file])
        return ans
Exemplo n.º 29
0
 def _write_to_pcap(packets_list):
     filename = get_temp_file(autoext=".pcap")
     wrpcap(filename, offline)
     return filename, filename