Hacking Fundamentals

This guide covers the essential commands and concepts we use when working with Linux systems, Windows environments, and network protocols. Whether we are gathering system information, managing files, or connecting to remote services, these fundamentals form the foundation of our daily workflow.

Linux Fundamentals

System Information

Before we start working on any system, we need to understand what we are dealing with. These commands help us gather basic information about the machine, network configuration, and running processes.

  • curl ifconfig.me – Display our public IP address
  • whoami – Show the current username (works on Windows too)
  • id – Display our user identity and group memberships
  • hostname – Show or set the system hostname
  • uname – Display basic OS and hardware information
  • uname -a – Show detailed system info: kernel name, hostname, kernel release, version, machine hardware name, and OS
  • uname -r – List only the kernel release number
  • pwd – Print the current working directory
  • ifconfig – View and configure network interface parameters
  • ip – Show and manipulate routing, network devices, interfaces, and tunnels
  • netstat – Display network connections and status
  • ss – Investigate sockets (modern replacement for netstat)
  • ps – Show process status
  • who – Display who is currently logged in
  • env – Print or set environment variables
  • lsblk – List block devices (storage)
  • lsusb – List connected USB devices
  • lsof – List open files and the processes using them
  • lspci – List PCI devices

User Management

We often need to switch between users or manage accounts on a system. These commands handle user and group operations.

  • sudo – Execute a command as another user (typically root)
  • su – Switch to another user ID (requires their password)
  • useradd – Create a new user account
  • userdel – Delete a user account and related files
  • usermod – Modify an existing user account
  • addgroup – Add a group to the system
  • delgroup – Remove a group from the system
  • passwd – Change a user’s password

Package Management

Most Linux distributions use package managers to install, update, and remove software. Here we focus on APT-based systems (Debian, Ubuntu, Parrot, etc.).

Repository Configuration Files:

  • /etc/apt/sources.list
  • /etc/apt/sources.list.d/parrot.list
  • apt-cache search <package> – Search the APT cache for a package
  • apt-cache show <package> – Get detailed information about a package
  • apt list --installed – List all installed packages
  • sudo apt install <package> -y – Install a package (auto-confirm)
  • sudo dpkg -i <file>.deb – Install a package using dpkg directly

Service and Process Management

Understanding what is running on a system is crucial. These commands help us manage services and processes.

  • ps – List running processes
  • ps aux – List all processes, including those run by other users
  • systemctl start <service> – Start a service (e.g., systemctl start ssh)
  • systemctl status <service> – Check the status of a service
  • systemctl enable <service> – Configure a service to start at boot
  • systemctl list-units --type=service – List all services
  • journalctl -u <service> --no-pager – View logs for a specific service
  • kill -l – List all available kill signals
  • kill -9 <PID> – Forcefully terminate a process
  • jobs – List background processes
  • bg – Resume a suspended process in the background
  • fg <ID> – Bring a background process to the foreground
  • ping -c 10 www.test.com & – Run a command in the background

Process Control Shortcuts:

  • [CTRL]+Z: Suspend the current process
  • [CTRL]+C: Send SIGINT to terminate the current task

Command Chaining

We can combine multiple commands to streamline our workflow:

  • ; – Execute commands sequentially (ignore errors)
  • && – Execute next command only if the previous succeeded
  • \| – Pipe output from one command to another

Examples:

# Run commands regardless of success
echo '1'; echo '2'; echo '3'

# Stop if a command fails
echo '1' && ls MISSING_FILE && echo '3'

Web Services

Sometimes we need to quickly host files or start a local web server.

  • apt install apache2 -y – Install Apache web server
  • python3 -m http.server – Start a Python HTTP server (default port 8000)
  • http-server -p 8080 – Start a simple HTTP server with npm
  • php -S 127.0.0.1:8080 – Start a PHP development server

After starting a service, we can access it at http://localhost or the specified port.

Navigation

  • cd - – Jump back to the previous directory
  • ls -i – List files with their inode numbers

Working with Files and Directories

  • touch <filename> – Create an empty file
  • mkdir -p <path> – Create a directory and all necessary parent directories

Example:

mkdir -p Storage/local/user/documents

Finding Files and Directories

  • which <command> – Locate the executable path for a command
  • find <location> <options> – Search for files and directories
  • locate <pattern> – Quickly find files using a pre-built database

FIND Examples:

# Find configuration files owned by root, larger than 20KB, modified after a specific date
find / -type f -name "*.conf" -user root -size +20k -newermt 2020-03-03 -exec ls -al {} \; 2>/dev/null

# Find files between 25KB and 28KB
find / -type f -name "*.conf" -size +25k -size -28k -newermt 2020-03-03 -exec ls -al {} \; 2>/dev/null

# Update the locate database
sudo updatedb

# Search for configuration files
locate *.conf

File Descriptors and Redirections

Linux uses file descriptors to handle input and output streams:

  • STDIN (0) – Standard input (keyboard)
  • STDOUT (1) – Standard output (screen)
  • STDERR (2) – Standard error (screen)

Redirection Operators:

  • > – Redirect STDOUT to a file (overwrite)
  • >> – Redirect STDOUT to a file (append)
  • 2> – Redirect STDERR
  • < – Redirect STDIN from a file
  • | – Pipe output to another command

Examples:

# Redirect output while suppressing errors
find /etc/ -name shadow 2>/dev/null > results.txt

# Redirect STDOUT and STDERR to separate files
find /etc/ -name shadow 2> stderr.txt 1> stdout.txt

# Read from a file
cat < stdout.txt

# Append output to a file
find /etc/ -name passwd >> stdout.txt 2>/dev/null

# Create a file with heredoc (type EOF to end)
cat << EOF > stream.txt

# Pipe through grep and count results
find /etc/ -name *.conf 2>/dev/null | grep systemd | wc -l

# Count installed packages
apt list --installed | grep -c 'installed'

Filtering Content

We often need to filter and format command output to find what we need.

  • head <file> – Show first 10 lines of a file
  • tail <file> – Show last 10 lines of a file
  • sort – Sort output alphabetically
  • grep <pattern> – Search for matching patterns
  • grep -v <pattern> – Exclude matching patterns
  • cut -d"<delim>" -f<field> – Extract specific fields
  • tr "<old>" "<new>" – Replace characters
  • column -t – Format output as a table
  • awk '{print $1, $NF}' – Extract specific columns
  • sed 's/old/new/g' – Substitute text
  • wc -l – Count lines

Practical Example:

# Find users with bash shells, format output, and count them
cat /etc/passwd | grep -v "false\|nologin" | tr ":" " " | awk '{print $1, $NF}' | wc -l

# Extract unique URLs from a file
cat site-src | grep "https://www.inlanefreight.com" | tr "'" "\n" | tr '"' "\n" | grep "https://www.inlanefreight.com" | sort -u | wc -l

Note: Unlike more, less does not remain in the terminal after closing.

Permission Management

  • chmod <permissions> <file> – Change file permissions
  • chown <user>:<group> <file> – Change file owner and group

Permission Examples:

# Add read permission for all users
chmod a+r shell

# Set specific permissions (rwx|r-x|r--)
chmod 754 shell

# Change owner to root
chown root:root shell

Keyboard Shortcuts

These shortcuts make our work in the terminal more efficient:

  • [CTRL]+A – Move cursor to beginning of line
  • [CTRL]+E – Move cursor to end of line
  • [CTRL]+[Left/Right] – Jump to beginning of current/previous word
  • [ALT]+B/F – Move backward/forward one word
  • [CTRL]+U – Erase from cursor to beginning of line
  • [CTRL]+K – Erase from cursor to end of line
  • [CTRL]+W – Erase the word before the cursor
  • [CTRL]+Y – Paste previously erased text
  • [CTRL]+C – Send SIGINT to end current task
  • [CTRL]+D – Close STDIN (End-of-File)
  • [CTRL]+L – Clear the terminal (same as clear)
  • [CTRL]+Z – Suspend current process
  • [CTRL]+R – Search through command history

Security Basics

Keeping our systems updated and properly firewalled is essential:

# Update package lists and upgrade all packages
apt update && apt dist-upgrade

# Configure firewall rules
iptables <rules>

Storage Management (LVM)

When working with logical volumes, we might need to extend storage:

# Check volume group size
vgdisplay

# Extend volume group by 1GB
vgextend VolGroup /dev/sdb1

# Check logical volume
lvdisplay /dev/VolGroup/root

# Extend logical volume
lvextend -L +1G /dev/VolGroup/root

# Check with df
df -ah

# Resize the filesystem
resize2fs /dev/VolGroup/root

# Verify changes
df -ah

Networking Fundamentals

VPN Connections

When we need to connect to a target network securely:

# Connect using OpenVPN
sudo openvpn user.ovpn

# Verify the connection
ifconfig

# Check accessible networks
netstat -rn

SSH Access

SSH is our primary method for secure remote access to Linux systems.

# Basic SSH login
ssh [email protected]

# Connect when older key algorithms are needed
ssh -oHostKeyAlgorithms=+ssh-rsa bob@<rhost>

Testing Connectivity

# Connect to a specific port with netcat
netcat 10.10.10.10 22

File Transfers

SCP allows us to securely copy files between systems:

# Upload a file to a remote server
scp source.txt [email protected]:/home/user/destination.txt

# Download a file from a remote server
scp [email protected]:/home/user/source.txt destination.txt

Protocols and Services

Telnet

Telnet operates on port 23 and sends all data, including credentials, in cleartext. We should avoid using it in production environments.

FTP (File Transfer Protocol)

FTP operates on port 21 (cleartext) or port 990 (FTPS with SSL/TLS). SFTP uses SSH on port 22.

Modes of Operation:

  • Active Mode: Data sent over a separate channel from the server’s port 20
  • Passive Mode: Data sent over a separate channel from a client port above 1023

Manual FTP Commands (used with telnet or netcat, not the FTP client):

  • USER <username> – Send username
  • PASS <password> – Send password
  • SYST – Check target system type
  • PASV – Enter passive mode
  • TYPE A – Switch to ASCII mode
  • TYPE I – Switch to binary mode
  • STAT – Get additional system information

FTP Client Commands:

# Switch to ASCII mode
ascii

# Download a file (client and server establish a new channel)
get <filename>

Email Protocols

Email delivery involves several components: Mail User Agent (MUA), Mail Submission Agent (MSA), Mail Transfer Agent (MTA), and Mail Delivery Agent (MDA).

SMTP (Simple Mail Transfer Protocol) - Port 25 (SMTPS on 465)

Used to communicate with MTA servers:

# Connect to SMTP server
telnet <rhost> 25

# Identify ourselves
helo telnet

# Specify sender
mail from: <[email protected]>

# Specify recipient
rcpt to: <[email protected]>

# Start message data
data
subject: This is the subject

# End message with a period on its own line
.
quit

POP3 (Post Office Protocol v3) - Port 110 (POP3S on 995)

Used to download messages from the MDA (messages are typically deleted after download):

# Connect to POP3 server
telnet <rhost> 110

# Authenticate
USER <user>
PASS <password>

# Check status
STAT

# List messages
LIST

# Retrieve first message
RETR 1

# Exit
QUIT

IMAP (Internet Message Access Protocol) - Port 143 (IMAPS on 993)

Changes are synchronized with the server. Each command must be preceded by a random string:

# Login
c1 LOGIN <username> <password>

# List folders
c2 LIST "" "*"

# Examine inbox
c3 EXAMINE INBOX

# Logout
c4 LOGOUT

Packet Sniffing

We can capture network traffic for analysis:

# Capture POP3 traffic and display in ASCII
sudo tcpdump port 110 -A

Windows Fundamentals

Remote Access (RDP)

Connecting to Windows machines via Remote Desktop Protocol:

# Connect using xfreerdp
xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:<rhost> /u:<username> /p:'<password>'

# Alternative syntax
xfreerdp /v:<targetIp> /u:htb-student /p:Password

PowerShell Basics

PowerShell is our primary command-line interface for Windows administration.

Downloading Files

# Download a file (similar to wget)
Invoke-WebRequest -uri <LOCAL-IP>/socat.exe -outfile C:\Windows\temp\socat.exe

System Information with WMI

Windows Management Instrumentation (WMI) provides detailed system information:

  • Get-WmiObject -Class Win32_OperatingSystem | select Version,BuildNumber – Get OS version and build
  • Get-WmiObject -Class Win32_Process – List processes
  • Get-WmiObject -Class Win32_Service – List services
  • Get-WmiObject -Class Win32_Bios – Get BIOS information
  • Get-WmiObject -Class Win32_OperatingSystem | select ComputerName – Get computer name
  • Get-WmiObject -Class Win32_BaseBoard – Get motherboard info
  • Get-WmiObject -Class Win32_Processor – Get processor info
  • Get-WmiObject -Class Win32_PhysicalMemory – Get memory info

Alternative with WMIC:

  • CMD
:: Get help
wmic /?

:: Get hostname
wmic computersystem get name

:: Brief OS info
wmic os list brief
  • PowerShell
# Detailed OS info
Get-WmiObject -Class Win32_OperatingSystem | select SystemDirectory,BuildNumber,SerialNumber,Version | ft

Directory Navigation

  • dir c:\ – List contents of C drive
  • tree "c:\Program Files (x86)\VMware" – Display directory structure
  • tree c:\ /f | more – Walk through all files one screen at a time

File Operations with PowerShell

  • Get-ChildItem -Path <path> – List directory contents
  • Get-ChildItem -Path <path> -Recurse – List contents recursively
  • get-alias – View available aliases
  • New-Alias -Name "Show-Files" Get-ChildItem – Create custom alias
  • get-help <cmdlet> – Show help for a command
  • Get-Help <cmdlet> -Online – Open online documentation
  • Update-Help – Install local help files

Permissions (icacls)

Managing NTFS permissions:

:: List permissions on a directory
icacls C:\Windows

:: Grant full control to a user
icacls c:\users /grant joe:f

:: Remove permissions
icacls c:\users /remove joe

:: List shared folders
net share

Windows Services

Services are managed via the Service Control Manager (SCM):

# Open Services GUI
services.msc

# List running services
Get-Service | ? {$_.Status -eq "Running"} | select -First 2 | fl

# Query a specific service
sc qc wuauserv

# Query service on remote machine
sc \\<hostname or IP> query <ServiceName>

# Stop/start a service
sc stop wuauserv
sc start wuauserv

# Configure service binary path (potential privilege escalation)
sc config wuauserv binPath=C:\Windows\Perfectlylegitprogram.exe

# View service permissions
sc sdshow wuauserv

# Check registry permissions
Get-ACL -Path HKLM:\System\CurrentControlSet\Services\wuauserv | Format-List

Running PowerShell Scripts

# Execute a script
.\PowerView.ps1;Get-LocalGroup | fl

# Import module for current session
Import-Module .\PowerView.ps1

# List loaded modules
Get-Module | select Name,ExportedCommands | fl

# Check execution policy
get-executionpolicy -list

# Bypass execution policy for current session
Set-ExecutionPolicy Bypass -Scope Process

The Windows Registry

The registry stores system and application configuration:

  • System registry: C:\Windows\System32\Config\
  • User registry (HKCU): C:\Windows\Users\<USERNAME>\Ntuser.dat

Run and RunOnce Keys (persistence locations):

  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
  • HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
  • HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
  • HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
:: Query Run keys
reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

:: List hidden files (registry hives)
gci -Hidden

Security Identifiers (SIDs)

:: Get current user SID
whoami /user

:: Get all user SIDs
wmic useraccount get name,sid

:: Get group SIDs
wmic group get name,sid,domain

SID Format: (SID)-(revision level)-(identifier-authority)-(subauthority1)-(subauthority2)-...

Windows Security Features

Local Group Policy – Can be used to enable Virtualization Based Security and Credential Guard.

:: Open Group Policy Editor
gpedit.msc

Windows Defender:

# Check which protections are enabled
Get-MpComputerStatus | findstr "True"

User Management

# Create a user interactively
$Password = Read-Host -AsSecureString
New-LocalUser "NEW_ACCOUNT_NAME" -Password $Password -FullName "USER_FULL_NAME" -Description "DESCRIPTION"

# Add to administrators group
Add-LocalGroupMember -Group "Administrators" -Member "NEW_ACCOUNT_NAME"

# Remove user
Remove-LocalUser -Name "USER_ACCOUNT_NAME"

# Command prompt alternative
net user <username> <password> /add
net localgroup administrators <username> /add

Microsoft Management Console (MMC)

:: Open MMC
mmc

Windows Subsystem for Linux (WSL)

# Install WSL (requires Administrator PowerShell and restart)
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

Quick Reference Tables

Port Numbers

ServicePortSecure Port
Telnet23-
SSH22-
FTP21990 (FTPS)
SMTP25465 (SMTPS)
POP3110995 (POP3S)
IMAP143993 (IMAPS)
HTTP80443 (HTTPS)
RDP3389-

File Descriptor Numbers

StreamNumberDescription
STDIN0Standard input
STDOUT1Standard output
STDERR2Standard error