Practical tips, examples, and SSH tunnels

Lord777

Professional
Messages
2,581
Reputation
15
Reaction score
1,322
Points
113
Practical examples of SSH that will take your remote system administrator skills to a new level. Commands and tips will help you not only use SSHit , but also navigate the web more efficiently.

Knowing a few tricks sshis useful for any system administrator, network engineer, or security specialist.

Practical examples of SSH​

  1. SSH socks proxy
  2. SSH Tunnel (Port Forwarding)
  3. SSH tunnel to the third host
  4. Reverse SSH tunnel
  5. Reverse SSH Proxy
  6. Installing a VPN over SSH
  7. Copying the SSH key (ssh-copy-id)
  8. Remote command execution (non-interactive)
  9. Remote packet sniffing and viewing in Wireshark
  10. Copying a local folder to a remote server via SSH
  11. Remote GUI Applications with SSH X11 Forwarding
  12. Remote file copying using rsync and SSH
  13. SSH over the Tor network
  14. SSH to an 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. SSH video streaming using VLC and SFTP
  19. Two-factor authentication
  20. Jumping hosts with SSH and -J
  21. Blocking SSH brute force attempts using iptables
  22. SSH Escape to change port forwarding

First the basics​


Parsing the SSH command line​


The following example uses the usual parameters that are often found when connecting to a remote server SSH.

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

  • -v: debugging information output is particularly useful when analyzing authentication issues. You can use it several times to display additional information.
  • - p 22: port for connecting to a remote SSH server. You don't need to specify 22, because this is the default value, but if the protocol is on some other port, then specify it using the parameter -p. The listening port is specified in the file sshd_configin the format Port 2222.
  • -C: compression for the connection. If your channel is slow or you view a lot of text, this can speed up communication.
  • neo@: the string before the @ character indicates the user name for authentication on the remote server. If you do not specify it, the default username will be the user name of the account you are currently logged in to (~$ whoami). You can also specify the user with a parameter -l.
  • remoteserver: the name of the host it connects to ssh, which can be the fully qualified domain name, 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 or parameter to the command line -4-6for proper resolving.

All of the above parameters are optional, except remoteserver.

Using the configuration file​


Although many people are familiar with the filesshd_config, there is also a client configuration file for the team ssh. The default value~/.ssh/config, but you can define it as a parameter for an option -F.

Code:
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, and the Port 2222 configuration parameter is used for all of them. The second one says that you should use a different username, port, FQDN, and IdentityFile for the remoteserver host.

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

Copying files over SSH using SCP​


The SSH client comes with two other very convenient tools for copying files over an encrypted ssh connection. See below for an example of standard usage of the scp and sftp commands. Note that many parameters for ssh are applied in these commands as well.

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

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

Don't forget about the difference in the port parameter. This brings up many people who run scpfrom the command line. Here is the port parameter-P, not -pas in the ssh client! You'll forget, but don't worry, everyone forgets.

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

Code:
sftp neo@remoteserver

Practical examples​


In many of these examples, you can achieve the result using different methods. As with all our tutorials and examples, the preference is for practical examples that just do the trick.

1. SSH socks proxy​


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

Code:
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 run the socks proxy on TCP port 8888. The second command checks that the port is active in listening mode. 127.0.0.1 indicates that the service is running 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.) on our network to connect to the proxy service via ssh socks proxy.

Code:
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 / General / Network Settings. Specify the IP address and port to connect to.

daaf8b54515ce6eee864c8416d41eef9.png


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 use a proxy server to encrypt web traffic on your local network, you probably want to select this option so that DNS queries are tunneled through an SSH connection.

Activating the socks proxy in Chrome​


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

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

Using other apps with a proxy​


Keep in mind that many other apps can also use socks proxies. The 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 auxiliary program. For example, proxychains allows you to run Microsoft RDP through the socks proxy, etc.

Code:
localhost:~$ proxychains rdesktop $RemoteWindowsServer

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

Hint: If you use remote desktop from Linux to Windows? Try the FreeRDP client. It's a more modern implementation than rdesktopthat, with much smoother interaction.

Option to use SSH via socks proxy​


You are sitting in a cafe or hotel — and you are forced to use a rather unreliable WiFi. From the laptop, locally launch an ssh proxy and install an ssh tunnel to the home network on the local Rasberry Pi. Using a browser or other applications configured for the socks proxy, we can access any network services on our home network or access the Internet via a 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 another port on the other end of the tunnel.

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

Let's analyze the parameter -L. You can think of it as the local listening side. So in the example above, port 9999 is listened on on the localhost side and forwarded via port 80 to the remoteserver. Note that 127.0.0.1 refers to localhost on the remote server!

Let's go up a step. In the following example, listening ports communicate with other nodes on the local network.

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

In these examples, we connect to a port on a web server, but it 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 a tunnel from a remote server to another service running on a third system.

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

In this example, we redirect the tunnel from remoteserver to the web server running on 10.10.10.10. Traffic from remoteserver to 10.10.10.10 is no longer in the 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, which will connect back to the local port on our localhost (or other system).

Code:
localhost:~$ ssh -v -R 0.0.0.0:1999:127.0.0.1:902 192.168.1.100 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 install a socks proxy on our ssh connection, but the proxy listens on the remote end of the server. Connections to this remote proxy now appear from the tunnel as traffic from our localhost.

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

Troubleshooting remote SSH tunnels​


If you have any problems with the remote SSH options, check with netstatwhich other interfaces the listening port is connected to. Although we specified 0.0.0.0 in the examples, if the GatewayPorts value in sshd_config is set to no, the listener will only be bound to localhost (127.0.0.1).

Security Warning​

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

6. Installing a VPN over SSH​


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

We can use SSH proxies and proxychains for this support point, but there are some limitations. For example, you won't be able to work directly with sockets, so we won't be able to scan ports inside the network via Nmap SYN.

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

The method uses ssh,iptables, tun interfacesand routing.

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

Code:
PermitRootLogin yes
PermitTunnel yes

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

Code:
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:

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

SSH Server side:

Code:
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 sping 10.10.10.10).

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

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

On the remote side, you must enable ip_forwardand iptables.

Code:
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 through an SSH tunnel at network layer 3. That's a win.

If you encounter any problems, use tcpdump and pingto determine the cause. Since we are playing at level 3, our icmp packets will go through this tunnel.

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


There are several ways to do this, but this command saves you time so that you don't have to copy files manually. It simply copies ~/. ssh/id_rsa. pub (or the default key) from your system to ~/.ssh/authorized_keysa remote server.

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

8. Remote command execution (non-interactive)​


The command sshcan 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 quotation marks.

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

In this examplegrep, it is executed on the local system after the log was downloaded via the ssh channel. If the file is large, it is more convenient to run grepit on the remote side, simply enclosing both commands in double quotes.

The other example performs the same function as ssh-copy-idin Example 7.

Code:
localhost:~$ cat ~/.ssh/id_rsa.pub | 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 in the local Wireshark GUI.

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

10. Copy 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 extracts the stream bzip2on the other side, creating a duplicate folder on the remote server.

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

11. Remote GUI Applications with SSH X11 forwarding​


If "x" is installed on the client and remote server, 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 it's still very useful. Launch a remote web browser or even the VMWawre Workstation console, as I do in this example.

Code:
localhost:~$ ssh -X remoteserver vmware

Requires a line X11Forwarding yesin the file sshd_config.

12. Remote file copying using rsync and SSH​


rsync in many ways, it is more convenient scpif you need to periodically back up a directory, a large number of files, or very large files. There is a function to recover from a transfer failure and copy only modified files, which saves traffic and time.

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

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

13. SSH over the Tor network​


The anonymous Tor network can tunnel SSH traffic using the command torsocks. The following command will push 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 issues (opsec). Where do your DNS queries go?

14. SSH to an EC2 instance​


To connect to an EC2 instance, you need a private key. Download it (extension .pem) 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/.

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

The-i option simply tells the ssh client to use this key. The file ~/.ssh/configis ideal for automatically configuring key usage when connecting to an ec2 host.

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

15. Editing text files using VIM via ssh/scp​


For all fansvim, this tip will save a little time. With vimscp, files are edited with a single command. This method simply creates the file locally in/tmp, and then copies it back once we've saved it from vim.

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

Note: The format is slightly different from the usual scpone . After the host, we have a double //one . This is a reference to the absolute path. A single slash will indicate the path relative to the home folder users.

Code:
**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​


Using sshfsthe file system clientssh, we can connect a local directory to a remote location with all file interactions in an encrypted session ssh.

Code:
localhost:~$ apt install sshfs

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

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

17. SSH multiplexing with ControlPath​


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

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

ControlPath specifies a socket for checking new connections 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 during this time you can reconnect using the existing socket. For more information, see the help ssh_config man.

18. SSH video streaming using VLC and SFTP​


Even long-time users sshof vlcI (Video Lan Client) do not always know about this convenient option when you really need to watch videos over the network. In the File | Open Network Stream settings of the programvlc, you can enter the location as sftp://. If you need a password, you will be prompted.

Code:
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, sshit initially has a two-factor authentication function, which means a password and an SSH key. The advantage 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 you have to navigate through multiple ssh hosts to get to the final destination network due to network segmentation, the-J shortcut will save you time.

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

The main thing to understand here is that this is not analogous to the commandssh host1, thenuser@host1:~$ ssh host2, etc. The-J option cleverly uses forwarding so that localhost establishes a session with the next host in the chain. So 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.

For this optionssh_config, specify the ProxyJump configuration option in. If you regularly have to go through several hosts, then automation via config will save a lot of time.

21. Blocking SSH brute force attempts using iptables​


Anyone who has managed the SSH service and viewed the logs knows about 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_configusing the Port # # configuration parameter.

iptablesYou can also easily block attempts to connect 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 also performs a bunch of other hostname-based intrusion detection (HIDS) measures.

22. SSH Escape to change port forwarding​


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

After clickingenter, try entering in the console ~C. This is a control sequence in the session that allows you to make changes to an existing connection.

Code:
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 forwarded our local port 1445 to the Windows 2003 host that we found on the internal network. Now just run msfconsoleit and you can move on (assuming that you plan to use this host).

Completion​


These examples, tips, and commands sshshould provide a starting point; additional information about each of the commands and capabilities is available on the help pages (man ssh, man ssh_config, man sshd_config).

I've always been fascinated by the ability to access systems and execute commands anywhere in the world. By developing your skills with toolsssh, you will become more effective in any game you play.

(c) https://habr.com/ru/articles/435546/
 
Top