从用户提供的路径中删除前导"../"
Removing leading "../" from user supplied path
我有一个简单的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对这个解决方案的评论
相关文章:
- 将数组的地址分配给变量并删除
- 如何删除所有子路径?
- 如何自动获取我的项目的路径并删除一些文件
- 如何从 CLion 的运行窗口中删除程序项目路径
- 如何在g++中从链接库中删除路径
- 无法删除 c++ 中具有完整路径的文件
- 如何从std :: filesystem ::路径中删除引号
- PySide 2的Shiboken2删除了原始头文件的路径
- 尝试使用窗口注册表中的路径和 DeleteFile() 方法删除.exe文件
- 如何从 qmake 中的包含路径中删除项目的根目录
- 在 cpp 中验证路径:无法使用 ASCII 代码删除特殊字符
- 如何删除"..使用 Visual Studio 2012 类的文件路径中的 /' 令牌<filesystem>?
- 获取路径删除和串联字符
- 尝试从__FILE__中删除项目路径
- 如何删除回收站中路径过长的文件夹或文件
- C ++如何从路径字符串中删除文件名
- 从Makefile中的c可执行文件中删除硬编码的路径
- 从用户提供的路径中删除前导"../"
- 通过删除点链接和重复斜杠来规范Unix文件路径
- MinGW GCC.exe正在从路径中删除所有