Mastering Linux Security and Hardening - Donald A. Tevault - E-Book

Mastering Linux Security and Hardening E-Book

Donald A. Tevault

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The third edition of Mastering Linux Security and Hardening is an updated, comprehensive introduction to implementing the latest Linux security measures, using the latest versions of Ubuntu and AlmaLinux.

In this new edition, you will learn how to set up a practice lab, create user accounts with appropriate privilege levels, protect sensitive data with permissions settings and encryption, and configure a firewall with the newest firewall technologies. You’ll also explore how to use sudo to set up administrative accounts with only the privileges required to do a specific job, and you’ll get a peek at the new sudo features that have been added over the past couple of years. You’ll also see updated information on how to set up a local certificate authority for both Ubuntu and AlmaLinux, as well as how to automate system auditing. Other important skills that you’ll learn include how to automatically harden systems with OpenSCAP, audit systems with auditd, harden the Linux kernel configuration, protect your systems from malware, and perform vulnerability scans of your systems. As a bonus, you’ll see how to use Security Onion to set up an Intrusion Detection System.

By the end of this new edition, you will confidently be able to set up a Linux server that will be secure and harder for malicious actors to compromise.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 864

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Linux Security and Hardening

Third Edition

A practical guide to protecting your Linux system from cyber attacks

Donald A. Tevault

BIRMINGHAM—MUMBAI

Mastering Linux Security and Hardening

Third Edition Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Aaron Tanna

Acquisition Editor – Peer Reviews: Gaurav Gavas

Project Editor: Rianna Rodrigues

Content Development Editor: Liam Draper

Copy Editor: Safis Editing

Technical Editor: Karan Sonawane

Proofreader: Safis Editing

Indexer: Manju Arasan

Presentation Designer: Ganesh Bhadwalkar

Developer Relations Marketing Executive: Meghal Patel

First published: January 2018

Second edition: February 2020

Third edition: February 2023

Production reference: 1210223

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-83763-051-6

www.packt.com

Contributors

About the author

Donald A. Tevault – you can call him Donnie – got involved with Linux way back in 2006 and has been working with it ever since. He holds the Linux Professional Institute Level 3 Security certification and the GIAC Incident Handler certification. Donnie is a professional Linux trainer, and thanks to the magic of the Internet, has taught Linux classes all over the world from the comfort of his living room. He has also been a Linux security researcher for an IoT security company.

I’d like to thank the good folk at Packt Publishing for making the publishing of this book such a smooth process. I’d also like to thank my cats for graciously allowing me to use their names in the demos, and Mike, my intrepid technical reviewer, for his suggestions that made the book better than it would have been.

About the reviewer

Michael Ernstoff is a Unix and Linux infrastructure and security specialist with over 25 years of experience. An independent consultant for over 20 years, Michael has worked for many well-known blue-chip companies, mainly in the banking and finance industries.

With extensive knowledge of host-based security, security hardening, and identity and access management. Michael has developed and implemented solutions for Security and Regulatory Compliance.

He is a keen amateur musician and has four children.

Join our book community

Join our community’s Discord space for discussions with the author and other readers:

https://packt.link/CyberSec

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Section 1: Setting up a Secure Linux System

Running Linux in a Virtual Environment

Looking at the threat landscape

Why do security breaches happen?

Keeping up with security news

Differences between physical, virtual, and cloud setups

Introducing VirtualBox and Cygwin

Installing a virtual machine in VirtualBox

Installing the EPEL repository on the CentOS 7 virtual machine

Installing the EPEL repository on the AlmaLinux 8/9 virtual machines

Configuring a network for VirtualBox virtual machines

Creating a virtual machine snapshot with VirtualBox

Using Cygwin to connect to your virtual machines

Installing Cygwin on your Windows host

Using the Windows 10 SSH client to interface with Linux virtual machines

Using the Windows 11 SSH client to interface with Linux virtual machines

Cygwin versus the Windows shell

Keeping the Linux systems updated

Updating Debian-based systems

Configuring auto updates for Ubuntu

Updating Red Hat 7-based systems

Updating Red Hat 8/9-based systems

Managing updates in an enterprise

Summary

Questions

Further reading

Answers

Securing Administrative User Accounts

The dangers of logging in as the root user

The advantages of using sudo

Setting up sudo privileges for full administrative users

Adding users to a predefined admin group

Creating an entry in the sudo policy file

Setting up sudo for users with only certain delegated privileges

Hands-on lab for assigning limited sudo privileges

Advanced tips and tricks for using sudo

The sudo timer

View your sudo privileges

Hands-on lab for disabling the sudo timer

Preventing users from having root shell access

Preventing users from using shell escapes

Preventing users from using other dangerous programs

Limiting the user’s actions with commands

Letting users run as other users

Preventing abuse via a user’s shell scripts

Detecting and deleting default user accounts

New sudo features

Special sudo considerations for SUSE and OpenSUSE

Summary

Questions

Further reading

Answers

Securing Normal User Accounts

Locking down users’ home directories the Red Hat way

Locking down users’ home directories the Debian/Ubuntu way

useradd on Debian/Ubuntu

adduser on Debian/Ubuntu

Hands-on lab for creating an encrypted home directory with adduser

Enforcing strong password criteria

Installing and configuring pwquality

Hands-on lab for setting password complexity criteria

Setting and enforcing password and account expiration

Configuring default expiry data for useradd for Red Hat-type systems only

Setting expiry data on a per-account basis with useradd and usermod

Setting expiry data on a per-account basis with chage

Hands-on lab for setting account and password expiry data

Preventing brute-force password attacks

Configuring the pam_tally2 PAM module on CentOS 7

Hands-on lab for configuring pam_tally2 on CentOS 7

Configuring pam_faillock on AlmaLinux 8/9

Hands-on lab for configuring pam_faillock on AlmaLinux 8 or AlmaLinux 9

Configuring pam_faillock on Ubuntu 20.04 and Ubuntu 22.04

Hands-on lab for configuring pam_faillock on Ubuntu 20.04 and Ubuntu 22.04

Locking user accounts

Using usermod to lock a user account

Using passwd to lock user accounts

Locking the root user account

Setting up security banners

Using the motd file

Using the issue file

Using the issue.net file

Detecting compromised passwords

Hands-on lab for detecting compromised passwords

Understanding centralized user management

Microsoft Active Directory

Samba on Linux

FreeIPA/Identity Management on RHEL-type distros

Summary

Questions

Further reading

Answers

Securing Your Server with a Firewall – Part 1

Technical requirements

An overview of the Linux firewall

An overview of iptables

Mastering the basics of iptables

Blocking ICMP with iptables

Blocking everything that isn’t allowed with iptables

Hands-on lab for basic iptables usage

Blocking invalid packets with iptables

Restoring the deleted rules

Hands-on lab for blocking invalid IPv4 packets

Protecting IPv6

Hands-on lab for ip6tables

nftables – a more universal type of firewall system

Learning about nftables tables and chains

Getting started with nftables

Configuring nftables on Ubuntu

Using nft commands

Hands-on lab for nftables on Ubuntu

Summary

Questions

Further reading

Answers

Securing Your Server with a Firewall — Part 2

Technical requirements

The Uncomplicated Firewall for Ubuntu systems

Configuring ufw

Working with the ufw configuration files

Hands-on lab for basic ufw usage

firewalld for Red Hat systems

Verifying the status of firewalld

Working with firewalld zones

Adding services to a firewalld zone

Adding ports to a firewalld zone

Blocking ICMP

Using panic mode

Logging dropped packets

Using firewalld rich language rules

Looking at iptables rules in RHEL/CentOS 7 firewalld

Creating direct rules in RHEL/CentOS 7 firewalld

Looking at nftables rules in RHEL/AlmaLinux 8 and 9 firewalld

Creating direct rules in RHEL/AlmaLinux firewalld

Hands-on lab for firewalld commands

Summary

Questions

Further reading

Answers

Encryption Technologies

GNU Privacy Guard (GPG)

Hands-on lab – creating your GPG keys

Hands-on lab – symmetrically encrypting your own files

Hands-on lab – encrypting files with public keys

Hands-on lab – signing a file without encryption

Encrypting partitions with Linux Unified Key Setup (LUKS)

Disk encryption during operating system installation

Hands-on lab – adding an encrypted partition with LUKS

Configuring the LUKS partition to mount automatically

Hands-on lab – configuring the LUKS partition to mount automatically

Encrypting directories with eCryptfs

Hands-on lab – encrypting a home directory for a new user account

Creating a private directory within an existing home directory

Hands-on lab – encrypting other directories with eCryptfs

Encrypting the swap partition with eCryptfs

Using VeraCrypt for cross-platform sharing of encrypted containers

Hands-on lab – getting and installing VeraCrypt

Hands-on lab – creating and mounting a VeraCrypt volume in console mode

Using VeraCrypt in GUI mode

OpenSSL and the Public Key Infrastructure

Commercial certificate authorities

Creating keys, certificate signing requests, and certificates

Creating a self-signed certificate with an RSA key

Creating a self-signed certificate with an Elliptic Curve key

Creating an RSA key and a Certificate Signing Request

Creating an EC key and a CSR

Creating an on-premises CA

Hands-on lab – setting up a Dogtag CA

Adding a CA to an operating system

Hands-on lab – exporting and importing the Dogtag CA certificate

Importing the CA into Windows

OpenSSL and the Apache webserver

Hardening Apache SSL/TLS on Ubuntu

Hardening Apache SSL/TLS on RHEL 9/AlmaLinux 9

Setting FIPS mode on RHEL 9/AlmaLinux 9

Hardening Apache SSL/TLS on RHEL 7/CentOS 7

Setting up mutual authentication

Introducing quantum-resistant encryption algorithms

Summary

Questions

Further reading

Answers

SSH Hardening

Ensuring that SSH protocol 1 is disabled

Creating and managing keys for passwordless logins

Creating a user’s SSH key set

Transferring the public key to the remote server

Hands-on lab – creating and transferring SSH keys

Disabling root user login

Disabling username/password logins

Hands-on lab – Disabling root login and password authentication

Enabling two-factor authentication

Hands-on lab — Setting up two-factor authentication on Ubuntu 22.04

Hands-on lab – Using Google Authenticator with key exchange on Ubuntu

Hands-on lab — Setting up two-factor authentication on AlmaLinux 8

Hand-on lab — Using Google Authenticator with key exchange on AlmaLinux 8

Configuring Secure Shell with strong encryption algorithms

Understanding SSH encryption algorithms

Scanning for enabled SSH algorithms

Hands-on lab – Scanning with Nmap

Disabling weak SSH encryption algorithms

Hands-on lab – disabling weak SSH encryption algorithms – Ubuntu 22.04

Hands-on lab – disabling weak SSH encryption algorithms – CentOS 7

Setting system-wide encryption policies on RHEL 8/9 and AlmaLinux 8/9

Hands-on lab – setting encryption policies on AlmaLinux 9

Configuring more detailed logging

Hands-on lab – configuring more verbose SSH logging

Configuring access control with whitelists and TCP Wrappers

Configuring whitelists within sshd_config

Hands-on lab – configuring whitelists within sshd_config

Configuring whitelists with TCP Wrappers

Configuring automatic logouts and security banners

Configuring automatic logout for both local and remote users

Configuring automatic logout in sshd_config

Creating a pre-login security banner

Configuring other miscellaneous security settings

Disabling X11 forwarding

Disabling SSH tunneling

Changing the default SSH port

Managing SSH keys

Setting different configurations for different users and groups

Creating different configurations for different hosts

Setting up a chroot environment for SFTP users

Creating a group and configuring the sshd_config file

Hands-on lab – Setting up a chroot directory for the sftpusers group

Sharing a directory with SSHFS

Hands-on lab – Sharing a directory with SSHFS

Remotely connecting from Windows desktops

Summary

Questions

Further reading

Answers

Section 2: Mastering File and Directory Access Control (DAC)

Mastering Discretionary Access Control

Using chown to change ownership of files and directories

Using chmod to set permissions on files and directories

Setting permissions with the symbolic method

Setting permissions with the numerical method

Using SUID and SGID on regular files

The security implications of the SUID and SGID permissions

Finding spurious SUID or SGID files

Preventing SUID and SGID usage on a partition

Using extended file attributes to protect sensitive files

Setting the a attribute

Setting the i attribute

Securing system configuration files

Summary

Questions

Further reading

Answers

Access Control Lists and Shared Directory Management

Creating an ACL for either a user or a group

Creating an inherited ACL for a directory

Removing a specific permission by using an ACL mask

Using the tar --acls option to prevent the loss of ACLs during a backup

Creating a user group and adding members to it

Adding members as we create their user accounts

Using usermod to add an existing user to a group

Adding users to a group by editing the /etc/group file

Creating a shared directory

Setting the SGID bit and the sticky bit on the shared directory

Using ACLs to access files in the shared directory

Setting the permissions and creating the ACL

Hands-on lab – creating a shared group directory

Summary

Questions

Further reading

Answers

Section 3: Advanced System Hardening Techniques

Implementing Mandatory Access Control with SELinux and AppArmor

How SELinux can benefit a systems administrator

Setting security contexts for files and directories

Installing the SELinux tools

Creating web content files with SELinux enabled

Fixing an incorrect SELinux context

Using chcon

Using restorecon

Using semanage

Hands-on lab – SELinux type enforcement

Troubleshooting with setroubleshoot

Viewing setroubleshoot messages

Using the graphical setroubleshoot utility

Troubleshooting in permissive mode

Working with SELinux policies

Viewing Booleans

Configuring the Booleans

Protecting your web server

Protecting network ports

Creating custom policy modules

Hands-on lab – SELinux Booleans and ports

How AppArmor can benefit a systems administrator

Looking at AppArmor profiles

Working with AppArmor command-line utilities

Troubleshooting AppArmor problems

Troubleshooting an AppArmor profile – Ubuntu 16.04

Troubleshooting an AppArmor profile – Ubuntu 18.04

Hands-on lab – Troubleshooting an AppArmor profile

Troubleshooting Samba problems in Ubuntu 22.04

Exploiting a system with an evil Docker container

Hands-on lab – Creating an evil Docker container

Summary

Questions

Further reading

Answers

Kernel Hardening and Process Isolation

Understanding the /proc filesystem

Looking at user-mode processes

Looking at kernel information

Setting kernel parameters with sysctl

Configuring the sysctl.conf file

Configuring sysctl.conf – Ubuntu

Configuring sysctl.conf – CentOS and AlmaLinux

Setting additional kernel-hardening parameters

Hands-on lab – scanning kernel parameters with Lynis

Preventing users from seeing each others’ processes

Understanding process isolation

Understanding Control Groups (cgroups)

Understanding namespace isolation

Understanding kernel capabilities

Hands-on lab – setting a kernel capability

Understanding SECCOMP and system calls

Using process isolation with Docker containers

Sandboxing with Firejail

Hands-on lab – using Firejail

Sandboxing with Snappy

Sandboxing with Flatpak

Summary

Questions

Further reading

Answers

Scanning, Auditing, and Hardening

Installing and updating ClamAV and maldet

Hands-on lab – installing ClamAV and maldet

Hands-on lab – configuring maldet

Updating ClamAV and maldet

Scanning with ClamAV and maldet

SELinux considerations

Scanning for rootkits with Rootkit Hunter

Hands-on lab – installing and updating Rootkit Hunter

Scanning for rootkits

Performing a quick malware analysis with strings and VirusTotal

Analyze a file with strings

Scanning the malware with VirusTotal

Understanding the auditd daemon

Creating audit rules

Auditing a file for changes

Auditing a directory

Auditing system calls

Using ausearch and aureport

Searching for file change alerts

Searching for directory access rule violations

Searching for system call rule violations

Generating authentication reports

Using pre-defined rulesets

Hands-on lab – using auditd

Hands-on lab –Using pre-configured rules with auditd

Auditing files and directories with inotifywait

Applying OpenSCAP policies with oscap

Installing OpenSCAP

Viewing the profile files

Getting the missing profiles for Ubuntu

Scanning the system

Remediating the system

Using SCAP Workbench

Choosing an OpenSCAP profile

Applying an OpenSCAP profile during system installation

Summary

Questions

Further reading

Answers

Logging and Log Security

Understanding the Linux system log files

The system log and the authentication log

The utmp, wtmp, btmp, and lastlog files

Understanding rsyslog

Understanding rsyslog logging rules

Understanding journald

Making things easier with Logwatch

Hands-on lab – installing Logwatch

Setting up a remote log server

Hands-on lab – setting up a basic log server

Creating an encrypted connection to the log server

Creating a stunnel connection on AlmaLinux 9 – server side

Creating a stunnel connection on AlmaLinux – client side

Creating a stunnel connection on Ubuntu – server side

Creating a stunnel connection on Ubuntu – client side

Separating client messages into their own files

Maintaining Logs in Large Enterprises

Summary

Questions

Further reading

Answers

Vulnerability Scanning and Intrusion Detection

Introduction to Snort and Security Onion

Obtaining and installing Snort

Hands-on lab – installing Snort via a Docker container

Using Security Onion

IPFire and its built-in Intrusion Prevention System (IPS)

Hands-on lab – Creating an IPFire virtual machine

Scanning and hardening with Lynis

Installing Lynis on Red Hat/CentOS

Installing Lynis on Ubuntu

Scanning with Lynis

Finding vulnerabilities with the Greenbone Security Assistant

Web server scanning with Nikto

Nikto in Kali Linux

Hands-on lab–Installing Nikto from Github

Scanning a web server with Nikto

Summary

Questions

Further reading

Answers

Prevent Unwanted Programs from Running

Mount Partitions with the no options

Understanding fapolicyd

Understanding the fapolicyd rules

Installing fapolicyd

Summary

Further reading

Questions

Answers

Security Tips and Tricks for the Busy Bee

Technical requirements

Auditing system services

Auditing system services with systemctl

Auditing network services with netstat

Hands-on lab – viewing network services with netstat

Auditing network services with Nmap

Port states

Scan types

Hands-on lab – scanning with Nmap

Password-protecting the GRUB2 bootloader

Hands-on lab – resetting the password for Red Hat/CentOS/AlmaLinux

Hands-on lab – resetting the password for Ubuntu

Preventing kernel parameter edits on Red Hat/CentOS/AlmaLinux

Preventing kernel parameter edits or recovery mode access on Ubuntu

Disabling the submenu for Ubuntu

Securely configuring BIOS/UEFI

Using a security checklist for system setup

Summary

Questions

Further reading

Answers

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Preface

Who this book is for

This book is aimed at Linux administrators in general, whether or not they specialize in Linux security. The techniques that we present can be used on either Linux servers or on Linux workstations.

We assume that our target audience has had some hands-on experience with the Linux command line and has basic knowledge of the Linux essentials.

What this book covers

Chapter 1, Running Linux in a Virtual Environment, gives an overview of the IT security landscape, and will inform the reader why learning Linux security would be a good career move. We’ll also show how to set up a virtual lab environment for the hands-on labs.

Chapter 2, Securing Administrative User Accounts, covers the dangers of always using the root user account, and introduces the benefits of using sudo instead.

Chapter 3, Securing Normal User Accounts, covers how to lock down normal user accounts, and ensure that the users use good-quality passwords.

Chapter 4, Securing Your Server with a Firewall – Part 1, involves working with the various types of firewall utilities.

Chapter 5, Securing Your Server with a Firewall – Part 2, continues the discussion about working with the various types of firewall utilities.

Chapter 6, Encryption Technologies, makes sure that important information—both at rest and in transit—are safeguarded with proper encryption.

Chapter 7, SSH Hardening, covers how to safeguard data in transit. The default Secure Shell configuration is anything but secure, and could lead to a security breach if left as is. This chapter shows how to fix that.

Chapter 8, Mastering Discretionary Access Control, covers how to set ownership and permissions on files and directories. We’ll also cover what SUID and SGID can do for us, and the security implications of using them. We’ll wrap things up by covering extended file attributes.

Chapter 9, Access Control Lists and Shared Directory Management, explains that normal Linux file and directory permissions settings aren’t very granular. With Access Control Lists, we can allow only a certain person to access a file, or we can allow multiple people to access a file with different permissions for each person. We’re also going to put what we’ve learned together in order to manage a shared directory for a group.

Chapter 10, Implementing Mandatory Access Control with SELinux and AppArmor, talks about SELinux, which is a Mandatory Access Control technology that is included with Red Hat-type Linux distributions. We’ll give a brief introduction here on how to use SELinux to prevent intruders from compromising a system. We’ll also give a brief introduction to AppArmor, which is another Mandatory Access Control technology that is included with Ubuntu and SUSE-type Linux distributions.

Chapter 11, Kernel Hardening and Process Isolation, covers how to tweak the Linux kernel to make it even more secure against certain types of attacks. It also covers some process isolation techniques to help prevent attackers from exploiting a Linux system.

Chapter 12, Scanning, Auditing, and Hardening, talks about how viruses that are a big problem for Windows users aren’t yet a huge problem for Linux users. If your organization has Windows clients that access Linux file servers, then this section is for you. You can use auditd to audit accesses to files, directories, or system calls on a Linux system. It won’t prevent security breaches, but it will let you know if some unauthorized person is trying to access a sensitive resource. SCAP, the Security Content Application Protocol, is a compliance framework that’s promulgated by the National Institute of Standards and Technology. OpenSCAP, the open source implementation, can be used to apply a hardening policy to a Linux computer.

Chapter 13, Logging and Log Security, gives you the basics about ryslog and journald, the two most prevalent logging systems that come with Linux-based operating systems. We’ll show you a cool way to make log reviews easier, and how to set up a secure central log server. We’ll do all of this just with the packages that come in your normal Linux distribution’s repositories.

Chapter 14, Vulnerability Scanning and Intrusion Detection, explains how to scan our systems to see if we’ve missed anything in our security configurations. We’ll also take a quick look at an intrusion detection system.

Chapter 15, Prevent Unwanted Programs from Running, explains how to use fapolicyd and partition mounting options to prevent untrusted programs from running on your system.

Chapter 16, Security Tips and Tricks for the Busy Bee, explains that since you’re dealing with security, we know that you’re a busy bee. This chapter introduces you to some quick tips and tricks to help make the job easier.

To get the most out of this book

A working knowledge of basic Linux commands and how to navigate through the Linux filesystem.A basic knowledge about tools such as less and grep.Familiarity with command-line editing tools, such as vim or nano.A basic knowledge of how to control systemd services with systemctl commands.

For hardware, you don’t need anything fancy. All you need is a machine that’s capable of running 64-bit virtual machines. So, you can use any host machine that runs with almost any modern CPU from either Intel or AMD. (There are a couple of exceptions, though. First, some Intel Core i3 and Core i5 CPUs lack the required hardware acceleration to run virtual machines. Also, AlmaLinux 9, which we’ll be using, won’t run on the first generation of x86_64 CPUs. So, if you have an x86_64 machine that was made prior to 2010, AlmaLinux 9 won’t run on it.) For memory, I’d recommend using a host machine with at least 8 GB.

You can run any of the three major desktop operating systems on your machine, because the virtualization software that we’ll be using comes in flavors for Windows, macOS, and Linux.

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Mastering-Linux-Security-and-Hardening-3E. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/wcaG3

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “open Firefox and navigate to https://localhost:9392"

A block of code is set as follows:

HTTP TRACK method is active, suggesting the host is vulnerable to XST Cookie wordpress_test_cookie created without the httponly flag

Any command-line input or output is written as follows:

sudo apt update sudo apt install podman

Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: “Set one to Bridged mode and leave the other in NAT mode.”

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837630516

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Share your thoughts

Once you’ve read Mastering Linux Security and Hardening, Third Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Section 1

Setting up a Secure Linux System

In this section, we will set up a practice lab with Ubuntu, CentOS, and AlmaLinux virtual machines. Windows users will learn how to remotely access Linux machines from Windows.

This section contains the following chapters:

Chapter 1, Running Linux in a Virtual Environment Chapter 2, Securing Administrative User AccountsChapter 3, Securing Normal User AccountsChapter 4, Securing Your Server with a Firewall – Part 1Chapter 5, Securing Your Server with a Firewall – Part 2Chapter 6, Encryption Technologies Chapter 7, SSH Hardening

1

Running Linux in a Virtual Environment

So, you may be asking yourself: Why do I need to study Linux security? Isn’t Linux already secure? After all, it’s not Windows. But the fact is, there are many reasons.

It’s true that Linux has certain advantages over Windows when it comes to security. These include the following:

Unlike Windows, Linux was designed from the ground up as a multiuser operating system. So, user security tends to be a bit better on a Linux system.Linux offers a better separation between administrative users and unprivileged users. This makes it a bit harder for intruders, and it also makes it a bit harder for a user to accidentally infect a Linux machine with something nasty.Linux is much more resistant to viruses and malware infections than Windows is. Certain Linux distributions come with built-in mechanisms, such as SELinux in Red Hat and its free-of-charge clones, and AppArmor in Ubuntu and SUSE, that help prevent intruders from taking control of a system.Linux is free and open source software. This allows anyone who has the skill to audit Linux code to hunt for bugs or backdoors.

But even with those advantages, Linux is just like everything else that’s been created by mankind. That is, it isn’t perfect.

Here are the topics that we’ll cover in this chapter:

Looking at the threat landscapeWhy every Linux administrator needs to learn about Linux securityA bit about the threat landscape, with some examples of how attackers have, at times, been able to breach Linux systemsResources for keeping up with IT security newsDifferences between physical, virtual, and cloud setupsSetting up Ubuntu Server and Red Hat-type virtual machines with VirtualBox, and installing the Extra Packages for Enterprise Linux (EPEL) repository in the Red Hat-type virtual machinesCreating virtual machine snapshotsInstalling Cygwin on a Windows host so that Windows users can connect to a virtual machine from their Windows hostsUsing the Windows 10/11 Bash shell to access Linux systemsHow to keep your Linux systems updated

Let’s begin by talking about threats.

Looking at the threat landscape

If you’ve kept up with IT technology news over the past few years, you’ll likely have seen at least a few articles about how attackers have compromised Linux servers. For example, while it’s true that Linux isn’t really susceptible to virus infections, there have been several cases where attackers have planted other types of malware on Linux servers. Here are some examples:

Botnet malware: This causes a server to join a botnet that is controlled by a remote attacker. One of the more famous cases involved joining Linux servers to a botnet that launched denial-of-service (DoS) attacks against other networks.Ransomware: This is designed to encrypt user data until the server owner pays a ransom fee. But even after paying the fee, there’s no guarantee that the data can be recovered.Cryptocoin mining software: This causes the CPUs of the server on which it’s planted to work extra hard and consume more energy. Cryptocoins that get mined go to the accounts of the attackers who planted the software.

And, of course, there have been plenty of breaches that don’t involve malware, such as where attackers have found a way to steal user credentials, credit card data, or other sensitive information.

Some security breaches come about because of plain carelessness. Here’s an example of where a careless Adobe administrator placed the company’s private security key on a public security blog: https://arstechnica.com/information-technology/2017/09/in-spectacular-fail-adobe-security-team-posts-private-pgp-key-on-blog/.

Now, let’s talk a bit more about security breaches.

Why do security breaches happen?

Regardless of whether you’re running Linux, Windows, or whatever else, the reasons for security breaches are usually the same. They could be security bugs in the operating system or security bugs in an application that’s running on that operating system. Often, a bug-related security breach could have been prevented had the administrators applied security updates in a timely manner.

Another big issue is poorly configured servers. A standard, out-of-the-box configuration of a Linux server is actually quite insecure and can cause a whole ton of problems. One cause of poorly configured servers is simply the lack of properly trained personnel to securely administer Linux servers. (Of course, that’s great news for the readers of this book, because—trust me—there’s no lack of well-paying IT security jobs.)

And now, in addition to Linux on servers and desktops, we have Linux on devices that are part of the Internet of Things (IoT). There have been many security problems with these devices, in large part because people just don’t know how to configure them securely.

As we journey through this book, we’ll see how to do business the right way, to make our servers as secure as possible. One thing we can do is to keep up with security-related news.

Keeping up with security news

If you’re in the IT business, even if you’re not a security administrator, you’ll want to keep up with the latest security news. In the age of the Internet, that’s easy to do.

First, there are quite a few websites that specialize in network security news. Examples include Packet Storm Security and The Hacker News. Regular tech news sites and Linux news websites, such as Ars Technica, Fudzilla, The Register, ZDNet, and LXer, also carry reports about network security breaches. And, if you’d rather watch videos than read, you’ll find plenty of good YouTube channels, such as BeginLinux Guru.

Finally, regardless of which Linux distro you’re using, be sure to keep up with the news and current documentation for your Linux distro. Distro maintainers should have a way of letting you know if a security problem crops up in their products.

Here are some links to some good security-related websites:

Packet Storm Security: https://packetstormsecurity.com/The Hacker News: https://thehackernews.com/

Here are some links to more generalized tech websites:

Ars Technica: https://arstechnica.com/Fudzilla: https://www.fudzilla.com/The Register: https://www.theregister.co.uk/ZDNet: https://www.zdnet.com/

You can check out some general Linux learning resources as well as Linux news sites:

LXer: http://lxer.com/BeginLinux Guru on YouTube: https://www.youtube.com/channel/UC88eard_2sz89an6unmlbeA

(Full disclosure: I am the world-famous BeginLinux Guru.)

One thing to always remember as you go through this book is that the only operating system you’ll ever see that’s totally 100% secure will be installed on a computer that never gets turned on.

Differences between physical, virtual, and cloud setups

So you can do the hands-on labs, I’ll introduce you to the concept of virtual machines. This is just a way of running one operating system within another operating system. So, it doesn’t matter whether you’re running Windows, macOS, or Linux on your host machine. In any case, you can run a Linux virtual machine that you can use for practice, and that you won’t have to worry about if it gets trashed.

Oracle’s VirtualBox, which is what we’ll be using, is great for what we’ll be doing. In an enterprise setting, you’ll find other forms of virtualization software that are better suited for use in data centers. In the past, server hardware could only handle doing one thing at a time, which meant that you had to have one server running DNS, another running DHCP, and so on. Nowadays, we have servers with gobs of memory, gobs of drive space, and CPUs with as many as 96 cores each. So, it’s now cheaper and more convenient to install multiple virtual machines on each server, with each virtual machine doing its own specific job. This also means that you not only have to worry about security on the physical server that hosts these virtual machines but you also need to worry about the security of each virtual machine. An added problem is that you need to ensure that the virtual machines remain properly isolated from each other, especially ones that contain sensitive data.

And then, there’s the cloud. Many different outfits provide cloud services, where a person or a company can spin up an instance of either Windows or their choice of a Linux distro. When setting up a Linux distro on a cloud service, there are things that you’ll have to do right away to enhance security. (That’s something that we’ll cover in Chapter 7, SSH Hardening.) And realize that when you set up a server on a cloud service, you’ll always have more concerns about proper security, because it will have an interface that connects to the wild and woolly Internet. (Your on-premises servers, except for ones that are meant to serve the public, are usually isolated from the Internet.)

With our introductory material out of the way, let’s get to the real meat of the matter, starting with an introduction to our virtualization software.

Introducing VirtualBox and Cygwin

Whenever I write or teach, I try very hard not to provide students with a cure for insomnia. Throughout this book, you’ll see a bit of theory whenever it’s necessary, but I mainly like to provide good, practical information. There will also be plenty of step-by-step hands-on labs and an occasional bit of humor.

The best way to do the labs is to use Linux virtual machines. Most of what we’ll do can apply to any Linux distro, but we will also do some things that are specific to either Red Hat Enterprise Linux (RHEL) or Ubuntu Linux. (RHEL is the most popular for enterprise use, while Ubuntu is the most popular for cloud deployments.) SUSE is the third big enterprise Linux distro. We won’t be doing too much with SUSE, but on occasion, I’ll point out some of its little quirks.

Red Hat is a billion-dollar company, so there’s no doubt about where they stand in the Linux market. But since Ubuntu Server is free of charge, we can’t judge its popularity strictly on the basis of its parent company’s worth. The reality is that Ubuntu Server is the most widely used Linux distribution for deploying cloud-based applications.

See here for details: http://www.zdnet.com/article/ubuntu-linux-continues-to-dominate-openstack-and-other-clouds/.

Since Red Hat is a fee-based product, we’ll substitute CentOS 7, AlmaLinux8, and AlmaLinux9, which are built from Red Hat source code and are free of charge. (We’re using all three of these distros because there are some differences between them, and all of them will be supported for quite some time to come.) CentOS and AlmaLinux offer various download images. You’ll want to download the DVD images, because they contain necessary things that are missing from the minimal images. Specifically, download these image files:

CentOS 7: CentOS-7-x86_64-DVD-2009.isoAlmaLinux 8: AlmaLinux-8-latest-x86_64-dvd.isoAlmaLinux 9: AlmaLinux-9-latest-x86_64-dvd.iso

For Ubuntu, we’ll concentrate on version 22.04, since it’s the newest Long Term Support (LTS) version. (We’ll also take an occasional look at Ubuntu 20.04, since it’s still supported and there are a few differences between it and 22.04.) A new LTS version of Ubuntu comes out in April of every even-numbered year, and non-LTS versions come out in April of every odd-numbered year and every October. For production use, you’ll mainly want to stick with the LTS versions, because the non-LTS versions can sometimes be a bit problematic.

There are several different virtualization platforms that you can use, but my own preferred choice is VirtualBox.

VirtualBox is available for Windows, Linux, and Mac hosts, and is free of charge for all of them. (It’s also available for Solaris hosts, but I doubt that many of you will be running that.) It has features that you have to pay for on other platforms, such as the ability to create snapshots of virtual machines.

Some of the labs that we’ll be doing will require you to simulate creating a connection from your host machine to a remote Linux server. If your host machine is either a Linux or a Mac machine, you’ll just be able to open the terminal and use the built-in Secure Shell (SSH) tools. If your host machine is running Windows, you’ll need to install some sort of Bash shell, such as Cygwin, or just use the Bash shell that’s built into Windows 10/11 Pro.

Installing a virtual machine in VirtualBox

For those of you who’ve never used VirtualBox, here’s a quick guide to get you going:

Download and install VirtualBox and the VirtualBox Extension Pack. You can get them from https://www.virtualbox.org/.Download the installation .iso files for Ubuntu Server 22.04, CentOS 7, AlmaLinux8, and AlmaLinux9. You can get them from https://ubuntu.com/, https://almalinux.org/, and https://www.centos.org/. Start VirtualBox and click the New icon at the top of the screen. Fill out the information where requested. Increase the virtual drive size to 20 GB, but leave everything else as the default settings, as shown here:

Figure 1.1:Create the virtual drive

Start the new virtual machine. Click on the folder icon that’s beside the Location dialog box and navigate to the directory where you stored the .iso files that you downloaded. Choose either the Ubuntu ISO file, the CentOS ISO file, or one of the AlmaLinux ISO files, as shown in the following screenshot. (If the ISO file doesn’t show up in the list, click the Add button in the top-left corner to add it.)

Figure 1.2: Choose the .iso file

Click the Start button on the dialog box to start installing the operating system. Note that for Ubuntu Server, you won’t be installing a desktop interface. For the CentOS 7 and AlmaLinux virtual machines, choose to install a Server without a graphical interface. (Later on, we’ll go through at least one exercise that will require a desktop interface for an AlmaLinux machine. You can create a virtual machine with a graphical interface at that time.)When installing Ubuntu, choose Try or Install Ubuntu Server when you get to this screen:

Figure 1.3: Installing Ubuntu

Repeat the procedure for the other Linux distros.Update the Ubuntu virtual machine with these two commands: sudo apt update sudo apt dist-upgrade Hold off on updating the CentOS and AlmaLinux virtual machines because we’ll do that in the next exercise.For Ubuntu, choose to install the OpenSSH Server on the SSH setup screen.

When installing Ubuntu, you’ll be asked to create a normal user account and password for yourself. It won’t ask you to create a root user password, but will instead automatically add you to the sudo group so that you’ll have admin privileges.

When you get to the user account creation screen of the CentOS or AlmaLinux installer, be sure to check the Make this user administrator box for your own user account, since it isn’t checked by default. It will offer you the chance to create a password for the root user, but that’s entirely optional. (In fact, I never do.)

The user account creation screen of the AlmaLinux 9 installer—which looks the same as the one on CentOS 7 and AlmaLinux 8—is shown here:

Figure 1.4: User creation for AlmaLinux

Important:

RHEL 9.1 and all of its clones were released a few months after I wrote the first draft of this chapter. You might already have noticed that there’s a bug in the 9.1 installer that wasn’t in the 9.0 installer. That is, the option to create a normal user account isn’t visible on the installer screen. I mean, it’s there, but you can’t see it and can’t scroll down to it. To bring it up, just keep hitting the Tab key until you’ve highlighted the option to create the root user password. Then, hit the Tab key once more, and then hit the Enter key. (Of course, there’s always the chance that the problem will get fixed by the time you read this.)

For Ubuntu 22.04, you’ll see just one self-explanatory screen to set up your real name, a username, and a password. The Ubuntu installer will automatically add your user account to the sudo group, which will give you full administrator privileges.

Here’s the user account creation screen for Ubuntu 22.04:

Figure 1.5: Ubuntu user creation

Now, let’s change gears and move on to CentOS 7.

Installing the EPEL repository on the CentOS 7 virtual machine

While the Ubuntu package repositories have pretty much everything that you need for this course, the CentOS and AlmaLinux package repositories are—shall we say—lacking. To have the packages that you’ll need for the CentOS and AlmaLinux hands-on labs, you’ll need to install the EPELrepository. (The EPEL project is run by the Fedora team.) When you install third-party repositories on Red Hat 7 and CentOS 7 systems, you’ll also need to install a priorities package and edit the .repo files to set the proper priorities for each repository. This will prevent packages from the third-party repository from overwriting official Red Hat and CentOS packages if they just happen to have the same name. The following steps will help you install the required packages and edit the .repo files:

The two packages that you’ll need to install EPEL are in the normal CentOS 7 repositories. To install them, just run this command: sudo yum install yum-plugin-priorities epel-release When the installation completes, navigate to the /etc/yum.repos.d directory, and open the CentOS-Base.repo file in your favorite text editor. After the last line of the base, updates, and extras sections, add the line priority=1. After the last line of the centosplus section, add the line priority=2. Save the file and close the editor. Each of the sections that you’ve edited should look something like this, except with the appropriate name and priority number: [base] name=CentOS-$releasever – Base mirrorlist=http://mirrorlist.centos.org/? release=$releasever&arch=$basearch&repo=os&infra=$infra #baseurl=http://mirror.centos.org/centos/ $releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 priority=1 Open the epel.repo file for editing. After the last line of the epel section, add the line priority=10. After the last line of each remaining section, add the line priority=11.Update the system and then create a list of the installed and available packages by running the following commands: sudo yum upgrade sudo yum list > yum_list.txt

Now, let’s move on to AlmaLinux.

Installing the EPEL repository on the AlmaLinux 8/9 virtual machines

To install the EPEL repository on AlmaLinux, all you have to do is run this command:

sudo dnf install epel-release

There’s no priorities package as there is on CentOS 7 and earlier, so we won’t have to worry about configuring the repository priorities.

When the package installation is complete, update the system and create a list of available software packages with these two commands:

sudo dnf upgrade sudo dnf list > dnf_list.txt

Next, let’s configure our network.

Configuring a network for VirtualBox virtual machines

Some of our training scenarios will require you to simulate creating a connection to a remote server. You would do this by using your host machine to connect to a virtual machine. When you first create a virtual machine on VirtualBox, the networking is set to NAT mode. In order to connect to the virtual machine from the host, you’ll need to set the virtual machine’s network adapter to Bridged Adapter mode. Here’s how you can do this:

Shut down any virtual machines that you’ve already created.On the VirtualBox Manager screen, open the Settings dialog for a virtual machine.Click the Network menu item. Change the Attached to setting from NAT to Bridged Adapter, and change the Promiscuous Mode setting to Allow All, as shown in this screenshot:

Figure 1.6: Configuring the network

Restart the virtual machine and set it to use a static IP address.

Tip

If you assign static IP addresses from the high end of your subnet range, it will be easier to prevent conflicts with low-number IP addresses that get handed out from your internet gateway.

Creating a virtual machine snapshot with VirtualBox

One of the beautiful things about working with virtual machines is that you can create a snapshot and roll back to it if you mess something up. With VirtualBox, that’s easy to do, by following these steps:

From the Machine menu of the VirtualBox Manager screen, select Tools/Snapshots.Further right on the screen, click on the Take icon to bring up the Snapshot dialog box. Either fill in the desired Snapshot Name or accept the default name. Optionally, you can create a description, as you see in this screenshot:

Figure 1.7: Taking a snapshot

After you’ve made changes to the virtual machine, you can roll back to the snapshot by shutting down the virtual machine, then highlighting the snapshot name, and clicking on the Restore button.

Using Cygwin to connect to your virtual machines

If your host machine is either a Linux or Mac machine, you’ll simply open the host’s terminal and use the tools that are already there to connect to the virtual machine. Windows 10 and Windows 11, even in the base Home Edition, now come with a Secure Shell client that’s built into both the normal Command Prompt and PowerShell, and you can use that if you desire. But if you’d prefer to use something that comes closer to the actual Linux experience, you might consider Cygwin.

Cygwin, a project of the Red Hat company, is a free open source Bash shell that’s built for Windows. It’s free of charge and easy to install.

Installing Cygwin on your Windows host

Here’s a quick how-to to get you going with Cygwin:

In your host machine’s browser, download the appropriate setup*.exe file for your version of Windows from http://www.cygwin.com/.Double-click on the setup icon to begin the installation. For the most part, just accept the defaults until you get to the package selection screen. (The one exception will be the screen where you select a download mirror.)At the top of the package selection screen, select Category from the View menu.Expand the Net category, as shown in the following screenshot:

Figure 1.8: Installing Cygwin packages

Scroll down until you see the openssh package. Under the New column, click on Skip (this causes a version number to appear in place of Skip), as you see in this screenshot:

Figure 1.9: Select the OpenSSH package

After you have selected the proper package, your screen should look like this:

Figure 1.10: After selecting the OpenSSH package

In the bottom right-hand corner, click Next. If a Resolving Dependencies screen pops up, click Next on it as well.Keep the setup file that you downloaded, because you’ll use it later to either install more software packages or to update Cygwin. (When you open Cygwin, any updated packages will show up on the Pending view on the View menu.)Once you open Cygwin from the Windows Start menu, you can resize it as you desire, and use either the Ctrl + + or Ctrl + - key combinations to resize the font.

Next, we’ll look at the Windows 10/11 Bash shell.

Using the Windows 10 SSH client to interface with Linux virtual machines

If you’re using Windows 10, you already have an SSH client built into your operating system.

So, let’s see how to do this:

To get to it, you can open the traditional Command Prompt from the Windows System menu, like so:

Figure 1.11: Windows 10 Command Prompt

Then, just type in the SSH commands the same as you would from a Mac or Linux machine, like this:

Figure 1.12: SSH remote from Windows Command Prompt

A better option is to use Windows PowerShell instead of the normal Command Prompt. Get to it as you see here:

Figure 1.13: PowerShell command prompt

As before, let’s use it to log in to my Orange Pi device, as you see here:

Figure 1.14: Remote login from PowerShell

If you have the choice, go with PowerShell instead of Command Prompt. PowerShell is a bit closer to the Linux Bash shell experience, and you’ll be much happier with it.

Using the Windows 11 SSH client to interface with Linux virtual machines

You’ll work with Windows 11 the same way, except that the menu entries for the Command Prompt and PowerShell are in different places. The Command Prompt now has its own Terminal item on the main menu, and PowerShell is now under the Windows Tools submenu. Windows 11 also has a third option, which is a built-in Ubuntu virtual machine. You’ll see an icon for that in the bottom taskbar.

Cygwin versus the Windows shell

Both Cygwin and the SSH client that’s built into Windows 10/11 have their pros and cons. In favor of Cygwin, you can install a variety of packages to customize it pretty much any way you want. Also, Cygwin stores the SSH known_hosts and keys files in the .ssh directory of the user’s home directory, which is where you’d expect to find them if you’re used to working with Linux. If you use the SSH client that’s built into Windows, you’ll have to search for these files in other locations.

In favor of the Windows 10/11 built-in SSH client, there’s the fact that it’s already there. Also, it’s much easier to use if you need to access your normal Windows folders because Cygwin traps you in its own sandboxed directory structure.

Keeping the Linux systems updated

Spend some time perusing the Common Vulnerabilities and Exposures database, and you’ll soon see why it’s so important to keep your systems updated. Yes, indeed, you’ll even find that there have been security flaws with our beloved Linux, as you can see here:

Figure 1.15: Common Vulnerabilities and Exposures

Updating a Linux system only requires one or two simple commands, and it’s generally faster and less painful than updating a Windows system.

You can find the Common Vulnerabilities and Exposures database here:

https://cve.mitre.org/

All of you conscientious, dedicated Linux administrators will definitely want to become familiar with this site.

Next, let’s look at updating the Debian-based systems, which include Ubuntu.

Updating Debian-based systems

Let’s take a look at how to update Debian-based systems:

On Debian and its many children, including Ubuntu, run two commands, as shown here: sudo apt update sudo apt dist-upgrade Occasionally, you’ll also need to remove some old packages that are no longer needed. How will you know? Easy. When you log in to the system, a message will appear on the command line. To remove these old packages, just run this command: sudo apt auto-remove

Next, we will configure auto updates for Ubuntu.

Configuring auto updates for Ubuntu

When you first install Ubuntu 22.04, automatic updates are turned on by default. To verify that, you’ll first check the status of the unattended-upgrades service, like so:

donnie@ubuntu2204-packt:~$ systemctl status unattended-upgrades ● unattended-upgrades.service - Unattended Upgrades Shutdown Loaded: loaded (/lib/systemd/system/unattended-upgrades.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2022-10-08 19:25:54 UTC; 52min ago . . . . . . donnie@ubuntu2204-packt:~$

Then, look in the /etc/apt/apt.conf.d/20auto-upgrades file. If auto-updating is enabled, you’ll see this:

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

I must confess, though, that I have mixed feelings about this. I mean, it’s nice that the security updates get installed without me having to do anything, but a lot of those updates require that the system be rebooted before they can take effect. By default, Ubuntu systems don’t automatically reboot after an update is installed. If you keep it that way, you’ll see a message about it when you log into the system. But if you prefer, you can set Ubuntu to automatically reboot after it automatically updates itself. Here’s how to do it:

Go into the /etc/apt/apt.conf.d directory and open the 50unattended-upgrades file in your favorite text editor. In the vicinity of line 67, you’ll see a line that says: //Unattended-Upgrade::Automatic-Reboot "false"; Uncomment the line by removing the leading slashes, and change false to true, like so: Unattended-Upgrade::Automatic-Reboot "true"; With this new configuration, Ubuntu will now reboot itself immediately after the automatic update process has completed. If you’d rather have the machine reboot at a specific time, scroll down to about line 103, where you’ll see this: //Unattended-Upgrade::Automatic-Reboot-Time "02:00"; Since this line is commented out with its pair of leading slashes, it currently has no effect. To have the machine reboot at 2:00 A.M., just uncomment this line. To have it reboot at, say, 10:00 P.M., uncomment the line and change the time to 22:00, like so: Unattended-Upgrade::Automatic-Reboot-Time "22:00";

Of course, there’s that old, basic precept that thou shalt not install system updates on a production system without first testing them on a test system. Any operating system vendor can occasionally supply you with problematic updates, and that has included Ubuntu. (I know what you’re saying: Preach it, Donnie.) Ubuntu’s automatic update feature is in direct opposition to that basic precept. If automatic updates have been enabled, disabling them is quite easy, if you choose to do so.

To disable automatic updates, just go into the /etc/apt/apt.conf.d directory and open the 20auto-upgrades file in your favorite text editor. Here’s what you’ll see: APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1"; Change the parameter for that second line to 0, so that the file will now look like this: APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "0";

Now, the system will still check for updates and show a message on the login screen when any are available, but it won’t automatically install them. And of course, it should go without saying that you need to check your systems on a regular basis to see if updates are available. If you do prefer to leave automatic updates enabled, be sure to either enable automatic rebooting or to log in to the system at least a couple of times a week to see if it needs to be rebooted.

If you want to see if there are any security-related updates available, but don’t want to see any non-security updates, use the unattended-upgrade command, like so: sudo unattended-upgrade --dry-run -d To manually install the security-related updates without installing non-security updates, just run: sudo unattended-upgrade -d

If you’re running some form of desktop Ubuntu on a workstation that gets shut down after every use, you can enable the automatic updates if you like, but there’s no need to enable automatic reboots.

Also, if you’re running a non-Ubuntu flavor of Debian, which would include Raspbian for the Raspberry Pi, you can give it the same functionality as Ubuntu by installing the unattended-upgrades package. Just run this command:

sudo apt install unattended-upgrades

You can also use the apt command to install only the security updates, but it would require piping the apt output into a convoluted set of text filters in order to mask the non-security updates. Using the unattended-upgrade command is much easier.

I said before that we should always test updates on a test system before we install them on a production system, and that certainly does hold true for corporate servers. But what do we do when we have a whole bunch of IoT devices that we need to keep updated, especially if these devices are all over the place out in the field and in consumer devices?