public class Barrel
{
private static Monkey[] defaultMonkeys = new[] { new RhesusMonkey() };
private IEnumerable monkeys = null;
public IEnumerable Monkeys
{
get
{
if (monkeys == null)
monkeys = MonkeysReady() ? PopulateMonkeys() : defaultMonkeys;
return monkeys;
}
}
}
雖然屬性型別為 IEnumerable<T> 且無 setter,但惡意呼叫端可將回傳值轉型為 Monkey[] 並修改靜態陣列內容,影響其他 Barrel 實例。解決方案:快取 ReadOnlyCollection<T> 或真正不可變集合。
protected void Page_Load(object sender, EventArgs e)
{
string lastLogin = Request["LastLogin"];
if (String.IsNullOrEmpty(lastLogin))
{
var cookie = new HttpCookie("LastLogin", DateTime.Now.ToShortDateString());
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
}
else
{
Response.Write("Welcome back! You last logged in on " + lastLogin);
Response.Cookies["LastLogin"].Value = DateTime.Now.ToShortDateString();
}
}
Request["LastLogin"] 優先取查詢字串值而非 Cookie。攻擊者構造 URL ?LastLogin= 即可注入腳本。經典反射型 XSS。
private decimal? LookupPrice(XmlDocument doc)
{
XmlNode node = doc.SelectSingleNode("//products/product[id/text()='" + Request["itemId"] + "']/price");
return node == null ? null : Convert.ToDecimal(node.InnerText);
}
未驗證使用者輸入直接拼接 XPath 查詢,攻擊者可注入 XPath 代碼竊取/破壞 XML 資料。原理同 SQL 注入。所有後續用於執行操作的文本輸入皆面臨注入風險。