Centos 7 firewall open port. Default firewall rules

Installed in operating system Firewall is used to prevent unauthorized traffic from passing between computer networks. Special rules for the firewall are created manually or automatically, which are responsible for access control. An OS developed on the Linux kernel, CentOS 7 has a built-in firewall, and it is managed using a firewall. FirewallD is enabled by default, and we would like to talk about setting it up today.

As mentioned above, the standard firewall in CentOS 7 is the FirewallD utility. That is why setting up a firewall will be discussed using this tool as an example. You can set filtering rules using the same iptables, but this is done in a slightly different way. We recommend that you familiarize yourself with the configuration of the mentioned utility by clicking on the following link, and we will begin analyzing FirewallD.

Firewall Basics

There are several zones - sets of rules for managing traffic based on trust in networks. All of them are given their own policies, the totality of which forms the firewall configuration. Each zone is assigned one or more network interfaces, which also allows you to adjust filtering. The applied rules directly depend on the interface used. For example, when connecting to a public Wi-Fi network the screen will increase the level of control, and in home network will open additional access for chain participants. The firewall in question contains the following zones:

  • trusted - maximum level trust in all network devices;
  • home - group local network. There is trust in the environment, but incoming connections are only available to certain machines;
  • work - work zone. There is trust in most devices, and additional services are activated;
  • dmz is a zone for isolated computers. Such devices are disconnected from the rest of the network and allow only certain incoming traffic;
  • internal — zone of internal networks. Trust is applied to all machines, additional services are opened;
  • external — zone reverse to the previous one. In external networks, NAT masquerading is active, closing the internal network, but not blocking the ability to gain access;
  • public - a zone of public networks with distrust of all devices and individual reception of incoming traffic;
  • block - all incoming requests are reset with an error sent icmp-host-prohibited or icmp6-adm-prohibited;
  • drop - minimum trust level. Incoming connections are dropped without any notification.

The policies themselves can be temporary or permanent. When parameters appear or edit, the firewall action immediately changes without the need to reboot. If temporary rules were applied, they will be reset after FirewallD is restarted. The permanent rule is called that way - it will be saved permanently when the -permanent argument is applied.

Enabling FirewallD

First you need to start FirewallD or make sure that it is in an active state. Only a functioning daemon (a program running in background) will apply the firewall rules. Activation is done in just a few clicks:

  1. Launch classic "Terminal" any convenient method, for example, through the menu "Applications".
  2. Enter the command sudo systemctl start firewalld.service and press the key Enter.
  3. The utility is managed on behalf of the superuser, so you will have to confirm your authenticity by entering a password.
  4. To make sure the service is functioning, specify firewall-cmd --state .
  5. In the graphical window that opens, re-confirm your authenticity.
  6. A new line will be displayed. Meaning "running" indicates that the firewall is working.

If you ever need to temporarily or permanently disable the firewall, we recommend using the instructions presented in our other article at the following link.

View default rules and available zones

Even a firewall operating normally has its own specific rules and accessible zones. Before you start editing policies, we recommend that you familiarize yourself with the current configuration. This is done using simple commands:

  1. The firewall-cmd --get-default-zone command will help you determine the default zone.
  2. After activating it, you will see a new line where the required parameter will be displayed. For example, in the screenshot below, the zone is considered active "public".
  3. However, several zones can be active at once, and they are associated with a separate interface. Find out this information via firewall-cmd --get-active-zones .
  4. The firewall-cmd --list-all command will display the rules configured for the default zone. Take a look at the screenshot below. You see that the active zone "public" rule assigned "default"- default operation, interface "enp0s3" and two services were added.
  5. If you want to find out all the available firewall zones, enter firewall-cmd --get-zones .
  6. The parameters of a specific zone are determined via firewall-cmd --zone=name --list-all , where name— zone name.

After defining required parameters you can proceed to modifying and adding them. Let's take a closer look at a few of the most popular configurations.

Setting up interface zones

As you know from the information above, each interface has its own default zone. It will remain there until the settings are changed by the user or programmatically. It is possible to manually transfer an interface to a zone for one session, and this is done by activating the command sudo firewall-cmd --zone=home --change-interface=eth0 . Result "success" indicates that the transfer was successful. Let us remind you that such settings are reset immediately after the firewall is rebooted.

When changing parameters like this, you should take into account that the services may be reset. Some of them do not support operation in certain zones, for example, although SSH is available in "home", but in custom or special ones the service will refuse to work. You can verify that the interface has been successfully linked to the new branch by entering firewall-cmd --get-active-zones .

If you want to reset your previously made settings, simply restart the firewall: sudo systemctl restart firewalld.service .

Sometimes it is not always convenient to change the interface zone for just one session. In this case, you will need to edit the configuration file so that all settings are entered on a permanent basis. To do this, we recommend using a text editor nano, which is installed from the official repository with sudo yum install nano . Next, all that remains is to do the following:

  1. Open the configuration file through an editor by typing sudo nano /etc/sysconfig/network-scripts/ifcfg-eth0 , where eth0— the name of the required interface.
  2. Confirm authenticity account to perform further actions.
  3. Find the parameter "ZONE" and change its value to the desired one, for example, public or home .
  4. Hold down the keys Ctrl+O to save changes.
  5. Don't change the file name, just click on Enter.
  6. Exit text editor through Ctrl+X.

Now the interface zone will be as you specified it until the next time you edit the configuration file. To make the updated settings take effect, run sudo systemctl restart network.service and sudo systemctl restart firewalld.service .

Setting the default zone

Above, we already demonstrated a command that allowed us to find out the default zone. It can also be changed by setting a parameter of your choice. To do this, just type sudo firewall-cmd --set-default-zone=name in the console, where name— name of the required zone.

The success of the command will be indicated by the inscription "success" on a separate line. After this, all current interfaces will be bound to the specified zone, unless otherwise specified in the configuration files.

Creating rules for programs and utilities

At the very beginning of the article, we talked about the action of each zone. Defining services, utilities and programs in such branches will allow you to apply individual parameters for each of them to suit the needs of each user. First, we recommend that you familiarize yourself with the full list of currently available services: firewall-cmd --get-services .

The result will be displayed directly in the console. Each server is separated by a space, and you can easily find the tool you are interested in in the list. If the required service is not available, it should be additionally installed. Read about installation rules in the official software documentation.

The above command shows only the service names. Detailed information for each of them is obtained through an individual file located along the path /usr/lib/firewalld/services. Such documents have XML format, the path, for example, to SSH looks like this: /usr/lib/firewalld/services/ssh.xml, and the document has the following content:

SSH
Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.

Service support in a specific zone is activated manually. IN "Terminal" you should issue the command sudo firewall-cmd --zone=public --add-service=http , where --zone=public- zone for activation, and --add-service=http— name of the service. Please note that such a change will only apply to one session.

Permanent addition is done via sudo firewall-cmd --zone=public --permanent --add-service=http , and the result "success" indicates the successful completion of the operation.

View full list You can create permanent rules for a specific zone by displaying the list in a separate console line: sudo firewall-cmd --zone=public --permanent --list-services .

Solving the problem of lack of access to the service

By default, firewall rules list the most popular and secure services as allowed, but some standard or third party applications he blocks. In this case, the user will need to manually change the settings to resolve the access problem. This can be done in two different ways.

Port forwarding

As you know, all network services use a specific port. It is easily detected by the firewall, and blocking can be carried out using it. To avoid such actions from the firewall, you need to open the required port with the command sudo firewall-cmd --zone=public --add-port=0000/tcp , where --zone=public- port area, --add-port=0000/tcp— port number and protocol. The firewall-cmd --list-ports option will display a list of open ports.

If you need to open ports included in the range, use the line sudo firewall-cmd --zone=public --add-port=0000-9999/udp , where --add-port=0000-9999/udp— range of ports and their protocol.

The above commands will only allow you to test the use of such parameters. If it was successful, you should add the same ports to the permanent settings, and this is done by entering sudo firewall-cmd --zone=public --permanent --add-port=0000/tcp or sudo firewall-cmd --zone=public --permanent --add-port=0000-9999/udp . The list of open permanent ports is viewed like this: sudo firewall-cmd --zone=public --permanent --list-ports .

Service Definition

As you can see, adding ports does not cause any difficulties, but the procedure becomes more complicated when applications are used a large number of. It becomes difficult to track all the ports in use, so a better option would be to define the service:


All you have to do is choose the most appropriate method for solving problems with access to the service and follow the instructions provided. As you can see, all actions are performed quite easily, and no difficulties should arise.

Creating custom zones

You already know that FirewallD initially created a large number of different zones with certain rules. However, there are situations when system administrator you need to create a custom zone, such as "publicweb" for an installed web server or "privateDNS"— for the DNS server. Using these two examples, we will look at adding branches:


In this article, you learned how to create custom zones and add services to them. We have already talked about setting them by default and assigning interfaces above; all you have to do is indicate the correct names. Remember to reboot your firewall after making any permanent changes.

As you can see, the FirewallD firewall is a fairly comprehensive tool that allows you to create the most flexible firewall configuration. All that remains is to make sure that the utility starts with the system and the specified rules immediately begin their work. Do this with the command sudo systemctl enable firewalld.

FirewallD is a firewall management tool available by default on CentOS 7 servers. It is basically a wrapper around IPTables and comes with a graphical configuration tool, firewall-config, and a firewall-config tool. command line firewall-cmd. With the IPtables service, every change requires deleting old rules and creating new rules in the file ` /etc/sysconfig/iptables`, and with firewalld only the differences are applied.

FirewallD zones

FirewallD uses services and zones instead of rules and chains in Iptables. By default, the following zones are available:

  • drop– Discard all incoming messages network packets no response, outgoing only network connections available.
  • block– Reject all incoming network packets with the message icmp-host-prohibited, only outgoing network connections are allowed.
  • public– only selected incoming connections are accepted, for use in public areas
  • external– For external networks with masquerading, only selected incoming connections are accepted.
  • dmz– demilitarized zone DMZ, publicly accessible with limited access to the internal network, only selected incoming connections are accepted.
  • work
  • home– For computers in the home zone, only selected incoming connections are accepted.
  • internal– For computers on your internal network, only selected incoming connections are accepted.
  • trusted– All network connections are accepted.

To get a list of all available zones:

# firewall-cmd --get-zones work drop internal external trusted home dmz public block

To view a list of default zones:

# firewall-cmd --get-default-zone public

To change the default zone:

Firewall Services

FirewallD services are XML configuration files containing service entry information for firewalld. To get a list of all available services:

# firewall-cmd --get-services amanda-client amanda-k5-client bacula bacula-client ceph ceph-mon dhcp dhcpv6 dhcpv6-client dns docker-registry dropbox-lansync freeipa-ldap freeipa-ldaps freeipa-replication ftp high-availability http https imap imaps ipp ipp-client ipsec iscsi-target kadmin kerberos kpasswd ldap ldaps libvirt libvirt-tls mdns mosh mountd ms-wbt mysql nfs ntp openvpn pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy proxy-dhcp ptp pulseaudio puppetmaster radius rpc-bind rsyncd samba samba-client sane smtp smtps snmp snmptrap squid ssh synergy syslog syslog-tls telnet tftp tftp-client tinc tor-socks transmission-client vdsm vnc-server wbem-https xmpp-bosh xmpp-client xmpp-local xmpp-server

Configuration files XML is stored in directories /usr/lib/firewalld/services/ And /etc/firewalld/services/.

Setting up a firewall with FirewallD

As an example, here's how you can configure a firewall with FirewallD if you're running a web server, SSH on port 7022, and a mail server.

First we will set the default zone for DMZ.

# firewall-cmd --set-default-zone=dmz # firewall-cmd --get-default-zone dmz

To add persistent service rules for HTTP and HTTPS in the DMZ, run the following command:

# firewall-cmd --zone=dmz --add-service=http --permanent # firewall-cmd --zone=dmz --add-service=https --permanent

Open port 25 (SMTP) and port 465 (SMTPS):

Firewall-cmd --zone=dmz --add-service=smtp --permanent firewall-cmd --zone=dmz --add-service=smtps --permanent

Open, IMAP, IMAPS, POP3 and POP3S ports:

Firewall-cmd --zone=dmz --add-service=imap --permanent firewall-cmd --zone=dmz --add-service=imaps --permanent firewall-cmd --zone=dmz --add-service= pop3 --permanent firewall-cmd --zone=dmz --add-service=pop3s --permanent

Since the SSH port is changed to 7022, we will remove the SSH service (port 22) and open port 7022

Firewall-cmd --remove-service=ssh --permanent firewall-cmd --add-port=7022/tcp --permanent

To implement the changes we need to restart the firewall:

Firewall-cmd --reload

Finally, you can list the rules.

The first step to protecting the server from external threats is a firewall, which filters incoming and outgoing traffic. In this article I want to discuss setting up iptables, a special case of a firewall on CentOS, and also talk about installing and disabling it. My guide will not be exhaustive; I will only consider those aspects that I consider the most important and that I myself use in my work.

This article is part of a single series of articles about the server.

Introduction

Iptables is currently the de facto standard among modern Linux distributions. I can’t even remember right off the bat what else is used as a firewall. So any Linux administrator has to deal with setting up this firewall in their work.

There are different connections to this firewall that are used for more “convenient” configuration. Ubuntu has ufw, in centos - firewalld, I don’t know the others. Personally, I don't see any convenience in using these tools. I'm used to setting up a Linux firewall the old fashioned way, as I learned at the very beginning of my work. I think this is the simplest and most convenient way, which I will share with you. Its essence boils down to the fact that a script is created with firewall rules. This script can be easily edited to suit your needs and transferred from server to server.

Disabling firewalld

I have already touched on the issue of disabling firewalld in the topic on . First of all, let's disable firewalld, which is present in centos 7 by default immediately after installation:

# systemctl stop firewalld

Now let’s remove it from startup so that it doesn’t turn on again after a restart:

# systemctl disable firewalld

After this, the firewall settings on the server become completely open. You can view iptables rules with the command:

Installing iptables

In fact, we already have a firewall on our server and it’s working, there are simply no rules, everything is open. We will need to install additional management utilities, without which it is impossible to configure iptables. For example, it will not be possible to restart the firewall:

# systemctl restart iptables.service Failed to issue method call: Unit iptables.service failed to load: No such file or directory.

Or you won’t be able to add it to autorun:

# systemctl enable iptables.service Failed to issue method call: No such file or directory

To avoid such errors, install the necessary package with utilities:

# yum -y install iptables-services

Now you can add iptables to startup and run:

# systemctl enable iptables.service # systemctl start iptables.service

Setting up a firewall

I use a script to manage firewall rules. Let's create it:

# mcedit /etc/iptables.sh

Next we will fill it with the necessary rules. I will parse all the significant parts of the script, and I will give it in full in the form text file at the end of the article. The rules are made in the form of pictures to prohibit copying and pasting. This can lead to errors in the operation of the rules, which I myself encountered while preparing the article.

We will consider a situation where the server is a gateway to the Internet for a local network.

First of all, let's set all the variables that we will use in the script. This is not necessary, but is recommended because it is convenient to transfer settings from server to server. It will be enough to simply reassign the variables.

Before applying the new rules, we clear all chains:

We block all traffic that does not match any of the rules:

Allow all localhost and local traffic:

We allow ping:

If you don't need this, then don't add allowing rules for icmp.

We open Internet access to the server itself:

If you want to open all incoming server connections, then add the following rule:

Now let's add protection against the most common network attacks. First, let's discard all packets that have no status:

Blocking null packets:

Protecting yourself from syn-flood attacks:

If you do not set restrictions on access from the local network, then we allow everyone to access the Internet:

Next we prohibit access from the Internet to the local network:

In order for our local network to use the Internet, we enable nat:

In order not to lose access to the server, after applying the rules, we allow connections via ssh:

And at the end we write down the rules so that they apply after a reboot:

We have compiled a simple config that blocks all incoming connections except ssh and allows access from the local network to the Internet. At the same time, we protected ourselves from some network attacks.

Save the script, make it executable and run:

# chmod 0740 /etc/iptables.sh # /etc/iptables.sh

Let's review the rules and check if all the rules are in place:

# iptables -L -v -n

Please note that you only need to apply the rules if you have access to the server console. If there is an error in the settings, you may lose access. Make sure that in an emergency you can disable the firewall and adjust the settings.

Opening ports

Now let’s expand our configuration a little and open ports in iptables for some services. Let's say we have a web server running and we need to open access to it from the Internet. Add rules for web traffic:

Permission has been added for incoming connections on ports 80 and 443, which the web server uses in its work.

If you have installed mail server, then you need to allow incoming connections to it on all used ports:

For correct operation DNS servers, you need to open UDP port 53

Port forwarding

Let's consider a situation when it is necessary to forward ports from an external interface to some computer on the local network. Let's say you need to get rdp access to computer 10.1.3.50 from the Internet. We forward TCP port 3389:

If you do not want to expose a known port from the outside, you can redirect from a non-standard port to the rdp port of the target computer:

If you forward a port from outside to the local network, be sure to comment out the rule that blocks access from the external network to the internal one. In my example this rule is: $IPT -A FORWARD -i $WAN -o $LAN1 -j REJECT

Or before this rule, create an allowing rule for external access to the internal service, for example like this:

$IPT -A FORWARD -i $WAN -d 10.1.3.50 -p tcp -m tcp --dport 3389 -j ACCEPT

Enabling logs

During setup, it is useful to enable logs to monitor blocked packages and find out why there is no access to the necessary services that we seem to have already opened. I send all blocked packets to separate chains (block_in, block_out, block_fw) corresponding to the direction of traffic and mark each direction in the logs. This makes it more convenient to do debriefing. Add the following rules to the very end of the script, before saving the settings:

You can track all blocked packages in the /var/log/messages file.

After you finish setting up, comment out these lines and disable logging. It’s definitely worth doing this, as the logs grow very quickly. I personally don’t see any practical sense in storing such information.

How to disable iptables

If you suddenly decide that you no longer need the firewall, you can disable it as follows:

# systemctl stop iptables.service

This command stops the firewall. And the following removes it from startup:

# systemctl disable iptables.service

By disabling the firewall, we allowed all connections.

Conclusion

As promised, I am posting a finished script with the basic set of rules that we have considered

I would like to point out once again that when setting up iptables you need to be extremely careful. Do not start this business if you do not have access to the server console. Even while writing this article, I lost access to the server due to a ridiculous error in the rules. This error arose due to copying and the loss of a double dash - it was replaced by a single one.

online course “Linux Administrator” at OTUS. The course is not for beginners; to enroll you need basic knowledge of networks and installing Linux on a virtual machine. The training lasts 5 months, after which successful course graduates will be able to undergo interviews with partners. What this course will give you:

  • Knowledge of Linux architecture.
  • Mastering modern methods and tools for data analysis and processing.
  • Ability to select a configuration for the required tasks, manage processes and ensure system security.
  • Proficient in the basic working tools of a system administrator.
  • Understanding of the specifics of deploying, configuring and maintaining networks built on Linux.
  • The ability to quickly solve emerging problems and ensure stable and uninterrupted operation of the system.
Test yourself on the entrance test and see the program for more details.

But iptables commands are complex, and many users have a hard time remembering all the options and when to use them. Therefore, distribution developers create their own add-ons over iptables, which help simplify firewall management. CentOS has an add-on for managing iptables called Firewalld.

Firewalld has several important differences compared to iptables. Here, network access control is performed at the level of zones and services, rather than chains and rules. And also the rules are updated dynamically, without interrupting running sessions. This article will look at setting up Firewall CentOS 7 using Firewalld as an example.

As I said above, Firewalld does not work with rule chains, but with zones. Each network interface can be assigned a specific zone. A zone is a set of rules, restrictions, and permissions that apply to that network interface. Only one zone can be selected per interface. The developers have created several preset zones:

  • drop- block all incoming packets, allow only outgoing ones
  • block- unlike the previous option, a message will be sent to the sender of the package to block his package;
  • public- incoming connections are supported only for ssh and dhclient;
  • external- supports NAT to hide the internal network;
  • internal- ssh, samba, mdns and dhcp services are allowed;
  • dmz- used for isolated servers that do not have access to the network. Only connections via SSH are allowed;
  • work- ssh and dhcp services are allowed;
  • home- similar to internal;
  • trusted- everything is allowed.

Thus, to allow or deny a service, you just need to add or remove it from the current zone or change the interface zone to one where it is allowed. An analogy can be drawn with the default action policy for packets in iptables. The trusted zone has an ACCEPT policy and allows all connections, the block zone has a DENY policy, which denies all connections, and all other zones can be considered successors of the block zone, plus they already have predefined rules for allowing network connections for some services.

Firewalld also has two types of configuration:

  • runtime- valid only until reboot, all changes that are not explicitly stated otherwise apply to this configuration;
  • permanent- permanent settings that will work even after a reboot.

Now you know everything you need, so let's move on to the firewalld-cmd utility.

Firewall-cmd syntax and options

You can manage Firewalld settings using: console utility firewall-cmd, and in graphical interface. CentOS is most often used on servers, so you will have to work in a terminal. Let's look at the syntax of the utility:

firewall-cmd options

The following syntax is used to manage zones:

firewall-cmd --configuration --zone=option zone

As a configuration, you need to specify the --permanent option to save changes after a reboot or specify nothing, then the changes will only be valid until a reboot. For the zone, use the name of the desired zone. Let's look at the utility options:

  • --state- display the firewall status;
  • --reload- reload the rules from the permanent configuration;
  • --complete-reload - hard reboot rules with breaking all connections;
  • --runtime-to-permanent- transfer runtime configuration settings to permanent configuration;
  • --permanent- use a permanent configuration;
  • --get-default-zone- display the default zone;
  • --set-default-zone- set the default zone;
  • --get-active-zones- display active zones;
  • --get-zones- display all available zones;
  • --get-services- display predefined services;
  • --list-all-zones- display the configuration of all zones;
  • --new-zone- create a new zone;
  • --delete-zone- delete a zone;
  • --list-all- display everything that has been added from the selected zone;
  • --list-services- display all services added to the zone;
  • --add-service- add a service to the zone;
  • --remove-service- remove the service from the zone;
  • --list-ports- display ports added to the zone;
  • --add-port- add a port to the zone;
  • --remove-port- remove the port from the zone;
  • --query-port- show whether the port has been added to the zone;
  • --list-protocols- display protocols added to the zone;
  • --add-protocol- add a protocol to the zone;
  • --remove-protocol- delete the protocol from the zone;
  • --list-source-ports- display source ports added to the zone;
  • --add-source-port- add a source port to the zone;
  • --remove-source-port- remove the source port from the zone;
  • --list-icmp-blocks- display a list of icmp blocking;
  • --add-icmp-block- add icmp blocking;
  • --add-icmp-block- remove icmp blocking;
  • --add-forward-port- add a port for redirection to NAT;
  • --remove-forward-port- remove the port for redirection to NAT;
  • --add-masquerade- enable NAT;
  • --remove-masquerade- remove NAT.

These are not all the options of the utility, but for this article they will be enough for us.

Setting up Firewall in CentOS 7

1. Firewall status

The first step is to look at the state of the firewall. To do this, run:

sudo systemctl status firewalld

If the Firewalld service is disabled, you need to enable it:

sudo systemctl start firewalld
sudo systemctl enable firewalld

Now you need to see if Firewalld is running using the firewall-cmd command:

sudo firewall-cmd --state

If the program is running and everything is fine, you will receive a "running" message.

2. Zone management

As you already understand, zones are the main tool for management network connections. To view the default zone, run:

sudo firewall-cmd --get-default-zone

In my case, this is the public zone. You can change the current zone using the --set-default-zone option:

sudo firewall-cmd --set-default-zone=public

To see which zones are in use for all network interfaces, run:

sudo firewall-cmd --get-active-zones

The list will display the zones and interfaces to which they are assigned. With this command you can view the configuration for a specific zone. For example, for the public zone:

3. Setting up services

You can view all predefined services with the command:

sudo firewall-cmd --get-services

The command will list all available services, you can add any of them to the zone to allow it. For example, let's allow a connection to http:

sudo firewall-cmd --zone=public --add-service=http --permanent

And to remove this service, run:

sudo firewall-cmd --zone=public --remove-service=http --permanent

In both cases we used the --permanent option to ensure that the configuration persists across reboots. After the changes you need to update the rules:

sudo firewall-cmd --reload

Then, if you look at the zone configuration, the added service will appear there:

sudo firewall-cmd --zone=public --list-all

4. How to open a port in Firewalld

If there is no service for the program you need, you can open its port manually. To do this, simply add the desired port to the zone. For example port 8083:

sudo firewall-cmd --zone=public --add-port=8083/tcp --permanent

To remove this port from the zone, run:

sudo firewall-cmd --zone=public --remove-port=8083/tcp --permanent

Similar to services to open a port in firewall centos 7 you need to restart the firewall.

sudo firewall-cmd --reload

5. Firewalld port forwarding

Port probing in Firewalld is much easier to configure than in iptables. If you need, for example, to redirect traffic from port 2223 to port 22, just add a redirect to the zone:

sudo firewall-cmd --zone=public --add-forward-port=port=2223:proto=tcp:toport=22

Here the redirection is performed only on the current machine. If you want to set up a NAT network and forward a port to another machine, then you need to first enable masquerade support:

sudo firewall-cmd --zone=public --add-masquerade

Then you can add the port:

sudo firewall-cmd --zone=public --add-forward-port=port=2223:proto=tcp:toport=22:toaddr=192.168.56.4

6. Advanced rules

If the functionality of zones is not enough for you, you can use advanced rules. The general syntax for advanced rules is:

rule family = "family" source value destination value log audit action

Here are the meanings of the main parameters:

  • As protocol families you can specify ipv4 or ipv6 or specify nothing, then the rule will apply to both protocols;
  • source And destination is the sender and receiver of the packet. These parameters can be IP address, service name, port, protocol, and so on;
  • log- allows you to log the passage of packets, for example in syslog. In this setting, you can specify the log line prefix and the logging detail level;
  • audit- This alternative way logging when messages will be sent to the auditd service.
  • Action is the action that needs to be performed on the matched packet. Available: accept, drop, reject, mark.

Let's look at a few examples. We need to block access to the server for the user with IP 135.152.53.5:

sudo firewall-cmd --zone=public --add-rich-rule "rule family="ipv4" source address=135.152.53.5 reject"

Or we need to deny the same user only access to port 22:

sudo firewall-cmd --zone=public --add-rich-rule "rule family="ipv4" source address=135.152.53.5 port port=22 protocol=tcp reject"

You can view all extended rules with the command:

sudo firewall-cmd --list-rich-rules

conclusions

In this article we looked at how it is done firewall setup in CentOS 7 and what tasks can be performed with it. The program is much easier to use than iptables, but in my opinion the Ubuntu firewall add-on is even easier to use.

Centos 7, unlike CentOS 6, comes with a new firewall in the database - firewalld. It can be disabled and replaced with the good old iptables, but if there are no direct prerequisites for this, then it is better to get used to something new rather than rely on the old. This doesn't mean Windows 10 better than Windows 7, and Windows XP is better than Windows 7 ;) Good example on this topic - selinux. If at first almost everyone (including me) turned it off and even scolded it a little, now almost no one advises it, only if they are sure that it is necessary. On the contrary, many are already accustomed (or are getting used to) using semanage. We won’t immediately disable firewalld, but let’s try how it tastes.

Firewalld is not a fundamentally different firewall. This is another add-on to netfilter, so if you have experience with iptables, then after a little trouble you can easily start using the new tool.

Starting and stopping firewalld

Let's check if firewalld is running:

# systemctl status firewalld

There will be more information here. To briefly say yes (it works) or no, you can do this:

# firewall-cmd --state
running

Ok, it works.

Stopping firewalld:

# systemctl stop firewalld

Auto start prohibition:

# systemctl disable firewalld

Start firewalld:

# systemctl start firewalld

Enabling autostart:

# systemctl enable firewalld

Firewalld zones

Firewalld makes extensive use of the concept of a zone. List of all valid zones by default:

# firewall-cmd --get-zones
block dmz drop external home internal public trusted work

Purpose of zones (conditionally, of course):

  • drop - all incoming packets are discarded (drop) without response. Only outgoing connections are allowed.
  • block - incoming connections are rejected (rejected) with the response icmp-host-prohibited (or icmp6-adm-prohibited). Only system-initiated connections are allowed.
  • public - default zone. From the name it is clear that this zone is aimed at working in public networks. We don't trust this network and only allow certain incoming connections.
  • external - zone for the external interface of the router (so-called masquerading). Only incoming connections that we define are allowed.
  • dmz - DMZ zone, only certain incoming connections are allowed.
  • work - work network zone. We still don't trust anyone, but not as much as before :) Only certain incoming connections are allowed.
  • home - home zone. We trust the environment, but only certain incoming connections are allowed
  • internal - internal zone. We trust the environment, but only certain incoming connections are allowed
  • trusted - everything is allowed.

List of all active zones:

# firewall-cmd --get-active-zones
public
interfaces: enp1s0

Yep, the public zone, to which the enp1so network interface is attached. Next, we’ll add a new port to the public zone on which sshd will hang.

Knowing the name of the network interface (for example, enp1s0), you can find out which zone it belongs to:

# firewall-cmd --get-zone-of-interface=enp1s0
public

You can find out which interfaces belong to a specific zone:

# firewall-cmd --zone=public --list-interfaces
enp1s0

Example: allowing ssh on a non-standard port

Let's allow access to the server via ssh on port 2234/tcp, and not on 22/tcp, as is the default. Along the way, let's touch a little on selinux.

First, let's see what is generally allowed on our server:

# firewall-cmd --permanent --list-all
public (default)
interfaces:
sources:
services: ssh dhcpv6-client
masquerade: no
forward-ports:
icmp-blocks:
rich rules:

I don’t use ipv6 yet, so I’ll immediately remove the corresponding one. rule from firewalld:

# firewall-cmd --permanent --zone=public --remove-service=dhcpv6-client

Let's permanently allow (so that it doesn't get lost after a reboot) the connection to port 2234/tcp (we'll hang sshd on it):

# firewall-cmd --permanent --zone=public --add-port=2234/tcp

Let's reload the rules:

# firewall-cmd --reload

Let's check:

# firewall-cmd --zone=public --list-ports
2234/tcp

Ok, the port is open. Editing the sshd config:

# nano /etc/ssh/sshd_config
...
port 2234
...

# systemctl restart sshd.service

But SELinux, which you hopefully haven’t disabled, will not allow you to connect to ssh on a non-standard port (port 2234/tcp for sshd is non-standard). You can skip this step and check how SELinux protection works, or you can configure everything right away:

# yum provides semanage
# yum install policycoreutils-python
# semanage port -a -t ssh_port_t -p tcp 2234

Now everything is ok. We check the ssh connection on the new port. If everything is ok, close access to port 22:

# firewall-cmd --permanent --zone=public --remove-service=ssh
# firewall-cmd --reload

Let's see what happened:

# firewall-cmd --list-all
public (default, active)
interfaces:
sources:
services:
ports: 2234/tcp
masquerade: no
forward-ports:
icmp-blocks:
rich rules:

That's all.

Various useful commands:

Enable blocking mode for all outgoing and incoming packets:

# firewall-cmd --panic-on

Disable blocking mode for all outgoing and incoming packets:

# firewall-cmd --panic-off

Find out whether blocking mode for all outgoing and incoming packets is enabled:

# firewall-cmd --query-panic

Reload firewalld rules without losing current connections:

# firewall-cmd --reload

Reload firewalld rules and reset current connections (recommended only in case of problems):

# firewall-cmd --complete-reload

Add a network interface to the zone:

# firewall-cmd --zone=public --add-interface=em1

Add a network interface to the zone (will be saved after rebooting the firewall):

# firewall-cmd --zone=public --permanent --add-interface=em1

You can specify in the ifcfg-enp1s0 config which zone this interface belongs to. To do this, add ZONE=work to the file /etc/sysconfig/network-scripts/ifcfg-enp1s0. If the ZONE parameter is not specified, the default zone will be assigned (the DefaultZone parameter in the /etc/firewalld/firewalld.conf file.

Allow port range:

# firewall-cmd --zone=public --add-port=5059-5061/udp

Masquerade (masquerade, aka nat, aka...):

Check status:

# firewall-cmd --zone=external --query-masquerade

Turn on:

# firewall-cmd --zone=external --add-masquerade

It should be noted here that you can enable masquerade for the public zone, for example.

Redirect incoming messages on port 22 to another host:

# firewall-cmd --zone=external --add-forward-port=port=22:proto=tcp:toaddr=192.168.1.23

Redirect incoming messages on port 22 to another host by changing the destination port (from 22 to 192.168.1.23:2055):

# firewall-cmd --zone=external /
--add-forward-port=port=22:proto=tcp:toport=2055:toaddr=192.168.1.23

I'll end here, because... there can be an infinite number of examples. I’ll just add that I personally haven’t fully formed my opinion about the firewalld innovation, because... It takes a long time to get used to the syntax, and if there are different OS Linux in your zoo, then in the first place there may be problems with habit. But mastering firewalld will broaden your horizons—more often than not, it's worth the effort.

Benefits of firewalld

The main advantage is that you are a little abstracted from iptables chains. To enable port forwarding, you do not have to think about PREROUTING or POSTROUTING in addition to FORWARD. You are given "IPtables API from the manufacturer", something like that. If you have enabled nat, then it does not matter where exactly (under what serial number of the current rules) the rule is located. You simply indicate - enable nat on eth0. And no nonsense;) This can be convenient if you need to organize a web interface for managing your firewall.

It is possible to check the status (for example, whether nat is enabled or not!). And also use this in your scripts, in the logic of your application, for example. I don’t know how to create a status request (on/off) in iptables. You can, of course, do something like iptables -L -t nat | grep "...", but you must admit, this is a little different from running "firewall-cmd --zone=external --query-masquerade". There are, for example, hundreds of VMs with CentOS, in which the names of wan interfaces or something like that may be slightly different. And so you have a universal cmdlet that will give the expected result on different machines.

Disadvantages of firewalld

The main drawback, in my opinion, is that when you get used to it, you will start to get used to “pure” iptables, which is in Debian, and in Ubuntu, and in CentOS, and, in general, everywhere. Even, by the way, in Mikrotik the syntax and chains are similar in type to iptables. This is not for everybody, of course. And a professional doesn’t care what to work with; if there are specific conditions, he will work with what he has. But... I’m a retrograde person and desperately resist (in the absence of obvious advantages) the new products that each major player implements for themselves. RedHat would benefit from having more and more new specialists become firewalld aces.

And if you switched to firewalld, then the pure iptables syntax will only hinder you - there will be a mess or the firewall will simply break down if you start changing/adding rules not using the standard firewalld syntax.

I don't want firewalld! Give me back my old iptables!

If you still want to go back to the past and replace firewalld with iptables, then it’s not at all difficult to do:

This is no place for beginners:

# systemctl disable firewalld
# systemctl stop firewalld

Install good old iptables:

# yum install iptables-services

Launch the firewall:

# systemctl start iptables
# systemctl start ip6tables

Autostart when turned on:

# systemctl enable iptables
# systemctl enable ip6tables

To save iptables rules after reboot:

# /sbin/iptables-save > /etc/sysconfig/iptables
# /sbin/ip6tables-save > /etc/sysconfig/ip6tables

Or the old fashioned way:

# service iptables save

The current rules are in the files:
/etc/sysconfig/iptables
/etc/sysconfig/ip6tables

Restarting iptables (for example, after making any changes):

# systemctl restart iptables.service