【问题标题】:How to retrieve the file that is outside of current directory using format specifier?如何使用格式说明符检索当前目录之外的文件?
【发布时间】:2018-11-19 08:24:36
【问题描述】:
char * read_file(char * filename) {
  char * file_contents = malloc(4096 * sizeof(char));

  FILE * file;
  file = fopen(filename, "r");

  fread(file_contents, 4096, sizeof(char), file);
  fclose(file);

  return file_contents;
}

char * read_flag() {
  return read_file("/flag.txt");  // outside of current working directory ;)
}

int main(int argc, char* argv[]) {
  setvbuf(stdin,  NULL, _IONBF, 0);
  setvbuf(stdout, NULL, _IONBF, 0);

  char * flag = read_flag();
  char input_filename[40];

  //Current directory is /home/problem
  printf("Current working directory is: ");
  system("pwd");

  printf("Enter a filename to print the contents of the file => ");
  scanf("%39s", input_filename);

  while ((directory_entry = readdir(directory)) != NULL) {
    if (strcmp(input_filename, directory_entry->d_name) == 0) {
      printf("File contents:\n");
      printf("%s\n", read_file(input_filename));

      return 0;
    }
  }
}

我需要打开此目录之外的文件(“/flag.txt”)。我在输入中尝试过类似“../”的内容以从该目录中退出,但它不起作用。我不确定如何输入文件名,以便它可以检索 /home/problem 目录之外的文件。我目前正在使用 Ubuntu 来执行此操作。我认为当我输入输入时,这个想法应该使用 %s%d 之类的东西。这是否可以使用任何说明符或利用该程序来读取全部内容?

【问题讨论】:

  • SQL 在哪里发挥作用?!
  • 你知道./ 是什么意思吗?你知道它指的是什么吗?顺便说一句:在您的程序片段中 directory 从未定义或初始化。
  • @joop 对不起,我错字了。应该是 /flag.txt 没有“。”

标签: c file code-injection format-specifiers


【解决方案1】:

如果文件位于解决方案目录之外,则需要使用\\/ 传递文件的完整路径。在基于 Windows 的系统上,这将是例如 C:\\folder\\file.txt。我目前不使用linux,但应该是/home/folder/file.txt

【讨论】:

  • 对于绝对路径名,添加前导斜杠:/home/folder/file.txt.
  • @joop 我执行代码时的当前目录是/home/problem。但是,我要访问的文件不在此目录中,即 ./flag.txt
  • @Y.M.您不能在不知道当前目录的情况下引用 ./flag.txt,因为第一部分 ./ 表示“在当前目录中”。所以当你说它在/home/problem 之外,名字是./file.txt 时,没有人知道那个文件在哪里。找出flag.txt 在哪个目录中。比如说它是文件夹 /somwhere/else/ ,然后您只需打开 /somwhere/else/flag.txt
【解决方案2】:

fopen 函数可能会失败,您应该处理它。阅读fopen(3)open(2)path_resolution(7)errno(3),了解可能的故障原因。详细信息可能是文件系统和计算机特定的(可能包括硬件故障)。

我建议在失败时使用perror(3)exit(3)(不要忘记将<stdio.h> 用于perror<stdlib.h> 用于exit):

FILE* file = fopen(filename, "r");
if (!file) {
    perror(filename);
    exit(EXIT_FAILURE);
}

然后你会在失败时收到一个有意义的错误消息(到stderr

我的猜测:您的根 file system(和 root directory / ...)没有 flag.txt 文件,您可能想要从 ~/flag.txt 检索您的 shell 所理解的内容。也许您想在您的主目录中检索它(然后构建它的文件路径,在 Linux 或 Unix 上使用 getenv("HOME");请参阅 this)。

另请参阅 globbingglob(7)

还可以阅读一些 Linux 编程书籍,也许是旧的 ALP

【讨论】:

  • 为什么fopen函数会失败?
  • 失败的原因有很多。阅读各种链接。而且由于故障不仅取决于您的程序,还取决于整个计算机的整个系统状态,因此您始终应该处理它。您无法合理地预测运行程序的计算机的状态。我猜你的Linux电脑没有/flag.txt(因为根目录/不是你的,而且hier(7)没有记录它应该有一个flag.txt文件)
猜你喜欢
  • 1970-01-01
  • 2017-11-16
  • 2011-03-10
  • 2017-03-05
  • 1970-01-01
  • 2022-11-23
  • 2019-12-08
  • 2017-10-11
  • 1970-01-01
相关资源
最近更新 更多