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