Iptables PortMapper

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1481
Joined: Fri Aug 29, 2003 8:39 pm

Iptables PortMapper

Post by ^rooker »

Makes mapping of several ports easier and needs less necessary lines:

Code: Select all



function map_through () {
   echo "IPT PortMapping: ";

   LAST_SERVER="";      #stores the last found server IP.
   LAST_PROTO="";       #stores the last found protocol (TCP, UDP,...)

   for map in $1
   do
      PROTO=`echo $map | awk -F":" '{print $1}'`
      PORT_IN=`echo $map | awk -F":" '{print $2}'`
      IP_SERVER=`echo $map | awk -F":" '{print $3}'`
      PORT_OUT=`echo $map | awk -F":" '{print $4}'`

      #    Remember/Use last valid server ip:
      if [ -z "$IP_SERVER" ]; then IP_SERVER=$LAST_SERVER; else LAST_SERVER=$IP_SERVER; fi
      #    assume PORT_IN==PORT_OUT, if no PORT_OUT given:
      if [ -z "$PORT_OUT" ]; then PORT_OUT=$PORT_IN; fi
      #    Remember/Use last valid protocol:
      if [ -z "$PROTO" ]; then PROTO=$LAST_PROTO; else LAST_PROTO=$PROTO; fi

      case "$PROTO" in
         U)    PROTOCOLS="UDP"; ;;
         T)    PROTOCOLS="TCP"; ;;
         UT)   PROTOCOLS="UDP TCP"; ;;
         *)    PROTOCOLS="TCP"; ;;        # Default Protocol
      esac

      if [[ -n "$PORT_IN" && -n "$PORT_OUT" ]] && [ -n "$IP_SERVER" ]
      then
         for PROTO in $PROTOCOLS; do
            echo "  - ($PROTO) From $PORT_IN to $IP_SERVER:$PORT_OUT"
   #      ${IPTABLES} -A PREROUTING -i ${OUT_DEV} -t nat -p $PROTO --dport $PORT_IN -j DNAT --to ${IP_SERVER}:${PORT_OUT}
   #      ${IPTABLES} -A FORWARD -p $PROTO -d ${IP_SERVER} --dport $PORT_OUT -i ${OUT_DEV} -o ${INT_DEV} -j ACCEPT
         done
      fi
   done
}

TESTMAP="U::192.168.1.10: :9999::1234 UT:20000:: ";
map_through "$TESTMAP"
User avatar
^rooker
Site Admin
Posts: 1481
Joined: Fri Aug 29, 2003 8:39 pm

License....

Post by ^rooker »

Oh. I forgot to mention that this code is licensed under the GPL. ;-)
Post Reply