|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Load one page in a real browser engine and photograph it. |
| 3 | +
|
| 4 | +Run as its own process with the DAST environment's Python, where Playwright |
| 5 | +lives; nothing from the app is imported. The answer is one line of JSON on |
| 6 | +standard output. |
| 7 | +
|
| 8 | +Why a real browser and not a single request: many sites sit behind a bot |
| 9 | +check (Imperva, Cloudflare and others) that answers the first request with a |
| 10 | +small page whose script sets a cookie and reloads into the real site. curl |
| 11 | +sees that small page and stops. A stripped down headless browser is stopped |
| 12 | +by it and paints nothing. Full Chromium in its newer headless mode, with the |
| 13 | +automation flag hidden and an ordinary window, language and time zone, gets |
| 14 | +through most of them, so this waits for the page to replace itself before |
| 15 | +taking the picture. |
| 16 | +
|
| 17 | +Every request the page makes is checked against private addresses unless |
| 18 | +they are allowed, so a page cannot steer the browser into the network this |
| 19 | +server sits in. |
| 20 | +
|
| 21 | + browser_shot.py URL OUT.png --user-agent UA [--timeout 45] [--allow-private] |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import argparse |
| 27 | +import ipaddress |
| 28 | +import json |
| 29 | +import os |
| 30 | +import re |
| 31 | +import socket |
| 32 | +import sys |
| 33 | +import time |
| 34 | +from urllib.parse import urlparse |
| 35 | + |
| 36 | +BOT_CHECKS = [ |
| 37 | + ("Imperva", r"_Incapsula_Resource|Incapsula incident ID"), |
| 38 | + ("Cloudflare", r"/cdn-cgi/challenge-platform|<title>Just a moment\.\.\.</title>|cf-chl-"), |
| 39 | + ("Akamai", r"bm-verify|akamai-bot"), |
| 40 | + ("PerimeterX", r"px-captcha|_pxAppId"), |
| 41 | + ("DataDome", r"captcha-delivery\.com"), |
| 42 | +] |
| 43 | +HIDE_AUTOMATION = """ |
| 44 | +Object.defineProperty(navigator, 'webdriver', {get: () => undefined}); |
| 45 | +Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']}); |
| 46 | +Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]}); |
| 47 | +window.chrome = window.chrome || {runtime: {}}; |
| 48 | +""" |
| 49 | + |
| 50 | + |
| 51 | +def bot_check(html: str) -> str: |
| 52 | + if len(html or "") > 30000: |
| 53 | + return "" |
| 54 | + for name, pattern in BOT_CHECKS: |
| 55 | + if re.search(pattern, html or "", re.I): |
| 56 | + return name |
| 57 | + return "" |
| 58 | + |
| 59 | + |
| 60 | +_public: dict = {} |
| 61 | + |
| 62 | + |
| 63 | +def public(host: str) -> bool: |
| 64 | + if not host: |
| 65 | + return False |
| 66 | + if host in _public: |
| 67 | + return _public[host] |
| 68 | + try: |
| 69 | + addrs = {i[4][0] for i in socket.getaddrinfo(host, None)} |
| 70 | + ok = bool(addrs) and all(ipaddress.ip_address(a.split("%")[0]).is_global for a in addrs) |
| 71 | + except (OSError, ValueError): |
| 72 | + ok = False |
| 73 | + _public[host] = ok |
| 74 | + return ok |
| 75 | + |
| 76 | + |
| 77 | +def main() -> int: |
| 78 | + ap = argparse.ArgumentParser() |
| 79 | + ap.add_argument("url") |
| 80 | + ap.add_argument("out") |
| 81 | + ap.add_argument("--user-agent", required=True) |
| 82 | + ap.add_argument("--timeout", type=int, default=45) |
| 83 | + ap.add_argument("--allow-private", action="store_true") |
| 84 | + args = ap.parse_args() |
| 85 | + out = {"ok": False, "title": "", "url": args.url, "status": 0, "bot_check": "", |
| 86 | + "bot_check_seen": "", "engine": "", "error": ""} |
| 87 | + deadline = time.monotonic() + args.timeout |
| 88 | + try: |
| 89 | + from playwright.sync_api import sync_playwright |
| 90 | + except ImportError: |
| 91 | + out["error"] = "playwright is not installed" |
| 92 | + print(json.dumps(out)) |
| 93 | + return 0 |
| 94 | + |
| 95 | + proxy = (os.environ.get("https_proxy") or os.environ.get("HTTPS_PROXY") |
| 96 | + or os.environ.get("http_proxy") or os.environ.get("HTTP_PROXY")) |
| 97 | + launch = {"args": ["--disable-blink-features=AutomationControlled", "--no-sandbox", |
| 98 | + "--disable-dev-shm-usage", "--disable-gpu"]} |
| 99 | + if proxy: |
| 100 | + launch["proxy"] = {"server": proxy} |
| 101 | + try: |
| 102 | + with sync_playwright() as p: |
| 103 | + try: |
| 104 | + # Full Chromium in the new headless mode looks like a browser. |
| 105 | + browser = p.chromium.launch(channel="chromium", **launch) |
| 106 | + out["engine"] = "chromium" |
| 107 | + except Exception: # noqa: BLE001 - only the headless shell is there |
| 108 | + browser = p.chromium.launch(**launch) |
| 109 | + out["engine"] = "headless shell" |
| 110 | + ctx = browser.new_context(user_agent=args.user_agent, |
| 111 | + viewport={"width": 1280, "height": 800}, |
| 112 | + locale="en-US", timezone_id="America/New_York", |
| 113 | + ignore_https_errors=True) |
| 114 | + ctx.add_init_script(HIDE_AUTOMATION) |
| 115 | + if not args.allow_private: |
| 116 | + ctx.route("**/*", lambda route: route.continue_() |
| 117 | + if public(urlparse(route.request.url).hostname or "") |
| 118 | + else route.abort("addressunreachable")) |
| 119 | + page = ctx.new_page() |
| 120 | + # A check that passes reloads or redirects into the site. Imperva |
| 121 | + # also puts its script on the real pages, so the script being on |
| 122 | + # the final page says nothing; the page having moved on does. |
| 123 | + moves = {"n": 0} |
| 124 | + page.on("framenavigated", |
| 125 | + lambda frame: moves.__setitem__("n", moves["n"] + 1) |
| 126 | + if frame == page.main_frame else None) |
| 127 | + resp = page.goto(args.url, wait_until="domcontentloaded", |
| 128 | + timeout=max(5000, int((deadline - time.monotonic()) * 1000))) |
| 129 | + out["status"] = resp.status if resp else 0 |
| 130 | + # A bot check replaces itself with the site. Wait for that, then |
| 131 | + # for the site to settle, but never past the deadline. |
| 132 | + while time.monotonic() < deadline - 5: |
| 133 | + try: |
| 134 | + name = bot_check(page.content()) |
| 135 | + except Exception: # noqa: BLE001 - mid navigation |
| 136 | + name = "?" |
| 137 | + if not name or moves["n"] >= 2: |
| 138 | + break |
| 139 | + if name != "?": |
| 140 | + out["bot_check_seen"] = name |
| 141 | + page.wait_for_timeout(1500) |
| 142 | + try: |
| 143 | + page.wait_for_load_state("networkidle", |
| 144 | + timeout=max(1000, int(min(10, deadline - time.monotonic() - 4) * 1000))) |
| 145 | + except Exception: # noqa: BLE001 - a page that keeps polling never idles |
| 146 | + pass |
| 147 | + html = page.content() |
| 148 | + out["bot_check"] = bot_check(html) |
| 149 | + if out["bot_check"]: |
| 150 | + out["bot_check_seen"] = out["bot_check"] |
| 151 | + if moves["n"] >= 2: |
| 152 | + out["bot_check"] = "" |
| 153 | + out["navigations"] = moves["n"] |
| 154 | + out["title"] = (page.title() or "")[:200] |
| 155 | + out["url"] = page.url |
| 156 | + page.screenshot(path=args.out, full_page=False) |
| 157 | + out["ok"] = True |
| 158 | + browser.close() |
| 159 | + except Exception as exc: # noqa: BLE001 - every failure is an answer |
| 160 | + out["error"] = f"{type(exc).__name__}: {str(exc).splitlines()[0][:200]}" |
| 161 | + print(json.dumps(out)) |
| 162 | + return 0 |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + sys.exit(main()) |
0 commit comments