File: nfq_asyncore.py

package info (click to toggle)
nfqueue-bindings 0.4-3
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 232 kB
  • sloc: ansic: 257; python: 211; perl: 183; makefile: 28; sh: 25
file content (60 lines) | stat: -rwxr-xr-x 1,411 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python

# need root privileges

import struct
import sys
import time
import asyncore

from socket import AF_INET, AF_INET6, inet_ntoa

sys.path.append('python')
sys.path.append('build/python')
import nfqueue

sys.path.append('dpkt-1.6')
from dpkt import ip

def cb(i,payload):
  print "python callback called !", i

  print "payload len ", payload.get_length()
  data = payload.get_data()
  pkt = ip.IP(data)
  print "proto:", pkt.p
  print "source: %s" % inet_ntoa(pkt.src)
  print "dest: %s" % inet_ntoa(pkt.dst)
  if pkt.p == ip.IP_PROTO_TCP:
    print "  sport: %s" % pkt.tcp.sport
    print "  dport: %s" % pkt.tcp.dport
    payload.set_verdict(nfqueue.NF_DROP)

  sys.stdout.flush()
  return 1

class AsyncNfQueue(asyncore.file_dispatcher):
  """An asyncore dispatcher of nfqueue events.

  """

  def __init__(self, cb, nqueue=0, family=AF_INET, maxlen=5000, map=None):
    self._q = nfqueue.queue()
    self._q.set_callback(cb)
    self._q.fast_open(nqueue, family)
    self._q.set_queue_maxlen(maxlen)
    self.fd = self._q.get_fd()
    asyncore.file_dispatcher.__init__(self, self.fd, map)
    self._q.set_mode(nfqueue.NFQNL_COPY_PACKET)

  def handle_read(self):
    print "Processing at most 5 events"
    self._q.process_pending(5)

  # We don't need to check for the socket to be ready for writing
  def writable(self):
    return False

async_queue = AsyncNfQueue(cb)
asyncore.loop()