⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snort.c

📁 该源码是用C语言编写的,实现网络入侵检测系统的功能
💻 C
📖 第 1 页 / 共 5 页
字号:
				printf("Decoding I4L-rawip on interface %s\n", print_interface(pv.interfaces[num]));
#else
                printf("Decoding I4L-rawip on interface %s\n", pv.interfaces[num]);
#endif

            grinders[num] = DecodeI4LRawIPPkt;

            break;
#endif

#ifdef DLT_I4L_IP
        case DLT_I4L_IP:
            if (! pv.readmode_flag && !pv.quiet_flag)
#ifdef WIN32
				printf("Decoding I4L-ip on interface %s\n", print_interface(pv.interfaces[num]));
#else
                printf("Decoding I4L-ip on interface %s\n", pv.interfaces[num]);
#endif

            grinders[num] = DecodeEthPkt;

            break;
#endif

#ifdef DLT_I4L_CISCOHDLC
        case DLT_I4L_CISCOHDLC:
            if (! pv.readmode_flag && !pv.quiet_flag)
                printf("Decoding I4L-cisco-h on interface %s\n", 
#ifdef WIN32
						   print_interface(pv.interfaces[num]));
#else
                           pv.interfaces[num]);
#endif

            grinders[num] = DecodeI4LCiscoIPPkt;

            break;
#endif

        default:                        /* oops, don't know how to handle this one */
            ErrorMessage("\n%s cannot handle data link type %d",
                         progname, datalink);
            CleanExit(SIGQUIT);
    }

    return 0;
}

/*
 * Function: InitializeInterfaces(void)
 *
 * Purpose - initialize all specified in command line interface(s)
 */
void InitializeInterfaces(void)
{
    int i;

    for(i = 0; i < ifr_count; i++)        /* going through all interfaces */
    {
        OpenPcap(pv.interfaces[i], i);
    }
}



/*
 * Function: void *InterfaceThread(void *arg)
 *
 * Purpose: wrapper for pthread_create() to create a thread per interface
 */
void *InterfaceThread(void *arg)
{
    static int intnum = 0;
    int myint;

#ifdef USE_PTHREADS
    pthread_mutex_lock(&pt_lock);        /* just to make sure we don't skip
                                         * any interfaces, and no threads
                                         * would start on the same interface
                                         * simultaneously */
#endif

    myint = intnum;
    intnum++;

#ifdef USE_PTHREADS
    pthread_mutex_unlock(&pt_lock);
#endif

    /* Read all packets on the device.  Continue until cnt packets read */
    if(pcap_loop(pds[myint], pv.pkt_cnt, (pcap_handler) ProcessPacket, NULL) < 0)
    {
        if(pv.daemon_flag)
            syslog(LOG_CONS | LOG_DAEMON, "pcap_loop: %s", pcap_geterr(pd));
        else
            ErrorMessage("pcap_loop: %s", pcap_geterr(pd));

        CleanExit(SIGQUIT);
    }
    CleanExit(SIGQUIT);

    return NULL;                /* avoid warnings */
}



/****************************************************************************
 *
 * Function: OpenPcap(char *, int)
 *
 * Purpose:  Open the libpcap interface
 *
 * Arguments: intf => name of the interface to open
 *            num  => number of the interface (to fill-in datalink and pd)
 *
 * Returns: 0 => success, exits on problems
 *
 ****************************************************************************/
int OpenPcap(char *intf, int num)
{
    bpf_u_int32 localnet, netmask;        /* net addr holders */
    struct bpf_program fcode;        /* Finite state machine holder */
    char errorbuf[PCAP_ERRBUF_SIZE];        /* buffer to put error strings in */
    bpf_u_int32 defaultnet = 0xFFFFFF00;

    /* if we're not reading packets from a file */
    if(pv.interfaces[num] == NULL)
    {
        if (!pv.readmode_flag)
        {
#ifdef DEBUG
            printf("pv.interface is NULL, looking up interface....   ");
#endif
            /* look up the device and get the handle */
            pv.interfaces[num] = pcap_lookupdev(errorbuf);
    
#ifdef DEBUG
#ifdef WIN32
			printf("found interface %s\n", print_interface(pv.interfaces[num]));
#else
            printf("found interface %s\n", pv.interfaces[num]);
#endif
#endif
            /* uh oh, we couldn't find the interface name */
            if(pv.interfaces[num] == NULL)
            {
                FatalError("ERROR: OpenPcap() interface lookup: \n\t%s\n", errorbuf);
            }
        }
        else
        {
            /* interface is null and we are in readmode */
         pv.interfaces[num] = "[reading from a file]"; /* some routines would hate it to be NULL */
        }
    }

    if(!pv.quiet_flag)
    {
        if (!pv.readmode_flag)
#ifdef WIN32
			printf("\nInitializing Network Interface %s\n", print_interface(pv.interfaces[num]));
#else
            printf("\nInitializing Network Interface %s\n", pv.interfaces[num]);
#endif
        else 
            printf("TCPDUMP file reading mode.\n");
    }
    if (!pv.readmode_flag)
    {
        if(pv.pkt_snaplen)        /* if it's set let's try it... */
        {
            if(pv.pkt_snaplen < MIN_SNAPLEN)        /* if it's < MIN set it to
                                                     * MIN */
            {
                 snaplen = MIN_SNAPLEN;
            }
            else
            {
                 snaplen = pv.pkt_snaplen;
            }
         }
         else
         {
             snaplen = SNAPLEN;        /* otherwise let's put the compiled value in */
         }
        
#ifdef DEBUG
        printf("snaplength info: set=%d/compiled=%d/wanted=%d\n", snaplen,
                   SNAPLEN, pv.pkt_snaplen);
#endif
    
        /* get the device file descriptor */
        pds[num] = pcap_open_live(pv.interfaces[num], snaplen,
                                      pv.promisc_flag ? PROMISC : 0, READ_TIMEOUT, errorbuf);

        /* lookup mtu */
        pv.mtus[num] = GetIfrMTU(pv.interfaces[num]);
            
        if (pv.mtus[num] == -1)
        {
#ifdef WIN32
			FatalError("ERROR: Can not get MTU of an interface %s!\n", print_interface(pv.interfaces[num]));
#else
            FatalError("ERROR: Can not get MTU of an interface %s!\n", pv.interfaces[num]);
#endif
        }
 
        
    }
    else
    {   /* reading packets from a file */

        if (!pv.quiet_flag)
        {
    	    printf("Reading network traffic from \"%s\" file.\n", intf);
        }
        /* open the file */
        pds[num] = pcap_open_offline(intf, errorbuf);

        /* the file didn't open correctly */
        if(pds[num] == NULL)
        {
            FatalError("ERROR => unable to open file %s for readback: %s\n",
                       intf, errorbuf);
        }
        /*
         * set the snaplen for the file (so we don't get a lot of extra crap
         * in the end of packets
         */
        snaplen = pcap_snapshot(pds[num]);

        /* captured framesize can not be bigger than snaplen */
        pv.mtus[num] = snaplen;

        printf("snaplen = %d\n", snaplen);
    }

    /* something is wrong with the opened packet socket */
    if(pds[num] == NULL)
    {
        FatalError("ERROR: OpenPcap() device %s open: \n\t%s\n",
#ifdef WIN32
				   print_interface(pv.interfaces[num]), errorbuf);
#else
                   pv.interfaces[num], errorbuf);
#endif
    }
    /* get local net and netmask */
    if(pcap_lookupnet(pv.interfaces[num], &localnet, &netmask, errorbuf) < 0)
    {
        ErrorMessage("WARNING: OpenPcap() device %s network lookup: \n\t%s\n",
#ifdef WIN32
				   print_interface(pv.interfaces[num]), errorbuf);
#else
                   pv.interfaces[num], errorbuf);
#endif
        /*
         * set the default netmask to 255.255.255.0 (for stealthed
         * interfaces)
         */
        netmask = htonl(defaultnet);
    }
    DefineIfaceVar(pv.interfaces[num], (u_char *) & localnet, (u_char *) & netmask);

    /* compile BPF filter spec info fcode FSM */
    if(pcap_compile(pds[num], &fcode, pv.pcap_cmd, 1, netmask) < 0)
    {
        ErrorMessage("ERROR: OpenPcap() FSM compilation failed: \n\t%s\n",
                     pcap_geterr(pds[num]));
        FatalError("PCAP command: %s\n", pv.pcap_cmd);
    }
    /* set the pcap filter */
    if(pcap_setfilter(pds[num], &fcode) < 0)
    {
        FatalError("ERROR: OpenPcap() setfilter: \n\t%s\n",
                   pcap_geterr(pds[num]));
    }
    /* get data link type */
    datalinks[num] = pcap_datalink(pds[num]);

    if(datalinks[num] < 0)
    {
        FatalError("ERROR: OpenPcap() datalink grab: \n\t%s\n",
                   pcap_geterr(pds[num]));
    }
    return 0;
}


/****************************************************************************
 *
 * Function  : GetIfrMTU()
 * Purpose   : Get Interface MTU value
 * Arguments : interface name (string)
 * Returns   : MTU (or -1)
 *
 ****************************************************************************/


int GetIfrMTU(char *name) {
#ifndef WIN32  
    int fd;
    struct ifreq ifr;
    int retval;


    retval = -1;

#ifdef LINUX
    /*
     * on linux platform with interface type 'any'
     * there's no way to automagically pick up mtu,
     * so we fall back to ETHERNET_MTU size....
     *
     * later it should be replaced to a more sophisticated
     * routine: lookup for all interfaces, lookup for all
     * MTUs, pick up the biggest... :)
     */
    if (!strcmp("any",name)) {
        return ETHERNET_MTU;
    }
#endif
 
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if ( fd < 0) {
        PrintError("socket");
        return -1;
    }

    strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));

#ifndef OSF1
#ifdef SIOCGIFMTU
    if (ioctl(fd, SIOCGIFMTU, &ifr) == 0)
        retval = ifr.ifr_metric;
#else
    if(1)
    {
        retval = ETHERNET_MTU;
    }
#endif
#else
    if (ioctl(fd, SIOCRIPMTU, &ifr) == 0)
        retval = ifr.ifr_metric;
#endif
    else
        PrintError("ioctl(SIOCGIFMTU)");    

    close(fd);
 
 return retval;
#else
 /* Winpcap pnly supports Ethernet Interfaces currently. Ethernet has 1MTU of 1500.*/
 return 1500;
#endif
}

/****************************************************************************
 *
 * Function  : DefineIfaceVar()
 * Purpose   : Assign network address and network mast to IFACE_ADDR_VARNAME
 *             variable.
 * Arguments : interface name (string) netaddress and netmask (4 octets each)
 * Returns   : void function
 *
 ****************************************************************************/
void DefineIfaceVar(char *iname, u_char * network, u_char * netmask)
{
    char valbuf[32];
    char varbuf[BUFSIZ + 1];

    snprintf(varbuf, BUFSIZ, "%s_ADDRESS", iname);

    snprintf(valbuf, 31, "%d.%d.%d.%d/%d.%d.%d.%d",
             network[0] & 0xff, network[1] & 0xff, network[2] & 0xff, network[3] & 0xff,
             netmask[0] & 0xff, netmask[1] & 0xff, netmask[2] & 0xff, netmask[3] & 0xff);
    VarDefine(varbuf, valbuf);
}

/****************************************************************************
 *
 * Function: CleanExit()
 *
 * Purpose:  Clean up misc file handles and such and exit
 *
 * Arguments: Signal
 *
 * Returns: void function
 *
 ****************************************************************************/
extern PluginSignalFuncNode *PluginCleanExitList;
extern PluginSignalFuncNode *PluginRestartList;

void CleanExit(int sig)
{
    PluginSignalFuncNode *idx;

    if(sig != SIGHUP)
        LogMessage("\nExiting...\n");
    else
        LogMessage("\nRestarting...\n");

    if(pv.logbin_flag)
    {
        pcap_dump_close(dumpd);
    }
    unlink(pv.pid_filename);

    pv.pid_filename[0] = 0;

    if(pv.alert_mode == ALERT_FAST || pv.alert_mode == ALERT_FULL)
    {
        if(alert != NULL)
        {
            fclose(alert);
        }
    }
    /* carry signals down to plugins */
    if(sig != SIGHUP)
    {
        idx = PluginCleanExitList;
    }
    else
    {
        idx = PluginRestartList;
    }

    while(idx != NULL)
    {
        idx->func(sig, idx->arg);
        idx = idx->next;
    }

#ifndef WIN32
    DropStats();
#else
	DropStats(0);
#endif
    /*
     * you will hardly run snort in daemon mode and read from file i that is
     * why no `LogMessage()' here
     */
/*    if( pv.readmode_flag )
    {
        puts("\n\n===============================================================================\n");

        recv = pc.tcp + pc.udp + pc.icmp + pc.arp + pc.ipx + pc.ipv6 + pc.other;

        printf("Snort processed %d packets.\n", (int) recv);

        puts("Breakdown by protocol:\n");
        printf("    TCP: %-10ld (%.3f%%)\n", pc.tcp, CalcPct((float) pc.tcp, recv));
        printf("    UDP: %-10ld (%.3f%%)\n", pc.udp, CalcPct((float) pc.udp, recv));
        printf("   ICMP: %-10ld (%.3f%%)\n", pc.icmp, CalcPct((float) pc.icmp, recv));
        printf("  FRAGS: %-10ld (%.3f%%)\n", pc.icmp, CalcPct((float) pc.frags, recv));
        printf("    ARP: %-10ld (%.3f%%)\n", pc.arp, CalcPct((float) pc.arp, recv));

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -