Python in the Void: Build Your Own Honeypot "PoohBear"

Python in the Void: Build Your Own Honeypot "PoohBear"

Creating a honeypot is a fascinating way to explore cybersecurity concepts and analyze malicious activity. Honeypots serve as decoys, luring attackers into a controlled environment to observe their tactics and techniques. In this tutorial, we’ll walk through building your own Python honeypot called "PoohBear".

PoohBear combines a Flask web app and a custom TCP socket listener, making it a versatile tool for capturing unauthorized access attempts and suspicious activities.


What is PoohBear?

PoohBear is a dual-purpose honeypot:

  1. A Flask-based web interface that mimics a file server and logs access attempts.

  2. A TCP socket listener that monitors for incoming connections on a specified port, logging any unauthorized access attempts.

This lightweight tool is perfect for beginners to hone their Python skills while learning about security monitoring.


How PoohBear Works

  1. Flask Web Interface

    • Mimics a directory structure where attackers can "interact" with files and folders.

    • Logs every attempted access to a file or folder for analysis.

  2. TCP Socket Listener

    • Listens for incoming connections on a specified port (default: 8080).

    • Logs details of any connection attempts, including IP addresses and timestamps.

  3. Integrated Logging

    • Logs all access attempts to both a log file (PoohBear.log) and a separate access log (access_log.txt) for detailed monitoring.

Setting Up PoohBear

1. Prerequisites

Before starting, ensure you have:

  • Python 3.x installed.

  • Flask installed (pip install flask).


2. The Code

Here’s the complete script for PoohBear. You can also download it from the linked GitHub repository.

import socket
import logging
import threading
from datetime import datetime
from flask import Flask, render_template, request, send_from_directory
import os

# Configure logging for the honeypot
logging.basicConfig(filename='PoohBear.log', level=logging.INFO, format='%(asctime)s - %(message)s')

# Flask App Configuration
app = Flask(__name__)

# Base directory for the honeypot files
BASE_DIR = "honeypot_files"

# Log access attempts
def log_access(file_or_folder):
    with open("access_log.txt", "a") as log_file:
        log_file.write(f"Access attempted: {file_or_folder}\n")
    logging.info(f"Access attempted: {file_or_folder}")

# Dynamically read directory contents
def get_directory_data(base_path):
    directory_data = []
    for entry in os.listdir(base_path):
        entry_path = os.path.join(base_path, entry)
        if os.path.isdir(entry_path):
            directory_data.append({'name': entry, 'type': 'folder'})
        else:
            directory_data.append({'name': entry, 'type': 'file'})
    return directory_data

@app.route('/')
def home():
    directory_data = get_directory_data(BASE_DIR)
    return render_template('index.html', directory=directory_data)


@app.route('/access', methods=['POST'])
def access_item():
    item_name = request.form.get('item_name')
    if not item_name:
        return "No item specified", 400

    log_access(item_name)
    item_path = os.path.join(BASE_DIR, item_name)

    if os.path.exists(item_path):
        if os.path.isfile(item_path):
            # Handle file: read content
            try:
                with open(item_path, 'r', errors='ignore') as file:
                    file_content = file.read()
                return render_template('access.html', item_name=item_name, file_content=file_content, directory=None)
            except Exception as e:
                return f"Error reading file: {str(e)}", 500
        elif os.path.isdir(item_path):
            # Handle folder: list contents
            try:
                directory_contents = get_directory_data(item_path)
                return render_template('access.html', item_name=item_name, file_content=None, directory=directory_contents)
            except Exception as e:
                return f"Error reading directory: {str(e)}", 500

    return "File or folder not found", 404


# Function to start the Flask app
def start_flask():
    app.run(debug=False, use_reloader=False, port=5000)

# Function to start the socket honeypot
def start_honeypot(host='0.0.0.0', port=8080):
    # Create a socket object
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to the host and port
    server_socket.bind((host, port))

    # Listen for incoming connections
    server_socket.listen(5)
    print(f"[+] PoohBear is running on {host}:{port}")

    while True:
        # Accept a connection
        client_socket, client_address = server_socket.accept()
        print(f"[!] Connection from {client_address}")

        # Log the connection details
        logging.info(f"Connection from {client_address}")

        # Close the connection
        client_socket.close()

if __name__ == "__main__":
    # Run the Flask app and socket honeypot concurrently
    flask_thread = threading.Thread(target=start_flask)
    honeypot_thread = threading.Thread(target=start_honeypot)

    flask_thread.start()
    honeypot_thread.start()

    flask_thread.join()
    honeypot_thread.join()

Step-by-Step Walkthrough

Step 1: Flask Web Interface

The Flask app is the heart of PoohBear’s web functionality.

  • Home Route (/)
    Displays the file directory and lets users interact with files or folders.

  • Access Route (/access)
    Logs attempted access and displays file content or folder structure.

How It Works:

  1. The BASE_DIR variable defines the directory structure for the honeypot.

  2. When a user interacts with a file or folder, their action is logged using the log_access function.

Customization:

  • Modify the BASE_DIR structure to simulate sensitive directories.

  • Use render_template to create convincing HTML pages for your honeypot.


Step 2: TCP Socket Listener

The socket honeypot listens for unauthorized connections.

  • Host: Default is 0.0.0.0 to accept connections from any IP.

  • Port: Default is 8080.

How It Works:

  1. When a connection is established, the honeypot logs the IP address and connection details.

  2. The socket closes immediately after logging.

Customization:

  • Add interaction responses to simulate a real server.

  • Change the listening port to mimic specific services (e.g., SSH on port 22).


Step 3: Concurrent Execution

PoohBear runs both the Flask app and the socket listener simultaneously using Python’s threading module.

  • flask_thread handles the Flask web app.

  • honeypot_thread runs the TCP socket listener.


Running PoohBear

  1. Save the script as poohbear.py.

  2. Open a terminal and run the script:

     python poohbear.py
    
  3. The Flask app will start on http://localhost:5000, and the honeypot will listen for TCP connections on port 8080.


Analyzing Access Attempts

  • Web Logs:
    Check PoohBear.log and access_log.txt for detailed records of attempted access.

  • Socket Logs:
    View connection attempts logged in PoohBear.log for insights into potential attacks.


Use Cases

  1. Learn Attack Patterns:
    Observe how attackers interact with a decoy server.

  2. Test Security Tools:
    Use PoohBear in a controlled environment to test IDS/IPS systems.

  3. Practice Forensics:
    Analyze logs to understand and respond to potential threats.


Conclusion

PoohBear is a simple yet effective honeypot for learning cybersecurity basics and monitoring suspicious activities. By combining a Flask web app with a TCP socket listener, it demonstrates the power of Python in creating practical security tools.

Stay Null. Stay Void. 🤘