analitics

Pages

Sunday, November 29, 2026

tkinter : basic security & DNS audit tool with httpx

Introduction to HTTPX and Security HTTPX is a modern Python HTTP client supporting sync and async requests, HTTP/1.1 and HTTP/2, connection pooling, and proxies.
In security audits, HTTPX helps enforce TLS verification (verify=True), set granular timeouts, limit connections, control redirects (follow_redirects=False), and inspect response headers, CDNs, and DNS-over-HTTPS.
Best practices: keep TLS verification enabled, set timeouts and connection limits, use a clear User-Agent with controlled pacing, and reuse client context managers.
Let's see the source code:
import importlib.util
import queue
import sys
import threading
import time
import tkinter as tk
from tkinter import scrolledtext
from urllib.parse import urlparse

REQUIRED = ["tkinter", "httpx"]
OPTIONAL = ["h2"]

missing_req = [p for p in REQUIRED if importlib.util.find_spec(p) is None]
if missing_req:
    print("Lipsesc pachete obligatorii:", ", ".join(missing_req))
    print("Instaleaza din Pip in Pydroid 3: httpx")
    sys.exit(1)

import httpx

HAS_H2 = importlib.util.find_spec("h2") is not None
missing_opt = [p for p in OPTIONAL if importlib.util.find_spec(p) is None]

CORE_HEADERS = [
    "strict-transport-security",
    "x-content-type-options",
    "content-security-policy",
    "x-frame-options",
]


def extract_host(url: str) -> str:
    parsed = urlparse(url)
    return (parsed.hostname or "").strip()


def evaluate_medium_headers(url: str, resp: httpx.Response) -> list[str]:
    out: list[str] = []
    h = {k.lower(): v for k, v in resp.headers.items()}
    ctype = h.get("content-type", "")
    is_html = "text/html" in ctype.lower()

    out.append(f"Status: {resp.status_code} | HTTP: {resp.http_version} | Type: {ctype or 'n/a'}")

    if resp.status_code in (301, 302, 303, 307, 308):
        out.append(f"  [REDIRECT] Location: {h.get('location', 'MISSING')}")
        return out

    csp_val = h.get("content-security-policy", "")
    has_frame_ancestors = "frame-ancestors" in csp_val.lower()

    for name in CORE_HEADERS:
        val = h.get(name)
        if name == "strict-transport-security":
            if not url.startswith("https://"):
                out.append("  strict-transport-security: N/A (HTTP)")
            else:
                out.append(f"  strict-transport-security: {val if val else 'MISSING (med)'}")
        elif name == "x-content-type-options":
            out.append(f"  x-content-type-options: {val if val else 'MISSING (med)'}")
        elif name == "content-security-policy":
            if val:
                out.append(f"  content-security-policy: PRESENT ({len(val)} chars)")
            else:
                lvl = "MISSING (med)" if is_html else "MISSING (low/non-html)"
                out.append(f"  content-security-policy: {lvl}")
        elif name == "x-frame-options":
            if val:
                out.append(f"  x-frame-options: {val}")
            elif has_frame_ancestors:
                out.append("  x-frame-options: COVERED BY CSP frame-ancestors")
            else:
                lvl = "MISSING (med)" if is_html else "MISSING (low/non-html)"
                out.append(f"  x-frame-options: {lvl}")

    return out


def check_cloudflare(client: httpx.Client, host: str, resp_headers: dict[str, str]) -> list[str]:
    out: list[str] = ["  [Cloudflare]"]
    cf_ray = resp_headers.get("cf-ray")
    cf_cache = resp_headers.get("cf-cache-status")
    server = resp_headers.get("server", "")

    is_cf = bool(cf_ray or "cloudflare" in server.lower())
    out.append(
        f"    Detected: {'YES' if is_cf else 'NO'} "
        f"(server={server or 'n/a'}, cf-ray={cf_ray or 'n/a'}, cache={cf_cache or 'n/a'})"
    )

    if is_cf and host:
        try:
            tr = client.get(f"https://{host}/cdn-cgi/trace", timeout=5.0)
            if tr.status_code == 200 and "colo=" in tr.text:
                kv = dict(line.split("=", 1) for line in tr.text.splitlines() if "=" in line)
                out.append(
                    f"    Trace: colo={kv.get('colo', 'n/a')} | http={kv.get('http', 'n/a')} "
                    f"| tls={kv.get('tls', 'n/a')} | warp={kv.get('warp', 'n/a')}"
                )
        except httpx.HTTPError:
            out.append("    Trace: unavailable")

    return out


def doh_query(client: httpx.Client, provider: str, domain: str, rtype: str) -> tuple[list[str], bool]:
    if provider == "google":
        url = "https://dns.google/resolve"
    else:
        url = "https://cloudflare-dns.com/dns-query"

    params = {"name": domain, "type": rtype}
    req_headers = {"Accept": "application/dns-json"}

    r = client.get(url, params=params, headers=req_headers, timeout=6.0)
    r.raise_for_status()
    data = r.json()
    ad_flag = bool(data.get("AD", False))
    answers = [str(item.get("data", "")) for item in data.get("Answer", []) if item.get("data")]
    return answers, ad_flag


def check_dns_doh(client: httpx.Client, host: str) -> list[str]:
    out: list[str] = [f"  [DNS DoH: {host}]"]
    if not host:
        out.append("    Invalid host")
        return out

    for rtype in ("A", "AAAA", "NS"):
        g_ans, c_ans = [], []
        g_ad, c_ad = False, False
        g_err, c_err = "", ""

        try:
            g_ans, g_ad = doh_query(client, "google", host, rtype)
        except httpx.HTTPError as e:
            g_err = str(e)

        try:
            c_ans, c_ad = doh_query(client, "cloudflare", host, rtype)
        except httpx.HTTPError as e:
            c_err = str(e)

        g_txt = ",".join(g_ans[:3]) if g_ans else (f"ERR:{g_err[:25]}" if g_err else "none")
        c_txt = ",".join(c_ans[:3]) if c_ans else (f"ERR:{c_err[:25]}" if c_err else "none")
        match = "OK" if (not g_err and not c_err and set(g_ans) == set(c_ans)) else "DIFF/ERR"
        out.append(f"    {rtype}: G=[{g_txt}](AD={g_ad}) | CF=[{c_txt}](AD={c_ad}) -> {match}")

    return out


class App:
    def __init__(self, root: tk.Tk) -> None:
        self.root = root
        self.root.title("HTTP + CF + DoH Audit")

        self.q: queue.Queue[tuple[str, str]] = queue.Queue()
        self.stop_flag = threading.Event()

        tk.Label(self.root, text="URL-uri / domenii:").pack(anchor="w", padx=6, pady=(4, 2))
        self.urls_box = tk.Text(self.root, height=3)
        self.urls_box.pack(fill=tk.X, padx=6)
        self.urls_box.insert("1.0", "https://google.com\nhttps://cloudflare.com\n")

        row1 = tk.Frame(self.root)
        row1.pack(fill=tk.X, padx=6, pady=(4, 2))

        tk.Label(row1, text="Pauza(s):").pack(side=tk.LEFT)
        self.delay_var = tk.StringVar(value="0.5")
        tk.Entry(row1, textvariable=self.delay_var, width=4).pack(side=tk.LEFT, padx=(2, 6))

        self.chk_cf = tk.BooleanVar(value=True)
        tk.Checkbutton(row1, text="CF", variable=self.chk_cf).pack(side=tk.LEFT)

        self.chk_doh = tk.BooleanVar(value=True)
        tk.Checkbutton(row1, text="DoH", variable=self.chk_doh).pack(side=tk.LEFT)

        row2 = tk.Frame(self.root)
        row2.pack(fill=tk.X, padx=6, pady=(2, 4))

        self.start_btn = tk.Button(row2, text="Start", command=self.start)
        self.start_btn.pack(side=tk.LEFT, padx=(0, 6))

        self.stop_btn = tk.Button(row2, text="Stop", command=self.stop, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=(0, 6))

        tk.Button(row2, text="Clear", command=self.clear).pack(side=tk.LEFT)

        self.status_var = tk.StringVar(value="Ready")
        tk.Label(self.root, textvariable=self.status_var, anchor="w").pack(fill=tk.X, padx=6)

        self.out = scrolledtext.ScrolledText(self.root, height=12)
        self.out.pack(fill=tk.BOTH, expand=True, padx=6, pady=(2, 6))
        self.out.configure(state=tk.DISABLED)

        self.log("Pachete OK: tkinter, httpx")
        if missing_opt:
            self.log("Optional lipsa: " + ", ".join(missing_opt) + " (HTTP/1.1)")
        else:
            self.log("Optional OK: h2 (HTTP/2)")

        self.poll()

    def log(self, msg: str) -> None:
        self.out.configure(state=tk.NORMAL)
        self.out.insert(tk.END, msg + "\n")
        self.out.see(tk.END)
        self.out.configure(state=tk.DISABLED)

    def clear(self) -> None:
        self.out.configure(state=tk.NORMAL)
        self.out.delete("1.0", tk.END)
        self.out.configure(state=tk.DISABLED)

    def start(self) -> None:
        urls = []
        for line in self.urls_box.get("1.0", tk.END).splitlines():
            u = line.strip()
            if u:
                if not u.startswith(("http://", "https://")):
                    u = "https://" + u
                urls.append(u)

        if not urls:
            self.log("[!] Niciun URL.")
            return

        try:
            delay = max(0.1, float(self.delay_var.get().strip()))
        except ValueError:
            delay = 0.5

        self.stop_flag.clear()
        self.start_btn.configure(state=tk.DISABLED)
        self.stop_btn.configure(state=tk.NORMAL)
        self.status_var.set("Running...")

        threading.Thread(
            target=self.worker,
            args=(urls, delay, self.chk_cf.get(), self.chk_doh.get()),
            daemon=True,
        ).start()

    def stop(self) -> None:
        self.stop_flag.set()
        self.status_var.set("Stopping...")

    def worker(self, urls: list[str], delay: float, run_cf: bool, run_doh: bool) -> None:
        timeout = httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=5.0)
        headers = {"User-Agent": "AuthorizedSecurityAudit/1.2"}

        with httpx.Client(
            http2=HAS_H2,
            timeout=timeout,
            headers=headers,
            verify=True,
            follow_redirects=False,
        ) as client:
            for i, url in enumerate(urls, start=1):
                if self.stop_flag.is_set():
                    self.q.put(("log", "[!] Oprit."))
                    break

                self.q.put(("status", f"Checking {i}/{len(urls)}: {url}"))
                lines = [f"=== {url} ==="]
                host = extract_host(url)

                try:
                    r = client.get(url)
                    h_low = {k.lower(): v for k, v in r.headers.items()}
                    lines.extend(evaluate_medium_headers(url, r))
                    if run_cf:
                        lines.extend(check_cloudflare(client, host, h_low))
                except httpx.HTTPError as e:
                    lines.append(f"  [!] HTTP/TLS Eroare: {e}")

                if run_doh and not self.stop_flag.is_set():
                    lines.extend(check_dns_doh(client, host))

                self.q.put(("log", "\n".join(lines)))

                if i < len(urls) and not self.stop_flag.is_set():
                    time.sleep(delay)

        self.q.put(("done", "Done"))

    def poll(self) -> None:
        while not self.q.empty():
            kind, val = self.q.get_nowait()
            if kind == "log":
                self.log(val)
            elif kind == "status":
                self.status_var.set(val)
            elif kind == "done":
                self.status_var.set(val)
                self.start_btn.configure(state=tk.NORMAL)
                self.stop_btn.configure(state=tk.DISABLED)
        self.root.after(100, self.poll)


if __name__ == "__main__":
    root = tk.Tk()
    App(root)
    root.mainloop()