示例#1
0
def main(arg1):
    global count
    global responses
    global responses_headers
    global response
    global response_header
    
    

    #nids.param("pcap_filter", "tcp")       # bpf restrict to TCP only, note
                                            # libnids caution about fragments

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

    #if len(sys.argv) == 2:                  # read a pcap file?
    nids.param("filename", arg1)
  

    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
示例#2
0
def main(arg1):
    global count
    global responses
    global responses_headers
    global response
    global response_header
    #global openstreams
    #pcaps_file = os.listdir(arg1)
    #for pcap_file in pcaps_file:
    #print pcap_file
    #responses_headers = []
    #openstreams = {}
    #responses = []

    #print "Atleast entered here"
    #nids.param("pcap_filter", "tcp")       # bpf restrict to TCP only, note
    # libnids caution about fragments

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

    #if len(sys.argv) == 2:                  # read a pcap file?
    nids.param("filename", arg1)

    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
示例#3
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
示例#4
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
示例#5
0
文件: sniffer.py 项目: amotl/sanchez
    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
示例#6
0
    def run(self):
        """

        :return:
        """

        nids.init()

        if self.is_handle_tcp:
            nids.register_tcp(self.__handleTCPStream)

        if self.is_handle_udp:
            nids.register_udp(self.__handleUDPDatagram)

        if self.is_handle_ip:
            nids.register_ip(self.__handleIPPackets)
        # 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 as e:
            logging.error("[NIDS_RUN_Error]: %r" % e)
        except (KeyboardInterrupt, SystemExit) as e:
            logging.error("[System_Exit]: %r" % e)
        except Exception as e:
            logging.error("[NIDS RUN Exception]: %r %s" %
                          (e, traceback.format_exc()))
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()
示例#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
示例#9
0
    def run(self):
        nids.init()
        nids.register_tcp(self.handle_tcp)

        try:
            nids.run()
            print("DONE")
            self.done = True
        except nids.error, e:
            print "[-] Error: %s" % (e)
def main():
    # Packet through Interface OR PCAP check.
    if pcap_path is not '':
        nids.param('filename', pcap_path)
    else:
        nids.param('device', interface)

    nids.init()
    nids.register_tcp(tcpcallback)

    nids.run()
示例#11
0
def main():
    if len(sys.argv) == 2:
        nids.param("filename", sys.argv[1])

    nids.init()
    nids.register_tcp(tcpcallback)

    try:
        nids.run()
    except nids.error, e:
        print "[-] Error: %s" % (e)
示例#12
0
def main():
    parser = argparse.ArgumentParser(description='minips.py - A minimal IPS', version='0.1',
            epilog='EXAMPLE: %(prog)s -p test.pcap -r \'shellcode\' \n')
    inputparser = parser.add_mutually_exclusive_group(required=True)
    inputparser.add_argument('-d', '--device', action='store', dest='device',
            help='network device to collect packets from')
    inputparser.add_argument('-p', '--pcap', action='store', dest='pcap',
            help='pcap file to read packets from')
    parser.add_argument('-r', '--regex', action='store', dest='regex', required=True,
            help='regex to match over network data')
    parser.add_argument('-i', '--igncase', action='store_true', dest='igncase', default=False,
            help='perform case insensitive regex match')
    parser.add_argument('-m', '--multiline', action='store_true', dest='multiline', default=False,
            help='perform multiline regex match')
    parser.add_argument('-k', '--killtcp', action='store_true', dest='killtcp', default=False,
            help='terminate matching tcp connections')
    parser.add_argument('-b', '--dispbytes', action='store', dest='dispbytes', required=False,
            help='max bytes to display')

    args = parser.parse_args()

    if args.device:
        globs['device'] = args.device
        nids.param('device', globs['device'])

    if args.pcap:
        globs['pcap'] = args.pcap
        nids.param('filename', globs['pcap'])

    if args.killtcp:
        globs['killtcp'] = True

    if args.igncase:
        globs['regexflags'] |= re.IGNORECASE

    if args.multiline:
        globs['regexflags'] |= re.MULTILINE
        globs['regexflags'] |= re.DOTALL

    if args.regex:
        globs['regexstr'] = args.regex
        globs['regexobj'] = re.compile(globs['regexstr'], globs['regexflags'])

    if args.dispbytes:
        globs['dispbytes'] = int(args.dispbytes)

    nids.init()
    nids.register_tcp(tcpcallback)
    nids.register_udp(udpcallback)

    try:
        nids.run()
    except nids.error, e:
        print "[-] Error: %s" % (e)
示例#13
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()
示例#14
0
    def run(self):
        files_dir = os.path.join(self.output_dir, "files")
        if not os.path.exists(files_dir):
            os.mkdir(files_dir)

        nids.init()
        nids.register_tcp(self.handle_tcp_stream_wrapper)
        try:
            nids.run()
            self.finish()
            self.save_stats()
        except nids.error, e:
            print >> sys.stderr, "nids/pcap error:", e
示例#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)
示例#16
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
示例#17
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)
示例#18
0
    def start(self):
        if self._filter:
            nids.param("pcap_filter", self._filter)
        if self._pcapfile:
            nids.param("filename", self._pcapfile)
        elif self._device:
            nids.param("device", self._device)

        # Initializing libnids
        nids.init()

        # Registering the handler
        nids.register_tcp(lambda tcp: self._handle_tcp_stream(tcp))

        # Running nids
        nids.run()
示例#19
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)
示例#20
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)
示例#21
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)
示例#22
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
示例#23
0
文件: npeid.py 项目: jbabbin/npeid
def main():
	global extract
	extract = False
	pcap = False
	if "-e" in sys.argv:
		extract = True
	nids.param("scan_num_hosts", 0)
	for arg in sys.argv[1:]:
		if arg.endswith('.pcap'):
			pcap = True
			nids.param("filename", arg)
	if not pcap:
		nids.param("device", "eth0")
	nids.init()
	nids.register_tcp(handleTcpStream)
	try:
		nids.run()
	except nids.error, e:
		print "nids/pcap error:", e
示例#24
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)
示例#25
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
示例#26
0
文件: parse.py 项目: amwelch/ifpy
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
示例#27
0
文件: parse.py 项目: amwelch/ifpy
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
示例#28
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
    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)
示例#30
0
def main():
    global count
    global responses
    #nids.param("pcap_filter", "tcp")       # bpf restrict to TCP only, note
                                            # libnids caution about fragments

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

    #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
示例#31
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)
示例#32
0
    def run(self):
        """

        :return:
        """

        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 as e:
            logging.error("[NIDS_RUN_Error]: %r" % e)
        except (KeyboardInterrupt, SystemExit) as e:
            logging.error("[System_Exit]: %r" % e)
        except Exception as e:
            logging.error("[NIDS RUN Exception]: %r" % e)
示例#33
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)
示例#34
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()
 def parse_pcap(self,options,file):
     try:
         import nids
     except:
         options.log.error("failed to import LibNIDS are you sure it's installed")
         sys.exit(-1)
     
     self.http_stream_list = []
     self.stream_hash = {} 
     self.stream_count = 0
     self.filename = os.path.basename(file) 
     self.log = options.log
     if options.pcap_bpf != None:
         nids.param("pcap_filter", options.pcap_bpf)
         
     nids.param("scan_num_hosts", 0)
     nids.param("filename", file)
     nids.init()
     nids.register_tcp(self.handleTcpStream)
     try:
         nids.run()
     except nids.error, e:
         options.log.error("nids/pcap error:" % (e))
示例#36
0
    def parse_pcap(self, options, file):
        try:
            import nids
        except:
            options.log.error(
                "failed to import LibNIDS are you sure it's installed")
            sys.exit(-1)

        self.http_stream_list = []
        self.stream_hash = {}
        self.stream_count = 0
        self.filename = os.path.basename(file)
        self.log = options.log
        if options.pcap_bpf != None:
            nids.param("pcap_filter", options.pcap_bpf)

        nids.param("scan_num_hosts", 0)
        nids.param("filename", file)
        nids.init()
        nids.register_tcp(self.handleTcpStream)
        try:
            nids.run()
        except nids.error, e:
            options.log.error("nids/pcap error:" % (e))
示例#37
0
def main():
    parser = argparse.ArgumentParser(
        description='minips.py - A minimal IPS',
        version='0.1',
        epilog='EXAMPLE: %(prog)s -p test.pcap -r \'shellcode\' \n')
    inputparser = parser.add_mutually_exclusive_group(required=True)
    inputparser.add_argument('-d',
                             '--device',
                             action='store',
                             dest='device',
                             help='network device to collect packets from')
    inputparser.add_argument('-p',
                             '--pcap',
                             action='store',
                             dest='pcap',
                             help='pcap file to read packets from')
    parser.add_argument('-r',
                        '--regex',
                        action='store',
                        dest='regex',
                        required=True,
                        help='regex to match over network data')
    parser.add_argument('-i',
                        '--igncase',
                        action='store_true',
                        dest='igncase',
                        default=False,
                        help='perform case insensitive regex match')
    parser.add_argument('-m',
                        '--multiline',
                        action='store_true',
                        dest='multiline',
                        default=False,
                        help='perform multiline regex match')
    parser.add_argument('-k',
                        '--killtcp',
                        action='store_true',
                        dest='killtcp',
                        default=False,
                        help='terminate matching tcp connections')
    parser.add_argument('-b',
                        '--dispbytes',
                        action='store',
                        dest='dispbytes',
                        required=False,
                        help='max bytes to display')

    args = parser.parse_args()

    if args.device:
        globs['device'] = args.device
        nids.param('device', globs['device'])

    if args.pcap:
        globs['pcap'] = args.pcap
        nids.param('filename', globs['pcap'])

    if args.killtcp:
        globs['killtcp'] = True

    if args.igncase:
        globs['regexflags'] |= re.IGNORECASE

    if args.multiline:
        globs['regexflags'] |= re.MULTILINE
        globs['regexflags'] |= re.DOTALL

    if args.regex:
        globs['regexstr'] = args.regex
        globs['regexobj'] = re.compile(globs['regexstr'], globs['regexflags'])

    if args.dispbytes:
        globs['dispbytes'] = int(args.dispbytes)

    nids.init()
    nids.register_tcp(tcpcallback)
    nids.register_udp(udpcallback)

    try:
        nids.run()
    except nids.error, e:
        print "[-] Error: %s" % (e)
示例#38
0
 def run(self):
     nids.run()
示例#39
0
                "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()

print("importing " + str(len(flows_to_import)) + " flows into mongodb!")
db.insertFlows(filename, flows_to_import)
db.setFileImported(filename)
示例#40
0
def main():
    from optparse import OptionParser
    parser = OptionParser()

    parser.add_option("-d",
                      "--device",
                      dest="device",
                      help="sniff on network device DEVICE",
                      metavar="DEVICE")
    parser.add_option("-f",
                      "--file",
                      dest="file",
                      help="use pcap logfile FILE",
                      metavar="FILE")
    parser.add_option("-l",
                      "--log",
                      dest="log",
                      action="store_true",
                      default=False,
                      help="create logs")
    parser.add_option("-p",
                      "--pid",
                      dest="pid",
                      help="attach to process PID",
                      metavar="PID")

    (options, args) = parser.parse_args()

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

    logfiles = {}

    sniff = Sniffer()
    sniff.starttime = datetime.now()

    def timestring():
        td = datetime.now() - sniff.starttime
        return "[% 8.3f]" % (td.seconds + td.microseconds / 1000000.0)

    def message_output_handler(message):
        if options.log:
            connection = message.source.connection

            if connection.session:
                if connection in logfiles:
                    logfile = logfiles[connection]
                else:
                    logname = "%s_%s.wlog" % (
                        connection.session.account,
                        datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))

                    print timestring(), 'Creating log file "%s"' % logname
                    logfile = log.Log(open(logname, "wb"))
                    logfile.write_header()

                    session = connection.session
                    sinfo = log.SessionInfo(session.game, session.version,
                                            session.locale,
                                            connection.client.address,
                                            connection.server.address,
                                            session.account)

                    logfile.write(sinfo)

                    logfiles[connection] = logfile

                if message.source is connection.client:
                    cls = messages.ClientMessage
                elif message.source is connection.server:
                    cls = messages.ServerMessage
                else:
                    cls = None

                if cls:
                    logfile.write(
                        cls(message.opcode, connection.client.address,
                            connection.server.address, message.data))
            else:
                # FIXME: This always discards the first message (SMSG_AUTH_CHALLENGE) because at that point,
                # the session is not yet known. We should cache this message and output it too.
                pass

        print timestring(), opcodes.names[message.opcode].ljust(55),

        if len(message.data) > 0:
            print "% 6d bytes" % len(message.data)
        else:
            print

    def session_output_handler(session):
        print timestring(), "New Session:", session

    sniff.message_handler = message_output_handler
    sniff.session_handler = session_output_handler

    if options.device:
        nids.param("device", options.device)
    if options.file:
        nids.param("filename", options.file)

    pid = None

    if options.pid is not None and options.pid.isdigit():
        pid = int(options.pid)
    elif options.pid == "auto":
        pid = findWowProcess()

    if pid:
        print timestring(), "Attaching to process", pid
        sniff.addProcess(pid)
    elif not options.file:
        print timestring(), "Warning: Not attaching to any process"

    nids.init()
    nids.register_tcp(sniff.tcp_handler)

    nids.run()
示例#41
0
文件: weave2.py 项目: HearthSim/weave
def main():
	from optparse import OptionParser
	parser = OptionParser()
	
	parser.add_option("-d", "--device", dest="device", help="sniff on network device DEVICE", metavar="DEVICE")
	parser.add_option("-f", "--file", dest="file", help="use pcap logfile FILE", metavar="FILE")
	parser.add_option("-l", "--log", dest="log", action="store_true", default=False, help="create logs")
	parser.add_option("-p", "--pid", dest="pid", help="attach to process PID", metavar="PID")
	
	(options, args) = parser.parse_args()
	
	nids.param("scan_num_hosts", 0) # Disable portscan detection
	
	logfiles = {}
	
	sniff = Sniffer()
	sniff.starttime = datetime.now()
	
	def timestring():
		td = datetime.now() - sniff.starttime
		return "[% 8.3f]" % (td.seconds + td.microseconds/1000000.0)
	
	def message_output_handler(message):
		if options.log:
			connection = message.source.connection
			
			if connection.session:
				if connection in logfiles:
					logfile = logfiles[connection]
				else:
					logname = "%s_%s.wlog" % (connection.session.account, datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
					
					print timestring(), 'Creating log file "%s"' % logname
					logfile = log.Log(open(logname, "wb"))
					logfile.write_header()
					
					session = connection.session
					sinfo = log.SessionInfo(session.game, session.version, session.locale, connection.client.address, connection.server.address, session.account)
					
					logfile.write(sinfo)
					
					logfiles[connection] = logfile
				
				if message.source is connection.client:
					cls = messages.ClientMessage
				elif message.source is connection.server:
					cls = messages.ServerMessage
				else:
					cls = None
				
				if cls:
					logfile.write(cls(message.opcode, connection.client.address, connection.server.address, message.data))
			else:
				# FIXME: This always discards the first message (SMSG_AUTH_CHALLENGE) because at that point,
				# the session is not yet known. We should cache this message and output it too.
				pass
			
		print timestring(), opcodes.names[message.opcode].ljust(55),
		
		if len(message.data) > 0:
			print "% 6d bytes" % len(message.data)
		else:
			print
	
	def session_output_handler(session):
		print timestring(), "New Session:", session
	
	sniff.message_handler = message_output_handler
	sniff.session_handler = session_output_handler
	
	if options.device:
		nids.param("device", options.device)
	if options.file:
		nids.param("filename", options.file)
	
	pid = None
	
	if options.pid is not None and options.pid.isdigit():
		pid = int(options.pid)
	elif options.pid == "auto":
		pid = findWowProcess()
	
	if pid:
		print timestring(), "Attaching to process", pid
		sniff.addProcess(pid)
	elif not options.file:
		print timestring(), "Warning: Not attaching to any process"
	
	nids.init()
	nids.register_tcp(sniff.tcp_handler)
	
	nids.run()
if len(sys.argv) < 2:
    print_usage()
    sys.exit(-1)

input_file = sys.argv[1]

nids.param("filename", input_file)
#nids.param("scan_num_hosts", 0)
nids.chksum_ctl([('0.0.0.0/0', False)])

# Loop forever (network device), or until EOF (pcap file)
# Note that an exception in the callback will break the loop!
try:
    nids.init()
    nids.register_tcp(handleTcpStream)
    nids.register_udp(handleUdpStream)
    nids.run()
except nids.error, e:
    print "nids/pcap error:", e
except Exception, e:
    print "misc. exception (runtime error in user callback?):", e

tcps = _tcp_bag.values()
tcps.sort(None, lambda x: x[0], False)
for tcp in tcps:
    if None in tcp:
        continue
    line = '%.3f\t%.3f\t%d\t%d' % (tcp[0], tcp[1]-tcp[0], tcp[2], tcp[3])
    print(line)
示例#43
0
def main():
	try:
		ifile=""
		global dev
		global filter
		global debug
		global response_dict
		global interactive
		global filter_by
		global cant_bytes_min
		global ssh_user_string

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


		opts, args = getopt.getopt(sys.argv[1:], "d:hVi:qf:Dt:b:s:", ["device=","help","version","input-file=","filter=","--debug","session-type=","min-bytes=","ssh-string="])
	except getopt.GetoptError: usage()

	for opt, arg in opts:
	    if opt in ("-h", "--help"): usage()
	    if opt in ("-V", "--version"): version()
	    if opt in ("-i", "--input-file"): ifile = arg
	    if opt in ("-d", "--capture-device"): dev = arg
	    if opt in ("-f", "--filter"): filter = arg
	    if opt in ("-D", "--debug"): debug=1
	    #if opt in ("-I", "--interactive"): interactive=True
	    if opt in ("-t", "--session-type"): filter_by = arg
	    if opt in ("-b", "--min-bytes"): cant_bytes_min = arg
	    if opt in ("-s", "--ssh-string"): ssh_user_string = arg
	try:

		if filter_by != "":
			interactive = True

		if ifile!="" and dev=="":
			if debug:
				print 'Input File : %s' % (ifile)
        		nids.param("filename", ifile)
		elif ifile=="" and dev!="":
			if debug:
				print 'Capturing from device : %s' % (dev)
		elif ifile=="" and dev=="":
			usage()
			sys.exit(1)

		if filter:
			if debug:
				print 'Filter: %s' % (filter)
			nids.param("pcap_filter",filter)

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

		nids.init()

	 	nids.register_tcp(handleTcpStream)

		try:
			if debug:
				print '  -- Start processing'
			nids.run()
			output()
		except nids.error, e:
			print "nids/pcap error:", e
			output()
		except Exception, e:
			print "misc. exception (runtime error from user callback?):", e
			output()
示例#44
0
文件: Nids.py 项目: faust/tcpextract
	def run(self):
		nids.run()