예제 #1
0
파일: pfilter.c 프로젝트: BobBall/sm
static void fail_retry(struct ipq_handle **h)
{
        ipq_perror("passer");
        ipq_destroy_handle(*h);

        *h = make_ipq();
}
int delay_cleanup()
{
    printf("Clean up buffering\n");
    ipq_destroy_handle(h);
//	pthread_cancel(pthread);
//	pthread_join(pthread, NULL);
}
예제 #3
0
void NS_CLASS packet_input_cleanup()
{
#ifndef NS_PORT
    ipq_destroy_handle(h);
#endif
    return;
}
예제 #4
0
void NS_CLASS packet_input_cleanup()
{
    packet_queue_destroy();

#ifndef NS_PORT
    ipq_destroy_handle(h);
#endif
}
/* InitInline is called before the Snort_inline configuration file is read. */
int InitInline()
{
    int status;

#ifdef DEBUG_GIDS
    printf("Initializing Inline mode \n");
#endif

    printf("Initializing Inline mode \n");

#ifndef IPFW
    ipqh = ipq_create_handle(0, PF_INET);
    if (!ipqh)
    {
        ipq_perror("InlineInit: ");
        ipq_destroy_handle(ipqh);
        exit(1);
    }
 
    status = ipq_set_mode(ipqh, IPQ_COPY_PACKET, PKT_BUFSIZE);
    if (status < 0)
    {
        ipq_perror("InitInline: ");
        ipq_destroy_handle(ipqh);
        exit(1);
    }
#endif /* IPFW */

    ResetIV();

    /* Just in case someone wants to write to a pcap file
     * using DLT_RAW because iptables does not give us datalink layer.
     */
    pd = pcap_open_dead(DLT_RAW, SNAPLEN);

    return 0;
}
예제 #6
0
int main(int argc, char **argv)
{
	int status;
	unsigned char buf[BUFSIZE];
	struct ipq_handle *h;
            
	h = ipq_create_handle(0, PF_INET);
	if (!h)
		die(h);

	status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
	if (status < 0)
		die(h);

	do {
		status = ipq_read(h, buf, BUFSIZE, 0);
		if (status < 0)
			die(h);

		switch (ipq_message_type(buf)) {
			case NLMSG_ERROR:
				fprintf(stderr, "Received error message %d\n",
					ipq_get_msgerr(buf));
				break;
			case IPQM_PACKET:
				ipq_packet_msg_t *m = ipq_get_packet(buf);
				struct iphdr *ip = (struct iphdr*) m->payload;
				struct tcphdr *tcp = (struct tcphdr*) (m->payload + (4 * ip->ihl));  
				int port = htons(tcp->dest);
				status = ipq_set_verdict(h, m->packet_id,
							 NF_ACCEPT, 0, NULL);
				if (status < 0)
					die(h);
				break;
			default:
				fprintf(stderr, "Unknown message type!\n");
				break;
		}
	} while (1);

	ipq_destroy_handle(h);
	return 0;
}
예제 #7
0
파일: daq_ipq.c 프로젝트: remfalc/vyt-daq
static void ipq_daq_shutdown (void* handle)
{
    IpqImpl* impl = (IpqImpl*)handle;

    if ( impl->ipqh )
        ipq_destroy_handle(impl->ipqh);

    if ( impl->device )
        free(impl->device);

    if ( impl->link )
        eth_close(impl->link);

    if ( impl->net )
        ip_close(impl->net);

    if ( impl->filter )
        free(impl->filter);

    if ( impl->buf )
        free(impl->buf);

    free(impl);
}
예제 #8
0
파일: libero.c 프로젝트: dosuser/libero2
void *processing(void *t){
	packet_ctx *ctx;
	int status;	

	do{
		/*********************************************
		* process쓰레드 들이 동시에 큐에 달라 붙어서 같은 자료를 처리 할수 있다.
		* 이 경우 어느 한쪽에서 메시지를 처리하고 메모리를 해제하면 나머지 쪽에서 문제가 생길수 있다. 
		* 그래서 큐에서 하나의 쓰레드에만 값을 넘겨 줘야 한다.
		**************************************************/
		pthread_mutex_lock(&queueLock);/*{{{*/
		if(ReadyQueue.currentSize>0){
			ctx = safe_dequeue(&ReadyQueue);
			pthread_mutex_unlock(&queueLock);
		}
		else{
			pthread_mutex_unlock(&queueLock);
			continue;
		}
/*}}}*/

	//에러 처리
		if(ctx==NULL) continue;/*{{{*/
			dlog(0,"processing\n");
			if (status < 0){
				die(ctx->h);
			}
/*}}}*/
                        
			switch (ipq_message_type(ctx->buf)) {
				//에러 처리
				case NLMSG_ERROR:
					dlog(0, "Received error message %d\n",
					ipq_get_msgerr(ctx->buf));
					break;
				case IPQM_PACKET: {
					/**********************
					*초기 변수 설정
					*
					*************************/
					ipq_packet_msg_t *m = ipq_get_packet(ctx->buf);/*{{{*/
					struct tcphdr *tcp=NULL;
					struct iphdr *ip=NULL;
					unsigned char *packet = NULL;
					unsigned char *tcpPayload=NULL;
					module_prototype module= NULL;
					int result=0;
					GListInfo *moduleList;
					sin_packet_info *packetInfo = malloc(sizeof(sin_packet_info));

					memset(packetInfo,0,sizeof(sin_packet_info));
					
					


					dump_ipq(m);/*}}}*/

					if(m->data_len > sizeof(struct iphdr)){
						packet = (unsigned char *)m + sizeof(ipq_packet_msg_t);//sizeof(*m)
					}
					
					ip =(struct iphdr *) packet;
					if(ip->protocol != 6){ //6 is TCP protocol number
						ipq_set_verdict(ctx->h,m->packet_id,NF_ACCEPT,0,NULL);
					}
					
					tcp =(struct tcphdr *) packet + sizeof(struct iphdr);
					dump_ip((struct iphdr *)packet);
					dump((char *)tcp,240);
					
					/***********************************
						packetInfo 설정

					***********************************/
				
					if(strcmp(m->outdev_name,"eth0")==0){
						packetInfo->direction = C2OUT;
					}else if(strcmp(m->indev_name,"eth0")==0){
						packetInfo->direction = OUT2C;
					}
					packetInfo->verdicted = 0;
					packetInfo->modified=0;
					packetInfo->action =SIN_ACCEPT;

				

					/************************
						분류기

					************************/
					/*
					while(0){
						char bound=-1;
						gpointer n;
						if(bound==C2O){//만일 패킷이 클라이언트에서 외부로 나가는 경우이면
							
							n = tree_find(&BWList, ip->daddr, NULL);
							if(n != NULL){
								cond *data = (cond *)n;
								if(data->type==DENY){
									if(data->action == CONNECTION_CLOSE){
										sessionManager(ctx->h,m->packet_id,CONNECTION_CLOSE);
										continue;// 다음 패킷 처리
								}
								}
								if(data->type==ALLOW){
									if(data->action == CONNECTION_ALLOW){
										sessionManager(ctx->h,m->packet_id,CONNECTION_ALLOW);
										continue;// 다음 패킷 처리

									}
								}
							}
						}
					}
					*/
					


							



					/**********************
					*  run modules 
					************************/					
					glist_rewind(&ModuleList);
					while((module=(module_prototype)glist_next(&ModuleList))!=NULL){
						result = (*module)(ctx->h,m,(const char*)tcp,240);
						/**********
						*허용이 아닌 경우 중단으로 해야 한다. 
						*이유는 ACCEPT이지만 다른 종류의 메시지를 보내야 하는 경우도 있기 때문이다.
						*다만 이 경우에 어떻게 하는게 좋을지 아직 모르겠다.
						***********/
						if(result == NF_DROP) break;
					}
					/*********************
					* 위에서 처리 한 결과대로 처리한다.
					* verdict는 한번만 호출되어야 하는것 같다.
					***********************/



					/********************
						윈도우 사이즈 조절
					*******************/
					if(result==NF_ACCEPT && ip->protocol == 6){
						uint16_t win;
						#if __BYTE_ORDER == __LITTLE_ENDIAN
							win = ntohs(tcp->window);
							if(win>MAXIMUM_WINDOW_SIZE){
								tcp->window =htons(MAXIMUM_WINDOW_SIZE);
								packetInfo->modified=1;
								//패킷을 수정 했으니 이것을 verdict 하도록 수정해야한다.

							}
						#elif __BYTE_ORDER == __BIG_ENDIAN
							if(win>MAXIMUM_WINDOW_SIZE) {
								tcp->window = MAXIMUM_WINDOW_SIZE;
								packetInfo->modified=1;
								//패킷을 수정 했으니 이것을 verdict 하도록 수정해야한다. 
						#endif
					}
					if(	packetInfo->modified == 0){
						status = ipq_set_verdict(ctx->h, m->packet_id,result, 0, NULL);
					}else{
						/*******************
							패킷 수정됐으니 체크섬 재계산-_-
						*******************/
						status = ipq_set_verdict(ctx->h, m->packet_id,result, 0,NULL);
					}

					if (status < 0) die(ctx->h);
					break;
        		                }
				default:
					fprintf(stderr, "Unknown message type!\n");
					break;
	}
	} while (1);
        
	ipq_destroy_handle(ctx->h);
	return 0;


}
예제 #9
0
int main(int argc, char **argv) 
{ 
	int status; 
	char str[100];
	char input[2];
	long interval = 0;
	int  i = 0;
	struct tw_pkt* tmp = NULL;
	pthread_t p;

	h = ipq_create_handle(0, PF_INET); 
	status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
	if(status < 0){
		die();
	}
	memset(str, 0, 100);
	memset(input, 0, 2);
	pre.tv_sec = now.tv_sec = 0;
	pre.tv_usec = now.tv_usec = 0;
	my_pkt_head.count = 0;
	my_pkt_head.head = my_pkt_head.end = NULL;

	printf("input a string\n");
	fgets(str, 100, stdin);
//	memcpy(str, argv[1], 100);
	encode(str, 100);
	
	input[0] = 1;
	
   	connect_to_kernel(input);

	printf("start to send information...\n");

	do{ 
		struct tw_pkt* tmp = malloc(sizeof(struct tw_pkt));
		memset(tmp->buf, 0, BUFSIZE);
		tmp->pre = tmp->next = NULL;
		status = ipq_read(h, tmp->buf, BUFSIZE, 0); 
		if(status < 0){
			die();
		}
		switch (ipq_message_type(tmp->buf)) { 
			case NLMSG_ERROR:{ 
				fprintf(stderr, "Received error message %d ", 
						ipq_get_msgerr(tmp->buf)); 
				break; 
			}
			case IPQM_PACKET:{ 
				ipq_packet_msg_t *m = ipq_get_packet(tmp->buf);
				printf("%ld packet_id rcv \n", m->packet_id);		
				enqueue(tmp);
				i++;
				if(i == 2){
					pthread_create(&p, NULL, tw_send, NULL);
				}
				break; 
			} 
			default:{
				fprintf(stderr, "Unknown message type! "); 
				break;
			}
		}
	} while (1); 

	input[0] = 2;
	connect_to_kernel(input);
	
	ipq_destroy_handle(h); 
	return 0; 
} 
예제 #10
0
void die() 
{ 
	ipq_perror("passer"); 
	ipq_destroy_handle(h); 
	exit(1); 
} 
예제 #11
0
static void die(struct ipq_handle *h)
{
    packet_queue_destroy();
    ipq_destroy_handle(h);
    exit(1);
}
예제 #12
0
파일: main.c 프로젝트: ebichu/dd-wrt
// Main entry point to application
int main(int argc, char *argv[])
{
	BYTE MsgBuff[MAXIPQMSG];
	struct sigaction SigAction;
	int i;

	// Read config & parameters
	if(!ReadConfig(argc, argv))
		return EXIT_FAILURE;

	// If we should act as neither a master nor a client (config error)
	if(!(Config.Flags & CONFIGFLAGS_MASTER) && !(Config.Flags & CONFIGFLAGS_CLIENT)){
		printf(APPTITLE": not configured to run as a master nor client\n");
		return EXIT_FAILURE;
	}

	// If we're to be a client, check we have an IP
	if(Config.Flags & CONFIGFLAGS_CLIENT && Config.MasterIp[0] == 0x00){
		printf(APPTITLE": Can not run as a client, no master IP specified 0x%02X\n", Config.Flags);
		return EXIT_FAILURE;
	}

	// Let the user know we're thinking of them
	if(Config.Flags & CONFIGFLAGS_MASTER)
		Log(LOG_NOTICE, "Acting as a master on port %d", Config.MasterPort);
	if(Config.Flags & CONFIGFLAGS_SELFCLIENT)
		Log(LOG_NOTICE, "Acting as a self-client with %d packet queues", Config.Queue);
	if(Config.Flags & CONFIGFLAGS_CLIENT)
		Log(LOG_NOTICE, "Acting as a client to %s:%d with %d packet queues", Config.MasterIp, Config.MasterPort, Config.Queue);
	else
		Log(LOG_NOTICE, "Acting stupid");

	// If we should daemonise
	if(Config.Flags & CONFIGFLAGS_DAEMON)
		// Daemonise
		Daemon();

	// If we should act as a master
	if(Config.Flags & CONFIGFLAGS_MASTER){

		// If we should act as _only_ a master
		if(!(Config.Flags & CONFIGFLAGS_CLIENT) && !(Config.Flags & CONFIGFLAGS_SELFCLIENT)){

			// Jump to main function in master.c which will perform this function
			MasterRun(NULL);

			return EXIT_SUCCESS;
		}
		// If we should act as a client as well
		else{

			// Start main thread in master.c which will perform this function
			pthread_create(&idMasterThread, NULL, &MasterRun, NULL);
		}
	}

	// Create an IPQ handle
	hIpq = ipq_create_handle(0, PF_INET);
	if(hIpq == NULL){

		// If we're running a master thread
		if(idMasterThread){

			// Set flag & wait for master thread to exit
			ExitMasterThread = 1;
			pthread_join(idMasterThread, NULL);
		}

		// Log it
		Log(LOG_ERR, "Failed to initialise IPQ (%s)", ipq_errstr());

		return EXIT_FAILURE;
	}

	// Set mode. Note: We set to packet mode so that we get to see the
	// number of bytes in the payload, the payload itself is ignored
	if (ipq_set_mode(hIpq, IPQ_COPY_PACKET, 0) == -1){

		// If we're running a master thread
		if(idMasterThread){

			// Set flag & wait for master thread to exit
			ExitMasterThread = 1;
			pthread_join(idMasterThread, NULL);
		}

		// Release IPQ
		ipq_destroy_handle(hIpq);

		// Tell the user
		Log(LOG_ERR, "Failed to configure IPQ (%s)", ipq_errstr());

		return EXIT_FAILURE;
	}

	// Allocate Packet queue memory
	for(i = 0; i < PacketQueues; i++)
		PacketQueue[i] = malloc(Config.Queue * sizeof(struct ipq_packet_msg));

	// Check allocations worked
	if(!PacketQueue){

		// Free anything that was allocated
		if(PacketQueue)
			free(PacketQueue);

		// If we're running a master thread
		if(idMasterThread){

			// Set flag & wait for master thread to exit
			ExitMasterThread = 1;
			pthread_join(idMasterThread, NULL);
		}

		// Release IPQ
		ipq_destroy_handle(hIpq);

		// Tell the user
		Log(LOG_ERR, "Failed to allocate sufficant memory");

		return EXIT_FAILURE;
	}

	// Inititalise the PacketQueue mutex
	pthread_mutex_init(&PacketQueueMutex, NULL);

	// If we're acting as a normal client
	if(Config.Flags & CONFIGFLAGS_CLIENT)
		// Start control thread
		pthread_create(&idControlThread, NULL, &ControlRun, NULL);

	// Install SIGTERM/etc handler to get out of 'while(!ExitMain)'
	memset(&SigAction, 0, sizeof(SigAction));
	SigAction.sa_handler = SignalHandler;
	sigaction(SIGINT, &SigAction, NULL);
	sigaction(SIGQUIT, &SigAction, NULL);
	sigaction(SIGTERM, &SigAction, NULL);
	// Install SIGHUP handler to reread config
	sigaction(SIGHUP, &SigAction, NULL);

	// Tell user
	Log(LOG_INFO, "Client up and running");

	// Enter main loop
	while(!ExitMain){

		// Wait up to 100mS to recieve a message
		int MsgSize = ipq_read(hIpq, MsgBuff, MAXIPQMSG, 100);

		// Error getting message
		if(MsgSize == -1){

			// TODO: This has started to happen occasionally. Don't know why.
			// ipq_errstr() = "Failed to receive netlink message"

			// Tell the user
			Log(LOG_ERR, "Error reading message from IPQ (%s)", ipq_errstr());
		}

		// Timeout getting message
		else if(MsgSize == 0){

			// Do background processing
			BackgroundProcessing();
		}

		// Got a message
		else{

			// Switch on message type
			switch (ipq_message_type(MsgBuff)){

			case NLMSG_ERROR:

				// Apparently we should call this (to clear the error?)
				ipq_get_msgerr(MsgBuff);

				// Tell the user
				Log(LOG_ERR, "Error reading message type from IPQ (%s)", ipq_errstr());
				break;

			case IPQM_PACKET:

				// Call a function to process the packet
				ProcessPacketMessage(ipq_get_packet(MsgBuff));

				// Do background processing
				BackgroundProcessing();
				break;

			default:

				// Tell the user
				Log(LOG_WARNING, "Undefined message type from IPQ");
				break;
			}
		}
	}

	// If we're running a control thread
	if(idControlThread){

		// Set flag & wait for control thread to exit
		ExitControlThread = 1;
		pthread_join(idControlThread, NULL);
	}

	// If we're running a master thread
	if(idMasterThread){

		// Set flag & wait for master thread to exit
		ExitMasterThread = 1;
		pthread_join(idMasterThread, NULL);
	}

	// Release IPQ
	ipq_destroy_handle(hIpq);

	// Release Packet queue memory
	for(i = 0; i < PacketQueues; i++)
		free(PacketQueue[i]);

	// Let the user know we're thinking of them
	Log(LOG_INFO, "Exited cleanly");

	return EXIT_SUCCESS;
}
예제 #13
0
int main()
{
 int status;
 unsigned char buf[BUFSIZE];
 struct ipq_handle *h;
printf("!@#");
 char *ip_dst_s="202.108.22.5";
 h = ipq_create_handle(0, PF_INET);
 if (!h)
  die(h);
                
 status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
 if (status < 0)
  die(h);
                
 do{

  status = ipq_read(h, buf, BUFSIZE, 0);
printf("!@#");
/*  if (status < 0)
   die(h);
                        
  switch (ipq_message_type(buf)) {
   case NLMSG_ERROR:
    fprintf(stderr, "Received error message %d/n",
      ipq_get_msgerr(buf));
    break;
                                
   case IPQM_PACKET: {
    ipq_packet_msg_t *m = ipq_get_packet(buf);
    struct libnet_ipv4_hdr* iph;
    iph=(struct libnet_ipv4_hdr*)m->payload;
    if(m->data_len<20){
     fprintf(stderr, "ip header is too short/n");
     die(h);
    }

    char *dst = libnet_addr2name4(iph->ip_dst.s_addr, LIBNET_DONT_RESOLVE);
    
    if(!strcmp(dst, ip_dst_s)){
      status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
     printf("dst ip:%s state: accept/n", dst);
    }
    else{
     status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL);
     printf("dst ip:%s state: drop/n", dst);
    }
 
    if (status < 0)
     die(h);
    break;
   }
   default:
    fprintf(stderr, "Unknown message type!/n");
    break;
  }*/
 } while (1);

 ipq_destroy_handle(h);
 return 0;
}
예제 #14
0
int main(int argc, char **argv)
{
	int status;
	unsigned char buf[BUFSIZE];
	struct ipq_handle *h;
	struct iphdr *iphead;
	h = ipq_create_handle(0, PF_INET);
	if (!h)
		die(h);
		
	status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
	if (status < 0)
		die(h);
		
	do{
		status = ipq_read(h, buf, BUFSIZE, 0);
		if (status < 0)
			die(h);
			
		switch (ipq_message_type(buf)) {
			case NLMSG_ERROR:
				fprintf(stderr, "Received error message %d\\n",
				        ipq_get_msgerr(buf));
				break;
				
			case IPQM_PACKET: {
				ipq_packet_msg_t *m = ipq_get_packet(buf);
				char *dest = NULL;
				struct in_addr daddr;
				iphead = (struct iphdr *)m->payload;

				if(iphead->daddr == inet_addr(TO))
				{
					status = ipq_set_verdict(h,m->packet_id,
							NF_ACCEPT,0,NULL);
					if(status < 0)
						die(h);
					break;
				}
				else
				{
					status = ipq_set_verdict(h,m->packet_id,
							NF_DROP,0,NULL);
					if(status < 0)
						die(h);
					break;
				}			


			//	status = ipq_set_verdict(h, m->packet_id,
			//	                         NF_ACCEPT, 0, NULL);
			//	if (status < 0)
			//		die(h);
			//	break;
			}
			
			default:
				fprintf(stderr, "Unknown message type!\\n");
				break;
		}
	} while (1);
	
	ipq_destroy_handle(h);
	return 0;
}
예제 #15
0
파일: pfilter.c 프로젝트: BobBall/sm
int main(int argc, char **argv)
{
        int verdict;
        unsigned char buf[BUFSIZE];
        struct ipq_handle *h;
        int cfd;
        int daemonize = 1;

        if (argc > 1) {
            if (!strcmp(argv[1], "-nd")) {
                daemonize = 0;
            }
        }

        srand(0);

        cfd = make_ipc();
        if ( cfd < 0 )
                exit(1);

        printhelp();

        h = make_ipq();

        if (daemonize) {
                FILE *logfile = 0;
                int pid;

                logfile = fopen(LOGFILE, "a");
                if (!logfile) {
                        perror("Failed to open " LOGFILE);
                        exit(1);
                }

                if ( daemon(0, 0) < 0 ) {
                        perror("Failed to daemonize");
                        exit(1);
                }

                if ( dup2(fileno(logfile), STDERR_FILENO) < 0 )
                        abort();
                fclose(logfile);

                pid = writepid();
                if (pid < 0)
                        return -1;

                /* disable low water mark check for io pages */
                if (setpriority(PRIO_PROCESS, pid, PRIO_SPECIAL_IO)) {
                        perror("Unable to prioritize tapdisk proc");
                        exit(1);
                }
                
                TRACE("Start pfilter PID %d\n", pid);
        }

        do {
                ssize_t status;
                int type;

                status = ipq_read(h, buf, BUFSIZE, 0);
                if (status < 0)
                        fail_retry(&h);

                type = ipq_message_type(buf);
                switch (type) {
                        case NLMSG_ERROR:
                                TRACE("pfilter: Received error message %d\n",
                                      ipq_get_msgerr(buf));
                                break;

                        case IPQM_PACKET: {
                                ipq_packet_msg_t *m = ipq_get_packet(buf);

                                verdict = filter();

                                status = ipq_set_verdict(h, m->packet_id,
                                                         verdict, 0, NULL);
                                if (status < 0)
                                        fail_retry(&h);

                                trace_data(verdict);
                                break;
                        }

                        default:
                                TRACE("pfilter: Unknown message type: %d\n", type);
                                break;
                }
        } while (1);

        ipq_destroy_handle(h);
        return 0;
}
예제 #16
0
static void die(struct ipq_handle *h)
{
	ipq_perror("passer");
	ipq_destroy_handle(h);
	exit(1);
}
예제 #17
0
int main(int argc, const char ** argv)
{
    static u8 buf[LTP_MAX_BUF_SIZE];
    struct ipq_handle *h = ipq_create_handle(0, NFPROTO_IPV4);

    if (!h) {
        LTP_ERROR_LOG("ipq_create_handle failed\n");
        goto error1;
    }

    int ret = ipq_set_mode(h, IPQ_COPY_PACKET, LTP_MAX_BUF_SIZE);
    if (-1 == ret) {
        LTP_ERROR_LOG("ipq_set_mode failed\n");
        goto error2;
    }

    register_exit_signal_handler();

    while (!g_ltp_daemon_exit) {
        ret = ipq_read(h, buf, LTP_MAX_BUF_SIZE, 0);
        if (ret < 0) {
            LTP_ERROR_LOG("ipq_read failed\n");
            goto error2;
        }
        ret = ipq_message_type(buf);
        if (likely(IPQM_PACKET == ret)) {
            LTP_DEBUG_LOG("Get one packet\n");
            ipq_packet_msg_t *pkt = ipq_get_packet(buf);
            if (likely(pkt)) {
            
                if (LTP_OK != ltp_ipq_rcv(pkt)) {
                    // Need not the error handler
                    LTP_ERROR_LOG("ltp_ipq_rcv failed\n");
                }
                
                ret = ipq_set_verdict(h, pkt->packet_id, NF_DROP, pkt->data_len, pkt->payload);
                if (-1 == ret) {
                    LTP_ERROR_LOG("ipq_set_verdict failed\n");
                    goto error2;
                }
                
            }
            else {
                LTP_ERROR_LOG("ipq_get_packet failed\n");
                goto error2;
            }
        }
        else if (NLMSG_ERROR == ret) {
            LTP_ERROR_LOG("Recevie error msg(%d)\n", ipq_get_msgerr(buf));
            goto error2;
        }
        else {
            LTP_ERROR_LOG("Unknown type\n");
            goto error2;
        }
    }

    ipq_destroy_handle(h);

    return LTP_OK;

error2:
    ipq_destroy_handle(h);
    h = NULL;
error1:
    return LTP_ERR;
}
int main(int argc, char **argv)
{
   int status, i;
   unsigned int payload_len, payload_offset;
   unsigned char buf[BUFSIZE], listtype[8];
   struct ipq_handle *h;
   unsigned char *match, *folder, *url;
   PURL current;

   strcpy (listtype, argv[1]);
   get_url_info();

   h = ipq_create_handle(0, PF_INET);
   if (!h)
   {
      die(h);
   }

   status = ipq_set_mode(h, IPQ_COPY_PACKET, BUFSIZE);
   if (status < 0)
   {
      die(h);
   }

   do
   {
      memset(buf, 0, sizeof(buf));
      status = ipq_read(h, buf, BUFSIZE, 0);
      if (status < 0)
      {
         die(h);
      }

      switch (ipq_message_type(buf)) 
      {
         case NLMSG_ERROR:
         {
            fprintf(stderr, "Received error message %d\n",
            ipq_get_msgerr(buf));
            break;
         }

         case IPQM_PACKET:  
         {
            ipq_packet_msg_t *m = ipq_get_packet(buf);
            char decision = 'n';
            struct iphdr *iph = ((struct iphdr *)m->payload);
            struct tcphdr *tcp = (struct tcphdr *)(m->payload + (iph->ihl<<2));
            match = folder = url = NULL;
            payload_offset = ((iph->ihl)<<2) + (tcp->doff<<2);
            payload_len = (unsigned int)ntohs(iph->tot_len) - ((iph->ihl)<<2) + (tcp->doff<<2);
            match = (char *)(m->payload + payload_offset);

            if(strstr(match, "GET ") == NULL && strstr(match, "POST ") == NULL && strstr(match, "HEAD ") == NULL)
            {
               status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
//printf("****NO HTTP INFORMATION!!!\n");
               if (status < 0)
               {
                  die(h);
               }
								
               break;		  
            }
	    
            for (current = purl; current != NULL; current = current->next)
            {
               if (current->folder[0] != '\0')
               {
                  folder = strstr(match, current->folder);
               }
//printf("####payload = %s\n\n", match);

               if ( (url = strstr(match, current->website)) != NULL ) 
               {
                  if (strcmp(listtype, "Exclude") == 0) 
                  {
                     if ( (folder != NULL) || (current->folder[0] == '\0') )
                     {
                        status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL);
//printf("####This page is blocked by Exclude list!");
                        decision = 'y';
										
                     }
                     else 
                     {
                        status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
//printf("###Website hits but folder no hit in Exclude list! packets pass\n");
                        decision = 'y';
                     }

                     if (status < 0)
                     {
                        die(h);
                     }
								
                     break;
									
                  }
                  else 
                  {
                     if ( (folder != NULL) || (current->folder[0] == '\0') )
                     {
                        status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
//printf("####This page is accepted by Include list!");
                        decision = 'y';
                     }
                     else 
                     {
                        status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL);
//printf("####Website hits but folder no hit in Include list!, packets drop\n");
                        decision = 'y';
                     }
										
                     if (status < 0)
                     {
                        die(h);
                     }

                     break;
                  }
               }
            }

            if (url == NULL) 
            {
               if (strcmp(listtype, "Exclude") == 0) 
               {
                  status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
//printf("~~~~No Url hits!! This page is accepted by Exclude list!\n");
                  decision = 'y';
               }
               else 
               {
                  status = ipq_set_verdict(h, m->packet_id, NF_DROP, 0, NULL);
//printf("~~~~No Url hits!! This page is blocked by Include list!\n");
                  decision = 'y';
               }

               if (status < 0)
               {
                  die(h);
               }
            }
								
            if (decision == 'n') 
            {
               ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);
//printf("~~~None of rules can be applied!! Traffic is allowed!!\n");
            }

            break;
         }

         default:
         {
            fprintf(stderr, "Unknown message type!\n");
            break;
         }
      }
   } while (1);

   ipq_destroy_handle(h);
   return 0;
}
예제 #19
0
static void die(struct ipq_handle *h)
{
    DEBUG(LOG_WARNING, 0, "Netfilter ERROR");
    ipq_destroy_handle(h);
    exit(1);
}
예제 #20
0
ip_noise_arbitrator_packet_logic_t * main_init_module(
        ip_noise_arbitrator_iface_t * * iface_ptr
        )
#endif
{
#ifndef __KERNEL__    
    int status;

    unsigned char message[IP_NOISE_MESSAGE_BUFSIZE];
    struct ipq_handle * h;

    ip_noise_messages_queue_t * packets_to_arbitrate_queue;
#endif
    int terminate = 0;
    
    ip_noise_decide_what_to_do_with_packets_thread_context_t * arbitrator_context;

#ifndef __KERNEL__
    pthread_t decide_what_to_with_packets_thread;
#endif    
    
    ip_noise_release_packets_thread_context_t * release_packets_context;
#ifndef __KERNEL__
    pthread_t release_packets_thread;
#endif
#ifndef __KERNEL__
    int check;
#endif
    ip_noise_delayer_t * delayer;

    ip_noise_arbitrator_data_t * data, * * data_ptr;
    ip_noise_flags_t flags;
    ip_noise_arbitrator_iface_t * arb_iface;
#ifndef __KERNEL__
    pthread_t arb_iface_thread;
#endif

    ip_noise_arbitrator_switcher_t * arb_switcher;
#ifndef __KERNEL__
    pthread_t arb_switcher_thread;
#endif
#ifdef __KERNEL__
    ip_noise_arbitrator_packet_logic_t * packet_logic;
#endif

    printf("IP-Noise Simulator\n");
    printf("Written by Shlomi Fish & Roy Glasberg and supervised by Lavy Libman\n");
    printf("The Technion - Israel Institute of Technolgy\n");
    printf("(c) 2001\n");

#ifndef __KERNEL__
    h = ipq_create_handle(0, PF_INET);
    if (h == NULL)
    {
        die(h);
    }

    status = ipq_set_mode(h, IPQ_COPY_PACKET, sizeof(message));

    if (status < 0)
    {
        die(h);
    }
#endif

#ifndef __KERNEL__
    packets_to_arbitrate_queue = ip_noise_messages_queue_alloc();
#endif

    delayer = ip_noise_delayer_alloc(
            ip_noise_delayer_release_function, 
#ifndef __KERNEL__
            (void *)h
#else
            NULL
#endif            
            );
    
    release_packets_context = malloc(sizeof(ip_noise_release_packets_thread_context_t));
    release_packets_context->delayer = delayer;
    release_packets_context->terminate = &terminate;

#ifndef __KERNEL__
    check = pthread_create(
        &release_packets_thread,
        NULL,
        release_packets_thread_func,
        (void *)release_packets_context
        );

    if (check != 0)
    {
        fprintf(stderr, "Could not create the release packets thread!\n");
        exit(-1);
    }
#endif

    data = ip_noise_arbitrator_data_alloc();
    data_ptr = malloc(sizeof(*data_ptr));
    *data_ptr = data;

    flags.reinit_switcher = 1;

    arb_switcher = ip_noise_arbitrator_switcher_alloc(data_ptr, &flags, &terminate);

#ifndef __KERNEL__
    check = pthread_create(
        &arb_switcher_thread,
        NULL,
        arb_switcher_thread_func,
        (void *)arb_switcher
        );

    if (check != 0)
    {
        fprintf(stderr, "Could not create the arbitrator switcher thread!\n");
        exit(-1);
    }
#endif

    arb_iface = ip_noise_arbitrator_iface_alloc(data_ptr, arb_switcher, &flags);

#ifdef __KERNEL__
    /*
     * We assign arb_iface to iface_ptr so it can later be de-allocated
     * inside the module ip_queue.c.
     *
     * */
    *iface_ptr = arb_iface;
#endif

#ifndef __KERNEL__
    check = pthread_create(
        &arb_iface_thread,
        NULL,
        arb_iface_thread_func,
        (void *)arb_iface
        );

    if (check != 0)
    {
        fprintf(stderr, "Could not create the arbitrator interface thread!\n");
        exit(-1);
    }
#endif


    arbitrator_context = malloc(sizeof(ip_noise_decide_what_to_do_with_packets_thread_context_t));
#ifndef __KERNEL__
    arbitrator_context->queue = packets_to_arbitrate_queue ;
    arbitrator_context->h = h;
#endif    
    arbitrator_context->terminate = &terminate;
    arbitrator_context->delayer = delayer;
    arbitrator_context->data = data_ptr;
    arbitrator_context->flags = &flags;

#ifndef __KERNEL__
    check = pthread_create(
        &decide_what_to_with_packets_thread,
        NULL,
        ip_noise_decide_what_to_do_with_packets_thread_func,
        (void *)arbitrator_context
        );

    if (check != 0)
    {
        fprintf(stderr, "Could not create the arbitrator thread!\n");
        exit(-1);
    }
#else
    packet_logic = ip_noise_arbitrator_packet_logic_alloc(data_ptr, &flags);

    return packet_logic;
    
#endif  

#ifndef __KERNEL__
    do
    {
        status = ipq_read(h, message, sizeof(message), 0);
        if (status < 0)
        {
            /* die(h); */
        }
        switch(ipq_message_type(message))
        {
            case NLMSG_ERROR:
                fprintf(
                    stderr, 
                    "Received error message %d\n",
                    ipq_get_msgerr(message)
                    );
                break;

            case IPQM_PACKET:
            {
                ip_noise_message_t * msg_with_time;
                struct timezone tz;

#if 0
                static int num = 0;
#endif

                msg_with_time = malloc(sizeof(ip_noise_message_t));

                /* We are copying the entire buffer, because otherwise we get
                 * errors, since ipq_get_packet still relies on this buffer
                 * for reference */

                memcpy(msg_with_time->message, message, sizeof(msg_with_time->message));

                msg_with_time->m = ipq_get_packet(msg_with_time->message);
                
                gettimeofday(&(msg_with_time->tv), &tz);
                
                
                ip_noise_messages_queue_enqueue(
                    packets_to_arbitrate_queue,
                    msg_with_time
                    );

#if 0
                printf("Received a message! (%i)\n", num++);
#endif

#if 0
                status = ipq_set_verdict(h, m->packet_id, NF_ACCEPT, 0, NULL);

                if (status < 0)
                {
                    die(h);
                }
#endif
                break;
            }

            default:
                fprintf(stderr, "Unknown message type!\n");
                break;                        
        }
    } while (1);
#endif

    ipq_destroy_handle(h);

    return 0;
}
예제 #21
0
static void die(struct ipq_handle * h)
{
    ipq_perror("IP-Noise Arbitrator");
    ipq_destroy_handle(h);
    exit(-1);
}
예제 #22
0
파일: sock.c 프로젝트: armedpot/honeytrap
/* returns a bound socket matching a connection request *
 * sets verdict on request packet if ipq or nfq was used and the port is already bound *
 * in the latter case, -1 is returned */
int get_boundsock(struct sockaddr_in *server_addr, uint16_t port, int type) {
    int fd, sockopt;
#ifdef USE_IPQ_MON
    int status;
#endif

    if ((type != SOCK_DGRAM) && (type != SOCK_STREAM)) {
        logmsg(LOG_ERR, 1, "Error - Socket type %d not supported.\n", type);
        exit(EXIT_FAILURE);
    }

    if (!(fd = socket(AF_INET, type, 0))) {
        logmsg(LOG_ERR, 1, "Error - Could not create socket: %m.\n");
        exit(EXIT_FAILURE);
    }

    sockopt = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(sockopt)) < 0)
        logmsg(LOG_WARN, 1, "Warning - Unable to set SO_REUSEADDR for server socket.\n");

    bzero((char *) server_addr, sizeof(struct sockaddr_in));
    server_addr->sin_family		= AF_INET;
    server_addr->sin_addr.s_addr	= bind_address.s_addr;
    server_addr->sin_port		= port;
    if ((bind(fd, (struct sockaddr *) server_addr, sizeof(struct sockaddr_in))) != 0) {
        /* we already got one server process */
        logmsg(LOG_DEBUG, 1, "Unable to bind to port %u/tcp: %m.\n", ntohs(port));
#ifdef USE_IPQ_MON
        /* hand packet processing back to the kernel */
        if ((status = ipq_set_verdict(h, packet->packet_id, NF_ACCEPT, 0, NULL)) < 0) {
            logmsg(LOG_ERR, 1, "Error - Could not set verdict on packet: %s.\n", ipq_errstr());
            ipq_destroy_handle(h);
            exit(EXIT_FAILURE);
        }
        logmsg(LOG_DEBUG, 1, "IPQ - Successfully set verdict on packet.\n");
        return(-1);
#else
#ifdef USE_NFQ_MON
        /* hand packet processing back to the kernel */
        /* nfq_set_verdict()'s return value is undocumented,
         * but digging the source of libnetfilter_queue and libnfnetlink reveals
         * that it's just the passed-through value of a sendmsg() */
        if (nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL) == -1) {
            logmsg(LOG_ERR, 1, "Error - Could not set verdict on packet.\n");
            nfq_destroy_queue(qh);
            exit(EXIT_FAILURE);
        }
        logmsg(LOG_DEBUG, 1, "NFQ - Successfully set verdict on packet.\n");

        /* a dynamic server is already present */
        close(fd);
        return(-1);
#else
        /* if bind() did not fail for 'port already in use' but for some other reason,
         *  we're in troubles and want a verbose error message */
        if (errno != 98) logmsg(LOG_NOISY, 1, "Warning - Could not bind to port %u/tcp: %m.\n", ntohs(port));
        exit(EXIT_FAILURE);
#endif
#endif
    }
    logmsg(LOG_DEBUG, 1, "Socket created, file descriptor is %d.\n", fd);

    return(fd);
}