[toc]

使用c语言将x86汇编代码注入到32位程序中

1.用c语言写一个弹出消息框MessageBoxA的程序

  1. 在项目中属性->高级->随机基地址中选择关闭
  2. 代码如下
1
2
3
4
5
6
7
8
#include <windows.h>
#include <stdio.h>
int main(int argc,char**argv)
{
MessageBoxA(NULL,"HellWorld","Text",MB_OK);
getchar();
return 0;
}

3.编译后运行查看结果

2. 用c语言写一个注入x86汇编指令的程序

1.完善Hello,World程序,打印出函数地址与进程pid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <windows.h>
#include <stdio.h>

void Message()
{
MessageBoxA(NULL, "HellWorld", "Text", MB_OK);
}
void AsmMessage(void* addr)
{
__asm {
mov edx, addr //addr is Message() address
call edx
}
}
int main(int argc, char** argv)
{
printf("MessageBoxA address is 0x%p\n", &MessageBoxA);
printf("Message() address is 0x%p\n", &Message);
printf("Current pid is %d\n",GetCurrentProcessId());
AsmMessage(&Message);
MSG msg;
while (GetMessageW(&msg, NULL, NULL, NULL))
{
}
return 0;
}

编译后运行查看结果

2. c语言编写shellcode代码并运行

  1. 运行Message程序查看Pid与函数地址

  2. 将以下三句汇编代码转为汇编指令

1
2
3
mov edx, 0x00411271
call edx
ret
  1. 转为汇编指令后存入字符数组中
1
char AddSunc[] ={0xBA,0x71,0x12,0x41,0x00,0xFF,0xD2,0xC3}; 
  1. 编写完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <windows.h>
#include <stdio.h>

char AddSunc[] ={0xBA,0x71,0x12,0x41,0x00,0xFF,0xD2,0xC3};

void InjectCode(DWORD dwProcId, LPVOID mFunc)
{
HANDLE hProcess, hThread;
LPVOID mFuncAddr, ParamAddr;
DWORD NumberOfByte;

hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcId);
mFuncAddr = VirtualAllocEx(hProcess, NULL, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProcess, mFuncAddr, mFunc, 1024, &NumberOfByte);
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)mFuncAddr, NULL, 0, &NumberOfByte);
WaitForSingleObject(hThread, INFINITE);
VirtualFreeEx(hProcess, mFuncAddr, 1024, MEM_RELEASE);
CloseHandle(hThread);
CloseHandle(hProcess);
}

int main()
{
InjectCode(78224, AddSunc);
return 0;
}
  1. 编译运行后成功注入

使用CE汇编脚本注入代码

1
2
3
4
5
6
7
8
9
10
11
12
13
[ENABLE]
Alloc(newaddr,100)
createThreadAndWait(newaddr)

newaddr:
call 00411271
ret


[DISABLE]
dealloc(newaddr)
//Auto Assembler Commands
//https://wiki.cheatengine.org/index.php?title=Auto_Assembler:Commands