Skip to main content

CentOS

Running a DHCP server on CentOS

If a connection to a network needs to be made, every computer needs a correct Internet Protocol (IP) configuration installed on their system to communicate. Assigning IP client configurations automatically from a central point using the Dynamic Host Control Protocol (DHCP) can make the administrator’s life easier and simplify the process of adding new machines to a network in comparison to the tedious work of manually setting up static IP information on each computer system in your network. In small home-based networks, people often use DHCP servers directly installed in silico on their Internet routers, but such devices often lack advanced features and have only a basic set of configuration options available. Most of the time, this is not sufficient for bigger networks or in the corporate environment, where you are more likely to find dedicated DCHP servers for more complex scenarios and better control. In this process, we will show you how to install and configure a DHCP server on a CentOS 7 system.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages. It is expected that your DHCP server will be using a static IP address; if you do not have one, refer to the process Building a static network connection, Configuring the System. If you plan to send DNS information to the clients through DHCP as well, you should have already applied the process Installing and configuring a simple nameserver, Working with FTP.

The Process

Here in this example, we will configure a DHCP server for a static network interface serving a single network with all its available IP addresses to all the computers connected directly to it (they are all in the same subnet).

  1. First, log in as root and type the following command in order to install the DHCP server packages:
    yum install dhcp
  2. In our example, we will use a network interface with the name, ifcfg-enp5s0f1, to serve our DHCP requests. Next, we need to collect some very important network information, which we will use later for configuring the DHCP server (change the network interface name to fit your own needs):
    cat /etc/sysconfig/network-scripts/ifcfg-enp5s0f1
  3. From this output, we need the following information, so please write it down (most likely, your output will be different):
    BOOTPROTO="static"
    IPADDR="192.168.1.8"
    NETMASK="255.255.255.0"
    GATEWAY="192.168.1.254"
  4. We also need the subnet network address, which can be calculated using the following line:
    ipcalc -n 192.168.1.8/24
  5. This will print the following output (write it down for later):
    NETWORK=192.168.1.0
  6. Now, we will open our main DHCP configuration file, after we make a backup of the original file:
    cp /etc/dhcp/dhcpd.conf /etc/dhcp/dhcpd.conf.BAK vi /etc/dhcp/dhcpd.conf
  7. Append the following lines to the end of the file, taking into account your individual network interface’s configuration from the preceding steps (routers = GATEWAY, subnet = NETWORK):
    authoriative;
    default-lease-time 28800;
    max-lease-time 86400;
    shared-network MyNetwork {
          option domain-name            "example.com";
          option domain-name-servers      8.8.8.8, 8.8.4.4;
          option routers                              192.168.1.254;
          subnet 192.168.1.0 netmask 255.255.255.0 {
              range 192.168.1.10 192.168.1.160;
          }
  8. Finally, start and enable the DHCP service:
    systemctl start dhcpd
    systemctl enable dhcpd

How Does It Work?

Here in this process, we showed you how easy it is to set up a DHCP server for a single network. With this, every time a new machine gets added to the network, the computer gets the correct IP information automatically, which it needs in order to connect to the network without any further human action.

So, what did we learn from this experience?

We started this process by installing the DHCP server package because it does not come with CentOS 7 out-of-the-box. Since our DHCP daemon communicates with its clients to assign IP information over a network interface, in the next step we had to choose a network device that would be used for the service. In our example, we selected a device named enp5s0f1. By default, the DHCP server can manage all available IP addresses from the same subnet as the associated network interface. Remember that your primary DHCP server’s network interface must be configured to get its own IP information statically and not through (another) DHCP server! Next, we used the cat command to print out all the interesting lines from our enp5s0f1 network interface configuration file, which we will need for configuring the DHCP server. Afterwards, we used the ipcalc tool to calculate the (subnet) network address for our DHCP server’s network interface. Then, we opened the main DHCP server configuration, started configuring some global settings, and defined a new shared network. In the global settings, we first set our DHCP server to be authoritative, which means it is the only and main responsible DHCP server in the network. Next, we defined default-lease-time to 28800 seconds, which is eight hours, and the max-lease-time to 86400, which is 24 hours. The lease time is the amount of time the DHCP server “rents out” an IP address to a client before it has to sign up again on the DHCP server asking for an extension of the IP. If it is not requesting a renewal of an existing lease at that time, the IP address will be released from the client and put into the pool of free IP addresses again, ready to be served to new machines that want to connect to the network. The client can define the amount of time it wants to lease an IP address by itself. If no time frame has been supplied from the client to the DHCP server, the default lease time will be used.

All subnets that share the same physical network interface should be defined within a shared-network declaration, so we defined this area using square brackets. This is also called a scope. In our example, we only have one network, so we only need one shared-network scope. Within it, we first defined a domain-name option, which will be sent and can be used by clients as their base domain name. Next, we added the domain name servers (DNS) to our configuration. Sending DNS information to the client is not mandatory for the DHCP server but can be useful. The more information a client gets for a given network, the better because fewer manual configuration steps have to be made.

Note
You can send out a lot of other useful information to the client (using DHCP) about the network he is connecting to: gateway, time, WINS, and so on.

Here in our example, we used the official Google DNS servers; if you have already set up your own DNS server, you could also use these addresses here. Next, we specified a routers option, which is another useful piece of information that will be sent out to the clients as well. Afterwards, we specified the most important part of any DHCP server: the subnet scope. Here, we defined our network ranges for assigning IP addresses for clients. We need to provide the subnet network address, its submask, and then the starting and ending IP address range that we want to allow to clients. In our example, we allow host IP addresses from 192.168.1.10, 192.168.1.11, 192.168.1.12 … to 192.168.1.160. If you have more than one subnet, you can use multiple subnet scope directives (called a multihomed DHCP server).

Next, we started the DHCP server and enabled it on boot. Your clients should now be able to get IP addresses dynamically from our new system.

In summary, we have only shown you some very basic DHCP server configuration options to get you started, and there are many more settings available, letting you build very complex DHCP server solutions. To get a better overview of its possibilities, please have a look at the example configuration file provided with the DHCP server documentation at less /usr/share/doc/dhcp-4*/dhcpd.conf.example.

There's more…

In the main process, we configured our basic DHCP server to be able to send complete IP network information to our clients so that they should be able to join our network. To use this server, you need to enable DHCP addressing on your client’s network interfaces. On CentOS clients, please do not forget to use BOOTPROTO=dhcp and remove all static entries such as IPADDR in the appropriate network-scripts ifcfg file (read the process, Building a static network connection, Configuring the System to get you started on network-scripts files). Then, to make a DHCP request, restart the network using systemctl restart network or try to do a reboot of the client system (with the ONBOOT=yes option). Confirm with ip addr list.

 

Priorities in CentOS

In this process, we will investigate the task of preparing YUM to manage additional repositories by installing a plugin known as YUM priorities. YUM has the ability to search, remove, install, retrieve, and update packages from various remote locations. Such features make YUM a powerful tool, but if you ever decide to add an additional third-party repository, there is a chance that conflicts will render the system unstable. Stability is one of the many advantages of using the CentOS operating system, and it is the purpose of this process to show you how this confidence can be maintained while simultaneously allowing for the addition of new repositories.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages.

The Process:

This process will show you how to prepare YUM in order to manage the process of using one or more third-party repositories by installing and configuring YUM priorities:

  1. To begin this process, log in as root and type the following:
    yum install yum-plugin-priorities
  2. Confirm the installation, and when complete type what is shown here:
    vi /etc/yum/pluginconf.d/priorities.conf
  3. You should ensure that this file indicates that the plugin is enabled. It should show the instruction enabled = 1. It is not expected that you will need to change anything in this file, but if you have made any changes, simply save and close the file before proceeding.
  4. We now need to establish a priority value for each repository. This is a numeric value in ascending order, where the highest priority is given the lowest number. To do this, open the following file as shown next:
    vi /etc/yum.repos.d/CentOS-Base.repo
  5. Add the following line at the end of the [base] section:
    priority=1
  6. Now, add the following line at the end of the [updates] section:
    priority=1
  7. And finally, add the following line at the end of the [extras] section:
    priority=1
  8. When complete, save and close the file before running a package update:
    yum update

How Does It Work?

YUM priorities is a simple plugin that enables YUM to decide what repositories will assume the highest priority when installing and updating new packages. Using this plugin will reduce the chance of package confusion by ensuring that any particular package will always be installed or updated from the same repository. In this way, you can add an unlimited number of repositories and enable YUM to stay in control of package management.

So, what did we learn from this experience?

Enhancing YUM with this plugin was simply a matter of installing the yum-pluginpriorities package and ensuring that it was enabled in its configuration file. We then discovered that the priority is set in ascending order, where the lowest values are given precedence over all others. This, of course, serves to simplify the overall process, and for this reason, we ensured that the default repositories were given a value of 1 (priority=1).

This will ensure that the default repositories maintain the highest priority, so when you do decide to add additional repositories you could assign them a priority value of 2, 3, 4… and 10, or more. On the other hand, it should be noted that we only set this value across three main sections: [base], [updates], and [extras]. In simple terms, this was only because the other sections are shown to be disabled. For example, you may have noticed that the [centosplus] section in /etc/yum.repos.d/CentOS-Base.repo include the following line: enabled=0, whereas the [updates] and [extras] sections show this value as enabled=1. Of course, if you intend to activate this repository, you will need to set a priority value for it, but for the purpose of this process, such an action was not required.
Finally, we ran a simple YUM package update in order to activate our revised settings.

So, as we can see, YUM priorities is an extremely flexible package that enables you to determine what repositories take priority when you want to expand your installation options. However, you should always be aware that YUM priorities may not be appropriate for your system, as you are giving it the power to decide what packages are to be ignored, what packages are installed, what packages are updated, and in what order and from which repository you will get them. For most users who tend not to stay away from the typical server functions, this may not be an immediate concern; you may even safely ignore this warning. But if stability and security are an overriding concern, and you do intend to use additional packages from external repositories, then you should give careful consideration to the use of this plugin or at least consider and research the integrity of the third-party repositories used.

 

Customizing CentOS system banners and messages

In this process, we will learn how to display a welcome message if a user successfully logs in to our CentOS 7 system using SSH or console, or opens a new terminal window in a graphical window manager. This is often used to show the user informative messages, or for legal reasons.

To Start With: What Do You Need?

To complete this process, you will require a minimal installation of the CentOS 7 operating system with root privileges and a console-based text editor of your choice.

The Process

  1. To begin, log in to your system using your root user account and create the following new file with your favorite text editor:
    vi /etc/motd
  2. Next, we will put in the following content in this new file:
    ###############################################
    # This computer system is for authorized users only.
    # All activity is logged and regularly checked.
    # Individuals using this system without authority or
    # in excess of their authority are subject to
    # having all their services revoked…
    ###############################################
  3. Save and close this file.
  4. Congratulations, you have now set a banner message for whenever a user successfully logs in to the system using ssh or a console.

How it works...

For legal reasons, it is strongly recommended that computers display a banner before allowing users to log in; lawyers suggest that the offense of unauthorized access can only be committed if the offender knows at the time that the access he intends to obtain is unauthorized. Login banners are the best way to achieve this. Apart from this reason, you can provide the user with useful system information.

So, what did we learn from this experience?

We started this process by opening the file, /etc/motd, which stands for a message of the day; this content will be displayed after a user logged in a console or ssh. Next, we put in that file a standard legal disclaimer and saved the file.

There's more…

As we have seen, the /etc/motd file displays static text after a user successfully logs in to the system. If you want to also display a message when an ssh connection is first established, you can use ssh banners. The banner behavior is disabled in the ssh daemon configuration file by default, which means that no message will be displayed if a user establishes an ssh connection. To enable this feature, log in as root on your server and open the /etc/ssh/sshd_config file using your favorite text editor, and put in the following content at the end of the file:
Banner /etc/ssh-banner

Then, create and open a new file called /etc/ssh-banner, and put in a new custom ssh greeting message.

Finally, restart your ssh daemon using the following line:
systemctl restart sshd.service

The next time someone establishes an ssh connection to your server, this new message will be printed out.

The motd file can only print static messages and some system information details, but it is impossible to generate real dynamic messages or use bash commands in it if a user successfully logs in.

Also, motd does not work in non-login shells, such as when you open a new terminal within a graphical window manager. In order to achieve this, we can create a custom script in the /etc/profile.d directory. All scripts in this directory get executed automatically if a user logs in to the system. First, we delete any content in the /etc/motd file, as we don’t want to display two welcome banners. Then, we open the new file, /etc/profile.d/motd.sh, with our text editor and create a custom message, such as the following, where we can use bash commands and write little scripts (use the backticks to run bash shell commands in this file):

#!/bin/bash
echo -e "
##################################
#
# Welcome to `hostname`, you are logged in as `whoami`
# This system is running `cat /etc/redhat-release`
# kernel is `uname -r`
# Uptime is
`uptime | sed 's/.*up ([^,]*), .*/1/'`
# Mem total `cat /proc/meminfo | grep MemTotal | awk {'print $2'}` kB
###################################"

 

CentOS Introduction

CentOS is a community-based enterprise-class operating system. It is available free of charge, and as a fully compatible derivative of Red Hat Enterprise Linux (RHEL), it represents the first choice operating system for organizations, companies, professionals, and home users all over the world who intend to run a server. It's widely respected as a very powerful and flexible Linux distribution and regardless as to whether you intend to run a web server, file server, FTP server, domain server, or a multi-role solution, it is the purpose of this book to deliver a series of turn-key solutions that will show you how quickly you can build a fully capable and comprehensive server system using the CentOS 6 operating system.

Installing and configuring Docker on CentOS

Traditional virtualization technologies provide hardware virtualization, which means they create a complete hardware environment so each virtual machine (VM) needs a complete operating system to run it. Therefore they have some major drawbacks because they are heavyweight and produce a lot of overhead while running. This is where the open-source Docker containerization engine offers an attractive alternative. It can help you build applications in Linux containers, thus providing application virtualization.

This means that you can bundle any Linux program of choice with all its dependencies and its own environment and then share it or run multiple instances of it, each as a completely isolated and separated process on any modern Linux kernel, thus providing native runtime performance, easy portability, and high scalability. Here, in this process, we will show you how to install and configure Docker on your CentOS 7 server.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to download additional rpm packages and a test Docker image.

The Process

While Docker is available as a package in the official CentOS 7 repository, we will use the official Docker repository to install it on our system instead.

  1. To begin, log in as root and update your YUM packages before downloading and executing the official Docker Linux installation script using the following command:
    yum update && curl -sSL https://get.docker.com/ | sh
  2. Next, enable Docker at boot time before starting the Docker daemon (the first time you start, it will take a while):
    systemctl enable docker && systemctl start docker
  3. Finally, after starting Docker you can verify that it’s working by typing:
    docker run hello-world

How Does It Work?

When installing any software on CentOS 7, most of the time it is very good advice to use the packages available in your official CentOS repository instead of downloading and installing from third-party locations. Hereby installing Docker using the official Docker repository instead, we made an exception. We did this because Docker is a very young project and is evolving fast, and it keeps changing a lot. While you can use Docker for running every Linux application, including critical web servers or programs dealing with confidential data, bugs found or introduced into the Docker program can have severe security consequences. By using the official Docker repository, we make sure we always get the latest updates and patches available as fast as possible right from the developers of this fast-moving project. So anytime you type yum update in the future, your package manager will automatically query and check the Docker repos to see if there is a new version of Docker available for you.

So what did we learn from this experience?

We started this process by logging into our server as root and updated the YUM package’s database. Then we used a command to download and execute the official Docker installation script from https://get.docker.com/ in one step. What this script does is add the official Docker repository to the YUM package manager as a new package source and then automatically install Docker in the background. Afterwards, we enabled the Docker service at boot-time and started it by using systemd. Finally, to test our installation, we issued the command docker run hello-world, which downloads a special image from the official Docker registry to test our installation. If everything went fine, you should see the following success message (output truncated):
Hello from Docker

This message shows that your installation appears to be working correctly.

 

Managing a MariaDB database on CentOS

In this process, we will learn how to create a new database and database user for the MariaDB server. MariaDB can be used in conjunction with a wide variety of graphical tools (for example, the free MySQL Workbench), but in situations where you simply need to create a database, provide an associated user, and assign the correct permissions, it is often useful to perform this task from the command line. Known as the MariaDB shell, this simple interactive and text based-command line facility supports the full range of SQL commands and affords both local and remote access to your database server. The shell provides you with complete control over your database server, and for this reason, it represents the perfect tool for you to start your MariaDB work.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system. It is expected that a MariaDB server is already installed and running on your server.

The Process

The MariaDB command-line tool supports executing commands in both the batch mode (reading from a file or standard input) and interactively (typing in statements and waiting for the results). We will use the latter in this process.

  1. To begin, log in on your CentOS 7 server with any system user you like and type the following command in order to access the MariaDB server using the MariaDB shell with the main MariaDB administration user called root (use the password created in the previous process):
    mysql -u root -p
  2. On successful login, you will be greeted with the MariaDB command-line interface. This feature is signified by the MariaDB shell prompt:
    MariaDB [(none)]>
  3. In this first step, we will create a new database. To do this, simply customize the following command by substituting an appropriate value for the new value using:
    CREATE DATABASE CHARACTER SET utf8 COLLATE utf8_general_ci;

    Note
    If this is your first introduction to the MariaDB shell, remember to end each line with a semi-colon (;) and press the Enter key after typing each command.

  4. Having created our database, we will now create a MariaDB user. Each user will consist of a username and a password that is completely independent of the operating system’s user. For reasons of security, we will ensure that access to the database is restricted to localhost only. To proceed, simply customize the following command by changing the values ,
    , and to reflect your needs:
    GRANT ALL ON .* TO ''@'localhost' IDENTIFIED BY '
    ' WITH GRANT OPTION;
  5. Next, make the MariaDB DBMS aware of your new user:
    FLUSH PRIVILEGES;
  6. Now simply type the following command to exit the MariaDB shell:
    EXIT;
  7. Finally, you can test the accessibility of your new by accessing the MariaDB shell from the command-line in the following way:
    mysql -u -p
  8. Now back at the MariaDB shell (MariaDB [(none)]>), type the following commands:
    SHOW DATABASES;
    EXIT;

How Does It Work?

During the course of this process, you were shown not only how to create a database, but also how to create a database user.

So what did we learn from this experience?

We started the process by accessing the MariaDB shell as the root user with the mysql command. By doing this, we were then able to create a database with a simple SQL function called CREATE DATABASE, providing a custom name for the field. We also specified utf8 as the character set of our new database together with a utf8_general_ci collation. A character set is how the characters are encoded in the database and a collation is a set of rules for comparing the characters in a character set. For historical reasons and to keep MariaDB backward-compatible with the older server versions, the default character set is latin1 and latin1_swedish_ci, but for any modern databases, you should always prefer to use utf-8 instead as it is the most standard and compatible encoding for international character sets (non-English alphabets). However, this command can be modified to invoke the need to check if a database name is already in use by using: CREATE DATABASE IF NOT EXISTS . In this way, you can then drop or remove a database by using the following command:
DROP DATABASE IF EXISTS ;

Having done this, it is simply a matter of adding a new database user with the appropriate permissions by running our GRANT ALL command. Here we provided with full privileges via a defined
for localhost. As a specific was elected, then this level of permission will be restricted to that particular database and using .* allows us to specify these rules to all the tables (using the asterisks symbol) in this database. The general syntax in order to provide a chosen user with specific permission is:
GRANT [type of permission] ON .

TO ''@'';

For security reasons, here in this process, we limit to localhost but if you want to grant permissions to remote users you will need to change this value (see later). In our example, we set [type of permission] to ALL but you can always decide to minimize the privileges by providing a single or a comma-separated list of privilege-types offered in the following way:
GRANT SELECT, INSERT, DELETE ON .* TO ''@'localhost';

Using the previous technique, here is a summary of the permissions that can be employed:

  • ALL: Allows the value with all available privilege-types
  • CREATE: Allows the value to create new tables or databases
  • DROP: Allows the value to delete tables or databases
  • DELETE: Allows the value to delete rows from tables
  • INSERT: Allows the value to insert rows into tables
  • SELECT: Allows the value to read from tables
  • UPDATE: Allows the value to update table rows

However, once the privileges were granted, the process then showed you that we must FLUSH the system in order to make our new settings available to the system itself. It is important to note that all commands within the MariaDB shell should end in a semicolon (;). Having completed our task, we simply exit the console using the EXIT; statement.

MariaDB is an excellent database system but like all services, it can be abused. So remain vigilant at all times, and by considering the previous advice, you can be confident that your MariaDB installation will remain safe and secure.

There's more…

Creating a restricted user is one way of providing database access but if you have a team of developers who require constant access to a development server, you may wish to consider providing a universal user who maintains superuser privilege. To do this, simply login to the MariaDB shell with your administrator user root, then create a new user in the following way:
GRANT ALL ON *.* TO ''@'localhost' IDENTIFIED BY '
' WITH GRANT OPTION;

By doing this, you will enable to add, delete, and manage databases across your entire MariaDB server (the asterisks in *.* tell MariaDB to apply the privileges to all the databases and all their associated tables found on the database server), but given the range of administrative features, this new user account will restrict all activities to localhost only. So in simple terms, if you want to provide with access to any database or to any table, always use an asterisk (*) in place of the database name or table name. Finally, every time you update or change a user permission, always be sure to use the FLUSH PRIVILEGES command before exiting the MariaDB shell with the EXIT; command.

Reviewing and revoking permissions or dropping a user on CentOS
It is never a good idea to keep user accounts active unless they are used, so your first consideration within the MariaDB shell (login with your administrator user root) will be to review their current status by typing:
SELECT HOST,USER FROM mysql.user WHERE USER='';

Having done this, if you intend to REVOKE permission(s) or remove a user listed here, you can do this with the DROP command. First of all, you should review what privileges the user of interest has by running:
SHOW GRANTS FOR ''@'localhost';

You now have two options, starting with the ability to revoke the user’s privileges as follows:
REVOKE ALL PRIVILEGES, GRANT OPTION FROM ''@'localhost';

Then you may either reallocate the privilege using the formula provided in the main process or alternatively, you can decide to remove the user by typing:
DROP USER ''@'localhost';

Finally, update all your privileges the usual way using FLUSH PRIVILEGES; before exiting the shell EXIT; command.

 

Printing with CUPS in CentOS

Print servers allow local printing devices to be connected to a network and be shared among several users and departments. There are many advantages using such a system, including the lack of a need to buy dedicated printer hardware for each user, room, or department. The Common Unix Printing System (CUPS) is the de-facto standard for print servers on Linux, as well as Unix distributions including OS X. It is built with a typical client/server architecture, where clients in the network send print jobs to the centralized print server that schedules these tasks, then delegates and executes the actual printing on a printer that is locally connected to our printer server or sends the print job remotely to the computer that has the physical connection to the requested printer or to a standalone network printer. If you set up your printers within the CUPS system, almost all Linux and OS X printing application on any client in your network will be automatically configured to use them out-of-the-box, without the need to install additional drivers. Here, in this process, we will show you how to get started with the CUPS printing server system.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to download additional packages. In this process, we will use the network interface with the IP address, 192.168.1.8, and the corresponding network address of 192.168.1.0/24 to serve the CUPS printer server to our network.

The Process

We begin this process by installing the CUPS printing server software, which is not available by default on a fresh CentOS 7 minimal system:

  1. To do this, log in as root and install the following package:
    yum install cups
  2. Next, create an SSL certificate for the CUPS server, which we will need for secure authentication to the CUPS web application (add a secure password when asked):
    cd /etc/pki/tls/certs make cups-server.key
  3. Now, let’s open the CUPS main configuration file to customize the server (backup first):
    cp /etc/cups/cupsd.conf /etc/cups/cupsd.conf.BAK vi /etc/cups/cupsd.conf
  4. First, to make CUPS available on the entire network, find the following line: Listen localhost:631, than change it to:
    Listen 631
  5. Next, we want to configure access to all normal web pages of the web-based CUPS frontend. Search for the directive (don’t confuse this with other directives such as ) and change the complete block by adding your network address. After changing, the complete block looks like this:

    Order allow,deny
    Allow 192.168.1.0/24
  6. Next, set access permissions for the /admin and /admin/conf Location directives, granting access to the local server only:

           Order allow,deny
            Allow localhost


            AuthType Default Require user @SYSTEM
            Order allow,deny
            Allow localhost
  7. Finally, add our SSL certificate information to the end of the configuration file:
    ServerCertificate /etc/pki/tls/certs/cups-server.crt
    ServerKey /etc/pki/tls/certs/cups-server.key
  8. Close and save the file, then restart the CUPS server and enable it on boot:
    systemctl restart cups.service systemctl enable cups.service
  9. Now, we have to open the CUPS server ports in firewalld so that other computers in the network can connect to it:
    firewall-cmd --permanent --add-service=ipp firewall-cmd --reload
  10. You can test the accessibility of your CUPS server from another computer in your 192.168.1.0/24 network by browsing to the following location (allow a security exception in the browser when asked):
    https://:631
  11. To access the administration area within the CUPS frontend, you need to be on the same server as CUPS is running (on a CentOS 7 minimal installation, please install a window manager and browser), and then use the system user, root, with the appropriate password to login.

How Does It Work?

In this process, we showed you how easy it is to install and set up a CUPS printing server.

So, what did we learn from this experience?

We began our journey by installing the CUPS server package on our server because it is not available on the CentOS 7 system by default. Afterwards, we generated a SSL key-pair, which we will need later in the process (to learn more, read the Generating self-signed certificates process.) It is used to allow the encrypted submission of your login credentials to the CUPS administration web frontend (over secure HTTPS connections). Next, we opened CUPS’s main configuration file, /etc/cups/cupsd.conf, with the text editor of our choice. As you may notice, the configuration format is very similar to the Apache configuration file format. We started changing the Listen address by removing the localhost name, therefore allowing all clients from everywhere in your network (192.168.1.0/24) to access our CUPS server at port 631 instead of allowing only the local interface to connect to the printer server.

Note
By default, the CUPS server has Browsing On enabled, which will broadcast, every 30 seconds, an updated list of all printers that are being shared in the system to all client computers on the same subnet. If you want to broadcast to other subnets as well, use the BrowseRelay directive.

Next, we configured access to the CUPS web interface. This frontend can be used to conveniently browse all available printers on the network, or even install new printers or configure them if you log in with an administrator account. As there are different tasks in the user interface, there are three different directives that can be used to fine-grain its access. Access to all normal web pages can be set using the directive, whereas all administration pages can be managed with and more specifically to change the configuration within the tag. In each of these Location tags, we added different Allow directives, thus granting normal CUPS web pages (such as, browsing all available network printers) from your complete network (for example, 192.168.1.0/24) while accessing the special administration pages is restricted to the server that runs the CUPS service (localhost). Remember, if this is too restrictive for your environment, you can always adjust these Allow settings. Also, there are various other Location types available, such as one that is used for activating our service in additional subnets. Please read the CUPS configuration manual using man cupsd.conf. Next, we configured SSL encryption, thus activating secure https:// addresses for the web interface. Then, we started the CUPS server for the first time and enabled it to start automatically when the server boots up. Finally, we added the ipp firewalld service, thus allowing incoming CUPS client connections to the server.

There's more…

Now that we have successfully set up and configured our CUPS server, it’s time to add some printers to it and print a test page. Here, we will show you how to add two different types of printers to the system using the command line.

Note
Adding or configuring printers can also be done using the graphical web-based CUPS interface.

First, we will install a true network printer that is already available in the same network (in our case, the 192.168.1.0/24 network) as our CUPS server and afterwards a locally connected printer (for example, via USB to our CUPS server or any other computer in the same network).

Note
Why should you want to install an already connected network printer to our CUPS server? CUPS can do much more than just printing: it is a centralized printer server, thus managing to schedule and queuing of printers and their jobs, serving printers in different subnets, and providing unified printing protocols and standards for convenient access on any Linux or Mac client.

How to add a network printer to the CUPS server

To start adding a network printer to our CUPS server, we will use the command lpinfo v to list all the available printing devices or drivers known to the CUPS server. Normally, the CUPS server will automatically identify all locally (USB, parallel, serial, and so on) and remotely available (network protocols such as socket, http, ipp, lpd, and so on) printers from most common printing protocols without any problems. In our example, the following network printer has been successfully identified (the output has been truncated):
network dnssd://Photosmart%20C5100%20series%20%5BF8B652%5D._pdldatastream._tcp.local/

Next, we will install this printer on the CUPS server to put it under its control. First, we need to look for the correct printer driver. As we can see in the last output, it is an HP Photosmart C5100 series printer. So, let’s search for the driver in the list of all currently installed drivers on our CUPS server:
lpinfo --make-and-model HP -m | grep Photosmart

The list does not contain our model C5100, so we have to install an additional HP driver package using:
yum install hplip

Now, if we issue our command again, we can find the correct driver:
lpinfo --make-and-model HP -m | grep Photosmart | grep c5100

Note
For other printer models and manufacturers, there are other driver packages available as well, for example, the gutenprint-cups RPM package.

The correct driver for this printer will be shown as follows:
drv:///hp/hpcups.drv/hp-photosmart_c5100_series.ppd

Now, we have everything ready to install the printer using the following syntax:
lpadmin -p
-v -m -L -E

In our example, we installed it using:
lpadmin -p hp-photosmart -v
"dnssd://Photosmart%20C5100%20series%20%5BF8B652%5D._pdl
datastream._tcp.local/" -m "drv:///hp/hpcups.drv/hp-
photosmart_c5100_series.ppd" -L room123 -E

Now, the printer should be under our CUPS server’s control and should immediately be shared and seen in the entire network from any Linux or OS X computer (on a CentOS 7 minimal client, you will first need to install the cups package as well and enable incoming ipp connections using firewalld’s ipp-client service before any shared network printer information from our CUPS server will become available).

You can later change the configuration of this printer by opening and changing the file at /etc/cups/printers.conf. To actually print a test page, you should now be able to access the printer using its name, hp-photosmart, from any client (on a CentOS 7 minimal client, you would need to install the package cups-client):
echo "Hello printing world" | lpr -P hp-photosmart -H 192.168.1.8:631

How to share a local printer to the CUPS server

If you want to share a local printer physically connected to our CUPS server, just plug in the printer to the system (for example, via USB) and follow the previous process, How to add a network printer to the CUPS server. In the step lpinfo -v, you should see it appear as a usb:// address, so you need to take this address and follow the rest of the steps.

If you want to connect and share a printer on your centralized CUPS server, which is physically connected to any other computer on your CUPS network, install the cups daemon on this other machine (follow all the steps in the main process) and then install the printer driver for it as shown here in this section. This will make sure that the local CUPS daemon will make the printer available on the network, as it would be on our centralized CUPS server. Now that it is available on the network, you can easily add it to our main CUPS server to enjoy all the benefits of a centralized printing server.

Here in this process, we have only scratched the surface and introduced you to the basics of setting up a CUPS server for your network. There is always more to learn, and you can build very complex CUPS server systems managing hundreds of printers in the corporate environment, which is outside the scope of this process.

 

Keeping YUM clean and tidy in CentOS

In this process, we will investigate the role of YUM with regard to ensuring that the working cache remains current. As a part of its typical mode of operation, YUM will create a cache that consists of metadata and packages. These files are very useful, but over time, they will accumulate in size to such an extent that you may find that YUM is acting erratically or not as intended. The frequency of this happening can vary from system to system, but it generally implies that the YUM cache system requires your immediate attention. Such a situation can be quite frustrating, but it is the purpose of this process to provide a quick solution that will serve to assist you in cleaning the cache and restoring
YUM to its original working state.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages.

The Process: 

Before we begin, it is important to realize that, while we are troubleshooting a current problem, this same process can be run as often as required in order to keep YUM in an optimal working state:

  1. We will begin this process by asking YUM to clean any cached package information. To do this, log in as root and type the following:
    yum clean packages
  2. Allow time for your system to respond and when finished, type the following command to remove any cached XML-based metadata:
    yum clean metadata
  3. Again, wait for YUM to respond and when ready, type the following command to remove any cached database files:
    yum clean dbcache
  4. Following this, you will want to clean all the files to confirm the preceding instructions and to ensure that unnecessary disk space is not used. To do this, type the following line:
    yum clean all
  5. Finally, you will want to rebuild the YUM cache by typing what is shown next:
    yum makecache

How Does It Work?

YUM is a very powerful tool that is known for its ability to resolve package dependencies and automate the process of package management, but as with all things, there are times when even the best utilities can get confused and may report errors or behave erratically.

Fixing this issue is relatively simple and the approach outlined in this process will also serve to keep your package manager in a healthy running state for the life of your operating system.

So, what have we learned from this experience?

During its typical operation, YUM will create a cache of metadata and packages that can be found at /var/cache/yum. These files are essential, but as they grow in size, this cache will ultimately serve to slow down the overall use of this utility and may even cause some issues. To address this situation, we started by using the following command to clean the current package-based cache using YUM’s clean packages parameter options. We then followed this by cleaning the metadata cache using the command clean metadata, which will remove any excess XML-based files. YUM uses a SQLite database as a part of its normal operation, so the next step was to remove any remaining database files using the clean dbcache parameters. The next step was to clean all files associated with enabled repositories in order to reclaim any unused disk space: yum clean all. Finally, we restored YUM to its normal working state by rebuilding the cache using the makecache option.

There’s More:

On a typical server, YUM is a great tool that will solve the most complex problems related to package dependencies and package management. However, in instances where you have knowingly mixed incompatible repositories or have used incomplete sources, there is a risk that YUM will not be able to help.

Note
Remember, in this situation, you should consider the following advice to be a temporary remedy only. A tendency to ignore any warnings provided by YUM will only lead to bigger problems later on.
If such instances occur, and if the error is RPM-based, as a temporary fix, you can skip broken packages by using the following command:
yum -y update --skip-broken

This command will allow YUM to continue working by bypassing any packages with errors, but as stated earlier this should be regarded as a temporary fix only. You should always be aware that a system with broken dependencies is not considered to be a healthy system. This situation is to be avoided at all costs, and under these circumstances fixing such errors should become your first priority. 

 

Becoming a CentOS superuser

In this process, we will learn how to provide nominated users or groups with the ability to execute a variety of commands with elevated privileges.

On CentOS Linux, many files, folders, or commands can only be accessed or executed by a user called root, which is the name of the user who can control everything on a Linux system. Having one root user per system may suit your needs, but for those who want a greater degree of flexibility, a solid audit trail, and the ability to provide a limited array of administrative capabilities to a select number of trusted users, you have come to the right place. It is the purpose of this process is to show you how to activate and configure the sudo (superuser do) command.

To Start With: What Do You Need?

To complete this process, you will require a minimal installation of the CentOS 7 operating system with root privileges. It is assumed that your server maintains one or more users (other than root) who qualify for this escalation in powers. If you did not create a system user account during installation, please do so by first before applying the process. 

The Process

To start this process, we will first test the sudo command with a non-privileged user.

  1. To begin, log in to your system using a non-root user account, then type the following to verify that sudo is not enabled (use your user account’s password when asked):
    sudo ls /var/log/audit
  2. This will print the following error output with , which is the user you are currently logged in with:
    is not in the sudoers file. This incident will be reported.
  3. Now, log out the system user using the command:
    logout
  4. Next, log in as root and use the following command to give the non-root user sudo power (change appropriately):
    usermod -G wheel
  5.  Now, you can test if sudo is working by logging out root again and re-logging in the user from step 1, and then trying again:
    sudo ls /var/log/audit
  6.  Congratulations, you’ve now set a normal user to have sudo powers and can view and execute files and directories restricted to the root user.

How it works...

Unlike some Linux distributions, CentOS does not provide sudo by default. Instead, you are typically allowed to access restricted parts of the system with the root user only. This offers a certain degree of security, but for a multi-user server, there is little to no flexibility unless you simply provide these individuals with full administrative root access permissions. This is not advisable, and for this reason, it was the purpose of this process is to show you how to provide one or more users with the right to execute commands with elevated privileges.

So, what did we learn from this experience?

We started by logging in to the system with a normal user account having no root privileges or sudo powers. With this user, we then tried to list a directory that normally only the root user is allowed to see, so we applied the sudo command on it. It failed, giving us the error that we are not in the sudoers list.

The sudo command provides nominated users or groups with the ability to execute a command as if they were the root user. All actions are recorded (in a file called /var/log/secure), so there will be a trace of all the commands and arguments used.

We then logged in as the true root user and added a group called wheel to the system user that we wanted sudo rights for. This group is used as a special administration group and every member of it is granted sudo rights automatically.

From now on, the nominated user can implement sudo in order to execute any command with elevated privileges. To do this, the user would be required to type the word sudo before any command, for example, they could run the following command:
sudo yum update

They will be asked to confirm their user password (not the root password!), and after successful authentication, the program will be executed as the user root.

Finally, we can say that there are three ways to become root on a CentOS Linux system:

First, to log in as the true user root to the system. Second, you can use the command, su – root, while any normal system user is logged in, giving the root user’s password to switch to a root shell prompt permanently. Third, you can give a normal user sudo rights so that they can execute single commands using their own passwords as if they were the root user while staying logged in as themselves.

Note
sudo (superuser do) should not be confused with the su (substitute user) command, which allows you to switch to another user permanently instead of executing only single commands as you would do being the root user.

The sudo command allows great flexibility for servers that have a lot of users, where one administrator is not enough to manage the whole system.

 

Setting up HTTPS with Secure Sockets Layer (SSL) in CentOS

In this process, we will learn how to add a secure connection to the Apache web server by creating a self-signed SSL certificate using OpenSSL. This is often a requirement for web servers if the sites running on them transfer sensitive data such as credit card or login information from the web browser to the server. In a previous process, you were shown how to install the Apache web server, and with the growing demand for secure connections, it is the purpose of this process to show you how to enhance your current server configuration by teaching you how to extend the features of the Apache web server.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages. It is expected that Apache web server has been installed and that it is currently running. Here we will create a new SSL certificate for Apache. If you want to learn more about it, refer to segment Chapter 6, Providing Security for advice on generating self-signed certificates. As a correct domain name is crucial for SSL to work, we will continue naming our Apache web server’s configured domain name centos7.home to make this process work (change it to fit your own needs).

The Process

Apache does not support SSL encryption by default and for this reason, we will begin by installing the necessary package mod_ssl using the yum package manager.

  1. To begin, log in as root and type the following command:
    yum install mod_ssl
  2. During the installation of the mod_ssl package, a self-signed certificate, as well as the key pair for the Apache web server, are generated automatically; these lack a proper common name for your web server’s domain name. Before we can re-generate our own required SSL files using the Makefile in the next steps, we need to delete those files:
    rm /etc/pki/tls/private/localhost.key /etc/pki/tls/certs/localhost.crt
  3. We are now required to create our intended self-signed certificate and server key for our Apache web server. To do this, type the following command:
    cd /etc/pki/tls/certs
  4. To create the self-signed Apache SSL keypair, consisting of the certificate and its embedded public key as well as the private key, type:
    make testcert
  5. In the process of creating the certificate, first you will be asked to enter a new passphrase and then verify it. Afterwards, you need to type it in again for the third time. As usual, enter a secure password. You will then be asked a number of questions. Complete all the required details by paying special attention to the common name value. This value should reflect the domain name of your web server or the IP address the SSL certificate is for. For example, you may type:
    www.centos7.home
  6. When the process of creating your certificate is complete, we will proceed by opening the main Apache SSL configuration in the following way (after making a backup):
    cp /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.BAK vi /etc/httpd/conf.d/ssl.conf
  7. Scroll down to the section that begins with and locate the line # DocumentRoot "/var/www/html" within this block. Then activate it by removing the # character, so it reads:
    DocumentRoot "/var/www/html"
  8.  Right below, find the line that reads #ServerName www.example.com:443. Activate this line and modify the value shown to match the common name value used during the creation of your certificate, as follows:
    ServerName www.centos7.home:443
  9. Save and close the file, next we need to enable the HTTPS port in our firewalld to allow incoming HTTP SSL connections over port 443:
    firewall-cmd --permanent --add-service=https && firewall-cmd --reload
  10. Now restart the Apache httpd service to apply your changes. Note that if prompted you have to enter the SSL passphrase you added when you created the SSL test certificate:
    systemctl restart httpd
  11. Well done! You can now visit your server with a secure connection by replacing all the available HTTP URLs we have defined for the server using HTTPS instead. For example, go to https://www.centos7.home instead of http://www.centos7.home.

    Note
    When you browse to this website, you will get a warning message that the signing certificate authority is not known. This exception is to be expected when using self-signed certificates and can be confirmed.

     

How Does It Work?

We began the process by installing mod_ssl using the YUM package manager, which is the default Apache module to enable SSL. The next step was then to go to the standard location where all the system’s certificates can be found in CentOS 7, that is, /etc/pki/tls/certs. Here we can find a Makefile, which is a helper script for conveniently generating self-signed SSL test certificates and which hides away complicated command line parameters for the OpenSSL program from you. Remember that the Makefile currently lacks a clean option and therefore every time we run it, we need to delete any old versions of the generated files from a former run manually, otherwise it will not start doing anything. After deleting the old Apache SSL files, we used make with the testcert parameter, which creates self-signed certificates for the Apache web server and puts them in the standard locations, already configured in the ssl.conf file (the SSLCertificateFile and SSLCertificateKeyFile directives), so we didn’t have to change anything here. During the process, you were asked to provide a password before completing a series of questions. Complete the questions but pay special attention to the Common name. As was mentioned in the main process, this value should reflect either the domain name of your server or your IP address. In the next phase, you were required to open Apache’s SSL configuration file in your favorite text editor which can be found at /etc/httpd/conf.d/ssl.conf. In it we enabled the DocumentRoot directive to put it under SSL control and activated the ServerName directive with an expected domain value that must be the same as the one we defined as our common name value. We than saved and closed the configuration file and enabled the HTTPS ports in our firewall, thus allowing incoming connections over the standard HTTPS 443 port. Having completed these steps, you can now enjoy the benefits of a secure connection using a self-signed server certificate. Just type https:// instead of http:// for any URL address available on your Apache web browser. However, if you are intending to use an SSL Certificate on a production server for members of the public, then your best option is to purchase an SSL certificate from a trusted Certificate Authority.

There's more…

We learned that since our SSL certificate is protected by a passphrase, so whenever we need to restart our Apache web server, we need to enter the password. This is impractical for server restarts as Apache will refuse to start without a password. To get rid of the password prompt, we will provide the passphrase in a special file and make sure it is only accessible by root.

  1. Create a backup of the file that will contain your password:
    cp /usr/libexec/httpd-ssl-pass-dialog /usr/libexec/httpd-ssl-passdialog.BAK
  2. Now overwrite this password file with the following content, replacing XXXX in the following command line with your current SSL passphrase:
    echo -e '#!/bin/bash\necho "XXXX"' > /usr/libexec/httpd-ssl-passdialog
  3. Finally, change the permissions so that only root can read and execute them:
    chmod 500 /usr/libexec/httpd-ssl-pass-dialog