从用户提供的路径中删除前导"../"

Removing leading "../" from user supplied path

本文关键字:删除 路径 用户      更新时间:2023-10-16

我有一个简单的c++应用程序,用于作为另一个用户在特定目录中执行perl脚本。

wrapper my-perl-script.pl

我想确保用户不会试图通过前缀"../"来欺骗c++应用程序在特定目录之外执行脚本。最好/最简单的方法是什么?

这是我的包装器源代码的精简版本。

int  main (int argc, char *argv[])
{
  /* set user here */
   stringstream userCmd;
   userCmd << "/path/to/scripts/";
   for ( int i = 1; i < argc; i++ ) {
      if ( i == 1) {
         // remove instances of ../ from the first argument
         userCmd << argv[i]
      }
      else {
         // add user supplied arguments for perl script to command
         userCmd << " " << argv[i];
      }
   }
  /* use system to execute the user command */

   return 0;
 }

我更喜欢使用字符串而不是原始指针/数组:

 int (int argc, char *argv[]) {
    std::string path (argv[1]);
    if (path.find("..") == std::string::npos)
    {
         //everything's fine
    }
    else
        std::cout << "No execution in parent directories allowed.";
}

不剪切".."的原因是,如果用户输入"../bad/evenworse/script.sh"

,路径将不再正确。

在Linux下,函数realpath()将为您提供所请求文件的绝对路径,您可以将其与您希望他们能够访问的基目录的路径进行比较。查看这里:realpath manpage

如果用户提供/path/to/scripts/../../../root/sensitive.sh, realpath()会将其转换为/root/sensitive.sh,您可以与允许的目录进行比较,并向用户抛出错误。

答案是不要删除相对路径。如果用户试图传递一个相对路径或完整的系统路径,那么他们是恶意的-直接终止应用程序。

int  main (int argc, char *argv[])
{
  if ( argc == 1 || argv[1][0] == '.' || argv[1][0] == '/' ) {
     return 0;
  }
  ...

感谢Johnathon Leffler对这个解决方案的评论