Ubuntu 18.04 Apache2 with PHP

Introduction

When you first create a new Ubuntu 18.04 server, there are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions.

Step 1 — Setting Up a Basic Firewall

Ubuntu 18.04 servers can use the UFW firewall to make sure only connections to certain services are allowed. We can set up a basic firewall very easily using this application.

Different applications can register their profiles with UFW upon installation. These profiles allow UFW to manage these applications by name. OpenSSH, the service allowing us to connect to our server now, has a profile registered with UFW.

You can see this by typing:

ufw app list
OutputAvailable applications:
  OpenSSH

We need to make sure that the firewall allows SSH connections so that we can log back in next time. We can allow these connections by typing:

ufw allow OpenSSH

Afterwards, we can enable the firewall by typing:

ufw enable

Type “y” and press ENTER to proceed. You can see that SSH connections are still allowed by typing:

ufw status
OutputStatus: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

As the firewall is currently blocking all connections except for SSH, if you install and configure additional services, you will need to adjust the firewall settings to allow acceptable traffic in. You can learn some common UFW operations in this guide.

Step 2 — Installing Apache

Apache is available within Ubuntu’s default software repositories, making it possible to install it using conventional package management tools.

Let’s begin by updating the local package index to reflect the latest upstream changes:

sudo apt update

Then, install the apache2 package:

sudo apt install -y apache2 

After confirming the installation, apt will install Apache and all required dependencies.

Step 3 — Adjusting the Firewall

Before testing Apache, it’s necessary to modify the firewall settings to allow outside access to the default web ports. Assuming that you followed the instructions in the prerequisites, you should have a UFW firewall configured to restrict access to your server.

During installation, Apache registers itself with UFW to provide a few application profiles that can be used to enable or disable access to Apache through the firewall.

List the ufw application profiles by typing:

sudo ufw app list

You will see a list of the application profiles:

OutputAvailable applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH

As you can see, there are three profiles available for Apache:

  • Apache: This profile opens only port 80 (normal, unencrypted web traffic)
  • Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
  • Apache Secure: This profile opens only port 443 (TLS/SSL encrypted traffic)

If you look at the Apache Full profile, it should show that it enables traffic to ports 80 and 443:

sudo ufw app info "Apache Full"
OutputProfile: Apache Full
Title: Web Server (HTTP,HTTPS)
Description: Apache v2 is the next generation of the omnipresent Apache web
server.

Ports:
  80,443/tcp

Allow incoming HTTP and HTTPS traffic for this profile:

sudo ufw allow 'Apache Full' 

You can verify the change by typing:

sudo ufw status

You should see HTTP traffic allowed in the displayed output:

OutputStatus: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Apache                     ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Apache (v6)                ALLOW       Anywhere (v6)

As you can see, the profile has been activated to allow access to the web server.

Step 4 — Checking your Web Server

At the end of the installation process, Ubuntu 18.04 starts Apache. The web server should already be up and running.

Check with the systemd init system to make sure the service is running by typing:

sudo systemctl status apache2
Output:
apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since Wed 2019-01-23 10:25:01 UTC; 12min ago
 Main PID: 4589 (apache2)
    Tasks: 55 (limit: 4661)
   CGroup: /system.slice/apache2.service
           ├─4589 /usr/sbin/apache2 -k start
           ├─4591 /usr/sbin/apache2 -k start
           └─4592 /usr/sbin/apache2 -k start

As you can see from this output, the service appears to have started successfully. However, the best way to test this is to request a page from Apache.

You can access the default Apache landing page to confirm that the software is running properly through your IP address. If you do not know your server’s IP address, you can get it a few different ways from the command line.

Try typing this at your server’s command prompt:

hostname -I

You will get back a few addresses separated by spaces. You can try each in your web browser to see if they work.

An alternative is typing this, which should give you your public IP address as seen from another location on the internet:

curl -4 icanhazip.com

When you have your server’s IP address, enter it into your browser’s address bar:

http://your_server_ip

You should see the default Ubuntu 18.04 Apache web page:

Apache default page

This page indicates that Apache is working correctly. It also includes some basic information about important Apache files and directory locations.

Step 5 — Hide Apache Version and Operating System

By-default the apache version and OS are shown in the response headers as shown below. This is a major security loophole exposing such details to the world and be used by hackers.

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel

From the figure, it shows the web server is running on Apache Version 2.4.29 and on Ubuntu OS. To hide those details, add the two lines in apache config file /etc/apache2/conf-enabled/security.conf

  • sudo cp /etc/apache2/conf-enabled/security.conf /etc/apache2/conf-enabled/security.conf.orig
  • sudo sed -i ‘s/ServerSignature On/ServerSignature Off/g’ /etc/apache2/conf-enabled/security.conf
  • sudo sed -i ‘s/ServerTokens OS/ServerTokens Prod/g’ /etc/apache2/conf-enabled/security.conf

Then reload Apache:

  1. sudo systemctl reload apache2

Refresh the browser and you’ll notice the version and OS details removed as shown below:

Step 6: Install ModEvasive

We can now obtain and install ModEvasive from Ubuntu’s software repository using the command below:

  1. sudo apt-get install -y libapache2-mod-evasive

If you get prompted for Postfix configuration, choose the appropriate response – for me it is “Satellite system” as I have a dedicated mailserver

You can always check if ModEvasive is running  and enabled by running the command below:

  1. $ sudo apachectl -M | grep evasive

You should get the below response from your system

  1. $ evasive20_module (shared)

Step 7: Configuring ModEvasive

Like most Ubuntu packages, ModEvasive has a configuration file that you can configure depending on your needs. The file is located at /etc/apache2/mods-enabled/evasive.conf.

To make changes to the file, open it with a nano editor:

  1. sudo vi /etc/apache2/mods-enabled/evasive.conf

Uncomment the entries on the file by removing the hash symbol at the beginning of each line. Then replace DOSEmailNotify with your personal email address (e.g. info@example.com).

The file should be similar to the below text when edited:

  1. <IfModule mod_evasive20.c>
  2. DOSHashTableSize 3097
  3. DOSPageCount 2
  4. DOSSiteCount 50
  5. DOSPageInterval 1
  6. DOSSiteInterval 1
  7. DOSBlockingPeriod 10
  8. DOSEmailNotify info@example.com
  9. DOSSystemCommand “su – someuser -c ‘/sbin/… %s …'”
  10. DOSLogDir “/var/log/mod_evasive”
  11. </IfModule>

Then, save the file by pressing :wq and Enter.

Step 8: Creating Log Directory for ModEvasive

On the above configuration file, we specified DOSLogDir as /var/log/mod_evasive this directory is not created by default when ModEvasive is installed. So we need to create it and set the appropriate file permissions.

  1. sudo mkdir /var/log/mod_evasive
  2. sudo chown -R www-data:www-data /var/log/mod_evasive

Step 9: Restart Apache

You can now restart Apache for the changes to take effect

  1. sudo systemctl restart apache2

Step 10: Testing ModEvasive

Once the ModEvasive configuration is in place, we can do some testing to make sure the module is working. There is a built in script that you can use to test ModEvasive on your server. Just run the command below:

  1. sudo perl /usr/share/doc/libapache2-mod-evasive/examples/test.pl

If you setup everything correctly, you should get the below output on the terminal screen:

  1. HTTP/1.1 403 Forbidden
  2. HTTP/1.1 403 Forbidden
  3. HTTP/1.1 403 Forbidden
  4. HTTP/1.1 403 Forbidden
  5. HTTP/1.1 403 Forbidden
  6. HTTP/1.1 403 Forbidden

Note: the test script didnt work for me and just gave a 400 Bad Request error!

I modified the print statement in test.pl to read:

print $SOCKET “GET /?$_ HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n”;

And then got the 403 forbidden error and also an email to report the event!

Step 11: Install mod_security

ModSecurity is a web application firewall for the Apache web server. In addition to providing logging capabilities, ModSecurity can monitor HTTP traffic in real time in order to detect attacks. ModSecurity also operates as an intrusion detection tool, allowing you to react to suspicious events that take place on your web systems.

sudo apt install -y libapache2-mod-security2

sudo systemctl restart apache2

Step 12: Enable rewrites/redirects using the mod_rewrite module

This module is used for rewrites (redirects), as the name suggests. You’ll need it if you use WordPress or any other CMS for that matter. To install it, just run:

sudo a2enmod rewrite
sudo systemctl restart apache2

Step 12: Install PHP 7.2

We can install PHP 7.2 and the Apache PHP module as follows:

sudo apt-get install -y php php-cgi libapache2-mod-php php-common php-pear php-mbstring php-gettext php-gd php-cli
sudo a2enconf php7.2-cgi

Then restart Apache:

sudo systemctl restart apache2

Create a PHP test file:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

and then navigate to:

http://SERVER_IP/info.php

Step 13: Enable the SSL website in apache

SSL/ TLS is a security layer to encrypt the connection between the web browser and your server. Most web browsers start to show sites as insecure today when the connection between the server and the web browser is not encrypted with SSL. In this chapter, I will show you how to secure your website with SSL.

Execute the following commands on your server to enable SSL (https://) support. Run:

sudo a2enmod ssl
sudo a2ensite default-ssl

which enables the SSL module and adds a symlink in the /etc/apache2/sites-enabled folder to the file /etc/apache2/sites-available/default-ssl.conf to include it into the active apache configuration. Then restart apache to enable the new configuration:

sudo systemctl restart apache2

Leave a Reply