Esempio n. 1
0
    def run(self):
        """
        """

        print "network sniffer started, pid=%s" % self.pid

        # apply BPF filter
        # see http://biot.com/capstats/bpf.html
        # bpf restrict to TCP only, note libnids caution about fragments
        nids.param('pcap_filter', self.bpf_filter)

        # various settings - may be essential
        nids.chksum_ctl([('0.0.0.0/0', False)])             # disable checksumming
        nids.param("scan_num_hosts", 0)                     # disable portscan detection
        #nids.param("scan_num_ports", 0)
        #nids.param("scan_delay", 0)

        nids.param("pcap_timeout", 64)
        nids.param("multiproc", True)
        nids.param("tcp_workarounds", True)

        #nids.param("filename", sys.argv[1])                # read a pcap file?
        nids.param("device", self.interface_name)           # read from network device

        # bootstrap
        nids.init()
        self.drop_root_privileges()
        nids.register_tcp(self.tcp_stream_handler)

        # 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
Esempio n. 2
0
def main():
    args = sys.argv[1:]
    print args

    # Default to listening to all devices
    nids.param("device", 'any')

    nids.param("pcap_filter", ' '.join(args) + ' and tcp')

    # disable portscan detection
    nids.param("scan_num_hosts", 0)

    # disable check-summing
    nids.chksum_ctl([('0.0.0.0/0', False)])

    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(handle_tcp)

    while True:
        try:
            nids.next()
        except nids.error, e:
            print "nids/pcap error:", e
Esempio n. 3
0
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()

    nids.register_tcp(handleTcpStream)
    nids.register_udp(handleUDP)
    nids.register_ip(handleIp)

    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
Esempio n. 4
0
def main():
    """
    Initialise libnids and process the pcap.  This is taken from the pynids
    example code.
    """

    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()

    nids.register_tcp(handleTcpStream)

    # 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
Esempio n. 5
0
 def nids_init(self):
     nids.param("device", self.interface)
     nids.param("pcap_filter", "port 80")
     nids.param("san_num_hosts", 0)
     #nids.param("dev_addon", ?) #might need this for monitor mode
     nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming
     nids.init()
     nids.register_tcp(self.handle_tcp)
     self.nids = nids
Esempio n. 6
0
    def __init__(self):
        nids.param("scan_num_hosts", 0)  # disable portscan detection
        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming

        # Default attribute values
        self._filter = ''
        self._device = ''
        self._pcapfile = ''
        self._callback = lambda x: x
def main():
    nids.param("pcap_filter", "vlan and port 25")
    nids.param("scan_num_hosts", 0)
    nids.chksum_ctl([('0.0.0.0/0', False)])
    nids.param("filename", sys.argv[1])

    nids.init()
    nids.register_tcp(tcp_callback)
    nids.run()
Esempio n. 8
0
def main():

    # parse args
    argparser = argparse.ArgumentParser()
    argparser.add_argument('PCAP', help='Path to the .pcap file to parse')
    argparser.add_argument('-H',
                           metavar='HOST',
                           default='127.0.0.1',
                           help='Address to listen on (DEFAULT: 127.0.0.1)')
    argparser.add_argument('-p',
                           metavar='PORT',
                           type=int,
                           default=3128,
                           help='Port to listen on (DEFAULT: 3128)')
    argparser.add_argument('-v',
                           action='append_const',
                           const=1,
                           default=[],
                           help='Increase the verbosity level')
    args = argparser.parse_args()

    HOST, PORT = args.H, args.p
    verbosity = len(args.v)

    # setup logger
    if verbosity == 0:
        log_level = logging.ERROR
    elif verbosity == 1:
        log_level = logging.INFO
    else:
        log_level = logging.DEBUG
    logging.basicConfig(format='%(levelname)s:%(message)s', level=log_level)

    # setup the reassembler
    nids.param("scan_num_hosts", 0)  # disable portscan detection
    nids.chksum_ctl(
        [('0.0.0.0/0', False)]
    )  # disable checksum verification: jsunpack says it may cause missed traffic
    nids.param("filename", args.PCAP)
    nids.init()
    nids.register_tcp(reassembleTcpStream)
    logging.info("Processing TCP streams...")
    nids.run()

    # process the open streams, which are not processed by pynids
    logging.info("Processing open streams...")
    for c, stream in openstreams.items():
        processTcpStream(stream)

    # run proxy server
    server = ProxyServer((HOST, PORT), ProxyRequestHandler)
    server.allow_reuse_address = True
    try:
        logging.info("Proxy listening on %s:%d" % (HOST, PORT))
        server.serve_forever()
    except KeyboardInterrupt:
        return 0
Esempio n. 9
0
	def __init__(self,fname=None,iface='all'):
		threading.Thread.__init__(self)
		nids.param("scan_num_hosts", 0)
		nids.chksum_ctl([('0.0.0.0/0', False)])
		if fname:
			nids.param("filename", fname)
		else:
			nids.param("device", iface)
		nids.init()
		nids.register_tcp(Nids.handler)
Esempio n. 10
0
 def __init__(self, fname=None, iface='all'):
     threading.Thread.__init__(self)
     nids.param("scan_num_hosts", 0)
     nids.chksum_ctl([('0.0.0.0/0', False)])
     if fname:
         nids.param("filename", fname)
     else:
         nids.param("device", iface)
     nids.init()
     nids.register_tcp(Nids.handler)
Esempio n. 11
0
    def main(self):
        #nids.param("filename", "bittorrent.pcap")
        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        # nids.register_udp()
        nids.init()
        nids.register_tcp(self.handleTcpStream)
        #nids.register_udp(self.handleUtp)

        # Loop forever (network device), or until EOF (pcap file)
        # Note that an exception in the callback will break the loop!

        nids.run()
Esempio n. 12
0
    def run_parser(self, out_queue):
        try:
            nids.param("filename", self.pcap_path)
            nids.param("scan_num_hosts", 0)     # disable portscan detection
            nids.init()
            nids.chksum_ctl([('0.0.0.0/0', False), ])
            nids.register_tcp(self._handleTcpStream)

            nids.run()

        except Exception:
            self.messages = []

        out_queue.put(self.messages)
Esempio n. 13
0
    def main(self):
        #nids.param("scan_num_hosts", 0)
        nids.param("filename", "test1.pcap")
        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        #nids.register_udp()
        nids.init()

        nids.register_tcp(self.handleTcpStream)
        # 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
Esempio n. 14
0
    def run(self, conf):
        self.conf = conf
        self.output = open(conf.output_file, 'a')

        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        nids.param('scan_num_hosts', 0)  # disable portscan detection
        nids.param('filename', conf.filename)
        nids.init()

        nids.register_udp(self.udp_handler)

        try:
            nids.run()
        except nids.error, e:
            print >> sys.stderr, 'nids/pcap error:', e
            sys.exit(1)
Esempio n. 15
0
    def run_parser(self, out_queue):
        try:
            nids.param("filename", self.pcap_path)
            nids.param("scan_num_hosts", 0)  # disable portscan detection
            nids.init()
            nids.chksum_ctl([
                ('0.0.0.0/0', False),
            ])
            nids.register_tcp(self._handleTcpStream)

            nids.run()

        except Exception:
            self.messages = []

        out_queue.put(self.messages)
Esempio n. 16
0
    def __init__(self, filename, protocol, port=None):
        threading.Thread.__init__(self)

        self.port = port
        self.protocol = protocol
        self.done = False
        self.connection_list = deque()
        self.lock = threading.Lock()
        self.delete_read_connections = False
        self.last_read_index = -1

        nids.param("filename", filename)
        nids.chksum_ctl([('0.0.0.0/0', False)])
        if port is None:
            nids.param("pcap_filter", "{}".format(self.protocol))
        else:
            nids.param("pcap_filter",
                       "{} port {}".format(self.protocol, self.port))
Esempio n. 17
0
def main():
    if len(sys.argv) == 2:
        nids.param("filename", sys.argv[1])

    nids.param("device", "all")
    nids.param("tcp_workarounds", True)
    nids.param("pcap_timeout", 128)
    nids.param("scan_num_hosts", 0)  # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming

    nids.init()

    tcpCapturer = TCPPacketCapturer()

    try:
        nids.run()
    except nids.error, e:
        print "[-] Error: %s" % (e)
Esempio n. 18
0
def main():
    if len(sys.argv) == 2:
        nids.param("filename", sys.argv[1])

    nids.param("device", "all")
    nids.param("tcp_workarounds", True)
    nids.param("pcap_timeout", 128)
    nids.param("scan_num_hosts",0)  # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming

    nids.init()

    tcpCapturer = TCPPacketCapturer()

    try:
        nids.run()
    except nids.error, e:
        print "[-] Error: %s" % (e)
Esempio n. 19
0
def main():

    # parse args
    argparser = argparse.ArgumentParser()
    argparser.add_argument('PCAP', help='Path to the .pcap file to parse')
    argparser.add_argument('-H', metavar='HOST', default='127.0.0.1', help='Address to listen on (DEFAULT: 127.0.0.1)')
    argparser.add_argument('-p', metavar='PORT', type=int, default=3128, help='Port to listen on (DEFAULT: 3128)')
    argparser.add_argument('-v', action='append_const', const=1, default=[], help='Increase the verbosity level')
    args = argparser.parse_args()

    HOST, PORT = args.H, args.p
    verbosity = len(args.v)

    # setup logger
    if verbosity == 0:
        log_level = logging.ERROR
    elif verbosity == 1:
        log_level = logging.INFO
    else:
        log_level = logging.DEBUG
    logging.basicConfig(format='%(levelname)s:%(message)s', level=log_level)

    # setup the reassembler            
    nids.param("scan_num_hosts", 0) # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksum verification: jsunpack says it may cause missed traffic
    nids.param("filename", args.PCAP)
    nids.init()
    nids.register_tcp(reassembleTcpStream)
    logging.info("Processing TCP streams...")
    nids.run()

    # process the open streams, which are not processed by pynids
    logging.info("Processing open streams...")
    for c, stream in openstreams.items():
        processTcpStream(stream)

    # run proxy server
    server = ProxyServer( (HOST,PORT), ProxyRequestHandler)
    server.allow_reuse_address = True
    try:
	logging.info("Proxy listening on %s:%d" % (HOST,PORT))
        server.serve_forever()
    except KeyboardInterrupt:
        return 0
Esempio n. 20
0
    def run(self, config):
        self.config = config
        self.config.output = open(self.config.output_file, 'a')
        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        nids.param('scan_num_hosts', 0)  # disable portscan detection
        if self.config.filename:
            nids.param('filename', self.config.filename)
        else:
            nids.param('filename', '-')
        nids.init()

        self.stream_handler = StreamHandler(self.config)
        nids.register_tcp(self.stream_handler.handle)

        try:
            nids.run()
        except nids.error, e:
            print >> sys.stderr, 'nids/pcap error:', e
            sys.exit(-1)
Esempio n. 21
0
def process_pcap(filename, protocols=[], dports=[]):
    global streams_, dports_
    streams_ = []
    dports_ = dports

    nids.param("scan_num_hosts", 0)         # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming
    nids.param("filename", filename)        # specify pcap file to parse
    nids.init()

    if not protocols or TCP in protocols:
        nids.register_tcp(handleTcpStream)

    # 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
Esempio n. 22
0
def extract(pcap_file):
    global ip_to_domain
    global ips
    ips = {}
    ip_to_domain = {}

    nids.param("tcp_workarounds", 1)
    nids.param("scan_num_hosts", 0)  # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
    nids.param("filename", pcap_file)
    nids.init()

    nids.register_tcp(handle_tcp_stream)
    nids.register_udp(udp_callback)

    try:
        nids.run()
    except Exception, e:
        print "Exception ", pcap_file + " ", e
        return
Esempio n. 23
0
def extract(pcap_file):
    global ip_to_domain
    global ips
    ips = {}
    ip_to_domain = {}

    nids.param("tcp_workarounds", 1)
    nids.param("scan_num_hosts", 0)          # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
    nids.param("filename", pcap_file)
    nids.init()

    nids.register_tcp(handle_tcp_stream)
    nids.register_udp(udp_callback)

    try:
        nids.run()
    except Exception, e:
        print "Exception ", pcap_file + " ", e
        return
Esempio n. 24
0
def extract_flows(pcap_file):
    global ts, requestdata, responsedata, requestcounter, http_req
    ts, requestdata, responsedata, requestcounter, http_req = \
        dict([]), dict([]), dict([]), dict([]), dict([])
    
    nids.param("tcp_workarounds", 1)
    nids.param("pcap_filter", "tcp")        # bpf restrict to TCP only, note
    nids.param("scan_num_hosts", 0)         # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming

    nids.param("filename", pcap_file)
    nids.init()
    nids.register_tcp(handle_tcp_stream)
    # print "pid", os.getpid()

    if DEBUG: print "Reading from pcap file:", pcap_file

    try:
        nids.run()
    except nids.error, e:
        print "nids/pcap error: ", pcap_file + " ",  e
Esempio n. 25
0
    def run(self, config):
        self.config = config
        self.stream_handler = StreamHandler(self.config)

        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        nids.param('scan_num_hosts', 0)  # disable portscan detection

        if self.config.filename:
            nids.param('filename', self.config.filename)
        else:
            nids.param('device', self.config.interface)

        nids.init()
        nids.register_tcp(self.stream_handler.tcp_callback)
        #nids.register_udp(self.stream_handler.udp_callback)

        try:
            nids.run()
        except nids.error, e:
            print >> sys.stderr, 'nids/pcap error:', e
            print >> sys.stderr, 'Error in %s' % self.filename
            traceback.print_exc(file=sys.stderr)
    def run(self, config):
        self.config = config
        self.stream_handler = StreamHandler(self.config)

        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
        nids.param('scan_num_hosts', 0)  # disable portscan detection

        if self.config.filename:
            nids.param('filename', self.config.filename)
        else:
            nids.param('device', self.config.interface)

        nids.init()
        nids.register_tcp(self.stream_handler.tcp_callback)
        #nids.register_udp(self.stream_handler.udp_callback)

        try:
            nids.run()
        except nids.error, e:
            print >> sys.stderr, 'nids/pcap error:', e
            print >> sys.stderr, 'Error in %s' % self.filename
            traceback.print_exc(file=sys.stderr)
Esempio n. 27
0
def main():
    logging.basicConfig(filename="mspCapturer.log",level=logging.DEBUG)
    if (len(sys.argv) != 2):
        logging.error( 'Invalid arguments. Usage: main.py <monitor port(s)>\n monitor ports should be specified in a comma seperated list ')
        sys.exit(1)
    logging.info( 'Set up Reassembler')
    nids.param("scan_num_hosts",0)  # disable portscan detection
    nids.chksum_ctl([('0.0.0.0/0', False)]) # disable checksumming
    nids.param("pcap_timeout", 128)
    nids.param("tcp_workarounds", True)
    nids.param("sk_buff_size", 256) #default 168
    nids.param("n_tcp_streams", 2048) #default 1024
    nids.param("device", "all")

    nids.init()

    assm = Reassembler(ports=sys.argv[1])
    try:
        nids.run()
    except KeyboardInterrupt:
        logging.error( "Reassembler Terminated: Quitting")
        sys.exit(2)
Esempio n. 28
0
 def __init__(
     self,
     protocol_uri,
     protocol_opts,
     pcap_filepath,
     output_dir,
     log_level,
     log_to_stdout,
     stats_file=None,
     dst=None,
     dest_port=None,
     src=None,
     src_port=None,
     start_date=None,
 ):
     self._log_to_stdout = log_to_stdout
     self._log_level = log_level
     self._proto_uri = protocol_uri
     self._proto_opts = protocol_opts
     self._dest_port = dest_port
     self._src_port = src_port
     self._src = src
     self._dst = dst
     self.output_dir = output_dir
     self._pcap_filepath = pcap_filepath
     self._start_date = start_date
     nids.param("scan_num_hosts", 0)  # disable portscan detection
     nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming
     nids.param("filename", pcap_filepath)
     self.stream_parsers = {}
     self.stats = {}
     if stats_file is None:
         now = datetime.utcnow()
         formatted_time = now.strftime("%Y-%m-%d--%H-%M-%S")
         self.stats_file_path = os.path.join(
             self.output_dir, "stats_{}.txt".format(formatted_time))
     else:
         self.stats_file_path = stats_file
Esempio n. 29
0
def sniff():
    if not _initialized:
        raise NameError('Module vars were not initialized.')

    nids.param('device', _device)
    nids.param('multiproc', 1)
    nids.param('scan_num_hosts', 0)
    nids.chksum_ctl([('0.0.0.0/0', False)])

    nids.init()
    nids.register_tcp(_handle_tcp_stream)
    nids.register_udp(_handle_udp_stream)
    nids.register_ip(_handle_ip_packets)

    arp_sniff = Process(target=scapy_sniff, kwargs=dict(store=0,
            iface=_device, prn=_parse_arp))
    dns_lookups = Process(target=_handle_dns_lookup)
    traf_dict = Process(target=_handle_new_traf)
    arp_sniff.start()
    dns_lookups.start()
    traf_dict.start()

    nids.run()
Esempio n. 30
0
                return

            nids.param("scan_num_hosts", 0)
            nids.param("filename", options['filename'])
            if options['bpf'] is not None:
                nids.param("pcap_filter", options['bpf'])

            try:
                nids.init()
            except Exception, e:
                self.complete = True
                chop.prnt("Error initting: ", e)
                return

            nids.chksum_ctl([
                ('0.0.0.0/0', False),
            ])
            nids.register_tcp(handleTcpStreams)
            nids.register_udp(handleUdpDatagrams)
            nids.register_ip(handleIpPackets)

            while (
                    not self.stopped
            ):  #This overall while prevents exceptions from halting the long running reading
                try:
                    if options[
                            'longrun']:  #long running don't stop until the proces is killed externally
                        while not self.stopped:
                            if not nids.next():
                                if self.abort:  #exit if sigabrt if no other data
                                    break
Esempio n. 31
0
    def __init__(self,
                 pcap_file=None,
                 device=None,
                 bpf_filter="tcp",
                 dst_tcp_port_filter=None,
                 dst_tcp_ip_filter=None,
                 src_tcp_port_filter=None,
                 src_tcp_ip_filter=None,
                 udp_port_filter=None,
                 udp_ip_filter=None,
                 data_level=1,
                 data_stream_direct=2,
                 std_output_enable=1,
                 file_output_path=None,
                 protocol_parse_conf=None,
                 is_handle_tcp=1,
                 is_handle_udp=1,
                 is_handle_ip=1,
                 sqlite3_output_enable=1,
                 sqlite3_output_path=None,
                 sqlite3_output_schema=None,
                 sqlite3_renew=False):
        """

        Args:
            pcap_file:
            device:
            bpf_filter:
            dst_port_filter:
            dst_ip_filter:
            src_port_filter:
            src_ip_filter:
            data_level:
            data_stream_direct:
            std_output_enable:
            file_tcpsession_path:
            protocol_parse_conf:
        """
        self.is_handle_tcp = is_handle_tcp
        self.is_handle_udp = is_handle_udp
        self.is_handle_ip = is_handle_ip

        self.bpf_filter = bpf_filter
        self.dst_tcp_port_filter = dst_tcp_port_filter
        self.dst_tcp_ip_filter = dst_tcp_ip_filter
        self.src_tcp_port_filter = src_tcp_port_filter
        self.src_tcp_ip_filter = src_tcp_ip_filter
        self.udp_ip_filter = udp_ip_filter
        self.udp_port_filter = udp_port_filter

        self.device = device
        self.pcap_file = pcap_file

        if pcap_file:
            nids.param("filename", pcap_file)
        elif device:
            nids.param("device", device)

        if bpf_filter:
            nids.param("pcap_filter",
                       bpf_filter)  ## bpf restrict to TCP only, note

        self.data_level = data_level
        self.data_stream_direct = data_stream_direct

        self.std_output_enable = std_output_enable

        self.file_output_path = file_output_path

        self.protocol_parse_conf = protocol_parse_conf

        nids.param("scan_num_hosts", 0)  # disable portscan detection

        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming

        nids.param("pcap_timeout", 64)
        nids.param("multiproc", 1)
        nids.param("tcp_workarounds", 1)

        # sqlite3 conf which store ip_handle statistic info
        self.sqlite3_output_enable = sqlite3_output_enable
        self.sqlite3_output_path = sqlite3_output_path
        self.sqlite3_output_schema = sqlite3_output_schema
        self.sqlite3_renew = sqlite3_renew

        # local ip
        if self.is_handle_ip:
            self.local_ip = networktools.get_local_ip(self.device)
        # var
        self.tcp_file_fh = None
        self.udp_file_fh = None
        self.ip_file_fh = None

        self.app_proto_fhs = {}

        if self.file_output_path:
            # 设置文件输出

            if os.path.exists(self.file_output_path) and os.path.isdir(
                    self.file_output_path):
                # delete old data

                mills.rm_dir(self.file_output_path)

            os.mkdir(self.file_output_path)

            tcp_file_path = mills.path(self.file_output_path, "tcp.txt")
            self.tcp_file_fh = codecs.open(tcp_file_path,
                                           mode='wb',
                                           encoding='utf-8',
                                           errors='ignore')

            udp_file_path = mills.path(self.file_output_path, "udp.txt")
            self.udp_file_fh = codecs.open(udp_file_path,
                                           mode='wb',
                                           encoding='utf-8',
                                           errors='ignore')
            ip_file_path = mills.path(self.file_output_path, "ip.txt")
            self.ip_file_fh = codecs.open(ip_file_path,
                                          mode='wb',
                                          encoding='utf-8',
                                          errors='ignore')

            port_list = set()
            proto_list = set()
            for port_filter in [
                    self.dst_tcp_port_filter, self.src_tcp_port_filter,
                    self.udp_port_filter
            ]:
                for port in port_filter:
                    port_list.add(port)

            for port in port_list:
                protocol = self.which_protocol_parse(port)

                if protocol:
                    proto_list.add(protocol)

            for protocol in proto_list:
                protocol_file_path = mills.path(self.file_output_path,
                                                "%s.txt" % protocol)
                protocol_file_fh = codecs.open(protocol_file_path,
                                               mode='wb',
                                               encoding='utf-8',
                                               errors='ignore')
                self.app_proto_fhs[protocol] = protocol_file_fh
Esempio n. 32
0
            if options.filename is "":
                chop.prnt("Empty Filename")
                self.complete = True
                return

            nids.param("scan_num_hosts",0)
            nids.param("filename",options.filename)

            try:
                nids.init()
            except Exception, e:
                self.complete = True
                chop.prnt("Error initting: ", e)
                return

            nids.chksum_ctl([('0.0.0.0/0',False),])
            nids.register_tcp(handleTcpStreams)
            nids.register_udp(handleUdpDatagrams)

            while(True): #This overall while prevents exceptions from halting the long running reading
                if self.stopped:
                    break
                try:
                    if options.longrun: #long running don't stop until the proces is killed externally
                        while not self.stopped:
                            if not nids.next():
                                time.sleep(.001)
                    else:
                        while not self.stopped and nids.next(): 
                            pass
                        self.stopped = True #Force it to true and exit
def TcpHandler(tcp):
	if tcp.nids_state == nids.NIDS_JUST_EST:
		tcp.server.collect = 1
		tcp.client.collect = 1
	elif tcp.nids_state == nids.NIDS_DATA:
		tcp.discard(0)  # keep data
	elif tcp.nids_state in [nids.NIDS_CLOSE, nids.NIDS_TIMEOUT, nids.NIDS_RESET]:
		((src, sport), (dst, dport)) = tcp.addr
		print "==========================(%s:%d <--> %s:%d)==========================" % (src, sport, dst, dport)
		print tcp.server.data[:tcp.server.count]
		print tcp.client.data[:tcp.client.count]

if len(sys.argv) < 2:
	print("usage : ./13_pynids_sample.py pcap_file")
	print("")
	exit(1)

# set libnids parameters
#nids.param("pcap_filter", "tcp")
nids.param("scan_num_hosts", 0)
nids.chksum_ctl([('0.0.0.0/0', False), ('::', False)])
nids.param("filename", sys.argv[1])
print "pcap_file=%s" % sys.argv[1]

nids.init()

nids.register_tcp(TcpHandler)

nids.run()

Esempio n. 34
0
                "src_port": sport,
                "dst_ip": dst,
                "dst_port": dport,
                "time": start_time[tcp.addr],
                "duration": (ts - start_time[tcp.addr]),
                "contains_flag": contains_flag[tcp.addr],
                "starred": 0,
                "flow": current_data
                }

        flows_to_import.append(flow)
        del data_flow[tcp.addr]


nids.param("pcap_filter", "tcp")  # restrict to TCP only
nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming

if len(sys.argv) == 2:
    filename = sys.argv[1]
    if "./" in filename:
        filename = filename[2:]
    print("importing pcaps from " + filename)
    nids.param("filename", filename)
else:
    print("pcap file required")
    exit()

nids.init()
nids.register_tcp(handleTcpStream)
nids.run()
Esempio n. 35
0
    def __init__(self,
                 pcap_file=None,
                 device=None,
                 bpf_filter="tcp",
                 dst_port_filter=None,
                 dst_ip_filter=None,
                 data_level=1,
                 data_stream_direct=2,
                 std_output_enable=1,
                 file_tcpsession_path=None,
                 protocol_parse_conf=None):
        """

        :param pcap_file:
        :param device:
        :param bpf_filter:
        :param dst_port_filter:
        :param dst_ip_filter:
        :param data_level:
        :param data_stream_direct:
        :param is_human_print:
        :param file_output_file:
        """
        self.dst_port_filter = dst_port_filter
        self.dst_ip_filter = dst_ip_filter
        self.device = device
        self.pcap_file = pcap_file

        if pcap_file:
            nids.param("filename", pcap_file)
        elif device:
            nids.param("device", device)

        if bpf_filter:
            nids.param("pcap_filter",
                       bpf_filter)  ## bpf restrict to TCP only, note

        self.data_level = data_level
        self.data_stream_direct = data_stream_direct
        self.std_output_enable = std_output_enable
        self.file_tcpsession_path = file_tcpsession_path
        self.protocol_parse_conf = protocol_parse_conf

        nids.param("scan_num_hosts", 0)  # disable portscan detection

        nids.chksum_ctl([('0.0.0.0/0', False)])  # disable checksumming

        nids.param("pcap_timeout", 64)
        nids.param("multiproc", 1)
        nids.param("tcp_workarounds", 1)

        self.file_hd_tcpsession = None
        self.file_hd_tcpsession_parse = None

        if self.file_tcpsession_path:
            self.file_hd_tcpsession = codecs.open(self.file_tcpsession_path,
                                                  mode='wb',
                                                  encoding='utf-8',
                                                  errors='ignore')
            if self.data_stream_direct == 2:
                file_tcpsession_path_parse = "%s_parse" % self.file_tcpsession_path

                self.file_hd_tcpsession_parse = codecs.open(
                    file_tcpsession_path_parse,
                    mode='wb',
                    encoding='utf-8',
                    errors='ignore')
Esempio n. 36
0
class ChopCore(Thread):
    def __init__(self, options, module_list, chp, chophelper):
        Thread.__init__(self)
        self.options = options
        self.module_list = module_list
        self.chophelper = chophelper
        self.stopped = False
        self.complete = False
        self.abort = False

        global chop
        chop = chp

    def stop(self):
        self.complete = True
        self.stopped = True

    def iscomplete(self):
        return self.complete

    def getptime(self):
        global ptimestamp
        return ptimestamp

    def getmeta(self):
        global metadata
        return metadata

    def prep_modules(self):
        self.chophelper.set_core(self)
        modules = self.module_list
        for module in modules:
            code = module.code
            code.chop = self.chophelper.setup_module(code.moduleName)

    def run(self):
        global chop
        #Initialize modules to be run
        options = self.options
        modules = self.module_list  #module_list
        module_options = {}

        chop.prettyprnt("RED", "Initializing Modules ...")

        for module in modules:
            name = module.name
            arguments = module.arguments  #shlex.split(module[1])
            code = module.code  #module[0]
            #Create module_data for all modules
            module.module_data = {'args': arguments}
            module.streaminfo = {}

            chop.prettyprnt("CYAN", "\tInitializing module '" + name + "'")
            try:
                module_options = code.init(module.module_data)
            except Exception, e:
                chop.prnt("Error Initializing Module", code.moduleName + ":",
                          e)
                self.complete = True
                return

            if 'error' in module_options:
                chop.prettyprnt(
                    "GREEN", "\t\t%s init failure: %s" %
                    (code.moduleName, module_options['error']))
                continue

            if module.legacy:
                if module_options['proto'] == 'tcp':
                    tcp_modules.append(module)
                    all_modules.append(module)
                    module.streaminfo['tcp'] = {}
                elif module_options['proto'] == 'ip':
                    ip_modules.append(module)
                    all_modules.append(module)
                    module.streaminfo['ip'] = {}
                elif module_options['proto'] == 'udp':
                    udp_modules.append(module)
                    all_modules.append(module)
                    module.streaminfo['udp'] = {}
                else:
                    chop.prnt("Undefined Module Type\n")
                    self.complete = True
                    return
            else:
                all_modules.append(module)
                #Proto is an array of dictionaries
                if not isinstance(module_options['proto'], list):  #Malformed
                    chop.prnt("%s has malformed proto list" %
                              module.code.moduleName)
                    self.complete = True
                    return

                for proto in module_options['proto']:
                    #Right now (4.0) each dictionary only has one key
                    #This might change in the future but should be easy
                    #since it's already a separate dictionary
                    if type(proto) is not dict:
                        chop.prnt("%s has malformed proto list" %
                                  module.code.moduleName)
                        self.complete = True
                        return

                    for input in proto.keys():
                        if input not in module.inputs:
                            module.inputs[input] = []

                        if proto[input] != '':
                            module.inputs[input].append(proto[input])
                            module.outputs.append(proto[input])

                        #Initialize the streaminfo array by type
                        if input != 'any' and input != 'ip':
                            module.streaminfo[input] = {}

                        if input == 'tcp':
                            tcp_modules.append(module)
                        elif input == 'udp':
                            udp_modules.append(module)
                        elif input == 'ip':
                            ip_modules.append(module)
                        elif input == 'any':  #Special input that catches all non-core types
                            #Initialize the streaminfo for all parents of the 'any' module
                            if not len(module.parents):
                                chop.prettyprnt(
                                    "GREEN",
                                    "WARNING: No Parent for %s to provide data"
                                    % (module.code.moduleName))
                            else:
                                for parent in module.parents:
                                    for output in parent.outputs:
                                        module.streaminfo[output] = {}
                        else:  # non-core types, e.g., 'http' or 'dns'
                            if len(module.parents
                                   ):  #Make sure parents give it what it wants
                                for parent in module.parents:
                                    if input not in parent.outputs:
                                        chop.prettyprnt(
                                            "GREEN",
                                            "WARNING: Parent to %s not providing %s data"
                                            % (module.code.moduleName, input))
                            else:
                                chop.prettyprnt(
                                    "GREEN",
                                    "WARNING: No Parent for %s providing %s data"
                                    % (module.code.moduleName, input))

        if not all_modules:
            chop.prnt("No modules")
            self.complete = True
            return

        chop.prettyprnt("RED", "Running Modules ...")

        #Actually run the modules
        if options['interface']:
            nids.param("scan_num_hosts", 0)
            nids.param("device", options['interface'])
            if options['bpf'] is not None:
                nids.param("pcap_filter", options['bpf'])

            try:
                nids.init()
            except Exception, e:
                chop.prnt("Error initting on interface: ", e)
                self.complete = True
                return

            nids.chksum_ctl([
                ('0.0.0.0/0', False),
            ])
            nids.register_tcp(handleTcpStreams)
            nids.register_udp(handleUdpDatagrams)
            nids.register_ip(handleIpPackets)

            while (
                    True
            ):  #This overall while prevents exceptions from halting the processing of packets
                if self.stopped:
                    break
                try:
                    while not self.stopped:
                        nids.next()
                        time.sleep(.001)  #XXX is this enough or too much?
                except Exception, e:
                    chop.prnt("Error processing packets", e)
Esempio n. 37
0
class ChopCore(Thread):
    def __init__(self,options, module_list, chp, chophelper):
        Thread.__init__(self)
        self.options = options
        self.module_list = module_list
        self.chophelper = chophelper 
        self.stopped = False
        self.complete = False

        global chop
        chop = chp

    def stop(self):
        self.complete = True
        self.stopped = True

    def iscomplete(self):
        return self.complete

    def getptime(self):
        global ptimestamp
        return ptimestamp

    def getmeta(self):
        global metadata
        return metadata

    def prep_modules(self):
        self.chophelper.set_core(self)
        modules = self.module_list
        for module in modules:
            module = module[0]
            module.chop = self.chophelper.setup_module(module.moduleName)

    def run(self):
        global chop
        #Initialize modules to be run
        options = self.options
        modules = self.module_list#module_list
        module_options = {}

        chop.prettyprnt("RED", "Initializing Modules ...")

        for module in modules:
            name = module[2]
            arguments = shlex.split(module[1])
            module = module[0]
            #Create module_data for all modules
            module.module_data = {'args':arguments}
            module.streaminfo = {}

            chop.prettyprnt("CYAN", "\tInitializing module '" + name + "'")
            try:
                module_options = module.init(module.module_data)
            except Exception, e:
                chop.prnt("Error Initializing Module", module.moduleName + ":", e)
                self.complete = True
                return

            if 'error' in module_options:
                chop.prettyprnt("GREEN", "\t\t%s init failure: %s" % (module.moduleName, module_options['error']))
                continue

            if module_options['proto'] == 'tcp' :
                tcp_modules.append(module)
                all_modules.append(module)
            elif module_options['proto'] == 'ip' :
                ip_modules.append(module)
                all_modules.append(module)
            elif module_options['proto'] == 'udp' :
                udp_modules.append(module)
                all_modules.append(module)
            else:
                chop.prnt("Undefined Module Type\n")
                self.complete = True
                return

        if not all_modules:
            chop.prnt("No modules")
            self.complete = True
            return

        chop.prettyprnt("RED", "Running Modules ...")

        #Actually run the modules
        if options['interface']:
            nids.param("scan_num_hosts",0)
            nids.param("device",options['interface'])
            if options['bpf'] is not None:
                nids.param("pcap_filter", options['bpf'])

            try:
                nids.init()
            except Exception, e:
                chop.prnt("Error initting: ", e) 
                self.complete = True
                return

            nids.chksum_ctl([('0.0.0.0/0',False),])
            nids.register_tcp(handleTcpStreams)
            nids.register_udp(handleUdpDatagrams)

            while(True): #This overall while prevents exceptions from halting the processing of packets
                if self.stopped:
                    break
                try:
                    while not self.stopped:
                        nids.next()
                        time.sleep(.001) #XXX is this enough or too much?
                except Exception, e:
                    chop.prnt("Error processing packets", e)
Esempio n. 38
0
                self.complete = True
                return

            nids.param("scan_num_hosts", 0)
            nids.param("filename", options["filename"])
            if options["bpf"] is not None:
                nids.param("pcap_filter", options["bpf"])

            try:
                nids.init()
            except Exception, e:
                self.complete = True
                chop.prnt("Error initting: ", e)
                return

            nids.chksum_ctl([("0.0.0.0/0", False)])
            nids.register_tcp(handleTcpStreams)
            nids.register_udp(handleUdpDatagrams)

            while True:  # This overall while prevents exceptions from halting the long running reading
                if self.stopped:
                    break
                try:
                    if options["longrun"]:  # long running don't stop until the proces is killed externally
                        while not self.stopped:
                            if not nids.next():
                                time.sleep(0.001)
                    else:
                        while not self.stopped and nids.next():
                            pass
                        self.stopped = True  # Force it to true and exit