以 argv[0] 为 NULL 调用 C 程序

Invoke C program with argv[0] as NULL

以下内容来自一本关于安全 C 编码的书:

Vulnerabilities can occur when inadequate space is allocated to copy a program input such as a command-line argument. Although argv[0] contains the program name by convention, an attacker can control the contents of argv[0] to cause a vulnerability in the following program by providing a string with more than 128 bytes. Furthermore, an attacker can invoke this program with argv[0] set to NULL:

int main(int argc, char *argv[]) {
   /* ... */
   char prog_name[128];
   strcpy(prog_name, argv[0]);
   /* ... */
}

请问如果argv[0]是程序名,攻击者如何调用argv[0]设置为NULL的程序?

通过使用像 execlp() 这样的函数来启动程序,而不是 运行 从 shell 启动程序。所有 exec 函数都要求调用者显式提供 argv 元素,它们很容易违反约定。

execlp("program_name", (char *)NULL);

请注意,此功能实际上有一些用途。不是特别 argv[0] == NULL,而是使 argv[0] 与程序名称不同的选项。还有另一个约定,登录 shell 是 运行,- 作为 argv[0] 的第一个字符(因为传统的登录过程不提供将参数传递给shell).