Practical tips, examples, and SSH tunnels

Original author: Hacker Target
  • Transfer
  • Tutorial

Practical examples of SSH that will bring your remote system administrator skills to a new level. Teams and tips will help not only use SSH, but also more competently navigate the network.

Knowledge of a few tricks sshis useful to any system administrator, network engineer or security specialist.

Case Studies SSH

  1. Ssh socks proxy
  2. SSH tunnel (port forwarding)
  3. SSH tunnel to the third host
  4. Reverse ssh tunnel
  5. SSH reverse proxy
  6. Installing VPN over SSH
  7. Copying SSH key (ssh-copy-id)
  8. Remote command execution (non-interactive)
  9. Remote packet capture and viewing in Wireshark
  10. Copy local folder to remote server via SSH
  11. Remote GUI Applications with SSH X11 Redirection
  12. Remote file copying using rsync and ssh
  13. SSH over the Tor network
  14. SSH to EC2 instance
  15. Editing text files using VIM via ssh / scp
  16. Mounting Remote SSH as a Local Folder with SSHFS
  17. SSH Multiplexing with ControlPath
  18. Streaming video over SSH using VLC and SFTP
  19. Two-factor authentication
  20. Jumps on hosts with SSH and -J
  21. Blocking SSH brute-force attempts using iptables
  22. SSH Escape to change port forwarding

First basics

SSH command line parsing

The following example uses common parameters that are often encountered when connecting to a remote server SSH.

localhost:~$ ssh -v -p 22 -C neo@remoteserver

  • -v: debugging output is especially useful when analyzing authentication problems. Can be used several times to display additional information.
  • - p 22: Port for connecting to a remote SSH server. 22 is not necessary to specify, because this is the default value, but if the protocol is on some other port, then we specify it with the help of the parameter -p. Port listening indicated in the file sshd_configformat Port 2222.
  • -C: compression for the connection. If you have a slow channel or you are viewing a lot of text, it can speed up the connection.
  • neo@: the line in front of the @ symbol indicates the user name for authentication on the remote server. If you do not specify it, the default will be the username of the account you are currently logged in to (~ $ whoami). The user can also be specified by parameter -l.
  • remoteserver: the name of the host to which it is connected ssh, it can be a fully qualified domain name, an IP address or any host in the local hosts file. To connect to a host that supports both IPv4 and IPv6, you can add a parameter to the command line -4or -6for proper resolution.

All of the above parameters are optional, except remoteserver.

Using a configuration file

Although many are familiar with the file sshd_config, there is also a client configuration file for the command ssh. The default value ~/.ssh/config, but it can be defined as a parameter for the option -F.

Host *
     Port 2222
Host remoteserver
     User neo
     Port 2112
     IdentityFile /home/test/.ssh/remoteserver.private_key

In the sample ssh configuration file above, there are two host entries. The first one denotes all the hosts, the Port 2222 configuration parameter is used for all. The second one says that for the remoteserver host you should use a different username, port, FQDN and IdentityFile.

The configuration file can save a lot of time on entering characters, allowing you to automatically apply an advanced configuration when connecting to specific hosts.

Copying Files over SSH with SCP

The SSH client comes with two other very handy tools for copying files over an encrypted ssh connection . See below for an example of the standard use of the scp and sftp commands. Note that many of the parameters for ssh apply to these commands.

localhost:~$ scp mypic.png neo@remoteserver:/media/data/mypic_2.png

In this example, the file mypic.png is copied to remoteserver in the folder / media / data and renamed to mypic_2.png .

Do not forget about the difference in the port parameter. On this come across many who run scpfrom the command line. Here is the port parameter -P, not -p, as in the ssh client! You will forget, but don't worry, everyone will forget.

For those familiar with the console ftp, many of the commands are similar in sftp. You can push , put, and ls as your heart desires.

sftp neo@remoteserver

Practical examples

In many of these examples, you can achieve results using different methods. As in all our textbooks and examples, preference is given to practical examples that simply do their job.

1. SSH socks proxy

The SSH Proxy feature is number 1 for a good reason. It is more powerful than many people assume, and gives you access to any system that a remote server has access to using almost any application. The ssh client can tunnel traffic through a SOCKS proxy with one simple command. It is important to understand that traffic to remote systems will come from a remote server, as will be indicated in the logs of the web server.

localhost:~$ ssh -D 8888 user@remoteserver
localhost:~$ netstat -pan | grep 8888
tcp        0      0*               LISTEN      23880/ssh

Here we run a socks proxy on TCP port 8888, the second command checks that the port is active in listening mode. indicates that the service works only on localhost. We can use a slightly different command to listen on all interfaces, including ethernet or wifi, this will allow other applications (browsers, etc.) in our network to connect to the proxy service via ssh socks proxy.

localhost:~$ ssh -D user@remoteserver

Now we can configure the browser to connect to socks-proxy. In Firefox, select Settings | Basic | Network settings . Specify the IP address and port to connect to.

Pay attention to the option at the bottom of the form so that the browser's DNS requests also go through the SOCKS proxy. If you are using a proxy server to encrypt web traffic on the local network, then you probably want to select this option so that the DNS requests are tunneled over an SSH connection.

Activation of socks-proxy in Chrome

Running Chrome with certain command-line options activates socks proxies, as well as tunneling DNS requests from the browser. Trust but check. Use tcpdump to verify that DNS queries are no longer visible.

localhost:~$ google-chrome --proxy-server="socks5://"

Using other applications with proxies

Keep in mind that many other applications can also use socks-proxies. A web browser is simply the most popular one. Some applications have configuration options for activating the proxy server. Others need a little help with an ancillary program. For example, proxychains allow you to run through Microsoft socks-proxy RDP, etc.

localhost:~$ proxychains rdesktop $RemoteWindowsServer

Socks-proxy configuration parameters are specified in the proxychains configuration file.

Hint: if using remote desktop from linux to windows? Try the FreeRDP client . This is a more modern implementation than rdesktopwith a much smoother interaction.

The option of using SSH through socks-proxy

You are sitting in a cafe or hotel - and you have to use rather unreliable WiFi. From a laptop, locally start ssh-proxy and set up an ssh-tunnel to the home network on the local Rasberry Pi. Using a browser or other applications configured for socks-proxy, we can access any network services in our home network or access the Internet through a home connection. Everything between your laptop and your home server (via Wi-Fi and the Internet to your home) is encrypted in the SSH tunnel.

2. SSH Tunnel (Port Forwarding)

In its simplest form, an SSH tunnel simply opens a port on your local system that connects to another port on the other end of the tunnel.

localhost:~$ ssh  -L 9999: user@remoteserver

Let's sort the parameter -L. It can be thought of as the local listening side. Thus, in the example above, port 9999 is tapped on the localhost side and redirected via port 80 to remoteserver. Please note that refers to localhost on a remote server!

We will rise on the step. In the following example, the listening ports are connected to other nodes on the local network.

localhost:~$ ssh  -L user@remoteserver

In these examples, we connect to a port on a web server, but this can be a proxy server or any other TCP service.

3. SSH tunnel to a third-party host

We can use the same parameters to connect the tunnel from a remote server to another service running on a third system.

localhost:~$ ssh  -L user@remoteserver

In this example, we are redirecting the tunnel from the remoteserver to the web server running on Traffic from remoteserver to is no longer in the SSH tunnel . The web server on will consider the remoteserver source of web requests.

4. Reverse ssh tunnel

Here we set up a listening port on a remote server that will connect back to the local port on our localhost (or another system).

localhost:~$ ssh -v -R user@remoteserver

In this SSH session, a connection is established from port 1999 on the remoteserver to port 902 on our local client.

5. Reverse SSH Proxy

In this case, we set up a socks proxy on our ssh connection, but the proxy listens at the remote end of the server. Connections to this remote proxy now appear from the tunnel as traffic from our localhost.

localhost:~$ ssh -v -R user@remoteserver

Troubleshooting problems with remote SSH tunnels

If you have problems with the operation of remote SSH options, check with netstatwhat other interfaces the listening port is connected to. Although we specified in the examples, but if the value of GatewayPorts in sshd_config is set to no , then the listener will be bound to localhost ( only.

Safety warning

Please note that when opening tunnels and socks-proxies, internal network resources may be accessed by unreliable networks (for example, the Internet!). This can be a serious security threat, so make sure you understand what the listener is and what it has access to.

6. Installing VPN over SSH

The general term among experts on attack methods (pentesters, etc.) is “the point of support in the network”. After establishing a connection in one system, this system becomes a gateway for further access to the network. The fulcrum that allows you to move in breadth.

For such a foothold, we can use SSH proxies and proxychains , however there are some limitations. For example, it will not be possible to work directly with sockets, so we will not be able to scan ports inside the network through NmapSYN .

Using this more advanced VPN option, the connection drops to level 3 . Then we can simply send traffic through the tunnel using standard network routing.

The method uses ssh, iptables, tun interfacesand routing.

You must first set these parameters in sshd_config. Since we are making changes to the interfaces of both the remote and client systems, we need root rights on both sides .

PermitRootLogin yes
PermitTunnel yes

Then we establish an ssh connection using the parameter that requests the initialization of tun devices.

localhost:~# ssh -v -w any root@remoteserver

Now we should have a tun device when showing interfaces ( # ip a). The next step is to add IP addresses to the tunnel interfaces.

SSH client side:

localhost:~# ip addr add peer dev tun0
localhost:~# ip tun0 up

SSH server side:

remoteserver:~# ip addr add peer dev tun0
remoteserver:~# ip tun0 up

We now have a direct route to another host ( route -nand ping

You can route any subnet through a host on the other side.

localhost:~# route add -net netmask dev tun0

On the remote side, you must turn on ip_forwardand iptables.

remoteserver:~# echo 1 > /proc/sys/net/ipv4/ip_forward
remoteserver:~# iptables -t nat -A POSTROUTING -s -o enp7s0 -j MASQUERADE

Boom! VPN over SSH tunnel at network level 3 . This is already a victory.

If there are any problems, use tcpdump and pingto establish the cause. Since we are playing at level 3, our icmp packages will go through this tunnel.

7. Copying an SSH key (ssh-copy-id)

There are several ways, but this command saves time, so as not to copy files manually. It simply copies ~ / .ssh / (or the default key) from your system to ~/.ssh/authorized_keysthe remote server.

localhost:~$ ssh-copy-id user@remoteserver

8. Remote command execution (non-interactive)

The command sshcan be associated with other commands for a normal user-friendly interface. Just add the command you want to run on the remote host as the last parameter in quotes.

localhost:~$ ssh remoteserver "cat /var/log/nginx/access.log" | grep badstuff.php

In this example, it grepis executed on the local system after the log has been downloaded via the ssh channel. If the file is large, it is more convenient to run grepon the remote side simply by enclosing both commands in double quotes.

Another example performs the same function as ssh-copy-idin example 7.

localhost:~$ cat ~/.ssh/ | ssh remoteserver 'cat >> .ssh/authorized_keys'

9. Remote packet capture and viewing in Wireshark

I took one of our tcpdump examples . Use it to remotely intercept packets and output the result directly to the local Wireshark GUI.

:~$ ssh root@remoteserver 'tcpdump -c 1000 -nn -w - not port 22' | wireshark -k -i -

10. Copying a local folder to a remote server via SSH

A beautiful trick that compresses a folder with bzip2(this is the -j parameter in the command tar) and then extracts the stream bzip2on the other side, creating a duplicate folder on the remote server.

localhost:~$ tar -cvj /datafolder | ssh remoteserver "tar -xj -C /datafolder"

11. Remote GUI Applications with SSH X11 Redirection

If “X's” are installed on the client and the remote server, then you can remotely execute the GUI command, with a window on your local desktop. This feature exists a long time ago, but is still very useful. Launch a remote web browser or even a VMWawre Workstation console, as I do in this example.

localhost:~$ ssh -X remoteserver vmware

Requires a line X11Forwarding yesin the file sshd_config.

12. Remote file copying with rsync and SSH

rsyncIn many ways, it is more convenient scpif periodic backup of a directory, a large number of files or very large files is required. There is a recovery function after the failure of the transfer and copy only the modified files, which saves traffic and time.

This example uses compression gzip(-z) and archive mode (-a), which includes recursive copying.

:~$ rsync -az /home/testuser/data remoteserver:backup/

13. SSH over the Tor network

An anonymous Tor network can tunnel SSH traffic using a command torsocks. The following command will proxy ssh-proxy through Tor.

localhost:~$ torsocks ssh myuntracableuser@remoteserver

Torsocks will use proxy port 9050 on localhost. As always, when using Tor, you need to seriously check what traffic is being tunneled and other operational security issues (opsec). Where do your DNS queries go?

14. SSH to EC2 instance

To connect to an EC2 instance, you need a private key. Download it (.pem extension) from the Amazon EC2 control panel and change permissions ( chmod 400 my-ec2-ssh-key.pem). Keep the key in a safe place or place it in your folder ~/.ssh/.

localhost:~$ ssh -i ~/.ssh/my-ec2-key.pem ubuntu@my-ec2-public

The -i option simply tells the ssh client to use this switch. The file is ~/.ssh/configideal for automatically configuring key usage when connected to the ec2 host.

Host my-ec2-public
   Hostname ec2???
   User ubuntu
   IdentityFile ~/.ssh/my-ec2-key.pem

15. Editing text files using VIM via ssh / scp

For all lovers, vimthis advice will save some time. With the help of vimfiles are edited for scp one command. This method simply creates the file locally in /tmp, and then copies it back as soon as we save it from vim.

localhost:~$ vim scp://user@remoteserver//etc/hosts

Note: The format is slightly different from the usual scp. After the host we have a double //. This is a link to an absolute path. One slash will be the path relative to the home folder users.

**warning** (netrw) cannot determine method (format: protocol://[user@]hostname[:port]/[path])

If you see such an error, double check the format of the command. This usually means a syntax error.

16. Mounting Remote SSH as a Local Folder with SSHFS

With the help of sshfs- the file system client ssh- we can connect the local directory to a remote location with all file interactions in an encrypted session ssh.

localhost:~$ apt install sshfs

On Ubuntu and Debian, install the package sshfs, and then simply accept the remote location to our system.

localhost:~$ sshfs user@remoteserver:/media/data ~/data/

17. SSH Multiplexing with ControlPath

By default, if there is an existing connection to a remote server using a sshsecond connection using sshor scpestablishing a new session with additional authentication. The option ControlPathallows you to use an existing session for all subsequent connections. This will significantly speed up the process: the effect is noticeable even in the local network, and even more so when connected to remote resources.

Host remoteserver
        ControlMaster auto
        ControlPath ~/.ssh/control/%r@%h:%p
        ControlPersist 10m

ControlPath specifies the socket to check for new connections for the presence of an active session ssh. The last option means that even after logging out of the console, the existing session will remain open for 10 minutes, so during this time you will be able to reconnect over the existing socket. See help for more information ssh_config man.

18. Streaming video over SSH using VLC and SFTP

Even long-time users sshand vlc(Video Lan Client) do not always know about this convenient option when you really need to watch videos over the network. In the settings File | Open Network Stream program vlccan enter location as sftp://. If a password is required, a prompt will appear.


19. Two-factor authentication

The same two-factor authentication as your bank account or Google account applies to the SSH service.

Of course, sshinitially it has a two-factor authentication function, which means a password and an SSH key. The advantage of a hardware token or Google Authenticator application is that it is usually a different physical device.

See our 8-minute guide to using Google Authenticator and SSH .

20. Jumping to hosts with ssh and -J

If, because of network segmentation, you have to go through several ssh hosts to get to the destination destination network, you will save time with the -J shortcut.

localhost:~$ ssh -J host1,host2,host3 user@host4.internal

The main thing here is to understand that this is not similar to the command ssh host1, then user@host1:~$ ssh host2, etc. The -J parameter cunningly uses redirection so that localhost establishes a session with the next host in the chain. Thus, in the example above, our localhost is authenticated to host4. That is, our localhost keys are used, and the session from localhost to host4 is fully encrypted.

To do this, ssh_configspecify the ProxyJump configuration option . If you regularly have to go through several hosts, then automation through the config will save a lot of time.

21. Blocking SSH brute-force attempts using iptables

Anyone who ran the SSH service and looked through the logs knows about the number of bruteforce attempts that occur every hour every day. A quick way to reduce noise in the logs is to transfer SSH to a non-standard port. Modify the file sshd_configusing the Port ## configuration parameter .

With the help, iptablestoo, you can easily block attempts to connect to the port upon reaching a certain threshold. A simple way to do this is to use OSSEC , since it not only blocks SSH, but also performs a bunch of other intrusion detection measures based on the host name (HIDS).

22. SSH Escape to change port forwarding

And our last example is sshintended to change the port forwarding on the fly within an existing session ssh. Imagine such a scenario. You are deep in the net; you may have jumped through half a dozen hosts and you need a local port on the workstation, which is redirected to the Microsoft SMB of the old Windows 2003 system (does anyone remember ms08-67?).

By clicking enter, try typing in the console ~C. This is a control sequence in a session that allows you to make changes to an existing connection.

localhost:~$ ~C
ssh> -h
      -L[bind_address:]port:host:hostport    Request local forward
      -R[bind_address:]port:host:hostport    Request remote forward
      -D[bind_address:]port                  Request dynamic forward
      -KL[bind_address:]port                 Cancel local forward
      -KR[bind_address:]port                 Cancel remote forward
      -KD[bind_address:]port                 Cancel dynamic forward
ssh> -L 1445:remote-win2k3:445
Forwarding port.

Here you can see that we have redirected our local port 1445 to the Windows 2003 host, which we found on the internal network. Now just run msfconsole, and you can go on (assuming that you plan to use this host).


These examples, tips and commands sshshould give a starting point; More information about each of the commands and features available on the help pages ( man ssh, man ssh_config, man sshd_config).

I have always been fascinated by the ability to access systems and execute commands anywhere in the world. Developing your skills in working with tools like sshyou will become more effective in any game you play.

Also popular now: