Monday, January 14, 2008

Man-Eater|MONITOR





This post is on monitoring bandwidth usage under Linux, the importance of which I until recently,had more than neglected.

One stop solution : IPTABLES

Your 2.6 kernel must have the following kernel modules, [I guess]: ip_tables,iptable_filter
The following script sets-up counter for various protocols.


#!/bin/bash

. bwusage.conf

foo() {
local VAR_NAME=\$"$1"
local VAL_VAR_NAME=`eval "expr \"$VAR_NAME\""`
if [ -z "$VAL_VAR_NAME" ]
then
eval "$1=\"\""
else
eval "$1=\" $2 $VAL_VAR_NAME\""
fi
}
foo INPUT_IFACE -i
foo OUTPUT_IFACE -o
foo DESTINATION -d
foo SOURCE -s

foot() {
echo $SHA_BANG$SHELL
for PROTOCOL in `sed -ne "s/^\([a-z]\+\)\t\([0-9]\)\+.*$/\1/p" $PROTOCOLS_FILE`
do
CMD="iptables -v -A $MODE $IFACE $SOURCE $DESTINATION -p $PROTOCOL"
echo $CMD
# CMD="iptables -v -A $MODE $OUTPUT_IFACE $SOURCE $DESTINATION -p $PROTOCOL"
# echo $CMD
done
}> $CMDLST

if [ $MODE == "INPUT" ]
then
IFACE=$INPUT_IFACE
else
IFACE=$OUTPUT_IFACE
fi
chmod +x $CMDLST

This is the variables declaration file.

#bwusage.conf
# This file is sourced by bwusage
#
PROTOCOLS_FILE=/etc/protocols
INPUT_IFACE=eth1
OUTPUT_IFACE=eth1
SOURCE="172.16.54.54"
DESTINATION="172.16.54.54/16"
MODE=OUTPUT
SHA_BANG=#!
CMDLST=cmdlist


The result is a file called cmdlist [or whatever $CMDLST equals] which needs to be executed to setup the rules. I found it useful to save the rules in text, as it can be utilized when you want to mass delete some/all of these rules. Replace -A by -D in $CMDLST

Although this serves the purpose, the following thought is worth considering:
Except the protocol=ip rule in any chain, upon matching one rule, it will not successfully match against another, yet it goes on to match it against the next. A TCP packet cannot be a RDP or UDP packet as well. So is it possible to specify rules in a way that further scanning is avoided.
If you do know how to do it please leave a comment detailing the same.

No comments: