Execute script on Snort alert

前端 未结 3 1656
执笔经年
执笔经年 2021-01-03 09:48

I currently am experimenting with a Raspberry Pi. I am running Snort, which is packet detection software. In the case Snort raises an alert, I would want to execute a (Pytho

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 09:52

    If piping the output delays receiving alerts until snort's stdout buffer is flushed:

    #!/usr/bin/env python
    from __future__ import print_function
    from subprocess import Popen, PIPE, STDOUT
    
    snort_process = Popen(['snort', '-A', 'console', '-c', 'snort.conf'],
                          stdout=PIPE, stderr=STDOUT, bufsize=1,
                          universal_newlines=True, close_fds=True)
    with snort_process.stdout:
        for line in iter(snort_process.stdout.readline, ''):
            #XXX run python script here:
            #    subprocess.call([sys.executable or 'python', '-m', 'your_module'])
            print(line, end='')
    rc = snort_process.wait()
    

    Then you could try a pseudo-tty to enable line-buffereing on snort's side.

    Or run snort -A unsock command and print each alert as soon as it is generated using Unix domain sockets:

    #!/usr/bin/env python
    import ctypes
    import os
    import socket
    from subprocess import Popen
    from snort import Alertpkt
    
    # listen for alerts using unix domain sockets (UDS)
    snort_log_dir = os.getcwd()
    server_address = os.path.join(snort_log_dir, 'snort_alert')
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    try:
        os.remove(server_address)
    except OSError:
        pass
    sock.bind(server_address)
    
    # start snort process
    snort_process = Popen(['snort', '-A', 'unsock', '-l', snort_log_dir,
                           '-c', 'snort.conf'], close_fds=True)
    # receive alerts
    alert = Alertpkt()
    try:
        while 1:
            if sock.recv_into(alert) != ctypes.sizeof(alert):
                break # EOF
            #XXX run python script here `subprocess.call([sys.executable or 'python', '-m', 'your_module'])`
            print("{:03d} {}".format(alert.val, alert.data))
    except KeyboardInterrupt:
        pass
    finally:
        sock.close()
        os.remove(server_address)
        if snort_process.poll() is None: # the process is still running
            snort_process.kill()
            snort_process.wait() # wait for snort process to exit
    

    In your case you could run a script on each alert instead of printing.

    snort.Alertpkt is a ctypes's defition of C struct Alertpkt.

    To try it, you could download the gist that contains a dummy snort script in addition to all the python modules and run run-script-on-alert-unsock.py (or run-script-on-alert-pty.py).

提交回复
热议问题