Friday, January 27, 2012

7 Default OpenSSH Security Options You Should Change in /etc/ssh/sshd_config


OpenSSH options are controlled through the /etc/ssh/sshd_config file. This article explains the 7 default options in sshd_config file that you should change.
In sshd_config, the lines that start with # are comments. For those options that uses the default values, the sshd_config file contains a commented line with the option and its default value.
This makes it easier for us, as we can see the OpenSSH option name and the default value without having to lookup somewhere else.

For example, sshd_config file contains the following commented line. This indicates that the PubkeyAuthentication option contains “yes” as the default value.
$ grep -i pubkey /etc/ssh/sshd_config
#PubkeyAuthentication yes
If you like to change this, you should remove the comment and change the value (from yes to no) as shown below.
$ vi /etc/ssh/sshd_config
PubkeyAuthentication no
I showed the above only as an example. You don’t need to change the default value of PubkeyAuthentication option, as allowing public key authentication is good.
You don’t need to modify any of the default values in the sshd_config file except the 7 options mentioned in this article.

1. Disable Root Login (PermitRootLogin)

By default you can ssh to the server as root. It is best not to allow root to login directly to the server. Instead, you should login to the system as your account and then do ‘su -’ to login as root.

If you have multiple sysadmins in your organization, and if they all login to the server directly as root, you might not know which sysadmin logged in as root. Instead, if you disable login as root, sysadmins are forced to login as their account first, before they can do ‘su -’, this makes the auditing easier.
Add the following entry to sshd_config to disable root to login to the server directly.
$ vi /etc/ssh/sshd_config
PermitRootLogin no

2. Allow Only Specific Users or Groups (AllowUsers AllowGroups)

By default anybody who is authenticated successfully are allowed to login. Instead you can restrict which users (or groups) you allow to login to the system.
This is helpful when you have created several user accounts on the system, but want only few of them to login.
This is also helpful when you are using NIS, openLDAP (or some other external system) for authentication. Every user in your company might have account on NIS, OpenLDAP etc. But, on a specific server you want only few of them to login. For example, on production system you want only sysadmins to login.
Add the following entry to the sshd_config file to allow only specific users to login to the system. In the example below only ramesh, john and jason can login to this system. Usernames should be separated by space.
$ vi /etc/ssh/sshd_config
AllowUsers ramesh john jason
Add the following entry to the sshd_config file to allow only the users who belong to a specific group to login. In the exampe below only users who belong to sysadmin and dba group can login to the system.
$ vi /etc/ssh/sshd_config
AllowGroups sysadmin dba

3. Deny Specific Users or Groups (DenyUsers DenyGroups)

Instead of allowing specific users (or groups), you can also deny specific users or groups.
Add the following entry to the sshd_config file to deny specific users to login to the system. In the example below cvs, apache, jane cannot login to this system. Usernames should be separated by space.
$ vi /etc/ssh/sshd_config
DenyUsers cvs apache jane
Add the following entry to the sshd_config file to deny users who belong to a specific group to login. In the exampe below users who belong to developers and qa group cannot login to the system.
$ vi /etc/ssh/sshd_config
DenyGroups developers qa
Note: You can use combination of all the Allow and Deny directivies. It is processed in this order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups

4. Change SSHD Port Number (Port)

By default ssh runs on port 22. Most of the attackers will check if a server is open on port 22, and will randomly use brute force to login to the server using several username and password combination.
If you change the port # to something different, others need to know exactly what port to use to login to the server using ssh. The exampe below uses port 222 for ssh.
$ vi /etc/ssh/sshd_config
Port 222
From your logs (/var/log/secure), if you see lot of invalid logins using ssh for accounts that don’t exist on your system, from the
ip-address that you don’t recognize, it migth be some brute-force attack. Those kind of ssh invalid login will stop, if you change the port number.
Please note that this causes little inconvenience to your team who login to the system, as they need to know both the ip-address and the port number.

5. Change Login Grace Time (LoginGraceTime)

When you ssh to a server, you have 2 minutes to login. If you don’t successfully login within 2 minutes, ssh will disconnect.
2 minutes time to login successfully is too much. You should consider changing it to 30 seconds, or may be 1 minute.
Add the following entry to the sshd_config file to change the login grace time from 2 minutes to 1 minute.
$ vi /etc/ssh/sshd_config
LoginGraceTime 1m

6. Restrict the Interface (IP Address) to Login (ListenAddress)

If you have multiple interfaces on the server that are configured to different ip-address, you might not want everybody to login to the server using all those ip-address.
Let us assume that you have the following 4 interfaces on the server:
  • eth0 – 192.168.10.200
  • eth1 – 192.168.10.201
  • eth2 – 192.168.10.202
  • eth3 – 192.168.10.203
By default ssh will listen on all of the above ip-addresses. If you want users to login only using ip-address 200 and 202, do the following in your sshd_config
$ vi /etc/ssh/sshd_config
ListenAddress 192.168.10.200
ListenAddress 192.168.10.202

7. Disconnect SSH when no activity (ClientAliveInterval)

Once you’ve successfully logged in to the system, you might want to get disconnected when there are no activities after x number of minutes. This is basically idle timeout.
In Bash, you can achieve this using TMOUT variable.
In OpenSSH, this can be achieved by combining ClientAliveCountMax and ClientAliveInterval options in sshd_config file.
  • ClientAliveCountMax – This indicates the total number of checkalive message sent by the ssh server without getting any response from the ssh client. Default is 3.
  • ClientAliveInterval – This indicates the timeout in seconds. After x number of seconds, ssh server will send a message to the client asking for response. Deafult is 0 (server will not send message to client to check.).
If you want ssh client to exit (timeout) automatically after 10 minutes (600 seconds), modify the sshd_config file and set the following two parameters as shown below.
$ vi /etc/ssh/sshd_config
ClientAliveInterval 600
ClientAliveCountMax 0

Linux File Systems: Ext2 vs Ext3 vs Ext4


ext2, ext3 and ext4 are all filesystems created for Linux. This article explains the following:
  • High level difference between these filesystems.
  • How to create these filesystems.
  • How to convert from one filesystem type to another.

Ext2

  • Ext2 stands for second extended file system.
  • It was introduced in 1993. Developed by Rémy Card.
  • This was developed to overcome the limitation of the original ext file system.
  • Ext2 does not have journaling feature.
  • On flash drives, usb drives, ext2 is recommended, as it doesn’t need to do the over head of journaling.
  • Maximum individual file size can be from 16 GB to 2 TB
  • Overall ext2 file system size can be from 2 TB to 32 TB

Ext3

  • Ext3 stands for third extended file system.
  • It was introduced in 2001. Developed by Stephen Tweedie.
  • Starting from Linux Kernel 2.4.15 ext3 was available.
  • The main benefit of ext3 is that it allows journaling.
  • Journaling has a dedicated area in the file system, where all the changes are tracked. When the system crashes, the possibility of file system corruption is less because of journaling.
  • Maximum individual file size can be from 16 GB to 2 TB
  • Overall ext3 file system size can be from 2 TB to 32 TB
  • There are three types of journaling available in ext3 file system.
    • Journal – Metadata and content are saved in the journal.
    • Ordered – Only metadata is saved in the journal. Metadata are journaled only after writing the content to disk. This is the default.
    • Writeback – Only metadata is saved in the journal. Metadata might be journaled either before or after the content is written to the disk.
  • You can convert a ext2 file system to ext3 file system directly (without backup/restore).

Ext4

  • Ext4 stands for fourth extended file system.
  • It was introduced in 2008.
  • Starting from Linux Kernel 2.6.19 ext4 was available.
  • Supports huge individual file size and overall file system size.
  • Maximum individual file size can be from 16 GB to 16 TB
  • Overall maximum ext4 file system size is 1 EB (exabyte). 1 EB = 1024 PB (petabyte). 1 PB = 1024 TB (terabyte).
  • Directory can contain a maximum of 64,000 subdirectories (as opposed to 32,000 in ext3)
  • You can also mount an existing ext3 fs as ext4 fs (without having to upgrade it).
  • Several other new features are introduced in ext4: multiblock allocation, delayed allocation, journal checksum. fast fsck, etc. All you need to know is that these new features have improved the performance and reliability of the filesystem when compared to ext3.
  • In ext4, you also have the option of turning the journaling feature “off”.
Warning: Don’t execute any of the commands given below, if you don’t know what you are doing. You will lose your data!

Creating an ext2, or ext3, or ext4 filesystem

Once you’ve partitioned your hard disk using fdisk command, use mke2fs to create either ext2, ext3, or ext4 file system.
Create an ext2 file system:
mke2fs /dev/sda1
Create an ext3 file system:
mkfs.ext3 /dev/sda1

(or)

mke2fs –j /dev/sda1
Create an ext4 file system:
mkfs.ext4 /dev/sda1

(or)

mke2fs -t ext4 /dev/sda1

Converting ext2 to ext3

For example, if you are upgrading /dev/sda2 that is mounted as /home, from ext2 to ext3, do the following.
umount /dev/sda2

tune2fs -j /dev/sda2

mount /dev/sda2 /home
Note: You really don’t need to umount and mount it, as ext2 to ext3 conversion can happen on a live file system. But, I feel better doing the conversion offline.

Converting ext3 to ext4

If you are upgrading /dev/sda2 that is mounted as /home, from ext3 to ext4, do the following.
umount /dev/sda2

tune2fs -O extents,uninit_bg,dir_index /dev/sda2

e2fsck -pf /dev/sda2

mount /dev/sda2 /home
Again, try all of the above commands only on a test system, where you can afford to lose all your data.

Thursday, January 26, 2012

Cron Vs Anacron: How to Setup Anacron on Linux (With an Example)


Anacron is the cron for desktops and laptops.
Anacron does not expect the system to be running 24 x 7 like a server.
When you want a background job to be executed automatically on a machine that is not running 24 x 7, you should use anacron.
For example, if you have a backup script scheduled everyday at 11 PM as a regular cron job, and if your laptop is not up at 11 PM, your backup job will not be executed.
However, if you have the same job scheduled in anacron, you can be sure that it will be executed once the laptop come back up.

Anacrontab Format

Just like how cron has /etc/crontab, anacron has /etc/anacrontab.
/etc/anacrontab file has the anacron jobs mentioned in the following format.
period   delay   job-identifier   command
Field 1 is Recurrence period: This is a numeric value that specifies the number of days.
  • 1 – daily
  • 7 – weekly
  • 30 – monthly
  • N – This can be any numeric value. N indicates number of days
Note: You can also use ‘@monthly’ for a job that needs to be executed monthly.
Field 2 is Delay: This indicates the delay in minutes. i.e X number of minutes anacron should wait before executing the job after the the machine starts.
Field 3 is Job identifier: It is the name for the job’s timestamp file. It should be unique for each job. This will be available as a file under the /var/spool/anacron directory. This file will contain a single line that indicates the last time when this job was executed.
# ls -1 /var/spool/anacron/
test.daily
cron.daily
cron.monthly
cron.weekly

# cat /var/spool/anacron/test.daily
20110507
Field 4 is command: Command or shell script that needs to be executed.
Just like shell scripts, comments inside anacrontab file starts with #
Note: For /etc/crontab file format, refer to our Linux Crontab: 15 Awesome Cron Job Examplesarticle.

Anacron Example

The following example executes the /home/sathiya/backup.sh script once in every 7 days.
On the day when the backup.sh job is supposed to executed, if the system is down for some reason, anacron will execute the backup.sh script 15 minutes after the system comes back up (without having to wait for another 7 days).
# cat /etc/anacrontab
7       15      test.daily      /bin/sh /home/sathiya/backup.sh

START_HOURS_RANGE and RANDOM_DELAY

The above example indicates that the backup.sh script should be executed every day, with a delay of 15 mins. i.e When the laptop was started, executed it only after 15 minutes.
What happens when the laptop or desktop was not shutdown? When does the job gets executed? This is specified by the START_HOURS_RANGE environment variable in the /etc/anacrontab file.
By default this is set to 3-22 in the file. This indicates the time range from 3 a.m to 10 p.m.
# grep START /etc/anacrontab
START_HOURS_RANGE=3-22
On top of the user defined delay specified in the 2nd field of the /etc/anacrontab file, anacron also randomly adds x number of minutes. The x is defined by the RANDOM_DELAY variable in the /etc/anacrontab file.
By default this is set to 45 in the file. This means that anacron will add x minutes (randomly picked from 0 and 45), and add this to the user defined delay.
# grep RANDOM /etc/anacrontab
RANDOM_DELAY=45

Cron Vs Anacron

Cron and anacron has its own advantages and disadvantages. Depending on your requirement, use one of them.
CronAnacron
Minimum granularity is minute (i.e Jobs can be scheduled to be executed every minute)Minimum granularity is only in days
Cron job can be scheduled by any normal user ( if not restricted by super user )Anacron can be used only by super user ( but there are workarounds to make it usable by normal user )
Cron expects system to be running 24 x 7. If a job is scheduled, and system is down during that time, job is not executed.Anacron doesn’t expect system to be running 24 x 7. If a job is scheduled, and system is down during that time, it start the jobs when the system comes back up.
Ideal for serversIdeal for desktops and laptops
Use cron when a job has to be executed at a particular hour and minuteUse anacron when a job has to be executed irrespective of hour and minute

Subversion Tutorial: 10 Most Used SVN Commands with Examples


SVN stands for Subversion.
Subversion is a free/open-source version control system. Subversion manages files and directories over time. A tree of files is placed into a central repository. The repository is much like an ordinary file server, except that it remembers every change ever made to your files and directories. This allows you to recover older versions of your code, or examine the history of how your code was changed.
This article explains some basic SVN commands with examples.

SVN Working Copy

SVN is a repository that holds all our versioned data, which is also called as SVN server. SVN client program which manages local reflections of portions of that versioned data which is called as working copy. SVN client can access its repository across networks. Multiple users can access the repository at the same time.

1. SVN Checkout – Create working copy

Checkout command is used to download sources from SVN repository to working copy. If you want to access files from the SVN server, checkout is the first operation you should perform.
SVN checkout creates the working copy, from where you can do edit, delete, or add contents. You can checkout a file, directory, trunk or whole project. To checkout you should know URL of the components you want to checkout.
Syntax:

$ svn checkout/co URL PATH
  • URL is the URL of the components to checkout
  • If PATH is omitted, the basename of the URL will be used as the destination. If multiple URLs are given each will be checked out into a subdirectory of PATH, with the name of the subdirectory being the basename of the URL.
The following example checks out the directory to the given target directory.
$ svn co https://www.sureshkumarpakalapati.in/project/branches/release/migration/data/cfg /home/sasikala/cfg/
A    /home/sasikala/cfg/ftp_user.cfg
A    /home/sasikala/cfg/inventory.cfg
A    /home/sasikala/cfg/email_user.cfg
A    /home/sasikala/cfg/svn-commands
Checked out revision 811.

$ ls /home/sasikala/cfg
.  ..  .svn  email_user.cfg  ftp_user.cfg  inventory.cfg  svn-commands
When you do a checkout, it creates hidden directory named .svn, which will have the repository details.

2. SVN Commit – Save changes to the repository

Whenever you do changes to the working copy, it will not reflect in SVN server. To make the changes permanent, you need to do SVN commit.
Syntax:

$ svn commit -m "log messages"
Explain why you are changing the file in the -m option.
For example, in my working copy, the file named “svn-commands” has the following content.
$ cat /home/sasikala/cfg/svn-commands
checkout
commit
add
delete
update
status

$ ls -l /home/sasikala/cfg/svn-commands
-rw-r--r--  1 root root 41 Apr 16 11:15 svn-commands
I made a change in this file (for example, making this file empty).
$ ls -l svn-commands
-rw-r--r--  1 root root 0 Apr 16 11:20 svn-commands
Now commit the file to make the changes permanent in the server.
$ svn commit -m "Making the file empty" svn-commands
Sending        svn-commands
Transmitting file data .
Committed revision 813.
After this whenever you update your working copy or checkout, the changes will appear in the server.

3. SVN List – Lists directory entries

svn list is useful when you want to view the content of the SVN repository, without downloading a working copy.
Syntax:

$ svn list
The following example lists all the files available in the given URL in the repository without downloading a working copy. When you execute svn list command with –verbose option it displays the following information.
  • Revision number of the last commit
  • Author of the last commit
  • Size (in bytes)
  • Date and time of the last commit
$ svn list --verbose https://www.sureshkumarpakalapati.in/project/branches/release/migration/data/bin
 16 sasikala 28361  Apr 16 21:11 README.txt
 21 sasikala  0  Apr 18 12:22 INSTALL
 22 sasikala  Apr 18 10:17 src/

4. SVN Add – Add a new file to SVN repository

When you want to add a new file (or directory) to the repository you need to use SVN add command. The repository will have newly added file, only when you do SVN commit. Now let us add a new file called “sureshstuff” to our repository.
  • Create a file in local working copy
  • $ ls -l /home/sasikala/cfg/sureshstuff
    -rw-r--r--  1 sasikala root 8 Apr 16 11:33 sureshstuff
  • Add the file into SVN repository
  • svn add filename will add the files into SVN repository.
    $ svn add sureshstuff
    A        sureshstuff
  • Commit the added the file
  • Until you commit, the added file will not be available in the repository.
    $ svn commit -m "Adding a file sureshstuff" sureshstuff
    Adding         sureshstuff
    Transmitting file data .
    Committed revision 814.

5. SVN Delete – Removing a file from repository

SVN delete command deletes an item from the working copy (or repository). File will be deleted from the repository when you do a SVN commit.
Syntax:
$ svn delete URL
Now let us remove the recently created file called “sureshstuff”.
$ svn delete sureshstuff
D         sureshstuff

$ svn commit -m "Removing sureshstuff file" sureshstuff
Deleting       sureshstuff
Committed revision 814.
Now you can do svn list and check whether the file was deleted from the repository.

6. SVN Diff – Display the difference

SVN diff displays the differences between your working copy and the copy in the SVN repository. You can find the difference between two revisions and two paths etc.,
Syntax:
$ svn diff filename

$ svn -r R1:R2 diff filename
The above example compares the filename@R1 and filename@R2.
Now the content of the file sureshstuff looks like this,
$ cat /home/sasikala/cfg/sureshstuff
testing
I edited the content of sureshstuff file from testing to tester, which is shown below using the svn diff command.
$ svn diff sureshstuff
Index: SURESHstuff
===================================================================
--- sureshstuff   (revision 815)
+++ sureshstuff   (working copy)
@@ -1 +1 @@
-testing
+tester

7. SVN Status – Status of the working copy

Use svn status command to get the status of the file in the working copy. It displays whether the working copy is modified, or its been added/deleted, or file is not under revision control, etc.
Syntax:

$ svn status PATH
The following example shows the status of my local working copy,
$ svn status /home/sasikala/cfg
M     /home/sasikala/cfg/ftp_user.cfg
M       /home/sasikala/cfg/sureshstuff
‘M’ represents that the item has been modified. “svn help status” command will explain various specifiers showed in SVN status command.

8. SVN Log – Display log message

As we discussed in the beginning of this article, SVN remembers every change made to your files and directories. To know all the commits made in a file or directory, use SVN log command.
Syntax:

$ svn log PATH
The following displays all the commits made on sureshstuff file
$ svn log sureshstuff
------------------------------------------------------------------------
r815 | sasikala | 2011-04-16 05:14:18 -0700 (Sat, 16 Apr 2011) | 1 line

Adding a file sureshstuff
------------------------------------------------------------------------
Since we made only one commit in the file sureshstuff, it shows only one log message with the details.

9. SVN Move – Rename file or directory

This command moves a file from one directory to another or renames a file. The file will be moved on your local sandbox immediately (as well as on the repository after committing).
Syntax:
$ svn move src dest
The following command renames the file “sureshstuff” to “tgs” in a single stroke.
$ svn move sureshstuff tgs
A         tgs
D         sureshstuff

$ ls
.#  ..  .svn  email_user.cfg  ftp_user.cfg  inventory.cfg  tgs
Now the file is renamed only in the working copy, not in the repository. To make the changes permanent, you need to commit the changes.
$ svn commit -m "Renaming sureshstuff to tgs" tgs
Adding         tgs
Transmitting file data .
Committed revision 816.

10. SVN Update – Update the working copy.

svn update command brings changes from the repository into your working copy. If no revision is specified, it brings your working copy up-to-date with the HEAD revision. Otherwise, it synchronizes the working copy to the revision given in the argument.
Always before you start working in your working copy, update your working copy. So that all the changes available in repository will be available in your working copy. i.e latest changes.
Syntax:

$ svn update PATH
In case some other user added/deleted file in URL, https://www.sureshkumarpakalapati.in/project/branches/release/migration/data/cfg, your working copy will not have those files by default, until you update your working copy.
$ svn update
A  new/usercfg
A  new/webcfg
Updated to revision 819.
In the above svn update command output, A represents that this file is “Added” to the working copy.