views:

775

answers:

1

I would like to make server that listen on UDP port 162 (SNMP trap) and then forwards this traffic to multiple clients. Also important is that the source port & address stays same (address spoofing).

I guess that best tool for this would be Twisted or Scapy or maybe vanilla sockets, only I can't find anything in the documentation for Twisted about source address spoofing/forging.

Any solution for this?

Edit:added bounty, mybe any solution with iptables?

+2  A: 

I am not comfortable with twisted or scapy, but it's quite straightforward to do this with vanilla python sockets. An extra advantage of that is that it will be even more portable. This code works in my limited tests:

#!/usr/bin/python
from socket import *
bufsize = 1024 # Modify to suit your needs
targetHost = "somehost.yourdomain.com"
listenPort = 1123

def forward(data, port):
    print "Forwarding: '%s' from port %s" % (data, port)
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(("localhost", port)) # Bind to the port data came in on
    sock.sendto(data, (targetHost, listenPort))

def listen(host, port):
    listenSocket = socket(AF_INET, SOCK_DGRAM)
    listenSocket.bind((host, port))
    while True:
        data, addr = listenSocket.recvfrom(bufsize)
        forward(data, addr[1]) # data and port

listen("localhost", listenPort)
Benson
One thing I forget to put in first part of question statement that I need source address and port from originating server (so actually server needs to fake source address), can socket do this?
Ib33X
No, no it can't. I think that the problem you're trying to solve here might be better solved by some iptables rules. Why do you want to do it with python, exactly?
Benson
Incidentally, I'd be very surprised if you can forge packet headers with twisted; scapy is probably your best bet. I'll have a look and see how hard it is.
Benson
Okay, so scapy will do it. I'll try to get an example written up tonight if I can.
Benson
iptables actually I am not that familiar with iptables so I need to learn new skill to do this in iptables, since I am more found off python I decide to learn how to do it in python, and for now I am not doing great ;)
Ib33X
Well, the problem is that what you're talking about doing is munging packets. Python is not a good tool for that task. In fact, this is less of a programming challenge and more of a sysadminning challenge. While you could write scapy code that woudl do it, it would be inefficient and slow. This belongs in a firewall ruleset. That said, I'll still see what I can find.
Benson
You can try using raw sockets to do your spoofing.
piotr
A good point. I could try throwing together a raw socket example. I still say this question is based on the incorrect assumption that it's a programming problem -- it should really be done with existing firewall software.
Benson