How to Install Apache Web Server on Ubuntu Server 18.04 LTS

Post Reply
User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

How to Install Apache Web Server on Ubuntu Server 18.04 LTS

Post: # 705Post LHammonds
Tue Jul 23, 2019 8:08 am

Greetings and salutations,

I hope this thread will be helpful to those who follow in my foot steps as well as getting any advice based on what I have done / documented.

To discuss this thread, please participate here: Ubuntu Forums

High-level overview

The Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows.

This tutorial will cover how to setup an Apache web server.

This is an overview image of a highly-available web server platform.
This article covers the web server install.
Image

Tools utilized in this process
Helpful links

The list below are sources of information that was helpful in the creation of this document.
Assumptions

This documentation will need to make use of some very-specific information that will most-likely be different for each person / location. And as such, this information will be noted in this section. They will be highlighted in red throughout the document as a reminder that you should plug-in your own value rather than actually using these "place-holder" values.

Under no circumstance should you use the actual values listed below. They are place-holders for the real thing. This is just a checklist template you need to have answered before you start the install process.

Wherever you see RED in this document, you need to substitute it for you will use in your environment.
  • Internet domain: mysite.mydomain.com -> 216.70.70.70 (Public IP) -> Firewall -> 192.168.107.91 (Internal IP)
  • Ubuntu Admin ID: administrator
  • Ubuntu Admin Password: myadminpass
  • Email Server Name (remote): srv-mail
  • Email Server Internal IP (remote): 192.168.107.25
Ubuntu Server - This tutorial assumes the server was configured according to this tutorial: How to install and configure Ubuntu Server

It is also assumed the reader knows how to use the VI editor. If not, you will need to beef up your skill set or use a different editor in place of it.

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Install Apache Web Server

Post: # 706Post LHammonds
Tue Jul 23, 2019 9:17 am

Install Apache

Code: Select all

sudo apt install apache2
Install PHP for Apache with MySQL/MariaDB support

Code: Select all

sudo apt install php7.2 libapache2-mod-php7.2 php7.2-mysql
TIP: You can search available PHP packages names by typing this:

Code: Select all

apt-cache search php7.2
Large File Upload Support

If your site will allow uploading of files larger than 8 MB, you can increase this limit in PHP. The below will modify the upload limit to allow files as large as 2,048 MB to be uploaded.

Code: Select all

sudo vi /etc/php/7.2/apache2/php.ini

Code: Select all

post_max_size = 2058M
upload_max_filesize = 2048M
Reload Apache for changes to the config to take affect:

Code: Select all

sudo systemctl reload apache2
Firewall Rules

Edit the firewall script that was created during the initial setup of the server (if you followed my instructions):

Code: Select all

sudo vi /var/scripts/prod/en-firewall.sh
Add (or enable) the following:

Code: Select all

echo "Adding Web Server rules"
ufw allow proto tcp to any port 80 comment 'HTTP Service' 1>/dev/null 2>&1
ufw allow proto tcp to any port 443 comment 'HTTPS Service' 1>/dev/null 2>&1
Run the updated rules:

Code: Select all

sudo /var/scripts/prod/en-firewall.sh
PHP Modules and Information

To verify Apache, PHP and modules are installed and enabled, lets create the famous phpinfo page.

Code: Select all

sudo touch /var/www/html/phpinfo.php
sudo chown www-data:www-data /var/www/html/phpinfo.php
sudo chmod 0644 /var/www/html/phpinfo.php
sudo echo "<?php phpinfo(); ?>" >> /var/www/html/phpinfo.php
Open a browser and load up the phpinfo page: http://192.168.107.91/phpinfo.php

You should be able to scroll down and see sections for each module we wanted enabled. If you don't see a dedicated section, then that module is not installed/enabled.

When done, do not forget to remove the info file:

Code: Select all

sudo rm /var/www/html/phpinfo.php

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Virtual Host Management

Post: # 707Post LHammonds
Tue Jul 23, 2019 10:40 am

Disable the default sites

It is best to disable and not use the default sites.

Code: Select all

sudo a2dissite 000-default
sudo a2dissite default-ssl
Web Site Root Folder

Create the web site root folder and default test page:

Code: Select all

sudo mkdir -p /var/www/mysite.mydomain.com
sudo chown www-data:www-data /var/www/mysite.mydomain.com
sudo chmod 0755 /var/www/mysite.mydomain.com
sudo touch /var/www/mysite.mydomain.com/index.php
sudo chown www-data:www-data /var/www/mysite.mydomain.com/index.php
sudo chmod 0644 /var/www/mysite.mydomain.com/index.php
sudo echo "<?php phpinfo(); ?>" >> /var/www/mysite.mydomain.com/index.php
DNS Resolution

Typically, when you setup a web site, you will have a domain name and a public IP associated to it so people from anywhere on the Internet can access your server through the domain name. But if you do not have that yet and want to setup the server as if you did, you can edit the local host file of your PC to "resolve" the friendly domain name to the correct IP (at least until you get it working at the DNS level). Just be sure to undo these changes once the DNS server starts handling the name resolution.

On a Linux PC, you edit the following file:

Code: Select all

sudo vi /etc/hosts
On a Windows PC, you edit the following file:

Code: Select all

notepad C:\Windows\System32\Drivers\etc\hosts
And add an entry like this:

Code: Select all

192.168.107.91   mysite.mydomain.com
You should be able to open a Command Prompt / Terminal and ping "mysite.mydomain.com" and your local host file should translate that to your IP address such as 192.168.107.91.

Code: Select all

# ping -c3 mysite.mydomain.com
PING mysite.mydomain.com (192.168.107.91) 56(84) bytes of data.
64 bytes from mysite.mydomain.com (192.168.107.91): icmp_seq=1 ttl=64 time=0.028 ms
64 bytes from mysite.mydomain.com (192.168.107.91): icmp_seq=2 ttl=64 time=0.049 ms
64 bytes from mysite.mydomain.com (192.168.107.91): icmp_seq=3 ttl=64 time=0.053 ms

--- mysite.mydomain.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2049ms
rtt min/avg/max/mdev = 0.028/0.043/0.053/0.012 ms
Virtual Host Creation

Create the virtual host configuration file for your domain / web site:

Code: Select all

sudo touch /etc/apache2/sites-available/mysite.mydomain.com.conf
sudo chown root:root /etc/apache2/sites-available/mysite.mydomain.com.conf
sudo chmod 0644 /etc/apache2/sites-available/mysite.mydomain.com.conf
Edit the virtual host configuration file:

Code: Select all

sudo vi /etc/apache2/sites-available/mysite.mydomain.com.conf
Set these values:

Code: Select all

<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  ServerName mydomain.com
  ServerAlias mysite.mydomain.com
  DocumentRoot /var/www/mysite.mydomain.com
  ErrorLog ${APACHE_LOG_DIR}/mysite.mydomain.com-error.log
  CustomLog ${APACHE_LOG_DIR}/mysite.mydomain.com-access.log combined
</VirtualHost>
Validate Virtual Host Syntax

Validate the configuration file syntax and ensure it shows "Syntax OK"

Code: Select all

sudo apache2ctl configtest
Enable Virtual Host

To enable the site we just created, run this command (specific to your configuration filename):

Code: Select all

sudo a2ensite mysite.mydomain.com
Disable Virtual Host

If you need to disable a site, run this command (specific to your configuration filename):

Code: Select all

sudo a2dissite mysite.mydomain.com
Reload Apache Configuration

Whenever changes are made to the configuration files, modules or certificates, you will need to reload Apache for it to take affect.

Code: Select all

sudo systemctl reload apache2

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Self-Signed SSL Certificate

Post: # 708Post LHammonds
Tue Jul 23, 2019 10:59 am

Create Self-Signed SSL Certificate

NOTE: This section is only here for historical reference. For production SSL use, see the Let's Encrypt section for SSL certificates from a source web browsers trust.

This will create a self-signed certificate that will expire 1,095 days (3 years) from the date it was created. Web browsers will complain about it being untrusted. It will still work but end-users will have to allow this exception (unless it is on a LAN and you can add the site to all computers trusted sites via group policy)

Code: Select all

a2enmod ssl
a2enmod rewrite
a2enmod headers
mkdir -p /etc/apache2/ssl/certs
mkdir -p /etc/apache2/ssl/private
openssl req -x509 -nodes -days 1095 -newkey rsa:2048 -keyout /etc/apache2/ssl/private/mysite.mydomain.com.key -out /etc/apache2/ssl/certs/mysite.mydomain.com.crt
  Country Name: US
  State: MyState
  Locality Name: MyCity
  Organication Name: MyCompany
  Organizational Unit Name: MyDepartment
  Common Name: mysite.mydomain.com
  Email Address: webmaster@mydomain.com
Ensure correct file ownership/permissions:

Code: Select all

chown root:root /etc/apache2/ssl/private/mysite.mydomain.com.key
chown root:root /etc/apache2/ssl/certs/mysite.mydomain.com.crt
chmod 600 /etc/apache2/ssl/private/mysite.mydomain.com.key
chmod 600 /etc/apache2/ssl/certs/mysite.mydomain.com.crt
To verify the certificate:

Code: Select all

openssl x509 -in /etc/apache2/ssl/certs/mysite.mydomain.com.crt -text -noout
To verify the private key:

Code: Select all

openssl rsa -in /etc/apache2/ssl/private/mysite.mydomain.com.key -check
Create the virtual host SSL configuration file:

Code: Select all

sudo touch /etc/apache2/sites-available/mysite.mydomain.com-ssl.conf
sudo chown root:root /etc/apache2/sites-available/mysite.mydomain.com-ssl.conf
sudo chmod 0644 /etc/apache2/sites-available/mysite.mydomain.com-ssl.conf
Edit the configuration file:

Code: Select all

sudo vi /etc/apache2/sites-available/mysite.mydomain.com-ssl.conf
Set these values:

Code: Select all

<IfModule mod_ssl.c>
  <VirtualHost _default_:443>
    ServerName mysite.mydomain.com
    ServerAlias mysite.mydomain.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/mysite.mydomain.com
    ErrorLog ${APACHE_LOG_DIR}/mysite.mydomain.com-error.log
    CustomLog ${APACHE_LOG_DIR}/mysite.mydomain.com-access.log combined
    SSLEngine on
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
      SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
      SSLOptions +StdEnvVars
    </Directory>
    <IfModule mod_headers.c>
      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
    </IfModule>
    BrowserMatch "MSIE [2-6]" \
      nokeepalive ssl-unclean-shutdown \
      downgrade-1.0 force-response-1.0
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    SSLCertificateFile /etc/apache2/ssl/certs/mysite.mydomain.com.crt
    SSLCertificateKeyFile /etc/apache2/ssl/private/mysite.mydomain.com.key
  </VirtualHost>
</IfModule>
Validate the configuration file syntax and ensure it shows "Syntax OK"

Code: Select all

apache2ctl configtest
Enable the site configuration:

Code: Select all

sudo a2ensite mysite.mydomain.com-ssl
Reload the Apache config so it is aware of the modified virtual host

Code: Select all

sudo systemctl reload apache2
Test the web page by visiting https://mysite.mydomain.com/index.php and make sure the page displays and shows the SSL certificate is active.

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Let's Encrypt SSL Certificate

Post: # 709Post LHammonds
Tue Jul 23, 2019 11:08 am

Let's Encrypt SSL Certificate

Let's Encrypt is a non-profit certificate authority run by Internet Security Research Group that provides X.509 certificates for Transport Layer Security encryption at no charge. The certificate is valid for 90 days, during which renewal can take place at any time.

This section will describe how to obtain a certificate and automate the renewal process.

Prerequisites
  • A registered domain name such as mydomain.com
  • Two Host A records on your authoritative DNS server for your domain such as:

    Code: Select all

    Type A, mydomain.com, 216.70.70.70
    Type A, mysite.mydomain.com, 216.70.70.70
  • Web server (such as Apache)
  • A Virtual Host configuration file
Install Certbot

The Ubuntu package repository has Certbot available but tends to be several versions behind what is available by the Cerbot developers. We can get the latest stable version of Certbot by adding the developers package repository.

Code: Select all

sudo add-apt-repository ppa:certbot/certbot
sudo apt update
sudo apt install python-certbot-apache
LetsEncrypt Permission Fix

While testing version 0.31.0, I found that I kept getting a "client lacks sufficient authorization" error message. The problem is that during the authorization phase, it re-directs the Virtual Host configuration to /var/lib/letsencrypt/http_challenges but the parent folder of /var/lib/letsencrypt has too restrictive of permissions set. The owner is set to root:root and permissions of 700 which means the web service (www-data) cannot view anything under that directory. The solution is to fix the permission on that folder so "other" users (www-data) can see the contents. NOTE: This folder only exists once you try to obtain your 1st SSL certification in the next section below.

Code: Select all

chmod 755 /var/lib/letsencrypt
Obtain the SSL Certificate

Code: Select all

sudo certbot --apache -d mydomain.com -d mysite.mydomain.com
We use -d to specify each name we would like the certificate to be valid for.

Upon the first time creating the certificate, you will be prompted for various information.

Once the information gathering is complete, Certbot will ask how to configure the HTTPS settings such as not forcing a redirect of HTTP to HTTPS or letting it add a redirect to force all HTTP traffic to HTTPS.

You can answer however you like but I like to do my own redirection (especially if this is already handled on a load balancer).

The new files will be placed here by default:

Code: Select all

/etc/letsencrypt/live/mydomain.com/fullchain.pem
/etc/letsencrypt/live/mydomain.com/privkey.pem
Look at the modified Virtual Host configuration file:

Code: Select all

sudo vi /etc/apache2/sites-available/mysite.mydomain.com.conf
The modified file now looks something like this:

Code: Select all

<IfModule mod_ssl.c>
  <VirtualHost _default_:443>
    ServerName mysite.mydomain.com
    ServerAlias mysite.mydomain.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/mysite.mydomain.com
    ErrorLog ${APACHE_LOG_DIR}/mysite.mydomain.com-error.log
    CustomLog ${APACHE_LOG_DIR}/mysite.mydomain.com-access.log combined
    SSLEngine on
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
      SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
      SSLOptions +StdEnvVars
    </Directory>
    <IfModule mod_headers.c>
      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
    </IfModule>
    BrowserMatch "MSIE [2-6]" \
      nokeepalive ssl-unclean-shutdown \
      downgrade-1.0 force-response-1.0
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/mysite.mydomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mysite.mydomain.com/privkey.pem
  </VirtualHost>
</IfModule>
Schedule For SSL Certificate Auto-Renew

Let's Encrypt certificates are only valid for 90 days. This encourages admins to automate their certificate renewal process.

You can force a simulated update to ensure the process will work using the dry-run option below. If you see "success" messages, then you should be OK when it comes time for the renew to run for real:

Code: Select all

sudo certbot renew --dry-run
Starting with Ubuntu 18.04 LTS, we now have a systemd timer. When enabled, it will check for renewals twice per day.

Code: Select all

sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer
Check the status with this command (which also shows when it last ran and when the next run will be):

Code: Select all

systemctl status certbot.timer
Example Output:

Code: Select all

● certbot.timer - Run certbot twice daily
   Loaded: loaded (/lib/systemd/system/certbot.timer; enabled; vendor preset: en
   Active: active (waiting) since Tue 2019-10-29 09:14:23 CDT; 6h ago
  Trigger: Tue 2019-10-29 20:05:09 CDT; 4h 20min left

Oct 29 09:14:23 srv-apache systemd[1]: Started Run certbot twice daily.
You can check the journal logs for certbot-related events:

Code: Select all

journalctl | grep certbot
Example Output:

Code: Select all

Oct 29 09:14:23 srv-apache systemd[1]: Started Run certbot twice daily.
Oct 29 09:16:47 srv-apache sudo[5618]:     root : TTY=pts/1 ; PWD=/etc/apache2/sites-available ; USER=root ; COMMAND=/usr/bin/certbot --apache -d mysite.mydomain.com
Oct 29 09:18:12 srv-apache sudo[5690]:     root : TTY=pts/1 ; PWD=/etc/apache2/sites-available ; USER=root ; COMMAND=/usr/bin/certbot --apache -d mysite.mydomain.com
Oct 29 12:00:01 srv-apache CRON[6946]: (root) CMD (test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew)

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Force SSL Usage

Post: # 710Post LHammonds
Tue Jul 23, 2019 11:22 am

Force SSL Usage

This section will describe how to modify the site configuration to ensure anyone that hits an http (port 80) URL will be automatically re-directed to the https (port 443) location...thus ensuring all traffic on the site is encrypted using SSL.

Enable the rewrite mod:

Code: Select all

sudo a2enmod rewrite
Restart Apache service for change to take affect:

Code: Select all

sudo systemctl restart apache2
Edit the non-secure Virtual Host configuration file:

Code: Select all

sudo vi /etc/apache2/sites-available/mysite.mydomain.com.conf
Add the following entries:

Code: Select all

  RewriteEngine On
  RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
Make sure the syntax is correct for the config file:

Code: Select all

sudo apache2ctl configtest
Reload the Apache configuration for changes to take affect:

Code: Select all

sudo systemctl reload apache2
Visit the non-ssl URL (http) and it should automatically swap it to the SSL URL (https).

http://mysite.mydomain.com

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Directory Security

Post: # 711Post LHammonds
Tue Jul 23, 2019 11:35 am

Directory Security

It is a good idea to have your site permission settings in a script that can be scheduled to run on a normal basis. Each site/application will need to have specific permissions set so use the following script as an example of things you can do to customize a script for your site.

Create the file and set appropriate ownership / permissions.

Code: Select all

touch /var/scripts/prod/mysite.mydomain.com-secure.sh
chown root:root /var/scripts/prod/mysite.mydomain.com-secure.sh
chmod 0755 /var/scripts/prod/mysite.mydomain.com-secure.sh
Edit the script:

Code: Select all

vi /var/scripts/prod/mysite.mydomain.com-secure.sh
Add the following to the file and make changes that match your site:

Code: Select all

#!/bin/bash
#############################################
## Name          : mysite.mydomain.com-secure.sh
## Version       : 1.1
## Date          : 2019-09-03
## Author        : LHammonds
## Compatibility : Ubuntu Server 18.04 LTS
## Requirements  : Run as root user
## Purpose       : Ensures ownership and permissions are set correctly.
## Run Frequency : Manual as needed or via crontab schedule.
################ CHANGE LOG #################
## DATE       WHO WHAT WAS CHANGED
## ---------- --- ----------------------------
## 2019-07-23 LTH Created script.
## 2019-09-03 LTH Added full path to executables.
#############################################
wwwdir='/var/www/mysite.mydomain.com'
webuser='www-data'
webgrp='www-data'
rootuser='root'

echo "Setting Ownership..."
/bin/chown -R ${webuser}:${webgrp} ${wwwdir}/
/bin/echo "Setting Folder Permissions..."
/usr/bin/find ${wwwdir}/ -type d -print0 | /usr/bin/xargs -0 /bin/chmod 0750
/bin/echo "Setting File Permissions..."
/usr/bin/find ${wwwdir}/ -type f -print0 | /usr/bin/xargs -0 /bin/chmod 0640
if [ -f ${wwwdir}/.htaccess ]; then
  /bin/chmod 0644 ${wwwdir}/.htaccess
fi
/bin/echo "Permission change complete."
Run the script and make sure there are no syntax errors:

Code: Select all

/var/scripts/prod/mysite.mydomain.com-secure.sh
Verify that file and folder permissions were set correctly:

Code: Select all

ls -l /var/www/mysite.mydomain.com
Crontab Schedule

The script can now be schedule to run automatically. The steps below will have the script run daily as the root user.

Make a backup of the root crontab schedule (this file should exist if you followed my instructions)

Code: Select all

cp /var/scripts/data/crontab.root /var/scripts/data/2019-07-23-crontab.root
Edit the root crontab schedule file:

Code: Select all

sudo vi /var/scripts/data/crontab.root
Add the following line which will schedule the script to run at 3am every day:

Code: Select all

0 3 * * * /var/scripts/prod/mysite.mydomain.com-secure.sh > /dev/null 2>&1
Replace the current root crontab schedule with the updated file:

Code: Select all

crontab -u root /var/scripts/data/crontab.root
You can verify the update by listing the current schedule:

Code: Select all

crontab -u root -l

User avatar
LHammonds
Site Admin
Site Admin
Posts: 779
Joined: Fri Jul 31, 2009 6:27 pm
Are you a filthy spam bot?: No
Location: Behind You
Contact:

Enhance Web Server Security

Post: # 712Post LHammonds
Wed Jul 24, 2019 10:04 am

This section covers settings that can be modified to make it a bit more secure.

ServerSignature

Turn off ServerSignature to prevent Apache from identifying itself and version number.

/etc/apache2/conf-available/security.conf

Code: Select all

ServerSignature Off
ServerTokens

Set ServerTokens to the least amount of information given.

This directive configures what you return as the Server HTTP response Header such as the the OS-Type and compiled in modules.

/etc/apache2/conf-available/security.conf

Code: Select all

ServerTokens Prod
Fail2Ban - Standard Filters

If you followed my instructions for setting up the Ubuntu Server, you should already have sshd being protected by Fail2Ban. Now we are going to add some pre-defined Apache filters.

Edit the jail configuration file:

Code: Select all

sudo vi /etc/fail2ban/jail.local
Add the following sections to the bottom:

Code: Select all

[apache-auth]
# detect password authentication failures
enabled  = true
port     = http,https
filter   = apache-auth
action   = iptables-multiport[name=auth, port="http,https"]
logpath  = %(apache_error_log)s
bantime  = 3600
maxretry = 3

[apache-noscript]
# detect potential search for exploits
enabled  = true
port     = http,https
filter   = apache-noscript
action   = iptables-multiport[name=noscript, port="http,https"]
logpath  = %(apache_error_log)s
bantime  = 3600
maxretry = 6

[apache-overflows]
# detect Apache overflow attempts
enabled  = true
port     = http,https
filter   = apache-overflows
action   = iptables-multiport[name=overflows, port="http,https"]
logpath  = %(apache_error_log)s
bantime  = 3600
maxretry = 2

[apache-badbots]
# detect spammer robots crawling email addresses
enabled  = true
port     = http,https
filter   = apache-badbots
action   = iptables-multiport[name=badbots, port="http,https"]
logpath  = %(apache_access_log)s
bantime  = 48h
maxretry = 1

[php-url-fopen]
# detect PHP remote injection attacks
enabled  = true
port     = http,https
filter   = php-url-fopen
action   = iptables-multiport[name=phpfopen, port="http,https"]
logpath  = %(apache_access_log)s
maxretry = 1
Restart the Fail2Ban service:

Code: Select all

sudo systemctl restart fail2ban
Check the status:

Code: Select all

sudo fail2ban-client status
Fail2Ban - WordPress Login

WordPress does not write login results to the web logs. However, we can make an assumption that anyone trying to access the login page multiple times in a short period of time does not know their credentials or they are trying to brute-force crack accounts. So let's create a filter that looks for anyone accessing the login page multiple time in a short timeframe.

Create a new filter:

Code: Select all

sudo touch /etc/fail2ban/filter.d/wordpress-login.conf
sudo chown root:root /etc/fail2ban/filter.d/wordpress-login.conf
sudo chmod 644 /etc/fail2ban/filter.d/wordpress-login.conf
Edit the filter file:

Code: Select all

sudo vi /etc/fail2ban/filter.d/wordpress-login.conf
Add this to the file:

Code: Select all

[Definition]
failregex = <HOST> - - .*(POST|GET) .*/wp-login.php HTTP.*
Edit the jail configuration file:

Code: Select all

sudo vi /etc/fail2ban/jail.local
Add the following sections to the bottom:

Code: Select all

[wordpress-login]
# detect multiple attempts to login
enabled  = true
port     = http,https
action   = iptables-multiport[name=wordpress, port="http,https"]
filter   = wordpress-login
logpath  = %(apache_access_log)s
bantime  = 3600
findtime = 60
maxretry = 6
Restart the Fail2Ban service:

Code: Select all

sudo systemctl restart fail2ban
Check the status:

Code: Select all

sudo fail2ban-client status

Post Reply