BASH   45
iptables
Guest on 8th February 2023 03:09:45 AM


  1. #!/bin/bash
  2. export IF_INET="enp1s0"
  3. export IF_LAN="enp3s0"
  4. export IP_LAN=192.168.99.0
  5. export IP_LAN_BITS=24
  6.  
  7. # restart network:
  8. #
  9. # systemctl restart networking.service
  10.  
  11. ##############################################################################
  12. function ip_forward ()
  13. {
  14.   INET_PORT="$1"
  15.   DEST_IP="$2"
  16.   DEST_PORT="$3"
  17.  
  18.   iptables -A PREROUTING -t nat \
  19.     -i "$IF_INET" -p tcp \
  20.     --dport "$INET_PORT" -j DNAT \
  21.     --to-destination "$DEST_IP":"$DEST_PORT"
  22.   iptables -A FORWARD -p tcp \
  23.     -d "$DEST_IP" \
  24.     --dport "$DEST_PORT" -j ACCEPT
  25. }
  26.  
  27. function ip_block_incoming ()
  28. {
  29.    # dest port can be 22, 80, or range like 20:200
  30.    DEST_PORT="$1"
  31.    iptables -A INPUT -i "$IF_INET" -p tcp \
  32.      --destination-port $DEST_PORT -j DROP
  33.    iptables -A INPUT -i "$IF_INET" -p udp \
  34.      --destination-port $DEST_PORT -j DROP
  35. }
  36.  
  37. function ip_block_incoming_udp ()
  38. {
  39.    # dest port can be 22, 80, or range like 20:200
  40.    DEST_PORT="$1"
  41.    iptables -A INPUT -i "$IF_INET" -p udp \
  42.      --destination-port $DEST_PORT -j DROP
  43. }
  44.  
  45. ##############################################################################
  46. # cleaning iptables
  47. iptables -F
  48. iptables -t nat -F
  49. iptables -t mangle -F
  50. # set up masquerading
  51. iptables -t nat -A POSTROUTING -o $IF_INET -j MASQUERADE
  52. # allow forwarding
  53. echo 1 > /proc/sys/net/ipv4/ip_forward
  54.  
  55. ##############################################################################
  56. # block incoming traffic we don't want
  57.  
  58. ip_block_incoming_udp 1:1024
  59.  
  60. # block up to 80
  61. ip_block_incoming 1:79
  62. # gap for port 80
  63. ip_block_incoming 81:98
  64. # gap for port 99
  65. ip_block_incoming 100:442
  66. # gap for port 443
  67. ip_block_incoming 444:1024
  68. # ...
  69.  
  70. ##############################################################################
  71. # port forward
  72. # send port 80 to this host's port 80
  73. ip_forward   80   192.168.99.99   80
  74. # send port 99 to this host's port 10
  75. ip_forward   99   192.168.99.98   10

Raw Paste

Login or Register to edit or fork this paste. It's free.