UseAfterFree (Windows 驅動程式程式代碼QL 查詢)
概觀
此 CodeQL 查詢 具有高精確度,有助於 Bug 自動化,但有一些限制,因此無法偵測 UseAfterFree 瑕疵的所有案例。
在釋放配置記憶體區塊之後,就會發生UseAfterFree缺陷(也稱為「懸空指標」)。
這類情況下的行為是未定義的,實際上可能會有非預期的後果,包括記憶體損毀、使用不正確的值或任意程式代碼執行。
建議
在釋放指標之後,立即將指標設定為 NULL。
範例
在下列範例中,pSomePointer
只有在值不是零,而且重新pSomePointer
參考呼叫 Method
Status
之前,才會Status
再次核取 。 Status
不幸的是,在的兩個參考pSomePointer
之間已變更,這可讓您透過先前釋放的指標執行 對的呼叫pSomePointer->Method()
。
NTSTATUS Status = x();
if (Status != 0)
{
// Release pSomePointer if the call to x() failed
ExFreePool(pSomePointer);
}
Status = y();
if (Status == 0)
{
// Because Status may no longer be the same value than it was before the pointer was released,
// this code may be using pSomePointer after it was freed, potentially executing arbitrary code.
Status = pSomePointer->Method();
}
在更正的範例中, pSomePointer
會在釋放后立即設定為 NULL
,而要檢查的條件是否安全,可呼叫 pSomePointer->Method()
檢查此額外條件以防止可能的 Bug。
NTSTATUS Status = x();
if (Status != 0)
{
// Release pSomePointer if the call to x() failed
ExFreePool(pSomePointer);
// Setting pSomePointer to NULL after being freed
pSomePointer = NULL;
}
Status = y();
// If pSomePointer was freed above, its value must have been set to NULL
if (Status == 0 && pSomePointer != NULL)
{
Status = pSomePointer->Method();
}
其他詳細資料
您可以在 Microsoft GitHub CodeQL 存放庫中找到此查詢。 如需 Windows 驅動程式開發人員如何下載和執行 CodeQL 的詳細資訊,請參閱 CodeQL 和靜態工具標誌測試頁面。