I just wrote a ping script in C for CGI.
It is working as intended but I am pretty sure that it is not secure because I take the user input for granted.
I do not know if there is a way to stitch a command together so that it is still recognised?
Does somebody know how to exploit my script and how I should fix it?
ping script source
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
printf("Content-Type: text/plain;charset=us-ascii\n\n");
FILE* in = NULL;
char buffer[100][100] = {};
char server[100] = {};
char concat_str[100] = {};
char* ping = "ping ";
char* option = " -c 4";
int print_counter = 0;
int read_counter = 0;
char* query;
query = getenv("QUERY_STRING");
if(query == NULL)
printf("ERROR\n");
else
sscanf(query,"server=%s", server);
strcat(concat_str, ping);
strcat(concat_str, server);
strcat(concat_str, option);
in = popen(concat_str, "r");
if(in == NULL)
{
printf("ERROR\n");
exit(1);
}
while(fgets(buffer[read_counter], 99, in) != NULL)
{
read_counter++;
}
pclose(in);
if(read_counter != 9)
{
printf("ERROR\n");
exit(1);
}
while(print_counter < (read_counter + 1))
{
printf("%s", buffer[print_counter]);
print_counter++;
}
return 0;
}
html source
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="http://xx.xx.xx.xx/ping.cgi">
<div><label>Server<input name="server" size="40"></label></div>
<div><input type="submit" value="start test"></div>
</form>
</body>
</html>
On a related note, is there an easy way to post the source code directly here without manually intending it 4 spaces?
Definitely not secure. The
popen()function passes its argument to a subshell, so shell metacharacters like;could be passed in through the query string to execute an arbitrary command.