13 improvements across security, architecture, and quality of life toβ¦#2
13 improvements across security, architecture, and quality of life toβ¦#2xPloits3c wants to merge 1 commit intoanubhavanonymous:mainfrom
Conversation
β¦ the TELE-TRACE codebase. 13 improvements across security, architecture, and quality of life to the TELE-TRACE codebase. The patched file (tele_trace_patched.py) is a complete drop-in replacement for the original tele_trace.py β all endpoints, all 9 platform checkers, Telegram auth, media download, SangMata history, catbox.moe upload, and the startup banner are fully preserved and functional. No external dependencies have been added. No template or static file changes are required.
|
Have you tested the changes !? |
|
Hi @anubhavanonymous, thanks for reviewing! |
Pull Request: TELE-TRACE v2.1 β Security, Architecture & QoL Improvements
Summary
This PR applies 13 improvements across security, architecture, and quality of life to the TELE-TRACE codebase. The patched file (
tele_trace_patched.py) is a complete drop-in replacement for the originaltele_trace.pyβ all endpoints, all 9 platform checkers, Telegram auth, media download, SangMata history, catbox.moe upload, and the startup banner are fully preserved and functional.No external dependencies have been added. No template or static file changes are required.
The Telethon logic has been significantly refactored. The two original scan functions (
_scanand_scan_username) have been decomposed into shared helper functions (_extract_profile,_download_all_media,_collect_history_response, etc.). While the refactored code preserves the exact same logical flow, API calls, and data structure of the original, it has not been tested against a live Telegram account.Before merging or deploying to production, the maintainer should:
api_id+api_hash).get_entity(), profile extraction, and history collection work as expected._send_history_request()/_collect_history_response()helpers.platform_scanand confirm all 9 checkers return accurate results with SSL verification now enabled.The existing
templates/andstatic/files require no changes and are fully compatible with this update.Changes Overview
run_async()except: passDetailed Changelog
1. CRITICAL SECURITY FIXES
1.1 β Re-enable SSL Certificate Verification
Problem: Both
_http_get()and_http_post_json()explicitly disabled TLS certificate verification withctx.check_hostname = Falseandctx.verify_mode = ssl.CERT_NONE. Every outbound request to GitHub, Instagram, Reddit, Discord, LinkedIn, and all other platforms was vulnerable to Man-in-the-Middle attacks.Fix: Removed the two offending lines. Both functions now use
ssl.create_default_context()which enables full certificate verification by default. Added explicitssl.SSLCertVerificationErrorhandling with a logged warning instead of silent failure. Also applied the same fix to the catbox.moe upload in/api/upload_for_search.Note for Termux users: If SSL errors occur due to missing CA certificates, install them with
pkg install ca-certificatesrather than disabling verification.1.2 β Add Timeout to
run_async()Problem: The
run_async()bridge function called.result()with no timeout. If any Telethon coroutine hung (network issue, unresponsive bot, DNS failure), the calling Flask thread would block indefinitely, making the entire application unresponsive.Fix: Added a configurable timeout (default: 120 seconds, adjustable via
TELETRACE_TIMEOUTenv var). On timeout, the future is cancelled and a clearTimeoutErroris raised with a descriptive message. The 120-second default is generous enough to accommodate slow photo downloads while still protecting against infinite hangs.1.3 β Eliminate Bare
except: passStatementsProblem: The original code contained numerous
except: passblocks that silently swallowed all exceptions β includingKeyboardInterrupt,SystemExit, and real bugs. This made debugging nearly impossible and masked errors that could corrupt state.Fix: Every bare
except: passhas been replaced with either:except (AttributeError, TypeError)for known-safe attribute access patterns (name, bio, status extraction)except Exception as e: logger.warning(...)for operations where failure is non-critical but should be logged (contact deletion, file removal, photo download)except Exception as e: logger.error(..., exc_info=True)for endpoint-level errors where a full traceback is valuableA global logger (
logging.getLogger("tele-trace")) is configured at module level and used consistently throughout the codebase.Locations patched (complete list):
_make_client()β old client disconnect_scan()βDeleteContactsRequestβ temp contact removal_scan()/_scan_username()β name, bio, status, emoji_status extraction_scan()/_scan_username()β profile photo fallback download_scan_username()βget_entity()failurelogout()β session file and config file removalupload_for_search()β catbox.moe upload_fmt_photo_date()β date parsingcheck_discord()β JSON parsing1.4 β Input Validation on API Endpoints
Problem: No input validation was performed on any endpoint. Malformed phone numbers, invalid usernames, or unexpected input types could cause crashes, confusing error messages, or unintended Telegram API calls.
Fix: Added two validation helpers:
validate_phone()β strips whitespace/dashes/parens, validates against^\+?[1-9]\d{6,14}$validate_username()β strips@prefix, validates against^[a-zA-Z0-9_\.]{1,64}$Applied to
/api/scan,/api/send_code, and/api/platform_scan. Invalid input returns a400with a clear error message.TimeoutErrorreturns504. Unexpected exceptions return500with a generic message (details logged server-side).Also added
user_idtype validation on/api/historyto catch non-numeric input early.1.5 β Basic Rate Limiting
Problem: No rate limiting existed on any endpoint. An attacker (or even an overeager user) could spam
/api/scanand trigger a flood ofImportContactsRequestcalls to Telegram, risking an account ban or temporary restriction.Fix: Implemented
SimpleRateLimiter, an in-memory per-IP rate limiter with configurable window and max requests. Applied via a@rate_limiteddecorator to the three most sensitive endpoints:/api/scanβ Telegram profile scan/api/platform_scanβ 9-platform username check/api/upload_for_searchβ catbox.moe image uploadDefaults: 5 requests per 60-second window per IP. Configurable via
TELETRACE_RATE_MAXandTELETRACE_RATE_WINDOWenvironment variables. Exceeded limits return429 Too Many Requests.2. ARCHITECTURAL REFACTORING
2.1 β Eliminate
_scan/_scan_usernameDuplicationProblem:
_scan()(phone lookup) and_scan_username()(username lookup) were two massive functions that shared approximately 80% of their code: name/bio/status extraction, flags, extra fields, usernames, emoji status, account age estimation, SangMata history interaction, photo/video download, and deduplication. Every bug fix or feature addition had to be applied in both places β and several inconsistencies already existed between them.Fix: Extracted all shared logic into dedicated helper functions:
_get_user_from_full()GetFullUserRequestresult_parse_status()_extract_extra_fields()_extract_usernames()_extract_emoji_status()_fmt_photo_date()_send_history_request()_collect_history_response()_download_all_media()_extract_profile()After refactoring,
_scan()and_scan_username()are each ~20 lines: they resolve the user (via phone import orget_entity), call_extract_profile(), set the phone field, and return. ~300 lines of duplicated code eliminated.The return data structure is identical to the original β no frontend changes needed.
2.2 β Concurrency Lock on Global State
Problem: The
_statedictionary (client,phone_code_hash,login_phone) was shared across Flask threads with no synchronization. Concurrent requests could overwritephone_code_hashduring login, corrupt the client reference during reconnection, or cause race conditions during logout.Fix: Added
_state_lock = threading.Lock()and applied it to all functions that modify_state:_make_client()β protects client replacement_send_code()β protects phone_code_hash and login_phone writes_logout()β protects full state resetRead-only access to
_state["client"]in scan functions does not require the lock since Pythonβs GIL provides atomic reference reads.Note: This is the minimum viable fix. True multi-user support would require per-session client instances or a client pool β documented as a future improvement.
2.3 β Centralized SangMata Parsing
Problem: The SangMata bot response parsing logic (quota detection, section splitting, entry regex extraction) was duplicated in three places:
_get_history(), inline in_scan(), and inline in_scan_username(). Each copy had subtle differences in variable naming but identical logic.Fix: Extracted
_parse_sangmata_response(text: str) -> dictas a single pure function. It handles:None/empty text β{"error": "Bot did not respond"}{"error": "quota_exceeded", "quota_error": "..."}[date] valueregex pattern{"error": "No history recorded"}All three call sites now use this single function, ensuring consistent behavior and a single place to fix parsing bugs.
3. QUALITY OF LIFE IMPROVEMENTS
3.1 β Configuration via Environment Variables
Problem: Host, port, timeouts, and rate limit parameters were hardcoded, making deployment inflexible β especially across different environments (Termux, VPS, Docker).
Fix: Added a
CONFIGdictionary at module level that reads from environment variables with sensible defaults:TELETRACE_HOST0.0.0.0TELETRACE_PORT7777TELETRACE_DEBUGfalseTELETRACE_TIMEOUT120TELETRACE_RATE_MAX5TELETRACE_RATE_WINDOW60Usage:
TELETRACE_PORT=8080 TELETRACE_RATE_MAX=10 python tele_trace.py3.2 β Health Check Endpoint
Problem: No way to programmatically verify the toolβs status without attempting a scan.
Fix: Added
GET /api/healthwhich returns:{ "server": "ok", "event_loop": true, "client_initialized": true, "session_file_exists": true, "config_file_exists": true, "telegram_auth": true }Returns
200when the server is operational. Telegram auth check has a 10-second timeout to avoid hanging the health endpoint. Useful for monitoring, uptime checks, and debugging connection issues.3.3 β Graceful Shutdown
Problem: The async event loop ran as a daemon thread and was killed abruptly on
Ctrl+CorSIGTERM. This could leave the Telegram session in a dirty state (open connection, pending requests).Fix: Registered signal handlers for
SIGINTandSIGTERMthat:call_soon_threadsafeSystemExit(0)3.4 β Fix MIME Type Detection
Problem: The original MIME detection used fragile byte offset checks:
The PNG check only worked because bytes 1-3 of the PNG signature happen to be
PNG, but this is not a proper magic byte check. The WEBP check was missing validation of theRIFFheader at bytes 0-3. Neither check handled JPEG or GIF, and no bounds checking was performed on short byte sequences.Fix: Replaced with a proper
detect_mime()function that checks:\x89PNG\r\n\x1a\nRIFFat bytes 0-3 ANDWEBPat bytes 8-11\xff\xd8at bytes 0-1GIF8at bytes 0-3Applied to all photo download paths and the profile photo fallback.
3.5 β Structured Logging Replaces
print()Problem: All diagnostic output used
print()with ad-hoc[History],[SSL]prefixes. No timestamps, no log levels, no ability to filter or redirect output. Error output was mixed with informational messages.Fix: Configured Pythonβs
loggingmodule at the top of the file:All
print()calls converted to appropriate log levels:logger.info()β successful operations (history response received, scan complete)logger.warning()β non-critical failures (contact deletion failed, SSL error, extra field extraction issue)logger.error()β endpoint failures withexc_info=Truefor full tracebackslogger.debug()β verbose diagnostics (individual photo download failures, disconnect errors)Werkzeugβs internal logger remains set to
ERRORto keep the console clean during normal operation.Files Changed
tele_trace.pyβtele_trace_patched.pyIMPROVEMENTS.mdtemplates/*static/*Compatibility
How to Test