pynids-0.6.1.orig/0000755000175000007640000000000011400762242013276 5ustar lucianoscodepynids-0.6.1.orig/CHANGES0000644000175000007640000000567511371574066014322 0ustar lucianoscodepynids Attribution: - Michael J. Pomraning JN - Jose Nazario RB - Richard Bejtlich JO - Jon Oberheide EC - Evan Cooke JF - Jeff Nathan 9 May 2010 - version 0.6.1 (JO) - bump bundled libnids to 1.24 (JO) - support for packet timestamps (JF) - support for pcap stats (JF) 9 Oct 2009 - version 0.6 (JO) - bump bundled libnids to 1.23 (JO) - added -fPIC to fix builds (JO) 3 May 2007 - version 0.5a (JO) - bump bundled libnids to 1.21 (JO) - add checksum control function (chksum_ctl) (EC) 31 Jan 2005 - version 0.5 - documented nids.param() variables. - documented TcpStream and HalfStream methods and members in module docstring. - added 'Prerequisites' to README. 27 Jan 2005 - version 0.5rc1 - setup.py nonstandard patch(1) invocation flummoxed FreeBSD (rpt. RB) 26 Jan 2005 - version 0.4 - docstrings added to module and module functions. - libnids-1.19 and ``nids_dispatch()'' patch bundled, allowing proper exception handling in callbacks all around. - API: 'dispatch' function added. Undocumented and subject to change if libnids adopts similar function. - misc: setup.py searches '/usr/local' by default. included. 24 Dec 2004 - version 0.4rc1 - makeRegisterFunc macro increfs user-supplied function. (On linux, at least, registration of bound methods would precipitate segfault.) - hs_get_data, hs_get_urgdata return strings now, not read-only buffers objects. 06 Dec 2004 - version 0.3 - API: 'pcap_timeout' parameter support for libnids >= 1.19 - API: 'collect' and 'collect_urg' are boolean-ified - tp_getset/tp_method reimplementation of TcpStream and HalfStream - fix possible memory corruption (noticed by JN): hlfs->data member not guaranteed to be allocated (e.g., in a NIDS_JUST_EST conn). API: We treat as an empty buffer in this case. - misc: Py_RETURN_NONE, PyModule_AddIntConstant(), "N" fmt specifier in udp handler - updated README 05 Dec 2004 - version 0.2 - "filename" awareness in nids.param() (patch JN) - exception throwing retracted for next()/run(), after difficulty indicated by JN. next() now returns as does nids_next(), and run() returns None. - updated README, Example 13 Aug 2003 - half-stream "data" member now raw PyBuffer - plug minor nids_param memleak - errbuf() retired in favor of module exception (nids.error). init, run, next and getfd modified accordingly - updated README 20 Jul 2003 - version 0.1 - mem: fix callTcpFunc() memleak, discretionary HalfStream ctor - run()/next() exception propagation - added Example, installation blurb 18 Jul 2003 - complete register_*, remove some error-checking (!) - pytuple4 - README, CHANGES 17 Jul 2003 - init, run, next, discard, getfd, register_tcp - TcpStream objects, HalfStream objects pynids-0.6.1.orig/nidsmodule.c0000644000175000007640000007221111371574261015621 0ustar lucianoscode/* nidsmodule.c - C implementation of pynids Copyright (c) 2003 Michael J. Pomraning $Id: nidsmodule.c,v 1.11 2005/02/01 05:50:06 mjp Exp $ This file is part of the pynids package, a python interface to libnids. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of 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 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA */ #include "Python.h" #include #include #include #include #include #include #include #ifdef DEBUG #define DBG(f, ...) fprintf(stderr, f, ##__VA_ARGS__) #else #define DBG(p, ...) #endif /* DEBUG */ #ifndef Py_RETURN_NONE # define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None #endif /* Py_RETURN_NONE */ /* ====================================================================== */ /* Module Globals and Utility Functions */ /* ====================================================================== */ static PyObject *pynids_error; /* nids.error */ static int pynids_offline_read = 0; /* see nids.init(), nids.next() */ static PyObject *tcpFunc = NULL; static PyObject *udpFunc = NULL; static PyObject *ipFunc = NULL; static PyObject *fragFunc = NULL; static struct nids_prm origNidsParams; typedef struct { PyObject_HEAD struct tcp_stream *tcps; PyObject *client; PyObject *server; } TcpStream; typedef struct { PyObject_HEAD struct half_stream *hlfs; } HalfStream; staticforward PyTypeObject TcpStream_Type; staticforward PyTypeObject HalfStream_Type; /* wrapHalfStream used by TcpStream getter */ static HalfStream *wrapHalfStream(struct half_stream *); static char pynidsmodule__doc__[] = "A wrapper around the libnids Network Intrusion Detection library.\n\ \n\ Functions:\n\ \n\ param() -- set various libnids parameters\n\ init() -- open the capture stream, prepare internal \n\ getfd() -- return the file descriptor associated with the capture stream\n\ get_pkt_ts() -- return the timestamp of the most recently received packet\n\ get_pcap_stats() -- return num packets rcvd, num pkts dropped,\n\ num pkts dropped by interface as a tuple\n\ register_ip_frag() -- install a callback for IP fragment processing\n\ register_ip() -- install a callback for reassembled IP packet processing\n\ register_tcp() -- install a callback for reaseembled TCP packet processing\n\ register_udp() -- install a callback for reassembled UDP packet processing\n\ chksum_ctl() -- control whether packets are checksum by source address\n\ next() -- process one packet from the capture stream, invoking callbacks\n\ run() -- process all packets from the capture stream, invoking callbacks\n\ \n\ Special objects and classes:\n\ \n\ error -- exception raised for serious libnids/pcap errors\n\ TcpStream -- class of argument to TCP callback function. Features:\n\ addr -- Connection tuple: ((src, sport), (dst, dport))\n\ discard(n) -- purge n bytes from the data buffer\n\ kill() -- send symmetric RSTs to tear down the connection\n\ nids_state -- see 'Constants,' below\n\ client -- half of the connection; a TcpStream object\n\ server -- half of the connection; a TcpStream object\n\ HalfStream -- class of TcpStream 'client' and 'server' members. Features:\n\ collect -- boolean controlling whether data is collected\n\ collect_urg -- boolean controlling URG data collection\n\ count -- number of bytes appended to 'data' since creation\n\ count_new -- number of newly collected bytes in 'data'\n\ count_new_urg -- number of new urgent bytes\n\ data -- string buffer of normal (non-urgent) data\n\ urgdata -- one-byte string buffer\n\ offset -- offset of newly collected bytes in 'data'\n\ state -- [*] numeric socket state\n\ \n\ * TCP state constants (e.g., TCP_ESTABLISHED) are not supplied by pynids\n\ \n\ See the libnids documentation or the pynids README for more information\n\ on the TcpStream and HalfStream objects.\n\ \n\ Constants:\n\ \n\ NIDS_CLOSE, NIDS_DATA, NIDS_EXITING, NIDS_JUST_EST, NIDS_RESET,\n\ NIDS_TIMED_OUT, NIDS_TIMEOUT -- possible values of the 'nids_state' member\n\ of a TcpStream object.\n"; static PyObject * raisePynidsError(void) { extern char nids_errbuf[]; PyErr_SetString(pynids_error, nids_errbuf); return NULL; } /* nids_dispatch_exc() * * Like nids_dispatch, but setting a Python exception upon serious error. * Non-serious error conditions (timeout, EOF) do not raise an exception. * * args: none * rtrn: >0 on successfully processing one packet * 0 timeout or EOF * -1 exception thrown (either in user callback or in nids/pcap) * */ static int nids_dispatch_exc(int n) { int ret; DBG("nids_dispatch_exc(%d)\n", n); ret = nids_dispatch(n); if (ret == -1) { /* pcap error trumps user callback exception */ raisePynidsError(); return -1; } if (PyErr_Occurred()) return -1; /* check for callback exception */ return ret; } /* pytuple4(tuple4): ((src, sport), (dst, dport)) */ static PyObject * pytuple4(struct tuple4 *addr) { struct in_addr in; PyObject *t1, *t2, *ret; in.s_addr = addr->saddr; t1 = Py_BuildValue("si", inet_ntoa(in), addr->source); if (! t1) return NULL; in.s_addr = addr->daddr; t2 = Py_BuildValue("si", inet_ntoa(in), addr->dest); if (! t2) { Py_DECREF(t1); return NULL; } ret = Py_BuildValue("OO", t1, t2); Py_DECREF(t1); Py_DECREF(t2); return ret; } /* ====================================================================== */ /* pynids Object Implementation */ /* ====================================================================== */ /* TcpStream ctor -- called by callTcpFunc, not user */ static TcpStream * wrapTcpStream(struct tcp_stream *t) { TcpStream *self; self = PyObject_New(TcpStream, &TcpStream_Type); if (self == NULL) return NULL; self->tcps = t; self->client = NULL; self->server = NULL; DBG("TcpStream_ctor(%p)\n", self); /* * wrap half streams on demand, if demanded... self->client = (PyObject *) wrapHalfStream(&t->client); self->server = (PyObject *) wrapHalfStream(&t->server); */ return self; } static void TcpStream_dealloc(TcpStream *self) { DBG("TcpStream_dealloc(%p)\n", self); self->tcps = NULL; /* libnids will free this when approp. */ if (self->client) { Py_DECREF(self->client); self->client = NULL; } if (self->server) { Py_DECREF(self->server); self->server = NULL; } PyObject_Del(self); } /* ====================================================================== */ /* TcpStreams: ctor, dtor, methods, members and type */ /* ====================================================================== */ static PyObject * TcpStream_discard(TcpStream *self, PyObject *args) { int i; if (!PyArg_ParseTuple(args, "i:discard", &i)) return NULL; nids_discard(self->tcps, i); Py_RETURN_NONE; } static PyObject * TcpStream_kill(TcpStream *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":kill")) return NULL; nids_killtcp(self->tcps); Py_RETURN_NONE; } static PyMethodDef TcpStream_methods[] = { {"discard", (PyCFunction)TcpStream_discard, METH_VARARGS}, {"kill", (PyCFunction)TcpStream_kill, METH_VARARGS}, {NULL, NULL} /* sentinel */ }; #define TS_GET_HLFS(ATTR) \ static PyObject * ts_get_##ATTR(TcpStream *self, void *unused) { \ if (!self->ATTR) { \ self->ATTR = (PyObject *) wrapHalfStream(&self->tcps->ATTR); \ if (!self->ATTR) return NULL; \ } \ Py_INCREF(self->ATTR); \ return self->ATTR; \ } /* RO attributes */ TS_GET_HLFS(client) TS_GET_HLFS(server) static PyObject * ts_get_addr(TcpStream *self, void *unused) { return pytuple4(&self->tcps->addr); } static PyObject * ts_get_nids_state(TcpStream *self, void *unused) { return PyInt_FromLong((long)self->tcps->nids_state); } static PyGetSetDef TcpStream_getsets[] = { {"client", (getter)ts_get_client}, {"server", (getter)ts_get_server}, {"addr", (getter)ts_get_addr}, {"nids_state", (getter)ts_get_nids_state}, {NULL} /* Sentinel */ }; statichere PyTypeObject TcpStream_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "TcpStream", /*tp_name*/ sizeof(TcpStream), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)TcpStream_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_HAVE_CLASS, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ TcpStream_methods, /*tp_methods*/ 0, /*tp_members*/ TcpStream_getsets, /*tp_getset*/ 0, /*tp_base*/ }; /* ====================================================================== */ /* HalfStreams: ctor, dtor, methods, members and type */ /* ====================================================================== */ static HalfStream * wrapHalfStream(struct half_stream *h) { /* called by TcpStream ctor */ HalfStream *self; self = PyObject_New(HalfStream, &HalfStream_Type); if (self == NULL) return NULL; self->hlfs = h; DBG("HalfStream_ctor(%p)\n", self); return self; } static void HalfStream_dealloc(HalfStream *self) { DBG("HalfStream_dealloc(%p, %d)\n", self, self->ob_refcnt); self->hlfs = NULL; PyObject_Del(self); } #define HS_GET_INT(ATTR) \ static PyObject * hs_get_##ATTR(HalfStream *self, void *unused) { \ return PyInt_FromLong((long)self->hlfs->ATTR); \ } /* FIXME - true bool support */ #define HS_GET_BOOL(ATTR) \ static PyObject * hs_get_##ATTR(HalfStream *self, void *unused) { \ return PyInt_FromLong(self->hlfs->ATTR ? 1L : 0L); \ } #define HS_SET_BOOL(ATTR) \ static int hs_set_##ATTR(HalfStream *self, PyObject *val, void *closure) { \ if (val == NULL) { \ PyErr_SetString(PyExc_TypeError, \ "Cannot delete the " #ATTR "attribute"); \ return -1; \ } \ DBG("hs_set_" #ATTR "(HalfStream * %p, bool %d)\n", \ self, PyObject_IsTrue(val)); \ self->hlfs->ATTR = PyObject_IsTrue(val); \ return 0; /* success */ \ } /* RW attributes */ HS_GET_BOOL(collect) HS_SET_BOOL(collect) HS_GET_BOOL(collect_urg) HS_SET_BOOL(collect_urg) /* RO attributes */ HS_GET_INT(state) static PyObject *hs_get_data(HalfStream *self, void *unused) { /* data may not be allocated if the conn/libnids has seen no data */ if (! self->hlfs->data) return PyString_FromStringAndSize("", 0); /* bufsize is an undocumented member */ return PyString_FromStringAndSize(self->hlfs->data, self->hlfs->bufsize); } static PyObject *hs_get_urgdata(HalfStream *self, void *unused) { /* u_char urgdata */ return PyString_FromStringAndSize(&(self->hlfs->urgdata), sizeof(self->hlfs->urgdata)); } HS_GET_INT(count) HS_GET_INT(offset) HS_GET_INT(count_new) HS_GET_INT(count_new_urg) static PyGetSetDef HalfStream_getsets[] = { {"state", (getter)hs_get_state}, {"collect", (getter)hs_get_collect, (setter)hs_set_collect}, {"collect_urg", (getter)hs_get_collect_urg, (setter)hs_set_collect_urg}, {"data", (getter)hs_get_data}, {"urgdata", (getter)hs_get_urgdata}, {"count", (getter)hs_get_count}, {"offset", (getter)hs_get_offset}, {"count_new", (getter)hs_get_count_new}, {"count_new_urg", (getter)hs_get_count_new_urg}, {NULL} /* Sentinel */ }; statichere PyTypeObject HalfStream_Type = { /* The ob_type field must be initialized in the module init function * to be portable to Windows without using C++. */ PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "HalfStream", /*tp_name*/ sizeof(HalfStream), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)HalfStream_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_HAVE_CLASS, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ HalfStream_getsets, /*tp_getset*/ 0, /*tp_base*/ }; /* ====================================================================== */ /* User-Defined libnids Handler Hooks */ /* ====================================================================== */ static void callTcpFunc(struct tcp_stream *ts, void **param) { PyObject *ret = NULL; TcpStream *tso = NULL; DBG("callTcpFunc - init tso\n"); tso = wrapTcpStream(ts); if (! tso) return; DBG("callTcpFunc - call func %p(%p)\n", tcpFunc, tso); ret = PyObject_CallFunction(tcpFunc, "O", tso); DBG("callTcpFunc - dealloc tso (ret: %p)\n", ret); Py_DECREF(tso); if (ret) { Py_DECREF(ret); } return; } static void callUdpFunc(struct tuple4 *addr, u_char *data, int len, struct ip *pkt) { PyObject *ret = NULL; DBG("callUdpFunc...\n"); ret = PyObject_CallFunction(udpFunc, "(Ns#s#)", pytuple4(addr), data, len, pkt, ntohs(pkt->ip_len)); if (ret) { Py_DECREF(ret); } return; } static void callIpFunc(struct ip *pkt) { PyObject *ret = NULL; DBG("callIpFunc...\n"); ret = PyObject_CallFunction(ipFunc, "s#", pkt, ntohs(pkt->ip_len)); if (ret) { Py_DECREF(ret); } return; } static void callFragFunc(struct ip *pkt) { PyObject *ret = NULL; ret = PyObject_CallFunction(fragFunc, "s#", pkt, ntohs(pkt->ip_len)); if (ret) { Py_DECREF(ret); } return; } /* makeRegisterFunc(type, static PyFunction ptr, dispatch) * * what PyObject * Invoker * ----------------------------------- * tcp tcpFunc callTcpFunc * udp udpFunc callUdpFunc * ip ipFunc callIpFunc * ip_frag fragFunc callFragFunc */ #define makeRegisterFunc(WHAT, FP, PYDISPATCH) \ \ static char pynids_register_##WHAT##__doc__[] = \ "register_" #WHAT "(func) -> None\n" \ "\n" \ "Register the given user-defined function as a callback handler.\n"; \ \ static PyObject * \ pynids_register_##WHAT (PyObject *na, PyObject *args) \ { \ PyObject *pyFunc = NULL; \ if (!PyArg_ParseTuple(args, "O:register_" #WHAT, &pyFunc)) \ return NULL; \ \ if (FP != NULL) { \ /* (re-)set single, global func ptr */ \ PyObject_Del(FP); \ } else { \ nids_register_##WHAT(PYDISPATCH); \ } \ DBG("Inside register_" #WHAT "(%p)\n", pyFunc); \ FP = pyFunc; \ Py_INCREF(FP); \ Py_RETURN_NONE; \ } /* What PyFunc * C-level Dispatch */ /* ---- -------- ---------------- */ makeRegisterFunc(tcp, tcpFunc, callTcpFunc); makeRegisterFunc(udp, udpFunc, callUdpFunc); makeRegisterFunc(ip, ipFunc, callIpFunc); makeRegisterFunc(ip_frag, fragFunc, callFragFunc); /* ====================================================================== */ /* Module Functions */ /* ====================================================================== */ static char pynids_chksum_ctl__doc__[] = "chksum_ctl([(addr1, True), (addr2, False)], ...) -> None\n\ \n\ takes as arguments an list of tuples where a tuple should have the\n\ following format:\n\ (Source address in CIDR format, Boolean whether to apply checksum)\n\ e.g. (\"192.168.1.10/24\", True)\n\ Internal checksumming functions will first check elements of this\n\ list one by one, and if the source ip of the current packet\n\ matches the source address and mask of a tuple then the packet with either\n\ be checksummed if the apply boolean is set to True, or not checksummed if\n\ the boolean is set to False. If the packet matches none of the list\n\ elements, the default action is to perform checksumming.\n"; static int _parse_prefix(char *prefix, u_int *netaddr, u_int *mask) { struct in_addr in; char *ptr, *data; u_int m; /* eat up white space */ data = prefix; while (*data == ' ' && *data == '\t') data++; /* find end */ ptr = data; while (*ptr != '/' && *ptr != '\n' && *ptr != '\0') ptr++; if (*ptr == '/') { *ptr = '\0'; ptr++; /* convert the ip to binary */ if (inet_pton(AF_INET, data, &in) < 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } *netaddr = in.s_addr; /* get mask */ m = 32 - atoi(ptr); *mask = (m >= 32) ? 0 : htonl((0xffffffff >> m) << m); } else if (strlen(data) >= 7) { /* convert the ip to binary */ if (inet_pton(AF_INET, data, &in) < 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } *netaddr = in.s_addr; *mask = 0xffffffff; } return 0; } static int _parse_chksum_tuple(struct nids_chksum_ctl *ctl, int i, PyObject *tuple) { PyObject *addr, *action; addr = PyTuple_GET_ITEM(tuple, 0); if (PyString_Check(addr) <= 0) { PyErr_SetString(PyExc_TypeError, "in (cidr_address, action) cidr_address must be string"); return -1; } if (_parse_prefix(PyString_AS_STRING(addr), &ctl[i].netaddr, &ctl[i].mask) < 0) return -1; action = PyTuple_GET_ITEM(tuple, 1); if (PyBool_Check(action) <= 0) { PyErr_SetString(PyExc_TypeError, "in (cidr_address, action) action must be boolean"); return -1; } if (action == Py_False) ctl[i].action = NIDS_DONT_CHKSUM; else ctl[i].action = NIDS_DO_CHKSUM; return 0; } static PyObject * pynids_chksum_ctl(PyObject *na, PyObject *args) { PyObject *items, *tuple; int i, n; struct nids_chksum_ctl *ctl = NULL; /* parse args */ if (!PyArg_ParseTuple(args, "O:chksum_ctl", &items)) return NULL; /* parse list of address/action tuples */ if (PyList_Check(items) > 0) { n = PyList_Size(items); ctl = (struct nids_chksum_ctl *) \ malloc(sizeof(struct nids_chksum_ctl) * n); if (ctl == NULL) { PyErr_SetString(PyExc_OSError, "could not allocate temp memory storage"); return NULL; } for (i=0; i 1 || (NIDS_MAJOR == 1 && NIDS_MINOR >= 19)) "pcap_timeout -- pcap capture timeout, in milliseconds (1024)\n" #endif /* libnids >= 1.19 */ "promisc -- non-zero if promiscuous mode is desired on capture device (1)\n\ sk_buff_size -- size of struct skbuff, used for queueing packets (168)\n\ syslog_level -- log level used when syslogging events (LOG_ALERT)\n\ scan_num_hosts -- hash table size for portscan detection (256)\n\ scan_num_ports -- minimum ports per src. host to qualify as a portscan (10)\n\ scan_delay -- maximum delay in milliseconds between (3000)\n\ \n\ Either 'device' or 'filename' must be specified before calling nids_init().\n\ Portscan detection may be disabled by setting 'scan_num_hosts' to zero. See\n\ the libnids documentation for more details.\n"; static PyObject * pynids_param(PyObject *na, PyObject *args) { PyObject *v = NULL; PyObject *ret = NULL; int *int_p = NULL; char **char_pp = NULL; char *name; if (!PyArg_ParseTuple(args, "s|O", &name, &v)) return NULL; /* is it an int parameter? */ if (!strcmp(name, "n_tcp_streams")) int_p = &nids_params.n_tcp_streams; else if (!strcmp(name, "n_hosts")) int_p = &nids_params.n_hosts; else if (!strcmp(name, "sk_buff_size")) int_p = &nids_params.sk_buff_size; else if (!strcmp(name, "dev_addon")) int_p = &nids_params.dev_addon; else if (!strcmp(name, "syslog_level")) int_p = &nids_params.syslog_level; else if (!strcmp(name, "scan_num_hosts")) int_p = &nids_params.scan_num_hosts; else if (!strcmp(name, "scan_num_ports")) int_p = &nids_params.scan_num_ports; else if (!strcmp(name, "scan_delay")) int_p = &nids_params.scan_delay; else if (!strcmp(name, "promisc")) int_p = &nids_params.promisc; else if (!strcmp(name, "one_loop_less")) int_p = &nids_params.one_loop_less; #if (NIDS_MAJOR > 1 || (NIDS_MAJOR == 1 && NIDS_MINOR >= 19)) else if (!strcmp(name, "pcap_timeout")) int_p = &nids_params.pcap_timeout; #endif /* libnids >= 1.19 */ if (int_p) { /* FIXME - type check val for intishness */ ret = PyInt_FromLong((long) *int_p); if (v) *int_p = (int) PyInt_AsLong(v); return ret; } /* is it a char * param? */ if (!strcmp(name, "device")) char_pp = &nids_params.device; else if (!strcmp(name, "pcap_filter")) char_pp = &nids_params.pcap_filter; else if (!strcmp(name, "filename")) char_pp = &nids_params.filename; if (char_pp) { /* XXX - error checking, PyMem alloc/free */ ret = Py_BuildValue("s", *char_pp); if (v) { /* free previous strdup -- fortunately libnids inits these to * NULL... */ if (*char_pp) free(*char_pp); *char_pp = (v == Py_None) ? NULL : strdup(PyString_AsString(v)); } return ret; } /****** if (!strcmp(name, "syslog")) func_pp = &nids.syslog; else if (!strcmp(name, "ip_filter")) func_pp = &nids.ip_filter; else if (!strcmp(name, "no_mem")) func_pp = &nids.no_mem; ******/ Py_RETURN_NONE; } static char pynids_getfd__doc__[] = "getfd() -> fd\n\ \n\ Returns the integral file descriptor of the live capture device or pcap\n\ savefile specified during the call to init(). The resultant fd is suitable\n\ for I/O polling with select.select(), for example.\n"; static PyObject * pynids_getfd(PyObject *na, PyObject *args) { int pcap_fd; if (!PyArg_ParseTuple(args, ":getfd")) return NULL; if ((pcap_fd = nids_getfd()) == -1) return raisePynidsError(); return PyInt_FromLong((long) pcap_fd); } static char pynids_next__doc__[] = "next() -> r\n\ \n\ Attempt to process one packet, returning 1 if a packet was processed and 0\n\ on timeout or EOF, as appropriate to the capture stream. Serious errors in\n\ pcap raise a nids.error exception.\n"; static PyObject * pynids_next(PyObject *na, PyObject *args) { int ret; if (!PyArg_ParseTuple(args, ":next")) return NULL; ret = nids_dispatch_exc(1); if (PyErr_Occurred()) return NULL; /* python callback error */ return PyInt_FromLong((long) ret); } static char pynids_dispatch__doc__[] = "dispatch(cnt) -> processed\n\ \n\ UNDOCUMENTED -- this function does not exist in libnids <= 1.19.\n"; static PyObject * pynids_dispatch(PyObject *na, PyObject *args) { int ret, cnt; if (!PyArg_ParseTuple(args, "i:dispatch", &cnt)) return NULL; ret = nids_dispatch_exc(cnt); if (ret == -1) return NULL; return PyInt_FromLong((long) ret); } static char pynids_run__doc__[] = "run() -> None\n\ \n\ On a live capture, process packets ad infinitum; on an offline read, process\n\ packets until EOF. In either case, an exception thrown in a user callback\n\ or in nids/pcap (as nids.error) may abort processing.\n"; static PyObject * pynids_run(PyObject *na, PyObject *args) { int r; if (!PyArg_ParseTuple(args, ":run")) return NULL; if (pynids_offline_read) { /* read until EOF, checking for exceptions along the way */ do { r = nids_dispatch_exc(1); } while (r > 0); } else { /* read forever, checking for exceptions along the way */ do { r = nids_dispatch_exc(1); } while (r >= 0); } if (r == -1) return NULL; #if 0 if (r != 0) runtime error! #endif Py_RETURN_NONE; } static char pynids_init__doc__[] = "init() -> None\n\ \n\ Initialize the nids library, as specified by previous calls to param(). In\n\ particular, the capture device 'device' or pcap savefile 'filename' is\n\ opened, the 'pcap_filter' compiled, and various internal mechanisms prepared.\n\ \n\ It is appropriate and recommended to drop process privileges after making\n\ this call.\n"; static PyObject * pynids_init(PyObject *na, PyObject *args) { int ok; if (!PyArg_ParseTuple(args, ":init")) return NULL; ok = nids_init(); if (! ok) return raisePynidsError(); if (nids_params.filename) pynids_offline_read = 1; else pynids_offline_read = 0; Py_RETURN_NONE; } static char pynids_get_pkt_ts__doc__[] = "get_pkt_time() -> float\n\ \n\ Returns the timestamp of the most recent packet as a float.\n"; static PyObject * pynids_get_pkt_ts(PyObject *na, PyObject *args) { double pkt_time; if (!PyArg_ParseTuple(args, ":get_pkt_ts")) return NULL; pkt_time = nids_last_pcap_header->ts.tv_sec + (nids_last_pcap_header->ts.tv_usec / 1000000.0); return PyFloat_FromDouble(pkt_time); } static char pynids_get_pcap_stats__doc__[] = "get_pcap_stats() -> tuple\n\ \n\ Returns the pcap recv, drop and interface drop statistics as a tuple.\n"; static PyObject * pynids_get_pcap_stats(PyObject *na, PyObject *args) { static struct pcap_stat ps; PyObject *pcap_stats_tuple; if (!PyArg_ParseTuple(args, ":get_pcap_stats")) return NULL; if (nids_params.pcap_desc == NULL || pcap_stats(nids_params.pcap_desc, &ps) != 0) { raisePynidsError(); return NULL; } pcap_stats_tuple = Py_BuildValue("III", ps.ps_recv, ps.ps_drop, ps.ps_ifdrop); if (! pcap_stats_tuple) return NULL; return pcap_stats_tuple; } /* List of functions defined in the module */ #define mkMethod(x) \ {#x, pynids_##x, METH_VARARGS, pynids_##x##__doc__} static PyMethodDef pynids_methods[] = { mkMethod(run), mkMethod(dispatch), mkMethod(getfd), mkMethod(next), mkMethod(register_tcp), mkMethod(register_udp), mkMethod(register_ip), mkMethod(register_ip_frag), mkMethod(chksum_ctl), mkMethod(init), mkMethod(param), mkMethod(get_pkt_ts), mkMethod(get_pcap_stats), {NULL, NULL} /* sentinel */ }; #undef mkMethod /* ====================================================================== */ /* Module Initialization */ /* ====================================================================== */ DL_EXPORT(void) initnids(void) { PyObject *m; /* Initialize the type of the new type object here; doing it here * is required for portability to Windows without requiring C++. */ TcpStream_Type.ob_type = &PyType_Type; HalfStream_Type.ob_type = &PyType_Type; /* Create the module and add the functions */ m = Py_InitModule3("nids", pynids_methods, pynidsmodule__doc__); /* Initialize, add our exception object */ pynids_error = PyErr_NewException("nids.error", NULL, NULL); Py_INCREF(pynids_error); PyModule_AddObject(m, "error", pynids_error); /* Add versioning info */ PyModule_AddStringConstant(m, "__version__", "0.6.1"); PyModule_AddObject(m, "__nids_version__", PyString_FromFormat("%d.%d", NIDS_MAJOR, NIDS_MINOR)); /* Add NIDS_ symbolic constants to the module */ #define setConst(CONST) \ PyModule_AddIntConstant(m, #CONST, CONST) setConst(NIDS_JUST_EST); setConst(NIDS_DATA); setConst(NIDS_CLOSE); setConst(NIDS_RESET); setConst(NIDS_TIMED_OUT); #ifndef NIDS_TIMEOUT #define NIDS_TIMEOUT NIDS_TIMED_OUT #endif setConst(NIDS_TIMEOUT); /* compat. w/ manpage */ setConst(NIDS_EXITING); /* Save the original nids_params */ origNidsParams = nids_params; } /* * vim:noet:ts=4: */ pynids-0.6.1.orig/Example0000644000175000007640000000404311371573600014622 0ustar lucianoscode#! /usr/bin/env python2 # pynids Example # $Id: Example,v 1.3 2005/01/27 04:53:45 mjp Exp $ import os, pwd import sys import nids NOTROOT = "nobody" # edit to taste end_states = (nids.NIDS_CLOSE, nids.NIDS_TIMEOUT, nids.NIDS_RESET) def handleTcpStream(tcp): print "tcps -", str(tcp.addr), " state:", tcp.nids_state if tcp.nids_state == nids.NIDS_JUST_EST: # new to us, but do we care? ((src, sport), (dst, dport)) = tcp.addr print tcp.addr if dport in (80, 8000, 8080): print "collecting..." tcp.client.collect = 1 tcp.server.collect = 1 elif tcp.nids_state == nids.NIDS_DATA: # keep all of the stream's new data tcp.discard(0) elif tcp.nids_state in end_states: print "addr:", tcp.addr print "To server:" print tcp.server.data[:tcp.server.count] # WARNING - may be binary print "To client:" print tcp.client.data[:tcp.client.count] # WARNING - as above def main(): #nids.param("pcap_filter", "tcp") # bpf restrict to TCP only, note # libnids caution about fragments nids.param("scan_num_hosts", 0) # disable portscan detection nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming if len(sys.argv) == 2: # read a pcap file? nids.param("filename", sys.argv[1]) nids.init() (uid, gid) = pwd.getpwnam(NOTROOT)[2:4] os.setgroups([gid,]) os.setgid(gid) os.setuid(uid) if 0 in [os.getuid(), os.getgid()] + list(os.getgroups()): print "error - drop root, please!" sys.exit(1) nids.register_tcp(handleTcpStream) print "pid", os.getpid() # Loop forever (network device), or until EOF (pcap file) # Note that an exception in the callback will break the loop! try: nids.run() except nids.error, e: print "nids/pcap error:", e except Exception, e: print "misc. exception (runtime error in user callback?):", e if __name__ == '__main__': main() pynids-0.6.1.orig/setup.py0000644000175000007640000000467311371574202015026 0ustar lucianoscode#! /usr/bin/env python # setup.py - Distutils instructions for the pynids package # This file is part of the pynids package, a python interface to libnids. # See the file COPYING for license information. from distutils.core import setup, Extension from distutils.command.build import build # nidsMaker from distutils.spawn import spawn # nidsMaker.run() import os, os.path pathjoin = os.path.join PKGNAME = 'libnids-1.24' PKGTAR = PKGNAME + '.tar.gz' BUILDDIR = PKGNAME INCLUDE_DIRS = ['/usr/local/include', '/opt/local/include'] LIBRARY_DIRS = ['/usr/local/lib', '/opt/local/lib'] EXTRA_OBJECTS = [] class nidsMaker(build): NIDSTAR = PKGTAR NIDSDIR = BUILDDIR include_dirs = [ pathjoin(NIDSDIR, 'src') ] library_dirs = [] extra_objects = [ pathjoin(NIDSDIR, 'src', 'libnids.a') ] def buildNids(self): # extremely crude package builder try: os.stat(self.NIDSDIR) return None # assume already built except OSError: pass spawn(['tar', '-zxf', self.NIDSTAR], search_path = 1) os.chdir(self.NIDSDIR) spawn([pathjoin('.','configure'), 'CFLAGS=-fPIC']) spawn(['make'], search_path = 1) os.chdir('..') def run(self): self.buildNids() build.run(self) INCLUDE_DIRS = nidsMaker.include_dirs + INCLUDE_DIRS EXTRA_OBJECTS = nidsMaker.extra_objects + EXTRA_OBJECTS setup (# Distribution meta-data name = "pynids", version = "0.6.1", description = "libnids wrapper", author = "Jon Oberheide", author_email = "jon@oberheide.org", license = "GPL", long_description = \ '''pynids is a python wrapper for libnids, a Network Intrusion Detection System library offering sniffing, IP defragmentation, TCP stream reassembly and TCP port scan detection. ------- ''', cmdclass = {'build': nidsMaker}, ext_modules = [ Extension( "nidsmodule", #define_macros = [ ("DEBUG", None), ], sources=["nidsmodule.c"], include_dirs = INCLUDE_DIRS, libraries = ["pcap", "net", "glib-2.0", "gthread-2.0"], library_dirs = LIBRARY_DIRS, extra_objects = EXTRA_OBJECTS ) ], url = "http://jon.oberheide.org/pynids/", ) pynids-0.6.1.orig/COPYING0000644000175000007640000004307611371573600014350 0ustar lucianoscode GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of 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 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. pynids-0.6.1.orig/README0000644000175000007640000001133211371574135014167 0ustar lucianoscodepynids-0.6.1 http://jon.oberheide.org/pynids/ Introduction ============ pynids is a python wrapper for libnids, a Network Intrusion Detection System library offering sniffing, IP defragmentation, TCP stream reassembly and TCP port scan detection. pynids is free software, copyright (C) 2003, 2004, 2005 Michael J. Pomraning . See the file COPYING for license information. libnids is (c) 1999 Rafal Wojtczuk and licensed under the GNU GPL. See http://www.packetfactory.net/projects/libnids/ for more information. Installation ============ Prerequisites ------------- Python >= 2.2 (www.python.org) libpcap (www.tcpdump.org) libnet (www.packetfactory.net/libnet) tar(1) and patch(1) libnids itself is supplied in the pynids distribution. Build and Install ----------------- $ python setup.py build $ python setup.py install API Translation =============== General ------- #include import nids extern nids_params nids.param(what [, new_val]) extern char nids_errbuf[] nids.error Exception instance struct tcp_stream TcpStream type nids_killtcp(tcp_s) tcpStreamObj.kill() nids_discard(tcp_s, 0) tcpStreamObj.discard(0) struct half_stream HalfStream type struct tuple4 ((src, sport), (dst, dport)) Callback Arguments ------------------ Packets and payloads are string buffers, whereas libnids-specific structs are their own types. Either bound methods or plain functions may be registered as callbacks -- their call signature differs only in the presence or absence of an initial 'self' argument. Examples of plain function callbacks: def ip_callback(pkt): pass def frag_callback(pkt): pass def udp_callback(addrs, payload, pkt): ((sip, sport), (dip, dport)) = addrs .... def tcp_callback(tcpStreamObj): clientHlf = tcpStreamObj.client serverHlf = tcpStreamObj.server Significant Differences ----------------------- - error handling (global nids_errbuf[], python exceptions) No function returns an error code; instead, a nids.error exception is raised for init() and getfd(). Unlike libnids, our next() function can detect pcap errors (again raised as nids.error). Exceptions in user callbacks will break either next() or run() calls. - nids_params (global settings) nids.param() handles accessing and changing libnet state variables; there is no object corresponding to a struct nids_prm. Some parameters are unimplemented -- see BUGS below. - half_stream members Only "collect" and "collect_urg" are mutable attributes. - Only one handler per register_* type Successive calls to, e.g., register_tcp() will simply replace the user-defined handle slotted for TCP packets. If you want multiple functions to process packet, implement your own: for f in tcp_func_list: f(tcp_s) - user_tcp_func(..., void **param) The user-controlled pointer has no analog in pynids. Programmers may store connection-specific data in a global dict, for example, keyed on tcpStream.addr. A bound methods registered as callbacks may of course access members of its corresponding object. - tuple4 structs IP addresses are represented as dotted quad strings, and tuple4 members are (re)arranged into a pair of two-tuples suitable for use as AF_INET addresses in the socket module. Significant Likenesses ---------------------- - pynids use, like libnids use, should be restricted to one and only one thread (static variables under the hood). See also "threads and GIL" in BUGS, below. - pcap_close() is apparently only called when nids_run() returns in libnids 1.18; beware fd leaks and inheritance. More generally, there is no way to de-initialize the underlying nids library (reclaiming memory allocated for stream reassembly, for instance). BUGS ==== - nids.param() . missing function hooks (syslog, no_mem, ip_filter) Should we just nail no_mem() down to throw nids.error and invalidate subsequent nids calls? . cannot distinguish between invalid members and char * members set to NULL; param("foo") and param("pcap_filter") could both return None, e.g. . missing type checking . implementation is awkward, comparable to old tp_getattr; better/easier as a module object with members/getsets. . invocation constrained; perhaps introduce a keyword function? - testing . generally insufficient (ip_fragments, tcpO.kill(), etc.) . memory profiling - threads and GIL libnids/libpcap routines have no knowledge of the python GIL, so pynids method calls will block other python threads.