pollux/tests/gemini_test_client.py
Jeena 9ca54e98c9 Fix denial of service, information disclosure and TLS identity bugs
An adversarial review of the request path turned up nine issues, all
reproduced against a running server before and after the fix.

The most serious was a permanent denial of service. The in-flight request
counter was decremented on paths that never incremented it; being unsigned
it wrapped to usize::MAX, after which every request was answered with
"41 Server unavailable" until the process restarted. A client that completed
the TLS handshake and disconnected without sending a request was enough --
a port scan, a health check, a cancelled page load. The counter is replaced
by a semaphore permit released on every exit path.

Two further remote denials of service: an error from accept() propagated out
of main and ended the process, so exhausting the descriptor limit killed the
server; and responses were read whole into memory, so cost scaled with
concurrent requests times file size. Accept errors are now logged and retried
after a backoff, and responses stream in 64 KiB chunks capped at 64 MiB.
Peers that open a socket and never send a ClientHello are bounded by a 10s
handshake timeout and a connection cap (max_connections, default 512).

Every virtual host was served whichever certificate came first in a HashMap,
which varies per process, so a host's certificate changed between restarts.
Because Gemini clients pin certificates on first use, this trained users to
dismiss the mismatch warning that would otherwise reveal interception.
Certificates are now selected by SNI with a deterministic fallback, so
unknown hosts still complete a handshake and receive 53.

Dotfiles inside a content root were public, exposing .git/config and any
credentials in it for capsule roots that are git working copies. Path
resolution is now in-tree: reject non-plain components, then compare
canonical prefixes. This replaces path-security, an unaudited micro-crate in
the security boundary that also rejected legitimate filenames containing
'%', '~' or '$'.

rustls moves 0.21 -> 0.23; the 0.21 branch is end of life. TLS 1.2 and 1.3
only, as before.

Malformed requests logged attacker-controlled text at ERROR on every request,
letting a client drive log volume; client-caused conditions now log at debug,
truncated. Hostname routing accepts the authority forms the specification
permits (mixed case, explicit port, userinfo, trailing dot), which previously
returned 53. Per-host port and log_level were accepted and silently ignored,
and now warn at startup.

Adds tests/connection_lifecycle.rs covering the counter underflow, the
oversized-response refusal, hidden files and authority normalization. Fixes
the test client, which sent host:port as SNI. 42 -> 56 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 04:30:38 +00:00

95 lines
No EOL
3.1 KiB
Python
Executable file

#!/usr/bin/env python3
"""
Simple Gemini Test Client
Makes a single Gemini request and prints the status line.
Used by integration tests for rate limiting validation.
Usage: python3 tests/gemini_test_client.py gemini://host:port/path
"""
import os
import sys
import socket
import ssl
def main():
if len(sys.argv) != 2:
print("Usage: python3 gemini_test_client.py <gemini-url>", file=sys.stderr)
sys.exit(1)
url = sys.argv[1]
# Parse URL (basic parsing) - allow any protocol for testing
if url.startswith('gemini://'):
url_parts = url[9:].split('/', 1) # Remove gemini://
host = url_parts[0]
path = '/' + url_parts[1] if len(url_parts) > 1 else '/'
else:
# For non-gemini URLs, try to extract host anyway for testing
if '://' in url:
protocol, rest = url.split('://', 1)
url_parts = rest.split('/', 1)
host = url_parts[0]
path = '/' + url_parts[1] if len(url_parts) > 1 else '/'
else:
# No protocol, assume it's host/path
url_parts = url.split('/', 1)
host = url_parts[0]
path = '/' + url_parts[1] if len(url_parts) > 1 else '/'
# Get port from environment or use default
port = int(os.environ.get('GEMINI_PORT', '1965'))
# Allow overriding the connection host (useful for testing with localhost)
connect_host = os.environ.get('GEMINI_CONNECT_HOST', host)
# SNI carries a hostname only: never a port, and never userinfo. Passing
# "host:port" here makes the handshake fail before the server sees anything.
sni_host = host.rsplit('@', 1)[-1]
if sni_host.startswith('['):
sni_host = sni_host[:sni_host.index(']') + 1] if ']' in sni_host else sni_host
elif ':' in sni_host:
sni_host = sni_host.rsplit(':', 1)[0]
sni_host = sni_host.rstrip('.')
try:
# Create SSL connection with permissive settings for self-signed certs
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
# Load default certificates to avoid some SSL issues
context.load_default_certs()
sock = socket.create_connection((connect_host, port), timeout=5.0)
ssl_sock = context.wrap_socket(sock, server_hostname=sni_host)
# Send request (full URL for Gemini protocol over TLS)
request = f"{url}\r\n"
ssl_sock.send(request.encode('utf-8'))
# Read full response (header + body)
response = b''
while len(response) < 1024: # Read up to 1KB for test responses
try:
data = ssl_sock.recv(1024)
if not data:
break
response += data
except:
break
ssl_sock.close()
if response:
# Decode and return the full response
full_response = response.decode('utf-8', errors='ignore')
print(full_response.strip())
else:
print("Error: No response")
except Exception as e:
print(f"Error: {e}")
if __name__ == '__main__':
main()