Popular Searches

Building a Directory Fuzzer

CybersecurityBeginner
Practice Now

Introduction

Directory fuzzing (or directory brute-forcing) is a common technique used in cybersecurity to discover hidden paths, directories, and files on a web server. Security professionals use industry-standard tools like gobuster, ffuf, or dirb to automate this process. These tools work by taking a list of common directory names (a wordlist) and rapidly making HTTP requests to see which ones exist on the target server.

In this lab, you will build your own custom directory fuzzer from scratch using Python. You will learn how to read a custom wordlist, execute rapid concurrent HTTP requests to speed up the discovery process, handle common web exceptions like 404 Not Found, and filter the results to output only the valid endpoints. By the end of this lab, you will have a functional security tool and a deeper understanding of how web enumeration works under the hood.

This kind of tool turns a simple idea into automation: take candidate paths, turn each into a request, then use the server's responses to infer what exists. Professional fuzzers add many more features, but the core logic is still built from those same basic steps.

Read Custom Wordlists

In this step, we will start building our Python fuzzer by writing the logic to read a custom wordlist. A wordlist is simply a text file containing a list of potential directory or file names, with one word per line.

The wordlist is the knowledge source that drives the scan. A fuzzer without a good candidate list is like a scanner with no targets. This is why enumeration quality depends not only on code speed but also on the realism and coverage of the input list.

Your lab environment has already been prepared with a sample wordlist named wordlist.txt located in your ~/project directory. We will create a Python script that opens this file, reads its contents, and stores the words in a list so we can use them later.

Create a new file named fuzzer.py in your ~/project directory using the nano text editor.

nano fuzzer.py

Add the following Python code to fuzzer.py. This code defines a function that opens the text file, reads each line, removes any trailing newline characters using the strip() method, and returns the cleaned list of words.

def read_wordlist(file_path):
    with open(file_path, 'r') as file:
        ## Read lines and remove newline characters
        words = [line.strip() for line in file.readlines()]
    return words

if __name__ == "__main__":
    ## Test the function by reading the provided wordlist
    wordlist = read_wordlist("wordlist.txt")
    print(f"Loaded {len(wordlist)} words from the wordlist.")
    print(f"First 3 words: {wordlist[:3]}")

Save the file by pressing Ctrl+O, then Enter. If you want to move straight into the next step, you can stay inside nano and continue editing. Use Ctrl+X only when you want to return to the terminal.

Now, execute your Python script to verify that it correctly reads the wordlist.

python3 fuzzer.py

You should see an output similar to the following, confirming that the script successfully loaded the words from the text file.

Loaded 10 words from the wordlist.
First 3 words: ['admin', 'backup', 'api']

Execute Concurrent HTTP Requests

In this step, we will add the core functionality of our fuzzer: making HTTP requests to a target web server. If we make these requests one by one (sequentially), the process will be very slow, especially with large wordlists. To solve this, we will use Python's concurrent.futures module to execute multiple requests at the same time (concurrently).

Concurrency matters because the bottleneck in web fuzzing is often waiting on network responses, not CPU usage. If your code can overlap many waiting requests, you can test far more candidates in the same amount of time.

We will also use the popular requests library to handle the HTTP communication. A local test web server is already running in your environment on http://127.0.0.1:8080.

If fuzzer.py is still open in nano, continue editing it. Otherwise, reopen it:

nano fuzzer.py

Update your script to include the requests and concurrent.futures modules. We will create a new function called check_directory that constructs a full URL and makes an HTTP GET request. We will then use a ThreadPoolExecutor to run this function concurrently for every word in our wordlist.

Replace the contents of fuzzer.py with the following code:

import requests
import concurrent.futures

TARGET_URL = "http://127.0.0.1:8080"

def read_wordlist(file_path):
    with open(file_path, 'r') as file:
        return [line.strip() for line in file.readlines()]

def check_directory(word):
    ## Construct the full URL
    url = f"{TARGET_URL}/{word}"
    ## Make the HTTP GET request
    response = requests.get(url)
    print(f"Checked {url} - Status: {response.status_code}")

if __name__ == "__main__":
    wordlist = read_wordlist("wordlist.txt")
    print(f"Starting fuzzing on {TARGET_URL}...\n")

    ## Use ThreadPoolExecutor to make concurrent requests
    ## max_workers defines how many threads will run simultaneously
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        executor.map(check_directory, wordlist)

Save the file with Ctrl+O and Enter. You can stay in nano and continue to the next step if you want to keep building the script before testing it.

Run your updated script to see the concurrent requests in action.

python3 fuzzer.py

You will see the script rapidly checking all the directories. Notice that some return a status code of 200 (meaning the directory exists), while others return 404 (meaning the directory does not exist).

Starting fuzzing on http://127.0.0.1:8080...

Checked http://127.0.0.1:8080/admin - Status: 200
Checked http://127.0.0.1:8080/backup - Status: 404
Checked http://127.0.0.1:8080/api - Status: 200
Checked http://127.0.0.1:8080/test - Status: 404
...

Handle HTTP 404 Exceptions

In this step, we will improve the robustness of our fuzzer. When brute-forcing directories, the vast majority of your requests will result in an HTTP 404 (Not Found) status code. Printing every single 404 response clutters the terminal and makes it hard to spot the actual discoveries.

This is where signal-to-noise discipline matters. Enumeration tools are useful only if the operator can separate meaningful findings from routine misses. Filtering expected failures is part of making the output analyzable.

Additionally, network requests can fail due to timeouts or connection resets. If we don't handle these exceptions, our script will crash midway through the scan. We will use a try...except block to catch network errors and add logic to silently ignore 404 status codes.

If you are still editing fuzzer.py, keep using the same nano session. Otherwise, reopen it:

nano fuzzer.py

Modify the check_directory function to include error handling and to filter out the 404 responses. Update your code to match the following:

import requests
import concurrent.futures

TARGET_URL = "http://127.0.0.1:8080"

def read_wordlist(file_path):
    with open(file_path, 'r') as file:
        return [line.strip() for line in file.readlines()]

def check_directory(word):
    url = f"{TARGET_URL}/{word}"
    try:
        ## Add a timeout to prevent hanging requests
        response = requests.get(url, timeout=3)

        ## If the page is not found, simply return and do nothing
        if response.status_code == 404:
            return

        ## Print the result for any other status code
        print(f"Checked {url} - Status: {response.status_code}")

    except requests.RequestException:
        ## Silently ignore connection errors and timeouts
        return

if __name__ == "__main__":
    wordlist = read_wordlist("wordlist.txt")
    print(f"Starting fuzzing on {TARGET_URL}...\n")

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        executor.map(check_directory, wordlist)

Save the file with Ctrl+O and Enter. If you want to test this intermediate version now, exit with Ctrl+X. Otherwise, continue directly to the final step and run the completed script once at the end.

Run the script again. This time, you should notice a much cleaner output. The script will no longer print the failed attempts, making it much easier to read.

python3 fuzzer.py

The output will now only show the directories that returned a status code other than 404.

Starting fuzzing on http://127.0.0.1:8080...

Checked http://127.0.0.1:8080/admin - Status: 200
Checked http://127.0.0.1:8080/api - Status: 200
Checked http://127.0.0.1:8080/hidden - Status: 200
Checked http://127.0.0.1:8080/images - Status: 200

Filter and Output Valid Endpoints

In this final step, we will polish our script to make it look and behave like a professional security tool. Instead of just ignoring 404s, a good fuzzer explicitly defines which HTTP status codes are considered "valid" (such as 200 OK, 301 Redirect, or 403 Forbidden).

We will define a list of valid status codes, format the output to clearly highlight discovered endpoints, and add some informative startup messages.

If you kept the file open, continue editing it. Otherwise, reopen fuzzer.py:

nano fuzzer.py

Replace the contents with the final version of our directory fuzzer:

import requests
import concurrent.futures
import sys

TARGET_URL = "http://127.0.0.1:8080"
## Define which HTTP status codes indicate a valid discovery
VALID_STATUS_CODES = [200, 204, 301, 302, 307, 401, 403]

def read_wordlist(file_path):
    try:
        with open(file_path, 'r') as file:
            return [line.strip() for line in file.readlines()]
    except FileNotFoundError:
        print(f"[-] Error: Wordlist '{file_path}' not found.")
        sys.exit(1)

def check_directory(word):
    url = f"{TARGET_URL}/{word}"
    try:
        response = requests.get(url, timeout=3)

        ## Filter and output only if the status code is in our valid list
        if response.status_code in VALID_STATUS_CODES:
            print(f"[+] Found: {url} (Status: {response.status_code})")

    except requests.RequestException:
        pass

if __name__ == "__main__":
    wordlist = read_wordlist("wordlist.txt")

    ## Print a professional-looking banner
    print("-" * 40)
    print(f"[*] Target URL    : {TARGET_URL}")
    print(f"[*] Wordlist size : {len(wordlist)} words")
    print(f"[*] Threads       : 10")
    print("-" * 40)
    print("[*] Starting directory fuzzing...\n")

    ## Increased max_workers for faster execution
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        executor.map(check_directory, wordlist)

    print("\n[*] Fuzzing completed.")

Save the file and exit the editor.

Execute your completed directory fuzzer.

python3 fuzzer.py

You should now see a clean, professional output that clearly identifies the hidden directories on the target server.

----------------------------------------
[*] Target URL    : http://127.0.0.1:8080
[*] Wordlist size : 10 words
[*] Threads       : 10
----------------------------------------
[*] Starting directory fuzzing...

[+] Found: http://127.0.0.1:8080/admin (Status: 200)
[+] Found: http://127.0.0.1:8080/api (Status: 200)
[+] Found: http://127.0.0.1:8080/hidden (Status: 200)
[+] Found: http://127.0.0.1:8080/images (Status: 200)

[*] Fuzzing completed.

Summary

In this lab, you built a custom Python directory fuzzer from scratch. You learned how to read and process custom wordlists from text files. You also utilized the requests library and concurrent.futures module to execute rapid, concurrent HTTP requests. Furthermore, you implemented error handling to gracefully manage network timeouts and ignore irrelevant HTTP 404 responses. Finally, you practiced filtering and formatting the output to clearly display valid, hidden directory endpoints.

You now have a foundational understanding of how industry-standard enumeration tools like gobuster and ffuf operate under the hood. You can continue to expand this script by adding command-line arguments (using the argparse module) to allow users to specify custom URLs, wordlists, and thread counts dynamically.