If StrictHostKeyChecking is enabled, ssh will refuse to connect to any remote host for which there is not a correct public key cached.. This is only useful when public key authentication
Trang 1warnings about host key changes By default, host keys for the localhost are checked, as
demonstrated in the following code:
NoHostAuthenticationForLocalhost no
NumberOfPasswordPrompts
This keyword requires an integer as an argument It specifies how many password attempts
should be made before the client gives up By default, this is 3, as shown in the following example:
NumberOfPasswordsPrompts 3
PasswordAuthentication
This token instructs the ssh client to attempt or not to attempt password-based authentication
via a yes/no argument When using key-based authentication for automated jobs or system
activity, it is often a good idea to set PasswordAuthentication to no This is covered in more
detail in Chapter 6
PasswordAuthentication yes
Port
This keyword tells the client what port on the remote server should be used for the SSH
connection The default is 22, as shown in the following example:
Port 22
PreferredAuthentications
This keyword tells ssh the order of preference for authentication techniques By default, this
uses hostbased,publickey,keyboard-interactive,password As you see in the example that
follows, I often take out hostbased authentication because of my fondness for user-specified
security This option only applies to protocol 2
PreferredAuthentications publickey,keyboard-interactive,password
Protocol
This argument tells the client which protocol should be used The default is 2,1—meaning
that protocol 2 will be attempted, and if it fails, protocol 1 will be used Normally, I explicitly
specify protocol 2 only, as in the following code line Multiple arguments are comma separated
Protocol 2
ProxyCommand
When using a proxy, the command string can be specified with a few expandable parameters
%his used for hostname, and %p is used for port The command can be any appropriate string
for your proxy Setting the command to none will disable this option
Trang 2This protocol 1 keyword will allow rhost-based authentication with RSA host authentication ifset to yes By default, as shown in the following code line, this is set to no It also requires ssh tohave SetUID root permissions For security reasons, both with host-based authentication andsshprotocol 1, the default is acceptable.
RhostsRSAAuthentication no
RSAAuthentication
If set to yes, as in the following example, RSA authentication will be attempted, provided theidentity file exists By default, this option is enabled This option applies to protocol 1 only.RSAAuthenticationtakes yes/no arguments
RSAAuthentication yes
SendEnv
The client can use SendEnv to send local environment variables to the remote server, providedthat sshd is configured to allow it This is only allowed using protocol 2 Environment variablesmay contain simple regular expressions using the * and ? characters
stahnke@rack: ~/.ssh> export TEST_ENV="OpenSSH testing"
stahnke@rack: ~/.ssh> cat config
stahnke@www: ~> set | grep TEST
TEST_ENV='OpenSSH testing'
Trang 3The ssh client can be configured to request data from the sshd server at given intervals using
ServerAliveInterval This is different from TCPKeepAlive, because the request is sent in the
SSH tunnel, encrypted at the application level TCPKeepAlive requests are standard TCP
pack-ets that can be spoofed
The arguments are specified in seconds; after the specified amount of time, if the sshclient has received no data from the sshd process it is connected to, it will send a message that
requires a response This option only applies to protocol 2 By default the value is 0, which
means that no keep-alive messages are sent Here is an example of ServerAliveInterval:
ServerAliveInterval 5
ServerAliveCountMax
This keyword tells the ssh client how many server keep-alive requests it should send without
response before giving up and terminating the connection These keep-alives are sent through
the ssh pipe and are therefore encrypted By default the value is 3 Following is an example:
ServerAliveCountMax 10
The time without response before the ssh client gives up on the server is ServerAliveCountMax×ServerAliveInterval
SmartcardDevice
Smart cards are devices (about the size of a credit card) that hold your personal identification
information When dealing with SSH, this means your private key; either RSA or DSA is stored
on the smart card
If you are using a smart-card reader, specify the path to the device By default, smart-cardusage is not enabled
StrictHostKeyChecking
When a connection is made to a remote system with a host key that is not cached or does not
match the key cached on disk, ssh will normally balk If StrictHostKeyChecking is enabled, ssh
will refuse to connect to any remote host for which there is not a correct public key cached If
set to no, ssh will make the connection and cache it automatically; however, a layer of security
against the man-in-the-middle attack is lost with this setting The default of ask requires ssh to
ask whether a connection should proceed if there is no record of the remote host’s public host
key on disk If a public host key changes in ask mode, the old key must be removed from the
known_hostsfile for a connection to be established
StrictHostKeyCheckingcan cause many users to dislike SSH; however, its added securitybenefits are real This allows the client to verify and reverify the server’s identity each connec-
tion This prevents IP spoofing from being a viable attack Educating users about the importance
of host key caching can assist with improving security
If your network is mainly DHCP based, then setting StrictHostKeyChecking to no is probablythe best option, as the host keys will constantly change
Trang 4For scripting and batch processing, sometimes setting StrictHostKeyChecking to no willallow the script to deal with more anomalies and complete successfully, if you are relativelysure the network is secured.
# StrictHostKeyChecking set to yes
stahnke@rack: ~/.ssh> > known_hosts
stahnke@rack: ~/.ssh> ssh www
No RSA host key is known for www and you have requested strict checking
Host key verification failed
After removing my public key cache, my connection to www is denied because no public key ispresent
# StrictHostKeyChecking set to ask
stahnke@rack: ~/.ssh> ssh www
The authenticity of host 'www (192.168.1.109)' can't be established
RSA key fingerprint is d9:2f:0d:72:a9:cb:5d:07:e6:23:23:e5:cb:ba:35:3f
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'www,192.168.1.109' (RSA) to the list of known hosts.When set to ask, StrictHostKeyChecking allows the connection to continue by having meenter yes
This directive tells the ssh client whether or not it should send TCP keep-alive messages to theserver via a yes/no argument By default, TCP keep-alive messages are sent For most purposesServerAliveIntervaland ServerAliveCountMax work as well as TCPKeepAlive and are moresecure since they cannot be tampered with because of the encrypted connection Following is
an example:
TCPKeepAlive no
UsePrivilegedPort
Normally ssh uses a high-numbered (> 1024) port for outbound connections If UsePrivilegedPort
is set to yes, it will use ports below 1024 The arguments for this keyword are yes and no Bydefault, it is set to no If enabled, the ssh client must have permissions of SetUID root, andtherefore should be avoided
Trang 5If you have different login names on remote systems, they can be specified per host under the
Hostkeyword Then the remote username is not required on the command line
If SSHFP (SSH FingerPrint) records are stored in DNS, the ssh client can check to see whether
the fingerprint returned from the server matches the one published via a resource record in DNS
If they do match, the key is automatically trusted Otherwise, the public keys are handled as if
this option was set to ask, thus making the user allow or deny the connection By default, this
keyword is set to no This applies to version 2 only Chapter 8 offers more discussion on this topic
XAuthLocation
The argument to XAuthLocation is the full path to the xauth program On Red Hat Linux systems,
it is found normally in /usr/X11/bin/xauth Your results may vary If no xauth is present, this
option is disabled
ssh_config documented
In an enterprise environment, accountability is a must Auditors, whether they are internal or
third party, come to audit information technology spaces and discover your adherence and
noncompliance toward policy
In my past experience with auditors, I find I have far fewer meetings to attend if I canprovide everything in a well-documented format with comments that make more sense to
auditing and business personnel than to UNIX administrators like myself It seems that without
exception, the auditors are more concerned about processes and following procedure than with
the actual security of the complete environment A configuration file with policy numbers next
to the line in the configuration file that shows compliance is oftentimes a good idea For example,
if your organization has a control that says “SSH Control 1) Only SSH Protocol 2 is allowed,” then
you might have a line in your ssh_config file that says Protocol 2 #Compliance to SSH Control 1
Note that the headings I use in the configuration file shown in Listing 5-9 are there to improve
readability for auditors and technical administrators; they are not provided in the stock
con-figuration files Arguments can be made that some keywords belong under headings other than
the ones I have chosen While they hail from my system-wide configuration file, copying them
directly to $HOME/.ssh/config will work, if permissions/ownership are correct
Trang 6Listing 5-9. A Fully Documented System-wide ssh_config File
# ssh_config system-wide configuration for OpenSSH clients
# This is the ssh client system-wide configuration file This
# file provides defaults for users that are compliant with SSH
# policy and ensure best practices are followed While this file
# is compliant, please keep in mind that users can change settings
# with user-specific overrides from the command line or their own
# config file in some cases
# Configuration data is parsed as follows:
# 1 command-line options
# 2 user-specific file
# 3 system-wide file
# Site-wide defaults for various options
# Relying on defaults can be challenging because the defaults can
# change upon upgrades Specifying settings explicitly is
# recommended if you understand the settings
# Version x.x
# Date:
Host *
#This means the configuration applies to any host In
# some cases options can be given that will allow different
# configurations depending on what host the user would like to
# connect to Under normal circumstances, all machines are treated
# Because this network occasionally has machines offline, we set a
# timeout value so scripts do not hang
CheckHostIP yes
# The DNS has been deemed quite reliable on this network This is
# recommended as another form of host validation
TCPKeepAlive no
# We are using ServerAliveInterval and ServerAliveCountMax
Trang 7# We encourage the use of digital credentials They are more
# difficult to spoof and cause less support calls/password resets
PasswordAuthentication yes
# Some users/applications need passwords Password policy
# (complexity, etc.) is enforced by the machines, not by OpenSSH
# In the intranet, agent forwarding is allowed to ease use of
# patching, and system hopping via ssh In a DMZ or untrusted
# network, we disable agent forwarding to prevent accessing the
# agent and crawling up the tunnel While we have no evidence of
# this being a simple task, or a policy, we have found it best
# practice
ForwardX11 yes
ForwardX11Trusted yes
# We always enable X11 forwarding Invariably our users will
# want to use an X-Windows System from somewhere, and we would
Trang 8# rather it be over an encrypted connection than the standard
# This file contains the public key cache of remote machines for
# the local system
BatchMode no
# This is a setting we change frequently on a per-user basis
# While the system-wide setting is no, users often change it to
# yes from running scheduled tasks (cron) or application
# connections This setting prevents the ssh client from asking
# for passwords or passphrases
StrictHostKeyChecking ask
# Ask is the default for the system and for the interactive users
# In a batch mode (cron), oftentimes this is changed to no
# We educate users about what a host key change is and why
# OpenSSH will not connect to a host with a changed key if they
# have already cached it This is done via emails and motd
# (message of the day on unix)
EscapeChar ~
# This character allows users to background their current
# session to run commands on the host they are connected from
# These ciphers are acceptable in the USA The legal department
# handles what encryption is allowed outside the USA
Trang 9# These only apply to protocol 2, because that is all that is
# allowed
Reading that configuration file is challenging if it is on a production system When I want
to troubleshoot, reading through lines of explanation is costly and not fun I shortened the
configuration file for use inside of a production environment, as you can see in Listing 5-10
The values of the settings have not changed Keeping the two documents in sync between
commented and not commented versions can be difficult I suggest editing the heavily
com-mented one and grepping out the comments Also, using a version control system of some sort
can aid with the task I do add a small header in this file to help the administrators who are
less familiar with OpenSSH
Listing 5-10. Less Verbose ssh_config Client Configuration File
#/etc/ssh/ssh_config
# This is the ssh client system-wide configuration file See
# ssh_config for more information This file provides defaults
# for users, and the values can be changed in per-user
# configuration files or on the command line
# Configuration data is parsed as follows:
# 1 command-line options
# 2 user-specific file
# 3 system-wide file
# Configuration values only changed the first time they are set
# Thus, host-specific definitions should be at the beginning of
# the configuration file, and defaults at the end
Trang 10Normally, system-wide client configurations are left fairly static Once options are agreed uponand set, they are oftentimes left alone for years, unless new releases of OpenSSH provide newfeatures for the client configuration that could potentially add value to your implementation.
In many environments, the preceding client configuration files will allow maximum securitywithout inhibiting usability too much There are, however, scenarios in which enabling a bitmore usability far outweighs the security needs
ForwardAgent
Agent forwarding is discussed in more depth in the next chapter, but for now think of it as
a backstage pass If you have a backstage pass, once you get past the first guard, the guard infront of the makeup area will not ask to see your pass, because if you are back there, you alreadyhave provided authorization somewhere
Agent forwarding allows you to move around to different hosts that forward authenticationagents once you have authenticated the first time Once you provide the passphrase to yourdigital credential, in this case an OpenSSH key, you can move to any system that accepts thatkey, if you add it to the agent
I use this every day in my job I start from the server where my private key is located I thenmove to a system I am working on Oftentimes I will find I need to grab a patch or configura-tion file update I then will scp to our patch repository and retrieve the patch I need, withoutever reauthenticating
This is only useful when public key authentication using the same private key is enabled
on multiple targets Inside the client configuration file, setting the ForwardAgent keyword toyesas in the following example will enable this time-saving authentication mechanism:ForwardAgent yes
StrictHostKeyChecking, BatchMode, and ConnectTimeout
To create an environment that can be run in an unattended manor, the system must be faulttolerant Enabling BatchMode means that a script or job will not just sit forever waiting for
a user-supplied password or passphrase if public key authentication fails Additionally, if a host
is unpingable, it will just move on
Trang 11Strict checking of host keys can also cause issues If your job is waiting for you to specifyyesto accept this key, it is not running If your environment does not get many host key changes,
leaving this at ask will probably be fine If you are constantly getting new systems, new IP
addresses, or new keys, setting this to no will greatly reduce the problems in your scripts It will
auto-cache the public keys of the remote hosts
The more educated end users of ssh often figure out they can get around the pesky promptfor a yes or no by changing this option to no Depending on your organization’s system policy,
that might be acceptable
Keep in mind that tuning a batch client configuration file requires public key tion as well Poor network reliability has also caused me to invoke a batch-like configuration
authentica-file before, where failures were very common and frustrating, perhaps in a wireless setting
Systems sometimes are offline due to incidents or scheduled maintenance It is alsorecommended you set a ConnectTimeout value that makes sense on your network(s) If a net-
work connection is expected to route around the world, a value of 4 seconds could be too short
Adjust this value to meet your needs
BatchMode yes
StrictHostKeyChecking no
ConnectTimeout 4
Host-based Authentication
Many fellow administrators and other information technology architects ask me about whether
or not they should allow host-based authentication inside of OpenSSH I highly discourage it
in nearly every situation It has been my experience that host-based authentication is enabled
because someone wants to take a shortcut At first glance, it might seem that this is the best way
to create a drop-in replacement for rlogin/rsh, and it is probably the easiest, but user-based
authentication has more auditing capabilities and can be controlled at a more granular level
Host-based authentication can be enabled to use host keys as the authentication credentials,
rather than simply an IP address, and does provide an encrypted communication mechanism,
so it is much more secure than traditional trust relationship authentication; however, host-based
authentication still requires that Host A trust the authentication performed on Host B
If the desire is to not be prompted for a password upon login, use user-based public keyauthentication There is no limit for how many keys can be on a host, or even how many a sin-
gle user can have
Host-based authentication, if you wish to use it, requires a few changes be made tossh_configand to sshd_config, along with caching of the host keys for the hosts involved In
Chapter 6, when I cover all types of authentication, I discuss and demonstrate host-based
authentication
Dealing with Users
Educating your user base about the options and security concerns available in the ssh_config
file is a daunting task On my systems that have large numbers of users, I provide users with
a ssh/config from /etc/skel that is populated in their home directory upon creation and
allows them to change it as they see fit Of course, certain settings can be completely overridden
by ssh_config and sshd_config from the remote system, which root solely controls
Trang 12If your organization and users are new to ssh, perhaps providing a web page or tutorialcan help them out I wrote a few and posted them onto our internal support site As usersasked additional questions, I updated and added to them Later, I even provided a zip file withsome Windows client programs and a Word document about the organizational security poli-cies surrounding SSH.
If your users primarily are dealing with Microsoft Windows workstations to connect toOpenSSH on various types of UNIX or Linux systems, you will want to take a look at Appendix A,which covers graphical Windows clients Many options that can be set inside of an ssh_config fileare configurable inside of a graphical client as well
Dealing with Administrators
Having all of the UNIX administrators on the same page for SSH can be difficult Some trators prefer telnet and ftp, while others have hundreds of scripts and refuse to convert them.Other challenges specifically with the client often lie in education about order of precedence
adminis-In one of the largest SSH implementations I was a part of, I commonly found the system-wideconfiguration client would be changed to enable batch usage This causes issues with realinteractive users The root cause of these unexpected changes was because the administratordid not understand the order of precedence for client settings, and because he had root-levelaccess, he just edited the system configuration rather than his individual file Once he and therest of the team learned about the ssh directory and what type of settings and environmentscan be set up inside of it, the problem plaguing this particular system for weeks occurred nomore
Summary
In this chapter, I covered the ssh client on as many levels as possible From the command-lineoptions to the primary and user configuration files, you have been introduced to all command-line options I demonstrated a few tricks involving common usage as well The knowledge youhave gained in this chapter and about the sshd server will provide an excellent foundation forlearning about public key authentication and uncovering some very serious power for automatingadministrative tasks
Trang 13C H A P T E R 6
■ ■ ■
Authentication
The discussion of OpenSSH thus far has covered its Telnet-like capabilities in conjunction
with introducing the ability to securely transfer files utilizing this technology For many end
users, their introduction to SSH is complete For power users and administrators, the
discus-sion thus far of OpenSSH has left out a drop-in replacement for rsh Traditional rsh allows
users to connect to a remote host based on IP address SSH supports per-user public key
authentication, allowing maximum flexibility without compromising security, which provides
a drop-in, secure replacement for rsh
This chapter begins with an introduction to public key authentication, discussing both how
it works and showing you how to configure it From there, I cover host-based authentication
and discuss OpenSSH’s authentication methods The chapter concludes with a quick how-to
section to serve as a reference
■ Note The discussion of authentication in this chapter will focus on SSH protocol version 2 Similar optionsare available using the now deprecated protocol 1, but the use of protocol 2 is encouraged
Public Key Authentication
Keys are a fixed bit length of data stored in a file that controls the encryption or decryption of
data and are used to authenticate a user or system Authentication is the ability to prove the
user is who he or she claims to be SSH understands keys and accepts these digital credentials
to allow remote access
When public key authentication is configured, a user can use ssh to access a system fromanother with authentication taking place behind the scenes To an end user or administrator,
it appears very similar to rsh or rlogin From a security perspective, keys are extremely difficult
to forge and offer much higher security than traditional password- or IP address–based tication This type of behavior enables several administrative benefits, including the ability to
authen-script commands on multiple hosts, and eases the burden of password management
Trang 141 In some cryptographic algorithms, such as those used with OpenSSH, the private key is all that isneeded for encryption and decryption because the public key can be regenerated from the private key.
What Is Public Key Authentication?
Public key cryptography, sometimes referred to as an asymmetric encryption algorithm, is
comprised of two pieces, a public key and private key When keys are created, the public andprivate keys are generated at the same time In the case of SSH, the private key needs to bekept private with strict permissions (600) The public key can be distributed to any system orperson who would like it If your private key is ever compromised, you must regenerate a newkey pair, revoke your old public key, and redistribute your public key If your public key hasbecome corrupt or misplaced, you can regenerate it, assuming your private key is still intact.Asymmetric algorithms require both keys to perform any type of decryption.1For exam-ple, if I encode a message with Sally’s public key, I know that only Sally (or anyone with herprivate key) can decode the message Conversely, if she has a message for me, she can encrypt
it using my public key, and then only I am able to decrypt it using my private key
Public key operations take a considerable amount of time to perform when comparedwith symmetric or block ciphers such as 3DES and AES With SSH, the public key authentica-tion takes place to establish the session and provide the end point with the secret key for theblock cipher The session then is connected via block ciphers and allows the encryption tooccur at a much faster rate This initial session setup ensures confidentiality by making surethe transmission of the secret block cipher key is encrypted
How Secure Is Public Key Authentication?
As you may recall from Chapter 2, after installing OpenSSH for the first time, when the nection attempt was made to the server, the ssh client told you the public key for this host was
con-not known After verifying the public key and accepting it by typing yes, the ssh client cached
the public key of the remote host This provided protection against man-in-the-middle attacks,because if a new server was put online that did not offer the same host keys, the ssh client wouldrequire user intervention to connect and accept the key change Using user-based public keystakes this security to a new level, because the host is authenticated (via the host keys), and theuser is authenticated via his or her private/public key This provides a layer of security overpasswords because password authentication is normally allowed from any host, while privatekeys are often stored only on well-secured hosts, and therefore are not normally allowed fromany source node on a network
A user of SSH can generate a key pair consisting of one private and one public key Theprivate key is meant to be kept private, which includes providing strict permissions so otherusers of the system cannot access the file, nor store it on an FTP server, nor exchange privatekeys with coworkers The private key is just that, private Compromising the private key allows
an attacker or adversary to assume your identity and act as you The public key, on the otherhand, can be shared with anyone The public key, if lost or tampered with, can be regenerated
as long as the private key still exists The public key file is what is placed on your remote systems
to allow user authentication via keys The private key provided by the client is then paired withthe public key on the remote host If they cryptographically match, the user is authenticated andthus granted access to the remote system If they do not match, depending on your configuration,
Trang 15SSH may try other authentication methods such as password authentication, or it may just
report a failed connection attempt
Public key authentication has a distinct advantage over password authentication in thatpasswords are not randomly generated because they normally have some semblance to words
Additionally, passwords allow authentication for users from any source node
Key-based authentication restricts the source nodes to the hosts with the private key stored
or available to them To compromise key-based authentication, either the private key must be
compromised or cracked Cracking a private key entails using ciphertext (encrypted
commu-nication packet captures) and applying mathematical algorithms to it until it unlocks This is
extremely time consuming and computationally intensive Provided a key length of 1024 bits
or greater is used, cracking private keys is not practical using today’s computing technology
Public Key Authentication vs Password Authentication
Public keys offer some distinct advantages over password-based authentication, such as the
ability to automate tasks easily through scripting of SSH commands, and assignment of multiple
public keys to a single user is allowed This can be advantageous in situations with accounts
that are used by several people (application and root accounts) Assigning each individual
a key means each login to the shared account is traceable to a user Public keys, however, can
be more difficult to manage and support from an end-user perspective
Password authentication must be performed each time a login is desired to a remote host
Additionally, changing passwords is sometimes difficult in environments with large numbers
of nodes Passphrases only have to be changed on private keys, which is normally a much smaller
number than for the total environment
Oftentimes, even when using public key authentication, the need for passwords does notdecrease significantly, as other services still require password for authentication, such as sudo,
ftp, and many commercial applications Getting rid of passwords completely is not always an
option, but if you use keys whenever possible, the speed at which you perform your job can
greatly increase
Table 6-1 shows a comparison between passwords and public key authentication
Table 6-1. Passwords vs Public Key Authentication
Passwords Public Key Authentication
Passwords are normally not random, and Keys are designed and generated using algorithms
are oftentimes easily guessed strings involving random numbers
Single accounts generally do not have Multiple keys per account are inherent to SSH
Passwords are subject to brute-force Keys are also subject to brute-force attacks, but the
attacks that normally complete in effort and computing power is normally orders of
a quick manner magnitude greater than the effort required to break
passwords