Beispiel #1
0
    def execute(self):

        if self.path and whitelisted(self.path):
            return

        ret = {
            'label': self.label,
            'n_deleted': 0,
            'n_special': 1,
            'path': self.path,
            'size': None
        }

        if self.path is None:
            # Function takes no path.  It returns the size.
            func_ret = self.func()
            if isinstance(func_ret, types.GeneratorType):
                # function returned generator
                for func_ret in self.func():
                    if True == func_ret or isinstance(func_ret, tuple):
                        # Return control to GTK idle loop.
                        # If tuple, then display progress.
                        yield func_ret
            # either way, func_ret should be an integer
            assert isinstance(func_ret, (int, long))
            ret['size'] = func_ret
        else:
            if os.path.isdir(self.path):
                raise RuntimeError(
                    'Attempting to run file function %s on directory %s' %
                    (self.func.func_name, self.path))
            # Function takes a path.  We check the size.
            oldsize = file_op.getsize(self.path)

            try:
                self.func(self.path)
            except DatabaseError as e:
                if -1 == e.message.find('file is encrypted or is not a database') and \
                   -1 == e.message.find('or missing database'):
                    raise
                logger().info(e.message)
                return

            try:
                newsize = file_op.getsize(self.path)
            except OSError as e:
                from errno import ENOENT
                if e.errno == ENOENT:
                    # file does not exist
                    newsize = 0
                else:
                    raise

            ret['size'] = oldsize - newsize
Beispiel #2
0
def get_globs_size(paths):
    """Get the cumulative size (in bytes) of a list of globs"""
    total_size = 0

    for path in paths:
        from glob import iglob
        for p in iglob(path):
            total_size += file_op.getsize(p)

    return total_size
Beispiel #3
0
    def scan(self):
        total_size = 0
        action_useful = {"paths": [], "action_key": self.action_key}

        for path in self.get_paths():
            size = file_op.getsize(path)

            action_useful["paths"].append(path)
            total_size += size

        return action_useful, total_size
Beispiel #4
0
    def execute(self, really_delete):
        """Make changes and return results"""

        if whitelisted(self.path):
            yield whitelist(self.path)
            return

        ret = {
            'label': _('Clean file'),
            'n_deleted': 0,
            'n_special': 1,
            'path': self.path,
            'size': None
        }
        if really_delete:
            oldsize = file_op.getsize(self.path)
            file_op.clean_json(self.path, self.address)
            newsize = file_op.getsize(self.path)
            ret['size'] = oldsize - newsize
        yield ret
Beispiel #5
0
    def execute(self):
        """Make changes and return results"""

        if whitelisted(self.path):
            yield whitelist(self.path)
            return

        ret = {
            # TRANSLATORS: Parts of this file will be deleted
            'label': _('Clean file'),
            'n_deleted': 0,
            'n_special': 1,
            'path': self.path,
            'size': None
        }

        oldsize = file_op.getsize(self.path)
        file_op.clean_ini(self.path, self.section, self.parameter)
        newsize = file_op.getsize(self.path)
        ret['size'] = oldsize - newsize
Beispiel #6
0
	def do_upload_virus(self, pathname, oldname):
		if file_op.getsize(pathname) <= constant.MALWARE_FILE_MAX_SIZE:
			sha256 = file_op.sha256_checksum(pathname)
			content = file_op.cat(pathname)

			if sha256 and content:
				sha256 = struct.pack("{}s".format(len(sha256)), sha256.encode("ascii"))
				oldname_len = struct.pack("<I", len(oldname))
				oldname = struct.pack("{}s".format(len(oldname)), oldname.encode("ascii"))

				status, data = net_op.create_http_request(constant.SERVER_URL,
					"POST",
					"/client/virus_upload",
					sha256 + oldname_len + oldname + content)

				return data

		return None
Beispiel #7
0
def run(payload, socket):
	response = {
		"cmd_id" : payload["cmd_id"],
		"session_id" : payload["args"]["session_id"],
		"pair_id" : payload["args"]["pair_id"],
		"size" : -1,
		"error" : ""
	}
	
	path = payload["args"]["path"];
	
	if os.path.exists(path):
		if os.path.isdir(path):
			response["size"] = file_op.getsizedir(path)
		else:
			response["size"] = file_op.getsize(path)
			
		socket.response(response)
Beispiel #8
0
    def execute(self, really_delete):
        """Make changes and return results"""

        if whitelisted(self.path):
            yield whitelist(self.path)
            return

        ret = {
            # TRANSLATORS: The file will be truncated to 0 bytes in length
            'label': _('Truncate'),
            'n_deleted': 1,
            'n_special': 0,
            'path': self.path,
            'size': file_op.getsize(self.path)
        }
        if really_delete:
            f = open(self.path, 'wb')
            f.truncate(0)
        yield ret
Beispiel #9
0
    def handleVirus(self,
                    filepath,
                    virusType=None,
                    level=None,
                    sha256=None,
                    newpath=None,
                    operation=OPERATION_ISOLATE):
        """This function is public,need to strict with args.
		args:
			filepath str  :filepath need to be handled.
			virusType=None:only for scanner.
			level=None	:only for scanner.
			sha256=None   :only for scanner.
			newpath=None  :only for moveto cmd.
			operation=OPERATION_ISOLATE :operation to do.

		return:
			if no error,return None,else,return error string.
		"""
        virus = Kdatabase().get_obj('virus')
        md5 = hashlib.md5()
        md5.update(filepath.encode('utf-8'))
        filename = md5.hexdigest()
        opsTime = '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())

        if operation == OPERATION_ISOLATE:
            # check before isolate
            if not os.path.exists(filepath):
                return "handle:No such file #{}#.".format(filepath)

            description = [
                os.path.split(filepath)[1],
                file_op.md5(filepath),
                file_op.sha1(filepath), sha256,
                Magic().from_file(filepath),
                file_op.getsize(filepath)
            ]

            ret = self.tryIsolateVirus(filepath, filename)

            if ret:
                return ret

            virus['lasttime'] = time_op.now()
            virus['isolateList'][filename] = [
                filepath, virusType, level, description, opsTime,
                OPERATION_ISOLATE
            ]
            virus['allHistory'].append([opsTime, filepath, sha256])

        elif operation == OPERATION_TRUST:
            self.addWhiteList(filepath, False)
            ret = self.moveFromIsolation(filepath, filename)
            if ret:
                return ret

            path, virusType, level, description, x, y = virus[
                'isolateList'].pop(filename)
            virus['handledList'][filename] = [
                filepath, virusType, level, description, opsTime,
                OPERATION_TRUST
            ]

        elif operation == OPERATION_UNTRUST:
            self.delWhiteList(filepath)
            path, virusType, level, description, x, y = virus['handledList'][
                filename]
            virus['untrustList'][filename] = [
                filepath, virusType, level, description, opsTime,
                OPERATION_UNTRUST
            ]

        elif operation == OPERATION_DELETE:
            # if file don't exist,ignore it,so no other errors.
            self.deleteFromIsolation(filepath, filename)
            path, virusType, level, description, x, y = virus[
                'isolateList'].pop(filename)
            virus['handledList'][filename] = [
                filepath, virusType, level, description, opsTime,
                OPERATION_DELETE
            ]

        elif operation == OPERATION_MOVETO:
            x, name = os.path.split(filepath)
            ret = self.moveFromIsolation(os.path.join(newpath, name), filename)
            if ret:
                return ret

            self.addWhiteList(filepath, False)
            path, virusType, level, description, x, y = virus[
                'isolateList'].pop(filename)
            virus['handledList'][filename] = [
                filepath, virusType, level, description, opsTime,
                OPERATION_MOVETO
            ]

        else:
            Klogger().warn("VirusScanner get unknow operation.")
            return "handleVirus:Unknow command."

        Kdatabase().dump('virus')