Перейти к содержимому

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

  • автор:

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

WARNING: nftables is the default firewall framework since Debian 10 Buster. This page is outdated.

  1. Introduction
  2. Basic firewall software
    1. Basic software for network traffic manipulation
      1. Using iptables for IPv4 traffic
      2. Using ip6tables for IPv6 traffic
      3. Using ebtables for ARP traffic
      4. Application firewalls

      Introduction

      A network firewall is a set of rules to allow or deny passage of network traffic, through one or more network devices. A network firewall may also perform more complex tasks, such as network address translation, bandwidth adjustment, provide encrypted tunnels and much more related to network traffic.

      Prior to version 5 (Lenny), a default Debian installation, did not have a default firewall enabled. But provides the needed tools to configure it manually.

      Basic firewall software

      Network traffic has different components, layers and protocols. For more references, check out the links section.

      The most known type of firewall, and the most initially implemented, are sets of rules based on netfilter software, based on a set of kernel modules and some user space tools.

      Basic software for network traffic manipulation

      The default Debian installation comes with the program iptables(8), configured to allow all traffic. This section briefly explains the different programs to handle network traffic manually, as well as two sample scripts.

      You need to be root, or use sudo, to launch these programs.

      You may find the iptables-persistent package useful.

      Using iptables for IPv4 traffic

      This is not an iptables manual, only a short introduction about the use of the program. For more extended explanations, see iptables(8)

      Basic invocation to define rules is:

      Tables and chains

      All rules, are stored on different tables.

      The default table is filter, which maintain the INPUT, OUTPUT and FORWARD chains, used for incoming, outgoing and redirected traffic respectively.

      Other present tables are mangle, nat and raw. You can also create and delete custom tables.

      Rules and program invocation may refer to a specific table using the -t table_name switch (or --table table_name).

      If no table is specified, the default table is used (the filter table).

      To list the ruleset of any table, the -L switch is used. For example:

      As you can see, the default policy in a default installation is to ACCEPT all traffic. There are no rules on any chain.

      Each of the default tables, contain different chains, to store rules for different points, in the kernel networking subsystem.

      You can list other tables using -t, for example, to see the nat (Network Address Translation) table:

      Matching and order

      When a packet is inspected through the rulesets, matches are searched from top to bottom of tables and chains.

      Into the rules, matches are searched from left to right, of the rule syntax used.

      When a packet does not match a rule, the search jumps to the next rule. If no rules matches, then the default policy is applied to the packet.

      If the packet matches any rule definition, then the target defined on the rule is applied (ACCEPT, REJECT, DROP, LOG, etc), and the following rules of the same chain are skipped.

      It is very important to keep this in mind when designing a ruleset, to reach the desired functionality and because of its impact on performance, in large rulesets.

      Policies and Targets

      Default policy is to ACCEPT all traffic, but the most common practice, is to change policies to DROP all traffic but the allowed.

      You have to be careful and sure that your rules are right, before put a policy to DROP, or you will lose connectivity.

      See the troubleshooting section for tips about this issue.

      Program switches

      There are other switches, to handle chains, tables, clear rules, counters and other elements. See iptables(8) man page.

      Modules

      The iptables program has an extensive collection of modules, to use different criteria to evaluate packets.

      There are modules for protocols, logging, states of the conection, etc. All compiled-in modules, are neatly explained in the man page.

      Modules may have parameters (-m module_name --parameter_name parameter_arguments).

      An example rule, using the state module, to drop incoming traffic with INVALID state (a parameter of the state module), defined in the headers of the packet, would be:

      Example scripts
      Installation

      You can put this scripts at any place that run at boot time or network initialization.

      Common places are:

      /etc/rc.local

      Before the exit 0. Will be launched at boot time.

      /etc/network/interfaces

      This is a more reasonable and standard place for networking related stuff.

      For example, if eth0 is your main or uniq interface, using DHCP:

      SystemD | firewall.service

      Most Debian distributions now include systemd. In order to bring up the iptable rules using systemd at start:

      Create a new file using any reasonable file text editor(I called mine firewall.service)

      Then add the following:

      Then enable the service:

      Example: Basic standalone machine firewall

      You can use this script in any stand-alone machine (for example a personal desktop) that does not need ports open to any place. Or see the final commented line, to open specific ports.

      A simple script like the one below, will provide your host with a reasonable amount of security. Be aware that the following script drops all packets which do not match an allow rule, so normal network error messages will not be seen. All allow rules have been commented out to protect the uninitiated.

      Example: Basic gateway machine firewall
      Using ip6tables for IPv6 traffic

      Because of growth, Internet is slowly switching to IPv6, that has a much larger address space than IPv4, and Debian is IPv6 capable.

      If you have IPv6 addresses, networks and conections in your firewall, you’ve to be careful and configure your rulesets for each protocol.

      To configure and manage IPv6 rulesets, you need to use ip6tables(8), which is provided by the default Debian install, in the package iptables.

      The usage and functionality, is very similar to iptables, but oriented to IPv6 traffic.

      For more references, see: ip6tables(8)

      Using ebtables for ARP traffic

      Ebtables (package ebtables) is used to set up, maintain, and inspect the tables of Ethernet frame rules in the Linux kernel. It is analogous to iptables, but operates at the MAC (ARP) layer, rather than the IP layer.

      If you need to filter or translate ARP traffic (at link layer), your firewall has bridged interfaces (for example a transparent bridge between a OpenVPN tunneled VLAN and a local VLAN, or bridged interfaces for virtualization), ebtables(8) is your friend.

      The design is very similar to netfilter’s iptables.

      It manages rulesets in tables with chains and targets, using user space tools, but this time it’s not in the default Debian installation, and you need to add it:

      For a more detailed explanation of its usage, look at the inevitable man page, and visit the official website (see links section).

      There are documents that explain howto integrate ebtables and iptables, using the iptables module physdev.

      Application firewalls

      To go more up, and manipulate the Layer 7 of the OSI model, and be able to define rules at application level, you need other tools.

      For example. you open the port 80 to your users, but you don’t want them to be able to download .exe files from internet. You need an application firewall or proxy.

      The default kernel in Debian does not have layer 7 patches, but you can install user space proxys to manage this kind of filters.

      See also the links section for the l7-filter project.

      Troubleshooting software and tips

      It’s very easy to lose connectivity when initially configuring a firewall. And it’s easier the more complex the firewall is.

      A basic skill for troubleshoot a firewall problem, is to know the points where the traffic passes, is turned, routed, can be rejected, etc. And to know how to monitor that points, and what is happening.

      The most effective is to analyze the traffic from end to end, from the initial request, the DNS, the interfaces by which must pass, the translations that have to do, the rejected traffic logs, the routing rules, etc.

      A common hack when doing ruleset designing, is to put a cron task, that flush rules every few minutes, in case you will make a mistake (working in remote).

      Graphic applications and frontends

      There are some tools, to configure firewalls using frontends and helpers.

      There are also command line "high level" tools, to avoid the "low level" syntax, or to simplify certain tasks. Anyway, the real power is in the large number of modules and options for basic command line programs, that often is not covered by frontends.

      Как открыть порт в Ubuntu / Debian

      Здравствуйте, друзья. Если у вас есть сервер или компьютер, тогда вам требуется Firewall. Firewall добавит дополнительный уровень безопасности вашей системе. С помощью брандмауэра (Firewall) вы можете открыть любой порт на Ubuntu / Debian и контролировать доступ к вашему компьютеру. В этом посте мы покажем как открыть порты в Ubuntu / Debian.

      UFW: это простой брандмауэр на Ubuntu / Debian

      По умолчанию брандмауэром Linux является IPTables. Хотя это очень эффективное и гибкое приложение, правда в том, что им сложно управлять. Поэтому сообщество создало не менее эффективные, но более простые в использовании альтернативы, такие как UFW.

      Вкратце, UFW означает Uncomplicated Firewall и является своего рода Front-end для IPTables, но предназначенный для Ubuntu / Debian. С его помощью вы можете быстро и легко настраивать правила и открывать порты в системе.

      Когда вы включаете UFW, он использует набор правил (профиль) по умолчанию, который должен быть подходящим для среднего домашнего пользователя. Короче говоря, все «входящие» запрещены, с некоторыми исключениями, чтобы облегчить жизнь домашним пользователям. Однако все эти настройки можно изменить и адаптировать к вашим потребностям.

      Одна из основных и необходимых операций, которые мы можем выполнить с помощью UFW — это открытие портов. Это требуется для того чтобы приложение или служба могли использовать нашу сеть как для входящих, так и для исходящих соединений.,

      Итак, давайте мы вам покажем, как открыть порты в Ubuntu / Debian с помощью UFW.

      Включение UFW на Ubuntu / Debian

      В официальной документации по UFW сказано, что по умолчанию UFW отключен. Давайте проверим это, выполните следующую команду:

      Скорее всего, вы увидите на экране ответ похожий на этот:

      Как вы поняли первым шагом перед настройкой UFW является его включение. Для того чтоб включить UFW выделите следующую команду.

      Вы должны увидеть следующий экран:

      Включение UFW на Ubuntu или Debian

      По английски это звучит как-то так «he firewall is active and enabled on system startup»

      Если вы снова проверите статус службы, вы должны получить следующий результат

      Проверить статус UFW в Ubuntu или Debian

      Теперь UFW активен в системе. Далее мы можем начать работать с UFW и открыть нужные нам порты.

      Открытие порт в Ubuntu / Debian с помощью UFW

      С помощью UFW мы можем начать открывать порты. Существует несколько способов сделать это, но все они одинаково просты.

      Перед началом работы всегда полезно быть осторожным с портами, которые вы собираетесь открывать. Многие приложения могут использовать его и через них получать важную информацию. Некоторые порты наоборот сделают брешь в вашей системе. Так что будьте очень осторожны.

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

      Заканчиваем мат. чать и приступаем.

      Чтобы открыть порт с в UFW, мы должны следовать следующему основному синтаксису:

      Например, если мы хотим открыть порт 80, через который работает HTTP. Требуется выполнить вот такую команду:

      Вы получите ответ в терминале подобное этому:

      Открыть порт 80 в Ubuntu или Debian

      В данном случае порт 80 был открыт в обоих протоколах TCP и UDP.

      Также можно указать протокол и порт, который будет открыт. Это очень полезно для контроля трафика.

      Если например вы хотите открыть порт 85, но только для протокола TCP, то вам нужно выполнить следующую команду.

      А если требуется открыть UDP порт, тогда команда будет такой.

      В обоих случаях вы получите ответ, похожий на этот:

      Открыть порт UDP или TCP в Ubuntu и Debian

      Открыть порт в Ubuntu / Debian, указав системную службу

      Некоторые службы и профили определены в UFW. Эти службы используют определенный порт, поэтому мы также можем открыть порты с помощью названия службы. Это очень удобно новичкам, которые не знают какая служба какой порт использует.

      Итак, чтобы открыть порты с помощью этого метода, нам нужно использовать следующий синтаксис:

      И вы должны получить следующий результат:

      Открыть порт SSH в UFW на Ubuntu или Debian

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

      Если вы хотите узнать, какие еще службы вы можете использовать, вы можете ознакомиться с ними, введя команду.

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

      Закрыть порт UFW в Ubuntu и Debian

      Как открыть мы показали, а теперь я покажу вам обратный процесс. Синтаксис аналогичен. Нам требуется просто изменить одно слово в команде с «allow» на «deny«. Например чтоб запретить доступ к порту 80 введите команду.

      Данная команда закроет порт 80 как на TCP, так и UDP. Так же как и в разрешающей команде можно использовать протоколы порта, TCP и UDP.

      Аналогично вы можете сделать то же самое и для служб. Например закрыть порты службы SSH, можно командой.

      Ответ в терминале будет таким:

      Закрыть порт службы SSH в UFW на Ubuntu и Debian

      Таким образом, вы можете контролировать входящий трафик.

      Заключение

      Благодаря UFW открыть порт в Ubuntu / Debian очень легко. В этой инструкции мы показали как открыть или закрыть определенный порт в Ubuntu или Debian.

      Управление портами в Linux (Ubuntu/Debian/CentOS)

      Как много времени проходит с момента заказа сервера на хостинге до первого подключения к готовому серверу? Несколько минут. На сколько полученный сервер готов к тому, чтобы использовать его на полную? На 100%. Ну или почти на 100. Точнее, совсем не на 100. Новый сервер подобен новорождённому ребёнку. У него одежды, нет приобретённого иммунитета и нет почти никаких навыков. Он уязвим для любого внешнего воздействия. И защиту от окружающих угроз мы должны ему дать. Наш новый сервер на начальном этапе не готов противостоять всему, что приходит к нему извне. А значит, его необходимо оснастить защитой. Такая защита для сервера – брандмауэр, или файрвол (firewall), или межсетевой экран.

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

      Управление портами в Ubuntu и Debian

      В операционных системах Ubuntu и Debian для управления брандмауэром довольно часто применяется утилита iptables. Её упрощённым интерфейсом является UFW (Uncomplicated Firewall). Открытие доступа к серверу для какого-либо приложения происходит путём регистрации этого приложения в UFW.

      В Ubuntu интерфейс UFW как правило присутствует по умолчанию, в Debian же необходимо будет сначала его проинсталлировать. Перед установкой брандмауэра рекомендуется обновить репозитории:

      Список приложений, зарегистрированных в брандмауэре, доступен по следующей команде:

      Если вы производите первоначальную настройку межсетевого экрана используя подключение к серверу по ssh , логично было бы сразу же прописать в UFW соответствующее этому протоколу правило:

      Эту команду также можно применить используя соответствующий номер порта вместо имени протокола. Для ssh это, как правило, порт 22:

      В Ubuntu команда для разрешения подключения по ssh выглядит как:

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

      Теперь, можно добавить в UFW правило, которое позволит разрешить передачу данных, например, по порту 80, или другими словами, при помощи протокола http . Это можно прописать командой:

      По аналогии можно также разрешить трафик с использованием порта 443, то есть по протоколу https :

      Подобными инструкциями можно давать разрешения для подключений, использующих несколько портов. Например, так выглядит команда на открытие целого диапазона портов (32810-32814):

      Также, помимо номеров портов и названий протоколов, в разрешительных правилах есть возможность использовать IP-адреса. Вот как выглядит команда, разрешающая подключение только с IP-адреса 10.10.10.233:

      Или из одной определённой подсети:

      Или с одного определённого IP-адреса и только по одному определённому порту:

      Естественно существует возможность и закрыть доступ для уже открытого подключения через определённый порт. Для этого используется команда deny . Следующей командой можно запретить подключения по протоколу http :

      Инструкция для закрытия всех подключений с определённого IP-адреса выглядит следующим образом:

      где 10.10.10.233 – IP-адрес, для которого будут закрыты все соединения на наш сервер.

      Уже созданные правила можно также удалить. Сделать это можно по номеру правила. Чтобы узнать номера правил, используйте следующую команду:

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

      Вывод команды sudo ufw status numbered - Управление портами в Linux

      Номера правил указаны в скобках в начале строки. Например, правило для подключения по 443-му порту имеет номер 3. Исходя из этого, команда для удаления этого правила будет выглядеть как:

      То же самое можно сделать командой:

      Посмотреть текущее состояние межсетевого экрана позволяет команда:

      Просмотр статуса UFW

      Для отключения брандмауэра служит следующая инструкция:

      Управление портами в Centos

      Клиентским интерфейсом для работы с межсетевым экраном в Centos является программа firewalld. Как правило, firewalld уже по умолчанию входит в состав служб Centos. Но если вдруг это не так, для его установки используйте следующие команды:

      Если окажется, что firewalld уже был установлен в системе, команда вернёт следующее сообщение:

      Сообщение об уже установленном firewalld

      Текущее состояние службы можно увидеть набрав команду:

      Если служба работает штатно, то вывод команды будет выглядеть так:

      Просмотр статуса firewalld

      Список приложений, которым доступ в firewalld уже предоставлен, можно увидеть с помощью команды:

      Такие приложения перечислены в строке services :

      Вывод команды sudo firewall-cmd --permanent --list-all

      Чтобы предоставить приложению или протоколу, например, http , возможность производить подключения к нашему серверу, необходимо использовать команду следующего вида:

      Этот протокол должен добавиться в строку services :

      Вывод команды sudo firewall-cmd --permanent --list-all - Управление портами в Linux

      Аналогичным образом можно открыть доступ для подключений к серверу по протоколу https :

      Вывод команды sudo firewall-cmd --permanent --list-all - Управление портами в Linux

      В firewalld также есть возможность предоставить доступ для подключений по определённому порту. Так, например, будет выглядеть команда для открытия доступа по udp-порту 32810:

      А так пишется команда для открытия доступа по пулу портов, например, для udp-портов с 32811 по 32814:

      И чтобы убедиться, что данные порты добавлены в список открытых, необходимо использовать следующую инструкцию:

      Список открытых портов в firewalld

      Доступ для подключений по определённому порту можно также и заблокировать. Например, закрытие доступа по udp-порту 32814 осуществляется командой:

      И наконец, для применения всех внесённых изменений, брандмауэр необходимо перезапустить:

      Заключение

      Итак, мы рассмотрели установку и запуск межсетевых экранов в операционных системах Linux, таких как Ubuntu, Debian и Centos. А также, мы научились открывать доступ для подключений к нашему серверу через определённые порты и протоколы.

      Configure Firewall (UFW) Open/Close Ports & Enable/Disable

      Robioki Denis

      UFW stands for “Uncomplicated Firewall” is the default firewall tool for Debian based operating systems. It is an alternative program to iptables that simplifies the process of configuring and managing the firewall.

      Generally, iptables is a very advanced tool with powerful functionality, but it’s syntax is very complex and difficult for beginners. While UFW provides user-friendly syntax that makes it easier to manage your firewall. UFW also provides a user-friendly front-end for managing iptables firewall rules.

      UFW may be the appropriate solution for you are looking to secure your network easily.

      In this tutorial, we will show you how to install and use UFW firewall on Linux.

      Requirements

      • A server running Ubuntu operating system.
      • A root password is configured on your system.

      Install UFW

      By default, UFW is installed in most Ubuntu operating systems. If not installed, you can install it by running the following command:

      apt-get install ufw -y

      Once the installation is completed, you can check the status of UFW firewall with the following command:

      You should see the following output:

      You can check all the options available with UFW using the following command:

      You should see the following screen:

      Configure UFW Default Policies

      By default, UFW is configured to allow all outgoing connections and deny all incoming connections. Before started with your UFW firewall, set your UFW firewall rules back to the defaults. You can set the default policy with the following commands:

      ufw default deny incoming
      ufw default allow outgoing

      Now, anyone trying to access your server can not be able to connect your server.

      Next, you will need to activate the UFW firewall to apply the changes. Before activating the UFW firewall, it is recommended to allow incoming SSH connection to access your server from a remote location. You can allow incoming SSH connection with the following command:

      If your SSH is configured to listen on a different port (2222 )then run the following command:

      Now, you can enable the UFW firewall using the following command:

      Allow incoming Connections

      There are several ways to allow incoming connections like, allow specific port, allow specific port range, allow specific IP address, allow specific subnet and allow specific network interface.

      Allow Specific Port

      By default UFW is configured to deny all incoming connections. So you will need to allow specific port as per your need.

      For example, to allow incoming HTTP connections run the following command:

      You can also specify port number instead service name as shown below:

      ufw allow 80/tcp

      To allow incoming connection on UDP port 21 run the following command:

      ufw allow 21/udp

      You can see a sample output of the above commands in the following screen:

      You can also check the status of UFW firewall with the following command:

      You should see the following screen:

      Allow Specific Port Range

      Instead of allowing single ports UFW also allows you to specify multiple port numbers in a single command. For example, you can allow incoming connections from ports 8000 to 9000 with the following command:

      To allow UDP port range 8000 to 9000, run the following command:

      ufw allow 8000:9000/tcp

      Allow Specific IP Address

      UFW allows you to access all ports from a specific IP address. For example, if you want to allow all incoming connections from the IP address 192.168.0.100 run the following command:

      ufw allow 8000:9000/udp

      You can also allow access to specific port (8080) from the specific IP address (192.168.0.101).

      ufw allow from 192.168.0.100

      Allow Specific Subnet

      You can also allow incoming connections from a range of IP addresses. For example, to allow all incoming connections from the IP address 192.168.0.1 to 192.168.0.254 run the following command:

      ufw allow from 192.168.0.101 to any port 8080

      You can also specify the destination port 8089 that the subnet 192.168.0.0/24 is allowed to connect to as shown below:

      ufw allow from 192.168.0.0/24

      Allow Specific Network Interface

      If you want to add firewall rules that only apply to a specific network interface (eth0). For example, allow all incoming connections to the network interface eth0 run the following command:

      ufw allow from 192.168.0.0/24 to any port 8089

      You can allow access on a specific port 9000 only to specific interface eth0 by running the following command:

      ufw allow in on eth0

      Deny incoming Connections

      You can deny all incoming connections on port 80, 443 and 25 with the following command:

      ufw allow in on eth0 to any port 9000

      To deny all incoming connections from specific subnet, run the following command:

      To deny all incoming connections from specific IP address, run the following command:

      ufw deny from 192.168.1.0/24

      List Application Profile

      By default, all application profile saved in the /etc/ufw/applications.d directory. You can list all application profile with the following command:

      ufw deny from 192.168.0.102

      You should see the following output:

      You can also see the information about a specific application with the following command:

      You should see the following output:

      You can see a sample output of above commands in the following screen:

      ufw app info Apache

      Delete UFW Rules

      There are two ways you can delete UFW rules, with the actual rule and with rule numbers.

      The first method to delete a rule by specifying the actual rule. For example, to delete a rule for port 80 and 443 run the following command:

      The second method to delete a rule by specifying rule numbers. First, you will need to find the number of the rule you want to delete. You can list all the rules with numbers as shown below:

      You should see the following output:

      Now, delete the rule number 6 with the following command:

      ufw status numbered

      To delete the rule number 3, run the following command:

      You can see the sample output of all commands in the following screen:

      Enable UFW Logging

      Enabling UFW logging is very useful to troubleshoot your firewall rules.

      You can enable logging with the following command:

      You can also disable the UFW logging any time with the following command:

      By default, UFW logs are stored in the file /var/log/ufw.log. You can see it with the following command:

      Reset & Disable UFW

      If you want to revert all of your changes that you have made with UFW, run the following command:

      ufw logging off

      The above command will disable UFW and delete all active rules.

      In some cases, you want to disable and deactivate all the rules. You can do it with the following command:

      tail -f /var/log/ufw.log

      Conclusion

      In the above tutorial, we learned how to install, configure and working with UFW firewall. I hope you have now enough knowledge to secure your system with the UFW.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом