Tunneling ssh mac os

SSH-туннель в Mac OS X

С развитием беспроводных технологий, повсеместно появляются точки доступа в Интернет посредством технологии Wi-Fi: на вокзалах и в аэропортах, в кафетериях и кинотеатрах, в гостиницах и даже в маршрутках, пока вы стоите в пробке неподалёку от какого-нибудь посещаемого места. Достаточно лишь достать из сумки MacBook, выбрать сеть с наилучшим сигналом и вот вы снова можете делать то, что вам нравится. Но так ли безопасны все эти точки доступа? Не «прослушивает» ли какой-либо злоумышленник траффик с целью выудить оттуда важную информацию вроде логинов/паролей, номеров кредитных карт да и вообще, вашей приватной информации?

Для начала стоит подумать о том, где взять SSH-доступ. Тут может быть несколько вариантов:

  • установить собственный сервер с настроенным доступом через SSH в каком-нибудь дата-центре;
  • приобрести недорогой тарифный план на хостинге, предоставляющем доступ к серверам по протоколу SSH;
  • приобрести услугу выделенного IP-адреса у своего провайдера и настроить SSH-сервер дома;

Есть и другие варианты. Как бы там ни было, я не буду заострять внимание на способах получения доступа к какому-либо серверу по SSH, а опишу, как создать и использовать SSH-тунель, в том случае, когда у вас уже есть SSH-доступ к другому компьютеру.

Запустите терминал и выполните в нём следующую команду:

Рассмотрим подробнее, что делает эта команда:

ssh — запуск утилиты, осуществляющей работу с SSH-сервером
-N — параметр, отвечающий за то, чтобы команды не транслировались на удалённый сервер
-D 9999 — параметр, указывающий, через какой адрес/порт пробрасывать данные

user_name — ваше имя для соединения на удалённом сервере
server_address — собственно, адрес сервера, через который будет происходить туннелирование

Например, в моём случае это будет выглядеть так:

После того, как вы выполните эту команду, вас попросят ввести пароль, соответствующий указанному в соединении пользователю. Как только вы это сделаете (при условии, что введёте правильный пароль), у вас готов SSH-туннель, и теперь можно указывать системе, чтобы трафик шёл не напрямую, через Wi-Fi-соединение, а через созданное вами безопасное соединение.

Запустите приложение «Системные настройки» и выберите в нём пункт «Сеть«:

В открывшемся окне выберите пункт с вашим беспроводным соединением и нажмите кнопку «Дополнительно«:

В окне дополнительных настроек выберите вкладку «Прокси«, включите пункт «SOCKS-прокси«, в поле адреса и порта впишите настройки: 127.0.0.1 (адрес вашего внутреннего сетевого интерфейса) и 9999 (порт, указанный при создании SSH-туннеля):

Теперь нажмите кнопку «ОК«, затем «Применить» и теперь ваш беспроводной трафик будет идти через SSH-туннель, что не позволит злоумышленникам его перехватить и прочитать.

Чтобы выключить проксирование, вернитесь к настройкам прокси и отключите пункт «SOCKS-прокси«, после чего подтвердите внесённые изменения, а в терминале с включённым туннелем нажмите комбинацию клавиш Ctrl+C, которая остановит выполнение приложения ssh.

Источник

Создание SSH-туннеля в OS X

Хорошо, когда для совершения платежей или передачи какой-то очень важной информации используется защищённое соединение по протоколу HTTPS. Но что делать, если защиты соединения нет, и при этом есть необходимость быть уверенным на 100% в том, что данные, передаваемые через публичные Wi-Fi сети останутся конфидециальными? В этом случае вам поможет организация SSH-туннеля. Всё, что вам потребуется, — SSH-доступ к какому-либо серверу и 5 минут времени.

Выполняем в терминале следующую комманду:

user_name — ваше имя для соединения на удалённом сервере
server_address — собственно, адрес сервера, через который будет происходить туннелирование
После того, как вы выполните эту команду, вас попросят ввести пароль, соответствующий указанному в соединении пользователю. Как только вы это сделаете (при условии, что введёте правильный пароль), у вас готов SSH-туннель, и теперь можно указывать системе, чтобы трафик шёл не напрямую, через Wi-Fi-соединение, а через созданное вами безопасное соединение.
Запустите приложение «Системные настройки» и выберите в нём пункт «Сеть», в открывшемся окне выберите пункт с вашим беспроводным соединением и нажмите кнопку «Дополнительно», в окне дополнительных настроек выберите вкладку «Прокси», включите пункт «SOCKS-прокси», в поле адреса и порта впишите настройки: 127.0.0.1 (адрес вашего внутреннего сетевого интерфейса) и 9999 (порт, указанный при создании SSH-туннеля).
Теперь нажмите кнопку «ОК», затем «Применить» и теперь ваш беспроводной трафик будет идти через SSH-туннель, что не позволит злоумышленникам его перехватить и прочитать.

Чтобы выключить проксирование, вернитесь к настройкам прокси и отключите пункт «SOCKS-прокси», после чего подтвердите внесённые изменения, а в терминале с включённым туннелем нажмите комбинацию клавиш Ctrl+C, которая остановит выполнение приложения ssh.

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Читайте также:  Горячие клавиши при включении windows

Источник

Какой хороший SSH-туннельный клиент для OS X?

Я использовал SSH Tunnel Manager для простой настройки и остановки туннелирования портов по SSH на различные серверы в моей компании. Это избавило меня от боли, связанной с открытием нового окна терминала, которое будет висеть там только ради открытого туннеля.

Это отлично работало (ну вроде), но SSH Tunnel Manager — это приложение PowerPC. С Lion это больше не поддерживается.

Что такое хорошая замена?

SSHTunnel — это бесплатный пользовательский интерфейс на основе какао для управления туннелем SSH. Работает на 10,5 и выше. Он давно не обновлялся, но код там достаточно стабилен. Это работало хорошо для меня в прошлом.

Почему бы просто не использовать SSH Tunnel через встроенный в OSX терминал? .

Запустите SSH туннель

Чтобы запустить SSH-туннель, просто откройте Mac OSX Terminal.app и подключитесь к удаленному серверу через SSH со следующими флагами:

Это запустит наш SSH-туннель через порт 8080 и направит весь трафик (безопасно) через сервер на example.com.

Сидеть в сети

Теперь давайте начнем просматривать веб-страницы, используя новый SSH-туннель (Chrome):

  • Откройте Google Chrome
  • Выберите «Chrome» вверху слева
  • Выберите «Настройки»
  • Выберите «Показать дополнительные настройки…»
  • Выберите «Изменить настройки прокси…»
  • Выберите «SOCKS Proxy»
  • Введите «127.0.0.1»
  • Введите порт ‘8080 ′
  • Сохраните изменения, выбрав «ОК»

Источник

SSH Tunnels

So far in this series of posts on ssh on macOS:

We have learned so far that ssh is a really useful and flexible protocol. It can be used to connect securely to a remote shell, or to transfer files securely.

Rather than providing the shell itself, ssh provides a secure way to transmit data to and from the remote shell. In a similar way, ssh can be used to provide access to other remote services as well.

SSH Tunnels with Two Computers

Access to important services are usually blocked behind a firewall or router. Since ssh , when setup correctly, is quite secure, you can usually get access to a server with ssh even when other protocols are blocked. (Though some administrators move ssh access to a different port than the default 22.)

You can use ssh port forwarding or ‘tunneling’ to gain access to other services through ssh .

Imagine you want to use Screen Sharing to connect to a remote Mac ( remote.example.com ). Screen Sharing on macOS uses the VNC port 5900 to connect to a remote Mac. Since VNC itself is inherently insecure, (mac Screen Sharing adds a few things to make it more secure) this port is blocked by many firewalls.

However, I do have ssh access to remote.example.com . So, how do I tell both systems to ‘tunnel’ the screen sharing traffic through ssh ?

(When you test this, remember to enable either ‘Screen Sharing’ or ‘Remote Management’ (i.e Apple Remote Desktop) access in the ‘Sharing’ pane in System Preferences on the remote Mac.)

The tunnel starts on my local machine and ends on remote.example.com at port 5900 (where the screen sharing service is listening on the remote Mac.)

The starting point also needs a port number, and I can basically choose freely. Port numbers under 1000 and over 49000 are reserved for the system and require root privileges. There are also many numbers that are commonly used by certain services (such as 5900 for VNC/Screen Sharing) and may already be in use. I will choose 5901 for the local port.

To connect the local port 5901 to port 5900 on the remote Mac use the following command:

(You can just try this with a second Mac or virtual machine in your network, even without a firewall.)

The syntax of this command is less than obvious. Let’s break it into pieces:

The -N option tells ssh that we do not want to invoke a remote shell or run a remote command.

The -L option creates a local port forwarding setup. This option takes a parameter with three or four parts, separated by colons : . The first pair ( localhost:5901 ) are the tunnel start point. The second pair ( localhost:5900 ) are the remote end point of the tunnel.

The second localhost is resolved on the remote host, so this means port 5900 on the remote host.

The last parameter states the remote host, to connect to, remote.example.com .

This commands tell ssh to connect to remote.example.com and establish a tunnel that transfers traffic from port 5901 on my computer to port 5900 on the remote computer.

Since the origin of my tunnel is usually on my local computer, the first localhost can be omitted, so you only see the origin port.

When you execute the command nothing will happen. You will not even get a new prompt, because the ssh process is running until you cancel it with ctrl-C. Don’t cancel it yet, however, since it needs to run to provide the tunnel.

Читайте также:  How do you know what windows you have

So, when you open the Screen Sharing application (from /System/Library/CoreServices/Applications/ ) and connect to localhost:5901 all traffic will be forwarded by ssh to port 5900 on the remote Mac.

You can also use the open command to connect with Screen Sharing:

You should be able connect with Screen Sharing, even when port 5900 is blocked by a Firewall.

When you are done with the Screen Sharing session, you can end the ssh tunnel process in Terminal with ctrl-C.

SSH triangle

You can also use ssh port to use the remote host as a gateway or ‘jump host’ to a third computer. Imagine you want to use Screen Sharing to connect to secundus.example.com behind a firewall and you only have ssh connection to primus.example.com available. You can tell primus to point the endpoint of an ssh tunnel at secundus with:

Note: secundus.example.com or whatever host or IP address you enter there will be resolved on the remote host. So you can use NAT IP addresses or .local host names here, even if they do not make sense in the network your work Mac is in. (They do have to make sense on the remote host, though, otherwise you will get an error.)

In the following examples the local IP address 192.168.1.200 or the Bonjour hostname Secundus.local will be resolved on the remote host, even if they don’t work on my local computer:

Either way, you can then point Screen Sharing at localhost:5902 and it will connect through primus to Screen Sharing on secundus .

Keep in mind, that while the connection from the start point (on your Mac) to the host primus is secured by ssh the connection from primus to secundus is not.

Stumbling over HTTP hosts

In general you can use ssh port forwarding (or tunnels) for any service. Some services however, may introduce extra pitfalls.

For example, I wanted to use ssh port forwarding to gain access to my home router’s web interface. I can use ‘Back to My Mac’ to ssh into one of the iMacs at home, and thought it should be easy to connect to the router with an ssh tunnel:

This seemed to work, but whenever I tried to point a browser to localhost:8080 it couldn’t connect to the web page. The problem here is not the ssh tunnel but the the web server on the router. As part of the http request, the browser sends the name of the domain requested to the web server. This allows web servers to host different pages for different domains. With this request, the browser told the router it wanted the web page for localhost and the router replied with “I don’t serve pages for that host”… (Your router might behave differently.)

With curl I could convince the router to serve me the page with:

However, since navigating the web interface of the router with curl is out of the question I had to find a different solution.

Tunnel All the Things!

What if I could send all traffic through the iMac at home?

With the command

I can create a tunnel from my computer (on port 9001) to the remote Mac that acts as a SOCKS proxy. Then I can set the Socks proxy to localhost:9001 in the proxy tab in the Network pane in System Preferences. You probably want to create a new network location for this setup. Then all network traffic will be securely routed through the ssh tunnel to my Mac at home where it can connect to the router.

This can also serve as a temporary VPN solution.

However it is somewhat painful to set up and maintain, so if you start using this more frequently, you probably need to look into a proper VPN service solution (some routers, ironically, provide one…).

Источник

How to Setup SSH Tunneling in Mac OS (or Ubuntu)

LAST UPDATED: AUGUST 10, 2021

If you want to setup SSH tunnel with your remote server using your Macbook, you can easily do so using the default Terminal application available in the Mac OS. Yes, we do not have to install any other application for doing so, like we do in Windows.

If you are a Windows user, I would recommend using Mobaxterm application for doing this.

What is SSH Tunneling?

An SSH tunnel or SSH port forwarding is a mechanism to establish a secure connection between a client machine and a server.

Let’s take a simple example to understand this. If we have a database server, let’s say MySQL running on a remote server with some IP address XXX.XXX.XXX.XXX and for which the port number 3306 which is the default port for MySQL is only available on the local network of the remote server. In this case, if you want to access the DB server from your local machine(connected to the internet), you won’t be able to do it. In such a scenario, we set up an SSH tunnel with the remote server, to securely connect to the local network of the remote server to access the 3306 port on the remote server.

Читайте также:  Не открывается образ iso windows 10

Let’s take another example If we are using AWS service and we have two servers one is a DB server and another is the SSH server on which the Web Server is running. On the SSH server, because we are running the Web server, port 80 would be open to all, because then only the website or the web application hosted on that server will be available to its users. But, for security, the DB server is never exposed to the internet and is kept on the local network, which will be accessible via the SSH server, as the SSH server is on the same local network.

Now, if you want to check something or do something on the DB server. or want to connect your local SQL client with the remote database, you won’t be able to do it directly. But because the DB server is accessible via the SSH server, we can setup an SSH tunnel with the SSH server to reach the DB server.

I hope the two examples are clear, and now you know, why SSH tunneling is needed. So let’s see how we can do this.

Using MacOS/Ubuntu Terminal

We can use the ssh command to set up an SSH tunnel with a remote server, considering the SSH port which is port number 22 is open for the remote server.

If our remote server name is my-remote-server.host and the SSH user is st-user, and on the same server a DB service let’s say MySQL is installed which is accessible via localhost:3306 on the remote server.

Then to connect to the DB server, we can run the following command to setup an SSH tunnel:

8888: This is the local port that we will open for the SSH tunnel on the local machine. Here you can give any port number after 1024, because until 1024 port number, all ports are privilege ports.

127.0.0.1: This is the IP for the localhost running on the remote server, this is also the destination we aim to reach via the SSH server.

3306: This is the destination port, assigned to the MySQL sever on the remote SSH server.

and then st-user@my-remote-server.host is the username and the IP address/URI for the SSH server.

Once you do this, you will be prompted to enter the password for the user st-user, so enter the password an hit Enter, and the SSH tunnel will be created. Now, you will be able to access the MySQL server using 127.0.0.1:8888 address from your local machine.

Using a .pem file

If your remote server is an EC2 instance on AWS and you have a .pem file as the SSH key, run the following command for the above scenario:

In this case you will not be asked for the password, as authentication will be done using your SSH key.

This was the scenario where the DB server was running on the localhost of the remote server. Next, let’s see how to connect to a separate DB server via a remote server.

Connect to Destination server via Remote Server:

If our DB server is my-db-server.host on which port 3306 is available for connection on the private network access to the remote SSH server my-remote-server.host, as shown in the picture below.

Then we can run the following command:

Note: If SSH connection is enabled on a different port other than the port number 22, then we can specify the port number in the above command using -p [PORT_NUMBER] argument. So, for example we have 2200 port for SSH enabled on our remote server, then the command would be:

Conclusion:

I hope this article helped you in understanding what SSH tunneling is and how we can setup an SSH tunnel using the Terminal in MacOS and in Ubuntu or other Linux based operating systems. If you were not able to do this or faced any issue running the above command do share in the comments below and we will help you out.

Источник

Оцените статью