Ssh – Routing TCP packets to a local UDP port

netcatsshtcpudp

A third party server sends UDP packets to an EC2 instance we've set up and I'm trying to route those packets to my local machine.

The client sends these packets to port 8975

To that effect I first established an ssh tunnel to my ec2 instance

ssh -4 -L 10000:localhost:10000 -i ~/.ssh/xxxx.pem ubuntu@13.xxx.x.xx

on my remote machine – I routed the packets received on port 8975 to 10000
using this command

netcat -l -u -p 8975 > /tmp/udp2tcp | netcat -l -p 10000 < /tmp/udp2tcp

udp2tcp is a fifo file

on my local machine – I'm taking the tcp packets I receive and converting them back to UDP

netcat localhost 10000 > /tmp/tcp2udp | netcat -l -u -p 8975 < /tmp/tcp2udp

When i run netcat localhost 10000 – i can see the packets flowing in on my local machine

but for some reason , there is no packets being routed as udp to port 8975 – i'm not sure what exactly i need to do

when i run sudo tcpdump -i any -S -vvv port 10000

This shows me packets flogin in

15:39:10.053013 IP (tos 0x0, ttl 64, id 64725, offset 0, flags [DF], proto TCP (6), length 52)
    localhost.48974 > localhost.webmin: Flags [.], cksum 0xfe28 (incorrect -> 0x5674), ack 1261213200, win 10567, options [nop,nop,TS val 1064223053 ecr 1064223053], length 0

but when i run sudo tcpdump -i any -S -v port 8975 – i dont see anything

Best Answer

As an alternative to SSH port forwarding, you may forward those UDP packets to your local machine by using point-to-point tunnel devices, SSH and the procedure explained below.

In the EC2 instance, do the following:

  1. In /etc/ssh/sshd_config file, set configuration parameter PermitTunnel to either point-to-point or yes.

  2. Create a point-to-point tunnel device that will receive UDP packets from the public network:

    $ sudo ip tuntap add dev tun8975 mode tun user ubuntu
    $ sudo ip addr add dev tun8975 172.16.19.22 peer 172.16.19.21
    $ sudo ip link set dev tun8975 up
    
  3. Configure either IPTABLES or NFTABLES to forward such UDP packets to the tunnel device

    $ sudo iptables -t nat -A PREROUTING '!' -i tun8975 -p udp --dport 8975 -j DNAT --to-destination 172.16.19.21:8975
    
    $ sudo nft add rule ip nat PREROUTING iifname '!=' "tun8975" udp dport 8975 dnat to 172.16.19.21:8975
    
  4. Ensure that kernel allows IP packet forwarding among network interfaces:

    $ sudo sysctl -w net.ipv4.ip_forward=1
    

Afterwards, in your local machine, do the following:

  1. Create a point-to-point tunnel device that SSH will use to output forwarded UDP packets:

    $ sudo ip tuntap add dev tun8975 mode tun
    $ sudo ip addr add dev tun8975 172.16.19.21 peer 172.16.19.22
    $ sudo ip link set dev tun8975 up
    
  2. Request SSH to forward traffic between the tunnel devices through its secure channel:

    $ sudo ssh -4 -o Tunnel=point-to-point -w 8975:8975 -i ~/.ssh/xxxx.pem ubuntu@13.xxx.x.xx
    
Related Topic