AutoIt脚本的反编译和代码格式化问题分析

最近集中冒出一波AutoIt的恶意脚本来,也就多看了几个这类的样本。AutoIt脚本是以“.au3”为扩展名的明文脚本,但病毒作者自然不会把明文的脚本放出来。所以自然用到了AutoIt自带的这个Au2Exe的工具:

可以看到AutoIt允许用户将au3的明文脚本编译成exe文件或者a3x文件。exe文件自不必赘述,就是我们平时熟悉的PE文件,但如果编译成exe文件,则失去了AutoIt脚本在恶意程序领域的优势(懂的自然懂,不细说),所以目前捕获的大多数恶意样本都是将脚本编译成a3x文件。


网上比较多的是Exe2Au3的反编译工具(据说早期版本的AutoIt是自带这个工具的,后来不带了),但下了几个,都很耿直——真的都只能反编译Exe文件,而对a3x文件表示无力。最后才找到了一个叫做Autoit3 Decompiler GUI的工具(//www.laike.net/softs/390596.html):

用这个工具,就能很简单的将a3x文件反编译成au3的明文脚本了。BUT——为什么万事总有个BUT——反编译出来的脚本看着有些忧桑……

就这代码格式……几十行还可以忍,一两百行已经是上限了……恶意代码动不动几千行,看着脑袋都大啊……本着磨刀不误砍柴工的思想,果断写了一个自动格式化脚本(by Python),贴出来和大家分享下。

说明:对AutoIt了解不多,仅针对我目前见过的脚本,做一个比较粗陋而暴力的格式化工作而已

#!/usr/bin/env python2.7
#-*- coding: utf-8 -*-
 
_AU3 = ';./sample.au3';
_AU3_OUT = ';./format.au3';
_INDENT = '; '; * 4
 
def au3formater(line, indent):
  line = line.strip().lower()
  
  next_indent = indent
  if (line.startswith(';end';) or
    line.startswith(';until';) or 
    line in (';next';, ';wend';)):
    indent -= 1
    next_indent -= 1
  elif line.startswith(';if';) and line.endswith(';then';):
    next_indent += 1
  elif (line.startswith(';func';) or 
     line.startswith(';for';) or 
     line.startswith(';select';) or
     line.startswith(';switch';) or
     line.startswith(';while';) or
     line == ';do';):
    next_indent += 1
  elif line.startswith(';else';) or line.startswith(';case';):
    indent -= 1
  new_line = _INDENT * indent + line
  
  return new_line, next_indent
 
def main():
  with open(_AU3, ';r';) as fp:
    with open(_AU3_OUT, ';w';) as fpw:
      indent = 0
      line = fp.readline()
      while line:
        new_line, indent = au3formater(line, indent)
        fpw.write(';%sn'; % new_line)
        line = fp.readline()
 
if __name__ == ';__main__';:
  main()

格式化完成后,看着就舒服多了(不确定是否是我个人的强迫症而已……):

当然,即便是看着舒服些了,即便是明文脚本,几千行的代码看着也是很忧桑的