Thursday, October 29, 2015

Ubuntu's ufw 設置 - 將WAN's IP某個Port轉到LAN's IP某個Port

REASON BEHIND....

因為前個週末和沛那邊提供的虛擬機沒有收回,想說可以用剩下的resource在開一台vm,可是Floating IP 只有一個,所以需要自己在接到Floating IP 的 vm 上做端口轉發來連接到另一個vm的ssh 端口。


WORKAROUND...



  1. enable forwarding in "/etc/default/ufw"
    • sudo cp /etc/default/{ufw,ufw.bak}
    • sudo vim /etc/default/ufw
      • ...
        #DEFUALT_FORWARD_POLICY = "DROP"
        DEFAULT_FORWARD_POLICY = "ACCEPT"
        ....

  2. enable ipv4 forwarding in "/etc/ufw/sysctl.conf"

    • sudo cp /etc/ufw/{sysctl.conf,sysctl.conf.bak}
    • sudo vim /etc/ufw/sysctl.conf
    • uncomment the line "net/ipv4/ip_forward=1"
      • ...
        # Uncomment this to allow ....
        net/ipv4/ip_forward=1
        #net/ipv6/conf/default/forwarding=1
        #net/ipv6/conf/all/forwarding=1
        ...
    • reload sysctl settings from "/etc/ufw/sysctl.conf" 
      • sudo sysctl -p /etc/ufw/sysctl.conf

  3. define forwarding rules in "/etc/ufw/before.rules"

    • sudo cp /etc/ufw/{before.rules,before.rules.bak}
    • sudo vim /etc/ufw/before.rules
    • add nat table rules right below the comment block at starting of the file (before the line "*filter")
      • # NAT table rules
        *nat
        :PREROUTING ACCEPT [0:0]
        :POSTROUTING ACCEPT [0:0]

        # -F to drop all previous nat rule in "iptables"
        -F
        #Port Forwardings
        -A PREROUTING -p tcp --dport <sourcePort> -j DNAT --to <destinationIP>:<destinationPort>
        # Forward traffic through eth0
        -A POSTROUTING -o eth0 -j MASQUERADE

        COMMIT

  4. reload ufw rules
    • sudo ufw disable && sudo ufw enable && sudo ufw reload
    • use "nc" to check if the port is listening
      • nc -zv <publicIP> <sourcePort>


More About "ufw"....

ufw rules are set in a few stages (I wasn't so clear about the flow but there are certain two stage - one through the config file "/etc/ufw/before.rules", and another through the ufw shell )

Here I would like to focus on setting some simple rules using ufw script.
  1. to allow certain port being access
    • ufw allow <#port>/<tcp/udp>
  2. to delete a rule
    • first list out all rules with a corresponding number for each
      • sudo ufw status numbered
    • delete certain rules 
      • sudo ufw delete <#rule>
  3. to check all set rule (will only list rules that were set using shell)
    • sudo ufw status
    • sudo ufw status verbose
    • sudo ufw status numbered

Reference...

[1] https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-14-04
[2] https://gist.github.com/kimus/9315140
[3] http://ubuntuforums.org/showthread.php?t=833844
[4] http://serverfault.com/questions/238563/can-i-use-ufw-to-setup-a-port-forward
[5] http://askubuntu.com/questions/660972/port-forwarding-with-ufw

No comments:

Post a Comment