xref: /aosp_15_r20/external/scapy/scapy/config.py (revision 7dc08ffc4802948ccbc861daaf1e81c405c2c4bd)
1*7dc08ffcSJunyu Lai## This file is part of Scapy
2*7dc08ffcSJunyu Lai## See http://www.secdev.org/projects/scapy for more informations
3*7dc08ffcSJunyu Lai## Copyright (C) Philippe Biondi <[email protected]>
4*7dc08ffcSJunyu Lai## This program is published under a GPLv2 license
5*7dc08ffcSJunyu Lai
6*7dc08ffcSJunyu Lai"""
7*7dc08ffcSJunyu LaiImplementation of the configuration object.
8*7dc08ffcSJunyu Lai"""
9*7dc08ffcSJunyu Lai
10*7dc08ffcSJunyu Laifrom __future__ import absolute_import
11*7dc08ffcSJunyu Laifrom __future__ import print_function
12*7dc08ffcSJunyu Laiimport os,time,socket,sys
13*7dc08ffcSJunyu Lai
14*7dc08ffcSJunyu Laifrom scapy import VERSION
15*7dc08ffcSJunyu Laifrom scapy.data import *
16*7dc08ffcSJunyu Laifrom scapy import base_classes
17*7dc08ffcSJunyu Laifrom scapy.themes import NoTheme, apply_ipython_style
18*7dc08ffcSJunyu Laifrom scapy.error import log_scapy
19*7dc08ffcSJunyu Laiimport scapy.modules.six as six
20*7dc08ffcSJunyu Lai
21*7dc08ffcSJunyu Lai############
22*7dc08ffcSJunyu Lai## Config ##
23*7dc08ffcSJunyu Lai############
24*7dc08ffcSJunyu Lai
25*7dc08ffcSJunyu Laiclass ConfClass(object):
26*7dc08ffcSJunyu Lai    def configure(self, cnf):
27*7dc08ffcSJunyu Lai        self.__dict__ = cnf.__dict__.copy()
28*7dc08ffcSJunyu Lai    def __repr__(self):
29*7dc08ffcSJunyu Lai        return str(self)
30*7dc08ffcSJunyu Lai    def __str__(self):
31*7dc08ffcSJunyu Lai        s = ""
32*7dc08ffcSJunyu Lai        keys = self.__class__.__dict__.copy()
33*7dc08ffcSJunyu Lai        keys.update(self.__dict__)
34*7dc08ffcSJunyu Lai        keys = sorted(keys)
35*7dc08ffcSJunyu Lai        for i in keys:
36*7dc08ffcSJunyu Lai            if i[0] != "_":
37*7dc08ffcSJunyu Lai                r = repr(getattr(self, i))
38*7dc08ffcSJunyu Lai                r = " ".join(r.split())
39*7dc08ffcSJunyu Lai                wlen = 76-max(len(i),10)
40*7dc08ffcSJunyu Lai                if len(r) > wlen:
41*7dc08ffcSJunyu Lai                    r = r[:wlen-3]+"..."
42*7dc08ffcSJunyu Lai                s += "%-10s = %s\n" % (i, r)
43*7dc08ffcSJunyu Lai        return s[:-1]
44*7dc08ffcSJunyu Lai
45*7dc08ffcSJunyu Laiclass Interceptor(object):
46*7dc08ffcSJunyu Lai    def __init__(self, name, default, hook, args=None, kargs=None):
47*7dc08ffcSJunyu Lai        self.name = name
48*7dc08ffcSJunyu Lai        self.intname = "_intercepted_%s" % name
49*7dc08ffcSJunyu Lai        self.default=default
50*7dc08ffcSJunyu Lai        self.hook = hook
51*7dc08ffcSJunyu Lai        self.args = args if args is not None else []
52*7dc08ffcSJunyu Lai        self.kargs = kargs if kargs is not None else {}
53*7dc08ffcSJunyu Lai    def __get__(self, obj, typ=None):
54*7dc08ffcSJunyu Lai        if not hasattr(obj, self.intname):
55*7dc08ffcSJunyu Lai            setattr(obj, self.intname, self.default)
56*7dc08ffcSJunyu Lai        return getattr(obj, self.intname)
57*7dc08ffcSJunyu Lai    def __set__(self, obj, val):
58*7dc08ffcSJunyu Lai        setattr(obj, self.intname, val)
59*7dc08ffcSJunyu Lai        self.hook(self.name, val, *self.args, **self.kargs)
60*7dc08ffcSJunyu Lai
61*7dc08ffcSJunyu Lai
62*7dc08ffcSJunyu Laiclass ProgPath(ConfClass):
63*7dc08ffcSJunyu Lai    pdfreader = "acroread"
64*7dc08ffcSJunyu Lai    psreader = "gv"
65*7dc08ffcSJunyu Lai    dot = "dot"
66*7dc08ffcSJunyu Lai    display = "display"
67*7dc08ffcSJunyu Lai    tcpdump = "tcpdump"
68*7dc08ffcSJunyu Lai    tcpreplay = "tcpreplay"
69*7dc08ffcSJunyu Lai    hexedit = "hexer"
70*7dc08ffcSJunyu Lai    tshark = "tshark"
71*7dc08ffcSJunyu Lai    wireshark = "wireshark"
72*7dc08ffcSJunyu Lai    ifconfig = "ifconfig"
73*7dc08ffcSJunyu Lai
74*7dc08ffcSJunyu Lai
75*7dc08ffcSJunyu Laiclass ConfigFieldList:
76*7dc08ffcSJunyu Lai    def __init__(self):
77*7dc08ffcSJunyu Lai        self.fields = set()
78*7dc08ffcSJunyu Lai        self.layers = set()
79*7dc08ffcSJunyu Lai    @staticmethod
80*7dc08ffcSJunyu Lai    def _is_field(f):
81*7dc08ffcSJunyu Lai        return hasattr(f, "owners")
82*7dc08ffcSJunyu Lai    def _recalc_layer_list(self):
83*7dc08ffcSJunyu Lai        self.layers = {owner for f in self.fields for owner in f.owners}
84*7dc08ffcSJunyu Lai    def add(self, *flds):
85*7dc08ffcSJunyu Lai        self.fields |= {f for f in flds if self._is_field(f)}
86*7dc08ffcSJunyu Lai        self._recalc_layer_list()
87*7dc08ffcSJunyu Lai    def remove(self, *flds):
88*7dc08ffcSJunyu Lai        self.fields -= set(flds)
89*7dc08ffcSJunyu Lai        self._recalc_layer_list()
90*7dc08ffcSJunyu Lai    def __contains__(self, elt):
91*7dc08ffcSJunyu Lai        if isinstance(elt, base_classes.Packet_metaclass):
92*7dc08ffcSJunyu Lai            return elt in self.layers
93*7dc08ffcSJunyu Lai        return elt in self.fields
94*7dc08ffcSJunyu Lai    def __repr__(self):
95*7dc08ffcSJunyu Lai        return "<%s [%s]>" %  (self.__class__.__name__," ".join(str(x) for x in self.fields))
96*7dc08ffcSJunyu Lai
97*7dc08ffcSJunyu Laiclass Emphasize(ConfigFieldList):
98*7dc08ffcSJunyu Lai    pass
99*7dc08ffcSJunyu Lai
100*7dc08ffcSJunyu Laiclass Resolve(ConfigFieldList):
101*7dc08ffcSJunyu Lai    pass
102*7dc08ffcSJunyu Lai
103*7dc08ffcSJunyu Lai
104*7dc08ffcSJunyu Laiclass Num2Layer:
105*7dc08ffcSJunyu Lai    def __init__(self):
106*7dc08ffcSJunyu Lai        self.num2layer = {}
107*7dc08ffcSJunyu Lai        self.layer2num = {}
108*7dc08ffcSJunyu Lai
109*7dc08ffcSJunyu Lai    def register(self, num, layer):
110*7dc08ffcSJunyu Lai        self.register_num2layer(num, layer)
111*7dc08ffcSJunyu Lai        self.register_layer2num(num, layer)
112*7dc08ffcSJunyu Lai
113*7dc08ffcSJunyu Lai    def register_num2layer(self, num, layer):
114*7dc08ffcSJunyu Lai        self.num2layer[num] = layer
115*7dc08ffcSJunyu Lai    def register_layer2num(self, num, layer):
116*7dc08ffcSJunyu Lai        self.layer2num[layer] = num
117*7dc08ffcSJunyu Lai
118*7dc08ffcSJunyu Lai    def __getitem__(self, item):
119*7dc08ffcSJunyu Lai        if isinstance(item, base_classes.Packet_metaclass):
120*7dc08ffcSJunyu Lai            return self.layer2num[item]
121*7dc08ffcSJunyu Lai        return self.num2layer[item]
122*7dc08ffcSJunyu Lai    def __contains__(self, item):
123*7dc08ffcSJunyu Lai        if isinstance(item, base_classes.Packet_metaclass):
124*7dc08ffcSJunyu Lai            return item in self.layer2num
125*7dc08ffcSJunyu Lai        return item in self.num2layer
126*7dc08ffcSJunyu Lai    def get(self, item, default=None):
127*7dc08ffcSJunyu Lai        if item in self:
128*7dc08ffcSJunyu Lai            return self[item]
129*7dc08ffcSJunyu Lai        return default
130*7dc08ffcSJunyu Lai
131*7dc08ffcSJunyu Lai    def __repr__(self):
132*7dc08ffcSJunyu Lai        lst = []
133*7dc08ffcSJunyu Lai        for num,layer in six.iteritems(self.num2layer):
134*7dc08ffcSJunyu Lai            if layer in self.layer2num and self.layer2num[layer] == num:
135*7dc08ffcSJunyu Lai                dir = "<->"
136*7dc08ffcSJunyu Lai            else:
137*7dc08ffcSJunyu Lai                dir = " ->"
138*7dc08ffcSJunyu Lai            lst.append((num,"%#6x %s %-20s (%s)" % (num, dir, layer.__name__,
139*7dc08ffcSJunyu Lai                                                    layer._name)))
140*7dc08ffcSJunyu Lai        for layer,num in six.iteritems(self.layer2num):
141*7dc08ffcSJunyu Lai            if num not in self.num2layer or self.num2layer[num] != layer:
142*7dc08ffcSJunyu Lai                lst.append((num,"%#6x <-  %-20s (%s)" % (num, layer.__name__,
143*7dc08ffcSJunyu Lai                                                         layer._name)))
144*7dc08ffcSJunyu Lai        lst.sort()
145*7dc08ffcSJunyu Lai        return "\n".join(y for x,y in lst)
146*7dc08ffcSJunyu Lai
147*7dc08ffcSJunyu Lai
148*7dc08ffcSJunyu Laiclass LayersList(list):
149*7dc08ffcSJunyu Lai    def __repr__(self):
150*7dc08ffcSJunyu Lai        s=[]
151*7dc08ffcSJunyu Lai        for l in self:
152*7dc08ffcSJunyu Lai            s.append("%-20s: %s" % (l.__name__,l.name))
153*7dc08ffcSJunyu Lai        return "\n".join(s)
154*7dc08ffcSJunyu Lai    def register(self, layer):
155*7dc08ffcSJunyu Lai        self.append(layer)
156*7dc08ffcSJunyu Lai
157*7dc08ffcSJunyu Laiclass CommandsList(list):
158*7dc08ffcSJunyu Lai    def __repr__(self):
159*7dc08ffcSJunyu Lai        s=[]
160*7dc08ffcSJunyu Lai        for l in sorted(self,key=lambda x:x.__name__):
161*7dc08ffcSJunyu Lai            if l.__doc__:
162*7dc08ffcSJunyu Lai                doc = l.__doc__.split("\n")[0]
163*7dc08ffcSJunyu Lai            else:
164*7dc08ffcSJunyu Lai                doc = "--"
165*7dc08ffcSJunyu Lai            s.append("%-20s: %s" % (l.__name__,doc))
166*7dc08ffcSJunyu Lai        return "\n".join(s)
167*7dc08ffcSJunyu Lai    def register(self, cmd):
168*7dc08ffcSJunyu Lai        self.append(cmd)
169*7dc08ffcSJunyu Lai        return cmd # return cmd so that method can be used as a decorator
170*7dc08ffcSJunyu Lai
171*7dc08ffcSJunyu Laidef lsc():
172*7dc08ffcSJunyu Lai    print(repr(conf.commands))
173*7dc08ffcSJunyu Lai
174*7dc08ffcSJunyu Laiclass CacheInstance(dict, object):
175*7dc08ffcSJunyu Lai    __slots__ = ["timeout", "name", "_timetable", "__dict__"]
176*7dc08ffcSJunyu Lai    def __init__(self, name="noname", timeout=None):
177*7dc08ffcSJunyu Lai        self.timeout = timeout
178*7dc08ffcSJunyu Lai        self.name = name
179*7dc08ffcSJunyu Lai        self._timetable = {}
180*7dc08ffcSJunyu Lai    def flush(self):
181*7dc08ffcSJunyu Lai        self.__init__(name=self.name, timeout=self.timeout)
182*7dc08ffcSJunyu Lai    def __getitem__(self, item):
183*7dc08ffcSJunyu Lai        if item in self.__slots__:
184*7dc08ffcSJunyu Lai            return object.__getattribute__(self, item)
185*7dc08ffcSJunyu Lai        val = dict.__getitem__(self,item)
186*7dc08ffcSJunyu Lai        if self.timeout is not None:
187*7dc08ffcSJunyu Lai            t = self._timetable[item]
188*7dc08ffcSJunyu Lai            if time.time()-t > self.timeout:
189*7dc08ffcSJunyu Lai                raise KeyError(item)
190*7dc08ffcSJunyu Lai        return val
191*7dc08ffcSJunyu Lai    def get(self, item, default=None):
192*7dc08ffcSJunyu Lai        # overloading this method is needed to force the dict to go through
193*7dc08ffcSJunyu Lai        # the timetable check
194*7dc08ffcSJunyu Lai        try:
195*7dc08ffcSJunyu Lai            return self[item]
196*7dc08ffcSJunyu Lai        except KeyError:
197*7dc08ffcSJunyu Lai            return default
198*7dc08ffcSJunyu Lai    def __setitem__(self, item, v):
199*7dc08ffcSJunyu Lai        if item in self.__slots__:
200*7dc08ffcSJunyu Lai            return object.__setattr__(self, item, v)
201*7dc08ffcSJunyu Lai        self._timetable[item] = time.time()
202*7dc08ffcSJunyu Lai        dict.__setitem__(self, item,v)
203*7dc08ffcSJunyu Lai    def update(self, other):
204*7dc08ffcSJunyu Lai        for key, value in other.iteritems():
205*7dc08ffcSJunyu Lai            # We only update an element from `other` either if it does
206*7dc08ffcSJunyu Lai            # not exist in `self` or if the entry in `self` is older.
207*7dc08ffcSJunyu Lai            if key not in self or self._timetable[key] < other._timetable[key]:
208*7dc08ffcSJunyu Lai                dict.__setitem__(self, key, value)
209*7dc08ffcSJunyu Lai                self._timetable[key] = other._timetable[key]
210*7dc08ffcSJunyu Lai    def iteritems(self):
211*7dc08ffcSJunyu Lai        if self.timeout is None:
212*7dc08ffcSJunyu Lai            return six.iteritems(self.__dict__)
213*7dc08ffcSJunyu Lai        t0=time.time()
214*7dc08ffcSJunyu Lai        return ((k,v) for (k,v) in six.iteritems(self.__dict__) if t0-self._timetable[k] < self.timeout)
215*7dc08ffcSJunyu Lai    def iterkeys(self):
216*7dc08ffcSJunyu Lai        if self.timeout is None:
217*7dc08ffcSJunyu Lai            return six.iterkeys(self.__dict__)
218*7dc08ffcSJunyu Lai        t0=time.time()
219*7dc08ffcSJunyu Lai        return (k for k in six.iterkeys(self.__dict__) if t0-self._timetable[k] < self.timeout)
220*7dc08ffcSJunyu Lai    def __iter__(self):
221*7dc08ffcSJunyu Lai        return six.iterkeys(self.__dict__)
222*7dc08ffcSJunyu Lai    def itervalues(self):
223*7dc08ffcSJunyu Lai        if self.timeout is None:
224*7dc08ffcSJunyu Lai            return six.itervalues(self.__dict__)
225*7dc08ffcSJunyu Lai        t0=time.time()
226*7dc08ffcSJunyu Lai        return (v for (k,v) in six.iteritems(self.__dict__) if t0-self._timetable[k] < self.timeout)
227*7dc08ffcSJunyu Lai    def items(self):
228*7dc08ffcSJunyu Lai        if self.timeout is None:
229*7dc08ffcSJunyu Lai            return dict.items(self)
230*7dc08ffcSJunyu Lai        t0=time.time()
231*7dc08ffcSJunyu Lai        return [(k,v) for (k,v) in six.iteritems(self.__dict__) if t0-self._timetable[k] < self.timeout]
232*7dc08ffcSJunyu Lai    def keys(self):
233*7dc08ffcSJunyu Lai        if self.timeout is None:
234*7dc08ffcSJunyu Lai            return dict.keys(self)
235*7dc08ffcSJunyu Lai        t0=time.time()
236*7dc08ffcSJunyu Lai        return [k for k in six.iterkeys(self.__dict__) if t0-self._timetable[k] < self.timeout]
237*7dc08ffcSJunyu Lai    def values(self):
238*7dc08ffcSJunyu Lai        if self.timeout is None:
239*7dc08ffcSJunyu Lai            return six.values(self)
240*7dc08ffcSJunyu Lai        t0=time.time()
241*7dc08ffcSJunyu Lai        return [v for (k,v) in six.iteritems(self.__dict__) if t0-self._timetable[k] < self.timeout]
242*7dc08ffcSJunyu Lai    def __len__(self):
243*7dc08ffcSJunyu Lai        if self.timeout is None:
244*7dc08ffcSJunyu Lai            return dict.__len__(self)
245*7dc08ffcSJunyu Lai        return len(self.keys())
246*7dc08ffcSJunyu Lai    def summary(self):
247*7dc08ffcSJunyu Lai        return "%s: %i valid items. Timeout=%rs" % (self.name, len(self), self.timeout)
248*7dc08ffcSJunyu Lai    def __repr__(self):
249*7dc08ffcSJunyu Lai        s = []
250*7dc08ffcSJunyu Lai        if self:
251*7dc08ffcSJunyu Lai            mk = max(len(k) for k in six.iterkeys(self.__dict__))
252*7dc08ffcSJunyu Lai            fmt = "%%-%is %%s" % (mk+1)
253*7dc08ffcSJunyu Lai            for item in six.iteritems(self.__dict__):
254*7dc08ffcSJunyu Lai                s.append(fmt % item)
255*7dc08ffcSJunyu Lai        return "\n".join(s)
256*7dc08ffcSJunyu Lai
257*7dc08ffcSJunyu Lai
258*7dc08ffcSJunyu Lai
259*7dc08ffcSJunyu Lai
260*7dc08ffcSJunyu Laiclass NetCache:
261*7dc08ffcSJunyu Lai    def __init__(self):
262*7dc08ffcSJunyu Lai        self._caches_list = []
263*7dc08ffcSJunyu Lai
264*7dc08ffcSJunyu Lai
265*7dc08ffcSJunyu Lai    def add_cache(self, cache):
266*7dc08ffcSJunyu Lai        self._caches_list.append(cache)
267*7dc08ffcSJunyu Lai        setattr(self,cache.name,cache)
268*7dc08ffcSJunyu Lai    def new_cache(self, name, timeout=None):
269*7dc08ffcSJunyu Lai        c = CacheInstance(name=name, timeout=timeout)
270*7dc08ffcSJunyu Lai        self.add_cache(c)
271*7dc08ffcSJunyu Lai    def __delattr__(self, attr):
272*7dc08ffcSJunyu Lai        raise AttributeError("Cannot delete attributes")
273*7dc08ffcSJunyu Lai    def update(self, other):
274*7dc08ffcSJunyu Lai        for co in other._caches_list:
275*7dc08ffcSJunyu Lai            if hasattr(self, co.name):
276*7dc08ffcSJunyu Lai                getattr(self,co.name).update(co)
277*7dc08ffcSJunyu Lai            else:
278*7dc08ffcSJunyu Lai                self.add_cache(co.copy())
279*7dc08ffcSJunyu Lai    def flush(self):
280*7dc08ffcSJunyu Lai        for c in self._caches_list:
281*7dc08ffcSJunyu Lai            c.flush()
282*7dc08ffcSJunyu Lai    def __repr__(self):
283*7dc08ffcSJunyu Lai        return "\n".join(c.summary() for c in self._caches_list)
284*7dc08ffcSJunyu Lai
285*7dc08ffcSJunyu Lai
286*7dc08ffcSJunyu Laiclass LogLevel(object):
287*7dc08ffcSJunyu Lai    def __get__(self, obj, otype):
288*7dc08ffcSJunyu Lai        return obj._logLevel
289*7dc08ffcSJunyu Lai    def __set__(self,obj,val):
290*7dc08ffcSJunyu Lai        log_scapy.setLevel(val)
291*7dc08ffcSJunyu Lai        obj._logLevel = val
292*7dc08ffcSJunyu Lai
293*7dc08ffcSJunyu Lai
294*7dc08ffcSJunyu Laidef isCryptographyValid():
295*7dc08ffcSJunyu Lai    """
296*7dc08ffcSJunyu Lai    Check if the cryptography library is present, and if it is recent enough
297*7dc08ffcSJunyu Lai    for most usages in scapy (v1.7 or later).
298*7dc08ffcSJunyu Lai    """
299*7dc08ffcSJunyu Lai    try:
300*7dc08ffcSJunyu Lai        import cryptography
301*7dc08ffcSJunyu Lai    except ImportError:
302*7dc08ffcSJunyu Lai        return False
303*7dc08ffcSJunyu Lai    from distutils.version import LooseVersion
304*7dc08ffcSJunyu Lai    return LooseVersion(cryptography.__version__) >= LooseVersion("1.7")
305*7dc08ffcSJunyu Lai
306*7dc08ffcSJunyu Lai
307*7dc08ffcSJunyu Laidef isCryptographyAdvanced():
308*7dc08ffcSJunyu Lai    """
309*7dc08ffcSJunyu Lai    Check if the cryptography library is present, and if it supports X25519,
310*7dc08ffcSJunyu Lai    ChaCha20Poly1305 and such (v2.0 or later).
311*7dc08ffcSJunyu Lai    """
312*7dc08ffcSJunyu Lai    try:
313*7dc08ffcSJunyu Lai        import cryptography
314*7dc08ffcSJunyu Lai    except ImportError:
315*7dc08ffcSJunyu Lai        return False
316*7dc08ffcSJunyu Lai    from distutils.version import LooseVersion
317*7dc08ffcSJunyu Lai    lib_valid = LooseVersion(cryptography.__version__) >= LooseVersion("2.0")
318*7dc08ffcSJunyu Lai    if not lib_valid:
319*7dc08ffcSJunyu Lai        return False
320*7dc08ffcSJunyu Lai
321*7dc08ffcSJunyu Lai    try:
322*7dc08ffcSJunyu Lai        from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
323*7dc08ffcSJunyu Lai        X25519PrivateKey.generate()
324*7dc08ffcSJunyu Lai    except:
325*7dc08ffcSJunyu Lai        return False
326*7dc08ffcSJunyu Lai    else:
327*7dc08ffcSJunyu Lai        return True
328*7dc08ffcSJunyu Lai
329*7dc08ffcSJunyu Laidef isPyPy():
330*7dc08ffcSJunyu Lai    """Returns either scapy is running under PyPy or not"""
331*7dc08ffcSJunyu Lai    try:
332*7dc08ffcSJunyu Lai        import __pypy__
333*7dc08ffcSJunyu Lai        return True
334*7dc08ffcSJunyu Lai    except ImportError:
335*7dc08ffcSJunyu Lai        return False
336*7dc08ffcSJunyu Lai
337*7dc08ffcSJunyu Laidef _prompt_changer(attr, val):
338*7dc08ffcSJunyu Lai    """Change the current prompt theme"""
339*7dc08ffcSJunyu Lai    try:
340*7dc08ffcSJunyu Lai        sys.ps1 = conf.color_theme.prompt(conf.prompt)
341*7dc08ffcSJunyu Lai    except:
342*7dc08ffcSJunyu Lai        pass
343*7dc08ffcSJunyu Lai    try:
344*7dc08ffcSJunyu Lai        apply_ipython_style(get_ipython())
345*7dc08ffcSJunyu Lai    except NameError:
346*7dc08ffcSJunyu Lai        pass
347*7dc08ffcSJunyu Lai
348*7dc08ffcSJunyu Laiclass Conf(ConfClass):
349*7dc08ffcSJunyu Lai    """This object contains the configuration of Scapy.
350*7dc08ffcSJunyu Laisession  : filename where the session will be saved
351*7dc08ffcSJunyu Laiinteractive_shell : can be "ipython", "python" or "auto". Default: Auto
352*7dc08ffcSJunyu Laistealth  : if 1, prevents any unwanted packet to go out (ARP, DNS, ...)
353*7dc08ffcSJunyu LaicheckIPID: if 0, doesn't check that IPID matches between IP sent and ICMP IP citation received
354*7dc08ffcSJunyu Lai           if 1, checks that they either are equal or byte swapped equals (bug in some IP stacks)
355*7dc08ffcSJunyu Lai           if 2, strictly checks that they are equals
356*7dc08ffcSJunyu LaicheckIPsrc: if 1, checks IP src in IP and ICMP IP citation match (bug in some NAT stacks)
357*7dc08ffcSJunyu LaicheckIPinIP: if True, checks that IP-in-IP layers match. If False, do not
358*7dc08ffcSJunyu Lai             check IP layers that encapsulates another IP layer
359*7dc08ffcSJunyu Laicheck_TCPerror_seqack: if 1, also check that TCP seq and ack match the ones in ICMP citation
360*7dc08ffcSJunyu Laiiff      : selects the default output interface for srp() and sendp(). default:"eth0")
361*7dc08ffcSJunyu Laiverb     : level of verbosity, from 0 (almost mute) to 3 (verbose)
362*7dc08ffcSJunyu Laipromisc  : default mode for listening socket (to get answers if you spoof on a lan)
363*7dc08ffcSJunyu Laisniff_promisc : default mode for sniff()
364*7dc08ffcSJunyu Laifilter   : bpf filter added to every sniffing socket to exclude traffic from analysis
365*7dc08ffcSJunyu Laihistfile : history file
366*7dc08ffcSJunyu Laipadding  : includes padding in disassembled packets
367*7dc08ffcSJunyu Laiexcept_filter : BPF filter for packets to ignore
368*7dc08ffcSJunyu Laidebug_match : when 1, store received packet that are not matched into debug.recv
369*7dc08ffcSJunyu Lairoute    : holds the Scapy routing table and provides methods to manipulate it
370*7dc08ffcSJunyu Laiwarning_threshold : how much time between warnings from the same place
371*7dc08ffcSJunyu LaiASN1_default_codec: Codec used by default for ASN1 objects
372*7dc08ffcSJunyu Laimib      : holds MIB direct access dictionary
373*7dc08ffcSJunyu Lairesolve  : holds list of fields for which resolution should be done
374*7dc08ffcSJunyu Lainoenum   : holds list of enum fields for which conversion to string should NOT be done
375*7dc08ffcSJunyu LaiAS_resolver: choose the AS resolver class to use
376*7dc08ffcSJunyu Laiextensions_paths: path or list of paths where extensions are to be looked for
377*7dc08ffcSJunyu Laicontribs : a dict which can be used by contrib layers to store local configuration
378*7dc08ffcSJunyu Laidebug_tls:When 1, print some TLS session secrets when they are computed.
379*7dc08ffcSJunyu Lai"""
380*7dc08ffcSJunyu Lai    version = VERSION
381*7dc08ffcSJunyu Lai    session = ""
382*7dc08ffcSJunyu Lai    interactive = False
383*7dc08ffcSJunyu Lai    interactive_shell = ""
384*7dc08ffcSJunyu Lai    stealth = "not implemented"
385*7dc08ffcSJunyu Lai    iface = None
386*7dc08ffcSJunyu Lai    iface6 = None
387*7dc08ffcSJunyu Lai    layers = LayersList()
388*7dc08ffcSJunyu Lai    commands = CommandsList()
389*7dc08ffcSJunyu Lai    logLevel = LogLevel()
390*7dc08ffcSJunyu Lai    checkIPID = 0
391*7dc08ffcSJunyu Lai    checkIPsrc = 1
392*7dc08ffcSJunyu Lai    checkIPaddr = 1
393*7dc08ffcSJunyu Lai    checkIPinIP = True
394*7dc08ffcSJunyu Lai    check_TCPerror_seqack = 0
395*7dc08ffcSJunyu Lai    verb = 2
396*7dc08ffcSJunyu Lai    prompt = Interceptor("prompt", ">>> ", _prompt_changer)
397*7dc08ffcSJunyu Lai    promisc = 1
398*7dc08ffcSJunyu Lai    sniff_promisc = 1
399*7dc08ffcSJunyu Lai    raw_layer = None
400*7dc08ffcSJunyu Lai    raw_summary = False
401*7dc08ffcSJunyu Lai    default_l2 = None
402*7dc08ffcSJunyu Lai    l2types = Num2Layer()
403*7dc08ffcSJunyu Lai    l3types = Num2Layer()
404*7dc08ffcSJunyu Lai    L3socket = None
405*7dc08ffcSJunyu Lai    L2socket = None
406*7dc08ffcSJunyu Lai    L2listen = None
407*7dc08ffcSJunyu Lai    BTsocket = None
408*7dc08ffcSJunyu Lai    min_pkt_size = 60
409*7dc08ffcSJunyu Lai    histfile = os.getenv('SCAPY_HISTFILE',
410*7dc08ffcSJunyu Lai                         os.path.join(os.path.expanduser("~"),
411*7dc08ffcSJunyu Lai                                      ".scapy_history"))
412*7dc08ffcSJunyu Lai    padding = 1
413*7dc08ffcSJunyu Lai    except_filter = ""
414*7dc08ffcSJunyu Lai    debug_match = 0
415*7dc08ffcSJunyu Lai    debug_tls = 0
416*7dc08ffcSJunyu Lai    wepkey = ""
417*7dc08ffcSJunyu Lai    cache_iflist = {}
418*7dc08ffcSJunyu Lai    cache_ipaddrs = {}
419*7dc08ffcSJunyu Lai    route = None # Filed by route.py
420*7dc08ffcSJunyu Lai    route6 = None # Filed by route6.py
421*7dc08ffcSJunyu Lai    auto_fragment = 1
422*7dc08ffcSJunyu Lai    debug_dissector = 0
423*7dc08ffcSJunyu Lai    color_theme = Interceptor("color_theme", NoTheme(), _prompt_changer)
424*7dc08ffcSJunyu Lai    warning_threshold = 5
425*7dc08ffcSJunyu Lai    warning_next_only_once = False
426*7dc08ffcSJunyu Lai    prog = ProgPath()
427*7dc08ffcSJunyu Lai    resolve = Resolve()
428*7dc08ffcSJunyu Lai    noenum = Resolve()
429*7dc08ffcSJunyu Lai    emph = Emphasize()
430*7dc08ffcSJunyu Lai    use_pypy = isPyPy()
431*7dc08ffcSJunyu Lai    use_pcap = os.getenv("SCAPY_USE_PCAPDNET", "").lower().startswith("y")
432*7dc08ffcSJunyu Lai    use_dnet = os.getenv("SCAPY_USE_PCAPDNET", "").lower().startswith("y")
433*7dc08ffcSJunyu Lai    use_bpf = False
434*7dc08ffcSJunyu Lai    use_winpcapy = False
435*7dc08ffcSJunyu Lai    use_npcap = False
436*7dc08ffcSJunyu Lai    ipv6_enabled = socket.has_ipv6
437*7dc08ffcSJunyu Lai    ethertypes = ETHER_TYPES
438*7dc08ffcSJunyu Lai    protocols = IP_PROTOS
439*7dc08ffcSJunyu Lai    services_tcp = TCP_SERVICES
440*7dc08ffcSJunyu Lai    services_udp = UDP_SERVICES
441*7dc08ffcSJunyu Lai    extensions_paths = "."
442*7dc08ffcSJunyu Lai    manufdb = MANUFDB
443*7dc08ffcSJunyu Lai    stats_classic_protocols = []
444*7dc08ffcSJunyu Lai    stats_dot11_protocols = []
445*7dc08ffcSJunyu Lai    temp_files = []
446*7dc08ffcSJunyu Lai    netcache = NetCache()
447*7dc08ffcSJunyu Lai    geoip_city = '/usr/share/GeoIP/GeoIPCity.dat'
448*7dc08ffcSJunyu Lai    geoip_city_ipv6 = '/usr/share/GeoIP/GeoIPCityv6.dat'
449*7dc08ffcSJunyu Lai    load_layers = ["l2", "inet", "dhcp", "dns", "dot11", "gprs",
450*7dc08ffcSJunyu Lai                   "hsrp", "inet6", "ir", "isakmp", "l2tp", "mgcp",
451*7dc08ffcSJunyu Lai                   "mobileip", "netbios", "netflow", "ntp", "ppp", "pptp",
452*7dc08ffcSJunyu Lai                   "radius", "rip", "rtp", "skinny", "smb", "snmp",
453*7dc08ffcSJunyu Lai                   "tftp", "x509", "bluetooth", "dhcp6", "llmnr",
454*7dc08ffcSJunyu Lai                   "sctp", "vrrp", "ipsec", "lltd", "vxlan", "eap"]
455*7dc08ffcSJunyu Lai    contribs = dict()
456*7dc08ffcSJunyu Lai    crypto_valid = isCryptographyValid()
457*7dc08ffcSJunyu Lai    crypto_valid_advanced = isCryptographyAdvanced()
458*7dc08ffcSJunyu Lai    fancy_prompt = True
459*7dc08ffcSJunyu Lai
460*7dc08ffcSJunyu Lai
461*7dc08ffcSJunyu Laiif not Conf.ipv6_enabled:
462*7dc08ffcSJunyu Lai    log_scapy.warning("IPv6 support disabled in Python. Cannot load Scapy IPv6 layers.")
463*7dc08ffcSJunyu Lai    for m in ["inet6","dhcp6"]:
464*7dc08ffcSJunyu Lai        if m in Conf.load_layers:
465*7dc08ffcSJunyu Lai            Conf.load_layers.remove(m)
466*7dc08ffcSJunyu Lai
467*7dc08ffcSJunyu Laiif not Conf.crypto_valid:
468*7dc08ffcSJunyu Lai    log_scapy.warning("Crypto-related methods disabled for IPsec, Dot11 "
469*7dc08ffcSJunyu Lai                      "and TLS layers (needs python-cryptography v1.7+).")
470*7dc08ffcSJunyu Lai
471*7dc08ffcSJunyu Laiconf=Conf()
472*7dc08ffcSJunyu Laiconf.logLevel=30 # 30=Warning
473*7dc08ffcSJunyu Lai
474*7dc08ffcSJunyu Lai
475*7dc08ffcSJunyu Laidef crypto_validator(func):
476*7dc08ffcSJunyu Lai    """
477*7dc08ffcSJunyu Lai    This a decorator to be used for any method relying on the cryptography library.
478*7dc08ffcSJunyu Lai    Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'.
479*7dc08ffcSJunyu Lai    """
480*7dc08ffcSJunyu Lai    def func_in(*args, **kwargs):
481*7dc08ffcSJunyu Lai        if not conf.crypto_valid:
482*7dc08ffcSJunyu Lai            raise ImportError("Cannot execute crypto-related method! "
483*7dc08ffcSJunyu Lai                              "Please install python-cryptography v1.7 or later.")
484*7dc08ffcSJunyu Lai        return func(*args, **kwargs)
485*7dc08ffcSJunyu Lai    return func_in
486