示例#1
0
//*************************
//  Main
//
int main(int argc, char *argv[])
{
	int sckt;
	pthread_t recvThread;
	char sendBuffer[BUFFER_SIZE];
	int indexBuffer;
	int sharedRecs;
	RTDBconf_var rec[MAX_RECS];
	unsigned int frameCounter = 0;
	int i, j;
	int life;

	struct sched_param proc_sched;
	pthread_attr_t thread_attr;

	struct itimerval it;
	struct _frameHeader frameHeader;

	struct timeval tempTimeStamp;

  nosend = 0;
	if ((argc < 2) || (argc > 3))
	{
		printUsage();
		return (-1);
	}
	if (argc == 3)
	{
		if(strcmp(argv[2], "nosend") == 0)
		{
			printf("\n*** Running in listing only mode ***\n\n");
			nosend = 1;
		}
		else
		{
			printUsage();
			return (-1);
		}
	}

	/* initializations */
	delay = 0;
	timer = 0;
	end = 0;
	RUNNING_AGENTS = 1;

	/* Assign a real-time priority to process */
	proc_sched.sched_priority=60;
	if ((sched_setscheduler(getpid(), SCHED_FIFO, &proc_sched)) < 0)
	{
		PERRNO("setscheduler");
		return -1;
	}

	if(signal(SIGALRM, signal_catch) == SIG_ERR)
	{
		PERRNO("signal");
		return -1;
	}

	if(signal(SIGINT, signal_catch) == SIG_ERR)
	{
		PERRNO("signal");
		return -1;
	}

	if((sckt = openSocket(argv[1])) == -1)
	{
		PERR("openMulticastSocket");
		printf("\nUsage: comm <interface_name>\n\n");
		return -1;
	}

	if(DB_init() == -1)
	{
		PERR("DB_init");
		closeSocket(sckt);
		return -1;
	}
	
	if((sharedRecs = DB_comm_ini(rec)) < 1)
	{
		PERR("DB_comm_ini");
		DB_free();
		closeSocket(sckt);
		return -1;
	}

#ifdef FILEDEBUG
	if ((filedebug = fopen("log.txt", "w")) == NULL)
	{
		PERRNO("fopen");
		DB_free();
		closeSocket(sckt);
		return -1;
	}
#endif

	/* initializations */
	for (i=0; i<MAX_AGENTS; i++)
	{
		lostPackets[i]=0;
		agent[i].lastFrameCounter = 0;
		agent[i].state = NOT_RUNNING;
		agent[i].removeCounter = 0;
	}
	myNumber = Whoami();
	agent[myNumber].state = RUNNING;

	/* receive thread */
	pthread_attr_init (&thread_attr);
	pthread_attr_setinheritsched (&thread_attr, PTHREAD_INHERIT_SCHED);
	if ((pthread_create(&recvThread, &thread_attr, receiveDataThread, (void *)&sckt)) != 0)
	{
		PERRNO("pthread_create");
		DB_free();
		closeSocket(sckt);
		return -1;
	}

	/* Set itimer to reactivate the program */
	it.it_value.tv_usec=(__suseconds_t)(TTUP_US);
	it.it_value.tv_sec=0;
	it.it_interval.tv_usec=(__suseconds_t)(TTUP_US);
	it.it_interval.tv_sec=0;
	setitimer (ITIMER_REAL, &it, NULL);

	printf("communication: STARTED in ");
#ifdef UNSYNC
	printf("unsync mode...\n");
#else
	printf("sync mode...\n");
#endif 


	MTRand randomGenerator;
	while (!end)
	{
		//pause();
		double waitTime = randomGenerator.randNorm(0,1) * TTUP_US * 0.05 + TTUP_US;
		usleep(waitTime);

		// not timer event
		if (timer == 0)
			continue;

#ifndef UNSYNC
		// dynamic agent 0
		if ((delay > (int)MIN_UPDATE_DELAY_US) && (agent[myNumber].dynamicID == 0) && timer == 1)
		{
			it.it_value.tv_usec = (__suseconds_t)(delay - (int)MIN_UPDATE_DELAY_US/2);
			it.it_value.tv_sec = 0;
			setitimer (ITIMER_REAL, &it, NULL);
			delay = 0;
			continue;
		}
#endif

		timer = 0;

		indexBuffer = 0;
		bzero(sendBuffer, BUFFER_SIZE);

		update_stateTable();

		// update dynamicID
		j = 0;	
		for (i = 0; i < MAX_AGENTS; i++)
		{
			if ((agent[i].state == RUNNING) || (agent[i].state == REMOVE))
			{
				agent[i].dynamicID = j;
				j++;
			}
			agent[myNumber].stateTable[i] = agent[i].state;
		}
		RUNNING_AGENTS = j;

		MAX_DELTA = (int)(TTUP_US/RUNNING_AGENTS * 2/3);

		// frame header
		frameHeader.number = myNumber;
		frameHeader.counter = frameCounter;
		frameCounter ++;
		for (i = 0; i < MAX_AGENTS; i++)
			frameHeader.stateTable[i] = agent[myNumber].stateTable[i];
		frameHeader.noRecs = sharedRecs;
		memcpy(sendBuffer + indexBuffer, &frameHeader, sizeof(frameHeader));
		indexBuffer += sizeof(frameHeader);

		for(i = 0; i < sharedRecs; i++)
		{
			// id
			memcpy(sendBuffer + indexBuffer, &rec[i].id, sizeof(rec[i].id));
			indexBuffer += sizeof(rec[i].id);

			// size
			memcpy(sendBuffer + indexBuffer, &rec[i].size, sizeof(rec[i].size));
			indexBuffer += sizeof(rec[i].size);

			// life and data
			life = DB_get(myNumber, rec[i].id, sendBuffer + indexBuffer + sizeof(life));
			memcpy(sendBuffer + indexBuffer, &life, sizeof(life));
			indexBuffer = indexBuffer + sizeof(life) + rec[i].size;
		}

		if (indexBuffer > BUFFER_SIZE)
		{
			PERR("Pretended frame is bigger that the available buffer.");
			PERR("Please increase the buffer size or reduce the number of disseminated records");
			break;
		}
	
		if (nosend == 0) 
		{
			if (sendData(sckt, sendBuffer, indexBuffer) != indexBuffer)
				PERRNO("Error sending data");
		}

		gettimeofday (&tempTimeStamp, NULL);
		lastSendTimeStamp.tv_sec = tempTimeStamp.tv_sec;
		lastSendTimeStamp.tv_usec = tempTimeStamp.tv_usec;

		// reset values for next round
		for (i=0; i<MAX_AGENTS; i++)
		{
			agent[i].delta = 0;
			agent[i].received = NO;
		}
	}

	FDEBUG (filedebug, "\nLost Packets:\n");
	for (i=0; i<MAX_AGENTS; i++)
		FDEBUG (filedebug, "%d\t", lostPackets[i]);
	FDEBUG (filedebug, "\n");
	
	printf("communication: STOPED.\nCleaning process...\n");

#ifdef FILEDEBUG
	fclose (filedebug);
#endif

	closeSocket(sckt);

	pthread_join(recvThread, NULL);

	DB_free();

	printf("communication: FINISHED.\n");

	return 0;
}
示例#2
0
int main(int argc, char *argv[]) {
    apr_pool_t *p = NULL;
    apr_pool_initialize();
    apr_pool_create(&p, NULL);

    apr_getopt_t *opt;
    apr_status_t rv;

    char ch = '\0';
    const char *optarg = NULL;
    const char *config_opts = NULL;
    const char *install_opts = NULL;
    const char *make_opts = NULL;
    const char *url = NULL;
    enum CommandType request = COMMAND_NONE;

    rv = apr_getopt_init(&opt, p, argc, argv);
    check(rv == APR_SUCCESS, "Fail to get options.");

    while (apr_getopt(opt, "I:Lc:m:i:d:SF:B:", &ch, &optarg) == APR_SUCCESS) {
        switch(ch) {
            case 'I':
                request = COMMAND_INSTALL;
                url = optarg;
                break;
            case 'L':
                request = COMMAND_LIST;
                break;
            case 'c':
                config_opts = optarg;
                break;
            case 'm':
                make_opts = optarg;
                break;
            case 'i':
                install_opts = optarg;
                break;
            case 'S':
                request = COMMAND_INIT;
                break;
            case 'F':
                request = COMMAND_FETCH;
                url = optarg;
                break;
            case 'B':
                request = COMMAND_BUILD;
                url = optarg;
                break;
        }
    }

    switch (request) {
        case COMMAND_INSTALL:
            check(url, "You must at least give a URL.");
            Command_install(p, url, config_opts, make_opts, install_opts);
            break;
        case COMMAND_LIST:
            DB_list();
            break;
        case COMMAND_FETCH:
            check(url != NULL, "You must give a URL.");
            Command_fetch(p, url, 1);
            log_info("Downloaded to %s and in /tmp/", BUILD_DIR);
            break;
        case COMMAND_BUILD:
            check(url, "You must at least give a URL.");
            Command_build(p, url, config_opts, make_opts, install_opts);
            break;
        case COMMAND_INIT:
            rv = DB_init();
            check(rv == 0, "Failed to make the database.");
            break;
        default:
            sentinel("Invalid command given.");
    }

    return 0;

error:
    return 1;
}
示例#3
0
void*
AI_db_alertparser_thread ( void *arg )
{
	unsigned int   i           = 0;
	char           ip[INET_ADDRSTRLEN] = { 0 };
	char           query[1024] = { 0 };
	int            rows        = 0;
	int            latest_cid  = 0;
	double         *geocoord = NULL;
	time_t         latest_time = time ( NULL );
	pthread_t      alerts_pool_thread;

	DB_result      res, res2;
	DB_row         row, row2;

	struct pkt_key  key;
	struct pkt_info *info  = NULL;
	AI_snort_alert  *alert = NULL;
	AI_snort_alert  *tmp   = NULL;
	AI_geoip_cache  *found = NULL;

	pthread_mutex_init ( &mutex, NULL );

	if ( !DB_init() )
	{
		AI_fatal_err ( "Unable to connect to the database specified in module configuration", __FILE__, __LINE__ );
	}

	/* Initialize the pool of alerts to be passed to the serialization thread */
	if ( !( alerts_pool = ( AI_snort_alert** ) malloc ( config->alert_bufsize * sizeof ( AI_snort_alert* ))))
		AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );

	for ( i=0; i < config->alert_bufsize; i++ )
		alerts_pool[i] = NULL;

	/* Initialize the thread for managing the serialization of alerts' pool */
	if ( pthread_create ( &alerts_pool_thread, NULL, AI_alerts_pool_thread, NULL ) != 0 )
	{
		AI_fatal_err ( "Failed to create the alerts' pool management thread", __FILE__, __LINE__ );
	}

	while ( 1 )
	{
		sleep ( config->databaseParsingInterval );

		memset ( query, 0, sizeof ( query ));
		snprintf ( query, sizeof (query), "select cid, unix_timestamp(timestamp), signature from event where cid > %d "
				"and unix_timestamp(timestamp) > %ld order by cid", latest_cid, latest_time );

		pthread_mutex_lock ( &mutex );

		if ( !( res = (DB_result) DB_query ( query )))
		{
			pthread_mutex_unlock ( &mutex );
			DB_close();
			AI_fatal_err ( "Fatal error while executing a query on the database", __FILE__, __LINE__ );
		}

		pthread_mutex_unlock ( &mutex );

		if (( rows = DB_num_rows ( res )) < 0 )
		{
			DB_close();
			AI_fatal_err ( "Could not store the query result", __FILE__, __LINE__ );
		} else if ( rows == 0 ) {
			continue;
		}

		while (( row = (DB_row) DB_fetch_row ( res )))
		{
			if ( !( alert = ( AI_snort_alert* ) malloc ( sizeof ( AI_snort_alert )) ))
			{
				AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );
			}

			memset ( alert, 0, sizeof ( AI_snort_alert ));
			latest_cid = (row[0]) ? strtol ( row[0], NULL, 10 ) : 0;
			alert->timestamp = (row[1]) ? ( time_t ) strtol ( row[1], NULL, 10 ) : 0;

			/* Parsing gid, sid, rev, name, timestamp and priority */
			memset ( query, 0, sizeof ( query ));
			snprintf ( query, sizeof ( query ), "select sig_gid, sig_sid, sig_rev, sig_name, sig_priority from signature "
					"where sig_id='%ld'", strtol ( row[2], NULL, 0 ));

			pthread_mutex_lock ( &mutex );

			if ( !( res2 = (DB_result) DB_query ( query )))
			{
				pthread_mutex_unlock ( &mutex );
				DB_close();
				AI_fatal_err ( "Fatal error while executing a query on the database", __FILE__, __LINE__ );
			}

			pthread_mutex_unlock ( &mutex );

			if (( rows = DB_num_rows ( res2 )) < 0 ) {
				DB_close();
				AI_fatal_err ( "Could not store the query result", __FILE__, __LINE__ );
			} else if ( rows > 0 ) {
				if (( row2 = (DB_row) DB_fetch_row ( res2 )))
				{
					alert->gid      = (row2[0]) ? strtol ( row2[0], NULL, 10 ) : 0;
					alert->sid      = (row2[1]) ? strtol ( row2[1], NULL, 10 ) : 0;
					alert->rev      = (row2[2]) ? strtol ( row2[2], NULL, 10 ) : 0;
					alert->desc     = (row2[3]) ? strdup ( row2[3] ) : NULL;
					alert->priority = (row2[4]) ? strtol ( row2[4], NULL, 10 ) : 0;
				}

				DB_free_result ( res2 );
			}

			/* Parsing IP header information */
			memset ( query, 0, sizeof ( query ));
			snprintf ( query, sizeof ( query ), "select ip_tos, ip_len, ip_id, ip_ttl, ip_proto, ip_src, ip_dst "
					"from iphdr where cid='%d'", latest_cid);

			pthread_mutex_lock ( &mutex );

			if ( !( res2 = (DB_result) DB_query ( query )))
			{
				pthread_mutex_unlock ( &mutex );
				DB_close();
				AI_fatal_err ( "Fatal error while executing a query on the database", __FILE__, __LINE__ );
			}

			pthread_mutex_unlock ( &mutex );

			if (( rows = DB_num_rows ( res2 )) < 0 ) {
				DB_close();
				AI_fatal_err ( "Could not store the query result", __FILE__, __LINE__ );
			} else if ( rows > 0 ) {
				if (( row2 = DB_fetch_row ( res2 )))
				{
					alert->ip_tos      = (row2[0]) ? strtol ( row2[0], NULL, 10 ) : 0;
					alert->ip_len      = (row2[1]) ? htons ( strtol ( row2[1], NULL, 10 )) : 0;
					alert->ip_id       = (row2[2]) ? htons ( strtol ( row2[2], NULL, 10 )) : 0;
					alert->ip_ttl      = (row2[3]) ? strtol ( row2[3], NULL, 10 ) : 0;
					alert->ip_proto    = (row2[4]) ? strtol ( row2[4], NULL, 10 ) : 0;
					alert->ip_src_addr = (row2[5]) ? htonl ( strtoul ( row2[5], NULL, 10 )) : 0;
					alert->ip_dst_addr = (row2[6]) ? htonl ( strtoul ( row2[6], NULL, 10 )) : 0;
				}

				DB_free_result ( res2 );
			}

			/* Parsing TCP header information */
			memset ( query, 0, sizeof ( query ));
			snprintf ( query, sizeof ( query ), "select tcp_sport, tcp_dport, tcp_seq, tcp_ack, tcp_flags, tcp_win "
					"from tcphdr where cid='%d'", latest_cid );

			pthread_mutex_lock ( &mutex );

			if ( !( res2 = (DB_result) DB_query ( query )))
			{
				pthread_mutex_unlock ( &mutex );
				DB_close();
				AI_fatal_err ( "Fatal error while executing a query on the database", __FILE__, __LINE__ );
			}

			pthread_mutex_unlock ( &mutex );

			if (( rows = DB_num_rows ( res2 )) < 0 ) {
				DB_close();
				AI_fatal_err ( "Could not store the query result", __FILE__, __LINE__ );
			} else if ( rows > 0 ) {
				if (( row2 = DB_fetch_row ( res2 )))
				{
					alert->tcp_src_port  = (row2[0]) ? htons ( strtol  ( row2[0], NULL, 10 )) : 0;
					alert->tcp_dst_port  = (row2[1]) ? htons ( strtol  ( row2[1], NULL, 10 )) : 0;
					alert->tcp_seq       = (row2[2]) ? htonl ( strtoul ( row2[2], NULL, 10 )) : 0;
					alert->tcp_ack       = (row2[3]) ? htonl ( strtoul ( row2[3], NULL, 10 )) : 0;
					alert->tcp_flags     = (row2[4]) ? strtol  ( row2[4], NULL, 10 ) : 0;
					alert->tcp_window    = (row2[5]) ? htons ( strtol  ( row2[5], NULL, 10 )) : 0;
				}

				DB_free_result ( res2 );
			}

			/* Finding the associated stream info, if any */
			if ( alert->ip_proto == IPPROTO_TCP )
			{
				key.src_ip   = alert->ip_src_addr;
				key.dst_port = alert->tcp_dst_port;

				if (( info = AI_get_stream_by_key ( key )))
				{
					AI_set_stream_observed ( key );
					alert->stream = info;
				}
			}

			/* Creating a new alert log if it doesn't exist, or appending the current alert to the log */
			if ( !alerts )
			{
				alerts = alert;
				alerts->next = NULL;
			} else {
				for ( tmp = alerts; tmp->next; tmp = tmp->next );
				tmp->next = alert;
			}
		}
		
		/* Get, if available, the geographical coordinates of the attacking IP address */
		if ( alert->ip_src_addr )
		{
			memset ( ip, 0, sizeof ( ip ));
			inet_ntop ( AF_INET, &(alert->ip_src_addr), ip, sizeof ( ip ));
			HASH_FIND_STR ( geoip, ip, found );

			if ( !found )
			{
				if ( !( found = (AI_geoip_cache*) malloc ( sizeof ( AI_geoip_cache ))))
				{
					AI_fatal_err ( "Fatal dynamic memory allocation error", __FILE__, __LINE__ );
				}

				geocoord = NULL;
				strcpy ( found->ip, ip );

				if ( AI_geoinfobyaddr ( ip, &geocoord ) > 0 )
				{
					found->geocoord[0] = geocoord[0];
					found->geocoord[1] = geocoord[1];
				} else {
					found->geocoord[0] = 0.0;
					found->geocoord[1] = 0.0;
				}

				HASH_ADD_STR ( geoip, ip, found );
				free ( geocoord );
			}

			alert->geocoord[0] = found->geocoord[0];
			alert->geocoord[1] = found->geocoord[1];
		}

		DB_free_result ( res );
		latest_time = time ( NULL );

		AI_serializer ( alert );
	}

	DB_close();
	pthread_exit ((void*) 0 );
	return (void*) 0;
}		/* -----  end of function AI_db_alert_parse  ----- */
示例#4
0
int default_init(const char *path)
{
    return DB_init(path);
}