OpenSSH is the implementation of the SSH protocol. OpenSSH is recommended for remote login, making backups, remote file transfer via scp or sftp, and much more. SSH is perfect to keep confidentiality and integrity for data exchanged between two networks and systems. However, the main advantage is server authentication, through the use of public key cryptography. From time to time there are rumors about OpenSSH zero day exploit. Here are a few things you need to tweak in order to improve OpenSSH server security.

Default Config Files and SSH Port

/etc/ssh/sshd_config – OpenSSH server configuration file.

/etc/ssh/ssh_config – OpenSSH client configuration file.

~/.ssh/ – Users ssh configuration directory.

~/.ssh/authorized_keys or ~/.ssh/authorized_keys – Lists the public keys (RSA or DSA) that can be used to log into the user’s account

/etc/hosts.allow and /etc/hosts.deny : Access controls lists that should be enforced by tcp-wrappers are defined here.

SSH default port : TCP 22

SSH Session in Action

#1: Disable OpenSSH Server

Workstations and laptop can work without OpenSSH server. If you need not to provide the remote login and file transfer capabilities of SSH, disable and remove the SSHD server. CentOS / RHEL / Fedora Linux user can disable and remove openssh-server with yum command:# chkconfig sshd off
# yum erase openssh-server
Debian / Ubuntu Linux user can disable and remove the same with apt-get command:# apt-get remove openssh-server
You may need to update your iptables script to remove ssh exception rule. Under CentOS / RHEL / Fedora edit the files /etc/sysconfig/iptables and /etc/sysconfig/ip6tables. Once donerestart iptables service:# service iptables restart
# service ip6tables restart

#2: Only Use SSH Protocol 2

SSH protocol version 1 (SSH-1) has man-in-the-middle attacks problems and security vulnerabilities. SSH-1 is obsolete and should be avoided at all cost. Open sshd_config file and make sure the following line exists:

Protocol 2

#3: Limit Users’ SSH Access

By default all systems user can login via SSH using their password or public key. Sometime you create UNIX / Linux user account for ftp or email purpose. However, those user can login to system using ssh. They will have full access to system tools including compilers and scripting languages such as Perl, Python which can open network ports and do many other fancy things. One of my client has really outdated php script and an attacker was able to create a new account on the system via a php script. However, attacker failed to get into box via ssh because it wasn’t in AllowUsers.

Only allow root, vivek and jerry user to use the system via SSH, add the following to sshd_config:

AllowUsers root vivek jerry

Alternatively, you can allow all users to login via SSH but deny only a few users, with the following line:

#4: Configure Idle Log Out Timeout Interval

User can login to server via ssh and you can set an idel timeout interval to avoid unattended ssh session. Open sshd_config and make sure following values are configured:

ClientAliveInterval 300
ClientAliveCountMax 0

You are setting an idle timeout interval in seconds (300 secs = 5 minutes). After this interval has passed, the idle user will be automatically kicked out (read as logged out). See how to automatically log BASH / TCSH / SSH users out after a period of inactivity for more details.

#5: Disable .rhosts Files

Don’t read the user’s ~/.rhosts and ~/.shosts files. Update sshd_config with the following settings:

IgnoreRhosts yes

SSH can emulate the behavior of the obsolete rsh command, just disable insecure access via RSH.

#6: Disable Host-Based Authentication

To disable host-based authentication, update sshd_config with the following option:

HostbasedAuthentication no

#7: Disable root Login via SSH

There is no need to login as root via ssh over a network. Normal users can use su or sudo (recommended) to gain root level access. This also make sure you get full auditing information about who ran privileged commands on the system via sudo. To disable root login via SSH, update sshd_config with the following line:

Saying “don’t login as root” is h******t. It stems from the days when people sniffed the first packets of sessions so logging in as yourself and su-ing decreased the chance an attacker would see the root pw, and decreast the chance you got spoofed as to your telnet host target, You’d get your password spoofed but not root’s pw. Gimme a break. this is 2005 – We have ssh, used properly it’s secure. used improperly none of this 1989 will make a damn bit of difference. -Bob

#8: Enable a Warning Banner

Set a warning banner by updating sshd_config with the following line:

Banner /etc/issue

Sample /etc/issue file:

----------------------------------------------------------------------------------------------
You are accessing a XYZ Government (XYZG) Information System (IS) that is provided for authorized use only.
By using this IS (which includes any device attached to this IS), you consent to the following conditions:
+ The XYZG routinely intercepts and monitors communications on this IS for purposes including, but not limited to,
penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM),
law enforcement (LE), and counterintelligence (CI) investigations.
+ At any time, the XYZG may inspect and seize data stored on this IS.
+ Communications using, or data stored on, this IS are not private, are subject to routine monitoring,
interception, and search, and may be disclosed or used for any XYZG authorized purpose.
+ This IS includes security measures (e.g., authentication and access controls) to protect XYZG interests--not
for your personal benefit or privacy.
+ Notwithstanding the above, using this IS does not constitute consent to PM, LE or CI investigative searching
or monitoring of the content of privileged communications, or work product, related to personal representation
or services by attorneys, psychotherapists, or clergy, and their assistants. Such communications and work
product are private and confidential. See User Agreement for details.
----------------------------------------------------------------------------------------------

*BSD PF Firewall Configuration

#9: Change SSH Port and Limit IP Binding

By default SSH listen to all available interfaces and IP address on the system. Limit ssh port binding and change ssh port (by default brute forcing scripts only try to connects to port # 22). To bind to 192.168.1.5 and 202.54.1.5 IPs and to port 300, add or correct the following line:

Port 300
ListenAddress 192.168.1.5
ListenAddress 202.54.1.5

A better approach to use proactive approaches scripts such as fail2ban or denyhosts (see below).

#10: Use Strong SSH Passwords and Passphrase

It cannot be stressed enough how important it is to use strong user passwords and passphrase for your keys. Brute force attack works because you use dictionary based passwords. You can force users to avoid passwords against a dictionary attack and use john the ripper tool to find out existing weak passwords. Here is a sample random password generator (put in your ~/.bashrc):

#11: Use Public Key Based Authentication

Use public/private key pair with password protection for the private key. See how to use RSAand DSA key based authentication. Never ever use passphrase free key (passphrase key less) login.

#12: Use Keychain Based Authentication

keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. It offers various security benefits over passphrase-free keys. See how to setup and use keychain software.

#13: Chroot SSHD (Lock Down Users To Their Home Directories)

By default users are allowed to browse the server directories such as /etc/, /bin and so on. You can protect ssh, using os based chroot or use special tools such as rssh. With the release of OpenSSH 4.8p1 or 4.9p1, you no longer have to rely on third-party hacks such as rssh or complicated chroot(1) setups to lock users to their home directories. See this blog post about new ChrootDirectory directive to lock down users to their home directories.

#14: Use TCP Wrappers

TCP Wrapper is a host-based Networking ACL system, used to filter network access to Internet. OpenSSH does supports TCP wrappers. Just update your /etc/hosts.allow file as follows to allow SSH only from 192.168.1.2 172.16.23.12 :

#15: Disable Empty Passwords

You need to explicitly disallow remote login from accounts with empty passwords, update sshd_config with the following line:

PermitEmptyPasswords no

#16: Thwart SSH Crackers (Brute Force Attack)

Brute force is a method of defeating a cryptographic scheme by trying a large number of possibilities using a single or distributed computer network. To prevents brute force attacks against SSH, use the following softwares:

DenyHosts is a Python based security tool for SSH servers. It is intended to prevent brute force attacks on SSH servers by monitoring invalid login attempts in the authentication log and blocking the originating IP addresses.

Brute Force Detection A modular shell script for parsing application logs and checking for authentication failures. It does this using a rules system where application specific options are stored including regular expressions for each unique auth format.

*BSD PF Example

The following will limits the maximum number of connections per source to 20 and rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.

#18: Use Port Knocking

Port knocking is a method of externally opening ports on a firewall by generating a connection attempt on a set of prespecified closed ports. Once a correct sequence of connection attempts is received, the firewall rules are dynamically modified to allow the host which sent the connection attempts to connect over specific port(s). A sample port Knocking example for ssh using iptables:

#19: Use Log Analyzer

Read your logs using logwatch or logcheck. These tools make your log reading life easier. It will go through your logs for a given period of time and make a report in the areas that you wish with the detail that you wish. Make sure LogLevel is set to INFO or DEBUG in sshd_config:

LogLevel INFO

#20: Patch OpenSSH and Operating Systems

It is recommended that you use tools such as yum, apt-get, freebsd-update and others to keep systems up to date with the latest security patches.

Other Options

To hide openssh version, you need to update source code and compile openssh again. Make sure following options are enabled in sshd_config:

# Turn on privilege separation
UsePrivilegeSeparation yes
# Prevent the use of insecure home directory and key file permissions
StrictModes yes
# Turn on reverse name checking
VerifyReverseMapping yes
# Do you need port forwarding?
AllowTcpForwarding no
X11Forwarding no
# Specifies whether password authentication is allowed. The default is yes.
PasswordAuthentication no

The receiving machine will connect to the Linode. Type yes and press Enter to continue connecting:

The authenticity of host '123.45.67.89 (123.45.67.89)' can't be established.
RSA key fingerprint is 39:6b:eb:05:f1:28:95:f0:da:63:17:9e:6b:6b:11:4a.
Are you sure you want to continue connecting (yes/no)? yes

Enter the root password for the Linode, as shown below

Warning: Permanently added '123.45.67.89' (RSA) to the list of known hosts.
root@123.45.67.89's password:

A standard Rackspace Linux Cloud Server image is set up with two partitions: one for the root file system and the other for the swap partition. This partition layout is sufficient for most servers and you usually won’t need to change it. However, there are circumstances where customised partitioning is required. If you need custom partitions, read on.

One of the common Rackspace Cloud hypervisors (the backend software running everything) is Citrix Xen Server 5.x, the default for our newer stock images. If your Cloud server is running on this platform it will have two block devices defined, /dev/xvda and /dev/xvdc. The /dev/xvda1 device houses the root partition with all your data and operating system, while /dev/xvdc1 operates as the swap partition.

Enter Rescue Mode

The root partition contains the active operating system, so we have to put the file system off-line before we can change its partition size. We’ll do this by putting the Cloud Server in rescue mode.

All commands used in this article are based on a 256MB CentOS Cloud Server but should apply to Cloud Servers on other Linux distributions as well.

Locate Root Partition

Once you’ve put your server into rescue mode, log on via ssh and run this command at the command prompt:

tune2fs -O ^has_journal /dev/xvdb1
Next check the current data size on the partition:

mount -oro /dev/xvdb1 /mnt; df -h /dev/xvdb1; umount /mnt
Output:

Filesystem Size Used Avail Use% Mounted on
/dev/xvdb1 9.4G 649M 8.3G 8% /mnt
In the example above 649MB of 9.4GB is used. We need to account for the space used by the operating system when we change the partition size. For our example we’ll plan to shrink it to 4GB.

To be on the safe side we’ll actually start by shrinking the root file system to a bit under our target (in this case, 3GB) to make sure it will fit the new partition. We’ll expand it to 4GB once we have our partition sizes set.

Shrink the file system to 3GB with the command:

resize2fs /dev/xvdb1 3G
If successful the output will look like this:

resize2fs 1.41.12 (17-May-2010)
Resizing the filesystem on /dev/xvdb1 to 786432 (4k) blocks.
The filesystem on /dev/xvdb1 is now 786432 blocks long.
If we check the size again:

mount -oro /dev/xvdb1 /mnt; df -h /dev/xvdb1; umount /mnt
We see:

Filesystem Size Used Avail Use% Mounted on
/dev/xvdb1 3.0G 642M 2.2G 23% /mnt
Hooray, the root file system is changed! The new file system is much smaller than the partition it resides. You may notice the used size value has changed from before. That reflects the file system storing metadata that describes the partition – a smaller partition needs less metadata space. There is no data lost.

Shrink Partition

This is the most dangerous part of the whole task. The file system will be damaged if the disk space it requires for files is larger than partition where it resides. Make sure you have a backup of your data.

Before we make any changes we’ll check the current partition layout with this command:

sfdisk -d /dev/xvdb > /root/xvdb.out
And use a text editor such as nano to open xvdb.out:

nano /root/xvdb.out
You will see the size of xvdb1 is 19920896, which is the maximum size for a partition on a 256MB Cloud Server. You may have a bigger Cloud Server and see a bigger partition size. The unit used in the size measurement is the “sector”; one sector is 512 bytes as you can see from the output of “sfdisk -uS -l /dev/xvdb”. That means the size value for 4GB is:

4GB / unit size = 4*1024*1024*1024 bytes / 512 bytes = 8388608
Edit the /root/xvbd.out file to change the size value for the /dev/xvdb1 partition to what we want. For our example server the end result will look like this:

If you created or changed a DOS partition, /dev/foo7, say, then use dd(1)
to zero the first 512 bytes: dd if=/dev/zero of=/dev/foo7 bs=512 count=1
(See fdisk(8).)
The /dev/xvdb1 partition is now changed to 4GB.

Align File System Size

Now we are going to expand the file system to fill the new partition, changing the file system from 3GB to 4GB.

resize2fs /dev/xvdb1
Output:

resize2fs 1.41.12 (17-May-2010)
Resizing the filesystem on /dev/xvdb1 to 1048576 (4k) blocks.
The filesystem on /dev/xvdb1 is now 1048576 blocks long.
Verify what we did by running:

mount -oro /dev/xvdb1 /mnt; df -h /dev/xvdb1; umount /mnt
Output:

Filesystem Size Used Avail Use% Mounted on
/dev/xvdb1 4.0G 647M 3.2G 17% /mnt
All good, the new size of 4.0G is what we expected.

Enable Journaling

Before we finish, don’t forget to enable journaling for the file system, since we disabled it earlier. An EXT3 file system without journaling is EXT2 – that will still work, but it wouldn’t have the safeguards of EXT3.

Go back to the Cloud Control Panel and have your server exit rescue mode. When it comes back up, connect to the server via SSH or the console.

Create New Partition

Assuming there are no problems, everything is ready. You can create new partitions from the free space you extracted from the root partition /dev/xvda1.

Before the change:

fdisk -l /dev/xvda | grep -B1 xvd
Output:

Disk /dev/xvda: 10.2 GB, 10200547328 bytes
—
Device Boot Start End Blocks Id System
/dev/xvda1 27 110404 4194304 83 Linux
Let us create a new partition as an example. The single English letters in bold are what you need to key-in to respond to prompts:

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.
Let’s check the partitions again:

fdisk -l /dev/xvda | grep -B1 xvd
Output:

Disk /dev/xvda: 10.2 GB, 10200547328 bytes
—
Device Boot Start End Blocks Id System
/dev/xvda1 27 110404 4194304 83 Linux
/dev/xvda2 110404 262144 5766144 83 Linux
As you can see from the output above, you have a new partition /dev/xvda2. You may reboot your server:

reboot
Then log back in and format the new partition:

mkfs -t ext3 /dev/xvda2
Finally, mount it to wherever you want such as /mnt like this:

The postgresql-server package includes the programs needed to create and run a PostgreSQL server, which will in turn allow you to create
and maintain PostgreSQL databases. PostgreSQL is an advanced Object-Relational database management system (DBMS) that supports almost all SQL constructs (including transactions, subselects and user-defined types and functions). You should install postgresql-server if you want to create and maintain your own PostgreSQL databases and/or your own PostgreSQL server. You also need to install the postgresql package.

You also need to install client package called postgrsql. This package contains the docs in HTML for the whole package, as well as command-line utilities for managing PostgreSQL databases on a PostgreSQL server.

Welcome to psql 8.1.9, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
Open TCP port 5432

Server migration

Migrating your data from one Linux server to another is only a simple affair if you’ve been running a simple server. If you have a lot of interdependent services or a highly customized setup then recreating your environment from scratch is an involved process. It gets less complex if you can copy over just the files you need without worrying about overwriting system files specific to the new server.

So that’s what we’re going to do here. We’ll look at how to prepare for a migration and what tools will make the job go easier. Continue reading →