前言
写了个Python小工具,突然想到防逆向的问题,写篇小文实践一下。
用PyInstaller打包程序
对有图形界面的程序,最简单的打包就是pyinstaller -F --noconsole xxx.py。
反编译该程序
一个比较经典的工具是pyinstxtractor。
对于Windows中打包的Python应用(python3.9,pyinstaller5.x+),可以直接提取。但对于同配置下MacOS中打包的应用不能提取。下面简单演示如何使用。
首先下载项目代码,将待提取可执行文件置于项目根目录下,以我反编译的项目replacer.exe为例,运行python python_exe_unpack.py -i replacer.exe。
运行后根目录下会出现unpacked目录,其中为抽取出的pyc文件。找到其中的程序入口文件,通常与可执行文件名字相同,或为main等,但也很可能不符合这一规律,所以需要自行确定,这里我的程序入口就是replace。修改抽取出的入口文件名,增加后缀为 replace.pyc。
然后执行uncompyle6 replacer.pyc>replacer.py,反编译pyc文件为源代码。这一步你很可能在反编译出的文件中发现类似Unknown magic number 227 in replacer.pyc的错误,这是因为不同Python版本的pyc文件前缀Magic Number不同,我们需要找到对应版本的Magic Number。一种简单的办法是把抽取出的struct文件,也修改为struct.pyc并对其进行反编译,如果能反编译成功,则将其文件前缀应用到replace.pyc中。
1 | od -c struct.pyc |
再反观replacer.pyc,明显缺少前缀。
1 | od -c replacer.pyc |
于是我们给replacer.pyc加上合适的Magic Number文件前缀,在这里是3 \r \r \n p y i 0 001 001 \0 \0。
1 | vim -b replacer.pyc |
但笔者的MacOS13进行如上操作后依然无法解析,报错struct.error: unpack requires a buffer of 2 bytes,换用Windows后解决,成功反编译出了replacer的源码。
PS:添加前缀后报错:Ill-formed bytecode file replacer.pyc <class 'ValueError'>; bad marshal data (unknown type code)通常也是由于Magic Number不对,对于python3.8及以上版本打包的可执行文件反编译似乎需要使用pycdc,还没验证。笔者测试了3.6、3.8和3.9打包的可执行文件,3.8和3.9均无法通过上述方法反编译,猜测是3.8后续更新导致。
PPS:上述.pyc反编译工具的作者也有点难顶啊😆,另外Pyinstaller的官方文档有时间也应该读一下。
在打包时加密程序
在pyinstaller打包时进行加密,只需要添加参数--key即可,例如pyinstaller -F --noconsole --key 12345 xxx.py。
Windows上使用这个参数需要安装tinyaes(或pycrypto),这个库需要Microsoft Visual C++,还要去安装Microsoft Visual C++ Build Tools。
反编译加密的程序(未实践)
用上面的方法加密后,PYZ-00.pyz_extracted中的文件就被加密了,也就是说仅能反编译出程序入口的源码。
用Cython加密程序
待补充,用Mac磕磕绊绊,丧失兴趣了~
参考
[1] https://zhuanlan.zhihu.com/p/109266820
[2] https://blog.csdn.net/as604049322/article/details/119834495
[3] https://pyinstaller.org/en/stable/advanced-topics.html#inspecting-archives
[4] https://pyinstaller.org/en/stable/advanced-topics.html#inspecting-executables
[5] https://github.com/WithSecureLabs/python-exe-unpacker
[6] https://blog.csdn.net/qq_15969343/article/details/120001351
[7] https://github.com/rocky/python-decompile3
[8] https://github.com/rocky/python-uncompyle6/
[9] https://blog.csdn.net/Zheng__Huang/article/details/112380221
[10] https://blog.csdn.net/weixin_44222568/article/details/111672799
[11] https://www.cnblogs.com/Here-is-SG/p/15885799.html
后记
首发于 silencezheng.top,转载请注明出处。