OpenWrt Forum Archive

Topic: SSH Tunnel to work as VPN.

The content of this topic has been archived between 7 Apr 2018 and 29 Apr 2018. There are no obvious gaps in this topic, but there may still be some posts missing at the end.

Hi guys,

my device is: TL-MR3040 v1

software : chaos_calmer/15.05.1

I'm not sure if this is the right place for my questions, but hope that you could help!

My goal is to set up a SSH tunnel that will forward all wireless clients to SSH server.
The same thing do a built-in VPN service...so maybe it's possible to do the same trick with SSH? How do you think?

I will very appreciate any advice or link to related discussions!

Unfortunately I cant achieve my goal for a 3 months already....even google doesnt help(

Cheers!

I think you should be more specific about what you have tried and what failed.

SSH allows set up a Socks Proxy server, but this only will redirect TCP connections, not UDP.

If you want to redirect a whole internet connection (TCP and UDP datagrams) like VPN you will need another software running in the server besides ssh daemon.

The simplest thing: Run locally in the server a VPN server and connect through a redirection in ssh.

(Last edited by iasimov on 19 Sep 2016, 23:29)

iasimov wrote:

SSH allows set up a Socks Proxy server, but this only will redirect TCP connections, not UDP.

If you want to redirect a whole internet connection (TCP and UDP datagrams) like VPN you will need another software running in the server besides ssh daemon.

The simplest thing: Run locally in the server a VPN server and connect through a redirection in ssh.

Hi, could you give more info about "connect through a redirection in ssh"? Is it possible to use SSH client while connecting to VPN server?




И если говоришь по ру, то не мог бы оставить какой то контактик свой?

I use   ssh dynamic port redirection (socks5) + redsocks + iptables redirect for transparent redirection of selected TCP connections. With some magic it works fine

bolvan wrote:

I use   ssh dynamic port redirection (socks5) + redsocks + iptables redirect for transparent redirection of selected TCP connections. With some magic it works fine

Hi, would you mind to give some advices or a brief guide "how to setup" using your method?

Maybe you have any kind of IM available for some communication?

vital21 wrote:

Hi, would you mind to give some advices or a brief guide "how to setup" using your method?

Its quite a long story and probably impossible to do for copy-pasters smile But fundamentally its quite easy, you just need to understand the logic, then process becomes interesting. Also may be some my decisions are not perfect, if you can suggest something shorter and more effective pls do it.

1)
openssh (not dropbear) client can give you local socks on selected port using server's ssh port redirection
create another (non-root) user, su, use ssh-keygen to create keys, copy pub key to "authorized_keys" on server (google for configuring key authentication in openssh)
After all done test if it works with curl.

opkg update
opkg install --force-overwrite openssh-client openssh-client-utils curl shadow-useradd
useradd -d /home/proxy proxy
mkdir -p /home/proxy
chown proxy:proxy /home/proxy
# openssh client barks if it has no access to /dev/tty
echo "chmod 666 /dev/tty" >>/etc/rc.local
chmod 666 /dev/tty
su proxy
cd
mkdir -m 700 .ssh
cd .ssh
ssh-keygen
# should see id_rsa id_rsa.pub
ls
# copy id_rsa.pub to authorized_keys on server
ssh -N -D 1098 -l proxy vps.mydomain.com
# in parallel session test with curl
curl --socks5 127.0.0.1:1098 http://google.com

2)
Create a way to keep openssh always running. Restart it if it disconnects.
/etc/init.d/socks_vps :

#!/bin/sh /etc/rc.common
# opkg install procps-ng-pgrep coreutils-nohup
START=95
STOP=10
USER=proxy
SCRIPT_DIR=/etc/my
SCRIPT=socks_vps.sh
LOGDIR=/var/log/socks_vps
restart() {
stop
start
}
start() {
[ -d $LOGDIR ] || {
     mkdir $LOGDIR
     chown $USER $LOGDIR
}
pgrep -U $USER $SCRIPT >/dev/null || su -c $SCRIPT_DIR/$SCRIPT $USER &
}
stop() {
killall $SCRIPT 2>/dev/null
PID=$(pgrep -U $USER ssh)
[ -n "$PID" ] && kill $PID
sleep 1
return 0
}

/etc/my/socks_vps.sh

#!/bin/sh
# opkg install coreutils-nohup
trap "" SIGHUP SIGINT
while :
do
    nohup ssh -4 -N -D 1098 -l proxy vps.mydomain.com >/dev/null 2>/var/log/socks_vps/svps.2.log
    sleep 10
done

opkg install procps-ng-pgrep coreutils-nohup
chmod +x /etc/my/socks_vps.sh
chmod +x /etc/init.d/socks_vps

Start : /etc/init.d/socks_vps start
Stop : /etc/init.d/socks_vps stop
Enable autoload : /etc/init.d/socks_vps enable


3) (updated)
Obtain redsocks package. Its present only in CC 15.05 and DD+. CC and DD use different libc and executables are not compatible. If you're on 15.05 or DD - just install from repo. If you're on <15.05 then take ipk from 15.05 and install manually.

4) Configure redsocks and make it always running.
/etc/redsocks.conf

........
      local_ip = 127.0.0.1;
      local_port = 1099;
........
      ip = 127.0.0.1;
      port = 1098;
      type = socks5;
........

The shit is that it cant start with normal /etc/init.d script because at the moment of its execution even "lo" is not up and executable exits with error. So hang on hotplug event and start from there
/etc/hotplug.d/iface/99-exec-on-updown

#!/bin/sh
local cmd
if [ "$ACTION" = ifup ]; then
cmd=$(uci get network.$INTERFACE.exec_on_up)
[ -n "$cmd" ] && $cmd
fi
if [ "$ACTION" = ifdown ]; then
cmd=$(uci get network.$INTERFACE.exec_on_down)
[ -n "$cmd" ] && $cmd
fi

/etc/init.d/network

config interface 'wan'
        ........
        option exec_on_up '/etc/init.d/redsocks start'

# autostart not working because network is down
/etc/init.d/redsocks disable
/etc/init.d/redsocks start

5)
And the final part. Create iptables filter to redirect some connections to transparent proxy "redsocks"
The reason why I started all this is russian censorship machine. They block web sites. I break http by fooling DPI but https must be redirected. I created ipset "zapret". It contains blocked IP addresses

/etc/firewall.user

SOXIFIER_PORT=1099
. /lib/functions/network.sh
# connections originating from router
network_find_wan wan_iface
for ext_iface in $wan_iface; do
    network_get_device ext_device $ext_iface
    iptables -t nat -C OUTPUT -p tcp --dport 443 -o $ext_device -m set --match-set zapret dst -j REDIRECT --to-port $SOXIFIER_PORT ||
     iptables -t nat -I OUTPUT -p tcp --dport 443 -o $ext_device -m set --match-set zapret dst -j REDIRECT --to-port $SOXIFIER_PORT
done
# forwarded connections
sysctl -w net.ipv4.conf.br-lan.route_localnet=1
iptables -t nat -C prerouting_lan_rule -p tcp --dport 443 -m set --match-set zapret dst -j DNAT --to 127.0.0.1:$SOXIFIER_PORT ||
iptables -t nat -I prerouting_lan_rule -p tcp --dport 443 -m set --match-set zapret dst -j DNAT --to 127.0.0.1:$SOXIFIER_PORT

Note that kernels before 3.10 cant DNAT to 127.0.0.1. They treat it as "martian" IP and deny.
uname -a
If version is older then bind redsocks to LAN address instead of 127.0.0.1 and change DNAT address as well or replace DNAT with REDIRECT.
Also check if iptables support "-C" command line option. Very old versions (AA) cannot.
Check if iptables has all required filter modules, install missing modules if it barks.
Only TCP can be redirected, UDP cannot

(Last edited by bolvan on 3 Nov 2016, 20:45)

bolvan wrote:
vital21 wrote:

Hi, would you mind to give some advices or a brief guide "how to setup" using your method?

Its quite a long story

Спасибо за подробную инфу. Правильно ли я понял, что схематически выглядит все так :

1) поднимается ссх клиент, коннектится к ссх серверу.
2) поднимается редсокс
3) с помощью iptables редирект на редсокс, который в свою очередь туннелит в ссх?
4) работает только с TCP

Поправте если что то  не так понял...


П.С. в случае если все получится настроить, можно будет позаимствовать ваш конфиг iptables?

Yes, all is right.
Russian topic is here :
https://rutracker.org/forum/viewtopic.php?t=5171734

The biggest problem with your device would be low flash space (4 mb) and only one USB ports which is probably  occupied by modem. Will need usb hub, flash drive and make extroot

(Last edited by bolvan on 14 Oct 2016, 10:57)

Update : procd greatly simplifies the task of keeping ssh client running.
No more script magic.

/etc/init.d/socks_vps :

#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50
STOP=50
USE_PROCD=1

USERNAME=proxy
COMMAND="ssh -N -D 1098 -l proxy vps.mydomain.com"

start_service() {
    procd_open_instance
    procd_set_param user $USERNAME
    procd_set_param respawn 10 10 0
    procd_set_param command $COMMAND
    procd_close_instance
}

(Last edited by bolvan on 14 Oct 2016, 14:36)

bolvan wrote:

Yes, all is right.

How about the iptables config? This is the big black hole for me...

bolvan wrote:

The biggest problem with your device

What is the best ( better ) device for such purposes? How do you think?

P.S. want to say big thanks for your advices, as nowadays it's not so easy to find answers for those tons of questions while learning "Networking"

vital21 wrote:

How about the iptables config? This is the big black hole for me...

Its there. see /etc/firewall.user. This is example, you need to add your own filters or adopt my 'zapret' system if your purpose is to circumvent censorship. Iptables is well documented. Here filters description : http://ipset.netfilter.org/iptables-extensions.man.html

What is the best ( better ) device for such purposes? How do you think?

Any device with at least 8 megs of flash will fit.
4 meg devices with usb will also fit if used with flash drive as extroot/

bolvan wrote:

3) Obtain redsocks package. Its missing before DD. If you're on a version lower than DD then you have to install SDK toolchain, copy redsocks package definition from trunk and compile yourself. Default SDK has problems out of the box, you'll see compiler errors, some links and executables are missing, google for that.  Or  compile your own toolchain from source. You cant just take binary from DD because DD has new libc , its not compatible with CC and lower.

Hi again, I got a new hardware, Asus RT-N66U, running Chaos Calmer 15.05.1.

And stuck on redsocks configuration...As i understand that CC do not support it...but what do you mean when you say "DD"?

I thought that CC is the last firmware from openwrt...

vital21 wrote:

I thought that CC is the last firmware from openwrt...

DD = designated driver
today's development trunk release

Hi, there is a problem with this part of setup:

# copy id_rsa.pub to authorized_keys on server
ssh -N -D 1098 -l proxy vps.mydomain.com

I dont have an access to SFTP session on this server ( by the way it's a VPN provider Torguard ). I usually use it with Bitvise client ( on Windows ). So the only way I could authenticate is  the login/password method.

Any suggestions?

bolvan wrote:

I created ipset "zapret". It contains blocked IP addresses

Could you advice a rule which will redirect all the traffic and all ports( not only 80 or 443 ), to SOXIFIER PORT?

vital21 wrote:

I dont have an access to SFTP session on this server ( by the way it's a VPN provider Torguard ). I usually use it with Bitvise client ( on Windows ). So the only way I could authenticate is  the login/password method.

Any suggestions?

Perhaps sshpass helps.
Its not standard openwrt package. need to compile with sdk

vital21 wrote:

Could you advice a rule which will redirect all the traffic and all ports( not only 80 or 443 ), to SOXIFIER PORT?

remove "--dport 443"
or even better dont use /etc/firewall.user but place redirect rule to /etc/config/firewall. This is more conformant with openwrt design. Raw iptables are not desired.
i used firewall.user because i havent found a way to do redirect for OUTPUT (connections originating from router itself) and didnt want to keep 2 points of modification, keeping it as simple as copy 1 file

(Last edited by bolvan on 2 Nov 2016, 15:26)

bolvan wrote:

remove "--dport 443"

With ALL port redirecting to SOCKS, my config seems to get broken.

After doing this I cant login to my router ( luci and dropbear are not working )

As a result I'm not able to start redsocks service, as well as open an ssh -N -D 1098 -l proxy vps.mydomain.com.

Could you suggest which ports should I left behind the firewall? Is there any iptables rule to exclude --dport? I saw something about  "!" Symbol, but cant figure out how to use it...

Exclude lan destinations.
! --dst 192.168.0.0/16

(Last edited by bolvan on 3 Nov 2016, 08:27)

bolvan wrote:

Exclude lan destinations.
! --dst 192.168.0.0/16

works for lan connections, but now I cant establish a ssh -N -D 1080 -l connect.

As i understand, firewall is not allowing this connection.


Here is my firewall.user

SOXIFIER_PORT=1099
. /lib/functions/network.sh
# connections originating from router
network_find_wan wan_iface
for ext_iface in $wan_iface; do
   network_get_device ext_device $ext_iface
   iptables -t nat -C OUTPUT -p tcp ! --dst 192.168.0.0/16 -j REDIRECT --to-port $SOXIFIER_PORT ||
   iptables -t nat -I OUTPUT -p tcp ! --dst 192.168.0.0/16 -j REDIRECT --to-port $SOXIFIER_PORT 
done
# forwarded connections
sysctl -w net.ipv4.conf.br-lan.route_localnet=1
iptables -t nat -C prerouting_lan_rule -p tcp ! --dst 192.168.0.0/16 -j DNAT --to 127.0.0.1:$SOXIFIER_PORT ||
iptables -t nat -I prerouting_lan_rule -p tcp ! --dst 192.168.0.0/16 -j DNAT --to 127.0.0.1:$SOXIFIER_PORT

Thanks for your help, by the way! I appreciate it!

To avoid loops without hardcoding server's excemption IP use uid filter.

-m owner ! --uid-owner nobody

nobody is the user redsocks runs under. see /etc/redsocks.conf or 'ps'
its applicable only to OUTPUT rule. forwarded packets have no uid associated
make sure iptables-mod-extra installed

OR

remove OUTPUT chain at all if you dont want to SSHify connections originating from the router itself

(Last edited by bolvan on 3 Nov 2016, 13:07)

Finally, it works! Would you mind to double-check my config?

First of all, as I cant configure auto-login for ssh session, I start it from command line with

ssh -N -D 1080 -l username SSH_SERVER_IP

and enter the password manually.

Secondly I start redsocks which is configured as

127.0.0.1 - ip:   localport - 1099:    serverport - 1080

Lastly I add

SOXIFIER_PORT=1099
. /lib/functions/network.sh
# forwarded connections
sysctl -w net.ipv4.conf.br-lan.route_localnet=1
iptables -t nat -C prerouting_lan_rule -p tcp ! --dst 192.168.0.0/16 -j DNAT --to 127.0.0.1:$SOXIFIER_PORT ||
iptables -t nat -I prerouting_lan_rule -p tcp ! --dst 192.168.0.0/16 -j DNAT --to 127.0.0.1:$SOXIFIER_PORT

Am i missing something or it's OK?

P.S. Did you try to compile/setup redsocks2 with DD? I tried, but seems its not working for me on ar71xx hardware...

Yes, config looks fine.
I'm not aware of redsocks2. redsocks1 works just fine and is present both in DD and CC 15.05.1
I compiled for you sshpass static binary  mips32 msb rel2. It will work on any ar71xx.
https://www.sendspace.com/file/933new

(Last edited by bolvan on 5 Nov 2016, 08:42)

WoW! Thanks a lot. I will test and report back asap