CodeQL 文档

边界错误的写入

ID: cpp/badly-bounded-write
Kind: problem
Security severity: 9.3
Severity: error
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-120
   - external/cwe/cwe-787
   - external/cwe/cwe-805
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

程序执行缓冲区复制或写入操作,但对复制大小的上限设置不正确。如果输入足够长,将导致目标缓冲区溢出。除了导致程序不稳定之外,还存在一些技术可以让攻击者利用此漏洞执行任意代码。

建议

使用预处理器定义来指定缓冲区的大小,并将相同的定义用作 strncpysnprintf 等函数的参数。这种技术将确保始终正确指定缓冲区大小,从而避免溢出。

示例

void congratulateUser(const char *userName)
{
	char buffer[80];

	// BAD: even though snprintf is used, this could overflow the buffer
	// because the size specified is too large.
	snprintf(buffer, 256, "Congratulations, %s!", userName);

	MessageBox(hWnd, buffer, "New Message", MB_OK);
}

在此示例中,开发人员使用了 snprintf 来控制可以写入 buffer 的最大字符数。不幸的是,由于代码首次编写后可能进行了修改,因此仍然可能发生有限的缓冲区溢出,因为 snprintf 的大小参数大于缓冲区的实际大小。

要解决此问题,可以将 snprintf 的第二个参数更改为 80,或者将缓冲区扩展到 256 个字符。另一种改进方法是使用预处理器定义,以便只在一个地方指定大小,从而可能防止将来再次出现此问题。

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私