Beispiel #1
0
def attach_filter(s, bpf_filter, iface):
    # XXX We generate the filter on the interface conf.iface
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s %d '%s'" % (
            conf.prog.tcpdump,
            conf.iface if iface is None else iface,
            MTU,
            bpf_filter,
        ))
    except OSError:
        log_interactive.warning("Failed to attach filter.",
                                exc_info=True)
        return
    lines = f.readlines()
    ret = f.close()
    if ret:
        log_interactive.warning(
            "Failed to attach filter: tcpdump returned %d", ret
        )
        return

    bp = get_bpf_pointer(lines)
    s.setsockopt(socket.SOL_SOCKET, SO_ATTACH_FILTER, bp)
Beispiel #2
0
def attach_filter(s, bpf_filter, iface):
    # XXX We generate the filter on the interface conf.iface 
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s 1600 '%s'" % (
            conf.prog.tcpdump,
            conf.iface if iface is None else iface,
            bpf_filter,
        ))
    except OSError as msg:
        log_interactive.warning("Failed to execute tcpdump: (%s)")
        return
    lines = f.readlines()
    if f.close():
        raise Scapy_Exception("Filter parse error")
    nb = int(lines[0])
    bpf = ""
    for l in lines[1:]:
        bpf += struct.pack("HBBI", *(int(e) for e in l.split()))

    # XXX. Argl! We need to give the kernel a pointer on the BPF,
    # python object header seems to be 20 bytes. 36 bytes for x86 64bits arch.
    bpfh = struct.pack("HL", nb, id(bpf) + (36 if IS_64BITS else 20))
    s.setsockopt(SOL_SOCKET, SO_ATTACH_FILTER, bpfh)
Beispiel #3
0
def _in6_getifaddr(ifname):
    """
    Returns a list of IPv6 addresses configured on the interface ifname.
    """

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        log_interactive.warning("Failed to execute ifconfig.")
        return []

    # Iterate over lines and extract IPv6 addresses
    ret = []
    for line in f:
        if "inet6" in line:
            addr = line.rstrip().split(
                None, 2)[1]  # The second element is the IPv6 address
        else:
            continue
        if '%' in line:  # Remove the interface identifier if present
            addr = addr.split("%", 1)[0]

        # Check if it is a valid IPv6 address
        try:
            socket.inet_pton(socket.AF_INET6, addr)
        except:
            continue

        # Get the scope and keep the address
        scope = in6_getscope(addr)
        ret.append((addr, scope, ifname))

    return ret
Beispiel #4
0
def attach_filter(s, bpf_filter, iface):
    # XXX We generate the filter on the interface conf.iface
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s %d '%s'" % (
            conf.prog.tcpdump,
            conf.iface if iface is None else iface,
            MTU,
            bpf_filter,
        ))
    except OSError:
        log_interactive.warning("Failed to attach filter.",
                                exc_info=True)
        return
    lines = f.readlines()
    ret = f.close()
    if ret:
        log_interactive.warning(
            "Failed to attach filter: tcpdump returned %d", ret
        )
        return

    bp = get_bpf_pointer(lines)
    s.setsockopt(socket.SOL_SOCKET, SO_ATTACH_FILTER, bp)
Beispiel #5
0
def attach_filter(s, bpf_filter, iface):
    # XXX We generate the filter on the interface conf.iface
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s 1600 '%s'" % (
            conf.prog.tcpdump,
            conf.iface if iface is None else iface,
            bpf_filter,
        ))
    except OSError as msg:
        log_interactive.warning("Failed to execute tcpdump: (%s)")
        return
    lines = f.readlines()
    if f.close():
        raise Scapy_Exception("Filter parse error")
    nb = int(lines[0])
    bpf = ""
    for l in lines[1:]:
        bpf += struct.pack("HBBI", *(int(e) for e in l.split()))

    # XXX. Argl! We need to give the kernel a pointer on the BPF,
    # python object header seems to be 20 bytes. 36 bytes for x86 64bits arch.
    bpfh = struct.pack("HL", nb, id(bpf) + (36 if IS_64BITS else 20))
    s.setsockopt(SOL_SOCKET, SO_ATTACH_FILTER, bpfh)
Beispiel #6
0
    def get_security_access(self, sock, level=1, seed_pkt=None):
        # type: (_SocketUnion, int, Optional[Packet]) -> bool
        log_interactive.info("Try bootloader security access for level %d" %
                             level)
        if seed_pkt is None:
            seed_pkt = self.get_seed_pkt(sock, level)
            if not seed_pkt:
                return False

        if not any(seed_pkt.securitySeed):
            return False

        key_pkt = self.get_key_pkt(seed_pkt, level)
        if key_pkt is None:
            return False

        try:
            res = sock.sr1(key_pkt, timeout=5, verbose=False)
            if sock.closed:
                log_interactive.critical("[-] Socket closed during scan.")
                raise Scapy_Exception("Socket closed during scan")
        except (OSError, ValueError, Scapy_Exception) as e:
            try:
                last_seed_req = self._results[-1].req
                last_state = self._results[-1].state
                if not self._populate_retry(last_state, last_seed_req):
                    log_interactive.critical(
                        "[-] Exception during retry. This is bad")
            except IndexError:
                log_interactive.warning("[-] Couldn't populate retry.")
            raise e

        return self.evaluate_security_access_response(res, seed_pkt, key_pkt)
Beispiel #7
0
def _in6_getifaddr(ifname):
    """
    Returns a list of IPv6 addresses configured on the interface ifname.
    """

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        log_interactive.warning("Failed to execute ifconfig.")
        return []

    # Iterate over lines and extract IPv6 addresses
    ret = []
    for line in f:
        if "inet6" in line:
            addr = line.rstrip().split(None, 2)[1] # The second element is the IPv6 address
        else:
            continue
        if '%' in line: # Remove the interface identifier if present
            addr = addr.split("%", 1)[0]

        # Check if it is a valid IPv6 address
        try:
            socket.inet_pton(socket.AF_INET6, addr)
        except:
            continue

        # Get the scope and keep the address
        scope = in6_getscope(addr)
        ret.append((addr, scope, ifname))

    return ret
Beispiel #8
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()
Beispiel #9
0
def _in6_getifaddr(ifname):
    """
    Returns a list of IPv6 addresses configured on the interface ifname.
    """

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError,msg:
        log_interactive.warning("Failed to execute ifconfig.")
        return []
Beispiel #10
0
def _in6_getifaddr(ifname):
    """
    Returns a list of IPv6 addresses configured on the interface ifname.
    """

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError, msg:
        log_interactive.warning("Failed to execute ifconfig.")
        return []
Beispiel #11
0
def attach_filter(s, filter):
    # XXX We generate the filter on the interface conf.iface 
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump,conf.iface,filter))
    except OSError,msg:
        log_interactive.warning("Failed to execute tcpdump: (%s)")
        return
Beispiel #12
0
    def _evaluate_response(self,
                           state,  # type: EcuState
                           request,  # type: Packet
                           response,  # type: Optional[Packet]
                           **kwargs  # type: Optional[Dict[str, Any]]
                           ):  # type: (...) -> bool
        if response and response.service == 0x51:
            log_interactive.warning(
                "ECUResetPositiveResponse detected! This might have changed "
                "the state of the ECU under test.")

        # remove args from kwargs since they will be overwritten
        kwargs["exit_if_service_not_supported"] = False  # type: ignore

        return super(UDS_ServiceEnumerator, self)._evaluate_response(
            state, request, response, **kwargs)
Beispiel #13
0
def attach_filter(s, bpf_filter, iface):
    # XXX We generate the filter on the interface conf.iface
    # because tcpdump open the "any" interface and ppp interfaces
    # in cooked mode. As we use them in raw mode, the filter will not
    # work... one solution could be to use "any" interface and translate
    # the filter from cooked mode to raw mode
    # mode
    if not TCPDUMP:
        return
    try:
        f = os.popen("%s -i %s -ddd -s 1600 '%s'" % (
            conf.prog.tcpdump,
            conf.iface if iface is None else iface,
            bpf_filter,
        ))
    except OSError, msg:
        log_interactive.warning("Failed to execute tcpdump: (%s)")
        return
Beispiel #14
0
def in6_getifaddr():
    """
    Returns a list of 3-tuples of the form (addr, scope, iface) where
    'addr' is the address of scope 'scope' associated to the interface
    'iface'.

    This is the list of all addresses of all interfaces available on
    the system.
    """

    # List all network interfaces
    if OPENBSD or SOLARIS:
        if SOLARIS:
            cmd = "%s -a6"
        else:
            cmd = "%s"
        try:
            f = os.popen(cmd % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for line in f:
            if "flags" in line:
                iface = line.split()[0].rstrip(':')
                splitted_line.append(iface)

    else:  # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    f.close()
    return ret
Beispiel #15
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 #16
0
def in6_getifaddr():
    """
    Returns a list of 3-tuples of the form (addr, scope, iface) where
    'addr' is the address of scope 'scope' associated to the interface
    'iface'.

    This is the list of all addresses of all interfaces available on
    the system.
    """

    # List all network interfaces
    if OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError as msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else: # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError as msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    return ret
Beispiel #17
0
def in6_getifaddr():
    """
    Returns a list of 3-tuples of the form (addr, scope, iface) where
    'addr' is the address of scope 'scope' associated to the interface
    'iface'.

    This is the list of all addresses of all interfaces available on
    the system.
    """

    # List all network interfaces
    if scapy.arch.OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError, msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

            # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(":")
                splitted_line.append(iface)
Beispiel #18
0
def in6_getifaddr():
    """
    Returns a list of 3-tuples of the form (addr, scope, iface) where
    'addr' is the address of scope 'scope' associated to the interface
    'iface'.

    This is the list of all addresses of all interfaces available on
    the system.
    """

    # List all network interfaces
    if scapy.arch.OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError, msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)
Beispiel #19
0
        except OSError,msg:
	    log_interactive.warning("Failed to execute ifconfig.")
	    return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else: # FreeBSD, NetBSD or Darwin
        try:
	    f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError,msg:
	    log_interactive.warning("Failed to execute ifconfig.")
	    return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
	ret += _in6_getifaddr(i)
    return ret	    


def read_routes6():
    """Return a list of IPv6 routes than can be used by Scapy."""

    # Call netstat to retrieve IPv6 routes
Beispiel #20
0
 def run(self, *args, **kargs):
     log_interactive.warning("run() method deprecated. The instance is now callable")
     self(*args,**kargs)
 def run(self, *args, **kargs):
     log_interactive.warning(
         "run() method deprecated. The instance is now callable")
     self(*args, **kargs)
Beispiel #22
0
        except OSError, msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else:  # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError, msg:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    return ret


def read_routes6():
    """Return a list of IPv6 routes than can be used by Scapy."""

    # Call netstat to retrieve IPv6 routes