Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ jobs:
mkw_platform_paths_tests \
mkw_runtime_config_tests \
mkw_nand_save_tests \
mkw_nand_guest_path_tests \
mkw_nand_settings_tests \
mkw_sc_serial_tests \
mkw_input_expr_tests \
Expand Down
5 changes: 5 additions & 0 deletions runtime/cmake/PlatformTests.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ target_include_directories(mkw_nand_save_tests PRIVATE "${MKW_TEST_RUNTIME_DIR}/
target_compile_features(mkw_nand_save_tests PRIVATE cxx_std_17)
add_test(NAME mkw_nand_save_tests COMMAND mkw_nand_save_tests)

add_executable(mkw_nand_guest_path_tests "${MKW_TEST_RUNTIME_DIR}/tests/nand_guest_path_tests.cpp")
target_include_directories(mkw_nand_guest_path_tests PRIVATE "${MKW_TEST_RUNTIME_DIR}/include")
target_compile_features(mkw_nand_guest_path_tests PRIVATE cxx_std_17)
add_test(NAME mkw_nand_guest_path_tests COMMAND mkw_nand_guest_path_tests)

add_executable(mkw_nand_settings_tests "${MKW_TEST_RUNTIME_DIR}/tests/nand_settings_tests.cpp")
find_package(Threads REQUIRED)
target_link_libraries(mkw_nand_settings_tests PRIVATE Threads::Threads)
Expand Down
49 changes: 49 additions & 0 deletions runtime/include/nand_guest_path.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#pragma once

#include <filesystem>
#include <optional>
#include <string>
#include <string_view>

namespace RuntimeNandGuestPath {

// A guest path component may only ever name an entry directly inside the directory it is
// appended to. ':' is refused on every host so a profile behaves the same everywhere: on
// Windows it forms a drive prefix ("C:"), which std::filesystem appends by *replacing* the
// path built so far, and an NTFS stream name ("file:stream").
inline bool IsSafeComponent(std::string_view component) {
if (component.empty() || component == "." || component == "..") {
return false;
}
if (component.find_first_of(":/\\") != std::string_view::npos ||
component.find('\0') != std::string_view::npos) {
return false;
}
// Belt and braces for any other host spelling of a root.
const std::filesystem::path part{std::string(component)};
return !part.has_root_name() && !part.has_root_directory();
}

// Appends a '/'-separated guest path below `root`, one component at a time. Empty
// components (leading, trailing or doubled slashes) are skipped; nullopt when any
// component could leave `root`.
inline std::optional<std::filesystem::path> AppendBelowRoot(const std::filesystem::path& root,
std::string_view guestPath) {
std::filesystem::path hostPath = root;
size_t cursor = 0;
while (cursor < guestPath.size()) {
const size_t slash = guestPath.find('/', cursor);
const size_t end = slash == std::string_view::npos ? guestPath.size() : slash;
if (end != cursor) {
const std::string_view component = guestPath.substr(cursor, end - cursor);
if (!IsSafeComponent(component)) {
return std::nullopt;
}
hostPath /= std::filesystem::path{std::string(component)};
}
cursor = end + 1;
}
return hostPath;
}

} // namespace RuntimeNandGuestPath
9 changes: 8 additions & 1 deletion runtime/src/hle/c_stdio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,14 @@ std::string RuntimeHle::FormatGuestPrintf(const std::string& fmt,
if (!flags.empty()) pieceBuilder << flags;
if (width >= 0) pieceBuilder << width;
if (precision >= 0) pieceBuilder << "." << precision;
pieceBuilder << length << spec;
// Only the integer conversions keep a length modifier, and only where guest and
// host agree on it: the guest's l/z/t are 32-bit, and %ls/%lc would make the host
// read the narrow value passed below as wide characters.
const bool integerSpec = spec != '\0' && std::strchr("diuxXo", spec) != nullptr;
if (integerSpec && (length == "ll" || length == "h" || length == "hh")) {
pieceBuilder << length;
}
pieceBuilder << spec;
const std::string piece = pieceBuilder.str();

auto appendWithSnprintf = [&](auto value) {
Expand Down
24 changes: 20 additions & 4 deletions runtime/src/hle/storage/nand_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ extern "C" int32_t NANDOpen_HLE(uint32_t pathPtr, uint32_t fileInfoPtr, uint32_t
}

const std::filesystem::path hostPath = TranslateNandPath(path);
if (hostPath.empty()) {
LogNandError("NANDOpen", "FAILED to translate path '%s'", path);
return NAND_RESULT_INVALID;
}

if (const auto result = NandCheckSystemSaveRead("NANDOpen", hostPath, mode))
return *result;
Expand Down Expand Up @@ -248,10 +252,15 @@ extern "C" int32_t NANDRead_HLE(uint32_t fileInfoPtr, uint32_t bufferPtr, uint32
return NAND_RESULT_INVALID;
}

uint8_t* buffer = (uint8_t*)Memory::GetPointer(bufferPtr);
if (!buffer) {
if (length == 0) {
return 0;
}
// The host pointer is only valid for the range it was resolved with.
if (!Memory::Contains(bufferPtr, length)) {
LogNandError("NANDRead", "invalid buffer 0x%08X length=%u", bufferPtr, length);
return NAND_RESULT_INVALID;
}
uint8_t* buffer = Memory::GetPointer(bufferPtr, length);

size_t bytesRead = std::fread(buffer, 1, length, handle->file);
return static_cast<int32_t>(bytesRead);
Expand All @@ -268,10 +277,14 @@ extern "C" int32_t NANDWrite_HLE(uint32_t fileInfoPtr, uint32_t bufferPtr, uint3
return NAND_RESULT_INVALID;
}

const uint8_t* buffer = (const uint8_t*)Memory::GetPointer(bufferPtr);
if (!buffer) {
if (length == 0) {
return 0;
}
if (!Memory::Contains(bufferPtr, length)) {
LogNandError("NANDWrite", "invalid buffer 0x%08X length=%u", bufferPtr, length);
return NAND_RESULT_INVALID;
}
const uint8_t* buffer = Memory::GetPointer(bufferPtr, length);

size_t bytesWritten = std::fwrite(buffer, 1, length, handle->file);
std::fflush(handle->file);
Expand Down Expand Up @@ -365,6 +378,9 @@ extern "C" int32_t NANDCreateDir_HLE(uint32_t pathPtr, uint32_t perm, uint32_t a
}

const std::filesystem::path hostPath = TranslateNandPath(path);
if (hostPath.empty()) {
return NAND_RESULT_INVALID;
}

if (PathExists(hostPath)) {
if (IsDirectory(hostPath)) {
Expand Down
28 changes: 12 additions & 16 deletions runtime/src/hle/storage/nand_fs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include "isa/big_endian.h"
#include "hle/storage/riivolution.h"
#include "nand_guest_path.h"
#include "runtime_log.h"

// ============================================================================
Expand Down Expand Up @@ -121,19 +122,11 @@ bool NandRename(const std::filesystem::path& from, const std::filesystem::path&
}

// Guest paths are absolute and already lexically resolved against the NAND root, so
// they are appended as relative components instead of replacing the root.
// they are appended as relative components instead of replacing the root. Empty when a
// component could leave the root (see nand_guest_path.h).
static std::filesystem::path BuildHostNandPath(const std::string& wiiPathStr) {
std::filesystem::path hostPath = GetNandBasePath();
size_t cursor = 0;
while (cursor < wiiPathStr.size()) {
const size_t slash = wiiPathStr.find('/', cursor);
const size_t end = slash == std::string::npos ? wiiPathStr.size() : slash;
if (end != cursor) {
hostPath /= wiiPathStr.substr(cursor, end - cursor);
}
cursor = end + 1;
}
return hostPath;
auto hostPath = RuntimeNandGuestPath::AppendBelowRoot(GetNandBasePath(), wiiPathStr);
return hostPath ? std::move(*hostPath) : std::filesystem::path{};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// Collapses "." and ".." components against the NAND root. Without this, guest paths like
Expand Down Expand Up @@ -255,12 +248,15 @@ static bool ResolveRiivolutionSaveHostPath(const std::string& absoluteWiiPath,
relative = absoluteWiiPath.substr(dataDir.size() + 1);
}

std::filesystem::path redirected = redirect.hostDirectory;
if (!relative.empty()) {
redirected /= std::filesystem::path(relative);
// The path belongs to the redirect either way; an unsafe one resolves to nothing
// rather than falling back to the NAND root.
auto redirected = RuntimeNandGuestPath::AppendBelowRoot(redirect.hostDirectory, relative);
if (!redirected) {
outHostPath.clear();
return true;
}

outHostPath = redirected;
outHostPath = std::move(*redirected);
CloneRiivolutionSaveIfNeeded(BuildHostNandPath(absoluteWiiPath), outHostPath, redirect);
return true;
}
Expand Down
30 changes: 20 additions & 10 deletions runtime/src/hle/storage/nand_isfs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ extern "C" int32_t NAND_IOS_Open_HLE(uint32_t pathPtr, uint32_t mode) {

// It's a NAND file path
const std::filesystem::path hostPath = TranslateNandPath(path);
if (hostPath.empty()) {
LogNandError("IOS_Open", "FAILED to translate path '%s'", path);
return ISFS_EINVAL;
}

if (const auto result = NandCheckSystemSaveRead("IOS_Open", hostPath, mode, true))
return *result;
Expand Down Expand Up @@ -481,11 +485,12 @@ extern "C" int32_t NAND_IOS_Read_HLE(uint32_t fd, uint32_t bufferPtr, uint32_t l
return 0;
}

uint8_t* buffer = (uint8_t*)Memory::GetPointer(bufferPtr);
if (!buffer) {
LogNandError("IOS_Read", "invalid buffer ptr 0x%08X", bufferPtr);
// The host pointer is only valid for the range it was resolved with.
if (!Memory::Contains(bufferPtr, length)) {
LogNandError("IOS_Read", "invalid buffer 0x%08X length=%u", bufferPtr, length);
return ISFS_EINVAL;
}
uint8_t* buffer = Memory::GetPointer(bufferPtr, length);

size_t bytesRead = std::fread(buffer, 1, length, handle->file);
handle->position += static_cast<uint32_t>(bytesRead);
Expand All @@ -505,11 +510,11 @@ extern "C" int32_t NAND_IOS_Write_HLE(uint32_t fd, uint32_t bufferPtr, uint32_t
return 0;
}

const uint8_t* buffer = (const uint8_t*)Memory::GetPointer(bufferPtr);
if (!buffer) {
LogNandError("IOS_Write", "invalid buffer ptr 0x%08X", bufferPtr);
if (!Memory::Contains(bufferPtr, length)) {
LogNandError("IOS_Write", "invalid buffer 0x%08X length=%u", bufferPtr, length);
return ISFS_EINVAL;
}
const uint8_t* buffer = Memory::GetPointer(bufferPtr, length);

size_t bytesWritten = std::fwrite(buffer, 1, length, handle->file);
std::fflush(handle->file);
Expand Down Expand Up @@ -591,7 +596,10 @@ extern "C" int32_t NAND_IOS_Ioctl_HLE(
}
const char* path = (const char*)Memory::GetPointer(inBufPtr + 6);
const std::filesystem::path hostPath = TranslateNandPath(path);

if (hostPath.empty()) {
return ISFS_EINVAL;
}

if (CreateDirectoryPath(hostPath)) {
return ISFS_OK;
}
Expand Down Expand Up @@ -625,9 +633,11 @@ extern "C" int32_t NAND_IOS_Ioctl_HLE(

// Return fake attributes (owner UID, group ID, permissions)
// Format: u32 ownerID, u16 groupID, u8 ownerPerm, u8 groupPerm, u8 otherPerm, u8 attrs
uint8_t* outBuf = (uint8_t*)Memory::GetPointer(outBufPtr);
if (outBuf && outLen >= 0x4c) {
std::memset(outBuf, 0, outLen);
if (outLen >= 0x4c) {
if (!Memory::Contains(outBufPtr, outLen)) {
return ISFS_EINVAL;
}
std::memset(Memory::GetPointer(outBufPtr, outLen), 0, outLen);
// Owner UID = 0
Memory::Write32(outBufPtr, 0);
// Group ID = 0
Expand Down
68 changes: 68 additions & 0 deletions runtime/tests/nand_guest_path_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include "nand_guest_path.h"

#include <iostream>
#include <stdexcept>

namespace fs = std::filesystem;
using RuntimeNandGuestPath::AppendBelowRoot;
using RuntimeNandGuestPath::IsSafeComponent;

static void Require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}

// Lexical containment: every accepted path must still start with the root's components.
static bool IsBelow(const fs::path& root, const fs::path& path) {
auto rootIt = root.begin();
auto pathIt = path.begin();
for (; rootIt != root.end(); ++rootIt, ++pathIt) {
if (pathIt == path.end() || *pathIt != *rootIt) return false;
}
return true;
}

int main() {
try {
#ifdef _WIN32
const fs::path root = "C:/Users/player/NAND";
#else
const fs::path root = "/home/player/NAND";
#endif
const auto save = AppendBelowRoot(root, "/title/00010004/524d4350/data/rksys.dat");
Require(save.has_value(), "Ordinary save path must translate");
Require(*save == root / "title" / "00010004" / "524d4350" / "data" / "rksys.dat",
"Ordinary save path must keep its components");
Require(IsBelow(root, *save), "Ordinary save path must stay below the root");

const auto slashes = AppendBelowRoot(root, "//shared2///wc24/");
Require(slashes && *slashes == root / "shared2" / "wc24",
"Empty components must be skipped");
const auto rootOnly = AppendBelowRoot(root, "/");
Require(rootOnly && *rootOnly == root, "The guest root maps to the host root");
const auto empty = AppendBelowRoot(root, "");
Require(empty && *empty == root, "An empty relative path maps to the base directory");

// A drive prefix replaces the path built so far on Windows.
Require(!AppendBelowRoot(root, "/title/C:/Windows/system.ini"), "Same-drive prefix must be refused");
Require(!AppendBelowRoot(root, "/D:/autorun.inf"), "Other-drive prefix must be refused");
Require(!AppendBelowRoot(root, "C:/Users/player/startup.bat"),
"Drive-absolute relative path must be refused");
Require(!AppendBelowRoot(root, "/title/C:"), "Bare drive component must be refused");
Require(!AppendBelowRoot(root, "/title/save.dat:stream"), "Stream name must be refused");

Require(!AppendBelowRoot(root, "/title/../../escape"), "Unresolved parent component must be refused");
Require(!AppendBelowRoot(root, "/title/./data"), "Unresolved current component must be refused");
Require(!AppendBelowRoot(root, R"(/title\..\escape)"), "Backslash separator must be refused");

Require(!IsSafeComponent(""), "Empty component is not a name");
Require(!IsSafeComponent(std::string_view("a\0b", 3)), "Embedded NUL must be refused");
Require(IsSafeComponent("rksys.dat"), "Plain file name is safe");
Require(IsSafeComponent("..data"), "Leading dots alone are an ordinary name");
Require(IsSafeComponent("wc24recv.mbx"), "WC24 mailbox name is safe");
} catch (const std::exception& error) {
std::cerr << "FAILED: " << error.what() << std::endl;
return 1;
}
std::cout << "nand_guest_path_tests passed" << std::endl;
return 0;
}
Loading