Skip to main content
Glama
TLS Handshake Analyzer / Bypass — MCP

TLS Handshake Analyzer / Bypass — MCP

by KMG305
README.md
<div align="center">

# TLS Handshake Analyzer / Bypass — MCP

**Browserless Multi-Engine TLS/HTTP2 Fingerprint Bypass & Handshake Analyzer, X.509 Diagnostics & Stateful Sessions for AI Agents (MCP), CLI, Python & FastAPI**

[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://www.python.org/)
[![CI Tests](https://img.shields.io/github/actions/workflow/status/KMG305/tls-analyzer-bypass-mcp/ci.yml?branch=main&style=for-the-badge&label=Tests)](https://github.com/KMG305/tls-analyzer-bypass-mcp/actions/workflows/ci.yml)
[![MCP Server](https://img.shields.io/badge/MCP-8%20Tools%20(stdio)-00A67E?style=for-the-badge)](./mcp_server.py)
[![Engines](https://img.shields.io/badge/Engines-BoringSSL%20%7C%20uTLS%20%7C%20OpenSSL-orange?style=for-the-badge)](#4-independent-tls-engines)
[![FastAPI](https://img.shields.io/badge/FastAPI-REST%20%2B%20OpenAPI-009688?style=for-the-badge&logo=fastapi&logoColor=white)](./app.py)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue?style=for-the-badge)](./LICENSE)

[Why This Exists](#why-this-exists) • [Live Proof](#live-proof) • [Engines](#4-independent-tls-engines) • [What You Can Do](#what-you-can-do) • [MCP Setup](#configuring-mcp-for-ai-clients) • [CLI Examples](#cli-quick-reference) • [REST API](#rest-api-fastapi)

</div>

---

## Why This Exists

Standard HTTP tools and fetch MCP servers (`requests`, `httpx`, `urllib`, Node `fetch`) use default system **OpenSSL** handshakes. Modern anti-bot/WAF layers inspect the TLS **ClientHello** (`JA3` / `JA4`), HTTP/2 **Akamai** fingerprint (`SETTINGS`, `WINDOW_UPDATE`, pseudo-header order), and header order — immediately returning `403` before your request even touches application logic.

**TLS Handshake Analyzer** gives **AI models (via MCP)** and developers a lightweight, browserless way to:

- Speak **real browser TLS/HTTP2/HTTP3** across **3 independent browser-grade C/Rust/Go stacks** (without launching Playwright/Chromium)
- Prove whether a target blocks on TLS vs credentials by contrasting against a **Python OpenSSL baseline**
- Inspect **raw TLS handshakes, timings, ALPN, cipher negotiation & X.509 chains** (even on expired or self-signed certs)
- Run **stateful multi-step flows** (`init` → `login` → authenticated API calls) with persistent cookie jars and pinned TLS state
- Pull **unfiltered full dumps** (`full_dump=True`) — every header, duplicate `Set-Cookie`, redirect hop, unlimited response body, and peer certificates

### Common Use Cases

| Use Case | Why Use This Tool |
|---|---|
| **AI-Agent Browserless Web Scraping** | Stop getting `403 Forbidden` when your MCP agent fetches pages via standard `httpx`/`requests`/`fetch` — swap in Chrome/Firefox/Safari TLS + HTTP/2 in one tool call |
| **Authenticated Logins & Session Workflows** | Sign in to **your own accounts** or private APIs multi-step (`session_id` keeps cookies & TLS stack aligned) at millisecond speed, without booting a 1 GB headless browser |
| **TLS Fingerprint / Anti-Bot Debugging** | Compare `curl_cffi`, `boring` (`wreq`), `utls`, and `openssl` side-by-side (`compare_tls_profiles`) to see whether Cloudflare, Akamai, or DataDome blocks your JA3/JA4 or header order |
| **Certificate & Protocol Auditing** | Diagnose expired/self-signed certs, SNI mismatches, OCSP/AIA chains, and TLS 1.0–1.3 server support matrices |

```mermaid
flowchart LR
    Client["AI Agent (MCP stdio) / CLI / Python / REST API"] --> Router["TLS Analyzer & Engine Router"]
    Router --> Curl["curl_cffi (libcurl-impersonate + BoringSSL)"]
    Router --> Boring["boring (wreq Rust + BoringSSL)"]
    Router --> Utls["utls (tls-client Go bogdanfinn/uTLS)"]
    Router --> OpenSSL["openssl (Python OpenSSL Baseline)"]
    Router --> Raw["Raw Socket TLS + X.509 Chain Inspector"]
    Curl & Boring & Utls & OpenSSL & Raw --> Target["Target Server / WAF / Cloudflare / Akamai"]
```

---

## Live Proof

### FastAPI Swagger UI (`/docs`)

Interactive OpenAPI 3.1 docs served locally on `http://127.0.0.1:8000/docs` with all **14 REST endpoints** and **8 request/validation schemas**:

![TLS Handshake Analyzer & Multi-Engine Fingerprint API Swagger UI](./docs/swagger-ui.png)

---

### Real Live JSON Output (`boring` Chrome vs `utls` Chrome vs `openssl` Baseline)

Live responses captured via `POST /api/self-fingerprint` against `https://tls.browserleaks.com/` — `boring` (`Chrome154`) and `utls` (`chrome_152`) emit authentic Chrome `HTTP/2`, `JA4`, `Akamai H2`, and Windows Chrome `User-Agent`, whereas standard Python `openssl` leaks `HTTP/1.1` and `python-requests/2.34.2`:

```json
{
  "boring_chrome": {
    "success": true,
    "engine": "boring",
    "profile": "Chrome154",
    "endpoint": "https://tls.browserleaks.com/",
    "http_version": "HTTP/2",
    "fingerprint": {
      "ja3_hash": "e1efe648fcaa52bddad1d96b35b9275f",
      "ja3n_hash": "bd4930bd9b000ee684830e44bab76fdf",
      "ja4": "t13d1517h2_8daaf6152771_cb7bf5808d99",
      "ja4_o": "t13d1517h2_acb858a92679_dddf77ad61fc",
      "akamai_hash": "52d84b11737d980aef856699f885ca86",
      "akamai_text": "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"
    }
  },
  "utls_chrome": {
    "success": true,
    "engine": "utls",
    "profile": "chrome_152",
    "endpoint": "https://tls.browserleaks.com/",
    "http_version": "HTTP/2",
    "fingerprint": {
      "ja3_hash": "2d25c56381929cc91bc97631a0a46f58",
      "ja3n_hash": "bd4930bd9b000ee684830e44bab76fdf",
      "ja4": "t13d1517h2_8daaf6152771_cb7bf5808d99",
      "ja4_o": "t13d1517h2_acb858a92679_ed4eee291a6e",
      "akamai_hash": "52d84b11737d980aef856699f885ca86",
      "akamai_text": "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36"
    }
  },
  "openssl_baseline": {
    "success": true,
    "engine": "openssl",
    "profile": "python-requests-openssl",
    "endpoint": "https://tls.browserleaks.com/",
    "http_version": "HTTP/1.1",
    "fingerprint": {
      "ja3_hash": "7291ea5e449f2c7b17582541703e549d",
      "ja3n_hash": "e768c332818abbe316c084106db8544a",
      "ja4": "t13d1712h1_ab0a1bf427ad_882d495ac381",
      "ja4_o": "t13d1712h1_fd0eb050439a_ef7e3bf95d98",
      "akamai_hash": "",
      "akamai_text": "",
      "user_agent": "python-requests/2.34.2"
    }
  }
}
```

<details>
<summary>Live <code>POST /api/analyze</code> JSON output (raw TLS handshake timings + X.509 certificate details)</summary>

```json
{
  "success": true,
  "certificate_verified": true,
  "host": "tls.browserleaks.com",
  "port": 443,
  "sni_hostname": "tls.browserleaks.com",
  "resolved_ip": "138.197.54.100",
  "timings_ms": {
    "dns": 11.72,
    "tcp_connect": 117.07,
    "tls_handshake": 130.31,
    "total": 259.1
  },
  "tls": {
    "version": "TLSv1.3",
    "cipher_suite": "TLS_AES_128_GCM_SHA256",
    "cipher_protocol": "TLSv1.3",
    "cipher_bits": 128,
    "alpn_protocol": "h2"
  },
  "certificate": {
    "subject": {
      "common_name": "tls.browserleaks.com",
      "rfc4514": "CN=tls.browserleaks.com"
    },
    "issuer": {
      "common_name": "YE1",
      "rfc4514": "CN=YE1,O=Let's Encrypt,C=US"
    },
    "validity": {
      "not_before": "2026-10-05T12:43:04+00:00",
      "not_after": "2027-01-03T12:43:03+00:00",
      "days_remaining": 52,
      "is_expired": false,
      "not_yet_valid": false
    },
    "public_key": {
      "type": "EC",
      "key_size": 256,
      "curve": "secp256r1"
    }
  }
}
```

</details>

---

## 4 Independent TLS Engines

| Engine | Backend Stack | Profiles | Highlights & Capabilities |
|---|---|---|---|
| `curl_cffi` *(default)* | `libcurl-impersonate` + **BoringSSL** | **53** + `random` | Native Chrome / Firefox / Safari / iOS / Edge / Tor profiles, **HTTP/1.1, HTTP/2 & HTTP/3**, custom `ja3` & `akamai` H2 strings, `header_order`, extra BoringSSL FP flags, sessions |
| `boring` | `wreq` (**Rust** + **BoringSSL**) | **139** + `random` | Latest browser enums (`Chrome154`, `Firefox152`, `Safari26_4`, `Edge148`, `OkHttp5`), OS platform spoofing (`windows` desktop default / `macos` / `linux` / `android` / `ios`), `OrigHeaderMap` ordering, low-level `TlsOptions`, BoringSSL leaf peer-cert PEM extraction, redirect history |
| `utls` | `tls-client` (**Go** `bogdanfinn/uTLS`) | **83** + `random` | Wide Go uTLS Chrome/Firefox/Safari/Brave/Opera/OkHttp/mobile identifiers, **auto-aligned browser HTTP headers & `header_order`** (prevents `tls-client/*` UA & H2 leaks), `platform` presets, custom `ja3`, raw `h2_settings`, `h2_settings_order`, `pseudo_header_order`, `connection_flow`, extension randomization |
| `openssl` | Python `requests` + system **OpenSSL** | `standard` | Intentionally un-impersonated baseline control — proves when a `403`/`429` block comes specifically from TLS fingerprinting |

> [!TIP]
> Friendly aliases like `chrome`, `firefox`, `safari`, `safari_ios`, `edge`, `opera`, `okhttp`, and `random` are **resolved dynamically** against whichever profiles your installed library versions expose — so upgrades never break on hardcoded version numbers.

---

## What You Can Do

### 1. AI-Native Browserless Access (`mcp_server.py`)

Exposes **8 MCP tools** over `stdio` with strict Pydantic schemas and descriptions so AI agents (Claude Code, OpenCode, Cursor, Antigravity, etc.) know every parameter automatically:

| MCP Tool | What It Does |
|---|---|
| `audit_tls_security_posture` | One-call security audit: **0–100 score, A–F grade** and severity-sorted findings (expired / soon-to-expire certs, weak RSA/EC/DSA keys, SHA-1/MD5 signatures, self-signed or untrusted chains, legacy TLS 1.0/1.1 still enabled, missing TLS 1.3) |
| `analyze_tls_handshake` | Raw socket DNS + TCP + TLS timing breakdown, negotiated TLS version/cipher/ALPN, SANs, full X.509 cert chain (+ unverified fallback on broken/self-signed certs), OCSP/CRL/AIA/extensions & PEMs with `full_dump=True` |
| `probe_tls_versions_matrix` | Tests `TLSv1.0`, `TLSv1.1`, `TLSv1.2`, and `TLSv1.3` individually against any host/port |
| `probe_tls_fingerprint` | Full HTTP/HTTPS client supporting `curl_cffi`, `boring`, `utls`, and `openssl`, `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`HEAD`/`OPTIONS`/`TRACE`, `json_body`, `form_data`, `body`, custom `headers`, exact `header_order`, `cookies`, `proxy` (HTTP/HTTPS/SOCKS5), `platform`, `http_version`, `ja3`, `akamai`, `tls_options`, `retries`/`retry_backoff`, `session_id`, and `full_dump` |
| `compare_tls_profiles` | Side-by-side matrix testing multiple browser profiles and/or all 4 engines in bounded parallel (`max_concurrency=4`, opt-in `retries`) against the same URL/payload (`statuses_differ`, `waf_detection`) |
| `inspect_profile_ja3_ja4` | Verifies the exact `JA3`, `JA3N`, `JA4`, `JA4_o`, `Akamai H2` text/hash, negotiated HTTP protocol, & emitted `User-Agent` on the wire via `tls.browserleaks.com` |
| `list_tls_fingerprint_profiles` | Returns all supported engines, aliases, platforms, capabilities, and available profile IDs |
| `manage_tls_session` | `list`, `inspect`, `clear`, `close`, or `close_all` persistent `session_id` sessions & cookie jars |

### 2. Multi-Step Login & Cookie Persistence (`session_id`)

Keep the exact pinned TLS configuration (`engine`, `profile`, `platform`, `http_version`, `proxy`, `verify`, `ja3`) and cookie jar alive across requests without silently drifting mid-session or losing CSRF/session cookies:

```python
from tls_analyzer import probe_tls_fingerprint, manage_tls_session

# Step 1: Hit init/login page cleanly (bypassing TLS WAF check)
init_res = probe_tls_fingerprint(
    "https://target.example.com/auth/init",
    engine="boring",
    profile="chrome",
    platform="windows",
    session_id="login-flow-1",
    full_dump=True,
)

# Step 2: Submit credentials reusing the exact session cookies & client
login_res = probe_tls_fingerprint(
    "https://target.example.com/auth/signin",
    engine="boring",
    method="POST",
    json_body={"user": "alice", "password": "secret"},
    session_id="login-flow-1",
    full_dump=True,
)

# Inspect stored cookies at any time
print(manage_tls_session("inspect", session_id="login-flow-1"))
```

### 3. Unfiltered Full Dump Mode (`full_dump=True`)

Default mode keeps output compact (`<= 2000` char previews, filtered WAF headers). Turn on **`full_dump=True`** (`--full-dump` in CLI) to remove filters and truncation caps:

- **All response headers** + ordered **`raw_headers` pairs** (preserving duplicate `Set-Cookie` headers)
- **Ordered request headers** (`request_debug.request_headers_ordered` & `request_headers_scope` proving custom `header_order` alignment)
- **Full cookie objects** (`name`, `value`, `domain`, `path`, `http_only`, `secure`)
- **Complete redirect hop history** across all 4 engines (`status_code`, `url`, headers per hop)
- **Unlimited untruncated response body** (+ `body_base64` via `include_binary_base64=True` for binary payloads)
- **BoringSSL peer certificate** details & PEM (with `engine="boring"`) and **full X.509 extensions / PEMs / shared ciphers** (with `analyze_tls`)

### 4. Low-Level TLS, HTTP/2 & Header Overrides

- **`ja3`**: Custom JA3 string override (`curl_cffi` & `utls`)
- **`akamai`**: Custom Akamai HTTP/2 fingerprint string (`curl_cffi`)
- **`header_order`**: Enforce exact HTTP header wire order across `curl_cffi`, `boring` (`OrigHeaderMap`), and `utls`
- **`platform`**: Spoof OS (`windows`, `macos`, `linux`, `android`, `ios`) on both `boring` and `utls`
- **`http_version`**: Force `http1.1`, `http2`, or `http3` (`http3` on `curl_cffi`)
- **`tls_options`**: Fine-grained native flags (e.g. `{"permute_extensions": true, "grease_enabled": true}` on `boring`/`curl_cffi`, or `{"h2_settings": ..., "pseudo_header_order": ..., "connection_flow": ..., "random_tls_extension_order": true}` on `utls`; set `{"browser_headers": false}` on `utls` if you explicitly want raw minimal headers)

### 5. WAF Detection & Baseline Proof

Every HTTP probe automatically summarizes WAF/CDN signals (`cf-ray`, `cf-mitigated`, `x-datadome`, `x-amz-cf-id`, `x-akamai-transformed`, `x-sucuri-id`, `x-px`) and, when `compare_baseline=True`, runs a side-by-side OpenSSL control request so you know immediately if status differences (`403` vs `200`) are caused by TLS fingerprinting.

---

## Installation & Setup

### 1. Clone and create a virtual environment

```bash
git clone https://github.com/KMG305/tls-analyzer-bypass-mcp.git
cd tls-analyzer-bypass-mcp

python -m venv .venv
```

Activate the virtual environment:

- **Windows (PowerShell):** `.\.venv\Scripts\Activate.ps1`
- **macOS / Linux:** `source .venv/bin/activate`

### 2. Install dependencies

```bash
pip install -r requirements.txt
```

### 3. Verify tests

```bash
python -m unittest discover -s tests -v
```

---

## Configuring MCP for AI Clients

The MCP server uses `stdio` transport ([`mcp_server.py`](./mcp_server.py)) and always points your AI host directly to the project's `.venv` Python binary so all TLS backends load cleanly regardless of working directory.

### Windows (`Claude Desktop` / `OpenCode` / `Cursor` / `Antigravity`)

```json
{
  "mcpServers": {
    "tls-analyzer-bypass-mcp": {
      "command": "C:\\path\\to\\tls-analyzer-bypass-mcp\\.venv\\Scripts\\python.exe",
      "args": [
        "C:\\path\\to\\tls-analyzer-bypass-mcp\\mcp_server.py"
      ]
    }
  }
}
```

### macOS / Linux

```json
{
  "mcpServers": {
    "tls-analyzer-bypass-mcp": {
      "command": "/absolute/path/to/tls-analyzer-bypass-mcp/.venv/bin/python",
      "args": [
        "/absolute/path/to/tls-analyzer-bypass-mcp/mcp_server.py"
      ]
    }
  }
}
```

### Claude Code

```bash
claude mcp add tls-analyzer-bypass-mcp -- /absolute/path/to/.venv/bin/python /absolute/path/to/mcp_server.py
```

---

## CLI Quick Reference

```bash
# 1. Raw TLS handshake + full X.509 extensions & PEM certificate chain
python tls_analyzer.py tls.browserleaks.com --full-dump

# 2. Probe TLSv1.0 - TLSv1.3 version support matrix
python tls_analyzer.py cloudflare.com --versions

# 3. Compare all 4 engines side-by-side against one target
python tls_analyzer.py cloudflare.com --engines curl_cffi,boring,utls,openssl --compare-profiles chrome

# 4. POST JSON using BoringSSL (wreq), Windows emulation, custom header order, and full dump
python tls_analyzer.py https://httpbin.org/post --engine boring --fingerprint chrome --platform windows --method POST --header-order "Content-Type,User-Agent" --json '{"hello":"world"}' --full-dump

# 5. Stateful multi-step session with Go uTLS + SOCKS5/HTTP proxy
python tls_analyzer.py https://target.example.com/login --engine utls --fingerprint chrome --session myflow --proxy http://127.0.0.1:8080 --full-dump

# 6. Inspect exact JA3 / JA4 / Akamai H2 & UA emitted on the wire
python tls_analyzer.py --self-fingerprint chrome --engine boring --full-dump

# 7. Security audit (score + grade + findings); exit code 2 if anything >= "high" is found (CI-friendly)
python tls_analyzer.py example.com --audit --fail-on high --expiry-warn-days 21
```

Sample `--audit` output (abridged):

```json
{
  "success": true,
  "host": "expired.example.org",
  "score": 35,
  "grade": "F",
  "findings": [
    { "severity": "critical", "code": "CERT_EXPIRED", "title": "Certificate has expired", "recommendation": "Renew and deploy a new certificate immediately." },
    { "severity": "medium", "code": "LEGACY_PROTOCOL_ENABLED", "title": "TLSv1.1 is enabled" }
  ]
}
```

Scoring: start at 100, subtract 40 / 25 / 10 / 3 per `critical` / `high` / `medium` / `low` finding; any `critical` finding forces grade `F`. Grades: A ≥ 90, B ≥ 80, C ≥ 65, D ≥ 50.

---

## REST API (FastAPI)

Start the API server:

```bash
python app.py
```

- **Root Metadata:** `http://127.0.0.1:8000/`
- **Interactive Swagger Docs:** `http://127.0.0.1:8000/docs`

Configuration via environment variables:

| Variable | Default | Purpose |
|---|---|---|
| `TLS_ANALYZER_HOST` | `127.0.0.1` | Bind address (keep loopback unless you add authentication) |
| `TLS_ANALYZER_PORT` | `8000` | Listen port |
| `TLS_ANALYZER_API_KEY` | *(unset)* | When set, every `/api/*` route requires `X-API-Key: <key>` or `Authorization: Bearer <key>` (`/`, `/health`, `/docs` stay open) |

> [!WARNING]
> This API makes outbound connections to arbitrary hosts on behalf of the caller. If you bind it to anything other than loopback, always set `TLS_ANALYZER_API_KEY`.

| Method & Path | Description |
|---|---|
| `GET /` | API metadata and endpoint index |
| `GET /health` | Liveness check |
| `GET /api/profiles` | Full catalog of all 4 engines, aliases, platforms, and profiles |
| `POST /api/analyze` | Raw TLS handshake + X.509 chain (+ `full_dump`) |
| `POST /api/audit` | Security audit: score, grade and findings |
| `POST /api/versions` | `TLSv1.0`–`TLSv1.3` matrix probe |
| `POST /api/fingerprint` | Single/session HTTP request via any engine (+ `full_dump`, `session_id`) |
| `POST /api/compare-profiles` | Side-by-side multi-profile / multi-engine comparison |
| `POST /api/self-fingerprint` | Live wire JA3 / JA4 / Akamai H2 verification |
| `GET /api/sessions` | List active persistent cookie/TLS sessions |
| `GET /api/sessions/{session_id}` | Inspect stored cookies and metadata for a session |
| `POST /api/sessions/{session_id}/clear` | Clear cookies inside an active session |
| `DELETE /api/sessions/{session_id}` | Close a specific session |
| `DELETE /api/sessions` | Close all active sessions |

---

## Project Structure

```text
tls-analyzer-bypass-mcp/
├── .github/
│   └── workflows/
│       └── ci.yml                      # Ruff lint + unittest matrix (Ubuntu/Windows, Python 3.11–3.13)
├── docs/
│   └── swagger-ui.png                  # Live FastAPI Swagger UI (/docs) screenshot
├── tls_analyzer.py                     # Core socket engine, X.509 parser, security audit, high-level API & CLI
├── tls_engines.py                      # Engine drivers (curl_cffi, boring, utls, openssl), presets & SessionRegistry
├── mcp_server.py                       # Official MCP stdio server exposing 8 AI tools
├── app.py                              # FastAPI REST API + OpenAPI /docs (optional API-key auth)
├── tests/
│   ├── test_analyzer.py                # Unit & local HTTPS integration tests (stdlib unittest)
│   └── test_audit.py                   # Security audit scoring + REST auth tests
├── pyproject.toml                      # Ruff configuration
├── .mcp.json                           # Project-level MCP config
├── claude_desktop_config.example.json  # Example Desktop MCP configuration
├── requirements.txt                    # Python dependencies
├── LICENSE                             # MIT License
└── .gitignore                          # Excludes .venv/, __pycache__/, caches, .env
```

---

## License

Licensed under the **MIT License**. See [LICENSE](./LICENSE) for full terms.