Example #1
0
 def download_complete(self, location):
     """Called when the file is done downloading, and MD5 has been successfull"""
     logging.debug("Download complete.")
     zippy = ZipFile(location, mode='r')
     extracted_path = os.path.join(self.save_directory,
                                   os.path.basename(location).strip(".zip"))
     zippy.extractall(extracted_path, pwd=self.password)
     bootstrapper_path = os.path.join(
         self.save_directory,
         self.bootstrapper)  #where we will find our bootstrapper
     old_bootstrapper_path = os.path.join(extracted_path, self.bootstrapper)
     if os.path.exists(bootstrapper_path):
         os.chmod(bootstrapper_path, 666)
         os.remove(bootstrapper_path)
     shutil.move(old_bootstrapper_path,
                 self.save_directory)  #move bootstrapper
     os.chmod(bootstrapper_path, stat.S_IRUSR | stat.S_IXUSR)
     bootstrapper_command = r'%s' % bootstrapper_path
     bootstrapper_args = r'"%s" "%s" "%s" "%s"' % (
         os.getpid(), extracted_path, self.app_path, self.postexecute)
     win32api.ShellExecute(0, 'open', bootstrapper_command,
                           bootstrapper_args, "", 5)
     self.complete = 1
     if callable(self.finish_callback):
         self.finish_callback()
Example #2
0
 def download_complete(self, location):
  """Called when the file is done downloading, and MD5 has been successfull"""
  logger.debug("Download complete.")
  zippy = ZipFile(location, mode='r')
  extracted_path = os.path.join(self.save_directory, os.path.basename(location).strip(".zip"))
  zippy.extractall(extracted_path, pwd=self.password)
  bootstrapper_path = os.path.join(self.save_directory, self.bootstrapper) #where we will find our bootstrapper
  old_bootstrapper_path = os.path.join(extracted_path, self.bootstrapper)
  if os.path.exists(bootstrapper_path):
   os.chmod(bootstrapper_path, 666)
   os.remove(bootstrapper_path)
  shutil.move(old_bootstrapper_path, self.save_directory) #move bootstrapper
  os.chmod(bootstrapper_path, stat.S_IRUSR|stat.S_IXUSR)
  if platform.system() == "Windows": 
   bootstrapper_command = r'%s' % bootstrapper_path
   bootstrapper_args = r'"%s" "%s" "%s" "%s"' % (os.getpid(), extracted_path, self.app_path, self.postexecute)
   win32api.ShellExecute(0, 'open', bootstrapper_command, bootstrapper_args, "", 5)
  else:
   #bootstrapper_command = [r'sh "%s" -l "%s" -d "%s" "%s"' % (bootstrapper_path, self.app_path, extracted_path, str(os.getpid()))]
   bootstrapper_command = r'"%s" "%s" "%s" "%s" "%s"' % (bootstrapper_path, os.getpid(), extracted_path, self.app_path, self.postexecute)
   shell = True
   #logging.debug("Final bootstrapper command: %r" % bootstrapper_command)
   subprocess.Popen([bootstrapper_command], shell=shell)
  self.complete = 1
  if callable(self.finish_callback):
   self.finish_callback()
Example #3
0
 def save(self, path):
     """
     Saves the ZipFile to `path`, which can be a file-system path or a
     file-like object.
     """
     zp_out = ZipFile(path, 'w')
     for zp_name in self._namelist:
         zp_out.writestr(zp_name, self.read(zp_name))
     zp_out.close()
def testCode2():
    object = "../processed/VirusShare_00000.zip"
    # opening zipped package
    fd = open(object, 'r')
    zf = ZipFile(fd)
    names = zf.namelist()  # name of compressed files

    lc = Launcher()
    count = 0
    reset = 0
    for filename in names:
        #print(filename)
        data = zf.read(filename, "infected")
        lc.launchFileAnalitics((filename, data))
        reset += 1
        count += 1
        if (reset >= 1000):
            print(str(count) + " processed")
            reset = 0
    print(str(count) + " processed")
Example #5
0
def testCode2():
    object = "../processed/VirusShare_00000.zip"
    # opening zipped package
    fd = open(object, 'r')
    zf = ZipFile(fd)
    names = zf.namelist()  # name of compressed files

    lc = Launcher()
    count = 0
    reset = 0
    for filename in names:
        # print(filename)
        data = zf.read(filename, "infected")
        lc.launchFileAnalitics((filename, data))
        reset += 1
        count += 1
        if(reset >= 1000):
            print(str(count) + " processed")
            reset = 0
    print(str(count) + " processed")
Example #6
0
def testCode2():
    object="../processed/VirusShare_00000.zip"
    #abriendo el paquete zipeado 
    fd=open(object,'r')
    zf= ZipFile(fd)
    names=zf.namelist() #nombre de los archivos comprimidos
    
    lc=Launcher()
    count=0
    reset=0
    for filename in names:
        #print(filename)
        data=zf.read(filename,"infected")
        lc.launchFileAnalitics((filename,data))
        reset+=1
        count+=1
        if(reset>=1000):
            print(str(count)+" procesados")
            reset=0
    print(str(count)+" procesados")
Example #7
0
    def __init__(self, io=None):
        """
        A light wrapper around the python :py:class:`zipfile.ZipFile` that
        enables in-memory modification.

        If `io` is provided, its contents are loaded. `io` may be a file-system
        path or a file-like object.
        """
        self.io = ZipFile(io, 'r') if io else None
        self._cache = {}
        # The ZipFile namelist() appears to re-scan on each call. Keeping track
        # ourselves more than halves iteration times.
        self._namelist = set(self.io.namelist() if io else ())
        self._o_namelist = frozenset(self._namelist)
Example #8
0
    def _find_local(self):
        """
        Use local sources, e.g. input files of URLs and zip files, to import
        malware samples.
        """
        sample_list = list()

        if self.opts.inputfile:
            for inputfile in self.opts.inputfile:
                with open(inputfile, 'rb') as handle:
                    found_samples = process_simple_list(handle.read())
                    if not len(found_samples):
                        logging.warning("Found no samples in local file %r", inputfile)
                    else:
                        logging.info("Found %d samples in local file %r", len(found_samples), inputfile)
                        sample_list.extend(found_samples)

        if self.opts.zip:
            for zip_filename in self.opts.zip:
                handle = ZipFile(zip_filename, 'r')
                found_samples = list()
                for entry in handle.infolist():
                    url = '://'.join([os.path.basename(zip_filename), entry.filename])
                    found_samples.append(
                        Namespace(url=url,
                                  url_sha1=hashstr(url, hashlib.sha1),
                                  _zip_handle=handle,
                                  _zip_filename=entry.filename,
                                  _read=lambda x: zip_tryopen(x._zip_handle, x._zip_filename).read(),
                                  source='zip'))
                if not len(found_samples):
                    logging.warning("Found no samples in local zip file %r", zip_filename)
                else:
                    logging.info("Found %d samples in local file %r", len(found_samples), zip_filename)
                    sample_list.extend(found_samples)

        return sample_list
Example #9
0
 def _unzip_file(self, zip_filepath, unpacked_dir):
     at_least_one_extracted = False
     with contextlib.closing(ZipFile(zip_filepath, 'r')) as zipped_file:
         os.mkdir(unpacked_dir)
         for payload_filename in zipped_file.namelist():
             if self.VALID_PAYLOAD_FILENAME_REGEX.search(payload_filename):
                 zipped_file.extract(member=payload_filename,
                                     path=unpacked_dir,
                                     pwd=self.config['zip_file_password'])
                 at_least_one_extracted = True
                 LOGGER.debug('Payload whose filename is %r -- extracted '
                              'from ZIP archive %r -- into directory %r',
                              payload_filename, zip_filepath, unpacked_dir)
             else:
                 LOGGER.warning('Payload filename: %r - does not match the required '
                                'pattern. Containing ZIP file\'s path: %r',
                                payload_filename, zip_filepath)
     if not at_least_one_extracted:
         raise ValueError(
             'no payload extracted from the {!r} archive (something '
             'wrong with this ZIP file?!)'.format(zip_filepath))
Example #10
0
class EditableZipFile(object):
    def __init__(self, io=None):
        """
        A light wrapper around the python :py:class:`zipfile.ZipFile` that
        enables in-memory modification.

        If `io` is provided, its contents are loaded. `io` may be a file-system
        path or a file-like object.
        """
        self.io = ZipFile(io, 'r') if io else None
        self._cache = {}
        # The ZipFile namelist() appears to re-scan on each call. Keeping track
        # ourselves more than halves iteration times.
        self._namelist = set(self.io.namelist() if io else ())
        self._o_namelist = frozenset(self._namelist)

    @property
    def namelist(self):
        """
        Returns a list of all paths in this ZipFile.
        """
        return self._namelist

    def read(self, path):
        """
        Returns the contents of `path` if it exists, returning `None` if it
        does not.
        """
        if path not in self._namelist:
            return None
        elif path in self._cache:
            return self._cache[path]
        elif self.io and path in self._o_namelist:
            return self.io.read(path)
        return None

    def write(self, path, data):
        """
        Writes `data` to `path`, overwritting any existing content.
        """
        # TODO: Evaluate using tempfile.TemporarySpooledFile to better support
        #       large files.
        self._cache[path] = data
        self._namelist.add(path)

    def save(self, path):
        """
        Saves the ZipFile to `path`, which can be a file-system path or a
        file-like object.
        """
        zp_out = ZipFile(path, 'w')
        for zp_name in self._namelist:
            zp_out.writestr(zp_name, self.read(zp_name))
        zp_out.close()

    def remove(self, path):
        """
        Removes a file from the ZipFile.
        """
        self._namelist.discard(path)
        self._cache.pop(path, None)

    def open(self, path, mode='r'):
        if mode == 'r':
            return StringIO(self.read(path))
        elif mode == 'w':
            out = StringIO()

            class ctx(object):
                def __enter__(self_):
                    return out

                def __exit__(self_, *exc_info):
                    self.write(path, out.getvalue())
                    out.close()

            return ctx()
        else:
            raise ValueError('expected r or w')

        class ctx(object):
            def __enter__(self):
                return self

            def __exit__(self, *exc_info):
                pass

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        """
        Closes the ZipFile and any underlying objects.
        """
        if self.io:
            self.io.close()

    def regex(self, regex):
        """
        Returns an iterator over every path that matches `regex`.
        """
        for p in self._namelist:
            if re.match(regex, p):
                yield p

    def directory_tree(self):
        """
        Returns a (potentially multilevel) dict representing the file
        hierarchy.
        """
        root = {}

        # Sort the paths by depth with the shortest occuring first.
        paths = [p.split('/') for p in self.namelist]
        paths.sort(key=lambda x: len(x))

        for path in paths:
            complete_path = '/'.join(path)

            path_root = root
            while len(path) > 1:
                path_part = path.pop(0)
                path_root = path_root.setdefault(path_part, {})
            path_root[path[0]] = complete_path

        return root

    close = __exit__