CodeQL 文档

无界写入

ID: cpp/unbounded-write
Kind: path-problem
Security severity: 9.3
Severity: error
Precision: medium
Tags:
   - reliability
   - security
   - external/cwe/cwe-120
   - external/cwe/cwe-787
   - external/cwe/cwe-805
Query suites:
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

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

程序执行缓冲区复制或写入操作,没有对复制大小的上限限制。意外的过长输入到达此代码将导致缓冲区溢出。除了导致程序不稳定之外,还存在一些技术可以让攻击者利用此漏洞来执行任意代码。

建议

始终控制缓冲区复制和缓冲区写入操作的长度。应使用 strncpy 代替 strcpy,使用 snprintf 代替 sprintf,在其他情况下,应优先使用 'n-variant' 函数。

示例

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

	// BAD: this could overflow the buffer if the UserName is long
	sprintf(buffer, "Congratulations, %s!", userName);

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

在此示例中,对 sprintf 的调用可能会导致 buffer 溢出。如果参数 userName 过长,导致结果字符串超过允许的 80 个字符,就会发生这种情况。

为了解决问题,应将对 sprintf 的调用替换为 snprintf,并指定最大长度为 80 个字符。

参考

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