带分号的C参数显示为截断

问题描述 投票:3回答:1

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

./commandinject Story.txt;whoami

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

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

这对strchr()来说非常简单,至少应该如此。我的问题是,当处理字符串argv[1]时,分号上的任何内容都是不可见的。我有一些打印出所有argv数组值的调试代码,我逐步通过gdb,注入的命令是不可见的,据我所知。

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

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

将打印出来

This is the command->Story.txt

真是奇怪的是

system(argv[1]); 

仍然执行注入的代码。我确信这是一个简单的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);
}
c string argv
1个回答
3
投票

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

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

./commandinject "Story.txt;whoami"
© www.soinside.com 2019 - 2024. All rights reserved.