【问题标题】:C++ check if path is outside a given directory [closed]C ++检查路径是否在给定目录之外[关闭]
【发布时间】:2021-04-18 02:55:41
【问题描述】:

检查给定路径 A 是否在另一个路径 B 之外的最简单方法是什么? 即:判断foo/../../bar/是否在foo/之外。

【问题讨论】:

  • 您也可以在 C++ 中包含 C 库,C 解决方案几乎总是适用于 C++。

标签: c++ security path filesystems


【解决方案1】:

这样的事情应该可以工作。另请注意,两条路径都应该存在。

#include <filesystem>
#include <algorithm>
#include <iterator>
#include <cassert>

bool isSafePath(const std::filesystem::path &root, const std::filesystem::path &child) {
    auto const normRoot = std::filesystem::canonical(root);
    auto const normChild = std::filesystem::canonical(child);
    
    auto itr = std::search(normChild.begin(), normChild.end(), 
                           normRoot.begin(), normRoot.end());
    
    return itr == normChild.begin();
}

int main(int argc, char **argv)
{
    assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg/index.html"));
    assert(isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/nvevg"));
    assert(isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../apps/CMakeLists.txt"));
    
    assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../../../../../etc/shadow"));
    assert(not isSafePath("/home/nvevg/projects/davshare/apps/", "/home/nvevg/projects/davshare/apps/../CMakeLists.txt"));
    assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/root/"));
    assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../www/"));
    assert(not isSafePath("www/root/nvevg", "www/root/nvevg/../../../../../../../../../etc/fstab"));
    
    return 0;
}

【讨论】:

  • 可以使用std::filesystem::path::lexically_relative 绕过现有的路径约束吗?
  • @qz- 如果我做对了,它不能——它只是给你一个相对于基础的路径,没有任何规范化(即不解析任何点-点/点路径组件),但是应该存在由 std::filesystem::canonical() 路径规范化的路径。所以你仍然需要找出这些点点是否在根之外的某个地方。
【解决方案2】:

有一个函数可以返回传递的两个函数之间的相对路径,称为relative。你可以检查结果路径是否以..开头

bool isSubPath(const std::string& base, const std::string& destination)
{
    std::string relative = std::filesystem::relative(destination, base);
    // size check for "." result
    // if path starts with ".." it's not subdir
    return relative.size() == 1 || relative[0] != '.' && relative[1] != '.';
}

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多