Evading Honeypots With Python Scripts
Understanding Honeypots
Honeypots are decoy systems designed to lure and detect potential attackers. They mimic real systems but are isolated and monitored. Evading honeypots requires careful analysis and specialized techniques.
graph TD A[Attacker] -->|Probes| B{Honeypot?} B -->|Yes| C[Detected] B -->|No| D[Real System] C -->|Alert| E[Security Team] D -->|Access| F[Potential Breach]
Techniques for Honeypot Evasion
1. Fingerprinting
Before interacting with a system, it’s crucial to determine if it’s a honeypot. Here’s a Python script to check for common honeypot signatures:
import socket
import ssl
def check_honeypot(ip, port):
try:
context = ssl.create_default_context()
with socket.create_connection((ip, port)) as sock:
with context.wrap_socket(sock, server_hostname=ip) as secure_sock:
cert = secure_sock.getpeercert()
if "honeypot" in str(cert).lower():
return True
except Exception as e:
print(f"Error: {e}")
return False
# Usage
target_ip = "192.168.1.100"
target_port = 443
if check_honeypot(target_ip, target_port):
print("Potential honeypot detected!")
else:
print("No honeypot indicators found.")
This script establishes an SSL connection and examines the certificate for honeypot-related keywords.
2. Timing-based Detection
Honeypots often respond faster than real systems due to their simplified nature. We can use this characteristic to our advantage:
import time
import requests
import statistics
def measure_response_time(url, samples=5):
times = []
for _ in range(samples):
start_time = time.time()
try:
response = requests.get(url, timeout=5)
end_time = time.time()
times.append(end_time - start_time)
except requests.RequestException:
pass
return statistics.mean(times) if times else None
# Usage
target_url = "http://example.com"
avg_response_time = measure_response_time(target_url)
if avg_response_time is not None:
if avg_response_time < 0.05:
print(f"Suspiciously fast average response time: {avg_response_time:.3f} seconds. Potential honeypot.")
else:
print(f"Normal average response time: {avg_response_time:.3f} seconds.")
else:
print("Failed to measure response time.")
This script takes multiple samples to calculate an average response time, providing a more reliable indicator.
3. Behavior Analysis
Real systems exhibit consistent and complex behavior. This script checks for inconsistencies in SSH behavior:
import paramiko
import random
import string
def generate_random_command():
return ''.join(random.choices(string.ascii_lowercase, k=5))
def analyze_ssh_behavior(hostname, username, password):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password)
# Execute a series of commands, including some random ones
commands = ["ls", "pwd", "whoami", "date", generate_random_command(), generate_random_command()]
for cmd in commands:
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read().decode().strip()
print(f"Command '{cmd}' output: {result}")
# Check for suspicious behavior
stdin, stdout, stderr = client.exec_command("cat /proc/version")
kernel_version = stdout.read().decode().strip()
if not kernel_version or "Linux version" not in kernel_version:
print("Suspicious kernel information. Potential honeypot.")
except paramiko.AuthenticationException:
print("Authentication failed. Potential honeypot or incorrect credentials.")
except paramiko.SSHException as e:
print(f"SSH error: {e}. Potential honeypot.")
finally:
client.close()
# Usage
analyze_ssh_behavior("192.168.1.100", "user", "password")
This script includes random command generation to test the system’s response to unexpected inputs.
Advanced Evasion Techniques
1. Traffic Obfuscation
Use this script to obfuscate your traffic using a custom encoding scheme:
import base64
import requests
import random
def custom_encode(data):
encoded = base64.b64encode(data.encode()).decode()
return ''.join(random.choice([c.upper(), c.lower()]) for c in encoded)
def obfuscate_request(url, payload):
encoded_payload = custom_encode(payload)
headers = {"X-Custom-Data": encoded_payload}
response = requests.get(url, headers=headers)
return response.text
# Usage
target_url = "http://example.com/api"
secret_payload = "sensitive_data"
result = obfuscate_request(target_url, secret_payload)
print(result)
This script uses a combination of base64 encoding and random case switching to obfuscate the payload.
2. Dynamic IP Rotation
Rotate your IP address to avoid detection using the Tor network:
import requests
import time
from stem import Signal
from stem.control import Controller
def rotate_ip():
with Controller.from_port(port=9051) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
time.sleep(5) # Allow time for the new circuit to be established
def make_request(url):
proxies = {
'http': 'socks5h://localhost:9050',
'https': 'socks5h://localhost:9050'
}
return requests.get(url, proxies=proxies)
# Usage
for i in range(5):
rotate_ip()
response = make_request("http://httpbin.org/ip")
print(f"Request {i+1} - Current IP: {response.json()['origin']}")
This script uses the Tor network to change the IP address for each request, making it harder to track and identify the source.
Mathematical Model for Honeypot Probability
We can use a simple Bayesian model to estimate the probability of a system being a honeypot based on observed characteristics:
$$ P(H|E) = \frac{P(E|H) \cdot P(H)}{P(E|H) \cdot P(H) + P(E|\neg H) \cdot P(\neg H)} $$
Where:
- $P(H|E)$ is the probability of the system being a honeypot given the evidence
- $P(E|H)$ is the probability of observing the evidence in a honeypot
- $P(H)$ is the prior probability of encountering a honeypot
- $P(E|\neg H)$ is the probability of observing the evidence in a non-honeypot system
- $P(\neg H)$ is the prior probability of encountering a non-honeypot system
Here’s a Python implementation of this model:
def calculate_honeypot_probability(evidence_probability, honeypot_prior=0.1):
p_h = honeypot_prior
p_not_h = 1 - p_h
p_e_given_h = evidence_probability
p_e_given_not_h = 1 - evidence_probability
numerator = p_e_given_h * p_h
denominator = (p_e_given_h * p_h) + (p_e_given_not_h * p_not_h)
return numerator / denominator
# Example usage
fast_response_prob = 0.95 # Probability of fast response being indicative of a honeypot
honeypot_prob = calculate_honeypot_probability(fast_response_prob)
print(f"Probability of system being a honeypot: {honeypot_prob:.2%}")
Conclusion
Evading honeypots requires a combination of techniques and constant vigilance. The methods presented here demonstrate various approaches to detect and evade honeypots, but it’s crucial to remember that these techniques should only be used in authorized, controlled environments. The ethical and legal approach to cybersecurity involves working with system owners to improve security, not attempting unauthorized access.
graph LR A[Reconnaissance] --> B{Honeypot?} B -->|Yes| C[Avoid] B -->|No| D[Proceed with Caution] D --> E[Further Analysis] E --> F{Confirm Real System} F -->|Yes| G[Engage Ethically] F -->|No| C
Remember, the goal of understanding honeypot evasion is to improve defensive measures and create more robust security systems, not to facilitate unauthorized access.