Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Passwordless SSH login

News SSH Recommended Links Reference SSH troubleshooting ssh-keygen SSH autologin Typical mistakes
Private and Public key management Reverse SSH Tunnels VNC over SSH          
SCP sftp Mini-tutorial Tips   Sysadmin Horror Stories Humor Etc

Introduction

Usually the remote Unix/Linux system authenticates you against the /etc/passwd or /etc/shadow file. That means each time you login or ftp something to the computer you need to enter your password for the remote system which you are accessing. That creates problem if the number of computers you access is large. You can't use a single password because this is a security hole and you can't use different passwords, because it is difficult to remember them all. People usually are good at remembering 5-7 passwords maximum. After that problems start.

There are many ways of improving this situation (using one time password generator like SecurID or other tokens, use of smartcards, buying a watch that can store passwords like Casio Databank, or using your smartphone as password directory (actually in view of recent events a very bad idea), etc.

But the SSH "password-less" authentication method is probably one of the best. It is based on public-key cryptography.

SSH provides two solutions to allow remote logins without password:

The whole process consists or two simple steps:

Keys generation

A private/public keys pair is generated using ssh-keygen command line utility.

Here there are several options as there are several versions of the SSH protocol and OpenSSH 2.5 and higher can generate several different types of keys (default is RSA):

Usually with ssh2 RSA is used, but you can have both keys generated and use them for different purposes, for example one for access from your desktop or laptop and one from other servers. 
Usually with ssh2 RSA is used, but you can have both keys generated and use them for different purposes, for example one for access from your desktop or laptop and one from other servers. 

The user will be prompted three times during the generation of the keys: once for the name of the output file and twice for the passphrase. Is case of passwordless certificates you can just hit Enter three times.

During a login, SSH checks for the existence of the file named authorized_keys in the user's ~/.ssh directory on the remote server. This file should have permissions 600 and owned by the user who owns this account.

It contains the list of public keys of users allowed to login to this account. The following occurs during the authentication process:

  1. The client informs the server which public key is being used for authentication.
  2. The server checks to see if the public key is known.
  3. The server encrypts a random number using the public key and transfers this to the client.
  4. Only the client is able to decrypt the random number with its private key.
  5. The client sends the server an MD5 checksum that it has calculated from the number.

Placement of the keys and protection of the private key

After a user created the pair he needs to place his private key to a proper directory of the client he uses (on Windows it's usually Teraterm or Putty).  It you need to provide passwordless logon from the other server or workstation on the Internet use additional key, not copy the one you just generated.

Then the user needs to distribute his public key by appending it to the ~/.ssh/authorized_keys in his home directory (or root home directory) on each remote server or creating a new one with his public key if it does not exists.

It is important to understand that:

NOTE: The distribution of private key via Internet can be intercepted. It is generally a bad idea. In no way private key can be downloaded in non-encrypted form or, worse, via non-encrypted protocol such as ftp. Even when you encrypt the key using traditional cryptography (for example triple DEC with password) private key distribution over Internet is a risk.

Typical errors

The distribution of private key via Internet can be intercepted. It is generally a bad idea. In no way private key can be downloaded in non-encrypted form or, worse, via via non-encrypted protocol such as ftp. Even when you encrypt the key using traditional cryptography (for example triple DEC with password) private key distribution over Internet is a risk.

People new to the ssh certificates area often make the following three typical errors:

  1. Wrong permissions  or ownership iether for .ssh directory or for authorized_keys file, or both.  This is the most typical error.
  2. Mix up of public and private keys sending private key to the target server (positioning keys in reverse order). It is important to understand that:
  3. Failure to check the correctness of the addition of public key to the authorized_keys file .  If copy and paste is used intead of cat command is used to add the public key to the authorized_keys you might add breaks or other extra symbol depending on terminal emulator you re using.  Which unvaldate the key.
  4. Coping public key to the wrong file. if you type the name authorized_keys, not copy it,  you can make a nasty typo in the name of the target such as authorised_keys, authorized-keys or authorized_key (I saw all three of those typo). Even more often this type of errors occurs if you copy public key from the other server and rename it as authorized_keys.   If you did not check the results, then troubleshooting of such an error is pretty difficult. So always check the correctness of your addition.  It is also possible accidentally add public key to the file  known_hosts instead of authorized_keys If you by mistake copy private key(s) to the file known_hosts instead of the file authorised keys  and foret to check the results of your addition you might troubleshoot the situation for a long time before you realize what went wrong.
  5. The distribution of private key via Internet can be intercepted. It is generally a bad idea to send them in unencryted form. In no way private key can be downloaded in non-encrypted form or, worse, via via non-encrypted protocol such as ftp. Even when you encrypt the key using traditional cryptography (for example triple DEC with password) private key distribution over Internet is a risk.

Tips for troubleshooting

 

Differences in security between RSA and DSA

A lot of paranoia exists as for the relative strength of cryptographic methods used. In any case the usual avenue of attack is stealing the key iether in transmission or from your desktop, not breaking the encryption. As Snowden materials reveled NSA is very interested in obtaining such keys and developed sophisticated methods related to this task.  So the protection of keys from stealing should be your primary concern.

In reality, there is no difference in the level of security of those two keys. Here is an excerpt from Bruce Schneier's Crypto-Gram for November 15, 1999:

The security of most other public-key algorithms -- ElGamal, DSA, etc. -- is based on the discrete logarithm problem. The two problems are very similar, and all of the modern factoring algorithms can be used to calculate discrete logarithms in the multiplicative group of a finite field. To a rough approximation, factoring a number of a certain size and calculating the discrete logarithm of numbers the same size takes the same amount of work. This means that for a given key size, RSA, ElGamal, DSA, etc. are approximately equally secure. (This isn't strictly true, but it's a good enough approximation for this essay.)

You can set the type of key SSH generates with the -t option. Thus to generate your RSA public and private key pair, you would run

ssh-keygen -t rsa

The keys generated are by default stored in your .ssh directory. If it is absent ssh-keygen creates it. Two files are generated:

  1. Private key. The name of the file is determined by the encryption algorithms specified in option -t. Private key file has no extension.

    Private key file has no extension

  2. Public key. corresponding public key has the same name as private key and the extension .pub.

The public key has the same name as private key and the extension .pub

Tips:

  1. If  ~/.ssh directory does not exits, you don't need to create it manually, ssh-keygen will do that for you with correct permissions if its unable to find it.
  2. Generally .ssh directory should have permission 700.

Distribution of the public key to remote servers

You can ftp or scp the public key to the destination system(s) and then, on the remote system, type cat id_rsa.pub >> .ssh/authorized_keys

A better way is to use piping capabilities. That allow to make change in one step:

cat .ssh/id_rsa.pub | ssh myserver " cat >> ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys

But there is an equally good, less well known command ssh-copy-id, which does essentially the same thing. For example:

ssh-copy-id -i .ssh/id_rsa.pub [email protected]

The utility ssh-copy-id provided with Open SSH package appends the public key to the remote-host’s  ~/.ssh/authorized_key file and will ensure the correct permissions on the file.

A rarely used and almost unknown command ssh-copy-id can distribute the public key to any host. It will also create directory .ssh if it does not exists. For example:
ssh-copy-id -i .ssh/id_rsa.pub [email protected]

It will also create directory .ssh if it does not exists and that's the advantage of this utility in comparison with other methods. Option -i should specify the full path and name of your public key. If it is not specify the utility will try to access default  RSA1 key at location ~/.ssh/identity.pub, which is typically not what you want...

Final result should look like (here the user is oracle):

-r-------- 1 oracle dba 415 Jul  5 17:07 authorized_keys
-rw-r--r-- 1 oracle dba 400 Jul  5 17:16 known_hosts
If you have loaded keys to the ssh-agent using the ssh-add, then ssh-copy-id will get the keys from the ssh-agent to copy to the remote-host. i.e, it copies the keys provided by ssh-add -L command to the remote-host, when you don’t pass option -i to the ssh-copy-id.

Third party software usage for key distribution

If you have OpenView, Nagios or similar monitoring system installed you can use their capabilities to distribute the key.

You can use xargs submitting to it list of servers and using scp command to distribute the files. Parallel is a Perl script written by Ole Tange that extends and improves capabilities of xargs that can optimize this operation creating multiple threads, one for each server.  To transfer file to remote computer you can use option --transfer:

Especially convenient are parallel command execution packages. Among the latter we can mention pdsh -- a variant of the rsh(1) command. ROMs are available from Fedora EPEL (pdsh-2.26-4.el6.x86_64.rpm CentOS 6 Download),  and SourceForge.net. Unlike rsh(1), which runs commands on a single remote host, pdsh can run multiple remote commands in parallel. pdsh uses a "sliding window" (or fanout) of threads to conserve resources on the initiating host while allowing some connections to time out. pdcp included in pdsh package.

 

Typical mistakes

If testing fails, try use ssh -v to see the messages generated and point of failure. Most often the problem is due to lack of of proper attention to details. Among most typical oversights: 

Two probably the most common mistakes in setting up passwordless login are as following

  1. Wrong permissions for authorized_keys file. Verify and, if necessary, reset permissions of authorized_keys on each remote host where you created or appended your public key to authorized_keys. You can use the following commands to ensure the right permissions are set:

    chmod 755 ~   # or 701 if you are restrictive about your home directory
    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
    SSH is very strict about the permissions that you have on your remote .ssh directory and the files in it. Typical problems with inability to login using your key are due to the write permissions for a group or world that you have on the file authorized_keys or .ssh directory at the remote server.
  2. You accidentally added public key to the file  known_hosts instead of authorized_keys   If you by mistake copy private key(s) to the file known_hosts instead of the file authorised keys you might troubleshoot the situation for a long time before you realize what went wrong.

Duplicates in .ssh/authorized_keys

If you execute ssh-copy-id multiple times on the local-host, it will keep appending the same key on the remote-host’s authorized_keys file without checking for duplicates. Even with duplicate entries everything works as expected. But you might wish to purge redundant (earlier) entries periodically to keep the file free from clutter.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Aug 07, 2018] Linux Basics How To Create and Install SSH Keys on the Shell

Notable quotes:
"... ssh-keygen -b 4096 -t rsa ..."
"... /root/.ssh/id_rsa ..."
Aug 07, 2018 | www.howtoforge.com
ssh-keygen -o -b 4096 -t rsa

The above command kicks off the SSH Key installation process for users. The -o option instructs ssh-keygen to store the private key in the new OpenSSH format instead of the old (and more compatible PEM format). It is highly recommended to use the -o option as the new OpenSSH format has an increased resistance to brute-force password cracking. In case the -o option does not work on your server (it has been introduced in 2014) or you need a private key in the old PEM format, then use the command ' ssh-keygen -b 4096 -t rsa '.

The -b option of the ssh-keygen command is used to set the key length to 4096 bit instead of the default 1024 bit for security reasons.

Upon entering the primary Gen Key command, users need to go through the following drill by answering the following prompts:

Enter the file where you wish to save the key (/home/demo/.ssh/id_rsa)

Users need to press ENTER in order to save the file to the user home

The next prompt would read as follows:

Enter passphrase

If, as an administrator, you wish to assign the passphrase, you may do so when prompted (as per the question above), though this is optional, and you may leave the field vacant in case you do not wish to assign a passphrase.

However, it is pertinent to note there that keying in a unique passphrase does offer a bevy of benefits listed below:

1. The security of a key, even when highly encrypted, depends largely on its invisibility to any other party. I 2. In the likely instance of a passphrase-secure private key falling into the custody of an unauthorized user, they will be rendered unable to log in to its allied accounts until they can crack the passphrase. This invariably gives the victim (the hacked user) precious extra time to avert the hacking bid On the downside, assigning a passphrase to the key requires you to key it in every time you make use of the Key Pair, which makes the process a tad tedious, nonetheless absolutely failsafe.

Here is a broad outline of the end-to-end key generation process:

root@server1:~# ssh-keygen -b 4096 -o -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KBZP/guc7lND8I239zKv8PRziF/5jnA6N0nEocCDlLA root@server1
The key's randomart image is:
+---[RSA 2048]----+
| .o.+ |
| ..o + . |
| . Eo o o o . |
| = .+ o . o |
| o +.S. . . |
| . o oo . . . .|
| +.....o+.+.|
| ... . +==Boo|
| .o.. +O==o|
+----[SHA256]-----+

The public key can now be traced to the link ~/.ssh/id_rsa.pub

The private key (identification) can now be traced to the link-/home/demo/.ssh/id_rsa 3

Step Two: Copying the Public Key

Once the distinct key pair has been generated, the next step remains to place the public key on the virtual server that we intend to use. Users would be able to copy the public key into the authorized_keys file of the new machine using the ssh-copy-id command. Given below is the prescribed format (strictly an example) for keying in the username and IP address, and must be replaced with actual system values:

ssh-copy-id [email protected]

As an alternative, users may paste the keys by using SSH (as per the given command):

cat ~/.ssh/id_rsa.pub | ssh [email protected] "cat >> ~/.ssh/authorized_keys"

Either of the above commands, when used, shall toss the following message on your system:

The authenticity of host '192.168.0.100 ' can't be established. RSA key fingerprint is b1:2d:32:67:ce:35:4d:5f:13:a8:cd:c0:c4:48:86:12. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.0.100' (RSA) to the list of known hosts. [email protected]'s password: Now try logging into the machine, with "ssh '[email protected]'", and check in: ~/.ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.

After the above drill, users are ready to go ahead and log into [email protected] without being prompted for a password. However, if you have earlier assigned a passphrase to the key (as per Step 2 above), you will be prompted to enter the passphrase at this point (and each time for subsequent log-ins.).

Step Three (This Step is Optional): Disabling the Password to Facilitate Root Login

After users have copied their SSH keys unto your server and ensured seamless log-in with the SSH keys only, they have the option to restrict the root login, and permit the same only through SSH keys. To accomplish this, users need to access the SSH configuration file using the following command:

sudo nano /etc/ssh/sshd_config

Once the file is accessed, users need to find the line within the file that includes PermitRootLogin , and modify the same to ensure a foolproof connection using the SSH key. The following command shall help you do that:

PermitRootLogin without-password

The last step in the process remains to implement the changes by using the following command:

reload ssh

The above completes the process of installing SSH keys on the Linux server.

Converting OpenSSH private key to new format

Most older OpenSSH keys are stored in the PEM format. While this format is compatible with many older applications, it has the drawback that the password of a password-protected private key can be attacked with brute-force attacks. This chapter explains how to convert a private key in PEM format to one in the new OpenSSH format.

ssh-keygen -p -o -f /root/.ssh/id_rsa

The path /root/.ssh/id_rsa is the path of the old private key file.

Conclusion

The above steps shall help you install SSH keys on any virtual private server in a completely safe, secure and hassle-free manner.

[Jun 10, 2011] CodeSnippets ssh-copy-id for automated pubkey append [sysadmin] [ssh] [deploy] [pubkey] [scp]

it's simple to add one key but this helps when i'm on a machine w/ multiple authorized hosts
use like `ssh-copy-id ww1.example.com` -- make sure you have `ssh-agent` running and have added keys w/ `ssh-add` (use `ssh-add -L` to check)
got this from the OpenSSH in Ubuntu, don't have it on mac afaik?
#!/bin/sh

# Shell script to install your public key on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/id_rsa.pub"

if [ "-i" = "$1" ]; then
  shift
  # check if we have 2 parameters left, if so the first is the new ID file
  if [ -n "$2" ]; then
    if expr "$1" : ".*\.pub" >/dev/null; then
      ID_FILE="$1"
    else
      ID_FILE="$1.pub"
    fi
    shift         # and this should leave $1 as the target name
  fi
else
  if [ x$SSH_AUTH_SOCK != x ] && ssh-add -L >/dev/null 2>&1; then
    GET_ID="$GET_ID ssh-add -L"
  fi
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
  GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
  echo "$0: ERROR: No identities found" >&2
  exit 1
fi

if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
  exit 1
fi

{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

EOF

[May 5, 2008] How To Set Up SSH With Public-Key Authentication On Debian Etch HowtoForge - Linux Howtos and Tutorials

here are a couple of additional tips: you don't need to create the .ssh direrectory yourself, ssh-keygen will do that for you if its unable to find it.
And to update keys:
ssh-copy-id -i .ssh/id_rsa [email protected]
You can also use ssh-copy-id to copy over your key to the remote host as well. If no .ssh directory or authorized_keys
This mini-howto explains how to set up an SSH server on Debian Etch with public-key authorization (and optionally with disabled password logins). SSH is a great tool to control Linux-based computers remotely. It's safe and secure.

There's no warranty that it'll work for you. All of these settings are applicable for Debian and -like systems! There may be slightly changes on other systems as well.

... ... ...

On your desktop machine, we install the ssh client (which we use to connect the server). Note that installing programs requires privilege! If you're not logged in as , please log in! (su root then type your password.) Then install the client:
apt-get install openssh-client

Switch back to your normal user (not , respectively). Then type these commands in order:

mkdir ~/.ssh
chmod 700 ~/.ssh
cd ~/.ssh

We generate our key-pair, a public-key and a private-key. The public-key will be placed on the server, and you will log in with your private-key. When asked, type your passphrase (it'll be needed for future logins, so remember it!):

ssh-keygen -t rsa -C "I love NY"

Then we copy the public key (which we've generated just before) to our (remote) server. The remote user should not be ! Choose the default non-root user as remote user. (Note the colon at the end of the line! It's important.)

scp -p id_rsa.pub remoteuser@remotehost:

Then we log in with SSH, and we copy the public key to its right place:

ssh remoteuser@remotehost
mkdir ~/.ssh
chmod 700 ~/.ssh
cat id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
mv id_rsa.pub ~/.ssh
logout

We have to delete the public key on the desktop, because otherwise the SSH client doesn't allow us to log in to the server. So, type this command:

rm id_rsa.pub

And then we log back:

ssh remoteuser@remotehost

If we've done everything precisely as detailed above, then you'll be asked for the passphrase. Type it, then you are in and have a fairly safe SSH-environment!

Disabling Password Authentication

Disabling it is a good way to have a safer SSH-installation. Then you can log in only with a key-pair, so be careful not to lose it! It's purely optional but safe to activate! But before doing it, please make sure that key-based authentication is working out-of-the-box. Sit down in front the server (so don't log in remotely as we have to restart the SSH later...) and type these commands manually as :

cd /etc/ssh
cp sshd_config sshd_config.orig
nano sshd_config

You will have the nano text-editor on screen open with the main SSH configuration file. Change these lines (don't bother if any of these lines have a '#' mark at the beginning; if they have, just delete the hashmark as well):

PermitRootLogin		yes
PasswordAuthentication	yes
UsePAM			yes

Passwordless SSH setup not working, any ideas

Some good ideas about troubleshooting in replies
LinuxQuestions.org

I followed this HowTo http://www.debian-administration.org/articles/152 and I've read numerous threads here at LQ and on the web but I cannot get this to function!

I want passwordless logons for root access to work and client servers.

I have set up an RSA key on my box for user@user-desktop (the basic Kubuntu machine name) and I copied/added the rsa_id_nopass.pub file to the end of the destination server's ~/.ssh/authorized_keys2 file, but it still isn't working; I am asked for a password (not passphrase) every time.

I have edited the ssh_config file (both on local machine and server) to use

RSAAuthentication yes
	PubkeyAuthentication yes

and restarted the sshd server on both machines.

I want to get root access for servers when I log in using these keys. Unfortunately it isn't giving me root or regular user access at all; 'ssh root@server' is acting like it would had none of my work been done.

My system is Kubuntu 7.04 and the test server is a RedHat Enterprise Linux 9, but the key setup would eventually go onto a few debian servers and RHEL servers. I also am failing to get this to function on two Kubuntu 7.04 boxes (one is at home, one is at work (this setup is for two regular user accounts, not root accounts)). Does this whole setup require that the user name is identical on both machines??? Cause that's just a pain if I have to become root just to not enter a root password five seconds later.

Thanks for any advice

====

It sounds like you've checked everything. Create the key pair; put public key in the remote box's ~/.ssh/authorized_keys2 file. Check that the remote ~/.ssh directory is chmod 700. The private key applies as long as you are currently running on the local box as the user you created the key for; the same user that has it in their ~/.ssh directory. You also have to be logging in as the user on the remote box that you created the ~/.ssh/authorized_keys2 file for.

Otherwise, everything you've done sounds correct. If things still don't work just post the line that created your key here, and we'll try to help you out some more.

Regards,

Alunduil

===

Try copying ~/.ssh/authorized_keys2 to ~/.ssh/authorized_keys.

[Oct 27, 2007] System Administration Toolkit Distributed administration using SSH

Simplifying remote login

Secure Shell (SSH) tools provide a secure method for logging in and exchanging information with a remote host. A number of different tools are provided, including the general-purpose SSH tool (which provides a remote terminal connection), SCP (a secure, host-to-host, copy solution), and SFTP, a secure file copy solution that works in a similar fashion to the standard FTP tools.

All of these tools are secure in that the information that is exchanged is encrypted. In addition, the authentication of connections is secured using a public or private key mechanism. One of the main benefits of SSH is that you can bypass the normal login and password exchange by copying your public key to a remote machine.

Although this is useful when using SSH to log in to a remote machine (as it means you don't have to provide a password), it is even more useful when performing remote administration. Having to type in a password can also make automated remote administration (for example, running a command through cron) impossible, because in an automated script, you won't be around to type in the password!

When using SSH to run commands across multiple machines without exchanging your public key, you need to type in your password for each machine.

A quick and simple way of setting this up is to create a public key:

$ ssh-keygen -t rsa
Follow the on-screen instructions, but don't set a password when prompted, as you will then need to enter the password each time you want to use the key. This creates a private and a public key file. Now you just need to append the contents of the public key file in .ssh/id_rsa.pub, and append it to the .ssh/authorized_keys file on the remote host and user you want to use when logging in. You need to append the public key file contents to each machine you want to log in to automatically.

Running a remote command

There are many ways in which you can run a remote command.

You can run a single remote command by adding the command you want to run to SSH after the login or host information. For example, to get the disk information for a remote host, you might use the command and get the output in Listing 1 below.

                
$ ssh [email protected] df

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/hda3             14544820   3611520  10194464  27% /
udev                    128044       564    127480   1% /dev
/dev/hdc1              1968872     50340   1818516   3% /var/tmp
/dev/hdc2              1968904   1482220    386668  80% /usr/portage
/dev/hdc3              1968904     35760   1833128   2% /home/build
shm                     128044         0    128044   0% /dev/shm

Bear in mind that the sequence in Listing 1 requires you to enter a password if you haven't already exchanged your public key with the remote host.

You can also execute a sequence of commands by separating each command with a semicolon and then placing the entire sequence of commands into quotes so that it is identified as a single argument.

An example of executing both a disk check and an uptime check is shown in Listing 2.

                
$ ssh [email protected] "df;uptime"
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/hda3             14544820   3611520  10194464  27% /
udev                    128044       564    127480   1% /dev
/dev/hdc1              1968872     50340   1818516   3% /var/tmp
/dev/hdc2              1968904   1488100    380788  80% /usr/portage
/dev/hdc3              1968904     35760   1833128   2% /home/build
shm                     128044         0    128044   0% /dev/shm
 14:31:27 up 12 min,  2 users,  load average: 0.01, 0.05, 0.06
 

You can string as many commands as you like into this operation. Filtering, for example, using grep or other tools, is also possible, but you need to make sure to embed the entire remote command expression into the quotes (see Listing 3).

                
$ ssh [email protected] "cat /var/log/messages|grep 'su\['"
Dec 17 18:05:37 localhost su[19218]: pam_authenticate: Permission denied
Dec 17 18:05:37 localhost su[19218]: FAILED su for root by mc
Dec 17 18:05:37 localhost su[19218]: - pts/1 mc:root
Dec 17 18:06:31 localhost su[19221]: pam_authenticate: Permission denied
Dec 17 18:06:31 localhost su[19221]: FAILED su for root by mc
Dec 17 18:06:31 localhost su[19221]: - pts/1 mc:root
Dec 17 18:06:40 localhost su[19222]: pam_authenticate: Permission denied
Dec 17 18:06:40 localhost su[19222]: FAILED su for root by mc
...

The first item to note about Listing 3 is that you are logging in directly to the remote machine as root. This is because the file you want to view is only accessible to the superuser. You must ensure that your system is configured to allow remote root logins for this to work.

The second important note about this example is that you've performed the grep operation remotely. In actual fact, you don't need to do this. The standard input and output of the remote host are replicated to the local machine, so the output from the command can be filtered locally, as shown here in Listing 4.

                
$ ssh [email protected] "cat /var/log/messages" | grep 'su\[' 
Dec 17 18:05:37 localhost su[19218]: pam_authenticate: Permission denied
Dec 17 18:05:37 localhost su[19218]: FAILED su for root by mc
Dec 17 18:05:37 localhost su[19218]: - pts/1 mc:root
Dec 17 18:06:31 localhost su[19221]: pam_authenticate: Permission denied
Dec 17 18:06:31 localhost su[19221]: FAILED su for root by mc
Dec 17 18:06:31 localhost su[19221]: - pts/1 mc:root
Dec 17 18:06:40 localhost su[19222]: pam_authenticate: Permission denied
Dec 17 18:06:40 localhost su[19222]: FAILED su for root by mc
Dec 17 18:06:40 localhost su[19222]: - pts/1 mc:root

Of course, the effect is essentially the same.

Using the remote pipe method, though, is useful when the information or command that you want to pipe with is remote. For example, you can use ls in combination with du to determine the disk usage of different directories with the command shown in Listing 5.

                
ssh [email protected] "ls -d /usr/local/* |xargs du -sh "
Password: 
4.0K    /usr/local/bin
4.0K    /usr/local/games
4.0K    /usr/local/lib
0       /usr/local/man
4.0K    /usr/local/sbin
12K     /usr/local/share
4.0K    /usr/local/src

Before moving on to redistributing these techniques to multiple machines, there's a quick trick for running remote interactive sessions directly without having to log in first.

Direct interactive sessions

As shown previously, you can directly run a number of different commands and chains of commands. One of the benefits of the SSH solution is that although the command itself is executed remotely, the input and output of the command are sourced from the calling machine. You can use this as a method for exchanging information between the two machines relating to the commands that you want to execute.

The commands that you execute can cover almost anything from a range of different commands. However, because you are running commands directly from the command line, there are limits to what you can execute directly with this method. For example, trying to edit a remote file with an editor using this method and techniques shown above usually fail (see Listing 6).

                
$ ssh [email protected] "emacs /etc/amavisd.conf"
emacs: standard input is not a tty

You can resolve this by forcing SSH to allocate a pseudo-tty device so that you can interact directly with the remote application.

SSH your Debian servers without password -- Debian Admin

Secure Shell is a program to log into another computer over a network, to execute commands in a remote machine, and to move files from one machine to another. It provides strong authentication and secure communications over unsecure channels. It is intended as a replacement for telnet, rlogin, rsh, and rcp. For SSH2, there is a replacement for FTP: sftp.This might be useful if you are trying to connect everytime to your server remotely.

A Trust relationship can be established for users on multiple servers runnt to run scripts or commands remotely.

Let's assume ServerA and ServerB both run the ssh daemons.

To allow ServerA to SSH to ServerB without password, please try the following:

# ssh-keygen -t rsa

Note: User here is root

This generates two files id_rsa.pub and id_rsa

Now, this needs to be copied to the authorized_keys file on ServerB

# scp id_rsa.pub ServerB:~/.ssh/authorized_keys

Enter password when prompted.

Note: If the ServerB is already having a trust relationship with more that one hosts already then the above will wipe the contents and write this key alone. In which case, copy the file to the remote server as something like ServerA_rsa.pub and then append the contents to authorized_keys as follows. This will allow the existing authroized_keys from being wiped off.

# scp id_rsa.pub ServerB:~/.ssh/ServerA_rsa.pub

# cat ServerA_rsa.pub >> authorized_keys

Thats it. Test if you are able to do a ssh from ServerA without a password:

# ssh serverB uname -a

This will run the command "uname -a"on ServerB and returns the result on ServerA.

The same procedure has to be followed in the reverse to allow ServerB to talk back to ServerA without any password.

And, if there is anyone other server to be added to the existing list follow the same procedure ensuring the key is appended to the remote servers authorized_keys file and not by overwriting it.

SSH, key authentication and batch mode - Blog de Pierrick Le Gall

Par Pierrick, vendredi 7 septembre 2007 à 16:12 / categorie:

A long time ago, I've tried to use connect to a SSH server with my private key in a batch mode (with a cron task). I didn't find the way to do it. Now I have. It is as simple as to have no passphrase on your private key. Less secure (but still much more secure than FTP connection) but makes SSH possible in cron task.

$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/pierrick/.ssh/id_dsa): /home/pierrick/.ssh/id_dsa2
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: /home/pierrick/.ssh/id_dsa2.pub.
Your identification has been saved in /home/pierrick/.ssh/id_dsa2.
Your public key has been saved in /home/pierrick/.ssh/id_dsa2.pub.

Add the content of /home/pierrick/.ssh/id_dsa2.pub into remote ~/.ssh/authorized_keys

$ export EDITOR=vi; crontab -e
* * * * * ssh -i /home/pierrick/.ssh/id_dsa2 remote_user@remote_server 'echo $(date) >> /tmp/pierrick.log'

And see that every second, the date is appended to the remote /tmp/pierrick.log

Commentaires

1. Le dimanche 9 septembre 2007 à 09:16, par Nicolas

An another better solution can be keychain. You can use a passphrase. keychain don't use the same solution than ssh-add to store the passphrase in a agent just for the current session. It stores the passphrase until the machine have to be rebooted.

2. Le jeudi 20 septembre 2007 à 10:35, par BooK

I have an agent running on my system, which I start with ssh-agent > ~/.ssh/agent. Making the agent known to your environment is as simple as typing . ~/.ssh/agent. This is a command one can type at the beginning of a cron command.

That way, you don't have to keep a private key without a password, and can still use it in a cron job.
You just have to make sure your agent is here after a reboot.

3. Le vendredi 21 septembre 2007 à 09:17, par Pierrick

BooK, alright to start an agent, but how do I add the key? "ssh-add" right? So I have to give the passphrase, right? So I have to right the clear passphrase somewhere, right? Where is security improvement

Debian Administration Password-less logins with OpenSSH

Because OpenSSH allows you to run commands on remote systems, showing you the results directly, as well as just logging in to systems it's ideal for automating common tasks with shellscripts and cronjobs. One thing that you probably won't want is to do though is store the remote system's password in the script. Instead you'll want to setup SSH so that you can login securely without having to give a password.

Thankfully this is very straightforward, with the use of public keys.

To enable the remote login you create a pair of keys, one of which you simply append to a file upon the remote system. When this is done you'll then be able to login without being prompted for a password - and this also includes any cronjobs you have setup to run.

If you don't already have a keypair generated you'll first of all need to create one.

If you do have a keypair handy already you can keep using that, by default the keys will be stored in one of the following pair of files:

If you have neither of the two files then you should generate one. The DSA-style keys are older ones, and should probably be ignored in favour of the newer RSA keytypes (unless you're looking at connecting to an outdated installation of OpenSSH). We'll use the RSA keytype in the following example.

To generate a new keypair you run the following command:

skx@lappy:~$ ssh-keygen -t rsa

This will prompt you for a location to save the keys, and a pass-phrase:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/skx/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/skx/.ssh/id_rsa.
Your public key has been saved in /home/skx/.ssh/id_rsa.pub.

If you accept the defaults you'll have a pair of files created, as shown above, with no passphrase. This means that the key files can be used as they are, without being "unlocked" with a password first. If you're wishing to automate things this is what you want.

Now that you have a pair of keyfiles generated, or pre-existing, you need to append the contents of the .pub file to the correct location on the remote server.

Assuming that you wish to login to the machine called mystery from your current host with the id_rsa and id_rsa.pub files you've just generated you should run the following command:

ssh-copy-id -i ~/.ssh/id_rsa.pub username@mystery

This will prompt you for the login password for the host, then copy the keyfile for you, creating the correct directory and fixing the permissions as necessary.

The contents of the keyfile will be appended to the file ~/.ssh/authorized_keys2 for RSA keys, and ~/.ssh/authorised_keys for the older DSA key types.

Once this has been done you should be able to login remotely, and run commands, without being prompted for a password:

skx@lappy:~$ ssh mystery uptime
 09:52:50 up 96 days, 13:45,  0 users,  load average: 0.00, 0.00, 0.00
What if it doesn't work?

There are three common problems when setting up passwordless logins:

Each of these problems is easily fixable, although the first will require you have root privileges upon the remote host.

If the remote server doesn't allow public key based logins you will need to updated the SSH configuration. To do this edit the file /etc/sshd/sshd_config with your favourite text editor.

You will need to uncomment, or add, the following two lines:

RSAAuthentication yes
PubkeyAuthentication yes

Once that's been done you can restart the SSH server - don't worry this won't kill existing sessions:

/etc/init.d/ssh restart

File permission problems should be simple to fix. Upon the remote machine your .ssh file must not be writable to any other user - for obvious reasons. (If it's writable to another user they could add their own keys to it, and login to your account without your password!).

If this is your problem you will see a message similar to the following upon the remote machine, in the file /var/log/auth:

Jun  3 10:23:57 localhost sshd[18461]: Authentication refused: 
 bad ownership or modes for directory /home/skx/.ssh

To fix this error you need to login to the machine (with your password!) and run the following command:

cd
chmod 700 .ssh

Finally if you're logging into an older system which has an older version of OpenSSH installed upon it which you cannot immediately upgrade you might discover that RSA files are not supported.

In this case use a DSA key instead - by generating one:

ssh-keygen

Then appending it to the file ~/.ssh/authorized_keys on the remote machine - or using the ssh-copy-id command we showed earlier.

Note if you've got a system running an older version of OpenSSH you should upgrade it unless you have a very good reason not to. There are known security issues in several older releases. Even if the machine isn't connected to the public internet, and it's only available "internally" you should fix it.

====

Re: Password-less logins with OpenSSH

Posted by whizse (62.209.xx.xx) on Fri 3 Jun 2005 at 12:12
[ Send Message ]

A great way to make use of ssh-agent is with the pam_ssh module. This makes it possible to only type one password when you log in (as usual) and also lock up you SSH keys. For the rest of the session you can use SSH without typing any passwords.

The information to enable this (for GDM at least) is available in the README in the libpam-ssh package.

===

Re: Password-less logins with OpenSSH

Posted by wouter (195.162.xx.xx) on Fri 3 Jun 2005 at 20:47
[ Send Message ]

It would be more secure to put the command in the authorized_keys file -- read sshd(8). The remote sshd server then executes the command and terminates without giving back a shell. That way, even when someone either compromises the key or the computer with the key on it, they can only execute that one command. Especially for your example of 'uptime' or any other simple command you need often, this would be even much more secure.

To backup remote servers, I use rsync over ssh with the key valid only for the rsync-listener (and a shell script to double-check the given parameters). It is the most secure way I can think of to backup servers directly. And it's pretty fast too...

===

Re: Password-less logins with OpenSSH

Posted by Kellen (68.15.xx.xx) on Sat 4 Jun 2005 at 05:32
[ Send Message | View Weblogs ]

Unless you have a very specific command that can be embedded in an authorized_keys file, you should always use a passphrase on your keys.

I worked on solving just this problem for an article I'm writing (which will be posted here in the not-too-distant future). Here is a section, with some minor modifications:

In order to script our backups while using a ssh key with a passphrase, we need an application which will retain use of the key over a long term. We'll use keychain, a tool which itself uses ssh-agent, which does the actual caching.

Install keychain:

~# apt-get install keychain
To set up local root's bash profile to run keychain on login, add these lines to ~/.bash_profile:
keychain --clear id_dsa
. ~/.keychain/$HOSTNAME-sh 

This will have keychain first clear the existing keys (in the case of a normal root compromise, the attacker can't access the remote systems), then attempt to load the id_dsa key and finally source the appropriate output from ssh-agent.

The next time root logs in, she will be prompted to enter the passphrase for the ssh key, and any subsequent process running as root will not need to use a password to log into the remote system.

Re: Password-less logins with OpenSSH
Posted by Anonymous (216.220.xx.xx) on Wed 8 Jun 2005 at 19:36

I have never been able to make this work without including the following line in the /etc/sshd_config of the remote box:

UsePAM no

Am I crazy?

#24
Re: Password-less logins with OpenSSH
Posted by Anonymous (71.116.xx.xx) on Mon 22 Aug 2005 at 20:11

You are not crazy... in locking down my debian/ubuntu ssh I found that I had to change this to no otherwise sshd still allowed password-based auth

#27

Re: Password-less logins with OpenSSH Posted by Anonymous (129.42.xx.xx) on Tue 25 Jul 2006 at 20:14
Only a little crazy. "ChallengeResponseAuthentication no" is the more specific setting for disabling the password prompt generated by the PAM module.

#33 Re: Password-less logins with OpenSSH Posted by redbeard (216.49.xx.xx) on Wed 27 Jun 2007 at 05:44
[ Send Message | View redbeard's Scratchpad | View Weblogs ]

I realize this is a really old thread, but it's a possible answer to a question I have. Is this really true? In other words, if I have:

UsePAM yes
ChallengeResponseAuthentication no
I can prevent using PAM passwords (requiring public/private key authentication) but still use the PAM framework for implementing other things? If that's the case, I'd be absolutely thrilled. Unfortuntaely, the man page is a little vague on ChallengeResponseAuthentication:
Specifies whether challenge-response authentication is allowed. All authentication styles from login.conf5 are supported. The default is "yes".
I'll repost this elsewhere if no one notices ;)

Re: Password-less logins with OpenSSH

Posted by Anonymous (69.128.xx.xx) on Wed 29 Jun 2005 at 05:28

Yes, you can use expect. I greatly caution against using this, since it has the same security issues passwordless secret keys have. You can customize the script below to change the ssh command or whatever. The interact command causes the script to "connect" the keyboard to the spawned command. You can read about expect for more information.

 
#!/usr/bin/expect spawn ssh user@host expect "Password: " { sleep 1 send "secret\r" } timeout { send_user "Error connecting" } # I have no idea why this needs to be here, except if it isn't the # password does not get sent and the login doesn't happen # So this should just timeout expect "alksjd" { send_user "Whoa" } timeout { } interact

Re: Password-less logins with OpenSSH

Posted by Anonymous (202.7.xx.xx) on Fri 14 Sep 2007 at 03:16

Also on FC6, but with Debian 4.0 as the client, and FC6 as the server, on the server I had to do:
chmod 644 ~/.ssh/authorized_keys
... for some reason (not sure why the permissions were set differently), in order to get password-less SSH logins to work. So that's perhaps another thing to check if it's not working for you.

[Oct 06, 2000] Pass on Passwords with scp Linux Journal By Dave Sirof

Learn how to propagate files quickly and do backups easily when you set up scp to work without needing passwords.

In this article, I show you how to use the scp (secure copy) command without needing to use passwords. I then show you how to use this command in two scripts. One script lets you copy a file to multiple Linux boxes on your network, and the other allows you to back up all of your Linux boxes easily.

If you're a Linux sysadmin, you frequently need to copy files from one Linux box to another. Or, you may need to distribute a file to multiple boxes. You could use FTP, but using scp has many advantages. For instance, scp is much more secure than FTP. scp travels across the LAN/WAN encrypted, while FTP uses clear text, even for passwords.

But what I like best about scp is it's easily scriptable. Suppose you need to distribute a file to 100 Linux boxes. I'd rather write a script to do this than type 100 sets of copy commands. If you use FTP in your script, things can get messy, because each Linux box you log into is going to ask for a password. But if you use scp in your script, you can set things up so the remote Linux boxes don't ask for a password. Believe it or not, this actually is much more secure than using FTP.

Here's an example demonstrating the most basic syntax for scp. To copy a file named abc.tgz from your local PC to the /tmp dir of a remote PC called bozo, use:

scp abc.tgz root@bozo:/tmp

You now are asked for bozo's root password, so we're not quite there yet. The system still is asking for a password, so it's not easily scriptable. To fix that, follow this one-time procedure, after which you can make endless password-less scp copies:

  1. Decide which user on the local machine will be using scp later on. Of course, root gives you the most power, and that's how I personally have done it. I'm not going to give you a lecture here on the dangers of root, so if you don't understand them, choose a different user. Whatever you choose, log in as that user now and stay there for the rest of the procedure. Log in as this same user when you use scp later on.
  2. Generate a public/private key pair on the local machine. Say what? If you're not familiar with public key cryptography, here's the 15-second explanation. In public key cryptography, you generate a pair of mathematically related keys, one public and one private. You then give your public key to anyone and everyone in the world, but you never ever give out your private key. The magic is in the mathematical makeup of the keys; anyone with your public key can use it to encrypt a message, but only you can decrypt it with your private key. Anyway, the syntax to create the key pair is:
     ssh-keygen -t rsa
  3. In response, you should see:

    Generating public/private rsa key pair
    Enter file in which to save the key ...

    Press Enter to accept this.

  4. In response, you should see:
    Enter passphrase (empty for no passphrase):

    You don't need a passphrase, so press Enter twice.

  5. In response, you should see:
    Your identification has been saved in ... 
    Your public key has been saved in ... 

    Note the name and location of the public key just generated. It always ends in .pub.

  6. Copy the public key just generated to all of your remote Linux boxes. You can use scp or FTP or whatever to make the copy. Assuming you're using root--again, see my warning in step 1--the key must be contained in the file /root/.ssh/authorized_keys. Or, if you are logging in as a user, for example, clyde, it would be in /home/clyde/authorized_keys. Notice that the authorized_keys file can contain keys from other PCs. So, if the file already exists and contains text, you need to append the contents of your public key file to what already is there.

Now, with a little luck, you should be able to scp a file to the remote box without needing to use a password. So let's test it by trying our first example again. Copy a file named xyz.tgz from your local PC to the /tmp dir of a remote PC called bozo:

 scp xyz.tgz root@bozo:/tmp

Wow--it copied with no password!

A word about security before we go on. This local PC just became pretty powerful, as it now has access to all the remote PCs with only the one local password. So that one password better be strong and well guarded.

Now for the fun part. Let's write a short script to copy a file called houdini from the local PC to the /tmp dir of ten remote PCs, located in ten different cities, in only five minutes of work. Of course, it would work the same with 100 or 1000 of PCs. Suppose the 10 PCs are called brooklyn, oshkosh, paris, bejing, winslow, rio, gnome, miami, minsk and tokyo. Here's the script:

 #!/bin/sh
for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk
tokyo
do
scp houdini root@$CITY:/tmp
echo $CITY " is copied"
done

It works like magic. With the echo line in this script, you should be able to watch as each city's copy is completed one after the next.

By the way, if you're new to shell scripting, here is a pretty good tutorial.

As you may know, scp is only one part of the much broader SSH program. Here's the cool part: when you followed my six-step procedure above, you also gained the ability to sit at your local PC and execute any command you like on any of the remote PCs--without a password, of course. Here's a simple example to view the date and time on the remote PC brooklyn:

 ssh brooklyn "date"

Let's now put these two concepts together for one final and seriously cool script. It's a down-and-dirty way to back up all of your remote Linux boxes. The example backs up the /home dir on each box. It's primitive compared to the abilities of commercial backup software, but you can't beat the price. Consider the fact that most commercial backup software charges license fees for each machine you back up. If you use such a package, instead of paying license fees to back up 100 PCs remotely, you could use the script to back up the 100 PCs to one local PC. Then, back up the local PC to your commercial package and save the license fees for 99 PCs. Anyway, the script below demonstrates the concepts, so you can write your own script to suit your own situation. Simply put this script in a cron job on your local PC; no script is required on the remote PCs. Please read the comments carefully, as they explain everything you need to know:

 #!/bin/sh
# Variables are upper case for clarity
# before using the script you need to create a dir called '/tmp/backups'
on each
# remote box & a dir called '/usr/backups' on the local box
# on this local PC
# Set the variable "DATE" & format the date cmd output to look pretty
#
DATE=$(date +%b%d)
# this 'for loop' has 3 separate functions
for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk
tokyo
do
# remove tarball on remote box from the previous time the script ran #
to avoid filling up your HD
# then echo it for troubleshooting
#
ssh -1 $CITY "rm -f /tmp/backups/*.tgz"
echo $CITY " old tarball removed"
# create a tarball of the /home dir on each remote box & put it in
/tmp/backups
# name the tarball uniquely with the date & city name
#
ssh $CITY "tar -zcvpf /tmp/backups/$CITY.$DATE.tgz /home/"
echo $CITY " is tarred"
# copy the tarball just create from the remote box to the /usr/backups
dir on
# the local box
#
scp root@$CITY:/tmp/backups/$CITY.$DATE.tgz /usr/backups
echo $CITY " is copied"
done
# the rest of the script is for error checking only, so it's optional:
# on this local PC
# create error file w todays date.
# If any box doesn't get backed, it gets written to this file
#
touch /u01/backup/scp_error_$DATE
for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk
tokyo
do
# Check if tarball was copied to local box. If not write to error file
# note the use of '||' which says do what's after it if what's before it
is not # true
#
ls /u01/backup/$CITY.$DATE.tgz || echo " $CITY did not copy" >>
scp_error_$DATE
# Check if tarball can be opened w/o errors. If errors write to error file.
tar ztvf /u01/backup/$CITY.$DATE.tgz || echo "tarball of $CITY is No
Good" >> scp_error_$DATE
done

That's about it. In this article, I've tried to give examples that demonstrate the concepts and are not necessarily ready to be used "as is". Some of the syntax may not work for all distributions, but in the interest of brevity, I could not include all the possibilities. For example, if you are using Red Hat 6.2 or before, the syntax requires some changes. So be creative, and hopefully you can use some of this work in your own environment.

Copyright (c) 2004, Dave Sirof. Originally published in Linux Gazette issue 98. Copyright (c) 2004, Specialized Systems Consultants, Inc.


Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

How To Set Up SSH With Public-Key Authentication On Debian Etch HowtoForge - Linux Howtos and Tutorials

How to set up Passwordless SSH access on a Linux server & disable password authentication

Reference

ssh-keygen [-q] [-b bits] -t type [-N new_passphrase] [-C comment] [-f output_keyfile]

ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

ssh-keygen -i [-f input_keyfile]

ssh-keygen -e [-f input_keyfile]

ssh-keygen -y [-f input_keyfile]

ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]

ssh-keygen -l [-f input_keyfile]

ssh-keygen -B [-f input_keyfile]

ssh-keygen -D reader

ssh-keygen -F hostname [-f known_hosts_file]

ssh-keygen -H [-f known_hosts_file]

ssh-keygen -R hostname [-f known_hosts_file]

ssh-keygen -U reader [-f input_keyfile]

ssh-keygen -r hostname [-f input_keyfile] [-g]

ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]

ssh-keygen -T output_file -f input_file [-v] [-a num_trials] [-W generator]

Description

ssh-keygen generates, manages and converts authentication keys for ssh(1). ssh-keygen can create RSA keys for use by SSH protocol version 1 and RSA or DSA keys for use by SSH protocol version 2. The type of key to be generated is specified with the -t option. If invoked without any arguments, ssh-keygen will generate an RSA key for use in SSH protocol 2 connections.

ssh-keygen is also used to generate groups for use in Diffie-Hellman group exchange (DH-GEX). See the MODULI GENERATION section for details.

Normally each user wishing to use SSH with RSA or DSA authentication runs this once to create the authentication key in ~/.ssh/identity, ~/.ssh/id_dsa or ~/.ssh/id_rsa. Additionally, the system administrator may use this to generate host keys, as seen in /etc/rc.

Normally this program generates the key and asks for a file in which to store the private key. The public key is stored in a file with the same name but ''.pub'' appended. The program also asks for a passphrase. The passphrase may be empty to indicate no passphrase (host keys must have an empty passphrase), or it may be a string of arbitrary length. A passphrase is similar to a password, except it can be a phrase with a series of words, punctuation, numbers, whitespace, or any string of characters you want. Good passphrases are 10-30 characters long, are not simple sentences or otherwise easily guessable (English prose has only 1-2 bits of entropy per character, and provides very bad passphrases), and contain a mix of upper and lowercase letters, numbers, and non-alphanumeric characters. The passphrase can be changed later by using the -p option.

There is no way to recover a lost passphrase. If the passphrase is lost or forgotten, a new key must be generated and copied to the corresponding public key to other machines.

For RSA1 keys, there is also a comment field in the key file that is only for convenience to the user to help identify the key. The comment can tell what the key is for, or whatever is useful. The comment is initialized to ''user@host'' when the key is created, but can be changed using the -c option.

After a key is generated, instructions below detail where the keys should be placed to be activated.

The options are as follows:

       -a trials
Specifies the number of primality tests to perform when screening DH-GEX candidates using the -T command.

-B' Show the bubblebabble digest of specified private or public key file.

-b bits
Specifies the number of bits in the key to create. For RSA keys, the minimum size is 768 bits and the default is 2048 bits. Generally, 2048 bits is considered sufficient. DSA keys must be exactly 1024 bits as specified by FIPS 186-2.

-C comment
Provides a new comment.

-c' Requests changing the comment in the private and public key files. This operation is only supported for RSA1 keys. The program will prompt for the file containing the private keys, for the passphrase if the key has one, and for the new comment.

-D reader
Download the RSA public key stored in the smartcard in reader.

-e' This option will read a private or public OpenSSH key file and print the key in a 'SECSH Public Key File Format' to stdout. This option allows exporting keys for use by several commercial SSH implementations.

-F hostname
Search for the specified hostname in a known_hosts file, listing any occurrences found. This option is useful to find hashed host names or addresses and may also be used in conjunction with the -H option to print found keys in a hashed format.

-f filename
Specifies the filename of the key file.

-G output_file
Generate candidate primes for DH-GEX. These primes must be screened for safety (using the -T option) before use.

-g' Use generic DNS format when printing fingerprint resource records using the -r command.

-H' Hash a known_hosts file. This replaces all hostnames and addresses with hashed representations within the specified file; the original content is moved to a file with a .old suffix. These hashes may be used normally by ssh and sshd, but they do not reveal identifying information should the file's contents be disclosed. This option will not modify existing hashed hostnames and is therefore safe to use on files that mix hashed and non-hashed names.

-i' This option will read an unencrypted private (or public) key file in SSH2-compatible format and print an OpenSSH compatible private (or public) key to stdout. ssh-keygen also reads the 'SECSH Public Key File Format'. This option allows importing keys from several commercial SSH implementations.

-l' Show fingerprint of specified public key file. Private RSA1 keys are also supported. For RSA and DSA keys ssh-keygen tries to find the matching public key file and prints its fingerprint.

-M memory
Specify the amount of memory to use (in megabytes) when generating candidate moduli for DH-GEX.

-N new_passphrase
Provides the new passphrase.

-P passphrase
Provides the (old) passphrase.

-p' Requests changing the passphrase of a private key file instead of creating a new private key. The program will prompt for the file containing the private key, for the old passphrase, and twice for the new passphrase.

-q' Silence ssh-keygen. Used by /etc/rc when creating a new key.

-R hostname
Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts (see the -H option above).

-r hostname
Print the SSHFP fingerprint resource record named hostname for the specified public key file.

-S start
Specify start point (in hex) when generating candidate moduli for DH-GEX.

-T output_file
Test DH group exchange candidate primes (generated using the -G option) for safety.

-t type
Specifies the type of key to create. The possible values are ''rsa1'' for protocol version 1 and ''rsa'' or ''dsa'' for protocol version 2.

-U reader
Upload an existing RSA private key into the smartcard in reader.

-v' Verbose mode. Causes ssh-keygen to print debugging messages about its progress. This is helpful for debugging moduli generation. Multiple -v options increase the verbosity. The maximum is 3.

-W generator
Specify desired generator when testing candidate moduli for DH-GEX.

-y' This option will read a private OpenSSH format file and print an OpenSSH public key to stdout.

Moduli Generation

ssh-keygen may be used to generate groups for the Diffie-Hellman Group Exchange (DH-GEX) protocol. Generating these groups is a two-step process: first, candidate primes are generated using a fast, but memory intensive process. These candidate primes are then tested for suitability (a CPU-intensive process).

Generation of primes is performed using the -G option. The desired length of the primes may be specified by the -b option. For example:

# ssh-keygen -G moduli-2048.candidates -b 2048

By default, the search for primes begins at a random point in the desired length range. This may be overridden using the -S option, which specifies a different start point (in hex).

Once a set of candidates have been generated, they must be tested for suitability. This may be performed using the -T option. In this mode ssh-keygen will read candidates from standard input (or a file specified using the -f option). For example:

# ssh-keygen -T moduli-2048 -f moduli-2048.candidates

By default, each candidate will be subjected to 100 primality tests. This may be overridden using the -a option. The DH generator value will be chosen automatically for the prime under consideration. If a specific generator is desired, it may be requested using the -W option. Valid generator values are 2, 3, and 5.

Screened DH groups may be installed in /etc/moduli. It is important that this file contains moduli of a range of bit lengths and that both ends of a connection share common moduli.

Files

~/.ssh/identity
Contains the protocol version 1 RSA authentication identity of the user. This file should not be readable by anyone but the user. It is possible to specify a passphrase when generating the key; that passphrase will be used to encrypt the private part of this file using 3DES. This file is not automatically accessed by ssh-keygen but it is offered as the default file for the private key. ssh(1) will read this file when a login attempt is made.

~/.ssh/identity.pub
Contains the protocol version 1 RSA public key for authentication. The contents of this file should be added to ~/.ssh/authorized_keys on all machines where the user wishes to log in using RSA authentication. There is no need to keep the contents of this file secret.

~/.ssh/id_dsa
Contains the protocol version 2 DSA authentication identity of the user. This file should not be readable by anyone but the user. It is possible to specify a passphrase when generating the key; that passphrase will be used to encrypt the private part of this file using 3DES. This file is not automatically accessed by ssh-keygen but it is offered as the default file for the private key. ssh(1) will read this file when a login attempt is made.

~/.ssh/id_dsa.pub
Contains the protocol version 2 DSA public key for authentication. The contents of this file should be added to ~/.ssh/authorized_keys on all machines where the user wishes to log in using public key authentication. There is no need to keep the contents of this file secret.

~/.ssh/id_rsa
Contains the protocol version 2 RSA authentication identity of the user. This file should not be readable by anyone but the user. It is possible to specify a passphrase when generating the key; that passphrase will be used to encrypt the private part of this file using 3DES. This file is not automatically accessed by ssh-keygen but it is offered as the default file for the private key. ssh(1) will read this file when a login attempt is made.

~/.ssh/id_rsa.pub
Contains the protocol version 2 RSA public key for authentication. The contents of this file should be added to ~/.ssh/authorized_keys on all machines where the user wishes to log in using public key authentication. There is no need to keep the contents of this file secret.

/etc/moduli
Contains Diffie-Hellman groups used for DH-GEX. The file format is described in moduli(5).



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: June 13, 2021