Пример #1
0
    def read(self, path):
        """Reads a `Template` from disk.

        Parameters
        ----------
        path: str
            Path from which the template will be read.

        """
        with open(path) as t:
            template = json.load(t)
        # Reading layers
        self._name = template['Name']
        self._version = template['Version']
        self._timestamp = template['Timestamp']
        self._description = template['Description']
        self._raw = template['raw']
        self._functions = template['Functions']
        for layer in template['layers']:
            l = TLayer(layer['name'],
                       raw=self._raw,
                       lslice=layer['lslice'],
                       custom=layer['custom'])
            # Reading the structs
            structs = layer["structs"]
            # Reading fields
            for field in layer['fields']:
                ftype = field['type']
                if ftype[0] == str(int):
                    ftype = (int, ftype[1])
                elif ftype[0] == str(str):
                    ftype = (str, ftype[1])
                elif ftype[0] == str(bytes):
                    ftype = (bytes, ftype[1])
                f = TField(name=field['name'],
                           value=bytearray.fromhex(field['value']),
                           raw=self._raw,
                           tslice=field['slice'],
                           custom=field['custom'],
                           size=field['size'],
                           ftype=ftype,
                           frepr=field['frepr'])
                f.layer = l
                l.addfield(f)
            # Initialization of the structs
            for f in structs:
                l.add_struct(f, structs[f]['fdeps'], structs[f]['sb'],
                             structs[f]['exp'])
            self.addlayer(l)
Пример #2
0
 def _tsharkfields(self, tshark_pkt, layer, scapy_pkt, fields_slices,
                   tlayer):
     """Returns the layers of a pyshark package."""
     raw = bytes(scapy_pkt)
     for sl in fields_slices:
         # Obtain the tshark repr of the field
         field = layer.get_field(sl[0])
         frepr = layer.get_field_value(sl[0])
         # Extract the type of the field
         if field.isdecimal():
             frepr = int(frepr)
             ftype = (int, 'big')
         else:
             frepr = str(frepr)
             ftype = (str, None)
         # Initialization of the tfield
         field = TField(name="_".join(sl[0].split('.')[1:]),
                        value=raw[sl[1]],
                        raw=raw.hex(),
                        tslice=str(sl[1]).encode().hex(),
                        custom=True,
                        size=sl[1].stop - sl[1].start,
                        ftype=ftype,
                        frepr=frepr,
                        layer=tlayer)
         yield field
Пример #3
0
 def _scapyfields(self, layer, offset, spkt, tlayer):
     """Generates template fields for a given scapy layer."""
     fdissect = self._dissect_fields(layer, offset)
     raw = bytes(spkt)
     for f in layer.fields_desc:
         # Obtain the scapy repr of the field
         frepr = layer.getfieldval(f.name)
         # Extract the type of the field
         if type(frepr) is int:
             ftype = (int, 'big')
         else:
             frepr = str(frepr)
             ftype = (str, None)
         # Initialization of the field
         field = TField(name=str(f.name),
                        value=raw[eval(fdissect[f.name])],
                        raw=raw.hex(),
                        tslice=fdissect[f.name].encode().hex(),
                        custom=False,
                        size=eval(fdissect[f.name]).stop -
                        eval(fdissect[f.name]).start,
                        frepr=frepr,
                        ftype=ftype,
                        layer=tlayer)
         yield field
Пример #4
0
 def _get_tlayer_fields(self, tshark_layer, tlayer, pkt_raw):
     """Generates template fields for a given tshark layer."""
     tshark_fields = self._traverse_fields(tshark_layer._all_fields)
     for tname, tvalue in tshark_fields.items():
         # Building the TField
         tfield = TField(
             fname=tname,
             fslice=slice(tvalue[2], tvalue[2]+tvalue[3]),
             fsize=tvalue[3],
             pkt_raw=pkt_raw,
             trepr=tvalue[0],
             ttype=tvalue[5],
             tmask=tvalue[4],
             layer=tlayer)
         yield tfield
Пример #5
0
    def read(self, path):
        """Reads a `Template` from disk.

        Parameters
        ----------
        path: str
            Path from which the template will be read.

        """
        with open(path) as t:
            template = json.load(t)
        # Reading and loading the template
        self._name = template['Name']
        self._version = template['Version']
        self._timestamp = template['Timestamp']
        self._description = template['Description']
        self._raw = bytes.fromhex(template['raw'])
        self._functions = template['Functions']
        # Reading and loading the layers
        for layer in template['layers']:
            l = TLayer(layer['name'], pkt_raw=self._raw,
                       lslice=eval(layer['lslice']))
            # Reading the structs
            structs = layer["structs"]
            # Reading and loading the fields
            for field in layer['fields']:
                f = TField(fname=field['name'],
                           fslice=eval(field['slice']),
                           fsize=field['size'],
                           pkt_raw=self._raw,
                           trepr=field['trepr'],
                           ttype=field['ttype'],
                           tmask=field['mask'],
                           layer=l,
                           ftype=Ftype(field['type']),
                           frepr=field['frepr'] if Ftype(field['type']) !=
                           Ftype.FT_BYTES else bytes.fromhex(field['frepr']))
                l.addfield(f)
            # Initialization of the structs
            for f in structs:
                l.add_struct(f, structs[f]['fdeps'],
                             structs[f]['sb'], structs[f]['exp'])
            self.addlayer(l)
Пример #6
0
 def _field(self, command):
     """Manages the access an creation of `TField`."""
     if len(command) == 1:
         Interface.print_help(LayerInterface._field_help())
     elif len(command) == 2 and command[1].lower() in self._l.fieldnames():
         fi = FieldInterface(self._l.getfield(command[1].lower()),
                             self._tindex, self._l.name, self._poisoner)
         fi.run()
     else:
         cp = CommandParser(LayerInterface._field_opts())
         args = cp.parse(command)
         if not args:
             Interface._argument_error()
             return
         # Print the help
         if args["-h"]:
             Interface.print_help(LayerInterface._field_help())
         # Adds a new field
         elif args["-a"]:
             Interface.color_dump(self._l.raw, self._l.slice.start)
             start = input("Start byte of the custom field: ")
             end = input("End byte of the custom field: ")
             if not start.isdecimal() or not end.isdecimal():
                 Interface._print_error(
                     "The start or end byte is not a number")
                 return
             else:
                 fslice = slice(int(start), int(end))
                 fvalue = self._l.raw[fslice]
                 fsize = len(fvalue)
                 new_field = TField(name=args["-a"],
                                    value=fvalue,
                                    tslice=str(fslice).encode().hex(),
                                    custom=True,
                                    size=fsize,
                                    raw=self._l.raw.hex(),
                                    layer=self._l)
                 # Set the type
                 ftype = input("Field type [int/str/bytes/hex]: ")
                 if ftype == "int":
                     new_field.to_int()
                 elif ftype == "str":
                     new_field.to_str()
                 elif ftype == "hex":
                     new_field.to_hex()
                 elif ftype == "bytes":
                     new_field.to_bytes()
                 # Add the field to the layer
                 self._l.addfield(new_field)
                 Interface._print_info("Field %s added to the layer" %
                                       args['-a'])
         # Deletes a field from the layer
         elif args["-d"]:
             del_field = self._l.getfield(args["-d"])
             if del_field:
                 self._l.delfield(del_field)
                 Interface._print_info("Field %s deleted from the layer" %
                                       args["-d"])
             else:
                 Interface._print_error("The field %s is not in the layer" %
                                        args["-d"])