From 8b78b676c1376ae28feccd957b03bbecea05eff1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0tampar?= Date: Thu, 12 Nov 2026 20:52:57 +0100 Subject: [PATCH] Adding vuln-test coverage for --multi-bit and --timeless (vulnserver listing and HTTP/2 endpoints) --- .github/workflows/tests.yml | 7 +- extra/vulnserver/vulnserver.py | 124 +++++++++++++++++++++++++++++++++ lib/core/settings.py | 2 +- lib/core/testing.py | 34 ++++++++- 4 files changed, 161 insertions(+), 6 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 98dedd5cd..9955c1ad2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -97,13 +97,14 @@ jobs: - name: Basic import test run: python -c "import sqlmap; import sqlmapapi" - - name: Install optional test deps (lxml, jinja2) + - name: Install optional test deps (lxml, jinja2, h2, cryptography) # lxml has no PyPy-2.7 wheel and 5.x is Py3-only, so it cannot be pip-installed there. The # tests that use it (test_xpath's real-XPath checks, and the --xpath/--ssti vuln-test # endpoints) skip themselves when the engine is unavailable, so these deps are only needed - # on the Py3 jobs. + # on the Py3 jobs. Same for h2/cryptography (vulnserver's HTTP/2 endpoint for --timeless and + # the reference-peer checks in test_http2). if: matrix.python-version != 'pypy-2.7' - run: python -m pip install -q lxml jinja2 + run: python -m pip install -q lxml jinja2 h2 cryptography - name: Unit tests # -B: do not write .pyc files. On Python 2 / PyPy a cached .pyc makes a module's __file__ diff --git a/extra/vulnserver/vulnserver.py b/extra/vulnserver/vulnserver.py index 0666edc48..d8564abb9 100644 --- a/extra/vulnserver/vulnserver.py +++ b/extra/vulnserver/vulnserver.py @@ -1492,6 +1492,22 @@ class ReqHandler(BaseHTTPRequestHandler): self.wfile.write(json.dumps({"error": {"message": str(ex)}}).encode(UNICODE_ENCODING)) return + if self.url == "/list": + # VULNERABLE: listing page whose (number of) rows depends on the injected 'min' value (e.g. for --multi-bit) + try: + with _lock: + _cursor.execute("SELECT id,name FROM users WHERE id>%s ORDER BY id" % self.params.get("min", "0")) + rows = _cursor.fetchall() + output = "" % "".join("
  • %s
  • " % (row[0], row[1]) for row in rows) + except Exception: + output = "error" + self.send_response(OK) + self.send_header("Content-type", "text/html; charset=%s" % UNICODE_ENCODING) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(output.encode(UNICODE_ENCODING)) + return + if self.url == "/echo": # A pure reflector: no engine of any kind behind it, it only shows the parameter back. Every # non-SQL switch must stay silent here. A differential built on "the page changed" is @@ -1776,6 +1792,114 @@ class ReqHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): return +def run_h2(address=LISTEN_ADDRESS, port=LISTEN_PORT + 1): + """ + Optional HTTP/2 (TLS) endpoint '/?id=1' (e.g. for --http2/--timeless), requiring 'h2' and 'cryptography' + Note: each stream is answered on its own thread with its own database connection (i.e. in order of completion) + """ + + import datetime + import socket + import ssl + + import h2.config + import h2.connection + import h2.events + + from cryptography import x509 + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID + + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"localhost")]) + now = datetime.datetime.utcnow() + cert = x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1)).not_valid_after(now + datetime.timedelta(days=1)).sign(key, hashes.SHA256()) + + handle, certFile = tempfile.mkstemp(suffix=".pem") + os.close(handle) + with open(certFile, "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) + f.write(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())) + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(certFile) + context.set_alpn_protocols(["h2"]) + local = threading.local() + + def _respond(conn, lock, sock, streamId, path): + if not hasattr(local, "db"): + local.db = sqlite3.connect(":memory:") + local.db.executescript(SCHEMA) + + try: + value = parse_qs(path.split('?', 1)[-1] if '?' in path else "").get("id", ["1"])[-1] + rows = local.db.execute("SELECT * FROM users WHERE id=%s LIMIT 0, 1" % value).fetchall() + status, body = "200", "%s" % "".join("%s" % _ for row in rows for _ in row) + except Exception as ex: + status, body = "500", "error: %s" % ex + + body = body.encode(UNICODE_ENCODING) + + with lock: + conn.send_headers(streamId, [(":status", status), ("content-length", str(len(body))), ("content-type", "text/html")]) + conn.send_data(streamId, body, end_stream=True) + sock.sendall(conn.data_to_send()) + + def _serve(sock): + conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=False)) + lock = threading.Lock() + paths = {} + + conn.initiate_connection() + sock.sendall(conn.data_to_send()) + + try: + while True: + data = sock.recv(65535) + if not data: + break + + with lock: + events = conn.receive_data(data) + sock.sendall(conn.data_to_send()) + + for event in events: + if isinstance(event, h2.events.RequestReceived): + paths[event.stream_id] = dict((_[0].decode() if isinstance(_[0], bytes) else _[0], _[1].decode() if isinstance(_[1], bytes) else _[1]) for _ in event.headers).get(":path", "/") + elif isinstance(event, h2.events.StreamEnded): + thread = threading.Thread(target=_respond, args=(conn, lock, sock, event.stream_id, paths.pop(event.stream_id, "/"))) + thread.daemon = True + thread.start() + except Exception: + pass + finally: + sock.close() + + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.settimeout(None) # Note: independent of (e.g. sqlmap's) default socket timeout, which would end the accept loop once idle + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind((address, port)) + server.listen(50) + + while True: + try: + client, _ = server.accept() + except socket.error: + continue + + try: + client.settimeout(None) + client = context.wrap_socket(client, server_side=True) + except Exception: + client.close() + continue + + thread = threading.Thread(target=_serve, args=(client,)) + thread.daemon = True + thread.start() + def run(address=LISTEN_ADDRESS, port=LISTEN_PORT): global _alive global _server diff --git a/lib/core/settings.py b/lib/core/settings.py index 500f2f14d..76ae2dafe 100644 --- a/lib/core/settings.py +++ b/lib/core/settings.py @@ -19,7 +19,7 @@ from lib.core.enums import OS from thirdparty import six # sqlmap version (...) -VERSION = "1.10.11.87" +VERSION = "1.10.11.88" TYPE = "dev" if VERSION.count('.') > 2 and VERSION.split('.')[-1] != '0' else "stable" TYPE_COLORS = {"dev": 33, "stable": 90, "pip": 34} VERSION_STRING = "sqlmap/%s#%s" % ('.'.join(VERSION.split('.')[:-1]) if VERSION.count('.') > 2 and VERSION.split('.')[-1] == '0' else VERSION, TYPE) diff --git a/lib/core/testing.py b/lib/core/testing.py index b919605bc..1f71bc1ec 100644 --- a/lib/core/testing.py +++ b/lib/core/testing.py @@ -96,6 +96,8 @@ def vulnTest(tests=None, label="vuln"): ("-u \"&echo=foobar*\" --flush-session", ("might be vulnerable to cross-site scripting",)), ("-u \"nosql?name=luther&password=x\" -p password --nosql --flush-session", ("is vulnerable to NoSQL injection", "back-end: 'MongoDB'", "NoSQL: GET parameter 'password'", "s3cr3t")), # NoSQL (MongoDB) operator-injection detection + blind regexp extraction ("-u \"graphql\" --graphql -T creds --flush-session --disable-hashing", ("found GraphQL endpoint", "introspection returned", "enumerated 6 injectable argument slot(s): 4 query, 2 mutation", "SQL injection via GraphQL (boolean-based)", "in-band data exposure", "back-end DBMS: 'SQLite'", "banner: '3.", "GraphQL database tables", "fetched 30 entries from table 'creds'", "db3a16990a0008a3b04707fdef6584a0", "GraphQL scan complete")), # GraphQL: endpoint detection + introspection + query-slots-first (mutations only as fallback) + boolean-blind/in-band + back-end fingerprint + batched blind dump of an injection-only table (SQLite-backed) + ("-u \"list?min=0\" --multi-bit --technique=B -T users --dump --flush-session", ("carries a multi-bit channel", "30 entries", "luther")), # --multi-bit: a listing page whose rows depend on the injected value carries several bits per request + ("-u \"?id=1\" --http2 --technique=T --timeless --dbms=sqlite --level=3 --risk=2 --banner --time-sec=5 --flush-session", ("turning on HTTP/2 timeless timing", "banner: '3.")), # --timeless: (SQLite heavy-query) time-based blind read by HTTP/2 response order (Note: --time-sec=5 as heavy queries scale with it) ("-u \"ldap/search?q=x\" --ldap --flush-session --disable-hashing", ("is vulnerable to LDAP injection", "Title: LDAP in-band data exposure", "LDAP: GET parameter 'q' in-band entries", "in-band data exposure", "LDAP scan complete")), # LDAP: error-based detection (unbalanced paren) + boolean oracle + directory attribute extraction via blind substring probing ("-u \"echo?q=x\" --xslt --flush-session --disable-hashing", ("no parameter appears to be injectable", "~is vulnerable to")), # reflection is not evaluation: a pure echo endpoint must not satisfy any non-SQL engine's oracle ("-u \"echo?q=x\" --xpath --flush-session --disable-hashing", ("no parameter appears to be injectable", "~is vulnerable to")), # same gate for --xpath (it used to confirm XPath injection from reflected text alone) @@ -133,6 +135,12 @@ def vulnTest(tests=None, label="vuln"): except ImportError: TESTS = tuple(_ for _ in TESTS if "--ssti" not in _[0]) logger.warning("skipping the SSTI vuln-test entry ('jinja2' not available)") + try: + __import__("h2") + __import__("cryptography") + except ImportError: + TESTS = tuple(_ for _ in TESTS if "" not in _[0]) + logger.warning("skipping the HTTP/2 vuln-test entry ('h2' or 'cryptography' not available)") # --test-filter / --test-skip narrow a (slow) full run to just the entries touching a change: # the needle is matched case-insensitively against each entry's command line and its expected @@ -236,6 +244,28 @@ def vulnTest(tests=None, label="vuln"): f.flush() base = "http://%s:%d/" % (address, port) + h2base = "" + + # optional HTTP/2 (TLS) endpoint (e.g. for --timeless) + if any("" in _[0] for _ in TESTS): + h2port = port + 1 if port < 65535 else port - 1 + thread = threading.Thread(target=vulnserver.run_h2, args=(address, h2port)) + thread.daemon = True + thread.start() + + for _ in xrange(20): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + if not s.connect_ex((address, h2port)): + h2base = "https://%s:%d/" % (address, h2port) + break + finally: + s.close() + time.sleep(0.5) + + if not h2base: + TESTS = tuple(_ for _ in TESTS if "" not in _[0]) + logger.warning("skipping the HTTP/2 vuln-test entry (unable to start HTTP/2 endpoint)") url = "%s?id=1" % base direct = "sqlite3://%s" % database tmpdir = tempfile.mkdtemp() @@ -260,10 +290,10 @@ def vulnTest(tests=None, label="vuln"): options = options.replace(u"\u0161u\u0107uraj", "sucuraj") checks = [check.replace(u"\u0161u\u0107uraj", "sucuraj") for check in checks] - for tag, value in (("", url), ("", base), ("", direct), ("", tmpdir), ("", request), ("", log), ("", multiple), ("", config), ("", url.replace("id=1", "id=MZ=%3d"))): + for tag, value in (("", url), ("", base), ("", direct), ("", tmpdir), ("", request), ("", log), ("", multiple), ("", config), ("", url.replace("id=1", "id=MZ=%3d")), ("", h2base)): options = options.replace(tag, value) - cmd = "%s \"%s\" %s --batch --non-interactive --debug --time-sec=1" % (sys.executable if ' ' not in sys.executable else '"%s"' % sys.executable, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "sqlmap.py")), options) + cmd = "%s \"%s\" %s --batch --non-interactive --debug%s" % (sys.executable if ' ' not in sys.executable else '"%s"' % sys.executable, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "sqlmap.py")), options, "" if "--time-sec" in options else " --time-sec=1") if "" in cmd: handle, tmp = tempfile.mkstemp()