_tmain.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. #include <tchar.h>
  2. #include <stdio.h>
  3. #include <windows.h>
  4. #include <Exception.hpp>
  5. #include <ExceptionWin32.hpp>
  6. #include <ResourceOwned.hpp>
  7. #include <ResourceTraitsWin32.hpp>
  8. #include "ImageInterpreter.hpp"
  9. #include "PatchSolutions.hpp"
  10. #include "Misc.hpp"
  11. #undef NKG_CURRENT_SOURCE_FILE
  12. #undef NKG_CURRENT_SOURCE_LINE
  13. #define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\_tmain.cpp")
  14. #define NKG_CURRENT_SOURCE_LINE() __LINE__
  15. static void Welcome() {
  16. _putts(TEXT("***************************************************"));
  17. _putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
  18. _putts(TEXT("* Version: 4.1 *"));
  19. _putts(TEXT("***************************************************"));
  20. _putts(TEXT(""));
  21. _putts(TEXT("Press Enter to continue or Ctrl + C to abort."));
  22. auto c = _gettchar();
  23. while (c != TEXT('\n') && _gettchar() != TEXT('\n')) {}
  24. }
  25. static void Help() {
  26. _putts(TEXT("***************************************************"));
  27. _putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
  28. _putts(TEXT("* Version: 4.1 *"));
  29. _putts(TEXT("***************************************************"));
  30. _putts(TEXT(""));
  31. _putts(TEXT("Usage:"));
  32. _putts(TEXT(" navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]"));
  33. _putts(TEXT(""));
  34. _putts(TEXT(" [-dry-run] Run patcher without applying any patches."));
  35. _putts(TEXT(" This parameter is optional."));
  36. _putts(TEXT(""));
  37. _putts(TEXT(" <Navicat Installation Path> The folder path where Navicat is installed."));
  38. _putts(TEXT(" This parameter must be specified."));
  39. _putts(TEXT(""));
  40. _putts(TEXT(" [RSA-2048 PEM File Path] The path to an RSA-2048 private key file."));
  41. _putts(TEXT(" This parameter is optional."));
  42. _putts(TEXT(" If not specified, an RSA-2048 private key file"));
  43. _putts(TEXT(" named \"RegPrivateKey.pem\" will be generated."));
  44. _putts(TEXT(""));
  45. _putts(TEXT("Example:"));
  46. _putts(TEXT(" navicat-patcher.exe \"C:\\Program Files\\PremiumSoft\\Navicat Premium 12\""));
  47. }
  48. static bool ParseCommandLine(int argc, PTSTR argv[], bool& bDryRun, std::xstring& NavInstallPath, std::xstring& RsaPrivateKeyPath) {
  49. if (argc == 2) {
  50. bDryRun = false;
  51. NavInstallPath = argv[1];
  52. RsaPrivateKeyPath.clear();
  53. return true;
  54. } else if (argc == 3) {
  55. if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
  56. bDryRun = true;
  57. NavInstallPath = argv[2];
  58. RsaPrivateKeyPath.clear();
  59. return true;
  60. } else {
  61. bDryRun = false;
  62. NavInstallPath = argv[1];
  63. RsaPrivateKeyPath = argv[2];
  64. return true;
  65. }
  66. } else if (argc == 4) {
  67. if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
  68. bDryRun = true;
  69. NavInstallPath = argv[2];
  70. RsaPrivateKeyPath = argv[3];
  71. return true;
  72. } else {
  73. return false;
  74. }
  75. } else {
  76. return false;
  77. }
  78. }
  79. static void SelectPatchSolutions(
  80. ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution0,
  81. ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution1,
  82. ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution2,
  83. ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution3)
  84. {
  85. // if RSA public is detected in libcc.dll, don't patch main application to keep digital signature valid.
  86. if ((lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) && lpSolution0.IsValid()) {
  87. LOG_HINT(0, "PatchSolution0 is suppressed in order to keep digital signature valid.");
  88. lpSolution0.Release();
  89. }
  90. }
  91. static void NavicatBackupDetect(const std::xstring& FilePath) {
  92. if (std::xstring BackupPath = FilePath + TEXT(".backup"); nkg::IsValidFilePath(BackupPath.c_str()) == true) {
  93. while (true) {
  94. LOG_SELECT(0, "Previous backup %s detected. Delete? (y/n)", BackupPath.c_str());
  95. auto select = _gettchar();
  96. while (select != TEXT('\n') && _gettchar() != TEXT('\n')) {}
  97. if (select == TEXT('Y') || select == TEXT('y')) {
  98. if (!DeleteFile(BackupPath.c_str())) {
  99. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to delete backup file."));
  100. } else {
  101. break;
  102. }
  103. } else if (select == TEXT('N') || select == TEXT('n')) {
  104. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Backup file still existed. Patch abort!"));
  105. } else {
  106. continue;
  107. }
  108. }
  109. _putts(TEXT(""));
  110. }
  111. }
  112. static void NavicatBackupMake(const std::xstring& FilePath) {
  113. std::xstring BackupPath = FilePath + TEXT(".backup");
  114. if (CopyFile(FilePath.c_str(), BackupPath.c_str(), TRUE) == FALSE) {
  115. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CopyFile failed."));
  116. }
  117. }
  118. static void LoadKey(
  119. nkg::RSACipher& Cipher, const std::xstring& KeyFilePath,
  120. nkg::PatchSolution* pSolution0,
  121. nkg::PatchSolution* pSolution1,
  122. nkg::PatchSolution* pSolution2,
  123. nkg::PatchSolution* pSolution3,
  124. nkg::PatchSolution* pSolution4)
  125. {
  126. if (KeyFilePath.empty() == false) {
  127. LOG_HINT(0, "Import RSA-2048 key from %s", KeyFilePath.c_str());
  128. Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(KeyFilePath);
  129. if (pSolution0 && !pSolution0->CheckKey(Cipher) ||
  130. pSolution1 && !pSolution1->CheckKey(Cipher) ||
  131. pSolution2 && !pSolution2->CheckKey(Cipher) ||
  132. pSolution3 && !pSolution3->CheckKey(Cipher) ||
  133. pSolution4 && !pSolution4->CheckKey(Cipher))
  134. {
  135. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("The RSA private key you provide cannot be used."));
  136. }
  137. } else {
  138. LOG_HINT(0, "Generating new RSA private key, it may take a long time...");
  139. do {
  140. Cipher.GenerateKey(2048);
  141. } while (pSolution0 && !pSolution0->CheckKey(Cipher) ||
  142. pSolution1 && !pSolution1->CheckKey(Cipher) ||
  143. pSolution2 && !pSolution2->CheckKey(Cipher) ||
  144. pSolution3 && !pSolution3->CheckKey(Cipher) ||
  145. pSolution4 && !pSolution4->CheckKey(Cipher)); // re-generate RSA key if one of 'CheckKey's return false
  146. }
  147. LOG_HINT(0, "Your RSA public key:\n%hs", Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>().c_str());
  148. }
  149. int _tmain(int argc, PTSTR argv[]) {
  150. bool bDryRun;
  151. std::xstring NavInstallPath;
  152. std::xstring RsaPrivateKeyPath;
  153. if (ParseCommandLine(argc, argv, bDryRun, NavInstallPath, RsaPrivateKeyPath) == false) {
  154. Help();
  155. return -1;
  156. } else {
  157. Welcome();
  158. try {
  159. if (nkg::IsValidDirectoryPath(NavInstallPath.c_str()) == false) {
  160. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Navicat installation path doesn't point to a directory."))
  161. .AddHint(TEXT("Are you sure the path you specified is correct?"))
  162. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
  163. }
  164. if (RsaPrivateKeyPath.empty() == false && nkg::IsValidFilePath(RsaPrivateKeyPath.c_str()) == false) {
  165. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key file path doesn't point to a file."))
  166. .AddHint(TEXT("Are you sure the path you specified is correct?"))
  167. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), RsaPrivateKeyPath.c_str()));
  168. }
  169. while (NavInstallPath.back() == TEXT('\\') || NavInstallPath.back() == TEXT('/')) {
  170. NavInstallPath.pop_back();
  171. }
  172. NavInstallPath.push_back(nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\'));
  173. nkg::RSACipher Cipher;
  174. std::xstring MainExePath;
  175. ResourceOwned hMainExe(FileHandleTraits{});
  176. ResourceOwned hMainExeMapping(GenericHandleTraits{});
  177. ResourceOwned lpMainExeMapping(MapViewHandleTraits{});
  178. ResourceOwned lpMainExeInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
  179. std::xstring LibccDllPath;
  180. ResourceOwned hLibccDll(FileHandleTraits{});
  181. ResourceOwned hLibccDllMapping(GenericHandleTraits{});
  182. ResourceOwned lpLibccDllMapping(MapViewHandleTraits{});
  183. ResourceOwned lpLibccDllInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
  184. ResourceOwned lpSolution0(CppObjectTraits<nkg::PatchSolution>{});
  185. ResourceOwned lpSolution1(CppObjectTraits<nkg::PatchSolution>{});
  186. ResourceOwned lpSolution2(CppObjectTraits<nkg::PatchSolution>{});
  187. ResourceOwned lpSolution3(CppObjectTraits<nkg::PatchSolution>{});
  188. ResourceOwned lpSolution4(CppObjectTraits<nkg::PatchSolution>{});
  189. //
  190. // Open main application
  191. //
  192. do {
  193. MainExePath = NavInstallPath + TEXT("Navicat.exe");
  194. hMainExe.TakeOver(
  195. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  196. );
  197. if (hMainExe.IsValid()) {
  198. LOG_SUCCESS(0, "Try to open Navicat.exe ... Ok!");
  199. break;
  200. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  201. LOG_FAILURE(0, "Try to open Navicat.exe ... Not found!");
  202. } else {
  203. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Navicat.exe"));
  204. }
  205. MainExePath = NavInstallPath + TEXT("Modeler.exe");
  206. hMainExe.TakeOver(
  207. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  208. );
  209. if (hMainExe.IsValid()) {
  210. LOG_SUCCESS(0, "Try to open Modeler.exe ... Ok!");
  211. break;
  212. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  213. LOG_FAILURE(0, "Try to open Modeler.exe ... Not found!");
  214. } else {
  215. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Modeler.exe"));
  216. }
  217. MainExePath = NavInstallPath + TEXT("Rviewer.exe");
  218. hMainExe.TakeOver(
  219. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  220. );
  221. if (hMainExe.IsValid()) {
  222. LOG_SUCCESS(0, "Try to open Rviewer.exe ... Ok!");
  223. break;
  224. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  225. LOG_FAILURE(0, "Try to open Rviewer.exe ... Not found!");
  226. } else {
  227. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Rviewer.exe"));
  228. }
  229. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Main application is not found."))
  230. .AddHint(TEXT("Are you sure you specified a valid Navicat installation path?"))
  231. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
  232. } while (false);
  233. //
  234. // Open libcc.dll, if have
  235. //
  236. do {
  237. LibccDllPath = NavInstallPath + TEXT("libcc.dll");
  238. hLibccDll.TakeOver(
  239. CreateFile(LibccDllPath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  240. );
  241. if (hLibccDll.IsValid()) {
  242. LOG_SUCCESS(0, "Try to open libcc.dll ... Ok!");
  243. break;
  244. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  245. LOG_FAILURE(0, "Try to open libcc.dll ... Not found!");
  246. } else {
  247. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open libcc.dll"));
  248. }
  249. } while (false);
  250. _putts(TEXT(""));
  251. //
  252. // Map main application
  253. //
  254. hMainExeMapping.TakeOver(CreateFileMapping(hMainExe, NULL, PAGE_READWRITE, 0, 0, NULL));
  255. if (hMainExeMapping.IsValid() == false) {
  256. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
  257. }
  258. lpMainExeMapping.TakeOver(MapViewOfFile(hMainExeMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
  259. if (hMainExeMapping.IsValid() == false) {
  260. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
  261. }
  262. lpMainExeInterpreter.TakeOver(
  263. new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpMainExeMapping))
  264. );
  265. lpSolution0.TakeOver(new nkg::PatchSolution0(lpMainExeInterpreter));
  266. //
  267. // Map libcc.dll, if have
  268. //
  269. if (hLibccDll.IsValid()) {
  270. hLibccDllMapping.TakeOver(CreateFileMapping(hLibccDll, NULL, PAGE_READWRITE, 0, 0, NULL));
  271. if (hMainExeMapping.IsValid() == false) {
  272. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
  273. }
  274. lpLibccDllMapping.TakeOver(MapViewOfFile(hLibccDllMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
  275. if (hMainExeMapping.IsValid() == false) {
  276. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
  277. }
  278. lpLibccDllInterpreter.TakeOver(
  279. new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpLibccDllMapping))
  280. );
  281. lpSolution1.TakeOver(new nkg::PatchSolution1(lpLibccDllInterpreter));
  282. lpSolution2.TakeOver(new nkg::PatchSolution2(lpLibccDllInterpreter));
  283. lpSolution3.TakeOver(new nkg::PatchSolution3(lpLibccDllInterpreter));
  284. lpSolution4.TakeOver(new nkg::PatchSolution4(lpLibccDllInterpreter));
  285. }
  286. //
  287. // Finding patch offsets
  288. //
  289. if (lpSolution0->FindPatchOffset() == false) {
  290. lpSolution0.Release();
  291. }
  292. if (lpSolution1.IsValid() && lpSolution1->FindPatchOffset() == false) {
  293. lpSolution1.Release();
  294. }
  295. if (lpSolution2.IsValid() && lpSolution2->FindPatchOffset() == false) {
  296. lpSolution2.Release();
  297. }
  298. if (lpSolution3.IsValid() && lpSolution3->FindPatchOffset() == false) {
  299. lpSolution3.Release();
  300. }
  301. if (lpSolution4.IsValid() && lpSolution4->FindPatchOffset() == false) {
  302. lpSolution4.Release();
  303. }
  304. _putts(TEXT(""));
  305. //
  306. // decide which solutions will be applied
  307. //
  308. SelectPatchSolutions(lpSolution0, lpSolution1, lpSolution2, lpSolution3);
  309. if (lpSolution0.IsValid() == false && lpSolution1.IsValid() == false && lpSolution2.IsValid() == false && lpSolution3.IsValid() == false && lpSolution4.IsValid() == false) {
  310. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No patch applied. Patch abort!"))
  311. .AddHint(TEXT("Are you sure your Navicat has not been patched/modified before?"));
  312. }
  313. _putts(TEXT(""));
  314. //
  315. // detecting backups
  316. //
  317. if (lpSolution0.IsValid()) {
  318. NavicatBackupDetect(MainExePath);
  319. }
  320. if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid() || lpSolution4.IsValid()) {
  321. NavicatBackupDetect(LibccDllPath);
  322. }
  323. //
  324. // Loading key
  325. //
  326. LoadKey(Cipher, RsaPrivateKeyPath, lpSolution0, lpSolution1, lpSolution2, lpSolution3, lpSolution4);
  327. if (bDryRun == false) {
  328. //
  329. // Saving private key if not given
  330. //
  331. if (RsaPrivateKeyPath.empty()) {
  332. Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(std::xstring{ std::xstring_extension{}, "RegPrivateKey.pem" });
  333. }
  334. //
  335. // Making backups
  336. //
  337. if (lpSolution0.IsValid()) {
  338. NavicatBackupMake(MainExePath);
  339. }
  340. if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid() || lpSolution4.IsValid()) {
  341. NavicatBackupMake(LibccDllPath);
  342. }
  343. //
  344. // Making patch. No way to go back here :-)
  345. //
  346. if (lpSolution0.IsValid()) {
  347. lpSolution0->MakePatch(Cipher);
  348. }
  349. if (lpSolution1.IsValid()) {
  350. lpSolution1->MakePatch(Cipher);
  351. }
  352. if (lpSolution2.IsValid()) {
  353. lpSolution2->MakePatch(Cipher);
  354. }
  355. if (lpSolution3.IsValid()) {
  356. lpSolution3->MakePatch(Cipher);
  357. }
  358. if (lpSolution4.IsValid()) {
  359. lpSolution4->MakePatch(Cipher);
  360. }
  361. if (RsaPrivateKeyPath.empty()) {
  362. LOG_HINT(
  363. 0,
  364. "New RSA-2048 private key has been saved to\n%s%cRegPrivateKey.pem",
  365. nkg::GetCurrentWorkingDirectory().c_str(),
  366. nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\')
  367. );
  368. _putts(TEXT(""));
  369. }
  370. _putts(TEXT("*******************************************************"));
  371. _putts(TEXT("* PATCH HAS BEEN DONE SUCCESSFULLY! *"));
  372. _putts(TEXT("* HAVE FUN AND ENJOY~ *"));
  373. _putts(TEXT("*******************************************************"));
  374. } else {
  375. _putts(TEXT("*******************************************************"));
  376. _putts(TEXT("* DRY-RUN MODE ENABLE! *"));
  377. _putts(TEXT("* NO PATCH WILL BE APPLIED! *"));
  378. _putts(TEXT("*******************************************************"));
  379. }
  380. return 0;
  381. } catch (nkg::Exception& e) {
  382. LOG_FAILURE(0, "%s:%zu ->", e.File(), e.Line());
  383. LOG_FAILURE(4, "%s", e.Message());
  384. if (e.HasErrorCode()) {
  385. LOG_HINT(4, "%s (0x%zx)", e.ErrorString(), e.ErrorCode());
  386. }
  387. for (auto& Hint : e.Hints()) {
  388. LOG_HINT(4, "Hint: %s", Hint.c_str());
  389. }
  390. return -1;
  391. }
  392. }
  393. }