CLI: add decrypt option

This commit is contained in:
Megamouse 2022-05-09 23:13:43 +02:00
parent 2f9b930c6b
commit 5ae9de4e3b
7 changed files with 278 additions and 162 deletions

View File

@ -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 <charconv>
#include <iostream>
LOG_CHANNEL(dec_log, "DECRYPT");
void decrypt_sprx_libraries(std::vector<std::string> modules, std::function<std::string(std::string old_path, std::string path, bool tried)> 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<u128> klics{u128{}};
if (const auto keys = g_fxo->try_get<loaded_npdrm_keys>())
{
// 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<u8*>(&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<u8*>(&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<u64> lo = std::bit_cast<be_t<u64>>(lo_);
be_t<u64> hi = std::bit_cast<be_t<u64>>(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
}

View File

@ -0,0 +1,3 @@
#pragma once
void decrypt_sprx_libraries(std::vector<std::string> modules, std::function<std::string(std::string old_path, std::string path, bool tried)> input_cb);

View File

@ -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

View File

@ -52,6 +52,7 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\Utilities\cheat_info.cpp" />
<ClCompile Include="Crypto\decrypt_binaries.cpp" />
<ClCompile Include="Emu\Audio\audio_device_listener.cpp" />
<ClCompile Include="Emu\Audio\audio_resampler.cpp" />
<ClCompile Include="Emu\Audio\FAudio\FAudioBackend.cpp">
@ -448,6 +449,7 @@
<ClInclude Include="..\Utilities\cheat_info.h" />
<ClInclude Include="..\Utilities\simple_ringbuf.h" />
<ClInclude Include="..\Utilities\transactional_storage.h" />
<ClInclude Include="Crypto\decrypt_binaries.h" />
<ClInclude Include="Emu\Audio\audio_device_listener.h" />
<ClInclude Include="Emu\Audio\audio_resampler.h" />
<ClInclude Include="Emu\Audio\FAudio\FAudioBackend.h">
@ -815,4 +817,4 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
</Project>

View File

@ -1060,6 +1060,9 @@
<ClCompile Include="Emu\perf_monitor.cpp">
<Filter>Emu</Filter>
</ClCompile>
<ClCompile Include="Crypto\decrypt_binaries.cpp">
<Filter>Crypto</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Crypto\aes.h">
@ -2110,6 +2113,9 @@
<ClInclude Include="Emu\Cell\Modules\cellRec.h">
<Filter>Emu\Cell\Modules</Filter>
</ClInclude>
<ClInclude Include="Crypto\decrypt_binaries.h">
<Filter>Crypto</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="Emu\RSX\Common\Interpreter\FragmentInterpreter.glsl">
@ -2119,4 +2125,4 @@
<Filter>Emu\GPU\RSX\Common\Interpreter</Filter>
</None>
</ItemGroup>
</Project>
</Project>

View File

@ -27,6 +27,7 @@
#include "headless_application.h"
#include "Utilities/sema.h"
#include "Crypto/decrypt_binaries.h"
#ifdef _WIN32
#include <windows.h>
#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<QCoreApplication> app(createApplication(argc, argv));
QScopedPointer<QCoreApplication> 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<std::string> 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))
{

View File

@ -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<u128> klics{u128{}};
if (const auto keys = g_fxo->try_get<loaded_npdrm_keys>())
std::vector<std::string> 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<u8*>(&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<u8*>(&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<u64> lo = std::bit_cast<be_t<u64>>(lo_);
be_t<u64> hi = std::bit_cast<be_t<u64>>(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.