Operating Systems

Introduction To Operating Systems

wwww

  1. Operating Systems — Linux, Windows, macOS
  2. The Operating System: The Security Battleground
  3. Part I: Linux (Most Important for Hackers)
    1. What is Linux and Why Is It Important?
      1. Installing Kali Linux in VirtualBox (Step‑by‑Step)
    2. The Linux Command Line (Terminal)
    3. The Linux File System – Understanding the Directory Tree
    4. File Permissions and Ownership – Controlling Access
    5. User and Group Management – Who Can Do What
    6. Processes – What Is Running on the System
    7. System Logs – Recording What Happened
    8. Services (Daemons) – Background Workhorses
    9. Package Management – Installing and Updating Software
    10. Firewall Configuration – Controlling Network Access
    11. SSH Configuration and Hardening
    12. Cron and Scheduled Tasks – Automating Jobs
    13. Practical Linux Security Audit Demo
  4. Part II: Windows and Active Directory
    1. Windows Architecture and Security‑Relevant Components
    2. PowerShell – The Swiss Army Knife for Windows
      1. What is PowerShell Used For?
      2. PowerShell Basics
      3. PowerShell for Security Tasks
    3. Windows Registry – The Configuration Database
    4. Windows Event Logs – The Forensic Trail
      1. What are Event Logs Used For?
    5. Active Directory – The Heart of Windows Domains
      1. What is Active Directory Used For?
      2. Key AD Concepts
      3. Common AD Attacks and Why They Matter
      4. Enumerating Active Directory (command line and PowerShell)
    6. NTFS Permissions – File System Access Control
      1. What are NTFS Permissions Used For?
  5. Part III: macOS (Increasingly Targeted)
    1. Introduction to macOS Security
    2. macOS File System and Important Directories
    3. macOS Command Line (Terminal)
      1. What is the Terminal Used For?
    4. macOS Security Features Relevant to Attackers
    5. macOS Penetration Testing Considerations
    6. Practical macOS Security Audit Demo
  6. Summary and Comparison Table
  7. What to Do Next

Operating Systems — Linux, Windows, macOS

The Operating System: The Security Battleground

Every cyberattack ultimately executes on an operating system. When an attacker exploits a vulnerability, escalates privileges, installs malware, or exfiltrates data, all of these actions are mediated by the OS. The files they read, the processes they manipulate, the accounts they abuse, and the logs they attempt to clear — all of it depends on the underlying OS. A security professional who does not understand operating systems at a deep level is working blind.

An Operating System (OS) is the fundamental software that controls your computer hardware and allows you to interact with it. It manages memory, processes, storage, and peripherals. It also provides a user interface and a platform for applications to run. Without an OS, your computer is just a collection of electronic components.

Why this matters in cybersecurity: Every attack, every security tool, and every compromised system runs on some OS. If you don’t understand how the OS works, you cannot understand how to hack it or how to defend it.

This chapter covers three major operating systems in depth, with a focus on practical, hands‑on skills:

  • Linux — the backbone of the internet and the preferred platform for security tools. We cover its architecture, file system, permissions, essential commands, user management, process control, logging, and services.
  • Windows — the dominant OS in corporate environments and the primary target of real‑world attacks. We cover its architecture, registry, command line, PowerShell, and Active Directory.
  • macOS — increasingly used in development and business, with its own security mechanisms. We cover its Unix foundation, key directories, built‑in security features, and reconnaissance commands.

The emphasis is practical: each concept is introduced alongside the commands that demonstrate it. By the end of this chapter you will be able to navigate, read, modify, and administer all three systems from the command line — the foundational skill for every security professional.

Part I: Linux (Most Important for Hackers)

What is Linux and Why Is It Important?

Linux is an open‑source operating system modelled on Unix. It is used on the majority of servers, embedded devices, and supercomputers. For hackers and security professionals, Linux is essential because:

  • It offers complete control over the system.
  • Almost all security tools (e.g., Nmap, Metasploit, Wireshark) are developed for Linux first.
  • It is free and runs on a wide range of hardware.
  • Its command‑line interface is powerful and scriptable.

The Linux Kernel: The core of Linux is the kernel, which manages hardware resources (CPU, memory, storage, network) and provides a secure interface for applications. Everything else — system libraries, utilities, and user interfaces — is built on top of this kernel.

Linux Distributions: A distribution (or distro) is a complete operating system that packages the Linux kernel with a package manager, system tools, and desktop environment. Common distributions include Ubuntu, Debian, CentOS, Fedora, and for security work, Kali Linux and Parrot OS.

For this course, we use Kali Linux — a Debian‑based distribution designed specifically for penetration testing. It comes pre‑installed with over 600 security tools. We recommend running Kali in a virtual machine (VirtualBox or VMware) to isolate it from your host system.

Installing Kali Linux in VirtualBox (Step‑by‑Step)

  1. Download VirtualBox from virtualbox.org and install it.
  2. Download the Kali Linux VirtualBox image from kali.org (the .ova file).
  3. Import the appliance in VirtualBox: File → Import Appliance, select the .ova, click Next and then Import.
  4. Start the virtual machine and log in with the default credentials: kali / kali.

You now have a safe, isolated lab environment for all your experiments.

The Linux Command Line (Terminal)

The command line is the most powerful way to interact with Linux. Open the terminal (click the terminal icon or press Ctrl+Alt+T). We will use it throughout this section.

First steps – basic commands:

pwd                     # Print working directory (show where you are)
ls                      # List files and folders in the current directory
cd Desktop              # Change directory to 'Desktop'
touch test.txt          # Create an empty file called test.txt
nano test.txt           # Edit the file (press Ctrl+X, then Y, then Enter to save)
rm test.txt             # Delete the file

The Linux File System – Understanding the Directory Tree

Linux uses a single, unified directory tree starting at the root (/). Every file and folder is located somewhere under this root. Knowing what goes where is crucial for finding configuration files, logs, and user data.

DirectoryPurpose
/The root of the entire file system.
/binEssential user commands (e.g., ls, cp, mv).
/bootBoot loader files, including the Linux kernel.
/devSpecial files representing hardware devices.
/etcSystem‑wide configuration files.
/homePersonal directories for regular users.
/libShared libraries and kernel modules.
/mediaMount points for removable media (USB drives, CD‑ROMs).
/mntTemporary mount points for manual mounts.
/optOptional add‑on software.
/procVirtual file system that provides process and system information.
/rootHome directory of the root (superuser) account.
/sbinSystem administration binaries (mostly for root).
/tmpTemporary files – cleared on reboot.
/usrUser programs, libraries, and documentation.
/varVariable data – logs, spool files, and cache.

Why it matters for security:

  • /etc/passwd and /etc/shadow store user account information and password hashes.
  • /var/log contains system and application logs that record security events.
  • /tmp is writable by all users and can be used by attackers to drop files.
  • /home directories may contain SSH keys, browser history, and other sensitive data.

Practical commands to explore the file system:

# View the contents of the most important files
cat /etc/passwd                     # List all user accounts (each line: username:password:UID:GID:...)
cat /etc/shadow                     # Password hashes (requires root) – only root can read this
cat /etc/group                      # Group definitions
ls -la /home                        # List all user home directories

# View command history (often reveals accidentally typed passwords)
cat ~/.bash_history                 # History of commands executed by the current user

# Monitor authentication logs in real time
tail -f /var/log/auth.log           # On Debian/Ubuntu – watch failed login attempts
tail -f /var/log/secure             # On RHEL/CentOS – same purpose

File Permissions and Ownership – Controlling Access

Every file and directory has an owner (a user), a group, and a set of permissions for the owner, the group, and all other users. Permissions are: read (r), write (w), and execute (x). The numeric values for these permissions are 4, 2, and 1 respectively.

Why it matters for security: Incorrect permissions can allow unauthorised users to read sensitive data, modify system files, or execute malicious code.

Viewing permissions: ls -l displays a string like -rw-r--r--.

CharacterMeaning
First char- file, d directory, l symbolic link
Next threeOwner permissions (r/w/x)
Next threeGroup permissions
Last threeOthers permissions

Changing permissions with chmod:

# Numeric method (sum of 4, 2, 1)
chmod 644 myfile.txt    # rw- r-- r--  (owner read+write, group read, others read)
chmod 755 myscript.sh   # rwx r-x r-x  (owner full, group/others read+execute)
chmod 700 secret        # rwx ------   (only owner can read/write/execute)

# Symbolic method
chmod u+x script.sh     # Add execute permission for the owner (u)
chmod g-w file.txt      # Remove write permission for the group (g)
chmod o+r file.txt      # Add read permission for others (o)

Changing owner and group (chown, chgrp):

chown user:group myfile   # Set both owner and group
chown user myfile         # Change owner only
chgrp group myfile        # Change group only

Special permissions (setuid, setgid, sticky bit) – why they matter:

  • setuid (u+s) – when set on an executable, the program runs with the owner’s privileges. Attackers look for setuid root binaries to escalate privileges.
  • setgid (g+s) – similar but inherits the group.
  • sticky bit (o+t) – on directories, only the file owner can delete files inside it (used on /tmp).
# Find all setuid executables (potential privilege escalation vectors)
find / -perm -u=s -type f 2>/dev/null

# Set special permissions
chmod u+s /usr/bin/passwd   # passwd runs as root
chmod g+s /shared           # files created in /shared inherit group
chmod o+t /tmp              # ensure only owners can delete their temp files

User and Group Management – Who Can Do What

Linux is a multi‑user system. Managing users and groups is essential for maintaining the principle of least privilege.

Important user files:

  • /etc/passwd – stores user account information (username, UID, home directory, login shell). The password field is usually an x (the hash is in /etc/shadow).
  • /etc/shadow – contains the actual password hashes (accessible only by root). The format is: username:encrypted_password:last_change:min:max:warn:inactive:expire.

Commands to manage users:

# Create, modify, and delete users
useradd john                  # Create user 'john' with default settings
useradd -m -s /bin/bash john  # Create with home directory and bash shell
passwd john                   # Set or change password for 'john'
usermod -aG sudo john         # Add 'john' to the 'sudo' group (give admin rights)
userdel john                  # Delete user 'john' (use -r to remove home directory)

# View current user and group information
whoami                        # Show the current user name
id john                       # Show UID, GID, and groups for 'john'
groups john                   # Show groups that 'john' belongs to
w                             # Show who is logged in and what they are doing
last                          # Show login history (from /var/log/wtmp)

Managing groups:

groupadd developers            # Create a new group
groupmod -n devs developers    # Rename group 'developers' to 'devs'
groupdel devs                  # Delete group
gpasswd -a john developers     # Add user 'john' to group 'developers'
gpasswd -d john developers     # Remove user 'john' from group 'developers'

Attackers who gain a foothold will attempt to escalate privileges by exploiting misconfigured users, weak passwords, or overly permissive sudo rules. sudo -l shows what commands you can run as root.

Processes – What Is Running on the System

A process is a running instance of a program. Every command you run creates at least one process. Processes have a Process ID (PID) and are owned by a user.

Attackers often leave backdoor processes, cryptocurrency miners, or reverse shells. Knowing how to list and kill processes is essential for incident response.

Viewing processes:

ps aux                       # Show all processes with detailed info (user, PID, CPU%, memory%, command)
ps auxf                      # Tree view – shows parent‑child relationships
ps -ef --forest              # Alternative tree view
top                          # Real‑time interactive process viewer (press 'q' to quit)
htop                         # Improved top (install if not present)
pstree                       # Show process tree (text)
ps -u john                   # Show processes owned by user 'john'
ps -eo pid,user,comm,%cpu,%mem   # Custom output columns

Managing processes (signals):

kill 1234                    # Send SIGTERM (terminate gracefully) to PID 1234
kill -9 1234                 # Send SIGKILL (force kill) – use only if necessary
killall process_name         # Kill all processes by name (e.g., killall firefox)
pkill pattern                # Kill processes whose command matches a pattern

Running processes in the background:

long_running_task &          # Start the task and put it in the background
jobs                         # List background jobs
fg %1                        # Bring job number 1 to the foreground
bg %1                        # Resume job number 1 in the background

System Logs – Recording What Happened

Log files are the primary source of forensic information. They record authentication attempts, system errors, service starts/stops, and more.

Traditional log files (varies by distribution):

FilePurpose
/var/log/messagesGeneral system messages (RHEL/CentOS)
/var/log/syslogSystem logging (Ubuntu/Debian)
/var/log/auth.logAuthentication events (Ubuntu/Debian)
/var/log/secureAuthentication events (RHEL/CentOS)
/var/log/kern.logKernel messages
/var/log/dmesgBoot‑time messages
/var/log/boot.logBoot process log
/var/log/cronCron job logs

Commands to read logs:

# View entire log
cat /var/log/auth.log

# View live updates (like `tail -f`)
tail -f /var/log/auth.log         # Watch new authentication events

# Search for specific patterns
grep "Failed password" /var/log/auth.log    # Find failed login attempts
grep "Accepted password" /var/log/auth.log  # Find successful logins

# Combine with other tools
grep -i "error" /var/log/syslog | less

Journalctl (for systems using systemd):

journalctl                       # View all journal entries
journalctl -f                    # Follow live logs (like `tail -f`)
journalctl -u sshd               # Show logs for the SSH service only
journalctl --since "1 hour ago"  # Filter by time
journalctl -p err                # Show only error‑level messages
journalctl _PID=1234             # Filter by process ID

Services (Daemons) – Background Workhorses

Services (also called daemons) are programs that run in the background waiting for requests – for example, a web server (Apache/nginx), an SSH server, or a database. Managing services is a core system administration task.

Unnecessary services increase the attack surface. Attackers often install new services for persistence (e.g., cron jobs, backdoor daemons).

Systemd is the default init system on most modern Linux distributions. Use systemctl to manage services.

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

# Check the status of a service
systemctl status sshd

# Start, stop, restart, and reload
sudo systemctl start sshd
sudo systemctl stop sshd
sudo systemctl restart sshd
sudo systemctl reload sshd        # Reload configuration without restarting

# Enable/disable at boot
sudo systemctl enable sshd        # Start automatically on boot
sudo systemctl disable sshd       # Do not start automatically

# View logs for a service
journalctl -u sshd

Package Management – Installing and Updating Software

Package managers simplify the installation, updating, and removal of software. Different distributions use different tools.

APT (Debian/Ubuntu):

sudo apt update                   # Refresh package lists from repositories
sudo apt upgrade                  # Upgrade all installed packages
sudo apt install nginx            # Install the nginx package
sudo apt remove nginx             # Remove but keep configuration files
sudo apt purge nginx              # Remove completely (including configs)
sudo apt search nginx             # Search for packages containing "nginx"
sudo apt show nginx               # Show detailed information about the package
apt list --installed              # List all installed packages

DNF (RHEL/CentOS/Fedora) – similar to APT:

sudo dnf install nginx
sudo dnf remove nginx
sudo dnf update
sudo dnf search nginx

pip (Python package manager):

pip install requests              # Install Python package
pip install requests==2.25.1      # Specific version
pip install --upgrade requests    # Upgrade to latest
pip uninstall requests            # Uninstall
pip freeze > requirements.txt     # Export list of installed packages
pip install -r requirements.txt   # Install from a requirements file

Firewall Configuration – Controlling Network Access

A firewall filters incoming and outgoing network traffic based on rules. On Linux, common tools include UFW (Uncomplicated Firewall) and iptables (legacy).

UFW (Ubuntu/Debian):

sudo ufw enable                   # Turn on the firewall
sudo ufw disable                  # Turn off (not recommended)
sudo ufw default deny incoming    # Drop all incoming connections by default
sudo ufw default allow outgoing   # Allow all outgoing by default
sudo ufw allow 22/tcp             # Allow incoming SSH (port 22)
sudo ufw allow 80/tcp             # Allow HTTP (port 80)
sudo ufw allow 443/tcp            # Allow HTTPS (port 443)
sudo ufw allow from 192.168.1.0/24   # Allow all traffic from the local network
sudo ufw deny from 203.0.113.0/24    # Block a specific subnet
sudo ufw status verbose           # Show current rules and status
sudo ufw reset                    # Reset to factory defaults

iptables (more low‑level, works on all distributions):

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

# Set default policies (drop incoming, drop forwarded, allow outgoing)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# Allow SSH and established connections
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Save and restore rules (persistent)
sudo iptables-save > /etc/iptables/rules.v4
sudo iptables-restore < /etc/iptables/rules.v4

SSH Configuration and Hardening

SSH (Secure Shell) is the standard method for remote administration. Securing SSH is critical to prevent unauthorised access.

Configuration file: /etc/ssh/sshd_config. Common hardening options:

Port 2222                         # Change from default port 22 to reduce automated attacks
PermitRootLogin no                # Never allow root to log in directly
PasswordAuthentication no         # Disable password‑based login (use keys only)
PubkeyAuthentication yes          # Require public key authentication
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3                    # Limit failed login attempts
MaxSessions 2                     # Limit concurrent sessions
ClientAliveInterval 300           # Disconnect idle clients after 5 minutes
LogLevel VERBOSE                  # Log more details
AllowUsers alice bob              # Only allow specific users
Protocol 2                        # Only use SSH v2 (disable v1)

Key management:

# Generate a new SSH key pair (Ed25519 is recommended)
ssh-keygen -t ed25519

# Copy the public key to a server
ssh-copy-id user@server

# Manual copy (if ssh-copy-id is unavailable)
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Set correct permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Cron and Scheduled Tasks – Automating Jobs

Cron is a time‑based job scheduler on Linux. It runs commands at specified times or intervals. This is essential for routine maintenance, but also for attackers who use cron to maintain persistence.

What is Cron used for?

  • System backups and log rotation.
  • Regular updates and security scans.
  • Monitoring scripts.
  • Attackers use it to re‑establish access (persistence) or to run malicious scripts periodically.

Why it matters for security: Attackers often add malicious cron jobs to re‑establish access after a system reboot or to periodically run scripts. Regularly checking cron entries is part of a good forensic routine.

Cron syntax:

┌─────────── minute (0–59)
│ ┌───────── hour (0–23)
│ │ ┌─────── day of month (1–31)
│ │ │ ┌───── month (1–12)
│ │ │ │ ┌─── day of week (0–7, Sunday=0 or 7)
│ │ │ │ │
* * * * * command_to_run

Managing cron jobs:

crontab -l                    # List cron jobs for the current user
crontab -e                    # Edit cron jobs for the current user
crontab -r                    # Remove all cron jobs for the current user

# System‑wide cron jobs (require root)
cat /etc/crontab              # View system crontab file
ls /etc/cron.d/               # Additional system cron directories
ls /etc/cron.daily/           # Daily scripts
ls /etc/cron.hourly/          # Hourly scripts
ls /etc/cron.weekly/          # Weekly scripts
ls /etc/cron.monthly/         # Monthly scripts

Practical cron examples with explanations:

# Run a backup script every 5 minutes
*/5 * * * * /home/user/backup.sh
# This is useful for frequent, small backups or monitoring tasks.

# Run a full backup at 2:30 AM every day when system load is low
30 2 * * * /usr/local/bin/full_backup
# Daily maintenance tasks are typically scheduled during off‑peak hours.

# Generate a weekly report every Sunday at midnight
0 0 * * 0 /usr/bin/weekly_report
# Weekly reports are often scheduled for the start of the week.

# Run a monthly cleanup on the 1st of each month at 3 PM
0 15 1 * * /usr/bin/cleanup_old_logs
# Monthly tasks are scheduled on the first day of the month.

# Start a monitoring service at system boot
@reboot /usr/bin/start_monitoring
# @reboot ensures the command runs every time the system starts.

Finding suspicious cron jobs (security perspective):

# Look for cron entries that reference unusual paths or encoded commands
crontab -l | grep -v "^#" | grep -v "^$"   # Show non‑comment, non‑empty entries
grep -r "base64" /etc/cron* ~/cron* 2>/dev/null   # Search for encoded content

# Check for cron jobs that run as root
sudo crontab -l -u root

# Look for suspicious patterns: wget, curl, netcat, reverse shell, base64 decoding
crontab -l | grep -E "wget|curl|nc|base64|bash -i|sh -i"

Practical Linux Security Audit Demo

Here is a small script that combines many of the concepts above to perform a basic system audit. It checks for open ports, SUID binaries, suspicious cron jobs, and failed login attempts.

#!/usr/bin/env python3
import subprocess
import re

def audit_linux():
    print("=== Linux Security Audit ===\n")

    # 1. Check listening ports and their associated services
    print("1. Listening ports (services):")
    result = subprocess.run(["ss", "-tulpn"], capture_output=True, text=True)
    lines = result.stdout.split("\n")[1:]  # skip header
    for line in lines:
        if line.strip():
            print("  " + line)

    # 2. Find SUID files (potential privilege escalation)
    print("\n2. SUID binaries (potential privesc):")
    result = subprocess.run(["find", "/", "-perm", "-u=s", "-type", "f"], 
                            capture_output=True, text=True, timeout=10)
    suid_files = result.stdout.split("\n")[:20]  # limit output
    for f in suid_files:
        if f:
            print("  " + f)

    # 3. Show current user's crontab
    print("\n3. Current user's cron jobs:")
    result = subprocess.run(["crontab", "-l"], capture_output=True, text=True)
    if result.returncode == 0:
        lines = result.stdout.split("\n")
        for line in lines:
            if line.strip() and not line.startswith("#"):
                print("  " + line)
    else:
        print("  No cron jobs for this user.")

    # 4. Check failed login attempts from auth.log
    print("\n4. Recent failed login attempts:")
    try:
        with open("/var/log/auth.log", "r") as f:
            lines = f.readlines()[-50:]  # last 50 lines
            for line in lines:
                if "Failed password" in line:
                    print("  " + line.strip())
    except FileNotFoundError:
        print("  /var/log/auth.log not found (maybe using secure log?)")
        try:
            with open("/var/log/secure", "r") as f:
                lines = f.readlines()[-50:]
                for line in lines:
                    if "Failed password" in line:
                        print("  " + line.strip())
        except FileNotFoundError:
            print("  Log file not accessible.")

if __name__ == "__main__":
    audit_linux()

Run this script as root or with sufficient permissions to get a comprehensive view of the system’s security posture.

Part II: Windows and Active Directory

Windows Architecture and Security‑Relevant Components

Windows is the dominant desktop OS in corporate environments and the primary target for attackers. Understanding its internals is crucial for penetration testing and incident response.

Key components for security professionals:

  • The Windows Registry – a hierarchical database storing configuration settings for the OS and applications. It is used for persistence (auto‑run entries), security policies, and system information.
  • The Windows Command Prompt (cmd.exe) and PowerShell – command‑line interfaces. PowerShell is especially powerful because it gives access to .NET, WMI, and the Windows API, enabling deep system manipulation.
  • Active Directory (AD) – a directory service that centralises authentication and authorisation for Windows domains. It stores user accounts, passwords, group memberships, and computer objects in a database (NTDS.dit) on domain controllers. Compromising a domain controller gives full control over the entire network.

Basic reconnaissance from the command line (cmd):

whoami                     # Show current user
whoami /priv               # Show privileges of the current user token
net user                   # List local user accounts
net localgroup administrators   # List members of the Administrators group
ipconfig /all              # Show network configuration
netstat -ano               # Show active connections (a=all, n=numeric, o=owning PID)
systeminfo                 # Display OS version, installed patches, domain membership

PowerShell – The Swiss Army Knife for Windows

PowerShell is a scripting language and shell built on .NET. It is used for system administration, automation, and increasingly for attacks (e.g., fileless malware).

What is PowerShell Used For?

  • System administration: Managing users, groups, services, and processes.
  • Automation: Writing scripts for repetitive tasks.
  • Security tasks: Enumerating users, checking logs, modifying firewall rules.
  • Attacks: Attackers use PowerShell for fileless execution, credential theft, and lateral movement.

PowerShell Basics

# Getting help
Get-Help Get-Process -Detailed

# Listing commands
Get-Command
Get-Command *process*

# Variables, arrays, and hash tables
$name = "Alice"
$numbers = @(1,2,3,4,5)
$config = @{"port"=80; "ssl"=$true}

# Conditionals and loops
if ($name -eq "Alice") {
    Write-Host "Hello Alice"
} else {
    Write-Host "Hello stranger"
}

foreach ($num in $numbers) {
    $num * 2
}

try {
    Get-Item "C:\nonexistent.txt"
} catch {
    Write-Host "File not found: $_"
}

# Common cmdlets
Get-Service               # List all services
Get-Process               # List all processes
Get-Location              # Show current directory
Set-Location C:\Windows   # Change directory

PowerShell for Security Tasks

# Enumerate users and groups in Active Directory (AD module required)
Get-ADUser -Filter * | Select-Object Name, SamAccountName, Enabled
Get-ADGroup -Filter * | Select-Object Name
Get-ADGroupMember -Identity "Domain Admins"

# If AD module is not installed, use .NET classes
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$domain.DomainControllers | Select-Object Name, IPAddress

# Local users and groups (without AD)
Get-LocalUser
Get-LocalGroup
Get-LocalGroupMember -Group "Administrators"

# Installed software
Get-WmiObject -Class Win32_Product | Select-Object Name, Version

# Network connections and firewall
Get-NetTCPConnection
Get-NetFirewallRule | Select-Object DisplayName, Enabled, Action

# Event log queries
Get-WinEvent -LogName Security -MaxEvents 10
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624}   # Successful logons
Get-WinEvent -FilterXPath *[System[EventID=4625]]              # Failed logons

Example: Find suspicious processes (high CPU, unusual names):

Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
Get-Process | Where-Object { $_.ProcessName -match "crypt|miner|backdoor" }

Windows Registry – The Configuration Database

The Registry is a hierarchical store of settings. It is divided into hives:

HiveDescription
HKEY_LOCAL_MACHINE (HKLM)System‑wide settings
HKEY_CURRENT_USER (HKCU)Settings for the currently logged‑on user
HKEY_CLASSES_ROOT (HKCR)File associations and COM objects
HKEY_USERS (HKU)Profiles for all users on the system
HKEY_CURRENT_CONFIG (HKCC)Hardware profile information

What is the Registry Used For?

  • Storing Windows and application configuration.
  • Controlling startup programs (persistence).
  • Managing security policies (UAC, Windows Defender).
  • Storing user preferences and settings.

Attackers often add persistence via Registry Run keys. Security settings (like UAC, Windows Defender) are also stored here.

Common registry keys of interest:

# Startup persistence (used by malware to maintain access)
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

# Services (attackers may install malicious services)
HKLM\SYSTEM\CurrentControlSet\Services

# Security settings (LSA, UAC)
HKLM\SYSTEM\CurrentControlSet\Control\Lsa
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

# Windows Defender (attackers may try to disable it)
HKLM\SOFTWARE\Policies\Microsoft\Windows Defender

# USB history (forensic evidence)
HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR

Using PowerShell to interact with the Registry:

# View startup items
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"

# Add a startup entry (persistence)
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" `
                 -Name "MyApp" -Value "C:\path\to\app.exe"

# Create a new key
New-Item -Path "HKCU:\SOFTWARE\MySecurityTool"

# Delete a registry value
Remove-ItemProperty -Path "HKCU:\SOFTWARE\MySecurityTool" -Name "Config"

# Export/import (using reg.exe)
reg export HKLM\SOFTWARE\MyApp C:\backup.reg
reg import C:\backup.reg

Windows Event Logs – The Forensic Trail

Windows logs security‑relevant events in the Security log, along with System, Application, and Setup logs. These are essential for detecting attacks.

What are Event Logs Used For?

  • Detecting failed and successful logon attempts.
  • Tracking process creation and service installation.
  • Monitoring changes to user accounts and groups.
  • Forensic investigations after a security incident.

Critical Security Event IDs to know:

Event IDDescription
4624Successful logon
4625Failed logon
4634Logoff
4648Logon with explicit credentials (runas)
4672Special privileges assigned to new logon (administrator)
4688Process creation
4698Scheduled task created
4700Scheduled task enabled
4720User account created
4725User account disabled
4726User account deleted
4732Member added to security‑enabled local group
4740Account locked out
4768Kerberos TGT requested
7045A new service was installed

Querying event logs with PowerShell:

# Get the last 10 security events
Get-WinEvent -LogName Security -MaxEvents 10

# Get all successful logons (ID 4624) in the last 24 hours
$time = (Get-Date).AddHours(-24)
Get-WinEvent -LogName Security -FilterHashtable @{Id=4624; StartTime=$time}

# Use XPath to find failed logons (4625)
Get-WinEvent -LogName Security -FilterXPath "*[System[EventID=4625]]"

# Count events by ID
Get-WinEvent -LogName Security | Group-Object Id | Sort-Object Count -Descending

Active Directory – The Heart of Windows Domains

Active Directory is Microsoft’s directory service. It stores information about users, computers, groups, and other objects in a domain. The domain controller (DC) hosts the database and authenticates users.

What is Active Directory Used For?

  • Centralised user and computer management.
  • Authentication and authorisation using Kerberos.
  • Group Policy for managing settings across the domain.
  • Single sign‑on for users across the network.

Key AD Concepts

  • Domain – a logical group of objects that share a common directory database.
  • Forest – a collection of domains that trust each other.
  • Organizational Unit (OU) – containers for organising objects (like folders).
  • Group Policy – settings that apply to users and computers.
  • Trust – a relationship between domains that allows users from one domain to access resources in another.

Common AD Attacks and Why They Matter

AttackDescriptionWhy It’s Dangerous
KerberoastingExtract service account hashes from the domain and crack them offline.Service accounts often have high privileges and weak passwords.
Golden TicketForge Kerberos Ticket‑Granting Tickets using the KRBTGT hash.Gives the attacker unrestricted access to the entire domain.
Pass‑the‑HashUse an NTLM hash to authenticate without the plaintext password.Allows lateral movement without knowing the actual password.
DCSyncUse replication permissions to pull password hashes from the DC.Exposes all user passwords for offline cracking.
BloodHoundUse graph theory to map attack paths in AD.Identifies the shortest path to domain admin privileges.

Enumerating Active Directory (command line and PowerShell)

Command line (cmd):

net user /domain                     # List all domain users
net group "Domain Admins" /domain    # List domain admins
net group "Domain Controllers" /domain

PowerShell (if the ActiveDirectory module is installed):

Import-Module ActiveDirectory
Get-ADUser -Filter * -Properties * | Select-Object Name, SamAccountName, LastLogonDate, Enabled
Get-ADGroupMember -Identity "Domain Admins"
Get-ADComputer -Filter * | Select-Object Name, OperatingSystem

Without the module, use ADSI:

$adsi = [ADSI]"LDAP://DC=domain,DC=local"
$searcher = New-Object System.DirectoryServices.DirectorySearcher($adsi)
$searcher.FindAll() | ForEach-Object { $_.Properties.name }

NTFS Permissions – File System Access Control

NTFS (New Technology File System) is the default file system for Windows. It provides fine‑grained access control via Access Control Lists (ACLs).

What are NTFS Permissions Used For?

  • Controlling who can read, write, or execute files and folders.
  • Implementing the principle of least privilege.
  • Protecting sensitive data from unauthorised access.

Permission levels:

PermissionEffect
Full ControlAll permissions (including changing permissions and taking ownership)
ModifyRead, write, delete, and execute
Read & ExecuteRead and execute files; list folder contents
List Folder ContentsTraverse folders (inherited only)
ReadView files and attributes
WriteCreate and modify files

Key concepts:

  • SID (Security Identifier) – a unique identifier for a security principal (user, group).
  • ACL (Access Control List) – a list of ACEs.
  • ACE (Access Control Entry) – a single entry that grants or denies a permission to a SID.
  • Inheritance – permissions that propagate from parent folders.

Managing NTFS permissions via PowerShell:

# View ACL of a folder
Get-Acl C:\Data

# Grant a user full control
$acl = Get-Acl C:\Data
$permission = "DOMAIN\john","FullControl","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
$acl.SetAccessRule($accessRule)
Set-Acl C:\Data $acl

# Remove a user's permissions
$acl.RemoveAccessRule($accessRule)
Set-Acl C:\Data $acl

Part III: macOS (Increasingly Targeted)

Introduction to macOS Security

macOS is Apple’s operating system for Mac computers. It is built on Darwin, a Unix‑like kernel, so it shares many command‑line tools with Linux. However, it has its own security architecture:

  • System Integrity Protection (SIP) – prevents even root from modifying critical system files.
  • Gatekeeper – blocks unsigned applications by default.
  • XProtect – Apple’s built‑in malware scanner.
  • FileVault – full‑disk encryption.
  • Apple Silicon (M‑series) – includes a Secure Enclave and hardware‑verified boot.

macOS is common in development, design, and corporate environments, making it an increasingly relevant target for attackers.

macOS File System and Important Directories

macOS uses a Unix‑like hierarchy, with these notable directories:

DirectoryPurpose
/ApplicationsUser‑installed applications (GUI).
/SystemCore operating system files (protected by SIP).
/LibrarySystem‑wide application support, preferences, and logs.
~/LibraryPer‑user application data, caches, preferences, and keychains.
/private/var/logSystem log files (system.log, secure.log).
/etcConfiguration files (symlink to /private/etc).
/tmpTemporary files (cleared on reboot).

Key files of interest for security:

  • /private/var/log/system.log – general system logs.
  • /private/var/log/secure.log – authentication logs.
  • ~/Library/Keychains/ – stores user passwords and certificates (accessible with security command).
  • ~/Library/Preferences/ – user preferences (plist files).

macOS Command Line (Terminal)

The default shell is Zsh (since macOS Catalina). All the basic Unix commands (ls, cd, pwd, grep, find, ps, netstat) work the same as on Linux.

What is the Terminal Used For?

  • Navigating the file system and viewing files.
  • Managing processes and services.
  • Viewing logs and system information.
  • Running security tools and scripts.

Initial reconnaissance commands:

whoami                    # Current user
id                        # User and group IDs
ps aux                    # Running processes
netstat -an | grep LISTEN # Listening ports
sudo dmesg | tail -20     # System messages (requires sudo)
system_profiler SPSoftwareDataType   # macOS version and software info
system_profiler SPHardwareDataType   # Hardware details (chip, RAM)
sysctl -a | grep machdep.cpu         # CPU information

Viewing logs:

tail -f /private/var/log/system.log
tail -f /private/var/log/secure.log   # Authentication events

Keychain access – extracting password hashes:

security dump-keychain -d ~/Library/Keychains/login.keychain

Checking launch agents and daemons (startup items):

ls /Library/LaunchAgents
ls /Library/LaunchDaemons
ls ~/Library/LaunchAgents

# Search for suspicious .plist files
find /Library/Launch* ~/Library/Launch* -name "*.plist" -exec grep -l "malicious" {} \;

macOS Security Features Relevant to Attackers

  • SIP prevents modification of /System, /usr, and /bin. Disabling SIP (from Recovery Mode) increases attack surface.
  • Gatekeeper can be bypassed by right‑clicking and selecting Open, but this may alert the user.
  • XProtect is signature‑based; it can miss novel malware.
  • FileVault protects data at rest, but attackers with physical access may still attempt to steal passwords from memory.
  • Apple Silicon adds additional hardware security, making low‑level attacks harder.

macOS Penetration Testing Considerations

  • Many security tools can be installed via Homebrew (/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)").
  • Python and Ruby are preinstalled, but you may need to install newer versions via Homebrew.
  • Enable Remote Login (SSH) in System Settings → Sharing for remote access.
  • Use plutil to inspect .plist files (property lists).

Example: Enumerate startup items with launchctl:

launchctl list                    # List all launch agents/daemons loaded for current user
sudo launchctl list               # List system‑wide launch daemons

Practical macOS Security Audit Demo

#!/usr/bin/env python3
import subprocess
import os

def audit_macos():
    print("=== macOS Security Audit ===\n")

    # 1. System version and hardware
    print("1. System overview:")
    result = subprocess.run(["system_profiler", "SPSoftwareDataType"], capture_output=True, text=True)
    for line in result.stdout.split("\n")[:5]:
        print("  " + line)

    # 2. Listening ports
    print("\n2. Listening ports:")
    result = subprocess.run(["netstat", "-an", "-p", "tcp"], capture_output=True, text=True)
    lines = result.stdout.split("\n")[1:]
    for line in lines:
        if "LISTEN" in line:
            print("  " + line.strip())

    # 3. Launch agents and daemons (suspicious?)
    print("\n3. User launch agents:")
    result = subprocess.run(["ls", "~/Library/LaunchAgents"], capture_output=True, text=True, shell=True)
    for item in result.stdout.split("\n"):
        if item:
            print("  " + item)

    # 4. Check for SIP status
    print("\n4. SIP status:")
    result = subprocess.run(["csrutil", "status"], capture_output=True, text=True)
    print("  " + result.stdout.strip())

if __name__ == "__main__":
    audit_macos()

Summary and Comparison Table

OSKey Security ConceptsEssential Tools/Commands
LinuxPermissions, SUID, /etc/passwd, /etc/shadow, logs, cronls, find, grep, ps, ss, sudo, systemctl, journalctl
WindowsRegistry, Active Directory, Kerberos, NTLM, PowerShellwhoami, net, Get-Process, Get-ADUser, Get-WinEvent, reg
macOSSIP, Gatekeeper, Keychain, launchd, system logssystem_profiler, security, plutil, launchctl

What to Do Next

  • Practice, practice, practice. Set up virtual machines for each OS and run through all the commands in this chapter.
  • Explore log files and understand what normal activity looks like – this will help you spot anomalies.
  • Simulate simple attacks (e.g., creating a cron job for persistence) and then detect them using the tools shown.
  • Use the provided demo scripts to automate audits and deepen your understanding of system internals.

Mastering the operating system is the first and most important step in becoming a proficient security professional. The commands and concepts in this chapter form the bedrock of everything that follows in penetration testing, forensics, and incident response.

Scroll to Top