使用 'cin' 的危险操作¶
ID: cpp/dangerous-cin
Kind: problem
Security severity: 10.0
Severity: error
Precision: high
Tags:
- reliability
- security
- external/cwe/cwe-676
Query suites:
- cpp-code-scanning.qls
- cpp-security-extended.qls
- cpp-security-and-quality.qls
此规则查找在 std::cin
上调用 std::istream::operator>>
但未在之前调用 cin.width
的情况。由于可能发生缓冲区溢出,因此在未指定输入长度的情况下从 cin
消费输入是危险的。
建议¶
在消费输入之前,始终通过调用 cin.width
指定从 cin
预期接收的任何输入的长度。
示例¶
以下示例展示了从 cin
消费输入的危险方法和安全方法。
#define BUFFER_SIZE 20
void bad()
{
char buffer[BUFFER_SIZE];
// BAD: Use of 'cin' without specifying the length of the input.
cin >> buffer;
buffer[BUFFER_SIZE-1] = '\0';
}
void good()
{
char buffer[BUFFER_SIZE];
// GOOD: Specifying the length of the input before using 'cin'.
cin.width(BUFFER_SIZE);
cin >> buffer;
buffer[BUFFER_SIZE-1] = '\0';
}
参考资料¶
常见漏洞枚举:CWE-676。