非短路逻辑的潜在危险使用¶
ID: cs/non-short-circuit
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- correctness
- logic
- external/cwe/cwe-480
- external/cwe/cwe-691
Query suites:
- csharp-security-and-quality.qls
逻辑运算符 |
和 &
(称为非短路运算符)不应使用。使用非短路运算符会降低程序效率,可能会造成混淆,甚至可能导致程序在第一个操作数充当第二个操作数的安全检查时崩溃。
建议¶
如果非短路运算符是无意的,则将该运算符替换为短路等效项。有时需要使用非短路运算符,因为操作数具有副作用。在这种情况下,更有效的方法是分别计算两个操作数,然后使用短路运算符组合结果。
示例¶
此示例将崩溃,因为即使 a
为 null,条件表达式的两个部分都将被计算。
class DangerousNonShortCircuitLogic
{
public static void Main(string[] args)
{
string a = null;
if (a != null & a.ToLower() == "hello world")
{
Console.WriteLine("The string said hello world.");
}
}
}
通过使用短路 AND 运算符可以轻松修复该示例。与前面的示例不同,该程序不会产生输出,但也不会崩溃。
class DangerousNonShortCircuitLogicFix
{
public static void Main(string[] args)
{
string a = null;
if (a != null && a.ToLower() == "hello world")
{
Console.WriteLine("The string said hello world.");
}
}
}