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

📄 spp_anomsensor.c

📁 该源码是用C语言编写的,实现网络入侵检测系统的功能
💻 C
📖 第 1 页 / 共 5 页
字号:
/* DO NOT EDIT THIS FILE. EDIT THE ORIGINAL SOURCE FILES INSTEAD AND RUN make *//*********************************************************************Spade, a Snort preprocessor plugin to report unusual packetsAuthor: James Hoagland, Silicon Defense (hoagland@SiliconDefense.com)copyright (c) 2000,2001 by Silicon Defense (http://www.silicondefense.com/)This program is free software; you can redistribute it and/ormodify it under the terms of the GNU General Public Licenseas published by the Free Software Foundation; either version 2of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  Spade description:SPADE, the Statistical Packet Anomaly Detection Engine, is a Snortpreprocessor plugin to report packets that are unusual for your network. Port scans and probes tend to be unusual, so this will tend to report them(as well as some benign packets that are simply uncommon).Spade's home page: http://www.silicondefense.com/spice/Please send complaints, kudos, and especially improvements and bugfixes tohoagland@SiliconDefense.com. This is a research project and would love tohave your feedback.  It is still under active development and may change atany time.This file (anomsensor_plug.c) is part of Spade v092200.1.  It contains allthe Snort- and sensor-specific code in Spade.*********************************************************************//* Internal version control: $Id: *//*#define LOG10 2.30258509299 */#define LOG2 0.69314718056 #include "spp_anomsensor.h"#include "rules.h"#include "log.h"#include <string.h>/* the threshold at which anomolous events are reported */double report_anom_thres;char *outfile; // the name of the output log filechar *statefile; // the name of the file to checkpoint to and recover fromint checkpoint_freq; // the frequency (in recorded packet counts) with which                     // to checkpointint prob_mode; // the probability calculation modeint as_debug= 0; // the bigger the number, the more debuging statements                 // that are activeint parts=0,part=11; // if parts is 1, the part indicates which part section                     // in record_packet should be run, overriding the                     // probabity mode; don't try to calculate anomaly scores                     // in this caseint adapting=0; // is there an adaptation module active on this run?int need_anom= 0; // does some module need the anomaly score calculateddouble last_anom_score; // the anomaly score for this packetint skip_packet;  // is this packet being skipped (not added to the tree)time_t last_pkt_time=(time_t)0; // the time of the last packet addedint tot_packets=0; // the total number of packets added to the tree                   // on this runint recent_packets= 0; // the number of packets added since the count was                       // last resetint alert_count= 0; // the count of alert sent about packetsint recent_alert_count= 0; // the count of alerts sent since the count was                           // last resetint pp_active= 0; // this is a count of how many modules have added                  // themselves to the preprocessor list and will be calling                  // record_maybe_skip()int pp_run_on_pkt= 0; // this is how many have called record_maybe_skip() so                      // far on this packet/* globals used in the tree and memory management */const char *featurename[NUM_FEATURES]={"sip","dip","sport","dport"};/*const char *featurename[NUM_FEATURES]={"sip","dip","sport","dport","ttl","win"};*/mindex TNULL;dmindex DMINDEXMASK;treeroot **ROOT_M;intnode **INT_M;leafnode **LEAF_M;mindex root_freelist;mindex int_freelist;mindex leaf_freelist;unsigned char ROOT_BLOCK_BITS;unsigned char INT_BLOCK_BITS;unsigned char LEAF_BLOCK_BITS;unsigned int MAX_ROOT_BLOCKS;unsigned int MAX_INT_BLOCKS;unsigned int MAX_LEAF_BLOCKS;mindex T[NUM_FEATURES];/*************//* The most basic role of Spade is to add packets to a tree in a certain waywhich will allow probabilities of various features to be calculated.  Thenext most basic thing it does is to calculate anomaly scores base on this. Typically, when a certain score threshold is exceeded, snort alerts aregenerated.  There are additional modules within the sensor (turned on byconfig file lines) which do additional things like adapting the reportingthreshold and generating statistics. */ /* A call to this function needs to be added to plugbase.c somehow */void SetupSpade(){    /* link the preprocessor keyword list to the init functions in        the preproc list to arrange for modules to run when specified */    RegisterPreprocessor("spade", SpadeInit);    RegisterPreprocessor("spade-homenet", SpadeHomenetInit);    RegisterPreprocessor("spade-stats", SpadeStatInit);    RegisterPreprocessor("spade-threshlearn", SpadeThreshlearnInit);    RegisterPreprocessor("spade-adapt", SpadeAdaptInit);    RegisterPreprocessor("spade-adapt2", SpadeAdapt2Init);    RegisterPreprocessor("spade-adapt3", SpadeAdapt3Init);    RegisterPreprocessor("spade-survey", SpadeSurveyInit);	if (as_debug) printf("Preprocessor: Spade is setup...\n");}/*========================================================================*//*========================= Spade core routines ==========================*//*========================================================================*//* snort config file line:	preprocessor spade: [ <anom-report-thresh> [ <state-file> [ <log-file> [ <prob-mode> [ <checkpoint-freq> ]]]]]	where:	  <anom-report-thresh> is the (initial) reporting threshold foranomalous events, or a negative number to not report (default -1)	  <state-file> is the name of the checkpoint and recovery file to recordto and startup from, or 0 not to checkpoint or recover (default spade.rcv)	  <log-file> is the name of the file to log to, or '-' for stdout(default '-')	  <prob-mode> is the probability mode to run in (0 for bayes net with 4features, 1 for full joint prob with 4 features, 2 for full joint with 3feaures, or 3 for full joint with 2 features) (default 3)	  <checkpoint-freq> is the fequency of checkpointing, in terms of treeaddition counts (default 50000)*//* Spade core init function:     set up anamaly sensor, register the signal handler,     register the preprocessor function */void SpadeInit(u_char *args){	pp_active++;	    /* parse the argument list from the rules file */    ParseSpadeArgs(args);	if (report_anom_thres >= 0) need_anom= 1;    /* Set the preprocessor function into the function list */    AddFuncToPreprocList(PreprocSpade);	if (strcmp(statefile,"0") && recover(statefile)) {		if (as_debug) printf("Recovered from file %s\n",statefile);	} else {		init_mem();		tree_init();	}#ifndef OLD_SNORT    // requires snort 1.6.1-beta3 or later	AddFuncToCleanExitList(SpadeCatchSig,NULL);	AddFuncToRestartList(SpadeCatchSig,NULL);#else	// use this if above won't compile    signal(SIGUSR1, CleanUpSpade);    signal(SIGQUIT, CleanUpSpade);    signal(SIGHUP, CleanUpSpade);#endif	if (as_debug) printf("Preprocessor: Spade Initialized\n");}/* Spade 'spade' argument parsing function  */void ParseSpadeArgs(char *args){    char **toks;    int numToks;    toks = mSplit(args, " ", 20, &numToks, '\\');   	if (numToks > 0) {		report_anom_thres = atof(toks[0]);	} else {		report_anom_thres= -1;	}	if (as_debug) printf("anomaly reporting threshold is %f\n",report_anom_thres);	if (numToks > 1) {		statefile = toks[1];	} else {		statefile= "spade.rcv";	}	if (as_debug) printf("state file is %s\n",statefile);	if (numToks > 2) {    	outfile = toks[2];    } else {    	outfile= "-";    }	if (as_debug) printf("output file is %s\n",outfile);	if (numToks > 3) {    	prob_mode = atoi(toks[3]);    	if (prob_mode > 3 || prob_mode < 0) {    		ErrorMessage("Warning: spp_anomsensor probabity mode #%d undefined, using #3 instead",prob_mode);    		prob_mode= 3;    	}    } else {    	prob_mode= 3;    }	if (as_debug) printf("probability mode is %d\n",prob_mode);	if (numToks > 4) {    	checkpoint_freq= atoi(toks[4]);    } else {    	checkpoint_freq= 50000;    }	if (as_debug) printf("checkpoint frequency is %d\n",checkpoint_freq);}/* Spade core routine that is called with each packet */void PreprocSpade(Packet *p){	if (record_maybe_skip(p)) return;	/* accepted packets only past here; anom score is last_anom_score */		if (report_anom_thres >= 0.0 && last_anom_score >= report_anom_thres) {		char logMessage[65];		alert_count++;		recent_alert_count++;		sprintf(logMessage,"spp_anomsensor: Anomaly threshold exceeded: %.4f",last_anom_score);		(*AlertFunc)(p, logMessage);	}}	/*========================================================================*//*========================= SpadeHomenet module ==========================*//*========================================================================*//* This module makes only packets to certain networks be considered for theanomaly sensor; list your most common networks first for increasedefficiency *//* snort config file line:	preprocessor spade-homenet: {<network>}	where <network> is a network in CIDR notation (address/numbits)	                   or an IP address */														ll_net *homelist= NULL;  // the only networks we should be looking at packets going to/* Spade homenet init function:     set up the homenet list */void SpadeHomenetInit(u_char *args){    char **toks;    int numToks;	if (as_debug) printf("Preprocessor: SpadeHomenet Initialized\n");    /* parse the argument list from the rules file */    toks = mSplit(args, " ", 200, &numToks, '\\');    if (strspn(toks[numToks-1]," \t") == strlen(toks[numToks-1])) numToks--; /* last is just whitespace */    homelist= create_netlist(toks,numToks);        if (as_debug) {    	ll_net *n;   		struct in_addr net;    	printf("SpadeHomenet nets are:\n");    	for (n=homelist; n != NULL; n=n->next) {    		net.s_addr= n->netaddr;    		printf("\t%s with mask %lx\n",inet_ntoa(net),(u_long)ntohl(n->netmask));    	}    }}// create a linked list of network specifications (address and netmask) from//  a array of strings representing an CIDR network spec or an IP addressll_net *create_netlist(char *nets[],int count) {	ll_net *prev=NULL,*head=NULL,*cur=NULL;	int i;    char **toks;    int num_toks;    int nmask;    struct in_addr net;		for (i=0; i < count; i++) {		cur= (ll_net *)malloc(sizeof(ll_net));		cur->next= NULL;		if (i > 0) {			prev->next= cur;		} else {			head= cur;		}				// this code based strongly on GenHomenet in snort.c		/* break out the CIDR notation from the IP address */	    toks = mSplit(nets[i],"/",2,&num_toks,0);        /* convert the CIDR notation into a real live netmask */	    if (num_toks < 2) {	    	nmask= 32;	    } else { 	    	nmask = atoi(toks[1]);	    }        if ((nmask >= 0) && (nmask <= 32))        {            cur->netmask = netmasks[nmask];        }        else        {            FatalError("ERROR: Bad CIDR size [%d], 1 to 32 please!\n",                       nmask);        }	    /* since PC's store things the "wrong" way, shuffle the bytes into 	       the right order */#ifndef WORDS_BIGENDIAN	    cur->netmask = htonl(cur->netmask);#endif	    /* convert the IP addr into its 32-bit value */	    if ((net.s_addr = inet_addr(toks[0])) ==-1)	    {	        FatalError("ERROR: network (%s) didn't translate with inet_addr, must be poorly formed\n",	                   toks[0]);	    }	    else	    {	        cur->netaddr = ((u_long)net.s_addr & cur->netmask);	    }	    free(toks);				prev= cur;	}		return head;}/*========================================================================*//*=========================== SpadeStat module ===========================*//*========================================================================*//* Whenever the CleanUpSpade is invoked, this module arranges for certain   specified statistics to be written to the log file.  The available   statistics depend on what is recorded in the tree, which depends on the   probability measure used.  There is no good way to have more granularity   at present.  You need to change the setting of the "parts" variable to 1   and set the part variable to one of the parts in the record_packet   routine (to which you might add a new part). */

⌨️ 快捷键说明

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