Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Securing SSH daemon

News SSH Recommended Books Recommended Links User Access Control Lists  Passwordless login  SSH autologin
Configuration Details SSH Usage in Pipes  TCP Wrappers  Xinetd X11 forwarding over SSH Tunneling/port forwarding SSH Bouncing
SOCKS4 proxy Public-Key Cryptography   Tips History Humor Etc

There are several ways to improve ssh security

  1. Pay special attention to patching sshd daemon, especially if ssh is used to access server from the Internet. In the past bugs in ssh were source of several mass compromises. Now ssh is more secure and bug free but still parching this complex daemon is important.
  2. Increase the minimal length of password to at least eight characters. 
  3. Implement more restrictive configuration of sshd daemon
  4. To avoid "passwordless login jungle" replace SSH public certificate  on a regular basis from centralized location, similarly like you change root passwords.  If you allow passwordless login generally it should be from a special server/workstation only and this workstation should have firewall enabled and configured in restrictive mode (everything that is not allowed is prohibited). The access to both authorized.keys and client-based private key also must be restricted. They should have permissions 600 on Unix.

Note: Automatic installation of iptables rules is a dangerous idea -- it's better to add such host to tcp wrapper deny list and strictly for ssh

Server Recommendations

Server configuration specifies how the daemon presents itself on the network, what protocols are offered, and what authentication methods are allowed. Specific recommendations are given for each topic. Recommendations specific to a particular Secure Shell implementation have also been noted.

Protocol Support

Two major versions of the Secure Shell protocol exist. Protocol 1 has been deprecated because of vulnerabilities, such as packet insertion and password-length determination. Whenever possible, use Protocol 2. Unfortunately, many legacy clients support only Protocol 1. If this protocol must be enabled, consult the Legacy Support recommendations later in this chapter. Consider migrating to clients that support Protocol 2 as soon as reasonably possible.

Network Access

By default, the sshd(1M) daemon listens on all network interfaces on its bound ports. For workstations or other systems on which accessibility is desired for all interfaces, this behavior is not a problem. For architectures such as the Service Delivery Network, in which management traffic is limited to a particular interface, this behavior is a problem. Limit network access with the ListenAddress keyword. Access is limited by a particular IP address, not by a network interface.

 # Listen only to the management network.
 ListenAddress 192.168.0.10

To further narrow down what the daemon will listen to, use either a host-based firewall, such as the SunScreen™ software, or TCP Wrappers.

For information about traffic-limited architectures, consult the Sun BluePrints OnLine article "Building Secure N-Tier Environments" (October 2000).

Keep-Alives

Occasionally, connections are temporarily suspended when a route is downed, a machine crashes, a connection is hijacked, or a man-in-the-middle attack is attempted. TCP keep-alives should be sent to detect any of these cases. If TCP keep-alives fail, the server will disconnect the connection and return allocated resources. Regular disconnects can aggravate users on faulty networks.

 KeepAlive yes
Data Compression

Optionally, compression can be used on the encrypted data streams. This use results in bandwidth savings for compressible data, such as interactive logins or log files, at the expense of more CPU resources. For uncompressible data such as encrypted or compressed files, the extra CPU time is wasted and decreases performance. For a single Secure Shell session, these losses are inconsequential. For a file server, the extra load could impact performance. In this case, turn compression off to prevent misconfigured clients from driving up the system load.

# Transferring ASCII data such as interactive logins or log files
 Compression yes 
# Transferring random data such as compressed or
 encrypted files
# Prevents performance issues and reduces CPU load
 Compression no
Privilege Separation

Privilege separation is an OpenSSH-only feature. The sshd(1M) daemon is split into two parts: a privileged process to deal with authentication and process creation and an unprivileged process to deal with incoming network connections. After successful authentication, the privileged process spawns a new process with the privileges of the authenticated user. The goal is to prevent compromise from an error in the network facing process. Unfortunately, privilege separation is not really compatible with pluggable authentication modules or SunSHIELD Basic Security Module (BSM) auditing. Some OpenSSH features are also disabled. If privilege separation is desired, consult the vendor documentation.

Note

The compilation options presented in Chapter 2 disable privilege separation.

 # OpenSSH only
 UsePrivilegeSeparation no
Login Grace Time

The default login grace time is the time a connection is allowed to exist before being successfully authenticated. The default of 600 seconds for the Solaris Secure Shell software and 120 seconds for later OpenSSH versions is too long. Reduce the time to 60 seconds.

 LoginGraceTime 60
Password and Public Key Authentication

Passwords are not always appropriate. A stronger means may be required, such as public-key cryptographic two-factor authentication. Secure Shell refers to the key pair as an identity. See "Managing Keys and Identities" on page 71 for more details. When passwords are deemed sufficient, do not allow empty passwords. They are too easy to guess.

 PasswordAuthentication yes
 PermitEmptyPasswords no
 PubKeyAuthentication yes
 DSAAuthentication yes
Superuser (root) Logins

Neither the Solaris Secure Shell software nor OpenSSH honors the values set in the /etc/default/login file. To prevent network superuser (root) logins, they must be explicitly denied. The Solaris Secure Shell software and OpenSSH default to yes. However, the default sshd_config(4) file in the Solaris Secure Shell software disables this feature. This forces a system administrator to log in as an unprivileged user, then change users (su) to the superuser. Enable superuser logins only if the system has no user accounts and the appropriate host protection is in place.

 PermitRootLogin no
Banners, Mail, and Message-of-the-Day

Some sites require that a banner be displayed after a user connects to a system, but before logging in. You can accomplished this with the Banner keyword. Set Banner to /etc/issue so that only one banner file exists for the entire system.

 Banner /etc/issue

In the Solaris OE, the interactive login shell is expected to display the message-of-the-day (MOTD) and to check for new mail. With some versions of OpenSSH, this feature causes the MOTD display and mail check to be done twice. Set these keywords to no to eliminate the duplication.

 CheckMail no
 PrintMotd no
Connection and X11 Forwarding

Secure Shell can tunnel TCP and X protocol connections through encrypted connections established between the client and server. Tunneling the traffic is referred to as forwarding. The forwarding occurs at the application level and is not completely transparent to the applications being forwarded. The applications need some configuration to use the tunnel.

Note

Data is protected only while it is in the tunnel between the client and server. After that, it is normal network traffic in the clear.

Tunneled traffic bypasses firewalls and intrusion detection systems. Allowing connection (TCP port) forwarding allows remote users safer access to email or the corporate web server. X forwarding allows system administrators to run GUI applications remotely, such as the Solaris™ Management Console software. This may not be functionality you want your users setting up. You can inconvenience users by turning off the functionality, but as long as they have shell access, they can run their own forwarders. Use role-based access control to explicitly limit what you want your users to do in this case.

If port forwarding is enabled, disable GatewayPorts and notify your users. GatewayPorts allows machines, other than the client, to access the forwarded ports in the tunnel. This access effectively bypasses any firewall usage. Again, users could run their own private forwarders on their client machines to defeat the server restrictions. Consider placing an intrusion detection sensor on the private network side of a Secure Shell bastion host to detect problem traffic.

 AllowTCPForwarding yes
 GatewayPorts no
 X11DisplayOffset 10
 X11Forwarding yes
 XAuthLocation /usr/X/bin/xauth

User Access Control Lists

User access control lists (ACLs) can be specified in the server configuration file. No other part of the Solaris OE honors this ACL. You can either specifically allow or deny individual users or groups. The default is to allow access to anyone with a valid account. You can use ACLs to limit access to particular users in NIS environments, without resorting to custom pluggable authentication modules. Use only one of the following four ACL keywords in the server configuration file: AllowGroups, AllowUsers, DenyGroups or DenyUsers.

 # Allow only the sysadmin staff
 AllowGroups staff
 # Prevent unauthorized users.
 DenyUsers jerk
User File Permissions

If a user has left their home directory or .ssh files world writable either by accident or by trickery, an intruder could insert identities allowing password-free access or alter the known_hosts file to allow man-in-the-middle attacks. With StrictModes enabled, the sshd(1M) daemon will not allow a login. But, users can be easily confused because they will not know why they cannot log in. No different error message is presented to them.

 StrictModes yes
UseLogin Keyword

For OpenSSH only, UseLogin specifies that the OpenSSH sshd(1M) call login(1) instead of performing the initial login tasks itself for interactive sessions.   forwarding.

 UseLogin no
Legacy Support

If legacy clients must be supported, strengthen the default configuration as much as possible. Default to Protocol 2 for the clients that support it. Disable all of the rhosts-style authentication methods. Increase the server key size and decrease the ephemeral key regeneration interval to minimize offline factoring attacks against the keys.

 # Enable protocol 1 but default to protocol 2.
 Protocol 2,1
 # Legacy support options - protocol 1 only
 HostKey /etc/ssh/ssh_host_key
 IgnoreRhosts yes
 IgnoreUserKnownHosts yes
 KeyRegenerationInterval 1800
 RhostsAuthentication no
 RhostsRSAAuthentication no
 RSAAuthentication yes
 ServerKeyBits 1024

Top updates

Bulletin Latest Past week Past month
Google Search


NEWS CONTENTS

Old News ;-)

[Nov 27, 2011] Improving security of ssh via tuning of configuration file

ssh security can be improved by modifying /etc/ssh/sshd_config  configuration file.

Securing SSH

Many network services like telnet, rlogin, and rsh are vulnerable to eavesdropping which is one of several reasons why SSH should be used instead. Red Hat's default configuration for SSH meets the security requirements for many environments. However, there are a few parameters in /etc/ssh/sshd_config that you may want to change on RHEL and other Linux systems.

The chapter Restricting System Access from Servers and Networks shows how direct logins can be disabled for shared and system accounts including root. But it's prudent to disable direct root logins at the SSH level as well.

PermitRootLogin no
Also ensure to have privilege separation enabled where the daemon is split into two parts. With privilege separation a small part of the code runs as root and the rest of the code runs in a chroot jail environment. Note that on older RHEL systems this feature can break some functionality, for example see Preventing Accidental Denial of Service.
UsePrivilegeSeparation yes
Since SSH protocol version 1 is not as secure you may want to limit the protocol to version 2 only:
Protocol 2
You may also want to prevent SSH from setting up TCP port and X11 forwarding if you don't need it:
AllowTcpForwarding no
X11Forwarding no
Ensure the StrictModes directive is enabled which checks file permissions and ownerships of some important files in the user's home directory like ~/.ssh, ~/.ssh/authorized_keys etc. If any checks fail, the user won't be able to login.
StrictModes yes
Ensure that all host-based authentications are disabled. These methods should be avoided as primary authentication.
IgnoreRhosts yes
HostbasedAuthentication no
RhostsRSAAuthentication no
Disable sftp if it's not needed:
#Subsystem      sftp    /usr/lib/misc/sftp-server
After changing any directives make sure to restart the sshd daemon:
/etc/init.d/sshd restart

 

[Jun 10, 2011] Password-less logins with OpenSSH

Posted by simms (69.157.xx.xx) on Sat 4 Jun 2005 at 12:51
[ Send Message ]

password-less DSA (isn't RSA less safe?) key logins can indeed be uber-convenient, but i have to agree with a lot of folks here that having these 'free entry' tokens out there (the id_dsa.pub part) makes me nervous.

having said that, if you have to use this method there are ways of making it less vulnerable. one thing every noob should know is that you can restrict which user accounts on the server are allowed to be accessed in a 'password-less' way via its /etc/ssh/sshd_config file.
the line

AuthorizedKeysFile %h/.ssh/SOME_ORIGINAL_NAME
can be made to point to a filename which is non-default (as above), and which you will only use in the home directories of users with severely restricted privileges.

while we're at it, sshd_config also contains the line PermitRootLogin that should likely be set to No unless you have a damn good reason.

finally, you can restrict which accounts can be accessed via SSH at all by explicitly listing them with
AllowUsers username

 

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?

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.

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
 

[Jun 10, 2011] TCP Wrapper for added Security on SSH

TCP Wrappers has been around for many years. It is used to restrict access to TCP services based on host name, IP address, network address, and so on. For more details on what TCP Wrappers is and how you can use it, see man tcpd.

The original code was written by Wietse Venema at the Eindhoven University of Technology, The Netherlands, between 1990 and 1995.

TCP Wrappers support in Secure Shell is given by using the library libwrap, which is a free software program library that implements generic TCP Wrapper functionality for network service daemons to use (rather than, or in addition to, their own host access control schemes).

To see if sshd is dynamically linked against libwrap, or has support build-in, use the following command:

ldd /usr/sbin/sshd | grep libwrap
libwrap.so.0 => /usr/lib/libwrap.so.0 (0x00b22000)

Logging of SSH Logins

Normally, the Port for SSH is open to the Internet World, can pass Firewalls and is therefore a door for Hackers. TCP Wrappers relies on the standard syslog facility to log connections, which can be checked in /etc/syslog.conf

# The authpriv file has restricted access.
authpriv.* /var/log/auth.log

If you look into this file with tail -f you will be noticed, that there are many (hopefully failed) SSH Connections. So, how to avoid this unnecessary traffic to your system?

[Aug 23, 2008]  OpenSSH blacklist script

That's sad -- RHN was compromised due and some troyanized OpenSSH packages were uploaded.
redhat.com
August 22, 2008

Last week Red Hat detected an intrusion on certain of its computer systems and took immediate action. While the investigation into the intrusion is on-going, our initial focus was to review and test the distribution channel we use with our customers, Red Hat Network (RHN) and its associated security measures. Based on these efforts, we remain highly confident that our systems and processes prevented the intrusion from compromising RHN or the content distributed via RHN and accordingly believe that customers who keep their systems updated using Red Hat Network are not at risk. We are issuing this alert primarily for those who may obtain Red Hat binary packages via channels other than those of official Red Hat subscribers.

In connection with the incident, the intruder was able to get a small number of OpenSSH packages relating only to Red Hat Enterprise Linux 4 (i386 and x86_64 architectures only) and Red Hat Enterprise Linux 5 (x86_64 architecture only) signed. As a precautionary measure, we are releasing an updated version of these packages and have published a list of the tampered packages and how to detect them.

To reiterate, our processes and efforts to date indicate that packages obtained by Red Hat Enterprise Linux subscribers via Red Hat Network are not at risk.

We have provided a shell script which lists the affected packages and can verify that none of them are installed on a system:

The script has a detached GPG signature from the Red Hat Security Response Team (key) so you can verify its integrity:

This script can be executed either as a non-root user or as root. To execute the script after downloading it and saving it to your system, run the command:

bash ./openssh-blacklist-1.0.sh

If the script output includes any lines beginning with "ALERT" then a tampered package has been installed on the system. Otherwise, if no tampered packages were found, the script should produce only a single line of output beginning with the word "PASS", as shown below:

   bash ./openssh-blacklist-1.0.sh
   PASS: no suspect packages were found on this system

The script can also check a set of packages by passing it a list of source or binary RPM filenames. In this mode, a "PASS" or "ALERT" line will be printed for each filename passed; for example:

bash ./openssh-blacklist-1.0.sh openssh-4.3p2-16.el5.i386.rpm
   PASS: signature of package "openssh-4.3p2-16.el5.i386.rpm" not on blacklist

Red Hat customers who discover any tampered packages, need help with running this script, or have any questions should log into the Red Hat support website and file a support ticket, call their local support center, or contact their Technical Account Manager.

[May 16, 2008] Linux gets security black eye

May 16, 2008
As has been widely reported, the maintainers of Debian's OpenSSL packages made some errors recently that have potentially compromised the security of any sshd-equipped system used remotely by Debian users. System administrators may wish to purge authorized_key files of public keys generated since 2006 by affected client machines.

Simply using a Debian-based machine to access a remote server via SSH would not be enough to put the machine at risk. However, if the user copied a public key generated on a Debian-based system to the remote server, for example to take advantage of the higher security offered by password-free logins, then the weak key could make the server susceptible to brute-force attacks, especially if the user's name is easily guessable.

Administrators of servers that run SSH may wish to go through users' authorized key files (typically ~/.ssh/authorized_keys), deleting any that may have been affected. A "detector" script, available here, appears to compare public key signatures against a list of just 262,800 entries. That in turn suggests that if the user's name is known, a brute force attack progressing at one guess per second could succeed within 73 hours (262,800 seconds).

A full explanation of the problem can be found here. In a nutshell, Debian's OpenSSL maintainers made some Debian-specific patches that, according to subscriber-only content at LWN.net, were aimed at fixing a memory mapping error that surfaced during testing with the valgrind utility. The unintended consequence was a crippling of the randomness of keys, making them predictable, and thus possible to guess using "brute-force" attacks. And unfortunately, the Debian maintainers failed to submit their patches upstream, and thus the problem did not surface until very recently (there's certainly a lesson to be learned, there). Not surprisingly, brute force attacks are way up this week, LWN.net also reported.

Users of Debian and Debian-based distributions such as Ubuntu should immediately upgrade the SSH software on their systems. The new ssh-client package will contain an "ssh-vulnkey" utility that, when run, checks the user's keys for the problem. Users should re-generate any affected keys as soon as possible.

Also possibly affected are "OpenVPN keys, DNSSEC keys, and key material for use in X.509 certificates and session keys used in SSL/TLS connections," though not apparently Keys generated with GnuPG or GNUTLS. More details can be found here (Debian resource page), as well as on this webpage, which also links to lists of common keys and brute-force scripts that boast of 20-minute typical break-in times.

-- Henry Kingman

[Dec 15, 2007] SSH Best Practices

HowtoForge

... ... ...

SSHv2 vs. SSHv1

There are numerous benefits to using the latest version of the SSH protocol, version 2, over it's older counterpart, version 1 and I'm not going into a lot of details on those benefits here - if you're interested, see the URL in the reference below or Google around. That being said if you don't have an explicit reason to use the older version 1, you should always be using version 2.

...To force everybody to use SSHv2, change it to:

Protocol 2

When you make this change don't forget to generate the appropriate HostKey's as well! SSHv2 requires the following keys:

# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key

... Once your changes are made, restart the SSH daemon:

# /etc/init.d/sshd restart

[ SUCCESSFUL ] Secure Shell Daemon
[ SUCCESSFUL ] Secure Shell Daemon

From another machine, try SSH'ing in. You can use the -v option to see which protocol is being used, and the '-oProtocol=' option to force one or the other - for example, "ssh -v -oProtocol=2 " would force protocol version 2.

... ... ...

Using TCP Wrappers

TCP Wrappers are used to limit access to TCP services on your machine. If you haven't heard of TCP Wrappers you've probably heard of /etc/hosts.allow and /etc/hosts.deny: these are the two configuration files for TCP Wrappers. In the context of SSH, TCP Wrappers allow you to decide what specific addresses or networks have access to the SSH service.

To use TCP Wrappers with SSH you need to make sure that OpenSSH was built with the -with-tcp-wrappers. This is the case on any modern distribution.

As I indicated earlier, TCP Wrappers are configured by editing the /etc/hosts.deny and /etc/hosts.allow files. Typically you tell hosts.deny to deny everything, then add entries to hosts.allow to permit specific hosts access to specific services.

An example:

# hosts.deny    This file describes the names of the hosts which are
#               *not* allowed to use the local INET services, as decided
#               by the '/usr/sbin/tcpd' server.
#
ALL: ALL
 
# hosts.allow   This file describes the names of the hosts which are
#               allowed to use the local INET services, as decided
#               by the '/usr/sbin/tcpd' server.
#
sshd: 207.46.236. 198.133.219.25

In the example above, access to SSH is limited to the network 207.46.236.0/24 and the address 198.133.219.25. Requests to any other service from any other address are denied by the "ALL: ALL" in hosts.deny. If you try to SSH into a machine and TCP Wrappers denies your access, you'll see something like this:

ssh_exchange_identification: Connection closed by remote host

This simple configuration change significantly hardens your installation since, with it in place, packets from hostile clients are dropped very early in the TCP session -- and before they can do any real damage to a potentially vulnerable daemon.

Public Key Authentication

...Public key authentication is no silver bullet - similarly, people generate passphrase-less keys or leave ssh-agents running when they shouldn't - but, in my opinion, it's a much better bet.

Just about every distribution ships with public key authentication enabled, but begin by making sure it is:

RSAAuthentication yes
PubkeyAuthentication yes

Both of these options default to "yes" and the "RSAAuthentication" option is for SSHv1 and the "PubkeyAuthentication" option is for SSHv2. If you plan on using this authentication method exclusively, while you're there, you may want to disable password authentication:

PasswordAuthentication no

Before you proceed, make sure you have a terminal open on your target machine. Once you restart the SSH daemon you will no longer be able to log in without a key... which we haven't generated yet!

Once you're sure, restart the SSH daemon:

# /etc/init.d/sshd restart

[ SUCCESSFUL ] Secure Shell Daemon
[ SUCCESSFUL ] Secure Shell Daemon

Now, from your desktop, try to SSH in to your target machine:

$ ssh rwm@brainy

Permission denied (publickey,keyboard-interactive).

We're locked out! This is a good thing. The next step, on your desktop, is to generate a key:

$ ssh-keygen -t dsa -C "Ryan's SSHv2 DSA Key (Jan 2008)"

Generating public/private dsa key pair.
Enter file in which to save the key (/home/rwm/.ssh/id_dsa):
Enter passphrase (empty for no passphrase): **********
Enter same passphrase again: **********
Your identification has been saved in /home/rwm/.ssh/id_dsa.
Your public key has been saved in /home/rwm/.ssh/id_dsa.pub.
The key fingerprint is:
98:4d:50:ba:ee:8b:79:be:b3:36:75:8a:c2:4a:44:4b Ryan's SSHv2 DSA Key (Jan 2008)

A few notes on this:

The command you just ran generated two files - id_dsa, your private key and id_dsa.pub, your public key. It is critical that you keep your private key private, but you can distribute your public key to any machines you would like to access.

Now that you have generated your keys we need to get the public key into the ~/.ssh/authorized_keys file on the target machine. The best way to do this is to copy-and-paste it - begin by concatenating the public key file:

$ cat .ssh/id_dsa.pub

ssh-dss AAAAB3NzaC1kc3MAAACBAL7p6bsg5kK4ES9BWLPCNABl20iQQB3R0ymaPMHK...
... ds= Ryan's SSHv2 DSA Key (Jan 2008)

This is a very long string. Make sure you copy all of it and that you do NOT copy the newline character at the end. In other words, copy from the "ssh" to the "2008)", but not past that.

The next step is to append this key to the end of the ~/.ssh/authorized_keys file on your target machine. Remember that terminal I told you to keep open a few steps ago? Type the following command into it, pasting the key you've just copied into the area noted KEY:

echo "KEY" >> ~/.ssh/authorized_keys

For example:

echo "ssh-dss AAAA5kS9BWLPCN...s= Ryan's SSHv2 DSA Key (Jan 2008)" >> ~/.ssh/authorized_keys

Now, try to SSH in again. If you did this procedure correctly then instead of being denied access, you'll be prompted for your passphrase:

$ ssh rwm@brainy

Enter passphrase for key '/home/rwm/.ssh/id_dsa':
Last login: Thu Jan 10 14:37:14 2008 from papa.engardelinux.org
[rwm@brainy ~]$

Viola! You're now logged in using public key authentication instead of password authentication.

[Jun 4, 2007] How To tcp wrapper - Myriad Network Customer Forum

A quick tutorial on how to configure tcp wrapper for SSH on your VDS or dedicated server. More detailed information can be obtained by looking at the man pages - 'man hosts.allow' - 'man hosts.deny'.

In a nutshell tcp wrapper can be used to control access to your server via SSH (and other daemons). It can be used in combination with a local firewall (iptables, ipchains, ipfw) or standalone.

From the man page.

The access control software consults two files. The search stops at the first match:

A very simplistic tcp wrapper implementation:

# Control access to SSH

vi /etc/hosts.allow

# Allow me access from home on IP 192.168.1.1
SSHD: 192.168.1.1

# Allow me access from work on IP 10.0.1.0/24
SSHD: 10.0.1.

vi /etc/hosts.deny

# Deny all other SSH attempts

SSHD: ALL

In the above example you will be able to connect via SSH from the IP address 192.168.1.1 and the netblock 10.0.1.0/24 (which includes IP address 10.0.1.1 through 10.0.1.254).


To verify tcp wrapper is working by attempting to connect from an IP address not in /etc/hosts.allow. You should see something similar in your logs (/var/log/secure):

Feb 20 08:05:46 server sshd[8273]: refused connect from 218.236.84.82 (218.236.84.82)

Above, you see the date, time, hostname, process (sshd), process id (8273) and the IP address where the person was attempting to connect from.

tcp wrapper is an excellent way to enchance security on your VDS or dedicated server and is not limited to just SSH.

Tom

[Jun 4, 2007] TCP Wrappers Configuration Files

Red Hat

15.2.3.2. Access Control

Option fields also allow administrators to explicitly allow or deny hosts in a single rule by adding the allow or deny directive as the final option.

For instance, the following two rules allow SSH connections from client-1.example.com, but deny connections from client-2.example.com:

sshd : client-1.example.com : allow
sshd : client-2.example.com : deny

By allowing access control on a per-rule basis, the option field allows administrators to consolidate all access rules into a single file: either hosts.allow or hosts.deny. Some consider this an easier way of organizing access rules.

[Jun 4, 2007]  Configuring SSH Secure Shell for TCP Wrappers Support

ssh.com

Configuring SSH Secure Shell for TCP Wrappers Support

To enable usage of TCP Wrappers with SSH Secure Shell, perform the following operations:

  1. If SSH Secure Shell was previously installed from binaries, you may want to uninstall it before continuing.
  2. Compile the source code:
    ./configure --with-libwrap 
    make
    Then, become root and run
    make install
    Note: If configure  does not find libwrap.a, do the following:
    • Locate libwrap.a
    • Run configure  again:
      make distclean
      ./configure --with-libwrap=/path_to_libwrap.a/
      
      Note: It is only necessary to specify the path to libwrap.a  if the library and the include files are located in a non-standard directory, i.e. if the library has been compiled to a local directory, or has been installed to somewhere else than the default location.
  3. Create or edit the /etc/hosts.allow  and /etc/hosts.deny  files. When a user tries to connect to the SSH Secure Shell server, the TCP wrapper daemon (tcpd) reads the /etc/hosts.allow  file for a rule that matches the client's hostname or IP. If /etc/hosts.allow  does not contain a rule allowing access, tcpd  reads /etc/hosts.deny  for a rule that would deny access. If neither of the files contains an accept or deny rule, access is granted by default. The syntax for the /etc/hosts.allow  and /etc/hosts.deny  files is as follows:
    daemon : client_hostname_or_IP
    The typical setup is to deny access to everyone listed in the /etc/hosts.deny  file. (This example shows both ssh1 and ssh2.)
    sshd1: ALL 
    sshd2: ALL 
    sshdfwd-X11 : ALL 
    
    or simply
    ALL: ALL 
    
    And then allow access only to trusted clients in the /etc/hosts.allow:
    sshd1 : trusted_client_IP_or_hostname
    sshd2 : .ssh.com foo.bar.fi
    sshdfwd-X11 : .ssh.com foo.bar.fi
    
    Based on the /etc/hosts.allow  file above, users coming from any host in the ssh.com domain or from the host foo.bar.fi are allowed to access.

[Dec 8, 2006] Crack watching

Automatic installation of iptable rules is a dangerious idea -- it's better to add such host to tcp wrapper dely list and strictly for ssh

sshdfilter automatically blocks ssh brute force attacks by reading sshd log output in real time and adding iptables rules based on authentication failures. Block rules are created by logging on with an invalid user name, or wrongly guessing the password for an existing account. Block rules are removed after a week to maintain a small list of blocks. It also comes with a LogWatch filter.

SoloPort Corporation - Home A Cure for the Common SSH Login Attack

A few months ago, I began seeing our 'secure' log files fill up with entries stating: "Failed password for illegal user [username]". I decided to search the Internet to find out if others were experiencing these attacks and, hopefully, find a solution. I did uncover a lot of information on the subject, but discovered only a few script-based solutions. None of these, however, seemed... well... elegant.

What I wanted was a way to stop the attacks altogether, yet allow ssh access from anywhere, when needed. In addition, I wanted to avoid using an approach that was so complicated it could lead to more pain than I was experiencing from the original problem.

The solution should behave similar to the following shell prompt activity:

 $ ssh name@hostname # No response (Ctrl-C to abort)
    ^C
    $ telnet hostname 1600 # Telnet into port 1600 to open port 22
    Trying 123.123.123.123...
    ^C
    $ ssh name@hostname # Now logins are allowed
    name@hostname's password:
    .
    .
    .
    $ telnet hostname 1601 # Telnet into port 1601 to close port 22
    Trying 123.123.123.123...
    ^C

Note that the ports used to open and close port 22 should appear closed, as well. This approach would be a sort of simplified "port knocking" technique.

Proposed Solution


The 'recent' module in iptables is designed to detect malicious access attempts and then help block or at least honeypot the potential intruder with delays. I've sort of turned this module on its head and, instead, used it to let people in.

The following represents the contents of an iptables file, drawn from a Red Hat distribution (the usual path is /etc/sysconfig/iptables). The highlighted text outlines the changes needed to support our style of port knocking.

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -s 10.0.0.0/24 -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -m recent --rcheck --name SSH -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m udp -p udp --dport 123 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 1599 -m recent --name SSH --remove -j DROP
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 1600 -m recent --name SSH --set -j DROP
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 1601 -m recent --name SSH --remove -j DROP
-A RH-Firewall-1-INPUT -j DROP
COMMIT

Note that there is a "close" port on either side of the "open" port. This should cause most linear port scans (ascending or descending) to leave port 22 closed, upon completion.

For an even more robust approach, use two separate "open" ports -- such as a knock at port 1300, followed by a knock at port 1600. Also keep in mind, once you have ssh-connected, you can then close the port without losing your established connection.

Conclusion
What's really convenient about this method is, when you're at a trusted location (say, in the office) and you unlock a target site (say, a home server), you need only knock once; The port will stay open for that specific source IP address, indefinitely (until you deliberately close the port or iptables is restarted). If you attempt to use the port from another location (say, a client's office), it will appear closed -- until you knock.

What I find most elegant about this approach is that you don't have to fill up your iptables with dozens of DROP entries in order to block the world of would-be attackers.

Sample Log
Here is a representative sample from a 'secure' log file:

 Jan  7 09:58:47 hostname sshd[24729]: Illegal user test from [IP_ADDRESS_A]
Jan  7 09:58:50 hostname sshd[24729]: Failed password for illegal user test from [IP_ADDRESS_A] port 51250 ssh2
Jan  7 09:58:52 hostname sshd[24731]: Illegal user guest from [IP_ADDRESS_A]
Jan  7 09:58:54 hostname sshd[24731]: Failed password for illegal user guest from [IP_ADDRESS_A] port 51396 ssh2
Jan  7 09:58:56 hostname sshd[24733]: Illegal user admin from [IP_ADDRESS_A]
Jan  7 09:58:58 hostname sshd[24733]: Failed password for illegal user admin from [IP_ADDRESS_A] port 51546 ssh2
Jan  7 09:59:00 hostname sshd[24735]: Illegal user admin from [IP_ADDRESS_A]
Jan  7 09:59:03 hostname sshd[24735]: Failed password for illegal user admin from [IP_ADDRESS_A] port 51688 ssh2
Jan  7 09:59:04 hostname sshd[24737]: Illegal user user from [IP_ADDRESS_A]
Jan  7 09:59:07 hostname sshd[24737]: Failed password for illegal user user from [IP_ADDRESS_A] port 51828 ssh2
Jan  7 09:59:11 hostname sshd[24739]: Failed password for root from [IP_ADDRESS_A] port 51963 ssh2
Jan  7 09:59:15 hostname sshd[24741]: Failed password for root from [IP_ADDRESS_A] port 52114 ssh2
Jan  7 09:59:20 hostname sshd[24743]: Failed password for root from [IP_ADDRESS_A] port 52288 ssh2
Jan  7 09:59:22 hostname sshd[24745]: Illegal user test from [IP_ADDRESS_A]
Jan  7 09:59:24 hostname sshd[24745]: Failed password for illegal user test from [IP_ADDRESS_A] port 52419 ssh2
Jan  7 16:35:22 hostname sshd[25103]: Failed password for nobody from [IP_ADDRESS_C] port 53721 ssh2
Jan  7 16:35:25 hostname sshd[25105]: Illegal user patrick from [IP_ADDRESS_C]
Jan  7 16:35:28 hostname sshd[25105]: Failed password for illegal user patrick from [IP_ADDRESS_C] port 53832 ssh2
Jan  7 16:35:31 hostname sshd[25107]: Illegal user patrick from [IP_ADDRESS_C]
Jan  7 16:35:33 hostname sshd[25107]: Failed password for illegal user patrick from [IP_ADDRESS_C] port 53907 ssh2
Jan  7 16:35:39 hostname sshd[25109]: Failed password for root from [IP_ADDRESS_C] port 54003 ssh2
Jan  7 16:35:45 hostname sshd[25111]: Failed password for root from [IP_ADDRESS_C] port 54093 ssh2
Jan  7 16:35:50 hostname sshd[25113]: Failed password for root from [IP_ADDRESS_C] port 54181 ssh2
Jan  7 16:35:58 hostname sshd[25115]: Failed password for root from [IP_ADDRESS_C] port 54312 ssh2
Jan  7 16:36:04 hostname sshd[25117]: Failed password for root from [IP_ADDRESS_C] port 54395 ssh2
Jan  7 16:36:07 hostname sshd[25119]: Illegal user rolo from [IP_ADDRESS_C]
Jan  7 16:36:10 hostname sshd[25119]: Failed password for illegal user rolo from [IP_ADDRESS_C] port 54488 ssh2
Jan  7 16:36:14 hostname sshd[25121]: Illegal user iceuser from [IP_ADDRESS_C]
Jan  7 16:36:16 hostname sshd[25121]: Failed password for illegal user iceuser from [IP_ADDRESS_C] port 54577 ssh2
Jan  7 16:36:21 hostname sshd[25123]: Illegal user horde from [IP_ADDRESS_C]
Jan  7 16:36:23 hostname sshd[25123]: Failed password for illegal user horde from [IP_ADDRESS_C] port 54681 ssh2
Jan  7 16:36:26 hostname sshd[25125]: Illegal user cyrus from [IP_ADDRESS_C]
Jan  7 16:36:28 hostname sshd[25125]: Failed password for illegal user cyrus from [IP_ADDRESS_C] port 54786 ssh2
Jan  7 16:36:32 hostname sshd[25127]: Illegal user www from [IP_ADDRESS_C]
Jan  7 16:36:34 hostname sshd[25127]: Failed password for illegal user www from [IP_ADDRESS_C] port 54878 ssh2
Jan  7 16:36:37 hostname sshd[25129]: Illegal user wwwrun from [IP_ADDRESS_C]
Jan  7 16:36:40 hostname sshd[25129]: Failed password for illegal user wwwrun from [IP_ADDRESS_C] port 54966 ssh2
Jan  7 16:36:43 hostname sshd[25131]: Illegal user matt from [IP_ADDRESS_C]
Jan  7 16:36:46 hostname sshd[25131]: Failed password for illegal user matt from [IP_ADDRESS_C] port 55050 ssh2
Jan  7 16:36:50 hostname sshd[25133]: Illegal user test from [IP_ADDRESS_C]
Jan  7 16:36:53 hostname sshd[25133]: Failed password for illegal user test from [IP_ADDRESS_C] port 55152 ssh2
Jan  7 16:36:57 hostname sshd[25135]: Illegal user test from [IP_ADDRESS_C]
Jan  7 16:36:59 hostname sshd[25135]: Failed password for illegal user test from [IP_ADDRESS_C] port 55263 ssh2
Jan  7 16:37:02 hostname sshd[25137]: Illegal user test from [IP_ADDRESS_C]
Jan  7 16:37:04 hostname sshd[25137]: Failed password for illegal user test from [IP_ADDRESS_C] port 55366 ssh2
Jan  7 16:37:08 hostname sshd[25139]: Illegal user test from [IP_ADDRESS_C]
Jan  7 16:37:10 hostname sshd[25139]: Failed password for illegal user test from [IP_ADDRESS_C] port 55457 ssh2
Jan  7 16:37:13 hostname sshd[25141]: Illegal user www-data from [IP_ADDRESS_C]
Jan  7 16:37:16 hostname sshd[25141]: Failed password for illegal user www-data from [IP_ADDRESS_C] port 55548 ssh2
Jan  7 16:37:21 hostname sshd[25143]: Failed password for mysql from [IP_ADDRESS_C] port 55637 ssh2
Jan  7 16:37:26 hostname sshd[25145]: Failed password for operator from [IP_ADDRESS_C] port 55724 ssh2
Jan  7 16:37:33 hostname sshd[25147]: Failed password for adm from [IP_ADDRESS_C] port 55799 ssh2
Jan  7 16:37:42 hostname sshd[25149]: Failed password for apache from [IP_ADDRESS_C] port 55912 ssh2
Jan  7 16:37:52 hostname sshd[25151]: Illegal user irc from [IP_ADDRESS_C]
Jan  7 16:37:54 hostname sshd[25151]: Failed password for illegal user irc from [IP_ADDRESS_C] port 56036 ssh2

Disclaimer
The security gained from using the above information cannot be guaranteed. If you use the above information for any purpose, you do so at your own risk.

Global and/or presistent ssh-agent

ssh-agents are very useful, however one often would like them to

This is quite easy, one only has to capture the output of the ssh-agent command and make it reusable. Put following lines to your ~/.bash_profile> :

 AGENTFILE=$HOME/.ssh/current-ssh-agent
test -f $AGENTFILE && . $AGENTFILE
if test -n "$SSH_AGENT_PID" \
  && ps -xo pid,comm | grep -q "$SSH_AGENT_PID ssh-agent$"; then
  if ssh-add -l >/dev/null; then
    # Everything seems OK.
    :
  else
    # Agent is running but knows no identities.
    echo SSH-AGENT:  No identities.  Remeber to run ssh-add!
  fi
else
  # No agent is running or AGENTFILE is lost so we have to start a new one.
  if ps -xo comm | grep -q "^ssh-agent$"; then
    echo SSH-AGENT:  Stray ssh-agent\?  Killing it.
    killall -TERM ssh-agent
  fi
  echo SSH-AGENT:  A new agent started.  Remeber to run ssh-add!
  ssh-agent | grep -v '^echo' >$AGENTFILE
fi
. $AGENTFILE
unset AGENTFILE

It will automatically reuse a running agent, if possible, and start a new one, if there's no running or the information how to connect it was lost. If the agent is found to know no identities, you are reminded to run ssh-add.

If you have a shell launched before the current ssh-agent was started, you can do

. ~/.ssh/current-ssh-agent

to update it.

If you are paranoid, you may want to delete all identities when you completely log-out, i.e. when your last login shell ends. This can be achieved by putting following lines to your ~/.bash_logout< :

if test $(w -hsf $(id -un) | wc -l) = 1; then
  ssh-add -D
fi

It's also possible to put a similar identity clean-up command to crontab, to allow a grace period for relogin w/o removing the identities.




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


Copyright © 1996-2014 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine. 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 make a contribution, supporting hosting of this site with different providers to distribute and speed up access. Currently there are two functional mirrors: softpanorama.info (the fastest) and softpanorama.net.

Disclaimer:

The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last modified: February 19, 2014