The Complete Debian Linux Guide: From Basics to Advanced System Administration

Master Debian Linux from installation to advanced server management. Learn the core principles, system administration techniques, and best practices for building secure and reliable Debian environments.

The Complete Debian Linux Guide: From Basics to Advanced System Administration
Debian Linux Guide illustration showing a professional system administrator managing Debian servers and terminals in a modern open-source environment. - Dargslan

SPONSORED

Sponsored by Dargslan Publishing — Explore our full collection of Linux and DevOps eBooks for self-learners and IT professionals at dargslan.com.


Table of Contents

  1. Introduction to Debian Linux
  2. Debian Philosophy and Principles
  3. Installation and Setup
  4. Package Management
  5. System Administration
  6. Network Configuration
  7. Security and Hardening
  8. Server Configuration
  9. Troubleshooting
  10. Advanced Topics

Introduction to Debian Linux

What is Debian?

Debian is one of the oldest, most respected, and widely-used Linux distributions in the world. First announced by Ian Murdock on August 16, 1993, Debian has become the foundation for hundreds of other Linux distributions, including the incredibly popular Ubuntu, Linux Mint, and many others. The name "Debian" is a portmanteau of the creator's first name, Ian, and his then-girlfriend (later wife) Debra's name.

Key characteristics that define Debian:

  • Community-driven: Unlike many other distributions, Debian is not backed by a single corporation. It's maintained by a global community of volunteers who dedicate their time and expertise to the project.
  • Stability-focused: Debian prioritizes stability over cutting-edge features, making it ideal for servers and production environments.
  • Free and open-source: Debian is committed to free software principles and includes only free software in its main repository.
  • Universal operating system: Debian supports more hardware architectures than any other Linux distribution.
  • Extensive package repository: With over 59,000 packages available, Debian offers one of the largest software collections in the Linux ecosystem.

Historical Overview

Understanding Debian's history helps contextualize its current position in the Linux ecosystem:

Year Milestone Significance
1993 Ian Murdock announces Debian Birth of one of the most influential Linux distributions
1996 Debian 1.1 "Buzz" released First stable release with 474 packages
1998 Debian Social Contract published Establishes community guidelines and free software commitment
2000 Debian 2.2 "Potato" released First release supporting PowerPC and ARM architectures
2005 Ubuntu launched based on Debian Extends Debian's influence to desktop users
2011 Debian 6.0 "Squeeze" released Major improvements to boot speed with dependency-based boot system
2015 Debian 8 "Jessie" released Systemd becomes default init system
2019 Debian 10 "Buster" released AppArmor enabled by default, improved UEFI support
2021 Debian 11 "Bullseye" released Kernel 5.10, improved hardware support
2023 Debian 12 "Bookworm" released Latest stable release with modern toolchains

Why Choose Debian?

For System Administrators:

  • Predictable release cycles and long-term support
  • Excellent documentation and community resources
  • Minimal security vulnerabilities due to rigorous testing
  • Consistent across different hardware platforms

For Developers:

  • Extensive package availability reduces dependency management headaches
  • Stable APIs mean fewer compatibility issues
  • Strong support for various programming languages and frameworks
  • Docker and container-friendly architecture

For Enterprise Environments:

  • No licensing costs or vendor lock-in
  • Professional support available from third-party vendors
  • Proven track record in production environments
  • Comprehensive security update process

For Home Users:

  • Free to use, modify, and distribute
  • Large community for support and troubleshooting
  • Works on older hardware with resource-efficient desktop environments
  • Privacy-focused with no telemetry or data collection

Debian Philosophy and Principles

The Debian Social Contract

The Debian Social Contract is a document that outlines Debian's commitment to the free software community. Originally published in 1997 and revised in 2004, it consists of five main points:

1. Debian will remain 100% free

Debian commits to keeping the system completely free software. The guidelines used to determine if software is "free" are provided in the Debian Free Software Guidelines (DFSG).

2. We will give back to the free software community

When Debian developers write new components or improve existing ones, they license them in a way consistent with the DFSG, ensuring contributions benefit the entire free software community.

3. We will not hide problems

Debian maintains its bug report database open and publicly accessible at all times. This transparency builds trust and allows users to make informed decisions.

4. Our priorities are our users and free software

Debian is guided by the needs of users and the free software community, not by commercial interests or proprietary software vendors.

5. Works that do not meet our free software standards

Debian acknowledges that some users require non-free software and provides separate repositories (contrib and non-free) for such software, clearly separated from the main distribution.

Debian Free Software Guidelines (DFSG)

The DFSG defines what Debian considers "free software." These guidelines have become influential beyond Debian and have inspired other definitions of open source:

Guideline Description Example
Free Redistribution License cannot restrict any party from selling or giving away the software GPL, MIT, Apache licenses allow this
Source Code Program must include source code and allow distribution in source code form All main repository packages include source
Derived Works License must allow modifications and derived works Can create custom versions of packages
Integrity of Author's Source Code License may restrict source code modification only if patch files are allowed Some licenses require change documentation
No Discrimination Against Persons or Groups License cannot discriminate against any person or group Cannot restrict use by specific organizations
No Discrimination Against Fields of Endeavor License cannot restrict use in specific fields Cannot prohibit commercial or research use
Distribution of License Rights must apply to all recipients License travels with the software
License Must Not Be Specific to Debian Rights must not depend on being part of Debian Software remains free outside Debian
License Must Not Contaminate Other Software License cannot restrict other software on the same medium Cannot require entire system to be GPL
Example Licenses GPL, BSD, Artistic licenses comply with DFSG But not proprietary licenses

Repository Structure

Debian organizes its software into different repositories based on freedom and support level:

Main Repository:

  • Contains only DFSG-compliant free software
  • Officially supported by Debian
  • Receives security updates and bug fixes
  • Default repository enabled on all Debian installations

Contrib Repository:

  • Contains DFSG-compliant software
  • Depends on software from non-free repository
  • Officially supported but with limitations
  • Must be explicitly enabled by users

Non-Free Repository:

  • Contains software that doesn't meet DFSG criteria
  • Includes proprietary drivers and firmware
  • Not officially supported by Debian
  • Available as a convenience to users who need it

Non-Free-Firmware Repository (since Debian 12):

  • Split from non-free for better organization
  • Contains only firmware files
  • Easier to include only firmware without other non-free software
  • Addresses practical hardware support needs

Release Branches

Debian maintains several parallel branches to serve different user needs:

Branch Description Target Users Update Policy
Stable Current stable release Production servers, conservative users Security and critical bug fixes only
Oldstable Previous stable release Legacy systems Security updates for ~1 year after new stable
Testing Next stable release in development Desktop users wanting newer software Regular updates, occasional breakage
Unstable (Sid) Active development branch Developers, testers Constant updates, may break frequently
Experimental Highly experimental packages Package maintainers, advanced developers Very unstable, for testing only

Detailed Branch Characteristics:

Stable Branch:

  • Release cycle: ~2 years between major releases
  • Package versions: Fixed at release time
  • Security support: Full support for entire release cycle
  • Ideal for: Production servers, mission-critical systems, users who prioritize stability
  • Example: Debian 12 "Bookworm" (current as of 2023)

Testing Branch:

  • Rolling release model with periodic freezes
  • Packages migrate from unstable after 2-10 days without critical bugs
  • More recent software than stable
  • Security updates may lag behind stable
  • Ideal for: Desktop users, developers who need recent packages

Unstable (Sid) Branch:

  • Named after the destructive character from Toy Story
  • Always called "Sid," never changes name
  • Receives uploads directly from package maintainers
  • May have incomplete dependencies or broken packages
  • Ideal for: Experienced users, package developers, bug hunters

Installation and Setup

Pre-Installation Planning

Before installing Debian, careful planning ensures a smooth installation and optimal system configuration:

Hardware Requirements

Minimum Requirements:

Component Minimum Recommended Notes
Processor 1 GHz 2 GHz or faster Multi-core beneficial for desktop environments
RAM 512 MB 2 GB+ Depends on desktop environment choice
Disk Space 10 GB 20 GB+ More needed for desktop environments
Graphics VGA capable 1024×768 or higher Higher resolution for modern desktop environments
Network Not required Ethernet or WiFi Internet access simplifies installation

Desktop Environment Requirements:

Desktop Environment RAM Required Disk Space Performance Character
GNOME 2 GB+ 5 GB Modern, resource-intensive, feature-rich
KDE Plasma 2 GB+ 4 GB Highly customizable, moderate resource use
XFCE 512 MB 2 GB Lightweight, traditional interface
LXDE/LXQt 512 MB 1.5 GB Very lightweight, minimal
MATE 1 GB 3 GB GNOME 2 fork, balanced approach
Cinnamon 2 GB 4 GB Modern, user-friendly
No Desktop 256 MB 1 GB Server or minimal installations

Partitioning Schemes

Basic Partitioning (Simple approach):

Partition Mount Point Size Filesystem Purpose
/dev/sda1 /boot 512 MB ext4 Boot files
/dev/sda2 swap 2× RAM swap Virtual memory
/dev/sda3 / Remaining ext4 Root filesystem

Advanced Partitioning (Production servers):

Partition Mount Point Size Filesystem Purpose
/dev/sda1 /boot/efi 512 MB vfat UEFI boot partition
/dev/sda2 /boot 1 GB ext4 Boot files
/dev/sda3 swap 8 GB swap Virtual memory
/dev/sda4 / 20 GB ext4 Root filesystem
/dev/sda5 /home 50 GB ext4 User data
/dev/sda6 /var 20 GB ext4 Variable data
/dev/sda7 /var/log 10 GB ext4 System logs
/dev/sda8 /tmp 10 GB ext4 Temporary files
/dev/sda9 /srv Remaining ext4 Service data

LVM Partitioning (Flexible approach):

Using Logical Volume Manager provides flexibility for future expansion and snapshots:

Physical Volumes: /dev/sda2
Volume Group: vg_debian
  Logical Volumes:
    - lv_root     → /         (20 GB)
    - lv_home     → /home     (50 GB)
    - lv_var      → /var      (30 GB)
    - lv_swap     → swap      (8 GB)
    - Unallocated space for future expansion

Installation Media Selection

Media Type Use Case Advantages Disadvantages
Netinst ISO Network installation Small download (~300 MB), always latest packages Requires internet connection
DVD ISO Complete installation Works offline, includes most packages Large download (~4.7 GB)
Live ISO Try before install Test compatibility, rescue system Slower installation
USB Stick Modern hardware Fast, reusable, portable Requires USB port
Network Boot (PXE) Multiple installations Centralized management Requires PXE server setup

Installation Process

Step 1: Creating Installation Media

Creating bootable USB on Linux:

# Identify your USB device
lsblk

# Write ISO to USB (replace sdX with your device)
sudo dd if=debian-12.0.0-amd64-netinst.iso of=/dev/sdX bs=4M status=progress && sync

Creating bootable USB on Windows:

Use Rufus or balenaEtcher:

  • Download Rufus from https://rufus.ie
  • Select Debian ISO file
  • Choose target USB device
  • Click "Start"

Creating bootable USB on macOS:

# Identify disk
diskutil list

# Unmount disk
diskutil unmountDisk /dev/diskX

# Write ISO
sudo dd if=debian-12.0.0-amd64-netinst.iso of=/dev/rdiskX bs=1m

# Eject
diskutil eject /dev/diskX

Step 2: Boot Configuration

BIOS/UEFI Settings to Configure:

Setting Recommended Value Purpose
Boot Mode UEFI (if available) Modern boot standard, faster, more features
Secure Boot Disabled initially May interfere with installation
Fast Boot Disabled Ensures installer can load
Boot Order USB/DVD first Allow booting from installation media
SATA Mode AHCI Better performance and compatibility
Virtualization Enabled Required for running VMs

Step 3: Installation Steps

1. Boot Menu Selection:

Debian GNU/Linux installer menu (BIOS mode)
----------------------------------------
Install
Graphical Install
Advanced options >
  Expert install
  Automated install
  Rescue mode
Help
Install with speech synthesis

Recommended: Choose "Graphical Install" for beginners, "Install" for experienced users on slow hardware.

2. Language and Locale Configuration:

Setting Example Notes
Language English Interface language
Location United States Determines timezone and mirror
Keymap American English Keyboard layout

3. Network Configuration:

The installer will attempt automatic network configuration via DHCP. If you need manual configuration:

Parameter Example Description
IP Address 192.168.1.100 Static IP for server
Netmask 255.255.255.0 Subnet mask
Gateway 192.168.1.1 Router address
DNS 8.8.8.8, 1.1.1.1 Name servers
Hostname debian-server Computer name
Domain example.com Domain name (optional)

4. User and Password Setup:

Root Password: Strong password for superuser
[Note: Can be left blank to disable root and use sudo instead]

User Account:
  Full Name: John Doe
  Username: johndoe
  Password: Strong user password

Password Best Practices:

  • Minimum 12 characters
  • Mix of uppercase, lowercase, numbers, symbols
  • Avoid dictionary words
  • Use password manager for complex passwords

5. Disk Partitioning:

The installer offers several partitioning methods:

Method Description Best For
Guided - use entire disk Automatic, single partition Beginners, simple setups
Guided - use entire disk with LVM Automatic with LVM Intermediate users, flexibility
Guided - use entire disk with encrypted LVM Automatic with encryption Security-conscious users
Manual Complete control Advanced users, servers

Guided Partitioning Options:

All files in one partition (recommended for new users)
Separate /home partition
Separate /home, /var, and /tmp partitions

6. Package Mirror Selection:

Choose a Debian mirror close to your location:

Mirror Selection Example Purpose
Country United States Geographic proximity
Mirror deb.debian.org (automatic) Download source
HTTP Proxy blank or http://proxy:3128 If behind corporate firewall

7. Software Selection:

Choose software to install:
[*] Debian desktop environment
  [ ] GNOME
  [ ] XFCE
  [ ] KDE Plasma
  [ ] Cinnamon
  [ ] MATE
  [ ] LXDE
[*] web server
[ ] print server
[*] SSH server
[*] standard system utilities

Software Selection Recommendations:

System Type Recommended Selections
Desktop Desktop environment of choice + standard utilities
Web Server Web server + SSH server + standard utilities
Database Server SSH server + standard utilities (install DB manually)
Development Desktop environment + SSH + standard utilities
Minimal Standard utilities only

8. GRUB Bootloader Installation:

Install GRUB boot loader: Yes
Device for boot loader: /dev/sda (or your primary disk)

Important Notes:

  • Install GRUB on the disk device (e.g., /dev/sda), not a partition (e.g., /dev/sda1)
  • For multi-boot systems, ensure GRUB is on the primary boot disk
  • UEFI systems will install to the EFI system partition automatically

Post-Installation Configuration

First Boot and Initial Setup

1. Update System:

# Switch to root
su -

# Update package lists
apt update

# Upgrade installed packages
apt upgrade -y

# Optional: Upgrade to latest versions (may install new packages)
apt full-upgrade -y

2. Configure sudo (if not configured during installation):

# Install sudo
apt install sudo -y

# Add user to sudo group
usermod -aG sudo johndoe

# Verify sudo configuration
sudo -l -U johndoe

3. Configure System Timezone:

# List available timezones
timedatectl list-timezones

# Set timezone
timedatectl set-timezone America/New_York

# Verify
timedatectl status

4. Configure System Locale:

# Install locales package
apt install locales -y

# Configure locales
dpkg-reconfigure locales

# Select desired locales, set default
# Example: en_US.UTF-8 UTF-8

5. Install Essential Tools:

# System utilities
apt install -y \
  curl \
  wget \
  git \
  vim \
  htop \
  net-tools \
  dnsutils \
  traceroute \
  tcpdump \
  rsync \
  screen \
  tmux \
  bash-completion \
  command-not-found

# Update command-not-found database
update-command-not-found

Firmware Installation

Many hardware devices require non-free firmware to function properly:

Check for missing firmware:

# Check kernel messages for firmware requests
dmesg | grep -i firmware

# Install non-free firmware
# Edit sources.list to include non-free
nano /etc/apt/sources.list

Add non-free and non-free-firmware to sources.list:

# Debian 12 (Bookworm) sources
deb http://deb.debian.org/debian/ bookworm main contrib non-free non-free-firmware
deb-src http://deb.debian.org/debian/ bookworm main contrib non-free non-free-firmware

deb http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware
deb-src http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware

deb http://deb.debian.org/debian/ bookworm-updates main contrib non-free non-free-firmware
deb-src http://deb.debian.org/debian/ bookworm-updates main contrib non-free non-free-firmware

Install common firmware packages:

apt update
apt install -y \
  firmware-linux \
  firmware-linux-nonfree \
  firmware-misc-nonfree \
  firmware-realtek \
  firmware-atheros \
  firmware-iwlwifi

Hardware-Specific Firmware:

Hardware Package Description
Intel WiFi firmware-iwlwifi Intel wireless adapters
Realtek firmware-realtek Realtek network and audio
AMD/ATI Graphics firmware-amd-graphics AMD GPU firmware
Nvidia Graphics nvidia-driver Nvidia proprietary driver
Broadcom WiFi firmware-b43-installer Broadcom wireless
Intel Graphics firmware-misc-nonfree Intel GPU firmware

Package Management

Package management is one of Debian's strongest features. Understanding the package management system is crucial for system administration.

APT (Advanced Package Tool)

APT is the high-level package management tool for Debian systems. It handles dependency resolution, package downloading, and installation.

Essential APT Commands

Complete APT Command Reference:

Command Purpose Example Notes
apt update Update package lists apt update Run before installing packages
apt upgrade Upgrade installed packages apt upgrade Safe, doesn't remove packages
apt full-upgrade Upgrade with package removal if needed apt full-upgrade May remove packages
apt install Install packages apt install nginx Installs dependencies automatically
apt remove Remove packages apt remove nginx Keeps configuration files
apt purge Remove packages and configs apt purge nginx Complete removal
apt autoremove Remove unnecessary dependencies apt autoremove Cleans up orphaned packages
apt search Search for packages apt search web server Find packages by keyword
apt show Show package details apt show nginx Detailed package information
apt list List packages apt list --installed Various filtering options
apt edit-sources Edit sources.list safely apt edit-sources Validates syntax
apt-cache policy Show package priorities apt-cache policy nginx Check available versions
apt-mark Mark packages apt-mark hold nginx Prevent package changes
apt-file Search file contents apt-file search nginx.conf Find which package provides file

Detailed APT Usage Examples

1. Updating and Upgrading:

# Update package lists from repositories
sudo apt update

# Show upgradable packages
apt list --upgradable

# Upgrade all packages (safe)
sudo apt upgrade

# Upgrade with intelligent dependency handling
sudo apt full-upgrade

# Upgrade specific package
sudo apt install --only-upgrade nginx

# Simulate upgrade (dry run)
sudo apt upgrade --simulate

2. Installing Packages:

# Install single package
sudo apt install apache2

# Install multiple packages
sudo apt install nginx php-fpm mariadb-server

# Install specific version
sudo apt install nginx=1.22.1-1

# Install without prompting
sudo apt install -y htop

# Install from .deb file
sudo apt install ./package.deb

# Reinstall package
sudo apt install --reinstall nginx

# Install with recommended packages
sudo apt install --install-recommends package-name

# Install without recommended packages
sudo apt install --no-install-recommends package-name

3. Removing Packages:

# Remove package (keep configuration)
sudo apt remove nginx

# Remove package and configuration
sudo apt purge nginx

# Remove package and dependencies
sudo apt autoremove nginx

# Remove unused dependencies
sudo apt autoremove

# Clean downloaded package files
sudo apt clean

# Remove outdated downloaded packages
sudo apt autoclean

4. Searching and Querying:

# Search for packages
apt search "text editor"

# Search with regular expressions
apt search "^vim"

# Show package details
apt show nginx

# List all available packages
apt list

# List installed packages
apt list --installed

# List upgradable packages
apt list --upgradable

# Show package dependencies
apt depends nginx

# Show reverse dependencies
apt rdepends nginx

# Show package changelog
apt changelog nginx

5. Package Holding and Pinning:

# Hold package at current version
sudo apt-mark hold nginx

# Unhold package
sudo apt-mark unhold nginx

# Show held packages
apt-mark showhold

# Prevent automatic installation
sudo apt-mark manual nginx

# Mark as automatically installed
sudo apt-mark auto nginx

# Show manually installed packages
apt-mark showmanual

dpkg (Debian Package Manager)

dpkg is the low-level package management tool. While APT is typically preferred for most operations, dpkg is useful for specific tasks.

Essential dpkg Commands

Command Purpose Example Use Case
dpkg -i Install .deb package dpkg -i package.deb Manual package installation
dpkg -r Remove package dpkg -r package-name Remove without dependencies
dpkg -P Purge package dpkg -P package-name Remove with configs
dpkg -l List installed packages dpkg -l | grep nginx Check installed packages
dpkg -L List package files dpkg -L nginx See what files package installed
dpkg -S Search which package owns file dpkg -S /usr/sbin/nginx Find package for file
dpkg -s Show package status dpkg -s nginx Check if package is installed
dpkg --configure Configure unpacked package dpkg --configure -a Fix incomplete installations
dpkg-reconfigure Reconfigure package dpkg-reconfigure tzdata Change package settings
dpkg --get-selections Show package selections dpkg --get-selections Backup package list
dpkg --set-selections Set package selections dpkg --set-selections < file Restore package list

dpkg Advanced Usage

1. Package Information:

# List all installed packages
dpkg -l

# List packages matching pattern
dpkg -l | grep -i python

# Show detailed package status
dpkg -s nginx

# List files installed by package
dpkg -L nginx

# Find which package owns a file
dpkg -S /usr/bin/vim

# Show package content without installing
dpkg -c package.deb

# Extract package files without installing
dpkg -x package.deb /tmp/extracted

# Extract package control information
dpkg -e package.deb /tmp/control

2. Package Installation and Removal:

# Install package
sudo dpkg -i package.deb

# Remove package (keep configs)
sudo dpkg -r package-name

# Purge package (remove configs)
sudo dpkg -P package-name

# Fix broken dependencies after dpkg installation
sudo apt --fix-broken install

# Configure all unpacked but unconfigured packages
sudo dpkg --configure -a

# Remove packages marked for removal
sudo dpkg --remove -a

3. Package Database Management:

# Audit package database for problems
sudo dpkg --audit

# Clear available packages information
sudo dpkg --clear-avail

# Update available packages information
sudo dpkg --update-avail packages_file

# Forget about uninstalled unavailable packages
sudo dpkg --forget-uninstalled

# Export list of installed packages
dpkg --get-selections > package-selections.txt

# Import package selections
sudo dpkg --set-selections < package-selections.txt
sudo apt-get dselect-upgrade

Repository Configuration

Debian uses /etc/apt/sources.list and files in /etc/apt/sources.list.d/ to define package repositories.

sources.list Format

Basic Format:

deb [options] repository_url distribution components
deb-src [options] repository_url distribution components

Field Explanation:

Field Description Examples
deb/deb-src Binary packages / Source packages deb for binary, deb-src for source
[options] Optional settings [arch=amd64 signed-by=/path/to/key]
repository_url Mirror URL http://deb.debian.org/debian/
distribution Debian release bookworm, bookworm-updates, bookworm-security
components Repository sections main, contrib, non-free, non-free-firmware

Standard Debian 12 (Bookworm) sources.list

# Main repository - free software
deb http://deb.debian.org/debian/ bookworm main contrib non-free non-free-firmware
deb-src http://deb.debian.org/debian/ bookworm main contrib non-free non-free-firmware

# Security updates
deb http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware
deb-src http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware

# Point release updates
deb http://deb.debian.org/debian/ bookworm-updates main contrib non-free non-free-firmware
deb-src http://deb.debian.org/debian/ bookworm-updates main contrib non-free non-free-firmware

# Backports (optional) - newer software versions
# deb http://deb.debian.org/debian/ bookworm-backports main contrib non-free non-free-firmware

Third-Party Repository Management

Adding Third-Party Repositories:

# Method 1: Using add-apt-repository (requires software-properties-common)
sudo apt install software-properties-common
sudo add-apt-repository "deb [arch=amd64] https://example.com/debian bookworm main"

# Method 2: Manual addition
echo "deb [arch=amd64] https://example.com/debian bookworm main" | sudo tee /etc/apt/sources.list.d/example.list

# Method 3: Using apt edit-sources (recommended, validates syntax)
sudo apt edit-sources

Managing GPG Keys:

# Download and add GPG key (old method)
wget -O- https://example.com/key.gpg | sudo apt-key add -

# Download and add GPG key (new method, recommended)
wget -O- https://example.com/key.gpg | sudo gpg --dearmor -o /usr/share/keyrings/example-archive-keyring.gpg

# Add repository with signed-by option
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/example-archive-keyring.gpg] https://example.com/debian bookworm main" | sudo tee /etc/apt/sources.list.d/example.list

# List GPG keys
apt-key list

# Remove GPG key
sudo apt-key del KEY_ID

Common Third-Party Repositories:

Repository Purpose Addition Command
Docker Container platform See Docker official documentation
Node.js JavaScript runtime NodeSource repository
PostgreSQL Database PostgreSQL APT repository
Backports Newer package versions Included in standard sources
Security Security updates Included in standard sources
Multimedia Media codecs deb-multimedia.org

APT Configuration

APT behavior can be customized through configuration files in /etc/apt/apt.conf.d/.

Common APT Configurations

1. Disable Recommended Packages:

# Create configuration file
sudo nano /etc/apt/apt.conf.d/99-no-recommends

# Add content:
APT::Install-Recommends "false";
APT::Install-Suggests "false";

2. Configure APT Proxy:

# Create proxy configuration
sudo nano /etc/apt/apt.conf.d/80-proxy

# Add content:
Acquire::http::Proxy "http://proxy.example.com:3128";
Acquire::https::Proxy "http://proxy.example.com:3128";

3. Enable Automatic Security Updates:

# Install unattended-upgrades
sudo apt install unattended-upgrades apt-listchanges

# Configure
sudo dpkg-reconfigure -plow unattended-upgrades

# Edit configuration
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

Unattended Upgrades Configuration:

Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}";
    "${distro_id}:${distro_codename}-security";
    "${distro_id}ESMApps:${distro_codename}-apps-security";
    "${distro_id}ESM:${distro_codename}-infra-security";
};

// Automatically reboot if required
Unattended-Upgrade::Automatic-Reboot "false";

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

// Send email on errors
Unattended-Upgrade::Mail "root";

// Remove unused dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";

4. APT Caching:

# Install apt-cacher-ng
sudo apt install apt-cacher-ng

# Configure clients to use cache
sudo nano /etc/apt/apt.conf.d/02proxy

# Add:
Acquire::http::Proxy "http://apt-cache-server:3142";

Package Building and Source Compilation

1. Install Build Dependencies:

# Install build essential packages
sudo apt install build-essential devscripts

# Get source package
apt source package-name

# Install build dependencies
sudo apt build-dep package-name

2. Building from Source:

# Download source
apt source nginx

# Change to source directory
cd nginx-*/

# Install dependencies
sudo apt build-dep nginx

# Build package
dpkg-buildpackage -us -uc

# Install built package
sudo dpkg -i ../nginx_*.deb

3. Creating Simple .deb Package:

Create directory structure:

mkdir -p mypackage/DEBIAN
mkdir -p mypackage/usr/local/bin

# Create control file
cat > mypackage/DEBIAN/control << EOF
Package: mypackage
Version: 1.0
Section: utils
Priority: optional
Architecture: all
Maintainer: Your Name <your.email@example.com>
Description: My custom package
 Long description of my package
EOF

# Add your files
cp myscript.sh mypackage/usr/local/bin/

# Build package
dpkg-deb --build mypackage

# Install
sudo dpkg -i mypackage.deb

System Administration

System administration encompasses managing users, processes, services, logs, and system resources.

User and Group Management

User Management Commands

Complete User Management Command Reference:

Command Purpose Example Options
adduser Add new user (interactive) adduser johndoe High-level, Debian-specific
useradd Add new user (manual) useradd -m -s /bin/bash johndoe Low-level, more control
usermod Modify user account usermod -aG sudo johndoe Change user properties
userdel Delete user userdel -r johndoe Remove user account
passwd Change password passwd johndoe Set/change passwords
chage Change password expiry chage -M 90 johndoe Password aging
addgroup Add new group addgroup developers Create group
groupadd Add new group (manual) groupadd -g 1500 developers Low-level group creation
groupmod Modify group groupmod -n newname oldname Change group properties
groupdel Delete group groupdel developers Remove group
gpasswd Administer groups gpasswd -a user group Group membership
newgrp Log in to new group newgrp developers Change current group
id Show user/group IDs id johndoe Display user information
whoami Show current user whoami Display current username
who Show logged-in users who Show users
w Show logged-in users and activity w Detailed user info
last Show login history last Last logged users
lastlog Show last login of all users lastlog Login reports

User Creation and Management

1. Creating Users:

# Interactive user creation (recommended)
sudo adduser johndoe

# Manual user creation with options
sudo useradd -m -s /bin/bash -c "John Doe" -G sudo,www-data johndoe

# Set password
sudo passwd johndoe

# Create system user (no login, for services)
sudo useradd -r -s /usr/sbin/nologin -d /var/lib/myservice myservice

useradd Options:

Option Purpose Example
-m Create home directory useradd -m user
-d Specify home directory useradd -d /custom/home user
-s Specify shell useradd -s /bin/zsh user
-c Set comment (full name) useradd -c "John Doe" user
-G Add to groups useradd -G sudo,docker user
-g Set primary group useradd -g users user
-u Set UID useradd -u 1500 user
-e Set expiry date useradd -e 2024-12-31 user
-r Create system user useradd -r serviceuser
-p Set encrypted password useradd -p $(openssl passwd -1 pass) user

2. Modifying Users:

# Add user to group
sudo usermod -aG sudo johndoe

# Change user's shell
sudo usermod -s /bin/zsh johndoe

# Change user's home directory
sudo usermod -d /new/home -m johndoe

# Lock user account
sudo usermod -L johndoe

# Unlock user account
sudo usermod -U johndoe

# Change username
sudo usermod -l newname oldname

# Set account expiry
sudo usermod -e 2024-12-31 johndoe

# Set comment/full name
sudo usermod -c "John Smith Doe" johndoe

3. Deleting Users:

# Delete user (keep home directory)
sudo userdel johndoe

# Delete user and home directory
sudo userdel -r johndoe

# Force delete (even if logged in)
sudo userdel -f johndoe

# Delete user and their mail spool
sudo userdel -r -f johndoe

Group Management

1. Creating and Managing Groups:

# Create new group
sudo addgroup developers

# Create group with specific GID
sudo groupadd -g 1500 developers

# Add user to group
sudo gpasswd -a johndoe developers
# or
sudo usermod -aG developers johndoe

# Remove user from group
sudo gpasswd -d johndoe developers

# List group members
getent group developers

# Delete group
sudo groupdel developers

# Rename group
sudo groupmod -n newname oldname

# Change group GID
sudo groupmod -g 1600 developers

2. Group Administration Commands:

Command Purpose Example
gpasswd -a user group Add user to group gpasswd -a john developers
gpasswd -d user group Remove user from group gpasswd -d john developers
gpasswd -A user group Set group administrator gpasswd -A admin developers
gpasswd -M user1,user2 group Set group members gpasswd -M john,jane developers
gpasswd group Set group password gpasswd developers
newgrp group Change current group newgrp developers

Password Policy

1. Configure Password Aging:

# Set maximum password age (90 days)
sudo chage -M 90 johndoe

# Set minimum password age (7 days)
sudo chage -m 7 johndoe

# Set password expiry warning (14 days before)
sudo chage -W 14 johndoe

# Set account expiry date
sudo chage -E 2024-12-31 johndoe

# Force password change on next login
sudo chage -d 0 johndoe

# View password aging information
sudo chage -l johndoe

# Set inactivity period (30 days after password expiry)
sudo chage -I 30 johndoe

2. Configure PAM Password Quality:

# Install password quality checking library
sudo apt install libpam-pwquality

# Configure password requirements
sudo nano /etc/security/pwquality.conf

pwquality.conf example:

# Minimum password length
minlen = 12

# Require at least one digit
dcredit = -1

# Require at least one uppercase character
ucredit = -1

# Require at least one lowercase character
lcredit = -1

# Require at least one special character
ocredit = -1

# Maximum consecutive characters
maxrepeat = 3

# Minimum character classes required
minclass = 3

# Check against dictionary
dictcheck = 1

# Require different from username
usercheck = 1

3. Configure Login Attempts:

# Edit PAM common-auth
sudo nano /etc/pam.d/common-auth

# Add after other auth lines:
auth required pam_faillock.so preauth silent audit deny=5 unlock_time=900
auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900

# Check failed login attempts
sudo faillock --user johndoe

# Reset failed login attempts
sudo faillock --user johndoe --reset

Process Management

Process Monitoring Commands

Essential Process Commands:

Command Purpose Key Options Example
ps Show processes aux, -ef ps aux | grep nginx
top Interactive process viewer h for help top
htop Enhanced process viewer F5 sort, F9 kill htop
pgrep Find processes by name -l, -f pgrep -l nginx
pkill Kill processes by name -9, -15 pkill -9 nginx
pidof Find PID by program name -s pidof nginx
kill Send signal to process -9, -15, -HUP kill -9 12345
killall Kill processes by name -9, -15 killall nginx
nice Start process with priority -n 10 nice -n 10 command
renice Change process priority -n 5 -p PID renice -n 5 -p 12345
pstree Show process tree -p, -u pstree -p
lsof List open files -p PID, -i lsof -i :80
fuser Identify file users -v, -k fuser -v /var/log/

Detailed Process Management

1. Viewing Processes:

# Show all processes (BSD style)
ps aux

# Show all processes (Unix style)
ps -ef

# Show processes for specific user
ps -u johndoe

# Show process tree
ps auxf

# Show threads
ps -eLf

# Custom format
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu

# Monitor processes continuously
watch -n 1 'ps aux --sort=-%cpu | head -20'

ps Output Columns:

Column Description Example Values
USER Process owner root, johndoe
PID Process ID 1234
%CPU CPU usage 12.5
%MEM Memory usage 2.3
VSZ Virtual memory size (KB) 234567
RSS Resident set size (KB) 12345
TTY Terminal pts/0, ?
STAT Process state R, S, D, Z
START Start time 10:30
TIME CPU time 0:05
COMMAND Command name nginx

Process States:

State Description Meaning
R Running Currently executing or runnable
S Sleeping Waiting for event to complete
D Uninterruptible sleep Usually waiting for I/O
T Stopped Stopped by job control signal
Z Zombie Terminated but not reaped by parent
I Idle Kernel thread

2. Using top and htop:

# Launch top
top

# Top keyboard shortcuts:
# h - Help
# M - Sort by memory
# P - Sort by CPU
# k - Kill process
# r - Renice process
# f - Select fields to display
# W - Save configuration
# q - Quit

# Launch htop (more user-friendly)
htop

# htop keyboard shortcuts:
# F1 - Help
# F2 - Setup
# F3 - Search
# F4 - Filter
# F5 - Tree view
# F6 - Sort by
# F9 - Kill
# F10 - Quit

3. Killing Processes:

# Kill process by PID (graceful)
kill 12345

# Force kill process
kill -9 12345

# Send HUP signal (reload configuration)
kill -HUP 12345

# Kill all processes with name
killall nginx

# Kill all processes matching pattern
pkill -9 -f "python.*script"

# Kill processes using specific file/port
fuser -k /var/log/myapp.log
fuser -k 80/tcp

# Interactive process killing
top  # then press 'k' and enter PID

Common Signals:

Signal Number Description Use Case
SIGHUP 1 Hangup Reload configuration
SIGINT 2 Interrupt Ctrl+C
SIGQUIT 3 Quit Ctrl+\
SIGKILL 9 Kill Force termination (cannot be caught)
SIGTERM 15 Terminate Graceful shutdown (default)
SIGSTOP 19 Stop Pause process
SIGCONT 18 Continue Resume stopped process
SIGUSR1 10 User-defined Application-specific
SIGUSR2 12 User-defined Application-specific

4. Process Priority:

# Start process with low priority
nice -n 10 command

# Start process with high priority (requires root)
sudo nice -n -10 command

# Change priority of running process
renice -n 5 -p 12345

# Change priority of all processes by user
sudo renice -n 10 -u johndoe

# View process priority
ps -eo pid,ni,cmd

Priority Values:

Nice Value Priority Description
-20 Highest Maximum priority
-10 High Important processes
0 Normal Default priority
10 Low Background tasks
19 Lowest Minimum priority

Service Management (systemd)

Systemd is the init system and service manager for Debian (since Debian 8).

systemctl Commands

Complete systemctl Reference:

Command Purpose Example Description
systemctl start Start service systemctl start nginx Start service now
systemctl stop Stop service systemctl stop nginx Stop service now
systemctl restart Restart service systemctl restart nginx Stop then start
systemctl reload Reload configuration systemctl reload nginx Reload config without restart
systemctl status Show service status systemctl status nginx Detailed status
systemctl enable Enable at boot systemctl enable nginx Start automatically
systemctl disable Disable at boot systemctl disable nginx Don't start automatically
systemctl is-active Check if running systemctl is-active nginx Returns active/inactive
systemctl is-enabled Check if enabled systemctl is-enabled nginx Returns enabled/disabled
systemctl list-units List active units systemctl list-units Show all active
systemctl list-unit-files List all units systemctl list-unit-files Show all available
systemctl daemon-reload Reload systemd systemctl daemon-reload After editing units
systemctl mask Mask service systemctl mask nginx Prevent starting
systemctl unmask Unmask service systemctl unmask nginx Allow starting
systemctl cat Show unit file systemctl cat nginx Display unit content
systemctl edit Edit unit file systemctl edit nginx Create override
systemctl show Show properties systemctl show nginx All properties

Service Management Examples

1. Basic Service Operations:

# Start service
sudo systemctl start nginx

# Stop service
sudo systemctl stop nginx

# Restart service
sudo systemctl restart nginx

# Reload configuration (if supported)
sudo systemctl reload nginx

# Reload or restart
sudo systemctl reload-or-restart nginx

# Check service status
systemctl status nginx

# Check if service is active
systemctl is-active nginx

# Check if service is enabled
systemctl is-enabled nginx

# View service logs
journalctl -u nginx

# Follow service logs
journalctl -u nginx -f

2. Service Enable/Disable:

# Enable service to start at boot
sudo systemctl enable nginx

# Enable and start service
sudo systemctl enable --now nginx

# Disable service
sudo systemctl disable nginx

# Disable and stop service
sudo systemctl disable --now nginx

# Mask service (prevent starting)
sudo systemctl mask nginx

# Unmask service
sudo systemctl unmask nginx

# Show service dependencies
systemctl list-dependencies nginx

3. Listing Services:

# List all active units
systemctl list-units

# List all services
systemctl list-units --type=service

# List all active services
systemctl list-units --type=service --state=active

# List all failed services
systemctl list-units --type=service --state=failed

# List all unit files
systemctl list-unit-files

# List enabled services
systemctl list-unit-files --state=enabled

# List disabled services
systemctl list-unit-files --state=disabled

4. Creating Custom Service:

Create service file:

sudo nano /etc/systemd/system/myapp.service

Example service file:

[Unit]
Description=My Application Service
Documentation=https://example.com/docs
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/app.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp

# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp

[Install]
WantedBy=multi-user.target

Service file sections explained:

Section Directive Purpose
[Unit] Description Service description
Documentation Documentation URL
After Start after these units
Before Start before these units
Requires Hard dependency
Wants Soft dependency
[Service] Type Service type (simple, forking, oneshot, etc.)
User Run as user
Group Run as group
ExecStart Command to start service
ExecStop Command to stop service
ExecReload Command to reload
Restart Restart policy
RestartSec Wait before restart
[Install] WantedBy Enable for target
RequiredBy Required by target
Also Enable with this service

Enable and start custom service:

# Reload systemd to recognize new service
sudo systemctl daemon-reload

# Enable service
sudo systemctl enable myapp

# Start service
sudo systemctl start myapp

# Check status
systemctl status myapp

# View logs
journalctl -u myapp -f

5. Service Troubleshooting:

# View detailed status
systemctl status nginx -l --no-pager

# View recent logs
journalctl -u nginx -n 50

# View logs since boot
journalctl -u nginx -b

# View logs with priority
journalctl -u nginx -p err

# Check service dependencies
systemctl list-dependencies nginx

# Check what's preventing service from starting
systemctl status nginx
journalctl -xe

# Reset failed state
sudo systemctl reset-failed nginx

# Analyze boot time
systemd-analyze blame

# Analyze service startup time
systemd-analyze critical-chain nginx

System Logging

Journal Management (journalctl)

Complete journalctl Reference:

Command Purpose Example
journalctl View all logs journalctl
journalctl -f Follow logs journalctl -f
journalctl -u service Service logs journalctl -u nginx
journalctl -b Current boot journalctl -b
journalctl -b -1 Previous boot journalctl -b -1
journalctl --since Time range journalctl --since "2024-01-01"
journalctl --until Until time journalctl --until "1 hour ago"
journalctl -p Priority level journalctl -p err
journalctl -k Kernel messages journalctl -k
journalctl --disk-usage Show disk usage journalctl --disk-usage
journalctl --vacuum-size Clean old logs journalctl --vacuum-size=100M
journalctl --vacuum-time Clean by time journalctl --vacuum-time=7d

Detailed journalctl Usage:

# View all logs
journalctl

# View logs with pager
journalctl --no-pager

# Follow logs (like tail -f)
journalctl -f

# View logs for specific service
journalctl -u nginx

# View logs for multiple services
journalctl -u nginx -u mysql

# View kernel messages
journalctl -k

# View logs since specific date/time
journalctl --since "2024-01-01 00:00:00"
journalctl --since "yesterday"
journalctl --since "1 hour ago"
journalctl --since "30 min ago"

# View logs until specific time
journalctl --until "2024-01-01 23:59:59"

# View logs between dates
journalctl --since "2024-01-01" --until "2024-01-31"

# View logs by priority
journalctl -p emerg    # Emergency (0)
journalctl -p alert    # Alert (1)
journalctl -p crit     # Critical (2)
journalctl -p err      # Error (3)
journalctl -p warning  # Warning (4)
journalctl -p notice   # Notice (5)
journalctl -p info     # Info (6)
journalctl -p debug    # Debug (7)

# View logs from current boot
journalctl -b

# View logs from previous boot
journalctl -b -1

# List available boots
journalctl --list-boots

# View logs in JSON format
journalctl -o json

# View logs in verbose format
journalctl -o verbose

# View logs with timestamps
journalctl -o short-precise

# Show only messages from today
journalctl --since today

# Show last 100 lines
journalctl -n 100

# Show disk usage
journalctl --disk-usage

# Verify journal files
journalctl --verify

# Rotate journal files
sudo journalctl --rotate

# Vacuum journal by size
sudo journalctl --vacuum-size=500M

# Vacuum journal by time
sudo journalctl --vacuum-time=30d

# Vacuum journal by file count
sudo journalctl --vacuum-files=5

Configure journal persistence:

# Edit journald configuration
sudo nano /etc/systemd/journald.conf

journald.conf example:

[Journal]
# Store logs persistently
Storage=persistent

# Maximum disk usage
SystemMaxUse=500M

# Keep logs for 30 days
MaxRetentionSec=30d

# Maximum single journal file size
SystemMaxFileSize=100M

# Forward to syslog
ForwardToSyslog=yes

# Compress logs
Compress=yes

# Set seal (integrity protection)
Seal=yes

Apply configuration:

# Restart journald
sudo systemctl restart systemd-journald

# Verify status
systemctl status systemd-journald

Traditional Logging

Despite systemd's journal, traditional log files in /var/log are still used:

Important Log Files:

File/Directory Content Purpose
/var/log/syslog System messages General system activity
/var/log/auth.log Authentication logs Login attempts, sudo usage
/var/log/kern.log Kernel messages Kernel and driver messages
/var/log/dmesg Boot messages Hardware detection at boot
/var/log/daemon.log Daemon messages Background services
/var/log/messages General messages Alternative to syslog
/var/log/user.log User-level logs User processes
/var/log/apache2/ Apache logs Web server activity
/var/log/nginx/ Nginx logs Web server activity
/var/log/mysql/ MySQL logs Database activity
/var/log/apt/ Package management Installation history
/var/log/dpkg.log Package changes Detailed package operations
/var/log/faillog Failed logins Login failures
/var/log/lastlog Last logins User last login times
/var/log/wtmp Login records Login/logout history
/var/log/btmp Failed logins Binary failed login log

Log Viewing Commands:

# View log file
cat /var/log/syslog

# View with less
less /var/log/syslog

# Follow log file
tail -f /var/log/syslog

# View last 100 lines
tail -n 100 /var/log/syslog

# View with line numbers
nl /var/log/syslog | less

# Search in log
grep "error" /var/log/syslog

# Search case-insensitive
grep -i "failed" /var/log/auth.log

# Count occurrences
grep -c "error" /var/log/syslog

# Show context around match
grep -C 5 "error" /var/log/syslog

# Search multiple files
grep "error" /var/log/*.log

# View compressed logs
zcat /var/log/syslog.1.gz | less
zgrep "error" /var/log/syslog.*.gz

Log Rotation

Logrotate manages automatic log file rotation:

# Edit global configuration
sudo nano /etc/logrotate.conf

# Add service-specific configuration
sudo nano /etc/logrotate.d/myapp

Example logrotate configuration:

/var/log/myapp/*.log {
    # Rotate daily
    daily
    
    # Keep 14 days of logs
    rotate 14
    
    # Compress old logs
    compress
    
    # Delay compression by one rotation
    delaycompress
    
    # Don't error if log is missing
    missingok
    
    # Don't rotate if empty
    notifempty
    
    # Create new log file with permissions
    create 0640 www-data adm
    
    # Run commands after rotation
    postrotate
        # Reload application to use new log file
        systemctl reload myapp
    endscript
    
    # Rotate based on size instead
    # size 100M
    
    # Email old logs before deletion
    # mail admin@example.com
}

Test logrotate configuration:

# Test configuration
sudo logrotate -d /etc/logrotate.d/myapp

# Force rotation
sudo logrotate -f /etc/logrotate.d/myapp

# Verbose output
sudo logrotate -v /etc/logrotate.conf

Logrotate options:

Option Description
daily, weekly, monthly, yearly Rotation frequency
rotate N Keep N old logs
size NM/NG Rotate when size reached
compress Compress old logs with gzip
delaycompress Compress on next rotation
create MODE OWNER GROUP Create new log with permissions
copytruncate Copy then truncate (for open files)
missingok Don't error if missing
notifempty Don't rotate if empty
sharedscripts Run scripts once for all logs
postrotate/endscript Commands after rotation
prerotate/endscript Commands before rotation
maxage N Remove logs older than N days
mail ADDRESS Email old logs
dateext Use date in filename

Network Configuration

Network configuration is crucial for servers and workstations. Debian offers multiple tools for network management.

Network Interfaces

Configuration Files

Primary network configuration file:

# Edit interfaces file
sudo nano /etc/network/interfaces

Basic interfaces configuration:

# Loopback interface
auto lo
iface lo inet loopback

# DHCP configuration
auto eth0
iface eth0 inet dhcp

# Static IP configuration
auto eth1
iface eth1 inet static
    address 192.168.1.100
    netmask 255.255.255.0
    gateway 192.168.1.1
    dns-nameservers 8.8.8.8 1.1.1.1

Advanced interface configurations:

# Static IPv4 with multiple IPs
auto eth0
iface eth0 inet static
    address 192.168.1.100/24
    gateway 192.168.1.1
    dns-nameservers 8.8.8.8 1.1.1.1
    dns-search example.com
    # Additional IP
    up ip addr add 192.168.1.101/24 dev eth0
    down ip addr del 192.168.1.101/24 dev eth0

# IPv6 configuration
iface eth0 inet6 static
    address 2001:db8::100
    netmask 64
    gateway 2001:db8::1

# VLAN configuration
auto eth0.100
iface eth0.100 inet static
    address 10.0.100.10/24
    vlan-raw-device eth0

# Bridge configuration
auto br0
iface br0 inet static
    address 192.168.1.100/24
    bridge_ports eth0 eth1
    bridge_stp off
    bridge_fd 0

# Bond configuration (network teaming)
auto bond0
iface bond0 inet static
    address 192.168.1.100/24
    slaves eth0 eth1
    bond_mode active-backup
    bond_miimon 100
    bond_downdelay 200
    bond_updelay 200

# Wireless configuration
auto wlan0
iface wlan0 inet dhcp
    wpa-ssid "NetworkName"
    wpa-psk "password"

Network Management Commands

Essential networking commands:

Command Purpose Example
ip addr Show IP addresses ip addr show
ip link Show network interfaces ip link show
ip route Show routing table ip route show
ifup Bring interface up ifup eth0
ifdown Bring interface down ifdown eth0
ifconfig Configure network interface (deprecated) ifconfig eth0
ping Test connectivity ping 8.8.8.8
traceroute Trace route to host traceroute google.com
netstat Network statistics netstat -tulpn
ss Socket statistics (modern netstat) ss -tulpn
nmap Network scanning nmap -sV 192.168.1.0/24
tcpdump Capture packets tcpdump -i eth0
dig DNS lookup dig google.com
nslookup DNS query nslookup google.com
host DNS lookup host google.com
wget Download files wget https://example.com/file
curl Transfer data curl https://api.example.com
nc Network connections nc -zv host 80
arp ARP table arp -a

Detailed network command usage:

# IP address management
ip addr show                    # Show all interfaces
ip addr show eth0              # Show specific interface
sudo ip addr add 192.168.1.100/24 dev eth0    # Add IP
sudo ip addr del 192.168.1.100/24 dev eth0    # Remove IP

# Link management
ip link show                   # Show all links
sudo ip link set eth0 up       # Bring interface up
sudo ip link set eth0 down     # Bring interface down
sudo ip link set eth0 mtu 9000 # Change MTU

# Routing
ip route show                  # Show routing table
sudo ip route add default via 192.168.1.1    # Add default route
sudo ip route add 10.0.0.0/8 via 192.168.1.254    # Add specific route
sudo ip route del 10.0.0.0/8   # Delete route

# DNS resolution
dig google.com                 # Standard query
dig @8.8.8.8 google.com        # Query specific DNS server
dig google.com MX              # Query MX records
dig +short google.com          # Short output
dig -x 8.8.8.8                 # Reverse lookup

# Port scanning
nmap 192.168.1.100             # Basic scan
nmap -sV 192.168.1.100         # Service version detection
nmap -sT 192.168.1.100         # TCP connect scan
nmap -sU 192.168.1.100         # UDP scan
nmap -p- 192.168.1.100         # Scan all ports
nmap -p 80,443 192.168.1.100   # Scan specific ports
nmap 192.168.1.0/24            # Scan network range

# Packet capture
sudo tcpdump -i eth0           # Capture on interface
sudo tcpdump -i eth0 port 80   # Capture specific port
sudo tcpdump -i eth0 host 192.168.1.100    # Capture specific host
sudo tcpdump -i eth0 -w capture.pcap       # Save to file
sudo tcpdump -r capture.pcap   # Read from file

# Socket statistics
ss -tulpn                      # Show all listening sockets
ss -t                          # Show TCP sockets
ss -u                          # Show UDP sockets
ss -a                          # Show all sockets
ss -s                          # Show socket statistics
ss -o state established        # Show established connections

# Test connectivity
ping -c 4 8.8.8.8              # Ping 4 times
ping6 2001:4860:4860::8888     # IPv6 ping
traceroute google.com          # Trace route
mtr google.com                 # Continuous traceroute

# Test port connectivity
nc -zv google.com 80           # Test TCP connection
nc -zuv 8.8.8.8 53             # Test UDP connection
timeout 5 bash -c '</dev/tcp/google.com/80' && echo "Port open"

# Bandwidth testing
iperf3 -s                      # Server mode
iperf3 -c server_ip            # Client mode

# Download/upload testing
wget https://example.com/file  # Download file
curl -O https://example.com/file    # Download with curl
curl -I https://example.com    # Get headers only
curl -X POST -d "data" https://api.example.com    # POST request

NetworkManager

NetworkManager provides a higher-level network configuration interface, especially useful for laptops and desktops.

Install NetworkManager:

sudo apt install network-manager

NetworkManager commands (nmcli):

Command Purpose Example
nmcli general General status nmcli general status
nmcli networking Networking control nmcli networking on
nmcli device Device management nmcli device show
nmcli connection Connection management nmcli connection show
nmcli radio Radio control nmcli radio wifi on

Detailed nmcli usage:

# General status
nmcli general status

# Show devices
nmcli device status
nmcli device show eth0

# Show connections
nmcli connection show
nmcli connection show "Wired connection 1"

# Create new connection
nmcli connection add con-name "Static-eth0" ifname eth0 type ethernet ip4 192.168.1.100/24 gw4 192.168.1.1

# Modify connection
nmcli connection modify "Static-eth0" ipv4.dns "8.8.8.8 1.1.1.1"
nmcli connection modify "Static-eth0" ipv4.method manual

# Activate/deactivate connection
nmcli connection up "Static-eth0"
nmcli connection down "Static-eth0"

# Delete connection
nmcli connection delete "Static-eth0"

# WiFi management
nmcli radio wifi on
nmcli device wifi list
nmcli device wifi connect "SSID" password "password"
nmcli device wifi connect "SSID" password "password" name "MyWiFi"

# Disconnect device
nmcli device disconnect eth0

# Reconnect device
nmcli device connect eth0

# Show WiFi password
nmcli connection show "MyWiFi" | grep psk

# Hotspot creation
nmcli device wifi hotspot ssid "MyHotspot" password "mypassword"

Firewall Configuration

UFW (Uncomplicated Firewall)

UFW provides a user-friendly interface to iptables.

Install UFW:

sudo apt install ufw

Essential UFW commands:

Command Purpose Example
ufw enable Enable firewall ufw enable
ufw disable Disable firewall ufw disable
ufw status Show firewall status ufw status verbose
ufw allow Allow traffic ufw allow 22/tcp
ufw deny Deny traffic ufw deny 23/tcp
ufw delete Delete rule ufw delete allow 22/tcp
ufw reset Reset to defaults ufw reset
ufw reload Reload rules ufw reload

Detailed UFW usage:

# Enable UFW
sudo ufw enable

# Disable UFW
sudo ufw disable

# Show status
sudo ufw status
sudo ufw status verbose
sudo ufw status numbered

# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow services
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw allow 8080/tcp

# Allow specific port ranges
sudo ufw allow 6000:6007/tcp
sudo ufw allow 6000:6007/udp

# Allow from specific IP
sudo ufw allow from 192.168.1.100
sudo ufw allow from 192.168.1.0/24

# Allow from IP to specific port
sudo ufw allow from 192.168.1.100 to any port 22

# Allow from IP to specific interface
sudo ufw allow in on eth0 from 192.168.1.0/24

# Deny traffic
sudo ufw deny 23/tcp
sudo ufw deny from 192.168.1.200

# Delete rules
sudo ufw delete allow 80/tcp
sudo ufw delete 5  # Delete rule number 5

# Insert rule at specific position
sudo ufw insert 1 allow from 192.168.1.100

# Application profiles
sudo ufw app list
sudo ufw allow 'Apache Full'
sudo ufw allow 'OpenSSH'

# Limit connections (rate limiting)
sudo ufw limit ssh

# Logging
sudo ufw logging on
sudo ufw logging medium
sudo ufw logging off

# Reset UFW
sudo ufw reset

# Show raw iptables rules
sudo ufw show raw

Create custom application profile:

sudo nano /etc/ufw/applications.d/myapp
[MyApp]
title=My Application
description=My custom application
ports=8080,8443/tcp
# Update application list
sudo ufw app update MyApp

# Allow application
sudo ufw allow MyApp

iptables

For more advanced firewall configuration, use iptables directly:

Basic iptables commands:

# View current rules
sudo iptables -L -n -v

# View NAT rules
sudo iptables -t nat -L -n -v

# Save rules
sudo iptables-save > /etc/iptables/rules.v4

# Restore rules
sudo iptables-restore < /etc/iptables/rules.v4

# Allow incoming SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
sudo iptables -A INPUT -i lo -j ACCEPT

# Drop all other incoming
sudo iptables -P INPUT DROP

# Allow all outgoing
sudo iptables -P OUTPUT ACCEPT

# Delete rule
sudo iptables -D INPUT 5

# Insert rule at position
sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

# Flush all rules
sudo iptables -F

Example complete firewall script:

#!/bin/bash

# Flush existing rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ping
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# Log dropped packets
iptables -A INPUT -j LOG --log-prefix "iptables-dropped: "

# Save rules
iptables-save > /etc/iptables/rules.v4

Security and Hardening

Security is paramount for any Linux system. This section covers essential security practices and hardening techniques.

User Security

SSH Configuration

Secure SSH configuration:

sudo nano /etc/ssh/sshd_config

Recommended SSH settings:

# Change default port (security through obscurity)
Port 2222

# Protocol version
Protocol 2

# Disable root login
PermitRootLogin no

# Enable public key authentication
PubkeyAuthentication yes

# Disable password authentication (after setting up keys)
PasswordAuthentication no
ChallengeResponseAuthentication no

# Disable empty passwords
PermitEmptyPasswords no

# Limit users
AllowUsers user1 user2
# Or limit groups
AllowGroups sshusers

# Use PAM
UsePAM yes

# Disable X11 forwarding (if not needed)
X11Forwarding no

# Set idle timeout
ClientAliveInterval 300
ClientAliveCountMax 2

# Maximum authentication attempts
MaxAuthTries 3

# Maximum sessions
MaxSessions 3

# Login grace time
LoginGraceTime 30

# Strict mode
StrictModes yes

# Only use strong ciphers
Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

# Only use strong MACs
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256

# Only use strong key exchange algorithms
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256

# Disable unused authentication methods
GSSAPIAuthentication no
HostbasedAuthentication no

Apply SSH configuration:

# Test configuration
sudo sshd -t

# Restart SSH service
sudo systemctl restart sshd

# Check status
sudo systemctl status sshd

SSH Key-Based Authentication:

# Generate SSH key pair (on client)
ssh-keygen -t ed25519 -C "your_email@example.com"
# or for RSA
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Copy public key to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# Or manually
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Set proper permissions on server
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

# Test connection
ssh user@server

SSH Security Best Practices:

Practice Command/Configuration Benefit
Change default port Port 2222 Reduce automated attacks
Disable root login PermitRootLogin no Force use of sudo
Use key authentication PasswordAuthentication no Much stronger than passwords
Limit users AllowUsers user1 user2 Restrict access
Set timeout ClientAliveInterval 300 Auto-disconnect idle sessions
Use fail2ban Install and configure Block brute-force attacks
Keep SSH updated apt update && apt upgrade openssh-server Patch vulnerabilities
Monitor logs journalctl -u sshd -f Detect suspicious activity

Fail2ban

Fail2ban monitors logs and bans IPs with suspicious activity.

Install Fail2ban:

sudo apt install fail2ban

Configure Fail2ban:

# Copy default configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Edit configuration
sudo nano /etc/fail2ban/jail.local

Example configuration:

[DEFAULT]
# Ban hosts for 1 hour
bantime = 3600

# Host is banned if it generates 5 failures within 10 minutes
findtime = 600
maxretry = 5

# Email notifications
destemail = admin@example.com
sendername = Fail2ban
mta = sendmail
action = %(action_mwl)s

[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s

[sshd-ddos]
enabled = true
port = ssh
logpath = %(sshd_log)s

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log

[nginx-noscript]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log

[nginx-badbots]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 2

[nginx-noproxy]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log

Fail2ban management:

# Start fail2ban
sudo systemctl start fail2ban

# Enable at boot
sudo systemctl enable fail2ban

# Check status
sudo fail2ban-client status

# Check specific jail
sudo fail2ban-client status sshd

# Unban IP
sudo fail2ban-client set sshd unbanip 192.168.1.100

# Ban IP manually
sudo fail2ban-client set sshd banip 192.168.1.200

# Reload configuration
sudo fail2ban-client reload

# Show banned IPs
sudo fail2ban-client banned

System Hardening

File System Security

Important file permissions:

# Secure home directories
sudo chmod 750 /home/*

# Secure SSH keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/id_*.pub

# Secure configuration files
sudo chmod 644 /etc/passwd
sudo chmod 640 /etc/shadow
sudo chmod 644 /etc/group
sudo chmod 640 /etc/gshadow

# Secure system files
sudo chmod 600 /boot/grub/grub.cfg
sudo chmod 700 /root
sudo chmod 600 /etc/ssh/sshd_config

# Find world-writable files
find / -xdev -type f -perm -0002 -ls 2>/dev/null

# Find files with no owner
find / -xdev -nouser -o -nogroup 2>/dev/null

# Find SUID/SGID files
find / -xdev -type f -perm -4000 -ls 2>/dev/null
find / -xdev -type f -perm -2000 -ls 2>/dev/null

Secure mount options in /etc/fstab:

# Add security options to mount points
/dev/sda5  /tmp      ext4  defaults,noexec,nosuid,nodev  0  2
/dev/sda6  /var/tmp  ext4  defaults,noexec,nosuid,nodev  0  2
/dev/sda7  /home     ext4  defaults,nosuid,nodev         0  2

Mount options explained:

Option Description Use Case
noexec Don't allow execution /tmp, /var/tmp
nosuid Ignore SUID/SGID bits /tmp, /home
nodev Don't allow device files /tmp, /home
ro Read-only /boot, /usr
relatime Update access times efficiently Performance

Kernel Hardening

Configure kernel parameters:

sudo nano /etc/sysctl.conf

Recommended sysctl settings:

# IP forwarding (disable if not a router)
net.ipv4.ip_forward = 0

# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0

# Don't send ICMP redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Enable SYN cookies (SYN flood protection)
net.ipv4.tcp_syncookies = 1

# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# Ignore ping requests
net.ipv4.icmp_echo_ignore_all = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Ignore bogus ICMP error responses
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Enable TCP/IP SYN cookies
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5

# Enable reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Increase system file descriptor limit
fs.file-max = 65535

# Allow for more PIDs
kernel.pid_max = 65536

# Restrict core dumps
fs.suid_dumpable = 0
kernel.core_uses_pid = 1

# Restrict access to kernel logs
kernel.dmesg_restrict = 1

# Hide kernel pointers
kernel.kptr_restrict = 2

# Restrict kernel performance events
kernel.perf_event_paranoid = 3

# Prevent unprivileged users from loading eBPF programs
kernel.unprivileged_bpf_disabled = 1

# Enable address space layout randomization (ASLR)
kernel.randomize_va_space = 2

Apply sysctl settings:

# Apply settings immediately
sudo sysctl -p

# Verify settings
sysctl net.ipv4.ip_forward
sysctl -a | grep accept_source_route

AppArmor

AppArmor provides mandatory access control (MAC) security.

AppArmor management:

# Check AppArmor status
sudo aa-status

# Enable AppArmor profile
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx

# Set profile to complain mode (log violations but don't enforce)
sudo aa-complain /etc/apparmor.d/usr.sbin.nginx

# Disable profile
sudo aa-disable /etc/apparmor.d/usr.sbin.nginx

# Reload all profiles
sudo systemctl reload apparmor

# View profile
cat /etc/apparmor.d/usr.sbin.nginx

# Generate profile from logs
sudo aa-logprof

# Update profiles
sudo aa-update

Create custom AppArmor profile:

sudo nano /etc/apparmor.d/usr.local.bin.myapp
#include <tunables/global>

/usr/local/bin/myapp {
  #include <abstractions/base>

  # Allow network access
  network inet stream,
  network inet6 stream,

  # Allow reading configuration
  /etc/myapp/** r,

  # Allow reading and writing data directory
  /var/lib/myapp/** rw,

  # Allow reading shared libraries
  /lib/** mr,
  /usr/lib/** mr,

  # Allow executing the binary
  /usr/local/bin/myapp mr,

  # Deny everything else
}
# Load profile
sudo apparmor_parser -r /etc/apparmor.d/usr.local.bin.myapp

# Set to enforce mode
sudo aa-enforce /etc/apparmor.d/usr.local.bin.myapp

Security Auditing

Lynis

Lynis is a security auditing tool for Unix-based systems.

Install Lynis:

sudo apt install lynis

Run security audit:

# Full system audit
sudo lynis audit system

# Audit with specific tests
sudo lynis audit system --tests-from-group security

# Save report
sudo lynis audit system --report-file /tmp/lynis-report.txt

# View report
cat /var/log/lynis-report.dat

# View warnings
grep Warning /var/log/lynis.log

Rootkit Detection

Install and use rkhunter:

# Install rkhunter
sudo apt install rkhunter

# Update definitions
sudo rkhunter --update

# Run scan
sudo rkhunter --check

# Check specific directories
sudo rkhunter --check --sk --disable none /usr /etc

# View report
cat /var/log/rkhunter.log

Install and use chkrootkit:

# Install chkrootkit
sudo apt install chkrootkit

# Run scan
sudo chkrootkit

# Check specific items
sudo chkrootkit -q

File Integrity Monitoring

Install and configure AIDE:

# Install AIDE
sudo apt install aide aide-common

# Initialize database
sudo aideinit

# Move database to proper location
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Run check
sudo aide --check

# Update database after legitimate changes
sudo aide --update
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Configure AIDE:

sudo nano /etc/aide/aide.conf
# Directories to monitor
/bin R+b+sha256
/sbin R+b+sha256
/usr/bin R+b+sha256
/usr/sbin R+b+sha256
/lib R+b+sha256
/etc R+b+sha256

# Exclude directories
!/var/log
!/var/cache
!/tmp
!/proc
!/sys

# Rules:
# R = Read-only files
# p = Permissions
# i = inode
# n = Number of links
# u = User
# g = Group
# s = Size
# b = Block count
# m = Modification time
# a = Access time
# c = Change time
# S = Check for growing size
# sha256 = SHA-256 checksum

Server Configuration

This section covers common server configurations for web servers, databases, and other services.

Web Servers

Apache HTTP Server

Install Apache:

sudo apt install apache2

Essential Apache commands:

Command Purpose
systemctl start apache2 Start Apache
systemctl stop apache2 Stop Apache
systemctl restart apache2 Restart Apache
systemctl reload apache2 Reload configuration
systemctl status apache2 Check status
apache2ctl -t Test configuration
apache2ctl -S Show virtual hosts
a2ensite sitename Enable site
a2dissite sitename Disable site
a2enmod modname Enable module
a2dismod modname Disable module

Basic virtual host configuration:

sudo nano /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined

    # Security headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
</VirtualHost>

Enable site:

# Create document root
sudo mkdir -p /var/www/example.com/public_html
sudo chown -R www-data:www-data /var/www/example.com

# Enable site
sudo a2ensite example.com

# Enable required modules
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod ssl

# Test configuration
sudo apache2ctl -t

# Reload Apache
sudo systemctl reload apache2

SSL/TLS Configuration with Let's Encrypt:

# Install Certbot
sudo apt install certbot python3-certbot-apache

# Obtain certificate
sudo certbot --apache -d example.com -d www.example.com

# Test renewal
sudo certbot renew --dry-run

# Auto-renewal is configured via systemd timer
systemctl list-timers | grep certbot

Apache performance tuning:

sudo nano /etc/apache2/mods-available/mpm_prefork.conf
<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers          5
    MaxSpareServers          10
    MaxRequestWorkers        150
    MaxConnectionsPerChild   3000
</IfModule>

Nginx

Install Nginx:

sudo apt install nginx

Essential Nginx commands:

Command Purpose
systemctl start nginx Start Nginx
systemctl stop nginx Stop Nginx
systemctl restart nginx Restart Nginx
systemctl reload nginx Reload configuration
systemctl status nginx Check status
nginx -t Test configuration
nginx -T Test and dump configuration
nginx -s reload Reload configuration

Basic server block configuration:

sudo nano /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.html index.htm index.php;

    # Logging
    access_log /var/log/nginx/example.com-access.log;
    error_log /var/log/nginx/example.com-error.log;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Main location
    location / {
        try_files $uri $uri/ =404;
    }

    # PHP-FPM configuration
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny access to hidden files
    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Cache static files
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

Enable server block:

# Create document root
sudo mkdir -p /var/www/example.com
sudo chown -R www-data:www-data /var/www/example.com

# Enable site
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

SSL/TLS Configuration:

# Install Certbot
sudo apt install certbot python3-certbot-nginx

# Obtain certificate
sudo certbot --nginx -d example.com -d www.example.com

Nginx SSL configuration:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    # SSL certificates
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # SSL protocols and ciphers
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;

    # SSL session cache
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    root /var/www/example.com;
    index index.html index.htm index.php;

    # ... rest of configuration ...
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

Nginx performance tuning:

sudo nano /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /run/nginx.pid;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

http {
    # Basic settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    # File size limits
    client_max_body_size 64M;
    client_body_buffer_size 128k;

    # Buffer sizes
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    # Include other configurations
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Database Servers

MariaDB/MySQL

Install MariaDB:

sudo apt install mariadb-server mariadb-client

Secure installation:

sudo mysql_secure_installation

Answer the prompts:

  • Set root password: Yes
  • Remove anonymous users: Yes
  • Disallow root login remotely: Yes
  • Remove test database: Yes
  • Reload privilege tables: Yes

Essential MySQL/MariaDB commands:

Command Purpose Example
systemctl start mariadb Start database
systemctl stop mariadb Stop database
systemctl restart mariadb Restart database
systemctl status mariadb Check status
mysql -u root -p Connect to database
mysqldump Backup database mysqldump -u root -p database > backup.sql
mysql Restore database mysql -u root -p database < backup.sql

Database management:

# Connect to MySQL
sudo mysql -u root -p

# Or without password (using socket authentication)
sudo mysql

Common SQL commands:

-- Create database
CREATE DATABASE myapp;

-- Create user
CREATE USER 'myappuser'@'localhost' IDENTIFIED BY 'strongpassword';

-- Grant privileges
GRANT ALL PRIVILEGES ON myapp.* TO 'myappuser'@'localhost';

-- Specific privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON myapp.* TO 'myappuser'@'localhost';

-- Grant remote access
CREATE USER 'myappuser'@'%' IDENTIFIED BY 'strongpassword';
GRANT ALL PRIVILEGES ON myapp.* TO 'myappuser'@'%';

-- Reload privileges
FLUSH PRIVILEGES;

-- Show databases
SHOW DATABASES;

-- Show users
SELECT User, Host FROM mysql.user;

-- Show grants
SHOW GRANTS FOR 'myappuser'@'localhost';

-- Drop user
DROP USER 'myappuser'@'localhost';

-- Drop database
DROP DATABASE myapp;

-- Change user password
ALTER USER 'myappuser'@'localhost' IDENTIFIED BY 'newpassword';

-- Show tables
USE myapp;
SHOW TABLES;

-- Describe table
DESCRIBE tablename;

-- Show table status
SHOW TABLE STATUS;

-- Show processes
SHOW PROCESSLIST;

-- Kill process
KILL processid;

Configure MariaDB:

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Performance tuning:

[mysqld]
# Basic settings
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp

# Bind address (0.0.0.0 for remote access, 127.0.0.1 for local only)
bind-address = 127.0.0.1

# Character set
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# InnoDB settings
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1

# Query cache (disabled in MariaDB 10.5+)
# query_cache_type = 1
# query_cache_size = 128M

# Connection settings
max_connections = 100
max_connect_errors = 1000
max_allowed_packet = 64M

# Table cache
table_open_cache = 4000

# Temporary tables
tmp_table_size = 64M
max_heap_table_size = 64M

# Thread cache
thread_cache_size = 50

# Logging
log_error = /var/log/mysql/error.log
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

# Binary logging (for replication)
# log_bin = /var/log/mysql/mariadb-bin
# log_bin_index = /var/log/mysql/mariadb-bin.index
# expire_logs_days = 10
# max_binlog_size = 100M

Database backup script:

#!/bin/bash

# Configuration
BACKUP_DIR="/var/backups/mysql"
MYSQL_USER="root"
MYSQL_PASSWORD="your_password"
RETENTION_DAYS=7

# Create backup directory
mkdir -p $BACKUP_DIR

# Get current date
DATE=$(date +%Y-%m-%d-%H%M%S)

# Backup all databases
mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD --all-databases --single-transaction --quick --lock-tables=false > $BACKUP_DIR/all-databases-$DATE.sql

# Compress backup
gzip $BACKUP_DIR/all-databases-$DATE.sql

# Remove old backups
find $BACKUP_DIR -name "*.sql.gz" -mtime +$RETENTION_DAYS -delete

# Log
echo "Backup completed: all-databases-$DATE.sql.gz"

PostgreSQL

Install PostgreSQL:

sudo apt install postgresql postgresql-contrib

PostgreSQL management:

# Connect as postgres user
sudo -u postgres psql

# Connect to specific database
sudo -u postgres psql -d database_name

# Run SQL file
sudo -u postgres psql -d database_name -f script.sql

Common PostgreSQL commands:

-- Create database
CREATE DATABASE myapp;

-- Create user
CREATE USER myappuser WITH PASSWORD 'strongpassword';

-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE myapp TO myappuser;

-- List databases
\l

-- Connect to database
\c myapp

-- List tables
\dt

-- Describe table
\d tablename

-- List users
\du

-- Quit
\q

-- Drop database
DROP DATABASE myapp;

-- Drop user
DROP USER myappuser;

-- Change password
ALTER USER myappuser WITH PASSWORD 'newpassword';

Configure PostgreSQL:

# PostgreSQL configuration
sudo nano /etc/postgresql/15/main/postgresql.conf

# Client authentication
sudo nano /etc/postgresql/15/main/pg_hba.conf

PostgreSQL backup:

# Backup single database
sudo -u postgres pg_dump myapp > myapp_backup.sql

# Backup all databases
sudo -u postgres pg_dumpall > all_databases_backup.sql

# Restore database
sudo -u postgres psql myapp < myapp_backup.sql

# Restore all databases
sudo -u postgres psql -f all_databases_backup.sql

Troubleshooting

Common Issues and Solutions

Boot Issues

Issue: System won't boot

Solution 1: Use recovery mode

# Reboot and select "Advanced options" in GRUB
# Select "Recovery mode"
# Select "root - Drop to root shell prompt"

# Mount filesystem as read-write
mount -o remount,rw /

# Check and repair filesystem
fsck -y /dev/sda1

# Update GRUB
update-grub

# Reboot
reboot

Solution 2: Boot from live USB

# Boot from Debian live USB
# Mount the system partition
sudo mount /dev/sda1 /mnt

# Mount other necessary filesystems
sudo mount --bind /dev /mnt/dev
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys

# Chroot into system
sudo chroot /mnt

# Fix GRUB
update-grub
grub-install /dev/sda

# Exit and reboot
exit
sudo reboot

Issue: GRUB rescue mode

# Find boot partition
grub rescue> ls
# Output: (hd0) (hd0,gpt1) (hd0,gpt2) ...

# Check each partition
grub rescue> ls (hd0,gpt1)/
grub rescue> ls (hd0,gpt2)/boot

# Set correct partition (example: hd0,gpt2)
grub rescue> set prefix=(hd0,gpt2)/boot/grub
grub rescue> set root=(hd0,gpt2)
grub rescue> insmod normal
grub rescue> normal

# After booting, reinstall GRUB
sudo update-grub
sudo grub-install /dev/sda

Network Issues

Issue: No network connectivity

Diagnosis:

# Check interface status
ip link show

# Check IP address
ip addr show

# Check routing table
ip route show

# Check DNS
cat /etc/resolv.conf

# Test connectivity
ping -c 4 8.8.8.8
ping -c 4 google.com

# Check if interface is up
sudo ip link set eth0 up

# Request DHCP address
sudo dhclient eth0

Issue: DNS not resolving

# Check resolv.conf
cat /etc/resolv.conf

# Manually set DNS
sudo nano /etc/resolv.conf
nameserver 8.8.8.8
nameserver 1.1.1.1
# If using NetworkManager
sudo nano /etc/NetworkManager/NetworkManager.conf

Add:

[main]
dns=none
# Restart NetworkManager
sudo systemctl restart NetworkManager

Issue: Slow network

# Check network statistics
ss -s

# Check packet loss
mtr google.com

# Check interface errors
ip -s link show eth0

# Disable IPv6 if causing issues
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1

Package Management Issues

Issue: Broken packages

# Fix broken dependencies
sudo apt --fix-broken install

# Reconfigure packages
sudo dpkg --configure -a

# Clean package cache
sudo apt clean
sudo apt autoclean

# Remove and reinstall package
sudo apt remove --purge package-name
sudo apt install package-name

# Force remove package
sudo dpkg --remove --force-remove-reinstreq package-name

Issue: Repository issues

# Update package lists
sudo apt update

# If signature issues
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys KEY_ID

# Clear cache
sudo rm -rf /var/lib/apt/lists/*
sudo apt update

# Check sources.list
cat /etc/apt/sources.list
ls /etc/apt/sources.list.d/

Issue: Held packages

# Show held packages
apt-mark showhold

# Unhold package
sudo apt-mark unhold package-name

# Upgrade held package
sudo apt install package-name

Disk Issues

Issue: Disk full

# Check disk usage
df -h

# Find largest directories
sudo du -h --max-depth=1 / | sort -hr | head -20

# Check inode usage
df -i

# Clean package cache
sudo apt clean

# Remove old kernels
sudo apt autoremove

# Clean journal logs
sudo journalctl --vacuum-size=100M

# Find large files
sudo find / -type f -size +100M -exec ls -lh {} \;

# Remove unused Docker images/containers
docker system prune -a

Issue: Filesystem corruption

# Check filesystem (unmount first)
sudo umount /dev/sda1
sudo fsck -y /dev/sda1

# For mounted root filesystem, use recovery mode or live USB

# Check SMART status
sudo apt install smartmontools
sudo smartctl -a /dev/sda

# Run SMART test
sudo smartctl -t long /dev/sda

Performance Issues

High CPU usage:

# Find CPU-intensive processes
top
htop
ps aux --sort=-%cpu | head

# Check load average
uptime
w

# Analyze process
strace -p PID

High memory usage:

# Check memory usage
free -h
vmstat 1

# Find memory-intensive processes
ps aux --sort=-%mem | head

# Check for memory leaks
valgrind --leak-check=full command

# Clear cache (usually not needed)
sudo sync
echo 3 | sudo tee /proc/sys/vm/drop_caches

High disk I/O:

# Install iotop
sudo apt install iotop

# Monitor I/O
sudo iotop

# Check I/O statistics
iostat -x 1

# Check disk read/write
vmstat 1

System Recovery

Backup and Restore

Full system backup:

# Backup system (excluding temporary files)
sudo tar -cvpzf /backup/system-backup-$(date +%Y%m%d).tar.gz \
  --exclude=/backup \
  --exclude=/proc \
  --exclude=/tmp \
  --exclude=/mnt \
  --exclude=/dev \
  --exclude=/sys \
  --exclude=/run \
  --exclude=/media \
  --exclude=/var/log \
  --exclude=/var/cache/apt/archives \
  --exclude=/usr/src/linux-headers* \
  --exclude=/home/*/.cache \
  --exclude=/root/.cache \
  --one-file-system /

# Restore system
sudo tar -xvpzf /backup/system-backup-20240101.tar.gz -C /

Using rsync for incremental backups:

# Backup to external drive
sudo rsync -aAXv \
  --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} \
  / /mnt/backup/

# Restore from backup
sudo rsync -aAXv /mnt/backup/ /

Automated backup script:

#!/bin/bash

BACKUP_SOURCE="/"
BACKUP_DEST="/mnt/backup"
DATE=$(date +%Y-%m-%d)

# Create backup directory
mkdir -p $BACKUP_DEST/$DATE

# Perform backup
rsync -aAXv \
  --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found","/var/cache/*"} \
  --link-dest=$BACKUP_DEST/latest \
  $BACKUP_SOURCE $BACKUP_DEST/$DATE/

# Update latest symlink
rm -f $BACKUP_DEST/latest
ln -s $BACKUP_DEST/$DATE $BACKUP_DEST/latest

# Keep only last 7 days
find $BACKUP_DEST -maxdepth 1 -type d -mtime +7 -exec rm -rf {} \;

echo "Backup completed: $DATE"

Advanced Topics

Containerization with Docker

Install Docker:

# Install dependencies
sudo apt install apt-transport-https ca-certificates curl gnupg lsb-release

# Add Docker GPG key
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker repository
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-compose-plugin

# Add user to docker group
sudo usermod -aG docker $USER

# Verify installation
docker --version
docker run hello-world

Essential Docker commands:

Command Purpose Example
docker ps List running containers docker ps -a
docker images List images docker images
docker run Run container docker run -d -p 80:80 nginx
docker stop Stop container docker stop container_id
docker start Start container docker start container_id
docker restart Restart container docker restart container_id
docker rm Remove container docker rm container_id
docker rmi Remove image docker rmi image_id
docker exec Execute command docker exec -it container_id bash
docker logs View logs docker logs -f container_id
docker pull Pull image docker pull nginx:latest
docker push Push image docker push username/image:tag
docker build Build image docker build -t myimage .

Example Dockerfile:

FROM debian:bookworm-slim

# Install dependencies
RUN apt-get update && apt-get install -y \
    nginx \
    php-fpm \
    php-mysql \
    && rm -rf /var/lib/apt/lists/*

# Copy configuration
COPY nginx.conf /etc/nginx/nginx.conf
COPY php.ini /etc/php/8.2/fpm/php.ini

# Copy application
COPY app/ /var/www/html/

# Set permissions
RUN chown -R www-data:www-data /var/www/html

# Expose ports
EXPOSE 80 443

# Start services
CMD service php8.2-fpm start && nginx -g 'daemon off;'

Docker Compose example:

version: '3.8'

services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./html:/usr/share/nginx/html:ro
    depends_on:
      - php
    networks:
      - app-network

  php:
    image: php:8.2-fpm
    volumes:
      - ./html:/var/www/html:ro
    networks:
      - app-network

  db:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_DATABASE: myapp
      MYSQL_USER: myappuser
      MYSQL_PASSWORD: myapppassword
    volumes:
      - db-data:/var/lib/mysql
    networks:
      - app-network

volumes:
  db-data:

networks:
  app-network:
    driver: bridge

Virtualization with KVM

Install KVM:

# Check if CPU supports virtualization
egrep -c '(vmx|svm)' /proc/cpuinfo

# Install KVM packages
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager

# Add user to groups
sudo usermod -aG libvirt $USER
sudo usermod -aG kvm $USER

# Verify installation
sudo systemctl status libvirtd
virsh list --all

Create virtual machine:

# Download ISO
wget https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-12.0.0-amd64-netinst.iso

# Create VM
virt-install \
  --name debian-vm \
  --ram 2048 \
  --disk path=/var/lib/libvirt/images/debian-vm.qcow2,size=20 \
  --vcpus 2 \
  --os-variant debian11 \
  --network bridge=virbr0 \
  --graphics vnc,listen=0.0.0.0 \
  --cdrom /path/to/debian-12.0.0-amd64-netinst.iso

# List VMs
virsh list --all

# Start VM
virsh start debian-vm

# Connect to console
virsh console debian-vm

# Shutdown VM
virsh shutdown debian-vm

# Force stop VM
virsh destroy debian-vm

# Delete VM
virsh undefine debian-vm
rm /var/lib/libvirt/images/debian-vm.qcow2

Configuration Management

Ansible

Install Ansible:

sudo apt install ansible

Basic inventory file:

[webservers]
web1.example.com
web2.example.com

[databases]
db1.example.com

[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/id_rsa

Example playbook:

---
- name: Configure web servers
  hosts: webservers
  become: yes
  
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600
    
    - name: Install Nginx
      apt:
        name: nginx
        state: present
    
    - name: Start and enable Nginx
      systemd:
        name: nginx
        state: started
        enabled: yes
    
    - name: Copy configuration file
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Reload Nginx
    
    - name: Copy website files
      copy:
        src: files/html/
        dest: /var/www/html/
        owner: www-data
        group: www-data
        mode: '0644'
  
  handlers:
    - name: Reload Nginx
      systemd:
        name: nginx
        state: reloaded

Run playbook:

ansible-playbook -i inventory.ini playbook.yml

Monitoring and Metrics

Prometheus and Grafana

Install Prometheus:

# Create prometheus user
sudo useradd --no-create-home --shell /bin/false prometheus

# Download Prometheus
cd /tmp
wget https://github.com/prometheus/prometheus/releases/download/v2.45.0/prometheus-2.45.0.linux-amd64.tar.gz
tar xvf prometheus-2.45.0.linux-amd64.tar.gz
cd prometheus-2.45.0.linux-amd64

# Copy files
sudo cp prometheus promtool /usr/local/bin/
sudo cp -r consoles console_libraries /etc/prometheus/

# Create configuration
sudo nano /etc/prometheus/prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']
  
  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9100']

Create systemd service:

sudo nano /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/usr/local/bin/prometheus \
  --config.file=/etc/prometheus/prometheus.yml \
  --storage.tsdb.path=/var/lib/prometheus/ \
  --web.console.templates=/etc/prometheus/consoles \
  --web.console.libraries=/etc/prometheus/console_libraries

[Install]
WantedBy=multi-user.target

Start Prometheus:

sudo systemctl daemon-reload
sudo systemctl start prometheus
sudo systemctl enable prometheus

This comprehensive guide covers the essential aspects of Debian Linux, from installation and basic system administration to advanced topics like containerization and monitoring


SPONSORED

Sponsored by Dargslan Publishing — Explore our full collection of Linux and DevOps eBooks for self-learners and IT professionals at dargslan.com.


Dargslan - TechBooksPro | Professional IT Books & Programming Guides
Discover professional IT books, programming guides, and technical resources. Expert-authored content covering web development, system administration, and cybersecurity.