Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 3 · Networking and hardening · Lesson 08 · 50 minutes

Install and harden a web stack

After this lesson you can
  • Install Linux, Apache, MariaDB and PHP and check that each part runs
  • Serve one PHP page that reads from the database with a least-rights account
  • Close the common weak points of the stack with settings and permissions
Lab files of this lesson (9)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A small shop needs a page that lists its products from a database. You install the stack on a practice system, and your team lead adds: "Put it online only when it is closed. The database must not be open to the network, no default accounts, no version in the headers, no file listing, and the web folder must not be writable by everyone." You build the page first, and then you close each point and prove it with a test.

Recall

Why does a rule file for nft start with "table ..." and "delete table ..." for its own table?

It removes an old copy of that table, so that loading the file replaces it as one step. The tables of other tools stay.

Which setting stops root from logging in over SSH, and which command checks the file before a reload?

PermitRootLogin no, and sudo sshd -t.

The idea

A web stack is the set of programs that serve a dynamic page. LAMP stands for Linux, Apache, MariaDB (or MySQL) and PHP. Apache hands a .php file to the PHP module, which runs it. The script asks MariaDB for data and writes the page.

A request through the stack
BrowserApachePHPMariaDBGET /products.phprun the scriptSELECT name, pricethree rowsthe page text200 OK and the pageBrowserApachePHPMariaDB123456
  1. Browser → Apache: GET /products.php
  2. Apache → PHP: run the script
  3. PHP → MariaDB: SELECT name, price
  4. MariaDB → PHP: three rows
  5. PHP → Apache: the page text
  6. Apache → Browser: 200 OK and the page

Each part has its own weak points, and you close them one by one:

PartWeak pointFix
MariaDBListens on the networkbind-address = 127.0.0.1
MariaDBAnonymous or test accountsRemove them
MariaDBThe web account can do too muchGrant only the rights that the page needs
ApacheShows its version in headers and error pagesServerTokens Prod, ServerSignature Off
ApacheLists the files of a folder with no index pageOptions -Indexes
FilesAnyone can write, or read secretsOwner root, group www-data, mode 750 and 640
The shop server after the fixes
NetworkShop serverOffice clientApacheMariaDB12NetworkShop serverOffice clientApacheMariaDB12
  1. Office client → Apache: GET /products.php: 200 OK
  2. Apache → MariaDB: kr_web may only SELECT

The firewall of lesson 3 is the next layer: it would let only the office reach port 80. This lesson closes the stack itself.

The package names differ by family. They were not tested, because the build machine runs Ubuntu only.

FamilyPackagesService namesWeb folder
Ubuntuapache2 mariadb-server php libapache2-mod-php php-mysqlapache2, mariadb/var/www/html
CentOS and RHELhttpd mariadb-server php php-mysqlndhttpd, mariadb/var/www/html
Archapache mariadb php php-apachehttpd, mariadb/srv/http

Worked example

All commands run with sudo. The password in the page is a lab password.

1. Install the stack and check each part

apt install -y installs without asking. Then ask each part: the service state with systemctl is-active, the version, and the web server with curl.

sudo apt install -y apache2 mariadb-server php libapache2-mod-php php-mysql
systemctl is-active apache2 mariadb
apache2 -v | head -1
mariadb --version
php -v | head -1
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1/
active
active
Server version: Apache/2.4.58 (Ubuntu)
mariadb  Ver 15.1 Distrib 10.11.14-MariaDB, for debian-linux-gnu (x86_64) using  EditLine wrapper
PHP 8.3.6 (cli) (built: Nov 18 2026 23:42:07) (NTS)
200

Your versions can differ. 200 is the default Apache page. Apache listens on port 80 on every address, and MariaDB on 127.0.0.1:3306.

2. Build the database and a least-rights account

Go to the lab folder, so that the files of this lesson are saved there and not in the folder of lesson 7.

cd ~/krlab/linux-advanced

Save this SQL file as shop.sql. It makes a database, a table with three rows, and the account kr_web that may only read that one table (SELECT). The account is bound to localhost: it cannot connect from another machine.

shop.sql

CREATE DATABASE krshop;
CREATE TABLE krshop.products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(6,2));
INSERT INTO krshop.products VALUES (1,'keyboard',25.00),(2,'mouse',12.50),(3,'monitor',140.00);
CREATE USER 'kr_web'@'localhost' IDENTIFIED BY 'Lab-db-pass-1';
GRANT SELECT ON krshop.products TO 'kr_web'@'localhost';

sudo mariadb opens the database shell as the administrator, with no password, because MariaDB trusts root on the local socket. -e runs one statement.

sudo mariadb < shop.sql
sudo mariadb -e "SHOW GRANTS FOR 'kr_web'@'localhost'"
Grants for kr_web@localhost
GRANT USAGE ON *.* TO `kr_web`@`localhost` IDENTIFIED BY PASSWORD '*586AFDE8BAC45BB988163CD2DD451DED9AD5E329'
GRANT SELECT ON `krshop`.`products` TO `kr_web`@`localhost`

USAGE means "no rights". The second line is the only right:

The one right of kr_web
GRANT SELECTthe only rightON krshop.productson this one tableTO kr_web@localhostfor this account, here onlyGRANT SELECTthe only rightON krshop.productson this one tableTO kr_web@localhostfor this account, here only

Test the limit. MYSQL_PWD gives the password to mariadb for one command (in real work, never put a password on the command line, because other users can see it in the process list).

MYSQL_PWD='Lab-db-pass-1' mariadb -u kr_web krshop -e "DELETE FROM products WHERE id=1"
ERROR 1142 (42000) at line 1: DELETE command denied to user 'kr_web'@'localhost' for table `krshop`.`products`

3. Serve a PHP page that reads the database

Save this page as products.php. It connects with the least-rights account, reads the table, and prints the count and the rows.

products.php

<?php
$db = new mysqli('localhost', 'kr_web', 'Lab-db-pass-1', 'krshop');
$rows = $db->query('SELECT name, price FROM products ORDER BY id')->fetch_all(MYSQLI_ASSOC);
header('Content-Type: text/plain');
echo 'products: ' . count($rows) . "\n";
foreach ($rows as $r) { echo $r['name'] . ' ' . $r['price'] . "\n"; }
sudo cp products.php /var/www/html/products.php
curl -s -i http://127.0.0.1/products.php
HTTP/1.1 200 OK
Server: Apache/2.4.58 (Ubuntu)
Content-Type: text/plain;charset=UTF-8

products: 3
keyboard 25.00
mouse 12.50
monitor 140.00

The whole stack works. Note the Server: header: it names the software and its version. Now close the weak points.

4. Remove anonymous and test accounts

Old installations had an account with an empty name, which let anyone in, and a database test that anyone could use. A fresh MariaDB on Ubuntu has neither, so plant both, find them with a query and remove them. -N leaves out the column names.

sudo mariadb -e "CREATE USER ''@'localhost'; CREATE DATABASE test;"
sudo mariadb -e "SELECT user, host FROM mysql.user; SHOW DATABASES;"
sudo mariadb -e "DROP USER IF EXISTS ''@'localhost'; DROP DATABASE IF EXISTS test;"
sudo mariadb -N -e "SELECT COUNT(*) FROM mysql.user WHERE user=''"
User	Host
	localhost
kr_web	localhost
mariadb.sys	localhost
mysql	localhost
root	localhost
Database
information_schema
krshop
mysql
performance_schema
sys
test
0

The first row of the user list has an empty name: that is the anonymous account. The last line shows 0 after the clean-up. sudo mariadb-secure-installation asks the same questions one by one.

5. Keep the database on localhost

Save this file as 99-krlab.cnf and copy it into the configuration folder of MariaDB. A later file wins, so the number 99 is read last. Restart the database and read the listener.

99-krlab.cnf

[mysqld]
bind-address = 127.0.0.1
sudo cp 99-krlab.cnf /etc/mysql/mariadb.conf.d/99-krlab.cnf
sudo systemctl restart mariadb
ss -tln | grep 3306
LISTEN 0      80         127.0.0.1:3306      0.0.0.0:*

Ubuntu already sets this value, so the file only makes your choice explicit. 0.0.0.0 would open the database to every network.

6. Hide the version and stop file listing

First show the problem. Make a folder with a file and no index page, and ask for the folder.

sudo mkdir -p /var/www/html/files
echo "internal list" | sudo tee /var/www/html/files/list.txt > /dev/null
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1/files/
200

Apache answered with a list of the files in the folder. Save this file as zz-krlab.conf. ServerTokens Prod and ServerSignature Off cut the version from the headers and the error pages. Options -Indexes turns the file listing off. The name starts with zz because Apache reads conf-enabled in alphabetical order and the last value wins: the default security.conf sets ServerTokens OS.

zz-krlab.conf

ServerTokens Prod
ServerSignature Off
<Directory /var/www/html>
    Options -Indexes
</Directory>

a2enconf enables a configuration file from conf-available. apache2ctl configtest checks the syntax, as sshd -t did. The warning about the server name is harmless here.

sudo cp zz-krlab.conf /etc/apache2/conf-available/zz-krlab.conf
sudo a2enconf zz-krlab
sudo apache2ctl configtest
sudo systemctl reload apache2
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1/files/
curl -sI http://127.0.0.1/products.php | grep -i '^server'
Enabling conf zz-krlab.
To activate the new configuration, you need to run:
  systemctl reload apache2
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Syntax OK
403
Server: Apache

AH00558 is only a warning: the machine has no full domain name. The folder is now 403 (forbidden), and the header names no version. PHP on Ubuntu already adds no X-Powered-By header.

7. Lock the permissions of the web folder

A world-writable folder lets any local account put a file in your site. find ... -perm -o+w lists the entries that others can write. Make one such folder, and then fix the whole tree. chown -R root:www-data gives the files to root with the group that Apache runs as. The folders get 750, and the files 640: Apache can read them through the group, and nobody else can read or write.

sudo chmod 777 /var/www/html/files
sudo find /var/www/html -perm -o+w
sudo chown -R root:www-data /var/www/html
sudo find /var/www/html -type d -exec chmod 750 {} +
sudo find /var/www/html -type f -exec chmod 640 {} +
sudo find /var/www/html -perm -o+w | wc -l
ls -l /var/www/html
sudo ls -l /var/www/html
curl -s http://127.0.0.1/products.php | head -1
/var/www/html/files
0
ls: cannot open directory '/var/www/html': Permission denied
total 20
drwxr-x--- 2 root www-data  4096 Nov 21 19:27 files
-rw-r----- 1 root www-data 10671 Nov 21 19:27 index.html
-rw-r----- 1 root www-data   314 Nov 21 19:27 products.php
products: 3

The page still works. Your own account can no longer even list the folder, so you need sudo, and no normal user can read products.php, which holds the database password. Apache does not own the files, so an attack that makes Apache write can write nowhere in the site.

Your turn

Add a second page for the shop. There are no steps here: use the worked example. In the lab folder, save this file as orders.sql. It builds the data, and it also plants one weak account that you must find. It is not the task.

orders.sql

CREATE TABLE krshop.orders (id INT PRIMARY KEY, item VARCHAR(40), qty INT);
INSERT INTO krshop.orders VALUES (1,'keyboard',2),(2,'mouse',5),(3,'monitor',1),(4,'cable',9),(5,'lamp',3);
CREATE USER ''@'localhost';
  1. Load the file into MariaDB.
  2. Make the account kr_report (password of your choice) with SELECT on krshop.orders and nothing else.
  3. Write report.php, in the same way as products.php, that prints orders: and the number of rows, then one line for each order. Put it in /var/www/html and give it the owner and mode of the other files.
  4. Remove the weak account.

Last, keep the stack off the network when you do not use it. Lesson 10 and the scenario test need no running web server (the scenario script starts the services again). When you have finished the course, remove the practice data, the accounts with lab passwords and the two PHP pages, which hold lab passwords, and stop the services last, because the first command needs MariaDB. Apache listens on port 80 on every address until you stop it.

sudo mariadb -e "DROP DATABASE krshop; DROP USER 'kr_web'@'localhost'; DROP USER 'kr_report'@'localhost'"
sudo rm /var/www/html/products.php /var/www/html/report.php
sudo systemctl disable --now apache2 mariadb

Check yourself

Why is a database that listens on 127.0.0.1 safer than one on 0.0.0.0?

Only programs on the same machine can connect to 127.0.0.1. A listener on 0.0.0.0 accepts connections from every network that reaches the machine, so every password guess and every flaw in the database is exposed.

The page needs only to read one table. Why not give the account all rights, to make it easier?

A flaw in the page, such as an SQL injection, lets an attacker run statements as that account. With SELECT on one table, the damage is limited to reading that table. With all rights, the attacker can change or drop data, and can read the other databases.

Hiding the Apache version is "security through obscurity". Is it useless?

It does not fix a flaw. It does take away a free hint for a scanner that looks for one exact version. Do it, and also keep the software updated.

Why do the web files belong to root and not to www-data?

Apache runs as www-data. If an attack takes control of Apache, it can then not change the site's own files. Give write rights only to the one folder that the application must write, such as an upload folder, and never run files from it.

Field notes

  • Keep the database password out of the web folder: read it from a file above the web root, or from the environment of the service.
  • The page used a fixed query. When a query takes input from the visitor, use prepared statements ($db->prepare()) so that the input is never part of the SQL. This is the main defence against SQL injection (OWASP Top 10, injection).
  • Turn on TLS before the site goes online: sudo a2enmod ssl and a certificate (the course "Networking hands-on" explains certificates). Redirect port 80 to 443, and add port 443 to the firewall.
  • Read /var/log/apache2/error.log and access.log. A request for /phpmyadmin or /wp-login.php on a site that has neither is a scanner.
  • The CIS Benchmarks for Apache and for MariaDB list the same points and many more.