Thursday, December 15, 2011

XenServer - Cannot Shut VM

Have you ever experienced  a situation where you could not shut one of your running XenServer running VM's?   In this brief article I'll present a workaround for this common problem...  From my personal experiences this problem is often caused when the domain of the specific VM is still active (this often happens as a result of inproper shutdown and/or storage cutoffs) - in such case the domain needs to be destroyed manually.  OK, so here's the problem - from the XenServer (v 5.6 SP1) dom0 CLI I'm trying to shut a VM (using the force option): #xe vm-reset-powerstate vm=xxxxxxx force=true
However the output I get is:  The operation could not be performed because a domain still exists for the specified VM.
vm: f087dxxxxx (xxxxxx)
domid: 5
  From the output we will need  two parameters :the domain id (5 in our case) and the UUID of the problematic VM , so write them down somewhere. Now we need to destroy the currently active domain, XenServer includes couple of good tools under /opt/xensource, the command that is relevant is:   #/opt/xensource/debug/destroy_domain -domid 5  Now, finally, we will be able shut the VM with:  #xe vm-reboot uuid=XXXX --force  And we're done.  Hope that helped some one out there. Cheers!

Wednesday, December 7, 2011

Perl SSH Log-in

Hi Folks, 

In the following post I will demonstrate a password-less login into Cisco appliance via the SSH protocol using a Perl script.

When combined with cron, it can be a great solution for saving your appliance configuration (show run) or checking status without the need to log-in into the appliance each time.

Pre requirements:
  • Perl
  • SSH client (duh!)
  • Net-SSH-Perl module

On Red-Hat (and friends) the module can be obtained via:
#yum install perl-Net-SSH-Perl -y 

Be sure to have a proper repository installed such as rpmforge 
Our simple script connects to the Cisco appliance via SSH and runs "show run" command (this account has enabled privilege).
The script itself should look like this:

#!/usr/bin/perl -w
use strict;
use warnings;
use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new('hostname');
$ssh->login('username', 'password');
my($out) = $ssh->cmd("show run");
print $out;

Since the script contains your appliance username & password don't forget to remove permissions for others:
#chmod o-rwx

Now, let's run the script:

Building configuration...

Current configuration : 8011 bytes
...more output ommited...

Works like charm!
Now, the only thing is left is to synchronize it with cron :)


Sunday, November 27, 2011

Howto configure LDAP with TLS

Configuring LDAP over TLS is a crucial step in order to achieve a secure directory based authentication.
In the following tutorial I'll demonstrate how to configure OpenLDAP with TLS.

For the demonstration both server & client I've used are CentOS 5.5 x86_64
My LDAP server is OpenLDAP v2.3.43

Let's get started.

Step1 - Generating and Signing Certificates:

First of all we need to generate and sign the OpenLDAP server certificates.
In this scenario we will both generate and sign our certificate (self signed), this solution is good for internal and usually small environments.
If you ever plan to use this in a big enterprise production environment you will need a proper CA, like Verisign or Terrena to sign the certificates.

Before continuing please make sure the open SSL package is installed.

Generate your private key and a certificate request form:

#cd /etc/openldap/cacerts
#openssl req -nodes -newkey rsa:2048 -keyout server.key -out server.csr  Sign the certificate with:
#openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 3650
Now you got both private and public keys.

After the certificates have been generated, assign the correct permissions and ownerships:

#chown ldap server.*
#chmod 0400 server.key
#chmod 0644 server.crt

Step2 - Server Side:

The following two lines need to be added in your server configuration file

TLSCertificateFile      /etc/openldap/cacerts/server.crt
TLSCertificateKeyFile   /etc/openldap/cacerts/server.key
Restart the LDAP server:
#/etc/init.d/ldap restart 

Step3 - Client Side:

Make sure the ssl parameter in your LDAP client configuration file (/etc/ldap.conf) looks like this:

ssl start_tls

Also, make sure /etc/openldap/ldap.conf includes the following parameters:

TLS_CACERTDIR /etc/openldap/cacerts

That's it, from this point your OpenLDAP is ready to be used over TLS.
Stay secure ;)

Friday, November 4, 2011

IPv6 Subnetting

In this article I will try to explain the basic concepts of IPv6 subnetting.
IPv6 subnetting may seem awkward at first glance but once you get used to the technique, it's really not that hard, actually whoever is familiar with IPv4 subnetting will feel comfortable really soon - just some practice is needed.

A fast refresher before we start:

1)IPv6 address consists of 128 bits total , when the first 64 bits represent the network and the last 64 bit represent represent the host, it's presented in Hexadecimal values.

2) Every character in IPv6 address represents 4 bits.

3) Each IPv6 set (like 2ffe) represent 16 bits  (4 characters ,each one is 4 bits length).

So, as an example let's suppose that our ISP has allocated our small corporation the following range:


Our requirement is to allocate one subnet to each department ,there are 8 departments in total.

Let's get busy:

Since we are required to have 8 subnets we need to understand how many bits are going to represent this subnetting.
In order to understand how many bits we will need, we will have to find which power of 2 will be enough for the needed allocation.

The formula here is very simple:

S=total subnets required
B=number of bits for subnet presentation

2^B >= S

In our case we will get:2^3>=8

That means 3 bits needed for our subnetting, so our new prefix will be /59 (56 that were given +3 subnet representation bits).

 /59 - means that 59 bits will be reserved for the network portion of the IPv6 address.

The subnetting will take place on the 3rd nibble of the 4th set (dd00).

We will represent the 3rd nibble of the 4th set (dd00) as Binaries, since only 3 bits are needed for subnetting - our lowest possible value will be 000 and our highest possible value will be 111, the last (4th) bit of the set stays untouched.

000 0
001 0
010 0
011 0
100 0
101 0
110 0
111 0

Next, we will convert the Binary values to Hexadecimal values, pay attention that we the change accurs on the 3 bits only while the 4th bit stays the same (0):

000 0 =>0
001 0 =>2
010 0 =>4
011 0 =>6
100 0 =>8
101 0 =>a
110 0 =>c
111 0 =>e

Lastly we will write down all the subnets we got ,it will look something like this:


And whoila, we got 8 subnets for each department - just what we wanted to achieve.

You can dissect the adress even more and add more layers of subnetting depending on your needs.

Monday, September 26, 2011

XenServer Backup Script

This handy bash script I wrote, enables Xen Server Administrators to create On-Line backups (Importing the VM into.xva file) while the backed up virtual machine is up and running.

I found this extremely useful for big production environments - where lots of VM's require an appropriate & efficient back-up solution and downtime is not an option.

The script is very simple and user friendly, it's executed as root from the dom0 machine and used as follows:
In order to list all the available VM's on the system:
#./ -l

In order to back up a VM:
#./ -p /path/to/backupdir -s vm-name

The script supports both interactive and unattended mode (-u flag), the later designed to be built into scripts as an automation solution for large production environments.

For any help/usage, just run:
#./ -h

Tested succesefully on XenServer 5.6 FP1 & XenServer 5.6 SP2.
Any comments, feed-backs or suggestions for improvements are very welcomed.

#This script used to create XenServer VM's online backup #Importing the VM into .xva file #Written by Paul Podolny - July 2011

AUTO=0 #Used for unattended mode
VMLIST=`xe vm-list is-control-domain=false |grep -i name-label|awk -F": " '{print $2}'`

list() {
echo "====================================="
echo "Listing available VM's on $HOSTNAME..."
echo "====================================="
for i in $VMLIST;do
      echo $i;let COUNT+=1
echo "================================="
echo "Total $COUNT Virtual Machines"
echo "================================="
exit 0

usage() {
cat << EOF
This script will backup your Xen VMs on-line:
-h Help/Usage.
-l List VM's.
-u Run in unattended mode (No questions asked).
-s Server Name (Backed Up VM).
-p Path to backup.

$0 -s server01 -p /nfs/backupdir/ -u
exit 0
check_dir() {
echo "=============================================================="
echo "XenServer Online Backup"
echo "=============================================================="
if  [ -e ${BACKUPPATH}/${VMNAME} ];then
        echo "Directory ${VMNAME} on path ${BACKUPPATH} seem to exist, will use it."

      echo "Creating dir. ${VMNAME} on backup path: ${BACKUPPATH}"
      mkdir ${BACKUPPATH}/${VMNAME}

echo "`date +%H:%M` Backing Up ${VMNAME}, please hold on...Do NOT interrupt with CTRL+C !!!"
echo "================================================="

#MAIN Prog
while getopts "s:p:lhu" flag ; do
        case $flag in
                l ) list;;
                s ) VMNAME=$OPTARG;;
                p)  BACKUPPATH=$OPTARG;;
                h ) usage;;
                u)  AUTO=1;;
                *)  usage;;

#Sanity check  - Make sure backup path + VM name specificed if [ -z ${VMNAME} ] || [ -z ${BACKUPPATH} ];then echo  "Error:Both backup path AND VM name must be specified, exiting..."
echo  "Use $0 -h  for help"
exit 1

#If running in interactive mode
if [ ${AUTO} != "1" ];then
      echo "Going to back-up ${VMNAME} to ${BACKUPPATH} ,is this OK? [y/n]"
      read ANSWER
      if [ ${ANSWER} != "y" ] && [ ${ANSWER} != "Y" ];then
            echo "Exiting by users request..."
            exit 1
      #else proceed with main program...
            TEMPUUID=$(xe vm-snapshot vm=$VMNAME new-name-label=snap_tmp_`date +%F`)
            xe template-param-set is-a-template=false ha-always-run=false uuid=$TEMPUUID
            xe vm-export vm=${TEMPUUID} filename=${BACKUPPATH}/${VMNAME}/${VMNAME}_backup_`date +%F`.xva
            echo "Removing Temporary Snapshot....(DO NOT PANIC!)"
            xe vm-uninstall uuid=${TEMPUUID} force=true
            echo "==============================================================="
            echo "### Back Up of ${VMNAME} Completed!###"
            echo  "`date +%H:%M`"


Thursday, September 22, 2011

Adding Users in OpenLDAP

In this quick tutorial I will show how to add users to your directory.
I will be using two CentOS 5.5 x64 hosts for this presentation:
  • server - will be my test OpenLDAP server.
  • test - will be my test client host.
Before we begin I will assume OpenLDAP is already correctly installed on your system  (you can refer to this procedure, to learn more about primary OpenLDAP installation & configuration).

In this example my root dn is:"dc=example,dc=org"
And my admin user on the LDAP server is "cn=Manager,dc=example,dc=org"

OK, let's get our hands dirty:

Server side:
First, check that LDAP server is installed and running:
root@server# rpm -qa|grep -i ldap
root@server# lsof -i :389
slapd   20221 ldap    7u  IPv6 4349285       TCP *:ldap (LISTEN)
slapd   20221 ldap    8u  IPv4 4349286       TCP *:ldap (LISTEN)

Next, we will add a user and change it's password:
root@server# useradd -g ldap-users john
root@server# passwd john

Now, we will copy user's "john" data from /etc/passwd and use one of the migration scripts OpenLDAP provides in order to create an appropriate "ldif" file:

root@server# grep john /etc/passwd > /etc/openldap/passwd.john
root@server# /usr/share/openldap/migration/ /etc/openldap/passwd.john /etc/openldap/passwd.john.ldif

We will add the newly created "ldif" file into our LDAP DB:

root@server# ldapadd -x -D "cn=Manager,dc=example,dc=org" -W -f  /etc/openldap/passwd.john.ldif

Enter LDAP Password:  
adding new entry "uid=john,ou=People,dc=example,dc=org"

Let's try to search for john user in the LDAP DB:

root@server# ldapsearch -x -LLL '(uid=john)'
dn: uid=john,ou=People,dc=example,dc=org
uid: john
cn: john
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
userPassword:: e2NyeXB0fSEh
shadowLastChange: 15239
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
loginShell: /bin/bash
uidNumber: 500
gidNumber: 500
homeDirectory: /home/john

Seems to be working, now let's switch to the client.

Client side:
Check that your client is configured with the LDAP server:
Add the server and the domain inside: /etc/ldap/ldap.conf

uri ldap://
base dc=example,dc=org

Edit /etc/nsswitch.conf for LDAP authentication:

passwd: files ldap
shadow: files ldap
group: files ldap

It's time to test our configuration from the client side:
First check that john isn't listed in your /etc/passwd local  file:

root@test# grep john /etc/passwd

As we can see, no john here.
Now try to "id" john:

root@test# id john
uid=500(john) gid=500 groups=500

Just as we wanted.

Monday, September 12, 2011

Import/Export MySQL Databases

Well to be honest, this is quite trivial but useful nevertheless so I will get straight to the point:

In order to export a DB into a file:
#mysqldump -u username -p{password} database_name > dbfile.sql
In a scenario where multiple DB's need a backup solution
A simple script like this can be implemented:

for i in `mysql -e "show databases;" |egrep -v '^Database$'`; do
#dump and backup to remote server
mysqldump -Q |gzip -cf >/backupdir/db_${i}-`date + %F`.sql.gz
rsync -avz -e ssh /backupdir/. server:/remote_dir/. 

To import an exported DB from a file:

# mysql -u username -p db_name < dbfile.sql 

Sunday, August 28, 2011

Puppet - Quick Tutorial

Puppet is an Open Source configuration management framework (somewhat similar to Cfengine) written in Ruby.
It provides a declarative language syntax and an abstraction layer that allow you to write configuration definitions that can be propogated across large scale computing environment - making it a critical tool for midsize-large computing sites.

In the following tutorial I will explain how to configure both client & server side, so let's start:

I will use 2 CentOS v5.5 x64 machines for this tutorial.

Server Side (hostname=test1):
1)Install RPMforge repository:

 #rpm -Uvh

2)Install the needed packages:
#yum -y puppet-server ruby ruby-rdoc

3)Configure server behaviour side:
#vi /etc/sysconfig/puppetmaster

...un-comment the following lines:

4)Configure site manifests;

We first tell puppet to import all the configuration under classes directory.
Next we tell Puppet that test2 will be our client upon which we want to use the 'test'  function:

#vi /etc/puppet/manifests/site.pp
import "classes/*" 

node "" {
    include test

Here we will define the 'test' function:
The configuration is pretty straighforward, we declare a file on which the owner and the group will be root, also the permission will be 440, so if permissions are modified , after puppet daemon is run it will be back to it's origin - aka 440:

#vi /etc/puppet/manifests/classes/test.pp
class test {
    file { "/tmp/puppet-test":
        owner => root,
        group => root,
        mode  => 440

5)Restart the server and check the configuration:
#/etc/init.d/puppetmaster restart
#puppetmaster --debug

Client Side (hostname=test2):

1)Install RPMforge repository:
#rpm -Uvh

2)Install the needed packages:
#yum install -y puppet ruby ruby-rdoc 

3)Configure client behavior side:
#vi /etc/sysconfig/puppet

#vi /etc/puppet/puppet.conf

Under the[puppetd]section add the server name:
server =

4)Restart the client and and check for any errors (-t flag is used for test):
#/etc/init.d/puppet restart
#puppetd -t

If no errors are found try to create the file with different permissions than 440 ,like:
#touch /tmp/puppet-test;chmod 777/tmp/puppet-test

Now run the Puppet client...
#puppetd --server

You should see the following output:
notice: Starting Puppet client version 0.23.2
info: Facts have changed; recompiling
info: Caching configuration at /var/lib/puppet/localconfig.yaml
notice: Starting configuration run
notice: //[/tmp/puppet-test]/mode: mode changed '644' to '440'
notice: Finished configuration run in 0.02 seconds

Check the permissions again:
#ls -ld /tmp/puppet-test
-r--r----- 1 root root 0 Aug 28 14:19 /tmp/puppet-test

...and it worked, the file is back to it's pre-configured status on Puppet master, just as we wanted.
This is just the very beginning, I will leave you to explore further by yourself.


Wednesday, July 20, 2011

Howto:Reduce LVM Root Partition

In this short tutorial I'll demonstrate how to reduce the size of LVM (/dev/VolGroup00/LogVol00) mounted on "/" (aka root partition).
Since the procedure cannot be done on the run (you will need to unmount the root partition...) , you will have to boot your machine either with some sort of Linux LiveCD or either with the original CentOS DVD/ISO which offers special rescue mode.

I didn't have a LiveCD so I used the original CentOS DVD for this task.

Boot the machine with a CentOS DVD/ISO (v 5.5 in my case) and enter the rescue mode by typing:
#linux rescue

CentOS will boot in rescue mode when a menu pops up and asks you if you want to mount your old partitions, chose "SKIP" (otherwise your original disk partitions will be mounted under /mnt/sysimage - in that case umount it before proceeding).

After you made sure your original disk partitions are not mounted you will have to activate the LVM in Rescue Mode:
# lvm vgchange -a y

Check the LVM for any filesystem errors, this is crucial for next step:
# e2fsck -f /dev/VolGroup00/LogVol00

It's time to resize the filesystem to a new size ,note that you should leave enough space for current data on the root partition or you will suffer a data loss.
In our case we are reducing the partition to a new size of 20GB.
Note that the procedure may take some time (depending on your root partition size, so do not panic!):
# resize2fs -f /dev/VolGroup00/LogVol00 20G

Finally, resize the LVM to the new size (20 GB):
#lvm lvreduce -L20G /dev/VolGroup00/LogVol00

You should boot your OS into regular mode and cross your fingers ...

Disclaimer: Do at your own risk, I'm not responsible for any data loss which may be caused to your system.

Monday, July 18, 2011

Basic LDAP Configuration on CentOS

LDAP today is a standard for central authentication solution, it is a very complex subject with hundreds of features and configurable options. In this short tutorial I will not try to explain the concepts of LDAP but rather demonstrate a quick way of setting up & configuring LDAP server (OpenLDAP in our case) on CentOS 6 machine, so lets start:

#yum -y install openldap openldap-servers openldap-clients migrationtools

2)Configure administrator password:

Copy the hashed password into:
Uncomment the line starts with rootpw and paste the output hashed password like this:
rootpw {SSHA}NJWxZ6g/z9tCJZWZzuPFAN4Uo1AQokU8

3)Next in the same file, set your DN:

Save changes and exit.

4)Open /etc/openldap/ldap.conf

... and add the following lines:
BASE dc=yourdomain,dc=com

Save changes and exit.

5)Copy the example DB file to your DIT directory:
#cp /usr/share/doc/openldap-servers-2.4.19/DB_CONFIG.example /var/lib/ldap/DB_CONFIG

6)Make sure ldap is started on desired run-levels + start the server:
#chkconfig slapd on
#/etc/init.d/slapd start

7)Edit /usr/share/migrationtools/
Rename the following lines with your credentials:
$DEFAULT_MAIL_DOMAIN = "dc=yourdomain,dc=com";
$DEFAULT_BASE = "dc=yourdomain,dc=com";

Save the file.

8)Generate LDIF file with the previously edited perl script:
/usr/share/migrationtools/ > /etc/openldap/yourdomain.ldif

9)Configure LDAP server logging in syslog configuration, open:/etc/syslog.conf

...and add the following lines:
#LDAP Logging
local4.debug          /var/log/slapd.log

Hup the syslog service:
#kill -HUP $(cat /var/run/

Restart LDAP service:
#/etc/init.d/slapd restart

Basic configuration is done, let's try to add an object and make a search:

#ldapadd -x -a -W -D  "cn=Manager,dc=yourdomain,dc=com" -f /etc/openldap/yourdomain.ldif

*lots of objects being added*

Restart the service:
#/etc/init.d/slapd restart

Next, make a general search (for any objectclass):
#ldapsearch -x -b "dc=yourdomain,dc=com" "objectclass=*" 

# extended LDIF
# LDAPv3
# base <> with scope subtree
# filter: cn=Manager,dc=yourdomain,dc=com
# requesting: objectclass=*

# search result
search: 2
result: 0 Success

# numResponses: 1

You should be able to see all the object classes of your LDAP DB.

Well this is just the basics to  get you going, feel free to explore further...


Tuesday, July 12, 2011

Enable SNMP on Cisco Devices (part 1)

In this short tutorial I'll demonstrate how to quickly configure SNMP on your Cisco appliance and test it's working.

There will be another tutorial dealing with how to configure the SNMP manager side.

1) Let's start by logging in to your Cisco appliance (In my case I used 851 series Cisco router with IOS version 12.3).

2) Enter configuration mode:
cisco851#configure terminal

3) Set your community string and the mode (read only, read write):
cisco851(config)#snmp-server community myComunity1 RW

4) Point the appliance to the SNMP manager (in our case , with the same community string you've set before: 

 cisco851(config)#snmp-server host version 2c myComunity1

5) Enable the trap types you wish to monitor, for example:

cisco851(config)#snmp-server enable traps snmp linkdown linkup coldstart warmstart

6) Save the configuration:
cisco851(config)#do wr

At this point the basic configuration on the Cisco appliance is done, let's see if we able to querry the appliance from our server.

I have used Ubuntu 11.04 x64 box with "snmp" package installed.

Check it's indeed installed with:
root@ubuntu:~#dpkg --list |grep snmp
If not get it with:
root@ubuntu:~#apt-get install snmp

After snmp package has been succefully installed it's time test the configuration.

Issue the following command and see if you're able to retrieve the SNMPv1 agent  or our Cisco appliance ( MIB tree list :

root@ubuntu:~#snmpwalk -v 1 -c myComunity1

At this point you should be able to list the entire tree (output was ommited), means Cisco side is configured successfully.

You can now get the desired info for monitoring purposes, like the system uptime:

root@ubuntu:~#snmpget -v 1 -c myComunity1

DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (490514418) 56 days, 18:32:24.18
Or our appiance hostname:

root@ubuntu:~#snmpget -v 1 -c myComunity1

SNMPv2-MIB::sysName.0 = STRING:
Mission accomplished.
In the next SNMP article I will touch the server side configuration.

Monday, June 20, 2011

Quick tcpdump tutorial

tcpdump is  undoubtedly a Swiss knife when debugging a complicated network issue.
This command line application includes dozens of features and allows you to monitor network traffic on a very detailed level.
Also, it may be your only option in situations when you don't have access to GUI based tools such as "wireshark" (former ethereal) .Another plus is the huge popularity the tool gained as  almost every modern Linux distro. supports it and comes with the tool installed.

In this short tutorial I will show some basic usage of this tool, lets get busy:

The utility is "kind-of intuitive" in terms of usage, the general syntax goes like this:
  |protocol|  |direction|  |address|  |port|  |logical expression| 

Example #1:
#tcpdump tcp dst 443 and tcp dst 23

In this command we are "sniffing" for traffic destined for host with destination port of 443 (https) and for host with destination port of 23 (telnet).

Example #2:
#tcpdump src and port 80

Here we are "sniffing" for traffic coming from destined to port 80 (http).
Easy? However these are just the basics... let's see some more advanced usage of this tool:

Example #3:
#tcpdump -i eth1 -A src and port 80

In this example we are running the command on a machine with more than one NIC, here the interface eth1 is used for sniffing (specified with -i eth1).
The -A flag presents the captured packets as ASCII data - this is useful for capturing web pages or text in general.

Example #4:
#tcpdump -e not port 22

In the following example we are listening to any traffic except port 22 (ssh), the -e flag specifies that tcpdump should look into the link level of captured packets.

Well these were just some of the basics to get you "on-track"...
Happy sniffing ;)

Tuesday, June 7, 2011

Installing and configuring fail2ban

If you're running a server that's exposed to the internet you will sooner or later realize while checking the server security logs that you're constantly being attacked, it can be via multiple ftp,ssh,http break-in attempts (brute force attacks),(D)DoS attacks and many other nasty stuff, what's for sure - this is not something that can be neglected.

A great solution for such scenario is an open source, Python-based application called "Fail2ban".

Fail2ban is capable of working with multiple log filesand multiple services.
The flexibility and integration with iptables is a major benefit of fail2ban - so the IP filtering is performed at the kernel-level.

Instalaltion pre-requirements:

Basically ,all of these should already be installed on your system (default install).

Installation process (I used a CentOS box for this example):

1)Install the application using Yum
#yum install fail2ban -y

2)Edit fail2ban configuration file called "jail.conf"
#vi /etc/fail2ban/jail.conf

3)Under the[DEFAULT] section we can find global configuration such as - friendly hosts, ban time, search time etc, lets adjust these parameters to meet our needs.

Here we will allow localhost, and subnet  to be ignored by fail2ban:

ignoreip =,,

If the host is violating the rules it will be banned to this amount of time (in seconds):

bantime  = 1209600

A host is banned if it has generated "maxretry" during the last "findtime"

findtime  = 1800

The number of failures before a host get banned.
maxretry = 3

4)Let's say we want  to enable fail2ban scan on ssh log-in attempts.
Scroll to section "[ssh-iptables]" and enable it:

enabled = true

Next,change the the SSH logfile we want to scan:

logfile = /var/log/secure

Adjust the max failures the system will allow:

maxretry = 3

Comment out the "sendmail-whois" section and change it to your mail, so you will receive mail alerts when fail2ban has banned some IP.

sendmail-whois[name=SSH,, sender=fail2ban]

5) That's it, save the file and restart fail2ban and iptables.
#/etc/init.d/iptables restart 
#/etc/init.d/fail2ban restart
#chkconfig iptables on
#chkconfig failban on

Don't forget to check that email works, and you are done.

Monday, May 2, 2011

Howto remove old NAT configuration from Cisco router

Recently I came upon a situation where my ISP has assigned me a static IP - instead of L2TP dialer (Virtual PPP Interface in Cisco) I was using before ...
Anyway, I started to remove old and irrelevant NAT settings that were associated with my old dialer ,but when I've tried to configure the new NAT settings I got an error:
%Dynamic mapping in use, cannot change

After scratching my head for awhile I found the solution.

To remove old NAT settings on Cisco router you need to 

1)Clear all old NAT translations
router#clear ip nat translatiom *

2)Disable old NAT pool settings
router(config)#no ip nat pool public_access netmask

3)And finally, disable the translation:
router(config)#no ip nat inside source list 1 pool public_access overload

From this point you can safely configure the new NAT settings.

Tuesday, April 26, 2011

Howto configure Apache with SSL (CentOS):

Configuring Apache server with SSL is an easy task when you know what you're doing ;) 
I decided to make one easy-to-understand quick tutorial that will serve as a memory refresher, In my case I used CentOS 5.5 x64. we go:

1.Make sure Apache is installed:
#rpm -qa|grep httpd

if no, install it:
#yum install httpd

2.Install mod_ssl module for Apache 2 to enable SSL support:
#yum install mod_ssl

3.Generate the certificate request and send the request (contents of server.csr) to your CA (such as Verisign for example):
#openssl req -nodes -newkey rsa:2048 -keyout myserver.key\
-out server.csr

Grant read permissions only to root on your private key:
#chmod 0400 myserver.key

4. After receiving the public key + bundle from your CA, unzip and put them in the same directory as your private key, in my case I used "/etc/ssl/crt":
#mv myserver.key /etc/ssl/crt/
#mv my_server_org_il* /etc/ssl/crt

There is a neat way to check if public key mathes private key, go to the directory with your certificates and execute the following commands:
For public key:
# openssl x509 -noout -modulus -in hostcert.pem | openssl sha1
For private key:
# openssl rsa -noout -modulus -in hostkey.pem | openssl sha1

As you can see the output is the same - means we're good to go.

5.Before making any change, backup both configuration files:
#cp /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.bak
#cp /etc/httpd/conf/http.conf /etc/httpd/conf/http.conf.bak

Edit ssl.conf:

#vi /etc/httpd/conf.d/ssl.conf

Now, it's up to you to decide whether you will be using VirtualHost block or not (, anyway the configuration should include the following lines:
ServerAdmin root@localhost
DocumentRoot /var/www/html/support
ErrorLog logs/support_mydoimain_com-error_log
CustomLog logs/support_mydoimain_com-access_log common
SSLEngine on
SSLCertificateFile /etc/ssl/crt/support_mydoimain_com.crt
SSLCertificateKeyFile /etc/ssl/crt/myserver.key
SSLCACertificateFile /etc/ssl/crt/

6. For proper URL redirection  - you can use this line to redirect all incoming http traffic to your https server, add it to: httpd.conf

RedirectPermanent /

7. Restart httpd service:
#/etc/init.d/httpd restart

Make sure Listen 443 line is located in ssl.conf
Make sure Listen 80 line is located in httpd.conf

To check the web-server is listening on both ports run:
#lsof -i :80
#lsof -i :443

Basic configuration is done, try to access the server from the browser: