Compare commits

..

No commits in common. "master" and "0.1.0" have entirely different histories.

15 changed files with 273 additions and 179 deletions

View file

@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[lib]
name = "ext"
name = "version"
crate-type = ["cdylib"]
[dependencies]

View file

@ -1,3 +1,3 @@
# hk4e-patch
Genshin Impact encryption patch (5.0.0)
Genshin Impact encryption patch (4.5.0)

11
build.rs Normal file
View file

@ -0,0 +1,11 @@
fn main() {
cc::Build::new().file("version.asm").compile("version");
println!("cargo:rerun-if-changed=version.asm");
println!(
"cargo:rustc-link-search=native={}",
std::env::var("OUT_DIR").unwrap()
);
println!("cargo:rustc-link-lib=static=version");
println!("cargo:rustc-link-arg=/DEF:version.def");
}

View file

@ -1 +0,0 @@
<RSAKeyValue><Exponent>AQAB</Exponent><Modulus>hEegnKISgDas5VTuRBUlixB+bvmPvXKa3kVO22UEZjPGMUFLmIl3DhH+dsZo7qJn/GfJCUkP1FA0MJ5Bj8PX8IatLJKIJ9dMCNdnAlkXTlMg86QQAhHZN83vP4swj5ILcrGNKl3YAZ49fvzo7nheuTt0/40f0HkHdNa1dUHECBs=</Modulus></RSAKeyValue>

View file

@ -3,49 +3,57 @@
use std::{sync::RwLock, time::Duration};
use lazy_static::lazy_static;
use modules::{CcpBlocker, Misc};
use windows::core::PCSTR;
use util::try_get_base_address;
use windows::Win32::Foundation::HINSTANCE;
use windows::Win32::System::Console;
use windows::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
use windows::Win32::{Foundation::HINSTANCE, System::LibraryLoader::GetModuleHandleA};
mod interceptor;
mod marshal;
mod modules;
mod util;
mod version;
use version::VersionDllProxy;
use crate::modules::{Http, MhyContext, ModuleManager, Security};
unsafe fn thread_func() {
let base = GetModuleHandleA(PCSTR::null()).unwrap().0 as usize;
let mut module_manager = MODULE_MANAGER.write().unwrap();
let base = loop {
if let Some(base) = try_get_base_address("UserAssembly.dll") {
break base;
}
// Block query_security_file ASAP
module_manager.enable(MhyContext::<CcpBlocker>::new(base));
std::thread::sleep(Duration::from_millis(500));
};
std::thread::sleep(Duration::from_secs(14));
std::thread::sleep(Duration::from_secs(7));
util::disable_memprotect_guard();
Console::AllocConsole().unwrap();
println!("Genshin Impact encryption patch\nMade by xeondev\nTo work with sakura-rs: git.xeondev.com/sakura-rs/sakura-rs");
println!("Base: {:X}", base);
println!("Genshin Impact encryption patch\nMade by xeondev\nTo work with NaviaImpact: git.xeondev.com/reversedrooms/NaviaImpact");
println!("UserAssembly: {:X}", base);
let mut module_manager = MODULE_MANAGER.write().unwrap();
module_manager.enable(MhyContext::<Http>::new(base));
module_manager.enable(MhyContext::<Security>::new(base));
module_manager.enable(MhyContext::<Misc>::new(base));
println!("Successfully initialized!");
}
lazy_static! {
static ref VERSION_DLL_PROXY: version::VersionDllProxy =
VersionDllProxy::new().expect("Failed to load version.dll");
static ref MODULE_MANAGER: RwLock<ModuleManager> = RwLock::new(ModuleManager::default());
}
#[no_mangle]
#[allow(non_snake_case)]
unsafe extern "system" fn DllMain(_: HINSTANCE, call_reason: u32, _: *mut ()) -> bool {
if call_reason == DLL_PROCESS_ATTACH {
VERSION_DLL_PROXY
.load_functions()
.expect("Failed to load functions from version.dll");
std::thread::spawn(|| thread_func());
}

View file

@ -1,8 +1,8 @@
use std::ffi::CStr;
use windows::{core::PCSTR, Win32::System::LibraryLoader::GetModuleHandleA};
use crate::util;
const PTR_TO_STRING_ANSI: usize = 0xF85E020;
const PTR_TO_STRING_ANSI: usize = 0xC61DB80;
type MarshalPtrToStringAnsi = unsafe extern "fastcall" fn(*const u8) -> *const u8;
pub unsafe fn ptr_to_string_ansi(content: &CStr) -> *const u8 {
@ -11,5 +11,5 @@ pub unsafe fn ptr_to_string_ansi(content: &CStr) -> *const u8 {
}
unsafe fn base() -> usize {
GetModuleHandleA(PCSTR::null()).unwrap().0 as usize
util::try_get_base_address("UserAssembly.dll").unwrap()
}

View file

@ -1,38 +0,0 @@
use std::ffi::CStr;
use super::{MhyContext, MhyModule, ModuleType};
use anyhow::Result;
use ilhook::x64::Registers;
use windows::{
core::s,
Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress},
};
pub struct CcpBlocker;
impl MhyModule for MhyContext<CcpBlocker> {
unsafe fn init(&mut self) -> Result<()> {
let winsock2 = GetModuleHandleA(s!("Ws2_32.dll")).unwrap();
let getaddrinfo = GetProcAddress(winsock2, s!("getaddrinfo")).unwrap();
self.interceptor
.attach(getaddrinfo as usize, on_getaddrinfo)
}
unsafe fn de_init(&mut self) -> Result<()> {
Ok(())
}
fn get_module_type(&self) -> super::ModuleType {
ModuleType::CcpBlocker
}
}
unsafe extern "win64" fn on_getaddrinfo(reg: *mut Registers, _: usize) {
let host_ptr = (*reg).rcx as *const i8;
let host = CStr::from_ptr(host_ptr).to_string_lossy();
if host == "dispatchosglobal.yuanshen.com" || host == "dispatchcnglobal.yuanshen.com" {
std::ptr::copy_nonoverlapping(c"0.0.0.0".as_ptr(), (*reg).rcx as *mut i8, 9);
}
}

View file

@ -5,20 +5,16 @@ use crate::marshal;
use anyhow::Result;
use ilhook::x64::Registers;
const WEB_REQUEST_UTILS_MAKE_INITIAL_URL: usize = 0x10421E00;
const BROWSER_LOAD_URL: usize = 0x10222B20;
const UNITY_WEB_REQUEST_SET_URL: usize = 0xCFC7FE0;
pub struct Http;
impl MhyModule for MhyContext<Http> {
unsafe fn init(&mut self) -> Result<()> {
self.interceptor.attach(
self.assembly_base + WEB_REQUEST_UTILS_MAKE_INITIAL_URL,
on_make_initial_url,
)?;
self.interceptor
.attach(self.assembly_base + BROWSER_LOAD_URL, on_browser_load_url)
self.assembly_base + UNITY_WEB_REQUEST_SET_URL,
on_uwr_set_url,
)
}
unsafe fn de_init(&mut self) -> Result<()> {
@ -30,32 +26,7 @@ impl MhyModule for MhyContext<Http> {
}
}
unsafe extern "win64" fn on_make_initial_url(reg: *mut Registers, _: usize) {
let str_length = *((*reg).rcx.wrapping_add(16) as *const u32);
let str_ptr = (*reg).rcx.wrapping_add(20) as *const u8;
let slice = std::slice::from_raw_parts(str_ptr, (str_length * 2) as usize);
let url = String::from_utf16le(slice).unwrap();
let mut new_url = if url.contains("/query_region_list") {
String::from("http://127.0.0.1:21041")
} else {
String::from("http://127.0.0.1:21000")
};
url.split('/').skip(3).for_each(|s| {
new_url.push_str("/");
new_url.push_str(s);
});
if !url.contains("/query_cur_region") {
println!("Redirect: {url} -> {new_url}");
(*reg).rcx =
marshal::ptr_to_string_ansi(CString::new(new_url.as_str()).unwrap().as_c_str()) as u64;
}
}
unsafe extern "win64" fn on_browser_load_url(reg: *mut Registers, _: usize) {
unsafe extern "win64" fn on_uwr_set_url(reg: *mut Registers, _: usize) {
let str_length = *((*reg).rdx.wrapping_add(16) as *const u32);
let str_ptr = (*reg).rdx.wrapping_add(20) as *const u8;
@ -68,8 +39,7 @@ unsafe extern "win64" fn on_browser_load_url(reg: *mut Registers, _: usize) {
new_url.push_str(s);
});
println!("Browser::LoadURL: {url} -> {new_url}");
println!("Redirect: {url} -> {new_url}");
(*reg).rdx =
marshal::ptr_to_string_ansi(CString::new(new_url.as_str()).unwrap().as_c_str()) as u64;
}

View file

@ -1,33 +0,0 @@
use super::{MhyContext, MhyModule, ModuleType};
use anyhow::Result;
use ilhook::x64::Registers;
pub struct Misc;
const SET_CUSTOM_PROPERTY_FLOAT: usize = 0x12199F0;
impl MhyModule for MhyContext<Misc> {
unsafe fn init(&mut self) -> Result<()> {
// Dither
self.interceptor.replace(
self.assembly_base + SET_CUSTOM_PROPERTY_FLOAT,
set_custom_property_float_replacement,
)
}
unsafe fn de_init(&mut self) -> Result<()> {
Ok(())
}
fn get_module_type(&self) -> super::ModuleType {
ModuleType::Misc
}
}
unsafe extern "win64" fn set_custom_property_float_replacement(
_: *mut Registers,
_: usize,
_: usize,
) -> usize {
0
}

View file

@ -4,14 +4,10 @@ use anyhow::Result;
use crate::interceptor::Interceptor;
mod ccp_blocker;
mod http;
mod misc;
mod security;
pub use ccp_blocker::CcpBlocker;
pub use http::Http;
pub use misc::Misc;
pub use security::Security;
#[derive(Default)]
@ -42,8 +38,6 @@ impl ModuleManager {
pub enum ModuleType {
Http,
Security,
Misc,
CcpBlocker,
}
pub trait MhyModule {

View file

@ -1,35 +1,25 @@
use std::ffi::CString;
use crate::marshal;
use super::{MhyContext, MhyModule, ModuleType};
use anyhow::Result;
use ilhook::x64::Registers;
const MHYRSA_PERFORM_CRYPTO_ACTION: usize = 0x95ED88;
const KEY_SIGN_CHECK: usize = 0x960C7C;
const SDK_UTIL_RSA_ENCRYPT: usize = 0xFC0CC30;
const IL2CPP_ARRAY_NEW: usize = 0x5432A0;
const KEY_SIGN_CHECK: usize = 0x4235;
const KEY_SIZE: usize = 268;
const KEY_SIZE: u64 = 272;
const KEY_PREFIX: u64 = 0x0D700010182020A01;
static SERVER_PUBLIC_KEY: &[u8] = include_bytes!("../../server_public_key.bin");
static SDK_PUBLIC_KEY: &str = include_str!("../../sdk_public_key.xml");
type Il2cppArrayNew = unsafe extern "fastcall" fn(u64, u64) -> *const u8;
pub struct Security;
impl MhyModule for MhyContext<Security> {
unsafe fn init(&mut self) -> Result<()> {
self.interceptor.attach(
self.assembly_base + MHYRSA_PERFORM_CRYPTO_ACTION,
on_mhy_rsa,
self.interceptor.replace(
self.assembly_base + IL2CPP_ARRAY_NEW,
il2cpp_array_new_replacement,
)?;
self.interceptor
.attach(self.assembly_base + KEY_SIGN_CHECK, after_key_sign_check)?;
self.interceptor.attach(
self.assembly_base + SDK_UTIL_RSA_ENCRYPT,
on_sdk_util_rsa_encrypt,
)
.attach(self.assembly_base + KEY_SIGN_CHECK, after_key_sign_check)
}
unsafe fn de_init(&mut self) -> Result<()> {
@ -41,28 +31,36 @@ impl MhyModule for MhyContext<Security> {
}
}
// Sign check of rsa key that we just replaced.
unsafe extern "win64" fn after_key_sign_check(reg: *mut Registers, _: usize) {
println!("key sign check!");
(*reg).rax = 1
}
unsafe extern "win64" fn on_mhy_rsa(reg: *mut Registers, _: usize) {
println!("key: {:X}", *((*reg).rdx as *const u64));
println!("len: {:X}", (*reg).r8);
static mut KEY_PTR: Option<*mut u8> = None;
unsafe extern "win64" fn il2cpp_array_new_replacement(
reg: *mut Registers,
actual_func: usize,
_: usize,
) -> usize {
let il2cpp_array_new = std::mem::transmute::<usize, Il2cppArrayNew>(actual_func);
let ret_val = il2cpp_array_new((*reg).rcx, (*reg).rdx) as usize;
if (*reg).r8 as usize == KEY_SIZE {
println!("[*] key replaced");
let rdx = (*reg).rdx;
if rdx == KEY_SIZE {
KEY_PTR = Some(ret_val as *mut u8);
} else {
if let Some(key_ptr) = KEY_PTR {
if *(key_ptr.wrapping_add(32) as *const u64) == KEY_PREFIX {
std::ptr::copy_nonoverlapping(
SERVER_PUBLIC_KEY.as_ptr(),
key_ptr.wrapping_add(32),
SERVER_PUBLIC_KEY.len(),
);
}
}
std::ptr::copy_nonoverlapping(
SERVER_PUBLIC_KEY.as_ptr(),
(*reg).rdx as *mut u8,
SERVER_PUBLIC_KEY.len(),
);
KEY_PTR = None;
}
}
unsafe extern "win64" fn on_sdk_util_rsa_encrypt(reg: *mut Registers, _: usize) {
println!("[*] SDK RSA: key replaced");
(*reg).rcx =
marshal::ptr_to_string_ansi(CString::new(SDK_PUBLIC_KEY).unwrap().as_c_str()) as u64;
ret_val
}

View file

@ -2,14 +2,23 @@ use core::iter::once;
use std::ffi::{c_void, OsStr};
use std::os::windows::ffi::OsStrExt;
use windows::Win32::System::LibraryLoader::{GetModuleHandleA, GetModuleHandleW, GetProcAddress};
use windows::Win32::System::LibraryLoader::{GetProcAddress, GetModuleHandleW};
use windows::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, PAGE_PROTECTION_FLAGS, VirtualProtect};
use windows::core::{s, PCSTR, PCWSTR};
use windows::core::{PCSTR, PCWSTR};
pub fn wide_str(value: &str) -> Vec<u16> {
OsStr::new(value).encode_wide().chain(once(0)).collect()
}
pub unsafe fn try_get_base_address(module_name: &str) -> Option<usize> {
let w_module_name = wide_str(module_name);
match GetModuleHandleW(PCWSTR::from_raw(w_module_name.as_ptr())) {
Ok(module) => Some(module.0 as usize),
Err(_) => None
}
}
// VMProtect hooks NtProtectVirtualMemory to prevent changing protection of executable segments
// We use this trick to remove hook
pub unsafe fn disable_memprotect_guard() {
@ -20,12 +29,7 @@ pub unsafe fn disable_memprotect_guard() {
PCSTR::from_raw(c"NtProtectVirtualMemory".to_bytes_with_nul().as_ptr()),
)
.unwrap();
let routine = if is_wine() {
GetProcAddress(ntdll, s!("NtPulseEvent")).unwrap()
} else {
GetProcAddress(ntdll, s!("NtQuerySection")).unwrap()
} as *mut u32;
let nt_query = GetProcAddress(ntdll, PCSTR::from_raw(c"NtQuerySection".to_bytes_with_nul().as_ptr())).unwrap();
let mut old_prot = PAGE_PROTECTION_FLAGS(0);
VirtualProtect(
@ -36,6 +40,7 @@ pub unsafe fn disable_memprotect_guard() {
)
.unwrap();
let routine = nt_query as *mut u32;
let routine_val = *(routine as *const usize);
let lower_bits_mask = !(0xFFu64 << 32);
@ -56,8 +61,3 @@ pub unsafe fn disable_memprotect_guard() {
)
.unwrap();
}
unsafe fn is_wine() -> bool {
let module = GetModuleHandleA(s!("ntdll.dll")).unwrap();
GetProcAddress(module, s!("wine_get_version")).is_some()
}

54
src/version.rs Normal file
View file

@ -0,0 +1,54 @@
use libloading::{Error, Library, Symbol};
use std::env;
use std::ffi::CStr;
static FUNCTION_NAMES: &[&CStr] = &[
c"GetFileVersionInfoA",
c"GetFileVersionInfoByHandle",
c"GetFileVersionInfoExA",
c"GetFileVersionInfoExW",
c"GetFileVersionInfoSizeA",
c"GetFileVersionInfoSizeExA",
c"GetFileVersionInfoSizeExW",
c"GetFileVersionInfoSizeW",
c"GetFileVersionInfoW",
c"VerFindFileA",
c"VerFindFileW",
c"VerInstallFileA",
c"VerInstallFileW",
c"VerLanguageNameA",
c"VerLanguageNameW",
c"VerQueryValueA",
c"VerQueryValueW",
];
#[no_mangle]
static mut ORIGINAL_FUNCTIONS: [*const usize; 17] = [0 as *const usize; 17];
pub struct VersionDllProxy {
library: Library,
}
impl VersionDllProxy {
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
let system_directory = env::var("windir")? + ("\\System32\\");
let dll_path = system_directory + "version.dll";
let library = unsafe { Library::new(dll_path) }?;
Ok(Self { library })
}
fn get_function<T>(&self, func_name: &CStr) -> Result<Symbol<T>, Error> {
unsafe { self.library.get(func_name.to_bytes_with_nul()) }
}
pub fn load_functions(&self) -> Result<(), Error> {
for (i, &name) in FUNCTION_NAMES.iter().enumerate() {
let fn_ptr = self.get_function::<Symbol<*mut usize>>(name)?;
unsafe { ORIGINAL_FUNCTIONS[i] = **fn_ptr };
println!("Loaded function {}@{:p}", name.to_str().unwrap(), unsafe {
ORIGINAL_FUNCTIONS[i]
});
}
Ok(())
}
}

112
version.asm Normal file
View file

@ -0,0 +1,112 @@
ifdef RAX
.code
extern ORIGINAL_FUNCTIONS:QWORD
GetFileVersionInfoA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[0 * 8]
GetFileVersionInfoA endp
GetFileVersionInfoByHandle proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[1 * 8]
GetFileVersionInfoByHandle endp
GetFileVersionInfoExA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[2 * 8]
GetFileVersionInfoExA endp
GetFileVersionInfoExW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[3 * 8]
GetFileVersionInfoExW endp
GetFileVersionInfoSizeA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[4 * 8]
GetFileVersionInfoSizeA endp
GetFileVersionInfoSizeExA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[5 * 8]
GetFileVersionInfoSizeExA endp
GetFileVersionInfoSizeExW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[6 * 8]
GetFileVersionInfoSizeExW endp
GetFileVersionInfoSizeW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[7 * 8]
GetFileVersionInfoSizeW endp
GetFileVersionInfoW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[8 * 8]
GetFileVersionInfoW endp
VerFindFileA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[9 * 8]
VerFindFileA endp
VerFindFileW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[10 * 8]
VerFindFileW endp
VerInstallFileA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[11 * 8]
VerInstallFileA endp
VerInstallFileW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[12 * 8]
VerInstallFileW endp
VerLanguageNameA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[13 * 8]
VerLanguageNameA endp
VerLanguageNameW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[14 * 8]
VerLanguageNameW endp
VerQueryValueA proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[15 * 8]
VerQueryValueA endp
VerQueryValueW proc
jmp QWORD ptr ORIGINAL_FUNCTIONS[16 * 8]
VerQueryValueW endp
else
.model flat, C
.stack 4096
.code
extern ORIGINAL_FUNCTIONS:DWORD
GetFileVersionInfoA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[0 * 4]
GetFileVersionInfoA endp
GetFileVersionInfoByHandle proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[1 * 4]
GetFileVersionInfoByHandle endp
GetFileVersionInfoExA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[2 * 4]
GetFileVersionInfoExA endp
GetFileVersionInfoExW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[3 * 4]
GetFileVersionInfoExW endp
GetFileVersionInfoSizeA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[4 * 4]
GetFileVersionInfoSizeA endp
GetFileVersionInfoSizeExA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[5 * 4]
GetFileVersionInfoSizeExA endp
GetFileVersionInfoSizeExW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[6 * 4]
GetFileVersionInfoSizeExW endp
GetFileVersionInfoSizeW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[7 * 4]
GetFileVersionInfoSizeW endp
GetFileVersionInfoW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[8 * 4]
GetFileVersionInfoW endp
VerFindFileA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[9 * 4]
VerFindFileA endp
VerFindFileW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[10 * 4]
VerFindFileW endp
VerInstallFileA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[11 * 4]
VerInstallFileA endp
VerInstallFileW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[12 * 4]
VerInstallFileW endp
VerLanguageNameA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[13 * 4]
VerLanguageNameA endp
VerLanguageNameW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[14 * 4]
VerLanguageNameW endp
VerQueryValueA proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[15 * 4]
VerQueryValueA endp
VerQueryValueW proc
jmp DWORD ptr ORIGINAL_FUNCTIONS[16 * 4]
VerQueryValueW endp
endif
end

19
version.def Normal file
View file

@ -0,0 +1,19 @@
EXPORTS
GetFileVersionInfoA
GetFileVersionInfoByHandle
GetFileVersionInfoExA
GetFileVersionInfoExW
GetFileVersionInfoSizeA
GetFileVersionInfoSizeExA
GetFileVersionInfoSizeExW
GetFileVersionInfoSizeW
GetFileVersionInfoW
VerFindFileA
VerFindFileW
VerInstallFileA
VerInstallFileW
VerLanguageNameA
VerLanguageNameW
VerQueryValueA
VerQueryValueW