Thursday, December 24, 2009

Quick & Easy - Rsync

Rsync is a great tool especially for data migration/mirroring/backups.Rsync's advantage is that it transfers the data in a "smart way", for example if a big sized file transfer was corrupted it will not resend the whole file, instead it breaks the data into chunks and re-transfers only the unfinished data. One of the advantages of rsync is that it knows how to cooperate with ssh, creating a very powerful tool.

Let's see some basic usages of rsync.
1) Transfer remote folder into local one:

jenova:/mysql_db # rsync -avz -e ssh root@remote:/tmp/. /mysql_db/

This will transfer all the contents of /tmp on the remote server to my /mysql_db folder.

2) Transfer local folder into remote one:

jenova:/mysql_db #rsync -avz -e ssh /mysql_db/ root@prana:/tmp/.

Notice the -e flag which tells rsync to use ssh as the network transfer method.

Sunday, December 20, 2009

Howto forward port on Cisco Router

Hi, in this short article I will demonstrate a way to configure port forwarding on your Cisco router.

This is our network topology, let's assume we want to allow anyone from the WAN side to connect to our web server (192.168.0.8) running Apache on port 80, the web server is located at a seperate DMZ segment (192.168.0.0/24):

This is how the general configuration will look like:

router(conf)#ip nat inside source "protocol" "internal IP" "internal port" interface "interface type" "external port"

So in our case the configuration will look like this:

router(conf)#ip nat inside source tcp 192.168.0.8 80 interface serial 0 80

Don't forget to apply a proper access list so the connections from the WAN side will not be blocked, I suggest using an extended access list to limit the connections only to the specific host in the DMZ.

Thursday, December 10, 2009

Some 'tr' useful examples

This is just a brief totorial for a great Unix tool called 'tr', very useful in text editing let's review couple of examples to make you understand the basics:
Before you start reading on I strongly recommend reading about regular expressions, a cool table that summarizes of reg. ex. can be found here:http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
OK, so let's start - we will take a look at one of my directories:
paul# ls
file01.txt file02.txt file03.txt file04.txt file05.txt
Let's make an output of upper cases names:

paul# ls | tr '[:lower:]' '[:upper:]'
FILE01.TXT
FILE02.TXT
FILE03.TXT
FILE04.TXT
FILE05.TXT


Another example, let's try to extract out only the numbers of the following string:

paul# echo -e"Abc1234d56E\n" | tr -cd '[:digit:]'
123456


We want to replace blank spaces with the " - " character:

paul# ls
bla bla.txt file01.txt file02.txt file03.txt file04.txt

paul# ls | tr '[:blank:]' '_'
bla_bla.txt
file01.txt
file02.txt
file03.txt
file04.txt
file05.txt


There are numerous of good example for usage of 'tr' , I will try to add more in the future.

Friday, December 4, 2009

Quick HOWTO:syslog-ng + cisco configuration

Hi all, in this short article I will demonstrate how to configure syslog-ng to caputre cisco log messages.

Let's start with the server side, I'm using Open SUSE11 VM in my case.

I will assume you have "syslog-ng" is already installed on your system.

So first, will need to edit /etc/sysconfig/syslog and change the following 2 lines:

SYSLOGD_PARAMS="-r"
SYSLOG_DAEMON="syslog-ng"


The 1st option (-r ) tells the Daemon to be in passive mode - act like a logging server.
The 2nd option tells syslog Daemon to use syslog-ng as the system default logging scheme.

Our main configuration file is /etc/syslog-ng/syslog-ng.conf
Open it with your favourite text editor and add:

options { sync (0);

time_reopen (10);
log_fifo_size (1000);
long_hostnames (off);
use_dns (yes);
use_fqdn (no);
create_dirs (no);
keep_hostname (yes);
};

source sys { unix-stream ("/dev/log"); internal(); };
source remote { udp(); };

destination std { file( "/var/log/syslog-ng/$HOST/$YEAR$MONTH/$FACILITY" create_dirs(yes)); };

log { source(sys); destination(std); };
log { source(remote); destination(std); };


Save the file, restart the service with /etc/init.d/syslog-restart
Verify syslog-ng is running on your run-level and listening on port 514:

chkconfig --list grep syslog
syslog 0:off 1:off 2:on 3:on 4:off 5:on 6:off


netstat -ntulp "pipe" grep ":514"

udp 0 0 0.0.0.0:514 0.0.0.0:* 32446/syslog-ng

All logs will be saved under: /var/log/syslog-ng/$HOSTNAME/$DATE/$LOG
(As we have stated to be in the syslog-ng config file), the server side is done, great.


Now let's login to our cisco router and access "configure terminal", from there execute theese commands:

service timestamps log datetime localtime
no logging console
no logging monitor
logging 192.168.0.180
Instead of the IP address, enter your logging server IP, save the configuration and exit the router.

Let's check if everything works, my router is called "cisco851" I've tried to enter privileged mode with wrong password, The result will be:

root@server01 # tail -f /var/log/syslog-ng/cisco851/200912/local4

Dec 4 14:15:58 cisco851 1895: Dec 4 12:15:59: %SYS-5-PRIV_AUTH_FAIL: Authentication to Privilage level 15 failed by paul on vty0 (192.168.0.180)

Dec 4 14:16:34 cisco851 1896: Dec 4 12:16:35: %SYS-5-PRIV_AUTH_FAIL: Authentication to Privilage level 15 failed by paul on vty0 (192.168.0.180)


We are done.

Friday, October 16, 2009

Quick format -AKA:Wipe the MBR

A quick and easy way to format a disk/flash disk using unix "dd":

This one will wipe both partition table + The Master Boot Record:
dd if=/dev/zero of=/dev/sdb1 bs=512 count=1

If you want to wipe out only the MBR and keep the partition table:
dd if=/dev/zero of=/dev/sdb1 bs=446 count=1

Configure SSH on a Cisco router.

SSH is a secure alternative to telnet as it's encrypted and almost impossible to be listened to, it's also great for remote management and monitoring via scripts.
By default SSH is disabled on Cisco routers, let's see how to configure it step by step.
First we need to set up an admin account on the router:

Router1(config)#aaa new-model
Router1(config)#username admin privilege 15 passwword P@ssw0rd

Next we will configure SSH service on the router:
Router1#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router1(config)#hostname Router1
Router1(config)#ip domain-name soulsphere.net
Router1(config)#crypto key generate rsa
The name for the keys will be: Router1.soulsphere.net
Choose the size of the key modulus in the range of 360 to 2048 for your
General Purpose Keys. Choosing a key modulus greater than 512 may take
a few minutes.

How many bits in the modulus [512]: 1024
Generating RSA keys ...
[OK]

Router1(config)#
Jun 27 15:04:15: %SSH-5-ENABLED: SSH 1.5 has been enabled
Router1(config)#ip ssh time-out 120
Router1(config)#ip ssh authentication-retries 4
Router1(config)#end
Router1#

SSH became available in Cisco's IOS, starting with release 12.1(1)T. However, only versions of IOS that support IPSec (DES or 3DES) encryption include SSH support.

If you're working with version 2 of SSH which is far more secure, you can switch the service to work only on version 2:

Router1(config)#ip ssh version 2

Saturday, September 26, 2009

Howto - Create new startup script.

Ok, this is pretty trivial but yet very important.

You're working under run-level 3 and you wish to execute a a super duper startup script - located under:/usr/local/bin/startup.sh, each time system enters run-level 3.
Let's see how it's done:
1.First of all chmod 700 /usr/local/bin/startup.sh (security reasons..).

2.Next, change directory to:
cd /etc/init.d/rc3.d/

3.From here we will create a symbolic link to the real location of the script:
ln -s /usr/local/bin/startup.sh S99startup.sh

The S99 prefix, S=start ,99=startup sequence (last one).
From now every time user enters run-level 3 the startup.sh script will run.

Compiling a Linux Kernel

In this article I will demonstrate how to compile a Linux kernel from source step by step, let's get busy ;)

1.The most recent Linux kernel source can be obtained from:http://www.kernel.org/.

The file comes as a .bz2 compressed file, so after you finish the download extract it with:
tar xvjf linux-2.6.31.1.tar.bz2 -C /usr/src

*important notice:before you begin compiling the kernel make sure your partition has plenty of free space allocated, the procedure may consume couple of gigs, so if you run out of space during the compiling procedure - the procedure will fail ,so if your /usr/src/x will be on your root partition please check it with df -h.

2. Make sure you have most recent gcc & ncurses develpoment tools installed, if you are using Debian based distro:
apt-get gcc install
apt-get install libncurses5-dev


Red Hat/Fedora users:
yum install gcc
yum install ncurses-devel

Suse users:
yast -i gcc
yast -i ncurses-devel

3. Switch to the extracted kernel's directory:

cd /usr/src/linux-2.6.31.1


I suggest running:
make mrproper

This will remove temporary files & leftovers from the source tree.


It's time to configure the features of your kernel, with the following 3 tools you can include/exclude certain modules from you kernel and build it from scratch, the tools are:

* make config -
This is a text-based tool that you step through to configure kernel options one by one. It is no longer recommended because the kernel provies so many options, and the interface involves simply stepping one by one through them tediously. However, make config is a standard tool and is provided with all Linux distributions

* make menuconfig -
The second type of make method is make menuconfig. It gives you a graphical menu-based display without requiring you to use the X Window System. When you use make menuconfig, you are presented with a directory tree menu system. Following each selection, you are presented with the available options. To include an option, use the y key; to exclude it, use the n key; and to include it as a module, use the m key. Letters that are highlighted are considered hotkeys and allow you to quickly maneuver through the menu options. To exit a window, select the Exit option, or press the Esc key twice.

* make xconfig -
The third type of make method is make xconfig. This method is very popular among new Linux users and users who are accustomed to graphical interface tools. The make xconfig tool requires X Window System support. When starting make xconfig, you are presented with a window with buttons for each class of configuration. Pressing a configuration button, you are prompted, in a tree style, the options available. You can then select, deselect, or modularize each option by pressing the corresponding button next to the item. One of the benefits of using this configuration method over the standard make config method is the backward mobility of the configuration. This means that if you change your mind, or make a mistake, you can move back and change the option in make xconfig.
 

When you're done setting the configuration of your brand new kernel the configuration will be stored inside  .config

4. It's time to compile the kernel but before that, we want to remove any irrelevant dependencies:

make clean

Ok, you are ready for the compilation, issue the next command:

make bzImage

This will build the kernel boot image ,it may take pretty long time, so be patient . The bzImage kernel image is not restricted to 520 KB or even 640 KB (unlike zImage). The bzImage is now the preferred boot image.
The resulting kernel image will be under "arch/x86/boot/bzImage"

5.
When the build of the boot image is done run:

make modules


Modules are parts of the kernel that are loaded on the fly, as they are needed. They are stored in individual files (e.g. ext3.o). The more modules you have, the longer this will take to compile, once again be patient.

6.It's time to install the modules:

make modules_install

This will copy all the modules to a new directory, "/lib/modules/a.b.c" where a.b.c is the kernel version.

7. now, you're left with 2 options - you can either run:
make install  (this will automatically copy the new image to /boot partition,create initrd image there and update your boot loader).

or you can set this manually (less recommended, as there is a good chance you will miss something):

*copy your bzImage file to the /boot partition and give it a uniqe name such as:

cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.31.1
cp System.map /boot/System.map-2.6.31.1


*create and initrd image with: mkinitrd -v /boot/initrd-2.6.31.1

*update the boot loader configuration file, a good chance you're using GRUB with your distro as a default boot loader, in that case you will need to edit /boot/grub/menu.lst

and add another instance for the new kernel, this will look something like this:


title Test Kernel (2.6.31.1)
root (hd0,1) kernel /boot/bzImage-2.6.31.1 ro root=LABEL=/
initrd /boot/initrd-2.6.31.1.img


That's it, you're done - now reboot your machine and when the GRUB menu comes up try booting up to the new kernel image.

Monday, September 14, 2009

Howto access contents of Linux ramdisk (initrd)

initrd - is a contraction of "initial ram disk." This initrd image is used by the kernel to load drivers before it starts booting. The purpose of this is to let users build modularized kernels that do not contain support for all 40 different SCSI controllers (for example) and still are able to boot from any SCSI hardware. In this case, the initrd image would contain the needed SCSI drivers and any other drivers needed to get the kernel off the ground.

In order to access it's contents we should follow the following steps:
cp /boot/initrd /tmp/initrd.gz
gzip /tmp/initrd.gz
mount /tmp/initrd /mnt -o loop

Monday, September 7, 2009

Mount ISO Image under Linux

Sometimes for various reasons we wish to mount ISO directly from the OS, in Linux the process is really simple and doesn't require any 3rd party tool like Window's "Daemon Tools" or "Alcohol"...
Lets see how it's done in 4 easy steps:

1)First become root:

#su -

2)Next, create the folder where the ISO will be extracted:
#mkdir /mnt/iso

3)Mount the ISO with:

mount -o loop CentOS-5.5-x86_64-bin-DVD-1of2.iso /mnt/iso/


4)Browse to folder:
#ls -F /mnt/iso

Quick & Easy!
Enjoy ;)

Saturday, August 15, 2009

Quick and easy GPG


GPG is a nice security feature which enables us to encrypt /decrypt our valuable info.
It's widely spread amongst the *nix community since it's a great tool to make sure your valuable data will remain untouched.

Usage:

(Symmetric authentication):
gpg -c filename
will encrypt the filename, you will be asked for a passphrase, eventually a new filename.gpg will be created - this is you encrypted file and it's ready to be sent.

gpg filename.gpg
will decrypt the file, via the same passphrase (symetric authentication) - preety simple.

(Asymmetric authentication):
You will need to generate a public and a private keys, to do so run:

$ gpg --gen-key


This will generate a pair of keys, during the process you will be asked for couple of questions such as your name, your e-mail etc.. eventually the keys will be stored in the ~/.gnupg directory. Once you’ve generated your keys, you can export your public key to some file:

$ gpg --export name > gpg.pub

Adding the --armor option produces ASCII output, which may be preferable if you intend
to e‑mail the public key. You can make the file accessible on your Web site, transfer it as an
e‑mail attachment, or distribute it in various other ways.
To encrypt e‑mail you send to others, you must obtain their public keys. Ask your
fellas how to obtain them. Once you’ve done so, you can add their keys to
your key database (that is, the set of keys GPG maintains):

$ gpg --import some_ones_public_key.pub

This command adds some_ones_public_key.pub to your set of public keys belonging to other people.

You can use:
$ gpg --list-keys to see list of keys.

To encrypt data, you use gpg with its --out and --encrypt options:

$ gpg --out encrypted-file --recipient uid --armor --encrypt original-file

The --recipient and --armor are optional but good options if you intend to transfer this data by mail.
If you receive a message or file that was encrypted with your public key, you can reverse
the encryption by using the --decrypt option:

$ gpg --out decrypted-file --decrypt encrypted-file


You’ll be asked to enter your passphrase. The result should be a decrypted version of the
original file.

GPG can be used to sign messages so that recipients know they come from
you. To do so, use the --sign or --clearsign option to gpg:

$ gpg --clearsign original-file


If you receive a signed message, you can verify the signature using the --verify option
to gpg:

$ gpg --verify received-file

Friday, August 7, 2009

Using the "at" command

At is a nice command that resembles crontab, but more straightforward.
Suppose you need to run a command once, at a pre-determined time, it's ideal to use "at".
Verify atd deamon is running:
chkconfig --list | grep atd
atd 0:off 1:off 2:off 3:on 4:on 5:on 6:off

Here are couple of examples:
at 1:00 am tomorrow my_cron_script.sh
at -m 10:20 at -f my_cron_script 2:00 july 11


You can use "atq" to view your que:
paul@machine2 ~]$ atq
16 Wed Jul 11 02:00:00 2007 a paul
17 Sat Jul 14 02:00:00 2007 a paul
14 Sun Jul 8 22:00:00 2007 a paul
15 Tue Jul 10 02:00:00 2007 a paul

Your can use atrm, to remove undesired jobs in que:

[paul@machine2 ~]$ atrm 16 14 15

Pay attention that the undesired jobs are gone now:
[paul@machine2 ~]$ atq
17 Sat Jul 14 02:00:00 2007 a paul

The at command can always be issued by a privileged user.
Other users must be listed in the file /etc/at.allow if it exists;
otherwise, they must not be listed in /etc/at.deny.
If neither file exists, only a privileged user can issue the command.

Thursday, July 2, 2009

The Linux Superblock


So what is a Superblock? Let's try to understand...

When you create a file system on a hard drive it will be sub devided into multiple file system blocks. These blocks are used for two purposes:

1. To store user data (Main usage)
2. Some blocks used for to store file system's metadata.

The metadata contains data about your file system, ie: superblock, inodes, usage, status and more. Therefore a superblock is one of the core elements of the filesystems metadata.

Each linux filesystem (ext2,ext3,ext4,reiserfs...) has a superblock.
As we can see with dumpe2fs (which used to querry ext filesystems) command there are multiple superblocks on the filesystem, one primary and couple of backups.

This is how it looks on my Linux system:

$dumpe2fs /dev/hda6 grep -i | superblock

Primary superblock at 1, Group descriptors at 2-2

Backup superblock at 8193, Group descriptors at 8194-8194
Backup superblock at 24577, Group descriptors at 24578-24578
Backup superblock at 40961, Group descriptors at 40962-40962
Backup superblock at 57345, Group descriptors at 57346-57346
Backup superblock at 73729, Group descriptors at 73730-73730

A Superblock contains information about the file system like -

* File system type
* Size
* Status
* Information about other metadata

It is critical and may cause severe problems when it's corrupted.
When superblock is corruped we will not able to run command like:

$e2fsck -f /dev/hda2

The system will prompt for error on superblock, a handful option will be replacement of the damaged superblock with a backup one, to do so we will have to determine the number of sector which the backup superblock resides:

Backup superblock at 8193, Group descriptors at 8194-8194

After we verified the sector, we can tell the filesystem to use the alternative superblock instead of the damaged one:

$e2fsck -f -b 8193 /dev/hda6


Wednesday, June 10, 2009

Couple of good tricks with SED

I've gathered couple of sed examples I find myself using again and again.

Replace instances in string "foo" with "bar" in a file:
#sed -i 's/foo/bar/g' file.txt


Delete blank lines from the document 'grep1.txt' and creates 'sed1.txt'
#sed -e '/^$/d' grep1.txt > sed1.txt

Remove a trailing character:
#sed 's/.$//'


Print all text after certain string:
#cat Document|sed '/STRING/,// !d'


Comment out lines containing "console output" string:
#sed -i 's/^\(console output\)$/#\1/1' file.txt

Delete all blank spaces until first character on each line:
#sed -e 's/^[ \t]*//' file.txt

Friday, May 22, 2009

Secure your browsing with SSH

If security concerns you and you have an SSH client on your laptop, and a reachable SSH server that has access to the web here is a great way of securing your traffic.

This method is very useful especially when surfing on public/unsecured WLANs and will make sure your http traffic is encrypted so some bad guy with a sniffer program cannot read your data.

Please note: that this will only encrypt your data from you to the server you will be forwarding the traffic to, from there to the internet the data will be again unsecured.

From your station run:

$ssh -DN 9999 username@ip-address-of-ssh-server





The -N option tells SSH server side not to open for prompt (this is available on SSH version 2 and later).
The -D options tells SSH to listen on a specific port (9999) and forward the traffic to our server.

This will create a SOCKS proxy on your station.
Next open your browser and set a proxy for: localhost:9999


That's it! From now on the traffic between you and SSH server will be encrypted, so no one on your LAN will be able to decrypt/listen to your valuable traffic.

Thursday, May 14, 2009

Adding another HD on Linux / Unix machine

Have you decided to add another HD to your Linux machine?
This guide will help you understand the procedure step by step.
Let's get started.

First after physical installation and basic BIOS check of the device you would like to see if the OS has recognized the disk.

To see attached SCSI devices,  execute:

[root@jenova media]# lsscsi

You should see the new disk on the next SCSI channel.

To check the disk exists on the system run:
[root@jenova media]#fdisk -l

Next we will run:
[root@jenova media]# fdisk /dev/sdb 

Command action
a   toggle a bootable flag
b   edit bsd disklabel
c   toggle the dos compatibility flag
d   delete a partition
l   list known partition types
m   print this menu
n   add a new partition
o   create a new empty DOS partition table
p   print the partition table
q   quit without saving changes
s   create a new empty Sun disklabel
t   change a partition's system id
u   change display/entry units
v   verify the partition table
w   write table to disk and exit
x   extra functionality (experts only)


If you issue the p command, you will see any partitions that
currently exist on the drive.
You can see by the output above there are
no existing partitions. This drive is un-partitionedd
and unformatted. 
To create a new partition, use the n command.
 
Command (m for help): p

Disk /dev/sdb: 50.0 GB, 50019202560 bytes
255 heads, 63 sectors/track, 6081 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot    Start       End    Blocks   Id  System

Command (m for help): n
Command action
e   extended
p   primary partition (1-4)

Partition number (1-4): 1
First cylinder (1-6081, default 1): 1
Last cylinder or +size or +sizeM or +sizeK (1-6081, default 6081): 6081
 
We can check the partition specifications we just entered
by using the p command again.

Command (m for help): p

Disk /dev/sdb: 50.0 GB, 50019202560 bytes
255 heads, 63 sectors/track, 6081 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot    Start       End    Blocks   Id  System
/dev/sdb1             1      6081  48845601   83  Linux


 
If you messed anything up, you can use the d command
and specify which partition you want to delete.


Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

Now that the partition has been created, you need to format
the drive. The most common Linux formats are ext2 and ext3.
You must specify which partition to format by calling the device
and partition number:

[root@jenova root]# mkfs -t ext3 /dev/sdb1
mke2fs 1.32 (09-Nov-2002)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
6111232 inodes, 12211400 blocks
610570 blocks (5.00%) reserved for the super user
First data block=0
373 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624, 11239424

Writing inode tables: done                      
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 38 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

In order to automatically mount a partition, you must edit the /etc/fstab file.
The fstab file tells Linux where to mount all partitions located within the system.

[root@roswell root]# vi /etc/fstab


We will mount the new partition as /media. Remember to create a directory named media, otherwise /etc/fstab won't be able to mount the partition.

The following line will be added to /etc/fstab:
 
/dev/sdb1   /media  ext3   defaults   1 2

Next, issue a simple mount command providing the partition name:

[root@jenova]# mount /dev/sdb1 /media


You're all done! You will be able to access the /media folder immediately and after the machine reboots as fstab will automatically re-mount it for you. If you want to verify the partition is successfully present and mounted, use the following commands:

[root@jenova media]# mount


/dev/sda1 on / type ext3 (rw)
none on /proc type proc (rw)
none on /dev/pts type devpts (rw,gid=5,mode=620)
usbdevfs on /proc/bus/usb type usbdevfs (rw)
/dev/sda2 on /boot type ext3 (rw)
/dev/sdc1 on /export type ext3 (rw)
none on /dev/shm type tmpfs (rw)
/dev/sdb1 on /media type ext3 (rw)

The red line shows our new drive freshly mounted.
You can check the space usage if you issue the following command.

[root@jenova media]# df -h


Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1             8.3G  2.4G  5.5G  30% /
/dev/sda2              99M   26M   69M  27% /boot
/dev/sdc1              16G   13G  2.3G  85% /export
none                  250M     0  250M   0% /dev/shm
/dev/sdb1              46G   33M   44G   1% /media

Sunday, April 26, 2009

BASH - Check if input is IP address

A little script I wrote, will help you determine wether the input is a legal IPv4 IP address:

#!/bin/bash
#
#Written by:Paul Podolny 26.4.2009
#Purpose: The script checks a passed IPv4 IP address and determines it's class.



#Check that input is passed in the form of IPv4 IP address
if [ ! "$(echo $1 | grep '[0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}')" ]
then
echo "Usage: '$0' "
exit 1
fi

DOTSCHK=`echo $1 | awk '{gsub("[0-9]","");print}' | wc -c`
if [ $DOTSCHK -ne 4 ];then
echo "illegal input"
exit 1
fi


for n in $(seq 1 4);do

OCTET=`echo $1 | awk -F "." '{print $'$n'}'`
if [ $OCTET -lt 0 -o $OCTET -gt 255 ]; then #check if the octet range is between 0 & 255
echo "$1 is not legal IP address"
exit 1
fi
done

echo "$1 is legal IP address"


#Check wether IP is external or internal + determines it's class.
case $1 in

192.168.*.*)
echo "$1 is class C internal IP address"
;;

172.*.*.*)
SCND=`echo $1 | awk -F "." '{print $2}'`
if [ $SCND -ge 16 -a $SCND -le 31 ];then
echo "$1 is class B internal IP address"
fi
;;

10.*.*.*)
echo "$1 is class A internal IP address"
;;

169.254.*.*)
echo "$1 is an APIPA IP address"
;;

*)
echo "$1 is an external IP address"
;;
esac

Sunday, April 5, 2009

Securing GRUB Boot Loader

Lots of us tend to think that Linux OS is secure, in fact it's an illusion that comes due to a fact that less home users use it therefore less hack tool are available for an average home user.
We forget some dominant backdoors that can cause serious trouble & malicious activity on sensitive servers.
One of these "backdoors" is leaving a boot loader unsecured. Don't forget that it's extremely easy to recover root password in linux, watch and see for yourselves (I used Red Hat Enterprise 5 for the example).

First of all we will reboot the server, and wait until GRUB boot loader comes up, press (esc) to pause the countdown:
We will highlight the Linux version and press 'e' for 'edit' this will bring us to a line with the
Kernel version, we will select 'e' again and we will be able to edit the line:
in the end of the line, after "rhgb quiet" we will add "single":


The machine will boot now in single mode, the shell will be the root shell so all that's left is
type passwd and hola, we obtained the root password.

Easy huh? To prevent such scenarios, linux includes a nice feature called grub-crypt.
(found in /sbin/grub-md5-crypt)
When we will run it, a key will be generated for us (depending on the password we passed). For those who are not familiar with cryptography md5 is a wi
dely used cryptographic function with a 128bit strength hash value.

All that's left now is to add the generated key to /etc/inittab file in the following syntax:
password --md5 :generated hash key:
that's it, save the file and reboot. Now if we try to edit GRUB boot loader we will be asked to authenticate:



Note that after the hash has been set into the /etc/inittab file it cannot be seen, so it's another cool security feature.

Have fun and stay secured ;)

Friday, April 3, 2009

Random password generator

A little handy script that will help you generate random passwords:

#!/bin/bash

#Written by Paul.P - 2.4.2009
#The script generates a random password, argument $1 sets password length

clear

#If no argument passed - default length of 12 will be used

length=$1

[ -n "$length" ] || length=12;echo "no arguments passed, using default length (12)"

#Strength check
if [ "$length" -lt 8 ];then
echo "the password of $length characters length is not strong enough."
exit 1
fi

password=$(dd if=/dev/urandom bs=512 count=1 2> /dev/null | tr -cd 'a-zA-Z0-9' \
| cut -c 1-$length)
echo "$password"

Wednesday, March 25, 2009

Using SSH,SCP & SFTP without passwords

SSH is commonly used protocol which allows you secure connectivity and wide spectrum of utilities & features.
For machines that you use alot it's often helpful to set them up so you don't have to use password(s) to log-in. Here is a procedure that shows how to do that step by step:

in the example we will use 2 hosts - host1 ( the local) host2 (the remote)

1-log in to the local machine (I logged in as adams to host1)
2-type the following to generate SSH key:

ssh-keygen -t dsa


Generating public/private dsa key pair.
Enter file in which to save the key (/adams/.ssh/id_dsa): /adams/.ssh/id_dsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
5b:1f:98:44:5f:10:b2:69:d1:27:c1:4d:d9:24:de:db adams@host1

3-you must secure the permissions of your authentication keys by closing permissions to your $HOME directory, .ssh directory and authentication files:

chmod go-w $HOME
chmod 700 $HOME/.ssh
chmod go-rwx $HOME/.ssh/*

4-type the following to copy the key to the remote server (replace adams with host2 username)

cd ~/.ssh
scp id_dsa.pub adams@host2:/tmp

you'll be prompted for password (that's OK)
adams@hosts2's password: ******

5-type the following to add the ssh key to the remote users authentication keys:

ssh adams@host2 'cat /tmp/id_dsa.pub >> /home/adams/.ssh/authorized_keys2'

6-for the sshd deamon to accept authorized_keys2 file - your $HOME dir and that file itself must have secure permisssions:

ssh adams@host2 chmod go-w $HOME $HOME/.ssh
ssh adams@host2 chmod 600 $HOME/.ssh/authorized_keys2

finally, remove the key from the /tmp dir:

ssh adams@host2 rm -rf /tmp/id_dsa.pub

that's it - from now on you shouldn't be asked for password every time you use ssh to host2.

Saturday, March 21, 2009

Usefull tricks with "dd"

1) create an iso file on a remote machine from a dvd in your station:

dd if=/dev/cdrom | ssh server1 'dd of=/tmp/iso/vmware.iso'



2)
copy the Linux MBR:
dd if=/dev/hda of=hda.mbr bs=512 count=1


3)Create compressed image of a drive :

dd if=/dev/hda1 bs=1M count=150 | gzip > hda1-image.gz

*you should know the size of the partition you're about to compress - use df -h for that.
also replace the "150" with the number of used megabytes on the partition.

4)Wipe a disk from Linux

dd bs=1048576 if=/dev/zero of=/dev/hda

Thursday, February 19, 2009

AWK - Replacing Strings in columns

Say we have a hosts file map on a NIS based network (or even a simple hosts file for a sake of simplicity) the network department decided to change one of the VLANS (for example from 100 to 200) as part of some infrastructure organizational change. We have thousands of entries that require update:

the host file looks like this:

10.100.5.1 server1.domain.com server1
10.100.5.2 server2.domain.com server2
10.100.5.3 server3.domain.com server3

awk '{gsub("100","200");print}' /etc/hosts

awk will acomplish this task as a charm, simple - yet very powerful editor.