Как открыть 22 порт ubuntu

от admin

Как открыть порт Ubuntu

Правильная настройка брандмауэра имеет очень важное значение для безопасности вашего сервера или даже домашнего компьютера, подключенного к сети интернет.

На промышленных серверах брандмауэр запрещает подключение к большинству из них, оставляя только необходимые. В этой статье мы рассмотрим как открыть порт iptables и закрыть все остальные. Хотя в большинстве дистрибутивов существуют специальные утилиты для настройки брандмауэра,мы будем использовать iptables, чтобы вы смогли понять процесс на самом низком уровне.

Просмотр правил Iptables

Прежде чем что-либо менять, нужно понять каким образом система работает сейчас. Возможно, для лучшего понимания материала вам сначала стоит ознакомиться со статьей iptables для начинающих. Для просмотра текущих правил iptables выполните такую команду:

sudo iptables -L

Здесь мы видим три цепочки OUTPUT, INPUT и FORWARD, за открытые порты отвечает цепочка INPUT, именно через нее проходят все входящие пакеты. Сейчас политика по умолчанию — ACCEPT, это значит, что подключение ко всем портам разрешено. Здесь нам нужно настроить все самим и это будет проще если бы какая-либо программа уже создала свои настройки, но этот вариант мы тоже рассмотрим ниже.

Как открыть порт iptables с нуля

Если в iptables уже есть какие-либо правила и вы хотите их удалить просто выполните:

sudo iptables -F

Теперь нам нужно добавить правила, которые разрешат обмен данными между любыми портами на локальном интерфейсе lo, это нужно чтобы не вызвать системных ошибок:

sudo iptables -A INPUT -i lo -j ACCEPT $ sudo iptables -A OUTPUT -o lo -j ACCEPT

Если кратко, то здесь добавляется два правила в цепочки INPUT и OUTPUT, разрешающие отправку и прием данных из интерфейса lo. Еще одно интересное и важное правило, которое многие упускают. Нужно запрещать только новые соединения, а пакеты для уже открытых нужно разрешать. Иначе получится, что мы отправляем серверу запрос (цепочка OUTPUT открыта), соединение открывается, но сервер не может нам ответить, потому что все пакеты отбрасываются в INPUT. Поэтому нужно разрешить все пакеты с состоянием ESTABLISHED и RELATED. Для этого есть модуль state:

sudo iptables -A INPUT -m state —state ESTABLISHED,RELATED -j ACCEPT

Теперь самое интересное, рассмотрим как открыть порт 22 и 80 для протокола TCP:

sudo iptables -A INPUT -p tcp —dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp —dport 80 -j ACCEPT

Опция -A сообщает, что нужно добавить пакет в конец цепочки, -p — указывает протокол, а —dport или Destination Port (порт назначения) указывает из какого порта пакеты нужно принимать. Теперь вы можете снова посмотреть список правил:

sudo iptables -L

Вывод очень упрощен и понять здесь что-то сложно, например, может показаться что у нас два одинаковых правила, хотя это не так. Чтобы отобразить более подробную информацию используйте:

sudo iptables -nvL

Чтобы все это в действительности заработало, осталось поменять политику по умолчанию на DROP:

sudo iptables -P INPUT DROP

Все, можете проверять. Все пользователи смогут получить доступ к портам 22 и 80, а к остальным доступа не будет.

Как открыть порт, если уже есть правила

Довольно часто возникает ситуация, когда вам нужно открыть порт Linux, а iptables уже содержит набор правил, запрещающих доступ к портам. Иногда вы добавляете правило, все как нужно, с помощью описанной выше команды, но не замечаете никакого эффекта. Рассмотрим почему так происходит.

Допустим, программа или предыдущий администратор для надежности добавили в конец цепочки правило такого вида:

sudo iptables -A INPUT -j DROP

Как вы понимаете, это значит, что все пакеты, которые до него доходят, будут отброшены. Ваше правило добавляется в конец цепочки, уже после этого. Естественно, что к нему уже никакие пакеты не дойдут, потому что они были отброшены ранее. Чтобы обойти эту проблему нужно использовать опцию -I (INSERT) вместо -A (ADD), она добавляет правило в начало цепочки и все будет работать. Осталось открыть порты Linux:

sudo iptables -I INPUT -p tcp —dport 1924 -j ACCEPT

Теперь смотрим список правил и проверяем:

sudo iptables -L

Выводы

В этой статье мы рассмотрели как открыть порт Ubuntu 16.04 или в любом другом Linux дистрибутиве, а также закрыть ненужные порты. Это повысит безопасность вашей системы. Только на первый взгляд кажется, что с iptables сложно работать. Если разобраться, то все будет достаточно просто. Надеюсь, эта информация была полезной для вас.

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: 7a6a2fcd0dc077b5 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Introduction

For an introduction to firewalls, please see Firewall.

UFW — Uncomplicated Firewall

The default firewall configuration tool for Ubuntu is ufw. Developed to ease iptables firewall configuration, ufw provides a user friendly way to create an IPv4 or IPv6 host-based firewall. By default UFW is disabled.

Gufw is a GUI that is available as a frontend.

Basic Syntax and Examples

Default rules are fine for the average home user

When you turn UFW on, it uses a default set of rules (profile) that should be fine for the average home user. That’s at least the goal of the Ubuntu developers. In short, all ‘incoming’ is being denied, with some exceptions to make things easier for home users.

Enable and Disable

Enable UFW

To turn UFW on with the default set of rules:

To check the status of UFW:

The output should be like this:

Note that by default, deny is being applied to incoming. There are exceptions, which can be found in the output of this command:

You can also read the rules files in /etc/ufw (the files whose names end with .rules).

Disable UFW

To disable ufw use:

Allow and Deny (specific rules)

Allow

example: To allow incoming tcp and udp packet on port 53

example: To allow incoming tcp packets on port 53

example: To allow incoming udp packets on port 53

example: To deny tcp and udp packets on port 53

example: To deny incoming tcp packets on port 53

example: To deny incoming udp packets on port 53

Delete Existing Rule

To delete a rule, simply prefix the original rule with delete. For example, if the original rule was:

Use this to delete it:

Services

You can also allow or deny by service name since ufw reads from /etc/services To see get a list of services:

Allow by Service Name

example: to allow ssh by name

Deny by Service Name

example: to deny ssh by name

Status

IconsPage/important.pngChecking the status of ufw will tell you if ufw is enabled or disabled and also list the current ufw rules that are applied to your iptables.

To check the status of ufw:

if ufw was not enabled the output would be:

Logging

To enable logging use:

To disable logging use:

Advanced Syntax

You can also use a fuller syntax, specifying the source and destination addresses, ports and protocols.

Allow Access

This section shows how to allow specific access.

Allow by Specific IP

example:To allow packets from 207.46.232.182:

Allow by Subnet

You may use a net mask :

Allow by specific port and IP address

example: allow IP address 192.168.0.4 access to port 22 for all protocols

Allow by specific port, IP address and protocol

example: allow IP address 192.168.0.4 access to port 22 using TCP

Enable PING

Note : Security by obscurity may be of very little actual benefit with modern cracker scripts. By default, UFW allows ping requests. You may find you wish to leave (icmp) ping requests enabled to diagnose networking problems.

In order to disable ping (icmp) requests, you need to edit /etc/ufw/before.rules and remove the following lines:

or change the «ACCEPT» to «DROP»

Deny Access

Deny by specific IP

example:To block packets from 207.46.232.182:

Deny by specific port and IP address

example: deny ip address 192.168.0.1 access to port 22 for all protocols

Working with numbered rules

Listing rules with a reference number

You may use status numbered to show the order and id number of rules:

Editing numbered rules

Delete numbered rule

You may then delete rules using the number. This will delete the first rule and rules will shift up to fill in the list.

Insert numbered rule

Advanced Example

Scenario: You want to block access to port 22 from 192.168.0.1 and 192.168.0.7 but allow all other 192.168.0.x IPs to have access to port 22 using tcp

IconsPage/important.pngThis puts the specific rules first and the generic second. Once a rule is matched the others will not be evaluated (see manual below) so you must put the specific rules first. As rules change you may need to delete old rules to ensure that new rules are put in the proper order.

To check your rules orders you can check the status; for the scenario the output below is the desired output for the rules to work properly

Scenario change: You want to block access to port 22 to 192.168.0.3 as well as 192.168.0.1 and 192.168.0.7.

Читать:
Как скрыть код листа в vba excel

IconsPage/important.pngIf you simply add the deny rule the allow would have been above it and been applied instead of the deny

Interpreting Log Entries

Based on the response to the post UFW log guide/tutorial ?.

The SPT and DPT values, along with SRC and DST values, will typically be the values you’ll focus on when analysing the firewall logs.

Pseudo Log Entry

It’s good practice to watch the dates and times. If things are out of order or blocks of time are missing then an attacker probably messed with your logs.

Hostname

The server’s hostname

Uptime

The time in seconds since boot.

Logged Event

Short description of the logged event; e.g. [UFW BLOCK]

If set, then the event was an incoming event.

If set, then the event was an outgoing event.

This provides a 14-byte combination of the Destination MAC, Source MAC, and EtherType fields, following the order found in the Ethernet II header. See Ethernet frame and EtherType for more information.

This indicates the source IP, who sent the packet initially. Some IPs are routable over the internet, some will only communicate over a LAN, and some will only route back to the source computer. See IP address for more information.

This indicates the destination IP, who is meant to receive the packet. You can use whois.net or the cli whois to determine the owner of the IP address.

This indicates the length of the packet.

I believe this refers to the TOS field of the IPv4 header. See TCP Processing of the IPv4 Precedence Field for more information.

I believe this refers to the Precedence field of the IPv4 header.

This indicates the “Time to live” for the packet. Basically each packet will only bounce through the given number of routers before it dies and disappears. If it hasn’t found its destination before the TTL expires, then the packet will evaporate. This field keeps lost packets from clogging the internet forever. See Time to live for more information.

Not sure what this one is, but it’s not really important for reading logs. It might be ufw’s internal ID system, it might be the operating system’s ID.

PROTO

This indicates the protocol of the packet — TCP or UDP. See TCP and UDP Ports Explained for more information.

This indicates the source. I believe this is the port, which the SRC IP sent the IP packet over. See List of TCP and UDP port numbers for more information.

This indicates the destination port. I believe this is the port, which the SRC IP sent its IP packet to, expecting a service to be running on this port.

WINDOW

This indicates the size of packet the sender is willing to receive.

This bit is reserved for future use & is always set to 0. Basically it’s irrelevant for log reading purposes.

SYN URGP

SYN indicates that this connection requires a three-way handshake, which is typical of TCP connections. URGP indicates whether the urgent pointer field is relevant. 0 means it’s not. Doesn’t really matter for firewall log reading.

How To Open a Port on Linux

How To Open a Port on Linux

A port is a communication endpoint. Within an operating system, a port is opened or closed to data packets for specific processes or network services.

Typically, ports identify a specific network service assigned to them. This can be changed by manually configuring the service to use a different port, but in general, the defaults can be used.

The first 1024 ports (port numbers 0 to 1023 ) are referred to as well-known port numbers and are reserved for the most commonly used services. These include SSH (port 22 ), HTTP (port 80 ), HTTPS (port 443 ).

Port numbers above 1024 are referred to as ephemeral ports.

  • Port numbers 1024 to 49151 are called the registered/user ports.
  • Port numbers 49152 to 65535 are called the dynamic/private ports.

In this tutorial, you will open an ephemeral port on Linux, since the most common services use the well-known ports.

Prerequisites

To complete this tutorial, you will need:

  • Familiarity with using the terminal.

List All Open Ports

Before opening a port on Linux, you must check the list of all open ports, and choose an ephemeral port to open that is not on that list.

Use the netstat command to list all open ports, including TCP and UDP, which are the most common protocols for packet transmission in the network layer.

This will print:

  • all listening sockets ( -l )
  • the port number ( -n )
  • TCP ports ( -t )
  • UDP ports ( -u )

Note: If your distribution doesn’t have netstat , you can use the ss command to display open ports by checking for listening sockets.

Verify that you are receiving consistent outputs using the ss command to list listening sockets with an open port:

This will print:

This gives more or less the same open ports as netstat .

Opening a Port on Linux to Allow TCP Connections

Now, open a closed port and make it listen for TCP connections.

For the purposes of this tutorial, you will be opening port 4000 . However, if that port is not open in your system, feel free to choose another closed port. Just make sure that it’s greater than 1023 .

Ensure that port 4000 is not used using the netstat command:

Or the ss command:

The output must remain blank, thus verifying that it is not currently used, so that you can add the port rules manually to the system iptables firewall.

For Ubuntu Users and ufw -based Systems

Use ufw — the command line client for the UncomplicatedFirewall.

Your commands will resemble:

Refer to How to Setup a ufw Firewall Setup for your distribution.

Note:

  • Ubuntu 14.0.4: “Allow Specific Port Ranges”
  • Ubuntu 16.0.4/18.0.4/20.0.4/22.0.4: “Allowing Other Connections / Specific Port Ranges”
  • Debian 9/10/11: “Allowing Other Connections / Specific Port Ranges”

For CentOS and firewalld -based Systems

Use firewall-cmd — the command line client for the firewalld daemon.

Your commands will resemble:

Refer to How to Set Up firewalld for your distribution.

Note:

  • CentOS 7/8: “Setting Rules for your Applications / Opening a Port for your Zones”
  • Rocky Linux 8/9: “Setting Rules for your Applications / Opening a Port for your Zones”

For Other Linux Distributions

Use iptables to change the system IPv4 packet filter rules.

Note:

  • Ubuntu 12.04: “A Basic Firewall”
  • Ubuntu 14.04: “Accept Other Necessary Connections”

Test the Newly Opened Port for TCP Connections

Now that you have successfully opened a new TCP port, it is time to test it.

First, start netcat ( nc ) and listen ( -l ) on port ( -p ) 4000 , while sending the output of ls to any connected client:

Now, after a client has opened a TCP connection on port 4000 , they will receive the output of ls . Leave this session alone for now.

Open another terminal session on the same machine.

Since you opened a TCP port, use telnet to check for TCP Connectivity. If the command doesn’t exist, install it using your package manager.

Input your server IP and the port number ( 4000 in this example) and run this command:

This command tries to open a TCP connection on localhost on port 4000 .

You’ll get an output similar to this, indicating that a connection has been established with the listening program ( nc ):

The output of ls ( while.sh , in this example) has also been sent to the client, indicating a successful TCP Connection.

Use nmap to check if the port ( -p ) is open:

This command will check the open port:

The port has been opened. You have successfully opened a new port on your Linux system.

Note: nmap only lists opened ports that have a currently listening application. If you don’t use any listening application, such as netcat, this will display the port 4000 as closed since there isn’t any application listening on that port currently. Similarly, telnet won’t work either since it also needs a listening application to bind to. This is the reason why nc is such a useful tool. This simulates such environments in a simple command.

But this is only temporary, as the changes will be reset every time you reboot the system.

Persisting Rules

The approach presented in this article will only temporarily update the firewall rules until the system shuts down or reboots. So similar steps must be repeated to open the same port again after a restart.

For ufw Firewall

ufw rules do not reset on reboot. This is because it is integrated into the boot process, and the kernel saves the firewall rules using ufw by applying appropriate config files.

For firewalld

You will need to apply the —permanent flag.

Refer to How to Set Up firewalld for your distribution.

Note:

  • CentOS 7/8: “Setting Rules for your Applications”
  • Rocky Linux 8/9: “Setting Rules for your Applications”

For iptables

You will need to save the configuration rules. These tutorials recommend iptables-persistent .

Note:

  • Ubuntu 12.04: “Saving Iptables Rules”
  • Ubuntu 14.04: “Saving your Iptables Configuration”

Conclusion

In this tutorial, you learned how to open a new port on Linux and set it up for incoming connections. You also used netstat , ss , telnet , nc , and nmap .

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Похожие статьи