带分号的 C 参数出现被截断

标签 c string argv

我正在做一项与 OWASP 命令注入(inject)相关的作业 Example 1 。简而言之,我接受一个参数(文件名),然后将其附加到字符串“cat”,因此我的程序捕获了提供的文件。如果我将用户输入直接传递给 system() 函数,用户可以潜入另一个由分号 ; 分隔的命令。例如:

./commandinject Story.txt;whoami

cat Story.txt 并打印当前用户。

我只是被要求检测分号,如果找到,则出错并请求另一个文件 - 循环直到给出有效输入。

这对于 strchr() 来说非常简单,至少应该是这样。 我的问题是,在处理字符串 argv[1] 时,从分号开始的任何内容都是不可见的。我有一些调试代码可以打印出所有 argv 数组值,并且我据我所知,单步执行 gdb 并且注入(inject)的命令是不可见的。

例如,当给出上面的输入时,代码

printf ("This is the command->%s\n", argv[1]);

将打印出来

This is the command->Story.txt

真正奇怪的是

system(argv[1]); 

仍然执行注入(inject)的代码。我确信我缺少的是一个简单的c-ism,但我希望得到一些帮助。

我应该注意,如果我在参数周围使用引号,我的代码可以正常工作并捕获分号。

#include <stdio.h>
#include <unistd.h>

#define COMMAND_SIZE 4096

int main(int argc, char **argv) {
  char cat[] = "cat ";
  char *command;
  char *commandRepeat;
  size_t commandLength;

  commandLength = strlen(cat) + strlen(argv[1]) + 1;
  command = (char *) malloc(commandLength);
  strncpy(command, cat, commandLength);
  strncat(command, argv[1], (commandLength - strlen(cat)) );

  // Search command string for ';'
  while(strchr(command, ';') != NULL){
    // ERROR, ask for filename again.
    // Use temporary buffer for user input
    commandRepeat = (char *) malloc(COMMAND_SIZE);
    printf("You used an invalid character ';'\nPlease enter the filename again: ");
    fgets(commandRepeat, COMMAND_SIZE, stdin);
    // Trim newline that fgets includes
    commandRepeat[strcspn(commandRepeat, "\n")] = '\0';

    // Prepare command string
    commandLength = strlen(cat) + strlen(commandRepeat) + 1;
    free(command);
    command = (char *) malloc(commandLength);
    strncpy(command, cat, commandLength);
    strncat(command, commandRepeat, (commandLength - strlen(cat)) );
    free(commandRepeat);
  }

  printf ("This is the command->%s\n", command);
  system(command);

  return (0);
}

最佳答案

shell 正在解释 ; 并运行下一个命令。如果您希望将其发送到您的程序,则需要将其放在引号中。

如果您的程序正常结束,您应该会看到 ; 执行后的位。

./commandinject "Story.txt;whoami"

关于带分号的 C 参数出现被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145683/

相关文章:

我们可以在 C 中反转这个字符串吗?

c - VS2013 假设 .c 文件的未识别符号的外部声明

mysql - 拆分逗号分隔字符串 --> FUNCTION db.CHARINDEX 不存在

string - 比较行并从匹配中创建新行

c++ - 使 argv 成为整数数组

c - 在 for 循环中打印方法后,C 中出现段错误

无法在 C 中为 "const char * const *my_array"赋值

c - 双指针字符操作

python - 有没有一种有效的方法可以将一个字符串拆分为两个字符串?

visual-studio-2010 - Visual Studio C++ 2010 __argv如何成为空指针?