#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syslog.h>

/* Code with multiple security bugs:
 * 1 - BoF using getenv with sprintf
 * 2 - Hardcoded path of logfile in /tmp
 * 3 - fopen use with race condition 
 * 4 - Stack overflow due to gets
 * 5 - Static bof due to fixed size buffer
 * 6 - Format string overflow 
 * 7 - Command injection due to misuse of system ()
 */

#define LOGFILE "/tmp/prog.log" /* SECURITY: Hard coded log file location in shared dir */ 

static char cmd[128];
static char format[] = "which %s\n";

FILE *initialize () 
{
	char user[100];
	FILE *log;
	sprintf(user, "%s", getenv("USER")); /* SECURITY: Buffer overflow */
	log = fopen(LOGFILE,"a"); /* SECURITY: Symlink attack possible */
	fprintf(log, "Started by user %s\n", user); /* Note: Should check return value */
	return log; 
}

int main(int argc, char *argv[]) 
{
	char buf[10];
	FILE *logfile;
	logfile = initialize();
	if ( logfile == NULL ) {
		fprintf (stderr, "Cannot use logfile\n");
		exit(1);
	}
	printf ("Which command?: ");
	gets(buf); /* SECURITY: Stack overflow, gets is dangerous */
	sprintf(cmd, format, buf); /* SECURITY: Static buffer overflow */
	fprintf(logfile, "Will execute: %s", cmd);
	syslog(36, cmd); /* SECURITY: Format string overflow */
	printf("You are looking for:\n");
	system(cmd); /*  SECURITY: Command injection, Note: Return value is not checked */ 
	fclose(logfile);
	exit(0);
}
