''' This module uses shannon's Entropy to detect packed malwares ''' import os import math import logging logging.basicConfig(level=logging.DEBUG) import scanmodule def main(): return Entropy() class Entropy(scanmodule.ScanModule): name = 'entropy' def populate(self, path): pass def load(self, path): pass def save(self, path): pass def __compute_score(self, path): return (self.__entropy(path) - 5) * 100 def is_malware(self, path): score = self.__compute_score(path) logging.info('Entropy score for ' + path + ' : ' + str(score)) return score > 75 def evaluate(self, path): ''' Computes an arbitraty score for the given path @ret A sorted list of the form [name, match_in_percent_superior_to_zero] ''' score = self.__compute_score(path) if score > 0: return [['MALWARE', score],] return None def __entropy(self, path): ''' Computes shannon's entropy for the given file @param path Path to the file ''' # Computes the frequency of each byte in the file fsize = max(float(os.path.getsize(path)), 1.0) freq = [0] * 256 with open(path, 'rb') as f: for c in f.read(): freq[ord(c)] += 1 entropy = 0.0 for f in freq: if f: f /= fsize entropy += f * math.log(f, 2) return -entropy