蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 getcustomer.asp 参数化 SQLite 查询、尾随空格修复与防 SQL 注入离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ajax-database.py
explore-ajax-database.py139 行
"""Offline Classic ASP AJAX + getcustomer.asp SQLite verification lab (IIS ASP & browser absent)."""
import html
import json
import sqlite3


def init_customers_db() -> sqlite3.Connection:
    conn = sqlite3.connect(":memory:")
    conn.row_factory = sqlite3.Row
    conn.execute(
        "CREATE TABLE CUSTOMERS ("
        "CUSTOMERID TEXT PRIMARY KEY, "
        "COMPANYNAME TEXT, "
        "CONTACTNAME TEXT, "
        "CITY TEXT, "
        "COUNTRY TEXT)"
    )
    conn.executemany(
        "INSERT INTO CUSTOMERS VALUES (?, ?, ?, ?, ?)",
        [
            ("ALFKI", "Alfreds Futterkiste", "Maria Anders", "Berlin", "Germany"),
            ("NORTS", "North/South", "Simon Crowther", "London", "UK"),
            ("WOLZA", "Wolski Zajazd", "Zbyszek Piestrzeniewicz", "Warszawa", "Poland"),
        ],
    )
    return conn


def getcustomer_asp_safe(conn: sqlite3.Connection, raw_q: str) -> str:
    """Safe parameterized version of getcustomer.asp with Trim() and HTML escaping."""
    cid = raw_q.strip()
    if not cid:
        return ""
    cur = conn.execute("SELECT * FROM CUSTOMERS WHERE CUSTOMERID = ?", (cid,))
    rows = cur.fetchall()
    parts = ["<table>"]
    for row in rows:
        for col in row.keys():
            parts.append(f"<tr><td><b>{html.escape(col)}</b></td>")
            parts.append(f"<td>{html.escape(str(row[col]))}</td></tr>")
    parts.append("</table>")
    return "".join(parts)


def main() -> None:
    cases = []
    conn = init_customers_db()

    # Case 1: Valid customer lookup & exact HTML <table> rendering
    alfki_html = getcustomer_asp_safe(conn, "ALFKI")
    expected1 = {
        "starts_table": True,
        "ends_table": True,
        "row_count": 5,
        "has_company": True,
        "has_city": True,
    }
    actual1 = {
        "starts_table": alfki_html.startswith("<table>"),
        "ends_table": alfki_html.endswith("</table>"),
        "row_count": alfki_html.count("<tr>"),
        "has_company": "<td><b>COMPANYNAME</b></td><td>Alfreds Futterkiste</td>" in alfki_html,
        "has_city": "<td><b>CITY</b></td><td>Berlin</td>" in alfki_html,
    }
    cases.append({
        "name": "getcustomer_sqlite_lookup_and_table",
        "summary": "Verify parameterized CUSTOMERID='ALFKI' lookup renders 5-row field/value HTML table.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Source HTML trailing-space bug (<option value="NORTS ">) handled via Trim
    raw_no_trim = conn.execute("SELECT COUNT(*) FROM CUSTOMERS WHERE CUSTOMERID = ?", ("NORTS ",)).fetchone()[0]
    trimmed_html = getcustomer_asp_safe(conn, "NORTS ")
    expected2 = {
        "untrimmed_matches": 0,
        "trimmed_finds_north_south": True,
        "trimmed_finds_london": True,
    }
    actual2 = {
        "untrimmed_matches": raw_no_trim,
        "trimmed_finds_north_south": "North/South" in trimmed_html,
        "trimmed_finds_london": "London" in trimmed_html,
    }
    cases.append({
        "name": "getcustomer_trim_trailing_space_bug",
        "summary": "Verify trimming 'NORTS ' fixes the trailing-space mismatch in source <option value='NORTS '>.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Parameterized query blocks SQL injection (' OR '1'='1)
    payload = "' OR '1'='1"
    safe_sqli_html = getcustomer_asp_safe(conn, payload)
    # Demonstrate why raw concatenation is dangerous (read-only in-memory count)
    unsafe_rows = conn.execute(f"SELECT * FROM CUSTOMERS WHERE CUSTOMERID='{payload}'").fetchall()
    expected3 = {
        "safe_html_empty_table": "<table></table>",
        "safe_leaked_rows": 0,
        "unsafe_concat_would_leak": 3,
    }
    actual3 = {
        "safe_html_empty_table": safe_sqli_html,
        "safe_leaked_rows": safe_sqli_html.count("<tr>"),
        "unsafe_concat_would_leak": len(unsafe_rows),
    }
    cases.append({
        "name": "getcustomer_sql_injection_blocked",
        "summary": "Verify parameterized query blocks ' OR '1'='1 injection while raw concatenation leaks 3 rows.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: Empty selection and unknown customer ID handling
    empty_out = getcustomer_asp_safe(conn, "")
    unknown_out = getcustomer_asp_safe(conn, "ZZZZZ")
    expected4 = {"empty_clears_hint": "", "unknown_empty_table": "<table></table>"}
    actual4 = {"empty_clears_hint": empty_out, "unknown_empty_table": unknown_out}
    cases.append({
        "name": "getcustomer_empty_and_unknown_id",
        "summary": "Verify empty selection clears #txtHint and unknown customer ID returns empty <table></table>.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    conn.close()
    print(json.dumps({
        "version": "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)",
        "cases": cases,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/asp-ajax-database-lab/explore-ajax-database.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-ajax-database.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:ASP

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a1425.zip

下载课程关联工程包:ASP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1422.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习