How to fake the source-port of a TCP packet

tcp

Is there an easy way (or is it possible at all) to rewrite a TCP packet as it leaves the machine?
For example if I run

telnet binfalse.de 22

it will search for an unused port to leave the machine. In this case it's 46576:

root@srv % lsof -i -P -n | grep telnet
telnet    10150   user    3u  IPv4 1159425      0t0  TCP 1.2.3.4:46576->87.118.88.39:22 (ESTABLISHED)

But now I want to rewrite these packets to let the server think the requests came from port 1337, or somewhat like this. Of course I know that I don't have to expect an answer in my telnet session.

EDIT:
Of course on 1337 another program is listening, so telling telnet to speak through 1337 is no option…

Best Answer

Assuming you are speaking about Linux, iptables has a mangle table that can do all sorts of crazy things to outgoing TCP traffic. iptables NAT features might help as well, because it really sounds like you want to do "port address translation" or "manual NAT."

Related Question