Thursday, August 28, 2014

How to install Cisco VPN client on Ubuntu

This tutorial shows you how to install Cisco VPN on Ubuntu 13.04 Raring or 13.10 Saucy. You don’t have to do anything special to install Cisco VPN client, because network manager supports Cisco IPSec VPNs after installed the vpnc plugin.

To get started, search for and install network-manager-vpnc package from Ubuntu Software Center. It installs the Cisco-compatible VPN client as well as the plugin for network manager.

Cisco VPN for network manager

Once installed, you can follow below steps to setup Cisco VPN for Ubuntu:

1.) Move your cursor to right-top corner system tray area, click on Network Manager icon and choose VPN Connections -> Configure VPN

setup Cisco VPN for Ubuntu

2.) In next window, click on Add button to add a new connection and then choose Cisco Compatible VPN (vpnc) from the drop-down menu.

setup cisco vpn connection

3.) Click on Create and you’re able to type in your Cisco VPN details in next window. After all, check off “Use this connection only for resources on its network” otherwise your traffic significantly slowed down

configure cisco vpn connection

Tuesday, August 12, 2014

Security Tip: Disable Root SSH Login on Linux

One of the biggest security holes you could open on your server is to allow directly logging in as root through ssh, because any cracker can attempt to brute force your root password and potentially get access to your system if they can figure out your password.

It’s much better to have a separate account that you regularly use and simply sudo to root when necessary. Before we begin, you should make sure that you have a regular user account and that you can su or sudo to root from it.
To fix this problem, we’ll need to edit the sshd_config file, which is the main configuration file for the sshd service. The location will sometimes be different, but it’s usually in /etc/ssh/. Open the file up while logged on as root.
vi /etc/ssh/sshd_config
Find this section in the file, containing the line with “PermitRootLogin” in it.
#LoginGraceTime 2m
#PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6

Make the line look like this to disable logging in through ssh as root.

PermitRootLogin no
Now you’ll need to restart the sshd service:

/etc/init.d/sshd restart
Now nobody can brute force your root login, at least.

Thursday, May 8, 2014

Installing Guest additions from the repositories

In case we have installed the OSE edition of Virtual Box from the repositories we can add the guest additions from the repositories.

Install the package virtualbox-guest-additions-iso Install virtualbox-guest-additions-iso in the host Ubuntu. The .iso file with an image of the OSE edition of the guest additions CD will install in the host directory /usr/share/virtualbox/VBoxGuestAdditions.iso. Mount this .iso file as a CD in your virtual machine's settings. In the guest you will then have access to a CD-ROM with the installer.

Installing Guest Additions from Virtual Box Manager

In case the Guest Additions fail to build we may have to install the Linux kernel headers (see How do I install kernel header files?) or build-essential Install build-essential tools in addition. It is also recommended to have dkms Install dkms installed
(see below - Note 4).

Selecting Devices -> Install Guest Additions (or press Host+D from the Virtual Box Manager) the Guest Additions CD .iso will be loaded but not installed in your guest OS. To install we need to run the installer script VBoxLinuxAdditions.run as root or from the Autorun Prompt (see below),

GNOME classic

To install the Guest Additions we will have a CD icon on our desktop as soon as the virtual drive is mounted:

alt text

Next step is to run the autorun.sh script (as root) on this mounted CD either by opening the drive or by choosing "Open With Autorun Prompt" from the right-click context menu as depicted above. This will build and install the vbox kernel modules needed

Unity

The guest additions is mounted as a virtual CD visible on the launcher:
enter image description here
In case the system is set up to autorun a CD it should just open the following autorun dialogue (if not select the CD symbol, choose open, then choose Open Autorun Prompt)

enter image description here

After having entered your credentials for root access the guest additions will build as seen from the terminal output:

enter image description here
Press Return to close the terminal.
Note 1
Guest Additions need a reboot of your guest OS to take effect.

Note 2
In some systems the Virtual Box Guest Additions CD icon may not be shown on the desktop, but will be accessible from the Places menu. If the CD still was not there you may have to manually add the VBoxGuestAdditions.iso as a CD-ROM in the Virtual Box Manager Storage menu. In an Ubuntu host the disk image is in /usr/share/virtualbox/VBoxGuestAdditions.iso.
Note 3
In some systems (e.g. when running Xubuntu guests) we may not have an Autorun Prompt for the mounted CD. Then we can install the guest additions by opening a terminal on the mounted guest additions .iso to run sudo ./VBoxLinuxAdditions.run. In Lubuntu guests we additionally need to install the GNU C compiler (gcc Install gcc) and the make Install make utility in the guest system to be able to compile the guest additions.
Note 4
Running DKMS in the guest OS will keep Guest Additions installed after a guest kernel update. It is not a prerequisite for Guest Additions but if used it should be installed before we install the Guest Additions.

Installing Guest Additions from a Terminal

In case Guest Additions are not installed properly we may not be able to boot to the GUI. In this case we need to boot holding the Shift key to access the Grub menu where we access a root shell as depicted in the following question (we do need to mount the filesystem read/write to proceed):
The Guest Additions .iso file needs to be installed on /dev/cdrom from the Virtual Box Manager (see above). We then may install Guest Additions by typing the following commands:
mount /dev/cdrom /mnt              # or any other mountpoint
cd /mnt
./VBoxLinuxAdditions.run
reboot

Remove Guest Additions

In case something went wrong with installing the guest additions, or the guest OS can not boot after installing we may have to remove the additions. This can be done by running an uninstallation script located in the guest /opt directory.
cd /opt/<VirtualBoxAdditions-x.x.xx>/
sudo ./uninstall.sh
Replace x.x.xx with your current version of guest additions.

Monday, April 28, 2014

ASCII Art for your SSH logins

Here is a nice way to spice up your SSH logins.
To create a cool ASCII art banner for your server, first start off by going here:

http://www.network-science.de/ascii/

Type your server name into the text field. On the font choice, select “_all fonts with your text_”. Click OK to generate the ASCII art. Copy the one you like into the clipboard.

On your server, paste this into the file /etc/banner

Edit /etc/ssh/sshd_config and change the “Banner” directive to
“Banner /etc/banner”

Restart SSH

Screen Command Examples to Manage Linux Terminals

Screen is a full-screen software program that can be used to multiplexes a physical console between several processes (typically interactive shells). It offers a user to open several separate terminal instances inside a one single terminal window manager.
The screen application is very useful, if you are dealing with multiple programs from a command line interface and for separating programs from the terminal shell. It also allows you to share your sessions with others users and detach/attach terminal sessions.
 
 
Screen Command Examples

On my Ubuntu 10.04 Server Edition, Screen has been installed by default. But, in Linux Mint does not have screen installed by default, I need to install it first using apt-get command before using it. Please follow your distribution installation procedure to install screen.
 
# apt-get install screen (On Debian based Systems)
# yum install screen (On RedHat based Systems)

Actually, Screen is a very good command in Linux which is hidden inside hundreds of Linux commands. Let’s start to see the function of Screen.

Start screen for the first time

Just type screen at the command prompt. Then the screen will show with interface exactly as the command prompt.
 
pungki@mint ~ $ screen

Show screen parameter

When you enter the screen, you can do all your work as you are in the normal CLI environment. But since the screen is an application, so it have command or parameters.
Type “Ctrl-A” and “?” without quotes. Then you will see all commands or parameters on screen.
 Screen key bindings, page 1 of 1.
 Command key:  ^A   Literal ^A:  a

  break       ^B b         flow        ^F f         lockscreen  ^X x         pow_break   B            screen      ^C c         width       W
  clear       C            focus       ^I           log         H            pow_detach  D            select      '            windows     ^W w
  colon       :            hardcopy    h            login       L            prev        ^H ^P p ^?   silence     _            wrap        ^R r
  copy        ^[ [         help        ?            meta        a            quit        \            split       S            writebuf    >
  detach      ^D d         history     { }          monitor     M            readbuf     <            suspend     ^Z z         xoff        ^S s
  digraph     ^V           info        i            next        ^@ ^N sp n   redisplay   ^L l         time        ^T t         xon         ^Q q
  displays    *            kill        K k          number      N            remove      X            title       A
  dumptermcap .            lastmsg     ^M m         only        Q            removebuf   =            vbell       ^G
  fit         F            license     ,            other       ^A           reset       Z            version     v

^]  paste .
"   windowlist -b
-   select -
0   select 0
1   select 1
2   select 2
3   select 3
4   select 4
5   select 5
6   select 6
7   select 7
8   select 8
9   select 9
I   login on
O   login off
]   paste .

To get out of the help screen, you can press “space-bar” button or “Enter“. (Please note that all shortcuts which use “Ctrl-A” is done without quotes).

Detach the screen

One of the advantages of screen that is you can detach it. Then, you can restore it without losing anything you have done on the screen. Here’s the sample scenario:

You are in the middle of SSH-on your server. Let’s say that you are downloading 400MB patch for your system using wget command.

The download process is estimated to take 2 hours long. If you disconnect the SSH session, or suddenly the connection lost by accident, then the download process will stop. You have to start from the beginning again. To avoid that, we can use screen and detach it.

Take a look at this command. First, you have to enter the screen.
 
pungki@mint ~ $ screen

Then you can do the download process. For examples on my Linux Mint, I am upgrading my dpkg package using apt-get command.
 
pungki@mint ~ $ sudo apt-get install dpkg
Sample Output
Reading package lists... Done
Building dependency tree      
Reading state information... Done
The following packages will be upgraded:
  dpkg
1 upgraded, 0 newly installed, 0 to remove and 1146 not upgraded.
Need to get 2,583 kB of archives.
After this operation, 127 kB of additional disk space will be used.
Get:1 http://debian.linuxmint.com/latest/ testing/main dpkg i386 1.16.10 [2,583 kB]
47% [1 dpkg 1,625 kB/2,583 kB 47%]                                        14,7 kB/s

While downloading in progress, you can press “Ctrl-A” and “d“. You will not see anything when you press those buttons. The output will be like this:
 
[detached from 5561.pts-0.mint]
pungki@mint ~ $

Re-attach the screen

After you detach the screen, let say you are disconnecting your SSH session and going home. In your home, you start to SSH again to your server and you want to see the progress of your download process. To do that, you need to restore the screen. You can run this command:
 
pungki@mint ~ $ screen -r

And you will see that the process you left is still running.
When you have more than 1 screen session, you need to type the screen session ID. Use screen -ls to see how many screen are available.
 
pungki@mint ~ $ screen -ls
Sample Output
pungki@mint ~ $ screen -ls
There are screens on:
        7849.pts-0.mint (10/06/2013 01:50:45 PM)        (Detached)
        5561.pts-0.mint (10/06/2013 11:12:05 AM)        (Detached)
2 Sockets in /var/run/screen/S-pungki

If you want to restore screen 7849.pts-0.mint, then type this command.
pungki@mint ~ $ screen -r 7849

Using Multiple Screen

When you need more than 1 screen to do your job, is it possible? Yes it is. You can run multiple screen window at the same time. There are 2 (two) ways to do it.

First, you can detach the first screen and the run another screen on the real terminal. Second, you do nested screen.

Switching between screens

When you do nested screen, you can switch between screen using command “Ctrl-A” and “n“. It will be move to the next screen. When you need to go to the previous screen, just press “Ctrl-A” and “p“.
To create a new screen window, just press “Ctrl-A” and “c“.

Logging whatever you do

Sometimes it is important to record what you have done while you are in the console. Let say you are a Linux Administrator who manage a lot of Linux servers.

With this screen logging, you don’t need to write down every single command that you have done. To activate screen logging function, just press “Ctrl-A” and “H“. (Please be careful, we use capital ‘H’ letter. Using non capital ‘h’, will only create a screenshot of screen in another file named hardcopy).

At the bottom left of the screen, there will be a notification that tells you like: Creating logfile “screenlog.0“. You will find screenlog.0 file in your home directory.

This feature will append everything you do while you are in the screen window. To close screen to log running activity, press “Ctrl-A” and “H” again.
Another way to activate logging feature, you can add the parameter “-L” when the first time running screen. The command will be like this.
 
pungki@mint ~ $ screen -L

Lock screen

Screen also have shortcut to lock the screen. You can press “Ctrl-A” and “x” shortcut to lock the screen. This is handy if you want to lock your screen quickly. Here’s a sample output of lock screen after you press the shortcut.
 
Screen used by Pungki Arianto  on mint.
Password:

You can use your Linux password to unlock it.

Add password to lock screen

For security reason, you may want to put the password to your screen session. A Password will be asked whenever you want to re-attach the screen. This password is different with Lock Screen mechanism above.

To make your screen password protected, you can edit “$HOME/.screenrc” file. If the file doesn’t exist, you can create it manually. The syntax will be like this.
 
password crypt_password

To create “crypt_password” above, you can use “mkpasswd” command on Linux. Here’s the command with password “pungki123“.
 
pungki@mint ~ $ mkpasswd pungki123
l2BIBzvIeQNOs

mkpasswd will generate a hash password as shown above. Once you get the hash password, you can copy it into your “.screenrc” file and save it. So the “.screenrc” file will be like this.
 
password l2BIBzvIeQNOs

Next time you run screen and detach it, password will be asked when you try to re-attach it, as shown below:
 
pungki@mint ~ $ screen -r 5741
Screen password:

Type your password, which is “pungki123” and the screen will re-attach again.

After you implement this screen password and you press “Ctrl-A” and “x” , then the output will be like this.
 
Screen used by Pungki Arianto  on mint.
Password:
Screen password:

A Password will be asked to you twice. First password is your Linux password, and the second password is the password that you put in your .screenrc file.

Leaving Screen

There are 2 (two) ways to leaving the screen. First, we are using “Ctrl-A” and “d” to detach the screen. Second, we can use the exit command to terminating screen. You also can use “Ctrl-A” and “K” to kill the screen.

That’s some of screen usage on daily basis. There are still a lot of features inside the screen command. You may see screen man page for more detail.

Linux Netcat NC Command Examples

Netcat or nc is a networking utility for debugging and investigating the network.
This utility can be used for creating TCP/UDP connections and investigating them. The biggest use of this utility is in the scripts where we need to deal with TCP/UDP sockets.

In this article we will learn about the netcat command by some practical examples.

1. Netcat in a Server-Client Architecture

The netcat utility can be run in the server mode on a specified port listening for incoming connections.

$ nc -l 2389
 
Also, it can be used in client mode trying to connect on the port(2389) just opened

$ nc localhost 2389
 
Now, if we write some text at the client side, it reaches the server side. Here is the proof :

$ nc localhost 2389
HI, server
 
On the terminal where server is running :
 
$ nc -l 2389
HI, server

So we see that netcat utility can be used in the client server socket communication.

2. Use Netcat to Transfer Files

The netcat utility can also be used to transfer files. At the client side, suppose we have a file named ‘testfile’ containing :
 
$ cat testfile
hello test

and at the server side we have an empty file ‘test’
Now, we run the server as :
 
$ nc -l 2389 > test

and run the client as :
 
cat testfile | nc localhost 2389

Now, when we see the ‘test’ file at the server end, we see :
 
$ cat test
hello test

So we see that the file data was transfered from client to server.

3. Netcat Supports Timeouts

There are cases when we do not want a connection to remain open forever. In that case, through ‘-w’ switch we can specify the timeout in a connection. So after the seconds specified along with -w flag, the connection between the client and server is terminated.

Server :
nc -l 2389

Client :
$ nc -w 10 localhost 2389

The connection above would be terminated after 10 seconds.

NOTE : Do not use the -w flag with -l flag at the server side as in that case -w flag causes no effect and hence the connection remains open forever.

4. Netcat Supports IPV6 Connectivity

The flag -4 or -6 specifies that netcat utility should use which type of addresses. -4 forces nc to use IPV4 address while -6 forces nc to use IPV6 address.

Server :
$ nc -4 -l 2389

Client :
$ nc -4 localhost 2389

Now, if we run the netstat command, we see :
$ netstat | grep 2389
tcp        0      0 localhost:2389          localhost:50851         ESTABLISHED
tcp        0      0 localhost:50851         localhost:2389          ESTABLISHED

The first field in the above output would contain a postfix ’6′ in case the IPV6 addresses are being used. Since in this case it is not, so a connection between server and client is established using IPV4 addresses.
Now, If we force nc to use IPV6 addresses

Server :
$ nc -6 -l 2389

Client :
$ nc -6 localhost 2389

Now, if we run the netstat command, we see :
$ netstat | grep 2389
tcp6       0      0 localhost:2389          localhost:33234         ESTABLISHED
tcp6       0      0 localhost:33234         localhost:2389          ESTABLISHED

So now a postfix ’6′ with ‘tcp’ shows that nc is now using IPV6 addresses.

5. Disable Reading from STDIN in Netcat

This functionality can be achieved by using the flag -d. In the following example, we used this flag at the client side.

Server :
$ nc -l 2389

Client :
$ nc -d localhost 2389
Hi

The text ‘Hi’ will not be sent to the server end as using -d option the read from stdin has been disabled.

6. Force Netcat Server to Stay Up

If the netcat client is connected to the server and then after sometime the client is disconnected then normally netcat server also terminates.

Server :
$ nc -l 2389

Client :
$ nc localhost 2389
^C

Server :
$ nc -l 2389
$

So, in the above example we see that as soon as the client got disconnected the server was also terminated.

This behavior can be controlled by using the -k flag at the server side to force the server to stay up even after the client has disconnected.

Server :
$ nc -k -l 2389

Client :
$ nc localhost 2389
^C

Server :
$ nc -k -l 2389

So we see that by using the -k option the server remains up even if the client got disconnected.

7. Configure Netcat Client to Stay Up after EOF

Netcat client can be configured to stay up after EOF is received. In a normal scenario, if the nc client receives an EOF character then it terminates immediately but this behavior can also be controlled if the -q flag is used. This flag expects a number which depicts number of seconds to wait before client terminates (after receiving EOF)

Client should be started like :
nc  -q 5  localhost 2389

Now if the client ever receives an EOF then it will wait for 5 seconds before terminating.

8. Use Netcat with UDP Protocol

By default all the sockets that nc utility creates are TCP protocols but this utility also works with UDP protocol. To enable UDP protocol the -u flag is used.

Server :
$ nc -4 -u -l 2389

Client :
$ nc -4 -u localhost 2389

Now, both the server and client are configured to use UDP protocol. This can be confirmed by the following netstat command. So we see that this connection is now using the UDP protocol.
 
$ netstat | grep 2389
udp        0      0 localhost:42634         localhost:2389          ESTABLISHED
 

Monday, April 21, 2014

The Beginner’s Guide to iptables, the Linux Firewall



Iptables is an extremely flexible firewall utility built for Linux operating systems. Whether you’re a novice Linux geek or a system administrator, there’s probably some way that iptables can be a great use to you. Read on as we show you how to configure the most versatile Linux firewall.

About iptables

iptables is a command-line firewall utility that uses policy chains to allow or block traffic. When a connection tries to establish itself on your system, iptables looks for a rule in its list to match it to. If it doesn’t find one, it resorts to the default action.
iptables almost always comes pre-installed on any Linux distribution. To update/install it, just retrieve the iptables package:
sudo apt-get install iptables
There are GUI alternatives to iptables like Firestarter, but iptables isn’t really that hard once you have a few commands down. You want to be extremely careful when configuring iptables rules, particularly if you’re SSH’d into a server, because one wrong command can permanently lock you out until it’s manually fixed at the physical machine.

Types of Chains

iptables uses three different chains: input, forward, and output.

Input – This chain is used to control the behavior for incoming connections. For example, if a user attempts to SSH into your PC/server, iptables will attempt to match the IP address and port to a rule in the input chain.

Forward – This chain is used for incoming connections that aren’t actually being delivered locally. Think of a router – data is always being sent to it but rarely actually destined for the router itself; the data is just forwarded to its target. Unless you’re doing some kind of routing, NATing, or something else on your system that requires forwarding, you won’t even use this chain.
There’s one sure-fire way to check whether or not your system uses/needs the forward chain.
iptables -L -v




The screenshot above is of a server that’s been running for a few weeks and has no restrictions on incoming or outgoing connections. As you can see, the input chain has processed 11GB of packets and the output chain has processed 17GB. The forward chain, on the other hand, has not needed to process a single packet. This is because the server isn’t doing any kind of forwarding or being used as a pass-through device.

Output – This chain is used for outgoing connections. For example, if you try to ping howtogeek.com, iptables will check its output chain to see what the rules are regarding ping and howtogeek.com before making a decision to allow or deny the connection attempt.

The caveat
Even though pinging an external host seems like something that would only need to traverse the output chain, keep in mind that to return the data, the input chain will be used as well. When using iptables to lock down your system, remember that a lot of protocols will require two-way communication, so both the input and output chains will need to be configured properly. SSH is a common protocol that people forget to allow on both chains.

Policy Chain Default Behavior

Before going in and configuring specific rules, you’ll want to decide what you want the default behavior of the three chains to be. In other words, what do you want iptables to do if the connection doesn’t match any existing rules?
To see what your policy chains are currently configured to do with unmatched traffic, run the iptables -L command.



As you can see, we also used the grep command to give us cleaner output. In that screenshot, our chains are currently figured to accept traffic.
More times than not, you’ll want your system to accept connections by default. Unless you’ve changed the policy chain rules previously, this setting should already be configured. Either way, here’s the command to accept connections by default:
iptables --policy INPUT ACCEPT
iptables --policy OUTPUT ACCEPT
iptables --policy FORWARD ACCEPT
By defaulting to the accept rule, you can then use iptables to deny specific IP addresses or port numbers, while continuing to accept all other connections. We’ll get to those commands in a minute.

If you would rather deny all connections and manually specify which ones you want to allow to connect, you should change the default policy of your chains to drop. Doing this would probably only be useful for servers that contain sensitive information and only ever have the same IP addresses connect to them.
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

Connection-specific Responses

With your default chain policies configured, you can start adding rules to iptables so it knows what to do when it encounters a connection from or to a particular IP address or port. In this guide, we’re going to go over the three most basic and commonly used “responses”.

Accept – Allow the connection.

Drop – Drop the connection, act like it never happened. This is best if you don’t want the source to realize your system exists.

Reject – Don’t allow the connection, but send back an error. This is best if you don’t want a particular source to connect to your system, but you want them to know that your firewall blocked them.
The best way to show the difference between these three rules is to show what it looks like when a PC tries to ping a Linux machine with iptables configured for each one of these settings.

Allowing the connection:


Dropping the connection:


Rejecting the connection:

Allowing or Blocking Specific Connections

With your policy chains configured, you can now configure iptables to allow or block specific addresses, address ranges, and ports. In these examples, we’ll set the connections to DROP, but you can switch them to ACCEPT or REJECT, depending on your needs and how you configured your policy chains.
Note: In these examples, we’re going to use iptables -A to append rules to the existing chain. iptables starts at the top of its list and goes through each rule until it finds one that it matches. If you need to insert a rule above another, you can use iptables -I [chain] [number] to specify the number it should be in the list.

Connections from a single IP address
This example shows how to block all connections from the IP address 10.10.10.10.
iptables -A INPUT -s 10.10.10.10 -j DROP
Connections from a range of IP addresses
This example shows how to block all of the IP addresses in the 10.10.10.0/24 network range. You can use a netmask or standard slash notation to specify the range of IP addresses.
iptables -A INPUT -s 10.10.10.0/24 -j DROP
or
iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP
Connections to a specific port
This example shows how to block SSH connections from 10.10.10.10.
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP
You can replace “ssh” with any protocol or port number. The -p tcp part of the code tells iptables what kind of connection the protocol uses.  If you were blocking a protocol that uses UDP rather than TCP, then -p udp would be necessary instead.
This example shows how to block SSH connections from any IP address.
iptables -A INPUT -p tcp --dport ssh -j DROP

Connection States

As we mentioned earlier, a lot of protocols are going to require two-way communication. For example, if you want to allow SSH connections to your system, the input and output chains are going to need a rule added to them. But, what if you only want SSH coming into your system to be allowed? Won’t adding a rule to the output chain also allow outgoing SSH attempts?
That’s where connection states come in, which give you the capability you’d need to allow two way communication but only allow one way connections to be established. Take a look at this example, where SSH connections FROM 10.10.10.10 are permitted, but SSH connections TO 10.10.10.10 are not. However, the system is permitted to send back information over SSH as long as the session has already been established, which makes SSH communication possible between these two hosts.
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -d 10.10.10.10 -m state --state ESTABLISHED -j ACCEPT

Saving Changes

The changes that you make to your iptables rules will be scrapped the next time that the iptables service gets restarted unless you execute a command to save the changes.  This command can differ depending on your distribution:
Ubuntu:
sudo /sbin/iptables-save
Red Hat / CentOS:
/sbin/service iptables save
Or
/etc/init.d/iptables save

Other Commands

List the currently configured iptables rules:
iptables -L
Adding the -v option will give you packet and byte information, and adding -n will list everything numerically. In other words – hostnames, protocols, and networks are listed as numbers.
To clear all the currently configured rules, you can issue the flush command.
iptables -F

Wednesday, January 29, 2014

Keeping SSH access secure

There are several worms which attempt to exploit vulnerable SSH servers, by logging in to a host with a collection of usernames and passwords such as "admin/admin", "test/test", "root/root", etc. These shouldn't be of much concern if you're keeping good passwords, but there are simple ways to prevent them regardless.

The most obvious way to prevent people connecting to your host is to only allow connections from small number of IP addresses, by the use of a firewall.
If you're currently running a firewall you can add to it to :
  • Accept incoming SSH connections from a trusted address.
  • Drop all other connections.
Using the iptables firewall commands you can do this as follows:
 
# All connectsion from address 1.2.3.4 to SSH (port 22)
iptables -A INPUT -p tcp -m state --state NEW --source 1.2.3.4 
--dport 22 -j ACCEPT

# Deny all other SSH connections
iptables -A INPUT -p tcp --dport 22 -j DROP

If you're not running a firewall, or you don't wish to mess with the setup you can look at another way of restricting access. The Debian packages of openSSH are compiled with tcpwrappers support, which means you can specify which hosts are allowed to connect without touching your firewall.

The two important files are:
 
/etc/hosts.allow
/etc/hosts.deny

The first can contain entries of hosts which are allowed to connect, the second contains addresses which are blocked.

Assuming that you wish to allow the remote addresses 1.2.3.x, and 192.168.0.x to connect but nothing else you would setup the files as follows. Firstly allow access by placing the following inside /etc/hosts.allow:
 
# /etc/hosts.allow
sshd: 1.2.3.0/255.255.255.0 
sshd: 192.168.0.0/255.255.255.0

Then disallow all further access by placing this in /etc/hosts.deny:
 
# /etc/hosts.deny
sshd: ALL

Finally you can look at the ssh configuration itself, this has several useful security options you can enable.

The ssh server is configured by the file /etc/ssh/sshd_config. If you wish you can restrict remote access to specific users.

For example to only allow "bob" and "chris" to login add the following:
 
AllowUsers bob chris

With this setting in place (after the server has been restarted with "/etc/init.d/ssh restart") all other users will be unable to connect via SSH even if they login with the correct username and password.

You can also explicitly deny particular users:
 
DenyUsers badness paula

Probably the most important setting you can change in the sshd_config file is the following:
 
PermitRootLogin no

With this setting set to "no" remote root logins are denied.

Linux fdisk Command Examples to Manage Hard Disk Partition


On Linux distributions, fdisk is the best tool to manage disk partitions. fdisk is a text based utility.

Using fdisk you can create a new partition, delete an existing partition, or change existing partition.

Using fidsk you are allowed to create a maximum of four primary partition, and any number of logical partitions, based on the size of the disk.

Keep in mind that any single partition requires a minimum size of 40MB.

In this article, let us review how to use fdisk command using practical examples.

Warning: Don’t delete, modify, or add partition, if you don’t know what you are doing. You will lose your data!

1. View All Existing Disk Partitions Using fdisk -l

Before you create a new partition, or modify an existing partition, you might want to view all available partition in the system.

Use fdisk -l to view all available partitions as shown below.
 
# fdisk -l

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        2904     1951866   83  Linux
/dev/sda7            2905        3147     1951866   83  Linux
/dev/sda8            3148        3264      939771   82  Linux swap / Solaris
/dev/sda9            3265        5283    16217586    b  W95 FAT32

The above will list partitions from all the connected hard disks. When you have more than one disk on the system, the partitions list are ordered by the device’s /dev name. For example, /dev/sda, /dev/sdb, /dev/sdc and so on.

2. View Partitions of a Specific Hard Disk using fdisk -l /dev/sd{a}

To view all partitions of the /dev/sda hard disk, do the following.
 
# fdisk -l /dev/sda

View all fdisk Commands Using fdisk Command 'm'

Use fdisk command m, to view all available fdisk commands as shown below.
 
# fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): m
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)

3. Delete a Hard Disk Partition Using fdisk Command 'd'

Let us assume that you like to combine several partitions (for example, /dev/sda6, /dev/sda7 and /dev/sda8) into a single disk partition. To do this, you should first delete all those individual partitions, as shown below.
 
# fdisk /dev/sda                                                 

The number of cylinders for this disk is set to 9729.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        2904     1951866   83  Linux
/dev/sda7            2905        3147     1951866   83  Linux
/dev/sda8            3148        3264      939771   82  Linux swap / Solaris
/dev/sda9            3265        5283    16217586    b  W95 FAT32

Command (m for help): d
Partition number (1-9): 8

Command (m for help): d
Partition number (1-8): 7

Command (m for help): d
Partition number (1-7): 6

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

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

4. Create a New Disk Partition with Specific Size Using fdisk Command 'n'

Once you’ve deleted all the existing partitions, you can create a new partition using all available space as shown below.
 
# fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): n
First cylinder (2662-5283, default 2662):
Using default value 2662
Last cylinder, +cylinders or +size{K,M,G} (2662-3264, default 3264):
Using default value 3264

In the above example, fdisk n command is used to create new partition with the specific size. While creating a new partition, it expects following two inputs.
  • Starting cylinder number of the partition to be create (First cylinder).
  • Size of the partition (or) the last cylinder number (Last cylinder, +cylinders or +size ).
Please keep in mind that you should issue the fdisk write command (w) after any modifications.
 
Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

5. View the Size of an existing Partition Using fdisk -s

As shown below, fdisk -s displays the size of the partition in blocks.
 
# fdisk -s /dev/sda7
4843566

The above output corresponds to about 4900MB.

6. Toggle the Boot Flag of a Partition Using fdisk Command a

fdisk command displays the boot flag of each partition. When you want to disable or enable the boot flag on the corresponding partition, do the following.
If you don’t know why are you are doing this, you’ll mess-up your system.
 
# fdisk /dev/sda

The number of cylinders for this disk is set to 9729.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux

Partition table entries are not in disk order

Command (m for help): a
Partition number (1-7): 5

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5            1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux

Partition table entries are not in disk order

Command (m for help):
As seen above, the boot flag is disabled on the partition /dev/sda5.

7. Fix Partition Table Order Using fdisk Expert Command 'f'

When you delete a logical partition, and recreate it again, you might see the “partition out of order” issue. i.e “Partition table entries are not in disk order” error message.

For example, when you delete three logical partitions (sda6, sda7 and sda8), and create a new partition, you might expect the new partition name to be sda6. But, the system might’ve created the new partition as sda7. This is because, after the partitions are deleted, sda9 partition has been moved as sda6 and the free space is moved to the end.

To fix this partition order issue, and assign sda6 to the newly created partition, execute the expert command f as shown below.
 
$ fdisk  /dev/sda

The number of cylinders for this disk is set to 9729.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)                               

Command (m for help): p

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed                     

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            3265        5283    16217586    b  W95 FAT32
/dev/sda7            2662        3264     4843566   83  Linux          

Partition table entries are not in disk order

Command (m for help): x

Expert command (m for help): f
Done.

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

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

Once the partition table order is fixed, you’ll not get the “Partition table entries are not in disk order” error message anymore.
 
# fdisk -l

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xf6edf6ed

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1        1959    15735636    c  W95 FAT32 (LBA)
/dev/sda2            1960        5283    26700030    f  W95 Ext'd (LBA)
/dev/sda3            5284        6528    10000462+   7  HPFS/NTFS
/dev/sda4            6529        9729    25712032+   c  W95 FAT32 (LBA)
/dev/sda5   *        1960        2661     5638752   83  Linux
/dev/sda6            2662        3264     4843566   83  Linux
/dev/sda7            3265        5283    16217586    b  W95 FAT32
 

8. Format the Partitions Using mkfs Command

After the partition is created, format it using the mkfs command as shown below.

         #mkfs.ext4 /dev/sda5
 

9. Mount the Partitions Using mount Command

After the partition is formated then it can be mounted using the mount command as shown below.

Create the mount point.
# mkdir <mount_point>

         #mkdir /test1
 
Mount the mount point.
 
         #mount /dev/sda5 /test1
 

10. Add the Partition entry to the '/etc/fstab' file


Add the partition entry to the “/etc/fstab” file

<device> <mount_point> <filesystem_type> <options> <dump_frequency> <fsck_order>


        /dev/sda5        /test1      ext4    default     0    0
 


 

Sunday, January 26, 2014

TCPDUMP (Packet Analyzer) Command Examples



tcpdump command is also called as packet analyzer. tcpdump command will work on most flavors of unix operating system. tcpdump allows us to save the packets that are captured, so that we can use it for future analysis. The saved file can be viewed by the same tcpdump command.


We can also use open source software like wireshark to read the tcpdump pcap files. In this tcpdump tutorial.

let us discuss some practical examples on how to use the tcpdump command.

1. Capture packets from a particular ethernet interface using tcpdump -i

When you execute tcpdump command without any option, it will capture all the packets flowing through all the interfaces. -i option with tcpdump command, allows you to filter on a particular ethernet interface.
 
$ tcpdump -i eth1 
 
14:59:26.608728 IP xx.domain.netbcp.net.52497 > valh4.lell.net.ssh:
 . ack 540 win 16554
14:59:26.610602 IP resolver.lell.net.domain > valh4.lell.net.24151:
 4278 1/0/0 (73)
14:59:26.611262 IP valh4.lell.net.38527 > resolver.lell.net.domain:
 26364+ PTR? 244.207.104.10.in-addr.arpa. (45)
 
In this example, tcpdump captured all the packets flows in the interface eth1 and displays in the standard output.

Note: Editcap utility is used to select or remove specific packets from dump file and translate them into a given format.

2. Capture only N number of packets using tcpdump -c

When you execute tcpdump command it gives packets until you cancel the tcpdump command. Using -c option you can specify the number of packets to capture.
 
$ tcpdump -c 2 -i eth0 
 
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
14:38:38.184913 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006:
 P 1457255642:1457255758(116) ack 1561463966 win 63652
14:38:38.690919 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006:
 P 116:232(116) ack 1 win 63652
2 packets captured
13 packets received by filter
0 packets dropped by kernel
 
The above tcpdump command captured only 2 packets from interface eth0.

Note: Mergecap and TShark: Mergecap is a packet dump combining tool, which will combine multiple dumps into a single dump file. Tshark is a powerful tool to capture network packets, which can be used to analyze the network traffic. It comes with wireshark network analyzer distribution.

3. Display Captured Packets in ASCII using tcpdump -A

The following tcpdump syntax prints the packet in ASCII.
 
$ tcpdump -A -i eth0
 
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
14:34:50.913995 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006:
P 1457239478:1457239594(116) ack 1561461262 win 63652
E.....@.@..]..i...9...*.V...]...P....h....E...>{..U=...g.
......G..7\+KA....A...L.
14:34:51.423640 IP valh4.lell.net.ssh > yy.domain.innetbcp.net.11006:
 P 116:232(116) ack 1 win 63652
E.....@.@..\..i...9...*.V..*]...P....h....7......X..!....Im.S.g.u:*..O&....^#Ba...
E..(R.@.|.....9...i.*...]...V..*P..OWp........
 
Note: Ifconfig command is used to configure network interfaces

4. Display Captured Packets in HEX and ASCII using tcpdump -XX

Some users might want to analyse the packets in hex values. tcpdump provides a way to print packets in both ASCII and HEX format.
 
$tcpdump -XX -i eth0
 
18:52:54.859697 IP zz.domain.innetbcp.net.63897 > valh4.lell.net.ssh: . ack 232 win 16511
        0x0000:  0050 569c 35a3 0019 bb1c 0c00 0800 4500  .PV.5.........E.
        0x0010:  0028 042a 4000 7906 c89c 10b5 aaf6 0f9a  .(.*@.y.........
        0x0020:  69c4 f999 0016 57db 6e08 c712 ea2e 5010  i.....W.n.....P.
        0x0030:  407f c976 0000 0000 0000 0000            @..v........
18:52:54.877713 IP 10.0.0.0 > all-systems.mcast.net: igmp query v3 [max resp time 1s]
        0x0000:  0050 569c 35a3 0000 0000 0000 0800 4600  .PV.5.........F.
        0x0010:  0024 0000 0000 0102 3ad3 0a00 0000 e000  .$......:.......
        0x0020:  0001 9404 0000 1101 ebfe 0000 0000 0300  ................
        0x0030:  0000 0000 0000 0000 0000 0000            ............

5. Capture the packets and write into a file using tcpdump -w

tcpdump allows you to save the packets to a file, and later you can use the packet file for further analysis.

$ tcpdump -w 08232010.pcap -i eth0 

tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
32 packets captured
32 packets received by filter
0 packets dropped by kernel
 
-w option writes the packets into a given file. The file extension should be .pcap, which can be read by any network protocol
analyzer.

6. Reading the packets from a saved file using tcpdump -r

You can read the captured pcap file and view the packets for analysis, as shown below.

$tcpdump -tttt -r data.pcap
 
2010-08-22 21:35:26.571793 00:50:56:9c:69:38 (oui Unknown) > 
Broadcast, ethertype Unknown (0xcafe), length 74:
        0x0000:  0200 000a ffff 0000 ffff 0c00 3c00 0000  ............<...
        0x0010:  0000 0000 0100 0080 3e9e 2900 0000 0000  ........>.).....
        0x0020:  0000 0000 ffff ffff ad00 996b 0600 0050  ...........k...P
        0x0030:  569c 6938 0000 0000 8e07 0000            V.i8........
2010-08-22 21:35:26.571797 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.50570:
 P 800464396:800464448(52) ack 203316566 win 71
2010-08-22 21:35:26.571800 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.50570: 
P 52:168(116) ack 1 win 71
2010-08-22 21:35:26.584865 IP valh5.lell.net.ssh > 11.154.12.255.netbios-ns: 
NBT UDP PACKET(137): QUERY; REQUEST; BROADC

7. Capture packets with IP address using tcpdump -n

In all the above examples, it prints packets with the DNS address, but not the ip address. The following example captures the packets and it will display the IP address of the machines involved.
 
$ tcpdump -n -i eth0
 
15:01:35.170763 IP 10.0.19.121.52497 > 11.154.12.121.ssh:
 P 105:157(52) ack 18060 win 16549
15:01:35.170776 IP 11.154.12.121.ssh > 10.0.19.121.52497:
 P 23988:24136(148) ack 157 win 113
15:01:35.170894 IP 11.154.12.121.ssh > 10.0.19.121.52497:
 P 24136:24380(244) ack 157 win 113

8. Capture packets with proper readable timestamp using tcpdump -tttt

$ tcpdump -n -tttt -i eth0

2010-08-22 15:10:39.162830 IP 10.0.19.121.52497 > 11.154.12.121.ssh: . ack 49800 win 16390
2010-08-22 15:10:39.162833 IP 10.0.19.121.52497 > 11.154.12.121.ssh: . ack 50288 win 16660
2010-08-22 15:10:39.162867 IP 10.0.19.121.52497 > 11.154.12.121.ssh: . ack 50584 win 16586

9. Read packets longer than N bytes

You can receive only the packets greater than n number of bytes using a filter ‘greater’ through tcpdump command
 
$ tcpdump -w g_1024.pcap greater 1024

10. Receive only the packets of a specific protocol type

You can receive the packets based on the protocol type. You can specify one of these protocols — fddi, tr, wlan, ip, ip6, arp, rarp, decnet, tcp and udp. The following example captures only arp packets flowing through the eth0 interface.
 
$ tcpdump -i eth0 arp
 
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
19:41:52.809642 arp who-has valh5.lell.net tell valh9.lell.net
19:41:52.863689 arp who-has 11.154.12.1 tell valh6.lell.net
19:41:53.024769 arp who-has 11.154.12.1 tell valh7.lell.net

11. Read packets lesser than N bytes

You can receive only the packets lesser than n number of bytes using a filter ‘less’ through tcpdump command
 
$ tcpdump -w l_1024.pcap  less 1024

12. Receive packets flows on a particular port using tcpdump port

If you want to know all the packets received by a particular port on a machine, you can use tcpdump command as shown below.
 
$ tcpdump -i eth0 port 22 
 
19:44:44.934459 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.63897:
 P 18932:19096(164) ack 105 win 71
19:44:44.934533 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.63897:
 P 19096:19260(164) ack 105 win 71
19:44:44.934612 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.63897:
 P 19260:19424(164) ack 105 win 71

13. Capture packets for particular destination IP and Port

The packets will have source and destination IP and port numbers. Using tcpdump we can apply filters on source or destination IP and port number. The following command captures packets flows in eth0, with a particular destination ip and port number 22.
 
$ tcpdump -w xpackets.pcap -i eth0 dst 10.181.140.216 and port 22

14. Capture TCP communication packets between two hosts

If two different process from two different machines are communicating through tcp protocol, we can capture those packets using tcpdump as shown below.
 
$tcpdump -w comm.pcap -i eth0 dst 16.181.170.246 and port 22

You can open the file comm.pcap using any network protocol analyzer tool to debug any potential issues.

15. tcpdump Filter Packets – Capture all the packets other than arp and rarp

In tcpdump command, you can give “and”, “or” and “not” condition to filter the packets accordingly.
 
$ tcpdump -i eth0 not arp and not rarp 
 
20:33:15.479278 IP resolver.lell.net.domain > valh4.lell.net.64639:  26929 1/0/0 (73)
20:33:15.479890 IP valh4.lell.net.16053 > resolver.lell.net.domain:  56556+ PTR? 255.107.154.15.in-addr.arpa. (45)
20:33:15.480197 IP valh4.lell.net.ssh > zz.domain.innetbcp.net.63897: P 540:1504(964) ack 1 win 96
20:33:15.487118 IP zz.domain.innetbcp.net.63897 > valh4.lell.net.ssh: . ack 540 win 16486
20:33:15.668599 IP 10.0.0.0 > all-systems.mcast.net: igmp query v3 [max resp time 1s]

Thursday, January 23, 2014

Linux route Add Command Examples

I am a new Linux user. How do I add a new or default gateway using route command on Linux operating systems? How can I use route command to show or set a new route on Linux based server or desktop system?

You can use any one of the following tool to add, display, delete Linux kernel routing table:











(a) route command : show / manipulate the IP routing table on Linux.
(b) ip command : show / manipulate routing, devices, policy routing and tunnels on Linux.

Display your current routing table

Open the Terminal or login to server using ssh/console. Type the following command to display routing table:
 
# route

 OR
 
# route -n

Sample outputs:
Fig.01: Display routing table using route command
Fig.01: Display routing table using route command

# ip route show

 OR
 
# ip route list

Sample outputs:
Fig.02: ip command in action
Fig.02: ip command in action

Linux add a default route using route command

Route all traffic via 192.168.1.254 gateway connected via eth0 network interface:
 
# route add default gw 192.168.1.254 eth0

Linux add a default gateway (route) using ip command

Route all traffic via 192.168.1.254 gateway connected via eth0 network interface:
 
# ip route add 192.168.1.0/24 dev eth0

Verify newly added route ip in the Linux kernel routing table

To verify new routing table, enter:
 
# ip route list
 
 OR
 
# route -n

Verify new route

Use the ping command to verify connectivity to your router or external network:
 
# ping your-router-ip-here
# ping your-ISPs-Gateway-ip-here
# ping 192.168.1.254
# ping www.cyberciti.biz

How do I make routing changes persistent across reboots?

To make route entry persistent in the Linux kernel routing table, you need to modify config file as per your Linux distributions.

RHEL/CentOS/Fedora/Scientific Linux persistent routing configuration

Edit /etc/sysconfig/network and set default gateway IP address:

 # vi /etc/sysconfig/network

Sample outputs:
 
GATEWAY=192.168.1.254
 
You can add additional static route for eth0 by editing /etc/sysconfig/network-scripts/route-eth0 file as follows:
 
10.0.0.0/8 via 10.10.29.65

The above config sets static routing for network 10.0.0.0/8 via 10.9.38.65 router.

Debian / Ubuntu Linux persistence static routing configuration

Edit /etc/network/interfaces file, enter:
 
# vi /etc/network/interfaces

Append the following in eth0 section:
 
up route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.254
down route del -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.254

Save and close the file.

Generic method to add persistent static routing on Linux

The following method works with almost all Linux distributions.
Edit /etc/rc.d/rc.local or /etc/rc.local, enter
 
# vi /etc/rc.local

Append the following line:
 
/sbin/ip route add 192.168.1.0/24 dev eth0

Save and close the file.

Usage of grep Command In Linux / UNIX

How do I use grep command on Linux, Apple OS X, and Unix-like operating systems? Can you give me a simple examples of the grep command?

The grep command is used to search text or searches the given file for lines containing a match to the given strings or words. By default, grep displays the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines. grep is considered as one of the most useful commands on Unix and other Linux operating systems.










Did you know?

The name, "grep", derives from the command used to perform a similar operation, using the Unix/Linux text editor ed:
g/re/p

The grep command syntax

The syntax is as follows:
 
grep 'word' filename
grep 'word' file1 file2 file3
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName
 

How do I use grep command to search a file?

Search /etc/passwd file for boo user, enter:
 
$ grep boo /etc/passwd

Sample outputs:
foo:x:1000:1000:foo,,,:/home/foo:/bin/ksh
You can force grep to ignore word case i.e match boo, Boo, BOO and all other combination with the -i option:
 
$ grep -i "boo" /etc/passwd

Use grep recursively

You can search recursively i.e. read all files under each directory for a string "192.168.1.5"
 
$ grep -r "192.168.1.5" /etc/

OR
 
$ grep -R "192.168.1.5" /etc/

Sample outputs:
/etc/ppp/options:# ms-wins 192.168.1.50
/etc/ppp/options:# ms-wins 192.168.1.51
/etc/NetworkManager/system-connections/Wired connection 1:addresses1=192.168.1.5;24;192.168.1.2;
You will see result for 192.168.1.5 on a separate line preceded by the name of the file (such as /etc/ppp/options) in which it was found. The inclusion of the file names in the output data can be suppressed by using the -h option as follows:
 
$ grep -h -R "192.168.1.5" /etc/

OR
 
$ grep -hR "192.168.1.5" /etc/

Sample outputs:
# ms-wins 192.168.1.50
# ms-wins 192.168.1.51
addresses1=192.168.1.5;24;192.168.1.2;

Use grep to search words only

When you search for boo, grep will match fooboo, boo123, barfoo35 and more. You can force the grep command to select only those lines containing matches that form whole words i.e. match only boo word:
 
$ grep -w "boo" file

Use grep to search 2 different words

Use the egrep command as follows:
 
$ egrep -w 'word1|word2' /path/to/file

Count line when words has been matched

The grep can report the number of times that the pattern has been matched for each file using -c (count) option:
 
$ grep -c 'word' /path/to/file

Pass the -n option to precede each line of output with the number of the line in the text file from which it was obtained:
 
$ grep -n 'root' /etc/passwd

Sample outputs:
1:root:x:0:0:root:/root:/bin/bash
1042:rootdoor:x:0:0:rootdoor:/home/rootdoor:/bin/csh
3319:initrootapp:x:0:0:initrootapp:/home/initroot:/bin/ksh

Grep invert match

You can use -v option to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:
 
$ grep -v bar /path/to/file

UNIX / Linux pipes and grep command

grep command often used with shell pipes. In this example, show the name of the hard disk devices:
 
# dmesg | egrep '(s|h)d[a-z]'

Display cpu model name:
 
# cat /proc/cpuinfo | grep -i 'Model'

However, above command can be also used as follows without shell pipe:
 
# grep -i 'Model' /proc/cpuinfo

Sample outputs:
model  : 30
model name : Intel(R) Core(TM) i7 CPU       Q 820  @ 1.73GHz
model  : 30
model name : Intel(R) Core(TM) i7 CPU       Q 820  @ 1.73GHz

How do I list just the names of matching files?

Use the -l option to list file name whose contents mention main():
 
$ grep -l 'main' *.c

Finally, you can force grep to display output in colors, enter:
 
$ grep --color vivek /etc/passwd
Sample outputs:
Grep command in action

If you enjoyed the grep tutorial, then you would share this tutorial in a proper manner.

Create a permanent virtual IP address in Linux [ permanently ]

In this post, we can see how to create a virtual IP address, based on an existing network interface (permanently).


In Linux you simply create a new, virtual interface in the interfaces file.
And add a network interface, based on an existing interface. The below example is a virtual IP based on eth0 – note if this is your second virtual IP you would use eth0:2, and so on.
You will need to change the IP addresses to match your network. Notice there is no gateway – usually you can only have one gateway per machine.
Restart networking for the changes to take effect.

Create a Virtual IP Address in Linux [ temporary ]

This post will detail how to set ip a virtual IP address and assign an interface to handle the traffic in the Linux OS. This may not work for all Linux distros but it should be accurate for most.

Run the ifconfig command to see what interfaces are available.
Run the ifconfig command again, however this time create a Virtual IP using the following syntax.
Example:
Substitute INTERFACE = the interface which this VIP will be based on, IP_ADDRESS = the new VIP IP address (note: this must exist) and NETMASK = the netmask of the new VIP.
Update the routing table using arping.
Example:
Substitute INTERFACE with the interface to bind this VIP to and VIP_IP_ADDRESS to the VIP IP address which was assigned in the above ifconfig statement.

Note: changes made will be lost when the machine is rebooted.

CentOS 6.3 Step by Step Installation Guide with Screenshots

This post will guide you a step-by-step installation of Community ENTerprise Operating System 6.3 (CentOS) with screenshots. Less than three weeks after the release of Red Hat Enterprise Linux (RHEL) 6.3. The CentOS Project has released its clone of RHEL 6.3 distribution on 09 July 2012.

CentOS 6.3 Features

CentOS Linux Distribution contains some new exciting features like.
  1. OpenOffice 3.2 has been replaced by LibreOffice 3.4, if you update from previous version of CentOS 6 using ‘yum update’ and have openoffice installed, the update will automatically remove openoffice and install libreoffice.
  2. Many drivers have been updated and improved in virtulisation.
  3. Upstream has deprecated the Matahari API for operating system management has been deprecated, and there’s new tools for moving physical and virtual machines into Virtual KVM machine instances. These new tools from Red Hat are virt-p2v and virt-v2v for physical-to-virtual and virtual-to-virtual migration, respectively.

Download CentOS 6.3 DVD ISO

  1. Download CentOS 6.3 32-bit DVD ISO – (3.6 GB)
  2. Download CentOS 6.3 64-bit DVD ISO – (4.0 GB)
  3. Download both 32-bit and 64-bit DVD ISO.

CentOS 6.3 Step by Step Graphical Installation Guide

Boot Computer with CentOS 6.3 OS Installation CD/DVD.

1. Select Install or Upgrade existing system options.

Select Install or Upgrade
Select Install or Upgrade

2. Choose skip media test as it may take long time to check media.

Skip CentOS 6.3 Media Test
Skip CentOS 6.3 Media Test

3. CentOS 6.3 Welcome Screen press Next.

CentOS 6.3 Welcome Screen
CentOS 6.3 Welcome Screen

4. Language Selection.

CentOS 6.3 Language Selection
CentOS 6.3 Language Selection

5. Select appropriate Keyboard.

CentOS 6.3 Keyboard Selection
CentOS 6.3 Keyboard Selection

6. Select Basic Storage Device if your hard drive is attached locally.

CentOS 6.3 Storage Device Selection
CentOS 6.3 Storage Device Selection

7. You may get Storage Device warning, you can click Yes, discard any data button to Continue.

CentOS 6.3 Storage Device Warning
CentOS 6.3 Storage Device Warning

8. Give a Hostname to the server and click on Configure Network button if you want to configure network while installation.

CentOS 6.3 Hostname and Network Setup
CentOS 6.3 Hostname and Network Setup

9. Click Wired tab and click on Add button.

CentOS 6.3 Network Setup
CentOS 6.3 Network Setup

10. Select Connect Automatically, go to ipv4 settings tab and select Method and select Manual in drop down. Click on Add tab to fill address box with IP Address, Netmask, Gateway and DNS Server. Here I’m using IP Address 192.168.1.6 and DNS Server is 4.2.2.2 for demo. This IP Address may vary in your environment.

CentOS 6.3 Network Configuration
CentOS 6.3 Network Configuration

11. Select Time Zone.

CentOS 6.3 Set Timezone
CentOS 6.3 Set Timezone

12. Give a root password.

CentOS 6.3 root Password
CentOS 6.3 root Password

13. Select appropriate partitioning as per your requirement.

CentOS 6.3 Partition Selection
CentOS 6.3 Partition Selection

14. Verify filesystem. Here, you can edit filesystem If you want.

CentOS 6.3 Partition Verify
CentOS 6.3 Partition Verify

15. Disk Format Warning, click on Format.

CentOS 6.3 Disk Format
CentOS 6.3 Disk Format

16. Select Write Changes to disk.

CentOS 6.3 Disk Changes
CentOS 6.3 Disk Changes

17. Hard Drive is Formatting.

CentOS 6.3 Disk Formatting
CentOS 6.3 Disk Formatting

18. Here, you can give Boot loader Password for better security.

CentOS 6.3 Boot Loader Password
CentOS 6.3 Boot Loader Password

19. Select the applications you want to install, you can choose Customize now and click Next.

CentOS 6.3 Package Selection
CentOS 6.3 Package Selection

20. Select the applications you want to install and click Next.

CentOS 6.3 Packages Selection
CentOS 6.3 Packages Selection

21. Installation started, this may take several minutes as per selection of packages.

CentOS 6.3 Installation
CentOS 6.3 Installation

22. Installation completed, Please remove CD/DVD and reboot system.

CentOS 6.3 Installation Completes
CentOS 6.3 Installation Completes

23. Welcome to CentOS 6.3 Login Screen.

CentOS 6.3 Login Screen
CentOS 6.3 Login Screen

24. CentOS 6.3 Desktop Screen.

CentOS 6.3 Desktop Screen
CentOS 6.3 Desktop Screen


Liked the article? Sharing is the best way to say thank you!