Friday, June 5, 2015

HowTo: Setup SSH Keys on a Linux / Unix System


HowTo: Setup SSH Keys on a Linux / Unix System

I recently read that SSH keys provide a secure way of logging into a Linux and Unix-based server. How do I set up SSH keys on a Linux or Unix based systems? In SSH for Linux/Unix, how do I set up public
key authentication?

I am assuming that you are using Linux or Unix-like server and client with the following software:
  • OpenSSH SSHD server
  • OpenSSH ssh client and friends on Linux (Ubuntu, Debian, {Free,Open,Net}BSD, RHEL, CentOS, OSX and co).

What is a public key authentication?

OpenSSH server supports various authentication schema. The two most popular are as follows:
  1. Passwords based authentication
  2. Public key based authentication. It is an alternative security method to using passwords. This method is recommended on a VPS, cloud, dedicated or even home based server.

How do I set up public key authentication?

You must generate both a public and a private key pair. For example:
                        ///////////
                       //Internet//
                       ////////////
                            |
     +---------------+      |       +-------------+
     | Unix/Linux    |      |       | Linux/Unix  |
     | Server with   +------+-------+ OSX/*BSD    |
     | OpenSSH SSHD  |              | Client      |
     +---------------+              +-------------+
  server1.cyberciti.biz          client1.cyberciti.biz
     75.126.153.206                  192.168.1.42
Where,
  • server1.cyberciti.biz - You store your public key on the remote hosts and you have an accounts on this Linux/Unix based server.
  • client1.cyberciti.biz - Your private key stays on the desktop/laptop/ computer (or local server) you use to connect to server1.cyberciti.biz server. Do not share or give your private file to anyone.
In public key based method you can log into remote hosts and server, and transfer files to them, without using your account passwords. Feel free to replace server1.cyberciti.biz and client1.cyberciti.biz names with your actual setup. Enough talk, let's set up public key authentication. Open the Terminal and type following commands if .ssh directory does not exists:
 
mkdir -p $HOME/.ssh
chmod 0700 $HOME/.ssh
 

#1: Create the key pair

On the computer (such as client1.cyberciti.biz), generate a key pair for the protocol.
 
ssh-keygen -t rsa
 
Sample outputs:
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/vivek/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/vivek/.ssh/id_rsa.
Your public key has been saved in /Users/vivek/.ssh/id_rsa.pub.
The key fingerprint is:
80:5f:25:7c:f4:90:aa:e1:f4:a0:01:43:4e:e8:bc:f5 vivek@desktop01
The key's randomart image is:
+--[ RSA 2048]----+
| oo    ...+.     |
|.oo  .  .ooo     |
|o .o. . .o  .    |
| o ...+o.        |
|  o .=.=S        |
| .  .Eo .        |
|                 |
|                 |
|                 |
+-----------------+
You need to set the Key Pair location and name. I recommend you use the default location if you do not yet have another key there, for example: $HOME/.ssh/id_rsa. You will be prompted to supply a passphrase (password) for your private key. I suggest that you setup a passphrase when prompted. You should see two new files in $HOME/.ssh/ directory:
  1. $HOME/.ssh/id_rsa - contains your private key.
  2. $HOME/.ssh/id_rsa.pub - contain your public key.

#2: Install the public key in remote server

Use scp or ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your account on the remote server/host (e.g., nixcraft@server1.cyberciti.biz). To do so, enter the following command on your client1.cyberciti.biz:
 
ssh-copy-id -i $HOME/.ssh/id_rsa.pub user@server1.cyberciti.biz
 
OR just copy the public key in remote server as authorized_keys in ~/.ssh/ directory:
 
scp $HOME/.ssh/id_rsa.pub user@server1.cyberciti.biz:~/.ssh/authorized_keys
 

A note about appending the public key in remote server

On some system ssh-copy-id command may not be installed, so use the following commands (when prompted provide the password for remote user account called vivek) to install and append the public key:
## First create .ssh directory on server ##
ssh vivek@server1.cyberciti.biz "umask 077; test -d .ssh || mkdir .ssh"
 
## cat local id.rsa.pub file and pipe over ssh to append the public key in remote server ##
cat $HOME/.ssh/id_rsa.pub | ssh vivek@server1.cyberciti.biz "cat >> .ssh/authorized_keys"
 

#3: Test it (type command on client1.cyberciti.biz)

The syntax is:
 
ssh user@server1.cyberciti.biz
 
Or copy a text file called foo.txt:
 
scp foo.txt user@server1.cyberciti.biz:/tmp/
 
You will be prompted for a passphrase. To get rid of passphrase whenever you log in the remote host, try ssh-agent and ssh-add commands.

What are ssh-agent and ssh-add, and how do I use them?

To get rid of a passphrase for the current session, add a passphrase to ssh-agent and you will not be prompted for it when using ssh or scp/sftp/rsync to connect to hosts with your public key. The syntax is as follows:
 
eval $(ssh-agent)
 
Type the ssh-add command to prompt the user for a private key passphrase and adds it to the list maintained by ssh-agent command:
 
ssh-add
 
Enter your private key passphrase. Now try again to log into user@server1.cyberciti.biz and you will not be prompted for a password:
 
ssh user@server1.cyberciti.biz
 

#4: Disable the password based login on a server

Login to your server, type:
## client commands ##
eval $(ssh-agent)
ssh-add
ssh user@server1.cyberciti.biz<
Edit /etc/ssh/sshd_config on server1.cyberciti.biz using a text editor such as nano or vim:
$ sudo vim /etc/ssh/sshd_config
OR directly jump to PermitRootLogin line using a vim text editor:
$ sudo vim +/PermitRootLogin /etc/ssh/sshd_config
Find PermitRootLogin and set it as follows:
 
PermitRootLogin no
 
Save and close the file. Reload/restart sshd server, type command as per your Linux/Unix version:
## CentOS/RHEL/Fedora Linux server reload sshd ##
sudo service sshd reload
 
## Debian/Ubuntu Linux server reload sshd ##
/etc/init.d/ssh reload
 
## Generic Unix method to reload sshd ##
kill -HUP `cat /var/run/sshd.pid`
 

#5: How to add or replace a passphrase for an existing private key?

 
ssh-keygen -p
 

#6: How to backup an existing private/public key?

Just copy files to your backup server or external USB pen/hard drive:
## Copy files to  home based nas server ##
rsync -avr $HOME/.ssh user@home.nas-server:/path/to/encrpted/nas/partition/
 
## Copy files to  usb pen drive mounted at /mnt/usb ##
cp -avr $HOME/.ssh/ /mnt/usb/backups/
 

Monday, June 1, 2015

How To Do A Full Backup Using The tar Command


How To Do A Full Backup
Using The tar Command



It's a good idea to do a full backup of the hard-drive after the initial installation as well as when you finally get your server set up the way you want. Having a snapshot of your system right after the initial installation gives you something to revert back to should you want to reconfigure your server without starting from scratch. Linux has many backup utilities but the old standard is still the favorite of admins because of the flexibility offered by its myriad of options. 

tar commands can become quite complex. It's easier to enter the command in a text file and make it a shell script. We also need to create a directory to hold the backup file. We'll use a separate directory so we can exclude that directory from the backup (we don't want tar trying to backup a file it's in the process of creating). Enter the following commands:

cd /
mkdir backups
cd backups

Then use the nano editor to create our shell script file with the command:

nano fullserver.sh

and enter the following command into it (and don't miss that period at the end of the command):

tar -cvpf /backups/fullbackup.tar --directory=/ --exclude=proc
--exclude=sys --exclude=dev/pts --exclude=backups .

The above command is on multiple lines for readability. Enter everything on the same line when entering the command in the editor. Once entered, exit the editor (Ctrl-X) saving the file. 

The c option creates the backup file. 

The v option gives a more verbose output while the command is running. This option can also be safely eliminated. 

The p option preserves the file and directory permissions. 

The f option needs to go last because it allows you to specify the name and location of the backup file which follows next in the command (in our case this is the /backups/fullbackup.tar file). 

The --directory option tells tar to switch to the root of the file system before starting the backup. 

We --exclude certain directories from the backup because the contents of the directories are dynamically created by the OS. We also want to exclude the directory that contains are backup file. 

Many tar references on the Web will give an exclude example as:

--exclude=/proc

However, this will often result in excluded directories still being backed up because there should not be the leading / (slash) character in front of the directory names. If you were to use the above example, tar would back up the proc directory which would result in errors saying that files had changed since they were read. 

In addition to holding your backup file, the /backups directory now holds your script file also. You have to make your script executable before you can run it. To do that and run it enter the following two commands:

chmod 750 /backups/fullserver.sh
./backups/fullserver.sh

To restore your "tar ball" you need to copy it to the top-most point in the file tree that it backed up. In our case the --directory option told tar to start backing up from the root of the file system so that's where we would want to copy the tar ball to. Then simply replace the c option with the x parameter line so:

tar -xvpf /fullbackup.tar

Having a backup file is nice but not of much use if the hard-drive itself fails. If your server is running the wu-ftpd FTP server daemon, you should FTP the tar ball off of your server so that it is stored on a different system. 

Note that with the use of the --exclude statements when doing the backup, the tar backup file (tar ball) isn't something you could use to do a "bare metal" restore (because the excluded directories would be missing). However, it does work very well if you do an initial vanilla install of the OS and then un-tar your tar ball on top of that. 

Saving Space With Compression 

You can compress your backup files to save storage space. Because a lot of Linux files are text files the space savings can be significant. Enough, perhaps, to be able to fit your archive file on a CD or DVD. 

To enable the compression you have to add the z switch to both the tar-ing and untar-ing commands. You also have to change the file name to indicate the compression. Our tar-ing command becomes:

tar -zcvpf /backups/fullbackup.tar.gz --directory=/ --exclude=proc
--exclude=sys --exclude=dev/pts --exclude=backups .

Likewise, our untar-ing command becomes:

tar -zxvpf /fullbackup.tar.gz