eibgrad

merlin-ovpn-port-forward-74860.sh

Sep 25th, 2021 (edited)
1,841
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/sh
  2. # version: 1.1.0, 28-sep-2021, by eibgrad
  3. # href: https://tinyurl.com/3ebyzyyu
  4.  
  5. SCRIPTS_DIR="/jffs/scripts"
  6. SCRIPT="$SCRIPTS_DIR/nat-start"
  7.  
  8. mkdir -p $SCRIPTS_DIR
  9.  
  10. create_script() {
  11. cat << "EOF" > $SCRIPT
  12. #!/bin/sh
  13. set -x # uncomment/comment to enable/disable debug mode
  14. {
  15. # ------------------------------ BEGIN OPTIONS ------------------------------- #
  16.  
  17. # interface source-ip/net proto extern-port intern-ip intern-port [comments...]
  18. PORT_FORWARDS="
  19. tun11 0.0.0.0/0 tcp 10022 $(nvram get lan_ipaddr) 22 router ssh server
  20. tun12 0.0.0.0/0 tcp 10080 192.168.1.200 80
  21. tun12 0.0.0.0/0 tcp 10443 192.168.1.200 443
  22. #tun12 188.188.188.188 tcp 10088 192.168.1.210 8088
  23. tun+ 199.199.199.0/24 udp 10999 192.168.1.210 999 all vpn network interfaces
  24. "
  25. # ------------------------------- END OPTIONS -------------------------------- #
  26.  
  27. # ---------------------- DO NOT CHANGE BELOW THIS LINE ----------------------- #
  28.  
  29. ipt() { iptables ${@/-[IA]/-D} 2>/dev/null; iptables $@; }
  30.  
  31. OIFS="$IFS"; IFS=$'\n'
  32.  
  33. for pf in $PORT_FORWARDS; do
  34.     # skip comments and blank lines
  35.     echo $pf | grep -Eq '^[[:space:]]*(#|$)' && continue
  36.  
  37.     # parse port forward into separate fields
  38.     for i in 1 2 3 4 5 6; do eval f$i="$(echo $pf | cut -d' ' -f$i)"; done
  39.  
  40.     # redirect external port on vpn to internal ip+port
  41.     ipt -t nat -I PREROUTING -i $f1 -s $f2 -p $f3 --dport $f4 \
  42.         -j DNAT --to $f5:$f6
  43. done
  44.  
  45. IFS="$OIFS"
  46.  
  47. # allow routing from vpn to router internal port
  48. ipt -I INPUT -i tun+ -m conntrack --ctstate DNAT -j ACCEPT
  49.  
  50. # allow routing from vpn to lan internal ip+port
  51. ipt -I FORWARD -i tun+ -m conntrack --ctstate DNAT -j ACCEPT
  52.  
  53. exit 0
  54. } 2>&1 | logger -t $(basename $0)[$$]
  55. EOF
  56. chmod +x $SCRIPT
  57. }
  58.  
  59. if [ -f $SCRIPT ]; then
  60.     echo "error: $SCRIPT already exists; requires manual installation"
  61. else
  62.     create_script
  63.     echo 'Done.'
  64. fi
RAW Paste Data