SSH - tips, examples and tunnels

Hands-on SSH examples that will take your remote sysadmin skills to the next level. Commands and tips will help not only to use SSH, but also to navigate the network more competently. Knowing a few ssh tricks is useful for any sysadmin, network engineer, or security professional.

On this page

First the basics

SSH command line parsing

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

1localhost:~$ ssh -v -p 22 -C neo@remoteserver
  • v: displaying debugging information is particularly useful when analyzing authentication problems. Can be used multiple times to display additional information.

  • p 22: port to connect to the remote SSH server. 22 is not necessary to specify, because it is the default value, but if the protocol is on some other port, then we specify it using the -p parameter. The listening port is specified in the sshd_config file in the format Port 2222.

  • C: Compression for connection. If you have a slow channel or browse a lot of text, this can speed up the connection.

  • neo@: the string before the @ symbol represents the username for authentication on the remote server. If not specified, it will default to the username of the account you’re currently logged in to (~$whoami). The user can also be specified as a parameter -l.

  • remoteserver: the name of the host to ssh to, this can be a fully qualified domain name, an IP address, or any host in a local file hosts. To connect to a host that supports IPv4 and IPv6, you can add the -4 or -6 option to the command line for correct resolution.

All the listed parameters are optional except remoteserver.

Using a configuration file

Although many are familiar with the sshd_config file, there is also a client configuration file for the ssh command. Defaults to ~/.ssh/config, but can be specified as an option parameter -F.

1Host *
2     Port 2222
3
4Host remoteserver
5     HostName remoteserver.thematrix.io
6     User neo
7     Port 2112
8     IdentityFile /home/test/.ssh/remoteserver.private_key

In the example ssh configuration file above, there are two host entries.

  • The first indicates all hosts, the Port 2222 configuration parameter is applied to all.
  • The second says that a different username, port, FQDN and IdentityFile should be used from the remoteserver host.

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

Copying SSH files using SCP

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

1localhost:~$ 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 mypic_2.png. Don’t forget the difference in the port setting. This happens to many who run scp from the command line. Here the port parameter is –P, not –p as in ssh-клієнті!

For those familiar with console ftp, many of the commands are similar to sftp. You can do push, put and ls.

sftp neo@remoteserver

Practical examples

Many of these examples can be achieved using different methods. As with all our tutorials and examples, the preference is for practical examples that just do the trick.

«««< HEAD

SSH socks proxy

=======

SSH socks-проксі

67d4dd7 (v4)

The SSH Proxy feature is number 1 for good reason. It is more powerful than many realize and gives you access to any system that the remote server can access, using almost any program. 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 originate from the remote server, as will be indicated in the web server logs.

1localhost:~$ ssh -D 8888 user@remoteserver
2
3localhost:~$ netstat -pan | grep 8888
4tcp        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 only running on localhost. We can apply a slightly different command to listen on all interfaces, including ethernet or wifi, this will allow other programs (browsers, etc.) on our network to connect to the proxy service via ssh socks-proxy

1localhost:~$ 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 | Basic | Network settings. Specify the IP address and port to connect to

socks-проксі port 8888

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

Activation of socks proxy in Chrome

Running Chrome with certain command line options activates the socks proxy and tunnels DNS queries from the browser. Use tcpdump to check if DNS queries are no longer visible.

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

Using other programs with a proxy

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

1localhost:~$ proxychains rdesktop $RemoteWindowsServer

The socks-proxy configuration parameters are specified in the proxychains configuration file.

Tip: If you’re using Linux Remote Desktop on Windows? Try the FreeRDP client. This is a more modern implementation than rdesktop, with a much smoother interaction.

An option to use SSH through socks-proxy

You are sitting in a cafe or hotel and are forced to use rather unreliable WiFi. We run the ssh-proxy locally from the laptop and establish 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 on our home network or access the Internet through a home connection. Everything between your laptop and your home server (via Wi-Fi and home internet) is encrypted in an SSH tunnel.

«««< HEAD

SSH tunnel (port forwarding)

=======

Тунель SSH (переадресація портів)

67d4dd7 (v4)

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

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

Let’s analyze the -L parameter. It can be served as a local listening party. Thus, in the example above, port 9999 is listened on the localhost side and forwarded through 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 this example, listening ports communicate with other nodes on the local network.

1localhost:~$ 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.

SSH tunnel to a third-party host

«««< HEAD We can use the parameters themselves to tunnel from a remote server to another service running on a third system.

SSH-тунель на сторонній хост

Ми можемо використовувати самі параметри для підключення тунелю з віддаленого сервера до іншої служби, запущеної на третій системі.

67d4dd7 (v4)

1localhost:~$ 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 the remoteserver to 10.10.10.10 is not in the SSH tunnel. A web server on 10.10.10.10 will consider remoteserver as the source of web requests.

«««< HEAD

Reverse SSH tunnel

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

Зворотній SSH-тунель

Тут налаштуємо порт, що прослуховує, на віддаленому сервері, який буде підключатися назад до локального порту на нашому localhost (або іншій системі).

67d4dd7 (v4) ‘‘‘bash 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.

<<<<<<< HEAD
### SSH reverse proxy
In this case, we are setting up a socks proxy on our ssh connection, but the proxy is listening on the remote end of the server.
Connections to this remote proxy now appear from the tunnel as traffic from our localhost.
=======
### Зворотній проксі SSH
У цьому випадку ми встановлюємо socks-проксі на нашому ssh-з'єднанні, проте проксі слухає на віддаленому кінці сервера. 
Підключення до цього дистанційного проксі тепер з'являються з тунелю як трафік з нашого localhost.
>>>>>>> 67d4dd7 (v4)
```bash
localhost:~$ ssh -v -R 0.0.0.0:1999 192.168.1.100 user@remoteserver

Troubleshooting problems with remote SSH tunnels

If you’re having trouble with remote SSH options, use netstat to check which interfaces the listening port is connected to. Although we specified 0.0.0.0 in the examples, but if GatewayPorts value in sshd_config is set to no, then the listener will be bound only to localhost (127.0.0.1).

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

«««< HEAD

Setting up a VPN over SSH

A common term among experts on attack methods (pentesters, etc.) - This is a “support point in the network.” Once a connection is established in one system, that system becomes a gateway for further access to the network. A fulcrum that allows for lateral movement.

Встановлення VPN по SSH

Загальний термін серед спеців за методами атаки (пентестери та ін.) - Це «точка опори в мережі». Після встановлення з’єднання в одній системі ця система стає шлюзом для подальшого доступу до мережі. Точка опори, що дозволяє рухатися вшир.

67d4dd7 (v4)

For such a foothold, we can use SSH proxies and proxychains, but 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 Nmap SYN.

Using this more advanced VPN option drops the connection down to level 3. We can then simply route the 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 both the remote and client interfaces, we need root privileges on both sides.

1PermitRootLogin yes
2PermitTunnel yes

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

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

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

SSH client side:

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

SSH server side:

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

Now we have a direct route to another host (route -n and ping 10.10.10.10). Any subnet can be routed through a host on the other side.

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

On the remote side, you need to enable ip_forward and iptables.

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

VPN over an SSH tunnel at network layer 3. If problems occur, use tcpdump and ping to determine the cause. Since we are playing at layer 3, our icmp packets will go through this tunnel.

«««< HEAD

SSH key copy (ssh-copy-id)

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

Копіювання ключа SSH (ssh-copy-id)

Тут є кілька способів, але ця команда заощаджує час, щоб не копіювати файли вручну. Вона просто копіює ~/.ssh/id_rsa.pub (або стандартний) з вашої системи в ~/.ssh/authorized_keys на віддаленому сервері.

67d4dd7 (v4)

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

«««< HEAD

Remote execution of commands (not interactive)

The ssh command can be combined with other commands for a convenient interface. Just add the command you want to run on the remote host as the last parameter in quotes.

Дистанційне виконання команд (не інтерактивно)

Команду ssh можна зв’язати з іншими командами для зручного інтерфейсу. Просто додайте команду, яку хочете запустити на віддаленому хості, як останній параметр у лапках.

67d4dd7 (v4)

1localhost:~$ 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.

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

«««< HEAD

Remote packet capture and viewing in Wireshark

Example of tcpdump. Use it to remotely capture packets with output directly in the local Wireshark GUI.

Дистанційне перехоплення пакетів та перегляд у Wireshark

Приклад tcpdump. Використовуйте його для віддаленого перехоплення пакетів з видачею результату безпосередньо у GUI локального Wireshark.

67d4dd7 (v4)

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

«««< HEAD

Copying a local folder to a remote SSH server

A nice trick that compresses a folder with bzip2 (that’s the -j option in the tar command) and then extracts the bzip2 stream on the other side, creating a duplicate folder on the remote server.

Копіювання локальної папки на віддалений сервер SSH

Гарний трюк, який стискає папку за допомогою bzip2 (це параметр -j у команді tar), а потім витягує потік bzip2 з іншого боку, створюючи на віддаленому сервері дублікат папки.

67d4dd7 (v4)

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

«««< HEAD

Remote GUI applications with SSH X11 forwarding

If both the client and the remote server have x’s installed, you can run a GUI command remotely, with a window on your local desktop. This feature has been around for a long time, but is still very useful.

Дистанційні програми GUI з переадресацією SSH X11

Якщо на клієнті та віддаленому сервері встановлені «ікси», можна віддалено виконати команду GUI, з вікном на вашому локальному робочому столі. Ця функція існує давно, але, як і раніше, дуже корисна.

67d4dd7 (v4)

Start a remote web browser or VMWawre Workstation console like I do in this example.

1localhost:~$ ssh -X remoteserver vmware

Requires X11Forwarding yes line in sshd_config file.

«««< HEAD

Copy files remotely using rsync and SSH

rsync is much more convenient than scp if 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 changed files, saving traffic and time.

Дистанційне копіювання файлів за допомогою rsync та SSH

rsync значно зручніше scp, якщо потрібно періодичне резервне копіювання каталогу, великої кількості файлів або дуже великих файлів. Тут є функція відновлення після збою передачі та копіювання лише змінених файлів, що зберігає трафік та час.

67d4dd7 (v4)

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

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

«««< HEAD

SSH through the Tor network

The anonymous Tor network can tunnel SSH traffic using the torsocks command. The following command will wake up the ssh proxy through Tor.

SSH через мержу Tor

Анонімна мережа Tor може тунелювати SSH-трафік за допомогою команди torsocks. Наступна команда прокине ssh-проксі через Tor.

67d4dd7 (v4)

1localhost:~$ torsocks ssh myuntracableuser@remoteserver

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

SSH до інстансу EC2

Для підключення до інстансу EC2 необхідний закритий ключ. Завантажте його (розширення .pem) з панелі керування Amazon EC2 та змініть роздільну здатність (chmod 400 my-ec2-ssh-key.pem). Зберігайте ключ у надійному місці або помістіть його у папку ~/.ssh/.

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

Параметр -i просто вказує на ssh-клієнту використовувати цей ключ. Файл ~/.ssh/config ідеально підходить для автоматичного налаштування використання ключа під час підключення до хоста ec2.

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

Редагування текстових файлів за допомогою VIM через ssh/scp

Для всіх любителів vim ця порада заощадить небагато часу. За допомогою vim файли редагуються через scp однією командою. Цей метод просто створює файл локально /tmp, а потім копіює його назад, як тільки ми його зберегли з vim.

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

Примітка: формат трохи відрізняється від звичайного scp. Після хоста у нас подвійний//. Це посилання абсолютний шлях. Один слеш означатиме шлях щодо домашньої папки users.

Якщо ви побачите таку помилку, двічі перевірте формат команди. Зазвичай це означає синтаксичну помилку.

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

Монтування віддаленого SSH як локальної папки з SSHFS

За допомогою sshfs – клієнта файлової системи ssh – ми можемо підключити локальний каталог до віддаленого розташування зі всіма взаємодіями файлів у зашифрованому сеансі ssh.

На Ubuntu та Debian встановимо пакет sshfs, а потім просто примонтуємо віддалене розташування до нашої системи.

1localhost:~$ apt install sshfs
2
3localhost:~$ sshfs user@remoteserver:/media/data ~/data/

Мультиплексування SSH за допомогою ControlPath

За промовчанням за наявності існуючого підключення до віддаленого сервера за допомогою ssh друге підключення за допомогою ssh або scp встановлює новий сеанс із додатковою автентифікацією.

Опція ControlPath дозволяє використовувати існуючий сеанс для всіх наступних з’єднань. Це значно прискорить процес: ефект помітний навіть у локальній мережі, а тим більше під час підключення до віддалених ресурсів.

ControlPath вказує сокет для перевірки новими з’єднаннями щодо наявності активної сесії ssh. Остання опція означає, що навіть після виходу з консолі існуючий сеанс залишиться відкритим 10 хвилин, тому протягом цього часу ви зможете повторно підключитися по існуючому сокету. Для отримання додаткової інформації дивіться довідку ssh_config man.

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

Потокове відео по SSH за допомогою VLC та SFTP

Навіть давні користувачі ssh і vlc (Video Lan Client) не завжди знають про цю зручну опцію, коли потрібно подивитися відео по мережі. У налаштуваннях File | Open Network Stream програми vlc можна ввести місцезнаходження як sftp://. Якщо потрібно пароль, з’явиться запит.

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

Двофакторна аутентифікація

Така ж двофакторна автентифікація, як у вашого банківського рахунку або облікового запису Google, може бути застосована до сервісу SSH. Звичайно, ssh спочатку має функцію двофакторної аутентифікації, під якою маються на увазі пароль і ключ SSH. Перевага апаратного токена або програми Google Authenticator полягає в тому, що це зазвичай інший фізичний пристрій.

Стрибки по хост з ssh і -J

Якщо через сегментацію мережі доводиться переходити через кілька хостів ssh, щоб дістатися кінцевої мережі призначення, вам заощадить час ярлик -J.

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

Тут головне розуміти, що це не аналогічно команді ssh host1, потім user@host1: ~ $ ssh host2 і т. д.

Параметр -J хитро використовує переадресацію, щоб localhost встановлював сеанс з наступним хостом у ланцюжку. Таким чином, у наведеному вище прикладі наш localhost автентифікується на host4. Тобто використовуються ключі localhost, а сеанс від localhost до host4 повністю зашифрований.

Для цієї можливості в ssh_config вкажіть опцію конфігурації ProxyJump. Якщо регулярно доводиться переходити через кілька хостів, то автоматизація через конфіг заощадить багато часу.

Блокування спроб брутфорсу SSH за допомогою iptables

Будь-хто, хто керував сервісом SSH та переглядав логи, знає про кількість спроб брутфорсу, які відбуваються щогодини щодня. Швидкий спосіб зменшити шум у логах – перенести SSH на нестандартний порт. Змініть файл sshd_config за допомогою параметра конфігурації Port##.

За допомогою iptables також можна легко блокувати спроби підключення до порту після досягнення певного порога. Простий спосіб зробити це – використовувати OSSEC, оскільки він не лише блокує SSH, але виконує купу інших заходів щодо виявлення вторгнень на базі імені хоста (HIDS).

SSH Escape для зміни переадресації портів

І наш останній приклад ssh призначено для зміни переадресації портів на льоту в рамках існуючого сеансу ssh. Уявіть такий сценарій. Ви глибоко в мережі; можливо, стрибнули через півдюжини хостів і вам потрібен локальний порт на робочій станції, який перенаправлений на Microsoft SMB старої системи Windows 2003 (хтось пам’ятає ms08-67?). Натиснувши клавішу enter, спробуйте ввести в консолі ~C. Це керуюча послідовність у сесії, що дозволяє вносити зміни до існуючого з’єднання.

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.

Тут ви можете побачити, що ми переадресували наш локальний порт 1445 на Windows 2003 хост, який знайшли у внутрішній мережі. Тепер просто запустіть msfconsole, і можна йти далі (припускаючи, що ви плануєте використовувати цей хост).