2014. november 25., kedd

Little dear ones of mine

How to take actions on a directory that contains hundreds of subdirectories, named like this...
0001
0002
....
0100
0101
...
0999
1000
...

...but just on the first some hundreds of them so their proper naming could be an issue. Solution:
#!/bin/bash

for i in $(seq 500);do
lngt=`expr length $i`
case $lngt in
    1)
    i=000$i
    ;;
    2)
    i=00$i
    ;;
    3)
    i=0$i
    ;;
esac
ls /home/samba/archive/$i -LRs >> /root/content.txt
done

It could be more solid but you know, always Keep It Simple&Stupid. :-)
Here is a more complex one. It's a cron driven script that checks your openvpn logfile and email you if an event (e.g. if certain user connects) found. It remembers its last run so that a logline never get processed twice. Also handles logrotate events.
#!/bin/bash

cd /var/log/openvpn
[ -e temp ] && rm temp
echo "" > connectionz
NOW=`cat openvpn.log|wc -l`
LAST=`cat last`
CHECK=$(($NOW-$LAST))
    if [[ $CHECK -ge 0 ]]; then # change found
    echo $NOW > last # if 0 then doesn't matter but no harmful
    else
    echo 0 > last # logrotation happened, nulling last
    LAST=0
    fi
tail -$CHECK openvpn.log|grep Initiated >
connectionz
while read line
 do
 USER=`echo $line|cut -d '[' -f2|cut -d ']' -f1`
 DATUM=`echo $line|cut -d ' ' -f2-5`
  if [ $USER = "JohnSmith" ] || [ $USER = "PeteSmith" ] || [ $USER = "JaneSmith" ] ; then
   echo "A user connected:"$USER" event time:"$DATUM >> temp
   echo "" >> temp
  fi
 done < connetionz
[ -e temp ] && cat temp | mail -n -s "OPENVPN CONNETION initiated" myemail@mydomain.com,yourdomain@yourdomain.com

2014. november 17., hétfő

IPTABLES - how to allow or deny certain countries of the world

It's a usual request for a sysadmin to ban or allow only a certain country in firewalls or .htaccesses of apache. Here are two common ways to do that.

Method 1.
Using xtables and maxmind

apt-get install libtext-csv-xs-perl module-assistant geoip-database libgeoip1
module-assistant --verbose --text-mode auto-install xtables-addons
mkdir /usr/share/xt_geoip
cd /usr/share/xt_geoip
# this is a rather old package but for free
wget http://terminal28.com/wp-content/uploads/2013/10/geoip-dl-build.tar.gz
tar xvf geoip-dl-build.tar.gz
./xt_geoip_dl
./xt_geoip_build -D . *.csv
##EXAMPLE ##EXAMPLE ##EXAMPLE ##EXAMPLE ##EXAMPLE ##EXAMPLE ##EXAMPLE 
iptables --flush # BEWARE
iptables -A INPUT -p tcp --dport 443 -m geoip --src-cc HU,CZ,PL,RO -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j DROP
 
 







Method 2.
Simply using https://www.countryipblocks.net/country_selection.php to get ranges to allow/deny