Running scripts from the command line with idascript
来源:互联网 发布:windows系统如何截图 编辑:程序博客网 时间:2024/06/03 19:20
Running scripts from the command line with idascript
In this blog post we are going to demonstrate how the ‘-S’ and ‘-t’ switches (that were introduced in IDA Pro 5.7) can be used to run IDC, Python or other supported scripts from the command line as if they were standlone scripts and how to use the idascript utility
Background
In order to run a script from the command line, IDA Pro needs to know which script to launch. We can specify the script and its argument via the “-S” switch:
idag -Sfirst.idc mydatabase.idb
Or:
idag -S"first.idc arg1 arg2" mydatabase.idb
In case the script does not require a database (for example, it works with the debugger and attaches to existing processes), then IDA Pro will be satisfied with the "-t" (create a temporary database) switch:
idag -S"first.idc arg1 arg2" -t
Where first.idc:
#include <idc.idc>static main(){ Message("Hello world from IDC!\n"); return 0;}
If we run IDA Pro with the following command:
idag -Sfirst.idc -t
We notice two things:
- Nothing is printed in the console window: This is because the message will show in the output window instead:
(It is possible to save all the text in the output window by using theIDALOG environment variable.)
- IDA Pro remains open and does not close: To exit IDA Pro when the script finishes, use Exit() IDC function.
In the following section, we will address those two problems withidascript.idc and idascript.py helper scripts and the idascript utility.
Running scripts from the command line
In order to print to the console window, we will not use IDC / Message() instead we will write to a file and when IDA Pro exits we will display the contents of that file.
Our second attempt with second.idc:
extern g_idcutil_logfile;static LogInit(){ g_idcutil_logfile = fopen("idaout.txt", "w"); if (g_idcutil_logfile == 0) return 0; return 1;}static LogWrite(str){ if (g_idcutil_logfile != 0) return fprintf(g_idcutil_logfile, "%s", str); return -1;}static LogTerm(){ if (g_idcutil_logfile == 0) return; fclose(g_idcutil_logfile); g_idcutil_logfile = 0;}static main(){ LogInit(); // Open log file LogWrite("Hello world from IDC!\n"); // Write to log file LogTerm(); // Close log file Exit(0); // Exit IDA Pro}
Now let us run IDA Pro:
idag -Ssecond.idc -t
and type afterwards:
type idaout.txt
to get the following output:
Hello world from IDC!
To simplify this whole process, we wrote a small win32 command line utility called idascript:
IDAScript 1.0 (c) Hex-Rays - A tool to run IDA Pro scripts from the command lineIt can be used in two modes:a) With a database:idascript database.idb script.(idc|py|...) [arg1 [arg2 [arg3 [...]]]]b) With a temporary database:idascript script.(idc|py|...) [arg1 [arg2 [arg3 [...]]]]
Since we will be using LogInit(), LogTerm(), LogWrite() and other helper functions over and over, we moved those common functions toidascript.idc.
The script first.idc can now be rewritten like this:
#include <idc.idc>#include "idascript.idc"static main(){ InitUtils(); // calls LogInit() Print(("Hello world from IDC!\n")); // Macro that calls LogWrite() Quit(0); // calls LogTerm() following by Exit()}
As for IDAPython, we wrote a small class to redirect all output toidaout.txt:
import sysclass ToFileStdOut(object): def __init__(self): self.outfile = open("idaout.txt", "w") def write(self, text): self.outfile.write(text) def flush(self): self.outfile.flush() def isatty(self): return False def __del__(self): self.outfile.close()sys.stdout = sys.stderr = ToFileStdOut()
Thus, hello.py can be written like this:
import idcimport idascriptprint "Hello world from IDAPython\n"for i in xrange(1, len(idc.ARGV)): print "ARGV[%d]=%s" % (i, idc.ARGV[i])idc.Exit(0)
Sample scripts
Process list
The sample script listprocs.idc will enumerate all processes and display their ID and name:
#include <idc.idc>#include <idascript.idc>static main(){ InitUtils(); LoadDebugger("win32", 0); auto q = GetProcessQty(), i; for (i=0;i<q;i++) Print(("[%08X] %s\n", GetProcessPid(i), GetProcessName(i))); Quit(0);}
Kill process
The killproc.idc script illustrates how to find processes by name and terminate them one by one:
#include <idc.idc>#include "idascript.idc"#include "procutil.idc"static main(){ InitUtils(); // Load the debugger LoadDebugger("win32", 0); // Get parameters if (ARGV.count < 1) QuitMsg(0, "Usage: killproc.idc ProcessName\n"); auto procs = FindProcessByName(ARGV[1]), i; if (procs.count == 0) QuitMsg(-1, "No process(es) with name " + ARGV[1]); for (i=procs.count-1;i>=0;i--) { auto pid = procs[i]; Print(("killing pid: %X\n", pid)); KillProcess(pid); } Quit(0);}
To test the script, let us suppose we have a few instances of notepad.exe we want to kill:
D:\idascript>idascript killproc.idc notepad.exekilling pid: 878killing pid: 14C8D:\idascript>
We used here the “ARGV” variable that contains all the parameters passed to IDA Pro via the -S switch, FindProcessByName() utility function and KillProcess() (check procutil.idc)
The trick behind terminating a process is to attach and call StopDebugger(). The following is an excerpt from procutil.idc utility script:
static KillProcess(pid){ if (!AttachToProcess(pid)) return 0; StopDebugger(); // Terminate the current process // Normally, we should get a PROCESS_EXIT event GetDebuggerEvent(WFNE_SUSP, -1);}
Process information
The procinfo.idc script will display thread count, register information and the command line arguments of the process in question:
#include "idascript.idc"#include "procutil.idc"static DumpProcessInfo(){ // Retrieve command line via Appcall Print(("Command line: %s\n", GetProcessCommandLine())); // Enum modules Print(("Module list:\n------------\n")); auto x; for (x = GetFirstModule();x!=BADADDR;x=GetNextModule(x)) Print(("Module [%08X] [%08X] %s\n", x, GetModuleSize(x), GetModuleName(x))); Print(("\nThread list:\n------------\n")); for (x=GetThreadQty()-1;x>=0;x--) { auto tid = GetThreadId(x); Print(("Thread [%x]\n", tid)); SelectThread(tid); Print((" EIP=%08X ESP=%08X EBP=%08X\n", Eip, Esp, Ebp)); }}static main(){ InitUtils(); // Load the debugger LoadDebugger("win32", 0); // Get parameters if (ARGV.count < 2) QuitMsg(0, "Usage: killproc.idc ProcessName\n"); auto procs = FindProcessByName(ARGV[1]), i; for (i=procs.count-1;i>=0;i--) { auto pid = procs[i]; if (!AttachToProcess(pid)) { Print(("Could not attach to pid=%x\n", pid)); continue; } DumpProcessInfo(); DetachFromProcess(); } Quit(0);}
The function GetProcessCommandLine is implemented (usingAppcall) like this:
static GetProcessCommandLine(){ // Get address of the GetCommandLine API auto e, GetCmdLn = LocByName("kernel32_GetCommandLineA"); if (GetCmdLn == BADADDR) return 0; // Set its prototype for Appcall SetType(GetCmdLn, "char * __stdcall x();"); try { // Retrieve the command line using Appcall return GetCmdLn(); } catch (e) { return 0; }}
Extracting function body
So far we did not really need a specific database to work with. In the following example (funcextract.idc) we will demonstrate how to extract the body of a function from a given database:
#include <idc.idc>#include "idascript.idc"static main(){ InitUtils(); if (ARGV.count < 2) QuitMsg(0, "Usage: funcextract.idc FuncName OutFile"); // Resolve name auto ea = LocByName(ARGV[1]); if (ea == BADADDR) QuitMsg(0, sprintf("Function '%s' not found!", ARGV[1])); // Get function start ea = GetFunctionAttr(ea, FUNCATTR_START); if (ea == BADADDR) QuitMsg(0, "Could not determine function start!\n"); // size = end - start auto sz = GetFunctionAttr(ea, FUNCATTR_END) - ea; auto fp = fopen(ARGV[2], "wb"); if (fp == 0) QuitMsg(-1, "Failed to create output file\n"); savefile(fp, 0, ea, sz); fclose(fp); Print(("Successfully extracted %d byte(s) from '%s'", sz, ARGV[1])); Quit(0);}
To test the script, we use idascript utility and pass a database name:
D:\idascript>idascript ar.idb funcextract.idc start start.binSuccessfully extracted 89 byte(s) from 'start'D:\idascript>
Other ideas
There are other ideas that can be implemented to create useful command line tools:
- Process memory read/write: Check the rwproc.idc script that allows you to read from the process memory to a file or the other way round.
- Associate .IDC with idascript.exe: This allows you to double-click on IDC scripts to run them from the Windows Explorer
- Scriptable debugger: Write scripts to debug a certain process and extract needed information
- …
Installing the idascript utility
Please download idascript and the needed scripts from here and follow these steps:
- Copy idascript.exe to the installation directory of IDA Pro (say %IDA%)
- Add IDA Pro directory to the PATH environment variable
- Copy idascript.idc and procutil.idc to %IDA%\idc
- Copy idascript.py to %IDA%\python
- Optional: Associate *.idc files with idascript.exe
Comments and suggestions are welcome!
- Running scripts from the command line with idascript
- Running the Compiler from the Command Line
- Running DataVision from the Command Line
- Control your scripts with command-line PHP
- Running a command on every machine in your domain from the command line
- Running Your iOS App in the Simulator From The Command Line
- The linux command line--part 4 Writing Shell Scripts
- 1: Command Line Python(Challenge: Working with the Command Line)
- Calling JNI Functions with Java Object Arguments from the Command Line
- Creating a website from the command line
- Event Configuration from the Command Line
- Creating SQL procedures from the command line
- Using the Code Coverage Tools from the Command Line
- Create a new repository on the command line/Push an existing repository from the command line
- Kaldi-Running the example scripts
- IS12 Changing Project Properties from the Command Line
- Import data in a Lookup Definition from the command-line
- Run an Oracle Xellerate Task Scheduler from the Command-Line
- 递推递归练习 K
- Android中的MVP模式及性能优化
- leetcode141~Linked List Cycle
- Map集合的四种遍历方式
- 对Hibernate的理解
- Running scripts from the command line with idascript
- K排列问题[2] (集合动规)
- 初次使用Maven中遇到的问题
- PLSQL Developer 突然启动慢的解决方案
- UVa 11292 Dragon of Loowater 贪心+排序
- vim编辑器显示行号
- Hackerrank World CodeSprint 9 Box Operations
- L2-009. 抢红包
- 【转】 vim swp交换文件的处理