OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[Onnx FE] Fix vulnerability issue in sanitize_path() helper (#35550)
Alicja Miloszewska1d7787526921
diff --git a/src/common/util/include/openvino/util/file_util.hpp b/src/common/util/include/openvino/util/file_util.hppindex 66931b852b0..a4aacbb02fd 100644--- a/src/common/util/include/openvino/util/file_util.hpp+++ b/src/common/util/include/openvino/util/file_util.hpp@@ -93,10 +93,15 @@ inline auto path_to_string(const std::filesystem::path& path) -> decltype(path_treturn path_to_string(path.native());}-/// \brief Remove path components which would allow traversing up a directory tree.-/// \param path A path to file-/// \return A sanitized path-std::string sanitize_path(const std::string& path);+/**+ * @brief Resolves and validates a path relative to a base directory to prevent path traversal.+ *+ * @param base Base directory. If empty, the current working directory is used.+ * @param relative_path Path relative to @p dir .+ * @return Absolute, normalized path within @p dir.+ * @throw std::runtime_error if the resolved path escapes the base directory.+ */+std::filesystem::path sanitize_path(const std::filesystem::path& base, const std::filesystem::path& relative_path);/*** @brief Interface function to get absolute path of filediff --git a/src/common/util/src/file_util.cpp b/src/common/util/src/file_util.cppindex 891c20f57f3..a5742d18c2e 100644--- a/src/common/util/src/file_util.cpp+++ b/src/common/util/src/file_util.cpp@@ -104,12 +104,20 @@ void ov::util::recursive_iterate_files(const std::filesystem::path& path,}}-std::string ov::util::sanitize_path(const std::string& path) {- const auto colon_pos = path.find(':');- const auto sanitized_path = path.substr(colon_pos == std::string::npos ? 0 : colon_pos + 1);- const std::string to_erase = "/.\\";- const auto start = sanitized_path.find_first_not_of(to_erase);- return (start == std::string::npos) ? "" : sanitized_path.substr(start);+std::filesystem::path ov::util::sanitize_path(const std::filesystem::path& base,+ const std::filesystem::path& relative_path) {+ const auto base_dir = base.empty() ? std::filesystem::current_path() : base;+ const auto base_canon = std::filesystem::weakly_canonical(base_dir);+ auto merged_canon = std::filesystem::weakly_canonical(base_dir / relative_path);++ if (const auto rel = merged_canon.lexically_relative(base_canon); rel.empty() || *rel.begin() == "..") {+ std::stringstream ss;+ ss << "Path '" << path_to_string(relative_path) << "' resolves to '" << path_to_string(merged_canon)+ << "' which is outside the base directory '" << path_to_string(base_canon) << "'";+ throw std::runtime_error(ss.str());+ }++ return ov::util::get_absolute_file_path(merged_canon);}std::filesystem::path ov::util::get_absolute_file_path(const std::filesystem::path& path) {diff --git a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cppindex a977c86dc04..67f4e6b44f3 100644--- a/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp+++ b/src/frontends/onnx/frontend/src/core/graph_iterator_proto.cpp@@ -22,6 +22,7 @@#include "openvino/frontend/onnx/graph_iterator.hpp"#include "openvino/util/file_util.hpp"#include "transform.hpp"+#include "utils/tensor_external_data.hpp"namespace {// THis is copied from utils/common.hpp@@ -281,7 +282,7 @@ bool extract_tensor_external_data(ov::frontend::onnx::TensorMetaInfo& tensor_metstd::string m_sha1_digest{}; // for future usefor (const auto& entry : tensor_info->external_data()) {if (entry.key() == "location") {- ext_location = ov::util::sanitize_path(entry.value());+ ext_location = entry.value();} else if (entry.key() == "offset") {ext_data_offset = std::stoull(entry.value());} else if (entry.key() == "length") {@@ -290,8 +291,15 @@ bool extract_tensor_external_data(ov::frontend::onnx::TensorMetaInfo& tensor_metm_sha1_digest = entry.value();}}- const auto full_path = ov::util::get_absolute_file_path(- ov::util::path_join({graph_iterator->get_model_dir(), ov::util::make_path(ext_location)}));+ if (ext_location == detail::ORT_MEM_ADDR) {+ // Specific ONNX Runtime Case when it passes a model with self-managed data+ tensor_meta_info.m_is_raw = true;+ tensor_meta_info.m_tensor_data = reinterpret_cast<uint8_t*>(ext_data_offset);+ tensor_meta_info.m_tensor_data_size = ext_data_length;+ tensor_meta_info.m_external_location = std::make_shared<std::string>(ext_location);+ return true;+ }+ const auto full_path = ov::util::sanitize_path(graph_iterator->get_model_dir(), ov::util::make_path(ext_location));const int64_t file_size = ov::util::file_size(full_path);if ((file_size <= 0 && ext_data_length > 0) || ext_data_length > static_cast<uint64_t>(file_size) ||ext_data_offset > static_cast<uint64_t>(file_size) - ext_data_length) {@@ -305,14 +313,7 @@ bool extract_tensor_external_data(ov::frontend::onnx::TensorMetaInfo& tensor_met? static_cast<size_t>(ext_data_length): static_cast<size_t>(file_size) - static_cast<size_t>(ext_data_offset);auto memory_mode = graph_iterator->get_memory_management_mode();- if (ext_location == "*/_ORT_MEM_ADDR_/*") {- // Specific ONNX Runtime Case when it passes a model with self-managed data- tensor_meta_info.m_is_raw = true;- tensor_meta_info.m_tensor_data = reinterpret_cast<uint8_t*>(ext_data_offset);- tensor_meta_info.m_tensor_data_size = ext_data_length;- tensor_meta_info.m_external_location = std::make_shared<std::string>(ext_location);- return true;- } else if (memory_mode == External_MMAP) {+ if (memory_mode == External_MMAP) {auto cache = graph_iterator->get_mmap_cache();auto cached_mapped_memory = cache->find(full_path);std::shared_ptr<ov::MappedMemory> mapped_memory;diff --git a/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp b/src/frontends/onnx/frontend/src/utils/tensor_external_data.cppindex 78bb94d97a4..605c3aacd46 100644--- a/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp+++ b/src/frontends/onnx/frontend/src/utils/tensor_external_data.cpp@@ -18,7 +18,7 @@ namespace detail {TensorExternalData::TensorExternalData(const TensorProto& tensor) {for (const auto& entry : tensor.external_data()) {if (entry.key() == "location") {- m_data_location = ov::util::sanitize_path(entry.value());+ m_data_location = entry.value();} else if (entry.key() == "offset") {m_offset = std::stoull(entry.value());} else if (entry.key() == "length") {@@ -41,10 +41,13 @@ TensorExternalData::TensorExternalData(const std::string& location, size_t offseBuffer<ov::MappedMemory> TensorExternalData::load_external_mmap_data(const std::filesystem::path& model_dir,MappedMemoryHandles cache) const {- const auto full_path =- model_dir.empty()- ? ov::util::make_path(m_data_location)- : ov::util::get_absolute_file_path(ov::util::path_join({model_dir, ov::util::make_path(m_data_location)}));+ std::filesystem::path full_path;+ try {+ full_path = ov::util::sanitize_path(model_dir, ov::util::make_path(m_data_location));+ } catch (const std::runtime_error& e) {+ throw error::invalid_external_data{e.what()};+ }+const int64_t file_size = ov::util::file_size(full_path);if (file_size <= 0 || m_data_length > static_cast<uint64_t>(file_size) ||m_offset > static_cast<uint64_t>(file_size) - m_data_length) {@@ -68,10 +71,12 @@ Buffer<ov::MappedMemory> TensorExternalData::load_external_mmap_data(const std::}Buffer<ov::AlignedBuffer> TensorExternalData::load_external_data(const std::filesystem::path& model_dir) const {- const auto full_path =- model_dir.empty()- ? ov::util::make_path(m_data_location)- : ov::util::get_absolute_file_path(ov::util::path_join({model_dir, ov::util::make_path(m_data_location)}));+ std::filesystem::path full_path;+ try {+ full_path = ov::util::sanitize_path(model_dir, ov::util::make_path(m_data_location));+ } catch (const std::runtime_error& e) {+ throw error::invalid_external_data{e.what()};+ }std::ifstream external_data_stream(full_path, std::ios::binary | std::ios::in | std::ios::ate);if (external_data_stream.fail()) {diff --git a/src/frontends/onnx/tests/models/external_data/inner_scope/external_data_file_in_up_dir.prototxt b/src/frontends/onnx/tests/models/external_data/inner_scope/external_data_file_in_up_dir.prototxtindex dcc4c33d0c6..c2d2a958f80 100644--- a/src/frontends/onnx/tests/models/external_data/inner_scope/external_data_file_in_up_dir.prototxt+++ b/src/frontends/onnx/tests/models/external_data/inner_scope/external_data_file_in_up_dir.prototxt@@ -18,14 +18,6 @@ graph {key: "location",value: "../tensors_data/tensor.data"}- external_data {- key: "offset",- value: "4096"- }- external_data {- key: "length",- value: "16"- }data_location: 1}input {diff --git a/src/frontends/onnx/tests/onnx_reader_external_data.cpp b/src/frontends/onnx/tests/onnx_reader_external_data.cppindex 624cf46d354..f5449fdb538 100644--- a/src/frontends/onnx/tests/onnx_reader_external_data.cpp+++ b/src/frontends/onnx/tests/onnx_reader_external_data.cpp@@ -18,6 +18,7 @@#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/frontend/manager.hpp"#include "openvino/op/constant.hpp"+#include "utils/tensor_external_data.hpp"using namespace std;using namespace ov;@@ -253,10 +254,7 @@ TEST_P(OnnxFeMmapFixture, onnx_external_invalid_up_dir_path) {core.read_model(path);FAIL() << "Incorrect path to external data not detected";} catch (const Exception& ex) {- EXPECT_PRED_FORMAT2(testing::IsSubstring,- string("tensor.data, offset: 4096, "- "data_length: 16)"),- ex.what());+ EXPECT_PRED_FORMAT2(testing::IsSubstring, string("which is outside the base directory"), ex.what());} catch (...) {FAIL() << "Importing onnx model failed for unexpected reason";}diff --git a/src/tests/test_utils/common_test_utils/tests/file_util_test.cpp b/src/tests/test_utils/common_test_utils/tests/file_util_test.cppindex 5488405ea55..45c64db8ce7 100644--- a/src/tests/test_utils/common_test_utils/tests/file_util_test.cpp+++ b/src/tests/test_utils/common_test_utils/tests/file_util_test.cpp@@ -88,33 +88,6 @@ TEST(file_util, path_join) {}}-TEST(file_util, sanitize_path) {- {- string path = "../../tensor.data";- EXPECT_STREQ("tensor.data", ov::util::sanitize_path(path).c_str());- }- {- string path = "/../tensor.data";- EXPECT_STREQ("tensor.data", ov::util::sanitize_path(path).c_str());- }- {- string path = "..";- EXPECT_STREQ("", ov::util::sanitize_path(path).c_str());- }- {- string path = "workspace/data/tensor.data";- EXPECT_STREQ("workspace/data/tensor.data", ov::util::sanitize_path(path).c_str());- }- {- string path = "..\\..\\tensor.data";- EXPECT_STREQ("tensor.data", ov::util::sanitize_path(path).c_str());- }- {- string path = "C:\\workspace\\tensor.data";- EXPECT_STREQ("workspace\\tensor.data", ov::util::sanitize_path(path).c_str());- }-}-using namespace testing;class TrimFileTest : public Test {@@ -676,4 +649,48 @@ TEST_P(FileUtilTestP, create_directories) {std::filesystem::remove_all(test_dir);}++class SanitizePathTest : public ::testing::Test {+protected:+ std::filesystem::path base{std::filesystem::temp_directory_path() / "ov_sanitize_test_base"};+};++TEST_F(SanitizePathTest, valid_nested_relative_path) {+ const auto result = ov::util::sanitize_path(base, "workspace/data/tensor.data");+ EXPECT_EQ(result, base / "workspace/data/tensor.data");+}++TEST_F(SanitizePathTest, invalid_single_dotdot) {+ EXPECT_THROW(ov::util::sanitize_path(base, ".."), std::runtime_error);+}++TEST_F(SanitizePathTest, invalid_dotdot_prefix) {+ EXPECT_THROW(ov::util::sanitize_path(base, "../tensors_data/tensor.data"), std::runtime_error);+}++TEST_F(SanitizePathTest, invalid_absolute_path_outside_base) {+ EXPECT_THROW(ov::util::sanitize_path(base, "/../tensor.data"), std::runtime_error);+}++#ifdef _WIN32+TEST_F(SanitizePathTest, invalid_windows_absolute_path_different_drive) {+ EXPECT_THROW(ov::util::sanitize_path(base, "C:\\workspace\\tensor.data"), std::runtime_error);+}++TEST_F(SanitizePathTest, invalid_windows_dotdot_backslash) {+ EXPECT_THROW(ov::util::sanitize_path(base, "..\\..\\tensor.data"), std::runtime_error);+}+#endif++TEST_F(SanitizePathTest, empty_dir_uses_cwd) {+ const auto result = ov::util::sanitize_path("", "tensors/data.bin");+ const auto expected = ov::util::get_absolute_file_path(+ std::filesystem::weakly_canonical(std::filesystem::current_path() / "tensors/data.bin"));+ EXPECT_EQ(result, expected);+}++TEST_F(SanitizePathTest, empty_dir_dotdot_still_rejected) {+ EXPECT_THROW(ov::util::sanitize_path("", ".."), std::runtime_error);+}+} // namespace ov::test