Practical Tips, Examples, and SSH Tunnels

Practical Tips, Examples, and SSH Tunnels
Practical examples SSHthat will take your skills as a remote system administrator to a new level. Commands and tips will help not only to use SSH, but also navigate the network more intelligently.

Knowing a few tricks ssh useful to any system administrator, network engineer or security professional.

Practical SSH Examples

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

Basics first

SSH Command Line Parsing

The following example uses common options often encountered when connecting to a remote server SSH.

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

  • -v: The debug output is especially useful when analyzing authentication problems. Can be used multiple times to display additional information.
  • - p 22: connection port to a remote SSH server. 22 does not have to be specified, because this is the default value, but if the protocol is on some other port, then we specify it using the parameter -p. The listening port is specified in the file sshd_config in the format Port 2222.
  • -C: compression for connection. If you have a slow channel or view a lot of text, this can speed up the connection.
  • neo@: The line before the @ sign indicates the username to authenticate to the remote server. If you don't specify it, it will default to the username of the account you're currently logged into (~$ whoami). The user can also be specified with the parameter -l.
  • remoteserver: name of the host to connect to 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 the command line parameter -4 or -6 for correct 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. Default value ~/.ssh/config, but it can be defined as a parameter to an option -F.

Host *
     Port 2222

Host remoteserver
     HostName remoteserver.thematrix.io
     User neo
     Port 2112
     IdentityFile /home/test/.ssh/remoteserver.private_key

The example ssh configuration file above has two host entries. The first one indicates all hosts, for all the Port 2222 configuration parameter is applied. The second one says that for the host remoteserver you should use a different username, port, FQDN, and IdentityFile.

A configuration file can save a lot of character typing time by allowing advanced configuration to be applied automatically when connecting to specific hosts.

Copying files over SSH using SCP

The SSH client comes with two other very handy tools for copying files over encrypted ssh connection. Below is an example of a typical use of the scp and sftp commands. Note that many of the options for ssh apply to these commands as well.

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

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

Don't forget about the difference in the port parameter. On this come across many who launch scp from the command line. Here is the port parameter -PAnd not -plike in ssh client! You will forget, but don't worry, everyone forgets.

For those familiar with console ftp, many of the commands are similar in sftp... You can do push, put ΠΈ lsas your heart desires.

sftp neo@remoteserver

Practical examples

In many of these examples, the result can be achieved by different methods. As in all of our textbooks and examples, preference is given to practical examples that just do the trick.

1. SSH socks proxy

The SSH Proxy feature is number 1 for a good reason. It's more powerful than most people think and gives you access to any system that a remote server has access to, using just about any application. An 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 web server logs.

localhost:~$ ssh -D 8888 user@remoteserver

localhost:~$ netstat -pan | grep 8888
tcp        0      0 127.0.0.1:8888       0.0.0.0:*               LISTEN      23880/ssh

Here we start a socks proxy on TCP port 8888, the second command checks that the port is active in listening mode. 127.0.0.1 specifies that the service only runs 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.) on our network to connect to the proxy service via the ssh socks proxy.

localhost:~$ ssh -D 0.0.0.0:8888 user@remoteserver

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

Practical Tips, Examples, and SSH Tunnels

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

Activating socks proxy in Chrome

Launching Chrome with certain command line options will enable the socks proxy as well as tunneling DNS requests from the browser. Trust but check. Use Tcpdump to check that DNS requests are no longer visible.

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

Using other applications with a proxy

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

localhost:~$ proxychains rdesktop $RemoteWindowsServer

The socks proxy configuration parameters are set in the proxychains configuration file.

Hint: if you are using remote desktop from Linux to Windows? Try Client Free RDP. This is a more modern implementation than rdesktop, with much smoother interaction.

Option to use SSH through socks proxy

You are sitting in a cafe or hotel - and are forced to use rather unreliable WiFi. From the laptop, we launch an ssh proxy locally and set up an ssh tunnel to the home network on the local Rasberry Pi. Using a browser or other applications configured for a socks proxy, we can access any network services on our home network or go online through our home connection. Everything between your laptop and your home server (via Wi-Fi and internet to your home) is encrypted in an 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 a different port on the other end of the tunnel.

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

Let's analyze the parameter -L. It can be thought of as the local listening side. Thus, in the example above, port 9999 is listening on the localhost side and forwarded on port 80 to the remoteserver. Note that 127.0.0.1 refers to localhost on the remote server!

Let's go up the stairs. The following example binds listening ports to other hosts on the local network.

localhost:~$ ssh  -L 0.0.0.0:9999:127.0.0.1:80 user@remoteserver

In these examples, we are connecting to a port on the web server, but this could be a proxy server or any other TCP service.

3. SSH tunnel to third party host

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

localhost:~$ ssh  -L 0.0.0.0:9999:10.10.10.10:80 user@remoteserver

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

4. Reverse SSH tunnel

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

localhost:~$ ssh -v -R 0.0.0.0:1999:127.0.0.1:902 192.168.1.100 user@remoteserver

This SSH session establishes a connection from port 1999 on the remoteserver to port 902 on our local client.

5. SSH Reverse Proxy

In this case, we are setting up a socks proxy on our ssh connection, however the proxy is listening on the remote end of the server. Connections to this remote proxy now come out of the tunnel as traffic from our localhost.

localhost:~$ ssh -v -R 0.0.0.0:1999 192.168.1.100 user@remoteserver

Troubleshooting Remote SSH Tunnels

If you're having trouble getting the SSH remote options to work, check with netstat, which other interfaces the listening port is connected to. Although we indicated 0.0.0.0 in the examples, but if the value GatewayPorts Π² sshd_config set to No., then the listener will only be bound to localhost (127.0.0.1).

Security Warning

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

6. Install VPN over SSH

A common term among attackers (pentesters, etc.) is "network fulcrum". Once a connection is established on one system, that system becomes the gateway for further access to the network. A fulcrum that allows you to move in breadth.

For such a foothold, we can use an SSH proxy 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 within the network through Nmap SYN.

Using this more advanced VPN option, the connection drops to 3 level. We can then simply route traffic through the tunnel using standard network routing.

The method uses ssh, iptables, tun interfaces and routing.

First you need to set these parameters in sshd_config. Since we are making changes to the interfaces of both the remote and client systems, we need root permissions on both sides.

PermitRootLogin yes
PermitTunnel yes

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

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

We should now have a tun device when showing interfaces (# ip a). The next step will add IP addresses to the tunnel interfaces.

SSH client side:

localhost:~# ip addr add 10.10.10.2/32 peer 10.10.10.10 dev tun0
localhost:~# ip tun0 up

SSH server side:

remoteserver:~# ip addr add 10.10.10.10/32 peer 10.10.10.2 dev tun0
remoteserver:~# ip tun0 up

Now we have a direct route to another host (route -n ΠΈ ping 10.10.10.10).

It is possible to route any subnet through the host on the other side.

localhost:~# route add -net 10.10.10.0 netmask 255.255.255.0 dev tun0

On the remote side, enable ip_forward ΠΈ iptables.

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

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

If there are any problems, use Tcpdump ΠΈ pingto determine the cause. Since we are playing at layer 3, our icmp packets will go through this tunnel.

7. Copy SSH key (ssh-copy-id)

There are several ways to do this, but this command saves time by not copying the files manually. It simply copies ~/.ssh/id_rsa.pub (or the default key) from your system to ~/.ssh/authorized_keys on a remote server.

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

8. Remote command execution (non-interactive)

The team ssh can be linked to other commands for the usual 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 grep is executed on the local system after the log has been downloaded over the ssh channel. If the file is large, it is more convenient to run grep on the remote side by simply enclosing both commands in double quotes.

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

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

9. Remote Packet Capture and Wireshark View

I took one of our tcpdump examples. Use it to capture packets remotely and return 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 nice trick that compresses a folder with bzip2 (this is the -j option in the command tar) and then fetches the stream bzip2 on 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 forwarding

If both the client and the remote server have "x" installed, then you can remotely execute a GUI command, with a window on your local desktop. This feature has been around for a long time, but is still very useful. Launch a remote web browser or even a VMWawre Workstation console like I do in this example.

localhost:~$ ssh -X remoteserver vmware

String required X11Forwarding yes in file sshd_config.

12. Remote copy files using rsync and SSH

rsync much more convenient scpif you need periodic backup of a directory, a large number of files, or very large files. There is a function to recover from a transfer failure and copy only changed files, which saves traffic and time.

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

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

13. SSH over the Tor network

The anonymous Tor network can tunnel SSH traffic with the command torsocks. The following command will send an ssh proxy through Tor.

localhost:~$ torsocks ssh myuntracableuser@remoteserver

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

14. SSH to EC2 instance

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

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

Parameter -i simply tells the ssh client to use that key. File ~/.ssh/config ideal for automatically configuring key usage when connecting to an ec2 host.

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

15. Edit text files with VIM via ssh/scp

For all lovers vim this tip will save you some time. By using vim files are edited via scp with one command. This method simply creates the file locally in /tmp, and then copies it back once we've saved 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 an absolute path reference. A single slash will mean the path is relative to the home folder users.

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

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

16. Mount remote SSH as a local folder with SSHFS

By means of sshfs - file system client ssh - we can mount a local directory to a remote location with all file interactions in an encrypted session ssh.

localhost:~$ apt install sshfs

Install the package on Ubuntu and Debian sshfs, and then just mount the remote location to our system.

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

17. Multiplexing SSH with ControlPath

By default, if there is an existing connection to a remote server using ssh second connection with ssh or scp establishes a new session with additional authentication. Option ControlPath allows 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
        HostName remoteserver.example.org
        ControlMaster auto
        ControlPath ~/.ssh/control/%r@%h:%p
        ControlPersist 10m

ControlPath specifies the socket for new connections to check for an active session ssh. The last option means that even after you exit the console, the existing session will remain open for 10 minutes, so that you can reconnect on the existing socket during that time. See help for more information. ssh_config man.

18. Stream video over SSH with VLC and SFTP

Even longtime users ssh ΠΈ vlc (Video Lan Client) do not always know about this convenient option when you really need to watch video over the network. In settings file | Open Network Stream Action vlc you can enter the location as sftp://. If a password is required, you will be prompted.

sftp://remoteserver//media/uploads/myvideo.mkv

19. Two-factor authentication

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

Of course, ssh initially has a two-factor authentication function, which means a password and an SSH key. The benefit of a hardware token or Google Authenticator app is that it's usually a different physical device.

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

20. Jumping hosts with ssh and -J

If network segmentation requires you to hop through multiple ssh hosts to get to your final destination network, the -J shortcut will save you time.

localhost:~$ ssh -J host1,host2,host3 [email protected]

The main thing here is to understand that this is not similar to the command ssh host1Then user@host1:~$ ssh host2 and so on. The -J option cleverly uses forwarding to have localhost establish a session with the next host in the chain. So in the example above, our localhost is authenticating to host4. That is, our localhost keys are used, and the session from localhost to host4 is fully encrypted.

For such an opportunity ssh_config specify configuration option ProxyJump. 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 with iptables

Anyone who has managed an SSH service and looked at the logs is aware of the number of brute force attempts that occur every hour of every day. A quick way to reduce log noise is to move SSH to a non-standard port. Make changes to the file sshd_config using a config option Port##.

With iptables you can also easily block connection attempts to a port when a certain threshold is reached. An easy way to do this is to use OSSEC, as it not only blocks SSH, but performs a bunch of other hostname-based intrusion detection (HIDS) measures.

22. SSH Escape to Change Port Forwarding

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

Pressing enter, try typing in console ~C. This is a session escape sequence that allows you to make changes to an existing connection.

localhost:~$ ~C
ssh> -h
Commands:
      -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 forwarded our local port 1445 to a Windows 2003 host we found on the internal network. Now just run msfconsole, and you're good to go (assuming you plan to use this host).

Completion

These examples, tips and commands ssh should give a starting point; Additional information about each of the commands and features is available on the man 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 with tools like ssh you will become more efficient in whatever game you play.

Source: habr.com

Add a comment