diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c714b2c --- /dev/null +++ b/.gitignore @@ -0,0 +1,263 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +!bin/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c2790d6 --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# COMFinder + +## IDA plugin for COM + +### 这是一个IDA的插件,依赖于IDAPython,用于查找标记COM组件中函数 + +## 效果图 + +左侧为IDA中效果,右侧对比了ComRaider + +![comfinder](comfinder.png) + +## 原理 + +1. 在IDAPython中通过pywin32的pythoncom获取COM组件中的原型 + +1. 使用独立的程序获取COM组件中原型对应的虚表 + + **特别注意:由于需要加载dll之后获取虚表,所以千万不要用于恶意程序分析** + +## 安装 + +1. 安装IDA的时候,要勾选IDAPython + +1. 用IDAPython的pip,安装pywin32 + + 默认情况下,使用命令:`C:\python27-x64\Scripts\pip.exe install pywin32` + +1. 将bin目录三个文件复制到插件目录 + + 默认情况下,在这个目录:`C:\Program Files\IDA 7.0\plugins` \ No newline at end of file diff --git a/bin/comfinder_x64.exe b/bin/comfinder_x64.exe new file mode 100644 index 0000000..99ab751 Binary files /dev/null and b/bin/comfinder_x64.exe differ diff --git a/bin/comfinder_x86.exe b/bin/comfinder_x86.exe new file mode 100644 index 0000000..94825a5 Binary files /dev/null and b/bin/comfinder_x86.exe differ diff --git a/bin/comhelper.py b/bin/comhelper.py new file mode 100644 index 0000000..37f90b9 --- /dev/null +++ b/bin/comhelper.py @@ -0,0 +1,221 @@ +import os +import sys +import subprocess +import pythoncom +import idaapi +import idautils +import idc + + + +invokekinds = {pythoncom.INVOKE_FUNC: "func", + pythoncom.INVOKE_PROPERTYGET : "get", + pythoncom.INVOKE_PROPERTYPUT : "put", + pythoncom.INVOKE_PROPERTYPUTREF : "put_ref", + } + +vartypes = { + pythoncom.VT_EMPTY: "Empty", + pythoncom.VT_NULL:"NULL", + pythoncom.VT_I2:"Integer_2", + pythoncom.VT_I4:"Integer_4", + pythoncom.VT_R4:"Real_4", + pythoncom.VT_R8:"Real_8", + pythoncom.VT_CY:"CY", + pythoncom.VT_DATE:"Date", + pythoncom.VT_BSTR:"String", + pythoncom.VT_DISPATCH:"IDispatch", + pythoncom.VT_ERROR:"Error", + pythoncom.VT_BOOL:"BOOL", + pythoncom.VT_VARIANT:"Variant", + pythoncom.VT_UNKNOWN:"IUnknown", + pythoncom.VT_DECIMAL:"Decimal", + pythoncom.VT_I1:"Integer_1", + pythoncom.VT_UI1:"Unsigned_integer_1", + pythoncom.VT_UI2:"Unsigned_integer_2", + pythoncom.VT_UI4:"Unsigned_integer_4", + pythoncom.VT_I8:"Integer_8", + pythoncom.VT_UI8:"Unsigned_integer_8", + pythoncom.VT_INT:"Integer", + pythoncom.VT_UINT:"Unsigned_integer", + pythoncom.VT_VOID:"Void", + pythoncom.VT_HRESULT:"HRESULT", + pythoncom.VT_PTR:"Pointer", + pythoncom.VT_SAFEARRAY:"SafeArray", + pythoncom.VT_CARRAY:"C_Array", + pythoncom.VT_USERDEFINED:"User_Defined", + pythoncom.VT_LPSTR:"Pointer_to_string", + pythoncom.VT_LPWSTR:"Pointer_to_Wide_String", + pythoncom.VT_FILETIME:"File_time", + pythoncom.VT_BLOB:"Blob", + pythoncom.VT_STREAM:"IStream", + pythoncom.VT_STORAGE:"IStorage", + pythoncom.VT_STORED_OBJECT:"Stored_object", + pythoncom.VT_STREAMED_OBJECT:"Streamed_object", + pythoncom.VT_BLOB_OBJECT:"Blob_object", + pythoncom.VT_CF:"CF", + pythoncom.VT_CLSID:"CLSID", +} + +type_flags= [ (pythoncom.VT_VECTOR, "Vector"), + (pythoncom.VT_ARRAY, "Array"), + (pythoncom.VT_BYREF, "ByRef"), + (pythoncom.VT_RESERVED, "Reserved"), +] + + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +p_initialized = False + + +class ComHelperResultChooser(idaapi.Choose2): + def __init__(self, title, items, flags=0, width=None, height=None, embedded=False, modal=False): + idaapi.Choose2.__init__( + self, + title, + [ + ["Address", idaapi.Choose2.CHCOL_HEX|10], + ["Function", idaapi.Choose2.CHCOL_PLAIN|25], + ["Parent", idaapi.Choose2.CHCOL_PLAIN|25], + ["Desc", idaapi.Choose2.CHCOL_PLAIN|40], + ], + flags=flags, + width=width, + height=height, + embedded=embedded) + self.items = items + self.selcount = 0 + self.n = len(items) + + def OnClose(self): + return + + def OnSelectLine(self, n): + self.selcount += 1 + idc.Jump(self.items[n][0]) + + def OnGetLine(self, n): + res = self.items[n] + res = [idc.atoa(res[0]), res[1], res[2], res[3]] + return res + + def OnGetSize(self): + n = len(self.items) + return n + + def show(self): + return self.Show() >= 0 + +#-------------------------------------------------------------------------- +# Plugin +#-------------------------------------------------------------------------- +class Comhelper_Plugin_t(idaapi.plugin_t): + comment = "Comhelper plugin for IDA Pro" + help = "Comhelper" + wanted_name = "Comhelper" + wanted_hotkey = "Shift-Alt-C" + flags = idaapi.PLUGIN_KEEP + + + def init(self): + global p_initialized + if p_initialized is False: + p_initialized = True + idaapi.register_action(idaapi.action_desc_t( + "Comhelper", + "Comhelper", + self.search, + None, + None, + 0)) + print("=" * 80) + print("Comhelper search shortcut key is "+self.wanted_hotkey) + print("=" * 80) + + return idaapi.PLUGIN_KEEP + + def term(self): + pass + + + def get_com_vas(self,dllpath,clsid,iid,count): + if idaapi.get_inf_structure().is_64bit(): + toolname = 'comfinder_x64.exe' + else: + toolname = 'comfinder_x86.exe' + toolpath = os.path.join(BASE_DIR,toolname) + try: + ret = subprocess.check_output([toolpath,dllpath,clsid,iid,count]) + except subprocess.CalledProcessError,e : + return ['LoadDll fail','GetProc fail','GetClass fail','CreateInstance fail'][e.returncode+1] + vas = [] + imagebase = ida_nalt.get_imagebase() + + for rvahex in ret.split('\n'): + rvahex = rvahex.strip() + if rvahex: + vas.append(int(rvahex,16)+imagebase) + return vas + + def search(self): + + exports = set([info[3] for info in idautils.Entries()]) + comexports = set(['DllUnregisterServer', 'DllEntryPoint', 'DllGetClassObject', 'DllCanUnloadNow', 'DllRegisterServer']) + dllpath = ida_nalt.get_input_file_path() + if not comexports.issubset(exports): + print('{} is not COM!'.format(dllpath)) + return + try: + tlb = pythoncom.LoadTypeLib(dllpath) + except: + print('{} is not COM!'.format(dllpath)) + return + classes = {} + + for i in range(tlb.GetTypeInfoCount()): + if tlb.GetTypeInfoType(i) == pythoncom.TKIND_COCLASS: + classes[tlb.GetDocumentation(i)[0]] = str(tlb.GetTypeInfo(i).GetTypeAttr().iid) + values = [] + for i in range(tlb.GetTypeInfoCount()): + if tlb.GetTypeInfoType(i) in [pythoncom.TKIND_DISPATCH,pythoncom.TKIND_INTERFACE]: + typeinfo = tlb.GetTypeInfo(i) + attr = typeinfo.GetTypeAttr() + name = tlb.GetDocumentation(i)[0] + iid = str(attr.iid) + clsid = classes.get(name[1:],None) + if clsid: + vas = self.get_com_vas(dllpath,clsid,iid,str(attr.cFuncs)) + if isinstance(vas,str): + print(vas) + else: + for findex in range(attr.cFuncs): + fundesc = typeinfo.GetFuncDesc(findex) + funnames = typeinfo.GetNames(fundesc.memid) + funname_ext = "{}_{}_{}".format(name,funnames[0],invokekinds[fundesc.invkind]) + + typ, flags, default = fundesc.rettype + desc = '' + if fundesc.invkind == pythoncom.INVOKE_FUNC: + desc += vartypes.get(typ,'UNKNOWN')+' (' + argi = 1 + for argdesc in fundesc.args: + typ, flags, default = argdesc + desc += '{} {}'.format(vartypes.get(typ,'UNKNOWN'),funnames[argi]) + if default is not None: + desc+='={}'.format(default) + desc += ' ,' + argi+=1 + desc += ')' + idaapi.set_name(vas[findex], funname_ext) + values.append([vas[findex],funname_ext,name,desc]) + ComHelperResultChooser("Comhelper",values).show() + + + + def run(self, arg): + self.search() + + +# register IDA plugin +def PLUGIN_ENTRY(): + return Comhelper_Plugin_t() diff --git a/comfinder.png b/comfinder.png new file mode 100644 index 0000000..95b0de9 Binary files /dev/null and b/comfinder.png differ diff --git a/comfinder.sln b/comfinder.sln new file mode 100644 index 0000000..9940023 --- /dev/null +++ b/comfinder.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27428.2011 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "comfinder", "comfinder\comfinder.vcxproj", "{54F62D4B-EB14-4B38-8211-A880FD39040C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Debug|x64.ActiveCfg = Debug|x64 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Debug|x64.Build.0 = Debug|x64 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Debug|x86.ActiveCfg = Debug|Win32 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Debug|x86.Build.0 = Debug|Win32 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Release|x64.ActiveCfg = Release|x64 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Release|x64.Build.0 = Release|x64 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Release|x86.ActiveCfg = Release|Win32 + {54F62D4B-EB14-4B38-8211-A880FD39040C}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3C59A952-D159-447E-9B17-094AB85F1447} + EndGlobalSection +EndGlobal diff --git a/comfinder/comfinder.cpp b/comfinder/comfinder.cpp new file mode 100644 index 0000000..63275e6 Binary files /dev/null and b/comfinder/comfinder.cpp differ diff --git a/comfinder/comfinder.vcxproj b/comfinder/comfinder.vcxproj new file mode 100644 index 0000000..9b9e52a --- /dev/null +++ b/comfinder/comfinder.vcxproj @@ -0,0 +1,169 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {54F62D4B-EB14-4B38-8211-A880FD39040C} + Win32Proj + comfinder + 10.0.16299.0 + + + + Application + true + v141 + MultiByte + + + Application + false + v141 + true + Unicode + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + false + + + false + false + + + + Use + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + Use + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + false + + + + + Use + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + MultiThreaded + + + Console + true + true + false + + + + + + + + + + Create + Create + Create + Create + + + + + + \ No newline at end of file diff --git a/comfinder/comfinder.vcxproj.filters b/comfinder/comfinder.vcxproj.filters new file mode 100644 index 0000000..ef51f60 --- /dev/null +++ b/comfinder/comfinder.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + 头文件 + + + 头文件 + + + + + 源文件 + + + 源文件 + + + \ No newline at end of file diff --git a/comfinder/comhelper.py b/comfinder/comhelper.py new file mode 100644 index 0000000..37f90b9 --- /dev/null +++ b/comfinder/comhelper.py @@ -0,0 +1,221 @@ +import os +import sys +import subprocess +import pythoncom +import idaapi +import idautils +import idc + + + +invokekinds = {pythoncom.INVOKE_FUNC: "func", + pythoncom.INVOKE_PROPERTYGET : "get", + pythoncom.INVOKE_PROPERTYPUT : "put", + pythoncom.INVOKE_PROPERTYPUTREF : "put_ref", + } + +vartypes = { + pythoncom.VT_EMPTY: "Empty", + pythoncom.VT_NULL:"NULL", + pythoncom.VT_I2:"Integer_2", + pythoncom.VT_I4:"Integer_4", + pythoncom.VT_R4:"Real_4", + pythoncom.VT_R8:"Real_8", + pythoncom.VT_CY:"CY", + pythoncom.VT_DATE:"Date", + pythoncom.VT_BSTR:"String", + pythoncom.VT_DISPATCH:"IDispatch", + pythoncom.VT_ERROR:"Error", + pythoncom.VT_BOOL:"BOOL", + pythoncom.VT_VARIANT:"Variant", + pythoncom.VT_UNKNOWN:"IUnknown", + pythoncom.VT_DECIMAL:"Decimal", + pythoncom.VT_I1:"Integer_1", + pythoncom.VT_UI1:"Unsigned_integer_1", + pythoncom.VT_UI2:"Unsigned_integer_2", + pythoncom.VT_UI4:"Unsigned_integer_4", + pythoncom.VT_I8:"Integer_8", + pythoncom.VT_UI8:"Unsigned_integer_8", + pythoncom.VT_INT:"Integer", + pythoncom.VT_UINT:"Unsigned_integer", + pythoncom.VT_VOID:"Void", + pythoncom.VT_HRESULT:"HRESULT", + pythoncom.VT_PTR:"Pointer", + pythoncom.VT_SAFEARRAY:"SafeArray", + pythoncom.VT_CARRAY:"C_Array", + pythoncom.VT_USERDEFINED:"User_Defined", + pythoncom.VT_LPSTR:"Pointer_to_string", + pythoncom.VT_LPWSTR:"Pointer_to_Wide_String", + pythoncom.VT_FILETIME:"File_time", + pythoncom.VT_BLOB:"Blob", + pythoncom.VT_STREAM:"IStream", + pythoncom.VT_STORAGE:"IStorage", + pythoncom.VT_STORED_OBJECT:"Stored_object", + pythoncom.VT_STREAMED_OBJECT:"Streamed_object", + pythoncom.VT_BLOB_OBJECT:"Blob_object", + pythoncom.VT_CF:"CF", + pythoncom.VT_CLSID:"CLSID", +} + +type_flags= [ (pythoncom.VT_VECTOR, "Vector"), + (pythoncom.VT_ARRAY, "Array"), + (pythoncom.VT_BYREF, "ByRef"), + (pythoncom.VT_RESERVED, "Reserved"), +] + + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +p_initialized = False + + +class ComHelperResultChooser(idaapi.Choose2): + def __init__(self, title, items, flags=0, width=None, height=None, embedded=False, modal=False): + idaapi.Choose2.__init__( + self, + title, + [ + ["Address", idaapi.Choose2.CHCOL_HEX|10], + ["Function", idaapi.Choose2.CHCOL_PLAIN|25], + ["Parent", idaapi.Choose2.CHCOL_PLAIN|25], + ["Desc", idaapi.Choose2.CHCOL_PLAIN|40], + ], + flags=flags, + width=width, + height=height, + embedded=embedded) + self.items = items + self.selcount = 0 + self.n = len(items) + + def OnClose(self): + return + + def OnSelectLine(self, n): + self.selcount += 1 + idc.Jump(self.items[n][0]) + + def OnGetLine(self, n): + res = self.items[n] + res = [idc.atoa(res[0]), res[1], res[2], res[3]] + return res + + def OnGetSize(self): + n = len(self.items) + return n + + def show(self): + return self.Show() >= 0 + +#-------------------------------------------------------------------------- +# Plugin +#-------------------------------------------------------------------------- +class Comhelper_Plugin_t(idaapi.plugin_t): + comment = "Comhelper plugin for IDA Pro" + help = "Comhelper" + wanted_name = "Comhelper" + wanted_hotkey = "Shift-Alt-C" + flags = idaapi.PLUGIN_KEEP + + + def init(self): + global p_initialized + if p_initialized is False: + p_initialized = True + idaapi.register_action(idaapi.action_desc_t( + "Comhelper", + "Comhelper", + self.search, + None, + None, + 0)) + print("=" * 80) + print("Comhelper search shortcut key is "+self.wanted_hotkey) + print("=" * 80) + + return idaapi.PLUGIN_KEEP + + def term(self): + pass + + + def get_com_vas(self,dllpath,clsid,iid,count): + if idaapi.get_inf_structure().is_64bit(): + toolname = 'comfinder_x64.exe' + else: + toolname = 'comfinder_x86.exe' + toolpath = os.path.join(BASE_DIR,toolname) + try: + ret = subprocess.check_output([toolpath,dllpath,clsid,iid,count]) + except subprocess.CalledProcessError,e : + return ['LoadDll fail','GetProc fail','GetClass fail','CreateInstance fail'][e.returncode+1] + vas = [] + imagebase = ida_nalt.get_imagebase() + + for rvahex in ret.split('\n'): + rvahex = rvahex.strip() + if rvahex: + vas.append(int(rvahex,16)+imagebase) + return vas + + def search(self): + + exports = set([info[3] for info in idautils.Entries()]) + comexports = set(['DllUnregisterServer', 'DllEntryPoint', 'DllGetClassObject', 'DllCanUnloadNow', 'DllRegisterServer']) + dllpath = ida_nalt.get_input_file_path() + if not comexports.issubset(exports): + print('{} is not COM!'.format(dllpath)) + return + try: + tlb = pythoncom.LoadTypeLib(dllpath) + except: + print('{} is not COM!'.format(dllpath)) + return + classes = {} + + for i in range(tlb.GetTypeInfoCount()): + if tlb.GetTypeInfoType(i) == pythoncom.TKIND_COCLASS: + classes[tlb.GetDocumentation(i)[0]] = str(tlb.GetTypeInfo(i).GetTypeAttr().iid) + values = [] + for i in range(tlb.GetTypeInfoCount()): + if tlb.GetTypeInfoType(i) in [pythoncom.TKIND_DISPATCH,pythoncom.TKIND_INTERFACE]: + typeinfo = tlb.GetTypeInfo(i) + attr = typeinfo.GetTypeAttr() + name = tlb.GetDocumentation(i)[0] + iid = str(attr.iid) + clsid = classes.get(name[1:],None) + if clsid: + vas = self.get_com_vas(dllpath,clsid,iid,str(attr.cFuncs)) + if isinstance(vas,str): + print(vas) + else: + for findex in range(attr.cFuncs): + fundesc = typeinfo.GetFuncDesc(findex) + funnames = typeinfo.GetNames(fundesc.memid) + funname_ext = "{}_{}_{}".format(name,funnames[0],invokekinds[fundesc.invkind]) + + typ, flags, default = fundesc.rettype + desc = '' + if fundesc.invkind == pythoncom.INVOKE_FUNC: + desc += vartypes.get(typ,'UNKNOWN')+' (' + argi = 1 + for argdesc in fundesc.args: + typ, flags, default = argdesc + desc += '{} {}'.format(vartypes.get(typ,'UNKNOWN'),funnames[argi]) + if default is not None: + desc+='={}'.format(default) + desc += ' ,' + argi+=1 + desc += ')' + idaapi.set_name(vas[findex], funname_ext) + values.append([vas[findex],funname_ext,name,desc]) + ComHelperResultChooser("Comhelper",values).show() + + + + def run(self, arg): + self.search() + + +# register IDA plugin +def PLUGIN_ENTRY(): + return Comhelper_Plugin_t() diff --git a/comfinder/stdafx.cpp b/comfinder/stdafx.cpp new file mode 100644 index 0000000..c9d5725 Binary files /dev/null and b/comfinder/stdafx.cpp differ diff --git a/comfinder/stdafx.h b/comfinder/stdafx.h new file mode 100644 index 0000000..03e83c9 Binary files /dev/null and b/comfinder/stdafx.h differ diff --git a/comfinder/targetver.h b/comfinder/targetver.h new file mode 100644 index 0000000..e2da66c Binary files /dev/null and b/comfinder/targetver.h differ