示例#1
0
int resolve(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) {
  assert(node != NULL);
  assert(service != NULL);
  assert(res != NULL);

  struct sockaddr_in addr;
  char *dns_query = NULL;
  char *dns_reply = NULL;
  int sock;
  int ret;  
  int query_len;

  // make query packet
  //dns_query = make_dns_query(node, service);
  dns_query = make_dns_query(node, &query_len);
  struct dns_t *tmp = parse_dns(dns_query);
  print_dns(tmp);
  
  // udp socket to dns server
  printf("resolve: send query of %d bytes to dns_ip:%s, dns_port:%d\n", query_len, dns_ip, dns_port);
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  if (inet_aton(dns_ip, &addr.sin_addr) == 0) {
    perror("Error! main, inet_aton");
    exit(-1);
  }
  addr.sin_port = htons(dns_port);
  
  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
    perror("Error! mydns, socket");
    exit(-1);
  }

  // send
  if (sendto(sock, dns_query, query_len, 0, (struct sockaddr *)&addr, sizeof(addr)) != query_len) {
    perror("Error! mydns, sendto, maybe use while");
    exit(-1);
  }

  // recv
  dns_reply = (char *)calloc(BUF_SIZE, sizeof(char));

  ret = recvfrom(sock, dns_reply, BUF_SIZE, 0, NULL, NULL);
  printf("resolve: recvd %s\n", dns_reply);

  if (ret == -1) {
    perror("Error! mydns, recvfrom");
    exit(-1);
  }
  
  // parse it 
  *res = (struct addrinfo *)calloc(1, sizeof(struct addrinfo));
  (*res)->ai_family = AF_INET;
  (*res)->ai_addr = parse_dns_reply(dns_reply);
  (*res)->ai_next = NULL;

  free(dns_reply);
  return 0;
}
示例#2
0
int main() {

  int count = get_qdcount("www.google.com");
  assert(count == 3);
  printf("get_qdcount passed test!\n");

  int query_len;
  char *dns_query = make_dns_query("www.google.com", &query_len);
  
  struct dns_t *query = parse_dns(dns_query);
  print_dns(query);

  return 0;
}
示例#3
0
STAT_FUNC_BEGIN int process_mesg(PKT *pkt)
{
    SDNS_STAT_TRACE();
    assert(pkt);

    /* 解析DNS报文 */
    if (parse_dns(pkt) == RET_ERR) {
        SDNS_STAT_INFO("parse failed");
        return RET_ERR;
    }

    /* 匹配ACL规则 */
    if (pass_acl(pkt) == RET_ERR) {
        char tmp_addr[INET_ADDRSTRLEN];

        inet_ntop(AF_INET, &(pkt->info.src_ip.ip4),
                tmp_addr, INET_ADDRSTRLEN);
        SDNS_STAT_INFO("NOT pass ACL, [%s]", tmp_addr); 
        return RET_ERR;
    }

    /* 查询RR记录 */
    if (query_zone(pkt) == RET_ERR) {
        char tmp_stat_msg[STAT_MSG_LEN];
        snprintf(tmp_stat_msg, sizeof(tmp_stat_msg), 
                "query zone failed, [domain: %s]/[type: %d]/[class: %d]",
                pkt->info.domain, pkt->info.q_type, pkt->info.q_class);
        SDNS_STAT_INFO("%s", tmp_stat_msg);
        return RET_ERR;
    }

    /* 排序算法: DRF + GeoIP */
    if (sort_answer(pkt) == RET_ERR) {
        SDNS_STAT_INFO("sort failed");
        return RET_ERR;
    }

    /* 组装应答报文 */
    if (cons_dns(pkt) == RET_ERR) {
        SDNS_STAT_INFO("cons failed");
        return RET_ERR;
    }

    return RET_OK;
}STAT_FUNC_END
示例#4
0
/****************************************************************************
  main program
****************************************************************************/
int main(int argc,char *argv[])
{
	int opt, i;
	bool correct = true;
	int max_runtime=0;
	int argc_new;
	struct torture_context *torture;
	struct torture_results *results;
	const struct torture_ui_ops *ui_ops;
	char **argv_new;
	poptContext pc;
	static const char *target = "other";
	NTSTATUS status;
	int shell = false;
	static const char *ui_ops_name = "subunit";
	const char *basedir = NULL;
	const char *extra_module = NULL;
	static int list_tests = 0;
	int num_extra_users = 0;
	enum {OPT_LOADFILE=1000,OPT_UNCLIST,OPT_TIMELIMIT,OPT_DNS, OPT_LIST,
	      OPT_DANGEROUS,OPT_SMB_PORTS,OPT_ASYNC,OPT_NUMPROGS,
	      OPT_EXTRA_USER,};

	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"format", 0, POPT_ARG_STRING, &ui_ops_name, 0, "Output format (one of: simple, subunit)", NULL },
		{"smb-ports",	'p', POPT_ARG_STRING, NULL,     OPT_SMB_PORTS,	"SMB ports", 	NULL},
		{"basedir",	  0, POPT_ARG_STRING, &basedir, 0, "base directory", "BASEDIR" },
		{"seed",	  0, POPT_ARG_INT,  &torture_seed, 	0,	"Seed to use for randomizer", 	NULL},
		{"num-progs",	  0, POPT_ARG_INT,  NULL, 	OPT_NUMPROGS,	"num progs",	NULL},
		{"num-ops",	  0, POPT_ARG_INT,  &torture_numops, 	0, 	"num ops",	NULL},
		{"entries",	  0, POPT_ARG_INT,  &torture_entries, 	0,	"entries",	NULL},
		{"loadfile",	  0, POPT_ARG_STRING,	NULL, 	OPT_LOADFILE,	"NBench load file to use", 	NULL},
		{"list", 	  0, POPT_ARG_NONE, &list_tests, 0, "List available tests and exit", NULL },
		{"unclist",	  0, POPT_ARG_STRING,	NULL, 	OPT_UNCLIST,	"unclist", 	NULL},
		{"timelimit",	't', POPT_ARG_INT,	NULL, 	OPT_TIMELIMIT,	"Set time limit (in seconds)", 	NULL},
		{"failures",	'f', POPT_ARG_INT,  &torture_failures, 	0,	"failures", 	NULL},
		{"parse-dns",	'D', POPT_ARG_STRING,	NULL, 	OPT_DNS,	"parse-dns", 	NULL},
		{"dangerous",	'X', POPT_ARG_NONE,	NULL,   OPT_DANGEROUS,
		 "run dangerous tests (eg. wiping out password database)", NULL},
		{"load-module",  0,  POPT_ARG_STRING, &extra_module,     0, "load tests from DSO file",    "SOFILE"},
		{"shell", 		0, POPT_ARG_NONE, &shell, true, "Run shell", NULL},
		{"target", 		'T', POPT_ARG_STRING, &target, 0, "samba3|samba4|other", NULL},
		{"async",       'a', POPT_ARG_NONE,     NULL,   OPT_ASYNC,
		 "run async tests", NULL},
		{"num-async",    0, POPT_ARG_INT,  &torture_numasync,  0,
		 "number of simultaneous async requests", NULL},
		{"maximum-runtime", 0, POPT_ARG_INT, &max_runtime, 0, 
		 "set maximum time for smbtorture to live", "seconds"},
		{"extra-user",   0, POPT_ARG_STRING, NULL, OPT_EXTRA_USER,
		 "extra user credentials", NULL},
		POPT_COMMON_SAMBA
		POPT_COMMON_CONNECTION
		POPT_COMMON_CREDENTIALS
		POPT_COMMON_VERSION
		{ NULL }
	};

	setlinebuf(stdout);

	/* we are never interested in SIGPIPE */
	BlockSignals(true, SIGPIPE);

	pc = poptGetContext("smbtorture", argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);

	poptSetOtherOptionHelp(pc, "<binding>|<unc> TEST1 TEST2 ...");

	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt) {
		case OPT_LOADFILE:
			lp_set_cmdline(cmdline_lp_ctx, "torture:loadfile", poptGetOptArg(pc));
			break;
		case OPT_UNCLIST:
			lp_set_cmdline(cmdline_lp_ctx, "torture:unclist", poptGetOptArg(pc));
			break;
		case OPT_TIMELIMIT:
			lp_set_cmdline(cmdline_lp_ctx, "torture:timelimit", poptGetOptArg(pc));
			break;
		case OPT_NUMPROGS:
			lp_set_cmdline(cmdline_lp_ctx, "torture:nprocs", poptGetOptArg(pc));
			break;
		case OPT_DNS:
			parse_dns(cmdline_lp_ctx, poptGetOptArg(pc));
			break;
		case OPT_DANGEROUS:
			lp_set_cmdline(cmdline_lp_ctx, "torture:dangerous", "Yes");
			break;
		case OPT_ASYNC:
			lp_set_cmdline(cmdline_lp_ctx, "torture:async", "Yes");
			break;
		case OPT_SMB_PORTS:
			lp_set_cmdline(cmdline_lp_ctx, "smb ports", poptGetOptArg(pc));
			break;
		case OPT_EXTRA_USER:
			{
				char *option = talloc_asprintf(NULL, "torture:extra_user%u",
							       ++num_extra_users);
				const char *value = poptGetOptArg(pc);
				lp_set_cmdline(cmdline_lp_ctx, option, value);
				talloc_free(option);
			}
			break;
		default:
			printf("bad command line option\n");
			exit(1);
		}
	}

	if (strcmp(target, "samba3") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:samba3", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
	} else if (strcmp(target, "samba4") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:samba4", "true");
	} else if (strcmp(target, "winxp") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:winxp", "true");
	} else if (strcmp(target, "w2k3") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:w2k3", "true");
	} else if (strcmp(target, "w2k8") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:w2k8", "true");
		lp_set_cmdline(cmdline_lp_ctx,
		    "torture:invalid_lock_range_support", "false");
	} else if (strcmp(target, "win7") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:win7", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:cn_max_buffer_size",
		    "0x00010000");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:rewind_support", "false");

		/* RAW-SEARCH for fails for inexplicable reasons against win7 */
		lp_set_cmdline(cmdline_lp_ctx, "torture:search_ea_support", "false");

		lp_set_cmdline(cmdline_lp_ctx, "torture:hide_on_access_denied",
		    "true");
	} else if (strcmp(target, "onefs") == 0) {
		lp_set_cmdline(cmdline_lp_ctx, "torture:onefs", "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:openx_deny_dos_support",
		    "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:sacl_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:ea_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:smblock_pdu_support",
		    "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:2_step_break_to_none",
		    "true");
		lp_set_cmdline(cmdline_lp_ctx, "torture:deny_dos_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:deny_fcb_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:read_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:writeclose_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:resume_key_support", "false");
		lp_set_cmdline(cmdline_lp_ctx, "torture:rewind_support", "false");
	}

	if (max_runtime) {
		/* this will only work if nobody else uses alarm(),
		   which means it won't work for some tests, but we
		   can't use the event context method we use for smbd
		   as so many tests create their own event
		   context. This will at least catch most cases. */
		signal(SIGALRM, max_runtime_handler);
		alarm(max_runtime);
	}

	if (extra_module != NULL) {
	    init_module_fn fn = load_module(talloc_autofree_context(), poptGetOptArg(pc));

	    if (fn == NULL) 
		d_printf("Unable to load module from %s\n", poptGetOptArg(pc));
	    else {
		status = fn();
		if (NT_STATUS_IS_ERR(status)) {
		    d_printf("Error initializing module %s: %s\n", 
			     poptGetOptArg(pc), nt_errstr(status));
		}
	    }
	} else { 
		torture_init();
	}

	if (list_tests) {
		print_test_list();
		return 0;
	}

	if (torture_seed == 0) {
		torture_seed = time(NULL);
	} 
	printf("Using seed %d\n", torture_seed);
	srandom(torture_seed);

	argv_new = discard_const_p(char *, poptGetArgs(pc));

	argc_new = argc;
	for (i=0; i<argc; i++) {
		if (argv_new[i] == NULL) {
			argc_new = i;
			break;
		}
	}

	if (!(argc_new >= 3 || (shell && argc_new >= 2))) {
		usage(pc);
		exit(1);
	}

	if (!parse_target(cmdline_lp_ctx, argv_new[1])) {
		usage(pc);
		exit(1);
	}

	if (!strcmp(ui_ops_name, "simple")) {
		ui_ops = &std_ui_ops;
	} else if (!strcmp(ui_ops_name, "subunit")) {
		ui_ops = &torture_subunit_ui_ops;
	} else {
		printf("Unknown output format '%s'\n", ui_ops_name);
		exit(1);
	}

	results = torture_results_init(talloc_autofree_context(), ui_ops);

	torture = torture_context_init(s4_event_context_init(NULL), results);
	if (basedir != NULL) {
		if (basedir[0] != '/') {
			fprintf(stderr, "Please specify an absolute path to --basedir\n");
			return 1;
		}
		torture->outputdir = basedir;
	} else {
		char *pwd = talloc_size(torture, PATH_MAX);
		if (!getcwd(pwd, PATH_MAX)) {
			fprintf(stderr, "Unable to determine current working directory\n");
			return 1;
		}
		torture->outputdir = pwd;
	}

	torture->lp_ctx = cmdline_lp_ctx;

	gensec_init(cmdline_lp_ctx);

	if (argc_new == 0) {
		printf("You must specify a test to run, or 'ALL'\n");
	} else if (shell) {
		run_shell(torture);
	} else {
		for (i=2;i<argc_new;i++) {
			if (!run_test(torture, argv_new[i])) {
				correct = false;
			}
		}
	}

	if (torture->results->returncode && correct) {
		return(0);
	} else {
		return(1);
	}
}
示例#5
0
int main(int argc, char**argv){

	//log files
	logs = fopen("/var/log/weperf/sensor/sensor.log", "a+");

	int clientSocket;
	char buffer[1024];
	char recv_buff[1024];
	char send_buff[1024];
	struct sockaddr_in serverAddr;
	socklen_t addr_size;

	//parse configurations from file
    if (ini_parse("/etc/weperf/sensor-config.ini", handler, &config) < 0) {
        client_log("Error", "Can't load 'config.ini'\n");
        return 1;
    }

	//casue zombies to be reaped automatically 
	if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
 		perror(0);
  		exit(1);
	}

	/*---- Create the socket. The three arguments are: ----*/
	/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
	clientSocket = socket(PF_INET, SOCK_STREAM, 0);

	/*---- Configure settings of the server address struct ----*/
	/* Address family = Internet */
	serverAddr.sin_family = AF_INET;
	/* Set port number, using htons function to use proper byte order */
	serverAddr.sin_port = htons(config.server_port);
	/* Set IP address to localhost */
	serverAddr.sin_addr.s_addr = inet_addr(config.server_addr);
	/* Set all bits of the padding field to 0 */
	memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

	/*---- Connect the socket to the server using the address struct ----*/
	addr_size = sizeof serverAddr;
	if(connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size)){
		client_log("Error", "Connecting to server - %s", strerror(errno));
		return 0;
	}

	client_log("Info", "Connected to server");

	//get IP of interface - add interface to config file
	struct ifreq ifr;
	strncpy(ifr.ifr_name, config.interface, IFNAMSIZ-1);
	ioctl(clientSocket, SIOCGIFADDR, &ifr);
	struct in_addr local_ip = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;

	printf("Local IP %s\n", inet_ntoa(local_ip));

	//timeout
	struct timeval tv;

	int bytes = 1;
	//receive loop
	while(bytes){

		FILE *fp;

		fd_set rfds;
		FD_ZERO(&rfds);
		FD_SET (clientSocket, &rfds);

		tv.tv_sec = 60;
		tv.tv_usec = 0;
				
		int ready = select(clientSocket + 1, &rfds, NULL, NULL, &tv);

		if(ready == -1 ){

		}else if(ready){
			bytes = recv(clientSocket, recv_buff, sizeof(recv_buff),0);
			struct srrp_request * request = (struct srrp_request *) recv_buff;

			if(request->type == SRRP_HB){
				//heatbeat request
				printf("Received hb request - %d bytes\n", bytes);
				//build response
				response_init((struct srrp_response *) send_buff, request->type, SRRP_SCES, request->dst_id, request->m_id);

				send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff), 0);
			}else if(request->type == SRRP_ETHER){
				//ethernet request
				printf("Received ether request - %d bytes\n", bytes);
				//build response
				response_init((struct srrp_response *) send_buff, request->type, SRRP_SCES, request->dst_id, request->m_id);

				//bit of a hack to break from srrp to send MAC address 
				memcpy(&((struct srrp_response *)send_buff)->results[0], config.ether, strlen(config.ether) + 1);
				//also for the ip
				memcpy(&((struct srrp_response *)send_buff)->results[3], &local_ip, sizeof(local_ip));

				send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff) /*header*/ + 100 /*mac*/ + sizeof(local_ip) /*ip*/, 0);
			}else if(request->type == SRRP_BW){				
				client_log("Info", "Recevived iperf request - %d bytes", bytes);

				if(fork() == 0){
					//listen for SIGCHLD so pclose resturns the status 
					signal(SIGCHLD, SIG_DFL);

					char * cmd_fmt = "iperf -c %s -p %d -t %d -y C";
					char cmd[100];

					//default params
					int dur = 10;

					//get parameters
					int i;
					for(i = 0; i < request->length; i++){
						if(request->params[i].param == SRRP_DUR){
							dur = request->params[i].value;
						}else{
							client_log("Error", "Invalid iperf parameter");
						}
					}

					//build command
					sprintf(cmd, cmd_fmt, inet_ntoa(request->dst_ip), config.tcp_iperf_port, dur);
					printf("%s\n", cmd);

					fp = popen(cmd, "r");
					if(fp == NULL){
						client_log("Error", "Failed to run command '%s'", cmd);
						_exit(1);
					}

					//get otuput	-	single line because of -y C flage
					char result[100];
					while(fgets(result, sizeof(result)-1, fp) != NULL){}

					int exit_status = pclose(fp);
					if(exit_status != 0){
						client_log("Error", "iperf failed exit status %d", exit_status);

						//should send resonpse with failed success code

						_exit(1);
					}else{

						//build response
						if(parse_iperf(request->type, request->dst_id, request->m_id, (struct srrp_response *) send_buff, result)){
							client_log("Error", "Failed to parse iperf response");
							_exit(0);
						}

						client_log("Info", "Sending iperf results");

						send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff), 0);
					}

					_exit(0);
				}

			}else if(request->type == SRRP_RTT){
				client_log("Info", "Received ping request - %d bytes", bytes);

				if(fork() == 0){
					//listen for SIGCHLD so pclose resturns the status 
					signal(SIGCHLD, SIG_DFL);
					
					char * command_fmt = "ping -c %d %s";
					char command[100];

					//default params
					int itterations = 5;

					//load in params
					int i;
					for(i = 0; i < request->length; i++){
						if(request->params[i].param == SRRP_ITTR){
							itterations = request->params[i].value;
						}else{
							client_log("Error", "Invalid ping parameter");
						}
					}

					//build command
					sprintf(command, command_fmt, itterations, inet_ntoa(request->dst_ip));
					printf("%s\n", command);

					fp = popen(command , "r");
					if(fp == NULL){
						client_log("Error", "Failed to run command %s", command);
						_exit(1);
					}

					//get otuput	-	single line because of -y C flage
					char result[100];
					while(fgets(result, sizeof(result)-1, fp) != NULL){}

					int exit_status = pclose(fp);
					if(exit_status != 0){
						client_log("Error", "command failed exit status %d", exit_status);

						//should respond

					}else{

						if(parse_ping(request->type, request->dst_id, request->m_id, (struct srrp_response *) send_buff, result)){
							client_log("Error", "Failed to parse ping response");
							_exit(0);
						}

						send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff), 0);

						_exit(0);
					}

				}	
			}else if(request->type == SRRP_UDP){
				client_log("Info", "Received UDP iperf request - %d bytes", bytes);

				if(fork() == 0){
					//listen for SIGCHLD so pclose resturns the status 
					signal(SIGCHLD, SIG_DFL);

					char * cmd_fmt = "iperf -c %s -u -p %d -b %dK -l %d -t %d -S %d -y C";
					char cmd[100];

					//default params
					int speed = 1;
					int size = 1470;
					int duration = 10;
					int dscp = 0;

					//load in params
					int i;
					for(i = 0; i < request->length; i++){
						if(request->params[i].param == SRRP_SPEED){
							speed = request->params[i].value;
						}else if(request->params[i].param == SRRP_SIZE){
							size = request->params[i].value;
						}else if(request->params[i].param == SRRP_DUR){
							duration = request->params[i].value;
						}else if(request->params[i].param == SRRP_DSCP){
							dscp = request->params[i].value;
						}else{
							client_log("Error", "Invalid udp parameter");
						}
					}

					sprintf(cmd, cmd_fmt, inet_ntoa(request->dst_ip), config.udp_iperf_port, speed, size, duration, dscp);

					printf("%s\n", cmd);

					fp = popen(cmd , "r");
					if(fp == NULL){
						client_log("Error", "Failed to run command %s", cmd);
						_exit(1);
					}

					//get otuput	-	single line because of -y C flage
					char result[200];
					while(fgets(result, sizeof(result)-1, fp) != NULL)
						printf("%s\n", result);

					int exit_status = pclose(fp);
					if(exit_status != 0){
						client_log("Error", "udp iperf failed exit status %d", exit_status);

						//should send resonpse with failed success code
						//parse_failure()

						_exit(1);
					}else{

						if(parse_udp(request->type, request->dst_id, request->m_id, (struct srrp_response *) send_buff, result, speed, dscp)){
							client_log("Error", "Failed to parse udp response");
							_exit(0);
						}

						send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff), 0);

						client_log("Info", "Sending udp iperf results");

						_exit(0);
					}
				}

			}else if(request->type == SRRP_DNS){
				client_log("Info", "Received dns request - %d bytes", bytes);

				if(fork() == 0){
					//listen for SIGCHLD so pclose resturns the status 
					signal(SIGCHLD, SIG_DFL);

					char * cmd_fmt = "nslookup %s %s";
					char cmd[100];

					char * domain_name 	= NULL;
					char * server 		= NULL;

					int i = 0;
					while(i < request->length){
						if(request->params[i].param == SRRP_DN){
							i = get_param_string(&domain_name, request, i);	
						}else if(request->params[i].param == SRRP_SERVER){
							i = get_param_string(&server, request, i);
						}else{
							client_log("Error", "Invalid param");
						}
					}

					if(!server || strcmp(server, "default") == 0)
						server = "";
					if(!domain_name || strcmp(server, "default") == 0)
						domain_name = (char *)config.nslookup_addr;

					sprintf(cmd, cmd_fmt, domain_name, server);

					printf("%s\n", cmd);

					struct timeval start, end;
					float mtime, secs, usecs;

					gettimeofday(&start, NULL);

					fp = popen(cmd , "r");
					if(fp == NULL){
						client_log("Error", "Failed to run command %s", cmd);
						_exit(1);
					}

					//get otuput
					char result[200];
					while(fgets(result, sizeof(result)-1, fp) != NULL){}

					//work out resolution time
					gettimeofday(&end, NULL);
					secs  = end.tv_sec  - start.tv_sec;
					usecs = end.tv_usec - start.tv_usec;
					mtime = ((secs) * 1000 + usecs/1000.0) + 0.5;

					int exit_status = pclose(fp);
					if(exit_status != 0){
						client_log("Info", "DNS status failure - exit status %d", exit_status);
						parse_failure(request->type, request->dst_id, request->m_id, (struct srrp_response *) send_buff);
					}else{
						client_log("Info", "DNS status sucess - exit status %d", exit_status);	
						parse_dns(request->type, request->dst_id, request->m_id, (struct srrp_response *) send_buff, mtime);
					}					

					send(clientSocket, send_buff, response_size((struct srrp_response *) send_buff), 0);

					client_log("Info", "Sending dns response");				

					_exit(0);
				}

			}else{
				//unrecognised data
				client_log("Error", "Recevied unrecognised data - %d - %d bytes", request->type, bytes);
			}
		}else{
			//timeout
			//dont care about timeout --- keep running
			client_log("Error", "Timeout");
			break;
		}
	}

	client_log("Info", "Recevied empty data, closing connection");

	fclose(logs);
	close(clientSocket);  

	return 0;
}
示例#6
0
			/**
			 * Create a new DNSPacket from Packet. This is not performance optimal,
			 * but it is expected that the parsing will be performed on a prefiltered
			 * packets. 
			 *
			 * @param p		original Packet
			 */        
			DNSPacket(const Packet &p)
				: Packet(const_buffer<uint8_t>(p.base(), p.length()))
			{
					parse_dns();
			}
示例#7
0
int main (int argc, char **argv)    {
    int  i,
         opt,
         socket;                    /* socket to write on             */
    char *packet,                   /* captured packet                */
         *device          = NULL,   /* interface to sniff on          */
         *ft_filename     = NULL,   /* fabrication table filename     */
         *output_filename = NULL,   /* output statistics filename     */
         filter[1024],              /* tcpdump style capture filter   */
         errbuf[PCAP_ERRBUF_SIZE];  /* error buffer for pcap          */
    pid_t pid;                      /* used in daemonizing            */
    FILE *os;                       /* output statistics file handle  */
    struct pcap_pkthdr pcap_h;      /* pcap packet header             */
    pcap_t *capdev;                 /* the capture device             */

    /*
     *  catch sig
     */

    /*if (signal(SIGINT, catch_signals) == SIG_ERR)   {
        perror ("sigset failed for SIGINT");
        exit (EXIT_FAILURE);
    }*/

    /*
     *  prepare the chewy center
     */

    memset(&chewycenter, '\0', sizeof(struct cc));

    /*
     *  parse the command line
     */

    while ((opt = getopt(argc, argv, "d:f:hi:o:psvz")) != EOF)    {
        switch (opt)  {
            case 'd':               /* default answer */
                chewycenter.default_answer = optarg;
                dflag++;
                break;
            case 'f':               /* fabrication table */
                ft_filename = optarg;
                fflag++;
                break;
            case 'i':               /* interface */
                device = optarg;
                break;
            case 'o':               /* output statistics filename */
                output_filename = optarg;
                oflag++;
                break;
            case 'p':               /* print only */
                pflag++;
                break;
            case 's':               /* supress printing of "ignored *" */
                sflag++;
                break;
            case 'v':               /* verbose */
                vflag++;
                break;
            case 'z':               /* daemonize */
                zflag++;
                break;
            case 'h':               /* usage */
            case '?':
                usage(argv);
                break;
        }
    }

    /*
     *  if there is no default spoof address or fabrication table specified
     *  and the user doesn't just want to print captured dns packets
     *  then we have a problem, because we have no idea what to spoof answers with
     */

    if (!dflag && !fflag && !pflag)
        usage(argv);

    /*
     *  if a fabrication table file was specified fill the ftable with values from it
     */

    if (fflag)
        fill_table(ft_filename);

    /*
     * daemonize if we have to
     * we do this after we fill the table because we chdir() here
     */

    if (zflag)  {
        pid = fork();

        if (pid < 0) {
            printf("\ncould not daemonize");
            exit (EXIT_FAILURE);
        }

        if (pid != 0)
            exit (EXIT_SUCCESS);

        fclose(stdin); fclose(stdout); fclose(stderr);
        setsid();
        chdir("/");
        umask(0);
    }

    /*
     *  make sure there is a device to sniff on
     */

    if (!device)
        device = pcap_lookupdev(errbuf);

    if (!device) {
        fprintf(stderr, "\ndevice lookup failed");
        exit (EXIT_FAILURE);
     }

    /*
     *  set capture filter
     *  defaults to only capturing traffic destined to a nameserver
     */

    argc -= optind;
    argv += optind;

    strcpy(filter, "udp dst port 53");
    if (argc != 0)  {
        strcat(filter, " and ");
        strcat(filter, copy_argv(argv));
    }

    /*
     *  prepare the device for capturing
     */

    capdev = set_cap_dev(device, filter);

    /*
     *  if we're not only watching grab a socket to write on
     */

    if (!pflag)
        if ((socket = libnet_open_raw_sock(IPPROTO_RAW)) == -1)
            libnet_error(LIBNET_ERR_FATAL, "network initialization failed\n");

    /*
     *  print some informative information
     */

    printf("\n[ dns hijacker %s ]\n", VERSION);
    printf("\nsniffing on:       %s", device);
    printf("\nusing filter:      %s", filter);
    if (dflag) printf("\ndefault answer:    %s", chewycenter.default_answer);
    if (fflag) printf("\nfabrication table: %s", ft_filename);
    if (pflag) printf("\nprint only mode");
    if (sflag) printf("\nsuppressing ignored activity output");
    printf("\n");

    /*
     *  main loop
     *  this is where it all happens...
     *  - sniff a packet
     *  - parse through that packet printing packet information and
     *    store relevant values in our struct
     *  - build an appropriate fabricated answer and
     *    store it in our struct
     *  - if we're not only watching
     *    write the packet
     *  - if we want to store statistics and we're not only watching
     *    open, write to, and close the statistics file
     */

    for (;;)   {
        packet = (u_char *)pcap_next(capdev, &pcap_h);

        if (packet == NULL)
            continue;

        parse_dns(packet, (int)pcap_h.caplen);

        if (!pflag)
            spoof_dns(socket);

        if (oflag && !pflag)  {
            os = fopen(output_filename, "w+");
            fprintf(os, "%d", num_spoofed_answers);
            fclose(os);
        }
    }

    /* not reached */
    return (EXIT_SUCCESS);
}
示例#8
0
void dynamic_parse(void *data, pattern_t *pattern, size_t offset)
{
    if(unlikely(!get_flags_dynamic_enable()))
        return;
    struct ssn_skb_values * ssv = ( struct ssn_skb_values *)data;
    //struct l2ct_var_dpi * lvd =  &(ssv->ssn->vars_dpi);
#if 0 
    if (unlikely(pattern->pattern_key.dynamic_current_phase - 1 & lvd->ac_state_tbl != pattern->pattern_key.dynamic_current_phase - 1)) {
        if (i != 4) {
        D("current_phase[%u], ldv[%p], ac_state_tbl[%u]\n", pattern->pattern_key.dynamic_current_phase,lvd, lvd->ac_state_tbl);
            aaa =4;
        }
        lvd->ac_state_tbl = 0;
        return;
    }
    lvd->ac_state_tbl |= pattern->pattern_key.dynamic_current_phase;

    if (lvd->ac_state_tbl < pattern->pattern_key.dynamic_need_phase)
        return;
    	lvd->ac_state_tbl = 0;
#endif
//get dns or ip + port list
    //char *sp = ssv->payload + offset + pattern->pattern_len;
    char *sp = ssv->payload + offset;
    char *ep = ssv->payload + ssv->payload_len;
    int pos = 0;
    uint32_t ip;
    uint32_t proto_mark;
    uint16_t port = 0;

    switch(pattern->pattern_key.dynamic_type) {
            case 1:
                    {
                            if (pattern->pattern_key.dynamic_port && pattern->pattern_key.dynamic_port != (uint16_t)-1)
                            {
                                    if(pattern->pattern_key.dynamic_dir && pattern->pattern_key.dynamic_port != ssv->ssn->sess_key.port_dst)
                                    {
                                            return;
                                    }

                                    if(0 == pattern->pattern_key.dynamic_dir && pattern->pattern_key.dynamic_port != ssv->ssn->sess_key.port_src)
                                    {
                                            return;
                                    }

                            } 
                           
                            if (pattern->pattern_key.dynamic_dir) 
                            {    
                                    if (pattern->pattern_key.dynamic_port == (uint16_t)-1) {

                                        study_cache_try_get(ssv->ssn->sess_key.ip_dst, ssv->dport, ssv->ssn->proto_mark, 0, DYNAMIC_TIMEO); 	
 #ifdef DYNAMIC_DEBUG
                                    LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n",
                                                    pattern->pattern_name, ssv->ssn->sess_key.ip_dst, IPQUADS(ssv->ssn->sess_key.ip_dst), ntohs(ssv->dport),  ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); 
#endif
                                   } else {
                                    study_cache_try_get(ssv->ssn->sess_key.ip_dst, pattern->pattern_key.dynamic_port, ssv->ssn->proto_mark, 0, DYNAMIC_TIMEO); 	
#ifdef DYNAMIC_DEBUG
                                    LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n",
                                                    pattern->pattern_name, ssv->ssn->sess_key.ip_dst, IPQUADS(ssv->ssn->sess_key.ip_dst), ntohs(pattern->pattern_key.dynamic_port),  ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); 
#endif
                                }
                            } 
                            else 
                            {
                                    if (pattern->pattern_key.dynamic_port == (uint16_t)-1) {

                                        study_cache_try_get(ssv->ssn->sess_key.ip_src, ssv->sport, ssv->ssn->proto_mark, 0, 0); 	
 #ifdef DYNAMIC_DEBUG
                                    LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n",
                                                    pattern->pattern_name, ssv->ssn->sess_key.ip_src, IPQUADS(ssv->ssn->sess_key.ip_src), ntohs(ssv->sport),  ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); 
#endif
                                    } else {
                                    study_cache_try_get(ssv->ssn->sess_key.ip_src, pattern->pattern_key.dynamic_port, ssv->ssn->proto_mark, 0, 0); 
#ifdef DYNAMIC_DEBUG
                                    LOG("pattern[%s]add ip and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type\n",
                                                    pattern->pattern_name, IPQUADS(ssv->ssn->sess_key.ip_src), ntohs(pattern->pattern_key.dynamic_port),  ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); 
#endif
                                    }
                            }

                            break;
                    }
            case 2:
                    {
                            //printf("dns type\n");
                            parse_dns(data, pattern, offset); 
                            break;
                    }
            case 3:// ip:port[10.211.55.88:88]
                    {
                            do{
                                    pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.ip_key, pattern->pattern_key.ip_key_len, 0);
                                    if (pos <= 0)
                                            return;
                                    sp += pos;
                                    for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) {
                                            if (sp >= ep)
                                                    return;
                                    }
                                    ip = ipv4_stonl(sp);
                                    if (unlikely(ip == 0xFFFFFFFF))
                                            return;
                                    sp += 6;
                                    if (pattern->pattern_key.dynamic_port) {
                                            port = pattern->pattern_key.dynamic_port;
                                    } else { 
                                            pos = substr_in_mainstr_nocase(sp, 16, ":", 0);
                                            if (pos > 0) {
                                                    sp += pos;
                                                    port = port_stons(sp);
                                                    if (port == 65535) {
                                                            port = 0;
                                                    }
                                            } 
                                    }
                                    if (likely(pattern->pattern_key.dynamic_indirect == 0) ) {
                                            if (pattern->pattern_key.dynamic_dir) {    
                                                    study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); 
                                            } else {
                                                    dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); 
                                            }

#ifdef DYNAMIC_DEBUG
                                            LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n",pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner);
#endif
                                    } else {
                                            if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) {

                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            }  else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) {
                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n",pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            }
                                    }
                            } while (pattern->pattern_key.mult_iplist && sp < ep);
                            //   lvd->is_dynamic = 1;
                            break;
                    }
            case 4://such as: "ip":"111.161.80.157","port":1935,
                    {
                            do{
                                    pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.ip_key, pattern->pattern_key.ip_key_len, 0);
                                    if (pos <= 0)
                                            return;
                                    sp += pos;
                                    for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) {
                                            if (sp >= ep)
                                                    return;
                                    }

                                    ip = ipv4_stonl(sp);
                                    if (unlikely(ip == 0xFFFFFFFF))
                                            return;
                                    sp += 6; 
                                    pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.port_key, pattern->pattern_key.port_key_len, 0);
                                    if (pos <= 0)
                                            return;
                                    sp += pos;
                                    for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) {
                                            if (sp >= ep)
                                                    return;
                                    }
                                    port = port_stons(sp);
                                    if (likely(pattern->pattern_key.dynamic_indirect == 0) ) {
                                            if (pattern->pattern_key.dynamic_dir) {    
                                                    study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); 
                                            } else {
                                                    dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); 
                                            }
#ifdef DYNAMIC_DEBUG
                                            LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner);
#endif 
                                    } else {
                                            if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) {

                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache  isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            } else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) {


                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache  isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            }

                                    }
                            } while (pattern->pattern_key.mult_iplist && sp < ep);
                            //                lvd->is_dynamic = 1;
                            break;

                    }

            case 5:
                    {
                            do{
                                    for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) {
                                            if (sp >= ep)
                                                    return;
                                    }

                                    ip = ipv4_stonl(sp);
                                    if (unlikely(ip == 0xFFFFFFFF))
                                            return;
                                    sp += 6;

                                    if (pattern->pattern_key.dynamic_port) {
                                            port = pattern->pattern_key.dynamic_port;
                                    } else { 
                                            pos = subhex_in_mainhex(sp, 16, pattern->pattern_key.port_key,pattern->pattern_key.port_key_len, 0);
                                            if (pos > 0) {
                                                    sp += pos;
                                                    port = port_stons(sp);
                                                    if (port == 65535) {
                                                            port = 0;
                                                    }
                                            } 
                                    }

                                    if (likely(pattern->pattern_key.dynamic_indirect == 0) ) {
                                            if (pattern->pattern_key.dynamic_dir) {    
                                                    study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); 
                                            } else {
                                                    dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); 
                                            }
#ifdef DYNAMIC_DEBUG
                                            LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner);
#endif 
                                    } else {
                                            if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) {

                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache  isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            } else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) {


                                                    if (pattern->pattern_key.dynamic_dir) {    
                                                            study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); 
                                                    } else {
                                                            dynamic_cache_try_get(ip, port, proto_mark, 0); 
                                                    }

#ifdef DYNAMIC_DEBUG
                                                    LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache  isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner);
#endif
                                            }

                                    }
                            } while (pattern->pattern_key.mult_iplist && sp < ep);
                            //                lvd->is_dynamic = 1;
                            break;

                    }


#if 0
            case 5://such as: ch1.dnf.qq.com,
                    {
                            do{
                                    for(; __isspace(*sp); sp++) {
                                            if (sp >= ep)
                                                    return;
                                    }
                                    pos = substr_in_mainstr_nocase(sp, ep - sp, pattern->port_key, 0);
                                    //pos = substr_in_mainstr_nocase(sp, 16, ":", 0);
                                    if (pos > 0) {
                                            strncopy(domain, sp, pos - strlen(pattern->port_key));
                                            sp += pos;
                                            port = simple_strtol(sp, NULL, 0);
                                            domain_cache_try_get(domain, ssv->ssn->proto_mark); 
                                            printk("---port=%u\n", port);
                                    }
                                    // else {
                                    //     port = pattern->dynamic_port;
                                    // }
                                    DEG("add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache\n", IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark); 
                            } while (pattern->mult_iplist && sp < ep);
                            lvd->is_dynamic = 1;
                            break;
                    }
#endif
            default: 
                    break;

    }

}