Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d99e4924fa924b6 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Introduction
Port forwarding via SSH (SSH tunneling) creates a secure connection between a local computer and a remote machine through which services can be relayed. Because the connection is encrypted, SSH tunneling is useful for transmitting information that uses an unencrypted protocol, such as IMAP, VNC, or IRC.
Types of Port Forwarding
SSH’s port forwarding feature can smuggle various types of Internet traffic into or out of a network. This can be used to avoid network monitoring or sniffers, or bypass badly configured routers on the Internet. Note: You might also need to change the settings in other programs (like your web browser) in order to circumvent these filters.
Local port forwarding is the most common type. For example, local port forwarding lets you bypass a company firewall that blocks Wikipedia.
Remote port forwarding is less common. For example, remote port forwarding lets you connect from your SSH server to a computer on your company’s intranet.
Dynamic port forwarding is rarely used. For example, dynamic port forwarding lets you bypass a company firewall that blocks web access altogether. Although this is very powerful, it takes a lot of work to set up, and it’s usually easier to use local port forwarding for the specific sites you want to access.
Port-forwarding is a widely supported technique and a feature found in all major SSH clients and servers, although not all clients do it the same way. For help on using a specific client, consult the client’s documentation. For example, the PuTTY manual has a section on port forwarding in PuTTY.
To use port forwarding, you need to make sure port forwarding is enabled in your server. You also need to tell your client the source and destination port numbers to use. If you’re using local or remote forwarding, you need to tell your client the destination server. If you’re using dynamic port forwarding, you need to configure your programs to use a SOCKS proxy server. Again, exactly how to do this depends on which SSH client you use, so you may need to consult your documentation.
Local Port Forwarding
Local port forwarding lets you connect from your local computer to another server. To use local port forwarding, you need to know your destination server, and two port numbers. You should already know your destination server, and for basic uses of port forwarding, you can usually use the port numbers in Wikipedia’s list of TCP and UDP port numbers.
For example, say you wanted to connect from your laptop to http://www.ubuntuforums.org using an SSH tunnel. You would use source port number 8080 (the alternate http port), destination port 80 (the http port), and destination server www.ubuntuforums.org. :
Where <host> should be replaced by the name of your laptop. The -L option specifies local port forwarding. For the duration of the SSH session, pointing your browser at http://localhost:8080/ would send you to http://www.ubuntuforums.org/.
In the above example, we used port 8080 for the source port. Ports numbers less than 1024 or greater than 49151 are reserved for the system, and some programs will only work with specific source ports, but otherwise you can use any source port number. For example, you could do:
This would forward two connections, one to www.ubuntuforums.org, the other to www.ubuntu.com. Pointing your browser at http://localhost:8080/ would download pages from www.ubuntuforums.org, and pointing your browser to http://localhost:12345/ would download pages from www.ubuntu.com.
The destination server can even be the same as the SSH server. For example, you could do:
This would forward connections to the shared desktop on your SSH server (if one had been set up). Connecting an SSH client to localhost port 5900 would show the desktop for that computer. The word "localhost" is the computer equivalent of the word "yourself", so the SSH server on your laptop will understand what you mean, whatever the computer’s actual name.
Remote Port Forwarding
Remote port forwarding lets you connect from the remote SSH server to another server. To use remote port forwarding, you need to know your destination server, and two port numbers. You should already know your destination server, and for basic uses of port forwarding, you can usually use the port numbers in Wikipedia’s list of TCP and UDP port numbers.
For example, say you wanted to let a friend access your remote desktop, using the command-line SSH client. You would use port number 5900 (the first VNC port), and destination server localhost:
The -R option specifies remote port forwarding. For the duration of the SSH session, Joe would be able to access your desktop by connecting a VNC client to port 5900 on his computer (if you had set up a shared desktop).
Dynamic Port Forwarding
Dynamic port forwarding turns your SSH client into a SOCKS proxy server. SOCKS is a little-known but widely-implemented protocol for programs to request any Internet connection through a proxy server. Each program that uses the proxy server needs to be configured specifically, and reconfigured when you stop using the proxy server.
For example, say you wanted Firefox to connect to every web page through your SSH server. First you would use dynamic port forwarding with the default SOCKS port:
The -D option specifies dynamic port forwarding. 1080 is the standard SOCKS port. Although you can use any port number, some programs will only work if you use 1080. -C enables compression, which speeds the tunnel up when proxying mainly text-based information (like web browsing), but can slow it down when proxying binary information (like downloading files).
- Type in about:config in the Firefox address bar
- Find the key called "network.proxy.socks_remote_dns" and set it to true
The SOCKS proxy will stop working when you close your SSH session. You will need to change these settings back to normal in order for Firefox to work again.
To make other programs use your SSH proxy server, you will need to configure each program in a similar way.
Forwarding GUI Programs
SSH can also forward graphical applications over a network, although it can take some work and extra software to forward programs to Windows or Mac OS.
Single Applications
If you are logging in from a Unix-like operating system, you can forward single applications over SSH very easily, because all Unix-like systems share a common graphics layer called X11. This even works under Mac OS X, although you will need to install and start the X11 server before using SSH.
To forward single applications, connect to your system using the command-line, but add the -X option to forward X11 connections:
Once the connection is made, type the name of your GUI program on the SSH command-line:
Your program will start as normal, although you might find it’s a little slower than it would be if it were running locally. The trailing & means that the program should run in "background mode", so you can start typing new commands in straight away, rather than waiting for your program to finish.
If you only want to run a single command, you can log in like this:
That will run Firefox, then exit when it finishes. See the SSH manual page for information about -f and -T.
If you start an application and it complains that it cannot find the display, try installing the xauth package from the Main repository (click here to install xauth). Xauth is installed by default with desktop installations but not server installations.
If you suspect that programs are running slowly because of a lack of bandwith, you can turn SSH compression on with the -C option:
Using -fTXC here is identical to -f -T -X -C.
Nested Windows
Xephyr is a program that gives you an X server within your current server. It’s available in the xserver-xephyr package in the Main repository (click here to install xserver-xephyr).
Two ssh forwarded desktops on dual monitors, click to enlarge
Setting up Xephyr was explained briefly in the Ubuntu forums.
Port Forwarding Explained
To get the most out of port forwarding, it’s helpful to know a bit about how the Internet works.
The Internet assigns computers virtual "ports", a bit like the USB ports on the back of your computer:
To let a digital camera share pictures with your PC, you connect the USB port on the camera to any USB port on the PC. The computer then talks to the camera about your photos, and shows you the result.
To let a web server share pages with your PC, you connect the web server port on the server to any Internet port on the PC. The computer then talks to the server about your page, and shows you the result.
Unlike a USB port, there is no physical component to an Internet port. There’s no actual wire, or actual hole on the back of your computer. It’s all just messages being sent over the Internet. Like other "virtual" computer concepts, Internet ports are just an analogy that help to explain what your computer is doing. Sometimes, that analogy breaks down:
There are two types of Internet port: normal "TCP" ports and strange "UDP" ports (which won’t be covered here).
Unlike USB ports, every computer has exactly 65,535 numbered TCP ports, some of which have a special purpose. For example, port number 80 is your web server port, so your web browser knows it should connect to port number 80 in order to download a web page.
Connections between Internet ports can be patched together, so a connection from computer A to computer B on port 12,345 could be patched through to port number 80 on computer C. This is known as port forwarding.
Troubleshooting
If you get a message like this when you try to forward a port:
then someone is already listening on that port number. You won’t be able to listen on that port until the other person has finished with it.
If forwarding doesn’t seem to work, even though you didn’t get a warning message, then your SSH server might have disabled forwarding. To check, do the following:
If you see something like this:
then forwarding is disabled on your server. See the SSH configuration page for more information.
SSH/OpenSSH/PortForwarding (последним исправлял пользователь knome 2013-12-13 23:26:10)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Configure Firewall with UFW on Ubuntu 20.04
A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. Firewalls have been a first line of defense in network security. In this tutorial, you will learn how to configure Firewall with UFW on Ubuntu 20.04 LTS.
UFW is an abbreviated to an Uncomplicated FireWall. UFW is easy to implement and highly recommended to secure a network. The default firewall configuration tool for Ubuntu is ufw. It provides a user friendly way to create an IPv4 or IPv6 host-based firewall. By default UFW is disabled.
Prerequisite
- Ubuntu 20.04/18.04 (Any debian based system)
- User with sudo privileges
- Fast Internet Connection
- Command Line Terminal
Step:1. Default UFW Policies
You can get the status of ufw whether firewall running on not using following commands.
Sample output must be look like below as we told earlier that by default UFW is disabled.
It is always a better policy that closes all ports on the server and open only required ports. Let’s block all incoming connection and only allow outgoing connections from our Ubuntu 20.04 LTS box with following commands.
Step:2. Enabling UFW
As told earlier ufw is disabled by default. UFW can be enabled by using below command,
Once ufw enabled, it runs across system restarts. We can verify that easily as follows,
- Disabling UFW
If you need to stop the firewall and disable on system startup, then use below commands,
Step:3. Open Specific Incoming Connections/Ports
- Open SSH TCP Port 22 Connections
Our next step is to allow incoming SSH ports. We can open SSH TCP port 22 using UFW as follows:
However, we can write the equivalent rule by specifying the port number instead of service name. We can allow ports using below command,
If you are running ssh on other TCP port than default port. for instance, port 2222 then use below command,
Few admins have a static IP address at home or office location. In that case, only allow ssh access from that static IP address such as 202.50.7.10 to Ubuntu server IP address such as 172.22.12.40,
To check whether the port is open in ufw firewall, then use follows command,
Step:4. Allowing Other Connections
Here, you should allow other connections that your server needs to respond to. The connections that you should allow totally depends on your specific needs. Let’s add more rules. Say you want to open ports and allow IP address with ufw.
The syntax is as follows to open TCP port 80 and 443 with ufw:
Next try to open UDP/1194 (OpenVPN) server:
- Allow Port Ranges with UFW
We can allow port ranges too, for instance, tcp and udp 2000 to 3000:
- AllowingSpecific IP Addresses
Suppose, you need to allow ALL connections from an specific IP address called 106.22.10.210, please use below commands,
Let’s allow connections from an IP address called 104.22.11.215 to port 25, then use below commands,
You can set destination IP Addr 224.224.224.224 for port 25 too using as follows,
- Connections to Specific Network Interface
You should look up your network interfaces before continuing. To do so, use below command,
If your server has a public network interface called ens33, you could allow HTTP traffic (port 80) to it with follows command,
If you want your MySQL database server (port 3306) to listen for connections on the private network interface eth1, for instance, you could use below command,
Step:5. Block or Deny Incoming Connections/Ports
If you want to close ports and block certain IP addresses. The syntax is to deny access as below.
Let’s suppose, you want to deny all connections from an IP address called 204.10.1.45, then use below commands,
Denying all connections from an IP/subnet called 104.13.40.15/29, use follows command,
Generally, it happens someone trying to intrude your infra. Then you can block that particular IP Addr (let’s say Hacker’s IP 4.1.1.2 on port 22) then go with below commands,
Step:6. Verifying the Status of UFW
You can see the status of UFW using below command,
- UFW Delete Rules
As you already learned how to add, deny, and list the firewall rules. It is time to delete unwanted rules.
The syntax is to list all of the current rules in a numbered format using follows command,
To delete 5th rule type the command,
Deleting By Actual Rule using below command,
Step:7. More Commands related to UFW
Let’s learn more commands related to UFW.
- Reload the ufw
- Reset the ufw
- View the Firewall Logs
By default all UFW entries are logged into /var/log/ufw.log file. Use the NA command/more command/tail command and other commands to view the ufw logs:
- Show the list of rules
Conclusion
Hence, you learned how To configure Firewall with UFW on Ubuntu. I hope you learned all aspects of UFW.
Как открыть порт на VPS
Для данной ОС управление открытием и закрытием портов как правило производится через файрволл ufw.
На свежеустановленной системе данный файрволл по умолчанию отключен, нужно будет открыть порт для ssh-соединения и включить файрволл. Если сначала включить файрволл, то доступа через ssh мы лишимся.
Команды:
— открываем стандартный порт для ssh. Если у Вас ssh у Вас работает по другому порту, то замените 22 на его номер.
Если открытие порта пройдет успешно, то появится сообщение «Rules updated».
— включаем файрволл.
Появится предупреждение о возможной блокировке ssh, соглашаемся.
Если после этого повторно выполнить sudo ufw status verbose, то увидим, что статус сменился на active, а также уже открытые порты.
После активации файрволла открыть порт можно командой: sudo ufw allow порт/протокол (можно указать диапазон портов через двоеточие). Пример:
Выполнив ещё раз sudo ufw status verbose можем убедиться, что порты успешно открылись.
2. Открыть порт на Ubuntu 18.04.
Будем использовать iptables. Посмотрим список действующих правил iptables. Команда:
На чистой VPS правил быть не должно, результатом этой команды должны быть сообщения, как на скриншоте.
Здесь мы видим три цепочки OUTPUT, INPUT и FORWARD, за открытые порты отвечает цепочка INPUT, именно через нее проходят все входящие пакеты. Сейчас политика по умолчанию — ACCEPT, это значит, что подключение ко всем портам разрешено.
Добавим правила, которые разрешат обмен данными между любыми портами на локальном интерфейсе lo и добавим в разрешенные уже установленное нами подключение, чтобы не потерять доступ к VPS по ssh. Команды:
Также откроем 22 порт для ssh-доступа в дальнейшем. Команда:
И сменим политику по умолчания для входящих подключений с разрешения на блокирование. Команда:
Сохраним изменения командой (иначе они пропадут после перезагрузки VPS):
Теперь снова смотрим список действующих правил командой:
Видим, что для входящих (цепочка INRUT) политика сменилась на DROP, а разрешены только те входящие подключения, правила для которых мы добавили выше.
Новый порт можно открыть командой вида: sudo iptables -I INPUT -p протокол —dport номер порта -j ACCEPT.
Обратите внимание, что ранее мы использовали -A, сейчас используем -I, чтобы избежать конфликта с правилам и добавленными ранее — опция -I добавит новое правило в начало списка.
Пример команды на открытие порта 1888 для протокола tcp:
Также не забываем сохранить командой: sudo /sbin/iptables-save
Командой sudo iptables -L снова проверим список правил. Видим, что порт успешно открыт.
3. Открытие портов через CSF
Сначала обновим пакеты на VPS, команды:
Сначала установим модули Perl, необходимые для CSF. Команды:
На Centos
На Ubuntu/Debian
Далее скачаем архив csf с официального сайта. Распакуем, перейдем в каталог с распакованным архивом и запустим установку.
В случае успешной установки должно вывестись сообщение «Install ation Completed». Далее нужно протестировать работу модулей командой:
Если все установлено и работает корректно, результатом вывода должно стать сообщение «RESULT: csf should function on this server».
Следующим шагом откроем конфигурационный файл CSF и переведем файрволл из тестового режима в рабочий. Команда:
Нам нужно сначала в файле изменить значение TESTING = «1» на TESTING = «0».
Далее запускаем файрволл и проверяем его статус. Должно быть «Active».
Чтобы теперь открыть порт через CSF, нам нужно снова открыть файл /etc/csf/csf.conf и найти строки, начинающиеся с директив TCP_IN, TCP_OUT, UDP_IN, UDP_OUT.
Секция TCP_IN открывает порты для входящих соединений по tcp-протоколу, секция TCP_OUT — для исходящих.
Секции UDP_IN и UDP_OUT = для входящих и исходящих соединений по udp-протоколу.
В соответствующей строке через запятую указываем номера портов, которые нужно открыть. В данном примере прописан tcp-порт 8888 для входящих соединений, также оставлены порты, которые в момент установки csf прописывает по умолчанию.
Сохраняем изменения и перезапускаем csf командой csf -r
Готово, порт открыт.
4. Открыть порт на Centos 7
На Centos7 в комплекте идет свой файрволл-надстройка над Iptables, который называется Firewalld.
Сначала проверим, запущен ли данный сервис, командой:
- drop — блокировать все входящие пакеты, разрешить только исходящие.
- block — в отличие от предыдущего варианта отправителю пакета будет отправлено сообщение по блокировке его пакета.
- public — поддерживаются входящие соединения только для ssh и dhclient.
- external — поддерживает NAT для скрытия внутренней сети.
- internal и home — разрешены сервисы ssh, samba, mdns и dhcp.
- dmz — используется для изолированных серверов, у которых нет доступа к сети. Разрешено только подключение по SSH.
- work — разрешены сервисы ssh и dhcp.
- trusted — всё разрешено.
На свежеустановленной Centos7 имеющемся интерфейсам по умолчанию будет назначена зона public. Посмотреть информацию о действующих правилах для зоны можно командой вида: sudo firewall-cmd —zone= имя зоны —list-all. Соответственно для зоны public команда будет выглядеть, как:
Можем видеть, что в зону public у нас уже по умолчанию добавлены сервисы ssh и dhcpv6-client
5. Открыть порт двумя способами
Первый способ — прямой командой вида: sudo firewall-cmd —zone=имя зоны —remove-port=номер порта/протокол —permanent
Пример для зоны: public, порта: 3471 и протокола: tcp
Опция —permanent нужна, чтобы добавленные правила сохранились после перезагрузки VPS. В завершение нужно перезапустить файрволл командой:
В случае успешного выполнения команд получим сообщение «success».
Второй способ — добавить соответствующий сервис к зоне, при этом будут открыть нужные для работы этого сервиса порт. Но добавлять можно только те сервисы, которые известны файрволлу, посмотреть их список можно командой:
Добавить сервис в зону — командой вида: sudo firewall-cmd —zone=имя зоны —add-service=имя сервиса —permanent
Например, команда добавления сервиса SMTP в зону public будет иметь вид:
После также нужно перезапустить файрволл sudo firewall-cmd —reload
Для проверки еще раз выполним sudo firewall-cmd —zone=public —list-all, как можем видеть в результатах вывода — сервис smtp добавлен, порт открыт.
Подобрать лучшие VPS с SSD-дисками, можно на нашем сайте.