|
Softpanorama |
May the source be with you, but remember the KISS principle ;-)
|
Secure Shell (SSH) was originally developed by Tatu Ylцnen, Finland, as a secure replacement for Telnet, rlogin, rcp, rsh. It is based on so called Public-Key Cryptography Optional compression of traffic is provided.
SSH can be many authentication schemes such as SecurID, Kerberos, S/KEY to provide a highly secure remote access point to UNIX servers. By default, the OpenSSH server listens for requests on port 22 and port 6010 for X11 forwarding.
SSH1 was the the first version (protocol v1.2 and v1.5) that was free in the earlier days, but licensing has become more restrictive and SSH Communications and DataFellows are trying to get people to move to the newer SSH2 (which is commercial).
OpenSSH has been produced by the OpenBSD team and community. It was first integrated in OpenBSD in 1999. Linux got it much later.
OpenSSH intended as a drop-in replacement for the Berkeley "r"-tools (rsh, rlogin, rcp). It can also tunnel via encrypted tunnel X windows and other TCP/IP application level protocols.
Like r-tools ssh supports cross computer pipes:
tar cvzf - . | rsh xxx.xxx.xxx.xxx "(cd $dir; tar xzf -)"
tar cvzf - . | ssh xxx.xxx.xxx.xxx "(cd $dir; tar xzf -)"
This is also possible to do in the reverse direction
ssh xxx.xxx.xxx.xxx "(cd $dir; tar cvzf -)" | tar xzf -
Openssh is a leading SSH implementation (by world famous OpenBSD team). It was first included into OpenBSD 2.6. The software is developed outside the USA, using code from roughly 10 countries, and is freely useable and re-useable by everyone under a BSD license. The OpenSSH suite includes the ssh program which replaces rlogin and telnet, scp which replaces rcp, and sftp which replaces ftp. Also included is sshd which is the server side of the package, and the other basic utilities like ssh-add, ssh-agent, ssh-keysign, ssh-keyscan, ssh-keygen and sftp-server.
The package includes several binaries:
Binary name Description ssh rlogin/rsh-like client program ssh-agent This command can store passphrase for private RSA keys in memory, to respond to challenges (challenge response) from the server. This simplifies repeated authentication (imitation of no password authentication) ssh-add Tool which adds keys to ssh-agent sftp FTP-like program that works over SSH1 and SSH2 protocol scp File copy program that acts like rcp ssh-keygen This command generates RSA public and private keys pair ssh-keyscan A utility for gathering the public ssh host keys from a
number of SSH servers. The keys gathered are
displayed on the standard output. This output can then be compared with the key in the file /etc/ssh/ssh_known_hosts and be included in the
file.ssh-keysign Utility for hostbased authentication sshd The daemon that permits you to login sftp-server SFTP server subsystem (started automatically by sshd)
OpenSSH supports SSH protocol versions 1.3, 1.5, and 2.0. Only the latest versions of v. 2.0 have required level of security. Earlier versions have serious security vulnerabilities.
It's not without drawbacks: since SSH is encrypted, troubleshooting is quite challenging. There are also multiple hazards that are inherent in the protocol of that level complexity. Vulnerabilities with SSH, especially were one of the major exploits that were used against ISPs. Beyond protocol problems, there are architecture issues by allowing encrypted pipes. It defeats IDS mechanisms.
|
Silk Tree propagate /etc/passwd and /etc/group files from a master to a list of hosts via SSH. Neither the sending nor the receiving end connect to each other as root. Instead there is a read-only sudo sub-component on the receiver's side that makes the final modifications in /etc. Many checks are made to ensure reliable authorization updates. ACLs are used to enforce a simple security policy. Differences between old and new versions are shown. Two small scripts are included for exporting LDAP users and groups.
Syntax
sshpass [options] command arguments
Options
If not option is given, sshpass reads the password from the standard input. The user may give at most one alternative source for the password:
-p password - The password is given on the command line. Please note the section titled “SECURITY CONSIDERATIONS”.
-f filename - The password is the first line of the file filename.
-d number - number is a file descriptor inherited by sshpass from the runner. The password is read from the open file descriptor.
-e - The password is taken from the environment variable “SSHPASS”.
Security Considerations
First and foremost, users of sshpass should realize that ssh’s insistance on only getting the password interactively is not without reason. It is close to impossible to securely store the password, and users of sshpass should consider whether ssh’s public key authentication provides the same end-user experience, while involving less hassle and being more secure.
The -p option should be considered the least secure of all of sshpass’s options. All system users can see the password in the command line with a simple “ps” command. Sshpass makes no attempt to hide the password, as such attempts create race conditions without actually solving the problem. Users of sshpass are encouraged to use one of the other password passing techniques, which are all more secure.
In particular, people writing programs that are meant to communicate the password programatically are encouraged to use an anonymous pipe and pass the pipe’s reading end to sshpass using the -d option.
sshpass Examples
1) Run rsync over SSH using password authentication, passing the password on the command line:
rsync –rsh=’sshpass -p 12345 ssh -l test’ host.example.com:path
2)sshpass -p [yourpassword] ssh [yourusername]@[host]
About: MindTerm is a complete ssh-client in pure Java. It can be used either as a standalone Java application or as a Java applet. Three packages of importance are provided (terminal, ssh, and security). The terminal package is a rather complete vt102/xterm-terminal, and the ssh-package contains the ssh- protocol and also "drop-in" socket replacements to use ssh-tunnels transparently from a Java application/applet. It also contains functionality to realize a ssh-server. Finally, the security package contains RSA, DES, 3DES, Blowfish, IDEA, and RC4 ciphers.
... ... ...
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 2When 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 DaemonFrom 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.25In 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 yesBoth 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 noBefore 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 DaemonNow, 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:
- You can generate a DSA (-t dsa), RSA (-t rsa), or SSHv1 (-t rsa1) key. In the example above I'm using dsa.
- I like to put the date I generated the key in the comment (-C) field, that way I can change it out every so often.
- You're entering a passphrase, not a password. Use a long string with spaces and punctuation. The longer and more complicated the better!
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.
About: Gnome-sshman is an SSH session manager for GNOME. It is easy and fast to use, and is useful for system administrators that need to connect to many SSH servers. Gnome-sshman saves ssh sessions and allows you to open a saved session with a double click in nautilus. Changes: The "open sessions folder" button was removed, so nautilus is now an optional dependency. A session information tool was added to view session data and attach notes to an ssh session. Telnet support was added. A warning is given if you are closing a session with opened tabs. A preferences window was added to change colors, fonts, and set other default options. Gconf support was added. Two bugs were corrected: a cypher module bug with the hwrandom module and a bug with GNOME 2.20 nautilus in background mode.
rshall
Runs commands on multiple remote hosts simultaneously. (Perl)
View the README
Download version 11.0 - gzipped tarball, 9 KB
Last update: November 2005
autosync
Copies files to remote hosts based on a configuration file. (Perl)
View the README
Download version 1.4 - gzipped tarball, 5 KB
Last update: April 2007
Simplifying remote loginSecure Shell (SSH) tools provide a secure method for logging in and exchanging information with a remote host. A number of different tools are provided, including the general-purpose SSH tool (which provides a remote terminal connection), SCP (a secure, host-to-host, copy solution), and SFTP, a secure file copy solution that works in a similar fashion to the standard FTP tools.
All of these tools are secure in that the information that is exchanged is encrypted. In addition, the authentication of connections is secured using a public or private key mechanism. One of the main benefits of SSH is that you can bypass the normal login and password exchange by copying your public key to a remote machine.
Although this is useful when using SSH to log in to a remote machine (as it means you don't have to provide a password), it is even more useful when performing remote administration. Having to type in a password can also make automated remote administration (for example, running a command through cron) impossible, because in an automated script, you won't be around to type in the password!
When using SSH to run commands across multiple machines without exchanging your public key, you need to type in your password for each machine.
A quick and simple way of setting this up is to create a public key:
$ ssh-keygen -t rsa
Follow the on-screen instructions, but don't set a password when prompted, as you will then need to enter the password each time you want to use the key. This creates a private and a public key file. Now you just need to append the contents of the public key file in .ssh/id_rsa.pub, and append it to the .ssh/authorized_keys file on the remote host and user you want to use when logging in. You need to append the public key file contents to each machine you want to log in to automatically.There are many ways in which you can run a remote command.
You can run a single remote command by adding the command you want to run to SSH after the login or host information. For example, to get the disk information for a remote host, you might use the command and get the output in Listing 1 below.
Listing 1. Running a simple command through SSH
$ ssh mc@gentoo.vm df Filesystem 1K-blocks Used Available Use% Mounted on /dev/hda3 14544820 3611520 10194464 27% / udev 128044 564 127480 1% /dev /dev/hdc1 1968872 50340 1818516 3% /var/tmp /dev/hdc2 1968904 1482220 386668 80% /usr/portage /dev/hdc3 1968904 35760 1833128 2% /home/build shm 128044 0 128044 0% /dev/shm
Bear in mind that the sequence in Listing 1 requires you to enter a password if you haven't already exchanged your public key with the remote host.
You can also execute a sequence of commands by separating each command with a semicolon and then placing the entire sequence of commands into quotes so that it is identified as a single argument.
An example of executing both a disk check and an uptime check is shown in Listing 2.
Listing 2. Executing a disk and an uptime check
$ ssh mc@gentoo.vm "df;uptime" Filesystem 1K-blocks Used Available Use% Mounted on /dev/hda3 14544820 3611520 10194464 27% / udev 128044 564 127480 1% /dev /dev/hdc1 1968872 50340 1818516 3% /var/tmp /dev/hdc2 1968904 1488100 380788 80% /usr/portage /dev/hdc3 1968904 35760 1833128 2% /home/build shm 128044 0 128044 0% /dev/shm 14:31:27 up 12 min, 2 users, load average: 0.01, 0.05, 0.06
You can string as many commands as you like into this operation. Filtering, for example, using grep or other tools, is also possible, but you need to make sure to embed the entire remote command expression into the quotes (see Listing 3).
Listing 3. Filtering using grep
$ ssh root@gentoo.vm "cat /var/log/messages|grep 'su\['" Dec 17 18:05:37 localhost su[19218]: pam_authenticate: Permission denied Dec 17 18:05:37 localhost su[19218]: FAILED su for root by mc Dec 17 18:05:37 localhost su[19218]: - pts/1 mc:root Dec 17 18:06:31 localhost su[19221]: pam_authenticate: Permission denied Dec 17 18:06:31 localhost su[19221]: FAILED su for root by mc Dec 17 18:06:31 localhost su[19221]: - pts/1 mc:root Dec 17 18:06:40 localhost su[19222]: pam_authenticate: Permission denied Dec 17 18:06:40 localhost su[19222]: FAILED su for root by mc ...
The first item to note about Listing 3 is that you are logging in directly to the remote machine as root. This is because the file you want to view is only accessible to the superuser. You must ensure that your system is configured to allow remote root logins for this to work.
The second important note about this example is that you've performed the grep operation remotely. In actual fact, you don't need to do this. The standard input and output of the remote host are replicated to the local machine, so the output from the command can be filtered locally, as shown here in Listing 4.
Listing 4. Output filtered locally
$ ssh root@gentoo.vm "cat /var/log/messages" | grep 'su\[' Dec 17 18:05:37 localhost su[19218]: pam_authenticate: Permission denied Dec 17 18:05:37 localhost su[19218]: FAILED su for root by mc Dec 17 18:05:37 localhost su[19218]: - pts/1 mc:root Dec 17 18:06:31 localhost su[19221]: pam_authenticate: Permission denied Dec 17 18:06:31 localhost su[19221]: FAILED su for root by mc Dec 17 18:06:31 localhost su[19221]: - pts/1 mc:root Dec 17 18:06:40 localhost su[19222]: pam_authenticate: Permission denied Dec 17 18:06:40 localhost su[19222]: FAILED su for root by mc Dec 17 18:06:40 localhost su[19222]: - pts/1 mc:root
Of course, the effect is essentially the same.
Using the remote pipe method, though, is useful when the information or command that you want to pipe with is remote. For example, you can use
lsin combination withduto determine the disk usage of different directories with the command shown in Listing 5.
Listing 5. Determining disk usage of different commands
ssh root@gentoo.vm "ls -d /usr/local/* |xargs du -sh " Password: 4.0K /usr/local/bin 4.0K /usr/local/games 4.0K /usr/local/lib 0 /usr/local/man 4.0K /usr/local/sbin 12K /usr/local/share 4.0K /usr/local/src
Before moving on to redistributing these techniques to multiple machines, there's a quick trick for running remote interactive sessions directly without having to log in first.
As shown previously, you can directly run a number of different commands and chains of commands. One of the benefits of the SSH solution is that although the command itself is executed remotely, the input and output of the command are sourced from the calling machine. You can use this as a method for exchanging information between the two machines relating to the commands that you want to execute.
The commands that you execute can cover almost anything from a range of different commands. However, because you are running commands directly from the command line, there are limits to what you can execute directly with this method. For example, trying to edit a remote file with an editor using this method and techniques shown above usually fail (see Listing 6).
Listing 6. Edit a remote file fails
$ ssh root@gentoo.vm "emacs /etc/amavisd.conf" emacs: standard input is not a tty
You can resolve this by forcing SSH to allocate a pseudo-tty device so that you can interact directly with the remote application.
SftpDrive Access SFTP as a Windows Drive Letter
SftpDrive lets your applications access your files from anywhere on the Internet safely and securely, like a VPN, without the VPN.
SSH is the industry standard for remote access to Linux, Mac OS X, and UNIX computers because it's safe, secure, and just works from anywhere on the Internet. SSH servers like OpenSSH and VShell have a powerful system called SFTP built-in. Unrelated to the archaic FTP protocol, SFTP is a modern, secure system that gives you the power to treat your network files as if they were right on your desktop. Stream movies and music. Run programs. Load and save any file from any application. Best of all, your SSH server is ready to go.
Many of us use the excellent OpenSSH as a secure, encrypted replacement for the venerable telnet and rsh commands. One of OpenSSH's (and the commercial SSH2's) intriguing features is its ability to authenticate users using the RSA and DSA authentication protocols, which are based upon a pair of complementary numerical "keys". And one of the main appeals of RSA and DSA authentication is the promise of being able to establish connections to remote systems without supplying a password. The keychain script makes handling RSA and DSA keys both convenient and secure. It acts as a front-end to ssh-agent, allowing you to easily have one long-running ssh-agent process per system, rather than per login session. This dramatically reduces the number of times you need to enter your passphrase from once per new login session to once every time your local machine is rebooted.
Keychain was first introduced in a series of IBM developerWorks articles.
- The first article introduces the concepts behind RSA/DSA key authentication and shows you how to set up primitive (with passphrase) RSA/DSA authentication.
- The second article shows you how to use keychain to set up secure, passwordless ssh access in an extremely convenient way. keychain also provides a clean, secure way for cron jobs to take advantage of RSA/DSA keys without having to use insecure unencrypted private keys.
- The third article shows you how to use ssh-agent's authentication forwarding mechanism.
Current versions of keychain are known to run on Linux, BSD, Cygwin, Tru64 UNIX, HP-UX, Mac OS X, and Solaris using whatever variant of Bourne shell you have available.
Secure Shell is a program to log into another computer over a network, to execute commands in a remote machine, and to move files from one machine to another. It provides strong authentication and secure communications over unsecure channels. It is intended as a replacement for telnet, rlogin, rsh, and rcp. For SSH2, there is a replacement for FTP: sftp.This might be useful if you are trying to connect everytime to your server remotely.A Trust relationship can be established for users on multiple servers running OpenSSH to allow a password free ssh session. This is sometime important when you want to run scripts or commands remotely.
Let’s assume ServerA and ServerB both run the ssh daemons.
To allow ServerA to SSH to ServerB without password, please try the following:
# ssh-keygen -t rsa
Note: User here is root
This generates two files id_rsa.pub and id_rsa
Now, this needs to be copied to the authorized_keys file on ServerB
# scp id_rsa.pub ServerB:~/.ssh/authorized_keys
Enter password when prompted.
Note: If the ServerB is already having a trust relationship with more that one hosts already then the above will wipe the contents and write this key alone. In which case, copy the file to the remote server as something like ServerA_rsa.pub and then append the contents to authorized_keys as follows. This will allow the existing authroized_keys from being wiped off.
# scp id_rsa.pub ServerB:~/.ssh/ServerA_rsa.pub
# cat ServerA_rsa.pub >> authorized_keys
Thats it. Test if you are able to do a ssh from ServerA without a password:
# ssh serverB uname -a
This will run the command “uname -a” on ServerB and returns the result on ServerA.
The same procedure has to be followed in the reverse to allow ServerB to talk back to ServerA without any password.
And, if there is anyone other server to be added to the existing list follow the same procedure ensuring the key is appended to the remote servers authorized_keys file and not by overwriting it.
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.logIf 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?
TCP wrappers provides limited, connection-oriented host-based firewall functionality with which connections can be denied or accepted based on the originating host. Connection attempts are logged using syslog(3C). OpenSSH uses this functionality by linking in the libwrap library. TCP wrappers is dependent on the name and IP address information returned by the name services, such as DNS. It cannot stop low-level network-based attacks, such as port scanning, IP spoofing, or denial of service. For those, a packet-based firewall solution such as SunScreenTM software is necessary. The Solaris 9 OE has TCP wrappers integrated into it, package SFWtcpd, which is located in the /usr/sfw directory. For the Solaris 8 OE, TCP wrappers can be found on the Software Companion CD (starting in the Solaris 8 10/00 release). For the Solaris 2.6 and 7 OE releases, TCP wrappers must be downloaded and built from the source. TCP wrappers is not required to build OpenSSH.
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:
- Access will be granted when a (daemon,client) pair matches an entry in the /etc/hosts.allow file.
- Otherwise, access will be denied when a (daemon,client) pair matches an entry in the /etc/hosts.deny file.
- Otherwise, access will be granted.
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
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 : denyBy 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.
Configuring SSH Secure Shell for TCP Wrappers Support
To enable usage of TCP Wrappers with SSH Secure Shell, perform the following operations:
- If SSH Secure Shell was previously installed from binaries, you may want to uninstall it before continuing.
- Compile the source code:
./configure --with-libwrap makeThen, become root and runmake installNote: Ifconfiguredoes not findlibwrap.a, do the following:
- Locate
libwrap.a- Run
configureagain:make distclean ./configure --with-libwrap=/path_to_libwrap.a/Note: It is only necessary to specify the path tolibwrap.aif 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.- Create or edit the
/etc/hosts.allowand/etc/hosts.denyfiles. When a user tries to connect to the SSH Secure Shell server, the TCP wrapper daemon (tcpd) reads the/etc/hosts.allowfile for a rule that matches the client's hostname or IP. If/etc/hosts.allowdoes not contain a rule allowing access,tcpdreads/etc/hosts.denyfor 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.allowand/etc/hosts.denyfiles is as follows:daemon : client_hostname_or_IPThe typical setup is to deny access to everyone listed in the/etc/hosts.denyfile. (This example shows both ssh1 and ssh2.)sshd1: ALL sshd2: ALL sshdfwd-X11 : ALLor simplyALL: ALLAnd 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.fiBased on the/etc/hosts.allowfile above, users coming from any host in the ssh.com domain or from the host foo.bar.fi are allowed to access.
4.6. Can I run Secure Shell from inetd?
Yes, you can. No, you generally shouldn't. And boy, do I hate this question :)
When the Secure Shell daemon is started, it processes its configuration file and generates a cryptographic key. This can take several seconds, especially on a slow or busy server, and the startup time can be unacceptably long.
However, as Mike Friedman
writes: "What many people (including me) do is run a 'backup' sshd at a non-standard port out of inetd, for use just when the standalone sshd has failed. This gives you a way to login to restart the regular sshd (or to investigate why it won't start!), but the latter would still be what most users normally connect to (at the standard port 22)." If you decide to run Secure Shell via inetd:
To reduce the startup time for SSH1, you can reduce the size of the key that is generated with the -b flag (e.g. "-b 512"). The default keysize is 768 bits, and a keysize of 512 bits should be small enough to reduce the startup time. This is not recommended, however, as a 512-bit key is significantly easier to break than a larger key. The key size cannot be altered at runtime with SSH2; a new server key must be generated with ssh-keygen2.
When starting sshd from inetd, be sure to pass it the -i flag so it behaves properly.
undated (cyberciti.biz)FUSE is a Linux kernel module also available for FreeBSD, OpenSolaris and Mac OS X that allows non-privileged users to create their own file systems without the need to write any kernel code. This is achieved by running the file system code in user space, while the FUSE module only provides a “bridge” to the actual kernel interfaces. FUSE was officially merged into the mainstream Linux kernel tree in kernel version 2.6.14.
You need to use SSHFS to access to a remote filesystem through SSH or even you can use Gmail account to store files.
Following instructions are tested on CentOS, Fedora Core and RHEL 4/5 only. But instructions should work with any other Linux distro without a problem.
Step # 1: Download and Install FUSE
Visit fuse home page and download latest source code tar ball. Use wget command to download fuse package:
# wget http://superb-west.dl.sourceforge.net/sourceforge/fuse/fuse-2.6.5.tar.gz
Untar source code:
# tar -zxvf fuse-2.6.5.tar.gz
Compile and Install fuse:
# cd fuse-2.6.5
# ./configure
# make
# make install
Step # 2: Configure Fuse shared libraries loading
You need to configure dynamic linker run time bindings using ldconfig command so that sshfs command can load shared libraries such as libfuse.so.2:
# vi /etc/ld.so.conf.d/fuse.conf
Append following path:
/usr/local/lib
Run ldconfig:
# ldconfigStep # 3: Install sshfs
Now fuse is loaded and ready to use. Now you need sshfs to access and mount file system using ssh. Visit sshfs home page and download latest source code tar ball. Use wget command to download fuse package:
# wget http://easynews.dl.sourceforge.net/sourceforge/fuse/sshfs-fuse-1.7.tar.gz
Untar source code:
# tar -zxvf sshfs-fuse-1.7.tar.gz
Compile and Install fuse:
# cd sshfs-fuse-1.7
# ./configure
# make
# make install
Mounting your remote filesystem
Now you have working setup, all you need to do is mount a filesystem under Linux. First create a mount point:
# mkdir /mnt/remote
Now mount a remote server filesystem using sshfs command:
# sshfs vivek@rock.nixcraft.in: /mnt/remote
Where,
- sshfs : SSHFS is a command name
- vivek@rock.nixcraft.in: - vivek is ssh username and rock.nixcraft.in is my remote ssh server.
- /mnt/remote : a local mount point
When promoted supply vivek (ssh user) password. Make sure you replace username and hostname as per your requirements.
Now you can access your filesystem securely using Internet or your LAN/WAN:
# cd /mnt/remote
# ls
# cp -a /ftpdata . &
To unmount file system just type:
# fusermount -u /mnt/remote...
Some co-workers turned me on to GNU screen last year. It's a handy addition to my toolbox. It became most useful after I learned how to use it with SSH. The original URL that gave me the solution appears to be gone (a message in the now-defunct gnu-screen Yahoo group). So I thought I'd write this up and see how it fares when people google gnu screen ssh.
The solution I settled on is a nested invocation I learned from Jason White. I recommend you read my screenrc and my slave screenrc in another window and read along here for commentary. You run an "outer" screen session (the "slave" session) that in turn runs an "inner" (or "master") session. You use the regular escape sequence (Ctrl-A d) to detatch from the master, and you map Ctrl-^ to be the control key for the slave session. If you press Ctrl-^ while using screen this way, you'll see one process in the slave session. It's running ssh-agent. That's the key to using ssh with screen. The slave's only purpose is to run ssh-agent. The master runs as a child of that. Consequently, all shells in the master session are running under the ssh-agent. Just run ssh-add from any master shell, and then all shells have your ssh identity.
For more information about GNU screen, see GNU Screen: an introduction and beginner's tutorial or Power Sessions with Screen. For more information about SSH, see openssh.com.
|
Nested Screens Not Necessary
phil_g 2004-07-06 08:57 am UTC (link) |
| You don't need to use nested screens to get this effect. I achieve it by the use of a simple wrapper script for screen. To attach to a screen session, I have a single script that I run; it loads the agent before starting screen. (I use keychain to ensure that only one agent instance is running, regardless of how many times I attach to screen.) See my attach-screen script for specific details. |
rsnapshot is a filesystem snapshot utility based on rsync. It makes it easy to make periodic snapshots of local machines, and remote machines over ssh. It uses hard links whenever possible, to greatly reduce the disk space required.
Warsync (Wrapper Around Rsync) is a server replication system mainly used to sync servers in LVS clusters. It is based on rsync over ssh and has native support for Debian package synchronization.
Spinner is useful for keeping telnet and ssh links from dropping due to inactivity. Many firewalls and some ISPs drop connections when they are perceived as idle. By having spinner running, the server is constantly sent a tiny amount of data over the link, preserving the connection. Spinner thus acts as a keep-alive. It displays a little "spinning" ASCII character in the top left corner of your terminal. It supports any terminal capable of handling VT100-style escape codes. Spinner can also function transparently by only sending null characters to the terminal. In this mode Spinner supports any terminal. It also has a mode called "Ghost in the Machine" in which you can use Spinner to write the spinner character to any TTY, not just your own.
crackblock is a daemon that monitors your /var/log/secure for ssh login failures and blocks brute-force password crack attempts.
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.
Fanout allows you to run non-interactive commands on remote machines simultaneously, collecting the output in an organized fashion.
AScopy is a site maintenance utility. Its main purpose is to be portable and usable across any platform that has a working Bash shell and SSH.
But what about administrators using SSH on other platforms? Will they just plop in this tool as a simple FTP replacement, get it to work in that limited role, and then declare success?The biggest issues with SSH lie at Layer 8 of the OSI model—politics and personnel:
- One vulnerability issue underlies all SSH implementations: Most administrators know nothing about SSH’s port-forwarding abilities (or choose to ignore them). They may very well regard the security problems as "a UNIX issue." So the first risk is proliferation of a naïve SSH security design across multiple platforms, with little ownership of the big issues.
- A second risk is the "convenience at all costs" approach to agent forwarding. Anyone who has read an SSH man page knows that agent forwarding has known risks when used in untrusted environments. Do the same vulnerabilities exist with other operating systems? For that matter, do all client and server SSH implementations carry the same warnings? We can’t answer all of these questions, but we can make a strong recommendation and review a suggested Slashdot poster’s mitigation.
- A third major issue is the port-forwarding risk that allows an innocent outbound connection (to a remote SSH server) to become a malicious inbound connection into your company’s intranet. This connection is encrypted and will be very difficult to monitor, thus adding to the danger.
Security mitigations must do more than suggest technical settings for one SSH version. (And the technical settings vary by version, anyway, so don’t expect this article to be a primer on SSH server and client security. There are too many features to discuss, and we must address greater issues than just technical settings.)
So what can your organization do to help secure multiple versions of SSH running on multiple operating systems?
While working on a project to create tutorials, I needed a way to watch how a user stepped through the process of using an application without being on-site.
VNC turned out to be a viable solution. I could remotely connect and view all the steps, while conversing about the process over the phone.
The trouble was there were firewalls at both ends. It would have been easy to just open the port normally used for VNC connectivity (5900) in the firewall, but it's definitely not secure.
Using VNC while tunneling over SSH was a quick and more secure way to accomplish the process/application watching goal.
Several steps are required to make it work.
Ideally, all inbound ports are closed on an Internet facing firewall. That will go a long way to keeping out the bad guys. Of course, any other remote access is then limited as well.
Opening up port 22 on the distant IPCop firewall works well for the purpose of tutorial generation and is easily accomplished using the IPCop Web-based GUI. A similar process is used if the user machine is behind a dedicated firewall appliance. The idea is to port forward the SSH traffic from the Internet to the VNC-equipped user desktop machine.
Port 22 on the user's Linux desktop also needs to be available for logging in via SSH. When the session is finished, the firewall's SSH port can then again be closed to inbound traffic.
Specialized remote access techniques should be considered, like port-knocking or using hardened firewall devices when a more permanent or bulletproof connection is needed.
21 July 2003
SSH tunnels can solve at least two problems. First, you can use an ssh tunnel to encrypt sensitive data as it traverses an insecure network. Secondly, reverse ssh tunnels can be used to provide remote access to services located behind a NAT device and / or firewall. The second has proved most useful to me, but we’ll cover both.
Background
TCP is a very common protocol used by computers to allow applications to talk to each other. For example, your web browser (application) requests a document from a web server (another application) running elsewhere—TCP is responsible (in part) for allowing your browser to talk to the remote server over a network of some sort. Part of this process involves creating a session, which is sort of a logical ‘channel’ that is maintained across a packet-switched network (as compared to, say, a circuit switched network). This channel allows the two parties on either end (the browser and the server) to conduct (possibly) useful communication across a potentially extremely diverse network (say, the Internet), regardless of the physical path that the data is actually taking.
SSH is the descendant of rsh and rlogin, which are non-encrypted programs for remote shell logins. Rsh and rlogin, like telnet, have a long lineage but now are outdated and insecure. However, these programs evolved a surprising number of nifty features over two decades of UNIX development, and the best of them made their way into SSH. Following are the 11 tricks I have found useful for squeezing the most power out of SSH.
Learn how to propagate files quickly and do backups easily when you set up scp to work without needing passwords.
In this article, I show you how to use the scp (secure copy) command without needing to use passwords. I then show you how to use this command in two scripts. One script lets you copy a file to multiple Linux boxes on your network, and the other allows you to back up all of your Linux boxes easily.
If you're a Linux sysadmin, you frequently need to copy files from one Linux box to another. Or, you may need to distribute a file to multiple boxes. You could use FTP, but using scp has many advantages. For instance, scp is much more secure than FTP. scp travels across the LAN/WAN encrypted, while FTP uses clear text, even for passwords.
But what I like best about scp is it's easily scriptable. Suppose you need to distribute a file to 100 Linux boxes. I'd rather write a script to do this than type 100 sets of copy commands. If you use FTP in your script, things can get messy, because each Linux box you log into is going to ask for a password. But if you use scp in your script, you can set things up so the remote Linux boxes don't ask for a password. Believe it or not, this actually is much more secure than using FTP.
Here's an example demonstrating the most basic syntax for scp. To copy a file named abc.tgz from your local PC to the /tmp dir of a remote PC called bozo, use:
scp abc.tgz root@bozo:/tmpYou now are asked for bozo's root password, so we're not quite there yet. The system still is asking for a password, so it's not easily scriptable. To fix that, follow this one-time procedure, after which you can make endless password-less scp copies:
- Decide which user on the local machine will be using scp later on. Of course, root gives you the most power, and that's how I personally have done it. I'm not going to give you a lecture here on the dangers of root, so if you don't understand them, choose a different user. Whatever you choose, log in as that user now and stay there for the rest of the procedure. Log in as this same user when you use scp later on.
- Generate a public/private key pair on the local machine. Say what? If you're not familiar with public key cryptography, here's the 15-second explanation. In public key cryptography, you generate a pair of mathematically related keys, one public and one private. You then give your public key to anyone and everyone in the world, but you never ever give out your private key. The magic is in the mathematical makeup of the keys; anyone with your public key can use it to encrypt a message, but only you can decrypt it with your private key. Anyway, the syntax to create the key pair is:
ssh-keygen -t rsa- In response, you should see:
Generating public/private rsa key pair
Enter file in which to save the key ...
Press Enter to accept this.
- In response, you should see:
Enter passphrase (empty for no passphrase):You don't need a passphrase, so press Enter twice.
- In response, you should see:
Your identification has been saved in ... Your public key has been saved in ...Note the name and location of the public key just generated. It always ends in .pub.
- Copy the public key just generated to all of your remote Linux boxes. You can use scp or FTP or whatever to make the copy. Assuming you're using root--again, see my warning in step 1--the key must be contained in the file /root/.ssh/authorized_keys. Or, if you are logging in as a user, for example, clyde, it would be in /home/clyde/authorized_keys. Notice that the authorized_keys file can contain keys from other PCs. So, if the file already exists and contains text, you need to append the contents of your public key file to what already is there.
Now, with a little luck, you should be able to scp a file to the remote box without needing to use a password. So let's test it by trying our first example again. Copy a file named xyz.tgz from your local PC to the /tmp dir of a remote PC called bozo:
scp xyz.tgz root@bozo:/tmpWow--it copied with no password!
A word about security before we go on. This local PC just became pretty powerful, as it now has access to all the remote PCs with only the one local password. So that one password better be strong and well guarded.
Now for the fun part. Let's write a short script to copy a file called houdini from the local PC to the /tmp dir of ten remote PCs, located in ten different cities, in only five minutes of work. Of course, it would work the same with 100 or 1000 of PCs. Suppose the 10 PCs are called brooklyn, oshkosh, paris, bejing, winslow, rio, gnome, miami, minsk and tokyo. Here's the script:
#!/bin/sh for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk tokyo do scp houdini root@$CITY:/tmp echo $CITY " is copied" doneIt works like magic. With the echo line in this script, you should be able to watch as each city's copy is completed one after the next.
By the way, if you're new to shell scripting, here is a pretty good tutorial.
As you may know, scp is only one part of the much broader SSH program. Here's the cool part: when you followed my six-step procedure above, you also gained the ability to sit at your local PC and execute any command you like on any of the remote PCs--without a password, of course. Here's a simple example to view the date and time on the remote PC brooklyn:
ssh brooklyn "date"Let's now put these two concepts together for one final and seriously cool script. It's a down-and-dirty way to back up all of your remote Linux boxes. The example backs up the /home dir on each box. It's primitive compared to the abilities of commercial backup software, but you can't beat the price. Consider the fact that most commercial backup software charges license fees for each machine you back up. If you use such a package, instead of paying license fees to back up 100 PCs remotely, you could use the script to back up the 100 PCs to one local PC. Then, back up the local PC to your commercial package and save the license fees for 99 PCs. Anyway, the script below demonstrates the concepts, so you can write your own script to suit your own situation. Simply put this script in a cron job on your local PC; no script is required on the remote PCs. Please read the comments carefully, as they explain everything you need to know:
#!/bin/sh # Variables are upper case for clarity # before using the script you need to create a dir called '/tmp/backups' on each # remote box & a dir called '/usr/backups' on the local box # on this local PC # Set the variable "DATE" & format the date cmd output to look pretty # DATE=$(date +%b%d) # this 'for loop' has 3 separate functions for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk tokyo do # remove tarball on remote box from the previous time the script ran # to avoid filling up your HD # then echo it for troubleshooting # ssh -1 $CITY "rm -f /tmp/backups/*.tgz" echo $CITY " old tarball removed" # create a tarball of the /home dir on each remote box & put it in /tmp/backups # name the tarball uniquely with the date & city name # ssh $CITY "tar -zcvpf /tmp/backups/$CITY.$DATE.tgz /home/" echo $CITY " is tarred" # copy the tarball just create from the remote box to the /usr/backups dir on # the local box # scp root@$CITY:/tmp/backups/$CITY.$DATE.tgz /usr/backups echo $CITY " is copied" done # the rest of the script is for error checking only, so it's optional: # on this local PC # create error file w todays date. # If any box doesn't get backed, it gets written to this file # touch /u01/backup/scp_error_$DATE for CITY in brooklyn oshkosh paris bejing winslow rio gnome miami minsk tokyo do # Check if tarball was copied to local box. If not write to error file # note the use of '||' which says do what's after it if what's before it is not # true # ls /u01/backup/$CITY.$DATE.tgz || echo " $CITY did not copy" >> scp_error_$DATE # Check if tarball can be opened w/o errors. If errors write to error file. tar ztvf /u01/backup/$CITY.$DATE.tgz || echo "tarball of $CITY is No Good" >> scp_error_$DATE doneThat's about it. In this article, I've tried to give examples that demonstrate the concepts and are not necessarily ready to be used "as is". Some of the syntax may not work for all distributions, but in the interest of brevity, I could not include all the possibilities. For example, if you are using Red Hat 6.2 or before, the syntax requires some changes. So be creative, and hopefully you can use some of this work in your own environment.
Copyright (c) 2004, Dave Sirof. Originally published in Linux Gazette issue 98. Copyright (c) 2004, Specialized Systems Consultants, Inc.
Ver.2.07(2004/12/8) Installer English/ Japanese SourceForge.jp WindowsXP/2000/NT4.0
PuTTY is a free implementation of Telnet and SSH for Win32 and Unix platforms, along with an xterm terminal emulator.
Release focus: Major feature enhancements
Changes:
PuTTY now supports IPv6, xterm 256-color control sequences, wildcards and recursive file transfer in PSFTP, and keepalives in all operating systems. A number of small bugs were fixed, security was improved for SSH2, and port forwarding can now be reconfigured mid-session.
Introduction
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.
My requirements looked something like this:
- Keep port 22 closed, until needed
- Provide a simple way to open and close port 22 from any remote location
- Ensure the method used is reasonably difficult for attackers to discover
- Use an "elegant" method (i.e. not a lot of software)
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... ^CNote 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 COMMITNote 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 ssh2Disclaimer
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
- survive logouts
- be started in one shell and be usable in others
This is quite easy, one only has to capture the output of the
ssh-agentcommand 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 AGENTFILEIt 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-agentto 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 fiIt'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.
GNU Screen and OpenSSH are two incredibly useful tools. In this tutorial, I hope to help users to work around a small, but annoying, problem that can arise when using SSH-Agent forwarding and Screen. This tutorial assumes you have knowledge of SSH, SSH-Agent, SSH-Agent-forwarding and GNU Screen. I also assume you're using a shell that can handle Bourne shell variable syntax.
The Problem
SSH-Agent forwarding breaks when screen is re-attached on a different host.
Details
The problem involves three hosts
* , A, B, and S. All of these hosts have Agent-Forwarding enabled in their SSH configuration.I log into host A and run ssh-agent, authenticating to my key. I connect from machine A to machine S using my agent/key to authenticate. On machine S, I start screen. I open several screen windows, all running shells. These shells inherit the ssh-agent variables from the parent shell that spawned the screen. (This is where the problem starts.)
I notice that it's time for work, so I drive to work and log into machine B, starting ssh-agent and authenticate to my key. I connect from machine B to machine S using my agent/key to authenticate. I resume the running screen that I started when logged in from machine A. Naturally, all of the ssh environment variables are still set the way they were prior to the screen de/re-attach. So now, despite having ssh-agent forwarding turned on and having an active agent, I can't connect to remote hosts via host S without some kind of magic.
* This problem could also involve two connections from the same host (which will be on different client ports,) to a second host. I think the above example is clearer.SSH Environment Variables
When you connect, using ssh-agent for authentication, to a host that has ssh-agent forwarding enabled, the following shell variables will be set:
SSH_CLIENT=192.168.25.198 4671 22 SSH_TTY=/dev/pts/11 SSH_AUTH_SOCK=/tmp/ssh-zIn16635/agent.16635 SSH_CONNECTION=192.168.25.198 4671 192.168.25.3 22The SSH_CLIENT variable contains three space-separated pieces of information. The IP address of the client making the connection, the client's port number, and the server's port number.
The SSH_TTY variable is set to the path to the tty device used for the shell opened when the SSH connection was created.
The SSH_AUTH_SOCK variable identifies the path of a unix-domain socket used to communicate with the agent. In other words, this variable sets up a "path" back to the host that is actually running the agent, so that future ssh connections can talk to/use that agent.
The SSH_CONNECTION variable contains four space-separated pieces of information. The IP address of the client, the port number of the client, the IP address of the server and the port number of the server. This variable is necessary to prevent agent hijacking.
So, now that I've reiterated the ssh(1) man page, we can see why, when we connect from A to S, and then from B to S, ssh-agent forwarding fails. In the initial connection, S defines the SSH environment variables to point to host A. When screen starts its shells, they inherit those variables. When host B connects and grabs that instance of screen, the sub-shells have no idea that anything has changed, so the variables now point to the "wrong" machine.
The Solution
The environment variables listed above are set correctly when host B connects to host S, so we need a way to get them propagated to the shells running inside screen. I wrote a small script to cull them out and stick them in a file. The script also re-formats them so that they will be easily integrated into the shell's environment. I called this script "grabssh."
#!/bin/sh SSHVARS="SSH_CLIENT SSH_TTY SSH_AUTH_SOCK SSH_CONNECTION DISPLAY" for x in ${SSHVARS} ; do (eval echo $x=\$$x) | se