[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Multiple discrete IP match rule - iptables



On Thu, 1 Apr 2004, Alano Stolf wrote:

> I have not found any reference on how to specify more than one IP (discrete IPs, not a range) in an iptables rule.
> For example, how can I log only the access to SMTP servers that are not the ones I may allow.
> For instance, a rule like this should be fine:
> iptables -A FORWARD -p tcp -d ! (IP_of_MySMTP_1 IP_of_MySMTP_2) --dport 25 -j LOG --log-prefix "Access to suspicious SMTP: "

Well, AFAIK there is no built-in way to do that, but it isn't too hard
to do yourself. The ruleset is a shell script anyway...

Here's how I do it:

#===============================================================================
#Variables
#===============================================================================

ALLOW_SSH=1
SSH_CLIENTS="130.161.x.x, 130.161.y.y/23, 130.161.z.z/22"
REGEXP='^\(\([01]\?[0-9]\{1,2\}\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\([01]\?[0-9]\{1,2\}\|2[0-4][0-9]\|25[0-5]\)\(/\([0-2]\?[0-9]\|3[0-2]\)\)\?$'

#===============================================================================
#Utility functions
#===============================================================================

get_ips() {
  if [ -f "$1" ]; then
    #Read data from file
    IPS=( `grep ${REGEXP} $1` )
  else
    #Read data from arguments
    ARGS=( ${*//,/ } )
    IPS=( )
    for i in "${ARGS[@]}"; do
      if echo $i | grep ${REGEXP} > /dev/null; then
        IPS=( "${IPS[@]}" "$i" )
      fi
    done
  fi
}

#===============================================================================
#Allow selected remote SSH clients to connect to the local server
#===============================================================================

if [ "$ALLOW_SSH" = "1" ]; then
  get_ips $SSH_CLIENTS
  for IP in "${IPS[@]}"; do
    if [ "$VERBOSE" = "1" ]; then
      echo Processing SSH client $IP...
    fi
    if [ "$CONNECTION_TRACKING" = "1" ]; then
      iptables -A INPUT -i $PUB_IFACE -p tcp \
               -s $IP --sport $EPHEMERAL_PORTS \
               -d $PUB_IP --dport 22 \
               -m state --state NEW -j ACCEPT
    fi

    iptables -A INPUT -i $PUB_IFACE -p tcp \
             -s $IP --sport $EPHEMERAL_PORTS \
             -d $PUB_IP --dport 22 -j ACCEPT

    iptables -A OUTPUT -o $PUB_IFACE -p tcp ! --syn \
             -s $PUB_IP --sport 22 \
             -d $IP --dport $EPHEMERAL_PORTS -j ACCEPT
  done
fi

#===============================================================================

The rest is up to you.

Grx HdV




Reply to: