最近想看看cuckoo里的文件識別功能是怎樣實現的,翻了cuckoo源碼,發現其對文件格式的判斷代碼如下:
def _get_filetype(self, data): """Gets filetype, uses libmagic if available. @param data: data to be analyzed. @return: file type or None. """ if not HAVE_MAGIC: return None try: ms = magic.open(magic.MAGIC_NONE) ms.load() file_type = ms.buffer(data) except: try: file_type = magic.from_buffer(data) except Exception: return None finally: try: ms.close() except: pass return file_type
其中用到了libmagic庫里的magic,libmagic是一個根據文件頭識別文件類型的開發庫,python可以利用該庫很方便地實現對文件格式的判斷。記錄一下安裝過程。安裝環境:winxp + python 2.7
安裝magic 模塊:
1、安裝pycparser-2.14 鏈接: https://pypi.python.org/pypi/pycparser
2、安裝VCForPython,鏈接: http://aka.ms/vcpython27
3、安裝cffi模塊,鏈接: https://pypi.python.org/pypi/cffi/#downloads
4、安裝libmagic 鏈接: https://pypi.python.org/pypi/python-libmagic
5、安裝file,安裝之后向環境變量path添加: ..\GnuWin32\bin
6、安裝magic模塊 鏈接: https://github.com/ahupp/python-magic
測試 import magic成功即可
More details see https://github.com/ahupp/python-magic
利用卡巴斯基的掃描結果對樣本進行分類整理(包含文件類型識別)的程序見:https://github.com/Viwilla/ClassifySamples