Category Archives: Scripts

Mikrotik Dual Wan

# NAT -----------------
# Enmascarar cualquier tráfico saliente por las interfaces wan:
# ether1 = canal_primario
# ether2 = canal_secundario
# ether3 = canal_terciario


ip firewall nat add chain=src-nat out-interface=ether1 action masquerade
ip firewall nat add chain=src-nat out-interface=ether2 action masquerade
ip firewall nat add chain=src-nat out-interface=ether3 action masquerade

# MANGLE -------------

# Marco el tráfico entrante de la red lan 10.2.59.0/24 para utilizar el canal primario

ip firewall mangle add src-address=10.2.59.0/24 action=mark-routing new-routing-mark=canal_primario chain=prerouting

# Marco el tráfico entrante de la red lan 10.2.60.0/24 utilizar el canal secundario

ip firewall mangle add src-address=10.2.60.0/24 action=mark-routing new-routing-mark=canal_secundario chain=prerouting

# Marco el tráfico entrante de la red lan 10.2.61.0/24 para utilizar el canal terciario

ip firewall mangle add src-address=10.2.61.0/24 action=mark-routing new-routing-mark=canal_terciario chain=prerouting

# Marco el tráfico saliente del router Mktik hacia los proveedores de servicio (en este caso 3 wans)

ip firewall mangle add src-address=192.168.56.2 action=mark-routing new-routing-mark=canal_primario chain=output
ip firewall mangle add src-address=192.168.57.2 action=mark-routing new-routing-mark=canal_secundario chain=output
ip firewall mangle add src-address=192.168.58.2 action=mark-routing new-routing-mark=canal_terciario chain=output


# ROUTE ----------------
# Estas son las reglas de enrutamiento basadas en marcas

ip route add gateway=192.168.56.1 routing-mark=canal_primario
ip route add gateway=192.168.57.1 routing-mark=canal_secundario
ip route add gateway=192.168.58.1 routing-mark=canal_terciario
ip route rule add dst-address=0.0.0.0/0 routing-mark=canal_primario table=canal_primario action=lookup
ip route rule add dst-address=0.0.0.0/0 routing-mark=canal_secundario table=canal_secundario action=lookup
ip route rule add dst-address=0.0.0.0/0 routing-mark=canal_terciario table=canal_terciario action=lookup
Advertisements

List openvpn valid certificates (using index.txt)

list_valid_certificates.sh

#!/bin/bash

# Run this script inside openvpn certificates directory.

rm -fv listado_certificados_validos.txt

CNT=`grep ^V index.txt | wc -l`

for i in 6 7
do
 grep ^V index.txt | cut -d / -f $i | sed 's+/emailAddress++g' | grep ^"CN" >> listado_certificados_validos.txt
done

CNT2=`cat listado_certificados_validos.txt | wc -l`

echo -e "-- VALIDANDO DATOS -- \n"

echo -e $CNT $CNT2" \n"

if [ $CNT2 -eq $CNT ]
then
 cat listado_certificados_validos.txt | sort | nl && echo -e "\nOK"
fi

Sync or copy playlist (.m3u) files

sync_playlist.sh

#!/bin/bash

PLAYLISTS=( rock_tracks.m3u jazz_songs.m3u shazam_01.m3u best_albums.m3u )
ROOTDIR=/home/user/Music/Playlists
DSTDIR=/home/user/Board
CMD="/usr/bin/rsync --progress -u"
TMP=`pwd`/.temp

mkdir $TMP

for i in "${PLAYLISTS[@]}"
do
 grep -v "^#" $ROOTDIR/$i | while read tracks; do du -k "${tracks}" >> $TMP/${i}.sum; done
done

cd $TMP
for i in *.sum
do
 FILE=`echo ${i} | sed s/.sum//g`
 SUM=`cat ${i} | awk '{total=total+$1} END {print total}' | awk '{ human = $1 / 1024} END {print human" M"}'`
 echo -e "$FILE == >> $SUM"
done
cd ..

echo -e "Do you want to synchronize the playlists? (y/n)"
read answer

if [ $answer = y ]
then
 for i in ${PLAYLISTS[@]}
 do
 DIRNAME=`echo ${i} | sed s/.m3u//g`
 mkdir -p $DSTDIR/"${DIRNAME}"
 grep -v "^#" $ROOTDIR/$i | while read tracks; do $CMD "${tracks}" $DSTDIR/"${DIRNAME}"; done
 ls -tr $DSTDIR/"${DIRNAME}" > $TMP/${i}
 mv $TMP/${i} $DSTDIR/"${DIRNAME}"
 done
fi

if [ $answer = n ]
then
 echo -e "OK"
fi

rm -r $TMP

Ossim lookup ip script – Execute using a rule

lookup_ip.pl

This script parse an ip address looking up geoip information and populating a database with its information and suricata ids information.

#!/usr/bin/perl

use Geo::IP::PurePerl;
use Email::MIME;
use Email::Sender::Simple qw(sendmail);
use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip );
use DBI;

my $gi = Geo::IP::PurePerl->new("/usr/local/share/GeoIP/GeoIP.dat", GEOIP_STANDARD);
my $srcip = $ARGV[0];
my $country = $gi->country_code_by_addr($ARGV[0]);
my $date = qx(date +%Y-%m-%d);
my $time = qx(date +%H:%M:%S);
my $sidname = $ARGV[1];
my $srcport = $ARGV[2];
my $protocol = $ARGV[3];
my $dstip = $ARGV[4];
my $dstport = $ARGV[5];

open (MYFILE, '>/tmp/temp.txt');
foreach $argnum (0 .. $#ARGV) {
 print MYFILE "$ARGV[$argnum]\n";
}
close (MYFILE);

my $regexp = create_iprange_regexp('192.168.0.0/16','10.0.0.0/8','172.16.0.0/16','172.17.0.0/16');
if ( match_ip($srcip, $regexp) ) {
 print "ip interna \n";
 exit 0;
} else {
 print "ip externa \n";
}

my $dbh = DBI->connect("DBI:Pg:dbname=siem;host=localhost", "database", "password", {'RaiseError' => 1});
my $registry = $dbh->do("INSERT INTO ips_db (date,time,sensor,sid_name,src_ip,src_port,dst_ip,dst_port,src_country,action) VALUES ('$date','$time','192.168.56.10','$sidname','$srcip','$srcport','$dstip','$dstport','$country','database')");

Perl transfer files using ssh (shortcut command)

transfer.pl

#!/usr/bin/perl

use Term::ANSIColor;

if (! defined $ARGV[0]) {
 print "Don't be stupid please...";
 exit 0;
}

my $file = "/home/user/hosts.txt";
my $keysdir = "/home/user/keys";
my $username = $ARGV[1];
my $remote_hostname = $ARGV[0];
my $xfer = $ARGV[2];
my $time = qx/date/;

if ( $ARGV[0] =~ /edit/) {
 my $command = "vim $file";
 system ($command);
 exit 0;
}

if ( $ARGV[0] =~ /list/) {
 print "\n";
 open (my $data, "<" , "$file")
 or die "Failed to open file: $!\n";
 while (my $row = <$data>) {
 chomp $row;
 print "$row\n"
 }
 exit 0;
}

if (! defined $ARGV[2]) {
 print "Please load a file!";
 exit 0;
}

open (my $data, "<" , "$file")
or die "Failed to open file: $!\n";

while (my $row = <$data>) {
 chomp $row;
 if ( $row =~ /$remote_hostname/) {
 if ( defined $ARGV[3] ) {
 my @args = ($row, $ARGV[3]);
 ssh_transfer_key(@args);
 exit 0;
 }
 else {
 ssh_transfer($row);
 exit 0;
 }
 }
}

print "Remote host not found!";

sub ssh_transfer() {

 my $row = $_[0];
 my @parts = split(",",$row);
 my $hostname = $parts[0];
 my $ipaddress = $parts[1];
 my $port = $parts[2];
 print $time;
 print "Transfering file to $hostname ...\n";
 print color("red"), "scp -P $port $xfer $username@$ipaddress:/tmp \n", color("reset");
 my $command = "scp -P $port $xfer $username"."@"."$ipaddress:/tmp/";
 system($command);
 exit 0;

}

sub ssh_transfer_key() {

 my $row = $_[0];
 my $key = $_[1];
 my @parts = split(",",$row);
 my $hostname = $parts[0];
 my $ipaddress = $parts[1];
 my $port = $parts[2];
 print $time;
 print "Transfering file to $hostname ...\n";
 print color("red"), "scp -i $keysdir/$key -P $port $xfer $username"."@"."$ipaddress:/tmp \n", color("reset");
 my $command = "scp -i $keysdir/$key -P $port $xfer $username"."@"."$ipaddress:/tmp/";
 system($command);
 exit 0;

}

close $data;

Cisco Wireless Controller – WPA PSK passphrase change Script and HTTP Publish

change_wlc_ssid_passphrase.pl

#!/usr/bin/perl

use Net::SSH::Expect;

my $ssh = Net::SSH::Expect->new (
 host => "192.168.10.3",
 raw_pty => 1
);

my $pass = generatePassword(10);
print ("Generating new WPA passphrase: ".$pass."\n");
print ("Getting into WLC...\n");
$ssh->run_ssh() or die "SSH process couldn't start: $!";
$ssh->waitfor('User:', 10) or die "prompt 'User' not found after 10 second";
$ssh->send("user");
$ssh->waitfor('Password:', 3) or die "prompt 'Password' not found after 3 second";
$ssh->send("password");
$ssh->waitfor('(Cisco Controller)', 3) or die "prompt 'Cisco Controller' not found";
print ("Disabling SSID Wlan\n");
$ssh->exec("config wlan disable 7");
print ("Setting passphrase to SSID Wlan\n");
$ssh->exec("config wlan security wpa akm psk set-key ascii $pass 7");
print ("Enabling SSID Wlan\n");
$ssh->exec("config wlan enable 7");
$ssh->exec("logout");
$ssh->send("y");

open (MYFILE, '>temp.txt');
my $html_prefix = '<strong><font size="12">';
my $html_suffix = '</font></strong>';
print MYFILE ($html_prefix.$pass.$html_suffix."\n");
close (MYFILE);
system("cp -rf temp.txt /var/www/html/wireless/index.html");
print ("Job done!\n");

sub generatePassword {
$length = shift;
$possible = 'abcdefghijkmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
while (length($password) < $length)
 { $password .= substr($possible, (int(rand(length($possible)))), 1);
}
return $password
}