One place for hosting & domains

      How To Add and Delete Users on CentOS 8


      Introduction

      When you first start using a fresh Linux server, adding and removing users is often one of first things you’ll need to do. In this guide, we will cover how to create user accounts, assign sudo privileges, and delete users on a CentOS 8 server.

      Prerequisites

      This tutorial assumes you are logged into a CentOS 8 server with a non-root sudo-enabled user. If you are logged in as root instead, you can drop the sudo portion of all the following commands, but they will work either way.

      Adding Users

      Throughout this tutorial we will be working with the user sammy. Please susbtitute with the username of your choice.

      You can add a new user by typing:

      Next, you’ll need to give your user a password so that they can log in. To do so, use the passwd command:

      You will be prompted to type in the password twice to confirm it. Now your new user is set up and ready for use!

      Note: if your SSH server disallows password-based authentication, you will not yet be able to connect with your new username. Details on setting up key-based SSH authentication for the new user can be found in step 5 of Initial Server Setup with CentOS 8.

      Granting Sudo Privileges to a User

      If your new user should have the ability to execute commands with root (administrative) privileges, you will need to give them access to sudo.

      We can do this by adding the user to the wheel group (which gives sudo access to all of its members by default).

      Use the usermod command to add your user to the wheel group:

      • sudo usermod -aG wheel sammy wheel

      Now your new user is able to execute commands with administrative privileges. To do so, append sudo ahead of the command that you want to execute as an administrator:

      You will be prompted to enter the password of the your user account (not the root password). Once the correct password has been submitted, the command you entered will be executed with root privileges.

      Managing Users with Sudo Privileges

      While you can add and remove users from a group with usermod, the command doesn’t have a way to show which users are members of a group.

      To see which users are part of the wheel group (and thus have sudo privileges), you can use the lid command. lid is normally used to show which groups a user belongs to, but with the -g flag, you can reverse it and show which users belong in a group:

      Output

      centos(uid=1000) sammy(uid=1001)

      The output will show you the usernames and UIDs that are associated with the group. This is a good way of confirming that your previous commands were successful, and that the user has the privileges that they need.

      Deleting Users

      If you have a user account that you no longer need, it’s best to delete it.

      To delete the user without deleting any of their files, use the userdel command:

      If you want to delete the user’s home directory along with their account, add the -r flag to userdel:

      With either command, the user will automatically be removed from any groups that they were added to, including the wheel group if applicable. If you later add another user with the same name, they will have to be added to the wheel group again to gain sudo access.

      Conclusion

      You should now have a good grasp on how to add and remove users from your CentOS 8 server. Effective user management will allow you to separate users and give them only the access that is needed for them to do their job.

      You can now move on to configuring your CentOS 8 server for whatever software you need, such as a LAMP or LEMP web stack.



      Source link

      How To Install and Use PostgreSQL on CentOS 8


      Introduction

      Relational database management systems are a key component of many websites and applications. They provide a structured way to store, organize, and access information.

      PostgreSQL, also known as Postgres, is a relational database management system that provides an implementation of Structured Query Language, better known as SQL. It’s used by many popular projects, both large and small, is standards-compliant, and has many advanced features like reliable transactions and concurrency without read locks.

      By following this guide, you will install the latest version of PostgreSQL on a CentOS 8 server.

      Prerequisites

      To complete this tutorial, you will need a server running CentOS 8. This server should have a non-root user with administrative privileges and a firewall configured with firewalld. To set this up, see our Initial Server Setup guide for CentOS 8.

      Step 1 — Installing PostgreSQL

      PostgreSQL is available from CentOS 8’s default AppStream software repository, and there are multiple versions which you can install. You can choose between these versions by enabling the appropriate collection of packages and dependencies that align with the version you want to install, with each collection referred to as a module stream.

      In DNF, CentOS 8’s default package manager, modules are special collections of RPM packages that together make up a larger application. This is intended to make installing packages and their dependencies more intuitive for users.

      List out the available streams for the postgresql module using the dnf command:

      • dnf module list postgresql

      Output

      postgresql 9.6 client, server [d] PostgreSQL server and client module postgresql 10 [d] client, server [d] PostgreSQL server and client module postgresql 12 client, server PostgreSQL server and client module

      You can see in this output that there are three versions of PostgreSQL available from the AppStream repository: 9.6, 10, and 12. The stream that provides Postgres version 10 is the default, as indicated by the [d] following it. If you want to install that version you could just run sudo dnf install postgresql-server and move on to the next step. However, even though version 10 is still maintained, this tutorial will install Postgres version 12, the latest release at the time of this writing.

      To install PostgreSQL version 12, you must enable that version’s module stream. When you enable a module stream, you override the default stream and make all of the packages related to the enabled stream available on the system. Note that only one stream of any given module can be enabled on a system at the same time.

      To enable the module stream for Postgres version 12, run the following command:

      • sudo dnf module enable postgresql:12

      When prompted, press y and then ENTER to confirm that you want to enable the stream:

      Output

      ==================================================================== Package Architecture Version Repository Size ==================================================================== Enabling module streams: postgresql 12 Transaction Summary ==================================================================== Is this ok [y/N]: y

      After enabling the version 12 module stream, you can install the postgresql-server package to install PostgreSQL 12 and all of its dependencies:

      • sudo dnf install postgresql-server

      When given the prompt, confirm the installation by pressing y then ENTER:

      Output

      . . . Install 4 Packages Total download size: 16 M Installed size: 62 M Is this ok [y/N]: y

      Now that the software is installed, you will perform some initialization steps to prepare a new database cluster for PostgreSQL.

      Step 2 — Creating a New PostgreSQL Database Cluster

      You have to create a new PostgreSQL database cluster before you can start creating tables and loading them with data. A database cluster is a collection of databases that are managed by a single server instance. Creating a database cluster consists of creating the directories in which the database data will be placed, generating the shared catalog tables, and creating the template1 and postgres databases.

      The template1 database is a template of sorts used to create new databases; everything that is stored in template1, even objects you add yourself, will be placed in new databases when they’re created. The postgres database is a default database designed for use by users, utilities, and third-party applications.

      The Postgres package we installed in the previous step comes with a handy script called postgresql-setup which helps with low-level database cluster administration. To create a database cluster, run the script using sudo and with the --initdb option:

      • sudo postgresql-setup --initdb

      You will see the following output:

      Output

      * Initializing database in '/var/lib/pgsql/data' * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log

      Now start the PostgreSQL service using systemctl:

      • sudo systemctl start postgresql

      Then, use systemctl once more to enable the service to start up whenever the server boots:

      • sudo systemctl enable postgresql

      This will give the following output

      Output

      Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /usr/lib/systemd/system/postgresql.service.

      Now that PostgreSQL is up and running, we will go over using roles to learn how Postgres works and how it is different from similar database management systems you may have used in the past.

      Step 3 — Using PostgreSQL Roles and Databases

      PostgreSQL uses a concept called roles to handle client authentication and authorization. These are in some ways similar to regular Unix-style accounts, but Postgres does not distinguish between users and groups and instead prefers the more flexible term role.

      Upon installation, Postgres is set up to use ident authentication, meaning that it associates Postgres roles with a matching Unix/Linux system account. If a role exists within Postgres, a Unix/Linux username with the same name is able to sign in as that role.

      The installation procedure created a user account called postgres that is associated with the default postgres role. In order to use PostgreSQL, you can log in to that account.

      There are a few ways to use this account to access the PostgreSQL prompt.

      Switching Over to the postgres Account

      Switch over to the postgres account on your server by typing:

      You can now access a Postgres prompt immediately by typing:

      This will log you into the PostgreSQL prompt, and from here you are free to interact with the database management system right away.

      Exit out of the PostgreSQL prompt by typing:

      This will bring you back to the postgres account’s Linux command prompt. Now return to your original account with the following:

      Accessing a Postgres Prompt Without Switching Accounts

      You can also run commands with the postgres account directly using sudo.

      For instance, in the previous example, you were instructed to access the Postgres prompt by first switching to the postgres user and then running psql to open the Postgres prompt. As an alternative, you could do this in one step by running the single command psql as the postgres user with sudo, like this:

      This will log you directly into Postgres without the intermediary bash shell.

      Again, you can exit the interactive Postgres session by typing:

      In this step, you used the postgres account to reach the psql prompt. But many use cases require more than one Postgres role. Read on to learn how to configure new roles.

      Step 4 — Creating a New Role

      Currently, you just have the postgres role configured within the database. You can create new roles from the command line with the createrole command. The --interactive flag will prompt you for the name of the new role and also ask whether it should have superuser permissions.

      If you are logged in as the postgres account, you can create a new user by typing:

      If, instead, you prefer to use sudo for each command without switching from your normal account, type:

      • sudo -u postgres createuser --interactive

      The script will prompt you with some choices and, based on your responses, execute the necessary Postgres commands to create a user to your specifications. For this tutorial, create a role named sammy and give it superuser privileges by entering y when prompted:

      Output

      Enter name of role to add: sammy Shall the new role be a superuser? (y/n) y

      You can get more control by passing some additional flags. Check out the options by looking at the man page for createuser:

      Your installation of Postgres now has a new role, but you have not yet added any databases. The next section describes this process.

      Step 5 — Creating a New Database

      Another assumption that the Postgres authentication system makes by default is that for any role used to log in, that role will have a database with the same name which it can access.

      This means that if the user you created in the last section is called sammy, that role will attempt to connect to a database which is also called sammy by default. You can create such a database with the createdb command.

      If you are logged in as the postgres account, you would type something like:

      If, instead, you prefer to use sudo for each command without switching from your normal account, you would type:

      • sudo -u postgres createdb sammy

      This flexibility provides multiple paths for creating databases as needed.

      Now that you’ve created a new database, you will log in to it with your new role.

      Step 6 — Opening a Postgres Prompt with the New Role

      To log in with ident-based authentication, you’ll need a Linux user with the same name as your Postgres role and database.

      If you don’t have a matching Linux user available, you can create one with the adduser command. You will have to do this from your non-root account with sudo privileges (meaning, not logged in as the postgres user):

      Once this new account is available, you can either switch over and then connect to the database by first typing:

      Or, you can do this inline:

      This command will log you in automatically.

      If you want your user to connect to a different database, you can do so by including the -d flag and specifying the database, like this:

      Once logged in, you can check your current connection information by typing:

      This will show the following output:

      Output

      You are connected to database "sammy" as user "sammy" via socket in "/var/run/postgresql" at port "5432".

      This is useful if you are connecting to non-default databases or with non-default users.

      Having connected to your database, you can now try out creating and deleting tables.

      Step 7 — Creating and Deleting Tables

      Now that you know how to connect to the PostgreSQL database system, you can learn some basic Postgres management tasks.

      First, create a table to store some data. As an example, you will make a table that describes some playground equipment.

      The basic syntax for this command is as follows:

      CREATE TABLE table_name (
          column_name1 col_type (field_length) column_constraints,
          column_name2 col_type (field_length),
          column_name3 col_type (field_length)
      );
      

      These commands give the table a name, and then define the columns as well as the column type and the max length of the field data. You can also optionally add table constraints for each column.

      For demonstration purposes, create a simple table like this:

      • CREATE TABLE playground (
      • equip_id serial PRIMARY KEY,
      • type varchar (50) NOT NULL,
      • color varchar (25) NOT NULL,
      • location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
      • install_date date
      • );

      This command will create a table that inventories playground equipment. It starts with an equipment ID, which is of the serial type. This data type is an auto-incrementing integer. You’ve also given this column the constraint of PRIMARY KEY, which means that the values must be unique and not null.

      For two of the columns (equip_id and install_date), the command does not specify a field length. This is because some column types don’t require a set length because the length is implied by the type.

      The next two lines create columns for the equipment type and color respectively, each of which cannot be empty. The line after these creates a location column and a constraint that requires the value to be one of eight possible values. The last line creates a date column that records the date on which you installed the equipment.

      You can see your new table by typing:

      This will show the following output:

      Output

      List of relations Schema | Name | Type | Owner --------+-------------------------+----------+------- public | playground | table | sammy public | playground_equip_id_seq | sequence | sammy (2 rows)

      Your playground table is here, but there’s also something called playground_equip_id_seq that is of the type sequence. This is a representation of the serial type that you gave your equip_id column. This keeps track of the next number in the sequence and is created automatically for columns of this type.

      If you want to see just the table without the sequence, you can type:

      This will yield the following:

      Output

      List of relations Schema | Name | Type | Owner --------+------------+-------+------- public | playground | table | sammy (1 row)

      In this step, you created a sample table. In the next step, you will try out adding, querying, and deleting entries in that table.

      Step 8 — Adding, Querying, and Deleting Data in a Table

      Now that you have a table, you can insert some data into it.

      As an example, add a slide and a swing by calling the table you want to add to, naming the columns, and then providing data for each column, like this:

      • INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2017-04-28');
      • INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2018-08-16');

      You should take care when entering the data to avoid a few common hangups. For one, do not wrap the column names in quotation marks, but the column values that you enter do need quotes.

      Another thing to keep in mind is that you do not enter a value for the equip_id column. This is because it is automatically generated whenever a new row in the table is created.

      Retrieve the information you’ve added by typing:

      • SELECT * FROM playground;

      You will see the following output:

      Output

      equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------- 1 | slide | blue | south | 2017-04-28 2 | swing | yellow | northwest | 2018-08-16 (2 rows)

      Here, you can see that your equip_id has been filled in successfully and that all of your other data has been organized correctly.

      If the slide on the playground breaks and you have to remove it, you can also remove the row from your table by typing:

      • DELETE FROM playground WHERE type = 'slide';

      Query the table again:

      • SELECT * FROM playground;

      You will see the following:

      Output

      equip_id | type | color | location | install_date ----------+-------+--------+-----------+-------------- 2 | swing | yellow | northwest | 2018-08-16 (1 row)

      Notice that your slide is no longer a part of the table.

      Now that you’ve added and deleted entries in your table, you can try adding and deleting columns.

      Step 9 — Adding and Deleting Columns from a Table

      After creating a table, you can modify it to add or remove columns. Add a column to show the last maintenance visit for each piece of equipment by typing:

      • ALTER TABLE playground ADD last_maint date;

      If you view your table information again, you will see the new column has been added (but no data has been entered):

      • SELECT * FROM playground;

      You will see the following:

      Output

      equip_id | type | color | location | install_date | last_maint ----------+-------+--------+-----------+--------------+------------ 2 | swing | yellow | northwest | 2018-08-16 | (1 row)

      Deleting a column is just as simple. If you find that your work crew uses a separate tool to keep track of maintenance history, you can delete the column by typing:

      • ALTER TABLE playground DROP last_maint;

      This deletes the last_maint column and any values found within it, but leaves all the other data intact.

      Having now added and deleted columns, you can try updating existing data in the final step.

      Step 10 — Updating Data in a Table

      So far, you’ve learned how to add records to a table and how to delete them, but this tutorial hasn’t yet covered how to modify existing entries.

      You can update the values of an existing entry by querying for the record you want and setting the column to the value you wish to use. You can query for the swing record (this will match every swing in your table) and change its color to red:

      • UPDATE playground SET color = 'red' WHERE type = 'swing';

      You can verify that the operation was successful by querying the data again:

      • SELECT * FROM playground;

      You will see the following:

      Output

      equip_id | type | color | location | install_date ----------+-------+-------+-----------+-------------- 2 | swing | red | northwest | 2010-08-16 (1 row)

      As you can see, your slide is now registered as being red.

      Conclusion

      You are now set up with PostgreSQL on your CentOS 8 server. However, there is still much more to learn with Postgres. Here are some more guides that cover how to use Postgres:



      Source link

      How To Set Up a Firewall Using firewalld on CentOS 8


      Introduction

      firewalld is firewall management software available for many Linux distributions, which acts as a frontend for Linux’s in-kernel nftables or iptables packet filtering systems.

      In this guide, we will show you how to set up a firewalld firewall for your CentOS 8 server, and cover the basics of managing the firewall with the firewall-cmd administrative tool.

      Prerequisites

      To complete this tutorial, you will need a server running CentOS 8. We will assume you are logged into this server as a non-root, sudo-enabled user. To set this up, see our Initial Server Setup for CentOS 8 guide.

      Basic Concepts in firewalld

      Before we begin talking about how to actually use the firewall-cmd utility to manage your firewall configuration, we should get familiar with a few concepts that the tool introduces.

      Zones

      The firewalld daemon manages groups of rules using entities called zones. Zones are sets of rules that dictate what traffic should be allowed depending on the level of trust you have in the network. Network interfaces are assigned to a zone to dictate the behavior that the firewall should allow.

      For computers that might move between networks frequently (like laptops), this kind of flexibility provides a good method of changing your rules depending on your environment. You may have strict rules in place prohibiting most traffic when operating on a public WiFi network, while allowing more relaxed restrictions when connected to your home network. For a server, these zones are often not as important because the network environment rarely, if ever, changes.

      Regardless of how dynamic your network environment may be, it is still useful to be familiar with the general idea behind each of the predefined zones for firewalld. The predefined zones within firewalld are, in order from least trusted to most trusted:

      • drop: The lowest level of trust. All incoming connections are dropped without reply and only outgoing connections are possible.
      • block: Similar to the above, but instead of simply dropping connections, incoming requests are rejected with an icmp-host-prohibited or icmp6-adm-prohibited message.
      • public: Represents public, untrusted networks. You don’t trust other computers but may allow selected incoming connections on a case-by-case basis.
      • external: External networks in the event that you are using the firewall as your gateway. It is configured for NAT masquerading so that your internal network remains private but reachable.
      • internal: The other side of the external zone, used for the internal portion of a gateway. The computers are fairly trustworthy and some additional services are available.
      • dmz: Used for computers located in a DMZ (isolated computers that will not have access to the rest of your network). Only certain incoming connections are allowed.
      • work: Used for work machines. Trust most of the computers in the network. A few more services might be allowed.
      • home: A home environment. It generally implies that you trust most of the other computers and that a few more services will be accepted.
      • trusted: Trust all of the machines in the network. The most open of the available options and should be used sparingly.

      To use the firewall, we can create rules and alter the properties of our zones and then assign our network interfaces to whichever zones are most appropriate.

      Rule Permanence

      In firewalld, rules can be applied to the current runtime ruleset, or be made permanent. When a rule is added or modified, by default, only the currently running firewall is modified. After the next reboot – or reload of the firewalld service – only the permanent rules will remain.

      Most firewall-cmd operations can take a --permanent flag to indicate that the changes should be applied to the permenent configuration. Additionally, the currently running firewall can be saved to the permanent configuration with the firewall-cmd --runtime-to-permanent command.

      This separation of runtime vs permanent configuration means that you can safely test rules in your active firewall, then reload to start over if there are problems.

      Installing and Enabling firewalld

      firewalld is installed by default on some Linux distributions, including many images of CentOS 8. However, it may be necessary for you to install firewalld yourself:

      • sudo dnf install firewalld

      After you install firewalld, you can enable the service and reboot your server. Keep in mind that enabling firewalld will cause the service to start up at boot. It is best practice to create your firewall rules and take the opportunity to test them before configuring this behavior in order to avoid potential issues.

      • sudo systemctl enable firewalld
      • sudo systemctl start firewalld

      When the server restarts, your firewall should be brought up, your network interfaces should be put into the zones you configured (or fall back to the configured default zone), and any rules associated with the zone(s) will be applied to the associated interfaces.

      We can verify that the service is running and reachable by typing:

      • sudo firewall-cmd --state

      Output

      running

      This indicates that our firewall is up and running with the default configuration.

      Getting Familiar with the Current Firewall Rules

      Before we begin to make modifications, we should familiarize ourselves with the default environment and rules provided by firewalld.

      Exploring the Defaults

      We can see which zone is currently selected as the default by typing:

      • firewall-cmd --get-default-zone

      Output

      public

      Since we haven’t given firewalld any commands to deviate from the default zone, and none of our interfaces are configured to bind to another zone, that zone will also be the only active zone (the zone that is controlling the traffic for our interfaces). We can verify that by typing:

      • firewall-cmd --get-active-zones

      Output

      public interfaces: eth0 eth1

      Here, we can see that our example server has two network interfaces being controlled by the firewall (eth0 and eth1). They are both currently being managed according to the rules defined for the public zone.

      How do we know what rules are associated with the public zone though? We can print out the default zone’s configuration by typing:

      • sudo firewall-cmd --list-all

      Output

      public (active) target: default icmp-block-inversion: no interfaces: eth0 eth1 sources: services: cockpit dhcpv6-client ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

      We can tell from the output that this zone is both the default and active, and that the eth0 and eth1 interfaces are associated with this zone (we already knew all of this from our previous inquiries). However, we can also see that this zone allows traffic for a DHCP client (for IP address assignment), SSH (for remote administration), and Cockpit (a web-based console).

      Exploring Alternative Zones

      Now we have a good idea about the configuration for the default and active zone. We can find out information about other zones as well.

      To get a list of the available zones, type:

      Output

      block dmz drop external home internal public trusted work

      We can see the specific configuration associated with a zone by including the --zone= parameter in our --list-all command:

      • sudo firewall-cmd --zone=home --list-all

      Output

      home target: default icmp-block-inversion: no interfaces: sources: services: cockpit dhcpv6-client mdns samba-client ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

      You can output all of the zone definitions by using the --list-all-zones option. You will probably want to pipe the output into a pager for easier viewing:

      • sudo firewall-cmd --list-all-zones | less

      Next we will learn about assiging zones to network interfaces.

      Selecting Zones for your Interfaces

      Unless you have configured your network interfaces otherwise, each interface will be put in the default zone when the firewall is started.

      Changing the Zone of an Interface

      You can move an interface between zones during a session by using the --zone= parameter in combination with the --change-interface= parameter. As with all commands that modify the firewall, you will need to use sudo.

      For instance, we can move our eth0 interface to the home zone by typing this:

      • sudo firewall-cmd --zone=home --change-interface=eth0

      Output

      success

      Note: Whenever you are moving an interface to a new zone, be aware that you are probably modifying which services will be operational. For instance, here we are moving to the home zone, which has SSH available. This means that our connection shouldn’t drop. Some other zones do not have SSH enabled by default, and switching to one of these zones could cause your connection to drop, preventing you from logging back into your server.

      We can verify that this was successful by asking for the active zones again:

      • firewall-cmd --get-active-zones

      Output

      home interfaces: eth0 public interfaces: eth1

      Adjusting the Default Zone

      If all of your interfaces can be handled well by a single zone, it’s probably easiest to just designate the best zone as default and then use that for your configuration.

      You can change the default zone with the --set-default-zone= parameter. This will immediately change any interface using the default zone:

      • sudo firewall-cmd --set-default-zone=home

      Output

      success

      Setting Rules for your Applications

      Let’s run through the basic way of defining firewall exceptions for the services you wish to make available.

      Adding a Service to your Zones

      The most straighforward method is to add the services or ports you need to the zones you are using. You can get a list of the available service definitions with the --get-services option:

      • firewall-cmd --get-services

      Output

      RH-Satellite-6 amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server finger freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server

      Note: You can get more details about each of these services by looking at their associated .xml file within the /usr/lib/firewalld/services directory. For instance, the SSH service is defined like this:

      /usr/lib/firewalld/services/ssh.xml

      <?xml version="1.0" encoding="utf-8"?>
      <service>
        <short>SSH</short>
        <description>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.</description>
        <port protocol="tcp" port="22"/>
      </service>
      

      You can enable a service for a zone using the --add-service= parameter. The operation will target the default zone or whatever zone is specified by the --zone= parameter. By default, this will only adjust the current firewall session. You can adjust the permanent firewall configuration by including the --permanent flag.

      For instance, if we are running a web server serving conventional HTTP traffic, we can temporarily allow this traffic for interfaces in our public zone by typing:

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

      You can leave out the --zone= flag if you wish to modify the default zone. We can verify the operation was successful by using the --list-all or --list-services operations:

      • sudo firewall-cmd --zone=public --list-services

      Output

      cockpit dhcpv6-client http ssh

      Once you have tested that everything is working as it should, you will probably want to modify the permanent firewall rules so that your service will still be available after a reboot. We can make our previous change permanent by retyping it and adding the --permanent flag:

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

      Output

      success

      Alternately, you could use the --runtime-to-permanent flag to save the currently running firewall configuration to the permanant config:

      • sudo firewall-cmd --runtime-to-permanent

      Be careful with this, as all changes made to the running firewall will be commited permenantly.

      Whichever method you chose, you can verify that it was successful by adding the --permanent flag to the --list-services operation. You need to use sudo for any --permanent operations:

      • sudo firewall-cmd --zone=public --list-services --permanent

      Output

      cockpit dhcpv6-client http ssh

      Your public zone will now allow HTTP web traffic on port 80. If your web server is configured to use SSL/TLS, you’ll also want to add the https service. We can add that to the current session and the permanent rule-set by typing:

      • sudo firewall-cmd --zone=public --add-service=https
      • sudo firewall-cmd --zone=public --add-service=https --permanent

      What If No Appropriate Service Is Available?

      The services that are included with the firewalld installation represent many of the most common applications that you may wish to allow access to. However, there will likely be scenarios where these services do not fit your requirements.

      In this situation, you have two options.

      Opening a Port for your Zones

      The easiest way to add support for your specific application is to open up the ports that it uses in the appropriate zone(s). This is done by specifying the port or port range, and the associated protocol (TCP or UDP) for the ports.

      For instance, if our application runs on port 5000 and uses TCP, we could temporarily add this to the public zone using the --add-port= parameter. Protocols can be designated as either tcp or udp:

      • sudo firewall-cmd --zone=public --add-port=5000/tcp

      Output

      success

      We can verify that this was successful using the --list-ports operation:

      • sudo firewall-cmd --zone=public --list-ports

      Output

      5000/tcp

      It is also possible to specify a sequential range of ports by separating the beginning and ending port in the range with a dash. For instance, if our application uses UDP ports 4990 to 4999, we could open these up on public by typing:

      • sudo firewall-cmd --zone=public --add-port=4990-4999/udp

      After testing, we would likely want to add these to the permanent firewall. Use sudo firewall-cmd --runtime-to-permanent to do that, or rerun the commands with the --permanent flag:

      • sudo firewall-cmd --zone=public --permanent --add-port=5000/tcp
      • sudo firewall-cmd --zone=public --permanent --add-port=4990-4999/udp
      • sudo firewall-cmd --zone=public --permanent --list-ports

      Output

      success success 5000/tcp 4990-4999/udp

      Defining a Service

      Opening ports for your zones is a straightforward solution, but it can be difficult to keep track of what each one is for. If you ever decommission a service on your server, you may have a hard time remembering which ports that have been opened are still required. To avoid this situation, it is possible to define a new service.

      Services are collections of ports with an associated name and description. Using services is easier to administer than ports, but requires a bit of up-front work. The easiest way to start is to copy an existing script (found in /usr/lib/firewalld/services) to the /etc/firewalld/services directory where the firewall looks for non-standard definitions.

      For instance, we could copy the SSH service definition to use for our example service definition like this. The filename minus the .xml suffix will dictate the name of the service within the firewall services list:

      • sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/example.xml

      Now, you can adjust the definition found in the file you copied. First open it in your favorite text editor. We’ll use vi here:

      • sudo vi /etc/firewalld/services/example.xml

      To start, the file will contain the SSH definition that you copied:

      /etc/firewalld/services/example.xml

      <?xml version="1.0" encoding="utf-8"?>
      <service>
        <short>SSH</short>
        <description>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.</description>
        <port protocol="tcp" port="22"/>
      </service>
      

      The majority of this definition is actually metadata. You will want to change the short name for the service within the <short> tags. This is a human-readable name for your service. You should also add a description so that you have more information if you ever need to audit the service. The only configuration you need to make that actually affects the functionality of the service will likely be the port definition where you identify the port number and protocol you wish to open. Multiple <port/> tags can be specified.

      For our example service, imagine that we need to open up port 7777 for TCP and 8888 for UDP. We can modify the existing definition with something like this:

      /etc/firewalld/services/example.xml

      <?xml version="1.0" encoding="utf-8"?>
      <service>
        <short>Example Service</short>
        <description>This is just an example service. It probably shouldn't be used on a real system.</description>
        <port protocol="tcp" port="7777"/>
        <port protocol="udp" port="8888"/>
      </service>
      

      Save and close the file.

      Reload your firewall to get access to your new service:

      • sudo firewall-cmd --reload

      You can see that it is now among the list of available services:

      • firewall-cmd --get-services

      Output

      RH-Satellite-6 amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server example finger freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master git grafana gre high-availability http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server

      You can now use this service in your zones as you normally would.

      Creating Your Own Zones

      While the predefined zones will probably be more than enough for most users, it can be helpful to define your own zones that are more descriptive of their function.

      For instance, you might want to create a zone for your web server, called publicweb. However, you might want to have another zone configured for the DNS service you provide on your private network. You might want a zone called “privateDNS” for that.

      When adding a zone, you must add it to the permanent firewall configuration. You can then reload to bring the configuration into your running session. For instance, we could create the two zones we discussed above by typing:

      • sudo firewall-cmd --permanent --new-zone=publicweb
      • sudo firewall-cmd --permanent --new-zone=privateDNS

      You can verify that these are present in your permanent configuration by typing:

      • sudo firewall-cmd --permanent --get-zones

      Output

      block dmz drop external home internal privateDNS public publicweb trusted work

      As stated before, these won’t be available in the runtime firewall yet:

      Output

      block dmz drop external home internal public trusted work

      Reload the firewall to bring these new zones into the active runtime configuration:

      • sudo firewall-cmd --reload
      • firewall-cmd --get-zones

      Output

      block dmz drop external home internal privateDNS public publicweb trusted work

      Now, you can begin assigning the appropriate services and ports to your zones. It’s usually a good idea to adjust the runtime firewall and then save those changes to the permanent configuration after testing. For instance, for the publicweb zone, you might want to add the SSH, HTTP, and HTTPS services:

      • sudo firewall-cmd --zone=publicweb --add-service=ssh
      • sudo firewall-cmd --zone=publicweb --add-service=http
      • sudo firewall-cmd --zone=publicweb --add-service=https
      • sudo firewall-cmd --zone=publicweb --list-all

      Output

      publicweb target: default icmp-block-inversion: no interfaces: sources: services: http https ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

      Likewise, we can add the DNS service to our privateDNS zone:

      • sudo firewall-cmd --zone=privateDNS --add-service=dns
      • sudo firewall-cmd --zone=privateDNS --list-all

      Output

      privateDNS target: default icmp-block-inversion: no interfaces: sources: services: dns ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:

      We could then change our interfaces over to these new zones to test them out:

      • sudo firewall-cmd --zone=publicweb --change-interface=eth0
      • sudo firewall-cmd --zone=privateDNS --change-interface=eth1

      At this point, you have the opportunity to test your configuration. If these values work for you, you will want to add these rules to the permanent configuration. You could do that by running all the commands again with the --permanent flag appended, but in this case we’ll use the --runtime-to-permanent flag to save our entire runtime configuration permanently:

      • sudo firewall-cmd --runtime-to-permanent

      After permanently applying these rules, reload the firewall to test that the changes remain:

      • sudo firewall-cmd --reload

      Validate that the correct zones were assigned:

      • firewall-cmd --get-active-zones

      Output

      privateDNS interfaces: eth1 publicweb interfaces: eth0

      And validate that the appropriate services are available for both of the zones:

      • sudo firewall-cmd --zone=publicweb --list-services

      Output

      http https ssh
      • sudo firewall-cmd --zone=privateDNS --list-services

      Output

      dns

      You have successfully set up your own zones! If you want to make one of these zones the default for other interfaces, remember to configure that behavior with the --set-default-zone= parameter:

      • sudo firewall-cmd --set-default-zone=publicweb

      Conclusion

      You should now have a fairly thorough understanding of how to administer the firewalld service on your CentOS system for day-to-day use.

      The firewalld service allows you to configure maintainable rules and rule-sets that take into consideration your network environment. It allows you to seamlessly transition between different firewall policies through the use of zones and gives administrators the ability to abstract the port management into more friendly service definitions. Acquiring a working knowledge of this system will allow you to take advantage of the flexibility and power that this tool provides.

      For more information on firewalld, please see the official firewalld documentation.



      Source link