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 addresswhoami– Show the current username (works on Windows too)id– Display our user identity and group membershipshostname– Show or set the system hostnameuname– Display basic OS and hardware informationuname -a– Show detailed system info: kernel name, hostname, kernel release, version, machine hardware name, and OSuname -r– List only the kernel release numberpwd– Print the current working directoryifconfig– View and configure network interface parametersip– Show and manipulate routing, network devices, interfaces, and tunnelsnetstat– Display network connections and statusss– Investigate sockets (modern replacement for netstat)ps– Show process statuswho– Display who is currently logged inenv– Print or set environment variableslsblk– List block devices (storage)lsusb– List connected USB deviceslsof– List open files and the processes using themlspci– 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 accountuserdel– Delete a user account and related filesusermod– Modify an existing user accountaddgroup– Add a group to the systemdelgroup– Remove a group from the systempasswd– 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 packageapt-cache show <package>– Get detailed information about a packageapt list --installed– List all installed packagessudo 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 processesps aux– List all processes, including those run by other userssystemctl start <service>– Start a service (e.g.,systemctl start ssh)systemctl status <service>– Check the status of a servicesystemctl enable <service>– Configure a service to start at bootsystemctl list-units --type=service– List all servicesjournalctl -u <service> --no-pager– View logs for a specific servicekill -l– List all available kill signalskill -9 <PID>– Forcefully terminate a processjobs– List background processesbg– Resume a suspended process in the backgroundfg <ID>– Bring a background process to the foregroundping -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 serverpython3 -m http.server– Start a Python HTTP server (default port 8000)http-server -p 8080– Start a simple HTTP server with npmphp -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 directoryls -i– List files with their inode numbers
Working with Files and Directories
touch <filename>– Create an empty filemkdir -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 commandfind <location> <options>– Search for files and directorieslocate <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 filetail <file>– Show last 10 lines of a filesort– Sort output alphabeticallygrep <pattern>– Search for matching patternsgrep -v <pattern>– Exclude matching patternscut -d"<delim>" -f<field>– Extract specific fieldstr "<old>" "<new>"– Replace characterscolumn -t– Format output as a tableawk '{print $1, $NF}'– Extract specific columnssed 's/old/new/g'– Substitute textwc -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 permissionschown <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 asclear)[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 usernamePASS <password>– Send passwordSYST– Check target system typePASV– Enter passive modeTYPE A– Switch to ASCII modeTYPE I– Switch to binary modeSTAT– 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 buildGet-WmiObject -Class Win32_Process– List processesGet-WmiObject -Class Win32_Service– List servicesGet-WmiObject -Class Win32_Bios– Get BIOS informationGet-WmiObject -Class Win32_OperatingSystem | select ComputerName– Get computer nameGet-WmiObject -Class Win32_BaseBoard– Get motherboard infoGet-WmiObject -Class Win32_Processor– Get processor infoGet-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 drivetree "c:\Program Files (x86)\VMware"– Display directory structuretree c:\ /f | more– Walk through all files one screen at a time
File Operations with PowerShell
Get-ChildItem -Path <path>– List directory contentsGet-ChildItem -Path <path> -Recurse– List contents recursivelyget-alias– View available aliasesNew-Alias -Name "Show-Files" Get-ChildItem– Create custom aliasget-help <cmdlet>– Show help for a commandGet-Help <cmdlet> -Online– Open online documentationUpdate-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\RunHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunHKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceHKEY_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
| Service | Port | Secure Port |
|---|---|---|
| Telnet | 23 | - |
| SSH | 22 | - |
| FTP | 21 | 990 (FTPS) |
| SMTP | 25 | 465 (SMTPS) |
| POP3 | 110 | 995 (POP3S) |
| IMAP | 143 | 993 (IMAPS) |
| HTTP | 80 | 443 (HTTPS) |
| RDP | 3389 | - |
File Descriptor Numbers
| Stream | Number | Description |
|---|---|---|
| STDIN | 0 | Standard input |
| STDOUT | 1 | Standard output |
| STDERR | 2 | Standard error |