Search This Blog

Wednesday, January 28, 2009

How do I label a Linux partition? How do I display current label?

How do I label a Linux partition? How do I display current label? A. You need to use e2label or tune2fs command line to change the label on an ext2/ext3 filesystem. e2label will display or change the filesystem label on the ext2 filesystem located on device.

Display current label

If the optional argument new-label is not present, e2label will simply display the current filesystem label. $ sudo e2label /dev/sda1 or # e2label /dev/sda1 Sample output:

/boot

Set a new label

If the optional argument new-label is present, then e2label will set the filesystem label to be new-label. Ext2 filesystem labels can be at most 16 characters long; if new-label is longer than 16 characters, e2label will truncate it and print a warning message. To set a new label, enter: # e2label /dev/sdb2 usbstroage It is also possible to set the filesystem label using the -L option of tune2fs, enter: # tune2fs -L usbstroage /dev/sdb2

Tuesday, January 27, 2009

Python code for an Ip range

def ipAddrRange(startAddr, endAddr):
   def incrAddr(addrList):
       addrList[3] += 1
       for i in (3,2,1):
           if addrList[i] == 256:
               addrList[i] = 0
               addrList[i-1] += 1

   def asString(addrList):
       return ".".join(map(str,addrList))

   startAddrList = map(int,startAddr.split("."))
   endAddrList = map(int,endAddr.split("."))

   curAddrList = startAddrList[:]
   yield asString(curAddrList)
   for i in range(4):
       while curAddrList[i] < endAddrList[i]:
           incrAddr(curAddrList)
           yield asString(curAddrList)

for addr in ipAddrRange("10.255.255.250","11.0.0.20"):
   print addr



Iprange module in Iptables

IP range match

The IP range match is used to match IP ranges, just as the --source and --destination matches are able to do as well. However, this match adds a different kind of matching in the sense that it is able to match in the manner of from IP - to IP, which the --source and --destination matches are unable to. This may be needed in some specific network setups, and it is rather a bit more flexible. The IP range match is loaded by using the -m iprange keyword.

Table 10-18. IP range match options

Match--src-range
Kernel2.4, 2.5 and 2.6
Exampleiptables -A INPUT -p tcp -m iprange --src-range 192.168.1.13-192.168.2.19
Explanation

This matches a range of source IP addresses. The range includes every single IP address from the first to the last, so the example above includes everything from 192.168.1.13 to 192.168.2.19. The match may also be inverted by adding an !. The above example would then look like -m iprange ! --src-range 192.168.1.13-192.168.2.19, which would match every single IP address, except the ones specified.

Match--dst-range
Kernel2.4, 2.5 and 2.6
Exampleiptables -A INPUT -p tcp -m iprange --dst-range 192.168.1.13-192.168.2.19
Explanation

The --dst-range works exactly the same as the --src-range match, except that it matches destination IP's instead of source IP's.

Thursday, January 22, 2009

Defending against brute force ssh attacks

Defending against brute force ssh attacks

By Rainer Wichmann [support@la-samhna.de] (last update: Nov 21, 2008)

Introduction

During 2005, bute force attacks on the ssh (secure shell) service became pretty popular. These attacks are based on a rather simple idea: use an automated program for trying, one after the other, many combinations of standard or frequently used account names and likewise frequently used password (e.g.: guest/guest).

Defence methods

There are a number of methods to defend against such brute force attacks. The following list is intended to give an overview of them, and briefly mention their respective advantages and disadvantages.

Strong passwords

Neither in a dictionary, nor trivial variations of trivial passwords (guest1 is just as bad as guest). Using the initials of the words in some sentence is a simple method to have a strong password that is easy to remind (Peter, Paul, and Mary went to school yesterday = PPaMwtsy).

  • Advantage: Simple
  • Disadvantages:
    • Requires enforcement (regular checks of user passwords with tools like e.g. john ("John the Ripper").
    • Does not reduce the (network, sshd) load caused by the attacks.

RSA authentication

If you don't use passwords, but only RSA keys for authentication, a brute force search for a valid password will obviously be useless.

(1) Generate an RSA key with ssh-keygen -t rsa. This will create the files /home/username/.ssh/id_rsa (the private key) and /home/username/.ssh/id_rsa.pub (the public key).

sh$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is:
32-digit_hexadecimal_fingerprint username@hostname

(2) On each machine to which where you want to login, put /home/username/.ssh/id_rsa.pub into /home/username/.ssh/authorized_keys. This file can hold more than one key, so it may be wise to concatenate the freshly generated key.

sh$ cat /home/username/.ssh/id_rsa.pub >> /home/username/.ssh/authorized_keys

(3) On each machine from which you want to login, place the file /home/username/.ssh/id_rsa into the directory /home/username/.ssh/.

(4) Disable password-based login by setting 'PasswordAuthentication no' in /etc/ssh/sshd_config, and restart the sshd daemon with /etc/init.d/sshd restart

  • Advantage: Pretty secure, if done properly
  • Disadvantages:
    • Users may use private keys without setting a passphrase to protect them. This implies that getting access to the private key would allow to login to any machine where the corresponding public key is installed.
    • Non-tech users may need help to generate RSA key for themselves (and for using them).
    • It is neccessary to carry the private key along to login from another host.

Using 'iptables' to block the attack

It is possible to set up iptables rules to block ssh attacks. The following ruleset (seen in the blog of Andrew Pollock) will allow at most 3 connections per minute from any host, and will block the host for another minute if this rate is exceeded.

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set \
--name SSH -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --rttl \
--name SSH -j LOG --log-prefix "SSH_brute_force "
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 \
--hitcount 4 --rttl --name SSH -j DROP

For whitelisting, a possible variation (also described by Andrew Pollock) would be:

(1) Create a custom chain for whitelisting first:

iptables -N SSH_WHITELIST

(2) Whitelist any host(s) that you like:

iptables -A SSH_WHITELIST -s TRUSTED_HOST_IP -m recent --remove --name SSH -j ACCEPT

(3) Add the blocking rules:

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set \
--name SSH
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH_WHITELIST
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \
--seconds 60 --hitcount 4 --rttl --name SSH -j ULOG --ulog-prefix SSH_brute_force
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \
--seconds 60 --hitcount 4 --rttl --name SSH -j DROP
  • Advantage: Transparent for users
  • Disadvantages:
    • Does not distinguish between successful logins and unsuccessful login attempts (i.e. three successful logins within one minute will trigger just like three unsuccessful login attempts).
    • As pointed out by one reader (L. Hamel), this method requires 'recent' (http://snowman.net/projects/ipt_recent/), an ipfilters patch that may not (yet) be in every distro's default kernel. So to use this technique with typical linux distros, you may have to patch the kernel.
    • R. McIntosh kindly notices that Debian/Ubuntu include this, but RHEL3/4/5 do not.

Using the sshd log to block attacks

It is possible to scan the syslog entries written by the sshd daemon for ongoing attacks, and block the attacker. There are several programs/scripts available that are specifically written for this purpose:

ssdfilter uses iptables for blocking (i.e. it dynamically adds custom firewall rules to block a specific attacker). You need to run sshdfilter instead of sshd. Sshdfilter will then start sshd and monitor its log.

Fail2Ban is a Python script which adds custom firewall rules to block an attacker. It can use the iptables, ipfwadm, or ipfw.

DenyHosts does not use firewall rules to block an attack. Rather, it writes blocking rules to /etc/hosts.deny. Thus, it requires an sshd daemon compiled with support for tcp_wrappers (default on most Linux distributions). Like Fail2Ban, DenyHosts is a Python script.

To find out whether your sshd daemon supports tcp_wrappers, you could use the command ldd /usr/sbin/sshd | grep libwrap. With tcp_wrappers supported you should get a line similar to libwrap.so.0 => /lib/libwrap.so.0 (0xb7f7e000) (numbers may be different). Without tcp_wrappers support, the output will be empty.

sh$ ldd /usr/sbin/sshd | grep libwrap
     libwrap.so.0 => /lib/libwrap.so.0 (0xb7f7e000)

Another method to test for tcp_wrappers support would be to add the line sshd: 127.0.0.1 to the file /etc/hosts.deny, and then try to connect to the local ssh server with the command ssh localhost. As you have just blocked localhost, this should fail with the error message ssh_exchange_identification: Connection closed by remote host:

sh$ ssh localhost
ssh_exchange_identification: Connection closed by remote host
  • Advantages:
    • Transparent for users
    • Can distinguish between unsuccessful login attempts (which are blocked) and successful logins (which are not blocked).
  • Disadvantages:
    • Many ssh attacks are fast and short (many connections in a short time). Thus, running a cron script to check the sshd logs for an ongoing attack may be pointless, as it may notice the attack only after it has finished (and the next attack will come from a different machine anyway).
    • Continuously monitoring the sshd log for an attack requires to run yet another daemon (in the case of sshdfilter, you have to run sshdfilter instead of sshd anyway).

Using tcp_wrappers to block attacks

In the preceding section the DenyHosts script was discussed, which scans the sshd logs to detect an attack, and then blocks it with a rule in /etc/hosts.deny. However, it is actually not necessary to scan the logs. It is possible to let the tcp wrapper library start a script whenever a connection is made, and let this script add rules to /etc/hosts.deny or /etc/hosts.allow, if the connecting host should be blocked.

(1) Download the sshblock.sh shell script (PGP signature), and copy it to /usr/local/bin/sshblock.sh (or wherever you like).

(2) Make it executable using the command chmod 755 /usr/local/bin/sshblock.sh

(3) Add the following three lines at the bottom of /etc/hosts.allow

#__START_SSHBLOCK__
#__END_SSHBLOCK__
sshd : ALL : spawn (/usr/local/bin/sshblock.sh %a)&

This will call the script /usr/local/bin/sshblock.sh for each ssh connection. The script will receive the remote IP address as the first and only argument. The script will write a temporary file /root/hosts.allow, and copy it to /etc/hosts.allow if it differs from that.

Requirements:

  • The sshd daemon must support tcp_wrappers (see preceding section on methods to test this).
  • The date command must support the '%s' format specifier to print seconds after the Epoch (use date +%s to test). Both GNU/Linux and FreeBSD date support this.

Configuration: at the top of the script, there are four variables that can be set: DONTBLOCK is the prefix of an address block that you do never want to be blocked (i.e. your own domain). The default is 192.168, which you can safely keep if you have no own domain, as this is a 'private' address block). At most (2) BURST_MAX connections from a host within BURST_TIM seconds are allowed (default: 5 within 60 sec), and blocks are removed after PURGE_TIM seconds (default: 3600 sec). In the script, this looks like:

# your own domain
DONTBLOCK=192.168

# block host if more than BURST_MAX connections within BURST_TIM seconds
BURST_MAX=5
BURST_TIM=60

# remove block after PURGE_TIM seconds
PURGE_TIM=3600
  • Advantage: Transparent for users
  • Disadvantages:
    • Does not distinguish between successful logins and unsuccessful login attempts (i.e. five successful logins within one minute will trigger just like five unsuccessful login attempts).
    • To remove a block, the script must run, which requires a connection from a non-blocked host (or follow a suggestion by Andreas Rizzi and install a cron job that calls the script with the parameter 127.0.0.0 once per hour).

Port knocking

As pointed out by Imre Veres, another solution to the problem is using knockd, which eliminates the need for having ssh listen on an open port.

Knockd watches predefined patterns in iptables' log, e.g. one hit to port 6356, one hit to port 9356 and two hits to port 3356. I.e. this is equivalent to knocking at a closed door with a "code" that is recognized by knockd. Knockd will then use iptables to open a predefined port (e.g. tcp/22 for sshd) for a predefined time (e.g. one minute). If a ssh session is opened within that time frame, it will remain open, though the ssh port will get closed by knockd after the predefined timeframe expires.

Kevin Hilton recommends fwknop on the grounds that "its much more sophisticated, very easy to set up (at least for ubuntu — probably other distributions as well), allows for encrypted communications, randomizes the source port, and is supported."

Michael Rash points out that fwkop supports Single Packet Authorization, which does not suffer from the traffic monitoring attack mentioned below under 'Disadvantages'.

  • Advantage: Fairly secure, as long as the attacker cannot monitor your traffic (since that could allow to determine and replay the portknock sequence)
  • Disadvantages:
    • Rather complicated scheme, not suitable for 'mere mortals'.
    • Requires a suitable program (e.g. knockd-client) for "port knocking" on the client (as well as knockd on the server)
    • As pointed out by Bond Masuda, it is pretty easy to detect the traffic pattern of 'portknocks followed by ssh connection', once an attacker can monitor your traffic. Thus simple portknocking provides no security against attackers who can spy on the local network. This problem is addressed by Single Packet Authorization in fwknop.

Thursday, January 1, 2009

Input/Output Redirection in Unix

Redirection is one of Unix's strongest points. Ramnick explains this concept in this article. He talks about Input, Output Redirection. He cites many simple and useful ways in which we can put redirection to good use.

Introduction

For those of you'll who have no idea what Redirection means, let me explain it in a few words. Whenever you run a program you get some output at the shell prompt. In case you don't want that output to appear in the shell window, you can redirect it elsewhere. you can make the output go into a file...or maybe go directly to the printer.. or you could make it disappear :)

This is known as Redirection. Not only can the output of programs be redirected, you can also redirect the input for programs. I shall be explaining all this in detail in this article. Lets begin...

File Descriptors

One important thing you have to know to understand Redirection is file descriptors. In Unix every file has a no. associated with it called the file descriptor. And in Unix everything is a file. Right from your devices connected to your machine to the normal text files storing some information - all of these are looked at, as files by the Operating System.

Similarly even your screen on which your programs display their output are files for Unix. These have file descriptors associated with it. So when a program actually executes it sends its output to this file descriptor and since this particular file descriptor happens to be pointing to the screen, the output gets displayed on the screen. Had it been the file descriptor of the printer, the output would have been printed by the printer. (There are ofcourse other factors which come into play, but I guess you got the idea of how everything is a file and you send whatver you want to particular files descriptors)

Whenever any program is executed (i.e. when the user types a command) the program has 3 important files to work with. They are standard input, standard output, and standard error. These are 3 files that are always open when a program runs. You could kind of consider them to be inherently present for all programs (For the techies.. basically when a child process is forked from a parent process, these 3 files are made available to the child process). For the rest, just remember that you always have these 3 files with you whenever you type any command at the prompt. As explained before a file descriptor, is associated with each of these files -

File Descriptor
Descriptor Points to -
0
Standard Input (Generally Keyboard)
1
Standard output (Generally Display/Screen)
2
Standard Error Ouput (Generally Display/Screen)

You could redirect any of these files to other files. In short if you redirect 1 (standard output) to the printer, your programs output would start getting printed instead of being displayed on the screen.

What is the standard input? That would be your keyboard. Most of the times since you enter commands with your keyboard, you could consider 0 to be your keyboard. Since you get the output of your command on the screen, 1 would be the screen (display) and the errors as well are shown on the screen to you, so 2 would also be the screen.

For those of you'll who like to think ahead of what is being discussed... you'll must have already understood that you can now avoid all those irritating, irrelevant error messages you often get while executing some programs. You could just redirect the standard error (2) to some file and avoid seeing the error messages on the screen!!

Output Redirection

The most common use of Redirection is to redirect the output (that normally goes to the terminal) from a command to a file instead. This is known as Output Redirection. This is generally used when you get a lot of output when you execute your program. Often you see that screens scroll past very rapidly. You could get all the output in a file and then even transfer that file elsewhere or mail it to someone.

The way to redirect the output is by using the ' > ' operator in shell command you enter. This is shown below. The ' > ' symbol is known as the output redirection operator. Any command that outputs its results to the screen can have its output sent to a file.

$ ls > listing

The ' ls ' command would normally give you a directory listing. Since you have the ' > ' operator after the ' ls ' command, redirection would take place. What follows the ' > ' tells Unix where to redirect the output. In our case it would create a file named ' listing ' and write the directory listing in that file. You could view this file using any text editor or by using the cat command.

Note: If the file mentioned already exists, it is overwritten. So care should be taken to enter a proper name. In case you want to append to an existing file, then instead of the ' > ' operator you should use the ' >> ' operator. This would append to the file if it already exists, else it would create a new file by that name and then add the output to that newly created file.

Input Redirection

Input Redirection is not as popular as Output Redirection. Since most of the times you would expect the input to be typed at the keyboard. But when it is used effectively, Input Redirection can be of great use. The general use of Input Redirection is when you have some kind of file, which you have ready and now you would like to use some command on that file.

You can use Input Redirection by typing the ' < ' operator. An excellent example of Input Redirection has been shown below.

$ mail cousin < my_typed_letter

The above command would start the mail program with contents of the file named ' my_typed_letter ' as the input since the Input Redirection operator was used.

Note: You can't have Input Redirection with any program/command. Only those commands that accept input from keyboard could be redirected to use some kind of text files as their input. Similarly Output Redirection is also useful only when the program sends its output to the terminal. In case you are redirecting the output of a program that runs under X, it would be of no use to you.

Error Redirection

This is a very popular feature that many Unix users are happy to learn. In case you have worked with Unix for some time, you must have realised that for a lot of commands you type you get a lot of error messages. And you are not really bothered about those error messages. For example whenever I perform a search for a file, I always get a lot of permission denied error messages. There may be ways to fix those things. But the simplest way is to redirect the error messages elsewhere so that it doesn't bother me. In my case I know that errors I get while searching for files would be of no use to me.

Here is a way to redirect the error messages

$ myprogram 2>errorsfile

This above command would execute a program named ' myprogram ' and whatever errors are generated while executing that program would all be added to a file named ' errorsfile ' rather than be displayed on the screen. Remember that 2 is the error output file descriptor. Thus ' 2> ' means redirect the error output.

$ myprogram 2>>all_errors_till_now

The above command would be useful in case you have been saving all the error messages for some later use. This time the error messages would append to the file rather than create a new file.

You might realize that in the above case since I wasn't interested in the error messages generated by the program I redirected the output to a file. But since those error messages don't interest me I would have to go and delete that file created every time I run that command. Else I would have several such files created all over whenever I redirect my unwanted error output. An excellent way around is shown below

$ find / -name s*.jpg 2>/dev/null

What's /dev/null ????? That something like a black hole. Whatever is sent to the ' /dev/null ' never returns. Neither does one know where it goes. It simple disappears. Isn't that fantastic !! So remember.. whenever you want to remove something.. something that you don't want ...you could just send it to /dev/null

Isnt Unix wonderful !!!

Different ways to use Redirection Operators

Suppose you want to create a text file quickly

$ cat > filename This is some text that I want in this file ^D

That's it!! Once you type the ' cat ' command, use the Redirection operator and add a name for a file. Then start typing your line. And finally press Ctrl+D. You will have a file named ' filename ' in the same directory.

Suppose you want to add a single line to an existing file.

$ echo "this is a new line" >> exsisting_file

That would add the new line to the file named ' existing_file ' . Remember to use ' >> ' instead of ' > ' else you would overwrite the file.

Suppose you wanted to join 2 files

$ cat file2 >> file1

Wow!! That a much neater way then to open a text editor and copy paste. The contents of ' file2 ' would be added to ' file1 ' .

Suppose you want to join a couple of files

$ cat file1 file2 > file3

This would add the contents of ' file1 ' and ' file2 ' and then write these contents into a new file named ' file3 ' .

Redirection works with many commands besides normal ones such as ' cat ' or ' ls ' . One example I could give you is in case you are programming using any language you could redirect the output messages of the compilation of your code so that you can view them later on. There are lots of commands where you can use Redirection. The more you use Unix the more you will come to know.