Exemplo n.º 1
0
void *patching(void *t){
	/**************
	* 변수 설정
	*************/
	int status;/*{{{*/
	char *buf;
	struct ipq_handle *h;
	packet_ctx *ctx;
	h = (struct ipq_handle *)t;

/*}}}*/
	while(1){
		ctx = (packet_ctx *)malloc(sizeof(packet_ctx));
		ctx->buf=(char *)malloc(sizeof(char) * BUFSIZE);
		ctx->status= ipq_read(h,ctx->buf,BUFSIZE,0);
		if(ctx->status < 0){
			dlog(0,"err!\n");
			die(h);
		}
		ctx->h = h;
		dlog(0,"buffer size :%d\n",ReadyQueue.currentSize);
		
		if(ReadyQueue.currentSize<30){
			pthread_mutex_lock(&queueLock);
			safe_queue(&ReadyQueue,ctx);
			pthread_mutex_unlock(&queueLock);		
		}
		else{
					dlog(0,stderr,"sleep 1 second\n");
					sleep(1);
		}

	}

}
Exemplo n.º 2
0
void IpqLoop()
{
    int status;
    struct pcap_pkthdr PHdr;
    unsigned char buf[PKT_BUFSIZE];
    static ipq_packet_msg_t *m;

#ifdef DEBUG_GIDS
    printf("Reading Packets from ipq handle \n");
#endif

    while(1)
    {
        ResetIV();
        status = ipq_read(ipqh, buf, PKT_BUFSIZE, 1000000);
        if (status < 0)
        {
            ipq_perror("IpqLoop: ");
        }
        /* man ipq_read tells us that when a timeout is specified
         * ipq_read will return 0 when it is interupted. */
        else if(status == 0)
        {
            /* Do the signal check. If we don't do this we will
             * evaluate the signal only when we receive an actual
             * packet. We don't want to depend on this. */
            sig_check();
        }
        else
        {
            switch(ipq_message_type(buf))
            {
                case NLMSG_ERROR:
                    fprintf(stderr, "Received error message %d\n", 
                            ipq_get_msgerr(buf));
                    break;

                case IPQM_PACKET: 
                    m = ipq_get_packet(buf);
                    g_m = m;
#ifdef DEBUG_INLINE
                    printf("%02X:%02X:%02X:%02X:%02X:%02X\n", m->hw_addr[0], m->hw_addr[1],
                           m->hw_addr[2], m->hw_addr[3], m->hw_addr[4], m->hw_addr[5]);
#endif              

                    TranslateToPcap(m, &PHdr);
                    PcapProcessPacket(NULL, &PHdr, (u_char *)m->payload);
                    HandlePacket(m);
                    break;
            } /* switch */
        } /* if - else */
    } /* while() */
}
void IpqLoop()
{
    int status;
    struct pcap_pkthdr PHdr;
    unsigned char buf[PKT_BUFSIZE];
    static ipq_packet_msg_t *m;

#ifdef DEBUG_GIDS
    printf("Reading Packets from ipq handle \n");
#endif

    while(1)
    {
        ResetIV();
        status = ipq_read(ipqh, buf, PKT_BUFSIZE, 0);
        if (status < 0)
        {
            ipq_perror("IpqLoop: ");
        }
        else
        {
            switch(ipq_message_type(buf))
            {
                case NLMSG_ERROR:
                    fprintf(stderr, "Received error message %d\n", 
                            ipq_get_msgerr(buf));
                    break;

                case IPQM_PACKET: 
                    m = ipq_get_packet(buf);
                    g_m = m;
#ifdef DEBUG_INLINE
                    printf("%02X:%02X:%02X:%02X:%02X:%02X\n", m->hw_addr[0], m->hw_addr[1],
                           m->hw_addr[2], m->hw_addr[3], m->hw_addr[4], m->hw_addr[5]);
#endif              

                    TranslateToPcap(m, &PHdr);
                    PcapProcessPacket(NULL, &PHdr, (u_char *)m->payload);
                    HandlePacket(m);
                    break;
            } /* switch */
        } /* if - else */
    } /* while() */
}
Exemplo n.º 4
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;
}
int main(void)
{
    int status;
    unsigned char buf[BUFSIZE];

    packet_list_t *element;
    ipq_packet_msg_t *pmsg;

    delay_init();

    pthread_t thread;
    pthread_create(&thread, NULL, _pkg_reinject, NULL);

    do {
        /* read packets from buffer */
        status = ipq_read(h, buf, BUFSIZE, 0);
        if (status > 0) {
            switch (ipq_message_type(buf)) {
            case NLMSG_ERROR:
                printf("Received error message %d\n", ipq_get_msgerr(buf));
                break;
            case IPQM_PACKET: {
                /* adding packet to pool */
                ipq_packet_msg_t *m = ipq_get_packet(buf);
                pmsg = (ipq_packet_msg_t*)malloc(sizeof(ipq_packet_msg_t) + m->data_len);
                memcpy(pmsg, m, sizeof(ipq_packet_msg_t) + m->data_len);

                element = (packet_list_t *)malloc(sizeof(packet_list_t));
                element->pmsg = pmsg;
                list_add_tail(&(element->list), &pkg_list);
                count_packet++;
                break;
            }
            default:
                printf("Unknown message type!\n");
                break;
            }
        }
        else
            printf("ipq_read error return: %s\n",ipq_errstr());
    } while (1);
    return 0;
}
Exemplo n.º 6
0
static void packet_input(int fd)
#endif
{
    rt_table_t *fwd_rt, *rev_rt, *next_hop_rt = NULL;
    struct in_addr dest_addr, src_addr;
    u_int8_t rreq_flags = 0;
    unsigned int ifindex;
    struct ip_data *ipd = NULL;
    int pkt_flags = 0;

#ifdef NS_PORT
    ifindex = NS_IFINDEX;	/* Always use ns interface */
    fwd_rt = NULL;		/* For broadcast we provide no next hop */
    ipd = NULL;			/* No ICMP messaging */

    struct hdr_cmn *ch = HDR_CMN(p);
    struct hdr_ip *ih = HDR_IP(p);

    src_addr.s_addr = ih->saddr();
    dest_addr.s_addr = ih->daddr();

    /* If this is a TCP packet and we don't have a route, we should
       set the gratuituos flag in the RREQ. */
    if (ch->ptype() == PT_TCP) {
	rreq_flags |= RREQ_GRATUITOUS;
    }
#else
    int status;
    char buf[sizeof(struct nlmsghdr)+sizeof(ipq_packet_msg_t)+BUFSIZE];
    char *dev_name;
    ipq_packet_msg_t *pkt;
    struct iphdr *ip;
    struct udphdr *udp;
    struct icmphdr *icmp = NULL;

    status =  ipq_read(h, buf, sizeof(buf), -1);
    
    if (status < 0) {
	DEBUG(LOG_DEBUG, 0, "%s", ipq_errstr());
	ipq_perror(NULL);
	return;
    }

    if (ipq_message_type(buf) == NLMSG_ERROR) {
	fprintf(stderr,
		"ERROR packet_input: Check that the ip_queue.o module is loaded.\n");
	die(h);
    }

    pkt = ipq_get_packet(buf);

#ifdef DEBUG_PACKET
    DEBUG(LOG_DEBUG, 0, "Protocol %u indev=%s outdev=%s\n",
	  pkt->hw_protocol, pkt->indev_name, pkt->outdev_name);
#endif

    if (pkt->hook == 0)
	dev_name = pkt->indev_name;
    else if (pkt->hook == 3)
	dev_name = pkt->outdev_name;
    else
	dev_name = NULL;

    /* We know from kaodv.c that this is an IP packet */
    ip = (struct iphdr *) pkt->payload;

    dest_addr.s_addr = ip->daddr;
    src_addr.s_addr = ip->saddr;

    switch (ip->protocol) {
	/* Don't process AODV control packets (UDP on port 654). They
	   are accounted for on the aodv socket */
    case IPPROTO_UDP:
	udp = (struct udphdr *) ((char *) ip + (ip->ihl << 2));
	if (ntohs(udp->dest) == AODV_PORT || ntohs(udp->source) == AODV_PORT)
	    goto accept;
	break;
	/* If this is a TCP packet and we don't have a route, we should
	   set the gratuituos flag in the RREQ. */
    case IPPROTO_TCP:
	rreq_flags |= RREQ_GRATUITOUS;
	break;
	/* We set the gratuitous flag also on ICMP ECHO requests, since
	   the destination will also need a route back for the reply... */
    case IPPROTO_ICMP:
	icmp = (struct icmphdr *) ((char *) ip + (ip->ihl << 2));
	if (icmp->type == ICMP_ECHO)
	    rreq_flags |= RREQ_GRATUITOUS;
#ifdef DEBUG_PACKET
	DEBUG(LOG_INFO, 0, "setting G flag for RREQ to %s",
	      ip_to_str(dest_addr));
#endif

	break;
#ifdef CONFIG_GATEWAY
    case IPPROTO_MIPE:
	if (internet_gw_mode) {
	    
	    ip = ip_pkt_decapsulate(ip);

	    if (ip == NULL) {
	      DEBUG(LOG_ERR, 0, "Decapsulation failed...");
	      exit(-1);
	    }
	    pkt_flags |= PKT_DEC;
	}
	break;
#endif /* CONFIG_GATEWAY */
    }

#ifdef DEBUG_PACKET
    DEBUG(LOG_INFO, 0, "pkt to %s", ip_to_str(dest_addr));
#endif

    if (dev_name) {
	ifindex = name2index(dev_name);
	if (ifindex < 0) {
	    DEBUG(LOG_ERR, 0, "name2index error!");
	    return;
	}
    } else
	ifindex = 0;
#endif				/* NS_PORT */

    /* If the packet is not interesting we just let it go through... */
    if (dest_addr.s_addr == AODV_BROADCAST ||
	dest_addr.s_addr == DEV_IFINDEX(ifindex).broadcast.s_addr) {
#ifdef NS_PORT
	/* Limit Non AODV broadcast packets (Rolf Winter
	 * <[email protected]). */
	ih->ttl() = ih->ttl() - 1;                
       
	if(ih->ttl() < 1)        
	    Packet::free(p);                
	else
	    sendPacket(p, dest_addr, 0.0);
	return;
#else
	goto accept;
#endif
    }
    
    /* Find the entry of the neighboring node and the destination  (if any). */
    rev_rt = rt_table_find(src_addr);
    fwd_rt = rt_table_find(dest_addr);

#ifdef CONFIG_GATEWAY
    /* Check if we have a route and it is an Internet destination (Should be
     * encapsulated and routed through the gateway). */
    if (fwd_rt && (fwd_rt->state == VALID) && 
	(fwd_rt->flags & RT_INET_DEST)) {
	/* The destination should be relayed through the IG */

	rt_table_update_timeout(fwd_rt, ACTIVE_ROUTE_TIMEOUT);
#ifdef NS_PORT
	p = pkt_encapsulate(p, fwd_rt->next_hop);

	if (p == NULL) {
	    DEBUG(LOG_ERR, 0, "IP Encapsulation failed!");
	   return;	    
	}
	/* Update pointers to headers */
	ch = HDR_CMN(p);
	ih = HDR_IP(p);
#else
	ip = ip_pkt_encapsulate(ip, fwd_rt->next_hop, BUFSIZE);

	if (ip == NULL) {
	    DEBUG(LOG_ERR, 0, "Minimal IP Encapsulation failed!");
	    exit(-1);	    
	}
#endif
	dest_addr = fwd_rt->next_hop;
	fwd_rt = rt_table_find(dest_addr);
	pkt_flags |= PKT_ENC;
    }
#endif /* CONFIG_GATEWAY */

    /* UPDATE TIMERS on active forward and reverse routes...  */

    /* When forwarding a packet, we update the lifetime of the
       destination's routing table entry, as well as the entry for the
       next hop neighbor (if not the same). AODV draft 10, section
       6.2. */
    if (fwd_rt && fwd_rt->state == VALID &&
	dest_addr.s_addr != DEV_IFINDEX(ifindex).ipaddr.s_addr) {

	rt_table_update_timeout(fwd_rt, ACTIVE_ROUTE_TIMEOUT);

	next_hop_rt = rt_table_find(fwd_rt->next_hop);
	
	if (next_hop_rt && next_hop_rt->state == VALID && 
	    next_hop_rt->dest_addr.s_addr != fwd_rt->dest_addr.s_addr)
	    rt_table_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);

    }
    /* Also update the reverse route and reverse next hop along the
       path back, since routes between originators and the destination
       are expected to be symmetric. */
    if (rev_rt && rev_rt->state == VALID) {
	
	rt_table_update_timeout(rev_rt, ACTIVE_ROUTE_TIMEOUT);

	next_hop_rt = rt_table_find(rev_rt->next_hop);

	if (next_hop_rt && next_hop_rt->state == VALID &&
	    rev_rt && next_hop_rt->dest_addr.s_addr != rev_rt->dest_addr.s_addr)
	    rt_table_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);

	/* Update HELLO timer of next hop neighbor if active */   
	if (!llfeedback && next_hop_rt->hello_timer.used) {
	    struct timeval now;
	
	    gettimeofday(&now, NULL);
	    hello_update_timeout(next_hop_rt, &now, 
				 ALLOWED_HELLO_LOSS * HELLO_INTERVAL);
	}
    }

    /* OK, the timeouts have been updated. Now see if either: 1. The
       packet is for this node -> ACCEPT. 2. The packet is not for this
       node -> Send RERR (someone want's this node to forward packets
       although there is no route) or Send RREQ. */

    /* If the packet is destined for this node, then just accept it. */
    if (memcmp(&dest_addr, &DEV_IFINDEX(ifindex).ipaddr, 
	       sizeof(struct in_addr)) == 0) {

#ifdef NS_PORT
	ch->size() -= IP_HDR_LEN;    // cut off IP header size 4/7/99 -dam
	target_->recv(p, (Handler*)0);
	p = 0;
	return;
#else
	goto accept;
#endif
    }
    if (!fwd_rt || fwd_rt->state == INVALID ||
	(fwd_rt->hcnt == 1 && (fwd_rt->flags & RT_UNIDIR))) {

	/* Check if the route is marked for repair or is INVALID. In
	 * that case, do a route discovery. */
	if (fwd_rt && (fwd_rt->flags & RT_REPAIR))
	    goto route_discovery;

	/* If a packet is received on the NF_IP_PRE_ROUTING hook,
	   i.e. inbound on the interface and we don't have a route to
	   the destination, we should send an RERR to the source and
	   then drop the package... */
	/* NF_IP_PRE_ROUTING = 0 */
#ifdef NS_PORT
#define PACKET_IS_INBOUND ch->direction() == hdr_cmn::UP
#else
#define PACKET_IS_INBOUND pkt->hook == 0
#endif

	if (PACKET_IS_INBOUND) {

	    struct in_addr rerr_dest;
	    RERR *rerr;
#ifdef NS_PORT
	    struct in_addr nh;
	    nh.s_addr = ch->prev_hop_;
	    
	    DEBUG(LOG_DEBUG, 0,
		  "No route, src=%s dest=%s prev_hop=%s - DROPPING!",
		  ip_to_str(src_addr), ip_to_str(dest_addr),
		  ip_to_str(nh));
#endif
	    if (fwd_rt) {
		rerr = rerr_create(0, fwd_rt->dest_addr,
				   fwd_rt->dest_seqno);

		rt_table_update_timeout(fwd_rt, DELETE_PERIOD);
	    } else
		rerr = rerr_create(0, dest_addr, 0);
	    
	    DEBUG(LOG_DEBUG, 0, "Sending RERR to prev hop %s for unknown dest %s", ip_to_str(src_addr), ip_to_str(dest_addr));
	    
	    /* Unicast the RERR to the source of the data transmission
	     * if possible, otherwise we broadcast it. */
	    
	    if (rev_rt && rev_rt->state == VALID)
		rerr_dest = rev_rt->next_hop;
	    else
		rerr_dest.s_addr = AODV_BROADCAST;

	    aodv_socket_send((AODV_msg *) rerr, rerr_dest,
			     RERR_CALC_SIZE(rerr), 1, &DEV_IFINDEX(ifindex));

	    if (wait_on_reboot) {
		DEBUG(LOG_DEBUG, 0, "Wait on reboot timer reset.");
		timer_set_timeout(&worb_timer, DELETE_PERIOD);
	    }
#ifdef NS_PORT
	    /* DEBUG(LOG_DEBUG, 0, "Dropping pkt uid=%d", ch->uid()); */
	    drop(p, DROP_RTR_NO_ROUTE);
#else
	    status = ipq_set_verdict(h, pkt->packet_id, NF_DROP, 0, NULL);
	    
	    if (status < 0)
		die(h);
#endif
	    return;
	}

      route_discovery:
	/* Buffer packets... Packets are queued by the ip_queue.o
	   module already. We only need to save the handle id, and
	   return the proper verdict when we know what to do... */

#ifdef NS_PORT
	packet_queue_add(p, dest_addr);
#else
	packet_queue_add(pkt->packet_id, dest_addr, ip);
	
#ifdef CONFIG_GATEWAY
	/* In gateway mode we handle packets in userspace */
	ipq_set_verdict(h, pkt->packet_id, NF_DROP, 0, NULL);
#endif
	/* Already seeking the destination? Then do not allocate any
	   memory or generate a RREQ. */
	if (seek_list_find(dest_addr))
	    return;

	/* If the request is generated locally by an application, we save
	   the IP header + 64 bits of data for sending an ICMP Destination
	   Host Unreachable in case we don't find a route... */
	if (src_addr.s_addr == DEV_IFINDEX(ifindex).ipaddr.s_addr && ip &&
	    pkt->data_len >= (ip->ihl << 2) + 8) {
	    ipd = (struct ip_data *) malloc(sizeof(struct ip_data));
	    if (ipd == NULL) {
		perror("Malloc for IP data failed!");
		exit(-1);
	    }
	    /* IP header + 64 bits data (8 bytes) */
	    ipd->len = (ip->ihl << 2) + 8;
	    memcpy(ipd->data, ip, ipd->len);
	} else
	    ipd = NULL;
#endif
	if (fwd_rt && (fwd_rt->flags & RT_REPAIR))
	    rreq_local_repair(fwd_rt, src_addr, ipd);
	else
	    rreq_route_discovery(dest_addr, rreq_flags, ipd);

	return;

    } else {

#ifdef NS_PORT
	/* DEBUG(LOG_DEBUG, 0, "Sending pkt uid=%d", ch->uid()); */
	sendPacket(p, fwd_rt->next_hop, 0.0);
#else	
      accept:

	if (pkt_flags & PKT_ENC || (pkt_flags & PKT_DEC))
	    status = ipq_set_verdict(h, pkt->packet_id, NF_ACCEPT, 
				     ntohs(ip->tot_len), (unsigned char *)ip);
	else
	    status = ipq_set_verdict(h, pkt->packet_id, NF_ACCEPT, 0, NULL);
	
	if (status < 0)
	    die(h);

#endif
	/* When forwarding data, make sure we are sending HELLO messages */
	gettimeofday(&this_host.fwd_time, NULL);

	if (!llfeedback && optimized_hellos)
	    hello_start();
    }
}
Exemplo n.º 7
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;
}
Exemplo n.º 8
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; 
} 
Exemplo n.º 9
0
Arquivo: pfilter.c Projeto: 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;
}
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;
}
Exemplo n.º 11
0
static void packet_input(int fd)
#endif
{
    rt_table_t *fwd_rt, *rev_rt, *repair_rt, *next_hop_rt;
    u_int32_t dest_addr, src_addr;
    u_int8_t rreq_flags = 0;
    unsigned int ifindex;
    struct ip_data *ipd = NULL;

#ifdef NS_PORT
    ifindex = NS_IFINDEX;	// Always use ns interface
    fwd_rt = NULL;		// In case of broadcast we provide no next hop
    ipd = NULL;			// No ICMP messaging

    struct hdr_cmn *ch = HDR_CMN(p);
    struct hdr_ip *ih = HDR_IP(p);

    src_addr = ih->saddr();
    dest_addr = ih->daddr();

    /*
       Any packets with our IP address as destination arriving here are
       packets that weren't caught by any agent attached to the node.
       Throw away those.
     */
    if (dest_addr == DEV_IFINDEX(ifindex).ipaddr) {
        DEBUG(LOG_WARNING, 0,
              "processPacket: Received orphan packet. Throwing it away.");
        Packet::free(p);
        return;
    }

    /* If this is a TCP packet and we don't have a route, we should
       set the gratuituos flag in the RREQ. */
    if (ch->ptype() == PT_TCP) {
        rreq_flags |= RREQ_GRATUITOUS;
    }
#else
    int status;
    char buf[BUFSIZE], *dev_name;
    ipq_packet_msg_t *pkt;
    struct iphdr *ip;
    struct udphdr *udp;
    struct icmphdr *icmp = NULL;

    ipq_read(h, buf, BUFSIZE, 0);

    status = ipq_message_type(buf);

    if (status == NLMSG_ERROR) {
        fprintf(stderr,
                "ERROR packet_input: Check that the ip_queue.o module is loaded.\n");
        die(h);
    }

    pkt = ipq_get_packet(buf);

#ifdef DEBUG_PACKET
    DEBUG(LOG_DEBUG, 0, "Protocol %u indev=%s outdev=%s\n",
          pkt->hw_protocol, pkt->indev_name, pkt->outdev_name);
#endif

    if (pkt->hook == 0)
        dev_name = pkt->indev_name;
    else if (pkt->hook == 3)
        dev_name = pkt->outdev_name;
    else
        dev_name = NULL;

    /* We know from kaodv.c that this is an IP packet */
    ip = (struct iphdr *) pkt->payload;

    dest_addr = ntohl(ip->daddr);
    src_addr = ntohl(ip->saddr);

    switch (ip->protocol) {
    /* Don't process AODV control packets (UDP on port 654). They
       are accounted for on the aodv socket */
    case IPPROTO_UDP:
        udp = (struct udphdr *) ((char *) ip + (ip->ihl << 2));
        if (ntohs(udp->dest) == AODV_PORT || ntohs(udp->source) == AODV_PORT)
            goto accept;
        break;
    /* If this is a TCP packet and we don't have a route, we should
       set the gratuituos flag in the RREQ. */
    case IPPROTO_TCP:
        rreq_flags |= RREQ_GRATUITOUS;
        break;
    /* We set the gratuitous flag also on ICMP ECHO requests, since
       the destination will also need a route back for the reply... */
    case IPPROTO_ICMP:
        icmp = (struct icmphdr *) ((char *) ip + (ip->ihl << 2));
        if (icmp->type == ICMP_ECHO)
            rreq_flags |= RREQ_GRATUITOUS;
#ifdef DEBUG_PACKET
        DEBUG(LOG_INFO, 0, "packet_input: setting G flag for RREQ to %s",
              ip_to_str(dest_addr));
#endif

        break;
    default:
    }

#ifdef DEBUG_PACKET
    DEBUG(LOG_INFO, 0, "packet_input: pkt to %s", ip_to_str(dest_addr));
#endif

    if (dev_name)
        ifindex = if_nametoindex(dev_name);
    else
        ifindex = 0;
#endif				/* NS_PORT */

    /* If the packet is not interesting we just let it go through... */
    if ((dest_addr == AODV_BROADCAST) ||
            (dest_addr == DEV_IFINDEX(ifindex).ipaddr) ||
            (dest_addr == DEV_IFINDEX(ifindex).broadcast) ||
            ((internet_gw_mode && this_host.gateway_mode)
             && ((dest_addr & DEV_IFINDEX(ifindex).netmask) !=
                 DEV_IFINDEX(ifindex).broadcast)))
        goto accept;

    /* Find the entry of the neighboring node and the destination  (if any). */
    rev_rt = rt_table_find_active(src_addr);
    fwd_rt = rt_table_find_active(dest_addr);


    /* If a packet is received on the NF_IP_PRE_ROUTING hook,
       i.e. inbound on the interface and we don't have a route to the
       destination, we should send an RERR to the source and then drop
       the package... */
    /* NF_IP_PRE_ROUTING = 0 */

#ifdef NS_PORT
#define PACKET_IS_INBOUND ch->direction() == hdr_cmn::UP
#else
#define PACKET_IS_INBOUND pkt->hook == 0
#endif

    if ((dest_addr != DEV_IFINDEX(ifindex).ipaddr) &&
            (!fwd_rt && PACKET_IS_INBOUND)) {
        rt_table_t *rt_entry;
        u_int32_t rerr_dest;
        RERR *rerr;

        DEBUG(LOG_DEBUG, 0, "packet_input: Sending RERR for unknown dest %s",
              ip_to_str(dest_addr));

        /* There is an expired entry in the routing table we want to send
           along the seqno in the RERR... */
        rt_entry = rt_table_find(dest_addr);

        if (rt_entry) {
            rerr = rerr_create(0, rt_entry->dest_addr, rt_entry->dest_seqno);
            rt_table_update_timeout(rt_entry, DELETE_PERIOD);
        } else
            rerr = rerr_create(0, dest_addr, 0);

        /* Unicast the RERR to the source of the data transmission if
         * possible, otherwise we broadcast it. */
        if (rev_rt)
            rerr_dest = rev_rt->next_hop;
        else
            rerr_dest = AODV_BROADCAST;

        aodv_socket_send((AODV_msg *) rerr, rerr_dest,
                         RERR_CALC_SIZE(rerr), 1, &DEV_IFINDEX(ifindex));

        if (wait_on_reboot) {
            DEBUG(LOG_DEBUG, 0, "packet_input: Wait on reboot timer reset.");
            timer_add_msec(&worb_timer, DELETE_PERIOD);
        }
#ifdef NS_PORT
        drop(p, DROP_RTR_NO_ROUTE);
#else
        status = ipq_set_verdict(h, pkt->packet_id, NF_DROP, 0, NULL);
        if (status < 0)
            die(h);
#endif
        return;
    }
    /* Check if the route is currently in repair. In that case just
       buffer the packet */
    repair_rt = rt_table_find(dest_addr);

    if (repair_rt && (repair_rt->flags & LREPAIR)) {
#ifdef NS_PORT
        packet_queue_add(p, dest_addr);
#else
        packet_queue_add(pkt->packet_id, dest_addr);
#endif
        return;
    }
    /*  update_timers:  */
    /* When forwarding a packet, we update the lifetime of the
       destination's routing table entry, as well as the entry for the
       next hop neighbor (if not the same). AODV draft 10, section
       6.2. */
    if (fwd_rt && dest_addr != DEV_IFINDEX(ifindex).ipaddr) {
        rt_table_update_timeout(fwd_rt, ACTIVE_ROUTE_TIMEOUT);

        next_hop_rt = rt_table_find_active(fwd_rt->next_hop);

        if (next_hop_rt && next_hop_rt->dest_addr != fwd_rt->dest_addr)
            rt_table_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);

    }
    /* Also update the reverse route and reverse next hop along the
       path back, since routes between originators and the destination
       are expected to be symmetric. */
    if (rev_rt) {
        rt_table_update_timeout(rev_rt, ACTIVE_ROUTE_TIMEOUT);

        next_hop_rt = rt_table_find_active(rev_rt->next_hop);

        if (next_hop_rt && next_hop_rt->dest_addr != fwd_rt->dest_addr)
            rt_table_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);
    }
#ifdef DEBUG_PACKET
    DEBUG(LOG_INFO, 0, "packet_input: d=%s s=%s",
          ip_to_str(dest_addr), ip_to_str(src_addr));
#endif				/* DEBUG_PACKET */

    if (!fwd_rt || (fwd_rt->hcnt == 1 && (fwd_rt->flags & UNIDIR))) {
        /* Buffer packets... Packets are queued by the ip_queue_aodv.o module
           already. We only need to save the handle id, and return the proper
           verdict when we know what to do... */
#ifdef NS_PORT
        packet_queue_add(p, dest_addr);
#else
        packet_queue_add(pkt->packet_id, dest_addr);

        /* If the request is generated locally by an application, we save
           the IP header + 64 bits of data for sending an ICMP Destination
           Host Unreachable in case we don't find a route... */
        if (src_addr == DEV_IFINDEX(ifindex).ipaddr) {
            ipd = (struct ip_data *) malloc(sizeof(struct ip_data));
            if (ipd < 0) {
                perror("Malloc for IP data failed!");
                exit(-1);
            }
            ipd->len = (ip->ihl << 2) + 8;	/* IP header + 64 bits data (8 bytes) */
            memcpy(ipd->data, ip, ipd->len);
        } else
            ipd = NULL;
#endif
        rreq_route_discovery(dest_addr, rreq_flags, ipd);
        return;
    }

accept:

#ifdef NS_PORT
    if (fwd_rt)
        sendPacket(p, fwd_rt->next_hop, 0.0);
    else
        drop(p, DROP_RTR_NO_ROUTE);
#else
    status = ipq_set_verdict(h, pkt->packet_id, NF_ACCEPT, 0, NULL);
    if (status < 0)
        die(h);
#endif
    return;
}
Exemplo n.º 12
0
Arquivo: main.c Projeto: 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;
}
Exemplo n.º 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;
}
Exemplo n.º 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;
}
Exemplo n.º 15
0
static int ipq_daq_acquire (
    void* handle, int cnt, DAQ_Analysis_Func_t callback, void* user)
{
    IpqImpl* impl = (IpqImpl*)handle;

    int n = 0;
    DAQ_PktHdr_t hdr;

    // If cnt is <= 0, don't limit the packets acquired.  However,
    // impl->count = 0 has a special meaning, so interpret accordingly.
    impl->count = (cnt == 0) ? -1 : cnt;
    hdr.device_index = 0;
    hdr.flags = 0;

    while ( impl->count < 0 || n < impl->count )
    {
        int ipqt, status = ipq_read(
            impl->ipqh, impl->buf, MSG_BUF_SIZE, impl->timeout);

        if ( status <= 0 )
        {
            if ( status < 0 )
            {
                DPE(impl->error, "%s: ipq_read=%d error %s",
                    __FUNCTION__, status, ipq_errstr());
                return DAQ_ERROR;
            }
            return 0;
        }

        ipqt = ipq_message_type(impl->buf);

        if ( ipqt == IPQM_PACKET )
        {
            DAQ_Verdict verdict;
            ipq_packet_msg_t* ipqm = ipq_get_packet(impl->buf);
            SetPktHdr(impl, ipqm, &hdr);
            impl->stats.hw_packets_received++;

            if (
                impl->fcode.bf_insns &&
                sfbpf_filter(impl->fcode.bf_insns, ipqm->payload,
                    hdr.caplen, hdr.caplen) == 0
            ) {
                verdict = DAQ_VERDICT_PASS;
                impl->stats.packets_filtered++;
            }
            else
            {
                verdict = callback(user, &hdr, (uint8_t*)ipqm->payload);
                impl->stats.verdicts[verdict]++;
                impl->stats.packets_received++;
            }
            if ( impl->passive ) verdict = DAQ_VERDICT_PASS;

            switch ( verdict ) {
            case DAQ_VERDICT_BLOCK:
            case DAQ_VERDICT_BLACKLIST:
                status = ipq_set_verdict(
                    impl->ipqh, ipqm->packet_id, NF_DROP, 0, NULL);
                break;

            case DAQ_VERDICT_REPLACE:
                status = ipq_set_verdict(
                    impl->ipqh, ipqm->packet_id, NF_ACCEPT,
                    hdr.pktlen, ipqm->payload);
                break;

            case DAQ_VERDICT_PASS:
            case DAQ_VERDICT_WHITELIST:
            case DAQ_VERDICT_IGNORE:
            default:
                status = ipq_set_verdict(
                    impl->ipqh, ipqm->packet_id, NF_ACCEPT, 0, NULL);
                break;
            }
            if ( status < 0 )
            {
                DPE(impl->error, "%s: ipq_set_verdict=%d error %s",
                    __FUNCTION__, status, ipq_errstr());
                return DAQ_ERROR;
            }
            n++;
        }
        else
        {
            // NLMSG_ERROR is supposed to be the only other valid type
            status = ipq_get_msgerr(impl->buf);
            DPE(impl->error, "%s: ipq_message_type=%d error=%d %s",
                __FUNCTION__, ipqt, status, ipq_errstr());
            // ipq_message_type=2 error=1 Timeout
            // keep looping upon timeout or other errors
        }
    }
    return 0;
}
Exemplo n.º 16
0
int doingDetection()
{
   int status;
   struct nlmsghdr *nlh;
   struct ndpi_ethher *ethernet;
   struct ndpi_iphdr *iph;
   ipq_packet_msg_t *ipq_packet;
   int ip_len;
   struct ndpi_id_struct *src, *dst;
   struct ndpi_flow *flow;
   struct ndpi_flow_struct *ndpi_flow = NULL;
   u_int32_t protocol = 0;
   u_int8_t proto;
   u_int64_t time;
   static u_int64_t lasttime=0;
   unsigned char payload[1024*1024];
	 while(1)
   {
     status = ipq_read(h, buf, sizeof(buf),0);
     if(status==0||status==-1)continue;
     memset(payload, 0x00, sizeof(payload));
     if(status > sizeof(struct nlmsghdr))
     {
       nlh = (struct nlmsghdr *)buf;//测试是否和ndpi_ethher一致。
       ipq_packet = ipq_get_packet(buf);
       ip_len=ipq_packet->data_len;
       time = ((uint64_t) ipq_packet->timestamp_sec) * detection_tick_resolution +ipq_packet->timestamp_usec / (1000000 / detection_tick_resolution);
			 memcpy(payload + ETH_HDRLEN, ipq_packet->payload, ip_len);
// 			printf("2\n");
 			 if(lasttime > time) {
        time = lasttime;
       }
       lasttime = time;
       iph = (struct ndpi_iphdr *)(&(ipq_packet->payload[0]));//需要测试是否和pcap来的一致
       if(iph)
			 {
//				 printf("before get_ndpi_flow\n");
         flow = get_ndpi_flow(iph, ip_len,&src, &dst, &proto);
//				 printf("after get_ndpi_flow\n");
			 }
			 if(flow != NULL) 
       {
         ndpi_flow = flow->ndpi_flow;
         flow->packets++, flow->bytes += ip_len;
       } else
         continue;
//			 printf("3\n");
       ip_packet_count++;
       total_bytes+=ip_len+24;
       if(flow->detection_completed) 
			 {
				 /*ipq_set_verdict(h, ipq_packet->packet_id, NF_ACCEPT,ipq_packet->data_len,payload + ETH_HDRLEN);*/
				 ipq_set_mark(h,ipq_packet->packet_id,1);
				 continue;
			 }
       protocol = (const u_int32_t)ndpi_detection_process_packet(ndpi_struct, ndpi_flow,(char *)iph,ip_len, time, src, dst);
//			 printf("4\n");
       if((flow->detected_protocol != NDPI_PROTOCOL_UNKNOWN)
           || ((proto == IPPROTO_UDP) && (flow->packets > 8))
           || ((proto == IPPROTO_TCP) && (flow->packets > 10)))
       {
         if(flow->detected_protocol==NDPI_PROTOCOL_UNKNOWN)
				 		flow->detected_protocol = ndpi_guess_undetected_protocol(ndpi_struct,
							   flow->protocol,
							   ntohl(flow->lower_ip),
							   ntohs(flow->lower_port),
							   ntohl(flow->upper_ip),
							   ntohs(flow->upper_port));
         flow->detection_completed = 1;
				 protocol_counter[flow->detected_protocol]+=flow->packets;
				 protocol_flows[flow->detected_protocol]++;
				 protocol_counter_bytes[flow->detected_protocol]+=flow->bytes;
         snprintf(flow->host_server_name, sizeof(flow->host_server_name), "%s", flow->ndpi_flow->host_server_name);
       }
			 ipq_set_verdict(h, ipq_packet->packet_id, NF_ACCEPT,ipq_packet->data_len,payload + ETH_HDRLEN);
       snprintf(flow->host_server_name, sizeof(flow->host_server_name), "%s", flow->ndpi_flow->host_server_name);
	    }
   }
}
Exemplo n.º 17
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;
}