I have been working on a reverse shell (not for malicious uses) and have started to learn how to use the popen function and get the output using stdout. I have started to test it out, and it was working fine, until I tried using the terminal command "ls". Could anyone point out (what I'm assuming is) my error and show me how to fix it?
Here is the code for the C program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
while (1){
char* command = (char *) malloc(15*sizeof(char));
char* output = (char *) malloc(2048);
printf(">> ");
scanf("%s", command);
FILE* cmd = popen(command, "r");
fputs(output, stdout);
pclose(cmd);
if (strlen(output) != 0){
printf("\n%s\n", output);
}
}
}
and here is the code for the input I've provided the program, and it's result:
>> cd /Users/
sh: /Users/: is a directory //output from previous command
>> >> ls //also why did the program print '>>' twice?
>>
Another question: Why did the program print >>
twice?
The code appears to be missing the connection between popen()
(really cmd
) and the output
variable. You could for example use fread()
to read from the cmd
"file" into output
.
Calling scanf("%s", ...)
will scan only one whitespace-separated word at a time. Your program is first running cd
, then on the next iteration it is running /Users/
.
The code is leaking memory by repeatedly allocating buffers command
and output
in the while
loop without free
-ing them.