_tmain.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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.0 *"));
  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.0 *"));
  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. {
  125. if (KeyFilePath.empty() == false) {
  126. LOG_HINT(0, "Import RSA-2048 key from %s", KeyFilePath.c_str());
  127. Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(KeyFilePath);
  128. if (pSolution0 && !pSolution0->CheckKey(Cipher) ||
  129. pSolution1 && !pSolution1->CheckKey(Cipher) ||
  130. pSolution2 && !pSolution2->CheckKey(Cipher) ||
  131. pSolution3 && !pSolution3->CheckKey(Cipher))
  132. {
  133. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("The RSA private key you provide cannot be used."));
  134. }
  135. } else {
  136. LOG_HINT(0, "Generating new RSA private key, it may take a long time...");
  137. do {
  138. Cipher.GenerateKey(2048);
  139. } while (pSolution0 && !pSolution0->CheckKey(Cipher) ||
  140. pSolution1 && !pSolution1->CheckKey(Cipher) ||
  141. pSolution2 && !pSolution2->CheckKey(Cipher) ||
  142. pSolution3 && !pSolution3->CheckKey(Cipher)); // re-generate RSA key if one of 'CheckKey's return false
  143. }
  144. LOG_HINT(0, "Your RSA public key:\n%hs", Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>().c_str());
  145. }
  146. int _tmain(int argc, PTSTR argv[]) {
  147. bool bDryRun;
  148. std::xstring NavInstallPath;
  149. std::xstring RsaPrivateKeyPath;
  150. if (ParseCommandLine(argc, argv, bDryRun, NavInstallPath, RsaPrivateKeyPath) == false) {
  151. Help();
  152. return -1;
  153. } else {
  154. Welcome();
  155. try {
  156. if (nkg::IsValidDirectoryPath(NavInstallPath.c_str()) == false) {
  157. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Navicat installation path doesn't point to a directory."))
  158. .AddHint(TEXT("Are you sure the path you specified is correct?"))
  159. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
  160. }
  161. if (RsaPrivateKeyPath.empty() == false && nkg::IsValidFilePath(RsaPrivateKeyPath.c_str()) == false) {
  162. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key file path doesn't point to a file."))
  163. .AddHint(TEXT("Are you sure the path you specified is correct?"))
  164. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), RsaPrivateKeyPath.c_str()));
  165. }
  166. while (NavInstallPath.back() == TEXT('\\') || NavInstallPath.back() == TEXT('/')) {
  167. NavInstallPath.pop_back();
  168. }
  169. NavInstallPath.push_back(nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\'));
  170. nkg::RSACipher Cipher;
  171. std::xstring MainExePath;
  172. ResourceOwned hMainExe(FileHandleTraits{});
  173. ResourceOwned hMainExeMapping(GenericHandleTraits{});
  174. ResourceOwned lpMainExeMapping(MapViewHandleTraits{});
  175. ResourceOwned lpMainExeInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
  176. std::xstring LibccDllPath;
  177. ResourceOwned hLibccDll(FileHandleTraits{});
  178. ResourceOwned hLibccDllMapping(GenericHandleTraits{});
  179. ResourceOwned lpLibccDllMapping(MapViewHandleTraits{});
  180. ResourceOwned lpLibccDllInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
  181. ResourceOwned lpSolution0(CppObjectTraits<nkg::PatchSolution>{});
  182. ResourceOwned lpSolution1(CppObjectTraits<nkg::PatchSolution>{});
  183. ResourceOwned lpSolution2(CppObjectTraits<nkg::PatchSolution>{});
  184. ResourceOwned lpSolution3(CppObjectTraits<nkg::PatchSolution>{});
  185. //
  186. // Open main application
  187. //
  188. do {
  189. MainExePath = NavInstallPath + TEXT("Navicat.exe");
  190. hMainExe.TakeOver(
  191. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  192. );
  193. if (hMainExe.IsValid()) {
  194. LOG_SUCCESS(0, "Try to open Navicat.exe ... Ok!");
  195. break;
  196. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  197. LOG_FAILURE(0, "Try to open Navicat.exe ... Not found!");
  198. } else {
  199. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Navicat.exe"));
  200. }
  201. MainExePath = NavInstallPath + TEXT("Modeler.exe");
  202. hMainExe.TakeOver(
  203. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  204. );
  205. if (hMainExe.IsValid()) {
  206. LOG_SUCCESS(0, "Try to open Modeler.exe ... Ok!");
  207. break;
  208. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  209. LOG_FAILURE(0, "Try to open Modeler.exe ... Not found!");
  210. } else {
  211. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Modeler.exe"));
  212. }
  213. MainExePath = NavInstallPath + TEXT("Rviewer.exe");
  214. hMainExe.TakeOver(
  215. CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  216. );
  217. if (hMainExe.IsValid()) {
  218. LOG_SUCCESS(0, "Try to open Rviewer.exe ... Ok!");
  219. break;
  220. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  221. LOG_FAILURE(0, "Try to open Rviewer.exe ... Not found!");
  222. } else {
  223. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Rviewer.exe"));
  224. }
  225. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Main application is not found."))
  226. .AddHint(TEXT("Are you sure you specified a valid Navicat installation path?"))
  227. .AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
  228. } while (false);
  229. //
  230. // Open libcc.dll, if have
  231. //
  232. do {
  233. LibccDllPath = NavInstallPath + TEXT("libcc.dll");
  234. hLibccDll.TakeOver(
  235. CreateFile(LibccDllPath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
  236. );
  237. if (hLibccDll.IsValid()) {
  238. LOG_SUCCESS(0, "Try to open libcc.dll ... Ok!");
  239. break;
  240. } else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  241. LOG_FAILURE(0, "Try to open libcc.dll ... Not found!");
  242. } else {
  243. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open libcc.dll"));
  244. }
  245. } while (false);
  246. _putts(TEXT(""));
  247. //
  248. // Map main application
  249. //
  250. hMainExeMapping.TakeOver(CreateFileMapping(hMainExe, NULL, PAGE_READWRITE, 0, 0, NULL));
  251. if (hMainExeMapping.IsValid() == false) {
  252. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
  253. }
  254. lpMainExeMapping.TakeOver(MapViewOfFile(hMainExeMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
  255. if (hMainExeMapping.IsValid() == false) {
  256. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
  257. }
  258. lpMainExeInterpreter.TakeOver(
  259. new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpMainExeMapping))
  260. );
  261. lpSolution0.TakeOver(new nkg::PatchSolution0(lpMainExeInterpreter));
  262. //
  263. // Map libcc.dll, if have
  264. //
  265. if (hLibccDll.IsValid()) {
  266. hLibccDllMapping.TakeOver(CreateFileMapping(hLibccDll, NULL, PAGE_READWRITE, 0, 0, NULL));
  267. if (hMainExeMapping.IsValid() == false) {
  268. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
  269. }
  270. lpLibccDllMapping.TakeOver(MapViewOfFile(hLibccDllMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
  271. if (hMainExeMapping.IsValid() == false) {
  272. throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
  273. }
  274. lpLibccDllInterpreter.TakeOver(
  275. new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpLibccDllMapping))
  276. );
  277. lpSolution1.TakeOver(new nkg::PatchSolution1(lpLibccDllInterpreter));
  278. lpSolution2.TakeOver(new nkg::PatchSolution2(lpLibccDllInterpreter));
  279. lpSolution3.TakeOver(new nkg::PatchSolution3(lpLibccDllInterpreter));
  280. }
  281. //
  282. // Finding patch offsets
  283. //
  284. if (lpSolution0->FindPatchOffset() == false) {
  285. lpSolution0.Release();
  286. }
  287. if (lpSolution1.IsValid() && lpSolution1->FindPatchOffset() == false) {
  288. lpSolution1.Release();
  289. }
  290. if (lpSolution2.IsValid() && lpSolution2->FindPatchOffset() == false) {
  291. lpSolution2.Release();
  292. }
  293. if (lpSolution3.IsValid() && lpSolution3->FindPatchOffset() == false) {
  294. lpSolution3.Release();
  295. }
  296. _putts(TEXT(""));
  297. //
  298. // decide which solutions will be applied
  299. //
  300. SelectPatchSolutions(lpSolution0, lpSolution1, lpSolution2, lpSolution3);
  301. if (lpSolution0.IsValid() == false && lpSolution1.IsValid() == false && lpSolution2.IsValid() == false && lpSolution3.IsValid() == false) {
  302. throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No patch applied. Patch abort!"))
  303. .AddHint(TEXT("Are you sure your Navicat has not been patched/modified before?"));
  304. }
  305. _putts(TEXT(""));
  306. //
  307. // detecting backups
  308. //
  309. if (lpSolution0.IsValid()) {
  310. NavicatBackupDetect(MainExePath);
  311. }
  312. if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) {
  313. NavicatBackupDetect(LibccDllPath);
  314. }
  315. //
  316. // Loading key
  317. //
  318. LoadKey(Cipher, RsaPrivateKeyPath, lpSolution0, lpSolution1, lpSolution2, lpSolution3);
  319. if (bDryRun == false) {
  320. //
  321. // Saving private key if not given
  322. //
  323. if (RsaPrivateKeyPath.empty()) {
  324. Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(std::xstring{ std::xstring_extension{}, "RegPrivateKey.pem" });
  325. }
  326. //
  327. // Making backups
  328. //
  329. if (lpSolution0.IsValid()) {
  330. NavicatBackupMake(MainExePath);
  331. }
  332. if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) {
  333. NavicatBackupMake(LibccDllPath);
  334. }
  335. //
  336. // Making patch. No way to go back here :-)
  337. //
  338. if (lpSolution0.IsValid()) {
  339. lpSolution0->MakePatch(Cipher);
  340. }
  341. if (lpSolution1.IsValid()) {
  342. lpSolution1->MakePatch(Cipher);
  343. }
  344. if (lpSolution2.IsValid()) {
  345. lpSolution2->MakePatch(Cipher);
  346. }
  347. if (lpSolution3.IsValid()) {
  348. lpSolution3->MakePatch(Cipher);
  349. }
  350. if (RsaPrivateKeyPath.empty()) {
  351. LOG_HINT(
  352. 0,
  353. "New RSA-2048 private key has been saved to\n%s%cRegPrivateKey.pem",
  354. nkg::GetCurrentWorkingDirectory().c_str(),
  355. nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\')
  356. );
  357. _putts(TEXT(""));
  358. }
  359. _putts(TEXT("*******************************************************"));
  360. _putts(TEXT("* PATCH HAS BEEN DONE SUCCESSFULLY! *"));
  361. _putts(TEXT("* HAVE FUN AND ENJOY~ *"));
  362. _putts(TEXT("*******************************************************"));
  363. } else {
  364. _putts(TEXT("*******************************************************"));
  365. _putts(TEXT("* DRY-RUN MODE ENABLE! *"));
  366. _putts(TEXT("* NO PATCH WILL BE APPLIED! *"));
  367. _putts(TEXT("*******************************************************"));
  368. }
  369. return 0;
  370. } catch (nkg::Exception& e) {
  371. LOG_FAILURE(0, "%s:%zu ->", e.File(), e.Line());
  372. LOG_FAILURE(4, "%s", e.Message());
  373. if (e.HasErrorCode()) {
  374. LOG_HINT(4, "%s (0x%zx)", e.ErrorString(), e.ErrorCode());
  375. }
  376. for (auto& Hint : e.Hints()) {
  377. LOG_HINT(4, "Hint: %s", Hint.c_str());
  378. }
  379. return -1;
  380. }
  381. }
  382. }