Difference between revisions of "Connecting to CS Systems with SSH"

(Created page with "From the SSH <code>man</code> page: ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to pro...")
 
m (Steve410 moved page SSH to Connecting to CS Systems with SSH: Adding specificity to the title.)
 
(68 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
From the SSH <code>man</code> page:
 
From the SSH <code>man</code> page:
  
    ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine.  It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network.  X11 connections, arbitrary TCP ports and UNIX-domain sockets can also be forwarded over the secure channel.
+
<!-- <pre style="white-space: pre-wrap;">ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine.  It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network.  X11 connections, arbitrary TCP ports and UNIX-domain sockets can also be forwarded over the secure channel.</pre>-->
 +
<blockquote>'''''ssh''' (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine.  It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network.  X11 connections, arbitrary TCP ports and UNIX-domain sockets can also be forwarded over the secure channel''.</blockquote>
  
The information provided on this page only covers a small portion of the things you can do with SSH and it is recommended that you read more about it via the <code>man</code> page or otherwise.
+
The information provided on this page only covers a small portion of the things you can do with SSH and it is recommended that you read more about it via the <code>man</code> page or from other sources.
  
= Required Client Software =
+
== Required Client Software ==
  
== Linux/Unix/macOS ==
+
=== Linux/Unix/macOS ===
OpenSSH is typically packaged with most unix and linux variants, which includes macOS. You can verify that ssh is installed by opening a terminal and running the following command:
+
OpenSSH is typically packaged with most Unix and Linux variants, which includes macOS. You can verify that ssh is installed by opening a terminal and running the following command:
  
    $ ssh -V
+
ssh -V
  
== Windows ==
+
=== Windows ===
Since April of 2018, SSH comes pre-installed in Microsoft Windows 10 and above and can be used via the command line. More information can be found [https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_overview here].
+
Since April of 2018, SSH (OpenSSH) comes pre-installed in Microsoft Windows 10 and above and can be used via the command line either by using the '''CMD''' shell or '''Powershell'''.   More information can be found at Microsoft's [https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_overview OpenSSH in Windows] page.  
  
= Using SSH =
+
You also have the option to run a 3rd party product called [https://www.chiark.greenend.org.uk/~sgtatham/putty/ PuTTY].  However, PuTTY uses different configurations for SSH Keys, X-Forwarding, etc. so, you'll need to find documentation for those items online.  The information you see below is specifically for OpenSSH, not PuTTY.
  
== Connecting to a Remote System ==
+
== Using SSH ==
Once you have confirmed that an SSH client is installed on your system, you can create a basic connection to a remote server using the following syntax:
 
  
    $ ssh username@server.host.name
+
=== Connecting to a Remote System ===
 +
For most of your connection needs in the CS Department, once you have confirmed that an SSH client is installed on your system, you can create a basic connection to a remote [[:Category:Linux_Clients|CS Linux client]] using the following syntax:
 +
 
 +
ssh <var>username</var>@<var>server.host.name</var>
  
 
'''Note:''' When typing your password, nothing will appear in the terminal. If you think you mistyped your password, you can press <code>Ctrl+U</code> to clear the input and try again.
 
'''Note:''' When typing your password, nothing will appear in the terminal. If you think you mistyped your password, you can press <code>Ctrl+U</code> to clear the input and try again.
  
== Using an Alternative Port ==
+
For example, to connect to one of our [[Linux Clients on the CS Undergrad Net|Ugrad Linux clients]], say, ''ugrad5'', and your username on that system is ''ckent1'', simply use:
The default connection port for SSH is TCP port 22, but sometimes you'll need to use an alternative port for any number of reasons.  To do this, you can use the <code>-p</code> parameter. For example, if you need to connect on TCP port 2222:
 
  
    $ ssh -p 2222 username@server.host.name
+
ssh ckent1@ugrad5.cs.jhu.edu
  
== Connecting with Key-Based Authentication ==
+
=== Using an Alternate Port ===
A very common authentication method built into SSH is key-based authentication. Instead of using a password to authenticate, a server may pre-authenticate a client by installing a public key. This system is far more secure than basic password authentication and is used on all ISI systems.
 
  
=== Generating a Key Pair ===
+
The ''default'' connection port for SSH is TCP port ''22'', but sometimes you'll need to use an alternate port for any number of reasons. To do this, you can use the <code>-p</code> parameter. For example, if you need to connect on TCP port ''2096'':
In order to configure key-based authentication for a server, you will need to generate a key pair. To do this, you use the <code>ssh-keygen</code> command. Running this command will invoke a "wizard" that will guide you through the key generation process for an RSA key pair:
 
  
    $ ssh-keygen
+
ssh -p 2096 <var>username</var>@<var>server.host.name</var>
    Generating public/private rsa key pair.
 
    Enter file in which to save the key (/Users/isiadmin/.ssh/id_rsa):
 
  
If you have never created an ssh key pair before, you can leave this blank. The default location of ssh keys is <code>~/.ssh/</code>, but you can put them anywhere you'd like.
+
=== Connecting with Key-Based Authentication ===
  
    Enter passphrase (empty for no passphrase):
+
A very common authentication method built into SSH is key-based authentication. Instead of using a password to authenticate, a server may pre-authenticate a client by installing a public key. This system is far more secure than basic password authentication and is available on all CS Linux clients.
  
We recommend setting a password for your private key. In the event that your private key is leaked, it could be used to log into any system having the matching public key configured. This helps to mitigate that risk. If nothing else, it will give you more time to revoke your old keys from your servers.
+
For more information, please see our [[Accessing Linux Clients with SSH Public Key Authentication]] page.
  
    Your identification has been saved in /example_directory/id_rsa.
+
=== X11 Forwarding ===
    Your public key has been saved in /example_directory/id_rsa.pub.
 
    The key fingerprint is:
 
    SHA256:pNeh9us0L5yTaMoK9s86gOSHzNr/j2iXyzqqWxWmHs0 user@local.machine
 
    The key's randomart image is:
 
    +---[RSA 2048]----+
 
    |                |
 
    |                |
 
    |    o  . .      |
 
    | . = . o o .    |
 
    |=.+ E . S .      |
 
    |.*.+  o .      |
 
    |..*.  . o+o    |
 
    |.o.o+=o.o.*+    |
 
    |oo.+BXX=..oo.    |
 
    +----[SHA256]-----+
 
  
Once the command finishes, it will generate both a private key and public keyThe public key will have the same name as your public key with a <code>.pub</code> filename extension.
+
SSH isn't just for running remote terminal sessionsIt can also be used to run GUI applications remotely. You can do this using a system called X11 Forwarding.
 
 
Your private key is to be kept securely on your local system. '''You should never transmit your private key over any network that may be monitored.'''
 
 
 
Your public key, on the other hand, may be safely transmitted in clear text. This key is used to encrypt data that can only be decrypted with the matching private key. The contents of the file should look similar to this:
 
  
    ssh-rsa ...[Random Base64-Encoded Data]... user@local.machine
+
==== Required Client Software for X11 Forwarding ====
  
This is what you'll need to give the administrator of the SSH server you're attempting to connect to. You can safely send this in an email.
+
===== Linux =====
  
=== Using a Private Key ===
+
If you're running a GUI on Linux, you probably already have X installed. You can verify with the following command:
If you let the <code>ssh-keygen</code> command store the key in the default location (<code>~/.ssh/id_rsa</code>), it will automatically be used when you connect. If you chose to install it someplace else (or simply have different keys for different systems), you'll need to indicate which key to use by using the <code>-i</code> parameter:
 
  
    $ ssh -i /path/to/id_rsa username@server.host.name
+
Xorg -version
  
== X11 Forwarding ==
+
===== Windows =====
SSH isn't just for running remote terminal sessions.  It can also be used to run GUI applications remotely.  You can do this using a system called X11 Forwarding.
 
  
=== Required Client Software ===
+
For X forwarding to work properly on Microsoft Windows, you will need to install an X window server, for example, a program like [https://sourceforge.net/projects/vcxsrv/ VcXsrv].
  
==== Linux ====
+
We don't directly support software installation on personal computers, but we'll note that when using VcXsrv on Windows 10 and 11:
If you're running a GUI on linux, you probably already have X installed.  You can verify with the following command:
 
  
    $ Xorg -version
+
* <kbd>ssh -X</kbd> might not work properly; <kbd>ssh -Y</kbd> might work instead.  Note that <code>-Y</code> is slightly less secure.  You can read the man pages for the full details, but using <code>-Y</code> causes the X server (on your desktop) to trust the remote system slightly more, which opens it up to some possible-if-unlikely attack vectors.  The problem with using <code>-X</code> appears to be related to the use of <code>xauth</code> on the Windows computer.  Interested parties are encouraged to read the VcXsrv and OpenSSH documentation to sort out the right configuration to use.
 +
* You need to set the <code>$DISPLAY</code> environment variable before running the command-line OpenSSH client.  In PowerShell, that can be done with <kbd>$env:DISPLAY = "localhost:0"</kbd> (or whichever display number VcXsrv is using, if it's not ":0").
  
==== Windows ====
+
===== macOS =====
For X forwarding to work properly on Microsoft Windows, you will need to install an X window server.  I recommend using [https://sourceforge.net/projects/vcxsrv/ VcXsrv].
 
  
==== macOS ====
 
 
Even though macOS is technically running a variation of X, you won't be able to use it for standard X applications like SSH.  In order to accomplish this, you can install [https://www.xquartz.org/ XQuartz].
 
Even though macOS is technically running a variation of X, you won't be able to use it for standard X applications like SSH.  In order to accomplish this, you can install [https://www.xquartz.org/ XQuartz].
  
 +
==== Using X11 Forwarding ====
  
=== Using X11 Forwarding ===
+
In order to enable X11 forwarding in your SSH connection, you will need to use the <code>-X</code> parameter:
In order to enable X11 Forwarding in your SSH connection, you will need to use the <code>-X</code> parameter:
 
  
    $ ssh -X username@server.host.name
+
ssh -X <var>username</var>@<var>server.host.name</var>
  
 
Once the session is established, you should be able to invoke any GUI application simply by executing the command.
 
Once the session is established, you should be able to invoke any GUI application simply by executing the command.
  
== Port Forwarding ==
+
=== Port Forwarding ===
 +
 
 
SSH has the ability to forward TCP traffic over the connection to enable the client to connect to resources on the remote system or vice versa.
 
SSH has the ability to forward TCP traffic over the connection to enable the client to connect to resources on the remote system or vice versa.
  
=== Local Port Forwarding ===
+
==== Local Port Forwarding ====
 +
 
 
If you want to connect to a service that is only accessible via the server you're connecting to, but want to be able to access it on your local PC, you can accomplish this using a local port forward using the <code>-L</code> parameter.
 
If you want to connect to a service that is only accessible via the server you're connecting to, but want to be able to access it on your local PC, you can accomplish this using a local port forward using the <code>-L</code> parameter.
  
    $ ssh -L local_port:remote_hostname:remote_port username@server.host.name
+
ssh -L <var>local_port</var>:<var>remote_hostname</var>:<var>remote_port</var> <var>username</var>@<var>server.host.name</var>
  
Let's assume the server you're connecting to has access to a mysql server that only accepts connections on port 3389 from your server, but you want to be able to use the management tool on your laptop to be able to make a change to the database.  You can run the following command:
+
Let's assume the server you're connecting to has access to a MySQL server that only accepts connections on port 3389 from your server, but you want to be able to use the management tool on your laptop to be able to make a change to the database.  You can run the following command:
  
    $ ssh -L 3390:mysql.remote.host:3389 username@server.host.name
+
ssh -L 3390:<var>mysql.remote.host</var>:3389 <var>username</var>@<var>server.host.name</var>
  
This will open a local socket on TCP port 3390 and forward all traffic to remote socket on the SSH server.  If you point your mysql tool to <code>127.0.0.1</code> on port 3390, the SSH server will attempt to connect to mysql.remote.host on TCP port 3389 and forward all traffic back through the tunnel to your client.
+
This will open a local socket on TCP port 3390 and forward all traffic to remote socket on the SSH server.  If you point your mysql tool to port 3390 on <code>127.0.0.1</code>, the SSH server will attempt to connect to mysql.remote.host on TCP port 3389 and forward all traffic back through the tunnel to your client.
 +
 
 +
==== Remote Port Forwarding ====
  
=== Remote Port Forwarding ===
 
 
If you have a local service that you want the server to be able to access, you can accomplish this using the <code>-R</code> parameter to invoke a remote port forward.
 
If you have a local service that you want the server to be able to access, you can accomplish this using the <code>-R</code> parameter to invoke a remote port forward.
  
    $ ssh -R remote_port:local_hostname:local_port username@server.host.name
+
ssh -R <var>remote_port</var>:<var>local_hostname</var>:<var>local_port</var> <var>username</var>@<var>server.host.name</var>
  
 
Let's say you're trying to download the latest version of nmap on your server, but the domain is blocked by the network security team. You can allow the server to connect through your own connection instead by using the following command:
 
Let's say you're trying to download the latest version of nmap on your server, but the domain is blocked by the network security team. You can allow the server to connect through your own connection instead by using the following command:
  
    $ ssh -R 8080:insecure.org:80 username@server.host.name
+
ssh -R 8080:insecure.org:80 <var>username</var>@<var>server.host.name</var>
 +
 
 +
On the server, you can now connect to port 8080 on 127.0.0.1, which will allow you download your software.
  
On the server, you can now connect to 127.0.0.1 on port 8080, which will allow you download your software.
+
==== Dynamic Port Forwarding ====
  
=== Dynamic Port Forwarding ===
 
 
In the event that there are a bunch of resources you need that are only available on the server's network, you can create a dynamic port forward using the <code>-D</code> flag:
 
In the event that there are a bunch of resources you need that are only available on the server's network, you can create a dynamic port forward using the <code>-D</code> flag:
  
    $ ssh -D local_port username@server.host.name
+
ssh -D <var>local_port</var> <var>username</var>@<var>server.host.name</var>
  
 
This will create a SOCKS5 proxy on the local port specified to be able to filter traffic through the server.  This is a great way to create a very simple VPN.
 
This will create a SOCKS5 proxy on the local port specified to be able to filter traffic through the server.  This is a great way to create a very simple VPN.
  
= Additional Resources =
+
== Configuring SSH ==
 +
 
 +
There are a lot of parameters you can set for your SSH connections, and remembering them can be a chore.  Fortunately there is an easy way to do this with SSH's client configuration file.
 +
 
 +
=== Setup ===
 +
 
 +
Typically the file can be found at <code>~/.ssh/config</code>. If you'd like to save it in another location or have different config files, you can specify which to use with the <code>-F</code> flag:
 +
 
 +
ssh -F <var>/path/to/config</var> <var>username</var>@<var>server.host.name</var>
 +
 
 +
If the file does not already exist, you can safely create it. Just make sure to set the appropriate permissions on the file.  The <code>.ssh</code> directory should be be set to Read, Write, and Enter for the owner only, and any config files should be set to Read and Write for the owner only:
 +
 
 +
mkdir ~/.ssh
 +
touch ~/.ssh/config
 +
chmod 0700 ~/.ssh/
 +
chmod 0600 ~/.ssh/config
 +
 
 +
=== Configuration ===
 +
 
 +
The SSH config file has a relatively straightforward syntax:
 +
 
 +
# Comments are prefixed with a hash
 +
Host <var>hostname</var>
 +
    <var>ParameterName</var> <var>Value</var>
 +
 
 +
Each <code>Host</code> line is followed by the settings for that host. You can specify settings for multiple hosts with a new <code>Host</code> line. For example:
 +
 
 +
# Server 1
 +
Host <var>server1.host.name</var>
 +
    <var>ParameterName</var> <var>Value</var>
 +
 +
# Server 2
 +
Host <var>server2.host.name</var>
 +
    <var>ParameterName</var> <var>Value</var>
 +
 
 +
When you connect to a host, SSH will scan the config file to determine if there is a matching <code>Host</code> entry for the server you're attempting to connect to.  This allows us to use a wildcard character (*) in this field for pattern matching.  For example:
 +
 
 +
# Default settings for any systems we connect to at jhu.edu:
 +
Host *.jhu.edu
 +
    <var>Parameter1</var> <var>Value</var>
 +
 +
# Default settings for all hosts we connect to:
 +
Host *
 +
    <var>Parameter2</var> <var>Value</var>
 +
 
 +
'''Note:''' If multiple patterns match a host, the settings will stack.  In this case, any host matching <code>Host *.jhu.edu</code> also matches <code>Host *</code>, so the settings from both will apply.  If the same parameter is set in different matching <code>Host</code> sections, the ''first'' one in the file will be the one that takes effect.
 +
 
 +
You can find a list of all parameters available in the [https://linux.die.net/man/5/ssh ssh(5) Man Page].
 +
 
 +
=== Useful Examples ===
 +
 
 +
==== Preventing Disconnects on JHU Servers ====
 +
 
 +
The primary firewall maintained by JHU IT gets millions of connections going through it at time, so reducing the number of stale connections is important to prevent the networks from becoming overloaded.  Unfortunately, this can cause some issues with SSH connections if they don't see enough activity.  We can prevent this from happening by using the <code>ServerAliveInterval</code> and <code>ServerAliveCountMax</code> parameters.
 +
 
 +
From the [https://linux.die.net/man/5/ssh ssh(5) Man Page]:
 +
 
 +
<blockquote>
 +
;'''ServerAliveCountMax'''
 +
:Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.
 +
 
 +
:The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds. This option applies to protocol version 2 only.
 +
   
 +
;'''ServerAliveInterval'''
 +
:Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server. This option applies to protocol version 2 only.
 +
</blockquote>
 +
 
 +
What we're going to do is enable a <code>ServerAliveInterval</code> that sends every 30 seconds and increase the <code>ServerAliveCountMax</code> from 3 to 5 just for a little extra buffer.
 +
 
 +
# Settings for all JHU hosts
 +
Host *.jhu.edu
 +
    ServerAliveInterval 30
 +
    ServerAliveCountMax 5
 +
 
 +
==== Giving a Connection a Nickname ====
 +
 
 +
Lets say you have a number of connections that have some really hard to remember hostnames or that need different kinds of parameters on the same server.  Since the config file is a pattern match of the command line parameter, we can hijack it to specify which server we '''actually''' want to connect to by using <code>HostName</code>.
 +
 
 +
From the [https://linux.die.net/man/5/ssh ssh(5) Man Page]:
 +
 
 +
<blockquote>
 +
;'''HostName'''
 +
:Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. The default is the name given on the command line. Numeric IP addresses are also permitted (both on the command line and in HostName specifications).
 +
</blockquote>
 +
 
 +
Assume we have the following config file:
 +
 
 +
# My Cloud Server
 +
Host thecloud
 +
    HostName mycloudserver42.ny2.us-east.us.americas.major-isp.tld
 +
    Port 2222
 +
    User myclouduser
 +
    IdentityFile ~/.ssh/id_rsa.cloud
 +
 
 +
Now instead of typing this:
 +
 
 +
ssh -p 2222 -i ~/.ssh/id_rsa.cloud myclouduser@mycloudserver42.ny2.us-east.us.americas.major-isp.tld
 +
 
 +
We can type this and it will do the same thing:
 +
 
 +
ssh thecloud
 +
 
 +
== Additional Resources ==
 +
 
 
* [https://linux.die.net/man/1/ssh SSH Man Page]
 
* [https://linux.die.net/man/1/ssh SSH Man Page]
 +
* [[:Category:SSH|SSH Category]] on the CS IT Support Wiki
 +
 +
[[Category:SSH]]

Latest revision as of 13:24, 15 March 2024

From the SSH man page:

ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and UNIX-domain sockets can also be forwarded over the secure channel.

The information provided on this page only covers a small portion of the things you can do with SSH and it is recommended that you read more about it via the man page or from other sources.

Required Client Software

Linux/Unix/macOS

OpenSSH is typically packaged with most Unix and Linux variants, which includes macOS. You can verify that ssh is installed by opening a terminal and running the following command:

ssh -V

Windows

Since April of 2018, SSH (OpenSSH) comes pre-installed in Microsoft Windows 10 and above and can be used via the command line either by using the CMD shell or Powershell. More information can be found at Microsoft's OpenSSH in Windows page.

You also have the option to run a 3rd party product called PuTTY. However, PuTTY uses different configurations for SSH Keys, X-Forwarding, etc. so, you'll need to find documentation for those items online. The information you see below is specifically for OpenSSH, not PuTTY.

Using SSH

Connecting to a Remote System

For most of your connection needs in the CS Department, once you have confirmed that an SSH client is installed on your system, you can create a basic connection to a remote CS Linux client using the following syntax:

ssh username@server.host.name

Note: When typing your password, nothing will appear in the terminal. If you think you mistyped your password, you can press Ctrl+U to clear the input and try again.

For example, to connect to one of our Ugrad Linux clients, say, ugrad5, and your username on that system is ckent1, simply use:

ssh ckent1@ugrad5.cs.jhu.edu

Using an Alternate Port

The default connection port for SSH is TCP port 22, but sometimes you'll need to use an alternate port for any number of reasons. To do this, you can use the -p parameter. For example, if you need to connect on TCP port 2096:

ssh -p 2096 username@server.host.name

Connecting with Key-Based Authentication

A very common authentication method built into SSH is key-based authentication. Instead of using a password to authenticate, a server may pre-authenticate a client by installing a public key. This system is far more secure than basic password authentication and is available on all CS Linux clients.

For more information, please see our Accessing Linux Clients with SSH Public Key Authentication page.

X11 Forwarding

SSH isn't just for running remote terminal sessions. It can also be used to run GUI applications remotely. You can do this using a system called X11 Forwarding.

Required Client Software for X11 Forwarding

Linux

If you're running a GUI on Linux, you probably already have X installed. You can verify with the following command:

Xorg -version
Windows

For X forwarding to work properly on Microsoft Windows, you will need to install an X window server, for example, a program like VcXsrv.

We don't directly support software installation on personal computers, but we'll note that when using VcXsrv on Windows 10 and 11:

  • ssh -X might not work properly; ssh -Y might work instead. Note that -Y is slightly less secure. You can read the man pages for the full details, but using -Y causes the X server (on your desktop) to trust the remote system slightly more, which opens it up to some possible-if-unlikely attack vectors. The problem with using -X appears to be related to the use of xauth on the Windows computer. Interested parties are encouraged to read the VcXsrv and OpenSSH documentation to sort out the right configuration to use.
  • You need to set the $DISPLAY environment variable before running the command-line OpenSSH client. In PowerShell, that can be done with $env:DISPLAY = "localhost:0" (or whichever display number VcXsrv is using, if it's not ":0").
macOS

Even though macOS is technically running a variation of X, you won't be able to use it for standard X applications like SSH. In order to accomplish this, you can install XQuartz.

Using X11 Forwarding

In order to enable X11 forwarding in your SSH connection, you will need to use the -X parameter:

ssh -X username@server.host.name

Once the session is established, you should be able to invoke any GUI application simply by executing the command.

Port Forwarding

SSH has the ability to forward TCP traffic over the connection to enable the client to connect to resources on the remote system or vice versa.

Local Port Forwarding

If you want to connect to a service that is only accessible via the server you're connecting to, but want to be able to access it on your local PC, you can accomplish this using a local port forward using the -L parameter.

ssh -L local_port:remote_hostname:remote_port username@server.host.name

Let's assume the server you're connecting to has access to a MySQL server that only accepts connections on port 3389 from your server, but you want to be able to use the management tool on your laptop to be able to make a change to the database. You can run the following command:

ssh -L 3390:mysql.remote.host:3389 username@server.host.name

This will open a local socket on TCP port 3390 and forward all traffic to remote socket on the SSH server. If you point your mysql tool to port 3390 on 127.0.0.1, the SSH server will attempt to connect to mysql.remote.host on TCP port 3389 and forward all traffic back through the tunnel to your client.

Remote Port Forwarding

If you have a local service that you want the server to be able to access, you can accomplish this using the -R parameter to invoke a remote port forward.

ssh -R remote_port:local_hostname:local_port username@server.host.name

Let's say you're trying to download the latest version of nmap on your server, but the domain is blocked by the network security team. You can allow the server to connect through your own connection instead by using the following command:

ssh -R 8080:insecure.org:80 username@server.host.name

On the server, you can now connect to port 8080 on 127.0.0.1, which will allow you download your software.

Dynamic Port Forwarding

In the event that there are a bunch of resources you need that are only available on the server's network, you can create a dynamic port forward using the -D flag:

ssh -D local_port username@server.host.name

This will create a SOCKS5 proxy on the local port specified to be able to filter traffic through the server. This is a great way to create a very simple VPN.

Configuring SSH

There are a lot of parameters you can set for your SSH connections, and remembering them can be a chore. Fortunately there is an easy way to do this with SSH's client configuration file.

Setup

Typically the file can be found at ~/.ssh/config. If you'd like to save it in another location or have different config files, you can specify which to use with the -F flag:

ssh -F /path/to/config username@server.host.name

If the file does not already exist, you can safely create it. Just make sure to set the appropriate permissions on the file. The .ssh directory should be be set to Read, Write, and Enter for the owner only, and any config files should be set to Read and Write for the owner only:

mkdir ~/.ssh
touch ~/.ssh/config
chmod 0700 ~/.ssh/
chmod 0600 ~/.ssh/config

Configuration

The SSH config file has a relatively straightforward syntax:

# Comments are prefixed with a hash
Host hostname
    ParameterName Value

Each Host line is followed by the settings for that host. You can specify settings for multiple hosts with a new Host line. For example:

# Server 1
Host server1.host.name
    ParameterName Value

# Server 2
Host server2.host.name
    ParameterName Value

When you connect to a host, SSH will scan the config file to determine if there is a matching Host entry for the server you're attempting to connect to. This allows us to use a wildcard character (*) in this field for pattern matching. For example:

# Default settings for any systems we connect to at jhu.edu:
Host *.jhu.edu
    Parameter1 Value

# Default settings for all hosts we connect to:
Host *
    Parameter2 Value

Note: If multiple patterns match a host, the settings will stack. In this case, any host matching Host *.jhu.edu also matches Host *, so the settings from both will apply. If the same parameter is set in different matching Host sections, the first one in the file will be the one that takes effect.

You can find a list of all parameters available in the ssh(5) Man Page.

Useful Examples

Preventing Disconnects on JHU Servers

The primary firewall maintained by JHU IT gets millions of connections going through it at time, so reducing the number of stale connections is important to prevent the networks from becoming overloaded. Unfortunately, this can cause some issues with SSH connections if they don't see enough activity. We can prevent this from happening by using the ServerAliveInterval and ServerAliveCountMax parameters.

From the ssh(5) Man Page:

ServerAliveCountMax
Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.
The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds. This option applies to protocol version 2 only.
ServerAliveInterval
Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server. This option applies to protocol version 2 only.

What we're going to do is enable a ServerAliveInterval that sends every 30 seconds and increase the ServerAliveCountMax from 3 to 5 just for a little extra buffer.

# Settings for all JHU hosts
Host *.jhu.edu
    ServerAliveInterval 30
    ServerAliveCountMax 5

Giving a Connection a Nickname

Lets say you have a number of connections that have some really hard to remember hostnames or that need different kinds of parameters on the same server. Since the config file is a pattern match of the command line parameter, we can hijack it to specify which server we actually want to connect to by using HostName.

From the ssh(5) Man Page:

HostName
Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. The default is the name given on the command line. Numeric IP addresses are also permitted (both on the command line and in HostName specifications).

Assume we have the following config file:

# My Cloud Server
Host thecloud
    HostName mycloudserver42.ny2.us-east.us.americas.major-isp.tld
    Port 2222
    User myclouduser
    IdentityFile ~/.ssh/id_rsa.cloud

Now instead of typing this:

ssh -p 2222 -i ~/.ssh/id_rsa.cloud myclouduser@mycloudserver42.ny2.us-east.us.americas.major-isp.tld

We can type this and it will do the same thing:

ssh thecloud

Additional Resources