GoodiesHQ

Altered Py Obfuscator

Nov 11th, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.46 KB | None | 0 0
  1. #!/usr/bin/python
  2. # This is not my code. Only added the main() function to make my life easier
  3. # Original URL: https://github.com/lhr0909/PythonObfuscator
  4. import re, os, sys, base64
  5.  
  6. class Obfuscator:
  7.     input_str = ""
  8.     words = dict()
  9.     word_list = []
  10.     output_lines = []
  11.  
  12.     def __init__(self, s):
  13.         self.input_str = s
  14.         self.words = dict()
  15.         self.word_list = []
  16.         self.output_lines = []
  17.  
  18.     def add_terminal(self, m):
  19.         if m.group(1) not in self.words:
  20.             self.words[m.group(1)] = 1
  21.         else:
  22.             self.words[m.group(1)] += 1
  23.         return ""
  24.  
  25.     def simple(self):
  26.         '''
  27.        simplistic version of obfuscating the script by using the exec() command
  28.        would be slow if the script is long and sophisticated
  29.        '''
  30.         #get rid of the Windows Line Breaks (might be optional)
  31.         indent_size = 0
  32.         indent_checked = False
  33.         s = self.input_str.replace("\r\n", "\n").split("\n")
  34.         for i in xrange(len(s)):
  35.             #check indentation (convert spaces to tabs)
  36.             line = s[i]
  37.             if line.startswith(" ") and not indent_checked:
  38.                 while line.startswith(" "):
  39.                     line = line[1:]
  40.                     indent_size += 1
  41.                 indent_checked = True
  42.             if indent_size > 0:
  43.                 line = s[i].replace(" " * indent_size, "\t")
  44.             s[i] = line
  45.             #add words
  46.             regex_terminal =  re.search(r"([A-Za-z0-9_]+)", line)
  47.             while regex_terminal != None:
  48.                 line = re.sub(r"([A-Za-z0-9_]+)", self.add_terminal, line, count=1)
  49.                 regex_terminal = re.search(r"([A-Za-z0-9_]+)", line)
  50.  
  51.  
  52.         #sort words by frequencies
  53.         for (key, value) in self.words.items():
  54.             self.words[key] = value * len(key)
  55.         self.word_list = self.words.keys()
  56.         self.word_list.sort(key=self.words.get)
  57.         self.word_list.reverse()
  58.  
  59.         # put the words to its own slot if the encoding is the same
  60.         last_i = 0
  61.         last_x = 1
  62.         wordLen = len(self.word_list)
  63.         i = 0
  64.         while i < wordLen:
  65.             word = self.word_list[i]
  66.  
  67.             try:
  68.                 x = int("0x" + word, 16)
  69.             except:
  70.                 i += 1
  71.                 continue
  72.  
  73.             if wordLen > x and i != x and x != last_x and i != last_i and self.word_list[i].lower() != self.word_list[x].lower():
  74.                 #print x, i, self.word_list[x], self.word_list[i]
  75.                 temp = self.word_list[i]
  76.                 self.word_list[i] = self.word_list[x]
  77.                 self.word_list[x] = temp
  78.                 #print x, i, self.word_list[x], self.word_list[i]
  79.                 last_x = x
  80.                 last_i = i
  81.                 i = 0
  82.                 continue
  83.             i += 1
  84.  
  85.         #replace words
  86.         for i in xrange(len(s)):
  87.             line = s[i]
  88.             for word in self.word_list:
  89.                 line = re.sub(r"\b" + word + r"\b", hex(self.word_list.index(word))[2:], line)
  90.             s[i] = line
  91.  
  92.         self.output_lines = s[:]
  93.         return "\n".join(s)
  94.  
  95.     def print_word_list(self):
  96.         for word in self.word_list:
  97.             print hex(self.word_list.index(word)), word
  98.  
  99.     def build_simple(self):
  100.         '''
  101.        return a string of obfuscated python script
  102.        '''
  103.         obf_str = base64.b64encode(self.simple())
  104.         words_str = "|".join(self.word_list)
  105.  
  106.         return r"""exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("%s")))(lambda a,b:b[int("0x"+a.group(1),16)],"%s".split("|")))""" % (obf_str, words_str)
  107.  
  108. def main():
  109.     if len(sys.argv) != 3:
  110.         print "Usage:\n\t%s <path_to_file> <output_file>" % sys.argv[0]
  111.         sys.exit(0)
  112.     if not os.path.isfile(sys.argv[1]):
  113.         print "Error:\n\t'%s' is not a file." % sys.argv[1]
  114.     iname   = sys.argv[1]
  115.     oname   = sys.argv[2]
  116.     f       = open(iname, 'r')
  117.     src     = f.read()
  118.     f.close()
  119.     obf     = Obfuscator(src)
  120.     end     = ""
  121.     try:
  122.         end = obf.build_simple()
  123.     except Error as e:
  124.         print "Error:\n\t%s" % str(e)
  125.         raise
  126.     f       = open(oname, "w")
  127.     f.write("#!/usr/bin/python\n")
  128.     f.write(str(end))
  129.     f.close()
  130.     try:
  131.         os.system("chmod +x %s" % oname)
  132.     except:
  133.         print "Could not execute 'chmod +x %s'. Are you root?" % oname
  134.     print "Obfuscated! Saved in '%s'\n\nBe sure to add your imports!" % oname
  135.  
  136. if __name__ == "__main__":
  137.     main()
Add Comment
Please, Sign In to add comment