diff --git a/rpcs3/Crypto/decrypt_binaries.cpp b/rpcs3/Crypto/decrypt_binaries.cpp new file mode 100644 index 0000000000..49ff13c36a --- /dev/null +++ b/rpcs3/Crypto/decrypt_binaries.cpp @@ -0,0 +1,165 @@ +#include "stdafx.h" +#include "decrypt_binaries.h" +#include "unedat.h" +#include "unself.h" +#include "Emu/IdManager.h" +#include "Emu/System.h" +#include "Utilities/StrUtil.h" + +#include +#include + +LOG_CHANNEL(dec_log, "DECRYPT"); + +void decrypt_sprx_libraries(std::vector modules, std::function input_cb) +{ + if (modules.empty()) + { + std::cout << "No paths specified" << std::endl; // For CLI + return; + } + + dec_log.notice("Decrypting binaries..."); + std::cout << "Decrypting binaries..." << std::endl; // For CLI + + // Always start with no KLIC + std::vector klics{u128{}}; + + if (const auto keys = g_fxo->try_get()) + { + // Second klic: get it from a running game + if (const u128 klic = keys->last_key()) + { + klics.emplace_back(klic); + } + } + + // Try to use the key that has been for the current running ELF + klics.insert(klics.end(), Emu.klic.begin(), Emu.klic.end()); + + for (const std::string& _module : modules) + { + const std::string old_path = _module; + + fs::file elf_file; + + bool tried = false; + bool invalid = false; + usz key_it = 0; + u32 file_magic{}; + + while (true) + { + for (; key_it < klics.size(); key_it++) + { + if (!elf_file.open(old_path) || !elf_file.read(file_magic)) + { + file_magic = 0; + } + + switch (file_magic) + { + case "SCE\0"_u32: + { + // First KLIC is no KLIC + elf_file = decrypt_self(std::move(elf_file), key_it != 0 ? reinterpret_cast(&klics[key_it]) : nullptr); + + if (!elf_file) + { + // Try another key + continue; + } + + break; + } + case "NPD\0"_u32: + { + // EDAT / SDAT + elf_file = DecryptEDAT(elf_file, old_path, key_it != 0 ? 8 : 1, reinterpret_cast(&klics[key_it]), true); + + if (!elf_file) + { + // Try another key + continue; + } + + break; + } + default: + { + invalid = true; + break; + } + } + + if (invalid) + { + elf_file.close(); + } + + break; + } + + if (elf_file) + { + const std::string exec_ext = fmt::to_lower(_module).ends_with(".sprx") ? ".prx" : ".elf"; + const std::string new_path = file_magic == "NPD\0"_u32 ? old_path + ".unedat" : + old_path.substr(0, old_path.find_last_of('.')) + exec_ext; + + if (fs::file new_file{new_path, fs::rewrite}) + { + new_file.write(elf_file.to_string()); + dec_log.success("Decrypted %s -> %s", old_path, new_path); + std::cout << "Decrypted " << old_path << " -> " << new_path << std::endl; // For CLI + } + else + { + dec_log.error("Failed to create %s", new_path); + std::cout << "Failed to create " << new_path << std::endl; // For CLI + } + + break; + } + + if (!invalid) + { + // Allow the user to manually type KLIC if decryption failed + + const std::string filename = old_path.substr(old_path.find_last_of(fs::delim) + 1); + const std::string text = input_cb ? input_cb(old_path, filename, tried) : ""; + + if (!text.empty()) + { + auto& klic = (tried ? klics.back() : klics.emplace_back()); + + ensure(text.size() == 32); + + // It must succeed (only hex characters are present) + u64 lo_ = 0; + u64 hi_ = 0; + std::from_chars(&text[0], &text[16], lo_, 16); + std::from_chars(&text[16], &text[32], hi_, 16); + + be_t lo = std::bit_cast>(lo_); + be_t hi = std::bit_cast>(hi_); + + klic = (u128{+hi} << 64) | +lo; + + // Retry with specified KLIC + key_it -= +std::exchange(tried, true); // Rewind on second and above attempt + dec_log.notice("KLIC entered for %s: %s", filename, klic); + continue; + } + + dec_log.notice("User has cancelled entering KLIC."); + } + + dec_log.error("Failed to decrypt \"%s\".", old_path); + std::cout << "Failed to decrypt \"" << old_path << "\"." << std::endl; // For CLI + break; + } + } + + dec_log.notice("Finished decrypting all binaries."); + std::cout << "Finished decrypting all binaries." << std::endl; // For CLI +} diff --git a/rpcs3/Crypto/decrypt_binaries.h b/rpcs3/Crypto/decrypt_binaries.h new file mode 100644 index 0000000000..f27e58146f --- /dev/null +++ b/rpcs3/Crypto/decrypt_binaries.h @@ -0,0 +1,3 @@ +#pragma once + +void decrypt_sprx_libraries(std::vector modules, std::function input_cb); diff --git a/rpcs3/Emu/CMakeLists.txt b/rpcs3/Emu/CMakeLists.txt index 551c80486c..4b81635a6d 100644 --- a/rpcs3/Emu/CMakeLists.txt +++ b/rpcs3/Emu/CMakeLists.txt @@ -88,6 +88,7 @@ endif() target_sources(rpcs3_emu PRIVATE ../Crypto/aes.cpp ../Crypto/aesni.cpp + ../Crypto/decrypt_binaries.cpp ../Crypto/ec.cpp ../Crypto/key_vault.cpp ../Crypto/lz.cpp diff --git a/rpcs3/emucore.vcxproj b/rpcs3/emucore.vcxproj index b2b1b45d62..01f148a381 100644 --- a/rpcs3/emucore.vcxproj +++ b/rpcs3/emucore.vcxproj @@ -52,6 +52,7 @@ + @@ -448,6 +449,7 @@ + @@ -815,4 +817,4 @@ - + \ No newline at end of file diff --git a/rpcs3/emucore.vcxproj.filters b/rpcs3/emucore.vcxproj.filters index 222104efaa..5d13deaee5 100644 --- a/rpcs3/emucore.vcxproj.filters +++ b/rpcs3/emucore.vcxproj.filters @@ -1060,6 +1060,9 @@ Emu + + Crypto + @@ -2110,6 +2113,9 @@ Emu\Cell\Modules + + Crypto + @@ -2119,4 +2125,4 @@ Emu\GPU\RSX\Common\Interpreter - + \ No newline at end of file diff --git a/rpcs3/main.cpp b/rpcs3/main.cpp index b288a2a9bf..67a1fc25a5 100644 --- a/rpcs3/main.cpp +++ b/rpcs3/main.cpp @@ -27,6 +27,7 @@ #include "headless_application.h" #include "Utilities/sema.h" +#include "Crypto/decrypt_binaries.h" #ifdef _WIN32 #include #include "util/dyn_lib.hpp" @@ -242,7 +243,12 @@ struct fatal_error_listener final : logs::listener } }; +// Arguments that force a headless application (need to be checked in create_application) constexpr auto arg_headless = "headless"; +constexpr auto arg_decrypt = "decrypt"; +constexpr auto arg_commit_db = "get-commit-db"; + +// Arguments that can be used with a gui application constexpr auto arg_no_gui = "no-gui"; constexpr auto arg_high_dpi = "hidpi"; constexpr auto arg_rounding = "dpi-rounding"; @@ -256,7 +262,6 @@ constexpr auto arg_updating = "updating"; constexpr auto arg_user_id = "user-id"; constexpr auto arg_installfw = "installfw"; constexpr auto arg_installpkg = "installpkg"; -constexpr auto arg_commit_db = "get-commit-db"; constexpr auto arg_timer = "high-res-timer"; constexpr auto arg_verbose_curl = "verbose-curl"; constexpr auto arg_any_location = "allow-any-location"; @@ -270,10 +275,14 @@ int find_arg(std::string arg, int& argc, char* argv[]) return -1; } -QCoreApplication* createApplication(int& argc, char* argv[]) +QCoreApplication* create_application(int& argc, char* argv[]) { - if (find_arg(arg_headless, argc, argv) != -1) + if (find_arg(arg_headless, argc, argv) != -1 || + find_arg(arg_decrypt, argc, argv) != -1 || + find_arg(arg_commit_db, argc, argv) != -1) + { return new headless_application(argc, argv); + } #ifdef __linux__ // set the DISPLAY variable in order to open web browsers @@ -562,7 +571,7 @@ int main(int argc, char** argv) // but I haven't found an implicit way to check for style yet, so we naively check them both here for now. const bool use_cli_style = find_arg(arg_style, argc, argv) != -1 || find_arg(arg_stylesheet, argc, argv) != -1; - QScopedPointer app(createApplication(argc, argv)); + QScopedPointer app(create_application(argc, argv)); app->setApplicationVersion(QString::fromStdString(rpcs3::get_version().to_string())); app->setApplicationName("RPCS3"); app->setOrganizationName("RPCS3"); @@ -588,6 +597,8 @@ int main(int argc, char** argv) parser.addOption(installfw_option); const QCommandLineOption installpkg_option(arg_installpkg, "Forces the emulator to install this pkg file.", "path", ""); parser.addOption(installpkg_option); + const QCommandLineOption decrypt_option(arg_decrypt, "Decrypt PS3 binaries.", "path(s)", ""); + parser.addOption(decrypt_option); const QCommandLineOption user_id_option(arg_user_id, "Start RPCS3 as this user.", "user id", ""); parser.addOption(user_id_option); parser.addOption(QCommandLineOption(arg_q_debug, "Log qDebug to RPCS3.log.")); @@ -961,6 +972,57 @@ int main(int argc, char** argv) } #endif + if (parser.isSet(arg_decrypt)) + { +#ifdef _WIN32 + if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()) + { + [[maybe_unused]] const auto con_out = freopen("CONOUT$", "w", stdout); + [[maybe_unused]] const auto con_in = freopen("CONIN$", "r", stdin); + } +#endif + + std::vector vec_modules; + for (const QString& mod : parser.values(decrypt_option)) + { + const QFileInfo fi(mod); + if (!fi.exists()) + { + std::cout << "File not found: " << mod.toStdString() << std::endl; + return 1; + } + if (!fi.isFile()) + { + std::cout << "Not a file: " << mod.toStdString() << std::endl; + return 1; + } + vec_modules.push_back(fi.absoluteFilePath().toStdString()); + } + + const auto input_cb = [](std::string old_path, std::string path, bool tried) -> std::string + { + const std::string hint = fmt::format("Hint: KLIC (KLicense key) is a 16-byte long string. (32 hexadecimal characters)" + "\nAnd is logged with some sceNpDrm* functions when the game/application which owns \"%0\" is running.", path); + + if (tried) + { + std::cout << "Failed to decrypt " << old_path << " with specfied KLIC, retrying.\n" << hint << std::endl; + } + + std::cout << "Enter KLIC of " << path << "\nHexadecimal only, 32 characters:" << std::endl; + + std::string input; + std::cin >> input; + + return input; + }; + + Emu.Init(); + decrypt_sprx_libraries(vec_modules, input_cb); + Emu.Quit(true); + return 0; + } + // Force install firmware or pkg first if specified through command-line if (parser.isSet(arg_installfw) || parser.isSet(arg_installpkg)) { diff --git a/rpcs3/rpcs3qt/main_window.cpp b/rpcs3/rpcs3qt/main_window.cpp index 7e98dd6cec..58e719a2de 100644 --- a/rpcs3/rpcs3qt/main_window.cpp +++ b/rpcs3/rpcs3qt/main_window.cpp @@ -48,7 +48,7 @@ #include "Crypto/unpkg.h" #include "Crypto/unself.h" -#include "Crypto/unedat.h" +#include "Crypto/decrypt_binaries.h" #include "Loader/PUP.h" #include "Loader/TAR.h" @@ -1298,169 +1298,46 @@ void main_window::DecryptSPRXLibraries() m_gui_settings->SetValue(gui::fd_decrypt_sprx, QFileInfo(modules.first()).path()); - gui_log.notice("Decrypting binaries..."); - - // Always start with no KLIC - std::vector klics{u128{}}; - - if (const auto keys = g_fxo->try_get()) + std::vector vec_modules; + for (const QString& mod : modules) { - // Second klic: get it from a running game - if (const u128 klic = keys->last_key()) - { - klics.emplace_back(klic); - } + vec_modules.push_back(mod.toStdString()); } - // Try to use the key that has been for the current running ELF - klics.insert(klics.end(), Emu.klic.begin(), Emu.klic.end()); - - for (const QString& _module : modules) + const auto input_cb = [this](std::string old_path, std::string path, bool tried) -> std::string { - const std::string old_path = sstr(_module); + const QString hint = tr("Hint: KLIC (KLicense key) is a 16-byte long string. (32 hexadecimal characters)" + "\nAnd is logged with some sceNpDrm* functions when the game/application which owns \"%0\" is running.").arg(qstr(path)); - fs::file elf_file; - - bool tried = false; - bool invalid = false; - usz key_it = 0; - u32 file_magic{}; - - while (true) + if (tried) { - for (; key_it < klics.size(); key_it++) - { - if (!elf_file.open(old_path) || !elf_file.read(file_magic)) - { - file_magic = 0; - } - - switch (file_magic) - { - case "SCE\0"_u32: - { - // First KLIC is no KLIC - elf_file = decrypt_self(std::move(elf_file), key_it != 0 ? reinterpret_cast(&klics[key_it]) : nullptr); - - if (!elf_file) - { - // Try another key - continue; - } - - break; - } - case "NPD\0"_u32: - { - // EDAT / SDAT - elf_file = DecryptEDAT(elf_file, old_path, key_it != 0 ? 8 : 1, reinterpret_cast(&klics[key_it]), true); - - if (!elf_file) - { - // Try another key - continue; - } - - break; - } - default: - { - invalid = true; - break; - } - } - - if (invalid) - { - elf_file.close(); - } - - break; - } - - if (elf_file) - { - const std::string exec_ext = _module.toLower().endsWith(".sprx") ? ".prx" : ".elf"; - const std::string new_path = file_magic == "NPD\0"_u32 ? old_path + ".unedat" : - old_path.substr(0, old_path.find_last_of('.')) + exec_ext; - - if (fs::file new_file{new_path, fs::rewrite}) - { - new_file.write(elf_file.to_string()); - gui_log.success("Decrypted %s -> %s", old_path, new_path); - } - else - { - gui_log.error("Failed to create %s", new_path); - } - - break; - } - else if (!invalid) - { - // Allow the user to manually type KLIC if decryption failed - - const std::string filename = old_path.substr(old_path.find_last_of(fs::delim) + 1); - - const QString hint = tr("Hint: KLIC (KLicense key) is a 16-byte long string. (32 hexadecimal characters)" - "\nAnd is logged with some sceNpDrm* functions when the game/application which owns \"%0\" is running.").arg(qstr(filename)); - - if (tried) - { - gui_log.error("Failed to decrypt %s with specfied KLIC, retrying.\n%s", old_path, sstr(hint)); - } - - input_dialog dlg(32, "", tr("Enter KLIC of %0").arg(qstr(filename)), - tried ? tr("Decryption failed with provided KLIC.\n%0").arg(hint) : tr("Hexadecimal only."), "00000000000000000000000000000000", this); - - QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont); - mono.setPointSize(8); - dlg.set_input_font(mono, true, '0'); - dlg.set_clear_button_enabled(false); - dlg.set_button_enabled(QDialogButtonBox::StandardButton::Ok, false); - dlg.set_validator(new QRegularExpressionValidator(QRegularExpression("^[a-fA-F0-9]*$"))); // HEX only - - connect(&dlg, &input_dialog::text_changed, &dlg, [&dlg](const QString& text) - { - dlg.set_button_enabled(QDialogButtonBox::StandardButton::Ok, text.size() == 32); - }); - - if (dlg.exec() == QDialog::Accepted) - { - const std::string text = sstr(dlg.get_input_text()); - - auto& klic = (tried ? klics.back() : klics.emplace_back()); - - ensure(text.size() == 32); - - // It must succeed (only hex characters are present) - u64 lo_ = 0; - u64 hi_ = 0; - std::from_chars(&text[0], &text[16], lo_, 16); - std::from_chars(&text[16], &text[32], hi_, 16); - - be_t lo = std::bit_cast>(lo_); - be_t hi = std::bit_cast>(hi_); - - klic = (u128{+hi} << 64) | +lo; - - // Retry with specified KLIC - key_it -= +std::exchange(tried, true); // Rewind on second and above attempt - gui_log.notice("KLIC entered for %s: %s", filename, klic); - continue; - } - else - { - gui_log.notice("User has cancelled entering KLIC."); - } - } - - gui_log.error("Failed to decrypt \"%s\".", old_path); - break; + gui_log.error("Failed to decrypt %s with specfied KLIC, retrying.\n%s", old_path, sstr(hint)); } - } - gui_log.notice("Finished decrypting all binaries."); + input_dialog dlg(32, "", tr("Enter KLIC of %0").arg(qstr(path)), + tried ? tr("Decryption failed with provided KLIC.\n%0").arg(hint) : tr("Hexadecimal only."), "00000000000000000000000000000000", this); + + QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont); + mono.setPointSize(8); + dlg.set_input_font(mono, true, '0'); + dlg.set_clear_button_enabled(false); + dlg.set_button_enabled(QDialogButtonBox::StandardButton::Ok, false); + dlg.set_validator(new QRegularExpressionValidator(QRegularExpression("^[a-fA-F0-9]*$"))); // HEX only + + connect(&dlg, &input_dialog::text_changed, &dlg, [&dlg](const QString& text) + { + dlg.set_button_enabled(QDialogButtonBox::StandardButton::Ok, text.size() == 32); + }); + + if (dlg.exec() == QDialog::Accepted) + { + return sstr(dlg.get_input_text()); + } + + return {}; + }; + + decrypt_sprx_libraries(vec_modules, input_cb); } /** Needed so that when a backup occurs of window state in gui_settings, the state is current.