getting started with ssh security and configuration

22
Getting started with SSH security and configuration A hands-on guide Skill Level: Intermediate Roger Hill ([email protected]) Independent author 01 Feb 2011 Are you a new UNIX® administrator who needs to be able to run communication over a network in the most secure fashion possible? Brush up on the basics, learn the intricate details of SSH, and delve into the advanced capabilities of SSH to automate securely your daily system maintenance, remote system management, and use within advanced scripts to manage multiple hosts. What is SSH? A basic description Secure Shell (SSH) was intended and designed to afford the greatest protection when remotely accessing another host over the network. It encrypts the network exchange by providing better authentication facilities as well as features such as Secure Copy (SCP), Secure File Transfer Protocol (SFTP), X session forwarding, and port forwarding to increase the security of other insecure protocols. Various types of encryption are available, ranging from 512-bit encryption to as high as 32768 bits, inclusive of ciphers, like Blowfish, Triple DES, CAST-128, Advanced Encryption Scheme (AES), and ARCFOUR. Higher-bit encryption configurations come at a cost of greater network bandwidth use. Figure 1 and Figure 2 show how easily a telnet session can be casually viewed by anyone on the network using a network-sniffing application such as Wireshark. Figure 1. Telnet protocol sessions are unencrypted. Getting started with SSH security and configuration Trademarks © Copyright IBM Corporation 2011 Page 1 of 22

Upload: others

Post on 12-Sep-2021

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Getting started with SSH security and configuration

Getting started with SSH security and configurationA hands-on guide

Skill Level: Intermediate

Roger Hill ([email protected])Independent author

01 Feb 2011

Are you a new UNIX® administrator who needs to be able to run communication overa network in the most secure fashion possible? Brush up on the basics, learn theintricate details of SSH, and delve into the advanced capabilities of SSH to automatesecurely your daily system maintenance, remote system management, and usewithin advanced scripts to manage multiple hosts.

What is SSH? A basic description

Secure Shell (SSH) was intended and designed to afford the greatest protectionwhen remotely accessing another host over the network. It encrypts the networkexchange by providing better authentication facilities as well as features such asSecure Copy (SCP), Secure File Transfer Protocol (SFTP), X session forwarding,and port forwarding to increase the security of other insecure protocols. Varioustypes of encryption are available, ranging from 512-bit encryption to as high as32768 bits, inclusive of ciphers, like Blowfish, Triple DES, CAST-128, AdvancedEncryption Scheme (AES), and ARCFOUR. Higher-bit encryption configurationscome at a cost of greater network bandwidth use. Figure 1 and Figure 2 show howeasily a telnet session can be casually viewed by anyone on the network using anetwork-sniffing application such as Wireshark.

Figure 1. Telnet protocol sessions are unencrypted.

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 1 of 22

Page 2: Getting started with SSH security and configuration

Frequently used acronyms

• API: Application programming interface

• FTP: File Transfer Protocol

• IETF: Internet Engineering Task Force

• POSIX: Portable Operating System Interface for UNIX

• RFC: Request for Comments

• VPN: Virtual private network

When using an unsecured, "clear text" protocol such as telnet, anyone on thenetwork can pilfer your passwords and other sensitive information. Figure 1 showsuser fsmythe logging in to a remote host through a telnet connection. He enters hisuser name fsmythe and password r@m$20!0, which are both then viewable by anyother user on the same network as our hapless and unsuspecting telnet user.

Figure 2. SSH protocol sessions are encrypted.

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 2 of 22

Page 3: Getting started with SSH security and configuration

Figure 2 provides an overview of a typical SSH session and shows how theencrypted protocol cannot be viewed by any other user on the same networksegment. Every major Linux® and UNIX® distribution now comes with a version ofthe SSH packages installed by default—typically, the open source OpenSSHpackages—so there is little need to download and compile from source. If you're noton a Linux or UNIX platform, a plethora of open source and freeware SSH-basedtools are available that enjoy a large following for support and practice, such asWinSCP, Putty, FileZilla, TTSSH, and Cygwin (POSIX software installed on top theWindows® operating system). These tools offer a UNIX- or Linux-like shell interfaceon a Windows platform.

Whatever your operating system, SSH touts many positive benefits forcommonplace, everyday computing. Not only is it dependable, secure, and flexible,but it is also simple to install, use, and configure—not to mention feature laden.

SSH architecture

IETF RFCs 4251 through 4256 define SSH as the "Secure Shell Protocol for remotelogin and other secure network services over an insecure network." The shellconsists of three main elements (see Figure 3):

• Transport Layer Protocol: This protocol accommodates serverauthentication, privacy, and integrity with perfect forward privacy. Thislayer can provide optional compression and is run over a TCP/IP

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 3 of 22

Page 4: Getting started with SSH security and configuration

connection but can also be used on top of any other dependable datastream.

• User Authentication Protocol: This protocol authenticates the client tothe server and runs over the transport layer.

• Connection Protocol: This protocol multiplexes the encrypted tunnel tonumerous logical channels, running over the User AuthenticationProtocol.

Figure 3. SSH protocol logical layers

The transport layer is responsible for key exchange and server authentication. It setsup encryption, integrity verification, and (optionally) compression and exposes to theupper layer an API for sending and receiving plain text packets. A userauthentication layer provides authentication for clients as well as severalauthentication methods. Common authentication methods include password, publickey, keyboard-interactive, GSSAPI, SecureID, and PAM.

The connection layer defines channels, global requests, and the channel requeststhrough which SSH services are provided. A single SSH connection can hostmultiple channels concurrently, each transferring data in both directions. Channelrequests relay information such as the exit code of a server-side process. The SSHclient initiates a request to forward a server-side port.

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 4 of 22

Page 5: Getting started with SSH security and configuration

This open architecture design provides extensive flexibility. The transport layer iscomparable to Transport Layer Security (TLS), and you can employ customauthentication methods to extend the user authentication layer. Through theconnection layer, you can multiplex secondary sessions into a single SSHconnection (see Figure 4).

Figure 4. SSH within the Seven-layer OSI Model

Common use of SSH for UNIX and Linux systems

You typically use SSH to allow users to log in to a remote host and executecommands. However, SSH also supports tunneling and X11 connections. It caneven transfer files using SFTP or SCP. SSH is applicable for numerous applicationswithin most common platforms, including Linux, UNIX, Windows, and Apple® OS X,although some applications may require features that are only available orcompatible with specific SSH clients or servers.

Here are a few common SSH syntax examples:

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 5 of 22

Page 6: Getting started with SSH security and configuration

• Remote host shell access (supersedes telnet and rlogin clear text,insecure protocols):

# ssh [email protected][[email protected]] ~

• Executing a single command on a remote host (replacing rsh):

# ssh [email protected] [email protected]'s password: ******

• Copying files from a local server to a remote host by way of the SCPcommand:

[email protected]'s password: ******file1.txt 100% 0 0.0KB/s 00:00file2.txt 100% 0 0.0KB/s 00:00

• In combination with SFTP, as a secure substitute to FTP file transfer:

sftp [email protected] to [email protected]'s password: *******sftp>

• In combination with rsync to back up, copy, and mirror files efficiently andsecurely to a local or remote host:

# rsync -avul --rsh=ssh /opt/edbdata/ [email protected]:/root/backup/[email protected]'s password: ******building file list ... done./file1.txtfile2.txtfile3.txtfile4.txtdir1/file5.txtdir2/file6.txt

sent 982813 bytes received 2116 bytes 1374860.38 bytes/sectotal size is 982138 speedup is 1.00

• Port forwarding or tunneling a port (not to be confused with a VPN):

ssh -L 8000:mailserver:110 example.com [email protected]'s password: ********

• Forwarding X sessions from a remote host (possible through multipleintermediate hosts):

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 6 of 22

Page 7: Getting started with SSH security and configuration

Edit /etc/ssh/sshd_config and change 2 keywords :AllowTcpForwarding yesX11Forwarding yes# service sshd restart$ export DISPLAY$ ssh -X [email protected]

• With the X11 forwarding configuration in conjunction with an X Windowsclient with SSH X11 tunneling to allow for the implementation of a UNIX orLinux GUI subsystem run over SSH securely on the same Windowsmachine host that is the source for the SSH session to the Linux or UNIXremote host:

ssh -ND 8000 [email protected] Settings, goto 'Manual Proxy Configuration' set "SOCKS Host" to example.com,the 'Port to 8000' , Enable SOCKS v5, and lastly set 'No Proxy for' fieldto 'localhost, 127.0.0.1'

• Securely mounting a directory on a remote server as a file system on alocal computer using sshfs:

# yum install sshfs fuse-utils (Install sshfs and fuse-utils)$sshfs example.com:/remote_dir /mnt/local_dir

• Automated remote host monitoring and management of servers throughone or more mechanism:

(Report number of apache processes running on the remote server example.com):$ ssh example.com ps -ef | grep httpd | wc [email protected]'s password: *****

SSH security and configuration best practices

With some of the previously illustrated code examples, many good systemsadministrators are nervous about some of the security implementations for SSHusage and functions. Although much has been said and written about the variousapproaches to SSH security and remote host security in general, here is a list ofprocesses and configurations that you can use to tighten and enhance SSH securitywith regard to remote host access:

• Restrict the root account to console access only:

# vi /etc/ssh/sshd_configPermitRootLogin no

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 7 of 22

Page 8: Getting started with SSH security and configuration

• Create private-public key pairs using a strong passphrase and passwordprotection for the private key (never generate a password-less key pair ora password-less passphrase key-less login):

(Use a higher bit rate for the encryption for more security)ssh-keygen -t rsa -b 4096

• Configure TCP wrappers to allow only selective remote hosts and denyundesirable hosts:

# vi /etc/hosts.denyALL: 192.168.200.09 # IP Address of badguy

• On workstations or laptops, disable the SSH server by turning off the SSHservice, and then removing the ssh server package:

# chkconfig sshd off# yum erase openssh-server

• Restrict SSH access by controlling user access:

# vi /etc/ssh/sshd_configAllowUsers fsmythe bnice swilsonDenyUsers jhacker joebadguy jripper

• Only use SSH Protocol 2:

# vi /etc/ssh/sshd_configProtocol 2

• Don't allow Idle sessions, and configure the Idle Log Out Timeout interval:

# vi /etc/ssh/sshd_configClientAliveInterval 600 # (Set to 600 seconds = 10 minutes)ClientAliveCountMax 0

• Disable host-based authentication:

# vi /etc/ssh/sshd_configHostbasedAuthentication no

• Disable users' .rhosts files:

# vi /etc/ssh/sshd_configIgnoreRhosts yes

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 8 of 22

Page 9: Getting started with SSH security and configuration

• Configure firewalls to accept SSH connections only from know networksegments:

Update /etc/sysconfig/iptables (Redhat specific file) to accept connection onlyfrom 192.168.100.0/24 and 209.64.100.5/27, enter:

-A RH-FW-1-INPUT -s 192.168.100.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT-A RH-FW-1-INPUT -s 209.64.100.5/27 -m state --state NEW -p tcp --dport 22 -j ACCEPT

• Restrict the available interfaces that SSH will listen on and bind to:

# vi /etc/ssh/sshd_configListenAddress 192.168.100.17ListenAddress 209.64.100.15

• Set user policy to enforce strong passwords to protect against brute force,social engineering attempts, and dictionary attacks:

# < /dev/urandom tr -dc A-Za-z0-9_ | head -c8oP0FNAUt[

• Confine SFTP users to their own home directories by using ChrootSSHD:

# vi /etc/ssh/sshd_configChrootDirectory /data01/home/%uX11Forwarding noAllowTcpForwarding no

• Disable empty passwords:

# vi /etc/ssh/sshd_configPermitEmptyPasswords no

• Rate-limit the number of incoming port 2022 connections within aspecified time:

Redhat iptables example (Update /etc/sysconfig/iptables):

-A INPUT -i eth0 -p tcp --dport 2022 -m state --state NEW -m limit --limit 3/min--limit-burst 3 -j ACCEPT

-A INPUT -i eth0 -p tcp --dport 2022 -m state --state ESTABLISHED -j ACCEPT-A OUTPUT -o eth0 -p tcp --sport 2022 -m state --state ESTABLISHED -j ACCEPT

• Configure iptables to allow only three connection attempts on port

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 9 of 22

Page 10: Getting started with SSH security and configuration

2022 within 30 seconds:

Redhat iptables example (Update /etc/sysconfig/iptables):-I INPUT -p tcp --dport 2022 -i eth0 -m state --state NEW -m recent --set

-I INPUT -p tcp --dport 2022 -i eth0 -m state --state NEW -m recent --update--seconds 30 --hitcount 3 -j DR

• Use a log analyzer such as logcheck, loggrep, splunk, or logwatchto better understand the logs and create logging reports. Also, increaselogging verbosity within the SSH application itself:

Installation of the logwatch package on Redhat Linux# yum install logwatch

• Configure an increase in SSH logging verbosity:

# vi /etc/ssh/sshd_configLogLevel DEBUG

• Always keep the SSH packages and required libraries up to date onpatches:

# yum update openssh-server openssh openssh-clients -y

• Conceal the OpenSSH version, require SSH source code, andre-compile. Then, make the following updates:

# vi /etc/ssh/sshd_configVerifyReverseMapping yes # Turn on reverse name checkingUsePrivilegeSeparation yes # Turn on privilege separationStrictModes yes # Prevent the use of insecure home directory

# and key file permissionsAllowTcpForwarding no # Turn off , if at all possibleX11Forwarding no # Turn off , if at all possiblePasswordAuthentication no # Specifies whether password authentication is

# allowed. The default is yes. Users must have# another authentication method available .

• Delete the rlogin and rsh binaries from the system, and replace them witha symlink to SSH:

# find /usr -name rsh/usr/bin/rsh# rm -f /usr/bin/rsh# ln -s /usr/bin/ssh /usr/bin/rsh

SSH supports numerous, diverse methods and techniques for authentication that

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 10 of 22

Page 11: Getting started with SSH security and configuration

you can enable or disable. Within the /etc/ssh/sshd_config file, you make theseconfigurations changes by entering the keyword listed for the authentication methodfollowed by yes or no. Here are some of the common configuration changes:

# RSAAuthentication yes# PubkeyAuthentication yes# RhostsRSAAuthentication no# HostbasedAuthentication no# RhostsRSAAuthentication and HostbasedAuthenticationPasswordAuthentication yesChallengeResponseAuthentication no# KerberosAuthentication noGSSAPIAuthentication yes

The keywords AllowedAuthentications and RequiredAuthenticationswithin the sshd_config file dictate which authentication methods and configurationsare used with SSH Protocol 2 only, and the syntax for them to allow password andpublic key authentication is as follows:

# vi /etc/ssh/sshd_configAllowedAuthentications publickey, passwordRequiredAuthentications publickey, password

Private and public key pairs for SSH

To help validate identities, SSH has a key management capacity and related agents.When configured with public key authentication, your key proves your identity toremote SSH hosts. An SSH-based identity consists of two parts: a public key and aprivate key. The private SSH key is the user's identity for outbound SSH connectionsand should be kept confidential. When a user initiates an SSH or SCP session to aremote host or server, he or she is said to be the SSH client. Through amathematical algorithm, a private key is like your electronic identification card; thepublic key is like the lock or gate mechanism that you present your ID card to. Yourprivate key says, "This really is Fred Smythe"; the public key says, "Yes, you areindeed the real Fred Smythe; you are now authenticated: Please enter."

Your public key represents who you will allow inbound access to through your gateor lock. Public keys need not be kept secret; they cannot be used to compromise asystem or for unwarranted access into a system. On a Linux or UNIX system, theseprivate and public key pairs are stored in ASCII text files; on Windows systems,some programs store the key pairs as text files, some in the Windows registry.

Multiple identifications using multiple private keys can be created with an SSHProtocol 2 configuration. Let's look at how to generate, set up, and configure an SSHprivate and public key pair on typical Linux hosts (see Figure 5).

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 11 of 22

Page 12: Getting started with SSH security and configuration

Figure 5. Diagram of the SSH private-public key pair transactions, as definedwithin the SSH defined architecture model

Steps for configuring public and private SSH key pairs

The example shown in step 1 (see Listing 1) uses the ssh-keygen utility for userfsmythe to create the SSH private-public key pair with the type of dsa.

Listing 1. Generate the SSH key pair

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 12 of 22

Page 13: Getting started with SSH security and configuration

[[email protected] ~]$ /usr/bin/ssh-keygen -t dsaGenerating public/private dsa key pair.Enter file in which to save the key (/home/fsmythe/.ssh/id_dsa):Enter passphrase (empty for no passphrase): ****** (Enter 'mypassword')Enter same passphrase again: ****** (Enter 'mypassword')Your identification has been saved in /home/fsmythe/.ssh/id_dsa.Your public key has been saved in /home/fsmythe/.ssh/id_dsa.pub.The key fingerprint is:33:af:35:cd:58:9c:11:91:0f:4a:0c:3a:d8:1f:0e:e6 [email protected][[email protected] ~]$

The example shown in step 2 (Listing 2) illustrates copying the private key of the keypair from the source to the destination host's authorized_keys file within the .sshsubdirectory under the home directory of the desired user account on the destinationhost.

Listing 2. Copy the private key from the source host to the authorized_keysfile on the destination host

[[email protected] ~]$ scp -p /home/fsmythe/.ssh/[email protected]:/home/fsmythe/.ssh/authorized_keysfsmythe@ thor01.com's password:id_dsa.pub 100% 624 0.6KB/s 00:00

The example shown for step 3 (see Listing 3) makes the first-time remote SSH call(ls -d /tmp) to the destination server, thereby caching the key within yourserver's .ssh/known_hosts file. You enter the same passphrase with which youcreated the SSH private-public key pair, and the output of the command run on theremote destination server is seen locally back on your source server.

Listing 3. Verify the SSH access by running a remote command on the targetremote host

[[email protected] ~]$ ssh [email protected] ls -d /tmpThe authenticity of host 'thor01.com (10.12.53.118)' can't be established.RSA key fingerprint is 84:4f:e5:99:0b:7d:54:d0:1b:3e:2b:96:02:34:41:25.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added 'thor01.com,10.12.53.118' (RSA) to the list of known hosts.Enter passphrase for key '/root/.ssh/id_dsa': ****** (Enter 'mypassword')/tmpfile1.txtfile2.txtdir3_5432

Note: For the examples above, you didn't have to enter the user fsmythe'spassword. Rather, you enter the passphrase that you set in the first step. If youwould rather not have to enter a passphrase when accessing the remote destination,create an empty passphrase by typing enter in step 1 when prompted for thepassphrase. Now, you won't have to type anything to access the thor01.com remotetarget machine as the user fsmythe.

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 13 of 22

Page 14: Getting started with SSH security and configuration

Configuring and using the ssh-agent

For the truly paranoid who refuse to create a password-less SSH public-private keypair, there's the ssh-agent utility. In a nutshell, you use the ssh-agent utility totemporarily grant password-less SSH access on a public-private key pairconfiguration that does have a passphrase set, but only for the current shell session.Before employing the ssh-agent utility, enter the passphrase as normal:

[[email protected] ~]# ssh [email protected] passphrase for key '/root/.ssh/id_dsa':****** (User must type password)Last login: Sat May 8 06:37:26 2010 from 10.12.53.118

Next, query ssh-agent to generate Bourne shell commands on stdout:

[[email protected] ~]# ssh-agent -sSSH_AUTH_SOCK=/tmp/ssh-vxZIxF1845/agent.1845; export SSH_AUTH_SOCK;SSH_AGENT_PID=1849; export SSH_AGENT_PID;echo Agent pid 1849;

In step 3, you set the aforementioned environmental variables in the current shellsession:

[root@example01 ~]# SSH_AUTH_SOCK=/tmp/ssh-vxZIxF1845/agent.1845;export SSH_AUTH_SOCKSSH_AGENT_PID=1849; export SSH_AGENT_PID;echo Agent pid 1849Agent pid 1849

Then, verify that the ssh-agent is running:

[[email protected] ~]# ps -fp $SSH_AGENT_PIDUID PID PPID C STIME TTY TIME CMDroot 1849 1 0 06:14 ? 00:00:00 ssh-agent -s

Now, list the currently loaded identities within the running ssh-agent:

[[email protected] ~]# ssh-add -lThe agent has no identities.

In step 6, add the desired SSH identities (preauthenticating them with the correctpassphrase for that SSH key):

[[email protected] ~]# ssh-addEnter passphrase for /root/.ssh/id_dsa:Identity added: /root/.ssh/id_dsa (/root/.ssh/id_dsa) ****** (Entered 'mypassword')

Now, you can verify that those identities are loaded into the running ssh-agent:

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 14 of 22

Page 15: Getting started with SSH security and configuration

[[email protected] ~]# ssh-add -l1024 33:af:35:cd:58:9c:11:91:0f:4a:0c:3a:d8:1f:0e:e6 /root/.ssh/id_dsa (DSA)

Finally, test the ssh-agent with SSH command syntax. Note that now there's nopassphrase prompt:

# Assuming target remote host has correct authorized key for private key from example01[[email protected] ~]# ssh -A [email protected] login: Sat May 8 06:36:27 2010 from 10.12.53.118[root@example02 ~]#

# Assuming target remote host has correct authorized key for private key from example03[[email protected] ~]# ssh -A [email protected] login: Sat May 8 07:04:05 2010 from 10.12.53.119[root@example03 ~]#

When you enter the passphrase using the ssh-add command, you are actuallydecrypting the private key and then placing it in memory through the agent for anyfuture SSH connections with that particular passphrase. Note that you can entermultiple private keys and pre-authenticate them with the ssh-add command.

The SSH tool ssh-keyscan, shown in Listing 4, allows you to gather the publicSSH host keys from multiple remote SSH hosts. The tool is helpful in building of the/etc/ssh_known_hosts files and is exceptionally fast and efficient. It is primarilysuited to shell scripts for automation purposes.

Listing 4. Example using ssh-keyscan

[root@example01 ~]# /usr/bin/ssh-keyscan -t rsa,dsa example02.com# example02.comSSH-2.0-OpenSSH_4.3example02.comssh-dss AAAAB3NzaC1kc3MAAACBALd5/TGn7jCL1DWWzYMw96jw3QOZGBXJgP4m9LACViyM0QHsewHGo841JdInfE825mVe0nB/UT15iylLOsI/jFCac+ljQRlO+h2q7WOwGveOUN7TxyKlejM+G1pg5DndGt05iYn+2dDfn5CmEsI+K0F2vk/+mpoSOk9HKq9VgwNzAAAAFQDPeLAth62TRUcN/nTYoqENBmW3SwAAAIEAryoKa+VaG5LQNjwBujAuA7hGl+DIWVb1aZ8xAHkcyL5XgrOWEKNnK9mDmEN66oMLfTMO3w8/OvbJUmcXcU3jnL3zguz2E2OIv6t6vAaF6niL7A/VhxGGxy4CJZnceufStrzZ3UKXRzjwlm0Bwu/LruVF2m3XLvR5XVwUgyWvw+AAAACAaK12k3uC/OOokBgieu/SuD5wCSBsf9rqG9ZFa32ujZwRZmA/AwPrZd6q3ASxmjtMp6zGQSzxPczUvLH9D9WIJo713bw8wCPo/7pqiQNRsOZXqlQyaXyrDout6CI683b1/rxsZKPrJpFNehrZwjWrwpYhK7VaTuzxvWtrDyDxWec=# example03.comSSH-2.0-OpenSSH_4.3example03.comssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq5So5VBeH4gPX1A1VEeQkGsb/miiWsWnNTW8ZWYj2IvU7rKpk/dBIp64WecYYYgDqTK5u0Q+yTijF8wEEI9rRyoh9p5QraM8qy9NxcHzyGqU4vSzfVrblIQrDI8iv7iwz7PxQAY76NmweaUyGEDfIErty4gCn/ksy85IgffATa9nt36a4iUhiDNifnE8dm1ZrKkvz3lIg0w+Cu0T9MY77AqLWjMoo0WoQArIvYa0soS3VhzgD/Biwu/sh3eHJtFUxTVxnATdkWkHKUI1wxma3j7jF0saTRKEQSvG6492W+U1FhEjFGNr7KeZXH99uFpuUWFA7xO7uaG/MLWSjPJMxw==# example04.comSSH-2.0-OpenSSH_4.3example04.comssh-dss AAAAB3NzaC1kc3MAAACBALd5/TGn7jCL1DWWzYMw96jw3QOZGBXJgP4m9LACViyM0QHsewHGo841JdInfE825mVe0nB/UT15iylLOsI/jFCac+ljQRlO+h2q7WOwGveOUN7TxyKlejM+G1pg5DndGt05iYn+2dDfn5CmEsI+K0F2vk/+mpoSOk9HKq9VgwNzAAAAFQDPeLAth62TRUcN/nTYoqENBmW3SwAAAIEAryoKa+VaG5LQNjwBujAuA7hGl+DIWVb1aZ8xAHkcyL5XgrOWEKNnK9mDmEN66oMLfTMO3w8/OvbJUmcXcU3jnL3zguz2E2OIv6t6vAaF6niL7A/VhxGGxy4CJZnceufStrzZ3UKXRzjwlm0Bwu/LruVF2m3XLvR5XVwUgyWvw+AAAACAaK12k3uC/OOokBgieu/SuD5wCSBsf9rqG9ZFa32ujZwRZmA/AwPrZd6q3ASxmjtMp6zGQSzxPczUvLH9D9WIJo713bw8wCPo/7pqiQNRsOZXqlQyaXyrDout6CI683b1/rxsZKPrJpFNehrZwjWrwpYhK7VaTuzxvWtrDyDxWec=# example05.comSSH-2.0-OpenSSH_4.3example05.comssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq5So5VBeH4gPX1A1VEeQkGsb/miiWsWnNTW8ZWYj2IvU7rKpk/dBIp64WecYYYgDqTK5u0Q+yTijF8wEEI9rRyoh9p5QraM8qy9NxcHzyGqU4vSzfVrblIQrDI8iv7iwz7PxQAY76NmweaUyGEDfIErty4gCn/ksy85IgffATa9nt36a4iUhiDNifnE8dm1ZrKkvz3lIg0w+Cu0T9MY77AqLWjMoo0WoQArIvYa0soS3VhzgD/Biwu/sh3eHJtFUxTVxnATdkWkHKUI1wxma3j7jF0saTRKEQSvG6492W+U1FhEjFGN

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 15 of 22

Page 16: Getting started with SSH security and configuration

r7KeZXH99uFpuUWFA7xO7uaG/MLWSjPJMxw==

Configuring SSH with UNIX applications or scripts

Configuration of SSH access for use by remote shell scripts and remote tools formaintenance, remote backup, and archival systems has great usefulness, but it hasalways been at the very least a subject of high controversy when it comes to serversecurity. Many shell scripts that a user might want to run, such as:

$ ssh [email protected]/usr/local/bin/dangerous_script.pl

cannot handle a required SSH passphrase prompting him or her to authenticate butin fact will break unless a password-less private-public SSH key pair, an ssh-agentconfiguration, or possibly a trusted host network mechanism—something that doesnot prompt for an SSH password—has been configured ahead of time. This isbecause SSH expects the passphrase from the current terminal associated with thatshell session. A user can get around this issue by using an expect script or possiblya Perl (see CPAN Module Net::SSH::Perl) script (or your shell script couldalternatively call one of the aforementioned types of scripts):

#!/usr/local/bin/expectspawn sftp $argvexpect "password:"send "mysshpassowrd\r"

Granting a password-less SSH mechanism for remote host access to typical users isjustification enough for a lynching in the eyes of some systems administrators.However, alternative security measures to justify the password-less SSHmechanism for remote host access, such as a user on the remote host machine onlygiven a restricted korn shell (rksh) account or restricted shell (rssh) instead of a fullbash or Bourne shell account. It is also possible on an authorized key to restrict auser to a subset of commands in a list so that in effect, the user can only use theexact commands required to run remotely without the possibility for further access oran accidental command run that could damage the system. The SSH restrictionexample provided in Listing 5 provides such a restriction type.

Listing 5. Example of configuration restricting the authorized_keys file onremote host

[fsmythe@example02 .ssh]$ more authorized_keyscommand="/usr/local/bin/secureScript.sh",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-dssAAAAB3NzaC1kc3MAAACBAOFsC6C7cJUGOZG4Ur9W0J6mxTTk5+MYTu5XfRESPLVwQA7HlUxhsXsxgmb1L1RgvR/g0JZnipDS+fGOrN2/IerSpgyzegTVxYLPrOovvuyCn5TA0+rmyrkV27so6yRDkdqTJc

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 16 of 22

Page 17: Getting started with SSH security and configuration

YzWNJOyDndnTrDc/LNmqLFKoGMQ33aur6RNv4VAAAAFQD4leC5Fc1VJqjvXCNsvazBhi84vQAAAIAWbshT80cTESgdX/srxX4KVNAzY1uhBz5V0UYR4FGP+aoe6laxRj+gQvFIvAKIrpikvBjgyW6cdT8+k0t8HGIQp20MzSBdY9sH8xdj05AG97Nb/L8xzkceB78qfXhV6txaM1CzssUtiOtaAygrywNPBDEN9MbEbwpVVVyd6iqZNgAAAIAmV0SUZoUr8dHdCtagRye4bGOQjoztpb4C0RbXQw+w7Jpzr6cZISdZsK4DTBjODvv2+/OWPm7NEzzWyLzHPBNul8hAHOUCOpp+mYWbXXF78BTk2Ess0SZu8dwpOtasTNEp+xPcsOvQx2Kdr17gTp+28SfpREuLudOr6R3KeTb+hw==fsmythe@example01

User fsmythe at host example01 is only allowed to execute the command="/usr/local/bin/secureScript.sh in this example.

Creating a trusted host environment using SSH

Finally, I mention the trusted host environment as an alternative to setting uppublic-private SSH key pairs. For automation or in a scripted environment in whichthese types of calls are necessary, the trusted host network, though still bearingsome security risks, has advantages over the public-private key pair scenario. Atrusted host network or trusted host authentication relies primarily on preconfiguredfiles that list a combination of users and hosts that are allowed access. There aretwo types of trusted-host authentication. The older (such as for OpenSSH andSSH1) and weaker uses the clear-text protocol commands (rsh, rcp, and rlogin);checks the two files; and sets one keyword in the sshd_config file:

/etc/hosts.equiv~/.rhosts

SSH Protocol 2 does not support this method. Instead, for a more secure trustedhost network, make the following changes in the /etc/ssh/sshd_config file (whichaccepts host names or IP Addresses), and configure the shosts.equiv and/or the.shosts files:

/etc/shosts.equiv~/.shosts

To enable a trusted-host environment in the /etc/ssh/sshd_config file for SSHProtocol 2, use:

PermitEmptyPasswords yesAllowSHosts remoteclient.comDenySHosts

For example, if you were on the server example.com and had configured your/etc/shosts.equiv file as follows:

+remoteclient.com fsmythe

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 17 of 22

Page 18: Getting started with SSH security and configuration

+secureserver.net sallyh+192.168.100.12 fsmythe-hackers.org james

you would allow user fsmythe trusted host authentication from the remote sourcesremoteclient.com, 192.168.100.12, and secureserver.net and user sallyh accessfrom secureserver.net, denying access from user james at the remote sourcehackers.org.

The trusted-host authentication and public-private SSH key pair authenticationmethods are similar and to a greater end achieve the same results. Table 1 providesa side-by-side comparison of the two authentication methods.

Table 1. Comparison of private-public SSH key pairs with trusted-hostconfigurationSSH aspect Trusted host Private-public key pair

Authenticate by IP address Yes Yes

Authenticate by host name Yes Yes

Use other public key features No Yes

Authenticate by remote username

Yes No

Allow wildcards in host namesand IP addresses

No Yes

Passphrase is necessary forlogin access

No No

Breaks on IP address or hostname change

Sometimes Yes

Configuration required on theserver and client

No Yes

Useful for automated tasks orscripting needs

Yes Yes

To those admins who are scoffing right now at the thought of allowing a trusted hostauthentication system using password-less remote SSH access on their network,consider the downside of public-private key pairs when using a script for remoteSSH functionality:

• If a server host name or IP address changes, the public-private key pairconfiguration will break because of the cached known hosts. The old entrywill need to be removed in the .ssh/known_hosts file and the SSH remotehost name and/or IP address re-cached again. This will break scriptsdependant on the private-public key pair.

• Private-public key pair authentication requires both client and server

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 18 of 22

Page 19: Getting started with SSH security and configuration

configuration. If an SSH public key changes or the pair is regenerated, allof the remote hosts will need the new public key in their authorized_keysfile.

• If the permissions of the .ssh/ folder or private or public key filesthemselves change, it could prevent the SSH password-less access fromoccurring. To disable strict file and directory permissions checking, set thekeyword StrictModes to no within /etc/ssh/sshd_config file.

• There is no centralized way to revoke a key once a key pair has beengenerated or to know exactly to whom the key has been distributed.

Conclusion

SSH is a powerful and secure network utility that countless users worldwide use fornumerous tasks. Offered as a safe and secure alternative to the clear-text protocolssuch as telnet and the r* series command and with multiple offerings of freelydistributable SSH clients and servers, SSH is difficult to beat. Used widely in manynetworks for mass remote monitoring, system maintenance, remote system auditing,reporting, and automation within scripting technologies, it appears that SSH is hereto stay and will continue to evolve.

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 19 of 22

Page 20: Getting started with SSH security and configuration

Downloads

Description Name Size Downloadmethod

Putty Windows SSH client installer putty-0.60-installer.exe 1.7MB HTTP

FileZilla Windows SSH installer FileZilla_3.3.2.1_win32-setup.exe 4.0MB HTTP

Tera Term Windows SSH installer teraterm-4.65.exe 7.5MB HTTP

WinSCP installation package winscp427setup.exe 2.9MB HTTP

Cygwin Universal Downloader SoftonicDownloader11694.exe 251KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 20 of 22

Page 21: Getting started with SSH security and configuration

Resources

Learn

• Secure Shell. Wikipedia provides a good introduction and discussion of SSH.

• OpenSSH: OpenSSH is a version of the connectivity tools that technical usersof the Internet rely on. It is available at no cost.

• RFC 4251: Read the SSH protocol architecture.

• The OpenSSH Protocol under the Hood (Girish Venkatachalam, Linux Journal,April 2007): Get the "nitty-gritty details" on OpenSSH.

• Server clinic: Connect securely with ssh (Cameron Laird, developerWorks, July2003): Learn more about securing your servers with SSH.

• SSH and ssh-agent: Learn more about and download the tools fromSymantec.

• SSH public keys: Learn more about the risks of using public keys.

• SSH tutorial for Linux: Suso.com offers a good tutorial for getting started withSSH in a Linux environment.

• Five SSH tricks: Discover five SSH tricks you simply must know.

• Top 20 OpenSSH Server Best Security Practices: Discover these server bestsecurity practices.

• AIX and UNIX developerWorks zone: The AIX and UNIX zone provides awealth of information relating to all aspects of AIX systems administration andexpanding your UNIX skills.

• New to AIX and UNIX? Visit the New to AIX and UNIX page to learn more.

• Technology bookstore: Browse the technology bookstore for books on this andother technical topics.

Discuss

• SSH user community: Get involved in the SSH community.

• Follow developerWorks on Twitter.

• developerWorks blogs: Check out our blogs and get involved in thedeveloperWorks community.

• Get involved in the My developerWorks community.

• Participate in the AIX and UNIX® forums:

• AIX Forum

ibm.com/developerWorks developerWorks®

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 21 of 22

Page 22: Getting started with SSH security and configuration

• AIX Forum for developers

• Cluster Systems Management

• Performance Tools Forum

• Virtualization Forum

• More AIX and UNIX Forums

About the author

Roger HillRoger Hill has worked as a UNIX®/Linux® systems engineer andprogrammer/developer in large, complex hybrid environments for thepast 23 years. His specialization for the past seven years has been onintercommunications between various UNIX, Linux, and Windows®platforms and creating seamless and secure automation for suchsystems. Roger holds an Associate's Degree in Computer InformationSystems, a Bachelor's Degree in Computer Science, and a Chancellor'sCertificate in Linux Administration and maintains nine professionaltechnical certifications.

developerWorks® ibm.com/developerWorks

Getting started with SSH security and configuration Trademarks© Copyright IBM Corporation 2011 Page 22 of 22