Example #1
0
File: data.py Project: netkey/scapy
def load_services(filename):
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)
    udct = DADict(_name="%s-udp" % filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    if lt[1].endswith(b"/tcp"):
                        tdct[lt[0]] = int(lt[1].split(b'/')[0])
                    elif lt[1].endswith(b"/udp"):
                        udct[lt[0]] = int(lt[1].split(b'/')[0])
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Example #2
0
def load_session(fname=None):
    # type: (Optional[Union[str, None]]) -> None
    """Load current Scapy session from the file specified in the fname arg.
    This will erase any existing session.

    params:
     - fname: file to load the scapy session from"""
    from scapy.config import conf
    if fname is None:
        fname = conf.session
    try:
        s = six.moves.cPickle.load(gzip.open(fname, "rb"))
    except IOError:
        try:
            s = six.moves.cPickle.load(open(fname, "rb"))
        except IOError:
            # Raise "No such file exception"
            raise

    scapy_session = six.moves.builtins.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)
    update_ipython_session(scapy_session)

    log_loading.info("Loaded session [%s]" % fname)
Example #3
0
File: data.py Project: netkey/scapy
def load_protocols(filename, _integer_base=10):
    """"Parse /etc/protocols and return values as a dictionary."""
    spaces = re.compile(b"[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dct[lt[0]] = int(lt[1], _integer_base)
                except Exception as e:
                    log_loading.info(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open %s file", filename)
    return dct
Example #4
0
def load_services(filename):
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)
    udct = DADict(_name="%s-udp" % filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    if lt[1].endswith(b"/tcp"):
                        tdct[lt[0]] = int(lt[1].split(b'/')[0])
                    elif lt[1].endswith(b"/udp"):
                        udct[lt[0]] = int(lt[1].split(b'/')[0])
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Example #5
0
 def resync(self):
     # TODO : At the moment, resync will drop existing Teredo routes
     #        if any. Change that ...
     self.invalidate_cache()
     self.routes = read_routes6()
     if self.routes == []:
         log_loading.info("No IPv6 support in kernel")
Example #6
0
def load_protocols(filename, _integer_base=10):
    """"Parse /etc/protocols and return values as a dictionary."""
    spaces = re.compile(b"[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dct[lt[0]] = int(lt[1], _integer_base)
                except Exception as e:
                    log_loading.info(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open %s file", filename)
    return dct
Example #7
0
 def resync(self):
     # TODO : At the moment, resync will drop existing Teredo routes
     #        if any. Change that ...
     self.invalidate_cache()
     self.routes = read_routes6()
     if self.routes == []:
         log_loading.info("No IPv6 support in kernel")
Example #8
0
 def post_build(self, pkt, pay):
     if not conf.contribs["http"]["auto_compression"]:
         return pkt + pay
     encodings = self._get_encodings()
     # Compress
     if "deflate" in encodings:
         import zlib
         pay = zlib.compress(pay)
     elif "gzip" in encodings:
         pay = gzip_compress(pay)
     elif "compress" in encodings:
         import lzw
         pay = lzw.compress(pay)
     elif "br" in encodings:
         if _is_brotli_available:
             pay = brotli.compress(pay)
         else:
             log_loading.info(
                 "Can't import brotli. brotli compression will "
                 "be ignored !")
     elif "zstd" in encodings:
         if _is_zstd_available:
             pay = zstandard.ZstdCompressor().compress(pay)
         else:
             log_loading.info(
                 "Can't import zstandard. zstd compression will "
                 "be ignored !")
     return pkt + pay
Example #9
0
def load_services(filename):
    spaces = re.compile("[ \t]+|\n")
    tdct=DADict(_name="%s-tcp"%filename)
    udct=DADict(_name="%s-udp"%filename)
    try:
        f=open(filename)
        for l in f:
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                if lt[1].endswith("/tcp"):
                    tdct[lt[0]] = int(lt[1].split('/')[0])
                elif lt[1].endswith("/udp"):
                    udct[lt[0]] = int(lt[1].split('/')[0])
            except Exception as e:
                log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e))
        f.close()
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct,udct
Example #10
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 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}

    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
Example #11
0
def init_session(
    session_name,  # type: Optional[Union[str, None]]
    mydict=None  # type: Optional[Union[Dict[str, Any], None]]
):
    # type: (...) -> 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")

    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)
Example #12
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
Example #13
0
    def load_from_powershell(self):
        if not conf.prog.os_access:
            return
        ifaces_ips = None
        for i in get_windows_if_list():
            try:
                interface = NetworkInterface(i)
                self.data[interface.guid] = interface
                # If no IP address was detected using winpcap and if
                # the interface is not the loopback one, look for
                # internal windows interfaces
                if not interface.ip:
                    if not ifaces_ips:  # ifaces_ips is used as a cache
                        ifaces_ips = get_ips()
                    # If it exists, retrieve the interface's IP from the cache
                    interface.ip = ifaces_ips.get(interface.name, "")
            except (KeyError, PcapNameNotFoundError):
                pass

        if not self.data and conf.use_winpcapy:
            _detect = pcap_service_status()

            def _ask_user():
                if not conf.interactive:
                    return False
                while True:
                    _confir = input("Do you want to start it ? (yes/no) [y]: ").lower().strip()  # noqa: E501
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
                return False
            _error_msg = "No match between your pcap and windows network interfaces found. "  # noqa: E501
            if _detect[0] and not _detect[2] and not (hasattr(self, "restarted_adapter") and self.restarted_adapter):  # noqa: E501
                warning("Scapy has detected that your pcap service is not running !")  # noqa: E501
                if not conf.interactive or _ask_user():
                    succeed = pcap_service_start(askadmin=conf.interactive)
                    self.restarted_adapter = True
                    if succeed:
                        log_loading.info("Pcap service started !")
                        self.load_from_powershell()
                        return
                _error_msg = "Could not start the pcap service ! "
            warning(_error_msg +
                    "You probably won't be able to send packets. "
                    "Deactivating unneeded interfaces and restarting Scapy might help. "  # noqa: E501
                    "Check your winpcap and powershell installation, and access rights.")  # noqa: E501
        else:
            # Loading state: remove invalid interfaces
            self.remove_invalid_ifaces()
            # Replace LOOPBACK_INTERFACE
            try:
                scapy.consts.LOOPBACK_INTERFACE = self.dev_from_name(
                    scapy.consts.LOOPBACK_NAME,
                )
            except:
                pass
Example #14
0
    def load_from_powershell(self):
        if not conf.prog.os_access:
            return
        ifaces_ips = None
        for i in get_windows_if_list():
            try:
                interface = NetworkInterface(i)
                self.data[interface.guid] = interface
                # If no IP address was detected using winpcap and if
                # the interface is not the loopback one, look for
                # internal windows interfaces
                if not interface.ip:
                    if not ifaces_ips:  # ifaces_ips is used as a cache
                        ifaces_ips = get_ips()
                    # If it exists, retrieve the interface's IP from the cache
                    interface.ip = ifaces_ips.get(interface.name, "")
            except (KeyError, PcapNameNotFoundError):
                pass

        if not self.data and conf.use_winpcapy:
            _detect = pcap_service_status()

            def _ask_user():
                if not conf.interactive:
                    return False
                while True:
                    _confir = input("Do you want to start it ? (yes/no) [y]: ").lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
                return False
            _error_msg = "No match between your pcap and windows network interfaces found. "
            if _detect[0] and not _detect[2] and not (hasattr(self, "restarted_adapter") and self.restarted_adapter):
                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)
                    self.restarted_adapter = True
                    if succeed:
                        log_loading.info("Pcap service started !")
                        self.load_from_powershell()
                        return
                _error_msg = "Could not start the pcap service ! "
            warning(_error_msg +
                    "You probably won't be able to send packets. "
                    "Deactivating unneeded interfaces and restarting Scapy might help. "
                    "Check your winpcap and powershell installation, and access rights.")
        else:
            # Loading state: remove invalid interfaces
            self.remove_invalid_ifaces()
            # Replace LOOPBACK_INTERFACE
            try:
                scapy.consts.LOOPBACK_INTERFACE = self.dev_from_name(
                    scapy.consts.LOOPBACK_NAME,
                )
            except:
                pass
Example #15
0
 def post_dissect(self, s):
     if not conf.contribs["http"]["auto_compression"]:
         return s
     encodings = self._get_encodings()
     # Un-chunkify
     if "chunked" in encodings:
         data = b""
         while s:
             length, _, body = s.partition(b"\r\n")
             try:
                 length = int(length, 16)
             except ValueError:
                 # Not a valid chunk. Ignore
                 break
             else:
                 load = body[:length]
                 if body[length:length + 2] != b"\r\n":
                     # Invalid chunk. Ignore
                     break
                 s = body[length + 2:]
                 data += load
         if not s:
             s = data
     # Decompress
     try:
         if "deflate" in encodings:
             import zlib
             s = zlib.decompress(s)
         elif "gzip" in encodings:
             s = gzip_decompress(s)
         elif "compress" in encodings:
             import lzw
             s = lzw.decompress(s)
         elif "br" in encodings:
             if _is_brotli_available:
                 s = brotli.decompress(s)
             else:
                 log_loading.info(
                     "Can't import brotli. brotli decompression "
                     "will be ignored !")
         elif "zstd" in encodings:
             if _is_zstd_available:
                 # Using its streaming API since its simple API could handle
                 # only cases where there is content size data embedded in
                 # the frame
                 bio = io.BytesIO(s)
                 reader = zstandard.ZstdDecompressor().stream_reader(bio)
                 s = reader.read()
             else:
                 log_loading.info(
                     "Can't import zstandard. zstd decompression "
                     "will be ignored !")
     except Exception:
         # Cannot decompress - probably incomplete data
         pass
     return s
Example #16
0
 def resync(self):
     # type: () -> None
     # TODO : At the moment, resync will drop existing Teredo routes
     #        if any. Change that ...
     self.invalidate_cache()
     self.routes = read_routes6()
     self.ipv6_ifaces = set()
     for route in self.routes:
         self.ipv6_ifaces.add(route[3])
     if self.routes == []:
         log_loading.info("No IPv6 support in kernel")
Example #17
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)
    }
    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"))
                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)
Example #18
0
 def load_from_powershell(self):
     if not conf.prog.os_access:
         return
     for i in get_windows_if_list():
         try:
             interface = NetworkInterface(i)
             self.data[interface.guid] = interface
         except (KeyError, PcapNameNotFoundError):
             pass
     
     if len(self.data) == 0 and conf.use_winpcapy:
         _detect = pcap_service_status()
         def _ask_user():
             if not conf.interactive:
                 return False
             while True:
                 _confir = raw_input("Do you want to start it ? (yes/no) [y]: ").lower().strip()
                 if _confir in ["yes", "y", ""]:
                     return True
                 elif _confir in ["no", "n"]:
                     return False
             return False
         _error_msg = "No match between your pcap and windows network interfaces found. "
         if _detect[0] and not _detect[2] and ((hasattr(self, "restarted_adapter") and not self.restarted_adapter)
                                              or not hasattr(self, "restarted_adapter")):
             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)
                 self.restarted_adapter = True
                 if succeed:
                     log_loading.info("Pcap service started !")
                     self.load_from_powershell()
                     return
             _error_msg = "Could not start the pcap service ! "
         warning(_error_msg +
                 "You probably won't be able to send packets. "
                 "Deactivating unneeded interfaces and restarting Scapy might help. "
                 "Check your winpcap and powershell installation, and access rights.", True)
     else:
         # Loading state: remove invalid interfaces
         self.remove_invalid_ifaces()
         # Replace LOOPBACK_INTERFACE
         try:
             scapy.consts.LOOPBACK_INTERFACE = self.dev_from_name(LOOPBACK_NAME)
         except:
             pass
Example #19
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)
Example #20
0
 def post_dissect(self, s):
     if not conf.contribs["http"]["auto_compression"]:
         return s
     encodings = self._get_encodings()
     # Un-chunkify
     if "chunked" in encodings:
         data = b""
         while s:
             length, _, body = s.partition(b"\r\n")
             try:
                 length = int(length, 16)
             except ValueError:
                 # Not a valid chunk. Ignore
                 break
             else:
                 load = body[:length]
                 if body[length:length + 2] != b"\r\n":
                     # Invalid chunk. Ignore
                     break
                 s = body[length + 2:]
                 data += load
         if not s:
             s = data
     # Decompress
     try:
         if "deflate" in encodings:
             import zlib
             s = zlib.decompress(s)
         elif "gzip" in encodings:
             s = gzip_decompress(s)
         elif "compress" in encodings:
             import lzw
             s = lzw.decompress(s)
         elif "br" in encodings:
             if _is_brotli_available:
                 s = brotli.decompress(s)
             else:
                 log_loading.info(
                     "Can't import brotli. brotli decompression "
                     "will be ignored !"
                 )
     except Exception:
         # Cannot decompress - probably incomplete data
         pass
     return s
Example #21
0
    def _pcap_check(cls):
        """Performs checks/restart pcap adapter"""
        if not conf.use_winpcapy:
            # 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
                return False

        _error_msg = ("No match between your pcap and windows "
                      "network interfaces found. ")
        if _detect:
            # No action needed
            return
        else:
            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
            _error_msg = "Could not start the pcap service ! "
        warning(_error_msg + "You probably won't be able to send packets. "
                "Deactivating unneeded interfaces and restarting "
                "Scapy might help. Check your winpcap/npcap installation "
                "and access rights.")
Example #22
0
def load_services(filename):
    # type: (str) -> Tuple[DADict[int, str], DADict[int, str]]
    spaces = re.compile(b"[ \t]+|\n")
    tdct = DADict(_name="%s-tcp" % filename)  # type: DADict[int, str]
    udct = DADict(_name="%s-udp" % filename)  # type: DADict[int, str]
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dtct = None
                    if lt[1].endswith(b"/tcp"):
                        dtct = tdct
                    elif lt[1].endswith(b"/udp"):
                        dtct = udct
                    else:
                        continue
                    port = lt[1].split(b'/')[0]
                    name = fixname(lt[0])
                    if b"-" in port:
                        sport, eport = port.split(b"-")
                        for i in range(int(sport), int(eport) + 1):
                            dtct[i] = name
                    else:
                        dtct[int(port)] = name
                except Exception as e:
                    log_loading.warning(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct, udct
Example #23
0
def load_protocols(filename,
                   _fallback=None,
                   _integer_base=10,
                   _cls=DADict[int, str]):
    # type: (str, Optional[bytes], int, type) -> DADict[int, str]
    """"Parse /etc/protocols and return values as a dictionary."""
    spaces = re.compile(b"[ \t]+|\n")
    dct = _cls(_name=filename)  # type: DADict[int, str]

    def _process_data(fdesc):
        # type: (Iterator[bytes]) -> None
        for line in fdesc:
            try:
                shrp = line.find(b"#")
                if shrp >= 0:
                    line = line[:shrp]
                line = line.strip()
                if not line:
                    continue
                lt = tuple(re.split(spaces, line))
                if len(lt) < 2 or not lt[0]:
                    continue
                dct[int(lt[1], _integer_base)] = fixname(lt[0])
            except Exception as e:
                log_loading.info(
                    "Couldn't parse file [%s]: line [%r] (%s)",
                    filename,
                    line,
                    e,
                )

    try:
        if not filename:
            raise IOError
        with open(filename, "rb") as fdesc:
            _process_data(fdesc)
    except IOError:
        if _fallback:
            _process_data(iter(_fallback.split(b"\n")))
        else:
            log_loading.info("Can't open %s file", filename)
    return dct
Example #24
0
def load_ethertypes(filename):
    spaces = re.compile("[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        f=open(filename)
        for l in f:
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                dct[lt[0]] = int(lt[1], 16)
            except Exception,e:
                log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e))
        f.close()
Example #25
0
def load_ethertypes(filename):
    spaces = re.compile("[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        f=open(filename)
        for l in f:
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                dct[lt[0]] = int(lt[1], 16)
            except Exception,e:
                log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e))
        f.close()
Example #26
0
 def _process_data(fdesc):
     for line in fdesc:
         try:
             shrp = line.find(b"#")
             if shrp >= 0:
                 line = line[:shrp]
             line = line.strip()
             if not line:
                 continue
             lt = tuple(re.split(spaces, line))
             if len(lt) < 2 or not lt[0]:
                 continue
             dct[lt[0]] = int(lt[1], _integer_base)
         except Exception as e:
             log_loading.info(
                 "Couldn't parse file [%s]: line [%r] (%s)",
                 filename,
                 line,
                 e,
             )
Example #27
0
def load_protocols(filename):
    spaces = re.compile("[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        for l in open(filename):
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                dct[lt[0]] = int(lt[1])
            except Exception,e:
                log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e))
    except IOError:
        log_loading.info("Can't open %s file" % filename)
    return dct
Example #28
0
def load_protocols(filename):
    spaces = re.compile("[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        for l in open(filename):
            try:
                shrp = l.find("#")
                if  shrp >= 0:
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                dct[lt[0]] = int(lt[1])
            except Exception as e:
                log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e))
    except IOError:
        log_loading.info("Can't open %s file" % filename)
    return dct
Example #29
0
File: main.py Project: 6WIND/scapy
def load_session(fname=None):
    """Load current Scapy session from the file specified in the fname arg.
    This will erase any existing session.

    params:
     - fname: file to load the scapy session from"""
    if fname is None:
        fname = conf.session
    try:
        s = six.moves.cPickle.load(gzip.open(fname,"rb"))
    except IOError:
        try:
            s = six.moves.cPickle.load(open(fname,"rb"))
        except IOError:
            # Raise "No such file exception"
            raise

    scapy_session = six.moves.builtins.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)
    update_ipython_session(scapy_session)

    log_loading.info("Loaded session [%s]" % fname)
Example #30
0
               chainCC=chainCC,
               nofilter=1)
    if res is not None:
        mac = res.payload.hwsrc
        conf.netcache.arp_cache[ip] = mac
        return mac
    return None

import scapy.layers.l2
scapy.layers.l2.getmacbyip = getmacbyip

try:
    import readline
    console = readline.GetOutputFile()
except (ImportError, AttributeError):
    log_loading.info("Could not get readline console. Will not interpret ANSI color codes.") 
else:
    conf.readfunc = readline.rl.readline
    orig_stdout = sys.stdout
    sys.stdout = console





def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, multi=0):
    if not isinstance(pkt, Gen):
        pkt = SetGen(pkt)
        
    if verbose is None:
        verbose = conf.verb
Example #31
0
                    l = l[:shrp]
                l = l.strip()
                if not l:
                    continue
                lt = tuple(re.split(spaces, l))
                if len(lt) < 2 or not lt[0]:
                    continue
                if lt[1].endswith("/tcp"):
                    tdct[lt[0]] = int(lt[1].split('/')[0])
                elif lt[1].endswith("/udp"):
                    udct[lt[0]] = int(lt[1].split('/')[0])
            except Exception,e:
                log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e))
        f.close()
    except IOError:
        log_loading.info("Can't open /etc/services file")
    return tdct,udct


class ManufDA(DADict):
    def fixname(self, val):
        return val
    def _get_manuf_couple(self, mac):
        oui = ":".join(mac.split(":")[:3]).upper()
        return self.__dict__.get(oui,(mac,mac))
    def _get_manuf(self, mac):
        return self._get_manuf_couple(mac)[1]
    def _get_short_manuf(self, mac):
        return self._get_manuf_couple(mac)[0]
    def _resolve_MAC(self, mac):
        oui = ":".join(mac.split(":")[:3]).upper()
Example #32
0
                    line = readline.rl.readline(prompt)
                if line.strip().endswith(":"):
                    end = False
                elif result == "":
                    end = True
                if line.strip() == "":
                    end = True
                result = result + "\n" + line
            return six.text_type(result)

        try:
            import readline
            console = readline.GetOutputFile()
        except (ImportError, AttributeError):
            log_loading.info(
                "Could not get readline console. Will not interpret ANSI color codes."
            )
        else:
            conf.readfunc = readLineScapy
            orig_stdout = sys.stdout
            sys.stdout = console


def get_working_if():
    try:
        # return the interface associated with the route with smallest
        # mask (route by default if it exists)
        return min(read_routes(), key=lambda x: x[1])[3]
    except ValueError:
        # no route
        return scapy.consts.LOOPBACK_INTERFACE
Example #33
0
from scapy.config import conf
from scapy.packet import Packet
from scapy.supersocket import SuperSocket
from scapy.contrib.isotp import ISOTPSocket
from scapy.error import warning, log_loading
from scapy.utils import PeriodicSenderThread

__all__ = [
    "GMLAN_TesterPresentSender", "GMLAN_InitDiagnostics",
    "GMLAN_GetSecurityAccess", "GMLAN_RequestDownload", "GMLAN_TransferData",
    "GMLAN_TransferPayload", "GMLAN_ReadMemoryByAddress",
    "GMLAN_BroadcastSocket"
]

log_loading.info("\"conf.contribs['GMLAN']"
                 "['treat-response-pending-as-answer']\" set to True). This "
                 "is required by the GMLAN-Utils module to operate "
                 "correctly.")
try:
    conf.contribs['GMLAN']['treat-response-pending-as-answer'] = False
except KeyError:
    conf.contribs['GMLAN'] = {'treat-response-pending-as-answer': False}


# Helper function
def _check_response(resp, verbose):
    # type: (Optional[Packet], Optional[bool]) -> bool
    if resp is None:
        if verbose:
            print("Timeout.")
        return False
    if verbose:
Example #34
0
    def data_for_encryption(self):
        return raw(self.data) + self.padding + struct.pack(
            "BB", self.padlen, self.nh)


###############################################################################
if conf.crypto_valid:
    from cryptography.exceptions import InvalidTag
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import (
        Cipher,
        algorithms,
        modes,
    )
else:
    log_loading.info("Can't import python-cryptography v1.7+. "
                     "Disabled IPsec encryption/authentication.")
    InvalidTag = default_backend = None
    Cipher = algorithms = modes = None

###############################################################################


def _lcm(a, b):
    """
    Least Common Multiple between 2 integers.
    """
    if a == 0 or b == 0:
        return 0
    else:
        return abs(a * b) // gcd(a, b)
Example #35
0
from scapy.error import log_loading
from scapy.consts import LINUX
from scapy.config import conf
import scapy.modules.six as six

PYTHON_CAN = False

try:
    if conf.contribs['CANSocket']['use-python-can']:
        from can import BusABC as can_BusABC    # noqa: F401
        PYTHON_CAN = True
    else:
        PYTHON_CAN = False
except ImportError:
    log_loading.info("Can't import python-can.")
except KeyError:
    log_loading.info("Configuration 'conf.contribs['CANSocket'] not found.")


if PYTHON_CAN:
    log_loading.info("Using python-can CANSocket.")
    log_loading.info("Specify 'conf.contribs['CANSocket'] = "
                     "{'use-python-can': False}' to enable native CANSockets.")
    from scapy.contrib.cansocket_python_can import (CANSocket, srcan, CAN_FRAME_SIZE, CAN_INV_FILTER)  # noqa: E501 F401

elif LINUX and six.PY3:
    log_loading.info("Using native CANSocket.")
    log_loading.info("Specify 'conf.contribs['CANSocket'] = "
                     "{'use-python-can': True}' "
                     "to enable python-can CANSockets.")
    FieldListField, XStrFixedLenField, PacketField, FCSField
from scapy.ansmachine import AnsweringMachine
from scapy.plist import PacketList
from scapy.layers.l2 import Ether, LLC, MACField
from scapy.layers.inet import IP, TCP
from scapy.error import warning, log_loading
from scapy.sendrecv import sniff, sendp
from scapy.utils import issubtype

if conf.crypto_valid:
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
else:
    default_backend = Ciphers = algorithms = None
    log_loading.info(
        "Can't import python-cryptography v1.7+. Disabled WEP decryption/encryption. (Dot11)"
    )  # noqa: E501

# Layers


class PrismHeader(Packet):
    """ iwpriv wlan0 monitor 3 """
    name = "Prism header"
    fields_desc = [
        LEIntField("msgcode", 68),
        LEIntField("len", 144),
        StrFixedLenField("dev", "", 16),
        LEIntField("hosttime_did", 0),
        LEShortField("hosttime_status", 0),
        LEShortField("hosttime_len", 0),
Example #37
0
except socket.error:
    def inet_aton(x):
        if x == "255.255.255.255":
            return "\xff"*4
        else:
            return socket.inet_aton(x)
else:
    inet_aton = socket.inet_aton

inet_ntoa = socket.inet_ntoa
try:
    inet_ntop = socket.inet_ntop
    inet_pton = socket.inet_pton
except AttributeError:
    from scapy.pton_ntop import *
    log_loading.info("inet_ntop/pton functions not found. Python IPv6 support not present")


def atol(x):
    try:
        ip = inet_aton(x)
    except socket.error:
        ip = inet_aton(socket.gethostbyname(x))
    return struct.unpack("!I", ip)[0]
def ltoa(x):
    return inet_ntoa(struct.pack("!I", x&0xffffffff))

def itom(x):
    return (0xffffffff00000000L>>x)&0xffffffffL

def do_graph(graph,prog=None,format=None,target=None,type=None,string=None,options=None):
Example #38
0
try:
    from matplotlib import get_backend as matplotlib_get_backend
    import matplotlib.pyplot as plt
    MATPLOTLIB = 1
    if "inline" in matplotlib_get_backend():
        MATPLOTLIB_INLINED = 1
    else:
        MATPLOTLIB_INLINED = 0
    MATPLOTLIB_DEFAULT_PLOT_KARGS = {"marker": "+"}
# RuntimeError to catch gtk "Cannot open display" error
except (ImportError, RuntimeError):
    plt = None
    MATPLOTLIB = 0
    MATPLOTLIB_INLINED = 0
    MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()
    log_loading.info("Can't import matplotlib. Won't be able to plot.")

# PYX


def _test_pyx():
    """Returns if PyX is correctly installed or not"""
    try:
        with open(os.devnull, 'wb') as devnull:
            r = subprocess.check_call(["pdflatex", "--version"],
                                      stdout=devnull,
                                      stderr=subprocess.STDOUT)
    except (subprocess.CalledProcessError, OSError):
        return False
    else:
        return r == 0
Example #39
0
from scapy.consts import WINDOWS
from scapy.error import warning, log_loading
from scapy.fields import StrField
from scapy.packet import Packet, bind_layers, bind_bottom_up, Raw
from scapy.utils import get_temp_file, ContextManagerSubprocess

from scapy.layers.inet import TCP, TCP_client

from scapy.modules import six

try:
    import brotli
    is_brotli_available = True
except ImportError:
    is_brotli_available = False
    log_loading.info("Can't import brotli. Won't be able to decompress "
                     "data streams compressed with brotli.")

if "http" not in conf.contribs:
    conf.contribs["http"] = {}
    conf.contribs["http"]["auto_compression"] = True

# https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

GENERAL_HEADERS = [
    "Cache-Control",
    "Connection",
    "Permanent",
    "Content-Length",
    "Content-MD5",
    "Content-Type",
    "Date",
Example #40
0
    FieldListField, XStrFixedLenField, PacketField
from scapy.ansmachine import AnsweringMachine
from scapy.plist import PacketList
from scapy.layers.l2 import Ether, LLC, MACField
from scapy.layers.inet import IP, TCP
from scapy.error import warning, log_loading
from scapy.sendrecv import sniff, sendp
from scapy.utils import issubtype


if conf.crypto_valid:
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
else:
    default_backend = Ciphers = algorithms = None
    log_loading.info("Can't import python-cryptography v1.7+. Disabled WEP decryption/encryption. (Dot11)")  # noqa: E501


# Layers


class PrismHeader(Packet):
    """ iwpriv wlan0 monitor 3 """
    name = "Prism header"
    fields_desc = [LEIntField("msgcode", 68),
                   LEIntField("len", 144),
                   StrFixedLenField("dev", "", 16),
                   LEIntField("hosttime_did", 0),
                   LEShortField("hosttime_status", 0),
                   LEShortField("hosttime_len", 0),
                   LEIntField("hosttime", 0),
Example #41
0
from scapy.layers.inet import IP
from scapy.layers.inet6 import IPv6
from scapy.compat import raw
from scapy.data import ETH_P_MACSEC, ETHER_TYPES, ETH_P_IP, ETH_P_IPV6
from scapy.error import log_loading
import scapy.modules.six as six

if conf.crypto_valid:
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import (
        Cipher,
        algorithms,
        modes,
    )
else:
    log_loading.info("Can't import python-cryptography v1.7+. "
                     "Disabled MACsec encryption/authentication.")


NOSCI_LEN = 14 + 6
SCI_LEN = 8
DEFAULT_ICV_LEN = 16


class MACsecSA(object):
    """Representation of a MACsec Secure Association

    Provides encapsulation, decapsulation, encryption, and decryption
    of MACsec frames
    """
    def __init__(self, sci, an, pn, key, icvlen, encrypt, send_sci, xpn_en=False, ssci=None, salt=None):  # noqa: E501
        if isinstance(sci, six.integer_types):
Example #42
0
    def data_for_encryption(self):
        return bytes(self.data) + self.padding + chr(self.padlen).encode('ascii') + chr(self.nh).encode('ascii')

#------------------------------------------------------------------------------
try:
    from cryptography.exceptions import InvalidTag
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.ciphers import (
        Cipher,
        algorithms,
        modes,
    )
except ImportError:
    # no error if pycrypto is not available but encryption won't be supported
    log_loading.info("Can't import python cryptography lib. "
                     "Disabled IPsec encryption/authentication.")
    algorithms = None
    Cipher = None
    modes = None

#------------------------------------------------------------------------------
def _lcm(a, b):
    """
    Least Common Multiple between 2 integers.
    """
    if a == 0 or b == 0:
        return 0
    else:
        return abs(a * b) // gcd(a, b)

class CryptAlgo(object):
Example #43
0
try:
    from matplotlib import get_backend as matplotlib_get_backend
    import matplotlib.pyplot as plt
    MATPLOTLIB = 1
    if "inline" in matplotlib_get_backend():
        MATPLOTLIB_INLINED = 1
    else:
        MATPLOTLIB_INLINED = 0
    MATPLOTLIB_DEFAULT_PLOT_KARGS = {"marker": "+"}
# RuntimeError to catch gtk "Cannot open display" error
except (ImportError, RuntimeError):
    plt = None
    MATPLOTLIB = 0
    MATPLOTLIB_INLINED = 0
    MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()
    log_loading.info("Can't import matplotlib. Won't be able to plot.")

# PYX


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

from scapy.error import log_loading
from scapy.consts import LINUX
from scapy.config import conf
import scapy.modules.six as six

PYTHON_CAN = False

try:
    if conf.contribs['CANSocket']['use-python-can']:
        from can import BusABC as can_BusABC    # noqa: F401
        PYTHON_CAN = True
except ImportError:
    log_loading.info("Can't import python-can.")
except KeyError:
    log_loading.info("Specify 'conf.contribs['CANSocket'] = "
                     "{'use-python-can': True}' to enable python-can.")


if PYTHON_CAN:
    from scapy.contrib.cansocket_python_can import (CANSocket,   # noqa: F401
                                                    srcan, CANSocketTimeoutElapsed, CAN_FRAME_SIZE, CAN_INV_FILTER)  # noqa: E501
elif LINUX and six.PY3:
    log_loading.info("Use native CANSocket. Specify "
                     "'conf.contribs['CANSocket'] = "
                     "{'use-python-can': True}' to enable python-can.")
    from scapy.contrib.cansocket_native import (CANSocket,   # noqa: F401
                                                srcan, CAN_FRAME_SIZE, CAN_INV_FILTER)  # noqa: E501
else:
Example #45
0
## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <*****@*****.**>
## This program is published under a GPLv2 license

"""
All layers. Configurable with conf.load_layers.
"""

import importlib
from scapy.config import conf
from scapy.error import log_loading
import logging
log = logging.getLogger("scapy.loading")

log_loading.info("Please, report issues to https://github.com/phaethon/scapy")

def _import_star(m):
    #mod = __import__("." + m, globals(), locals())
    mod = importlib.import_module("scapy.layers." + m)
    for k,v in mod.__dict__.items():
        globals()[k] = v

for _l in conf.load_layers:
    log_loading.debug("Loading layer %s" % _l)
    try:
        _import_star(_l)
    except Exception as e:
        log.warning("can't import layer %s: %s" % (_l,e))

Example #46
0
except socket.error:
    def inet_aton(x):
        if x == "255.255.255.255":
            return "\xff"*4
        else:
            return socket.inet_aton(x)
else:
    inet_aton = socket.inet_aton

inet_ntoa = socket.inet_ntoa
try:
    inet_ntop = socket.inet_ntop
    inet_pton = socket.inet_pton
except AttributeError:
    from scapy.pton_ntop import *
    log_loading.info("inet_ntop/pton functions not found. Python IPv6 support not present")


def atol(x):
    try:
        ip = inet_aton(x)
    except socket.error:
        ip = inet_aton(socket.gethostbyname(x))
    return struct.unpack("!I", ip)[0]
def ltoa(x):
    return inet_ntoa(struct.pack("!I", x&0xffffffff))

def itom(x):
    return (0xffffffff00000000L>>x)&0xffffffffL

def do_graph(graph,prog=None,format=None,target=None,type=None,string=None,options=None):
Example #47
0
    XShortField, X3BytesField, XIntField, ByteField, \
    ShortField, ObservableDict, XShortEnumField, XByteEnumField
from scapy.packet import Packet, bind_layers
from scapy.config import conf
from scapy.error import log_loading
"""
UDS
"""

try:
    if conf.contribs['UDS']['treat-response-pending-as-answer']:
        pass
except KeyError:
    log_loading.info("Specify \"conf.contribs['UDS'] = "
                     "{'treat-response-pending-as-answer': True}\" to treat "
                     "a negative response 'requestCorrectlyReceived-"
                     "ResponsePending' as answer of a request. \n"
                     "The default value is False.")
    conf.contribs['UDS'] = {'treat-response-pending-as-answer': False}


class UDS(Packet):
    services = ObservableDict({
        0x10: 'DiagnosticSessionControl',
        0x11: 'ECUReset',
        0x14: 'ClearDiagnosticInformation',
        0x19: 'ReadDTCInformation',
        0x22: 'ReadDataByIdentifier',
        0x23: 'ReadMemoryByAddress',
        0x24: 'ReadScalingDataByIdentifier',
        0x27: 'SecurityAccess',
Example #48
0
CANSocket.
"""

from scapy.error import log_loading
from scapy.consts import LINUX
from scapy.config import conf
import scapy.modules.six as six

PYTHON_CAN = False

try:
    if conf.contribs['CANSocket']['use-python-can']:
        from can import BusABC as can_BusABC  # noqa: F401
        PYTHON_CAN = True
except ImportError:
    log_loading.info("Can't import python-can.")
except KeyError:
    log_loading.info("Specify 'conf.contribs['CANSocket'] = "
                     "{'use-python-can': True}' to enable python-can.")

if PYTHON_CAN:
    from scapy.contrib.cansocket_python_can import (
        CANSocket,  # noqa: F401
        srcan,
        CANSocketTimeoutElapsed,
        CAN_FRAME_SIZE,
        CAN_INV_FILTER)
elif LINUX and six.PY3:
    log_loading.info("Use native CANSocket. Specify "
                     "'conf.contribs['CANSocket'] = "
                     "{'use-python-can': True}' to enable python-can.")