Centos 7 open port. Setting up a firewall with FirewallD

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 public Wi-Fi, a firewall will increase the level of control, and on a home network it will provide additional access for participants in the chain. The firewall in question contains the following zones:

  • trusted — maximum level of 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 area. 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. That's why the permanent rule is called that - it will be preserved for permanent basis when using the -permanent argument.

Enabling FirewallD

First you need to start FirewallD or make sure that it is in an active state. Only a running daemon (a program that runs in the background) will apply 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 determining the necessary parameters, you can proceed to changing 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. To get started, we recommend that you familiarize yourself with the full list of available ones on this moment 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 required service missing, it must be installed additionally. 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 are in 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.

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 utilities controls, 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 provide it in full as a 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 are used by web server in your 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 rdp port destination 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; for admission you need basic knowledge of networks and Linux installation to the 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 either using the firewall-cmd console utility or in the 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 of rules with interruption of 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 certain 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 the centos 7 firewall, 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.

Today I will introduce you to my vision of the initial configuration of a universal server on a popular OS. I will talk about how to do the basic setup of a centos server immediately after installation to use it in any capacity at your discretion. Given practical advice increase security and ease of use of the server. The article will be relevant for the two latest Centos releases - 7 and 8.

  1. List the initial centos settings that I perform on a freshly installed server.
  2. Show examples of configurations I use in a typical setup.
  3. Give advice on setting up centos based on your experience with the system.
  4. Provide a list of typical programs and utilities that help administer the server.

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

Introduction

After the release of the new Centos 8 release, it became difficult to describe in a single article initial setup both servers, but I didn't want to split the article because it has a lot of incoming links from different places. It’s more convenient to maintain general material on both releases, which is what I’ll do. At the same time, the differences between the two versions will be clearly visible; for a couple of years after the release of centos 8, both will be relevant and you will have to use both versions, depending on the situation.

Used on Centos 7 package manager yum, and in Centos 8 - dnf. At the same time, they left a symbolic link from yum to dnf, so you can write both the first name and the second. For consistency, I will use yum throughout, but I warn you, just so you understand why I do it this way. In fact, CentOS 8 uses dnf, this is another, more modern package manager that allows you to work with different versions the same software. For this purpose, separate repositories that appeared for centos 8 are used.

Initial setup of CentOS

Personally, I start any system setup, be it centos or another, after installation by completely updating the system. If the installation image was fresh, or the installation was carried out over the network, then most likely there will be no updates. Most often they exist, since installation images are not always updated regularly.

Updating the system

# yum update

For ease of administration, I always install Midnight Commander, or just mc:

# yum install mc

And immediately for it I turn on syntax highlighting for all files that are not explicitly marked in the file /usr/share/mc/syntax/Syntax syntax for sh and bash scripts. This universal syntax is fine for configuration files that you most often need to work with on the server. Overwriting the file unknown.syntax. This is the pattern that will be applied to .conf and .cf files, since there is no explicit syntax attached to them.

# cp /usr/share/mc/syntax/sh.syntax /usr/share/mc/syntax/unknown.syntax

Network utilities will come in handy next. Depending on the set of initial packages that you select when installing the system, you will have one or another set of network utilities. Here is a list of those that I personally am used to - ifconfig, netstat, nslookup and some others. If you need it, just like me, then I suggest installing them separately if they are not already installed. If you don't particularly need them and don't use them, you can skip installing them. Let's check what we have in the system at the moment

# ifconfig

If you see the answer:

Bash: ifconfig: command not found

This means the utility is not installed. Instead of ifconfig in CentOS there is now a utility ip. This applies not only to centos. This is the picture in almost all popular modern Linux distributions. I've been used to ifconfig for a long time, although I haven't used it much lately. I always liked that in different Linux distributions everything is approximately the same. Using ifconfig you can configure the network not only in Linux, but also in freebsd. It's comfortable. And when each distribution has its own tool, this is not convenient. Although now this is no longer very relevant, since I no longer work with Freebsd, and the ip utility is available in all Linux distributions. However, if you need ifconfig, you can install the package net-tools, which includes:

# yum install net-tools

In order for the nslookup or, for example, host commands to work, we need to install the package bind-utils. If this is not done, then use the command:

#nslookup

The output will be:

Bash: nslookup: command not found

So let's install bind-utils:

# yum install bind-utils

Disable SELinux

Disable SELinux. Its use and configuration is a separate matter. I won't do this now. So let's turn it off:

# mcedit /etc/sysconfig/selinux

change the value

SELINUX=disabled

You can reboot for the changes to take effect:

# reboot

And if you want to disable SELinux without rebooting, then run the command:

#setenforce 0

I constantly receive a lot of criticism about disabling SELinux. I know how it works, I know how to configure it. It's really not very complicated and not difficult to master. This is my conscious choice, although sometimes I tweak it. The way I work with the system is such that I most often do not need SELinux, so I don’t waste time on it and disable centos in the basic setup. System security is a complex endeavor, especially in modern world web development, where microservices and containers rule the roost. SELinux is a niche tool that is not needed always and not everywhere. Therefore, it has no place in this article. Those who need it will separately enable SELinux and configure it.

Specifying network parameters

We continue with the basic setup of centos after installation. Now we will do it if for some reason we did not do this during installation, or if you need to change them. IN general case, the network in Centos is configured using NetworkManager and its console utility nmtui. It comes with the basic installation of the system. It's simple and clear GUI, so there's nothing to tell. I'm more used to configuring the network through network-scripts configuration files. In centos version 7 they are present out of the box, in version 8 they were removed. To use them to configure the network, you must separately install the package network-scripts.

# yum install network-scripts

Now you can configure the network. To do this, open the file /etc/sysconfig/network-scripts/ifcfg-eth0

# mcedit /etc/sysconfig/network-scripts/ifcfg-eth0

If you receive network settings via dhcp, then the minimum set of settings in the configuration file will be like this.

TYPE="Ethernet" BOOTPROTO="dhcp" DEFROUTE="yes" IPV4_FAILURE_FATAL="no" NAME="eth0" DEVICE="eth0" ONBOOT="yes"

To configure a static IP address, the settings will be as follows.

TYPE="Ethernet" BOOTPROTO="none" DEFROUTE="yes" IPV4_FAILURE_FATAL="no" NAME="eth0" DEVICE="eth0" ONBOOT="yes" IPADDR=192.168.167.117 DNS1=192.168.167.113 PREFIX=28 GATEWAY= 192.168.167.113

In the IPADDR field we enter your address, in PREFIX the network mask, in GATEWAY the gateway, DNS address of the dns server. Save the file and restart the network to apply the settings:

# systemctl restart network

Setting up a firewall

Adding repositories

When setting up Centos, you often need software that is not included in the standard turnip. For installation additional packages necessary . The most popular is EPEL. There used to be rpmforge, but it has been closed for several years. Everyone forgot about him. We connect the EPEL repository. Everything is simple with it, it is added from the standard turnip:

# yum install epel-release

Also for CentOS 7, the REMI repository is extremely useful, which allows you to install more recent versions of php, unlike those in the standard repository. Let me remind you that this is version PHP 5.4, which is no longer any good and has been removed from support.

# rpm -Uhv http://rpms.remirepo.net/enterprise/remi-release-7.rpm

For Centos 8 remi is not yet relevant, but I think it is temporary. In principle, these two repositories in centos are usually enough for me in the general case. Others are connected for specific needs for installing various software.

Setting up history storage in bash_history

Let's move on with the setup centos systems on server. It will be useful to make some changes to the standard mechanism for saving command history. It often helps out when you need to remember one of the previously entered commands. The standard settings have some limitations that are inconvenient. Here is their list:

  1. By default, only the last 1000 commands are saved. If there are more of them, the older ones will be deleted and replaced with new ones.
  2. There are no execution dates for the commands, just a list of them in order of execution.
  3. The command list file is updated after the session ends. During parallel sessions, some commands may be lost.
  4. Absolutely all commands are saved, although there is no point in storing some.

The list of recently executed commands is stored in the user's home directory in the file .bash_history(dot at the beginning). You can open it with any editor and view it. To display the list more conveniently, you can enter the command in the console:

#history

and see a numbered list. You can quickly find a specific command by filtering only the necessary lines, for example like this:

#history | grep yum

This way we will see all the options for running the yum command, which are stored in history. We will correct the listed shortcomings standard settings storing command history in CentOS. To do this you need to edit the file .bashrc, which is located in the same directory as the history file. Add the following lines to it:

Export HISTSIZE=10000 export HISTTIMEFORMAT="%h %d %H:%M:%S " PROMPT_COMMAND="history -a" export HISTIGNORE="ls:ll:history:w:htop"

The first option increases the file size to 10,000 lines. You can make more, although this size is usually enough. The second parameter specifies that the date and time the command was executed should be stored. The third line forces immediately after executing the command to save it to history. In the last line we create a list of exceptions for those commands that do not need to be recorded in history. I gave an example of the simplest list. You can add it at your discretion.

To apply the changes, you need to log out and connect again or run the command:

# source ~/.bashrc

That's all about setting up command history storage. There are a lot of interesting things you can configure in the .bashrc file. At one time I got carried away and experimented, but then I abandoned everything because it didn’t make sense. When working with customer servers, I most often see the default bash, so it’s better to get used to it and work in it. And individual settings and decorations are the lot of personal computers and servers. Not workers. So I don’t configure anything else according to the standard in the centos server in this regard.

Automatic system update

To maintain server security at the proper level, it is necessary to at least update it in a timely manner - like the kernel itself with system utilities, as well as other packages. You can do this manually, but for more efficient work it is better to configure automatic execution. It is not necessary to install updates automatically, but at least check for their appearance. I usually follow this strategy.

Yum-cron

To automatically check for updates in Centos 7, the utility will help us yum-cron. It is installed traditionally via yum from the standard repository.

# yum install yum-cron

After installing yum-cron, an automatic task is created to run the utility in /etc/cron.daily And /etc/cron.hourly. By default, the utility downloads found updates, but does not apply them. Instead, the administrator on local Mailbox notification of updates is sent to root. Then you are already in manual mode come in and decide whether to install updates or not at a time convenient for you. I find this mode of operation the most convenient, so I do not change these settings.

You can configure yum-cron through the configuration files, which are located at /etc/yum/yum-cron.conf And yum-cron-hourly.conf. They are well commented, so in detailed explanations dont need. I draw your attention to the section , where you can specify parameters for sending messages. By default, mail is sent via local host. You can change the settings here and send messages through a third-party mail server. But instead, I personally prefer to globally configure the entire server to forward local root mail to an external mailbox through authorization on another smtp server.

Dnf-automatic

As I said earlier, Centos 8 uses a different package manager - dnf. Configuring package updates there is done through the utility dnf-automatic. Let's install it and configure it.

# yum install dnf-automatic

It is no longer cron that manages scheduled launches, but systemd with its built-in scheduler. View timers automatic start you can use the command:

# systemctl list-timers *dnf-*

If there are no tasks there, then you can add a timer manually:

# systemctl enable --now dnf-automatic.timer

The default timer is set to start dnf-automatic an hour after the server boots and repeats daily. The timer config lives here - /etc/systemd/system/multi-user.target.wants/dnf-automatic.timer.

The config for dnf-automatic lives in /etc/dnf/automatic.conf. By default, it only downloads updates, but does not apply them. The config is well commented, so you can customize it as you wish. No special explanation is required. Configure updating system packages at your discretion. As I already said, I just download them automatically. I always keep the installation under control with manual control.

Disable message flooding in /var/log/messages

Continuing to configure centos, we will correct one small inconvenience. In the default installation of the 7th version of the system, your entire system log /var/log/messages After some time the server will be clogged with the following records.

Oct 16 14:01:01 xs-files systemd: Created slice user-0.slice. Oct 16 14:01:01 xs-files systemd: Starting user-0.slice. Oct 16 14:01:01 xs-files systemd: Started Session 14440 of user root. Oct 16 14:01:01 xs-files systemd: Starting Session 14440 of user root. Oct 16 14:01:01 xs-files systemd: Removed slice user-0.slice. Oct 16 14:01:01 xs-files systemd: Stopping user-0.slice. Oct 16 15:01:01 xs-files systemd: Created slice user-0.slice. Oct 16 15:01:01 xs-files systemd: Starting user-0.slice. Oct 16 15:01:01 xs-files systemd: Started Session 14441 of user root. Oct 16 15:01:01 xs-files systemd: Starting Session 14441 of user root. Oct 16 15:01:01 xs-files systemd: Started Session 14442 of user root. Oct 16 15:01:01 xs-files systemd: Starting Session 14442 of user root. Oct 16 15:01:01 xs-files systemd: Removed slice user-0.slice. Oct 16 15:01:01 xs-files systemd: Stopping user-0.slice. Oct 16 16:01:01 xs-files systemd: Created slice user-0.slice. Oct 16 16:01:01 xs-files systemd: Starting user-0.slice. Oct 16 16:01:01 xs-files systemd: Started Session 14443 of user root. Oct 16 16:01:01 xs-files systemd: Starting Session 14443 of user root. Oct 16 16:01:01 xs-files systemd: Removed slice user-0.slice.

I didn't notice them in Centos 8, so I don't need to do anything there. No practical benefit They don't carry messages, so we'll turn them off. To do this, we will create a separate rule for rsyslog, where we will list all the message templates that we will cut. Let's place this rule in separate file /etc/rsyslog.d/ignore-systemd-session-slice.conf.

# cd /etc/rsyslog.d && mcedit ignore-systemd-session-slice.conf if $programname == "systemd" and ($msg contains "Starting Session" or $msg contains "Started Session" or $msg contains "Created slice" or $msg contains "Starting user-" or $msg contains "Starting User Slice of" or $msg contains "Removed session" or $msg contains "Removed slice User Slice of" or $msg contains "Stopping User Slice of" ) then stop

Save the file and restart rsyslog to apply the settings.

# systemctl restart rsyslog

It is necessary to understand that in this case we disable flooding in the log file only for local server. If you store logs on , then this rule will need to be configured on it.

Installing iftop, atop, htop, lsof on CentOS

And finally, to complete the setup, let’s add a few useful utilities, which may be useful during server operation.

iftop shows the loading of the network interface in real time, can be launched with various keys, I will not dwell on this in detail, there is information on this topic on the Internet. We put:

# yum install iftop

And two interesting task managers, I most often use htop, but sometimes atop comes in handy. Let's install both, see for yourself, figure out what you like best, what suits you:

# yum install htop # yum install atop

To display information about which files are used by which processes, I advise you to install the utility lsof. It will most likely come in handy sooner or later when you diagnose the server.

# yum install wget bzip2 traceroute gdisk

That's all for me. Basic CentOS setup completed, you can begin installing and configuring the main functionality.

Setting up system mail

To finish setting up the CentOS server, let's make sure that mail addressed to the local root is sent through an external mail server to the selected mailbox. If this is not done, then it will be locally compiled into a file /var/spool/mail/root. And there may be an important helpful information. Let's configure it to be sent to the system administrator's mailbox.

I talked about this in detail in a separate article -. Here are just the commands and quick setup. Install the necessary packages:

# yum install mailx cyrus-sasl cyrus-sasl-lib cyrus-sasl-plain postfix

Let's draw something like this config for postfix.

Cat /etc/postfix/main.cf ## DEFAULT CONFIG BEGIN ###################### queue_directory = /var/spool/postfix command_directory = /usr/sbin daemon_directory = /usr/libexec/postfix data_directory = /var/lib/postfix mail_owner = postfix inet_interfaces = localhost inet_protocols = all unknown_local_recipient_reject_code = 550 alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases debug_peer_level = 2 debugg er_command = PATH =/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5 sendmail_path = /usr/sbin/sendmail.postfix newaliases_path = /usr/bin/ newaliases.postfix mailq_path = /usr/bin/mailq.postfix setgid_group = postdrop html_directory = no manpage_directory = /usr/share/man sample_directory = /usr/share/doc/postfix-2.10.1/samples readme_directory = /usr/share/ doc/postfix-2.10.1/README_FILES ## DEFAULT CONFIG END ###################### # Server name as output by the command hostname myhostname = centos-test. xs.local # Here, logically, you need to leave only the domain, but in this case it is better to leave the full name of the server so that the sender field # contains the full name of the server, this makes it more convenient to parse service messages mydomain = centos-test.xs.local mydestination = $myhostname myorigin = $mydomain # Server address through which we will send mail relayhost = mailsrv.mymail.ru:25 smtp_use_tls = yes smtp_sasl_auth_enable = yes smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_sasl_security_options = noanonymous smtp _tls_security_level = may

We create a file with information about the username and password for authorization.

# mcedit /etc/postfix/sasl_passwd mailsrv.mymail.ru:25 [email protected]:password

Create a db file.

# postmap /etc/postfix/sasl_passwd

Now you can restart postfix and check if it works.

# systemctl restart postfix

To the standard alias for root in /etc/aliases, add an external address where mail addressed to root will be duplicated. To do this, edit the specified file, changing the last line.

#root: marc

Root: root, [email protected]

Updating the certificate database:

#newaliases

Let's send a letter via the console to the local root:

# df -h | mail -s "Disk usage" root

The letter should go to an external mailbox. If you use a mailbox from Yandex, you will most likely receive an error in the mail server log and the letter will not be sent.

Relay=smtp.yandex.ru:25, delay=0.25, delays=0/0/0.24/0.01, dsn=5.7.1, status=bounced (host smtp.yandex.ru said: 553 5.7.1 Sender address rejected: not owned by auth user. (in reply to MAIL FROM command))

This error means that your mail sender is not the same mailbox that you use for authorization. I tell you how to fix this in a separate article -. With other mail systems where there is no such check, everything should be fine as is.

This completes the local mail setup. Now all letters addressed to the local root, for example, reports from cron, will be duplicated to an external mailbox, and sent through a full-fledged mail server. So the letters will be delivered normally, without ending up in spam (although not necessarily, there are also heuristic filters).

Conclusion

We've gone through some initial steps to set up a CentOS server, which is what I usually do when preparing a server right after installation. I don’t pretend to be the absolute truth; I may be missing something or doing something that’s not entirely correct. I will be glad to have reasonable and meaningful comments and suggestions.

..
  • 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.

    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– Drop all incoming network packets without response, only outgoing network connections are 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 from 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 files XML configurations, with 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.

    Internet