Skip to main content

CentOS

Installing a MariaDB database server on CentOS

Supporting over 70 collations, more than 30 character sets, multiple storage engines, and deployment in virtualized environment, MySQL is a mission-critical database server that is used by production servers all over the world. It is capable of hosting a vast number of individual databases and it can provide support for various roles across your entire network. MySQL server has become synonymous with the World Wide Web (WWW), is used by desktop software, extends local services, and is one of the world’s most popular relational database systems. The purpose of this process is to show you how to download, install, and lockdown MariaDB, which is the default implementation of MySQL in CentOS 7. MariaDB is open source and fully compatible with MySQL and adds several new features; for example, a non-blocking client API library, new storage engines with better performance, enhanced server status variables, and replication.

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. It is expected that your server will be using a static IP address.

The Process

As the MariaDB Database Management System (DBMS) is not installed by default on CentOS 7, we will start this process by installing the required packages.

  1. To begin, log in as root and type the following command to install the required packages:
    yum install mariadb-server mariadb
  2. When complete, ensure the service starts at boot before starting the service:
    systemctl enable mariadb.service && systemctl start mariadb.service
  3. Finally, begin the secure installation process with the following command:
    mysql_secure_installation
  4. When you first run the previous command, you will be asked to provide a password but as this value has not been set, press the Enter key to represent the value (blank) none.
  5. Now you will be asked a number of simple questions which will help you in the process of hardening your MariaDB DBMS system. It is good advice to choose Yes (Y) to every question for maximum security unless you are already a MariaDB expert and really require a certain feature. 
  6. Finally, test if you can connect and login to the MariaDB service locally using the MariaDB command-line client called mysql. The test passes if the following command outputs all the MariaDB user names together with their associated hosts known to the MariaDB server (enter the administrator root password you set in the last step when prompted):
    echo "select User,Host from user" | mysql -u root -p mysql

How Does It Work?

MariaDB is a fast, efficient, multithreaded, and robust SQL database server. It supports multiple users and provides access to a number of storage engines, and by following a few short steps, you now know how to install, secure, and login to your MariaDB server.

So what did we learn from this experience?

We started the process by installing the necessary package for the MariaDB server (mariadb-server) and also the client shell interface (mariadb) for controlling and querying the server. Having done this, we then proceeded to ensure that the MariaDB daemon (mariadb.service) would start during the boot process before we actually started it. At this point we had a working installation, but in order to ensure that our installation was safe we then invoked the secure installation script in order to guide us through a few simple steps to harden our basic installation. As the basic installation process does not enable us to set a default password for the root user, we did it here as a first step in the script, so we could be certain that no one could access the MariaDB root user account without the required authorization. We then discovered that a typical MariaDB installation maintains an anonymous user. The purpose of this is to allow anyone to login to our database server without having to have a valid user account. It is typically used for testing purposes only, and unless you are in unique circumstances that require this facility, it is always advisable to remove this feature. Following this, and to ensure that the root user could not access our MariaDB server installation, we then opted to disallow remote root access before removing the test database and performing a reload of the privilege tables. Finally, we ran a small test to see if we could connect to the database with the root user and query some data from the user table (which is part of the standard mysql database).

Having completed the steps of the process, we have learned that the process of installing and securing the MariaDB server is very simple. Of course, there are always more things that can be done in order to make the installation useful but the purpose of this process was to show you that the most important part of installing your new database system was to make it secure. Remember, the act of running mysql_secure_installation is recommended for all MariaDB servers and it is advisable regardless of whether you are building a development server or one that is used in a production environment. As a server administrator, security should always remain your top priority.

 

Using secure alternatives to FTP on CentOS

While using FTP is still popular to share data or to transfer files over the network, you must be aware that you are using a very unsecure network protocol that has no protection built into it out-of-the-box. This means that, during network transfer, your data is fully exposed to potential attackers. This is not what you want for transferring sensitive data, such as login credentials, at all. To avoid these potential risks, we will show you in this process how to use and set up two alternatives for securing FTP using FTPS (FTP over SSL or FTP/SSL) or SFTPS (SSH-enabled FTP).

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. You should already have installed and configured a basic vsftpd server (for details check, Providing Web Services for how to do it). Also, for setting up SFTP, we will need to create some self-signed certificates; if you want to know the details behind it, please read the Generating self-signed certificates process.

The Process

You have to choose beforehand if you want to use SFTP or FTPS. These two methods cannot be applied together, so you have to decide which option to choose first. If you switch between those methods, you need to restore the default configuration file state of vsftpd.conf or sshd_config first.

Securing your vsftpd server with SSL–FTPS
To secure your vsftpd server with SSL-FTPS performs the following steps:

  1. Log in as root and go to the standard certificate location:
    cd /etc/pki/tls/certs
  2. Now, let’s create a SSL key pair consisting of the certificate and its embedded public key, as well as the private key in one file for our ftp-server configuration (remember that the Common name value should reflect the domain name of your FTP server):
    make ftp-server.pem
  3. Change to a more secure file access rule:
    chmod 400 /etc/pki/tls/certs/ftp-server.pem
  4. Now, before working on it, first make a backup of the vsftpd.conf file.
    cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.BAK
  5. Now, enable SSL and add the key pair file that we just created to our vsftpd configuration:
    echo "rsa_cert_file=/etc/pki/tls/certs/ftp-server.pem
    ssl_enable=YES
    force_local_data_ssl=YES
    force_local_logins_ssl=YES
    pasv_min_port=40000
    pasv_max_port=40100" >> /etc/vsftpd/vsftpd.conf
  6. Next, we need to add a new firewalld service file, so open the following:
    vi /etc/firewalld/services/ftps.xml
  7. Put in the following content:


    enable FTPS ports
  8. Finally, reload the firewall, add the ftps service, and restart your vsftpd server:
    firewall-cmd --reload; firewall-cmd --permanent --add-service=ftps;
    firewall-cmd --reload
    systemctl restart vsftpd

Securing your vsftpd server using SSH – SFTP
To secure your vsftpd server using SSL-SFTP perform the following steps:

  1. First, create a group for all valid SFTP users:
    groupadd sshftp
  2. We will work on the sshd main config file, so please make a backup before making any changes:
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.BAK
  3. Now, open the sshd_config file, go to the line containing the Subsystem directive, disable it (which means putting a # sign at the beginning of the line), and add the following line to read as shown:
    #Subsystem sftp /usr/libexec/openssh/sftp-server
    Subsystem sftp internal-sftp
  4. Next, add the following lines to the end of the file to enable SFTP:
    Match Group sshftp
    ChrootDirectory /home
    ForceCommand internal-sftp
  5. Finally, restart the sshd daemon.
    systemctl restart sshd

How Does It Work?

Here in this process, you have learned how to make your file sharing more secure by switching from the standard FTP protocol to using FTP over SSL, or FTP over SSH. Regardless of which option you prefer, SSL is used to encrypt the data during transmitting, which helps you keep your privacy. Which variant you choose is up to you, but remember that SFTP is a bit easier to set up as you do not have to configure additional ports or certificates in your firewall, because everything runs over SSH and this should be enabled by default on most systems.

So, what did we learn from this experience?

We began the process by configuring FTPS. We went into a special directory called /etc/pki/tls/certs, where CentOS stores all its certificates. In it, there is a Makefile, which we used to create a .pem file that contains the public/private key pair and a self-signed certificate that we needed for our FTP server’s configuration. Afterwards, we used chmod to ensure that only the root user can read this file. Then, we appended six lines of code to our main vsftpd configuration file (first, we made a backup of the original file); they are pretty self-explanatory: enable the SSL protocol, use the self-signed certificate, disallow any non-SSL communication, and use a static range of passive control ports. Also, we created a new firewall service that will open these passive control ports that are needed for FTPS.

Afterwards, we configured SFTP using a chroot jail. If setting up SFTP without it, every login user can view the root filesystem, which is very insecure. Configuring SFTP is done completely in the main sshd config file. After making a backup of the original file, we changed the FTP subsystem to internal-sftp, which is a newer ftp server version, has better performance, and runs in the same process. Next, we added three lines to the vsftpd configuration file; only users in the sshftp group are using SFTP and are put into a chroot jail and can only view files up to their home directory. ForceCommand ignores all local settings by the users and enforces these rules here instead. To add new chrooted SFTP users, all you have to do is create a standard Linux user account and add them to the sshftp user group.

There's more…

If you want to test your enabled FTPS server, you need an FTP client that supports “FTP over TLS.” You have to find and enable this option in your FTP client’s settings. Under Linux, you can install the lftp client to test if you can connect to our FTPS server. First, install the lftp package (for example, yum install lftp). Then, configure the client using TLS:
echo "set ftp:ssl-auth TLS
set ftp:ssl-force true
set ftp:ssl-protect-list yes
set ftp:ssl-protect-data yes
set ftp:ssl-protect-fxp yes
set ssl:verify-certificate no" >~/.lftprc

Now, you can connect and test your FTPS server using the following:
lftp -u username

If you want to test your enabled SFTP server, you need the program called sftp:
sftp john@ -p 22

Note
You have to remember that all the changes to sshd_config will be reflected in SFTP as well. So, if you disabled root login or ran SSH over a different port than 22, you have to take it into consideration when you try to log in to SFTP.

 

Using YUM to remove packages in CentOS

In this process, we will investigate the role of using YUM with the intention of removing packages from your server. During the lifetime of your server, it is possible that certain applications and services may no longer be required. In such situations, it is typical that you will want to remove such packages in order to optimize your working environment, and it is the purpose of this process to show you how this is done.

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.

The Process:

This process will show you how to remove one or more packages by invoking the yum remove option. To do this, you will need to log in as the root user and complete the following process:

  1. To remove a single package, replace the package_name value with the appropriate value and type the following:
    yum remove package_name
  2. Wait for the transaction summary and confirmation prompt to be displayed, and then press either the Y key to confirm, or the N key to decline the transaction, as shown next:
    Is this ok [y/d/N]: y
  3. If you have declined the transaction, then no further work is required and you will exit YUM. However, if you have confirmed the transaction, then simply watch the progress of package removal until it is confirmed and prints out a Complete! message.

How Does It Work?

Applications that are no longer required can be removed with YUM. The process is very intuitive and similar to installing a new package, and it only requires you to confirm the name of the packages you want to remove.

So, what have we learned from this experience?

Having invoked the remove command, YUM will search your system to discover the relevant package; and by reading the package headers and metadata, it will also determine what dependencies this will affect. For example, if we wanted to remove a package called wget, we would begin by issuing the remove command like so: yum remove wget. YUM,
in turn, would then locate the package details from your system and obtain a transaction summary that may include any necessary dependencies that are no longer required. The transaction printed out will remain pending until you instruct YUM to remove the package(s) concerned. When confirmed, YUM will complete the transaction, which in return will result in the removal of the package or packages. 

You should take extra care if the summary makes reference to any dependencies as these may be required by other RPMs. If you are concerned that certain dependencies should remain on the system, it is often a good idea to end the current transaction and simply de-activate or disable the software concerned. As with the install command, you can also remove multiple packages at a time, leaving a single space between the package names:
yum remove package_name1 package_name2 package_name3

 

CentOS static network connection building

In this process, we will learn how to configure a static IP address for a new or existing CentOS server.

While a dynamically assigned IP address or DHCP reservation may be fine for most desktop and laptop users, if you are setting up a server, it is often the case that you will require a static IP address. From web pages to e-mail, databases to file sharing, a static IP address will become a permanent location from which your server will deliver a range of applications and services, and it is the intention of this process to show you how easily it can be achieved.

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 and a console-based text editor of your choice.

The Process

For the purpose of this process, you will be able to find all the relevant files in the directory, /etc/sysconfig/network-scripts/. First, you need to find out the correct name of the network interface that you want to set as static. If you need to set more than one network interface as static, repeat this process for every device.

  1. To do this, log in as root and type the following command to get a list of all of your system’s network interfaces:
    ip addr list
  2. If you have only one network card installed, it should be very easy to find out its name; just select the one not named lo (which is the loopback device). If you got more than one, having a look at the IP addresses of the different devices can help you choose the right one. In our example, the device is called enp0s3.
  3. Next, make a backup of the network interface configuration file (change the enp0s3 part accordingly, if your network interface is named differently):
    cp /etc/sysconfig/network-scripts/ifcfg-enp0s3/etc/sysconfig/networkscripts/ifcfg-enp0s3.BAK

  4. When you are ready to proceed, open the following file in your favorite text editor by typing what is shown next:
    vi /etc/sysconfig/network-scripts/ifcfg-enp0s3

  5. Now, work down the file and apply the following changes:
    NM_CONTROLLED="no"
    BOOTPROTO=none
    DEFROUTE=yes
    PEERDNS=no
    PEERROUTES=yes
    IPV4_FAILURE_FATAL=yes

  6. Now, add your IP information by customizing the values of XXX.XXX.XXX.XXX as required:
    IPADDR=XXX.XXX.XXX.XXX
    NETMASK= XXX.XXX.XXX.XXX
    BROADCAST= XXX.XXX.XXX.XXX

  7. We must now add a default gateway. Typically, this should be the address of your router. To do this, simply add a new line at the bottom of the file, as shown next, and customize the value as required:
    GATEWAY=XXX.XXX.XXX.XXX

  8. When ready, save and close the file before repeating this step for any remaining Ethernet devices that you want to make static. When doing this, remember to assign a different IP address to each device.

  9. When finished, save and close this file before restarting your network service:
    systemctl restart network

How it works…

In this process, you have seen the process associated with changing the state of your server’s IP address from a dynamic value obtained from an external DHCP provider to that of a static value assigned by you. This IP address will now form a unique network location from which you will be able to deliver a whole host of services and applications. It is a permanent modification, and yes, you could say that the process itself was relatively straightforward.

So, what have we learned from this experience?

Having started the process by identifying your network interface name of choice and creating a backup of the original Ethernet configuration files, we then opened the configuration file located at /etc/sysconfig/network-scripts/ifcfg-XXX (with XXX being the name of your interface, for example, enp0s3). As being static no longer requires the services of the network manager, we disabled NM_CONTROLLED by setting the value to no. Next, as we are in the process of moving to a static IP address, BOOTPROTO has been set to none, as we are no longer using DHCP. To complete our configuration changes, we then moved on to add our specific network values and set the IP address, the netmask, broadcast, and the default gateway address.

In order to assist the creation of a static IP address, the default gateway is a very important setting in as much as it allows the server to contact the wider world through a router.

When finished, we were asked to save and close the file before repeating this step for any remaining Ethernet devices. Having done this, we were then asked to restart the network service in order to complete this process and to enable our changes to take immediate effect.

 

Securing Apache in CentOS

Even though the Apache HTTP server is one of the most mature and safe server applications included in CentOS 7, there is always room for improvement and a large number of options and techniques are available to harden your web server’s security even more. While we cannot show the user every single security feature as it is outside of the scope this book, in this process, we will try to teach what is considered to be good practice when it comes to securing your Apache web server for a production 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 and a console-based text editor of your choice. It is expected that your server will be using a static IP address and Apache is installed and currently running, and that your server supports one or more domains or subdomains.

The Process

Most of the security options and techniques have to be set up in the main Apache configuration file, so we will begin this process by opening it in our favorite text editor.

Configuring httpd.conf to provide better security

  1. To begin, log in as root and open the main Apache config file:
    vi /etc/httpd/conf/httpd.conf
  2. Now go to your main document root. To do so, search the directive called:
  3. Within the beginning and closing tags find the line Options Indexes FollowSymLinks, then disable (comment out) this line by putting a # in front of it, so it reads:
    # Options Indexes FollowSymLinks
  4. Now scroll down to the end of the configuration file and insert the following line one line before the line # Supplemental configuration. We do not want our server to leak any detailed information through the header, so we type:
    ServerTokens Prod
  5. Afterwards, reload the Apache configuration to apply your changes:
    apachectl configtest && systemctl reload httpd

Removing unneeded httpd modules

Even the most stable, mature, and well-tested programs can include bugs and cause vulnerabilities, as the latest news about the Heartbleed bug in OpenSSL or Shellshock in Bash have shown, and the Apache web server is no exception. Therefore, it is often beneficial to remove all unneeded software to limit the functionality, and thus the likelihood of security problems in your system. For the Apache web server, we can remove all unneeded modules to increase security (this can also increase performance and memory consumption). Let’s start this process by reviewing all the currently installed Apache modules.

  1. To show all currently installed and loaded Apache modules, type as user root:
    httpd -M
  2. All the modules outputted by the preceding command are loaded into the Apache web server by special configuration files in the /etc/httpd/conf.modules.d folder where they are grouped together by their primary target into the following files:
    00-base.conf, 00-dav.conf, 00-lua.conf, 00-mpm.conf, 00-proxy.conf, 00ssl.conf, 00-systemd.conf, 01-cgi.conf, 10-php.conf
  3. So instead of going through all the modules individually, this file structure in the conf.modules.d folder can make our life much easier because we can disable/enable whole groups of modules. For example, if you know that you will not need any Apache DAV modules because you will not provide any WebDAV server, you can disable all DAV-related modules by renaming the extension of the 00-dav.conf configuration file since only files with the ending .conf are read and loaded automatically by Apache. In order to do so, type:
    mv /etc/httpd/conf.modules.d/00-dav.conf /etc/httpd/conf.modules.d/00dav.conf.BAK
  4. Afterwards, reload the Apache configuration to apply your changes to the modules directory:
    apachectl configtest && systemctl reload httpd
  5. If you need more fine-grained control, you can also enable/disable single modules in all the configuration files in this directory as well. For example, open 00-base.conf in your favorite text editor and disable a single line by adding a # to the beginning of the line of choice you want to disable. For example:
    # LoadModule userdir_module modules/mod_userdir.so
  6. If you decide to use some disabled modules files later, just rename the .BAK file to the original file name or remove the # in a specific module config file before reloading httpd once again.

Protecting your Apache files

Another really simple way to increase the security of your Apache web server is to protect your server-side scripts and configurations. In our scenario, we have one user (root) who alone is responsible and maintains the complete Apache web server, websites (for example, uploading new HTML pages to the server), server-side scripts, and configurations. Therefore, we will give him/her full file permissions (read/write/execute). The apache user still needs proper read and execute permissions to serve and access all Apache related files, thus minimizing the risk that your Apache web server is exposing some potential security risks to other system users or can get compromised through HTTP hacks. Do this in two steps:

  1. First we will change or reset the ownership of the complete Apache configuration directory and the standard web root directory to owner root and group apache:
    chown -R root:apache /var/www/html /etc/httpd/conf*
  2. Afterwards, we will change the file permissions so no one other than our dedicated apache user (and also root) can read those files:
    chmod 750 -R /var/www/html /etc/httpd/conf*

How Does It Work?

We began this process by opening the main Apache configuration file httpd.conf to change settings for our main Apache root web content directory /var/www/html. Here we disabled the complete Options directive which included the Indexes as well as the FollowSymLinks parameter. As we have learned, if you request a directory instead of a file from the Apache server, index.html or the index.htm file within this directory will be sent automatically. Now the Indexes option configures the Apache web server in such a way that if no such file can be found in the requested directory, Apache will auto-generate a listing of the directory’s content, as if you had typed ls (for list directory) in that directory on the command line, and show it to the user as a HTML page. We don’t want this feature in general because it can expose secret or private data to unauthorized users and a lot of system administrators will tell you that indexing is considered to be a security threat in general. The FollowSymLinks directive should also not be used in production systems because if you make a mistake with it, it can easily expose parts of the file system, such as the complete root directory. Finally, we add another measurement to increase the server’s base security and this is done by disabling the server version banner information. When the Apache web server generates either a web page or an error page, valuable information, for example the Apache server version and the activated modules, is sent automatically to the browser and a possible attacker can gain valuable information about your system. We stopped this from happening by simply setting ServerTokens to Prod. Afterwards, we showed you how to disable Apache modules to reduce the general risk of bugs and exploitations of your system. Finally, we showed how to adjust your Apache file permissions which can also be a good general protection.

There are lots of other things to consider when it comes to hardening your Apache web server but most of these techniques, such as Limiting HTTP request methods, TraceEnable, setting cookies with HttpOnly and secure flags, disabling the HTTP 1.0 protocol or SSL v2, or modifying the HTTP header with useful security-related HTTP or custom headers such as X-XSS-Protection, are much more advanced concepts and can restrict a general purpose Apache web server too much.

 

Building a secondary (slave) DNS server on CentOS

To guarantee high-availability in your network, it can be useful to operate more than one DNS server in your environment to catch up with any server failures. This is particularly true if you run a public DNS server where continuous access to the service is crucial and where it is not uncommon to have five and more DNS servers at once. Since configuring and managing multiple DNS servers can be time-consuming, the BIND DNS server uses the feature of transferring zone files between the nodes so that every DNS server has the same domain resolving and configuration information. In order to do this, we need to define one primary and one or more secondary or slave DNS servers. Then we only have to adjust our zone file once on the primary server which will transfer the current version to all our secondary servers, keeping everything consistent and up-to-date. For a client, it will then make no difference which DNS server they are connecting to.

To Start With: What Do You Need?

To complete this process, you will require at least two CentOS 7 servers in the same network which can see and ping each other. An Internet connection will be required to download and install the BIND server software on all the computers we want to include in our DNS server farm. In this example, we have two servers, 192.168.1.7 which is already installed and configured as a BIND server, and 192.168.1.15 which will be our second BIND server within the subnet 192.168.1.0/24. You should also have read and applied the zone file process from this chapter division and create a forward and reverse zone file because this is what we want to transfer between DNS servers.

The Process

We begin this process by installing BIND on every CentOS 7 computer we want to include in our BIND DNS server cluster. To do this, follow the process, Setting up an authoritative-only DNS server for all the remaining systems. Before we can start, we need to define which server will be our primary DNS server. For simplicity in our example, we will choose the server with the IP address 192.168.1.7. Now let’s make all our DNS server nodes aware of their role.

Changes to the primary DNS server

  1. Let’s log in as root on the primary server and open its main configuration:
    vi /etc/named.conf
  2. Now we define which secondary DNS server(s) will be allowed to receive the zone files at all, write the following command somewhere between the options curly brackets in a new line (we only have one secondary DNS server with the IP address 192.168.1.15, change accordingly):
    allow-transfer { 192.168.1.15; };
    notify yes;
  3. Also, we must allow the other nameservers to connect to our primary nameserver. In order to do this, you need to change your listen-on directive to include the DNS server’s primary network interface (in our example 192.168.1.7 , so change appropriately):
    listen-on port 8053 { 127.0.0.1;192.168.1.7; };
  4. Save and close the file. Now open the new port 8053 in your server’s firewall (or you can create a firewalld service for it )
    firewall-cmd --permanent --zone=public --add-port=8053/tcp --addport=8053/udp;firewall-cmd --reload
  5. Save and close the file. Next, update the zone files we created earlier to include the IP addresses of all the new nameservers we have available in the system. Change both the forward and reverse zone files, /var/named/centos7.home.db and /var/named/db.1.168.192, to include our new secondary DNS server. In the forward zone file, add the following lines (you can also use the nsupdate program to do this) into the appropriate sections:
    NS ns2.centos7.home.
    ns2 A 192.168.1.15
  6. In the reverse zone file, add instead into the appropriate sections:
    NS ns2.centos7.home. 15 PTR ns2.centos7.home.
  7. Finally, restart BIND and recheck the configuration file:
    named-checkconf && systemctl restart named

Changes to the secondary DNS server(s)

For simplicity and to demonstrate, just install named on any server you want to use as a BIND slave (we only show the important configuration here):

  1. Log in to the new server as root, install BIND, and open its main configuration:
    yum install bind; vi /etc/named.conf
  2. Now locate the line include /etc/named.rfc1912.zones;. Immediately following this line, create a space for your work and add the following zones (replace the zone and file names appropriately):
    zone "centos7.home" IN {
        type slave;
        masters port 8053 { 192.168.1.7; };
        file "/var/named/centos7.home.db";
    };
    zone "1.168.192.in-addr.arpa" IN {
         type slave;
         masters port 8053{ 192.168.1.7; };
         file "/var/named/db.1.168.192.db";
    };
  3. Save and close the file. Then fix some incorrect BIND folder permissions and enable named to write into its zone file directory before restarting BIND:
    chown :named /var/named -R; chmod 775 /var/named -R
    setsebool -P named_write_master_zones 1
    named-checkconf && systemctl restart named
  4. Now initiate a new zone transfer using:
    rndc refresh centos7.home.
  5. After waiting a while, to test if our secondary DNS server is working as expected, check if the master zone files have been transferred:
    ls /var/named/*.db
  6. Finally, we can now test if we can query our local domain on the secondary DNS server too:
    dig @127.0.0.1 client2.centos7.home.

How Does It Work?

In this process, we showed you how to set up secondary BIND servers in your network which can help in increasing the stability and availability of your DNS server system.

So what did we learn from this experience?

We started our journey by deciding which of our servers should be the primary and which should be the slave DNS servers. Then we opened the BIND main configuration file on the primary server and introduced two lines of code to configure our server to be the head of our DNS cluster. The allow-transfer directive defines to which clients we want to transfer our updated zone files while the notify yes directive enables automatic transfer when any changes to the zone files happen. If you have got several secondary BIND DNS servers, you can add more than one IP address into the allow-transfer directive, separated by semicolons. Then we opened our zone files we created in a former process and introduced a new line IN NS which defines the IP address of our secondary DNS servers we need to be aware on every DNS node in our system. If we have got multiple servers, then we introduce multiple IN NS lines. Finally, we introduced a small comment to easily check the successful zone file transfer on our secondary servers.

Afterwards, we configured our slave DNS server(s). Here we introduced the same zone file definitions as on the primary server’s BIND configuration, with the exceptions that we used type slave instead of master to denote we are a secondary DNS server and will get a copy of the zone files from the master node by defining the primary DNS server’s IP address using the masters directive (please do not forget that our master BIND is listening on the non-default port 8053 in our example).

Since we had not created or copied the zone files ourselves on the slave DNS server, it was then easy to check if the zone file transfer had been successful after restarting the BIND service using the ls command. Finally, we verified the transferred zone file content by running test queries using dig or nslookup to see if we could resolve the same local hostnames on our secondary DNS server. Remember if you later make changes to your master’s zone files you have to increase their serial number in order that those changes get transferred to all your slaves.

 

Generating self-signed certificates on CentOS

In this process, we will learn how to create self-signed Secure Sockets Layer (SSL) certificates using the OpenSSL toolkit. SSL is a technology used to encrypt messages between two ends of communication (for example, a server and client) so that a third-party cannot read the messages sent between them. Certificates are not used for encrypting the data, but they are very important in this communication process to ensure that the party you are communicating with is exactly the one you suppose it to be. Without them, impersonation attacks would be much more common.

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 and a console-based text editor of your choice.

Note
Generally speaking, if you are intending to use an SSL Certificate on a production server, you will probably want to purchase a SSL Certificate from a trusted Certificate Authority. There are many options open to you regarding what certificate best suits your requirements and your budget, but for the purpose of this process, we will confine our discussion to a self-signed certificate that is more than adequate for any development server or internal network.

The Process

  1. To begin, log in as root and go to the following directory so that we can use the Makefile to generate our intended certificates and keyfiles:
    cd /etc/pki/tls/certs
  2. Now, to create a self-signed certificate with an embedded public key (both in the file, server.crt) along with its private key for the server (with the filename as server.key), type the following:
    make server.crt
  3. You will then be asked for a password and will receive a series of questions, to which you should respond with the appropriate values. Complete all the required details by paying special attention to the common name value, which should reflect the domain name of the server or IP address that you are going to use this certificate for. For example, you may type:
    mylocaldomainname.home
  4. To create a pem file that includes a self-signed certificate and a public and a private key in one file, and is valid for five years, type the following:
    make server.pem DAYS=1825
  5. Now, let’s create a key pair (a private key and self-signed certificate that includes the public key) for an Apache web server that we will need for enabling https, and which will be generated in /etc/pki/tls/private/localhost.key and /etc/pki/tls/certs/localhost.crt (use a secure password and repeat it in the second command):
    make testcert
  6. To create a Certificate Signing Request (CSR) file instead of a self-signed certificate, use this:
    make server.csr

How Does It Work?

Here in this process we introduced you to the SSL technology that uses public key cryptography (PKI) (where two forms of keys exist: public and private). On the server, we store the private key and our clients get a public key. Every message sent from one end to the other is encrypted by the key belonging to one side and can only be decrypted by the corresponding key from the other. For example, a message encrypted with the server’s private key can only be decrypted and read by the client’s public key and vice versa. The public key is sent to the client through a certificate file, where it is part of the file. As said before, the public key is encrypting and decrypting the data and the certificate is not responsible for this, but rather for identifying a server against a client and making sure that you are actually connected to the same server you are trying to connect. If you want to set up secure services using SSL encryption in protocols such as FTPS, HTTPS, POP3S, IMAPS, LDAPS, SMTPS, and so on, you need a signed server certificate to work with. If you want to use these services for your business, and you want them to be trusted by the people who are using and working with them, for example, on the public Internet, your certificate should be signed from an official certification authority (CA). Certificate prices are paid by subscription and can be very expensive. If you don’t plan to offer your certificate or SSL-enabled services to a public audience, or you want to offer them only within a company’s intranet or just want to test out things before buying, here you can also sign the certificate by yourselves (self-signed) with the OpenSSL toolkit.

Note
The only difference between a self-signed certificate and one coming from an official CA is that most programs using the certificate for communication will give you a warning that it does not know about the CA and that you should not trust it. After confirming the security risk, you can work with the service normally.

So, what did we learn from this experience?

We started this process by going to the standard location where all the system’s certificates can be found in CentOS 7: /etc/pki/tls/certs. Here, we can find a Makefile, which is a helper script for conveniently generating public/private key pairs, SSL CSRs, and self-signed SSL test certificates. It works by hiding away from you complicated command line parameters for the OpenSSL program. It is very easy to use and will automatically recognize your target through the file extension of your filename parameter. So, it was a simple process to generate an SSL key pair by providing an output filename with the .crt extension. As said before, you will be asked for a password and a list of questions regarding the ownership of the certificate, with the most important question being the common name. This should reflect the domain name of the server you are planning to use this certificate for, because most programs, such as web browsers or email clients, will check the domain names to see if they are valid. The result of running this command was the certificate with its embedded public key in file server.crt, as well as the corresponding private key for the server called server.key.

Next, we created a .pem file and provided a DAYS parameter to make the certificate valid for five years instead of the default one year when you are running without it. A pem file is a container file that contains both parts of the key pair: the private keys and the self-signed certificate (with its embedded public key). This file format is sometimes required by some programs, such as vsftpd, to enable SSL encryption instead of providing the key-pair in two separated files. Next, we ran the Makefile target testcert, which generates a private key as well as a public key, plus the certificate in the correct location, where the Apache web server is expecting them for setting up HTTPS. Please note that, if you need to repeat any Makefile run later, you need to delete the generated output files; for example, for Apache, you need to delete the following files before you can build the output files again:
rm /etc/pki/tls/certs/localhost.crt /etc/pki/tls/private/localhost.key make testcert

Finally, we showed you how to generate a CSR file, which will be needed if you plan to purchase an SSL certificate from a trusted certificate authority.

There's more…

We did not cover all the possibilities that the Makefile script has to offer to generate certificates. If you run the command, make, without giving any target parameter, the program will print out a usage help text with all possible options.

As we have learned, the public and private keys are generated in pairs and will encrypt and decrypt each partner’s messages. You can verify that your key pairs are valid and belong together by comparing the output of the following (which must be exactly the same):
openssl x509 -noout -modulus -in server.crt | openssl md5 openssl rsa -noout -modulus -in server.key | openssl md5

 

 

Using YUM to install packages on CentOS

In this process, we will investigate the role of YUM in installing new packages on your server. An important task for every server administrator is the installation of applications and services. There are several different ways to achieve this, but the most effective method involves the YUM package manager. YUM is able to search through any number of repositories, automatically resolve package dependencies, and specify the installation of one or more packages. YUM is a modern and definitive way to install your packages on your server, and it is the purpose of this process to show you how it is done.

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’s also good if you have already found some interesting packages to install, which can be learned by using the instructions from the Using YUM to search for packages process. 

The Process

This process will show you how to install one or more packages by invoking the YUM installation option. To do this, you will need to log in as the root user and complete the following process:

  1. To install a single package, replace the package_name value with the appropriate value and type the following:
    yum install package_name
  2. Your system will now provide a transaction report that will require your approval. So, when prompted, simply respond by using the Y or N key and press the Return key to either accept or decline the transaction, as shown as follows:
    Is this ok [y/d/N]: y
  3. If you have declined the transaction, then no further work is required and you will exit the package management routine. However, if you have confirmed the transaction, then watch the progress of your installation, and in the end, it will show you a Complete! Message.
  4. Congratulations! You now have successfully installed your package of choice.

How Does It Work?

All packages are stored in the RPM package file format, and it is the role of YUM to provide access to those files that are stored in various repositories on the Internet. YUM is the power behind the package management for CentOS and it really does make the installation process very easy, but what have we learned from this experience?

Having invoked the install command, YUM will conduct a search of the various repositories in order to find the relevant headers and metadata associated with the package in question. For example, if you wanted to install a package called wget, you would begin by issuing the install command like so: yum install wget. YUM will then locate the package and generate a transaction summary that will not only indicate the required disk size and expected installation size but will also indicate any necessary dependencies required by the requested package. YUM will then check several different repositories (base, extras, and updates) and, having resolved the need for any necessary
dependencies, YUM will be asking us to confirm the request before continuing with the installation process. So, as you can see, by using the Y key, we will be providing YUM with the permission to fulfill the request, which in turn will result in the download, verification, and installation of the package(s) concerned.

There’s More:

There are times when you may wish to install more than one package at a time. To do this, simply invoke the same install command, but instead of naming a single package, simply identify the full list of packages you may require in such a way that it forms a long shopping list:
yum install package_name1 package_name2 package_name3

The number of packages you can install in this way is unlimited, but always leave a single space between each package name and keep the command on a single line. For very long installation instructions, line-wrapping may occur.
You do not need to list the packages in any particular order and the request will be processed in exactly the same way as it was in the original process, and again after listing the transaction summary, it will remain pending until it is confirmed or declined. Again, use the Y key to confirm your request so that the process completes.

 

 

Using YUM to search for packages in CentOS

In this process, we will investigate the role of using YUM to find a package. YUM was developed to improve the installation of RPM software packages, and it is used to access a growing list of packages that provide a full range of services offered by your server. YUM is simple to use, but if you are not sure what a package is called, then your duties as the server administrator can become that much harder. To overcome this, YUM maintains an extensive range of discovery tools and it is the purpose of this process to show you how to use this functionality in order to search through the various repositories and find the package you need.

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.

The Process:

This process will show you how to find one or more packages by invoking YUM’s searching options. To do this, you will need to log in as the root user and complete the following process:

  1. To search for a single package, replace the keyword value with the appropriate phrase, string, or parameter, and type the following:
    yum search keyword
  2. Wait for a summary of the search results, and when a list is generated, you can query any package shown by simply replacing package_name with the appropriate value:
    yum info package_name
  3. If the preceding results prove satisfactory, and you want to view a list of dependencies associated with the package in question, type the following:
    yum deplist package_name

How Does It Work?

Searching for packages with YUM can be achieved in the same way as you would search for anything on the World Wide Web (WWW). The types of words you can search for can be as specific or as general as you like. They can even consist of full or partial words;
having found a package that you may be interested in, you will have noticed that this process has also served to show you how to discover additional information about the package in question.

So, what have we learned from this experience?

YUM maintains extensive search features and it allows you to query packages by keyword, package name, and pathname. For example, if you want to locate the correct package for compiling C, Objective-C, and C++ code, you can use the yum search compiler query. When using these search terms on the command line, there are a number
of related results, and each package carries a brief description that enables us to use a simple process of elimination in order to select the most obvious or the most relevant value. With this in mind, you can then query YUM using the info parameter to find out
more about certain packages. This option reveals the full package details together with a detailed description of what functionality the package is intended to provide. Generally speaking, you may not need to know any further details.

However, there may be circumstances in which you want to know how this package interacts with the server as a whole (especially if you are working with source installations or troubleshooting broken packages), so we can use YUM’s deplist parameter that can give quite a detailed report; if you do happen to have any broken packages, you could simply use this output to detail what dependencies you may or may not need to install in order to fix an underlying issue. This command is particularly useful when debugging dependencies or when working with source-based installations.

There’s More:

Sometimes, you may not want to search for a specific package, and instead, you may prefer to display the contents of your repositories in a catalog-style format. Again, this is easy to do and YUM provides for this functionality with the following commands. If you would like to simply list all the packages available to you from the current repositories used by your system, type yum list all. However, because this list may be quite exhaustive, you may prefer to page through the results by using yum list all | less. In a similar fashion, if you would simply like to list all the software currently installed on your system, type yum list installed | less. If you would like to determine which packages provide for a specific file or feature, simply run the following command at any time by substituting your_filename_here with something more relevant to your own needs: yum provides your_filename_here.

 

Setting your hostname and resolving the network on CentOS

The process of setting the hostname is typically associated with the installation process. If you ever need to change it or your server’s Domain Name System (DNS) resolver, this process will show you how.

To Start With: What Do You Need?

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

The Process

To start this process, we shall start by accessing the system as root and opening the following file in order to name or rename your current server’s hostname:

  1. Log in as root and type in the following command to see the current hostname:
    hostnamectl status
  2. Now, change the hostname value to your preferred name. For example, if you want to call your server jimi, you would type (change appropriately):
    hostnamectl set-hostname jimi

    Note
    Static hostnames are case-sensitive and restricted to using an Internet-friendly alphanumeric string of text. The overall length should be no longer than 63 characters, but try to keep it much shorter.

  3. Next, we need the IP address of the server. Type in the following command to find it (you need to identify the correct network interface in the output):
    ip addr list
  4. Afterward, we will set the Fully Qualified Domain Name (FQDN), in order to do this, we will need to open and edit the host's file:
    vi /etc/hosts
  5. Here, you should add a new line appropriate to your needs. For example, if your server’s hostname was called jimi, (with an IP address of 192.168.1.100, and a domain name of henry.com) your final line to append will look like this:
    192.168.1.100          jimi.henry.com jimi

    Note
    For a server found on a local network only, it is advisable to use a non-Internet based top-level address. For example, you could use .local or .lan, or even .home, and by using these references you will avoid any confusion with the typical .com, .co.uk, or .net domain names.

  6. Next, we will open the resolv.conf file, which is responsible for configuring static DNS server addresses that the system will use:
    vi /etc/resolv.conf

  7. Replace the content of the file with the following:
    # use google for dns
    nameserver 8.8.8.8
    nameserver 8.8.4.4

  8. When complete, save and close your file before rebooting your server to allow the changes to take immediate effect. To do this, return to your console and type:
    reboot

  9. On a successful reboot, you can now check your new hostname and FQDN by typing the following commands and waiting for the response:
    hostname --fqdn

  10. To test if we can resolve domain names to IP addresses using our static DNS server addresses, use the following command:
    ping -c 10 google.com

 

How it works…

A hostname is a unique label created to identify a machine on a network. It is restricted to alphanumeric-based characters, and making a change to your server’s hostname can be achieved by using the hostnamectl command. A DNS server is used to translate domain names to IP addresses. There are several public DNS servers available; in a later process, we will build our own DNS service.

So, what have we learned from this experience?

In the first stage of the process, we changed the current hostname used by our server with the hostnamectl command. This command can set three different types of hostnames. Using the command with the set-hostname parameter will set the same name for all three hostnames: the high-level pretty hostname, which might include all kinds of special characters (for example, Lennart's Laptop), the static hostname which is used to initialize the kernel hostname at boot (for example lennarts-laptop), and the transient hostname, which is a default received from network configurations.

Following this, we set the FQDN of our server. A FQDN is a hostname along with a domain name after it. A domain name gets important when you are running a private DNS, or allowing external access to your server. Besides using a DNS server setting the FQDN can be achieved by updating the host's file found at /etc/hosts.

This file is used by CentOS to map hostnames to an IP address, and it is often found to be incorrect on a new, un-configured, or recently installed server. For this reason, we first had to find out the IP address of the server using ip addr list.

An FQDN should consist of a short hostname and the domain name. Based on the example shown in this process, we set the FQDN for a server named henry, whose IP address is 192.168.1.100 and domain name is henry.com.

Saving this file would arguably complete this process. However, because the kernel makes a record of the hostname during the boot process, there is no choice but to reboot your server before you can use the changed settings.

Next, we opened the system’s resolv.conf file, which keeps the IP addresses of the system’s DNS servers. If your server does not use or have any DNS records, your system is not able to use domain names for network destinations in any program at all. In our example, we entered the public Google DNS server IP addresses, but you are allowed to use any DNS server you want or have to use (often in a cooperate environment, behind a firewall, you have to use internal DNS server infrastructures). On a successful reboot, we confirmed your new settings by using the hostname command, which can print out the hostname or the FQDN based on the parameters given.

So, in conclusion, you can say that this process has not only served to show you how to rename your server and resolve the network but has also shown you the difference between a hostname and domain name:

As we have learned, a server is not only known by the use of a shorter, easier-to-remember, and quicker-to-type single-word-based hostname, it also consists of three values separated with a period (for example jimi.henry.com). The relationship between these values may have seemed strange at first, especially where many people would have seen them as a single value, but by completing this process you have discovered that the domain name remains distinct from the hostname by virtue of being determined by the resolver subsystem, and it is only by putting them together that your server will yield the FQDN of the system as a whole.

There's more…

The hosts file consists of a list of IP addresses and corresponding hostnames, and if your network contains computers whose IP addresses are not listed in an existing DNS record, then in order to speed up your network it is often recommended that you add them to this file.

This can be achieved on any operating system, but to do this on CentOS, simply open the host's file in your favorite text editor, as shown next:
vi /etc/hosts

Now, scroll down to the bottom of the file and add the following values by substituting the domain names and IP addresses shown here with something more appropriate to your own needs:

192.168.1.100 www.example1.lan

192.168.1.101 www.example2.lan

You can even use an external address such as:
83.166.169.228 www.packtpub.com

This method provides you with the chance to create mappings between domain names and IP addresses without the need to use a DNS, and it can be applied to any workstation or server. The list is not restricted by size, and you can even employ this method to block access to certain websites by simply re-pointing all requests to visit a known website to a different IP address. For example, if the real address of www.website.com is 192.168.1.200 and you want to restrict access to it, then simply make the following changes to the host's file on the computer that you want to block from access:
127.0.0.1 www.website.com

It isn’t failsafe, but in this instance, anyone trying to access www.website.com on this system will automatically be sent to 127.0.0.1, which is your local network address, so this will just block access.

When you have finished, remember to save and close your file in the usual way before proceeding to enjoy the benefits of faster and safer domain name resolution across any available network.